370 lines
18 KiB
JavaScript
370 lines
18 KiB
JavaScript
#!/usr/bin/env node
|
|
// verifyCatan.js — headless checks for Settlers of Catan:
|
|
// • rules: piece limits (15/5/4 + ships), Road Building capped by supply,
|
|
// the official bank-shortage rule, stats bookkeeping
|
|
// • all-AI soak (base 3p/4p + every Seafarers scenario): games end (base),
|
|
// limits never exceeded, 95 resource cards conserved, no stalls
|
|
// • 3D dice tray throws: every face pair lands on the rolled faces, inside the
|
|
// tray, separated
|
|
// • screen layout: furniture on screen, no overlaps, board hull clear of HUD
|
|
// Usage: node tools/verifyCatan.js [--quick]
|
|
|
|
import * as L from '../src/games/catan/CatanLogic.js';
|
|
import * as AI from '../src/games/catan/CatanAI.js';
|
|
import { RESOURCE_TYPES, COSTS } from '../src/games/catan/CatanBoard.js';
|
|
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
|
|
import { planTrayThrow, topFace, restingQ } from '../src/ui/dice/Dice3D.js';
|
|
import {
|
|
TRAY_WORLD, TRAY_FELT, DIE_SIZE, TOTAL_CHIP, trayGround, throwOrigin, hudFurniture, onScreen, rectsOverlap,
|
|
boardFrame, RAIL, stackLayers, stackTop, caddySlot, CADDY, CADDY_CARD, handPilePos, HAND, HAND_CARD, devCardPos, DEV,
|
|
} from '../src/games/catan/CatanLayout.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}`);
|
|
|
|
// Deterministic Math.random for reproducible soaks.
|
|
function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; }
|
|
|
|
const total = (res) => RESOURCE_TYPES.reduce((t, r) => t + res[r], 0);
|
|
function cardsInPlay(s) {
|
|
return RESOURCE_TYPES.reduce((t, r) => t + s.bank[r], 0) + s.players.reduce((t, p) => t + total(p.resources), 0);
|
|
}
|
|
|
|
// ── An all-AI game driver mirroring CatanGame.advance() ──────────────────────
|
|
function playGame({ players = 4, expansion = 'base', scenario = null, maxTurns = 400 } = {}) {
|
|
let s = L.createInitialState(players, { tilePlacement: 'random', expansion, scenario });
|
|
L.setPlayerNames(s, Array.from({ length: players }, (_, i) => `P${i}`));
|
|
const problems = [];
|
|
let turns = 0, guard = 0;
|
|
const check = () => {
|
|
if (cardsInPlay(s) !== 95) problems.push(`cards ${cardsInPlay(s)} != 95`);
|
|
for (const p of s.players) {
|
|
const left = L.piecesLeft(s, p.seat);
|
|
for (const k of ['road', 'settlement', 'city', 'ship']) if (left[k] < 0) problems.push(`seat ${p.seat} ${k} over limit`);
|
|
for (const r of RESOURCE_TYPES) if (p.resources[r] < 0) problems.push(`seat ${p.seat} negative ${r}`);
|
|
}
|
|
for (const r of RESOURCE_TYPES) if (s.bank[r] < 0) problems.push(`bank negative ${r}`);
|
|
};
|
|
while (s.phase !== 'gameOver' && turns < maxTurns && guard++ < 200000) {
|
|
const seat = s.currentPlayer;
|
|
if (s.phase === 'setup') {
|
|
s = s.setup.placing === 'settlement'
|
|
? L.placeSetupSettlement(s, seat, AI.chooseSetupSettlement(s, seat))
|
|
: L.placeSetupRoad(s, seat, AI.chooseSetupRoad(s, seat));
|
|
} else if (s.phase === 'rollPhase') {
|
|
if (AI.choosePreRoll(s, seat)) {
|
|
s = L.playKnight(s, seat);
|
|
if (s.phase === 'moveRobber') { const m = AI.chooseRobberMove(s, seat); s = L.moveRobber(s, m.hexId, m.targetSeat); }
|
|
}
|
|
if (s.phase === 'rollPhase') s = L.rollDice(s);
|
|
} else if (s.phase === 'goldPick') {
|
|
for (const e of [...s.goldPickQueue]) s = L.resolveGoldPick(s, e.seat, AI.chooseGoldPick(s, e.seat, e.amount));
|
|
} else if (s.phase === 'discard') {
|
|
for (const d of [...s.discardQueue]) s = L.applyDiscard(s, d, AI.chooseDiscard(s, d));
|
|
} else if (s.phase === 'moveRobber') {
|
|
const m = AI.chooseRobberMove(s, seat);
|
|
s = L.moveRobber(s, m.hexId, m.targetSeat);
|
|
} else if (s.phase === 'action') {
|
|
let steps = 0;
|
|
while (s.phase === 'action' && steps++ < 60) {
|
|
const a = AI.chooseAction(s, seat);
|
|
if (a.type === 'endTurn') { s = L.endTurn(s); break; }
|
|
const before = JSON.stringify(s.players[seat]) + s.phase;
|
|
switch (a.type) {
|
|
case 'buildCity': s = L.buildCity(s, seat, a.nodeId); break;
|
|
case 'buildSettlement': s = L.buildSettlement(s, seat, a.nodeId); break;
|
|
case 'buildRoad': s = L.buildRoad(s, seat, a.edgeId); break;
|
|
case 'buyDev': s = L.buyDevCard(s, seat); break;
|
|
case 'bankTrade': s = L.tradeWithBank(s, seat, a.give, a.get); break;
|
|
case 'playDev':
|
|
if (a.card === 'knight') s = L.playKnight(s, seat);
|
|
else if (a.card === 'roadBuilding') s = L.playRoadBuilding(s, seat);
|
|
else if (a.card === 'yearOfPlenty') s = L.playYearOfPlenty(s, seat, a.r1, a.r2);
|
|
else if (a.card === 'monopoly') s = L.playMonopoly(s, seat, a.resource);
|
|
break;
|
|
default: break;
|
|
}
|
|
if (s.phase === 'moveRobber') { const m = AI.chooseRobberMove(s, seat); s = L.moveRobber(s, m.hexId, m.targetSeat); }
|
|
check();
|
|
if (s.phase === 'gameOver') break;
|
|
const after = JSON.stringify(s.players[seat]) + s.phase;
|
|
if (before === after && a.type !== 'playDev') { s = L.endTurn(s); break; }
|
|
}
|
|
if (s.phase === 'action') s = L.endTurn(s);
|
|
turns++;
|
|
}
|
|
check();
|
|
if (problems.length) break;
|
|
}
|
|
return { s, turns, problems, ended: s.phase === 'gameOver' };
|
|
}
|
|
|
|
// ── A tiny hand-built state for rule tests ───────────────────────────────────
|
|
function freshAction(players = 3) {
|
|
seedRandom(7);
|
|
let s = L.createInitialState(players, { tilePlacement: 'standard' });
|
|
// run setup with the AI
|
|
while (s.phase === 'setup') {
|
|
const seat = s.currentPlayer;
|
|
s = s.setup.placing === 'settlement'
|
|
? L.placeSetupSettlement(s, seat, AI.chooseSetupSettlement(s, seat))
|
|
: L.placeSetupRoad(s, seat, AI.chooseSetupRoad(s, seat));
|
|
}
|
|
s.phase = 'action';
|
|
s.currentPlayer = 0;
|
|
return s;
|
|
}
|
|
function give(s, seat, res) {
|
|
for (const [r, n] of Object.entries(res)) { s.players[seat].resources[r] += n; s.bank[r] -= n; }
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
section('Rules — piece limits');
|
|
{
|
|
const s0 = freshAction();
|
|
ok('fresh supply', JSON.stringify(L.piecesLeft(s0, 0)) === JSON.stringify({ road: 13, settlement: 3, city: 4, ship: 15 }),
|
|
JSON.stringify(L.piecesLeft(s0, 0)));
|
|
|
|
// 15 roads → no legal road edges
|
|
const s1 = L.cloneState(s0);
|
|
const extra = L.legalRoadEdges(s1, 0, false);
|
|
ok('has legal roads before limit', extra.length > 0);
|
|
s1.players[0].roads = Array.from({ length: 15 }, (_, i) => i);
|
|
ok('15 roads → no legal road edges', L.legalRoadEdges(s1, 0, false).length === 0);
|
|
give(s1, 0, COSTS.road);
|
|
const s1b = L.buildRoad(s1, 0, extra[0]);
|
|
ok('buildRoad refused at limit', s1b.players[0].roads.length === 15);
|
|
|
|
// 5 settlements → no legal settlement nodes; city frees one
|
|
const s2 = L.cloneState(s0);
|
|
const p = s2.players[0];
|
|
while (p.settlements.length < 5) p.settlements.push(1000 + p.settlements.length); // fake ids beyond geometry
|
|
ok('5 settlements → none legal', L.legalSettlementNodes(s2, 0, false).length === 0);
|
|
const s3 = L.cloneState(s0);
|
|
const nid = s3.players[0].settlements[0];
|
|
give(s3, 0, COSTS.city);
|
|
const s4 = L.buildCity(s3, 0, nid);
|
|
ok('city upgrade returns a settlement to supply', L.piecesLeft(s4, 0).settlement === L.piecesLeft(s3, 0).settlement + 1
|
|
&& L.piecesLeft(s4, 0).city === 3);
|
|
|
|
// 4 cities → no legal cities
|
|
const s5 = L.cloneState(s0);
|
|
s5.players[0].cities = [2001, 2002, 2003, 2004];
|
|
ok('4 cities → no legal city nodes', L.legalCityNodes(s5, 0).length === 0);
|
|
give(s5, 0, COSTS.city);
|
|
const s6 = L.buildCity(s5, 0, s5.players[0].settlements[0]);
|
|
ok('buildCity refused at limit', s6.players[0].cities.length === 4);
|
|
|
|
// Road Building capped by supply
|
|
const s7 = L.cloneState(s0);
|
|
s7.players[0].roads = Array.from({ length: 14 }, (_, i) => i);
|
|
s7.players[0].devCards = ['roadBuilding'];
|
|
const s8 = L.playRoadBuilding(s7, 0);
|
|
ok('Road Building with 1 road left grants 1', s8.freeRoads === 1, `freeRoads=${s8.freeRoads}`);
|
|
const s9 = L.cloneState(s0);
|
|
s9.players[0].devCards = ['roadBuilding'];
|
|
ok('Road Building normally grants 2', L.playRoadBuilding(s9, 0).freeRoads === 2);
|
|
}
|
|
|
|
section('Rules — bank shortage');
|
|
{
|
|
// Find a number whose hexes produce for 2+ seats of one resource.
|
|
const base = freshAction(4);
|
|
let tested2 = false, tested1 = false, testedOk = false;
|
|
for (let n = 2; n <= 12 && !(tested2 && tested1 && testedOk); n++) {
|
|
if (n === 7) continue;
|
|
const pr = L.productionFor(base, n);
|
|
for (const [res, bySeat] of Object.entries(pr.owed)) {
|
|
const seats = Object.keys(bySeat);
|
|
const need = seats.reduce((t, k) => t + bySeat[k], 0);
|
|
// plenty in the bank → paid in full
|
|
if (!testedOk) {
|
|
const s = L.cloneState(base); s.phase = 'rollPhase';
|
|
const pay = L.productionFor(s, n).pay[res];
|
|
ok(`full bank pays everyone (${res} on ${n})`, JSON.stringify(pay) === JSON.stringify(bySeat));
|
|
testedOk = true;
|
|
}
|
|
if (seats.length >= 2 && !tested2) {
|
|
const s = L.cloneState(base);
|
|
const take = s.bank[res] - (need - 1); // leave one short
|
|
s.bank[res] -= take; s.players[0].resources[res] += take;
|
|
const pr2 = L.productionFor(s, n);
|
|
ok(`2+ claimants, bank short → nobody gets ${res}`, !pr2.pay[res] && pr2.shortages.some((x) => x.res === res && !x.single));
|
|
tested2 = true;
|
|
}
|
|
if (seats.length === 1 && need >= 2 && !tested1) {
|
|
const s = L.cloneState(base);
|
|
const take = s.bank[res] - 1; // bank holds exactly 1
|
|
s.bank[res] -= take; s.players[(Number(seats[0]) + 1) % 4].resources[res] += take;
|
|
const pr2 = L.productionFor(s, n);
|
|
ok(`single claimant takes what's left of ${res}`, pr2.pay[res]?.[seats[0]] === 1);
|
|
tested1 = true;
|
|
}
|
|
}
|
|
}
|
|
ok('found a 2-claimant case', tested2);
|
|
// single-claimant with need>=2 needs a city; force one if the board didn't offer it
|
|
if (!tested1) {
|
|
const s = L.cloneState(base);
|
|
const seat = 0;
|
|
const nid = s.players[seat].settlements[0];
|
|
s.players[seat].settlements = s.players[seat].settlements.filter((x) => x !== nid);
|
|
s.players[seat].cities.push(nid);
|
|
for (let n = 2; n <= 12 && !tested1; n++) {
|
|
if (n === 7) continue;
|
|
const pr = L.productionFor(s, n);
|
|
for (const [res, bySeat] of Object.entries(pr.owed)) {
|
|
const seats = Object.keys(bySeat);
|
|
if (seats.length !== 1 || bySeat[seats[0]] < 2) continue;
|
|
const t = L.cloneState(s);
|
|
const take = t.bank[res] - 1;
|
|
t.bank[res] -= take; t.players[(Number(seats[0]) + 1) % 4].resources[res] += take;
|
|
ok(`single claimant (city) takes the last ${res}`, L.productionFor(t, n).pay[res]?.[seats[0]] === 1);
|
|
tested1 = true; break;
|
|
}
|
|
}
|
|
}
|
|
ok('found a single-claimant case', tested1);
|
|
}
|
|
|
|
section('Rules — stats');
|
|
{
|
|
seedRandom(11);
|
|
const r = playGame({ players: 4 });
|
|
const st = r.s.stats;
|
|
const rolled = st.rolls.reduce((a, b) => a + b, 0);
|
|
ok('stats exist', !!st);
|
|
ok('rolls only on 2..12', st.rolls[0] === 0 && st.rolls[1] === 0);
|
|
ok('rolls counted', rolled > 10, `rolled ${rolled}`);
|
|
const produced = st.produced.reduce((t, x) => t + total(x), 0);
|
|
ok('production recorded', produced > 0);
|
|
ok('steals balance', st.stolen.reduce((a, b) => a + b, 0) === st.lostToSteal.reduce((a, b) => a + b, 0));
|
|
}
|
|
|
|
section('AI soak');
|
|
{
|
|
const N = QUICK ? 30 : 200;
|
|
for (const players of [3, 4]) {
|
|
let ended = 0, turnSum = 0, problems = 0, maxTurns = 0;
|
|
for (let g = 0; g < N; g++) {
|
|
seedRandom(1000 + g * 7 + players);
|
|
const r = playGame({ players });
|
|
if (r.problems.length) { problems++; if (problems <= 3) console.error(` game ${g}: ${r.problems[0]}`); }
|
|
if (r.ended) { ended++; turnSum += r.turns; maxTurns = Math.max(maxTurns, r.turns); }
|
|
}
|
|
ok(`base ${players}p: all ${N} games end`, ended === N, `${ended}/${N}`);
|
|
ok(`base ${players}p: no invariant breaks`, problems === 0, `${problems} games`);
|
|
console.log(` base ${players}p: ${ended}/${N} ended, avg ${(turnSum / Math.max(1, ended)).toFixed(1)} turns, max ${maxTurns}`);
|
|
}
|
|
const M = QUICK ? 6 : 30;
|
|
for (const scenario of ['new-shores', 'four-islands', 'oceania', 'fog-island']) {
|
|
let ended = 0, problems = 0, crashes = 0;
|
|
for (let g = 0; g < M; g++) {
|
|
seedRandom(5000 + g);
|
|
try {
|
|
const r = playGame({ players: 4, expansion: 'seafarers', scenario, maxTurns: 300 });
|
|
if (r.problems.length) { problems++; if (problems <= 2) console.error(` ${scenario} ${g}: ${r.problems[0]}`); }
|
|
if (r.ended) ended++;
|
|
} catch (e) { crashes++; if (crashes <= 2) console.error(` ${scenario} ${g}: ${e.stack}`); }
|
|
}
|
|
ok(`seafarers ${scenario}: no crashes`, crashes === 0, `${crashes}`);
|
|
ok(`seafarers ${scenario}: no invariant breaks`, problems === 0, `${problems}`);
|
|
console.log(` seafarers ${scenario}: ${ended}/${M} ended within 300 turns`);
|
|
}
|
|
}
|
|
|
|
section('Dice tray throws');
|
|
{
|
|
const seeds = QUICK ? 3 : 12;
|
|
let wrong = 0, outside = 0, close = 0, n = 0, maxDur = 0;
|
|
const half = DIE_SIZE / 2;
|
|
for (const human of [true, false]) {
|
|
for (let a = 1; a <= 6; a++) for (let b = 1; b <= 6; b++) for (let k = 0; k < seeds; k++) {
|
|
const rng = mulberry32(a * 100 + b * 10 + k + (human ? 0 : 5000));
|
|
const plan = planTrayThrow(TRAY_WORLD, throwOrigin(human), [a, b], rng, DIE_SIZE);
|
|
n++;
|
|
maxDur = Math.max(maxDur, plan.duration);
|
|
const ends = plan.dice.map((d) => d.frames[d.frames.length - 1]);
|
|
if (topFace(ends[0].q) !== a || topFace(ends[1].q) !== b) wrong++;
|
|
for (const e of ends) {
|
|
if (e.u < half - 0.5 || e.u > TRAY_WORLD.w - half + 0.5 || e.v < half - 0.5 || e.v > TRAY_WORLD.h - half + 0.5) outside++;
|
|
}
|
|
if (Math.hypot(ends[0].u - ends[1].u, ends[0].v - ends[1].v) < DIE_SIZE * 1.15) close++;
|
|
}
|
|
}
|
|
ok('every throw lands on the rolled faces', wrong === 0, `${wrong}/${n}`);
|
|
ok('both dice rest inside the tray', outside === 0, `${outside}`);
|
|
ok('dice rest apart (no overlap)', close === 0, `${close}/${n}`);
|
|
ok('throws finish within 3 s', maxDur <= 3.2, maxDur.toFixed(2));
|
|
// the resting dice project onto the felt
|
|
const p0 = trayGround(0, 0), p1 = trayGround(TRAY_WORLD.w, TRAY_WORLD.h);
|
|
ok('tray projection maps the world onto the felt', Math.abs(p0.x - TRAY_FELT.x) < 1e-6 && Math.abs(p1.y - (TRAY_FELT.y + TRAY_FELT.h)) < 1e-6);
|
|
for (let f = 1; f <= 6; f++) ok(`restingQ shows ${f}`, topFace(restingQ(f, f * 0.7)) === f);
|
|
}
|
|
|
|
section('Screen layout');
|
|
{
|
|
for (const opponents of [2, 3]) for (const buttons of [8, 9]) {
|
|
const furn = hudFurniture({ opponents, buttons });
|
|
for (const r of furn) ok(`${r.name} on screen (${opponents} opp, ${buttons} btn)`, onScreen(r), JSON.stringify(r));
|
|
for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) {
|
|
ok(`${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i], furn[j]));
|
|
}
|
|
}
|
|
for (const [expansion, scenario] of [['base', null], ['seafarers', 'new-shores'], ['seafarers', 'four-islands'], ['seafarers', 'oceania'], ['seafarers', 'fog-island']]) {
|
|
seedRandom(3);
|
|
const s = L.createInitialState(4, { expansion, scenario });
|
|
const fr = boardFrame(L.geoFor(s));
|
|
ok(`${scenario ?? 'base'}: frame on screen`, onScreen(fr.bounds), JSON.stringify(fr.bounds));
|
|
for (const r of hudFurniture({ opponents: 3, buttons: expansion === 'base' ? 8 : 9 })) {
|
|
ok(`${scenario ?? 'base'}: frame clear of ${r.name}`, !rectsOverlap(fr.bounds, r), JSON.stringify(fr.bounds));
|
|
}
|
|
ok(`${scenario ?? 'base'}: frame clear of the rail`, fr.bounds.y + fr.bounds.h <= RAIL.y);
|
|
// every port sits on the sea band (outside the hull, inside the frame)
|
|
for (const port of s.ports) {
|
|
const out = 30;
|
|
const px = port.x + Math.cos(port.angle) * out, py = port.y + Math.sin(port.angle) * out;
|
|
ok(`${scenario ?? 'base'}: port inside frame`, px > fr.bounds.x && px < fr.bounds.x + fr.bounds.w && py > fr.bounds.y && py < fr.bounds.y + fr.bounds.h);
|
|
}
|
|
}
|
|
// the rolled-total chip sits above the felt, clear of the buttons and caddy
|
|
const chip = { x: TOTAL_CHIP.x - TOTAL_CHIP.r, y: TOTAL_CHIP.y - TOTAL_CHIP.r, w: TOTAL_CHIP.r * 2, h: TOTAL_CHIP.r * 2 };
|
|
ok('total chip on screen', onScreen(chip));
|
|
for (const r of hudFurniture({ opponents: 3, buttons: 9 }).filter((f) => f.name !== 'tray')) {
|
|
ok(`total chip clear of ${r.name}`, !rectsOverlap(chip, r), JSON.stringify(r));
|
|
}
|
|
ok('total chip centre is above the felt', TOTAL_CHIP.y < TRAY_FELT.y);
|
|
|
|
// stacks: monotonic and capped
|
|
let mono = true;
|
|
for (let n = 1; n <= 25; n++) if (stackLayers(n) < stackLayers(n - 1)) mono = false;
|
|
ok('stack layers grow with the count', mono);
|
|
ok('stack layers are capped', stackLayers(25) <= 12 && stackLayers(19) >= 10);
|
|
ok('an empty stack has no layers', stackLayers(0) === 0);
|
|
for (let i = 0; i < 6; i++) {
|
|
const sl = caddySlot(i);
|
|
const full = stackTop(i, i === 5 ? 25 : 19), bottom = caddySlot(i).card;
|
|
ok(`caddy slot ${i} inside the caddy`, sl.x >= CADDY.x && sl.y + sl.h <= CADDY.y + CADDY.h && sl.x + sl.w <= CADDY.x + CADDY.w);
|
|
ok(`caddy slot ${i}: a full stack stays in its well`, full.y - CADDY_CARD.h / 2 >= sl.y && bottom.y + CADDY_CARD.h / 2 <= sl.y + sl.h
|
|
&& full.x + CADDY_CARD.w / 2 <= sl.x + sl.w && bottom.x - CADDY_CARD.w / 2 >= sl.x);
|
|
if (i < 5) ok(`caddy slot ${i} clear of slot ${i + 1}`, sl.y + sl.h < caddySlot(i + 1).y);
|
|
}
|
|
// hand piles stay in the hand zone for 1..5 groups
|
|
for (let n = 1; n <= 5; n++) {
|
|
const last = handPilePos(n - 1, n);
|
|
ok(`hand: ${n} piles fit`, last.x + HAND_CARD.w / 2 + 14 <= HAND.x + HAND.w && handPilePos(0, n).x - HAND_CARD.w / 2 >= HAND.x);
|
|
}
|
|
for (let n = 1; n <= 9; n++) {
|
|
const last = devCardPos(n - 1, n);
|
|
ok(`dev: ${n} cards fit`, last.x + HAND_CARD.w / 2 <= DEV.x + DEV.w + 0.5);
|
|
}
|
|
}
|
|
|
|
console.log(`\n${pass} passed, ${fail} failed`);
|
|
process.exit(fail ? 1 : 0);
|