#!/usr/bin/env node // verifyParchisi.js — headless checks for Parchisi ("Monsoon Veranda"): // • rules on hand-built positions: entering (a 5 / dice totalling 5 / 5-5), // the entry bop, captures (+20), safety squares (and the share-safe house // rule), blockades (passing, landing, home path, not moved together on // doubles), exact count home (+10), doubles backs, third doubles, the // full-roll rule, bonus forfeits, finishRoll / re-rolls, opening, ranks // • threat odds: exact roll counts on textbook positions // • AI soak at 2, 3 and 4 players: games finish, invariants hold, every AI // plan uses the whole roll // • skill ladder (mirrored seeds, two players) // • dice throws land on the rolled faces inside the tray // • board geometry: path continuity for every colour, nests / home slots, // layout bounds and overlaps // Usage: node tools/verifyParchisi.js [--quick] import * as L from '../src/games/parchisi/ParchisiLogic.js'; import * as AI from '../src/games/parchisi/ParchisiAI.js'; import * as B from '../src/games/parchisi/ParchisiBoard.js'; import * as Lay from '../src/games/parchisi/ParchisiLayout.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 N = L.NEST, H = L.HOME; // A state with given pawns (progress arrays), current player and dice. function pos(pawns, { player = 'red', dice = null, opts = {}, players = null } = {}) { const ps = players ?? Object.keys(pawns); let s = L.createInitialState(ps, opts); for (const c of ps) s.pawns[c] = (pawns[c] ?? [N, N, N, N]).slice(); s.currentPlayer = player; if (dice) s = L.rollSpecificDice(s, dice[0], dice[1]); return s; } const mv = (m) => `${m.pawnIdx}:${m.from}>${m.to}/${m.combine ? m.combine.join('+') : m.dieUsed}${m.hit ? '*' : ''}`; const moves = (s) => L.getValidMoves(s).map(mv).sort(); // progress for colour c standing on track square sq const at = (c, sq) => L.progressAt(c, sq); section('Rules'); { ok('seats: 2 → opposite corners', L.seatColors(2).join() === 'red,yellow'); ok('seats: 3 and 4', L.seatColors(3).length === 3 && L.seatColors(4).length === 4); ok('progress 0 is the entry, 63 the home-entry', L.trackIdx('red', 0) === L.ENTRY.red && L.trackIdx('red', 63) === L.HOME_ENTRY.red); for (const c of L.COLORS) ok(`${c}: home-entry is the square behind its entry`, L.trackIdx(c, 63) === (L.ENTRY[c] + 5) % 68); // entering let s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [5, 2] }); ok('a 5 enters a pawn', moves(s).includes('0:-1>0/5')); ok('no other move with everything in the nest', moves(s).length === 1, moves(s).join(' ')); s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [1, 4] }); ok('two dice totalling 5 enter a pawn', moves(s).includes('0:-1>0/1+4')); s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [3, 3] }); ok('3-3 does not enter (no 5, and doubles never combine)', moves(s).length === 0); s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [5, 5] }); let a = L.applyMove(s, L.getValidMoves(s)[0]); ok('5-5 enters two pawns', L.getValidMoves(a).some((m) => m.from === N) && L.getValidMoves(a).length >= 1); // entry bop s = pos({ red: [N, N, N, N], yellow: [at('yellow', L.ENTRY.red), N, N, N] }, { dice: [5, 1] }); const bop = L.getValidMoves(s).find((m) => m.from === N); ok('entering bops a lone opponent on your entry (even though it is safe)', bop?.hit?.color === 'yellow'); a = L.applyMove(s, bop); ok('the bopped pawn goes home to its nest, +20 to you', a.pawns.yellow[0] === N && a.movesLeft.includes(20)); s = pos({ red: [N, N, N, N], yellow: [at('yellow', L.ENTRY.red), at('yellow', L.ENTRY.red), N, N] }, { dice: [5, 1] }); ok('an opponent blockade on your entry keeps you in', !L.getValidMoves(s).some((m) => m.from === N)); // capture & safety s = pos({ red: [10, N, N, N], yellow: [at('yellow', L.trackIdx('red', 13)), N, N, N] }, { dice: [3, 6] }); const cap = L.getValidMoves(s).find((m) => m.to === 13); ok('landing on a lone opponent (not safe) captures', cap?.hit?.color === 'yellow'); a = L.applyMove(s, cap); ok('capture: +20 bonus chip and stats', a.movesLeft.includes(20) && a.stats.red.captures === 1 && a.stats.yellow.captured === 1); ok('the +20 is used whole by one pawn', L.getValidMoves(a).filter((m) => m.dieUsed === 20).every((m) => m.to - m.from === 20)); const noBonus = L.applyMove(pos({ red: [10, N, N, N], yellow: [at('yellow', L.trackIdx('red', 13)), N, N, N] }, { dice: [3, 6], opts: { captureBonus: false } }), cap); ok('house rule: no capture bonus', !noBonus.movesLeft.includes(20)); const safeSq = 4; // a white safety square const pr = at('red', safeSq); s = pos({ red: [pr - 2, N, N, N], yellow: [at('yellow', safeSq), N, N, N] }, { dice: [2, 6] }); ok('cannot land on a safety square held by an opponent', !L.getValidMoves(s).some((m) => m.to === pr)); s = pos({ red: [pr - 2, N, N, N], yellow: [at('yellow', safeSq), N, N, N] }, { dice: [2, 6], opts: { shareSafe: true } }); const share = L.getValidMoves(s).find((m) => m.to === pr); ok('house rule share-safe: may share it, without capturing', share && !share.hit); // blockades const bq = at('yellow', L.trackIdx('red', 14)); s = pos({ red: [10, N, N, N], yellow: [bq, bq, N, N] }, { dice: [6, 2] }); ok('cannot pass an opponent blockade', !L.getValidMoves(s).some((m) => m.to > 13 && m.pawnIdx === 0 && m.from === 10)); s = pos({ red: [10, 14, 14, N], yellow: [N, N, N, N] }, { dice: [6, 3] }); ok('cannot pass your own blockade either', !L.getValidMoves(s).some((m) => m.pawnIdx === 0 && m.to > 14)); s = pos({ red: [66, 68, 68, N], yellow: [N, N, N, N] }, { dice: [3, 1] }); ok('a blockade on your home path blocks your own pawns', !L.getValidMoves(s).some((m) => m.pawnIdx === 0 && m.to > 68)); ok('two pawns may share a home-path square', L.getValidMoves(pos({ red: [66, 68, N, N], yellow: [N, N, N, N] }, { dice: [2, 5] })).some((m) => m.pawnIdx === 0 && m.to === 68)); s = pos({ red: [20, 20, 30, 40], yellow: [N, N, N, N] }, { dice: [3, 3] }); a = L.applyMove(s, L.getValidMoves(s).find((m) => m.pawnIdx === 0 && m.dieUsed === 3)); ok('doubles: the second pawn of a blockade may not follow to the same square', !L.getValidMoves(a).some((m) => m.pawnIdx === 1 && m.to === 23)); ok('…but it may use a back (4) instead', L.getValidMoves(a).some((m) => m.pawnIdx === 1 && m.to === 24)); // home s = pos({ red: [69, N, N, N], yellow: [N, N, N, N] }, { dice: [2, 6] }); ok('exact count into HOME', L.getValidMoves(s).some((m) => m.to === H) && !L.getValidMoves(s).some((m) => m.dieUsed === 6 && m.pawnIdx === 0)); a = L.applyMove(s, L.getValidMoves(s).find((m) => m.to === H)); ok('reaching HOME earns +10', a.movesLeft.includes(10) && a.stats.red.home === 1); const fin = pos({ red: [H, H, H, 70], yellow: [N, N, N, N] }, { dice: [1, 3] }); const won = L.applyMove(fin, L.getValidMoves(fin).find((m) => m.to === H)); ok('fourth pawn home wins', won.phase === 'game_over' && won.winner === 'red'); ok('rankings put the winner first', L.rankings(won)[0] === 'red'); // doubles & backs s = pos({ red: [10, 20, 30, H], yellow: [N, N, N, N] }, { dice: [2, 2] }); ok('doubles with every pawn out add the backs (5 and 5)', s.movesLeft.slice().sort().join() === '2,2,5,5'); s = pos({ red: [10, 20, 30, N], yellow: [N, N, N, N] }, { dice: [2, 2] }); ok('no backs while a pawn is still in the nest', s.movesLeft.join() === '2,2'); let r = L.finishRoll(L.applyMove(L.applyMove(s, L.getValidMoves(s)[0]), L.getValidMoves(L.applyMove(s, L.getValidMoves(s)[0]))[0])); ok('after doubles the same player rolls again', r.currentPlayer === 'red' && r.phase === 'roll' && r.lastEvent.type === 'again'); // three doubles let t3 = pos({ red: [10, 50, 66, N], yellow: [N, N, N, N] }); t3.consecutiveDoubles = 2; const pen = L.rollSpecificDice(t3, 4, 4); ok('third doubles: most advanced pawn back to the nest, turn over', pen.pawns.red[2] === N && pen.currentPlayer === 'yellow' && pen.lastEvent.type === 'threeDoubles' && pen.lastEvent.pawnIdx === 2 && pen.lastEvent.dice.join() === '4,4'); t3 = pos({ red: [10, 50, 66, N], yellow: [N, N, N, N] }, { opts: { threeDoubles: false } }); t3.consecutiveDoubles = 2; ok('house rule: no third-doubles penalty', L.rollSpecificDice(t3, 4, 4).phase === 'move'); // full-roll rule { // yellow blockade 6 ahead of pawn 0; pawn 1 near home. 5 then 6 (pawn 0 then 1) // or 6 with pawn 1 first both use the whole roll; pawn 1 taking the 5 first // strands the 6, so it is not offered. const blk = at('yellow', L.trackIdx('red', 16)); const st = pos({ red: [10, 62, H, H], yellow: [blk, blk, N, N] }, { dice: [5, 6] }); const v = moves(st); ok('full-roll rule: a first move that strands the other die is not offered', v.join(' ') === '0:10>15/5 1:62>68/6', v.join(' ')); const st2 = pos({ red: [65, H, H, H], yellow: [N, N, N, N] }, { dice: [6, 1] }); ok('no higher-die rule: with one die usable either may be played', moves(st2).join(' ') === '0:65>66/1 0:65>71/6', moves(st2).join(' ')); const st3 = pos({ red: [69, N, N, N], yellow: [N, N, N, N] }, { dice: [2, 3] }); ok('full-roll rule: 2+3 must enter a pawn rather than spend the 2 going home', moves(st3).join(' ') === '1:-1>0/2+3', moves(st3).join(' ')); } // forfeits and passing s = pos({ red: [69, N, N, N], yellow: [N, N, N, N] }, { dice: [2, 4] }); a = L.applyMove(s, L.getValidMoves(s).find((m) => m.to === H)); ok('with nothing able to use them, leftover dice and the +10 end the roll', L.turnDone(a)); r = L.finishRoll(a); ok('finishRoll passes the turn and counts the forfeited bonus', r.currentPlayer === 'yellow' && r.stats.red.forfeits === 1); // opening const op = L.rollOpening(L.createInitialState(L.seatColors(4)), mulberry32(4)); const last = op.opening[op.opening.length - 1]; ok('opening: the starter threw the highest die of the last round', last[op.currentPlayer] === Math.max(...Object.values(last)) && Object.values(last).filter((f) => f === last[op.currentPlayer]).length === 1); ok('moveText reads well', /enters \(5\)/.test(L.moveText({ from: N, to: 0, dieUsed: 5 })) && /capture/.test(L.moveText({ from: 3, to: 8, dieUsed: 5, hit: {} }))); } section('Threat odds'); { const sq = L.trackIdx('red', 20); // one yellow pawn 3 squares behind a lone red pawn, yellow still has nest pawns let s = pos({ red: [20, N, N, N], yellow: [at('yellow', sq) - 3, N, N, N] }); ok('3 behind: 13/36 (any 3, or 1+2)', Math.abs(AI.hitProb(s, 'yellow', sq) - 13 / 36) < 1e-9, `${AI.hitProb(s, 'yellow', sq) * 36}`); s = pos({ red: [20, N, N, N], yellow: [at('yellow', sq) - 3, at('yellow', sq) - 30, at('yellow', sq) - 40, H] }); ok('3 behind with every yellow pawn out: 4-4 backs add one roll → 14/36', Math.abs(AI.hitProb(s, 'yellow', sq) - 14 / 36) < 1e-9, `${AI.hitProb(s, 'yellow', sq) * 36}`); s = pos({ red: [20, N, N, N], yellow: [at('yellow', sq) - 8, N, N, N] }); ok('8 behind: 5/36 (2+6, 3+5, 4+4)', Math.abs(AI.hitProb(s, 'yellow', sq) - 5 / 36) < 1e-9, `${AI.hitProb(s, 'yellow', sq) * 36}`); const safeP = L.progressAt('red', 21); s = pos({ red: [safeP, N, N, N], yellow: [at('yellow', 21) - 3, N, N, N] }); ok('a pawn on a safety square is never at risk', AI.threatOf(s, 'red', safeP) === 0); s = pos({ red: [L.progressAt('red', L.ENTRY.yellow), N, N, N], yellow: [N, N, N, N] }); ok('sitting on an opponent\'s entry while they have nest pawns: 15/36 (a 5 or a total of 5)', Math.abs(AI.threatOf(s, 'red', s.pawns.red[0]) - 15 / 36) < 1e-9); s = pos({ red: [20, 20, N, N], yellow: [at('yellow', sq) - 3, N, N, N] }); ok('a blockade is never at risk', AI.threatOf(s, 'red', 20) === 0); const blk = at('yellow', L.trackIdx('red', 22)); s = pos({ red: [20, 22, 22, N], yellow: [at('yellow', sq) - 6, N, N, N], green: [blk, N, N, N] }, { players: ['red', 'yellow', 'green'] }); ok('dangerReport lists exposed pawns with who threatens them', AI.dangerReport(s, 'red').some((d) => d.pawnIdx === 0 && d.by.some((b) => b.color === 'yellow'))); } section('AI soak'); AI.SKILL[5] = { ...AI.SKILL[5] }; function play(skills, seed, n = 2, { check = false } = {}) { const dice = mulberry32(seed), noise = mulberry32(seed * 13 + 5); let s = L.rollOpening(L.createInitialState(L.seatColors(n)), dice); const sk = Object.fromEntries(s.players.map((c, i) => [c, skills[i % skills.length]])); let guard = 0, bad = 0, partial = 0; while (s.phase !== 'game_over' && guard++ < 5000) { if (s.phase === 'roll') { s = L.rollDice(s, dice); continue; } const plan = AI.chooseMoves(s, sk[s.currentPlayer], noise); for (const m of plan) { if (check && !L.getValidMoves(s).some((q) => q.pawnIdx === m.pawnIdx && q.to === m.to && q.dieUsed === m.dieUsed)) bad++; s = L.applyMove(s, m); if (s.phase === 'game_over') break; } if (s.phase === 'game_over') break; if (!L.turnDone(s)) partial++; if (check) { const occ = new Map(); for (const c of s.players) s.pawns[c].forEach((p) => { if (p < -1 || p > H) bad++; if (L.onTrack(p)) { const k = L.trackIdx(c, p); occ.set(k, (occ.get(k) ?? 0) + 1); } }); for (const v of occ.values()) if (v > 2) bad++; for (const c of s.players) for (let h = L.HOME_PATH0; h < H; h++) if (s.pawns[c].filter((p) => p === h).length > 2) bad++; } s = L.finishRoll(s); } return { winner: s.winner, players: s.players, guard, bad, partial }; } { const G = QUICK ? 18 : 90; let fin = 0, bad = 0, partial = 0; for (let g = 0; g < G; g++) { const r = play([1 + (g % 5), 1 + ((g + 2) % 5), 1 + ((g + 4) % 5), 3], 500 + g, 2 + (g % 3), { check: true }); if (r.winner) fin++; bad += r.bad; partial += r.partial; } ok(`${G} all-AI games at 2–4 players all finish`, fin === G, `${fin}/${G}`); ok('board invariants hold (≤ 2 per square, legal moves only)', bad === 0, `${bad}`); ok('every AI plan uses the whole roll', partial === 0, `${partial}`); const t0 = Date.now(); let st = L.rollOpening(L.createInitialState(L.seatColors(4)), mulberry32(8)); st.pawns.red = [10, 20, 30, 40]; st.currentPlayer = 'red'; st = L.rollSpecificDice(st, 6, 6); AI.chooseMoves(st, 5, () => 0.5); ok('a skill-5 search on doubles-with-backs stays quick', Date.now() - t0 < 1200, `${Date.now() - t0} ms`); const h = AI.hint(L.rollSpecificDice(pos({ red: [10, N, N, N], yellow: [at('yellow', L.trackIdx('red', 13)), N, N, N] }), 3, 6)); ok('hint takes the capture', h.moves.some((m) => m.hit), h.reason); ok('hint explains itself', /captures a pawn/i.test(h.reason), h.reason); } section('Skill ladder (mirrored seeds, 2 players)'); { const pairs = (a, b, n, off) => { let w = 0; for (let i = 0; i < n; i++) { const r1 = play([a, b], 9000 + off + i), r2 = play([b, a], 9000 + off + i); if (r1.winner === r1.players[0]) w++; if (r2.winner === r2.players[1]) w++; } return w / (2 * n); }; const n = QUICK ? 20 : 150; for (const [a, b, need] of [[2, 1, 0.6], [3, 2, 0.58], [4, 3, 0.52], [5, 4, 0.52]]) { const r = pairs(a, b, n, a * 1000); console.log(` skill ${a} vs ${b}: ${(r * 100).toFixed(1)}% over ${2 * n} games`); if (!QUICK) ok(`skill ${a} beats skill ${b}`, r > need, `${(r * 100).toFixed(1)}%`); } } section('Dice throws'); { const rng = mulberry32(3); let badFace = 0, outside = 0; for (let k = 0; k < (QUICK ? 40 : 160); k++) { const c = L.COLORS[k % 4]; const faces = [1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)]; const plan = planTrayThrow(Lay.TRAY_WORLD, Lay.throwOrigin(c), faces, rng, Lay.DIE_SIZE, { spread: 1.4, sep: 1.5, aim: { u0: 0.2, u1: 0.8, v0: 0.3, v1: 0.7 } }); plan.dice.forEach((d, i) => { const f = d.frames[d.frames.length - 1]; if (topFace(f.q) !== faces[i]) badFace++; if (f.u < 0 || f.u > Lay.TRAY_WORLD.w || f.v < 0 || f.v > Lay.TRAY_WORLD.h) outside++; }); } ok('throws land on the rolled faces', badFace === 0, `${badFace}`); ok('dice stay in the tray', outside === 0, `${outside}`); const r4 = Lay.diceRest(4); ok('four resting dice (roll + backs) are apart', r4.every((a, i) => r4.every((b, j) => i === j || Math.hypot(a.u - b.u, a.v - b.v) > Lay.DIE_SIZE * 1.3))); } section('Board & layout'); { for (const c of L.COLORS) { let okPath = true; for (let p = 0; p < H - 1; p++) { const a = B.cellOf(c, p), b = B.cellOf(c, p + 1); if (!a || !b || Math.hypot(a.x - b.x, a.y - b.y) > B.CELL * 1.5) okPath = false; } ok(`${c}: every step of the path is to a neighbouring cell`, okPath); const last = B.cellOf(c, H - 1), hs = B.homeSlot(c, 0); ok(`${c}: the last home-path square touches its HOME triangle`, Math.hypot(last.x - hs.x, last.y - hs.y) < B.CELL * 1.9); const r = B.NEST_RECT[c]; ok(`${c}: nest seats inside the nest`, [0, 1, 2, 3].every((i) => { const q = B.nestSlot(c, i); return q.x > B.ORIGIN_X + r.col0 * B.CELL && q.x < B.ORIGIN_X + (r.col1 + 1) * B.CELL && q.y > B.ORIGIN_Y + r.row0 * B.CELL && q.y < B.ORIGIN_Y + (r.row1 + 1) * B.CELL; })); const ent = B.cellOf(c, 0), nc = B.nestCenter(c); ok(`${c}: entry square sits beside its nest`, Math.hypot(ent.x - nc.x, ent.y - nc.y) < B.CELL * 5.5); } const cells = new Set(); for (let i = 0; i < 68; i++) { const t = B.trackXY(i); cells.add(`${t.col},${t.row}`); } for (const c of L.COLORS) for (let k = 0; k < 7; k++) { const t = B.homeXY(c, k); cells.add(`${t.col},${t.row}`); } ok('68 track + 28 home-path cells are all distinct', cells.size === 96); 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; const 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(', ')); for (const c of L.COLORS) { const b = Lay.plateParts(c).bubble; ok(`${c} speech bubble on screen and off the board`, inScreen(b) && !overlap(b, Lay.BOARD_RECT)); } ok('six move chips fit on the chip card', [0, 5].every((i) => { const r = Lay.chipRect(i, 6); return r.x >= Lay.CHIPS.x && r.x + r.w <= Lay.CHIPS.x + Lay.CHIPS.w; })); } console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);