#!/usr/bin/env node // verifyStratego.js: headless checks for Stratego ("Fog of War"): // • combat table: every rank against every rank // • movement: one step, Scout runs, asteroid fields and pieces block // • two-square rule (incl. Scout spans) and the chase rule // • reveal modes: assisted remembers survivors, classic forgets them; // viewFor never leaks a hidden enemy rank // • setup: tray accounting, place/remove/swap, fill, layouts round-trip, // every built-in formation (and its randomizations) is legal // • fuzz: thousands of random games end with a valid result; save/load // (JSON) round-trips; replay reproduces the game // • AI: legal moves within budget; never reads hidden ranks; the skill // ladder holds over mirrored games // • layout: HUD rectangles on screen and clear of the board and each other // Usage: node tools/verifyStratego.js [--quick] import * as D from '../src/games/stratego/StrategoData.js'; import * as L from '../src/games/stratego/StrategoLogic.js'; import * as S from '../src/games/stratego/StrategoSetups.js'; import * as AI from '../src/games/stratego/StrategoAI.js'; import { handle } from '../src/games/stratego/StrategoEngine.js'; import * as LAY from '../src/games/stratego/StrategoLayout.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}`); // Build a play-phase state from a sparse piece list: [r, c, owner, rank, extra?] function position(pieces, { current = 0, reveal = 'assisted', variant = 'classic' } = {}) { const s = L.createInitialState({ variant, reveal }); s.phase = 'play'; s.current = current; let id = 0; for (const [r, c, owner, rank, extra] of pieces) { s.board[r][c] = { id: owner * 100 + (++id), owner, rank, moved: false, scout: false, origin: r * 10 + c, ...(extra ?? {}) }; } return s; } const mv = (s, a, b, c, d) => L.applyMove(s, a, b, c, d); // ── combat ──────────────────────────────────────────────────────────────────── section('combat'); { const { FLAG, BOMB, SPY, MINER, MARSHAL, battleResult } = D; for (let a = 1; a <= 10; a++) { ok(`${a} takes the flag`, battleResult(a, FLAG) === 'attacker'); ok(`${a} vs bomb`, battleResult(a, BOMB) === (a === MINER ? 'attacker' : 'defender')); for (let d = 1; d <= 10; d++) { let want = a === d ? 'both' : a > d ? 'attacker' : 'defender'; if (a === SPY && d === MARSHAL) want = 'attacker'; ok(`${a} vs ${d}`, battleResult(a, d) === want); } } ok('marshal attacking spy wins', battleResult(MARSHAL, SPY) === 'attacker'); } // ── movement ────────────────────────────────────────────────────────────────── section('movement'); { let s = position([[6, 0, 0, 5], [9, 9, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); let m = L.legalMovesFor(s, 6, 0); ok('single step: 3 moves from the edge', m.length === 3, m.length); s = position([[6, 1, 0, 2], [9, 9, 0, 0], [0, 9, 1, 0], [1, 1, 1, 4]]); m = L.legalMovesFor(s, 6, 1); ok('scout runs up to the enemy and may attack it', m.some((x) => x.r === 1 && x.c === 1 && x.attack) && m.some((x) => x.r === 2 && x.c === 1)); ok('scout cannot pass the enemy', !m.some((x) => x.r === 0 && x.c === 1)); s = position([[6, 2, 0, 2], [9, 9, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); m = L.legalMovesFor(s, 6, 2); ok('asteroid field blocks the scout', !m.some((x) => x.r <= 5 && x.c === 2), JSON.stringify(m)); s = position([[3, 2, 1, 2], [9, 9, 0, 0], [0, 9, 1, 0], [9, 0, 0, 4]], { current: 1 }); ok('scout cannot cross into the field from above', !L.legalMovesFor(s, 3, 2).some((x) => x.r === 4)); s = position([[6, 0, 0, 11], [7, 0, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); ok('bombs and flags do not move', L.legalMovesFor(s, 6, 0).length === 0 && L.legalMovesFor(s, 7, 0).length === 0); const before = s; ok('illegal move returns the same state', L.applyMove(s, 6, 0, 5, 0) === before); } // ── two-square & chase ──────────────────────────────────────────────────────── section('repetition rules'); { // red 5 shuttles 7,4 ↔ 6,4; blue shuttles a 4 far away let s = position([[7, 4, 0, 5], [9, 9, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); const seq = [[7, 4, 6, 4], [0, 0, 1, 0], [6, 4, 7, 4], [1, 0, 0, 0], [7, 4, 6, 4], [0, 0, 1, 0]]; for (const m of seq) { const n = mv(s, ...m); ok(`shuttle ${m}`, n !== s); s = n; } const blocked = L.movesFor(s, 6, 4).find((x) => x.r === 7 && x.c === 4); ok('4th shuttle is blocked by the two-square rule', blocked?.blocked === 'two-square', JSON.stringify(blocked)); ok('other moves still allowed', L.legalMovesFor(s, 6, 4).length > 0); // a different piece moving resets the count s = position([[7, 4, 0, 5], [8, 8, 0, 4], [9, 9, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); for (const m of [[7, 4, 6, 4], [0, 0, 1, 0], [6, 4, 7, 4], [1, 0, 0, 0], [8, 8, 7, 8], [0, 0, 1, 0], [7, 4, 6, 4], [1, 0, 0, 0]]) s = mv(s, ...m); ok('interleaved move resets the two-square count', !L.movesFor(s, 6, 4).find((x) => x.r === 7 && x.c === 4)?.blocked); // scout span: runs 9,0→6,0, back to 8,0 (inside the span), then 6,0 again → 4th blocked s = position([[9, 1, 0, 2], [9, 9, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); for (const m of [[9, 1, 6, 1], [0, 0, 1, 0], [6, 1, 8, 1], [1, 0, 0, 0], [8, 1, 7, 1], [0, 0, 1, 0]]) { const n = mv(s, ...m); ok(`scout ${m}`, n !== s); s = n; } const sb = L.movesFor(s, 7, 1); ok('scout: a 4th move inside the span is blocked', sb.filter((x) => x.r >= 6 && x.r <= 9 && x.c === 1 && !x.attack).every((x) => x.blocked === 'two-square'), JSON.stringify(sb)); ok('scout: leaving the span is fine', sb.some((x) => x.r < 6 && !x.blocked)); // chase: red 6 chases a blue 4 around open ground s = position([[6, 4, 0, 6], [9, 9, 0, 0], [0, 9, 1, 0], [4, 4, 1, 4]]); // red steps adjacent (5,4), blue flees to 4,5... red follows to 5,5, blue back to 4,4, red to 5,4 (seen) → blocked const chase = [[6, 4, 5, 4], [4, 4, 4, 5], [5, 4, 5, 5], [4, 5, 4, 4]]; for (const m of chase) { const n = mv(s, ...m); ok(`chase ${m}`, n !== s); s = n; } const cb = L.movesFor(s, 5, 5).find((x) => x.r === 5 && x.c === 4); ok('chase back into a repeated position is blocked', cb?.blocked === 'chase', JSON.stringify(cb)); ok('chaser can still break off', L.legalMovesFor(s, 5, 5).length > 0); ok('chased unit is never chase-blocked', L.movesFor({ ...s, current: 1 }, 4, 4).every((x) => x.blocked !== 'chase')); } // ── reveal modes & view safety ──────────────────────────────────────────────── section('reveal modes'); { for (const reveal of ['assisted', 'classic']) { let s = position([[6, 4, 0, 7], [9, 9, 0, 0], [0, 9, 1, 0], [5, 4, 1, 4], [0, 0, 1, 9]], { reveal }); const red = s.board[6][4]; s = mv(s, 6, 4, 5, 4); ok(`${reveal}: attacker won`, s.board[5][4]?.id === red.id); ok(`${reveal}: winner ${reveal === 'assisted' ? 'stays revealed' : 'goes back face-down'}`, L.isKnownTo(s, 1, s.board[5][4]) === (reveal === 'assisted')); const v = L.viewFor(s, 1); ok(`${reveal}: AI view rank for red winner`, (v.board[5][4].rank != null) === (reveal === 'assisted')); ok(`${reveal}: battle is in the public log`, v.log.at(-1).aRank === 7 && v.log.at(-1).dRank === 4); const vr = L.viewFor(s, 0); ok(`${reveal}: unrevealed enemy hidden from red`, vr.board[0][0].rank === null && vr.board[0][9].rank === null); ok(`${reveal}: own ranks visible`, vr.board[9][9].rank === 0); } // scout runs are public let s = position([[9, 1, 0, 2], [9, 9, 0, 0], [0, 9, 1, 0], [0, 0, 1, 4]]); s = mv(s, 9, 1, 6, 1); ok('scout run marks the piece publicly', s.board[6][1].scout === true && s.board[6][1].moved === true); } // ── setup ───────────────────────────────────────────────────────────────────── section('setup'); { for (const variant of D.VARIANT_ORDER) { let s = L.createInitialState({ variant }); const tot = D.VARIANTS[variant].size; ok(`${variant}: tray starts full`, L.trayTotal(s, 0) === tot); s = L.setupPlace(s, 0, 9, 0, D.FLAG); ok(`${variant}: place flag`, s.board[9][0]?.rank === D.FLAG && L.trayTotal(s, 0) === tot - 1); ok(`${variant}: cannot place a second flag`, L.setupPlace(s, 0, 9, 1, D.FLAG) === s); ok(`${variant}: cannot place outside the zone`, L.setupPlace(s, 0, 5, 0, 2) === s); s = L.setupSwap(s, 0, L.keyOf(9, 0), L.keyOf(8, 3)); ok(`${variant}: move into an empty square`, s.board[8][3]?.rank === D.FLAG && !s.board[9][0]); s = L.setupRemove(s, 0, 8, 3); ok(`${variant}: remove returns to tray`, L.trayTotal(s, 0) === tot); s = L.setupFill(s, 0); ok(`${variant}: fill completes`, L.setupComplete(s, 0)); const lay = L.readLayout(s, 0); ok(`${variant}: read layout is valid`, L.layoutValid(lay, variant), lay); const s2 = L.applyLayout(L.createInitialState({ variant }), 1, lay); ok(`${variant}: layout mirrors onto seat 1`, L.readLayout(s2, 1) === lay); ok(`${variant}: cannot start until both deployed`, L.startBattle(s) === s); let s3 = L.applyLayout(s, 1, S.aiLayout(variant, 3)); s3 = L.startBattle(s3); ok(`${variant}: start battle`, s3.phase === 'play' && s3.current === 0); const ids = new Set(); for (const row of s3.board) for (const p of row) if (p) ids.add(p.id); ok(`${variant}: unique ids`, ids.size === tot * 2); for (const pr of S.presetsFor(variant)) { ok(`${variant}: preset ${pr.id} legal`, L.layoutValid(pr.layout, variant)); let good = true; for (let i = 0; i < 40; i++) if (!L.layoutValid(S.randomize(pr.layout), variant)) good = false; ok(`${variant}: preset ${pr.id} randomizations legal`, good); } for (let skill = 1; skill <= 5; skill++) ok(`${variant}: AI layout skill ${skill}`, L.layoutValid(S.aiLayout(variant, skill), variant)); } } // ── fuzz ────────────────────────────────────────────────────────────────────── section('fuzz: random games'); { const N = QUICK ? 200 : 1200; const reasons = {}; let bad = 0, replayBad = 0, jsonBad = 0; const rng = L.makeRng(12345); for (let g = 0; g < N; g++) { const variant = g % 3 === 0 ? 'barrage' : 'classic'; let s = L.createInitialState({ variant, reveal: g % 2 ? 'classic' : 'assisted', layouts: [S.randomLayout(variant, rng), S.aiLayout(variant, 1 + (g % 5))] }); s = L.startBattle(s); const start = s; let n = 0; while (s.phase === 'play' && n < 40000) { const ms = L.allLegalMoves(s, s.current); if (!ms.length) { bad++; break; } const m = ms[Math.floor(rng() * ms.length)]; const nx = L.applyMove(s, m.fr, m.fc, m.tr, m.tc); if (nx === s) { bad++; break; } s = nx; n++; if (g < 30 && n % 50 === 0) { const j = JSON.parse(JSON.stringify(s)); if (JSON.stringify(L.allLegalMoves(j, j.current)) !== JSON.stringify(L.allLegalMoves(s, s.current))) jsonBad++; } } reasons[s.endReason] = (reasons[s.endReason] ?? 0) + 1; if (s.phase === 'over' && s.endReason === 'flag' && s.winner == null) bad++; if (g < 40) { const st = L.replayStates(start, s.log); if (JSON.stringify(st.at(-1).board) !== JSON.stringify(s.board)) replayBad++; } // piece conservation for (let seat = 0; seat < 2; seat++) { if (L.aliveCount(s, seat) + s.captured[seat].length !== D.VARIANTS[variant].size) bad++; } } ok('random games end cleanly', bad === 0, `${bad} bad`); ok('every game ended', Object.keys(reasons).every((k) => k !== 'null' && k !== 'undefined'), JSON.stringify(reasons)); ok('JSON round-trip keeps the rules state', jsonBad === 0); ok('replay reproduces the final board', replayBad === 0); console.log(` endings: ${JSON.stringify(reasons)}`); } // ── AI ──────────────────────────────────────────────────────────────────────── section('AI'); { // never reads hidden ranks: give it a view, then scramble the hidden ranks // in the real state; the view (and thus the choice) can't change. let s = L.createInitialState({ layouts: [S.aiLayout('classic', 3, 1), S.aiLayout('classic', 3, 2)] }); s = L.startBattle(s); const v = L.viewFor(s, 1); let leak = false; for (const row of v.board) for (const p of row) if (p && p.owner === 0 && p.rank != null) leak = true; ok('view hides every unrevealed enemy rank', !leak); const a = AI.chooseMove(v, 4, { seed: 7 }); const b = AI.chooseMove(JSON.parse(JSON.stringify(v)), 4, { seed: 7 }); ok('AI is deterministic for a seed (view only)', a.fr === b.fr && a.fc === b.fc && a.tr === b.tr && a.tc === b.tc); ok('engine handle: move', !!handle('move', { view: L.viewFor({ ...s, current: 1 }, 1), skill: 3 })); ok('engine handle: hint', !!handle('hint', { view: L.viewFor(s, 0), ms: 200 })); const bel = handle('belief', { view: L.viewFor(s, 0), id: s.board[0][0].id }); ok('beliefs sum to 1', bel && Math.abs(bel.reduce((t, e) => t + e.p, 0) - 1) < 1e-6); // legal + timed over full games let illegal = 0, slow = 0, maxMs = 0; const games = QUICK ? 2 : 4; for (let g = 0; g < games; g++) { let st = L.startBattle(L.createInitialState({ variant: g % 2 ? 'barrage' : 'classic', reveal: g % 2 ? 'classic' : 'assisted', layouts: [S.aiLayout(g % 2 ? 'barrage' : 'classic', 5), S.aiLayout(g % 2 ? 'barrage' : 'classic', 2)] })); while (st.phase === 'play') { const skill = st.current === 0 ? 5 : 2; const t = Date.now(); const m = AI.chooseMove(L.viewFor(st, st.current), skill); const dt = Date.now() - t; maxMs = Math.max(maxMs, dt); if (dt > AI.SKILL[skill].ms * 2 + 200) slow++; const n = L.applyMove(st, m.fr, m.fc, m.tr, m.tc); if (n === st) { illegal++; break; } st = n; } } ok('AI moves are always legal', illegal === 0); ok('AI stays inside its time budget', slow === 0, `max ${maxMs}ms`); // ladder: mirrored pairs (same deployments, seats swapped) const ladder = QUICK ? [[3, 1, 4]] : [[2, 1, 8], [3, 1, 8], [4, 2, 8], [5, 3, 6]]; for (const [hi, lo, pairs] of ladder) { let hiW = 0, loW = 0; for (let i = 0; i < pairs; i++) { const variant = 'classic'; // Barrage (8 units) is too luck-heavy to rank skills const L0 = S.aiLayout(variant, 4, 1000 + i), L1 = S.aiLayout(variant, 4, 2000 + i); for (const swap of [false, true]) { const skills = swap ? [lo, hi] : [hi, lo]; let st = L.startBattle(L.createInitialState({ variant, layouts: swap ? [L1, L0] : [L0, L1] })); while (st.phase === 'play') { const m = AI.chooseMove(L.viewFor(st, st.current), skills[st.current]); st = L.applyMove(st, m.fr, m.fc, m.tr, m.tc); } if (st.winner != null) { if (skills[st.winner] === hi) hiW++; else loW++; } } } ok(`skill ${hi} beats skill ${lo}`, hiW > loW, `${hiW}-${loW}`); console.log(` skill ${hi} vs ${lo}: ${hiW}-${loW}`); } } // ── layout ──────────────────────────────────────────────────────────────────── section('layout'); { const R = LAY.HUD_RECTS; const on = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= LAY.W && r.y + r.h <= LAY.H; const hit = (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 names = Object.keys(R); for (const n of names) ok(`${n} on screen`, on(R[n]), JSON.stringify(R[n])); for (let i = 0; i < names.length; i++) for (let j = i + 1; j < names.length; j++) { ok(`${names[i]} clear of ${names[j]}`, !hit(R[names[i]], R[names[j]])); } const last = LAY.leftRowRect(11); ok('12 tracker rows fit the left column', last.y + last.h <= LAY.LEFT.y + LAY.LEFT.h); ok('cellAt inverts tileCenter', (() => { for (let r = 0; r < 10; r++) for (let c = 0; c < 10; c++) { const p = LAY.tileCenter(r, c); const q = LAY.cellAt(p.x, p.y); if (!q || q.r !== r || q.c !== c) return false; } return true; })()); } console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);