fertig-classic-games/tools/verifyBackgammon.js

504 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
// verifyBackgammon.js — headless checks for Backgammon ("Tavli at the kafeneio"):
// • rules on hand-built positions: maximum-dice and higher-die rules, bar
// entry and dancing, bearing off (exact, overshoot, blocked by a higher
// checker), hits, the opening roll, gammon / backgammon, the cube (offer,
// take, drop, ownership, 64 cap), Jacoby, matches + Crawford, notation
// • turn generation = an unrestricted brute force on positions from real games
// • bear-off table: exact small values, monotone in checkers, race odds sane
// • AI soak: all-AI games with the cube finish legally; every AI turn is one
// of the legal maximal turns; checkers always 15 a side
// • skill ladder with mirrored seeds (same dice, seats swapped)
// • dice throws land on the rolled faces inside the roller's half
// • layout: furniture on screen and apart, stacks inside their points,
// tray / bar / cube placements, hit-testing, mirror symmetry
// • checker registry: a move relocates exactly the top checker
// Usage: node tools/verifyBackgammon.js [--quick]
import * as L from '../src/games/backgammon/BackgammonLogic.js';
import * as AI from '../src/games/backgammon/BackgammonAI.js';
import * as Bearoff from '../src/games/backgammon/BackgammonBearoff.js';
import * as Lay from '../src/games/backgammon/BackgammonLayout.js';
import { CheckerSet } from '../src/games/backgammon/BackgammonCheckers.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
import { planTrayThrow, topFace } from '../src/ui/dice/Dice3D.js';
const QUICK = process.argv.includes('--quick');
let pass = 0, fail = 0;
function ok(label, cond, detail = '') {
if (cond) pass++;
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
}
const section = (n) => console.log(`\n${n}`);
const near = (a, b, eps) => Math.abs(a - b) <= eps;
// Build a state: white / black = { idx: count }, plus bar / off.
function pos({ white = {}, black = {}, bar = {}, off = {}, dice = null, player = 'white', opts = {} }) {
const s = L.createInitialState(opts);
for (let i = 0; i < 24; i++) s.points[i] = { color: null, count: 0 };
for (const [i, n] of Object.entries(white)) s.points[i] = { color: 'white', count: n };
for (const [i, n] of Object.entries(black)) s.points[i] = { color: 'black', count: n };
s.bar = { white: bar.white ?? 0, black: bar.black ?? 0 };
const placed = (c) => Object.values(c === 'white' ? white : black).reduce((a, b) => a + b, 0) + s.bar[c];
s.borneOff = { white: off.white ?? 15 - placed('white'), black: off.black ?? 15 - placed('black') };
s.currentPlayer = player;
s.phase = 'roll';
if (dice) {
s.dice = dice.slice();
s.movesLeft = dice[0] === dice[1] ? [dice[0], dice[0], dice[0], dice[0]] : dice.slice();
s.phase = 'move';
}
return s;
}
const mv = (m) => `${m.from}>${m.to}/${m.dieUsed}`;
// ── rules ────────────────────────────────────────────────────────────────────
section('Rules');
{
const s0 = L.createInitialState();
ok('15 checkers a side at the start', L.checkerTotals(s0).white === 15 && L.checkerTotals(s0).black === 15);
ok('pip counts start at 167', L.computePipCount(s0, 'white') === 167 && L.computePipCount(s0, 'black') === 167);
ok('a fresh game begins with the opening roll', s0.phase === 'opening');
// opening roll
const tie = L.openingWith(s0, 4, 4);
ok('opening tie stays in the opening', tie.phase === 'opening' && tie.opening.white === 4);
const ow = L.openingWith(s0, 5, 2);
ok('higher opening die starts and plays both numbers', ow.currentPlayer === 'white' && ow.dice[0] === 5 && ow.dice[1] === 2 && ow.phase === 'move' && ow.movesLeft.length === 2);
const ob = L.openingWith(s0, 1, 6);
ok('black can start too, dice reordered for the starter', ob.currentPlayer === 'black' && ob.dice[0] === 6 && ob.dice[1] === 1);
ok('opening roll counts in the starter\'s stats', ob.stats.black.rolls === 1 && ob.stats.black.pips === 7 && ob.stats.white.rolls === 0);
// maximum dice: both must be used when possible
{
// single checker on 10 (point 11): 10-6=4 blocked, 10-1=9 open, 9-6=3 open → must play 1 then 6
const s = pos({ white: { 10: 1, 0: 14 }, black: { 4: 2, 23: 13 }, dice: [6, 1] });
const turns = L.legalTurns(s);
ok('max-dice: every legal turn uses both dice', turns.length > 0 && turns.every((t) => t.moves.length === 2), JSON.stringify(turns.map((t) => t.moves.map(mv))));
const v = L.getValidMoves(s).map(mv);
ok('max-dice: the only first step is the 1 that unlocks the 6', v.length === 1 && v[0] === '10>9/1', v.join(','));
}
{
// only one die can be played → it must be the higher one
const s = pos({ white: { 20: 1, 0: 14 }, black: { 11: 2, 23: 13 }, dice: [6, 3] });
const v = L.getValidMoves(s).map(mv);
ok('higher-die rule: forced to play the 6', v.length === 1 && v[0] === '20>14/6', v.join(','));
const s2 = pos({ white: { 20: 1, 0: 14 }, black: { 14: 2, 11: 2, 23: 11 }, dice: [6, 3] });
const v2 = L.getValidMoves(s2).map(mv);
ok('higher-die rule: the 3 is fine when the 6 cannot be played at all', v2.length === 1 && v2[0] === '20>17/3', v2.join(','));
}
{
// doubles: play as many as possible
const s = pos({ white: { 12: 1 }, black: { 0: 2, 23: 13 }, dice: [4, 4] });
const turns = L.legalTurns(s);
ok('doubles: blocked after two steps → turns use exactly two 4s', turns.length === 1 && turns[0].moves.length === 2, JSON.stringify(turns.map((t) => t.moves.map(mv))));
const s1 = pos({ white: { 12: 1, 0: 14 }, black: { 4: 2, 23: 13 }, dice: [4, 4] });
ok('doubles: only one 4 playable → a one-move turn', L.legalTurns(s1).every((t) => t.moves.length === 1));
}
// bar entry
{
const s = pos({ white: { 5: 14 }, bar: { white: 1 }, black: { 18: 2, 19: 2, 0: 11 }, player: 'white' });
const r = L.rollSpecificDice(s, 6, 5);
ok('dance: both entry points made → no move', !L.hasAnyMove(r) && L.turnDone(r));
ok('dance is counted in the stats', r.stats.white.dances === 1 && r.stats.white.barTurns === 1);
const r2 = L.rollSpecificDice(s, 6, 3);
const v = L.getValidMoves(r2).map(mv);
ok('bar first: only the entering move is legal', v.length === 1 && v[0] === 'bar>21/3', v.join(','));
const b = pos({ black: { 18: 14 }, bar: { black: 1 }, white: { 5: 15 }, player: 'black' });
const rb = L.rollSpecificDice(b, 2, 2);
ok('black enters on White\'s home board (a 2 → point 2)', L.getValidMoves(rb).some((m) => m.from === 'bar' && m.to === 1));
}
// hits
{
const s = pos({ white: { 8: 2, 5: 13 }, black: { 3: 1, 23: 14 }, dice: [5, 2] });
const m = L.getValidMoves(s).find((x) => x.from === 8 && x.to === 3);
ok('landing on a lone checker is a hit', m && m.hit);
const a = L.applyMove(s, m);
ok('the hit checker goes to the bar', a.bar.black === 1 && a.points[3].color === 'white' && a.points[3].count === 1);
ok('hit stats', a.stats.white.hits === 1 && a.stats.black.hitTaken === 1);
ok('applyMove consumes exactly the die', a.movesLeft.length === 1 && a.movesLeft[0] === 2);
ok('the turn is not over until both dice are used', !L.turnDone(a));
const b2 = L.applyMove(a, L.getValidMoves(a)[0]);
ok('turnDone once the dice are spent; endTurn passes the dice', L.turnDone(b2) && L.endTurn(b2).currentPlayer === 'black' && L.endTurn(b2).phase === 'roll');
}
// bearing off
{
const s = pos({ white: { 2: 1, 4: 1 }, black: { 23: 15 }, dice: [6, 1] });
const v = L.getValidMoves(s).map(mv);
ok('overshoot: the 6 bears off the highest checker only', v.includes('4>off/6') && !v.includes('2>off/6'), v.join(','));
ok('every ordering is offered (2>1 then 4>off reaches the same place as the reverse)', v.includes('4>3/1') && v.includes('2>1/1'), v.join(','));
const s2 = pos({ white: { 7: 1, 3: 1 }, black: { 23: 15 }, dice: [4, 2] });
ok('no bearing off while a checker is outside home', L.getValidMoves(s2).every((m) => m.to !== 'off'));
const s3 = pos({ white: { 0: 1 }, black: { 23: 15 }, dice: [3, 1] });
const end = L.applyMove(s3, L.getValidMoves(s3).find((m) => m.dieUsed === 3));
ok('bearing off the last checker ends the game (higher die)', end.phase === 'game_over' && end.winner === 'white');
ok('wasted pips are counted', end.stats.white.pipsWasted === 2);
}
// gammons
{
const g = pos({ white: { 0: 1 }, black: { 10: 15 }, dice: [1, 2] });
const gm = L.applyMove(g, L.getValidMoves(g).find((m) => m.to === 'off'));
ok('gammon when the loser bore off nothing', gm.result.kind === 'gammon' && gm.result.points === 2);
const bg = pos({ white: { 0: 1 }, black: { 3: 1, 10: 14 }, dice: [1, 2] });
const bgm = L.applyMove(bg, L.getValidMoves(bg).find((m) => m.to === 'off'));
ok('backgammon when a loser checker is in the winner\'s home', bgm.result.kind === 'backgammon' && bgm.result.points === 3);
const bb = pos({ white: { 0: 1 }, black: { 10: 14 }, bar: { black: 1 }, dice: [1, 2] });
ok('backgammon when a loser checker is on the bar', L.applyMove(bb, L.getValidMoves(bb).find((m) => m.to === 'off')).result.kind === 'backgammon');
const sg = pos({ white: { 0: 1 }, black: { 20: 14 }, off: { black: 1 }, dice: [1, 2] });
ok('single game once the loser has borne one off', L.applyMove(sg, L.getValidMoves(sg).find((m) => m.to === 'off')).result.kind === 'single');
const jg = pos({ white: { 0: 1 }, black: { 10: 15 }, dice: [1, 2], opts: { jacoby: true } });
const jr = L.applyMove(jg, L.getValidMoves(jg).find((m) => m.to === 'off')).result;
ok('Jacoby: no gammon with a centred cube', jr.kind === 'single' && jr.points === 1 && jr.jacobyWaived);
const jc = pos({ white: { 0: 1 }, black: { 10: 15 }, dice: [1, 2], opts: { jacoby: true } });
jc.cube = { value: 2, owner: 'white' };
const jcr = L.applyMove(jc, L.getValidMoves(jc).find((m) => m.to === 'off')).result;
ok('Jacoby: the gammon counts once the cube is turned (2 × 2)', jcr.kind === 'gammon' && jcr.points === 4);
}
// the cube
{
let s = pos({ white: { 5: 15 }, black: { 18: 15 } });
ok('either player may double from the centre', L.canDouble(s, 'white') && !L.canDouble(s, 'black'));
s = L.offerDouble(s);
ok('offer → phase double, offerer remembered', s.phase === 'double' && s.pendingDouble === 'white');
const t = L.takeDouble(s);
ok('take → cube 2 owned by the taker; offerer still rolls', t.cube.value === 2 && t.cube.owner === 'black' && t.phase === 'roll' && t.currentPlayer === 'white');
ok('the cube owner alone may redouble', !L.canDouble(t, 'white') && L.canDouble({ ...t, currentPlayer: 'black' }, 'black'));
const d = L.dropDouble(s);
ok('drop → offerer wins the current stake', d.phase === 'game_over' && d.winner === 'white' && d.result.kind === 'drop' && d.result.points === 1);
const big = { ...pos({ white: { 5: 15 }, black: { 18: 15 } }), cube: { value: 64, owner: 'white' } };
ok('no doubling past 64', !L.canDouble(big, 'white'));
const off = pos({ white: { 5: 15 }, black: { 18: 15 }, opts: { cubeEnabled: false } });
ok('no doubling with the cube switched off', !L.canDouble(off, 'white'));
}
// matches
{
let m = L.createMatch(5);
m = L.recordGame(m, { winner: 'white', points: 2, kind: 'gammon' });
ok('match score adds the points', m.score.white === 2 && !m.over);
m = L.recordGame(m, { winner: 'white', points: 2, kind: 'gammon' });
ok('reaching match point → the next game is Crawford', m.score.white === 4 && m.crawford);
ok('Crawford game: cube disabled', L.gameOptions(m, { cube: true }).cubeEnabled === false);
m = L.recordGame(m, { winner: 'black', points: 1, kind: 'single' });
ok('after Crawford the cube is back', !m.crawford && m.hadCrawford && L.gameOptions(m, { cube: true }).cubeEnabled);
m = L.recordGame(m, { winner: 'black', points: 4, kind: 'drop' });
ok('no second Crawford game', !m.crawford);
m = L.recordGame(m, { winner: 'white', points: 1, kind: 'single' });
ok('match over at the target', m.over && m.winner === 'white');
const one = L.recordGame(L.createMatch(0), { winner: 'black', points: 2, kind: 'gammon' });
ok('a single game is over at once', one.over && one.winner === 'black' && one.score.black === 2);
ok('Jacoby only applies to single games', L.gameOptions(L.createMatch(5), { jacoby: true }).jacoby === false && L.gameOptions(L.createMatch(0), { jacoby: true }).jacoby === true);
}
// notation
{
ok('notation from the mover\'s side', L.moveText('white', { from: 12, to: 6, hit: true }) === '13/7*' && L.moveText('black', { from: 0, to: 6, hit: false }) === '24/18');
ok('repeated moves collapse', L.turnText('white', [{ from: 12, to: 8 }, { from: 12, to: 8 }]) === '13/9(2)');
ok('bar / off notation', L.moveText('white', { from: 'bar', to: 20 }) === 'bar/21' && L.moveText('white', { from: 2, to: 'off' }) === '3/off');
}
// combined (same-checker) paths
{
const s = L.openingWith(L.createInitialState(), 6, 5);
const paths = L.checkerPaths(s, 23);
ok('checkerPaths: 6-5 runner goes to 18 or (lover\'s leap) 13; their 6-point blocks the 5', [17, 12].every((t) => paths.some((p) => p.to === t)) && !paths.some((p) => p.to === 18), paths.map((p) => p.to).join(','));
ok('checkerPaths: 11 uses two dice', paths.find((p) => p.to === 12)?.moves.length === 2);
}
}
// ── turn generation vs brute force ───────────────────────────────────────────
section('Turn generation');
{
function brute(me, op, dice) {
const res = new Map();
let max = 0;
const rec = (m, o, rem, seq) => {
let any = false;
for (const d of [...new Set(rem)]) {
L.forEachStep(m, o, d, (f, to) => {
any = true;
const m2 = m.slice(), o2 = o.slice();
L.stepP(m2, o2, f, to);
const r = rem.slice(); r.splice(r.indexOf(d), 1);
rec(m2, o2, r, seq.concat([d]));
});
}
if (!any) {
if (seq.length > max) { max = seq.length; res.clear(); }
if (seq.length === max) { const k = L.posKey(m, o); if (!res.has(k)) res.set(k, seq); }
}
};
rec(me, op, dice, []);
let keys = [...res.keys()];
if (max === 1 && dice.length === 2 && dice[0] !== dice[1]) {
const hi = Math.max(...dice);
if ([...res.values()].some((q) => q[0] === hi)) keys = keys.filter((k) => res.get(k)[0] === hi);
}
return new Set(keys);
}
const rng = mulberry32(77);
let checked = 0, bad = 0;
for (let g = 0; g < (QUICK ? 15 : 60); g++) {
let s = L.rollOpening(L.createInitialState(), rng);
while (s.phase === 'opening') s = L.rollOpening(s, rng);
let guard = 0;
while (s.phase !== 'game_over' && guard++ < 500) {
if (s.phase === 'roll') s = L.rollDice(s, rng);
const { me, op } = L.boardsFor(s, s.currentPlayer);
const A = new Set(L.enumerateTurns(me, op, s.movesLeft).map((t) => t.key));
const B = brute(me, op, s.movesLeft);
checked++;
if (A.size !== B.size || [...A].some((k) => !B.has(k))) bad++;
const turns = L.legalTurns(s);
const t = turns[Math.floor(rng() * turns.length)];
for (const m of t.moves) { s = L.applyMove(s, m); if (s.phase === 'game_over') break; }
if (s.phase !== 'game_over') s = L.endTurn(s);
}
}
ok(`enumerateTurns matches brute force on ${checked} positions`, bad === 0, `${bad} mismatches`);
}
// ── bear-off table ───────────────────────────────────────────────────────────
section('Bear-off table');
{
const t0 = Date.now();
let steps = 0;
while (!Bearoff.buildStep(5000)) steps++;
ok('table builds in slices', steps > 3 && Bearoff.ready(), `steps ${steps}`);
ok(`54,264 positions (built in ${Date.now() - t0} ms)`, Bearoff.size() === 54264);
const E = (c) => Bearoff.expectedRolls(c).e;
ok('1 checker on the ace: exactly 1 roll', near(E([1, 0, 0, 0, 0, 0]), 1, 1e-6));
ok('2 checkers on the ace: exactly 1 roll', near(E([2, 0, 0, 0, 0, 0]), 1, 1e-6));
ok('1 checker on the 6-point: 1.25 rolls (9 of 36 rolls fall short)', near(E([0, 0, 0, 0, 0, 1]), 1.25, 1e-5));
ok('4 on the ace: 1 + 30/36 (only doubles do it at once)', near(E([4, 0, 0, 0, 0, 0]), 1 + 30 / 36, 1e-5));
const rng = mulberry32(5);
let mono = true;
for (let k = 0; k < 400; k++) {
const c = [0, 0, 0, 0, 0, 0];
const n = 1 + Math.floor(rng() * 13);
for (let i = 0; i < n; i++) c[Math.floor(rng() * 6)]++;
const j = Math.floor(rng() * 6);
const c2 = c.slice(); c2[j]++;
if (E(c2) + 1e-6 < E(c)) mono = false;
}
ok('adding a checker never makes the bear-off faster', mono);
const p = Bearoff.raceWinProb([0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 0]);
ok('a short bear-off beats a long one, even off roll', p > 0.9, `p=${p}`);
const sym = Bearoff.raceWinProb([2, 2, 2, 2, 2, 2], [2, 2, 2, 2, 2, 2]);
ok('equal bear-offs: the side on roll is the favourite', sym < 0.5 && sym > 0.15, `p=${sym}`);
}
// ── AI ───────────────────────────────────────────────────────────────────────
section('AI');
AI.SKILL[5].budgetMs = 0; // deterministic searches in tests
function playGame(skW, skB, seed, { cube = false, check = false } = {}) {
const dice = mulberry32(seed), noise = mulberry32(seed * 7 + 1);
let s = L.createInitialState({ cubeEnabled: cube });
while (s.phase === 'opening') s = L.rollOpening(s, dice);
let guard = 0, legalBad = 0, consBad = 0, dbl = 0;
while (s.phase !== 'game_over' && guard++ < 1500) {
if (s.phase === 'roll') {
const p = s.currentPlayer, sk = p === 'white' ? skW : skB;
if (cube && L.canDouble(s, p) && AI.shouldDouble(s, p, sk, null, noise)) {
dbl++;
s = L.offerDouble(s);
s = AI.shouldTake(s, L.other(p), p === 'white' ? skB : skW, null, noise) ? L.takeDouble(s) : L.dropDouble(s);
if (s.phase === 'game_over') break;
}
s = L.rollDice(s, dice);
}
const sk = s.currentPlayer === 'white' ? skW : skB;
const r = AI.chooseTurn(s, sk, noise);
if (check) {
const { me, op } = L.boardsFor(s, s.currentPlayer);
const keys = new Set(L.enumerateTurns(me, op, s.movesLeft).map((t) => t.key));
let t = s;
for (const m of r.moves) t = L.applyMove(t, m);
const after = L.boardsFor({ ...t, phase: 'move' }, s.currentPlayer);
if (!keys.has(L.posKey(after.me, after.op))) legalBad++;
}
for (const m of r.moves) { s = L.applyMove(s, m); if (s.phase === 'game_over') break; }
if (s.phase !== 'game_over') {
if (!L.turnDone(s)) legalBad++;
s = L.endTurn(s);
}
const tot = L.checkerTotals(s);
if (tot.white !== 15 || tot.black !== 15) consBad++;
}
return { winner: s.winner, result: s.result, guard, legalBad, consBad, dbl };
}
{
const N = QUICK ? 40 : 240;
let fin = 0, legal = 0, cons = 0, cubeGames = 0, drops = 0, kinds = { single: 0, gammon: 0, backgammon: 0, drop: 0 };
for (let g = 0; g < N; g++) {
const r = playGame(1 + (g % 5), 1 + ((g * 3) % 5), 300 + g, { cube: true, check: g % 4 === 0 });
if (r.winner && r.guard < 1500) fin++;
legal += r.legalBad; cons += r.consBad;
if (r.dbl) cubeGames++;
if (r.result?.kind === 'drop') drops++;
kinds[r.result?.kind ?? 'single']++;
}
ok(`${N} all-AI games with the cube all finish`, fin === N, `${fin}/${N}`);
ok('every AI turn is a legal maximal turn and ends the roll', legal === 0, `${legal} bad`);
ok('checkers conserved (15 a side) throughout', cons === 0);
ok('the AIs use the cube', cubeGames > N * 0.2, `${cubeGames} games with a double, ${drops} drops`);
ok('gammons happen but are not the norm', kinds.gammon + kinds.backgammon > 0 && kinds.gammon + kinds.backgammon < N * 0.5, JSON.stringify(kinds));
// cube judgement on clear positions
const crush = pos({ white: { 0: 3, 1: 3, 2: 3, 3: 3, 4: 3 }, black: { 18: 3, 19: 3, 20: 3, 21: 3, 22: 3 }, off: { white: 0, black: 0 } });
// white needs ~45 pips, black ~75 → white is a huge favourite
ok('skill 5 doubles a big race lead', AI.shouldDouble(crush, 'white', 5, null, () => 0.5));
const even = L.createInitialState();
even.phase = 'roll';
ok('skill 5 does not double the opening position', !AI.shouldDouble(even, 'white', 5, null, () => 0.5));
ok('skill 5 takes from the opening position', AI.shouldTake(L.offerDouble(even), 'black', 5, null, () => 0.5));
const hopeless = pos({ white: { 0: 2 }, black: { 0: 0, 12: 15 }, off: { white: 13 } });
ok('skill 5 drops a hopeless race', !AI.shouldTake(L.offerDouble(hopeless), 'black', 5, null, () => 0.5));
const m5 = L.createMatch(5); m5.score = { white: 4, black: 2 };
ok('dead cube: no double when a win already takes the match', !AI.shouldDouble(crush, 'white', 5, m5, () => 0.5));
// hint / explain
const op = L.openingWith(L.createInitialState(), 3, 1);
const h = AI.hint(op);
ok('hint for 3-1 opening makes the 5-point (8/5 6/5)', L.turnText('white', h.moves) === '8/5 6/5' || L.turnText('white', h.moves) === '6/5 8/5', L.turnText('white', h.moves));
ok('hint reason names the 5-point', /5-point/.test(h.reason), h.reason);
const op2 = L.openingWith(L.createInitialState(), 6, 1);
ok('hint for 6-1 opening makes the bar point (13/7 8/7)', /13\/7/.test(L.turnText('white', AI.hint(op2).moves)) && /8\/7/.test(L.turnText('white', AI.hint(op2).moves)), L.turnText('white', AI.hint(op2).moves));
}
section('Skill ladder (mirrored seeds)');
{
const pairs = (a, b, n, off) => {
let w = 0;
for (let i = 0; i < n; i++) {
if (playGame(a, b, 9000 + off + i).winner === 'white') w++;
if (playGame(b, a, 9000 + off + i).winner === 'black') w++;
}
return w / (2 * n);
};
const n = QUICK ? 30 : 150;
for (const [a, b] of [[2, 1], [3, 2], [4, 3]]) {
const r = pairs(a, b, n, a * 1000);
console.log(` skill ${a} vs ${b}: ${(r * 100).toFixed(1)}% over ${2 * n} games`);
ok(`skill ${a} beats skill ${b}`, r > (QUICK ? 0.5 : 0.55), `${(r * 100).toFixed(1)}%`);
}
const n5 = QUICK ? 8 : 60;
const t0 = Date.now();
const r5 = pairs(5, 4, n5, 5000);
console.log(` skill 5 vs 4: ${(r5 * 100).toFixed(1)}% over ${2 * n5} games (${((Date.now() - t0) / 1000).toFixed(0)} s)`);
if (!QUICK) ok('skill 5 beats skill 4', r5 > 0.55, `${(r5 * 100).toFixed(1)}%`);
// search time for one skill-5 decision in a busy middle game
const busy = L.rollSpecificDice({ ...L.createInitialState(), phase: 'roll' }, 3, 3);
const t1 = Date.now();
AI.chooseTurn(busy, 5, () => 0.5);
const dt = Date.now() - t1;
ok('a skill-5 decision on a double takes under 1.5 s (node)', dt < 1500, `${dt} ms`);
}
// ── dice ─────────────────────────────────────────────────────────────────────
section('Dice throws');
{
const lay = Lay.makeLayout(false);
const rng = mulberry32(3);
let badFace = 0, outside = 0, close = 0;
for (let k = 0; k < (QUICK ? 40 : 200); k++) {
const who = k % 2 ? 'white' : 'black';
const faces = [1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)];
const plan = planTrayThrow(lay.TRAY_WORLD, lay.throwOrigin(who), faces, rng, Lay.DIE_SIZE, { spread: 1.4, sep: 1.6, aim: { u0: 0.22, u1: 0.78, v0: 0.42, v1: 0.58 } });
plan.dice.forEach((d, i) => {
const last = d.frames[d.frames.length - 1];
if (topFace(last.q) !== faces[i]) badFace++;
if (last.u < Lay.DIE_SIZE / 2 - 1 || last.u > lay.TRAY_WORLD.w - Lay.DIE_SIZE / 2 + 1 || last.v < 0 || last.v > lay.TRAY_WORLD.h) outside++;
});
if (Math.hypot(plan.dice[0].u - plan.dice[1].u, plan.dice[0].v - plan.dice[1].v) < Lay.DIE_SIZE * 0.9) close++;
}
ok('every throw lands on the rolled faces', badFace === 0, `${badFace}`);
ok('dice stay inside the roller\'s half', outside === 0, `${outside}`);
ok('dice rarely land on top of each other', close <= 2, `${close}`);
const rest4 = lay.diceRest(4);
ok('four resting dice fit inside the half, apart', rest4.every((r) => r.u > Lay.DIE_SIZE && r.u < lay.TRAY_WORLD.w - Lay.DIE_SIZE) && rest4[1].u - rest4[0].u > Lay.DIE_SIZE * 1.5);
}
// ── layout ───────────────────────────────────────────────────────────────────
section('Layout');
{
const F = Lay.hudFurniture();
const inScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= Lay.W && r.y + r.h <= Lay.H;
for (const [k, r] of Object.entries(F)) ok(`${k} on screen`, inScreen(r), JSON.stringify(r));
const keys = Object.keys(F);
const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
let ov = [];
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) if (overlap(F[keys[i]], F[keys[j]])) ov.push(`${keys[i]}×${keys[j]}`);
ok('HUD furniture never overlaps', ov.length === 0, ov.join(', '));
ok('opponent speech bubble stays clear of the case', !overlap(Lay.OPP_PARTS.bubble, Lay.CASE) && inScreen(Lay.OPP_PARTS.bubble));
for (const mirror of [false, true]) {
const lay = Lay.makeLayout(mirror);
const tag = mirror ? ' (mirrored)' : '';
const xs = [...Array(24).keys()].map((i) => lay.pointX(i));
ok(`24 distinct point columns${tag}`, new Set(xs.map((x, i) => `${x}|${i < 12}`)).size === 24);
// point 1 next to the tray, point 12 / 13 at the far side
ok(`your 1-point sits beside the tray${tag}`, Math.abs(lay.pointX(0) - lay.trayX) < Math.abs(lay.pointX(11) - lay.trayX));
let stackOk = true, zoneOk = true;
for (let idx = 0; idx < 24; idx++) {
const z = lay.pointZone(idx);
for (let s = 0; s < 15; s++) {
const p = lay.slotPos(idx, s);
const inField = p.y - Lay.CR >= Lay.FY - 1 && p.y + Lay.CR <= Lay.FY + Lay.FH + 1;
const inTri = idx < 12 ? p.y - Lay.CR >= Lay.FY + Lay.FH - Lay.PH - 2 : p.y + Lay.CR <= Lay.FY + Lay.PH + 2;
if (!inField || !inTri || Math.abs(p.x - lay.pointX(idx)) > 0.01) stackOk = false;
if (lay.hitTest(p.x, p.y) !== idx) zoneOk = false;
}
if (z.w !== Lay.PW) zoneOk = false;
}
ok(`15-checker pyramids stay inside their triangle${tag}`, stackOk);
ok(`every stack slot hit-tests to its own point${tag}`, zoneOk);
ok(`pyramid tiers: 5 + 4 + 3 + 2 + 1${tag}`, lay.stackSlot(4).tier === 0 && lay.stackSlot(5).tier === 1 && lay.stackSlot(14).tier === 4);
const off = [...Array(15).keys()].map((s) => lay.offPos('white', s));
const offB = [...Array(15).keys()].map((s) => lay.offPos('black', s));
ok(`15 borne-off checkers fit in each half of the tray${tag}`, off.every((p) => p.y > Lay.MID_Y + 15 && p.y < Lay.FY + Lay.FH) && offB.every((p) => p.y < Lay.MID_Y - 15 && p.y > Lay.FY));
ok(`tray hit-test${tag}`, lay.hitTest(off[3].x, off[3].y) === 'off' && lay.hitTest(offB[3].x, offB[3].y) === 'off');
const bar = [...Array(6).keys()].map((s) => lay.barPos('white', s, 6));
const cubeW = lay.cubePos('white'), cubeC = lay.cubePos(null);
ok(`bar checkers clear the cube${tag}`, bar.every((p) => Math.abs(p.y - cubeW.y) >= Lay.CR + 32 && Math.abs(p.y - cubeC.y) >= Lay.CR + 32));
ok(`bar hit-test${tag}`, lay.hitTest(bar[0].x, bar[0].y) === 'bar');
ok(`throw origins inside the case span${tag}`, ['white', 'black'].every((w) => { const o = lay.throwOrigin(w); return o.u > 0 && o.u < lay.TRAY_WORLD.w; }));
}
const a = Lay.makeLayout(false), b = Lay.makeLayout(true);
ok('mirroring is a reflection about the case centre', [...Array(24).keys()].every((i) => Math.abs(a.pointX(i) + b.pointX(i) - 2 * Lay.CASE_CX) < 0.01) && Math.abs(a.trayX + b.trayX - 2 * Lay.CASE_CX) < 0.01);
}
// ── checker registry ─────────────────────────────────────────────────────────
section('Checker registry');
{
const img = () => ({ setDepth() { return this; }, setAlpha() { return this; }, setTexture() { return this; }, setPosition() { return this; }, setScale() { return this; }, setRotation() { return this; } });
const scene = { add: { image: () => img() }, tweens: { add() {} } };
const cs = new CheckerSet(scene, Lay.makeLayout(false), 10).build();
let s = L.openingWith(L.createInitialState(), 6, 5);
cs.sync(s);
const where = () => cs.items.map((it) => `${it.key}#${it.slot}`);
const ok15 = () => ['white', 'black'].every((c) => [...cs.lists[c].values()].reduce((a, l) => a + l.length, 0) === 15);
ok('initial assignment: 15 a side', ok15());
const rng = mulberry32(9);
let stable = true, conserved = true;
for (let t = 0; t < 400 && s.phase !== 'game_over'; t++) {
if (s.phase === 'roll') s = L.rollDice(s, rng);
const moves = L.getValidMoves(s);
if (!moves.length) { s = L.endTurn(s); continue; }
const m = moves[Math.floor(rng() * moves.length)];
const mover = cs.topOf(s.currentPlayer, m.from);
const victim = m.hit ? cs.topOf(L.other(s.currentPlayer), m.to) : null;
const before = where();
s = L.applyMove(s, m);
cs.sync(s);
const after = where();
const changed = after.map((w, i) => (w !== before[i] ? i : -1)).filter((i) => i >= 0);
const allowed = new Set([mover?.id, victim?.id]);
if (!changed.every((i) => allowed.has(i)) || (mover && cs.items[mover.id].key === `${before[mover.id].split('#')[0]}` && m.from !== m.to)) stable = false;
if (!ok15()) conserved = false;
if (L.turnDone(s) && s.phase !== 'game_over') s = L.endTurn(s);
}
ok('a move relocates only the moving checker (and a hit victim)', stable);
ok('registry conserves 15 a side', conserved);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);