Error using deepcopy in board object to validate the legal moves in a chess game implementation using python

71 views Asked by At

I've been working on my chess game project and tackling the challenge of implementing the logic for checks and checkmates. One issue arose when pieces continued to move despite obstructing the path of the piece attacking the king.

I've realized that there was no built-in mechanism to validate the legality of a move, so I decided to add it in the Piece class as a separate method. The logic inside the method was to create a duplicate of the board stored in a separate variable, ensuring it had a distinct reference from the original board. Manipulating this new reference, I then checked whether the board was in a check state after a move. If it was, the move was deemed illegal, so the method returned false, otherwise it returned true. I decided to use the deepcopy function from the copy module, however after running the program this error showed: TypeError: cannot pickle 'pygame.surface.Surface' object

This is the actual code block of the method:

    def is_legal_move(self,x,y,board):
        row,col = self.get_new_coordinates(x,y)
        #Almacenar tablero en una nueva variable para luego hacer los calculos de validación del movimiento
        board_copy = copy.deepcopy(board)
        board_copy.generate_moves()
        #Se iguala la pieza actual en el tablero a una nueva referencia
        piece_sample = board_copy.virtual_board[self.get_row()][self.get_column()]
        king = board_copy.get_king()
        enemy_pieces = board_copy.get_pieces()
        new_destination = (row,col)

        #Mover pieza de forma virtual
        board_copy.update_board_status(self.get_row(),self.get_column(),row,col,piece_sample)

        is_in_check = board_copy.is_in_check(king,enemy_pieces)

        if not board.checked_status:
            if is_in_check and (new_destination in self.moves):
                return False
            elif new_destination in self.moves:
               return True
            
        return False

virtual_board is an attribute of the Board class. It's a matrix in which I can visualize and manipulate the computer representation of the board so the changes that are done there are then represented visually with pygame

1

There are 1 answers

0
Sal On

The 'deepcopy' function uses pickling to create a deep copy of an objects. If that object cannot be pickled it will raise a type-error. (which is what is happening here) https://docs.python.org/3/library/copy.html

A better way to do this is to create a custom copying function

def customCopyBoard(self, board):
   #Assuming you have a constructor for your Board class
   newBoard = Board()
   for row in range(len(board.virtual_board)):
      for col in range(len(board.virtual_board[row])):
         p = board.virtual_board[row][col]
         if p:
            newBoard.virtual_board[row][col] = p.copy()
   return newBoard