Home > Mobile >  cannot pickle socket object python
cannot pickle socket object python

Time:01-04

I have a chess game and to check the valid moves which doesn't give a check to the king, I use is_check() method. In that, I use deepcopy to copy the board object. It used to work earlier without any exceptions, but recently I connected my chess game my localhost database and it has been giving me cannot pickle socket object error. Here is my code for the above part.

def in_check(self, piece, move):
    # create a deep copy of the piece and the board
    temp_piece = copy.deepcopy(piece)

    temp_board = copy.deepcopy(self)

    # move the piece on the deep copy of the board
    temp_board.move(temp_piece, move)

    # check if any rival pieces can capture the king
    for row in range(TABLE_ROWS):
        for col in range(TABLE_COLUMNS):
            if temp_board.squares[row][col].has_rival(piece.color):
                p = temp_board.squares[row][col].piece

                temp_board.calc_moves(p, row, col, bool=False)
                for m in p.valid_moves:
                    if isinstance(m.final.piece, King):
                        return True
    return False 

this temp_board = copy.deepcopy(self) is the line giving me the error. I tried asking ChatGPT but it keeps giving code which tries to exclude socket but it doesn't work. Anybody got any idea what I can do? greatly appreciated.

edit: I think I should also mention that this exception occurs only when I load the game and not when I start a new game. It works perfectly when I start a new game but when I load/resume a game. It gives me this error.

CodePudding user response:

I finally figured out the error. all of these things happen inside a class Board. when the game is loaded it creates an instance of the SQL connection called self.data and it could not be deepcpoied. To fix that, I deleted the MySQL object once it loaded the game data from the database. here is the code,

class Board:

   def __init__(self):
    global uid, game_load
    self.black_king_col = None
    self.black_king_row = None
    self.squares = [[0, 0, 0, 0, 0, 0, 0, 0] for _ in range(TABLE_COLUMNS)]
    self.create()  # Calling this function creates the board for the game
    self.last_move = None

    if game_load:
        self.data = SqlData()
        self.data.load_data("white", uid)
        self.data.load_data("black", uid)
        self.load_pieces("white")
        self.load_pieces("black")
        game_load = False
        del self.data   #  This deletes once the above execution is over.

since object is deleted it will not be copied and not cause the error, and also setting the game_load to false because I do not want this block of code to execute again.

To explain the lines above. I am loading the pieces data from the database into csv files and then fetching that data to my game.

  • Related