feat: minimal MCTS engine with UCI

Bitboard board with fancy magics and fully legal move generation, checked
by a perft suite. PUCT search over a node arena with FPU reduction and
in-tree draw detection. Hand-written value (eval + quiescence) and
heuristic policy stand in until the network is trained. UCI loop with a
search thread, OpenBench-compatible bench and Makefile.

Bench: 546127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rektdieandclaude committed 2026-11-15 00:31:20 +01:00
commit d3044c0b88
19 files changed
+1997

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# Build output
obj/
*.exe
Rigby
# Networks and data
*.bin
*.nnue
*.pb
*.pb.gz
*.binpack
# Editors
.vscode/
.idea/
+84
View File
@@ -0,0 +1,84 @@
# Rigby - MCTS chess engine
# OpenBench calls: make EXE=<name> [EVALFILE=<net>] [CXX=<compiler>]
SRC_DIR := src
OBJ_DIR := obj
EXE ?= Rigby
EVALFILE ?=
CXX ?= clang++
ifeq ($(origin CXX),default)
CXX := clang++
endif
ifeq ($(OS),Windows_NT)
EXE_EXT := .exe
PLATFORM := windows
else
EXE_EXT :=
UNAME_S := $(shell uname -s)
ARCH := $(shell uname -m)
ifeq ($(UNAME_S),Darwin)
PLATFORM := mac
else
PLATFORM := unix
endif
endif
CXXFLAGS := -std=c++20 -O3 -flto -Wall -Wextra -DNDEBUG
LDFLAGS := -O3 -flto
ifeq ($(PLATFORM),windows)
ARCH_FLAGS := -march=native
# clang on Windows defaults to MSVC; use the MinGW runtime like Eleanor does.
ifneq ($(findstring clang,$(CXX)),)
CXXFLAGS += --target=x86_64-w64-windows-gnu
LDFLAGS += --target=x86_64-w64-windows-gnu
endif
CXXFLAGS += -pthread
LDFLAGS += -pthread -static
else ifeq ($(PLATFORM),mac)
ifeq ($(ARCH),arm64)
ARCH_FLAGS := -mcpu=apple-m1
else
ARCH_FLAGS := -march=native
endif
CXXFLAGS += -pthread
LDFLAGS += -pthread
else
ifeq ($(ARCH),aarch64)
ARCH_FLAGS := -mcpu=native
else
ARCH_FLAGS := -march=native
endif
CXXFLAGS += -pthread
LDFLAGS += -pthread -static
endif
ifneq ($(EVALFILE),)
CXXFLAGS += -DEVALFILE=\"$(EVALFILE)\"
endif
CXXFLAGS += $(ARCH_FLAGS)
LDFLAGS += $(ARCH_FLAGS)
SRCS := $(wildcard $(SRC_DIR)/*.cpp)
OBJS := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRCS))
DEPS := $(OBJS:.o=.d)
MAKEFLAGS += -j
$(EXE)$(EXE_EXT): $(OBJS)
$(CXX) $^ -o $@ $(LDFLAGS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
$(CXX) $(CXXFLAGS) -MMD -MP -c -o $@ $<
$(OBJ_DIR):
mkdir $(OBJ_DIR)
-include $(DEPS)
.PHONY: clean
clean:
rm -rf $(OBJ_DIR) $(EXE)$(EXE_EXT)
+64
View File
@@ -0,0 +1,64 @@
# Rigby
Rigby is a UCI chess engine built on Monte Carlo Tree Search (PUCT). The goal is a
neural-network-guided MCTS engine, later a Monte Carlo Graph Search (MCGS), with a
value and policy network trained with [bullet](https://github.com/jw1912/bullet) on
data generated by Leela Chess Zero, and CUDA inference.
Every change is validated with SPRT on OpenBench.
## Current state (0.1-dev)
- Bitboard board with fancy magic attacks, fully legal move generation, copy-make.
Verified with a perft suite (`Rigby perftsuite`).
- PUCT search: node arena with contiguous children, first-play urgency reduction,
two-fold repetition, 50-move and insufficient-material draws inside the tree.
- Placeholder evaluation until the network exists: a small hand-written
evaluation behind a capture-only quiescence search for the value, and move
heuristics (captures, promotions, checks, pawn threats) for the policy.
- Single-threaded, no tree reuse between moves.
## Building
Needs `clang++` (C++20) and `make`. On Windows clang must have a MinGW runtime,
the build targets `x86_64-w64-windows-gnu`, same as Eleanor.
```
make
make EXE=Rigby-dev
```
## UCI
Standard commands: `uci`, `isready`, `ucinewgame`, `position`, `go`
(`wtime btime winc binc movestogo movetime nodes depth infinite`), `stop`, `quit`,
`setoption`.
Extra commands:
| Command | Meaning |
| --- | --- |
| `d` | Print the board, FEN and hash key |
| `eval` | Static and quiescence evaluation of the current position |
| `perft <depth>` | Perft with per-move breakdown |
| `perftsuite [maxdepth]` | Standard perft positions with expected counts |
| `bench [playouts]` | Fixed playout search over the bench positions |
`go depth N` limits the mean playout depth. `nodes` in `info` lines are playouts.
### Options
| Option | Default | Meaning |
| --- | --- | --- |
| Hash | 64 | Tree memory in MB. A node takes 20 bytes. |
| Threads | 1 | Only 1 for now. |
| MoveOverhead | 20 | Milliseconds kept back per move. |
| CPuct | 160 | Exploration constant x100. |
| FPUReduction | 30 | First-play urgency reduction x100. |
| PolicyTemp | 100 | Policy softmax temperature x100. |
## Bench
`Rigby bench` runs 5000 playouts on each of 16 positions. The reported node count is
the number of positions visited in the tree over all playouts, so it changes
whenever search behaviour changes, while the playout count stays fixed.
+150
View File
@@ -0,0 +1,150 @@
#include "bitboard.h"
namespace rigby::attacks {
u64 pawn[2][64];
u64 knight[64];
u64 king[64];
u64 between[64][64];
u64 line[64][64];
namespace {
struct Magic {
u64 mask;
u64 magic;
u64* table;
int shift;
unsigned index(u64 occ) const { return unsigned(((occ & mask) * magic) >> shift); }
};
Magic rook_magics[64];
Magic bishop_magics[64];
u64 rook_table[0x19000];
u64 bishop_table[0x1480];
constexpr int ROOK_DIRS[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
constexpr int BISHOP_DIRS[4][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
u64 slide(int sq, u64 occ, const int (&dirs)[4][2]) {
u64 result = 0;
for (const auto& d : dirs) {
int f = file_of(sq) + d[0];
int r = rank_of(sq) + d[1];
while (f >= 0 && f < 8 && r >= 0 && r < 8) {
const int s = make_square(f, r);
result |= bb(s);
if (occ & bb(s)) break;
f += d[0];
r += d[1];
}
}
return result;
}
u64 step_attacks(int sq, const int (*steps)[2], int count) {
u64 result = 0;
for (int i = 0; i < count; i++) {
const int f = file_of(sq) + steps[i][0];
const int r = rank_of(sq) + steps[i][1];
if (f >= 0 && f < 8 && r >= 0 && r < 8) result |= bb(make_square(f, r));
}
return result;
}
// Finds a magic for every square by trial and error (fancy magic bitboards).
void init_magics(Magic* magics, u64* table, const int (&dirs)[4][2], u64 seed) {
static u64 occupancies[4096];
static u64 reference[4096];
static int epoch[4096];
static int attempt = 0; // shared across calls, so stale epochs never look fresh
Prng rng(seed);
u64* ptr = table;
for (int sq = 0; sq < 64; sq++) {
Magic& m = magics[sq];
const u64 edges = ((RANK_1_BB | RANK_8_BB) & ~rank_bb(sq)) | ((FILE_A_BB | FILE_H_BB) & ~file_bb(sq));
m.mask = slide(sq, 0, dirs) & ~edges;
const int bits = popcount(m.mask);
m.shift = 64 - bits;
m.table = ptr;
int size = 0;
u64 subset = 0;
do {
occupancies[size] = subset;
reference[size] = slide(sq, subset, dirs);
size++;
subset = (subset - m.mask) & m.mask;
} while (subset);
for (;;) {
do {
m.magic = rng.sparse();
} while (popcount((m.magic * m.mask) >> 56) < 6);
attempt++;
bool ok = true;
for (int i = 0; i < size; i++) {
const unsigned idx = m.index(occupancies[i]);
if (epoch[idx] < attempt) {
epoch[idx] = attempt;
ptr[idx] = reference[i];
} else if (ptr[idx] != reference[i]) {
ok = false;
break;
}
}
if (ok) break;
}
ptr += size_t(1) << bits;
}
}
} // namespace
u64 bishop(int sq, u64 occ) {
const Magic& m = bishop_magics[sq];
return m.table[m.index(occ)];
}
u64 rook(int sq, u64 occ) {
const Magic& m = rook_magics[sq];
return m.table[m.index(occ)];
}
void init() {
static constexpr int KNIGHT_STEPS[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}};
static constexpr int KING_STEPS[8][2] = {{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}};
static constexpr int WHITE_PAWN_STEPS[2][2] = {{-1, 1}, {1, 1}};
static constexpr int BLACK_PAWN_STEPS[2][2] = {{-1, -1}, {1, -1}};
for (int sq = 0; sq < 64; sq++) {
knight[sq] = step_attacks(sq, KNIGHT_STEPS, 8);
king[sq] = step_attacks(sq, KING_STEPS, 8);
pawn[WHITE][sq] = step_attacks(sq, WHITE_PAWN_STEPS, 2);
pawn[BLACK][sq] = step_attacks(sq, BLACK_PAWN_STEPS, 2);
}
init_magics(rook_magics, rook_table, ROOK_DIRS, 0x2545F4914F6CDD1DULL);
init_magics(bishop_magics, bishop_table, BISHOP_DIRS, 0x5DEECE66DULL);
for (int a = 0; a < 64; a++) {
for (int b = 0; b < 64; b++) {
between[a][b] = line[a][b] = 0;
if (a == b) continue;
if (bishop(a, 0) & bb(b)) {
line[a][b] = (bishop(a, 0) & bishop(b, 0)) | bb(a) | bb(b);
between[a][b] = bishop(a, bb(b)) & bishop(b, bb(a));
} else if (rook(a, 0) & bb(b)) {
line[a][b] = (rook(a, 0) & rook(b, 0)) | bb(a) | bb(b);
between[a][b] = rook(a, bb(b)) & rook(b, bb(a));
}
}
}
}
} // namespace rigby::attacks
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include <bit>
#include "types.h"
namespace rigby {
constexpr u64 bb(int sq) { return 1ULL << sq; }
inline int lsb(u64 b) { return std::countr_zero(b); }
inline int popcount(u64 b) { return std::popcount(b); }
inline int pop_lsb(u64& b) {
const int sq = lsb(b);
b &= b - 1;
return sq;
}
constexpr u64 FILE_A_BB = 0x0101010101010101ULL;
constexpr u64 FILE_H_BB = FILE_A_BB << 7;
constexpr u64 RANK_1_BB = 0xFFULL;
constexpr u64 RANK_8_BB = RANK_1_BB << 56;
constexpr u64 file_bb(int sq) { return FILE_A_BB << file_of(sq); }
constexpr u64 rank_bb(int sq) { return RANK_1_BB << (8 * rank_of(sq)); }
// Small, fast, deterministic generator (xorshift64*). Used for magics and Zobrist keys.
struct Prng {
u64 state;
explicit Prng(u64 seed) : state(seed ? seed : 0x9E3779B97F4A7C15ULL) {}
u64 next() {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
return state * 2685821657736338717ULL;
}
u64 sparse() { return next() & next() & next(); }
};
namespace attacks {
void init();
extern u64 pawn[2][64];
extern u64 knight[64];
extern u64 king[64];
// Squares strictly between two aligned squares, 0 otherwise.
extern u64 between[64][64];
// The full line through two aligned squares (both included), 0 otherwise.
extern u64 line[64][64];
u64 bishop(int sq, u64 occ);
u64 rook(int sq, u64 occ);
inline u64 queen(int sq, u64 occ) { return bishop(sq, occ) | rook(sq, occ); }
} // namespace attacks
} // namespace rigby
+215
View File
@@ -0,0 +1,215 @@
#include "eval.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
namespace rigby::eval {
namespace {
constexpr int MATE = 30000;
constexpr int QS_MAX_PLY = 32;
constexpr float Q_SCALE = 300.0f;
constexpr int MG_VALUE[6] = {90, 320, 335, 480, 980, 0};
constexpr int EG_VALUE[6] = {110, 290, 305, 520, 940, 0};
constexpr int SEE_VALUE[6] = {100, 300, 310, 500, 900, 0};
constexpr int PHASE_WEIGHT[6] = {0, 1, 1, 2, 4, 0};
// Material folded into piece-square tables, indexed [piece][square].
int mg_table[12][64];
int eg_table[12][64];
// Positional part only (no material), white's view, used by the policy.
int mg_pst[6][64];
void pst_for(int type, int sq, int& mg, int& eg) {
const int f = file_of(sq);
const int r = rank_of(sq);
const int center = std::abs(2 * f - 7) + std::abs(2 * r - 7); // 2..14
const bool central_file = f == 3 || f == 4;
switch (type) {
case PAWN:
mg = (r >= 1 && r <= 6) ? (r - 1) * 6 + (central_file ? (r - 1) * 4 : 0) : 0;
eg = (r >= 1 && r <= 6) ? (r - 1) * 14 : 0;
break;
case KNIGHT:
mg = 24 - center * 4;
eg = 18 - center * 3;
break;
case BISHOP:
mg = 12 - center * 2;
eg = 10 - center * 2;
break;
case ROOK:
mg = (r == 6 ? 20 : 0) + (central_file ? 6 : 0);
eg = r == 6 ? 15 : 0;
break;
case QUEEN:
mg = 6 - center;
eg = 20 - center * 2;
break;
default: // KING: shelter in the middlegame, centralise in the endgame
mg = -std::min(r, 3) * 25 + ((f <= 2 || f >= 6) ? 15 : -15);
eg = 30 - center * 4;
break;
}
}
int victim_type(const Position& pos, Move m) { return m.is_en_passant() ? PAWN : piece_type(pos.piece_on(m.to())); }
} // namespace
void init() {
for (int type = PAWN; type <= KING; type++) {
for (int sq = 0; sq < 64; sq++) {
int mg, eg;
pst_for(type, sq, mg, eg);
mg_pst[type][sq] = mg;
mg_table[make_piece(WHITE, type)][sq] = MG_VALUE[type] + mg;
eg_table[make_piece(WHITE, type)][sq] = EG_VALUE[type] + eg;
mg_table[make_piece(BLACK, type)][sq ^ 56] = -(MG_VALUE[type] + mg);
eg_table[make_piece(BLACK, type)][sq ^ 56] = -(EG_VALUE[type] + eg);
}
}
}
int static_eval(const Position& pos) {
int mg = 0, eg = 0, phase = 0;
u64 occ = pos.occupancy();
while (occ) {
const int sq = pop_lsb(occ);
const int piece = pos.piece_on(sq);
mg += mg_table[piece][sq];
eg += eg_table[piece][sq];
phase += PHASE_WEIGHT[piece_type(piece)];
}
phase = std::min(phase, 24);
int score = (mg * phase + eg * (24 - phase)) / 24;
if (popcount(pos.pieces_of(WHITE, BISHOP)) >= 2) score += 30;
if (popcount(pos.pieces_of(BLACK, BISHOP)) >= 2) score -= 30;
return (pos.stm == WHITE ? score : -score) + 10;
}
int quiescence(const Position& pos, int alpha, int beta, int ply) {
const bool in_check = pos.in_check();
int best = -MATE + ply;
int stand_pat = 0;
if (!in_check) {
stand_pat = static_eval(pos);
if (stand_pat >= beta || ply >= QS_MAX_PLY) return stand_pat;
best = stand_pat;
alpha = std::max(alpha, stand_pat);
}
MoveList list;
generate_legal(pos, list);
if (list.empty()) return in_check ? -MATE + ply : 0;
if (in_check && ply >= QS_MAX_PLY) return static_eval(pos);
Move moves[256];
int scores[256];
int count = 0;
for (Move m : list) {
const bool tactical = m.is_capture() || (m.is_promotion() && m.promo_type() == QUEEN);
if (!in_check && !tactical) continue;
int score = 0;
if (m.is_capture()) {
const int victim = victim_type(pos, m);
// Delta pruning: even winning the piece for free cannot reach alpha.
if (!in_check && !m.is_promotion() && stand_pat + SEE_VALUE[victim] + 200 <= alpha) continue;
score = SEE_VALUE[victim] * 16 - piece_type(pos.piece_on(m.from()));
}
if (m.is_promotion()) score += SEE_VALUE[m.promo_type()] * 16;
moves[count] = m;
scores[count++] = score;
}
for (int i = 0; i < count; i++) {
int best_idx = i;
for (int j = i + 1; j < count; j++)
if (scores[j] > scores[best_idx]) best_idx = j;
std::swap(moves[i], moves[best_idx]);
std::swap(scores[i], scores[best_idx]);
Position child = pos;
child.make_move(moves[i]);
const int score = -quiescence(child, -beta, -alpha, ply + 1);
if (score > best) {
best = score;
if (score > alpha) {
alpha = score;
if (alpha >= beta) break;
}
}
}
return best;
}
float value(const Position& pos) { return cp_to_q(quiescence(pos, -MATE, MATE, 0)); }
void policy(const Position& pos, const MoveList& moves, float temperature, float* out) {
const int us = pos.stm;
const int them = us ^ 1;
const u64 occ = pos.occupancy();
const u64 their_pawns = pos.pieces_of(them, PAWN);
const u64 pawn_threats = them == WHITE ? (((their_pawns << 7) & ~FILE_H_BB) | ((their_pawns << 9) & ~FILE_A_BB))
: (((their_pawns >> 7) & ~FILE_A_BB) | ((their_pawns >> 9) & ~FILE_H_BB));
// Squares from which each piece type would give a direct check.
const int eksq = pos.king_square(them);
u64 check_squares[6];
check_squares[PAWN] = attacks::pawn[them][eksq];
check_squares[KNIGHT] = attacks::knight[eksq];
check_squares[BISHOP] = attacks::bishop(eksq, occ);
check_squares[ROOK] = attacks::rook(eksq, occ);
check_squares[QUEEN] = check_squares[BISHOP] | check_squares[ROOK];
check_squares[KING] = 0;
const float inv_temp = 1.0f / std::max(temperature, 0.01f);
float max_logit = -1e30f;
for (int i = 0; i < moves.size(); i++) {
const Move m = moves[i];
const int from = m.from();
const int to = m.to();
const int type = piece_type(pos.piece_on(from));
float s = 0.0f;
if (m.is_capture()) s += 1.0f + 0.004f * SEE_VALUE[victim_type(pos, m)] - 0.0015f * SEE_VALUE[type];
if (m.is_promotion()) s += m.promo_type() == QUEEN ? 2.5f : -2.5f;
if (m.is_castle()) s += 0.8f;
s += 0.01f * float(mg_pst[type][relative_square(us, to)] - mg_pst[type][relative_square(us, from)]);
if (type != PAWN && type != KING) {
if (pawn_threats & bb(to)) s -= 0.004f * SEE_VALUE[type];
if (pawn_threats & bb(from)) s += 0.003f * SEE_VALUE[type];
}
if (check_squares[m.is_promotion() ? m.promo_type() : type] & bb(to)) s += 0.5f;
out[i] = s * inv_temp;
max_logit = std::max(max_logit, out[i]);
}
float total = 0.0f;
for (int i = 0; i < moves.size(); i++) {
out[i] = std::exp(out[i] - max_logit);
total += out[i];
}
for (int i = 0; i < moves.size(); i++) out[i] /= total;
}
float cp_to_q(int cp) { return std::tanh(float(cp) / Q_SCALE); }
int q_to_cp(float q) {
q = std::clamp(q, -0.9999f, 0.9999f);
return int(std::lround(Q_SCALE * std::atanh(q)));
}
} // namespace rigby::eval
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "position.h"
namespace rigby::eval {
// Stand-in evaluation until the network arrives. Everything here is replaced by
// the value and policy heads of the net trained on Lc0 data.
void init();
// Static evaluation in centipawns, from the side to move's view.
int static_eval(const Position& pos);
// Capture-only search on top of the static evaluation, side to move's view.
int quiescence(const Position& pos, int alpha, int beta, int ply);
// Expected score in [-1, 1] for the side to move.
float value(const Position& pos);
// Writes softmax-normalised priors for `moves` into `out`.
void policy(const Position& pos, const MoveList& moves, float temperature, float* out);
// Conversion between centipawns and Q in [-1, 1]. One scale for both directions,
// so reported scores match what the search actually optimises.
float cp_to_q(int cp);
int q_to_cp(float q);
} // namespace rigby::eval
+28
View File
@@ -0,0 +1,28 @@
#include <cstdlib>
#include <string>
#include "bitboard.h"
#include "eval.h"
#include "perft.h"
#include "position.h"
#include "uci.h"
int main(int argc, char* argv[]) {
rigby::attacks::init();
rigby::zobrist::init();
rigby::eval::init();
if (argc > 1) {
const std::string cmd = argv[1];
if (cmd == "bench") {
rigby::run_bench(argc > 2 ? std::atoi(argv[2]) : 5000);
return 0;
}
if (cmd == "perftsuite") {
return rigby::perft_suite(argc > 2 ? std::atoi(argv[2]) : 6) ? 0 : 1;
}
}
rigby::uci_loop();
return 0;
}
+297
View File
@@ -0,0 +1,297 @@
#include "mcts.h"
#include <algorithm>
#include <cmath>
#include <iostream>
#include <sstream>
#include "eval.h"
#include "uci_io.h"
namespace rigby {
// ---------------------------------------------------------------------------
// Tree
// ---------------------------------------------------------------------------
void Tree::resize_mb(size_t mb) {
const size_t count = std::max<size_t>(mb * 1024 * 1024 / sizeof(Node), 1024);
nodes_.assign(count, Node{});
nodes_.shrink_to_fit();
clear();
}
void Tree::clear() {
used_ = 2; // index 0 is the null child, index 1 is the root
nodes_[root()] = Node{};
}
u32 Tree::alloc(u32 count) {
if (used_ + count > nodes_.size()) return 0;
const u32 idx = u32(used_);
used_ += count;
return idx;
}
// ---------------------------------------------------------------------------
// Searcher
// ---------------------------------------------------------------------------
Searcher::Searcher() { tree_.resize_mb(64); }
i64 Searcher::elapsed_ms() const {
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time_).count();
}
void Searcher::compute_time_limit(const SearchLimits& limits) {
time_limit_ms_ = 0;
if (limits.infinite) return;
if (limits.movetime) {
time_limit_ms_ = std::max<i64>(1, limits.movetime - params.move_overhead);
return;
}
const int us = root_pos_.stm;
if (limits.time[us] <= 0) return;
const i64 remaining = std::max<i64>(1, limits.time[us] - params.move_overhead);
const i64 moves_left = limits.movestogo ? std::min(limits.movestogo, 40) : 25;
const i64 target = remaining / moves_left + limits.inc[us] * 3 / 4;
time_limit_ms_ = std::clamp<i64>(target, 1, remaining / 2 + 1);
}
bool Searcher::should_stop(const SearchLimits& limits) const {
if (stop_flag.load(std::memory_order_relaxed)) return true;
if (limits.nodes && iterations_ >= limits.nodes) return true;
if (limits.depth && iterations_) {
// "depth" is the mean playout depth. Solved positions may never get
// there, so a depth limit also carries a generous playout cap.
if (int(depth_sum_ / iterations_) >= limits.depth) return true;
if (iterations_ >= (u64(1000) << std::min(2 * limits.depth, 14))) return true;
}
// The clock is cheap but not free; look at it every 64 playouts.
if (time_limit_ms_ && (iterations_ & 63) == 0 && elapsed_ms() >= time_limit_ms_) return true;
return false;
}
bool Searcher::is_repetition(const Position& pos) const {
// history_.back() is the key of `pos` itself. Any earlier occurrence with the
// same side to move inside the reversible window counts as a draw (two-fold).
const int n = int(history_.size());
for (int back = 4; back <= pos.halfmove && back < n; back += 2)
if (history_[n - 1 - back] == pos.key) return true;
return false;
}
float Searcher::expand(u32 idx, const Position& pos, int depth) {
Node& node = tree_[idx];
MoveList moves;
generate_legal(pos, moves);
if (moves.empty()) {
node.state = pos.in_check() ? TERMINAL_LOSS : TERMINAL_DRAW;
return node.state == TERMINAL_LOSS ? -1.0f : 0.0f;
}
// The root must always produce a move, so it is never declared drawn.
if (depth > 0 && (pos.halfmove >= 100 || pos.insufficient_material() || is_repetition(pos))) {
node.state = TERMINAL_DRAW;
return 0.0f;
}
const u32 first = tree_.alloc(u32(moves.size()));
if (!first) {
// Out of memory: keep the node as a leaf and just evaluate it again.
tree_full_ = true;
return eval::value(pos);
}
float priors[256];
eval::policy(pos, moves, params.policy_temperature, priors);
for (int i = 0; i < moves.size(); i++) {
Node& child = tree_[first + i];
child = Node{};
child.move = moves[i].raw();
child.policy = u16(std::lround(std::clamp(priors[i], 0.0f, 1.0f) * 65535.0f));
}
node.first_child = first;
node.num_children = u8(moves.size());
node.state = EXPANDED;
return eval::value(pos);
}
u32 Searcher::select_child(u32 idx) const {
const Node& node = tree_[idx];
// node.q is from the view of the side that moved into this node, so the side
// to move here sees -q.
const float parent_q = node.visits ? -node.q : 0.0f;
float visited_policy = 0.0f;
for (u32 i = 0; i < node.num_children; i++) {
const Node& child = tree_[node.first_child + i];
if (child.visits) visited_policy += child.prior();
}
const float fpu = parent_q - params.fpu_reduction * std::sqrt(visited_policy);
const float explore = params.cpuct * std::sqrt(float(std::max<u32>(node.visits, 1)));
u32 best = node.first_child;
float best_score = -1e30f;
for (u32 i = 0; i < node.num_children; i++) {
const u32 c = node.first_child + i;
const Node& child = tree_[c];
const float q = child.visits ? child.q : fpu;
const float score = q + explore * child.prior() / float(1 + child.visits);
if (score > best_score) {
best_score = score;
best = c;
}
}
return best;
}
void Searcher::playout() {
Position pos = root_pos_;
history_.resize(root_history_size_);
path_.clear();
u32 idx = Tree::root();
path_.push_back(idx);
int depth = 0;
float value;
for (;;) {
const Node& node = tree_[idx];
if (node.state == TERMINAL_LOSS) {
value = -1.0f;
break;
}
if (node.state == TERMINAL_DRAW) {
value = 0.0f;
break;
}
if (node.state == UNEXPANDED) {
value = expand(idx, pos, depth);
break;
}
idx = select_child(idx);
pos.make_move(Move::from_raw(tree_[idx].move));
history_.push_back(pos.key);
path_.push_back(idx);
depth++;
}
// `value` is from the view of the side to move at the leaf. Each node stores
// the view of the side that moved into it, so flip before every update.
for (size_t i = path_.size(); i-- > 0;) {
value = -value;
Node& node = tree_[path_[i]];
node.visits++;
node.q += (value - node.q) / float(node.visits);
}
iterations_++;
depth_sum_ += u64(depth);
seldepth_ = std::max(seldepth_, depth);
}
u32 Searcher::best_child(u32 idx) const {
const Node& node = tree_[idx];
u32 best = 0;
for (u32 i = 0; i < node.num_children; i++) {
const u32 c = node.first_child + i;
if (!best) {
best = c;
continue;
}
const Node& a = tree_[c];
const Node& b = tree_[best];
// Most visits wins; ties go to the better Q, then to the higher prior.
if (a.visits != b.visits ? a.visits > b.visits : a.visits ? a.q > b.q : a.policy > b.policy) best = c;
}
return best;
}
void Searcher::print_info() const {
const Node& root = tree_[Tree::root()];
const i64 ms = elapsed_ms();
const u32 best = best_child(Tree::root());
std::ostringstream out;
out << "info depth " << (iterations_ ? std::max<u64>(1, depth_sum_ / iterations_) : 0) << " seldepth "
<< seldepth_;
const float q = best && tree_[best].visits ? tree_[best].q : -root.q;
out << " score cp " << eval::q_to_cp(q);
out << " nodes " << iterations_ << " nps " << (ms ? iterations_ * 1000 / u64(ms) : iterations_) << " time " << ms;
out << " hashfull " << (tree_.used() * 1000 / tree_.capacity());
out << " pv";
u32 idx = Tree::root();
for (int ply = 0; ply < 64; ply++) {
const u32 c = best_child(idx);
if (!c || !tree_[c].visits) break;
out << ' ' << Move::from_raw(tree_[c].move).to_uci();
idx = c;
}
uci_io::send(out.str());
}
SearchResult Searcher::search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print) {
start_time_ = Clock::now();
root_pos_ = root;
history_ = history;
if (history_.empty() || history_.back() != root.key) history_.push_back(root.key);
root_history_size_ = history_.size();
tree_.clear();
iterations_ = 0;
depth_sum_ = 0;
seldepth_ = 0;
tree_full_ = false;
compute_time_limit(limits);
SearchResult result;
MoveList root_moves;
generate_legal(root, root_moves);
if (root_moves.empty()) {
if (print) uci_io::send("info depth 0 score " + std::string(root.in_check() ? "mate 0" : "cp 0"));
return result;
}
i64 last_info = 0;
// Always run at least one playout so the root gets expanded.
do {
playout();
if (print && (iterations_ & 1023) == 0) {
const i64 ms = elapsed_ms();
if (ms - last_info >= 1000) {
last_info = ms;
print_info();
}
}
} while (!should_stop(limits));
if (print) {
print_info();
if (tree_full_) uci_io::send("info string tree memory full, raise Hash");
}
const u32 best = best_child(Tree::root());
result.best = Move::from_raw(tree_[best].move);
result.nodes = iterations_;
result.tree_positions = iterations_ + depth_sum_;
result.time_ms = elapsed_ms();
return result;
}
} // namespace rigby
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <atomic>
#include <chrono>
#include <vector>
#include "position.h"
namespace rigby {
enum NodeState : u8 {
UNEXPANDED = 0,
EXPANDED,
TERMINAL_LOSS, // side to move is checkmated
TERMINAL_DRAW,
};
// 20 bytes. Children of a node sit next to each other in the arena, so a node
// only needs the index of its first child.
struct Node {
u32 first_child = 0;
u32 visits = 0;
float q = 0.0f; // running mean, from the view of the side that played `move`
u16 move = 0;
u16 policy = 0; // prior scaled to 0..65535
u8 num_children = 0;
u8 state = UNEXPANDED;
float prior() const { return float(policy) * (1.0f / 65535.0f); }
};
class Tree {
public:
void resize_mb(size_t mb);
void clear();
// Returns the index of `count` fresh nodes, or 0 when the arena is full.
u32 alloc(u32 count);
Node& operator[](u32 idx) { return nodes_[idx]; }
const Node& operator[](u32 idx) const { return nodes_[idx]; }
static constexpr u32 root() { return 1; }
size_t used() const { return used_; }
size_t capacity() const { return nodes_.size(); }
private:
std::vector<Node> nodes_;
size_t used_ = 0;
};
struct SearchLimits {
u64 nodes = 0;
i64 movetime = 0;
i64 time[2] = {0, 0};
i64 inc[2] = {0, 0};
int movestogo = 0;
int depth = 0;
bool infinite = false;
};
struct SearchParams {
float cpuct = 1.60f;
float fpu_reduction = 0.30f;
float policy_temperature = 1.00f;
i64 move_overhead = 20;
};
struct SearchResult {
Move best;
u64 nodes = 0; // playouts
u64 tree_positions = 0; // positions visited across all playouts (bench signature)
i64 time_ms = 0;
};
class Searcher {
public:
SearchParams params;
std::atomic<bool> stop_flag{false};
Searcher();
void set_hash(size_t mb) { tree_.resize_mb(mb); }
// Synchronous search. `history` holds the keys of every position that led to
// `root`, including the key of `root` itself (for repetition detection).
SearchResult search(const Position& root, const std::vector<u64>& history, const SearchLimits& limits,
bool print_info);
private:
using Clock = std::chrono::steady_clock;
Tree tree_;
Position root_pos_;
std::vector<u64> history_;
size_t root_history_size_ = 0;
std::vector<u32> path_;
Clock::time_point start_time_;
i64 time_limit_ms_ = 0;
u64 iterations_ = 0;
u64 depth_sum_ = 0;
int seldepth_ = 0;
bool tree_full_ = false;
void playout();
float expand(u32 idx, const Position& pos, int depth);
u32 select_child(u32 idx) const;
bool is_repetition(const Position& pos) const;
void compute_time_limit(const SearchLimits& limits);
i64 elapsed_ms() const;
bool should_stop(const SearchLimits& limits) const;
u32 best_child(u32 idx) const;
void print_info() const;
};
} // namespace rigby
+145
View File
@@ -0,0 +1,145 @@
#include "position.h"
namespace rigby {
namespace {
void add_targets(MoveList& list, int from, u64 targets, u64 theirs) {
while (targets) {
const int to = pop_lsb(targets);
list.add(Move(from, to, (theirs & bb(to)) ? Move::CAPTURE : Move::QUIET));
}
}
void add_pawn_move(MoveList& list, int from, int to, bool capture, bool promotion) {
if (promotion) {
const int base = capture ? Move::PROMO_CAPTURE : Move::PROMO;
// Queen first: it is by far the most common promotion.
for (int k = 3; k >= 0; k--) list.add(Move(from, to, base + k));
} else {
list.add(Move(from, to, capture ? Move::CAPTURE : Move::QUIET));
}
}
} // namespace
// Fully legal generation using check and pin masks.
void generate_legal(const Position& pos, MoveList& list) {
list.clear();
const int us = pos.stm;
const int them = us ^ 1;
const u64 occ = pos.occupancy();
const u64 ours = pos.colors[us];
const u64 theirs = pos.colors[them];
const int ksq = pos.king_square(us);
const u64 checkers = pos.attackers_to(ksq, occ) & theirs;
const int num_checkers = popcount(checkers);
// King moves: the king itself must not block a slider ray on its destination.
{
const u64 occ_no_king = occ ^ bb(ksq);
u64 targets = attacks::king[ksq] & ~ours;
while (targets) {
const int to = pop_lsb(targets);
if (!pos.square_attacked(to, them, occ_no_king))
list.add(Move(ksq, to, (theirs & bb(to)) ? Move::CAPTURE : Move::QUIET));
}
}
if (num_checkers > 1) return;
const u64 check_mask = num_checkers ? (attacks::between[ksq][lsb(checkers)] | checkers) : ~0ULL;
const u64 diag_sliders = pos.pieces[BISHOP] | pos.pieces[QUEEN];
const u64 orth_sliders = pos.pieces[ROOK] | pos.pieces[QUEEN];
u64 pinned = 0;
{
u64 snipers = ((attacks::rook(ksq, 0) & orth_sliders) | (attacks::bishop(ksq, 0) & diag_sliders)) & theirs;
while (snipers) {
const int s = pop_lsb(snipers);
const u64 blockers = attacks::between[ksq][s] & occ;
if (blockers && !(blockers & (blockers - 1)) && (blockers & ours)) pinned |= blockers;
}
}
// A pinned knight can never move.
u64 knights = pos.pieces_of(us, KNIGHT) & ~pinned;
while (knights) {
const int from = pop_lsb(knights);
add_targets(list, from, attacks::knight[from] & ~ours & check_mask, theirs);
}
u64 diag = diag_sliders & ours;
while (diag) {
const int from = pop_lsb(diag);
u64 targets = attacks::bishop(from, occ) & ~ours & check_mask;
if (pinned & bb(from)) targets &= attacks::line[ksq][from];
add_targets(list, from, targets, theirs);
}
u64 orth = orth_sliders & ours;
while (orth) {
const int from = pop_lsb(orth);
u64 targets = attacks::rook(from, occ) & ~ours & check_mask;
if (pinned & bb(from)) targets &= attacks::line[ksq][from];
add_targets(list, from, targets, theirs);
}
const int up = us == WHITE ? 8 : -8;
const u64 start_rank = us == WHITE ? (RANK_1_BB << 8) : (RANK_8_BB >> 8);
const u64 promo_rank = us == WHITE ? RANK_8_BB : RANK_1_BB;
u64 pawns = pos.pieces_of(us, PAWN);
while (pawns) {
const int from = pop_lsb(pawns);
u64 allowed = check_mask;
if (pinned & bb(from)) allowed &= attacks::line[ksq][from];
const int to = from + up;
if (!(occ & bb(to))) {
if (allowed & bb(to)) add_pawn_move(list, from, to, false, promo_rank & bb(to));
const int to2 = to + up;
if ((start_rank & bb(from)) && !(occ & bb(to2)) && (allowed & bb(to2)))
list.add(Move(from, to2, Move::DOUBLE_PUSH));
}
u64 captures = attacks::pawn[us][from] & theirs & allowed;
while (captures) {
const int cap = pop_lsb(captures);
add_pawn_move(list, from, cap, true, promo_rank & bb(cap));
}
if (pos.ep != NO_SQUARE && (attacks::pawn[us][from] & bb(pos.ep))) {
// Rare enough to verify by brute force: rebuild the occupancy and look for any attacker.
const int captured_sq = pos.ep - up;
const u64 occ_after = (occ ^ bb(from) ^ bb(captured_sq)) | bb(pos.ep);
const u64 their_pawns = pos.pieces_of(them, PAWN) & ~bb(captured_sq);
const u64 attackers = (attacks::rook(ksq, occ_after) & orth_sliders & theirs) |
(attacks::bishop(ksq, occ_after) & diag_sliders & theirs) |
(attacks::knight[ksq] & pos.pieces_of(them, KNIGHT)) |
(attacks::pawn[us][ksq] & their_pawns);
if (!attackers) list.add(Move(from, pos.ep, Move::EN_PASSANT));
}
}
if (num_checkers) return;
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));
}
} // namespace rigby
+83
View File
@@ -0,0 +1,83 @@
#include "perft.h"
#include <chrono>
#include <iostream>
namespace rigby {
u64 perft(const Position& pos, int depth) {
MoveList list;
generate_legal(pos, list);
if (depth <= 1) return depth == 1 ? u64(list.size()) : 1;
u64 nodes = 0;
for (Move m : list) {
Position child = pos;
child.make_move(m);
nodes += perft(child, depth - 1);
}
return nodes;
}
void perft_divide(const Position& pos, int depth) {
const auto start = std::chrono::steady_clock::now();
MoveList list;
generate_legal(pos, list);
u64 total = 0;
for (Move m : list) {
Position child = pos;
child.make_move(m);
const u64 n = depth > 1 ? perft(child, depth - 1) : 1;
total += n;
std::cout << m.to_uci() << ": " << 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_suite(int max_depth) {
struct Case {
const char* fen;
int depth;
u64 nodes;
};
static constexpr Case CASES[] = {
{"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", 6, 119060324},
{"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", 5, 193690690},
{"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", 7, 178633661},
{"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1", 5, 15833292},
{"rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", 5, 89941194},
{"r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10", 5, 164075551},
{"8/8/1k6/2b5/2pP4/8/5K2/8 b - d3 0 1", 6, 1440467},
{"8/8/4k3/8/2p5/8/B2P2K1/8 w - - 0 1", 6, 1015133},
{"r3k2r/1b4bq/8/8/8/8/7B/R3K2R w KQkq - 0 1", 4, 1274206},
{"2K2r2/4P3/8/8/8/8/8/3k4 w - - 0 1", 6, 3821001},
{"8/8/2k5/5q2/5n2/8/5K2/8 b - - 0 1", 4, 23527},
};
bool all_ok = true;
u64 total = 0;
const auto start = std::chrono::steady_clock::now();
for (const Case& c : CASES) {
if (c.depth > max_depth) continue;
Position pos;
pos.set_fen(c.fen);
const u64 n = perft(pos, c.depth);
total += n;
const bool ok = n == c.nodes;
all_ok &= ok;
std::cout << (ok ? "[ OK ] " : "[FAIL] ") << c.fen << " depth " << c.depth << ": " << n;
if (!ok) std::cout << " (expected " << c.nodes << ")";
std::cout << std::endl;
}
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") << " - " << total << " nodes in " << ms
<< " ms (" << (ms ? total * 1000 / ms : total) << " nps)" << std::endl;
return all_ok;
}
} // namespace rigby
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "position.h"
namespace rigby {
u64 perft(const Position& pos, int depth);
// Prints the node count of every root move, then the total.
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);
} // namespace rigby
+245
View File
@@ -0,0 +1,245 @@
#include "position.h"
#include <cstring>
#include <sstream>
namespace rigby {
namespace zobrist {
u64 piece_square[12][64];
u64 castling[16];
u64 ep_file[8];
u64 side;
void init() {
Prng rng(0xC0FFEE1234567ULL);
for (auto& piece : piece_square)
for (u64& k : piece) k = rng.next();
for (u64& k : castling) k = rng.next();
for (u64& k : ep_file) k = rng.next();
side = rng.next();
}
} // namespace zobrist
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;
}
}
} // namespace
Position::Position() { std::memset(board, NO_PIECE, sizeof(board)); }
void Position::put_piece(int piece, int sq) {
board[sq] = u8(piece);
pieces[piece_type(piece)] |= bb(sq);
colors[piece_color(piece)] |= bb(sq);
key ^= zobrist::piece_square[piece][sq];
}
void Position::remove_piece(int sq) {
const int piece = board[sq];
board[sq] = NO_PIECE;
pieces[piece_type(piece)] ^= bb(sq);
colors[piece_color(piece)] ^= bb(sq);
key ^= zobrist::piece_square[piece][sq];
}
void Position::move_piece(int from, int to) {
const int piece = board[from];
const u64 mask = bb(from) | bb(to);
board[from] = NO_PIECE;
board[to] = u8(piece);
pieces[piece_type(piece)] ^= mask;
colors[piece_color(piece)] ^= mask;
key ^= zobrist::piece_square[piece][from] ^ zobrist::piece_square[piece][to];
}
bool Position::set_fen(std::string_view fen) {
*this = Position();
std::istringstream ss{std::string(fen)};
std::string placement, side, rights, ep_str;
ss >> placement >> side >> rights >> ep_str;
if (placement.empty() || side.empty()) return false;
int rank = 7, file = 0;
for (char c : placement) {
if (c == '/') {
rank--;
file = 0;
} else if (c >= '1' && c <= '8') {
file += c - '0';
} else {
const auto idx = PIECE_CHARS.find(c);
if (idx == std::string_view::npos || file > 7 || rank < 0) return false;
put_piece(int(idx), make_square(file, rank));
file++;
}
}
if (popcount(pieces_of(WHITE, KING)) != 1 || popcount(pieces_of(BLACK, KING)) != 1) return false;
stm = side == "b" ? BLACK : WHITE;
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 (ep_str.size() == 2 && ep_str[0] >= 'a' && ep_str[0] <= 'h') {
const int sq = make_square(ep_str[0] - 'a', ep_str[1] - '1');
if (sq >= 0 && sq < 64 && (attacks::pawn[stm ^ 1][sq] & pieces_of(stm, PAWN))) ep = sq;
}
if (!(ss >> halfmove)) halfmove = 0;
if (!(ss >> fullmove)) fullmove = 1;
key ^= zobrist::castling[castling];
if (ep != NO_SQUARE) key ^= zobrist::ep_file[file_of(ep)];
if (stm == BLACK) key ^= zobrist::side;
// The side not to move must not be in check.
return !(attackers_to(king_square(stm ^ 1), occupancy()) & colors[stm]);
}
std::string Position::fen() const {
std::string out;
for (int rank = 7; rank >= 0; rank--) {
int empty = 0;
for (int file = 0; file < 8; file++) {
const int piece = board[make_square(file, rank)];
if (piece == NO_PIECE) {
empty++;
continue;
}
if (empty) out += char('0' + empty);
empty = 0;
out += PIECE_CHARS[piece];
}
if (empty) out += char('0' + empty);
if (rank) out += '/';
}
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';
out += ' ';
out += ep == NO_SQUARE ? "-" : square_name(ep);
out += ' ' + std::to_string(halfmove) + ' ' + std::to_string(fullmove);
return out;
}
void Position::make_move(Move m) {
const int from = m.from();
const int to = m.to();
const int us = stm;
const int them = us ^ 1;
const int moving = piece_type(board[from]);
halfmove++;
if (ep != NO_SQUARE) {
key ^= zobrist::ep_file[file_of(ep)];
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;
}
move_piece(from, to);
if (moving == PAWN) {
halfmove = 0;
if (m.flag() == Move::DOUBLE_PUSH) {
const int ep_sq = (from + to) / 2;
if (attacks::pawn[us][ep_sq] & pieces_of(them, PAWN)) {
ep = ep_sq;
key ^= zobrist::ep_file[file_of(ep)];
}
} else if (m.is_promotion()) {
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];
stm = them;
key ^= zobrist::side;
if (stm == WHITE) fullmove++;
}
u64 Position::attackers_to(int sq, u64 occ) const {
return (attacks::pawn[BLACK][sq] & pieces_of(WHITE, PAWN)) | (attacks::pawn[WHITE][sq] & pieces_of(BLACK, PAWN)) |
(attacks::knight[sq] & pieces[KNIGHT]) | (attacks::king[sq] & pieces[KING]) |
(attacks::bishop(sq, occ) & (pieces[BISHOP] | pieces[QUEEN])) |
(attacks::rook(sq, occ) & (pieces[ROOK] | pieces[QUEEN]));
}
bool Position::square_attacked(int sq, int by, u64 occ) const {
const u64 them = colors[by];
return (attacks::pawn[by ^ 1][sq] & pieces[PAWN] & them) || (attacks::knight[sq] & pieces[KNIGHT] & them) ||
(attacks::king[sq] & pieces[KING] & them) ||
(attacks::bishop(sq, occ) & (pieces[BISHOP] | pieces[QUEEN]) & them) ||
(attacks::rook(sq, occ) & (pieces[ROOK] | pieces[QUEEN]) & them);
}
bool Position::insufficient_material() const {
if (pieces[PAWN] | pieces[ROOK] | pieces[QUEEN]) return false;
// K vs K, or K + single minor vs K.
return popcount(occupancy()) <= 3;
}
Move Position::parse_uci(std::string_view uci) const {
MoveList list;
generate_legal(*this, list);
for (Move m : list)
if (m.to_uci() == uci) return m;
return {};
}
std::string Position::pretty() const {
std::string out = "\n +---+---+---+---+---+---+---+---+\n";
for (int rank = 7; rank >= 0; rank--) {
for (int file = 0; file < 8; file++) {
const int piece = board[make_square(file, rank)];
out += " | ";
out += piece == NO_PIECE ? ' ' : PIECE_CHARS[piece];
}
out += " | " + std::to_string(rank + 1) + "\n +---+---+---+---+---+---+---+---+\n";
}
out += " a b c d e f g h\n\nFen: " + fen() + "\n";
char buf[32];
std::snprintf(buf, sizeof(buf), "%016llX", static_cast<unsigned long long>(key));
out += "Key: " + std::string(buf) + "\n";
return out;
}
} // namespace rigby
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <string>
#include <string_view>
#include "bitboard.h"
#include "types.h"
namespace rigby {
namespace zobrist {
void init();
}
// Plain copy-make position. Small enough to copy at every tree step.
struct Position {
u64 pieces[6] = {};
u64 colors[2] = {};
u8 board[64];
int stm = WHITE;
int castling = 0;
int ep = NO_SQUARE; // only set when a capture there is pseudo-legal
int halfmove = 0;
int fullmove = 1;
u64 key = 0;
Position();
bool set_fen(std::string_view fen);
std::string fen() const;
void make_move(Move m);
u64 occupancy() const { return colors[WHITE] | colors[BLACK]; }
u64 pieces_of(int color, int type) const { return pieces[type] & colors[color]; }
int king_square(int color) const { return lsb(pieces_of(color, KING)); }
int piece_on(int sq) const { return board[sq]; }
u64 attackers_to(int sq, u64 occ) const;
bool square_attacked(int sq, int by, u64 occ) const;
u64 checkers() const { return attackers_to(king_square(stm), occupancy()) & colors[stm ^ 1]; }
bool in_check() const { return checkers() != 0; }
bool insufficient_material() const;
// Returns a null move when the string is not a legal move here.
Move parse_uci(std::string_view uci) const;
std::string pretty() const;
private:
void put_piece(int piece, int sq);
void remove_piece(int sq);
void move_piece(int from, int to);
};
void generate_legal(const Position& pos, MoveList& list);
} // namespace rigby
+113
View File
@@ -0,0 +1,113 @@
#pragma once
#include <cstdint>
#include <string>
#include <string_view>
namespace rigby {
using u64 = std::uint64_t;
using u32 = std::uint32_t;
using u16 = std::uint16_t;
using u8 = std::uint8_t;
using i64 = std::int64_t;
constexpr std::string_view START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
enum Color : int { WHITE = 0, BLACK = 1 };
enum PieceType : int { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, NO_PIECE_TYPE };
// A piece is color * 6 + type, NO_PIECE marks an empty square.
constexpr int NO_PIECE = 12;
constexpr int make_piece(int color, int type) { return color * 6 + type; }
constexpr int piece_type(int piece) { return piece % 6; }
constexpr int piece_color(int piece) { return piece / 6; }
constexpr std::string_view PIECE_CHARS = "PNBRQKpnbrqk";
// clang-format off
enum Square : int {
A1, B1, C1, D1, E1, F1, G1, H1,
A2, B2, C2, D2, E2, F2, G2, H2,
A3, B3, C3, D3, E3, F3, G3, H3,
A4, B4, C4, D4, E4, F4, G4, H4,
A5, B5, C5, D5, E5, F5, G5, H5,
A6, B6, C6, D6, E6, F6, G6, H6,
A7, B7, C7, D7, E7, F7, G7, H7,
A8, B8, C8, D8, E8, F8, G8, H8,
NO_SQUARE
};
// clang-format on
constexpr int file_of(int sq) { return sq & 7; }
constexpr int rank_of(int sq) { return sq >> 3; }
constexpr int make_square(int file, int rank) { return rank * 8 + file; }
// Mirrors the square vertically for black, so tables can be written from white's view.
constexpr int relative_square(int color, int sq) { return color == WHITE ? sq : sq ^ 56; }
enum CastlingRight : int { WHITE_OO = 1, WHITE_OOO = 2, BLACK_OO = 4, BLACK_OOO = 8 };
inline std::string square_name(int sq) {
return {char('a' + file_of(sq)), char('1' + rank_of(sq))};
}
// 16-bit move: from (6) | to (6) | flags (4).
class Move {
public:
enum Flag : u16 {
QUIET = 0,
DOUBLE_PUSH = 1,
KING_CASTLE = 2,
QUEEN_CASTLE = 3,
CAPTURE = 4,
EN_PASSANT = 5,
PROMO = 8, // + 0..3 for knight, bishop, rook, queen
PROMO_CAPTURE = 12, // + 0..3
};
constexpr Move() = default;
constexpr Move(int from, int to, int flag) : data_(u16(from | (to << 6) | (flag << 12))) {}
static constexpr Move from_raw(u16 raw) {
Move m;
m.data_ = raw;
return m;
}
constexpr int from() const { return data_ & 63; }
constexpr int to() const { return (data_ >> 6) & 63; }
constexpr int flag() const { return data_ >> 12; }
constexpr bool is_capture() const { return flag() & 4; }
constexpr bool is_promotion() const { return flag() & 8; }
constexpr bool is_castle() const { return flag() == KING_CASTLE || flag() == QUEEN_CASTLE; }
constexpr bool is_en_passant() const { return flag() == EN_PASSANT; }
constexpr int promo_type() const { return (flag() & 3) + KNIGHT; }
constexpr u16 raw() const { return data_; }
constexpr explicit operator bool() const { return data_ != 0; }
constexpr bool operator==(const Move&) const = default;
std::string to_uci() const {
if (!data_) return "0000";
std::string s = square_name(from()) + square_name(to());
if (is_promotion()) s += "nbrq"[promo_type() - KNIGHT];
return s;
}
private:
u16 data_ = 0;
};
struct MoveList {
Move moves[256];
int count = 0;
void add(Move m) { moves[count++] = m; }
void clear() { count = 0; }
int size() const { return count; }
bool empty() const { return count == 0; }
Move operator[](int i) const { return moves[i]; }
const Move* begin() const { return moves; }
const Move* end() const { return moves + count; }
};
} // namespace rigby
+254
View File
@@ -0,0 +1,254 @@
#include "uci.h"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "eval.h"
#include "mcts.h"
#include "perft.h"
#include "position.h"
#include "uci_io.h"
namespace rigby {
namespace {
constexpr const char* ENGINE_NAME = "Rigby";
constexpr const char* ENGINE_VERSION = "0.1-dev";
constexpr const char* ENGINE_AUTHOR = "rektdie";
constexpr int DEFAULT_HASH_MB = 64;
constexpr int DEFAULT_BENCH_PLAYOUTS = 5000;
using uci_io::send;
struct Engine {
Position pos;
std::vector<u64> history;
Searcher searcher;
std::thread worker;
Engine() {
pos.set_fen(START_FEN);
history = {pos.key};
searcher.set_hash(DEFAULT_HASH_MB);
}
void stop() {
searcher.stop_flag = true;
if (worker.joinable()) worker.join();
}
};
void print_id() {
send(std::string("id name ") + ENGINE_NAME + " " + ENGINE_VERSION);
send(std::string("id author ") + ENGINE_AUTHOR);
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");
// 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 FPUReduction type spin default 30 min 0 max 200");
send("option name PolicyTemp type spin default 100 min 10 max 500");
send("uciok");
}
void set_option(Engine& e, std::istringstream& is) {
std::string token, name, value;
is >> token; // "name"
while (is >> token && token != "value") name += (name.empty() ? "" : " ") + token;
while (is >> token) value += (value.empty() ? "" : " ") + token;
std::string lname = name;
std::transform(lname.begin(), lname.end(), lname.begin(), [](unsigned char c) { return char(std::tolower(c)); });
int v = 0;
try {
v = std::stoi(value);
} catch (...) {
send("info string invalid value for option " + name);
return;
}
if (lname == "hash")
e.searcher.set_hash(size_t(std::clamp(v, 1, 65536)));
else if (lname == "threads")
; // single-threaded for now
else if (lname == "moveoverhead")
e.searcher.params.move_overhead = std::clamp(v, 0, 5000);
else if (lname == "cpuct")
e.searcher.params.cpuct = float(v) / 100.0f;
else if (lname == "fpureduction")
e.searcher.params.fpu_reduction = float(v) / 100.0f;
else if (lname == "policytemp")
e.searcher.params.policy_temperature = float(v) / 100.0f;
else
send("info string unknown option " + name);
}
void set_position(Engine& e, std::istringstream& is) {
std::string token, fen;
is >> token;
if (token == "startpos") {
fen = START_FEN;
} else if (token == "fen") {
while (is >> token && token != "moves") fen += token + " ";
} else {
return;
}
Position pos;
if (!pos.set_fen(fen)) {
send("info string invalid fen: " + fen);
return;
}
e.pos = pos;
e.history = {pos.key};
while (is >> token) {
if (token == "moves") continue;
const Move m = e.pos.parse_uci(token);
if (!m) {
send("info string illegal move: " + token);
break;
}
e.pos.make_move(m);
e.history.push_back(e.pos.key);
}
}
void go(Engine& e, std::istringstream& is) {
SearchLimits limits;
std::string token;
bool limited = false;
while (is >> token) {
if (token == "wtime") is >> limits.time[WHITE], limited = true;
else if (token == "btime") is >> limits.time[BLACK], limited = true;
else if (token == "winc") is >> limits.inc[WHITE];
else if (token == "binc") is >> limits.inc[BLACK];
else if (token == "movestogo") is >> limits.movestogo;
else if (token == "movetime") is >> limits.movetime, limited = true;
else if (token == "nodes") is >> limits.nodes, limited = true;
else if (token == "depth") is >> limits.depth, limited = true;
else if (token == "infinite") limits.infinite = true;
}
if (!limited) limits.infinite = true;
e.stop();
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("bestmove " + result.best.to_uci());
});
}
} // namespace
void run_bench(int playouts_per_position) {
static constexpr const char* POSITIONS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4",
"rnbqkb1r/pp1p1ppp/4pn2/2p5/2PP4/2N5/PP2PPPP/R1BQKBNR w KQkq - 0 4",
"r1bq1rk1/ppp2ppp/2np1n2/2b1p3/2B1P3/2NP1N2/PPP2PPP/R1BQ1RK1 w - - 0 7",
"2rq1rk1/pp1bppbp/2np1np1/8/3NP3/1BN1BP2/PPPQ2PP/2KR3R b - - 8 11",
"r2qr1k1/1p1nbppp/p2pbn2/4p3/4P3/1NN1BP2/PPPQ2PP/2KR1B1R w - - 3 12",
"r1b2rk1/2q1bppp/p2ppn2/1p6/3BPP2/2N2B2/PPPQ2PP/R4R1K b - - 2 14",
"3r1rk1/p4pp1/1pq1p2p/2p1Pn2/2P2P2/P2Q2P1/1P4BP/3RR1K1 b - - 0 22",
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"8/5pk1/6p1/7p/7P/6P1/5PK1/8 w - - 0 40",
"4r1k1/r1q2ppp/ppp2n2/4P3/5Rb1/1N1BQ3/PPP3PP/R5K1 w - - 1 17",
"r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15",
"8/8/8/4k3/8/8/2KR4/8 w - - 0 1",
"6k1/6p1/8/6KQ/1r6/q2b4/8/8 w - - 0 32",
};
Searcher searcher;
SearchLimits limits;
limits.nodes = u64(std::max(playouts_per_position, 1));
// Every playout always counts as one node, so a fixed playout budget would
// give the same total for every build. Instead the bench signature counts
// each position visited in the tree, which moves whenever search changes.
u64 total_nodes = 0;
const auto start = std::chrono::steady_clock::now();
for (const char* fen : POSITIONS) {
Position pos;
if (!pos.set_fen(fen)) {
std::cout << "info string bench: invalid fen " << fen << std::endl;
continue;
}
searcher.stop_flag = false;
const SearchResult r = searcher.search(pos, {pos.key}, limits, false);
total_nodes += r.tree_positions;
}
const auto ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::cout << total_nodes << " nodes " << (ms ? total_nodes * 1000 / u64(ms) : total_nodes) << " nps" << std::endl;
}
void uci_loop() {
auto engine = std::make_unique<Engine>();
Engine& e = *engine;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream is(line);
std::string cmd;
is >> cmd;
if (cmd == "uci") {
print_id();
} else if (cmd == "isready") {
send("readyok");
} else if (cmd == "ucinewgame") {
e.stop();
e.pos.set_fen(START_FEN);
e.history = {e.pos.key};
} else if (cmd == "position") {
e.stop();
set_position(e, is);
} else if (cmd == "go") {
go(e, is);
} else if (cmd == "stop") {
e.stop();
} else if (cmd == "quit") {
break;
} else if (cmd == "setoption") {
e.stop();
set_option(e, is);
} else if (cmd == "d") {
send(e.pos.pretty());
} else if (cmd == "eval") {
send("static " + std::to_string(eval::static_eval(e.pos)) + " cp, qsearch " +
std::to_string(eval::quiescence(e.pos, -30000, 30000, 0)) + " cp (side to move)");
} else if (cmd == "perft") {
int depth = 5;
is >> depth;
e.stop();
perft_divide(e.pos, depth);
} else if (cmd == "perftsuite") {
int depth = 6;
is >> depth;
e.stop();
perft_suite(depth);
} else if (cmd == "bench") {
int playouts = DEFAULT_BENCH_PLAYOUTS;
is >> playouts;
e.stop();
run_bench(playouts);
} else if (!cmd.empty()) {
send("info string unknown command: " + cmd);
}
}
e.stop();
}
} // namespace rigby
+9
View File
@@ -0,0 +1,9 @@
#pragma once
namespace rigby {
void uci_loop();
// Fixed-node search over a fixed set of positions; the last line is parsed by OpenBench.
void run_bench(int playouts_per_position);
} // namespace rigby
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <iostream>
#include <mutex>
#include <string_view>
namespace rigby::uci_io {
// The search thread and the input thread both write to stdout; keep lines whole.
inline std::mutex& output_mutex() {
static std::mutex m;
return m;
}
inline void send(std::string_view line) {
std::lock_guard<std::mutex> lock(output_mutex());
std::cout << line << std::endl;
}
} // namespace rigby::uci_io