isKingInCheck method

bool isKingInCheck()

Checks if the king is in check.

Implementation

bool isKingInCheck() {
  int kingRow = -1, kingCol = -1;

  // Locate the king.
  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.type == PieceType.king &&
          piece.color == turn) {
        kingRow = row;
        kingCol = col;
        break;
      }
    }
  }

  // Check if any opponent's piece can attack the king.
  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) {
        if (MoveValidator.isValidMove(
          this,
          Position(row: row, col: col),
          Position(row: kingRow, col: kingCol),
        )) {
          return true;
        }
      }
    }
  }
  return false;
}