I'm attempting to build a chess engine from scratch in Python. Part of this involves storing the current position in a 2D array and updating the position after a move. I have discovered a frustratingly bizarre behaviour when writing the "move" code:
Initial position is this array, where '00' indicates an empty square:
position
[['WR', 'WN', 'WB', 'WQ', 'WK', 'WB', 'WN', 'WR'],
['Wp', 'Wp', 'Wp', 'Wp', 'Wp', 'Wp', 'Wp', 'Wp'],
['00', '00', '00', '00', '00', '00', '00', '00'],
['00', '00', '00', '00', '00', '00', '00', '00'],
['00', '00', '00', '00', '00', '00', '00', '00'],
['00', '00', '00', '00', '00', '00', '00', '00'],
['Bp', 'Bp', 'Bp', 'Bp', 'Bp', 'Bp', 'Bp', 'Bp'],
['BR', 'BN', 'BB', 'BQ', 'BK', 'BB', 'BN', 'BR']]
I try to move a white pawn from [1,2] to [2,2]:
position[1][2]='00'
position[2][2]='Wp'
But now the output has additionally written a white pawn to [3,2], [4,2] and [5,2]!
position
[['WR', 'WN', 'WB', 'WQ', 'WK', 'WB', 'WN', 'WR'],
['Wp', 'Wp', '00', 'Wp', 'Wp', 'Wp', 'Wp', 'Wp'],
['00', '00', 'Wp', '00', '00', '00', '00', '00'],
['00', '00', 'Wp', '00', '00', '00', '00', '00'],
['00', '00', 'Wp', '00', '00', '00', '00', '00'],
['00', '00', 'Wp', '00', '00', '00', '00', '00'],
['Bp', 'Bp', 'Bp', 'Bp', 'Bp', 'Bp', 'Bp', 'Bp'],
['BR', 'BN', 'BB', 'BQ', 'BK', 'BB', 'BN', 'BR']]
I assume this is because Python assumes all of the empty rows are the same object, so updates all of them together. How do I get around this, and only update the row that I specify?
EDIT in reply to requests for the position definition:
# Set up starting position
position=[['00']*8]*8
position[0]=['WR','WN','WB','WQ','WK','WB','WN','WR']
position[1]=['Wp']*8
position[6]=['Bp']*8
position[7]=['BR','BN','BB','BQ','BK','BB','BN','BR']