isCheckmate method

bool isCheckmate()

Checks if the game is in a checkmate state. turn is the player loses the game

Implementation

bool isCheckmate() {
  if (!isKingInCheck()) return false;

  // Try all possible moves for the king's color to see if any escape check.
  for (int row = 0; row < 8; row++) {
    for (int col = 0; col < 8; col++) {
      ChessPiece? piece = getPiece(Position(row: row, col: col));
      if (piece != null && piece.color == turn) {
        for (int newRow = 0; newRow < 8; newRow++) {
          for (int newCol = 0; newCol < 8; newCol++) {
            if (MoveValidator.isValidMove(
              this,
              Position(row: row, col: col),
              Position(row: newRow, col: newCol),
            )) {
              ChessPiece? capturedPiece = getPiece(
                Position(row: newRow, col: newCol),
              );
              movePiece(
                Position(row: row, col: col),
                Position(row: newRow, col: newCol),
              );
              bool stillInCheck = isKingInCheck();
              movePiece(
                Position(row: newRow, col: newCol),
                Position(row: row, col: col),
              );
              board[newRow][newCol] = capturedPiece; // Restore piece
              if (!stillInCheck) return false;
            }
          }
        }
      }
    }
  }
  return true;
}