2014-03-02 76 views
1

我一直在嘗試編寫一個簡單的井字棋遊戲大約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)適用於人類的行動。當計算機採取行動時,它就會失敗。

回答

1

cpu_move這裏返回一個整數:

return move 

更改它返回一個列表。

+0

這是正確的。我對返回值感到困惑。我應該已經完成​​了'return board' – BBedit

+0

@ user2071506是的,你沒有發佈的追蹤可能已經告訴你哪一行介紹了錯誤 – zhangxaochen

1

我沒有看到human_move函數,但無論如何,你的問題是你試圖索引一個整數。

當您返回board時,從cpu_move您返回一個int。看看你回來的東西:你回來了move,這是一個整數,並沒有__getitem__方法(這是索引調用的方法)。

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) 
相關問題