Chess960 support #18

Merged
claude merged 1 commits from chess960 into main 2026-11-15 22:19:44 +01:00
10 changed files with 203 additions and 57 deletions

No files matched your search

+5
View File
@@ -11,6 +11,9 @@ Every change is validated with SPRT on OpenBench.
- Bitboard board with fancy magic attacks, fully legal move generation, copy-make.
Verified with a perft suite (`Rigby perftsuite`).
- Chess960: any castling rook placement, X-FEN and Shredder-FEN castling rights,
`UCI_Chess960` for king-takes-rook castling notation. Verified with the 960
positions of the standard Chess960 perft suite to depth 5 (`perftfile`).
- PUCT search: node arena with contiguous children, first-play urgency reduction,
two-fold repetition, 50-move and insufficient-material draws inside the tree.
- Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data
@@ -56,6 +59,7 @@ Extra commands:
| `evalfens` | Network evaluation of fixed positions, to compare with the trainer's `--check` |
| `perft <depth>` | Perft with per-move breakdown |
| `perftsuite [maxdepth]` | Standard perft positions with expected counts |
| `perftfile <epd> [maxdepth]` | Perft of every `<fen> ;D1 <n> ;D2 <n> ...` line of a file (e.g. a Chess960 suite) |
| `bench [playouts]` | Fixed playout search over the bench positions |
`go depth N` limits the mean playout depth. `nodes` in `info` lines are playouts.
@@ -82,6 +86,7 @@ terminal).
| RootCPuct | 233 | Exploration constant at the root x100. |
| FPUReduction | 30 | First-play urgency reduction x100. |
| PolicyTemp | 100 | Policy softmax temperature x100. |
| UCI_Chess960 | false | Write and read castling as the king taking its rook (`e1h1`). |
## Bench
+1 -1
View File
@@ -483,7 +483,7 @@ void Searcher::print_info() const {
out << " hashfull " << (tree_.used() * 1000 / tree_.capacity());
out << " pv";
for (const Move m : principal_variation()) out << ' ' << m.to_uci();
for (const Move m : principal_variation()) out << ' ' << root_pos_.uci(m);
uci_io::send(out.str());
}
+34 -14
View File
@@ -1,3 +1,5 @@
#include <bit>
#include "position.h"
namespace rigby {
@@ -138,20 +140,31 @@ void generate(const Position& pos, MoveList& list) {
if (NOISY || num_checkers) return;
// Castling, Chess960 rules: the king goes to the g/c file and the rook to
// the f/d file. Every square either piece crosses or lands on must be empty
// apart from the two of them, and the king must not cross or land on an
// attacked square. The moved rook is taken out of the occupancy for that
// check, since it may be what shields one of those squares.
const int rank_base = us == WHITE ? 0 : 56;
const int oo = us == WHITE ? WHITE_OO : BLACK_OO;
const int ooo = us == WHITE ? WHITE_OOO : BLACK_OOO;
const u64 our_rooks = pos.pieces_of(us, ROOK);
if ((pos.castling & oo) && (our_rooks & bb(rank_base + 7)) &&
!(occ & (bb(rank_base + 5) | bb(rank_base + 6))) && !pos.square_attacked(rank_base + 5, them, occ) &&
!pos.square_attacked(rank_base + 6, them, occ))
list.add(Move(ksq, rank_base + 6, Move::KING_CASTLE));
if ((pos.castling & ooo) && (our_rooks & bb(rank_base + 0)) &&
!(occ & (bb(rank_base + 1) | bb(rank_base + 2) | bb(rank_base + 3))) &&
!pos.square_attacked(rank_base + 3, them, occ) && !pos.square_attacked(rank_base + 2, them, occ))
list.add(Move(ksq, rank_base + 2, Move::QUEEN_CASTLE));
for (const bool king_side : {true, false}) {
const int right = us == WHITE ? (king_side ? WHITE_OO : WHITE_OOO) : (king_side ? BLACK_OO : BLACK_OOO);
if (!(pos.castling & right)) continue;
const int rook = pos.castle_rook[std::countr_zero(unsigned(right))];
if (!(our_rooks & bb(rook))) continue;
const int king_to = rank_base + (king_side ? 6 : 2);
const int rook_to = rank_base + (king_side ? 5 : 3);
const u64 others = occ ^ bb(ksq) ^ bb(rook);
const u64 king_path = attacks::between[ksq][king_to] | bb(king_to);
const u64 rook_path = attacks::between[rook][rook_to] | bb(rook_to);
if ((king_path | rook_path) & others) continue;
// The destination is checked even when the king already stands on it:
// the rook leaving can uncover an attack along the rank.
u64 check = king_path;
bool safe = true;
while (check && safe) safe = !pos.square_attacked(pop_lsb(check), them, others);
if (safe) list.add(Move(ksq, king_to, king_side ? Move::KING_CASTLE : Move::QUEEN_CASTLE));
}
}
} // namespace
@@ -167,8 +180,15 @@ bool has_legal_move(const Position& pos) {
const u64 ours = pos.colors[us];
const int ksq = pos.king_square(us);
// In check or with an en passant capture around, just generate everything.
if (pos.in_check() || pos.ep != NO_SQUARE) {
// In check, with an en passant capture around, or with Chess960 castling
// that a king step cannot stand in for, just generate everything.
const int our_rights = pos.castling & (us == WHITE ? WHITE_OO | WHITE_OOO : BLACK_OO | BLACK_OOO);
const bool standard_castling = !our_rights || (ksq == (us == WHITE ? E1 : E8) &&
(!(our_rights & (WHITE_OO | BLACK_OO)) ||
file_of(pos.castle_rook[us == WHITE ? 0 : 2]) == 7) &&
(!(our_rights & (WHITE_OOO | BLACK_OOO)) ||
file_of(pos.castle_rook[us == WHITE ? 1 : 3]) == 0));
if (pos.in_check() || pos.ep != NO_SQUARE || !standard_castling) {
MoveList list;
generate<false>(pos, list);
return !list.empty();
+1 -1
View File
@@ -98,7 +98,7 @@ void update(const Accumulator& before, const Position& pos, Move m, Accumulator&
const int rank_base = us == WHITE ? 0 : 56;
const int rook = make_piece(us, ROOK);
const bool king_side = m.flag() == Move::KING_CASTLE;
sub_piece(rook, rank_base + (king_side ? 7 : 0));
sub_piece(rook, pos.castle_rook_square(m));
add_piece(rook, rank_base + (king_side ? 5 : 3));
}
+51 -1
View File
@@ -1,6 +1,10 @@
#include "perft.h"
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
namespace rigby {
@@ -30,13 +34,59 @@ void perft_divide(const Position& pos, int depth) {
child.make_move(m);
const u64 n = depth > 1 ? perft(child, depth - 1) : 1;
total += n;
std::cout << m.to_uci() << ": " << n << "\n";
std::cout << pos.uci(m) << ": " << n << "\n";
}
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::cout << "\nNodes: " << total << "\nTime: " << ms << " ms\nNPS: " << (ms ? total * 1000 / ms : total) << std::endl;
}
bool perft_file(const std::string& path, int max_depth) {
std::ifstream in(path);
if (!in) {
std::cout << "cannot open " << path << std::endl;
return false;
}
bool all_ok = true;
int lines = 0, failed = 0;
u64 total = 0;
const auto start = std::chrono::steady_clock::now();
std::string line;
while (std::getline(in, line)) {
const auto semi = line.find(';');
if (semi == std::string::npos) continue;
Position pos;
if (!pos.set_fen(line.substr(0, semi))) {
std::cout << "[FAIL] bad fen: " << line << std::endl;
all_ok = false;
continue;
}
lines++;
std::istringstream ss(line.substr(semi));
std::string tag;
u64 expected = 0;
bool ok = true;
while (ss >> tag >> expected) {
const int depth = std::atoi(tag.c_str() + 2); // ";D<n>"
if (depth > max_depth) break;
const u64 n = perft(pos, depth);
total += n;
if (n != expected) {
std::cout << "[FAIL] " << line.substr(0, semi) << " depth " << depth << ": " << n << " (expected "
<< expected << ")" << std::endl;
ok = false;
break;
}
}
all_ok &= ok;
failed += !ok;
}
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::cout << (all_ok ? "All perft tests passed" : "PERFT FAILED") << " - " << lines << " positions, " << failed
<< " failed, " << total << " nodes in " << ms << " ms" << std::endl;
return all_ok;
}
bool perft_suite(int max_depth) {
struct Case {
const char* fen;
+5
View File
@@ -1,5 +1,7 @@
#pragma once
#include <string>
#include "position.h"
namespace rigby {
@@ -9,5 +11,8 @@ u64 perft(const Position& pos, int depth);
void perft_divide(const Position& pos, int depth);
// Runs the standard perft positions; returns true when every count matches.
bool perft_suite(int max_depth);
// Runs every "<fen> ;D1 <nodes> ;D2 <nodes> ..." line of an EPD file up to
// max_depth (Chess960 suites use Shredder-FEN castling); true when all match.
bool perft_file(const std::string& path, int max_depth);
} // namespace rigby
+74 -37
View File
@@ -1,5 +1,6 @@
#include "position.h"
#include <bit>
#include <cstring>
#include <sstream>
@@ -25,18 +26,8 @@ void init() {
namespace {
// rights &= CASTLE_MASK[from] & CASTLE_MASK[to] after every move.
constexpr int castle_mask(int sq) {
switch (sq) {
case A1: return ~WHITE_OOO & 15;
case E1: return ~(WHITE_OO | WHITE_OOO) & 15;
case H1: return ~WHITE_OO & 15;
case A8: return ~BLACK_OOO & 15;
case E8: return ~(BLACK_OO | BLACK_OOO) & 15;
case H8: return ~BLACK_OO & 15;
default: return 15;
}
}
// Index into castle_rook of a right (a single CastlingRight bit).
constexpr int right_index(int right) { return std::countr_zero(unsigned(right)); }
} // namespace
@@ -93,11 +84,31 @@ bool Position::set_fen(std::string_view fen) {
stm = side == "b" ? BLACK : WHITE;
// KQkq (X-FEN: the outermost rook on that side of the king) or
// Shredder-FEN file letters (HAha) naming the castling rook.
for (char c : rights) {
if (c == 'K') castling |= WHITE_OO;
if (c == 'Q') castling |= WHITE_OOO;
if (c == 'k') castling |= BLACK_OO;
if (c == 'q') castling |= BLACK_OOO;
if (c == '-') continue;
const int color = (c >= 'a' && c <= 'z') ? BLACK : WHITE;
const char upper = char(color == BLACK ? c - 32 : c);
const int rank_base = color == WHITE ? 0 : 56;
const int kfile = file_of(king_square(color));
if (rank_of(king_square(color)) != rank_of(rank_base)) continue;
const u64 rooks = pieces_of(color, ROOK) & rank_bb(rank_base);
int rook = NO_SQUARE;
if (upper == 'K') {
for (int f = 7; f > kfile && rook == NO_SQUARE; f--)
if (rooks & bb(rank_base + f)) rook = rank_base + f;
} else if (upper == 'Q') {
for (int f = 0; f < kfile && rook == NO_SQUARE; f++)
if (rooks & bb(rank_base + f)) rook = rank_base + f;
} else if (upper >= 'A' && upper <= 'H' && (rooks & bb(rank_base + (upper - 'A')))) {
rook = rank_base + (upper - 'A');
}
if (rook == NO_SQUARE || file_of(rook) == kfile) continue;
const bool king_side = file_of(rook) > kfile;
const int right = color == WHITE ? (king_side ? WHITE_OO : WHITE_OOO) : (king_side ? BLACK_OO : BLACK_OOO);
castling |= right;
castle_rook[right_index(right)] = u8(rook);
}
if (ep_str.size() == 2 && ep_str[0] >= 'a' && ep_str[0] <= 'h') {
@@ -136,10 +147,18 @@ std::string Position::fen() const {
out += stm == WHITE ? " w " : " b ";
if (!castling) out += '-';
if (castling & WHITE_OO) out += 'K';
if (castling & WHITE_OOO) out += 'Q';
if (castling & BLACK_OO) out += 'k';
if (castling & BLACK_OOO) out += 'q';
for (int right : {WHITE_OO, WHITE_OOO, BLACK_OO, BLACK_OOO}) {
if (!(castling & right)) continue;
// K/Q when the rook is the outermost one on its side (X-FEN), else its file.
const int color = right & (WHITE_OO | WHITE_OOO) ? WHITE : BLACK;
const int rook = castle_rook[right_index(right)];
const int ksq = king_square(color);
const u64 rooks = pieces_of(color, ROOK) & rank_bb(rook);
const u64 beyond = file_of(rook) > file_of(ksq) ? rooks & ~((bb(rook) << 1) - 1) : rooks & (bb(rook) - 1);
char c = beyond ? char('A' + file_of(rook)) : (file_of(rook) > file_of(ksq) ? 'K' : 'Q');
if (color == BLACK) c = char(c + 32);
out += c;
}
out += ' ';
out += ep == NO_SQUARE ? "-" : square_name(ep);
out += ' ' + std::to_string(halfmove) + ' ' + std::to_string(fullmove);
@@ -159,14 +178,24 @@ void Position::make_move(Move m) {
ep = NO_SQUARE;
}
if (m.is_capture()) {
const int captured_sq = m.is_en_passant() ? (us == WHITE ? to - 8 : to + 8) : to;
remove_piece(captured_sq);
halfmove = 0;
if (m.is_castle()) {
// Lift both pieces first: in Chess960 the king and rook squares can overlap.
const int rook_from = castle_rook_square(m);
const int rank_base = us == WHITE ? 0 : 56;
const bool king_side = m.flag() == Move::KING_CASTLE;
remove_piece(from);
remove_piece(rook_from);
put_piece(make_piece(us, KING), to);
put_piece(make_piece(us, ROOK), rank_base + (king_side ? 5 : 3));
} else {
if (m.is_capture()) {
const int captured_sq = m.is_en_passant() ? (us == WHITE ? to - 8 : to + 8) : to;
remove_piece(captured_sq);
halfmove = 0;
}
move_piece(from, to);
}
move_piece(from, to);
if (moving == PAWN) {
halfmove = 0;
if (m.flag() == Move::DOUBLE_PUSH) {
@@ -179,17 +208,20 @@ void Position::make_move(Move m) {
remove_piece(to);
put_piece(make_piece(us, m.promo_type()), to);
}
} else if (m.is_castle()) {
const int rank_base = us == WHITE ? 0 : 56;
if (m.flag() == Move::KING_CASTLE)
move_piece(rank_base + 7, rank_base + 5);
else
move_piece(rank_base + 0, rank_base + 3);
}
key ^= zobrist::castling[castling];
castling &= castle_mask(from) & castle_mask(to);
key ^= zobrist::castling[castling];
if (castling) {
// A king move drops both of its rights; a move from or to a castling
// rook's square drops that rook's right.
int lost = moving == KING ? (us == WHITE ? WHITE_OO | WHITE_OOO : BLACK_OO | BLACK_OOO) : 0;
for (int i = 0; i < 4; i++)
if (castle_rook[i] == from || castle_rook[i] == to) lost |= 1 << i;
if (castling & lost) {
key ^= zobrist::castling[castling];
castling &= ~lost;
key ^= zobrist::castling[castling];
}
}
stm = them;
key ^= zobrist::side;
@@ -217,14 +249,19 @@ bool Position::insufficient_material() const {
return popcount(occupancy()) <= 3;
}
Move Position::parse_uci(std::string_view uci) const {
Move Position::parse_uci(std::string_view text) const {
MoveList list;
generate_legal(*this, list);
for (Move m : list)
if (m.to_uci() == uci) return m;
if (uci(m) == text) return m;
return {};
}
std::string Position::uci(Move m) const {
if (!m.is_castle() || !chess960) return m.to_uci();
return square_name(m.from()) + square_name(castle_rook_square(m));
}
std::string Position::pretty() const {
std::string out = "\n +---+---+---+---+---+---+---+---+\n";
for (int rank = 7; rank >= 0; rank--) {
+16
View File
@@ -12,6 +12,11 @@ namespace zobrist {
void init();
}
// UCI_Chess960: castling moves are written as the king taking its own rook
// (e1h1) instead of the king's destination (e1g1). Positions themselves always
// support any castling rook placement.
inline bool chess960 = false;
// Plain copy-make position. Small enough to copy at every tree step.
struct Position {
u64 pieces[6] = {};
@@ -19,6 +24,9 @@ struct Position {
u8 board[64];
int stm = WHITE;
int castling = 0;
// The rook each castling right moves, indexed by the right's bit
// (WHITE_OO, WHITE_OOO, BLACK_OO, BLACK_OOO).
u8 castle_rook[4] = {H1, A1, H8, A8};
int ep = NO_SQUARE; // only set when a capture there is pseudo-legal
int halfmove = 0;
int fullmove = 1;
@@ -44,6 +52,14 @@ struct Position {
// Returns a null move when the string is not a legal move here.
Move parse_uci(std::string_view uci) const;
// The move in UCI notation, castling written as chess960 asks. Works for
// any move of the game (the castling rooks never change), so the root
// position can print a whole PV.
std::string uci(Move m) const;
// The rook a castling move takes along; the king's rank tells the colour.
int castle_rook_square(Move m) const {
return castle_rook[(rank_of(m.from()) == 0 ? 0 : 2) + (m.flag() == Move::QUEEN_CASTLE)];
}
std::string pretty() const;
+2 -2
View File
@@ -474,14 +474,14 @@ std::string note(const std::string& text) { return " " + LABEL + text + RESET;
std::string bestmove(const Position& root, Move move) {
return " " + LABEL + "bestmove " + RESET + BOLD + BRIGHT_GREEN + san(root, move) + RESET + FAINT + " (" +
move.to_uci() + ")" + RESET + "\n";
root.uci(move) + ")" + RESET + "\n";
}
std::string san(const Position& pos, Move m) {
if (!m) return "--";
std::string s;
if (m.is_castle()) {
s = file_of(m.to()) > file_of(m.from()) ? "O-O" : "O-O-O";
s = m.flag() == Move::KING_CASTLE ? "O-O" : "O-O-O";
} else {
const int type = piece_type(pos.piece_on(m.from()));
if (type == PAWN) {
+14 -1
View File
@@ -53,6 +53,7 @@ void print_id() {
send("option name Hash type spin default " + std::to_string(DEFAULT_HASH_MB) + " min 1 max 65536");
send("option name Threads type spin default 1 min 1 max 1");
send("option name MoveOverhead type spin default 20 min 0 max 5000");
send("option name UCI_Chess960 type check default false");
// Search constants, exposed as integers (x100) so SPSA can tune them.
send("option name CPuct type spin default 160 min 1 max 1000");
send("option name RootCPuct type spin default 233 min 1 max 1000");
@@ -70,6 +71,11 @@ void set_option(Engine& e, std::istringstream& is) {
std::string lname = name;
std::transform(lname.begin(), lname.end(), lname.begin(), [](unsigned char c) { return char(std::tolower(c)); });
if (lname == "uci_chess960") {
chess960 = value == "true";
return;
}
int v = 0;
try {
v = std::stoi(value);
@@ -148,7 +154,7 @@ void go(Engine& e, std::istringstream& is) {
e.searcher.stop_flag = false;
e.worker = std::thread([&e, pos = e.pos, history = e.history, limits] {
const SearchResult result = e.searcher.search(pos, history, limits, true);
send(e.searcher.pretty ? pretty::bestmove(pos, result.best) : "bestmove " + result.best.to_uci());
send(e.searcher.pretty ? pretty::bestmove(pos, result.best) : "bestmove " + pos.uci(result.best));
});
}
@@ -273,6 +279,13 @@ void uci_loop() {
is >> depth;
e.stop();
perft_suite(depth);
} else if (cmd == "perftfile") {
// perftfile <epd> [max depth]: lines of "<fen> ;D1 <nodes> ;D2 <nodes> ..."
std::string path;
int depth = 6;
is >> path >> depth;
e.stop();
perft_file(path, depth);
} else if (cmd == "bench") {
int playouts = DEFAULT_BENCH_PLAYOUTS;
is >> playouts;