I wrote early version of chess in python. I have a problem with this:
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
my code:
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'
I don't know what does not work
The value recieved from input() has a 'string' type (even if it looks like number), so you should convert it to integer.
self.board[int(destination_x)][int(destination_y)] = 'K'
The code above will fail if you enter something else than digits, so it is better to add an additional check before:
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'