Search for Mate

Before we can discus move searching and the Alpha Beta algorithm we need a way to check for check mates. This method will actually be located in our static Search class. This method will loop through all of the moves for all the chess pieces on the board and see if they actually have a valid move. If they do then we are not in a check mate situation. If there aren’t any valid moves for this board position that we know that this is either a check mate (if the king is in check) or a stale mate. This method is very expensive to execute so we only call it if there is a check on any king on the board or if there are 0 possible moves. I will explain in more detail in my Alpha Beta method.

The Search for Mate method returns true if a check mate or stale mate is found. The actual values of type of mate and side mated are stored in the three reference variables passed into the method.

internal static bool SearchForMate(ChessPieceColor movingSide, Board examineBoard, ref bool blackMate, ref bool whiteMate, ref bool staleMate)
{
 bool foundNonCheckBlack = false;
 bool foundNonCheckWhite = false;
 for (byte x = 0; x < 64; x++)
 {
  Square sqr = examineBoard.Squares[x];

  //Make sure there is a piece on the square
  if (sqr.Piece == null)
   continue;

  //Make sure the color is the same color as the one we are moving.
  if (sqr.Piece.PieceColor != movingSide)
   continue;

  //For each valid move for this piece
  foreach (byte dst in sqr.Piece.ValidMoves)
  {

   //We make copies of the board and move so we don't change the original
   Board board = examineBoard.FastCopy();

   //Make move so we can examine it
   Board.MovePiece(board, x, dst, ChessPieceType.Queen);

   //We Generate Valid Moves for Board
   PieceValidMoves.GenerateValidMoves(board);

   if (board.BlackCheck == false)
   {
    foundNonCheckBlack = true;
   }
   else if (movingSide == ChessPieceColor.Black)
   {
    continue;
   }

   if (board.WhiteCheck == false )
   {
    foundNonCheckWhite = true;
   }
   else if (movingSide == ChessPieceColor.White)
   {
    continue;
   }
  }
 }

 if (foundNonCheckBlack == false)
 {
  if (examineBoard.BlackCheck)
  {
   blackMate = true;
   return true;
  }
  if (!examineBoard.WhiteMate && movingSide != ChessPieceColor.White)
  {
   staleMate = true;
   return true;
  }
 }

 if (foundNonCheckWhite == false)
 {
  if (examineBoard.WhiteCheck)
  {
   whiteMate = true;
   return true;
  }
  if (!examineBoard.BlackMate && movingSide != ChessPieceColor.Black)
  {
   staleMate = true;
   return true;
  }
 }

 return false;
}

The Search for Mate method is also used in your Chess Engine Make Move method which will check if the last move made by the human player caused a check mate. This will be done every time a player makes a move.

Want to skip to the end, download the full chess engine source code on GitHub