我有一个名为Unit
的课程,它是游戏中的通用单元。此Unit
的实例可以是Cavalry
,Infantry
等,每个单元都有坐标,指示其在网格上的初始位置。我想创建这个Unit
类的许多实例,以便填充地图。
这就是我所拥有的:
#create units for team 1
#(self, name, x, y, char, color, move_range, atk_range, unit_size, morale, power, fatigue, team)
team_1_cavalry =[(Unit('Cavalry', i+20, 10, 'A', libtcod.yellow, 6, 1, 1000, 100, 1.5, 500, 1)) for i in range(11) ]
team_1_infantry = [(Unit('Heavy Infantry', i+20, 9, '=', libtcod.yellow, 3, 1, 2000, 100, 1.0, 200, 1)) for i in range(11)]
team_1_elephants = [(Unit('War Elephants', 20, 8, 'R', libtcod.yellow, 5, 1, 37, 100, 100, 800, 1)) for i in range(2)]
#create units for team 2
team_2_cavalry = [(Unit('Cavalry', 20+i, 15, 'A', libtcod.green, 6, 1, 500, 1000, 1.5, 500, 2)) for i in range (5)]
team_2_infantry = [(Unit('Roman Infantry', 20+i, 16, '=', libtcod.green, 3, 1, 2000, 100, 1.0, 200, 2)) for i in range(20)]
#the list of objects with those two
team1 = []
team2 = []
for unit in team_1_cavalry, team_1_infantry, team_1_elephants:
team1.append(unit)
for unit in team_2_cavalry, team_2_infantry:
team2.append(unit)
teams = [team1, team2]
我尝试做的是用生成的类实例填充两个列表。然后迭代这些列表以对其中的实例执行各种操作。但是,每当我尝试做任何事情时,我都会收到错误List object has no attribute [attribute]
我很清楚我应该将每个类别的单元组成一个继承自单元类的类,我只是想知道这是否绝对有必要使这项工作以及为什么我的方式这样做是行不通的。
答案 0 :(得分:5)
你的问题在这里:
for unit in team_1_cavalry, team_1_infantry, team_1_elephants:
这是迭代元组team_1_cavalry, team_1_infantry, team_1_elephants
。因此,首先unit
是整个列表team_1_cavalry
,然后是整个列表team_1_infantry
,然后它就是整个列表team_1_elephants
。
您想要的是以下之一:
for unit_group in team_1_cavalry, team_1_infantry, team_1_elephants:
for unit in unit_group:
for unit in team_1_cavalry + team_1_infantry + team_1_elephants:
for unit in itertools.chain(team_1_cavalry, team_1_infantry, team_1_elephants)
第二个可能是最简单的 - 只要你知道你正在制作一个不必要的大临时列表,并且这个列表总是足够小,以至于没有性能影响。
但是,如果你真的不需要三个单独的列表,为什么甚至创建它们呢?如果你这样做可能会更简单:
team_1 = [(Unit('Cavalry', i+20, 10, 'A', libtcod.yellow, 6, 1, 1000, 100, 1.5, 500, 1)) for i in range(11) ]
team_1 += [(Unit('Heavy Infantry', i+20, 9, '=', libtcod.yellow, 3, 1, 2000, 100, 1.0, 200, 1)) for i in range(11)]
team_1 += [(Unit('War Elephants', 20, 8, 'R', libtcod.yellow, 5, 1, 37, 100, 100, 800, 1)) for i in range(2)]
现在,team_1
只是团队1中所有三种类型的单位。
答案 1 :(得分:1)
在:
self.navigationItem.rightBarButtonItem=right;
您正在构建列表列表(team1和team2是列表)。
如果您想创建2个单一列表:
UIBarButtonItem
*buttonItem = [UIBarButtonItem appearance];
NSMutableDictionary *textAttributes = [NSMutableDictionary dictionary];
[textAttributes setObject:[UIColor blackColor] forKey:UITextAttributeFont];
[buttonItem setTitleTextAttributes:textAttributes forState:UIControlStateNormal];
正如你所说,你应该考虑使用类。