我正在编写Tic-Tac-Toe游戏。我完成了大部分程序。但我不断收到以下错误,我不明白我做错了什么。我尝试过不同的格式化。
Traceback (most recent call last):
File "C:/Users/Akshay Sastry/Documents/CS 303E/Tic-Tac-Toe.py", line 66, in <module>
main()
File "C:/Users/Akshay Sastry/Documents/CS 303E/Tic-Tac-Toe.py", line 3, in main
while isWinner(board) == 0 and movesLeft(board) == True:
File "C:/Users/Akshay Sastry/Documents/CS 303E/Tic-Tac-Toe.py", line 20, in isWinner
if (b[0][0]=='x') and (b[0][0]==b[0][1]==b[0][2]):
TypeError: 'NoneType' object has no attribute '__getitem__'
这是我的代码:
def main():
board = makeBoard()
while isWinner(board) == 0 and movesLeft(board) == True:
printBoard(board)
p1row, p1col = input("Enter a row and column for x: ")
board[p1row][p1col] = 'x'
if isWinner(board) == 0 and movesLeft(board) == True:
printBoard(board)
p2row, p2col = input("Enter a row and column for o: ")
board[p2row][p2col] = 'o'
if isWinner(board) != 0:
print isWinner(board), 'won!'
else:
print 'Tie game.'
def makeBoard():
board = [['*','*','*'],['*','*','*'],['*','*','*']]
def isWinner(b):
if (b[0][0]=='x') and (b[0][0]==b[0][1]==b[0][2]):
return 'x'
elif (b[1][0]=='x') and (b[1][0]==b[1][1]==b[1][2]):
return 'x'
elif (b[2][0]=='x') and (b[2][0]==b[1][1]==b[2][2]):
return 'x'
elif (b[0][0]=='x') and (b[0][0]==b[1][0]==b[2][0]):
return 'x'
elif (b[0][1]=='x') and (b[0][1]==b[1][1]==b[2][1]):
return 'x'
elif (b[0][2]=='x') and (b[0][2]==b[1][2]==b[2][2]):
return 'x'
elif (b[0][0]=='x') and (b[0][0]==b[1][1]==b[2][2]):
return 'x'
elif (b[0][2]=='x') and (b[0][2]==b[1][1]==b[2][0]):
return 'x'
elif (b[0][0]=='o') and (b[0][0]==b[0][1]==b[0][2]):
return 'o'
elif (b[1][0]=='o') and (b[1][0]==b[1][1]==b[1][2]):
return 'o'
elif (b[2][0]=='o') and (b[2][0]==b[1][1]==b[2][2]):
return 'o'
elif (b[0][0]=='o') and (b[0][0]==b[1][0]==b[2][0]):
return 'o'
elif (b[0][1]=='o') and (b[0][1]==b[1][1]==b[2][1]):
return 'o'
elif (b[0][2]=='o') and (b[0][2]==b[1][2]==b[2][2]):
return 'o'
elif (b[0][0]=='o') and (b[0][0]==b[1][1]==b[2][2]):
return 'o'
elif (b[0][2]=='o') and (b[0][2]==b[1][1]==b[2][0]):
return 'o'
else:
return 0
def printBoard(board):
for i in range(3):
for j in range(3):
print board[i][j],
print
def movesLeft(board):
if board[0].count("*") != 0 or board[1].count("*") != 0 or board[2].count("*") != 0:
return True
else:
return False
main()
答案 0 :(得分:3)
您的makeBoard()
函数返回None
。你应该这样做:
def makeBoard():
return [['*','*','*'],['*','*','*'],['*','*','*']]
答案 1 :(得分:1)
您的isWinner
功能可以缩小3倍,如下所示
def isWinner(b):
for i in range(3):
if (b[i][0] != '*') and (b[i][0]==b[i][1]==b[i][2]): # all rows
return b[i][0]
if (b[0][i] != '*') and (b[0][i]==b[1][i]==b[2][i]): # all cols
return b[0][i]
if (b[0][0] != '*') and (b[0][0]==b[1][1]==b[2][2]): # tl-br diag
return b[0][0]
elif (b[0][2] != '*') and (b[0][2]==b[1][1]==b[2][0]): # bl-tr diag
return b[0][2]
else:
return 0
然而,对于更大的电路板,例如连接4,你将遍历电路板上的所有点并编写一个方法,在每个方向上检查一个任意距离的循环,而不是对一行中的每个位置进行硬编码在。。