From aa97abaadcea3a6ba34f32a4ff35ca44cad5abf4 Mon Sep 17 00:00:00 2001 From: claude Date: Sun, 11 Oct 2026 00:12:02 +0200 Subject: [PATCH] Add Chess960 (FRC) and DFRC support - castling moves are stored as "king takes own rook" (from = king square, to = castling rook square) - per-colour castling rook squares (Board::castleRook), so DFRC (different back ranks for white/black) works - FEN parsing/printing: KQkq (X-FEN) and Shredder-FEN file letters - Board::CanCastle(): generic castling legality (empty paths, king not attacked, rook x-ray check) - MakeMove handles arbitrary king/rook start squares (king and rook may stay in place or swap through each other's squares) - UCI_Chess960 option: castling printed/parsed as king-takes-rook when on, standard e1g1 style otherwise (both are accepted when parsing) - viri format, perft castle check and castling right updates no longer assume a1/h1/a8/h8 --- README.md | 1 + source/board.cpp | 202 +++++++++++++++++++++++++++++++++++++++------ source/board.h | 15 +++- source/move.h | 29 ++++--- source/movegen.tpp | 27 ++---- source/perft.cpp | 4 +- source/types.h | 5 +- source/uci.cpp | 7 ++ source/utils.cpp | 28 +++++-- 9 files changed, 247 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 2243450..7ed3989 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ You can interact with the engine via these commands: - `position startpos` - `ucinewgame` — Resets the position and game state +- `setoption name UCI_Chess960 value true` — Enables Chess960 (FRC / DFRC) castling notation (king takes own rook, e.g. `e1h1`). Positions can be given as `position fen [FEN]` with X-FEN or Shredder-FEN castling rights - `quit` — Terminates the program - `go` — Begins search and returns the best move - Parameters (all in **milliseconds**): diff --git a/source/board.cpp b/source/board.cpp index 2a3ec7f..d6ef388 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -20,7 +20,8 @@ #include "termcolor.hpp" void Board::Reset() { - castlingRights = 0; + castlingRights = 0; + castleRook = {h1, a1, h8, a8}; enPassantTarget = noEPTarget; halfMoves = 0; @@ -90,10 +91,10 @@ void Board::SetByFen(std::string_view fen) { sideToMove = tokens[1] == "b"; for (const char piece : tokens[2]) { - if (piece == 'K') castlingRights |= whiteKingRight; - else if (piece == 'Q') castlingRights |= whiteQueenRight; - else if (piece == 'k') castlingRights |= blackKingRight; - else if (piece == 'q') castlingRights |= blackQueenRight; + AddCastlingRight(piece); + + + } if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]); @@ -181,7 +182,7 @@ std::string Board::GetFen() { for (const auto& [right, symbol] : castlingOptions) { if (castlingRights & right) { - fen << symbol; + fen << CastlingSymbol(right, symbol); hasCastlingRights = true; } } @@ -849,8 +850,8 @@ void Board::RemovePiece(int piece, int square, bool color) { static void UpdateCastlingRights(Board &board, int square, int type, int color) { if (type == Rook) { board.hashKey ^= UTILS::zCastle[board.castlingRights]; - int queenSideRook = color ? a8 : a1; - int kingSideRook = color ? h8 : h1; + int queenSideRook = board.castleRook[Board::CastleIdx(color, false)]; + int kingSideRook = board.castleRook[Board::CastleIdx(color, true)]; if (square == queenSideRook) { board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight; @@ -903,6 +904,20 @@ void Board::MakeMove(Move move) { int newEpTarget = noEPTarget; + int castleRookFrom = -1; + int castleRookTo = -1; + + // Castling moves are stored as "king takes own rook" (to == rook square), which also covers Chess960. + // Translate them to the king's real destination so the rest of the function can treat the king like any other mover. + if (move.IsCastle()) { + const bool kingSide = move.GetFlags() == kingCastle; + const int backRank = move.MoveTo() & ~7; + + castleRookFrom = move.MoveTo(); + castleRookTo = backRank + (kingSide ? 5 : 3); + move = Move(move.MoveFrom(), backRank + (kingSide ? 6 : 2), move.GetFlags()); + } + int attackerPiece = GetPieceType(move.MoveFrom()); int attackerColor = GetPieceColor(move.MoveFrom()); @@ -980,32 +995,32 @@ void Board::MakeMove(Move move) { break; case kingCastle: { - int rookSquare = attackerColor ? h8 : h1; + int rookSquare = castleRookFrom; RemovePiece(Rook, rookSquare, attackerColor); - SetPiece(Rook, rookSquare - 2, attackerColor); + SetPiece(Rook, castleRookTo, attackerColor); SetPiece(attackerPiece, move.MoveTo(), attackerColor); { - accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook); + accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, castleRookTo, Rook, move.MoveFrom(), King, rookSquare, Rook); } break; } case queenCastle: { - int rookSquare = attackerColor ? a8 : a1; + int rookSquare = castleRookFrom; RemovePiece(Rook, rookSquare, attackerColor); - SetPiece(Rook, rookSquare + 3, attackerColor); + SetPiece(Rook, castleRookTo, attackerColor); SetPiece(attackerPiece, move.MoveTo(), attackerColor); { - accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook); + accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, castleRookTo, Rook, move.MoveFrom(), King, rookSquare, Rook); } break; @@ -1311,7 +1326,11 @@ bool Board::IsLegal(Move &move) { Bitboard king = pieces[King] & colors[us]; int kingSquare = king.getLS1BIndex(); - int moveType = move.GetFlags(); + int moveType = move.GetFlags(); + + // Castling is fully validated by CanCastle() (move generation / IsPseudoLegal) + if (moveType == kingCastle || moveType == queenCastle) + return true; if (moveType == epCapture) { int epCapturedSquare = to + (us == White ? -8 : 8); @@ -1365,7 +1384,7 @@ bool Board::IsPseudoLegal(Move &move) { const int movingPiece = GetPieceType(from); if (movingPiece == nullPieceType) return false; if (!colors[us].IsSet(from)) return false; - if (colors[us].IsSet(to)) return false; + if (colors[us].IsSet(to) && flag != kingCastle && flag != queenCastle) return false; const bool isCapture = move.IsCapture(); const int targetPiece = GetPieceType(to); @@ -1441,23 +1460,23 @@ bool Board::IsPseudoLegal(Move &move) { if (flag == kingCastle) { if (!(castlingRights & kingRight)) return false; - const U64 KingSide = us ? 0xf000000000000000ULL : 0xf0ULL; - const U64 mask = us ? 0x7000000000000000ULL : 0x70ULL; - const int targetSq = us ? g8 : g1; + + + const int targetSq = castleRook[CastleIdx(us, true)]; if (to != targetSq) return false; - if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false; - if (mask & colorThreats[them]) return false; + if (!CanCastle(us, true)) return false; + return true; } else { if (!(castlingRights & queenRight)) return false; - const U64 QueenSide = us ? 0x1f00000000000000ULL : 0x1fULL; - const U64 mask = us ? 0x1c00000000000000ULL : 0x1cULL; - const int targetSq = us ? c8 : c1; + + + const int targetSq = castleRook[CastleIdx(us, false)]; if (to != targetSq) return false; - if ((Bitboard(QueenSide) & occupied).PopCount() != 2) return false; - if (mask & colorThreats[them]) return false; + if (!CanCastle(us, false)) return false; + return true; } } @@ -1529,6 +1548,137 @@ void Board::CalcCheckZones() { checkZones[3] = MOVEGEN::getRookAttack(oppKingSquare, occupied); } +// Squares from a to b (both inclusive) on the same rank +static Bitboard CastleSpan(int a, int b) { + const int lo = std::min(a, b); + const int hi = std::max(a, b); + + return Bitboard((~0ULL << lo) & (~0ULL >> (63 - hi))); +} + +// Full castling legality (right, empty paths, king not attacked on its way) for standard chess, Chess960 and DFRC. +// Wherever they start, the king ends up on the g/c file and the rook on the f/d file of the back rank. +bool Board::CanCastle(bool us, bool kingSide) { + const int idx = CastleIdx(us, kingSide); + + if (!(castlingRights & (1 << idx))) + return false; + + const int base = us ? 56 : 0; + const int rookFrom = castleRook[idx]; + + Bitboard kings = pieces[King] & colors[us]; + if (!kings) + return false; + + const int kingFrom = kings.getLS1BIndex(); + + if ((kingFrom >> 3) != (base >> 3) || !(pieces[Rook] & colors[us]).IsSet(rookFrom)) + return false; + + const int kingTo = base + (kingSide ? 6 : 2); + const int rookTo = base + (kingSide ? 5 : 3); + + const Bitboard kingPath = CastleSpan(kingFrom, kingTo); + const Bitboard rookPath = CastleSpan(rookFrom, rookTo); + + // Everything except the castling king and rook has to stay out of both paths + Bitboard others = occupied ^ Bitboard::GetSquare(kingFrom) ^ Bitboard::GetSquare(rookFrom); + if ((kingPath | rookPath) & others) + return false; + + // The king can't castle out of, through or into check + if (kingPath & colorThreats[!us]) + return false; + + // Moving the castling rook away can open the back rank towards the king's destination + Bitboard occAfter = others | Bitboard::GetSquare(kingTo) | Bitboard::GetSquare(rookTo); + Bitboard enemyRooks = (pieces[Rook] | pieces[Queen]) & colors[!us]; + + if (MOVEGEN::getRookAttack(kingTo, occAfter) & enemyRooks) + return false; + + return true; +} + +// Parses one character of the FEN castling field: X-FEN / standard (KQkq) or Shredder-FEN (rook file letters). +// Needs the pieces to be placed already. +void Board::AddCastlingRight(char symbol) { + if (symbol == '-') + return; + + const bool color = std::islower(static_cast(symbol)) ? Black : White; + const int base = color ? 56 : 0; + const char letter = static_cast(std::tolower(static_cast(symbol))); + + Bitboard kings = pieces[King] & colors[color]; + if (!kings) + return; + + const int kingSq = kings.getLS1BIndex(); + if ((kingSq >> 3) != (base >> 3)) + return; + + const int kingFile = kingSq & 7; + const Bitboard rooks = pieces[Rook] & colors[color]; + + int rookSq = -1; + bool kingSide = false; + + if (letter == 'k') { + // X-FEN: the outermost rook on the king's side + kingSide = true; + + for (int file = 7; file > kingFile; file--) { + if (rooks.IsSet(base + file)) { + rookSq = base + file; + break; + } + } + } else if (letter == 'q') { + for (int file = 0; file < kingFile; file++) { + if (rooks.IsSet(base + file)) { + rookSq = base + file; + break; + } + } + } else if (letter >= 'a' && letter <= 'h') { + // Shredder-FEN: the file of the castling rook + const int file = letter - 'a'; + + if (file == kingFile || !rooks.IsSet(base + file)) + return; + + kingSide = file > kingFile; + rookSq = base + file; + } + + if (rookSq < 0) + return; + + const int idx = CastleIdx(color, kingSide); + + castlingRights |= (1 << idx); + castleRook[idx] = rookSq; +} + +// KQkq when the rook is on its standard corner, the rook's file letter (Shredder-FEN) otherwise +char Board::CastlingSymbol(uint8_t right, char standardSymbol) const { + const int idx = std::countr_zero(static_cast(right)); + const int file = castleRook[idx] & 7; + + const bool kingSideSymbol = standardSymbol == 'K' || standardSymbol == 'k'; + + if (file == (kingSideSymbol ? 7 : 0)) + return standardSymbol; + + const char fileLetter = static_cast('a' + file); + + return std::isupper(static_cast(standardSymbol)) + ? static_cast(std::toupper(static_cast(fileLetter))) + : fileLetter; +} + bool Board::GivesDirectCheck(Move &move) { int attackerType = nullPieceType; diff --git a/source/board.h b/source/board.h index 9b6ed3c..3e05888 100644 --- a/source/board.h +++ b/source/board.h @@ -38,7 +38,11 @@ public: bool sideToMove = White; - uint8_t castlingRights = 0; + uint8_t castlingRights = 0; + + // Squares of the castling rooks, indexed by CastleIdx(color, kingSide). + // Standard chess: h1, a1, h8, a8. Chess960 / DFRC positions override them while parsing the FEN. + std::array castleRook = {h1, a1, h8, a8}; int enPassantTarget = noEPTarget; short positionIndex = 0; @@ -95,5 +99,12 @@ public: bool GivesDirectCheck(Move &move); bool IsLegal(Move &move); - bool IsPseudoLegal(Move &move); + bool IsPseudoLegal(Move &move); + + // Index of a castling right, same bit order as CASTLING_RIGHTS (white K, white Q, black K, black Q) + static constexpr int CastleIdx(bool color, bool kingSide) { return color * 2 + (kingSide ? 0 : 1); } + + bool CanCastle(bool us, bool kingSide); + void AddCastlingRight(char symbol); + char CastlingSymbol(uint8_t right, char standardSymbol) const; }; \ No newline at end of file diff --git a/source/move.h b/source/move.h index b918a32..ffdfaef 100644 --- a/source/move.h +++ b/source/move.h @@ -68,8 +68,21 @@ public: return (GetFlags() == kingCastle || GetFlags() == queenCastle); } + // Castling moves are stored as "king takes own castling rook": from = king square, to = rook square. + // This is the UCI_Chess960 notation and it can't clash with a normal king move. + // CastleKingDest() is the square the king actually ends up on (g/c file of the back rank). + int CastleKingDest() { + return (MoveTo() & ~7) + (GetFlags() == kingCastle ? 6 : 2); + } + + // Destination square used when printing the move: standard UCI prints the king's + // destination (e1g1), UCI_Chess960 prints the rook square (e1h1). + int PrintTo() { + return (IsCastle() && !UCIChess960) ? CastleKingDest() : MoveTo(); + } + void PrintMove() { - std::cout << squareCoords[MoveFrom()] << squareCoords[MoveTo()]; + std::cout << squareCoords[MoveFrom()] << squareCoords[PrintTo()]; int flags = GetFlags(); @@ -86,7 +99,7 @@ public: std::string GetMoveString() { std::string result = squareCoords[MoveFrom()]; - result += squareCoords[MoveTo()]; + result += squareCoords[PrintTo()]; int flags = GetFlags(); @@ -110,16 +123,8 @@ public: viriMove = MoveFrom(); if (flags == kingCastle || flags == queenCastle) { - uint16_t moveTo = 0; - bool side = (MoveFrom() / 8 == 0) ? White : Black; - - if (flags == kingCastle) { - moveTo = (side == White) ? h1 : h8; - } else { - moveTo = (side == White) ? a1 : a8; - } - - viriMove |= (moveTo << 6); + // Castling is already stored as king takes rook, which is what the viri format expects + viriMove |= (MoveTo() << 6); viriMove |= 0x8000; diff --git a/source/movegen.tpp b/source/movegen.tpp index 0f5f37a..4c8e6e1 100644 --- a/source/movegen.tpp +++ b/source/movegen.tpp @@ -241,28 +241,11 @@ void GenKingMoves(Board &board) { moves.PopBit(square); } - // Generating castles - int kingRight = board.sideToMove ? blackKingRight : whiteKingRight; - int queenRight = board.sideToMove ? blackQueenRight : whiteQueenRight; - - if (board.castlingRights & queenRight) { - U64 QueenSide = board.sideToMove ? 0x1f00000000000000 : 0x1f; - U64 mask = board.sideToMove ? 0x1c00000000000000 : 0x1c; - int targetSquare = board.sideToMove ? c8 : c1; - if ((Bitboard(QueenSide) & board.occupied).PopCount() == 2 - && !(mask & board.colorThreats[!board.sideToMove])) { - board.AddMove(Move(kingSquare, targetSquare, queenCastle)); - - } - } - - if (board.castlingRights & kingRight) { - U64 KingSide = board.sideToMove ? 0xf000000000000000 : 0xf0; - U64 mask = board.sideToMove ? 0x7000000000000000 : 0x70; - int targetSquare = board.sideToMove ? g8 : g1; - if ((Bitboard(KingSide) & board.occupied).PopCount() == 2 - && !(mask & board.colorThreats[!board.sideToMove])) { - board.AddMove(Move(kingSquare, targetSquare, kingCastle)); + // Generating castles (Chess960 aware): encoded as the king taking its own castling rook + for (const bool kingSide : {false, true}) { + if (board.CanCastle(board.sideToMove, kingSide)) { + board.AddMove(Move(kingSquare, board.castleRook[Board::CastleIdx(board.sideToMove, kingSide)], + kingSide ? kingCastle : queenCastle)); } } diff --git a/source/perft.cpp b/source/perft.cpp index 8662173..15cb953 100644 --- a/source/perft.cpp +++ b/source/perft.cpp @@ -39,8 +39,8 @@ static bool IsDirectCheck(Board& pos, Move move) { int to = move.MoveTo(); int flags = move.GetFlags(); if (flags == kingCastle || flags == queenCastle) { - int rookFrom = mover ? (flags == kingCastle ? h8 : a8) : (flags == kingCastle ? h1 : a1); - int rookTo = flags == kingCastle ? rookFrom - 2 : rookFrom + 3; + // Castling is stored as "king takes own rook", so the rook's destination follows from the back rank of "to" + int rookTo = (to & ~7) + (flags == kingCastle ? 5 : 3); Bitboard rookAtt = MOVEGEN::getRookAttack(rookTo, pos.occupied); return rookAtt.IsSet(kingSq); } diff --git a/source/types.h b/source/types.h index 1debcfa..79beada 100644 --- a/source/types.h +++ b/source/types.h @@ -3,7 +3,10 @@ #include #include -using U64 = uint64_t; +using U64 = uint64_t; + +// UCI_Chess960 option: castling moves are printed/parsed as "king takes own rook" when enabled +inline bool UCIChess960 = false; constexpr std::string_view StartingFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; constexpr std::string_view KiwiPeteFen = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -"; diff --git a/source/uci.cpp b/source/uci.cpp index 924463d..5905b03 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -378,6 +378,12 @@ static void SetOption(std::string& command, SEARCH::SearchContext* ctx) { return; } + if (command.find("UCI_Chess960") != std::string::npos) { + UCIChess960 = command.find("value true") != std::string::npos + || command.find("value 1") != std::string::npos; + return; + } + if (command.find("UCI_ShowWDL") != std::string::npos) { UCIShowWDL = command.find("value true") != std::string::npos || command.find("value 1") != std::string::npos; @@ -434,6 +440,7 @@ static void PrintEngineInfo() { std::cout << "option name Hash type spin default 8 min 1 max 1024" << std::endl; std::cout << "option name Threads type spin default 1 min 1 max 512" << std::endl; std::cout << "option name UCI_ShowWDL type check default false" << std::endl; + std::cout << "option name UCI_Chess960 type check default false" << std::endl; #ifdef TUNING PrintTunablesUCI(); diff --git a/source/utils.cpp b/source/utils.cpp index 5caf46d..a309264 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -152,12 +152,28 @@ Move parseMove(Board &board, std::string_view str) { } } } else { - for (Move move : board.moveList) { + bool found = false; + + // Exact match first. Castling moves are stored as "king takes own rook", + // so this also covers the UCI_Chess960 castling notation (e1h1). + for (int i = 0; i < board.currentMoveIndex; i++) { + Move move = board.moveList[i]; if (move.MoveFrom() == from && move.MoveTo() == to) { flag = move.GetFlags(); + found = true; break; } } + + // Standard UCI castling notation: the king's destination square (e1g1) + if (!found) { + for (int i = 0; i < board.currentMoveIndex; i++) { + Move move = board.moveList[i]; + if (move.IsCastle() && move.MoveFrom() == from && move.CastleKingDest() == to) { + return move; + } + } + } } return Move(from, to, flag); @@ -177,11 +193,11 @@ std::array CompressPieces(Board board) { int pieceCode = pieceType; if (pieceType == Rook) { - if ((square == a1 && (board.castlingRights & whiteQueenRight)) - || (square == h1 && (board.castlingRights & whiteKingRight)) - || (square == a8 && (board.castlingRights & blackQueenRight)) - || (square == h8 && (board.castlingRights & blackKingRight))) - pieceCode = UNMOVED_ROOK; + // castling rooks, wherever they started (Chess960 aware) + for (int idx = 0; idx < 4; idx++) { + if ((board.castlingRights & (1 << idx)) && square == board.castleRook[idx] && pieceColor == (idx >> 1)) + pieceCode = UNMOVED_ROOK; + } } pieceCode |= (pieceColor << 3); // Shift the color to the 3rd bit (bit 3)