Search code examples
chessbitboard

Given a chess app built with magic bitboard how do I check for checkmate?


OK, I have this chess app built with bitboard and I want to check if a given move put the opponent pieces in checkmate.

Verifying a check situation is easy. You build the bitmask of the enemy pieces' attack and you AND that with the bitmask of the opposite king, if the result is not zero, you have a check.

But what about check mate? A checkmate is something that will happen after the check. I mean, I move a piece, the app detects that the move generated a check. Then how do I know if this check is a check mate? Do I have to generate all possible bitboards for all possible plays of the opponent and check if there is a move that can remove the king from check? This not appears to be practical. Is there another way?


Solution

  • I don't think there is any other way. The final algorithm to me looks like:

  • Obviously, firstly check if by moving the king the opponent may run away from the check.
  • For each opponent's piece check if it is "pinned" (that means that by moving it the opponents clears the way for any other check). Just temporarily "remove" it from the board and see if after that a new check is created.
  • If it is not pinned: check if by moving that piece the opponent may block the check condition. This is done by intersecting two subsets of cells: one is a set of cells, where the opponent's piece may move, the other is a "line" between the opponent's king and the figure that attacks, and, therefore, "checks" it.
  • If these subsets intersect and the condition in the second step is passed - looks like the current situation is **not** a checkmate.
  • If there is no figure that is not forked __AND__ can block the check - the situation __is__ a checkmate.