canCastleKingSide static method

bool canCastleKingSide(
  1. ChessBoardInterface board,
  2. PieceColor color
)

Validates if a king-side castling move is legal for the given color (player) on the board.

Implementation

static bool canCastleKingSide(ChessBoardInterface board, PieceColor color) {
  if (hasLostCastlingRights(board, color, true)) {
    return false; // Castling lost
  }

  int row = (color == PieceColor.white) ? 7 : 0;
  if (board.getPiece(Position(row: row, col: 5)) != null ||
      board.getPiece(Position(row: row, col: 6)) != null) {
    return false;
  }

  if (board.isKingInCheck()) return false;

  ChessBoardInterface tempBoard = board.deepCopy();
  tempBoard.movePiece(Position(row: row, col: 4), Position(row: row, col: 5));
  if (tempBoard.isKingInCheck()) return false;

  tempBoard = board.deepCopy();
  tempBoard.movePiece(Position(row: row, col: 4), Position(row: row, col: 6));
  if (tempBoard.isKingInCheck()) return false;

  return true;
}