python - 简单程序中的错误: TypeError: into object has no attribute '__getitem__'

标签 python function pygame

我已经尝试编写一个简单的 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) 对于人类的移动效果很好。当计算机采取行动时它就会失败。

最佳答案

cpu_move 在此处返回一个整数:

return move

将其更改为返回列表。

关于python - 简单程序中的错误: TypeError: into object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22130288/

相关文章:

python - 当我按下空格键时在我的鼠标位置画一个圆圈(Pygame)

python - 将不同列表中的两个元素组合成一个坐标元组

python - Python中枚举串口(包括虚拟端口)的跨平台方法是什么?

C函数参数神秘漂移?

php - 如何让PDO更简单

python - 矩形不会停止移动

python - Pygame 弹雨碰撞和残像

android - sl4a python 为安卓手机做一个Toast

python - 在 Django 应用程序中实现 memcached 需要哪些步骤?

Javascript 函数定义说明