How do I avoid infinite recursion when checking if a chess move is legal?

95 views Asked by At

I am creating a chess game in Python for a school project, but don't know how to check if a move is legal without causing a stack overflow.

  1. My algorithm works by making the move
  2. Checking if the king is now in check (by seeing if the king's position is in a piece's legal moves)
  3. Undoing the move and checking the next

If any move places the king in check, the move is illegal, so I don't return it.

I have defined the Board as a 2d list:

[[None for i in range(8)] for j in range(8)]

with pieces on each correct position, and I have defined a method in each piece class to return a list of legal moves. However, I don't know how to check if a move puts the king in check, thus meaning it is illegal. I tried by making a move, then calling the in_check method:

def in_check(self, colour):
    king_pos = None
    for piece in pieces:
      if isinstance(piece, King) and piece.colour == colour:
        king_pos = piece.pos
        break

    return bool([piece for piece in pieces if king_pos in piece.legal_moves(self.board.board)])

to see if it put the king in check, but that in turn calls each piece's legal_moves method:

new_legal_moves = []
for move in legal:
    g.board.move_piece(self.pos, move)
    if not g.in_check(self.colour):
        new_legal_moves.append(move)

    g.board.move_piece(move, self.pos)

    return new_legal_moves

How do I avoid avoid infinite recursion?

Added the rest of my code here: https://pastebin.com/GP4z5KuX

0

There are 0 answers