2015-08-20 61 views
-2

我在python中编写了早期版本的国际象棋。我有这样一个问题:Python中的国际象棋:列表索引必须是整数,而不是str

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' 

我不知道什么行不通

+0

Downvote的问题是googleable容易,对不起。 – xXliolauXx

回答

2

输入(收到的值)“字符串'类型(即使它看起来像数字),所以你应该将其转换为整数。

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' 
+0

'self.board [None] [None]'也会失败 –

+0

@PadraicCunningham我已经添加了完整的move()方法代码,它在这些变量中不允许为None,当然这只是一个示例 – svfat

+1

您还应该捕获destination_x或destination_y在界限之外的位置 –

相关问题