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
This commit is contained in:
claude committed 2026-10-11 00:12:02 +02:00
1 parent e984510434
commit aa97abaadc
9 files changed
+247 -71

No files matched your search

+1
View File
@@ -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**):
+176 -26
View File
@@ -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<unsigned char>(symbol)) ? Black : White;
const int base = color ? 56 : 0;
const char letter = static_cast<char>(std::tolower(static_cast<unsigned char>(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<unsigned>(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<char>('a' + file);
return std::isupper(static_cast<unsigned char>(standardSymbol))
? static_cast<char>(std::toupper(static_cast<unsigned char>(fileLetter)))
: fileLetter;
}
bool Board::GivesDirectCheck(Move &move) {
int attackerType = nullPieceType;
+13 -2
View File
@@ -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<int, 4> 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;
};
+17 -12
View File
@@ -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;
+5 -22
View File
@@ -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));
}
}
+2 -2
View File
@@ -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);
}
+4 -1
View File
@@ -3,7 +3,10 @@
#include <array>
#include <string_view>
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 -";
+7
View File
@@ -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();
+22 -6
View File
@@ -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<uint8_t, 16> 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)