Search code examples
pythondictionarychess

Python: modifying a value in one dictionary changes another dictionary


I'm making a chess program on Python by using dictionaries, and to set up my board I do:

EmptyBoard = {
    8:['☐','☒','☐','☒','☐','☒','☐','☒'],
    7:['☒','☐','☒','☐','☒','☐','☒','☐'],
    6:['☐','☒','☐','☒','☐','☒','☐','☒'],
    5:['☒','☐','☒','☐','☒','☐','☒','☐'],
    4:['☐','☒','☐','☒','☐','☒','☐','☒'],
    3:['☒','☐','☒','☐','☒','☐','☒','☐'],
    2:['☐','☒','☐','☒','☐','☒','☐','☒'],
    1:['☒','☐','☒','☐','☒','☐','☒','☐'],
    ' ':['⒜','⒝','⒞','⒟','⒠','⒡','⒢','⒣']
    }   #regular letters aren't wide enough

Default = {
    8:['♜','♞','♝','♛','♚','♝','♞','♜'],
    7:['♟','♟','♟','♟','♟','♟','♟','♟'],
    2:['♙','♙','♙','♙','♙','♙','♙','♙'],
    1:['♖','♘','♗','♕','♔','♗','♘','♖']
    }

Board = {}

def NewGame():
    Board.update(EmptyBoard)
    Board.update(Default)
    # some more code

NewGame()

this is fine until I have to edit a block in Board like so:

Board[3][2] = "X"
print(EmptyBoard[3][2]) # ==> Results in 'X', should stay '☐' or '☒'

this changes both Board[x][y] and whichever one of EmptyBoard and Default that [x][y] happens to be in.

This clones the pieces for every move after their first.

How do I make it so that only Board is edited?


Solution

  • Both Default and EmptyBoard are dictionaries from something to list. When you call update in NewGame, you set Board[3] (for example) to refer to the exact same list as EmptyBoard[3]. Then, if you write something like:

    Board[3][4] = X
    

    you change that list - which is shared between Board and EmptyBord (or Board and Default).

    To fix it, use deepcopy:

    import copy
    
    def NewGame():
        Board.update(copy.deepcopy(EmptyBoard))
        Board.update(copy.deepcopy(Default))
        ...
    

    One more thing - the convention is to start variables in python with a small letter.