#!/usr/bin/env node // verifyAzul.js — headless checks for Azul: // • rules: lineAccepts edge cases, scorePlacement table, floor clamp, first- // player marker, end trigger + bonus breakdown, free-wall variant rules // • previewMove agrees with applyMove + resolveRound over random states // • all-AI soak across 2–4 players, both wall variants and mixed skills: every // game finishes, 100 tiles conserved after every step, scores add up // • tile-id tracker (AzulTiles) keeps one id per tile through whole games // • skill ladder: mirrored seats/seeds // • screen layout: furniture on screen, no overlaps, children inside parents // Usage: node tools/verifyAzul.js [--quick] import * as L from '../src/games/azul/AzulLogic.js'; import * as AI from '../src/games/azul/AzulAI.js'; import { COLORS, FLOOR_SIZE, lineCapacity, wallColumnFor, wallColor, } from '../src/games/azul/AzulData.js'; import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; import { TileTracker, TILE_COUNT, colorOfId } from '../src/games/azul/AzulTiles.js'; import { hudFurniture, furnitureChildren, onScreen, rectsOverlap, inside, circleRectOverlap, RING, } from '../src/games/azul/AzulLayout.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 totalTiles = (s) => { const c = L.tileCensus(s); return COLORS.reduce((n, k) => n + c[k].total, 0); }; // A blank player for direct rule tests. function blankPlayer() { return { seat: 0, name: 'T', score: 0, floor: [], lines: Array.from({ length: 5 }, () => ({ color: null, count: 0 })), wall: Array.from({ length: 5 }, () => Array(5).fill(false)), wallColors: Array.from({ length: 5 }, () => Array(5).fill(null)), stats: L.emptyStats(), }; } function setWall(p, row, col, color = wallColor(row, col)) { p.wall[row][col] = true; p.wallColors[row][col] = color; } // ── rules ─────────────────────────────────────────────────────────────────────── section('Rules'); { const p = blankPlayer(); ok('empty line accepts any colour', COLORS.every((c) => L.lineAccepts(p, 2, c))); p.lines[2] = { color: 'red', count: 1 }; ok('line holding red accepts red', L.lineAccepts(p, 2, 'red')); ok('line holding red rejects blue', !L.lineAccepts(p, 2, 'blue')); p.lines[0] = { color: 'blue', count: 1 }; ok('full line rejects', !L.lineAccepts(p, 0, 'blue')); setWall(p, 3, wallColumnFor(3, 'yellow')); ok('wall already has yellow in row 3 → rejects', !L.lineAccepts(p, 3, 'yellow')); ok('…but accepts black in row 3', L.lineAccepts(p, 3, 'black')); // Free wall: colour-in-row rule only. const q = blankPlayer(); setWall(q, 1, 0, 'red'); ok('free: row with red rejects red', !L.lineAccepts(q, 1, 'red', true)); ok('free: row with red accepts blue', L.lineAccepts(q, 1, 'blue', true)); setWall(q, 0, 3, 'blue'); ok('free: options exclude columns already holding the colour', JSON.stringify(L.wallOptions(q, 1, 'blue', true)) === JSON.stringify([1, 2, 4])); } { // scorePlacement table. const w = Array.from({ length: 5 }, () => Array(5).fill(false)); const at = (r, c) => { w[r][c] = true; return L.scorePlacement(w, r, c); }; ok('lone tile = 1', at(2, 2) === 1); ok('horizontal pair = 2', at(2, 3) === 2); ok('vertical join = 2', at(1, 2) === 2); ok('cross = h + v', at(1, 3) === 2 + 2, `${L.scorePlacement(w, 1, 3)}`); const run = L.placementRun(w, 1, 3); ok('placementRun covers both runs', run.cells.length === 3 && run.horizontal === 2 && run.vertical === 2); } { // First-player marker + floor clamp + scoring. let s = L.createInitialState({ playerCount: 2, seed: 7 }); s.factories[0] = ['red', 'red', 'blue', 'blue']; s.current = 0; s = L.applyMove(s, { source: { type: 'factory', index: 0 }, color: 'red', line: 0 }); ok('leftovers go to the centre', s.center.filter((t) => t === 'blue').length === 2); ok('overflow hits the floor', s.players[0].floor.length === 1 && s.lastMove.overflow === 1); s = L.applyMove(s, { source: { type: 'center' }, color: 'blue', line: 1 }); ok('first centre take gets the marker', s.players[1].floor[0] === 'first' && !s.centerHasFirst && s.startPlayer === 1); ok('stats count the marker', s.players[1].stats.firstTaken === 1); } { // End trigger + bonus breakdown. let s = L.createInitialState({ playerCount: 2, seed: 11 }); const p = s.players[0]; for (let c = 0; c < 4; c++) setWall(p, 0, c); for (let r = 1; r < 5; r++) setWall(p, r, 0); // column 0 complete with (0,0) p.lines[0] = { color: wallColor(0, 4), count: 1 }; s.factories = s.factories.map(() => []); s.center = []; s.centerHasFirst = false; s.phase = 'scoring'; const r = L.resolveRound(s); ok('completing a row ends the game', r.phase === 'gameOver'); const b = r.roundSummary[0].endBonuses; ok('row bonus counted', b.rows.length === 1 && b.rowPts === 2); ok('column bonus counted', b.cols.length === 1 && b.colPts === 7); const st = r.players[0].stats; ok('stats add up to the score', st.placementPts - st.floorLost + st.bonusPts === r.players[0].score, `${st.placementPts}-${st.floorLost}+${st.bonusPts} vs ${r.players[0].score}`); } { // Floor clamp. let s = L.createInitialState({ playerCount: 2, seed: 3 }); s.players[0].floor = ['red', 'red', 'red', 'red']; s.players[0].score = 2; s.factories = s.factories.map(() => []); s.center = []; s.centerHasFirst = false; s.phase = 'scoring'; const r = L.resolveRound(s); ok('floor penalty clamps at zero', r.players[0].score === 0 && r.roundSummary[0].floorLost === 2 && r.roundSummary[0].floorPenalty === -6); } { // Free wall: dump when nowhere to go, choices respected. let s = L.createInitialState({ playerCount: 2, seed: 5, variant: 'free' }); const p = s.players[0]; setWall(p, 0, 0, 'blue'); setWall(p, 2, 1, 'red'); setWall(p, 3, 2, 'red'); setWall(p, 4, 3, 'red'); // Row 1 has cells 1..4 free; red is already in columns 1,2,3 → only column 4. p.lines[1] = { color: 'red', count: 2 }; // Row 0: blue present → line for yellow, choose column 2. p.lines[0] = { color: 'yellow', count: 1 }; s.factories = s.factories.map(() => []); s.center = []; s.centerHasFirst = false; s.phase = 'scoring'; const r = L.resolveRound(s, { 0: { 0: 2, 1: 1 } }); // column 1 already holds red const pl = r.roundSummary[0].placements; ok('free: chosen column used', pl.find((x) => x.row === 0)?.col === 2); ok('free: illegal choice falls back to the best legal column', pl.find((x) => x.row === 1)?.col === 0); // Now a dump case. let s2 = L.createInitialState({ playerCount: 2, seed: 6, variant: 'free' }); const q = s2.players[0]; for (let c = 0; c < 4; c++) setWall(q, c + 1, c, 'black'); // black in columns 0..3 setWall(q, 0, 4, 'red'); // row 0 col 4 taken q.lines[0] = { color: 'black', count: 1 }; s2.factories = s2.factories.map(() => []); s2.center = []; s2.centerHasFirst = false; s2.phase = 'scoring'; const before2 = totalTiles(s2); const r2 = L.resolveRound(s2); ok('free: unplaceable line is dumped to the floor', r2.roundSummary[0].dumped.length === 1 && r2.roundSummary[0].floorPenalty === -1); ok('free: dump conserves tiles', totalTiles(r2) === before2); } // ── previewMove vs reality ──────────────────────────────────────────────────── section('previewMove agrees with applyMove + resolveRound'); { const rnd = seedRandom(42); let checked = 0, bad = 0; for (let g = 0; g < (QUICK ? 30 : 120); g++) { const variant = g % 3 === 2 ? 'free' : 'standard'; let s = L.createInitialState({ playerCount: 2 + (g % 3), seed: 1000 + g, variant }); let guard = 0; while (s.phase !== 'gameOver' && guard++ < 400) { if (s.phase === 'scoring') { s = L.resolveRound(s); continue; } const moves = L.legalMoves(s); const m = moves[Math.floor(rnd() * moves.length)]; const pv = L.previewMove(s, m); const seat = s.current; const before = s.players[seat]; const after = L.applyMove(s, m); const pa = after.players[seat]; checked++; const floorBefore = before.floor.length; const okTake = pv.taken === after.lastMove.taken && pv.placed === after.lastMove.placed && pv.overflow === after.lastMove.overflow; const okFloor = pa.floor.length === floorBefore + pv.floorSlots.length; let okPts = true; if (pv.completes && variant === 'standard') { // Clear other lines below so only this line (and full lines above it) tile. const t = JSON.parse(JSON.stringify(after)); t.factories = t.factories.map(() => []); t.center = []; t.phase = 'scoring'; const tp = t.players[seat]; for (let i = m.line + 1; i < 5; i++) tp.lines[i] = { color: null, count: 0 }; const r = L.resolveRound(t); const pl = r.roundSummary[seat].placements.find((x) => x.row === m.line); okPts = !!pl && pl.points === pv.wallPoints && pl.col === pv.wallCol; } if (!(okTake && okFloor && okPts)) { bad++; if (bad <= 3) console.error(' preview mismatch', JSON.stringify({ m, pv, last: after.lastMove })); } s = after; } } ok(`previewMove matches (${checked} random moves)`, bad === 0, `${bad} mismatches`); } // ── AI soak ───────────────────────────────────────────────────────────────────── function playGame({ players = 4, skills = null, seed = 1, variant = 'standard', onStep = null, maxSteps = 600 } = {}) { let s = L.createInitialState({ playerCount: players, seed, variant, names: Array.from({ length: players }, (_, i) => `P${i}`) }); const skillOf = (seat) => (skills ? skills[seat] : 3); const problems = []; let steps = 0; const check = () => { const t = totalTiles(s); if (t !== 100) problems.push(`tiles ${t} != 100 (round ${s.round})`); for (const p of s.players) { if (p.score < 0) problems.push(`seat ${p.seat} negative score`); if (p.floor.length > FLOOR_SIZE) problems.push('floor overfull'); for (let i = 0; i < 5; i++) if (p.lines[i].count > lineCapacity(i)) problems.push('line overfull'); for (let r = 0; r < 5; r++) { const seen = new Set(); for (let c = 0; c < 5; c++) { const col = L.cellColor(p, r, c); if (col) { if (seen.has(col)) problems.push('colour repeated in a row'); seen.add(col); } } } for (let c = 0; c < 5; c++) { const seen = new Set(); for (let r = 0; r < 5; r++) { const col = L.cellColor(p, r, c); if (col) { if (seen.has(col)) problems.push('colour repeated in a column'); seen.add(col); } } } } }; while (s.phase !== 'gameOver' && steps++ < maxSteps) { if (s.phase === 'scoring') { const choices = {}; for (const p of s.players) choices[p.seat] = AI.chooseWallColumns(s, p.seat, skillOf(p.seat)); s = L.resolveRound(s, choices); } else { const m = AI.chooseMove(s, skillOf(s.current)); if (!m) { problems.push('AI returned no move'); break; } if (!L.isLegalMove(s, m)) problems.push(`illegal AI move ${JSON.stringify(m)}`); s = L.applyMove(s, m); } onStep?.(s); check(); if (problems.length) break; } if (s.phase !== 'gameOver') problems.push(`did not finish (${steps} steps, round ${s.round})`); if (s.phase === 'gameOver') { for (const p of s.players) { const st = p.stats; if (st.placementPts - st.floorLost + st.bonusPts !== p.score) problems.push(`seat ${p.seat} stats don't add up`); if (st.roundScores[st.roundScores.length - 1] !== p.score) problems.push(`seat ${p.seat} roundScores end != score`); } } return { s, problems, steps }; } section('All-AI soak'); { seedRandom(9); const N = QUICK ? 60 : 240; let finished = 0, rounds = 0, issues = 0; const scoreSum = { 2: 0, 3: 0, 4: 0 }, games = { 2: 0, 3: 0, 4: 0 }; const t0 = Date.now(); for (let g = 0; g < N; g++) { const players = 2 + (g % 3); const variant = g % 4 === 3 ? 'free' : 'standard'; const skills = Array.from({ length: players }, (_, i) => 1 + ((g + i * 2) % 5)); const { s, problems } = playGame({ players, skills, seed: 5000 + g, variant }); if (problems.length) { issues++; if (issues <= 5) console.error(` game ${g}: ${problems.slice(0, 3).join('; ')}`); } if (s.phase === 'gameOver') { finished++; rounds += s.round; } for (const p of s.players) scoreSum[players] += p.score; games[players] += players; } ok(`${N} games finish cleanly`, issues === 0 && finished === N, `${issues} with problems, ${finished} finished`); console.log(` avg rounds ${(rounds / Math.max(1, finished)).toFixed(2)} · avg score 2p ${(scoreSum[2] / games[2]).toFixed(1)} 3p ${(scoreSum[3] / games[3]).toFixed(1)} 4p ${(scoreSum[4] / games[4]).toFixed(1)} · ${((Date.now() - t0) / N).toFixed(0)} ms/game`); } // ── skill ladder ───────────────────────────────────────────────────────────── function ladder(a, b, pairs, players = 2) { let winsA = 0, games = 0, marginA = 0; for (let i = 0; i < pairs; i++) { for (const flip of [false, true]) { seedRandom(77 + i * 2 + (flip ? 1 : 0)); const skills = Array.from({ length: players }, (_, k) => (k === 0) !== flip ? a : b); const { s } = playGame({ players, skills, seed: 9000 + i }); const rank = L.finalRanking(s); const seatA = flip ? 1 : 0; if (rank[0].seat === seatA) winsA++; const sa = s.players[seatA].score; const others = s.players.filter((p) => p.seat !== seatA).map((p) => p.score); marginA += sa - Math.max(...others); games++; } } return { rate: winsA / games, margin: marginA / games, games }; } section('Skill ladder (mirrored seats + seeds, 2 players)'); { const P = QUICK ? 20 : 80; const t0 = Date.now(); const l31 = ladder(3, 1, P); const l53 = ladder(5, 3, P); const l43 = ladder(4, 3, P); const l54 = ladder(5, 4, P); const l21 = ladder(2, 1, P); const l32 = ladder(3, 2, P); console.log(` 2 vs 1: ${(l21.rate * 100).toFixed(0)}% (margin ${l21.margin.toFixed(1)})`); console.log(` 3 vs 2: ${(l32.rate * 100).toFixed(0)}% (margin ${l32.margin.toFixed(1)})`); console.log(` 3 vs 1: ${(l31.rate * 100).toFixed(0)}% (margin ${l31.margin.toFixed(1)})`); console.log(` 4 vs 3: ${(l43.rate * 100).toFixed(0)}% (margin ${l43.margin.toFixed(1)})`); console.log(` 5 vs 4: ${(l54.rate * 100).toFixed(0)}% (margin ${l54.margin.toFixed(1)})`); console.log(` 5 vs 3: ${(l53.rate * 100).toFixed(0)}% (margin ${l53.margin.toFixed(1)}) [${((Date.now() - t0) / 1000).toFixed(1)}s]`); ok('skill 3 beats skill 1 ≥ 70%', l31.rate >= 0.7, `${(l31.rate * 100).toFixed(0)}%`); ok('skill 5 beats skill 3 ≥ 58%', l53.rate >= 0.58, `${(l53.rate * 100).toFixed(0)}%`); ok('skill 4 out-scores skill 3', l43.margin > 0, `${l43.margin.toFixed(1)}`); } // ── tile-id tracker ───────────────────────────────────────────────────────────── section('Tile tracker (stable sprite ids)'); { seedRandom(21); let games = 0, bad = 0, steps = 0, needless = 0; for (let g = 0; g < (QUICK ? 12 : 40); g++) { const players = 2 + (g % 3); let tracker = null; const check = (s, changes) => { steps++; // Every container holds exactly the colours the state says. const c = tracker.counts(); const cen = L.tileCensus(s); for (const col of COLORS) { const inBag = tracker.idsIn('bag').filter((id) => colorOfId(id) === col).length; const inLid = tracker.idsIn('lid').filter((id) => colorOfId(id) === col).length; if (inBag !== cen[col].bag || inLid !== cen[col].lid) { bad++; return; } } s.factories.forEach((f, i) => { const ids = tracker.idsIn(`f${i}`); if (ids.map(colorOfId).join() !== f.join()) bad++; }); for (const p of s.players) { for (let r = 0; r < 5; r++) { const ids = tracker.idsIn(`l${p.seat}.${r}`); if (ids.length !== p.lines[r].count || ids.some((id) => colorOfId(id) !== p.lines[r].color)) bad++; } const fl = tracker.idsIn(`fl${p.seat}`); if (fl.length !== p.floor.filter((t) => t !== 'first').length) bad++; } const total = Object.values(c).reduce((a, b) => a + b, 0); if (total !== TILE_COUNT) bad++; // Wall tiles never move once set. for (const ch of changes ?? []) if (ch.from.kind === 'wall') needless++; }; playGame({ players, seed: 700 + g, variant: g % 2 ? 'free' : 'standard', skills: Array.from({ length: players }, () => 3), onStep: (s) => { if (!tracker) { tracker = new TileTracker(s); check(s, []); return; } check(s, tracker.sync(s)); }, }); games++; } ok(`tracker matches the engine after every step (${games} games, ${steps} steps)`, bad === 0, `${bad} mismatches`); ok('wall tiles never move', needless === 0, `${needless}`); { // A single take moves exactly the taken tiles plus the leftovers. let s = L.createInitialState({ playerCount: 3, seed: 4 }); const t = new TileTracker(s); s.factories[0] = s.factories[0]; const f0 = s.factories[0]; const color = f0[0]; const ch = t.sync(L.applyMove(s, { source: { type: 'factory', index: 0 }, color, line: 'floor' })); ok('a take moves only that plate\'s four tiles', ch.filter((c) => c.moved).length === f0.length && ch.every((c) => c.fromKey === 'f0'), ch.map((c) => `${c.fromKey}->${c.toKey}`).join(' ')); } } // ── layout ────────────────────────────────────────────────────────────────────── section('Screen layout'); for (const players of [2, 3, 4]) { const f = hudFurniture({ players }); for (const r of f) ok(`${players}p ${r.name} on screen`, onScreen(r), JSON.stringify(r)); const isPlate = (r) => r.name.startsWith('plate'); for (let i = 0; i < f.length; i++) for (let j = i + 1; j < f.length; j++) { const a = f[i], b = f[j]; if (a.overlapOk?.includes(b.name) || b.overlapOk?.includes(a.name)) continue; let hit; if (isPlate(a) && isPlate(b)) { const ca = { x: a.x + a.w / 2, y: a.y + a.h / 2 }, cb = { x: b.x + b.w / 2, y: b.y + b.h / 2 }; hit = Math.hypot(ca.x - cb.x, ca.y - cb.y) < RING.r * 2 + 4; } else if (isPlate(a)) hit = circleRectOverlap(a.x + a.w / 2, a.y + a.h / 2, RING.r, b); else if (isPlate(b)) hit = circleRectOverlap(b.x + b.w / 2, b.y + b.h / 2, RING.r, a); else hit = rectsOverlap(a, b); ok(`${players}p ${a.name} clear of ${b.name}`, !hit, `${JSON.stringify(a)} ${JSON.stringify(b)}`); } const byName = new Map(f.map((r) => [r.name, r])); for (const k of furnitureChildren({ players })) { const p = byName.get(k.parent); ok(`${players}p ${k.name} inside ${k.parent}`, !!p && inside(k, p), `${JSON.stringify(k)} in ${JSON.stringify(p)}`); } } console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);