fertig-classic-games/tools/verifyForbiddenIsland.js

345 lines
19 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
// verifyForbiddenIsland.js: headless checks for the co-op island engine + AI.
// • setup: 24 tiles on the diamond, deck composition, opening hands, 6 floods
// • give: costs an action, same tile only (Messenger: anywhere), treasure
// cards only, over-limit receiver discards and play resumes
// • swim: human chooses (phase 'swim'), AI auto-swims, Pilot/Diver/Explorer
// swim rules, drowning loses
// • specials: Sandbags any phase, Helicopter lifts a same-tile group only and
// can rescue a pending swimmer; escape spends the Helicopter
// • Waters Rise puts the reshuffled flood discard on top of the flood deck
// • losses: landing sunk, both temples sunk, skull
// • determinism: same seed + same actions → same state
// • fuzz: AI-vs-island games run to completion with only legal actions;
// win rate reported per skill
// Usage: node tools/verifyForbiddenIsland.js [--quick]
import * as D from '../src/games/forbiddenisland/IslandData.js';
import * as L from '../src/games/forbiddenisland/IslandLogic.js';
import * as AI from '../src/games/forbiddenisland/IslandAI.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}`);
// A fresh dry board with chosen roles; hands cleared so tests set them exactly.
function fresh(roles = ['pilot', 'engineer', 'messenger', 'diver'], seed = 1234) {
const s = L.createInitialState({ roles, seed, skipInitialFlood: true });
s.pendingFlood = [];
for (const p of s.players) p.hand = [];
return s;
}
const tileAt = (s, r, c) => Object.values(s.tiles).find((t) => t.r === r && t.c === c).id;
const T = (k) => `treasure:${k}`;
// ── setup ───────────────────────────────────────────────────────────────────
section('setup');
{
ok('24 cells', D.CELLS.length === 24 && D.TILES.length === 24);
ok('messenger is dealable', D.ROLE_KEYS.includes('messenger') && D.ROLE_KEYS.length === 6);
const deck = D.buildTreasureDeck();
ok('treasure deck 28', deck.length === 28);
const s = L.createInitialState({ seed: 7 });
ok('6 flooded at start', Object.values(s.tiles).filter((t) => t.state === 'flooded').length === 6);
ok('2 cards each, no Waters Rise', s.players.every((p) => p.hand.length === 2 && !p.hand.includes(D.SPECIAL.WATERS_RISE)));
ok('all start on landing', s.players.every((p) => p.tileId === 'fools-landing'));
const total = s.treasureDeck.length + s.players.reduce((n, p) => n + p.hand.length, 0);
ok('no cards lost in deal', total === 28);
}
// ── give ────────────────────────────────────────────────────────────────────
section('give card');
{
let s = fresh(['pilot', 'engineer', 'messenger', 'diver']);
s.players[0].hand = [T('fire'), D.SPECIAL.SANDBAGS];
const gives = L.legalActions(s, 0).filter((a) => a.type === 'give');
ok('give only treasure cards', gives.every((a) => a.card === T('fire')));
ok('give to all 3 on same tile', new Set(gives.map((a) => a.targetSeat)).size === 3);
const s2 = L.applyAction(s, 0, gives[0]);
ok('give costs an action', s2.actionsLeft === D.ACTIONS_PER_TURN - 1);
ok('card moved', s2.players[0].hand.length === 1 && s2.players[gives[0].targetSeat].hand.includes(T('fire')));
// Different tile: no give unless Messenger.
s = fresh(['pilot', 'engineer', 'messenger', 'diver']);
s.players[0].hand = [T('fire')];
s.players[1].tileId = tileAt(s, 0, 2);
ok('no give across tiles', !L.legalActions(s, 0).some((a) => a.type === 'give' && a.targetSeat === 1));
ok('illegal give refused', L.applyAction(s, 0, { type: 'give', seat: 0, targetSeat: 1, card: T('fire') }) === s);
s.current = 2; s.players[2].hand = [T('wind')];
ok('messenger gives anywhere', L.legalActions(s, 2).some((a) => a.type === 'give' && a.targetSeat === 1));
// Over the limit: receiver discards, then play resumes.
s = fresh();
s.players[0].hand = [T('earth')];
s.players[1].hand = [T('wind'), T('wind'), T('fire'), T('fire'), T('ocean')];
let g = L.applyAction(s, 0, { type: 'give', seat: 0, targetSeat: 1, card: T('earth') });
ok('overflow → discard phase', g.phase === 'discard' && g.pendingDiscard === 1 && g.discardReturn === 'actions');
g = L.discardCard(g, 1, T('ocean'));
ok('discard returns to actions', g.phase === 'actions' && g.current === 0 && g.actionsLeft === 2);
}
// ── swimming ────────────────────────────────────────────────────────────────
section('swim');
function sinkUnder(s, seat) { s.tiles[s.players[seat].tileId].state = 'sunk'; }
{
// Human pawn on a tile that sinks during flood → swim phase with options.
let s = fresh(['engineer', 'pilot']);
const here = tileAt(s, 2, 2);
s.players[0].tileId = here; s.players[1].tileId = tileAt(s, 3, 3);
s.tiles[here].state = 'flooded';
s.floodDeck = [here, ...s.floodDeck.filter((x) => x !== here)];
s.waterLevel = 1; s.phase = 'flood';
let f = L.resolveFlood(s);
if (f.phase !== 'lost') {
ok('human swim pending', f.phase === 'swim' && f.pendingSwim?.seat === 0);
const opt = f.pendingSwim.options[0];
ok('swim options adjacent', f.pendingSwim.options.every((id) => {
const a = f.tiles[id], b = f.tiles[here]; return Math.abs(a.r - b.r) + Math.abs(a.c - b.c) === 1;
}));
const g = L.resolveSwim(f, 0, opt);
ok('swim resolves + advances', g.players[0].tileId === opt && g.phase === 'actions' && g.current === 1);
ok('bad swim refused', L.resolveSwim(f, 0, here) === f);
// Helicopter rescue during a pending swim.
f.players[1].hand.push(D.SPECIAL.HELICOPTER);
const dest = tileAt(f, 3, 0);
const h = L.playHelicopter(f, 1, [0], dest);
ok('helicopter rescues swimmer', h.players[0].tileId === dest && h.phase === 'actions' && !h.pendingSwim);
} else ok('swim setup lost unexpectedly', false, f.lossReason);
// autoSwim moves the human too.
const a = L.resolveFlood(s, { autoSwim: true });
ok('autoSwim', a.phase === 'actions' && a.tiles[a.players[0].tileId].state !== 'sunk');
// Role swim rules (via swimChoices).
s = fresh(['pilot', 'diver', 'explorer', 'engineer']);
const c = tileAt(s, 2, 2);
for (const p of s.players) p.tileId = c;
sinkUnder(s, 0);
ok('pilot flies anywhere', L.swimChoices(s, 0).length === 23);
ok('explorer diagonals', L.swimChoices(s, 2).length === 8);
ok('engineer orthogonal', L.swimChoices(s, 3).length === 4);
// Diver: sink the ring around → nearest tiles are two steps away.
for (const id of L.adjacentTiles(s, c)) s.tiles[id].state = 'sunk';
const dv = L.swimChoices(s, 1);
ok('diver swims to nearest', dv.length > 0 && dv.every((id) => {
const t = s.tiles[id], o = s.tiles[c]; return Math.abs(t.r - o.r) + Math.abs(t.c - o.c) === 2;
}));
ok('engineer boxed in', L.swimChoices(s, 3).length === 0);
}
// ── specials ────────────────────────────────────────────────────────────────
section('specials');
{
let s = fresh();
const fl = tileAt(s, 1, 1); s.tiles[fl].state = 'flooded';
s.players[2].hand = [D.SPECIAL.SANDBAGS];
const sb = L.playSandbags(s, 2, fl);
ok('sandbags off-turn', sb !== s && sb.tiles[fl].state === 'dry');
s.phase = 'flood';
ok('sandbags during flood step', L.playSandbags(s, 2, fl) !== s);
// Helicopter: same-tile group only.
s = fresh();
s.players[0].hand = [D.SPECIAL.HELICOPTER];
s.players[1].tileId = tileAt(s, 0, 2);
const dest = tileAt(s, 5, 2);
ok('heli refuses split group', L.playHelicopter(s, 0, [0, 1], dest) === s);
const h = L.playHelicopter(s, 0, [0, 2, 3], dest);
ok('heli lifts group', [0, 2, 3].every((i) => h.players[i].tileId === dest) && !h.players[0].hand.length);
// Escape spends the Helicopter.
s = fresh();
for (const k of D.TREASURE_KEYS) s.players[0].captured[k] = true;
ok('no escape without lift', !L.canEscape(s));
s.players[3].hand = [D.SPECIAL.HELICOPTER];
const w = L.attemptEscape(s);
ok('escape wins, spends lift', w.phase === 'won' && !w.players[3].hand.length);
}
// ── Waters Rise ─────────────────────────────────────────────────────────────
section('waters rise');
{
const s = fresh();
s.floodDiscard = ['bronze-gate', 'iron-gate', 'watchtower'];
s.floodDeck = s.floodDeck.filter((x) => !s.floodDiscard.includes(x));
s.treasureDeck = [D.SPECIAL.WATERS_RISE, T('fire'), T('wind'), ...s.treasureDeck];
const lvl = s.waterLevel;
const e = L.endActions(s);
ok('level +1', e.waterLevel === lvl + 1);
ok('discard on top of flood deck', new Set(e.floodDeck.slice(0, 3)).size === 3 && e.floodDeck.slice(0, 3).every((x) => s.floodDiscard.includes(x)));
ok('Waters Rise counts as one of the two draws', e.players[0].hand.length === 1);
}
// ── losses ──────────────────────────────────────────────────────────────────
section('losses');
{
let s = fresh(); s.tiles['fools-landing'].state = 'sunk';
ok('landing sunk', L.checkLoss(s)?.phase === 'lost');
s = fresh(); for (const id of D.TREASURES.fire.tiles) s.tiles[id].state = 'sunk';
ok('both temples sunk', L.checkLoss(s)?.phase === 'lost');
s.players[0].captured.fire = true;
ok('captured treasure safe', L.checkLoss(s) === null);
s = fresh(); s.waterLevel = D.MAX_WATER;
ok('skull', L.checkLoss(s)?.phase === 'lost');
}
section('layouts');
{
for (const key of D.LAYOUT_KEYS) {
const cells = D.LAYOUTS[key].cells;
const set = new Set(cells.map(([r, c]) => `${r},${c}`));
// flood-fill orthogonally from the first cell: every shape must be one island
const seen = new Set([`${cells[0][0]},${cells[0][1]}`]); const q = [cells[0]];
while (q.length) { const [r, c] = q.pop(); for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const k = `${r + dr},${c + dc}`; if (set.has(k) && !seen.has(k)) { seen.add(k); q.push([r + dr, c + dc]); } } }
ok(`${key}: 24 connected cells in the 6×6 grid`, cells.length === 24 && seen.size === 24 && cells.every(([r, c]) => r >= 0 && r < 6 && c >= 0 && c < 6));
const s = L.createInitialState({ seed: 5, layout: key });
ok(`${key}: tiles dealt onto the shape`, s.layout === key && Object.values(s.tiles).every((t) => set.has(`${t.r},${t.c}`)));
}
const a = L.createInitialState({ seed: 5, layout: 'atoll' }), b = L.createInitialState({ seed: 5, layout: 'hook' });
ok('layouts have their own neighbour tables', JSON.stringify(L.adjacentTiles(a, 'fools-landing')) !== JSON.stringify(L.adjacentTiles(b, 'fools-landing')) || a.tiles['fools-landing'].r !== b.tiles['fools-landing'].r);
let s = fresh(); s.tiles['fools-landing'].state = 'sunk';
ok('loss kind: dock', L.checkLoss(s)?.lossKind === 'dock');
s = fresh(); for (const id of D.TREASURES.wind.tiles) s.tiles[id].state = 'sunk';
const lr = L.checkLoss(s);
ok('loss kind: relic + which', lr?.lossKind === 'relic' && lr.lossTreasure === 'wind');
s = fresh(); s.actionsLeft = 0; const r0 = s.round; s.current = s.players.length - 1;
s = L.resolveFlood(L.endActions(s), { autoSwim: true });
ok('round advances when the turn wraps to the first seat', s.current === 0 && s.round === r0 + 1);
}
// ── determinism ─────────────────────────────────────────────────────────────
section('determinism');
{
const a = L.createInitialState({ seed: 99 }), b = L.createInitialState({ seed: 99 });
ok('same seed same setup', JSON.stringify(a) === JSON.stringify(b));
const ea = L.resolveFlood(L.endActions(a), { autoSwim: true }), eb = L.resolveFlood(L.endActions(b), { autoSwim: true });
ok('same seed same turn', JSON.stringify(ea) === JSON.stringify(eb));
}
// ── public knowledge / fairness ─────────────────────────────────────────────
section('public knowledge');
{
const s = fresh();
const v = L.publicView(s);
ok('view hides flood order', JSON.stringify(v.floodDeck) === JSON.stringify(s.floodDeck.slice().sort()));
ok('view hides treasure order', JSON.stringify(v.treasureDeck) === JSON.stringify(s.treasureDeck.slice().sort()));
// Waters Rise: the reshuffled discard becomes a known top segment.
const w = fresh();
w.floodDiscard = ['bronze-gate', 'iron-gate', 'watchtower', 'observatory'];
w.floodDeck = w.floodDeck.filter((x) => !w.floodDiscard.includes(x));
w.treasureDeck = [D.SPECIAL.WATERS_RISE, T('fire'), ...w.treasureDeck];
const e = L.endActions(w);
ok('known segment recorded', e.floodKnown.length === 1 && e.floodKnown[0].length === 4);
const odds = L.floodDrawOdds(e, 2);
ok('top segment odds = 2/4', w.floodDiscard.every((id) => Math.abs(odds[id] - 0.5) < 1e-9));
ok('rest of deck odds = 0', Object.entries(odds).filter(([id]) => !w.floodDiscard.includes(id)).every(([, p]) => p === 0));
const odds5 = L.floodDrawOdds(e, 5);
const rest = e.floodDeck.length - 4;
ok('overflow spreads to rest', Math.abs(odds5['bronze-gate'] - 1) < 1e-9 && Math.abs(odds5[e.floodDeck.find((x) => !w.floodDiscard.includes(x))] - 1 / rest) < 1e-9);
const f = L.resolveFlood({ ...e, phase: 'flood' }, { autoSwim: true });
ok('drawn cards leave the segment', f.floodKnown.flat().length === Math.max(0, 4 - D.WATER_TRACK[e.waterLevel]));
// Same public position, different hidden deck order → same decision.
let same = 0, trials = 0;
for (let seed = 1; seed <= 12; seed++) {
const a = L.createInitialState({ seed, humanSeat: -1 });
const b = L.cloneState(a);
b.floodDeck = b.floodDeck.slice().reverse();
b.treasureDeck = b.treasureDeck.slice().reverse();
trials++;
if (JSON.stringify(AI.chooseAction(a, 0, 5)) === JSON.stringify(AI.chooseAction(b, 0, 5))) same++;
}
ok('AI ignores hidden deck order', same === trials, `${same}/${trials}`);
}
// ── AI sanity positions ─────────────────────────────────────────────────────
section('AI positions');
{
// Carrier with a full set next to its temple walks over and captures.
let s = fresh(['engineer', 'pilot']);
const temple = D.TREASURES.fire.tiles[0];
const nb = L.adjacentTiles(s, temple).find((id) => !s.tiles[id].treasure && !s.tiles[id].landing);
s.players[0].tileId = nb;
s.players[0].hand = [T('fire'), T('fire'), T('fire'), T('fire')];
const a1 = AI.chooseAction(s, 0, 5);
ok('walks to temple', a1?.type === 'move' && a1.tileId === temple, JSON.stringify(a1));
s = L.applyAction(s, 0, a1);
ok('captures', AI.chooseAction(s, 0, 5)?.type === 'capture');
// Flooded landing within reach gets shored.
s = fresh(['engineer', 'pilot']);
s.tiles['fools-landing'].state = 'flooded';
const plan = AI.planTurn(s, 0, 5).actions;
ok('shores the landing', plan.some((a) => a.type === 'shoreUp' && a.tiles.includes('fools-landing')), JSON.stringify(plan));
// Never breaks a full set by giving into a full hand.
s = fresh(['messenger', 'engineer']);
s.players[0].hand = [T('wind'), T('wind'), T('wind'), T('wind')];
s.players[1].hand = [T('fire'), T('fire'), T('ocean'), T('earth'), T('earth')];
const p2 = AI.planTurn(s, 0, 5).actions;
ok('keeps the full set', !p2.some((a) => a.type === 'give' && a.card === T('wind')), JSON.stringify(p2));
}
// ── fuzz: AI plays every seat ───────────────────────────────────────────────
section('fuzz + AI');
function playGame(seed, skill, difficulty = 'novice', nPlayers = 4) {
const roles = D.ROLE_KEYS.slice().sort(() => 0.5 - ((seed * 9301 + 49297) % 233280) / 233280).slice(0, nPlayers);
let s = L.createInitialState({ roles, seed, difficulty, humanSeat: -1, layout: D.LAYOUT_KEYS[seed % D.LAYOUT_KEYS.length] });
let guard = 0;
while (!L.isGameOver(s) && guard++ < 4000) {
if (L.canEscape(s)) { s = L.attemptEscape(s); break; }
if (s.phase === 'actions') {
const seat = s.current;
const free = AI.chooseFreeCard(s, seat);
if (free) {
const n = free.type === 'sandbags' ? L.playSandbags(s, free.seat, free.tileId) : L.playHelicopter(s, free.seat, free.pawnSeats, free.destTileId);
if (n === s) return { error: `free card refused ${JSON.stringify(free)}` };
s = n; continue;
}
const act = AI.chooseAction(s, seat, skill);
if (!act) { s = L.endActions(s); continue; }
const legal = L.legalActions(s, seat).some((a) => JSON.stringify(a) === JSON.stringify(act));
if (!legal) return { error: `illegal ${JSON.stringify(act)}` };
s = L.applyAction(s, seat, act);
} else if (s.phase === 'discard') {
s = L.discardCard(s, s.pendingDiscard, AI.chooseDiscard(s, s.pendingDiscard));
} else if (s.phase === 'flood') {
s = L.resolveFlood(s, { autoSwim: true });
} else return { error: `stuck in ${s.phase}` };
// invariants
// Captured-treasure cards go to the discard pile, so all 28 stay in circulation.
const cards = s.treasureDeck.length + s.treasureDiscard.length + s.players.reduce((n, p) => n + p.hand.length, 0);
if (cards !== 28) return { error: `card count ${cards}` };
if (s.phase !== 'lost' && s.players.some((p) => s.tiles[p.tileId].state === 'sunk') && s.phase !== 'swim') return { error: 'pawn on sunk tile' };
}
if (!L.isGameOver(s)) return { error: 'did not finish' };
return { won: s.phase === 'won', reason: s.lossReason };
}
{
// Full mode plays enough games for the ladder to be meaningful (all-AI teams,
// Novice, alternating 4- and 2-player); quick mode only checks legality.
const N = QUICK ? 12 : 80;
const wins = {};
for (const skill of [1, 3, 5]) {
let w = 0, errors = 0; const reasons = {};
for (let i = 0; i < N; i++) {
const r = playGame(1000 + i, skill, 'novice', i % 2 ? 2 : 4);
if (r.error) { errors++; if (errors <= 3) console.error(` seed ${1000 + i}: ${r.error}`); continue; }
if (r.won) w++; else reasons[r.reason] = (reasons[r.reason] ?? 0) + 1;
}
wins[skill] = w;
ok(`skill ${skill}: no engine/AI errors`, errors === 0, `${errors} errors`);
const top = Object.entries(reasons).sort((a, b) => b[1] - a[1]).slice(0, 2).map(([r, n]) => `${n}× ${r}`).join('; ');
console.log(` skill ${skill} (novice, 2p/4p): won ${w}/${N} ${top ? `— losses: ${top}` : ''}`);
}
if (!QUICK) {
ok('ladder: skill 5 beats skill 3', wins[5] > wins[3], JSON.stringify(wins));
ok('ladder: skill 3 beats skill 1', wins[3] > wins[1], JSON.stringify(wins));
ok('skill 5 wins at least a third on Novice', wins[5] >= N / 3, `${wins[5]}/${N}`);
}
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);