我正在編寫一個Tic-Tac-Toe遊戲。我完成了大部分程序。但我不斷收到以下錯誤,我不明白我做錯了什麼。我嘗試過不同的格式。Tic-Tac-Toe TypeError:'NoneType'對象沒有屬性'__getitem__'
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()
哇!不能相信我錯過了那個。謝謝! – user2303670 2013-04-21 05:07:47