I have come across something in Python that I don't understand.
I wrote some code that plays legal chess moves. The position of the pieces is remembered in a dictionary that I've called board
, with an integer representing the square as a key, and the name of a piece as its value.
These values obviously change as the game progresses. I wanted to add a reset button, and originally thought I could just create a backup (e.g. backup = board
), and then a function that would say board = backup
. I've found this works but only if I add a second statement of the dictionary.
Here is some code that might make it clearer:
board = {11: 'white rook', 12: 'white knight', 13: 'white bishop'}
backup = board
# if I comment out this next line the code doesn't work
board = {11: 'white rook', 12: 'white knight', 13: 'white bishop'}
def move_knight():
board[12] = 'empty' # as the knight moves away
def reset():
global board
board = backup
print("board in reset function =", board)
move_knight()
print("board after knight's move =", board)
reset()
print("board after reset =", board)
In a sense I have solved my problem but would like to understand why.