fertig-classic-games/tools/verifyDominion.js

241 lines
13 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
// verifyDominion.js — headless checks for the Dominion "Steward's Hall" table:
// • screen layout for every variant (2–4 players × Base/Prosperity × every
// preset + Random): furniture on screen, no overlaps, children inside their
// parents, one treasury tile per basic pile, kingdom slots that don't touch,
// in-play / hand / opponent-fan rows that stay inside their furniture
// • card art: every card's frame exists in its sheet (PNG header sizes)
// • scoring ceremony maths (reckoning) equals the engine's finalScores, and
// seatStats agrees with the log, across an all-AI soak
// • Throne Room / King's Court tuck detection only tucks real doubled cards
// • engine fingerprint: the AI-vs-AI games are byte-for-byte what they were
// before the table overhaul (the overhaul must not touch the rules)
// Usage: node tools/verifyDominion.js [--quick]
import fs from 'node:fs';
import * as Lg from '../src/games/dominion/DominionLogic.js';
import * as AI from '../src/games/dominion/DominionAI.js';
import { CARDS, getCard, isType } from '../src/games/dominion/DominionCards.js';
import { registerExpansionCards } from '../src/games/dominion/expansions/index.js';
import {
computeLayout, splitBasics, furniture, furnitureChildren, inPlayPositions, handPositions,
oppHandPositions, rectsOverlap, inside, onScreen, centred, MAT, HAND_ZONE, PLAY, HAND, MINI,
} from '../src/games/dominion/DominionLayout.js';
import { reckoning, seatStats, tuckInfo } from '../src/games/dominion/DominionScoring.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 VARIANTS = [
['base', ['standard', 'size-distortion', 'deck-top', 'silver-gold', 'helpful-actions', 'random']],
['prosperity', ['beginners', 'friendly-interactive', 'bigger-treasures', 'the-king', 'random']],
];
function layoutFor(state) {
const basicIds = Object.keys(state.supply).filter((id) => !state.kingdom.includes(id));
basicIds.sort((a, b) => getCard(a).cost - getCard(b).cost);
return {
L: computeLayout({ playerCount: state.playerCount, basics: splitBasics(basicIds, (id) => getCard(id).types), kingdomCount: state.kingdom.length }),
basicIds,
};
}
// ── Layout ──────────────────────────────────────────────────────────────────
section('Layout');
{
const seen = new Set();
for (const [exp, modes] of VARIANTS) {
for (const mode of modes) {
for (let pc = 2; pc <= 4; pc++) {
for (let seed = 1; seed <= (mode === 'random' ? 6 : 1); seed++) {
const s = Lg.createInitialState({ seed: seed * 101 + pc, playerCount: pc, deckMode: mode, expansion: exp });
const { L, basicIds } = layoutFor(s);
const tag = `${exp}/${mode}/${pc}p`;
const furn = furniture(L);
for (const [name, r] of furn) ok(`${tag} ${name} on screen`, onScreen(r), JSON.stringify(r));
for (let i = 0; i < furn.length; i++) {
for (let j = i + 1; j < furn.length; j++) {
const [a, ra] = furn[i], [b, rb] = furn[j];
ok(`${tag} ${a} ∩ ${b}`, !rectsOverlap(ra, rb), `${JSON.stringify(ra)} vs ${JSON.stringify(rb)}`);
}
}
for (const [name, r, parent] of furnitureChildren(L)) ok(`${tag} ${name} inside parent`, inside(r, parent, 0.5), `${JSON.stringify(r)} in ${JSON.stringify(parent)}`);
ok(`${tag} one tile per basic pile`, L.tiles.length === basicIds.length && basicIds.every((id) => L.tiles.some((t) => t.id === id)));
ok(`${tag} tiles readable`, L.tileSize.h >= 70, `h=${L.tileSize.h}`);
ok(`${tag} kingdom slot per card`, L.kingdom.length === s.kingdom.length);
for (let i = 0; i < L.tiles.length; i++) for (let j = i + 1; j < L.tiles.length; j++) {
const a = L.tiles[i], b = L.tiles[j];
ok(`${tag} tiles ${a.id}/${b.id} apart`, !rectsOverlap(centred(a.x, a.y + 9, a.w, a.h + 28), centred(b.x, b.y + 9, b.w, b.h + 28)));
}
for (let i = 0; i < L.kingdom.length; i++) for (let j = i + 1; j < L.kingdom.length; j++) {
const a = L.kingdom[i], b = L.kingdom[j];
ok(`${tag} kingdom ${i}/${j} apart`, !rectsOverlap(centred(a.x, a.y + 10, L.kSize.w, L.kSize.h + 40), centred(b.x, b.y + 10, L.kSize.w, L.kSize.h + 40)));
}
ok(`${tag} kingdom in cost order`, s.kingdom.every((id, i) => i === 0 || getCard(s.kingdom[i - 1]).cost <= getCard(id).cost));
ok(`${tag} plates for every opponent`, L.plates.length === pc - 1);
const sig = `${pc}-${L.tiles.length}`;
if (!seen.has(sig)) {
seen.add(sig);
for (const p of L.plates) {
for (let n = 0; n <= 14; n++) {
const { xs } = oppHandPositions(p, n);
ok(`${tag} plate ${p.seat} fan of ${n} inside`, xs.every((x) => x - MINI.w / 2 >= p.rect.x0 && x + MINI.w / 2 <= p.rect.x1));
}
}
}
}
}
}
}
// Rows that grow with the game.
for (let n = 1; n <= 30; n++) {
const pos = inPlayPositions(n, []);
ok(`in-play ${n} inside mat`, pos.every((p) => p.x - PLAY.w / 2 >= MAT.x0 && p.x + PLAY.w / 2 <= MAT.x1 && p.y + PLAY.h / 2 <= MAT.y1));
const tucked = Array.from({ length: n }, (_, i) => i % 3 === 2);
const tp = inPlayPositions(n, tucked);
ok(`in-play ${n} with tucks inside mat`, tp.every((p) => p.x - PLAY.w / 2 >= MAT.x0 - 0.5 && p.x + PLAY.w / 2 <= MAT.x1 + 0.5 && p.y + PLAY.h / 2 <= MAT.y1));
ok(`in-play ${n} tucked follow parent`, tp.every((p, i) => !tucked[i] || p.x > tp[i - 1].x));
}
for (let n = 1; n <= 20; n++) {
const { xs } = handPositions(n);
ok(`hand ${n} inside zone`, xs.every((x) => x - HAND.w / 2 >= HAND_ZONE.x0 && x + HAND.w / 2 <= HAND_ZONE.x1));
ok(`hand ${n} ordered`, xs.every((x, i) => i === 0 || x > xs[i - 1]));
}
}
// ── Card art ────────────────────────────────────────────────────────────────
section('Card art');
{
registerExpansionCards();
const pngSize = (f) => { const b = fs.readFileSync(f); return { w: b.readUInt32BE(16), h: b.readUInt32BE(20) }; };
const sheets = {
'dominion-cards': pngSize('assets/images/dominioncards.png'),
'dominion-prosperity': pngSize('assets/images/dominion-prosperity.png'),
};
for (const def of Object.values(CARDS)) {
const sh = sheets[def.sheet];
ok(`${def.id} sheet known`, !!sh, def.sheet);
if (!sh) continue;
const frames = Math.floor(sh.w / 270) * Math.floor(sh.h / 390);
ok(`${def.id} frame ${def.frame} in sheet`, def.frame >= 0 && def.frame < frames, `${frames} frames`);
}
const used = new Map();
for (const def of Object.values(CARDS)) {
const k = `${def.sheet}#${def.frame}`;
ok(`${def.id} frame not shared`, !used.has(k), used.get(k));
used.set(k, def.id);
}
}
// ── Soak: scoring ceremony + tucks + engine fingerprint ────────────────────
section('Soak');
function playGame(seed, pc, exp, mode, onStep) {
let s = Lg.createInitialState({ seed, playerCount: pc, deckMode: mode, expansion: exp });
let steps = 0;
while (!Lg.isGameOver(s) && steps < 20000) {
steps++;
if (s.pending) s = Lg.resolvePending(s, AI.resolvePending(s, 3));
else {
const seat = s.turn;
if (s.phase === 'action') { const iid = AI.chooseAction(s, seat); s = iid != null ? Lg.playAction(s, iid) : Lg.endActionPhase(s); }
else if (s.players[seat].hand.some((c) => isType(c.id, 'treasure'))) s = Lg.playAllTreasures(s);
else { const b = AI.chooseBuy(s, seat, 3); s = b ? Lg.buyCard(s, b) : Lg.endTurn(s); }
}
onStep?.(s);
}
return s;
}
{
const out = [];
let tuckSeen = 0;
for (const [exp, modes] of [['base', ['standard', 'size-distortion', 'random']], ['prosperity', ['beginners', 'the-king', 'random']]]) {
for (const mode of modes) {
for (let pc = 2; pc <= 4; pc++) {
for (let seed = 1; seed <= 4; seed++) {
const s = playGame(seed * 7919 + pc, pc, exp, mode, (st) => {
const seat = st.turn;
const cards = st.players[seat].inPlay;
const { tucked, mult } = tuckInfo(st.log, seat, cards);
for (let i = 0; i < cards.length; i++) {
if (!tucked[i]) continue;
tuckSeen++;
const parent = cards[i - 1]?.id;
if (!(parent === 'throneroom' || parent === 'kingscourt') || !isType(cards[i].id, 'action') || mult[i] !== (parent === 'kingscourt' ? 3 : 2)) {
ok(`tuck ${exp}/${mode} under ${parent}`, false, cards.map((c) => c.id).join(','));
} else pass++;
}
});
out.push(Lg.finalScores(s).map((x) => x.vp).join(',') + '|' + s.turnsTaken.join(',') + '|' + s.log.length);
const scores = Lg.finalScores(s);
for (const sc of scores) {
const rk = reckoning(s, sc.seat);
const sum = rk.groups.reduce((a, g) => a + g.vp, 0) + rk.tokens;
ok(`${exp}/${mode}/${pc}p seed ${seed} seat ${sc.seat} reckoning = finalScores`, sum === sc.vp, `${sum} vs ${sc.vp}`);
ok('census adds up', rk.census.treasure + rk.census.action + rk.census.victory + rk.census.curse === rk.total);
const st = seatStats(s, sc.seat);
ok('bought = buy log events', st.bought === s.log.filter((e) => e.kind === 'buy' && e.seat === sc.seat).length);
ok('turns match', st.turns === s.turnsTaken[sc.seat]);
}
ok(`${exp}/${mode}/${pc}p seed ${seed} game finished`, Lg.isGameOver(s));
}
}
}
}
// The AI rarely buys Throne Room, so script the tuck cases directly.
const scripted = (exp, hand, steps) => {
let st = Lg.createInitialState({ seed: 5, playerCount: 2, deckMode: exp === 'base' ? 'size-distortion' : 'the-king', expansion: exp });
st.players[0].hand = hand.map((id, i) => ({ iid: 9000 + i, id }));
for (const step of steps) st = step(st);
return { st, ...tuckInfo(st.log, 0, st.players[0].inPlay) };
};
{
const { st, tucked, mult } = scripted('base', ['throneroom', 'smithy', 'copper'], [
(s) => Lg.playAction(s, 9000), (s) => Lg.resolvePending(s, { iid: 9001 }),
]);
ok('Throne Room target tucked ×2', st.players[0].inPlay.map((c) => c.id).join() === 'throneroom,smithy' && tucked[1] && mult[1] === 2, JSON.stringify({ tucked, mult }));
}
{
const { st, tucked } = scripted('base', ['village', 'throneroom', 'smithy'], [
(s) => Lg.playAction(s, 9000), (s) => Lg.playAction(s, 9001), (s) => Lg.resolvePending(s, { iid: null }),
(s) => Lg.playAction(s, 9002),
]);
ok('skipped Throne Room tucks nothing', st.players[0].inPlay.some((c) => c.id === 'smithy') && !tucked.some(Boolean), JSON.stringify({ ids: st.players[0].inPlay.map((c) => c.id), tucked }));
}
{
const { st, tucked, mult } = scripted('prosperity', ['kingscourt', 'smithy', 'copper'], [
(s) => Lg.playAction(s, 9000), (s) => Lg.resolvePending(s, { iid: 9001 }),
]);
ok("King's Court target tucked ×3", st.players[0].inPlay.map((c) => c.id).join() === 'kingscourt,smithy' && tucked[1] && mult[1] === 3, JSON.stringify({ ids: st.players[0].inPlay.map((c) => c.id), tucked, mult }));
}
// Recorded from the engine + AI before the 2026-11-25 table overhaul.
// Base games must be byte-for-byte what they were before the overhaul (the
// AI's buy-restriction fix only touches Prosperity, whose games used to stall).
let hb = 0;
for (const ch of out.slice(0, 36).join(';')) hb = (Math.imul(hb, 31) + ch.charCodeAt(0)) >>> 0;
ok('base engine fingerprint unchanged (36 AI games)', hb === 2754080371, `hash ${hb}`);
ok('72 soak games recorded', out.length === 72, `${out.length}`);
}
// ── Larger random soak ──────────────────────────────────────────────────────
if (!QUICK) {
section('Random soak');
for (let g = 0; g < 120; g++) {
const exp = g % 2 ? 'prosperity' : 'base';
const pc = 2 + (g % 3);
const s = playGame(90000 + g, pc, exp, 'random');
ok(`random game ${g} finished`, Lg.isGameOver(s));
for (const sc of Lg.finalScores(s)) {
const rk = reckoning(s, sc.seat);
ok(`random game ${g} seat ${sc.seat} reckoning`, rk.groups.reduce((a, x) => a + x.vp, 0) + rk.tokens === sc.vp);
}
}
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);