我一直在嘗試編寫一個簡單的井字棋遊戲大約1周>。 <'一個簡單程序中的錯誤:TypeError:into object has no attribute'__getitem__'
完整的源:http://pastebin.com/6dgjen9u
在測試我的程序在main()
:
,我發現了錯誤:
File "x:\programming\python\tac.py", line 64, in display_board
print "\n\t", board[0], " |", board[1], " |", board[2]
TypeError: 'int' object has no attribute '__getitem__'
該負責功能在這裏:
def display_board(board):
""" Display game board on screen."""
print "\n\t", board[0], " |", board[1], " |", board[2]
print "\t", "------------"
print "\t", board[3], " |", board[4], " |", board[5]
print "\t", "------------"
print "\t", board[6], " |", board[7], " |", board[8], "\n"
def cpu_move(board, computer, human):
""" Takes computer's move + places on board."""
# make a copy of the board
board = board[:]
bestmoves = (0,2,6,8,4,3,5,1,7)
# if computer can win, play that square:
for move in legal_moves(board):
board[move] = computer
if winning_board(board) == computer:
print "[debug] cpu win:", move
return move
# undo the move because it was empty before
board[move] = EMPTY
# if player can win, block that square:
for move in legal_moves(board):
board[move] = human
if winning_board(board) == human:
print "[debug] block human:", move
return move
board[move] = EMPTY
# chose first best move that is legal
for move in bestmoves:
if move in legal_moves(board):
board[move] = computer
print "[debug] next best move:", move
return move
def change_turn(turn):
if turn == X:
return O
else:
return X
def main():
human, computer = go_first()
board = new_board()
display_board(board)
turn = X
while winning_board(board) == None:
if human == turn:
board = human_move(board, human)
turn = change_turn(turn)
display_board(board)
else:
board = cpu_move(board, computer, human)
turn = change_turn(turn)
display_board(board)
我不知道是什麼導致錯誤,因爲display_board(board)
適用於人類的行動。當計算機採取行動時,它就會失敗。
這是正確的。我對返回值感到困惑。我應該已經完成了'return board' – BBedit
@ user2071506是的,你沒有發佈的追蹤可能已經告訴你哪一行介紹了錯誤 – zhangxaochen