I am making a chess game and have a class function that calculates all the legal moves. It does so by having a piece as a parameter and gets all its possible attacking moves. It then loops through these moves and move the piece their temporarily to see if that moves puts himself in check, if it does then it isn't a legal move:
def calculate_legal_moves(self, piece):
"""Get all the legal moves of a piece and returns them"""
legal_moves = []
if not isinstance(piece, Pawn):
possible_legal_moves = self.get_attacking_moves(piece)
for move in possible_legal_moves:
if isinstance(self.board[move[0]][move[1]], Piece):
if not piece.colour == self.board[move[0]][move[1]].colour:
possible_board = self.preliminary_move_piece(self.board, piece.position, move)
if not self.is_in_check(piece.colour, possible_board):
legal_moves.append(move)
else:
possible_board = self.preliminary_move_piece(self.board, piece.position, move)
if not self.is_in_check(piece.colour, possible_board):
legal_moves.append(move)
else:
if piece.colour == "White":
legal_moves.append([piece.position[0]-1, piece.position[1]])
if piece.position[0] == 6:
legal_moves.append([piece.position[0]-2, piece.position[1]])
else:
legal_moves.append([piece.position[0]+1, piece.position[1]])
if piece.position[0] == 1:
legal_moves.append([piece.position[0]+2, piece.position[1]])
return legal_moves
def preliminary_move_piece(self, chess_board, old_coords, new_coords):
chess_board[new_coords[0]][new_coords[1]] = self.board[old_coords[0]][old_coords[1]]
chess_board[old_coords[0]][old_coords[1]] = 0
if isinstance(chess_board[new_coords[0]][new_coords[1]], Piece):
chess_board[new_coords[0]][new_coords[1]].position = [new_coords[0], new_coords[1]]
return chess_board
The problem is, that I pass in the instance of the board (a 2d array) and move a piece temporarily to see if that puts him in check, however it seems to be passing the instance variable by reference and so is actually permanently changing the pieces position, thus my piece automatically moves to the last possible legal move when i click on it. Is there a way that I can leave my instance variable (self.board) untouched when i use the preliminary_move_piece function