#!/usr/bin/env node // verifySplendor.js — headless checks for Splendor: // • rules: takes, take-2 threshold, reserve (gold, limit, blind), buy (bonuses, // gold, refill, purchased cards), hand limit discard phase, noble visits incl. // the choice phase, end-of-round finish, ranking tiebreak, helper queries // • previewBuy / effectiveCost / affordState agree with applyAction // • all-AI soak (2–4 players, mixed skills): every game ends, tokens and the 90 // cards are conserved after every step, decision times stay small // • skill ladder: mirrored seats and seeds, 2 players // • screen layout: furniture on screen and apart, children inside parents // • art sheets: PNG header sizes match the frame maps // Usage: node tools/verifySplendor.js [--quick] import fs from 'node:fs'; import * as L from '../src/games/splendor/SplendorLogic.js'; import * as AI from '../src/games/splendor/SplendorAI.js'; import { GEMS, GOLD, CARDS, NOBLES, tokenSupplyFor, HAND_LIMIT, MAX_RESERVED, LOCATION, NOBLE_INFO, cardFrame, nobleFrame, deckBackFrame, } from '../src/games/splendor/SplendorData.js'; import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; import { computeLayout, furniture, onScreen, rectsOverlap, inside, ledgerParts, slotRect, deckRect, MARKET, BANK, bankCell, BANK_ORDER, GALLERY, DOCK, stackPos, MINI, RES, trackX, TRACK, W, H, } from '../src/games/splendor/SplendorLayout.js'; import { cameoPos } from '../src/games/splendor/SplendorHud.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}`); function seedRandom(seed) { const r = mulberry32(seed); Math.random = r; return r; } const ALL = [...GEMS, GOLD]; const tokensIn = (s) => { const t = {}; for (const c of ALL) t[c] = s.bank[c] + s.players.reduce((n, p) => n + p.tokens[c], 0); return t; }; const cardCount = (s) => { let n = 0; for (const t of [1, 2, 3]) n += s.decks[t].length + s.board[t].filter(Boolean).length; for (const p of s.players) n += p.reserved.length + p.cards.length; return n; }; // Put `p` at the current seat with the given tokens/bonuses (direct rule tests). function rig(s, { tokens = {}, bonuses = {}, seat = s.current } = {}) { const p = s.players[seat]; for (const c of ALL) { s.bank[c] += p.tokens[c]; p.tokens[c] = 0; } for (const [c, n] of Object.entries(tokens)) { p.tokens[c] = n; s.bank[c] -= n; } for (const [c, n] of Object.entries(bonuses)) p.bonuses[c] = n; return s; } const fresh = (pc = 2, seed = 11) => L.createInitialState({ playerCount: pc, seed }); // ── rules ───────────────────────────────────────────────────────────────────────────── section('Rules'); { ok('90 cards, 40/30/20', CARDS.length === 90 && [1, 2, 3].map((t) => CARDS.filter((c) => c.tier === t).length).join() === '40,30,20'); ok('15 location names, 10 noble names', LOCATION.length === 15 && NOBLE_INFO.length === 10); for (const pc of [2, 3, 4]) { const s = fresh(pc); ok(`${pc}p: supply`, GEMS.every((g) => s.bank[g] === tokenSupplyFor(pc)[g]) && s.bank.gold === 5); ok(`${pc}p: ${pc + 1} nobles, 4 cards a row`, s.nobles.length === pc + 1 && [1, 2, 3].every((t) => s.board[t].filter(Boolean).length === 4)); ok(`${pc}p: 90 cards`, cardCount(s) === 90); } // take3 let s = fresh(); const s1 = L.applyAction(s, { type: 'take3', colors: ['white', 'blue', 'green'] }); ok('take3 moves 3 tokens', s1.players[0].tokens.white === 1 && s1.bank.white === s.bank.white - 1 && s1.current === 1); ok('take3 rejects duplicates in disguise', L.applyAction(s, { type: 'take3', colors: ['red', 'red', 'red'] }).players[0].tokens.red === 1); // take2 threshold s = fresh(2); // 4 per colour ok('take2 legal at 4', L.isLegal(s, { type: 'take2', color: 'red' })); const s2 = L.applyAction(s, { type: 'take2', color: 'red' }); ok('take2 takes two', s2.players[0].tokens.red === 2 && s2.bank.red === 2); s2.current = 0; ok('take2 illegal below 4', !L.isLegal(s2, { type: 'take2', color: 'red' }) && L.applyAction(s2, { type: 'take2', color: 'red' }) === s2); // reserve s = fresh(); const card = s.board[1][0]; const r1 = L.applyAction(s, { type: 'reserve', cardId: card.id, tier: 1 }); ok('reserve takes the card + 1 gold', r1.players[0].reserved[0].id === card.id && r1.players[0].tokens.gold === 1 && r1.bank.gold === 4); ok('reserve refills the slot', r1.board[1][0] && r1.board[1][0].id !== card.id && r1.decks[1].length === s.decks[1].length - 1); ok('lastAction names the refill', r1.lastAction.refill?.slot === 0 && r1.lastAction.refill.cardId === r1.board[1][0].id); const r2 = L.applyAction(r1, { type: 'reserveDeck', tier: 3 }); ok('blind reserve flagged', r2.players[1].reserved[0].blind === true && r2.decks[3].length === s.decks[3].length - 1); ok('blind reserve hidden from rivals', L.visibleReserved(r2.players[1], 0)[0].hidden === true && !L.visibleReserved(r2.players[1], 1)[0].hidden); ok('reserve with no gold left', (() => { const t = fresh(); t.bank.gold = 0; const u = L.applyAction(t, { type: 'reserveDeck', tier: 1 }); return u.players[0].tokens.gold === 0 && u.players[0].reserved.length === 1; })()); { const t = fresh(); t.players[0].reserved = [CARDS[0], CARDS[1], CARDS[2]].map((c) => ({ ...c })); ok('reserve limit 3', !L.legalActions(t).some((a) => a.type.startsWith('reserve')) && MAX_RESERVED === 3); } // buy with bonuses + gold { const t = fresh(); const c = t.board[2][0]; const cost = c.cost; const tokens = { gold: 1 }; const bonuses = {}; let first = true; for (const g of GEMS) { if (!cost[g]) continue; if (first) { bonuses[g] = 1; tokens[g] = cost[g] - 2; first = false; } // 1 bonus + 1 gold cover 2 else tokens[g] = cost[g]; } for (const g of GEMS) if (tokens[g] < 0) tokens[g] = 0; rig(t, { tokens, bonuses }); const pv = L.previewBuy(t, t.players[0], c); const before = tokensIn(t); const u = L.applyAction(t, { type: 'buy', cardId: c.id, source: 'board' }); const p = u.players[0]; ok('buy: affordable with gold', pv.affordable && L.affordState(t.players[0], c).kind === (pv.gold ? 'gold' : 'now')); ok('buy: card recorded + bonus + points', p.cards.length === 1 && p.cards[0].id === c.id && p.bonuses[c.bonus] === (bonuses[c.bonus] ?? 0) + 1 && p.points === c.points); ok('buy: previewBuy matches payment', GEMS.every((g) => u.lastAction.pay[g] === pv.pay[g]) && u.lastAction.gold === pv.gold); ok('buy: tokens conserved', ALL.every((g) => tokensIn(u)[g] === before[g])); ok('buy: refill from deck', u.board[2][0] && u.board[2][0].id !== c.id); ok('buy: stats', p.stats.bought[2] === 1 && p.stats.goldSpent === pv.gold && p.stats.bonusSaved === pv.saved); } // buy from reserve { const t = fresh(); const c = CARDS.find((x) => x.tier === 1 && Object.keys(x.cost).length === 1); t.players[0].reserved = [{ ...c, blind: true }]; rig(t, { tokens: { ...c.cost } }); const u = L.applyAction(t, { type: 'buy', cardId: c.id, source: 'reserve' }); ok('buy from reserve', u.players[0].reserved.length === 0 && u.players[0].cards[0].id === c.id && !('blind' in u.players[0].cards[0])); } // unaffordable buy rejected { const t = fresh(); const c = t.board[3][0]; ok('unaffordable buy rejected', L.applyAction(t, { type: 'buy', cardId: c.id }) === t && L.affordState(t.players[0], c).kind !== 'now'); } // effectiveCost { const p = { tokens: { white: 1, blue: 0, green: 0, red: 0, black: 0, gold: 0 }, bonuses: { white: 2, blue: 0, green: 0, red: 0, black: 0 } }; const card = { cost: { white: 3, blue: 2 } }; const rows = L.effectiveCost(p, card); ok('effectiveCost covered/owed/short', rows[0].covered === 2 && rows[0].owed === 1 && rows[0].short === 0 && rows[1].short === 2); ok('affordState near', L.affordState({ ...p, tokens: { ...p.tokens, gold: 1 } }, card).kind === 'near'); } // discard phase { const t = fresh(); rig(t, { tokens: { white: 3, blue: 3, green: 3 } }); const u = L.applyAction(t, { type: 'take3', colors: ['red', 'black', 'white'] }); ok('over 10 parks in discard', u.phase === 'discard' && u.current === 0); ok('no actions while parked', L.legalActions(u).length === 0); const v = L.applyDiscard(u, { white: 1 }); ok('partial discard stays parked', v.phase === 'discard'); const w = L.applyDiscard(v, { blue: 1 }); ok('discard completes the turn', w.phase === 'turn' && w.current === 1 && L.tokenTotal(w.players[0]) === HAND_LIMIT); ok('gold may be returned', (() => { const a = fresh(); rig(a, { tokens: { gold: 2, white: 3, blue: 3, green: 3 } }); a.phase = 'discard'; const b = L.applyDiscard(a, { gold: 1 }); return b.players[0].tokens.gold === 1 && b.phase === 'turn'; })()); } // nobles: single auto visit, choice when two { const t = fresh(3); t.nobles = [NOBLES[0], NOBLES[1], NOBLES[2]]; // wb4, bg4, gr4 rig(t, { bonuses: { white: 4, blue: 3 } }); const c = t.board[1].find(Boolean); t.board[1][0] = { ...c, bonus: 'blue', cost: {} }; const u = L.applyAction(t, { type: 'buy', cardId: t.board[1][0].id }); ok('one noble visits automatically', u.players[0].nobles.length === 1 && u.players[0].nobles[0].id === 'n0' && u.lastVisit?.nobleId === 'n0' && u.players[0].points === 3 + c.points * 0 + (t.board[1][0].points)); const t2 = fresh(3); t2.nobles = [NOBLES[0], NOBLES[1], NOBLES[2]]; rig(t2, { bonuses: { white: 4, blue: 3, green: 4 } }); t2.board[1][0] = { ...t2.board[1][0], bonus: 'blue', cost: {} }; const v = L.applyAction(t2, { type: 'buy', cardId: t2.board[1][0].id }); ok('two nobles → choice phase', v.phase === 'noble' && v.pendingNobles.length === 2 && v.current === 0); const w = L.applyNobleChoice(v, 'n1'); ok('chosen noble visits, other stays', w.players[0].nobles[0].id === 'n1' && w.nobles.some((n) => n.id === 'n0') && w.current === 1); ok('illegal noble choice ignored', L.applyNobleChoice(v, 'n2') === v); ok('AI picks a pending noble', v.pendingNobles.includes(AI.chooseNoble(v))); } // end of game: finish the round { const t = fresh(3); t.current = 1; t.players[1].points = 14; t.board[1][0] = { ...t.board[1][0], points: 1, cost: {} }; const u = L.applyAction(t, { type: 'buy', cardId: t.board[1][0].id }); ok('15 triggers the final round', u.triggeredEnd && u.endTriggeredBy === 1 && u.phase === 'turn' && u.current === 2); const v = L.applyAction(u, { type: 'take3', colors: ['white', 'blue', 'green'] }); ok('game ends when the round completes', v.phase === 'gameOver' && v.current === 0); } // ranking tiebreak { const t = fresh(3); t.players[0].points = 15; t.players[0].cardsCount = 12; t.players[1].points = 15; t.players[1].cardsCount = 10; t.players[2].points = 15; t.players[2].cardsCount = 12; const r = L.finalRanking(t); ok('fewest cards wins a tie', r[0].seat === 1 && r[0].wonOnTiebreak && r[0].place === 1); ok('full tie shares a place', r[1].place === 2 && r[2].place === 2); } } // ── preview vs reality ─────────────────────────────────────────────────────────────── section('Preview vs applyAction'); { seedRandom(5); let checked = 0; for (let g = 0; g < (QUICK ? 6 : 20); g++) { let s = L.createInitialState({ playerCount: 2 + (g % 3), seed: 900 + g }); for (let step = 0; step < 400 && !L.isGameOver(s); step++) { const p = L.currentPlayer(s); for (const a of L.legalActions(s).filter((x) => x.type === 'buy')) { const card = L.cardById(s, a.cardId); const pv = L.previewBuy(s, p, card); const u = L.applyAction(s, a); const q = u.players[p.seat]; const tok = GEMS.every((c) => q.tokens[c] === p.tokens[c] - pv.pay[c]) && q.tokens.gold === p.tokens.gold - pv.gold; if (!tok || !pv.affordable) { ok('previewBuy payment', false, `game ${g} step ${step}`); break; } if (pv.unlocks.length && u.phase !== 'noble' && !u.players[p.seat].nobles.some((n) => pv.unlocks.some((x) => x.id === n.id))) { ok('previewBuy unlocks', false, `game ${g} step ${step}`); } checked++; } s = AI.settle(L.applyAction(s, AI.chooseAction(s, 2))); } } ok(`${checked} buy previews matched`, checked > 50); } // ── soak ───────────────────────────────────────────────────────────────────────────── section('All-AI soak'); { const games = QUICK ? 24 : 120; let finished = 0, maxTurns = 0, worstMs = 0, totalTurns = 0, conserveFail = 0, passes = 0, nobleChoices = 0, discards = 0, awardsSeen = 0; const t0 = Date.now(); for (let g = 0; g < games; g++) { const rnd = seedRandom(3000 + g); const pc = 2 + (g % 3); const skills = Array.from({ length: pc }, (_, i) => 1 + ((g + i * 2) % 5)); let s = L.createInitialState({ playerCount: pc, seed: 4000 + g }); const supply = tokensIn(s); let guard = 0; while (!L.isGameOver(s) && guard++ < 600) { const tA = Date.now(); const a = AI.chooseAction(s, skills[s.current], rnd); worstMs = Math.max(worstMs, Date.now() - tA); if (a.type === 'pass') passes++; let u = L.applyAction(s, a); if (u === s) { ok('AI chose a legal action', false, JSON.stringify(a)); break; } if (u.phase === 'discard') discards++; if (u.phase === 'noble') nobleChoices++; u = AI.settle(u); const t = tokensIn(u); if (!ALL.every((c) => t[c] === supply[c]) || cardCount(u) !== 90 || ALL.some((c) => u.bank[c] < 0) || u.players.some((p) => ALL.some((c) => p.tokens[c] < 0) || L.tokenTotal(p) > HAND_LIMIT)) conserveFail++; s = u; } if (L.isGameOver(s)) { finished++; const turns = s.turn / pc; totalTurns += turns; maxTurns = Math.max(maxTurns, turns); const pts = s.players.map((p) => p.points); ok('someone reached 15', Math.max(...pts) >= 15); ok('points = cards + nobles', s.players.every((p) => p.points === p.cards.reduce((n, c) => n + c.points, 0) + p.nobles.length * 3)); ok('pointsByTurn length = turns', s.players.every((p) => p.stats.pointsByTurn.length === p.stats.turns)); awardsSeen += L.awardsFor(s).length; } } ok(`${finished}/${games} games finished`, finished === games); ok('tokens + 90 cards conserved, hand limit kept', conserveFail === 0, `${conserveFail} bad steps`); ok('awards produced', awardsSeen > games); console.log(` avg ${(totalTurns / Math.max(1, finished)).toFixed(1)} turns/player (max ${maxTurns.toFixed(0)}), worst decision ${worstMs}ms, ${discards} discards, ${nobleChoices} noble choices, ${passes} passes, ${((Date.now() - t0) / 1000).toFixed(1)}s`); ok('decisions stay under 400ms', worstMs < 400, `${worstMs}ms`); } // ── ladder ─────────────────────────────────────────────────────────────────────────── section('Skill ladder (2 players, mirrored)'); { const pairs = QUICK ? [[5, 3], [3, 1]] : [[2, 1], [3, 2], [4, 3], [5, 4]]; const N = QUICK ? 10 : 30; for (const [a, b] of pairs) { let wins = 0, games = 0; for (let g = 0; g < N; g++) { for (const swap of [false, true]) { const rnd = seedRandom(7000 + g * 3 + (swap ? 1 : 0)); let s = L.createInitialState({ playerCount: 2, seed: 8000 + g }); const seatA = swap ? 1 : 0; let guard = 0; while (!L.isGameOver(s) && guard++ < 500) { s = AI.settle(L.applyAction(s, AI.chooseAction(s, s.current === seatA ? a : b, rnd))); } if (L.finalRanking(s)[0].seat === seatA) wins++; games++; } } const pct = (100 * wins) / games; console.log(` skill ${a} vs ${b}: ${pct.toFixed(0)}%`); ok(`skill ${a} beats ${b}`, pct > 50, `${pct.toFixed(0)}%`); } } // ── layout ─────────────────────────────────────────────────────────────────────────── section('Layout'); for (const pc of [2, 3, 4]) { const F = furniture(pc); for (const [name, r] of F) ok(`${pc}p ${name} on screen`, onScreen(r), JSON.stringify(r)); for (let i = 0; i < F.length; i++) for (let j = i + 1; j < F.length; j++) { ok(`${pc}p ${F[i][0]} / ${F[j][0]} apart`, !rectsOverlap(F[i][1], F[j][1])); } for (const Lr of computeLayout(pc).ledgers) { const P = ledgerParts(Lr); for (const r of P.reserve) ok(`${pc}p ledger ${Lr.seat} reserve slot inside`, inside(r, Lr)); for (const g of GEMS) { const col = P.cols[g]; const last = stackPos(col, 9, 10); ok(`${pc}p ledger ${Lr.seat} ${g} stack of 10 inside`, inside({ x: last.x - MINI.w / 2, y: col.stackTop, w: MINI.w, h: last.y + MINI.h / 2 - col.stackTop }, Lr)); ok(`${pc}p ledger ${Lr.seat} ${g} chip clear of stack`, col.chip.y - 16 > last.y + MINI.h / 2 - 4); } ok(`${pc}p ledger ${Lr.seat} columns clear of reserve`, P.cols.black.x + P.cols.black.w < P.reserve[0].x); for (const n of [4, 5]) { const last = cameoPos(Lr, n - 1, n); ok(`${pc}p ledger ${Lr.seat} ${n} cameos inside`, last.y + last.size / 2 <= Lr.y + Lr.h && last.x + last.size / 2 < P.cols.white.x); } } } for (const t of [1, 2, 3]) { ok(`deck ${t} inside market`, inside(deckRect(t), MARKET)); for (let i = 0; i < 4; i++) ok(`slot ${t}/${i} inside market`, inside(slotRect(t, i), MARKET)); } for (const c of BANK_ORDER) ok(`case cell ${c} inside`, inside(bankCell(c), BANK)); for (let i = 0; i < 5; i++) { const x = GALLERY.x + 14 + i * 148; ok(`noble slot ${i} inside gallery`, x + 112 <= GALLERY.x + GALLERY.w); } ok('register spans 0..15', trackX(0) > TRACK.x && trackX(15) + 60 < TRACK.x + TRACK.w); ok('dock on screen', onScreen(DOCK) && DOCK.y + DOCK.h <= H && DOCK.x + DOCK.w <= W); ok('reserve card size sane', RES.w > MINI.w); // ── art sheets ─────────────────────────────────────────────────────────────────────── section('Art sheets'); function pngSize(path) { const b = fs.readFileSync(path); return { w: b.readUInt32BE(16), h: b.readUInt32BE(20) }; } { const cards = pngSize('assets/images/splendor-cards.png'); const cols = Math.floor(cards.w / 270), rows = Math.floor(cards.h / 390); const maxFrame = Math.max(...CARDS.map(cardFrame), ...NOBLES.map(nobleFrame), deckBackFrame(3)); ok(`splendor-cards ${cards.w}×${cards.h} holds frame ${maxFrame}`, cols * rows > maxFrame && cols === 8, `${cols}×${rows}`); const gems = pngSize('assets/images/splendor-gems.png'); ok(`splendor-gems ${gems.w}×${gems.h} = 6 frames`, gems.w / 64 >= 6 && gems.h === 64); } console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);