这是我的代码,这是一个棋盘游戏。我不知道为什么我会犯这个错误:
TypeError: argument of type 'NoneType' is not iterable.
这个问题出现在move_tiger()
函数中,但是我在move_goat()
函数中使用了相同的代码,它工作得很好。有人能告诉我这个错误在我的例子中意味着什么吗,因为我认为我没有试图遍历move_tiger()
函数中的任何内容。谢谢你的帮助。
class Board:
def __init__(self):
self.board = dict()
# a, b, c, d, and e are keys
self.board['a'] = ['T']
self.board['b'] = ['0','T','0','0','T','0']
self.board['c'] = ['0','0','0','0','0','0']
self.board['d'] = ['0','0','0','0','0','0']
self.board['e'] = ['0','0','0','0']
self.phase = 'add'
self.numgoats = 0
def print_board(self):
for letter in 'abcde':
for vertex in self.board[letter]:
print vertex,
print
def content(self, position):
row=list(position)[0]
column=list(position)[1]
return self.board[row][int(column)]
def _set(self, position, value):
self.board[position[0]][position[1]] = value
def neighbors(self, position):
if position == ('a',0):
return [('b',1),('b',2),('b',3),('b',4)]
# bunch of extraneous elif's that all return something skipped
elif position == ('e',3):
return [('e',2),('d',4)]
def add_goat(self, position):
if self.phase == 'add':
if self.content(position) == '0':
self._set(position, 'G')
self.numgoats+=1
if self.numgoats==3:
self.phase = 'move'
def move_goat(self, old, new):
if self.phase!='move':
print "invalid move; try again"
elif self.content(old) == 'G' and self.content(new) == '0' and new in self.neighbors(old):
self.board[old[0]][old[1]] = '0'
self.board[new[0]][new[1]] = 'G'
else:
print "invalid move; try again"
def move_tiger(self, old, new):
if self.content(old) == 'T' and self.content(new) == '0' and new in self.neighbors(old):
self.board[old[0]][old[1]] = '0'
self.board[new[0]][new[1]] = 'T'
else:
print "invalid move; try again"
myboard = Board()
myboard.print_board()
myboard.add_goat(('b',0))
myboard.print_board()
myboard.add_goat(('c',0))
myboard.print_board()
myboard.add_goat(('d',0))
myboard.print_board()
myboard.move_goat(('c',0),('c',1))
myboard.print_board()
myboard.move_goat(('c',1),('b',5))
myboard.print_board()
myboard.move_tiger(('b',4),('b',3))
myboard.print_board
此代码生成以下内容:
T
0 T 0 0 T 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0
T
G T 0 0 T 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0
T
G T 0 0 T 0
G 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0
T
G T 0 0 T 0
G 0 0 0 0 0
G 0 0 0 0 0
0 0 0 0
T
G T 0 0 T 0
0 G 0 0 0 0
G 0 0 0 0 0
0 0 0 0
invalid move; try again
T
G T 0 0 T 0
0 G 0 0 0 0
G 0 0 0 0 0
0 0 0 0
Traceback (most recent call last):
File "game2.py", line 110, in <module>
myboard.move_tiger(('b',4),('b',3))
File "game2.py", line 91, in move_tiger
if self.content(old) == 'T' and self.content(new) == '0' and new in self.neighbors(old):
TypeError: argument of type 'NoneType' is not iterable
当
old
值为("b", 4)
时发生异常,因为self.neighbors(old)
返回None
。 我不确定是否完全理解代码的作用,但也许您应该检查一下在neighbors
方法中是否遗漏了一个case。在Python中,所有函数(和方法)都隐式地返回
None
,除非它们在执行期间到达显式的return
语句。似乎您的neighbours
方法接收到一个position
,它不被任何if-elif
分支所覆盖。尝试在
neighbours
中添加else
分支,以便可以看到意外的position
:相关问题 更多 >
编程相关推荐