0

I'm new to Python and I'm making my own chess game to help learn it. I know this topic has been covered a lot, but I don't understand how to apply the answers I've found to my specific situation.

Here's a very basic overview of the problem:

class blank:
    def __init__(self,row,col):
        self.row = row
        self.col = col

    def __str__(self):
        return '.'

class pawn:
    def __init__(self,row,col):
        self.row = row
        self.col = col

    def __str__(self):
        return 'p'

def addpiece(brd,tr,tc):
    nb = brd
    nb[tr][tc] = pawn(tr,tc)
    return nb

original_board = [[blank(rr,cc) for rr in range(8)] for cc in range(8)]
for row1 in original_board: print(' '.join([str(elem) for elem in row1]))
print('=====\n')

new_board = addpiece(original_board,1,1)
for row2 in original_board: print(' '.join([str(elem) for elem in row2]))

Each piece type (and a blank square) is a class; the board is a list of lists. If I want to see if a potential move will put the player in check, I made duplicate board (new_board), so the original_board variable is supposed to stay the same for the moment. I change one of the squares in the new_board (e.g., put a pawn in the middle), but the original_board variable changes anyway.

I know the problem has something to do with the variable ID following original_board into the function and assigning it to the dummy variable nb. I suppose I could change the original_board to a tuple of tuples and then change it back afterwards, but that doesn't seem very elegant. Any suggestions? Thanks.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

1

The problem is nb = brd doesn’t create a copy, it just creates a new reference to the same object. You can try using deepcopy instead:

from copy import deepcopy
nb = deepcopy(brd)
Jaime M
  • 161
  • 6