Python 中的国际象棋:列表索引必须是整数,而不是 str

Chess in Python: list indices must be integers, not str

我在 python 写了国际象棋的早期版本。我对此有疑问:

File "C:/Users/Goldsmitd/PycharmProjects/CHESS/chess_ver0.04.py", line 39, in move self.board[destination_x][destination_y] = 1 TypeError: list indices must be integers, not str

我的代码:

class Chess_Board:
    def __init__(self):
        self.board = self.create_board()

    def create_board(self):
        board_x=[]

        for x in range(8):
            board_y =[]
            for y in range(8):
                if (x==7 and y==4):
                    board_y.append('K')

                elif (x== 7 and y == 3):
                   board_y.append('Q')

                else:
                   board_y.append('.')

            board_x.append(board_y)

        return board_x


class WHITE_KING(Chess_Board):
    def __init__(self):
        Chess_Board.__init__(self)
        self.symbol = 'K'
        self.position_x = 7
        self.position_y = 4


    def move (self):

        print ('give x and y cordinates fo white king')
        destination_x = input()
        destination_y = input()

        self.board[destination_x][destination_y] = 'K'

不知道什么不行

input() 收到的值具有 'string' 类型(即使它看起来像数字),所以你应该把它转换成整数。

self.board[int(destination_x)][int(destination_y)] = 'K'

如果您输入的不是数字,上面的代码将失败,因此最好在之前添加额外的检查:

def move (self):
    destination_x = None
    destination_y = None
    while not (destination_x and destination_y):
        print ('give x and y cordinates fo white king')
        try:
            destination_x = int(input())
            destination_y = int(input())
        except ValueError as e:
            pass
    self.board[destination_x][destination_y] = 'K'