0
我是Python的初学者,我遇到了一些项目问题。无法在网格上的特定位置返回python中的元素
我的网格看起来像这样:
class World(object):
def __init__(self):
self.grid = []
xsize = 20
ysize = 20
self.maxX = xsize
self.maxY = ysize
for irow in range(self.maxY):
row = []
for icol in range(self.maxX):
row.append(None)
self.grid.append(row)
positions = []
for i in range(self.maxX):
for j in range(self.maxY):
positions.append((i,j))
numteam1 = 0
numteam2 = 0
numrobot = 0
randpos = random.sample(positions, numteam1 + numteam2)
team1 = randpos[0:numrobot-1]
team2 = randpos[numrobot:]
for point in team1:
x = point[0]
y = point[1]
self.grid[y][x] = AttackRobot(1, x, y, self)
self.grid[y][x] = MedicRobot(1, x, y, filename)
for point in team2:
x = point[0]
y = point[1]
self.grid[y][x] = AttackRobot(2,x,y,self)
self.grid[y][x] = MedicRobot(2,x,y,self, filename)
,然后我有这个方法:
def test_position(self, x, y):
if x <0 or x >= 20:
return None
if y <0 or y >= 20:
return None
else:
return (self.grid[y][x] = Robot)
此fonction假定在(X,Y)在网格上以返回元件
然后我用这种方法:
def print_board(w):
print "-" * 60
for y in range(19,-1,-1):
line = ""
for x in range(0,20):
r = w.test_position(x, y)
if r == None:
line += ".... "
else:
if isinstance(r, AttackRobot):
rtype = "A"
elif isinstance(r, MedicRobot):
rtype = "M"
else:
rtype = "!"
if r.get_team() == 1:
line += "%s%02i%s " % (rtype, r.get_health(), r.get_direction())
else:
line += "%s%02i%s " % (rtype.lower(), r.get_health(), r.get_direction())
print line
print "-" * 60
我得到一个错误。
Traceback (most recent call last):
File "T05.py", line 10, in <module>
print_board(world)
File "/Users/quentindumoulin/Desktop/test.py", line 19, in print_board
if r.get_team() == 1:
AttributeError: 'bool' object has no attribute 'get_team'
我相信你的意思是用'return self.grid [y] [x] == Robot'来结束'test_position'(注意两个等号);那不就是一个解析错误吗? – jwodder
@jwodder:根据'print_board'中的逻辑,我简单地认为'return self.grid [x] [y]'更有可能是什么意思(不知道'= Robot'从哪里偷偷来了)。 – Mac