I've been trying to program a simple Tic-Tac-Toe game for about 1 week now >.<'
Full source: http://pastebin.com/6dgjen9u
When testing my program in main():
I'm getting the error:
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__'
The responsible functions here:
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)
I have no idea what is causing the error because display_board(board) works fine for the human's move. It just fails when the computer takes its move.