我一直在尝试编写一个简单的Tic-Tac-Toe游戏大约1周>。<'
完整来源: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)
对于人类的行动很有效。它只是在计算机移动时失败。
答案 0 :(得分:1)
cpu_move
在此处返回一个整数:
return move
更改它以返回列表。
答案 1 :(得分:1)
我没有看到human_move
函数,但无论如何,你的问题是你试图索引一个整数。
当您从board
返回cpu_move
时,您将返回一个int。看看你要返回的内容:你正在返回move
,这是一个整数,并且没有__getitem__
方法(这是索引调用的方法)。
答案 2 :(得分:1)
您的cpu_move
函数可能会在此处返回int
:
for move in bestmoves:
if move in legal_moves(board):
board[move] = computer
print "[debug] next best move:", move
return move
当您将此值用于display_board
函数时,这可能是问题所在:
board = cpu_move(board, computer, human)
turn = change_turn(turn)
display_board(board)