From 5ef0a7c848ad938bf6ed24127c0c3663082d692c Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Tue, 1 Dec 2026 22:12:01 -0700 Subject: [PATCH] Rework Stratego as Fog of War with sci-fi theme and belief-based AI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace the single-file game with a modular command-deck scene: art, pieces, HUD, battle cinematics, dialogs, end screen, talk, sound, layout, and a worker-threaded AI engine. - Rewrite the AI around a belief-distribution model: sample worlds from per-piece rank probabilities (priors from origin + behavioural evidence), then rollout with expectiminimax; skill scales samples, depth, blunder rate, and battle-memory half-life. - Add two game variants (Classic 40-unit, Barrage 8-unit), two reveal modes (Assisted / Classic), and three battle-speed presets. - Implement ISF fair-play rules (two-square and chase), Scout long moves, and per-piece public marks (moved, scout-run). - Add a deployment phase with a Barracks tray, six built-in formations per variant, three player-saved slots, and an auto-fill heuristic; persist layouts and full game state to localStorage for resume. - Add an engagement cinematic with skippable stage, inline clash, and per-outcome effects (bomb, flag, mutual, standard). - Add opponent comm lines per skill tier, Web Audio ambience and SFX, and a full tutorial (tutorial.md). - Add tools/verifyStratego.js: headless tests for combat, movement, repetition rules, reveal safety, setup, fuzzed games, AI legality and skill ladder, and HUD layout. - Fix "Zahtzee" → "Yahtzee" in the game registry and enable the Stratego tutorial flag. --- src/data/gamesRegistry.js | 4 +- src/games/stratego/StrategoAI.js | 611 ++++++-- src/games/stratego/StrategoArt.js | 465 ++++++ src/games/stratego/StrategoBattle.js | 268 ++++ src/games/stratego/StrategoData.js | 153 +- src/games/stratego/StrategoDialogs.js | 273 ++++ src/games/stratego/StrategoEndScreen.js | 85 + src/games/stratego/StrategoEngine.js | 76 + src/games/stratego/StrategoGame.js | 1909 +++++++++++++---------- src/games/stratego/StrategoHud.js | 308 ++++ src/games/stratego/StrategoLayout.js | 55 + src/games/stratego/StrategoLogic.js | 669 +++++--- src/games/stratego/StrategoPieces.js | 138 ++ src/games/stratego/StrategoSetups.js | 159 ++ src/games/stratego/StrategoSound.js | 207 +++ src/games/stratego/StrategoTalk.js | 69 + src/games/stratego/StrategoWorker.js | 11 + src/games/stratego/tutorial.md | 105 ++ tools/verifyStratego.js | 297 ++++ 19 files changed, 4587 insertions(+), 1275 deletions(-) create mode 100644 src/games/stratego/StrategoArt.js create mode 100644 src/games/stratego/StrategoBattle.js create mode 100644 src/games/stratego/StrategoDialogs.js create mode 100644 src/games/stratego/StrategoEndScreen.js create mode 100644 src/games/stratego/StrategoEngine.js create mode 100644 src/games/stratego/StrategoHud.js create mode 100644 src/games/stratego/StrategoLayout.js create mode 100644 src/games/stratego/StrategoPieces.js create mode 100644 src/games/stratego/StrategoSetups.js create mode 100644 src/games/stratego/StrategoSound.js create mode 100644 src/games/stratego/StrategoTalk.js create mode 100644 src/games/stratego/StrategoWorker.js create mode 100644 src/games/stratego/tutorial.md create mode 100644 tools/verifyStratego.js diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 4475d55..9735ba8 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -31,7 +31,7 @@ registerGame({ slug: 'backgammon', name: 'Backgammon', category: 'tabletop', min registerGame({ slug: 'parchisi', name: 'Parchisi', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, defaultOpponents: 3, hasTutorial: true, iconFrame: 1 }); registerGame({ slug: 'blackjack', name: 'Blackjack', category: 'casino', cardGame: true, minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 2 }); registerGame({ slug: 'holdem', name: "Texas Hold 'Em", category: 'casino', cardGame: true, minPlayers: 2, maxPlayers: 8, minOpponents: 3, maxOpponents: 7, iconFrame: 3 }); -registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 4 }); +registerGame({ slug: 'yatzi', name: 'Yahtzee', category: 'cards', minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 4 }); registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 }); registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 }); registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 2, maxPlayers: 6, minOpponents: 1, maxOpponents: 5, defaultOpponents: 5, hasTutorial: true, iconFrame: 7 }); @@ -73,7 +73,7 @@ registerGame({ slug: 'splendor', name: 'Splendor', category: 'cards', cardGame: registerGame({ slug: 'labyrinth', name: 'Labyrinth', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 43, defaultPlayfield: 'fantasy' }); registerGame({ slug: 'videopoker', name: 'Video Poker', category: 'casino', cardGame: true, minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 44 }); registerGame({ slug: 'farkel', name: 'Farkle', category: 'cards', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 45 }); -registerGame({ slug: 'stratego', name: 'Stratego', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: false, iconFrame: 46, defaultPlayfield: 'combat' }); +registerGame({ slug: 'stratego', name: 'Stratego', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 46 }); registerGame({ slug: 'kiitos', name: 'Kiitos', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 47 }); registerGame({ slug: 'monopoly', name: 'Monopoly', category: 'tabletop', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, defaultOpponents: 3, hasTutorial: true, iconFrame: 48 }); registerGame({ slug: 'triominoes', name: 'Tri-Ominoes', category: 'word', minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 49 }); diff --git a/src/games/stratego/StrategoAI.js b/src/games/stratego/StrategoAI.js index d18d461..7ca2dda 100644 --- a/src/games/stratego/StrategoAI.js +++ b/src/games/stratego/StrategoAI.js @@ -1,171 +1,498 @@ -// Stratego — heuristic opponent. No Phaser, no timers. It evaluates every legal -// move for one ply and scores it with a material + position + information model. +// Fog of War: the opposing commander. Pure (no Phaser, no timers); runs in a +// worker through StrategoEngine. // -// Hidden information is the heart of it: the AI knows its own pieces, sees -// revealed enemies, and for the rest reasons over the *distribution* of enemy -// ranks still unaccounted for (full army − captured − currently-revealed). A -// piece that has moved can't be a Bomb or Flag, which sharpens the estimate. -// Skill 1–5 scales lookahead breadth, blunder rate, and pacing like the other AIs. +// It only ever reads a viewer-safe snapshot (StrategoLogic.viewFor): its own +// ranks, the enemy ranks it is allowed to see, and public facts (who has +// moved, known scouts, where pieces started, the battle record). +// +// 1. Beliefs. Each hidden enemy piece gets a probability for every rank +// still unaccounted for. Priors come from where it started (flags and +// bombs live at the back), then evidence: a piece that has moved is no +// Bomb or Flag; one that ran more than a square is a Scout; one that +// stepped up to a piece of ours the enemy knows is probably stronger, +// one that backed away is probably weaker. The table is then balanced +// so each rank's column adds up to how many of that rank remain. +// 2. Sampled worlds. A handful of full guesses are drawn from the beliefs. +// 3. Rollouts. In each world, every legal move is played and followed by a +// few plies where each side picks the move that looks best *from what +// that side knows* (the enemy can't see our hidden ranks, so it judges +// attacks on them by expectation; we judge attacks on theirs by our +// beliefs) while the score counts what actually happens in that world. +// That is what makes bluffs work: an unknown piece is scary to attack. +// 4. The move with the best average across worlds wins, with skill-scaled +// noise and the occasional blunder for the weaker commanders. +// +// In 'classic' reveal mode the AI must remember battle results like you do; +// weaker commanders forget them over time. import { - GRID, FLAG, BOMB, SPY, SCOUT, MARSHAL, buildArmy, battleResult, - canMove, forwardDir, + GRID, FLAG, BOMB, SPY, SCOUT, MINER, MARSHAL, battleResult, canMove, + isLake, variantOf, lineOf, colOf, } from './StrategoData.js'; -import { allLegalMoves } from './StrategoLogic.js'; +import { allLegalMoves, makeRng, keyOf } from './StrategoLogic.js'; -const SKILL_PROFILES = { - 1: { topN: 8, blunder: 0.42, noise: 60, delay: [700, 1200] }, - 2: { topN: 5, blunder: 0.26, noise: 38, delay: [650, 1100] }, - 3: { topN: 3, blunder: 0.14, noise: 22, delay: [600, 1000] }, - 4: { topN: 2, blunder: 0.05, noise: 10, delay: [520, 900] }, - 5: { topN: 1, blunder: 0.00, noise: 4, delay: [440, 820] }, +export const SKILL = { + 1: { samples: 3, depth: 1, blunder: 0.28, noise: 40, halfLife: 8, ms: 160, delay: [700, 1200] }, + 2: { samples: 6, depth: 2, blunder: 0.14, noise: 22, halfLife: 18, ms: 260, delay: [650, 1100] }, + 3: { samples: 12, depth: 2, blunder: 0.06, noise: 10, halfLife: 45, ms: 420, delay: [600, 1000] }, + 4: { samples: 24, depth: 3, blunder: 0.02, noise: 4, halfLife: 140, ms: 650, delay: [520, 900] }, + 5: { samples: 40, depth: 3, blunder: 0, noise: 1, halfLife: Infinity, ms: 950, delay: [440, 820] }, }; -function profileFor(skill) { return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3]; } - +export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3))); +export function profileFor(skill) { return SKILL[clampSkill(skill)]; } export function nextThinkDelay(skill) { const [lo, hi] = profileFor(skill).delay; return lo + Math.random() * (hi - lo); } -// Rough piece worth for the evaluator (Flag handled separately as a win). -const VALUE = { - [FLAG]: 10000, [BOMB]: 70, - 1: 60, // Spy — kills the Marshal - 2: 25, // Scout - 3: 60, // Miner — defuses bombs - 4: 40, // Sergeant - 5: 55, // Lieutenant - 6: 80, // Captain - 7: 120, // Major - 8: 170, // Colonel - 9: 300, // General - [MARSHAL]: 450, -}; -const val = (rank) => VALUE[rank] ?? 50; -const WIN = 1e7; +const RANK_LIST = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; +const MOVABLE = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +const WIN = 1e5; +const BASE_VAL = { [FLAG]: 0, [BOMB]: 25, 1: 70, 2: 22, 3: 45, 4: 30, 5: 45, 6: 65, 7: 100, 8: 150, 9: 260, [MARSHAL]: 400 }; +const INFO = { [FLAG]: 0, [BOMB]: 6, 1: 30, 2: 1, 3: 4, 4: 3, 5: 4, 6: 6, 7: 10, 8: 18, 9: 34, [MARSHAL]: 55 }; +const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; +const LAKE = (() => { const a = new Uint8Array(100); for (let k = 0; k < 100; k++) a[k] = isLake(Math.floor(k / 10), k % 10) ? 1 : 0; return a; })(); +const md = (a, b) => Math.abs(Math.floor(a / 10) - Math.floor(b / 10)) + Math.abs((a % 10) - (b % 10)); -// Value swing of moverRank attacking a known defenderRank, from mover's view. -function knownAttackValue(moverRank, defenderRank) { - if (defenderRank === FLAG) return WIN; - const res = battleResult(moverRank, defenderRank); - if (res === 'attacker') return val(defenderRank); - if (res === 'defender') return -val(moverRank); - return val(defenderRank) - val(moverRank); // mutual loss +// Deterministic 0..1 hash (memory decay must not flicker turn to turn). +function hash01(a, b) { + let h = Math.imul(a ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(b + 0x632be5ab, 0xc2b2ae35); + h ^= h >>> 15; h = Math.imul(h, 0x2c1b3c6d); h ^= h >>> 12; + return ((h >>> 0) % 100000) / 100000; } -// The multiset of enemy ranks that are still on the board but unrevealed: -// full army − pieces the enemy has lost − enemy pieces currently shown. -function unknownEnemyCounts(state, enemy) { - const counts = {}; - for (const r of buildArmy()) counts[r] = (counts[r] ?? 0) + 1; - for (const r of state.captured[enemy]) counts[r] = (counts[r] ?? 0) - 1; - for (let r = 0; r < GRID; r++) { - for (let c = 0; c < GRID; c++) { - const p = state.board[r][c]; - if (p && p.owner === enemy && p.revealed) counts[p.rank] = (counts[p.rank] ?? 0) - 1; +// ── 1. what we know ─────────────────────────────────────────────────────────── +export function analyze(view, skill = 3) { + const prof = profileFor(skill); + const me = view.viewer, op = 1 - me; + const counts = variantOf(view.variant).counts; + const barrage = view.variant === 'barrage'; + + // Battle memory (classic mode keeps ranks out of the board; the log has them). + const seen = new Map(); // enemy piece id → { rank, ply } + for (const e of view.log) { + if (!e.attack) continue; + if (e.seat === op && e.result === 'attacker') seen.set(e.id, { rank: e.aRank, ply: e.ply }); + if (e.seat === me && e.result === 'defender') seen.set(e.defId, { rank: e.dRank, ply: e.ply }); + } + const recalls = (id, ply) => { + if (view.reveal !== 'classic' || prof.halfLife === Infinity) return true; + const age = view.ply - ply; + return hash01(id, ply) < Math.pow(0.5, age / prof.halfLife); + }; + + const mine = [], foes = []; + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = view.board[r][c]; + if (!p) continue; + const sq = r * 10 + c; + if (p.owner === me) mine.push({ id: p.id, sq, rank: p.rank, moved: p.moved, knownToFoe: p.knownToFoe }); + else { + let rank = p.rank; + if (rank == null && p.scout) rank = SCOUT; + if (rank == null && seen.has(p.id)) { const m = seen.get(p.id); if (recalls(p.id, m.ply)) rank = m.rank; } + foes.push({ id: p.id, sq, rank, moved: p.moved, scout: p.scout, origin: p.origin }); } } - for (const k of Object.keys(counts)) if (counts[k] <= 0) delete counts[k]; - return counts; -} -// Expected value of attacking an *unknown* enemy, averaged over its possible -// ranks. A target that has already moved can be neither a Bomb nor a Flag. -function expectedAttackValue(moverRank, counts, targetHasMoved) { - let total = 0, weight = 0; - for (const k of Object.keys(counts)) { - const rank = Number(k); - if (targetHasMoved && (rank === BOMB || rank === FLAG)) continue; - const w = counts[k]; - total += w * knownAttackValue(moverRank, rank); - weight += w; - } - if (weight === 0) return knownAttackValue(moverRank, MARSHAL) * 0.5; // shouldn't happen - return total / weight; -} + // Ranks still hidden among the enemy pieces. + const rem = {}; + for (const k of RANK_LIST) rem[k] = counts[k] ?? 0; + for (const k of view.captured[op]) rem[k]--; + for (const f of foes) if (f.rank != null) rem[f.rank]--; + for (const k of RANK_LIST) if (rem[k] < 0) rem[k] = 0; + const hidden = foes.filter((f) => f.rank == null); -const hasMoved = (p) => p.lastSquare !== null; - -// Threat estimate: value we'd expect to lose if our piece sits at (r,c) and an -// adjacent enemy attacks it next turn. Uses known ranks where possible. -function squareThreat(state, seat, r, c, moverRank, counts) { - const enemy = 1 - seat; - let worst = 0; - for (const [dr, dc] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) { - const nr = r + dr, nc = c + dc; - if (nr < 0 || nr >= GRID || nc < 0 || nc >= GRID) continue; - const occ = state.board[nr][nc]; - if (!occ || occ.owner !== enemy || !canMove(occ.rank)) continue; - // From the enemy's perspective they'd be attacking our (known to them only - // if we're revealed) piece; we just estimate the danger to us. - let loss; - if (occ.revealed) { - const res = battleResult(occ.rank, moverRank); - loss = res === 'attacker' ? val(moverRank) : res === 'both' ? val(moverRank) * 0.5 : 0; - } else { - // Unknown attacker: chance it outranks us, weighted across the distribution. - let bad = 0, wt = 0; - for (const k of Object.keys(counts)) { - const rank = Number(k); - if (rank === BOMB || rank === FLAG) continue; // can't attack us - const res = battleResult(rank, moverRank); - bad += counts[k] * (res === 'attacker' ? 1 : res === 'both' ? 0.5 : 0); - wt += counts[k]; + // Priors + evidence. + const recent = []; + for (let i = view.log.length - 1; i >= 0 && recent.length < 12; i--) if (view.log[i].seat === op) recent.push(view.log[i]); + const myAt = new Map(mine.map((m) => [m.sq, m])); + const W = hidden.map((f) => { + const w = {}; + const li = Math.max(0, Math.min(3, lineOf(op, Math.floor(f.origin / 10)))); + const cc = colOf(op, f.origin % 10); + const edge = Math.min(cc, 9 - cc) <= 1; + for (const k of RANK_LIST) { + if (!rem[k]) continue; + let x = 1; + if (!barrage) { + if (k === FLAG) x = [0.12, 0.4, 1.5, 6][li] * (edge ? 1.4 : 1); + else if (k === BOMB) x = [0.9, 1, 1.6, 2][li]; + else if (k === SCOUT) x = [1.6, 1.2, 0.9, 0.7][li]; + else if (k === MINER) x = [0.7, 1, 1.2, 1.2][li]; + else if (k === SPY) x = [0.4, 1.1, 1.3, 1][li]; + else if (k >= 9) x = [0.8, 1, 1.1, 0.9][li]; + } else if (k === FLAG) x = [0.5, 0.8, 1.1, 1.6][li]; + if (f.moved && (k === FLAG || k === BOMB)) x = 0; + w[k] = x; + } + // Behaviour around our pieces the enemy can see. + for (const e of recent) { + if (e.id !== f.id || e.attack || keyOf(e.tr, e.tc) !== f.sq) continue; + for (const [dr, dc] of DIRS) { + const nr = e.tr + dr, nc = e.tc + dc; + const m = nr >= 0 && nr < 10 && nc >= 0 && nc < 10 ? myAt.get(nr * 10 + nc) : null; + if (!m || !m.knownToFoe || !canMove(m.rank)) continue; + if (Math.abs(e.fr - nr) + Math.abs(e.fc - nc) === 1) continue; // was already touching + for (const k of MOVABLE) if (w[k]) { + const beats = battleResult(k, m.rank) === 'attacker'; + w[k] *= beats ? 3 : k === m.rank ? 0.8 : 0.35; + } + } + for (const m of mine) { + if (!m.knownToFoe || !canMove(m.rank) || m.rank < 3) continue; + const wasNext = Math.abs(e.fr - Math.floor(m.sq / 10)) + Math.abs(e.fc - (m.sq % 10)) === 1; + const nowNext = md(f.sq, m.sq) === 1; + if (wasNext && !nowNext) { + for (const k of MOVABLE) if (w[k]) w[k] *= k < m.rank ? 2 : 0.5; + } } - loss = wt ? (bad / wt) * val(moverRank) : 0; } - if (loss > worst) worst = loss; + return w; + }); + + // Balance: rows sum to 1, columns to the remaining counts. + const P = W.map((w) => ({ ...w })); + const norm = () => { + for (const row of P) { + let t = 0; for (const k in row) t += row[k]; + if (t > 0) for (const k in row) row[k] /= t; + } + }; + norm(); + for (let it = 0; it < 14; it++) { + for (const k of RANK_LIST) { + if (!rem[k]) continue; + let t = 0; for (const row of P) t += row[k] ?? 0; + if (t > 1e-9) { const f = rem[k] / t; for (const row of P) if (row[k]) row[k] *= f; } + } + norm(); + } + hidden.forEach((f, i) => { f.belief = P[i]; }); + + // What the enemy can infer about OUR hidden pieces (they know the army list). + const myRem = {}; + for (const k of RANK_LIST) myRem[k] = counts[k] ?? 0; + for (const k of view.captured[me]) myRem[k]--; + for (const m of mine) if (m.knownToFoe) myRem[m.rank]--; + const distOf = (moved) => { + const d = {}; let t = 0; + for (const k of RANK_LIST) { + const n = Math.max(0, myRem[k]); + if (!n || (moved && (k === FLAG || k === BOMB))) continue; + d[k] = n; t += n; + } + if (t) for (const k in d) d[k] /= t; + return d; + }; + return { me, op, mine, foes, hidden, rem, foeDist: [distOf(false), distOf(true)] }; +} + +// ── 2. sampled worlds ───────────────────────────────────────────────────────── +function sampleWorld(view, info, rng) { + const { me, mine, foes, hidden, rem } = info; + const W = { + rank: new Int8Array(100).fill(-1), + owner: new Int8Array(100).fill(-1), + moved: new Uint8Array(100), + known: new Uint8Array(100), // our piece: foe knows it; their piece: we know it + pid: new Int16Array(100).fill(-1), + }; + for (const m of mine) { + W.rank[m.sq] = m.rank; W.owner[m.sq] = me; W.moved[m.sq] = m.moved ? 1 : 0; W.known[m.sq] = m.knownToFoe ? 1 : 0; + } + const left = { ...rem }; + // Most-constrained first: pieces that have moved can't be bombs or flags. + const order = hidden.map((f, i) => i).sort((a, b) => (hidden[b].moved - hidden[a].moved) || (rng() - 0.5)); + const assigned = new Map(); + for (const i of order) { + const f = hidden[i]; + let t = 0; + const opts = []; + for (const k in f.belief) { + const w = left[k] > 0 ? f.belief[k] : 0; + if (w > 0) { opts.push([Number(k), w]); t += w; } + } + let pick = null; + if (t > 0) { + let x = rng() * t; + for (const [k, w] of opts) { x -= w; if (x <= 0) { pick = k; break; } } + if (pick == null) pick = opts[opts.length - 1][0]; + } else { + const any = RANK_LIST.filter((k) => left[k] > 0 && (!f.moved || canMove(k))); + const any2 = any.length ? any : RANK_LIST.filter((k) => left[k] > 0); + pick = any2.length ? any2[Math.floor(rng() * any2.length)] : 4; + } + left[pick] = (left[pick] ?? 0) - 1; + assigned.set(f.id, pick); + } + for (let i = 0; i < foes.length; i++) { + const f = foes[i]; + const rank = f.rank != null ? f.rank : assigned.get(f.id); + W.rank[f.sq] = rank; W.owner[f.sq] = 1 - me; W.moved[f.sq] = f.moved ? 1 : 0; + W.known[f.sq] = f.rank != null ? 1 : 0; + W.pid[f.sq] = i; + } + return W; +} + +// ── 3. evaluation pieces ────────────────────────────────────────────────────── +function buildCtx(view, info, W, skill) { + const me = info.me, op = info.op; + let myFlag = -1, opFlag = -1; + const alive = [{}, {}]; + for (let k = 0; k < 100; k++) { + if (W.owner[k] < 0) continue; + const s = W.owner[k] === me ? 0 : 1; + alive[s][W.rank[k]] = (alive[s][W.rank[k]] ?? 0) + 1; + if (W.rank[k] === FLAG) { if (s === 0) myFlag = k; else opFlag = k; } + } + const opBombs = []; + for (let k = 0; k < 100; k++) if (W.owner[k] === op && W.rank[k] === BOMB && opFlag >= 0 && md(k, opFlag) <= 2) opBombs.push(k); + + const val = [new Float32Array(12), new Float32Array(12)]; // [mine, theirs] + for (let s = 0; s < 2; s++) { + const other = 1 - s; + for (const k of RANK_LIST) { + let v = BASE_VAL[k]; + if (k === SPY) v = alive[other][MARSHAL] ? 70 : 12; + if (k === MINER) { const n = alive[s][MINER] ?? 0; v = 45 + (n <= 2 ? 30 : 0) + (n <= 1 ? 45 : 0); } + if (k === MARSHAL && !alive[other][SPY]) v = 450; + val[s][k] = v; + } + } + // Positional tables: [mine actual, theirs actual, theirs as THEY see it]. + const pos = [0, 1, 2].map(() => RANK_LIST.map(() => new Float32Array(100))); + const myBack = me === 0 ? 9 : 0, opBack = 9 - myBack; + const FP = { 1: 0, 2: 1.5, 3: 5, 4: 3, 5: 3, 6: 3, 7: 3, 8: 2.5, 9: 2.5, 10: 2 }; + const ADV = { 1: -0.15, 2: 0.3, 3: 0.25, 4: 0.25, 5: 0.25, 6: 0.25, 7: 0.25, 8: 0.1, 9: 0.1, 10: 0.1 }; + for (let sq = 0; sq < 100; sq++) { + if (LAKE[sq]) continue; + const r = Math.floor(sq / 10); + const myAdv = Math.abs(r - myBack), opAdv = Math.abs(r - opBack); + for (const k of MOVABLE) { + // ours: head for (this world's) enemy flag; miners to the bombs round it + let v = ADV[k] * myAdv; + if (opFlag >= 0) v += FP[k] * (18 - md(sq, opFlag)) / 18; + if (k === MINER && opBombs.length) { + let d = 99; for (const b of opBombs) d = Math.min(d, md(sq, b)); + v += 4 * Math.max(0, 1 - d / 12); + } + pos[0][k][sq] = v; + // theirs: closeness to our flag is a danger to us + let t = 0.1 * opAdv; + if (myFlag >= 0) t += (k === SPY ? 1 : 2) * Math.max(0, 8 - md(sq, myFlag)); + pos[1][k][sq] = t; + pos[2][k][sq] = 0.25 * opAdv; + } + } + return { + me, op, val, pos, info, W, skill, + revealCost: view.reveal === 'classic' ? 0.5 : 1, + firstMove: skill >= 3 ? 1.5 : 0, + }; +} + +const side = (ctx, seat) => (seat === ctx.me ? 0 : 1); +const sgn = (ctx, seat) => (seat === ctx.me ? 1 : -1); +// pos table for a seat: ours, or theirs as it really matters / as they see it. +const posT = (ctx, seat, perceive) => (seat === ctx.me ? ctx.pos[0] : perceive ? ctx.pos[2] : ctx.pos[1]); + +// Value (to us) of `seat`'s piece at fk attacking/moving to tk, if the +// defender's rank were `d`. W is not modified. +function outcome(ctx, W, seat, a, fk, tk, d, perceive) { + const s = sgn(ctx, seat), foe = 1 - seat; + const sa = side(ctx, seat), sd = 1 - sa; + const pa = posT(ctx, seat, perceive), pd = posT(ctx, foe, perceive); + if (d === FLAG) return s * WIN; + const res = battleResult(a, d); + let v = 0; + const loseA = () => { v -= s * (ctx.val[sa][a] + pa[a][fk]); }; + const loseD = () => { v += s * (ctx.val[sd][d] + (pd[d]?.[tk] ?? 0)); }; + if (res === 'attacker') { + loseD(); + v += s * (pa[a][tk] - pa[a][fk]); + if (!W.known[fk]) v -= s * INFO[a] * (seat === ctx.me ? ctx.revealCost : 0.5); + } else if (res === 'defender') { + loseA(); + if (!W.known[tk]) v += s * INFO[d] * (foe === ctx.me ? ctx.revealCost : 0.5); + } else { loseA(); loseD(); } + return v; +} + +// Score of a move for `seat` in world W (to us). perceive=true judges a +// hidden defender by what the mover knows instead of what it really is. +function delta(ctx, W, seat, fk, tk, perceive) { + const a = W.rank[fk]; + if (W.owner[tk] < 0) { + const p = posT(ctx, seat, perceive); + let v = sgn(ctx, seat) * (p[a][tk] - p[a][fk]); + if (seat === ctx.me && !W.moved[fk]) v -= ctx.firstMove; + return v; + } + const d = W.rank[tk]; + if (!perceive || W.known[tk]) return outcome(ctx, W, seat, a, fk, tk, d, perceive); + // Expected over what the mover believes the defender could be. + let dist; + if (seat === ctx.me) { + const pid = W.pid[tk]; + dist = pid >= 0 && ctx.info.foes[pid].belief ? ctx.info.foes[pid].belief : null; + } else dist = ctx.info.foeDist[W.moved[tk] ? 1 : 0]; + if (!dist) return outcome(ctx, W, seat, a, fk, tk, d, perceive); + let v = 0, t = 0; + for (const k in dist) { + const p = dist[k]; + if (p <= 0) continue; + const ov = outcome(ctx, W, seat, a, fk, tk, Number(k), perceive); + v += p * Math.max(-WIN / 4, Math.min(WIN / 4, ov)); t += p; + } + return t ? v / t : 0; +} + +// Play the move in W (really). Returns true if a flag fell. +function play(ctx, W, fk, tk) { + const a = W.rank[fk], seat = W.owner[fk]; + W.moved[fk] = 1; + if (W.owner[tk] < 0) { + W.rank[tk] = a; W.owner[tk] = seat; W.moved[tk] = 1; W.known[tk] = W.known[fk]; W.pid[tk] = W.pid[fk]; + W.rank[fk] = -1; W.owner[fk] = -1; W.known[fk] = 0; W.pid[fk] = -1; + return false; + } + const d = W.rank[tk]; + const res = battleResult(a, d); + if (res === 'attacker') { + W.rank[tk] = a; W.owner[tk] = seat; W.moved[tk] = 1; W.known[tk] = 1; W.pid[tk] = W.pid[fk]; + } else if (res === 'defender') { + W.known[tk] = 1; + } else { W.rank[tk] = -1; W.owner[tk] = -1; W.known[tk] = 0; W.pid[tk] = -1; } + W.rank[fk] = -1; W.owner[fk] = -1; W.known[fk] = 0; W.pid[fk] = -1; + return d === FLAG; +} + +function genMoves(W, seat) { + const out = []; + for (let k = 0; k < 100; k++) { + if (W.owner[k] !== seat) continue; + const a = W.rank[k]; + if (!canMove(a)) continue; + const r = Math.floor(k / 10), c = k % 10; + for (const [dr, dc] of DIRS) { + let nr = r + dr, nc = c + dc; + const max = a === SCOUT ? 10 : 1; + for (let s = 0; s < max; s++, nr += dr, nc += dc) { + if (nr < 0 || nr > 9 || nc < 0 || nc > 9) break; + const t = nr * 10 + nc; + if (LAKE[t]) break; + if (W.owner[t] < 0) { out.push(k, t); continue; } + if (W.owner[t] !== seat) out.push(k, t); + break; + } + } + } + return out; +} + +function copyW(W) { + return { rank: W.rank.slice(), owner: W.owner.slice(), moved: W.moved.slice(), known: W.known.slice(), pid: W.pid.slice() }; +} + +// After our root move: each side in turn plays what looks best to it. +function rollout(ctx, W, plies, rng) { + let seat = ctx.op, total = 0, disc = 0.9; + for (let p = 0; p < plies; p++) { + const mv = genMoves(W, seat); + if (!mv.length) return total + (seat === ctx.me ? -WIN / 2 : WIN / 2) * disc; + let best = -1, bestV = -Infinity; + const s = sgn(ctx, seat); + for (let i = 0; i < mv.length; i += 2) { + const v = s * delta(ctx, W, seat, mv[i], mv[i + 1], true) + rng() * 0.01; + if (v > bestV) { bestV = v; best = i; } + } + const fk = mv[best], tk = mv[best + 1]; + total += disc * delta(ctx, W, seat, fk, tk, false); + if (play(ctx, W, fk, tk)) return total; + seat = 1 - seat; disc *= 0.9; + } + return total; +} + +// Danger on a square right after we arrive (used when not looking ahead). +function threatAt(ctx, W, tk) { + let worst = 0; + const r = Math.floor(tk / 10), c = tk % 10; + for (const [dr, dc] of DIRS) { + const nr = r + dr, nc = c + dc; + if (nr < 0 || nr > 9 || nc < 0 || nc > 9) continue; + const k = nr * 10 + nc; + if (W.owner[k] !== ctx.op || !canMove(W.rank[k])) continue; + const v = -outcome(ctx, W, ctx.op, W.rank[k], k, tk, W.rank[tk], false); + if (v > worst) worst = v; } return worst; } -// Score one move for `seat` (higher = better). -function scoreMove(state, seat, m, counts) { - const mover = state.board[m.fr][m.fc]; - let score = 0; - - if (m.attack) { - const target = state.board[m.tr][m.tc]; - score += target.revealed - ? knownAttackValue(mover.rank, target.rank) - : expectedAttackValue(mover.rank, counts, hasMoved(target)); - } else { - // Reward advancing toward the enemy; scouts get a touch more for ranging. - const advance = (m.tr - m.fr) * forwardDir(seat); - score += advance * (mover.rank === SCOUT ? 2.5 : 1.5); - // Discourage marching the Marshal/Spy out into the open early. - if (mover.rank === MARSHAL || mover.rank === SPY) score -= 2; - } - - // Penalise landing where a stronger enemy can take us next turn. - score -= squareThreat(state, seat, m.tr, m.tc, mover.rank, counts) * 0.6; - - return score; -} - -// Choose a move for `seat`. Returns { type:'move', fr, fc, tr, tc } or null. -export function chooseMove(state, seat, skill = 3) { +// ── 4. choosing ─────────────────────────────────────────────────────────────── +/** Pick a move for view.viewer. Returns { fr, fc, tr, tc, score } or null. */ +export function chooseMove(view, skill = 3, opts = {}) { const prof = profileFor(skill); - const moves = allLegalMoves(state, seat); - if (moves.length === 0) return null; - - const counts = unknownEnemyCounts(state, 1 - seat); - const scored = moves.map((m) => ({ m, s: scoreMove(state, seat, m, counts) })); - scored.sort((a, b) => b.s - a.s); - - let pick; - if (Math.random() < prof.blunder) { - const pool = scored.slice(0, Math.max(1, Math.ceil(scored.length / 3))); - pick = pool[Math.floor(Math.random() * pool.length)]; - } else { - const pool = scored.slice(0, Math.min(prof.topN, scored.length)); - let best = pool[0], bestV = -Infinity; - for (const e of pool) { - const v = e.s + (prof.noise ? (Math.random() * 2 - 1) * prof.noise : 0); - if (v > bestV) { bestV = v; best = e; } + const rng = makeRng(opts.seed ?? Math.floor(Math.random() * 1e9)); + const moves = allLegalMoves(view, view.viewer); + if (!moves.length) return null; + const info = analyze(view, skill); + const t0 = Date.now(); + const budget = opts.ms ?? prof.ms; + const nS = opts.samples ?? prof.samples; + const depth = opts.depth ?? prof.depth; + const sums = new Float64Array(moves.length); + let done = 0; + for (let si = 0; si < nS; si++) { + if (si >= 2 && Date.now() - t0 > budget) break; + const W0 = sampleWorld(view, info, rng); + const ctx = buildCtx(view, info, W0, skill); + for (let i = 0; i < moves.length; i++) { + const m = moves[i]; + const fk = m.fr * 10 + m.fc, tk = m.tr * 10 + m.tc; + let v = delta(ctx, W0, info.me, fk, tk, false); + if (v < WIN / 2) { + const W = copyW(W0); + if (!play(ctx, W, fk, tk)) { + if (depth > 1) v += rollout(ctx, W, depth - 1, rng); + else if (W.owner[tk] === info.me) v -= 0.6 * threatAt(ctx, W, tk); + } + } + sums[i] += v; + } + done++; + } + const scored = moves.map((m, i) => ({ m, s: sums[i] / Math.max(1, done) })); + scored.sort((a, b) => b.s - a.s); + let pick; + if (!opts.best && rng() < prof.blunder) { + const pool = scored.slice(0, Math.max(1, Math.ceil(scored.length / 3))); + pick = pool[Math.floor(rng() * pool.length)]; + } else if (opts.best) { + pick = scored[0]; + } else { + let bestV = -Infinity; + for (const e of scored.slice(0, 6)) { + const v = e.s + (rng() * 2 - 1) * prof.noise; + if (v > bestV) { bestV = v; pick = e; } } - pick = best; } const { fr, fc, tr, tc } = pick.m; - return { type: 'move', fr, fc, tr, tc }; + return { fr, fc, tr, tc, score: pick.s, samples: done }; +} + +/** The strongest suggestion for the side to move (the player's Hint). */ +export function hint(view, opts = {}) { + return chooseMove(view, 5, { best: true, ms: opts.ms ?? 900, ...opts }); +} + +/** Ranked guesses for one hidden enemy piece (used by the HUD's inspect). */ +export function beliefFor(view, id) { + const info = analyze(view, 5); + const f = info.foes.find((x) => x.id === id); + if (!f) return null; + if (f.rank != null) return [{ rank: f.rank, p: 1 }]; + return Object.entries(f.belief).map(([k, p]) => ({ rank: Number(k), p })).sort((a, b) => b.p - a.p); } diff --git a/src/games/stratego/StrategoArt.js b/src/games/stratego/StrategoArt.js new file mode 100644 index 0000000..dcc1a8e --- /dev/null +++ b/src/games/stratego/StrategoArt.js @@ -0,0 +1,465 @@ +// StrategoArt.js: baked canvas textures for the Fog of War command deck. +// All procedural; the only image file is the pencil-sketch unit sheet +// (stratego-pieces.png), which StrategoPieces lays on the block faces. +// +// sg-deck the whole backdrop: deep space, nebula, starfield, and +// the glass panels of the left column and right rail +// sg-board the holo-table: gunmetal bezel, glass, lit grid, home +// zone tints, coordinates, and the two asteroid fields +// sg-face-0/1 a unit block seen from the front (red / blue): metal +// body, lower edge, pale sketch card inset +// sg-back-0/1 the same block from behind: faction crest +// sg-crest-0/1 large crests for cards and the end screen +// sg-rock-0..4 asteroids that drift over the fields +// sg-glow, sg-dot, sg-spark, sg-ring, sg-scan, sg-beam + +import { canvas, rr } from '../../ui/casino/CasinoArt.js'; +import { GRID, isLake } from './StrategoData.js'; +import { + W, H, FRAME, FRAME_PAD, TILE, PITCH, BOARD_W, LEFT, CARD_OPP, CARD_YOU, LOG, CONTROLS, +} from './StrategoLayout.js'; + +export const DISPLAY_FONT = 'Righteous, "Julius Sans One", sans-serif'; +export const UI_FONT = '"Julius Sans One", "Segoe UI", sans-serif'; +export const MONO_FONT = '"Share Tech Mono", Consolas, "Courier New", monospace'; +export const RES = 2; // piece textures baked at 2× +export const BLOCK = { w: 70 * RES, face: 66 * RES, edge: 6 * RES }; + +export const HUE = { + cyan: 0x5fd4ff, cyanHex: '#5fd4ff', cyanDim: '#3a86a8', + amber: 0xffb547, amberHex: '#ffb547', + red: 0xff5a4a, redHex: '#ff6b5b', + ink: '#d9ecf7', inkDim: '#7f9bb0', panel: 0x08101c, +}; +const FACTION = [ + { light: '#f07a64', mid: '#c2402f', dark: '#6d1d14', edge: '#3d0f0a', glow: 'rgba(255,110,90,', crest: '#ffd2c4' }, + { light: '#7aa4f5', mid: '#3f6fd0', dark: '#1d3670', edge: '#0d1a3a', glow: 'rgba(100,160,255,', crest: '#d2e2ff' }, +]; + +function addCanvas(scene, key, c) { + if (scene.textures.exists(key)) scene.textures.remove(key); + scene.textures.addCanvas(key, c); +} +function seeded(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} +function radial(ctx, x, y, r, stops) { + const g = ctx.createRadialGradient(x, y, 0, x, y, r); + stops.forEach(([o, c]) => g.addColorStop(o, c)); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); +} + +// ── backdrop ────────────────────────────────────────────────────────────────── +function starfield(ctx, w, h, rnd, n) { + for (let i = 0; i < n; i++) { + const x = rnd() * w, y = rnd() * h; + const b = Math.pow(rnd(), 3); + const r = 0.4 + b * 1.4; + const tint = rnd(); + ctx.fillStyle = tint < 0.15 ? `rgba(255,210,170,${0.3 + b * 0.7})` : tint < 0.35 ? `rgba(170,210,255,${0.3 + b * 0.7})` : `rgba(235,240,255,${0.25 + b * 0.75})`; + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); + if (b > 0.75) { + ctx.strokeStyle = `rgba(200,230,255,${0.25 * b})`; ctx.lineWidth = 0.8; + ctx.beginPath(); ctx.moveTo(x - 7 * b, y); ctx.lineTo(x + 7 * b, y); ctx.moveTo(x, y - 7 * b); ctx.lineTo(x, y + 7 * b); ctx.stroke(); + } + } +} + +function panel(ctx, x, y, w, h, { notch = true, alpha = 0.84 } = {}) { + ctx.save(); + // drop shadow + ctx.fillStyle = 'rgba(0,0,0,0.45)'; + rr(ctx, x + 4, y + 8, w, h, 14); ctx.fill(); + const g = ctx.createLinearGradient(x, y, x, y + h); + g.addColorStop(0, `rgba(14,26,44,${alpha})`); + g.addColorStop(1, `rgba(6,11,20,${alpha})`); + ctx.fillStyle = g; + rr(ctx, x, y, w, h, 14); ctx.fill(); + // faint hex mesh + ctx.save(); + rr(ctx, x, y, w, h, 14); ctx.clip(); + ctx.strokeStyle = 'rgba(95,212,255,0.035)'; ctx.lineWidth = 1; + const s = 18, hh = s * Math.sqrt(3) / 2; + for (let yy = y - s; yy < y + h + s; yy += hh * 2) { + for (let xx = x - s; xx < x + w + s; xx += s * 3) { + for (const [ox, oy] of [[0, 0], [s * 1.5, hh]]) { + const cx = xx + ox, cy = yy + oy; + ctx.beginPath(); + for (let i = 0; i < 6; i++) { + const a = Math.PI / 3 * i; + const px = cx + s * Math.cos(a), py = cy + s * Math.sin(a); + if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); + } + ctx.closePath(); ctx.stroke(); + } + } + } + // top sheen + const sh = ctx.createLinearGradient(x, y, x, y + 60); + sh.addColorStop(0, 'rgba(120,200,255,0.10)'); sh.addColorStop(1, 'rgba(120,200,255,0)'); + ctx.fillStyle = sh; ctx.fillRect(x, y, w, 60); + ctx.restore(); + // border + lit corner brackets + ctx.strokeStyle = 'rgba(95,212,255,0.32)'; ctx.lineWidth = 1.5; + rr(ctx, x + 0.5, y + 0.5, w - 1, h - 1, 14); ctx.stroke(); + ctx.strokeStyle = 'rgba(140,225,255,0.95)'; ctx.lineWidth = 2.5; + ctx.shadowColor = 'rgba(95,212,255,0.9)'; ctx.shadowBlur = 8; + const L = 22; + const corner = (cx, cy, dx, dy) => { ctx.beginPath(); ctx.moveTo(cx + dx * L, cy); ctx.lineTo(cx, cy); ctx.lineTo(cx, cy + dy * L); ctx.stroke(); }; + corner(x + 3, y + 3, 1, 1); corner(x + w - 3, y + 3, -1, 1); corner(x + 3, y + h - 3, 1, -1); corner(x + w - 3, y + h - 3, -1, -1); + ctx.shadowBlur = 0; + if (notch) { + // a header rule + ctx.strokeStyle = 'rgba(95,212,255,0.28)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.moveTo(x + 14, y + 50); ctx.lineTo(x + w - 14, y + 50); ctx.stroke(); + ctx.fillStyle = 'rgba(95,212,255,0.8)'; + ctx.fillRect(x + 14, y + 48, 42, 3); + } + ctx.restore(); +} + +function bakeDeck(scene) { + const c = canvas(W, H), ctx = c.getContext('2d'); + const rnd = seeded(4711); + const g = ctx.createLinearGradient(0, 0, 0, H); + g.addColorStop(0, '#04060c'); g.addColorStop(0.55, '#070c18'); g.addColorStop(1, '#0a1020'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); + // nebulae + ctx.globalCompositeOperation = 'lighter'; + radial(ctx, 820, 120, 620, [[0, 'rgba(70,40,120,0.30)'], [0.5, 'rgba(40,30,90,0.12)'], [1, 'rgba(0,0,0,0)']]); + radial(ctx, 1500, 860, 700, [[0, 'rgba(20,90,120,0.28)'], [0.6, 'rgba(10,40,70,0.10)'], [1, 'rgba(0,0,0,0)']]); + radial(ctx, 260, 900, 520, [[0, 'rgba(140,50,60,0.20)'], [1, 'rgba(0,0,0,0)']]); + radial(ctx, 1150, 520, 380, [[0, 'rgba(60,80,160,0.12)'], [1, 'rgba(0,0,0,0)']]); + for (let i = 0; i < 40; i++) { + const x = rnd() * W, y = rnd() * H, r = 60 + rnd() * 200; + radial(ctx, x, y, r, [[0, `rgba(${80 + rnd() * 80 | 0},${60 + rnd() * 90 | 0},${140 + rnd() * 100 | 0},0.05)`], [1, 'rgba(0,0,0,0)']]); + } + ctx.globalCompositeOperation = 'source-over'; + starfield(ctx, W, H, rnd, 1400); + // a distant planet limb behind the header + ctx.save(); + ctx.beginPath(); ctx.arc(1140, -1580, 1640, 0, Math.PI * 2); ctx.closePath(); + const pg = ctx.createRadialGradient(1300, -1400, 1400, 1140, -1580, 1640); + pg.addColorStop(0, 'rgba(30,60,110,0.0)'); pg.addColorStop(0.9, 'rgba(30,70,120,0.22)'); pg.addColorStop(1, 'rgba(110,190,255,0.38)'); + ctx.fillStyle = pg; ctx.fill(); + ctx.restore(); + // panels + panel(ctx, LEFT.x, LEFT.y, LEFT.w, LEFT.h); + panel(ctx, CARD_OPP.x, CARD_OPP.y, CARD_OPP.w, CARD_OPP.h, { notch: false }); + panel(ctx, CARD_YOU.x, CARD_YOU.y, CARD_YOU.w, CARD_YOU.h, { notch: false }); + panel(ctx, LOG.x, LOG.y, LOG.w, LOG.h); + panel(ctx, CONTROLS.x, CONTROLS.y, CONTROLS.w, CONTROLS.h, { notch: false }); + // faction accent bars on the commander cards + for (const [card, f] of [[CARD_OPP, FACTION[1]], [CARD_YOU, FACTION[0]]]) { + const bg = ctx.createLinearGradient(card.x, 0, card.x + card.w, 0); + bg.addColorStop(0, f.mid); bg.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = bg; ctx.globalAlpha = 0.55; + ctx.fillRect(card.x + 10, card.y + 6, card.w * 0.7, 3); + ctx.globalAlpha = 1; + } + // vignette + const v = ctx.createRadialGradient(W / 2, H / 2, H * 0.4, W / 2, H / 2, H * 1.05); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(0,0,0,0.55)'); + ctx.fillStyle = v; ctx.fillRect(0, 0, W, H); + addCanvas(scene, 'sg-deck', c); +} + +// ── the holo-table ──────────────────────────────────────────────────────────── +function asteroid(ctx, x, y, r, rnd, shade = 1) { + const pts = []; + const n = 9 + Math.floor(rnd() * 5); + for (let i = 0; i < n; i++) { + const a = (i / n) * Math.PI * 2; + const rr2 = r * (0.72 + rnd() * 0.34); + pts.push([x + Math.cos(a) * rr2, y + Math.sin(a) * rr2]); + } + ctx.save(); + ctx.beginPath(); pts.forEach(([px, py], i) => (i ? ctx.lineTo(px, py) : ctx.moveTo(px, py))); ctx.closePath(); + const g = ctx.createRadialGradient(x - r * 0.4, y - r * 0.45, r * 0.1, x, y, r * 1.1); + g.addColorStop(0, `rgba(${150 * shade | 0},${136 * shade | 0},${122 * shade | 0},1)`); + g.addColorStop(0.55, `rgba(${86 * shade | 0},${76 * shade | 0},${70 * shade | 0},1)`); + g.addColorStop(1, `rgba(${28 * shade | 0},${24 * shade | 0},${26 * shade | 0},1)`); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + for (let i = 0; i < 4 + rnd() * 4; i++) { + const cx = x + (rnd() - 0.5) * r * 1.2, cy = y + (rnd() - 0.5) * r * 1.2, cr = r * (0.08 + rnd() * 0.18); + ctx.fillStyle = 'rgba(20,16,18,0.55)'; ctx.beginPath(); ctx.arc(cx, cy, cr, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(200,185,165,0.25)'; ctx.lineWidth = Math.max(0.8, cr * 0.25); + ctx.beginPath(); ctx.arc(cx + cr * 0.15, cy + cr * 0.15, cr, Math.PI * 0.9, Math.PI * 1.9); ctx.stroke(); + } + // a rim light from the board's glow + ctx.strokeStyle = 'rgba(120,210,255,0.35)'; ctx.lineWidth = 1.5; + ctx.beginPath(); pts.forEach(([px, py], i) => (i ? ctx.lineTo(px, py) : ctx.moveTo(px, py))); ctx.closePath(); ctx.stroke(); + ctx.restore(); +} + +function bakeBoard(scene) { + const c = canvas(FRAME.w, FRAME.h), ctx = c.getContext('2d'); + const rnd = seeded(902); + // bezel + ctx.fillStyle = 'rgba(0,0,0,0.6)'; rr(ctx, 6, 12, FRAME.w - 6, FRAME.h - 8, 22); ctx.fill(); + const bz = ctx.createLinearGradient(0, 0, FRAME.w, FRAME.h); + bz.addColorStop(0, '#2a3442'); bz.addColorStop(0.5, '#151b25'); bz.addColorStop(1, '#232b37'); + ctx.fillStyle = bz; rr(ctx, 0, 0, FRAME.w, FRAME.h, 22); ctx.fill(); + ctx.strokeStyle = 'rgba(255,255,255,0.12)'; ctx.lineWidth = 2; rr(ctx, 2, 2, FRAME.w - 4, FRAME.h - 4, 20); ctx.stroke(); + // bezel rivets & vents + for (let i = 0; i < 4; i++) { + const x = i % 2 ? FRAME.w - 16 : 16, y = i < 2 ? 16 : FRAME.h - 16; + radial(ctx, x, y, 5, [[0, '#9aa8b8'], [1, '#2a323e']]); + } + for (let i = 0; i < 8; i++) { + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + rr(ctx, FRAME.w / 2 - 70 + i * 18, FRAME.h - 13, 10, 5, 2); ctx.fill(); + rr(ctx, FRAME.w / 2 - 70 + i * 18, 8, 10, 5, 2); ctx.fill(); + } + // glass + const gx = FRAME_PAD - 10, gy = FRAME_PAD - 10, gw = BOARD_W + 20; + const gg = ctx.createRadialGradient(FRAME.w / 2, FRAME.h / 2, 60, FRAME.w / 2, FRAME.h / 2, gw * 0.75); + gg.addColorStop(0, '#0d2238'); gg.addColorStop(1, '#050b16'); + ctx.fillStyle = gg; rr(ctx, gx, gy, gw, gw, 12); ctx.fill(); + ctx.strokeStyle = 'rgba(95,212,255,0.85)'; ctx.lineWidth = 2; + ctx.shadowColor = 'rgba(95,212,255,0.9)'; ctx.shadowBlur = 14; + rr(ctx, gx, gy, gw, gw, 12); ctx.stroke(); + ctx.shadowBlur = 0; + // zones + const zone = (r0, r1, color) => { + const y0 = FRAME_PAD + r0 * PITCH - 4, y1 = FRAME_PAD + (r1 + 1) * PITCH; + const zg = ctx.createLinearGradient(0, y0, 0, y1); + zg.addColorStop(0, color.replace('A', r0 === 0 ? '0.13' : '0.02')); + zg.addColorStop(1, color.replace('A', r0 === 0 ? '0.02' : '0.13')); + ctx.fillStyle = zg; ctx.fillRect(gx + 2, y0, gw - 4, y1 - y0); + }; + zone(0, 3, 'rgba(90,140,255,A)'); + zone(6, 9, 'rgba(255,90,70,A)'); + // tiles + for (let r = 0; r < GRID; r++) for (let cc = 0; cc < GRID; cc++) { + if (isLake(r, cc)) continue; + const x = FRAME_PAD + cc * PITCH, y = FRAME_PAD + r * PITCH; + const tg = ctx.createLinearGradient(x, y, x, y + TILE); + tg.addColorStop(0, 'rgba(60,110,150,0.20)'); tg.addColorStop(1, 'rgba(30,60,95,0.28)'); + ctx.fillStyle = tg; rr(ctx, x, y, TILE, TILE, 6); ctx.fill(); + ctx.strokeStyle = 'rgba(110,205,255,0.30)'; ctx.lineWidth = 1; + rr(ctx, x + 0.5, y + 0.5, TILE - 1, TILE - 1, 6); ctx.stroke(); + // tiny corner ticks: a targeting grid + ctx.strokeStyle = 'rgba(150,225,255,0.45)'; + for (const [tx, ty, dx, dy] of [[x + 4, y + 4, 1, 1], [x + TILE - 4, y + 4, -1, 1], [x + 4, y + TILE - 4, 1, -1], [x + TILE - 4, y + TILE - 4, -1, -1]]) { + ctx.beginPath(); ctx.moveTo(tx + dx * 6, ty); ctx.lineTo(tx, ty); ctx.lineTo(tx, ty + dy * 6); ctx.stroke(); + } + } + // the centre line + ctx.strokeStyle = 'rgba(95,212,255,0.18)'; ctx.setLineDash([6, 8]); ctx.lineWidth = 1.5; + const midY = FRAME_PAD + 5 * PITCH - GAP_HALF(); + ctx.beginPath(); ctx.moveTo(gx + 10, midY); ctx.lineTo(gx + gw - 10, midY); ctx.stroke(); + ctx.setLineDash([]); + // asteroid fields + for (const c0 of [2, 6]) { + const x = FRAME_PAD + c0 * PITCH, y = FRAME_PAD + 4 * PITCH, s = PITCH * 2 - 4; + ctx.save(); + rr(ctx, x, y, s, s, 10); ctx.clip(); + ctx.fillStyle = '#04060b'; ctx.fillRect(x, y, s, s); + radial(ctx, x + s * 0.4, y + s * 0.45, s * 0.8, [[0, 'rgba(150,80,40,0.35)'], [0.5, 'rgba(90,40,90,0.22)'], [1, 'rgba(0,0,0,0)']]); + radial(ctx, x + s * 0.7, y + s * 0.7, s * 0.5, [[0, 'rgba(60,90,160,0.25)'], [1, 'rgba(0,0,0,0)']]); + for (let i = 0; i < 60; i++) { + ctx.fillStyle = `rgba(220,200,180,${0.15 + rnd() * 0.4})`; + ctx.fillRect(x + rnd() * s, y + rnd() * s, 1.2, 1.2); + } + for (let i = 0; i < 14; i++) asteroid(ctx, x + rnd() * s, y + rnd() * s, 4 + rnd() * 9, rnd, 0.55 + rnd() * 0.3); + ctx.restore(); + // hazard border + ctx.save(); + ctx.strokeStyle = 'rgba(255,181,71,0.7)'; ctx.lineWidth = 2; ctx.setLineDash([10, 7]); + rr(ctx, x + 1, y + 1, s - 2, s - 2, 10); ctx.stroke(); + ctx.setLineDash([]); + ctx.fillStyle = 'rgba(255,181,71,0.85)'; + ctx.font = `bold 11px ${UI_FONT}`; ctx.textAlign = 'center'; + ctx.fillText('· NO TRANSIT ·', x + s / 2, y + s - 8); + ctx.restore(); + } + // coordinates + ctx.fillStyle = 'rgba(140,215,255,0.75)'; ctx.font = `15px ${DISPLAY_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (let cc = 0; cc < GRID; cc++) { + const x = FRAME_PAD + cc * PITCH + TILE / 2; + ctx.fillText('ABCDEFGHIJ'[cc], x, FRAME.h - FRAME_PAD / 2 + 2); + ctx.fillText('ABCDEFGHIJ'[cc], x, FRAME_PAD / 2 - 2); + } + for (let r = 0; r < GRID; r++) { + const y = FRAME_PAD + r * PITCH + TILE / 2; + ctx.fillText(String(GRID - r), FRAME_PAD / 2 - 2, y); + ctx.fillText(String(GRID - r), FRAME.w - FRAME_PAD / 2 + 2, y); + } + addCanvas(scene, 'sg-board', c); +} +const GAP_HALF = () => (PITCH - TILE) / 2; + +// ── crests ──────────────────────────────────────────────────────────────────── +// Terran Vanguard: a winged arrowhead in a ring. Helix Dominion: a hexagon +// round a double helix. +export function drawCrest(ctx, seat, x, y, r, color, line = 2) { + ctx.save(); + ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = line; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; + if (seat === 0) { + ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.arc(x, y, r * 0.84, Math.PI * 0.15, Math.PI * 0.85); ctx.stroke(); + // arrowhead + ctx.beginPath(); + ctx.moveTo(x, y - r * 0.68); ctx.lineTo(x + r * 0.3, y + r * 0.18); ctx.lineTo(x, y + r * 0.02); ctx.lineTo(x - r * 0.3, y + r * 0.18); + ctx.closePath(); ctx.fill(); + // wings + for (const s of [-1, 1]) { + ctx.beginPath(); + ctx.moveTo(x + s * r * 0.22, y - r * 0.05); + ctx.lineTo(x + s * r * 0.78, y - r * 0.28); + ctx.lineTo(x + s * r * 0.62, y - r * 0.08); + ctx.lineTo(x + s * r * 0.74, y + r * 0.02); + ctx.lineTo(x + s * r * 0.3, y + r * 0.12); + ctx.closePath(); ctx.fill(); + } + ctx.beginPath(); ctx.moveTo(x - r * 0.18, y + r * 0.42); ctx.lineTo(x + r * 0.18, y + r * 0.42); ctx.stroke(); + } else { + ctx.beginPath(); + for (let i = 0; i < 6; i++) { + const a = Math.PI / 3 * i - Math.PI / 2; + const px = x + r * Math.cos(a), py = y + r * Math.sin(a); + if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); + } + ctx.closePath(); ctx.stroke(); + const h = r * 0.62, amp = r * 0.3; + for (const ph of [0, Math.PI]) { + ctx.beginPath(); + for (let t = 0; t <= 1.0001; t += 0.05) { + const py = y - h + t * h * 2, px = x + Math.sin(t * Math.PI * 2 + ph) * amp; + if (t) ctx.lineTo(px, py); else ctx.moveTo(px, py); + } + ctx.stroke(); + } + ctx.lineWidth = line * 0.7; + for (let t = 0.125; t < 1; t += 0.25) { + const py = y - h + t * h * 2, s1 = Math.sin(t * Math.PI * 2) * amp; + ctx.beginPath(); ctx.moveTo(x + s1, py); ctx.lineTo(x - s1, py); ctx.stroke(); + } + } + ctx.restore(); +} + +// ── unit blocks ─────────────────────────────────────────────────────────────── +function blockBody(ctx, f) { + const { w, face, edge } = BLOCK; + // lower edge (thickness) + const eg = ctx.createLinearGradient(0, face - 10, 0, face + edge); + eg.addColorStop(0, f.dark); eg.addColorStop(1, f.edge); + ctx.fillStyle = eg; rr(ctx, 0, edge, w, face, 16); ctx.fill(); + // face + const g = ctx.createLinearGradient(0, 0, w, face); + g.addColorStop(0, f.light); g.addColorStop(0.45, f.mid); g.addColorStop(1, f.dark); + ctx.fillStyle = g; rr(ctx, 0, 0, w, face, 16); ctx.fill(); + // bevel + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.moveTo(14, 2.5); ctx.lineTo(w - 14, 2.5); ctx.stroke(); + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 2; + rr(ctx, 1, 1, w - 2, face - 2, 15); ctx.stroke(); +} + +function bakeBlocks(scene) { + const { w, face, edge } = BLOCK; + for (let seat = 0; seat < 2; seat++) { + const f = FACTION[seat]; + // front + let c = canvas(w, face + edge), ctx = c.getContext('2d'); + blockBody(ctx, f); + const ix = 9, iy = 9, iw = w - 18, ih = face - 18; + ctx.fillStyle = 'rgba(0,0,0,0.35)'; rr(ctx, ix - 1, iy - 1, iw + 2, ih + 2, 10); ctx.fill(); + const card = ctx.createLinearGradient(0, iy, 0, iy + ih); + card.addColorStop(0, '#f1f4f6'); card.addColorStop(1, '#cfd8df'); + ctx.fillStyle = card; rr(ctx, ix, iy, iw, ih, 9); ctx.fill(); + // faint holo-grid on the card + ctx.save(); rr(ctx, ix, iy, iw, ih, 9); ctx.clip(); + ctx.strokeStyle = 'rgba(60,110,150,0.10)'; ctx.lineWidth = 1; + for (let i = ix; i < ix + iw; i += 12) { ctx.beginPath(); ctx.moveTo(i, iy); ctx.lineTo(i, iy + ih); ctx.stroke(); } + for (let i = iy; i < iy + ih; i += 12) { ctx.beginPath(); ctx.moveTo(ix, i); ctx.lineTo(ix + iw, i); ctx.stroke(); } + ctx.restore(); + ctx.strokeStyle = f.dark; ctx.lineWidth = 2; rr(ctx, ix, iy, iw, ih, 9); ctx.stroke(); + addCanvas(scene, `sg-face-${seat}`, c); + + // back + c = canvas(w, face + edge); ctx = c.getContext('2d'); + blockBody(ctx, f); + const bg = ctx.createRadialGradient(w / 2, face / 2, 4, w / 2, face / 2, w * 0.55); + bg.addColorStop(0, f.mid); bg.addColorStop(1, f.dark); + ctx.fillStyle = bg; rr(ctx, ix, iy, iw, ih, 9); ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 2; rr(ctx, ix, iy, iw, ih, 9); ctx.stroke(); + // panel lines + rivets + ctx.strokeStyle = 'rgba(255,255,255,0.12)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(ix + 8, iy + ih - 14); ctx.lineTo(ix + iw - 8, iy + ih - 14); ctx.stroke(); + for (const [rx, ry] of [[ix + 8, iy + 8], [ix + iw - 8, iy + 8], [ix + 8, iy + ih - 7], [ix + iw - 8, iy + ih - 7]]) { + radial(ctx, rx, ry, 3.2, [[0, 'rgba(255,255,255,0.7)'], [1, 'rgba(0,0,0,0.3)']]); + } + ctx.shadowColor = f.glow + '0.9)'; ctx.shadowBlur = 10; + drawCrest(ctx, seat, w / 2, face / 2 - 4, 30, f.crest, 4); + ctx.shadowBlur = 0; + addCanvas(scene, `sg-back-${seat}`, c); + + // big crest + c = canvas(160, 160); ctx = c.getContext('2d'); + ctx.shadowColor = f.glow + '1)'; ctx.shadowBlur = 16; + drawCrest(ctx, seat, 80, 80, 62, f.crest, 6); + addCanvas(scene, `sg-crest-${seat}`, c); + } +} + +// ── bits ────────────────────────────────────────────────────────────────────── +function bakeBits(scene) { + const rnd = seeded(77); + for (let i = 0; i < 5; i++) { + const s = 64, c = canvas(s, s), ctx = c.getContext('2d'); + asteroid(ctx, s / 2, s / 2, s * 0.38, rnd, 0.8 + rnd() * 0.25); + addCanvas(scene, `sg-rock-${i}`, c); + } + let c = canvas(128, 128), ctx = c.getContext('2d'); + radial(ctx, 64, 64, 64, [[0, 'rgba(255,255,255,1)'], [0.25, 'rgba(255,255,255,0.55)'], [1, 'rgba(255,255,255,0)']]); + addCanvas(scene, 'sg-glow', c); + c = canvas(32, 32); ctx = c.getContext('2d'); + radial(ctx, 16, 16, 16, [[0, 'rgba(255,255,255,1)'], [0.5, 'rgba(255,255,255,0.8)'], [1, 'rgba(255,255,255,0)']]); + addCanvas(scene, 'sg-dot', c); + c = canvas(48, 48); ctx = c.getContext('2d'); + ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.shadowColor = '#fff'; ctx.shadowBlur = 6; + ctx.beginPath(); ctx.moveTo(24, 2); ctx.lineTo(24, 46); ctx.moveTo(2, 24); ctx.lineTo(46, 24); ctx.stroke(); + radial(ctx, 24, 24, 8, [[0, 'rgba(255,255,255,1)'], [1, 'rgba(255,255,255,0)']]); + addCanvas(scene, 'sg-spark', c); + c = canvas(128, 128); ctx = c.getContext('2d'); + ctx.strokeStyle = 'rgba(255,255,255,0.95)'; ctx.lineWidth = 5; ctx.shadowColor = '#fff'; ctx.shadowBlur = 10; + ctx.beginPath(); ctx.arc(64, 64, 52, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'sg-ring', c); + c = canvas(8, 6); ctx = c.getContext('2d'); + ctx.fillStyle = 'rgba(150,225,255,0.07)'; ctx.fillRect(0, 0, 8, 2); + addCanvas(scene, 'sg-scan', c); + c = canvas(256, 24); ctx = c.getContext('2d'); + const bg = ctx.createLinearGradient(0, 0, 256, 0); + bg.addColorStop(0, 'rgba(255,255,255,0)'); bg.addColorStop(0.7, 'rgba(255,255,255,0.7)'); bg.addColorStop(1, 'rgba(255,255,255,1)'); + ctx.fillStyle = bg; ctx.fillRect(0, 9, 256, 6); + radial(ctx, 246, 12, 12, [[0, 'rgba(255,255,255,1)'], [1, 'rgba(255,255,255,0)']]); + addCanvas(scene, 'sg-beam', c); +} + +let baked = false; +export async function prepareStrategoArt(scene) { + try { + if (document.fonts?.load) { + await Promise.race([ + Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]), + new Promise((res) => setTimeout(res, 1200)), + ]); + } + } catch (_) { /* fall back */ } + if (!baked || !scene.textures.exists('sg-deck') || !scene.textures.exists('sg-face-0')) { + bakeDeck(scene); bakeBoard(scene); bakeBlocks(scene); bakeBits(scene); + baked = true; + } +} diff --git a/src/games/stratego/StrategoBattle.js b/src/games/stratego/StrategoBattle.js new file mode 100644 index 0000000..2a35865 --- /dev/null +++ b/src/games/stratego/StrategoBattle.js @@ -0,0 +1,268 @@ +// StrategoBattle.js: the engagement cinematic. Both units are pulled up onto +// a stage over the board (yours on the left), a hidden enemy shudders and +// flips over with a hologram flicker, the ranks rise, the winner fires and +// the loser goes up in a burst. Then the winner flies home. +// +// Speeds: 'full' (about five seconds), 'quick' (the same scene at ~3×) and +// 'off' (a short clash drawn on the board square itself). Any time during a +// scene, skip() runs the rest at ~14× (the scene binds it to a click and to +// Space). Every tween and timer goes through a Runner so that works. + +import * as Phaser from 'phaser'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { playScifiLaunch, playScifiExplode, playScifiRiser, playScifiReveal, playScifiWoosh } from '../../ui/Sounds.js'; +import { FLAG, BOMB, SPY, MINER, MARSHAL, battleResult, rankLabel, rankName, PLAYER_COLORS } from './StrategoData.js'; +import { PieceView } from './StrategoPieces.js'; +import { STAGE, TILE, PIECE } from './StrategoLayout.js'; +import { DISPLAY_FONT, UI_FONT, HUE } from './StrategoArt.js'; + +const SPEED_K = { full: 1, quick: 3.2, off: 1 }; + +class Runner { + constructor(scene, k) { this.scene = scene; this.k = k; this.tweens = []; this.timers = []; } + tween(cfg) { + const c = { ...cfg }; + if (c.duration) c.duration = c.duration / this.k; + if (c.delay) c.delay = c.delay / this.k; + const t = this.scene.tweens.add(c); + this.tweens.push(t); + return t; + } + tweenP(cfg) { return new Promise((res) => this.tween({ ...cfg, onComplete: (...a) => { cfg.onComplete?.(...a); res(); } })); } + wait(ms) { + return new Promise((res) => { + const ev = this.scene.time.delayedCall(ms / this.k, res); + this.timers.push(ev); + }); + } + skip() { + const f = 14 / this.k; + if (f <= 1) return; + this.k = 14; + for (const t of this.tweens) { try { t.timeScale = f; } catch (_) { /* finished */ } } + for (const e of this.timers) { try { e.timeScale = f; } catch (_) { /* */ } } + } +} + +function outcomeWords(res, attacker, defender, humanAttacked) { + const humanWon = res === 'both' ? null : (res === 'attacker') === humanAttacked; + let title = humanWon == null ? 'MUTUAL DESTRUCTION' : humanWon ? 'VICTORY' : 'DEFEAT'; + let sub = ''; + if (defender === FLAG) sub = 'FLAG CAPTURED'; + else if (defender === BOMB) sub = attacker === MINER ? 'BOMB DEFUSED' : 'BOMB!'; + else if (attacker === SPY && defender === MARSHAL) sub = 'MARSHAL ASSASSINATED'; + else if (res === 'both') sub = `${rankName(attacker)} vs ${rankName(defender)}`; + else sub = `${rankName(res === 'attacker' ? attacker : defender)} wins`; + return { title, sub, humanWon }; +} + +/** + * Play one engagement. opts: { mover, target, at:{x,y}, human, speed, + * depth, aiKnown (can the player already see the enemy unit?), onImpact(res) }. Returns a Promise; the returned + * object's .skip() fast-forwards. + */ +export function playBattle(scene, opts) { + const run = new Runner(scene, SPEED_K[opts.speed] ?? 1); + const p = opts.speed === 'off' ? inlineClash(scene, run, opts) : stageScene(scene, run, opts); + return { done: p, skip: () => run.skip() }; +} + +// ── the full stage ──────────────────────────────────────────────────────────── +async function stageScene(scene, run, { mover, target, at, human, depth, aiKnown, onImpact }) { + const res = battleResult(mover.rank, target.rank); + const humanAttacked = mover.owner === human; + const humanPiece = humanAttacked ? mover : target; + const aiPiece = humanAttacked ? target : mover; + const aiHidden = !aiKnown; + const hx = STAGE.cx - STAGE.offset, ax = STAGE.cx + STAGE.offset, cy = STAGE.cy; + const scale = STAGE.size / PIECE.w; + const objs = []; + const add = (o) => { objs.push(o); return o; }; + + const dim = add(scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x02040a, 0).setDepth(depth)); + run.tween({ targets: dim, fillAlpha: 0.8, duration: 320 }); + // a holo platform under each unit + const plat = add(scene.add.graphics().setDepth(depth + 1).setAlpha(0)); + for (const [x, seat] of [[hx, human], [ax, 1 - human]]) { + plat.fillStyle(PLAYER_COLORS[seat], 0.18).fillEllipse(x, cy + 118, 230, 52); + plat.lineStyle(2, PLAYER_COLORS[seat], 0.8).strokeEllipse(x, cy + 118, 230, 52); + } + run.tween({ targets: plat, alpha: 1, duration: 500, delay: 250 }); + const vs = add(scene.add.text(STAGE.cx, cy + 6, 'VS', { fontFamily: DISPLAY_FONT, fontSize: '54px', color: HUE.cyanHex }) + .setOrigin(0.5).setDepth(depth + 2).setAlpha(0).setShadow(0, 0, HUE.cyanHex, 20, true, true)); + run.tween({ targets: vs, alpha: 0.85, duration: 400, delay: 500 }); + + const hv = new PieceView(scene, humanPiece, { faceUp: true, depth: depth + 3, scale: 1, x: at.x, y: at.y }); + const av = new PieceView(scene, aiPiece, { faceUp: !aiHidden, depth: depth + 3, scale: 1, x: at.x, y: at.y }); + add(hv); add(av); + playScifiWoosh(scene); + run.tween({ targets: hv.c, x: hx, y: cy, scale, duration: 900, ease: 'Cubic.easeOut' }); + await run.tweenP({ targets: av.c, x: ax, y: cy, scale, duration: 900, ease: 'Cubic.easeOut' }); + hv.baseScale = scale; av.baseScale = scale; + + // reveal the hidden enemy + if (aiHidden) { + playScifiRiser(scene); + const prog = { t: 0 }; + await run.tweenP({ + targets: prog, t: 1, duration: 1150, ease: 'Linear', + onUpdate: () => { + const amp = prog.t * 18, f = 7 + prog.t * 6; + av.c.x = ax + Math.sin(prog.t * f * Math.PI * 2) * amp; + av.c.y = cy + Math.cos(prog.t * f * Math.PI * 2 + 1) * amp * 0.25; + }, + }); + av.c.setPosition(ax, cy); + await run.tweenP({ targets: av.c, scaleX: 0, duration: 200, ease: 'Sine.easeIn' }); + playScifiReveal(scene); + av.faceUp = true; av.paint(); + await run.tweenP({ targets: av.c, scaleX: scale, duration: 220, ease: 'Sine.easeOut' }); + // hologram flicker + await run.tweenP({ targets: av.c, alpha: { from: 0.4, to: 1 }, duration: 60, yoyo: true, repeat: 2 }); + av.c.setAlpha(1); + } else { + await run.wait(250); + } + + // ranks rise + const mk = (piece, x) => add(scene.add.text(x, cy, rankLabel(piece.rank), { + fontFamily: DISPLAY_FONT, fontSize: `${40 + Math.min(10, piece.rank) * 7}px`, color: '#ffffff', stroke: '#000000', strokeThickness: 6, + }).setOrigin(0.5).setDepth(depth + 5).setScale(0.2).setAlpha(0)); + const ht = mk(humanPiece, hx), at2 = mk(aiPiece, ax); + run.tween({ targets: vs, alpha: 0, duration: 200 }); + run.tween({ targets: ht, scale: 1, alpha: 1, y: cy - 150, x: hx + 30, duration: 600, ease: 'Back.easeOut' }); + await run.tweenP({ targets: at2, scale: 1, alpha: 1, y: cy - 150, x: ax - 30, duration: 600, ease: 'Back.easeOut' }); + + const words = outcomeWords(res, mover.rank, target.rank, humanAttacked); + const title = add(scene.add.text(STAGE.cx, cy - 250, words.title, { + fontFamily: DISPLAY_FONT, fontSize: '64px', color: words.humanWon == null ? HUE.amberHex : words.humanWon ? '#8dffb4' : '#ff7d6b', + stroke: '#000000', strokeThickness: 8, + }).setOrigin(0.5).setDepth(depth + 6).setAlpha(0).setScale(0.7)); + const sub = add(scene.add.text(STAGE.cx, cy + 190, words.sub, { + fontFamily: UI_FONT, fontSize: '26px', color: HUE.ink, stroke: '#000000', strokeThickness: 4, + }).setOrigin(0.5).setDepth(depth + 6).setAlpha(0)); + run.tween({ targets: title, alpha: 1, scale: 1, duration: 260, ease: 'Back.easeOut' }); + run.tween({ targets: sub, alpha: 1, duration: 300, delay: 120 }); + + const winner = res === 'attacker' ? (humanAttacked ? hv : av) : res === 'defender' ? (humanAttacked ? av : hv) : null; + const loser = winner === hv ? av : winner === av ? hv : null; + const xOf = (v) => (v === hv ? hx : ax); + const txtOf = (v) => (v === hv ? ht : at2); + const fadeOut = (v) => { + run.tween({ targets: v.c, alpha: 0, scale: scale * 0.7, duration: 420, delay: 100 }); + run.tween({ targets: txtOf(v), alpha: 0, duration: 280 }); + }; + + if (target.rank === BOMB && res === 'defender') { + // the attacker walks into the bomb + await run.tweenP({ targets: hv === loser ? hv.c : av.c, x: (xOf(loser) + xOf(winner)) / 2 + (loser === hv ? -30 : 30), duration: 260, ease: 'Quad.easeIn' }); + burst(scene, run, xOf(winner) - (loser === hv ? 70 : -70), cy, depth + 4, true); + onImpact?.(res); + fadeOut(loser); fadeOut(winner); + } else if (target.rank === BOMB) { + // a Miner defuses: the bomb fizzles out in cyan + await run.tweenP({ targets: winner.c, x: (xOf(winner) * 2 + xOf(loser)) / 3, duration: 300, ease: 'Quad.easeOut' }); + const ring = add(scene.add.image(xOf(loser), cy, 'sg-ring').setTint(HUE.cyan).setDepth(depth + 4).setBlendMode(Phaser.BlendModes.ADD).setScale(0.6)); + run.tween({ targets: ring, scale: 2.4, alpha: 0, duration: 600 }); + onImpact?.(res); + fadeOut(loser); + } else if (target.rank === FLAG) { + const flash = add(scene.add.image(xOf(loser), cy, 'sg-glow').setTint(0xffe08a).setDepth(depth + 4).setBlendMode(Phaser.BlendModes.ADD).setScale(0.5)); + run.tween({ targets: flash, scale: 5, alpha: 0, duration: 900 }); + onImpact?.(res); + fadeOut(loser); + } else if (res === 'both') { + await Promise.all([fire(scene, run, hx, ax, cy, depth + 4, PLAYER_COLORS[human]), fire(scene, run, ax, hx, cy, depth + 4, PLAYER_COLORS[1 - human])]); + burst(scene, run, ax, cy, depth + 4); burst(scene, run, hx, cy, depth + 4); + onImpact?.(res); + fadeOut(hv); fadeOut(av); + } else { + await fire(scene, run, xOf(winner), xOf(loser), cy, depth + 4, PLAYER_COLORS[winner === hv ? human : 1 - human]); + burst(scene, run, xOf(loser), cy, depth + 4); + onImpact?.(res); + fadeOut(loser); + } + await run.wait(1250); + + // winner flies home + run.tween({ targets: [title, sub], alpha: 0, duration: 380 }); + run.tween({ targets: plat, alpha: 0, duration: 380 }); + if (winner && !(target.rank === BOMB && res === 'defender')) { + run.tween({ targets: txtOf(winner), alpha: 0, duration: 300 }); + run.tween({ targets: winner.c, x: at.x, y: at.y, scale: 1, duration: 450, ease: 'Cubic.easeInOut' }); + } + await run.tweenP({ targets: dim, fillAlpha: 0, duration: 460 }); + cleanup(scene, objs); +} + +// ── on the square ───────────────────────────────────────────────────────────── +async function inlineClash(scene, run, { mover, target, at, depth, onImpact }) { + const res = battleResult(mover.rank, target.rank); + const objs = []; + const chip = (rank, seat, dx) => { + const t = scene.add.text(at.x + dx, at.y - 4, rankLabel(rank), { + fontFamily: DISPLAY_FONT, fontSize: '30px', color: '#ffffff', stroke: '#000000', strokeThickness: 5, + backgroundColor: seat === 0 ? '#7d2118' : '#223f86', padding: { x: 7, y: 1 }, + }).setOrigin(0.5).setDepth(depth + 3).setScale(0.3).setAlpha(0); + objs.push(t); + run.tween({ targets: t, scale: 1, alpha: 1, y: at.y - TILE * 0.62, duration: 220, ease: 'Back.easeOut' }); + return t; + }; + chip(mover.rank, mover.owner, -24); + chip(target.rank, target.owner, 24); + playScifiLaunch(scene); + await run.wait(420); + if (!(target.rank === BOMB && res === 'attacker')) burst(scene, run, at.x, at.y, depth + 2, false, 0.55); + onImpact?.(res); + await run.wait(560); + await run.tweenP({ targets: objs, alpha: 0, duration: 200 }); + cleanup(scene, objs); +} + +// ── effects ─────────────────────────────────────────────────────────────────── +function fire(scene, run, fromX, toX, y, depth, color) { + playScifiLaunch(scene); + const shot = scene.add.image(fromX, y, 'sg-dot').setTint(color).setDepth(depth).setScale(0.9).setBlendMode(Phaser.BlendModes.ADD); + const core = scene.add.image(fromX, y, 'sg-dot').setDepth(depth + 1).setScale(0.45).setBlendMode(Phaser.BlendModes.ADD); + const prog = { t: 0 }; + return run.tweenP({ + targets: prog, t: 1, duration: 380, ease: 'Linear', + onUpdate: () => { + const x = fromX + (toX - fromX) * prog.t, yy = y - 80 * Math.sin(prog.t * Math.PI); + shot.setPosition(x, yy); core.setPosition(x, yy); + if (Math.random() < 0.7) { + const tr = scene.add.image(x, yy, 'sg-dot').setTint(color).setDepth(depth - 1).setScale(0.5).setAlpha(0.7).setBlendMode(Phaser.BlendModes.ADD); + scene.tweens.add({ targets: tr, alpha: 0, scale: 0.1, duration: 260, onComplete: () => tr.destroy() }); + } + }, + onComplete: () => { shot.destroy(); core.destroy(); }, + }); +} + +function burst(scene, run, x, y, depth, big = false, size = 1) { + playScifiExplode(scene); + if (size >= 1) scene.cameras.main.shake(big ? 320 : 200, big ? 0.008 : 0.004); + const flash = scene.add.image(x, y, 'sg-glow').setTint(0xffc070).setDepth(depth + 1).setBlendMode(Phaser.BlendModes.ADD).setScale(0.3 * size); + run.tween({ targets: flash, scale: (big ? 4.2 : 3) * size, alpha: 0, duration: 520, ease: 'Cubic.easeOut', onComplete: () => flash.destroy() }); + [0, 1, 2].forEach((i) => { + const ring = scene.add.image(x + (i ? (Math.random() - 0.5) * 30 : 0), y + (i ? (Math.random() - 0.5) * 30 : 0), 'sg-ring') + .setTint(i === 0 ? 0xffffff : 0xff6a2a).setDepth(depth).setBlendMode(Phaser.BlendModes.ADD).setScale(0.1 * size); + run.tween({ targets: ring, scale: (1.6 + i * 0.5) * size * (big ? 1.4 : 1), alpha: 0, duration: 520 + i * 90, delay: i * 80, ease: 'Cubic.easeOut', onComplete: () => ring.destroy() }); + }); + const n = Math.round((big ? 26 : 16) * size); + for (let i = 0; i < n; i++) { + const a = Math.random() * Math.PI * 2, d = (60 + Math.random() * 120) * size * (big ? 1.4 : 1); + const sp = scene.add.image(x, y, 'sg-spark').setTint(Math.random() < 0.5 ? 0xffd080 : 0xff6a2a).setDepth(depth + 2) + .setScale(0.3 + Math.random() * 0.4).setBlendMode(Phaser.BlendModes.ADD).setRotation(Math.random() * 3); + run.tween({ targets: sp, x: x + Math.cos(a) * d, y: y + Math.sin(a) * d, alpha: 0, scale: 0.05, duration: 500 + Math.random() * 400, ease: 'Cubic.easeOut', onComplete: () => sp.destroy() }); + } +} + +function cleanup(scene, objs) { + for (const o of objs) { + try { + if (o instanceof PieceView) o.destroy(); + else { scene.tweens.killTweensOf(o); o.destroy(); } + } catch (_) { /* already gone */ } + } +} diff --git a/src/games/stratego/StrategoData.js b/src/games/stratego/StrategoData.js index 5ecb762..a494465 100644 --- a/src/games/stratego/StrategoData.js +++ b/src/games/stratego/StrategoData.js @@ -1,14 +1,14 @@ -// Stratego — static data. No Phaser, no game state: just the board geometry, -// the rank/army vocabulary, combat rules, the per-seat setup zones, and -// spritesheet frame helpers. Everything dynamic (the placed armies, whose turn, -// what's revealed) lives in StrategoLogic.js. +// Fog of War (Stratego rules): static data. No Phaser and no game state: +// the board shape, the rank/army vocabulary, variants, combat, setup zones, +// factions and spritesheet helpers. Everything dynamic (the placed armies, +// whose turn, who knows what) lives in StrategoLogic.js. // 10×10 board. export const GRID = 10; -// ── Lakes ──────────────────────────────────────────────────────────────────── -// Two 2×2 impassable lakes straddle the centre rows (4–5). They block movement -// entirely — pieces can neither stop on nor pass through them (Scouts included). +// ── Asteroid fields ("lakes") ──────────────────────────────────────────────── +// Two 2×2 fields straddle the centre rows (4–5). Nothing may stop on or pass +// through them, Scouts included. export const LAKES = (() => { const set = new Set(); for (const c0 of [2, 6]) { @@ -20,54 +20,85 @@ export const LAKES = (() => { })(); export function isLake(r, c) { return LAKES.has(r * GRID + c); } -// ── Ranks & army ───────────────────────────────────────────────────────────── -// Rank values: 1 (Spy) … 10 (Marshal) plus two non-numeric special pieces — -// Bomb (BOMB) and Flag (FLAG). Higher rank wins a straight fight; the specials -// below override that. `count` is how many each side gets (40 total). +// ── Ranks ──────────────────────────────────────────────────────────────────── +// 1 (Spy) … 10 (Marshal), plus the two immovable specials Bomb and Flag. export const FLAG = 0; // immovable; capturing it wins export const BOMB = 11; // immovable; destroys any attacker except a Miner (3) export const SPY = 1; export const SCOUT = 2; export const MINER = 3; +export const GENERAL = 9; export const MARSHAL = 10; +export const RANK_ORDER = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 0]; // strongest first // rank → metadata. `frame` is the spritesheet cell (0=Flag, 1..10=rank, 11=Bomb). export const RANKS = { - [FLAG]: { name: 'Flag', count: 1, frame: 0, canMove: false }, - 1: { name: 'Spy', count: 1, frame: 1, canMove: true }, - 2: { name: 'Scout', count: 8, frame: 2, canMove: true }, - 3: { name: 'Miner', count: 5, frame: 3, canMove: true }, - 4: { name: 'Sergeant', count: 4, frame: 4, canMove: true }, - 5: { name: 'Lieutenant', count: 4, frame: 5, canMove: true }, - 6: { name: 'Captain', count: 4, frame: 6, canMove: true }, - 7: { name: 'Major', count: 3, frame: 7, canMove: true }, - 8: { name: 'Colonel', count: 2, frame: 8, canMove: true }, - 9: { name: 'General', count: 1, frame: 9, canMove: true }, - [MARSHAL]: { name: 'Marshal', count: 1, frame: 10, canMove: true }, - [BOMB]: { name: 'Bomb', count: 6, frame: 11, canMove: false }, + [FLAG]: { name: 'Flag', short: 'F', frame: 0, canMove: false }, + 1: { name: 'Spy', short: 'S', frame: 1, canMove: true }, + 2: { name: 'Scout', short: '2', frame: 2, canMove: true }, + 3: { name: 'Miner', short: '3', frame: 3, canMove: true }, + 4: { name: 'Sergeant', short: '4', frame: 4, canMove: true }, + 5: { name: 'Lieutenant', short: '5', frame: 5, canMove: true }, + 6: { name: 'Captain', short: '6', frame: 6, canMove: true }, + 7: { name: 'Major', short: '7', frame: 7, canMove: true }, + 8: { name: 'Colonel', short: '8', frame: 8, canMove: true }, + 9: { name: 'General', short: '9', frame: 9, canMove: true }, + [MARSHAL]: { name: 'Marshal', short: 'M', frame: 10, canMove: true }, + [BOMB]: { name: 'Bomb', short: 'B', frame: 11, canMove: false }, }; -// The 40-piece roster for one side, as a flat list of rank values. -export function buildArmy() { +// What each unit does, for the reference/inspect panels. +export const RANK_NOTES = { + [FLAG]: 'Capture the enemy Flag to win. Cannot move.', + 1: 'Defeats the Marshal, but only when the Spy attacks. Loses to everything else.', + 2: 'Moves any distance in a straight line, and may attack at the end of the run.', + 3: 'The only unit that can defuse a Bomb.', + 4: 'Line trooper.', + 5: 'Junior officer.', + 6: 'Officer.', + 7: 'Strike craft. Strong mid-rank.', + 8: 'Senior officer.', + 9: 'Heavy walker. Second only to the Marshal.', + [MARSHAL]: 'Highest rank. Falls only to a Bomb or a Spy that attacks it.', + [BOMB]: 'Cannot move. Destroys any attacker except a Miner.', +}; + +// ── Variants ───────────────────────────────────────────────────────────────── +export const VARIANTS = { + classic: { + name: 'Classic', size: 40, drawPly: 400, + counts: { [FLAG]: 1, 1: 1, 2: 8, 3: 5, 4: 4, 5: 4, 6: 4, 7: 3, 8: 2, 9: 1, [MARSHAL]: 1, [BOMB]: 6 }, + blurb: 'The full 40-unit army on each side. A long, careful war of nerves.', + }, + barrage: { + name: 'Barrage', size: 8, drawPly: 200, + counts: { [FLAG]: 1, 1: 1, 2: 2, 3: 1, 9: 1, [MARSHAL]: 1, [BOMB]: 1 }, + blurb: 'Eight units each, deployed anywhere in your four rows. Fast and bluffy.', + }, +}; +export const VARIANT_ORDER = ['classic', 'barrage']; +export function variantOf(v) { return VARIANTS[v] ?? VARIANTS.classic; } +export function countOf(variant, rank) { return variantOf(variant).counts[rank] ?? 0; } + +// The roster for one side, as a flat list of rank values. +export function buildArmy(variant = 'classic') { const army = []; - for (const key of Object.keys(RANKS)) { - const rank = Number(key); - for (let i = 0; i < RANKS[rank].count; i++) army.push(rank); + const counts = variantOf(variant).counts; + for (const rank of RANK_ORDER) { + for (let i = 0; i < (counts[rank] ?? 0); i++) army.push(rank); } - return army; // length 40 + return army; } export const ARMY_SIZE = 40; -export function canMove(rank) { return RANKS[rank].canMove; } -export function rankName(rank) { return RANKS[rank].name; } +export function canMove(rank) { return rank != null && !!RANKS[rank]?.canMove; } +export function rankName(rank) { return RANKS[rank]?.name ?? 'Unknown'; } // ── Combat ─────────────────────────────────────────────────────────────────── -// Resolve an attack: the moving (attacker) piece steps onto a square held by a -// defender. Returns who survives: 'attacker', 'defender', or 'both' (mutual -// destruction). Specials: -// • Flag — always loses (its capture ends the game; handled by caller). -// • Bomb — destroys any attacker, except a Miner (3) which defuses it. -// • Spy — defeats the Marshal (10) only when the Spy is the attacker. +// 'attacker', 'defender', or 'both' (mutual destruction). +// • Flag — always loses (its capture ends the game). +// • Bomb — destroys any attacker, except a Miner which defuses it. +// • Spy — defeats the Marshal only when the Spy attacks. // • else — higher rank wins; equal ranks destroy each other. export function battleResult(attacker, defender) { if (defender === FLAG) return 'attacker'; @@ -78,32 +109,48 @@ export function battleResult(attacker, defender) { } // ── Setup zones ────────────────────────────────────────────────────────────── -// Seat 0 (human, red) fills the bottom four rows; seat 1 (AI, blue) the top -// four. Each zone is 4 rows × 10 cols = 40 cells, exactly one army. -export function setupRows(seat) { - return seat === 0 ? [6, 7, 8, 9] : [0, 1, 2, 3]; -} -export function inSetupZone(seat, r) { - return setupRows(seat).includes(r); -} -// The row of a seat's zone closest to its own edge (where the flag hides). +// Seat 0 (you, red) fills the bottom four rows; seat 1 (AI, blue) the top four. +export function setupRows(seat) { return seat === 0 ? [6, 7, 8, 9] : [0, 1, 2, 3]; } +export function inSetupZone(seat, r) { return seat === 0 ? r >= 6 : r <= 3; } export function backRow(seat) { return seat === 0 ? 9 : 0; } -// The row of a seat's zone facing the enemy (its front line). export function frontRow(seat) { return seat === 0 ? 6 : 3; } -// Forward direction (row delta) for a seat advancing toward the enemy. export function forwardDir(seat) { return seat === 0 ? -1 : 1; } +// Seat-relative line (0 = front, 3 = home edge) and column (0 = owner's left). +export function lineOf(seat, r) { return seat === 0 ? r - 6 : 3 - r; } +export function rowOfLine(seat, li) { return seat === 0 ? 6 + li : 3 - li; } +export function colOf(seat, c) { return seat === 0 ? c : GRID - 1 - c; } -// ── Colors ─────────────────────────────────────────────────────────────────── +// ── Factions & colours ─────────────────────────────────────────────────────── +export const FACTIONS = [ + { name: 'Terran Vanguard', short: 'Vanguard' }, + { name: 'Helix Dominion', short: 'Dominion' }, +]; export const PLAYER_COLORS = [0xc2402f, 0x3f6fd0]; // red, blue -export const PLAYER_COLOR_HEX = ['#c2402f', '#3f6fd0']; -export const PLAYER_DARK = [0x7d2118, 0x223f86]; // shaded body edge +export const PLAYER_COLOR_HEX = ['#e0614f', '#6a93ea']; +export const PLAYER_DARK = [0x6d1d14, 0x1d3670]; +export const PLAYER_LIGHT = [0xff8a6e, 0x8fb6ff]; // ── Spritesheet / label helpers ────────────────────────────────────────────── export function pieceFrame(rank) { return RANKS[rank].frame; } -// Corner label printed on movable pieces (Stratego prints the rank number). -// Bomb/Flag show a letter instead; immovable pieces have no number in the game. +// Corner label: the rank number, or F / B / S for the specials. export function rankLabel(rank) { if (rank === FLAG) return 'F'; if (rank === BOMB) return 'B'; + if (rank === SPY) return 'S'; return String(rank); } +// One-char codes used for stored layouts: F B S 2–9 M, '.' for empty. +export function rankCode(rank) { return rank == null ? '.' : RANKS[rank].short; } +export function codeRank(ch) { + if (ch === '.' || ch == null) return null; + if (ch === 'F') return FLAG; + if (ch === 'B') return BOMB; + if (ch === 'S') return SPY; + if (ch === 'M') return MARSHAL; + const n = Number(ch); + return n >= 2 && n <= 9 ? n : null; +} + +// Board coordinates from the player's side: files A–J left to right, ranks +// 1–10 from the bottom (your home edge) up. +export function squareName(r, c) { return `${'ABCDEFGHIJ'[c]}${GRID - r}`; } diff --git a/src/games/stratego/StrategoDialogs.js b/src/games/stratego/StrategoDialogs.js new file mode 100644 index 0000000..a6307ac --- /dev/null +++ b/src/games/stratego/StrategoDialogs.js @@ -0,0 +1,273 @@ +// StrategoDialogs.js: command-deck pop-ups: dark glass with a lit cyan +// frame. Each opener returns { close() } and swallows clicks beneath. + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { DISPLAY_FONT, UI_FONT, HUE } from './StrategoArt.js'; +import { VARIANTS, VARIANT_ORDER, codeRank, FLAG, BOMB, SPY, MARSHAL } from './StrategoData.js'; +import { presetsFor, loadSlots, saveSlot, SLOT_COUNT, randomize } from './StrategoSetups.js'; +import { layoutValid } from './StrategoLogic.js'; + +export const BTN = 0x12304a, BTN_GO = 0x1f6a3a, BTN_WARN = 0x7a1a14, BTN_ALT = 0x4a3a12; + +export function frame(scene, x, y, w, h, depth, title = null) { + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.55).fillRoundedRect(x + 6, y + 10, w, h, 16); + g.fillGradientStyle(0x0e1c30, 0x0e1c30, 0x060c16, 0x060c16, 0.97).fillRoundedRect(x, y, w, h, 16); + g.fillStyle(0x0e1c30, 0.97).fillRoundedRect(x, y, w, 30, { tl: 16, tr: 16, bl: 0, br: 0 }); + g.lineStyle(1.5, HUE.cyan, 0.45).strokeRoundedRect(x, y, w, h, 16); + g.lineStyle(3, HUE.cyan, 1); + const L = 26; + for (const [cx, cy, dx, dy] of [[x + 4, y + 4, 1, 1], [x + w - 4, y + 4, -1, 1], [x + 4, y + h - 4, 1, -1], [x + w - 4, y + h - 4, -1, -1]]) { + g.beginPath().moveTo(cx + dx * L, cy).lineTo(cx, cy).lineTo(cx, cy + dy * L).strokePath(); + } + const objs = [g]; + if (title) { + objs.push(scene.add.text(x + w / 2, y + 44, title, { + fontFamily: DISPLAY_FONT, fontSize: '32px', color: HUE.ink, + }).setOrigin(0.5).setDepth(depth + 1).setShadow(0, 0, HUE.cyanHex, 12, true, true)); + g.lineStyle(1, HUE.cyan, 0.35).lineBetween(x + 40, y + 76, x + w - 40, y + 76); + } + return objs; +} + +export function blocker(scene, depth, alpha = 0) { + return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x02040a, alpha).setDepth(depth).setInteractive(); +} + +export function handle(objs, onClose) { + let closed = false; + return { objs, close() { if (closed) return; closed = true; objs.forEach((o) => o?.destroy?.()); onClose?.(); } }; +} + +const txt = (scene, x, y, s, size, color, depth, style = {}) => scene.add.text(x, y, s, { + fontFamily: UI_FONT, fontSize: `${size}px`, color, ...style, +}).setDepth(depth); + +const SPEED = { full: 'Full cinematic', quick: 'Quick', off: 'Off (on the board)' }; +const REVEAL = { assisted: 'Assisted: stay revealed', classic: 'Classic: back face-down' }; +const DEPLOY = { empty: 'Empty barracks', last: 'Last formation', random: 'Random formation' }; +const onOff = (v) => (v ? 'On' : 'Off'); + +/** The new-game card. prefs = { variant, reveal, speed, deploy }. */ +export function openNewGame(scene, { prefs, depth, opponentName, onStart, onLeave }) { + const objs = [blocker(scene, depth - 1, 0.65)]; + const w = 820, h = 680; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(...frame(scene, x, y, w, h, depth, 'Mission Briefing')); + const p = { ...prefs }; + const cx = x + w / 2; + objs.push(txt(scene, cx, y + 104, `Terran Vanguard against ${opponentName} of the Helix Dominion.`, 18, HUE.inkDim, depth + 1).setOrigin(0.5)); + const labelX = x + 64, ctlX = x + 560; + const rowY = (i) => y + 172 + i * 80; + const rows = []; + const addRow = (i, title, get, fn) => { + objs.push(txt(scene, labelX, rowY(i), title, 22, HUE.ink, depth + 1).setOrigin(0, 0.5)); + const btn = new Button(scene, ctlX, rowY(i), get(), () => { fn(); refresh(); }, { width: 400, height: 48, fontSize: 18, bg: BTN }).setDepth(depth + 2); + objs.push(btn); + rows.push({ btn, get }); + }; + const cyc = (list, v) => list[(list.indexOf(v) + 1) % list.length]; + addRow(0, 'Rules', () => `${VARIANTS[p.variant].name} (${VARIANTS[p.variant].size} units)`, () => { p.variant = cyc(VARIANT_ORDER, p.variant); }); + addRow(1, 'After a battle', () => REVEAL[p.reveal], () => { p.reveal = p.reveal === 'assisted' ? 'classic' : 'assisted'; }); + addRow(2, 'Battle scenes', () => SPEED[p.speed], () => { p.speed = cyc(['full', 'quick', 'off'], p.speed); }); + addRow(3, 'Start deployment with', () => DEPLOY[p.deploy], () => { p.deploy = cyc(['empty', 'last', 'random'], p.deploy); }); + const blurb = txt(scene, cx, y + 520, '', 17, HUE.inkDim, depth + 1, { align: 'center', wordWrap: { width: w - 120 } }).setOrigin(0.5); + objs.push(blurb); + function refresh() { + rows.forEach((r) => r.btn.setLabel(r.get())); + const rev = p.reveal === 'classic' + ? 'Classic: after a fight the survivor turns back face-down, as on the real board. You have to remember what you saw.' + : 'Assisted: a unit that wins a fight stays face-up for the rest of the game.'; + blurb.setText(`${VARIANTS[p.variant].blurb}\n${rev}`); + } + refresh(); + let hRef = null; + objs.push(new Button(scene, cx - 140, y + h - 62, 'Begin Deployment', () => { hRef.close(); onStart({ ...p }); }, + { width: 250, height: 52, fontSize: 19, bg: BTN_GO }).setDepth(depth + 2)); + objs.push(new Button(scene, cx + 140, y + h - 62, 'Leave', () => { hRef.close(); onLeave(); }, + { width: 250, height: 52, fontSize: 19, bg: BTN_WARN }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} + +export function openPauseMenu(scene, { settings, match, depth, onChange, onRules, onNewGame, onResign, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.6)]; + const w = 660, h = 820; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(...frame(scene, x, y, w, h, depth, 'Command Menu')); + const cx = x + w / 2; + let hRef = null; + const cyc = (k, order) => onChange(k, order[(order.indexOf(settings[k]) + 1) % order.length]); + const rows = [ + ['Resume', () => hRef.close(), BTN_GO], + [() => `Battle scenes: ${SPEED[settings.speed]}`, () => cyc('speed', ['full', 'quick', 'off'])], + [() => `Show legal moves: ${onOff(settings.showMoves)}`, () => onChange('showMoves', !settings.showMoves)], + [() => `Mark enemy units that have moved: ${onOff(settings.autoMarks)}`, () => onChange('autoMarks', !settings.autoMarks)], + [() => `Intel estimates on hover: ${onOff(settings.intel)}`, () => onChange('intel', !settings.intel)], + [() => `Ship ambience: ${onOff(settings.ambience)}`, () => onChange('ambience', !settings.ambience)], + ['How to Play', () => onRules()], + ['New Game…', () => { hRef.close(); onNewGame(); }, BTN_ALT], + ]; + if (match === 'play') rows.push(['Surrender', () => { hRef.close(); onResign(); }, BTN_WARN]); + rows.push(['Leave the Deck', () => { hRef.close(); onLeave(); }, BTN_WARN]); + rows.forEach(([label, fn, bg], i) => { + const text = typeof label === 'function' ? label() : label; + const btn = new Button(scene, cx, y + 130 + i * 58, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, { + width: 560, height: 46, fontSize: 17, bg: bg ?? BTN, + }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(txt(scene, cx, y + h - 52, + 'Click a unit, then a square · or drag it · right-click an enemy unit to tag a guess\nSpace skip battle · Z undo · H hint · Esc menu', + 14, HUE.inkDim, depth + 1, { align: 'center' }).setOrigin(0.5)); + hRef = handle(objs, onClose); + return hRef; +} + +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', yesBg = BTN_WARN, depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.6)]; + const w = 600, h = 300; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(...frame(scene, x, y, w, h, depth)); + objs.push(scene.add.text(x + w / 2, y + 62, heading, { fontFamily: DISPLAY_FONT, fontSize: '28px', color: HUE.ink }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(txt(scene, x + w / 2, y + 138, text, 18, HUE.inkDim, depth + 1, { align: 'center', wordWrap: { width: w - 90 } }).setOrigin(0.5)); + let hRef = null; + if (no) { + objs.push(new Button(scene, x + w / 2 - 128, y + h - 58, yes, () => { hRef.close(); onYes?.(); }, { width: 230, height: 48, fontSize: 18, bg: yesBg }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 128, y + h - 58, no, () => { hRef.close(); onNo?.(); }, { width: 230, height: 48, fontSize: 18, bg: BTN }).setDepth(depth + 2)); + } else { + objs.push(new Button(scene, x + w / 2, y + h - 58, yes, () => { hRef.close(); onYes?.(); }, { width: 240, height: 48, fontSize: 18, bg: BTN_GO }).setDepth(depth + 2)); + } + hRef = handle(objs); + return hRef; +} + +export function toast(scene, text, { depth, x = 838, y = 1004, ms = 2600, color = HUE.ink } = {}) { + const t = scene.add.text(x, y, text, { + fontFamily: UI_FONT, fontSize: '19px', color, backgroundColor: '#0b1828', padding: { x: 18, y: 10 }, + align: 'center', wordWrap: { width: 800 }, + }).setOrigin(0.5).setDepth(depth).setAlpha(0); + scene.tweens.add({ targets: t, alpha: 1, duration: 180 }); + scene.tweens.add({ targets: t, alpha: 0, delay: ms, duration: 400, onComplete: () => t.destroy() }); + return t; +} + +// ── formation previews ──────────────────────────────────────────────────────── +const CODE_COLOR = (rank) => { + if (rank === FLAG) return [0xffd34a, '#1a1206']; + if (rank === BOMB) return [0x3a3f48, '#ffb547']; + if (rank === SPY) return [0x6a3fa0, '#ffffff']; + if (rank >= 8 || rank === MARSHAL) return [0xc2402f, '#ffffff']; + if (rank >= 5) return [0x8a3a2c, '#ffe2d8']; + return [0x4a2a24, '#ffd2c4']; +}; +/** A 10×4 mini-map of a layout (front line on top, as you'd see it). */ +export function drawLayoutPreview(scene, x, y, layout, cell, depth) { + const objs = []; + const g = scene.add.graphics().setDepth(depth); + objs.push(g); + g.fillStyle(0x050b16, 1).fillRoundedRect(x - 4, y - 4, cell * 10 + 8, cell * 4 + 8, 5); + for (let i = 0; i < 40; i++) { + const li = Math.floor(i / 10), c = i % 10; + const rank = layout ? codeRank(layout[i]) : null; + const cx = x + c * cell, cy = y + li * cell; + if (rank == null) { g.lineStyle(1, HUE.cyan, 0.18).strokeRect(cx + 1, cy + 1, cell - 2, cell - 2); continue; } + const [bg, fg] = CODE_COLOR(rank); + g.fillStyle(bg, 1).fillRect(cx + 1, cy + 1, cell - 2, cell - 2); + if (cell >= 16) { + objs.push(scene.add.text(cx + cell / 2, cy + cell / 2, layout[i], { fontFamily: DISPLAY_FONT, fontSize: `${Math.round(cell * 0.6)}px`, color: fg }) + .setOrigin(0.5).setDepth(depth + 1)); + } + } + return objs; +} + +/** Formations: built-in presets plus three saved slots. */ +export function openFormations(scene, { variant, current, depth, onApply, onClose }) { + const objs = [blocker(scene, depth - 1, 0.65)]; + const w = 1320, h = 900; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(...frame(scene, x, y, w, h, depth, 'Formations')); + let hRef = null; + const presets = presetsFor(variant); + objs.push(txt(scene, x + 60, y + 96, 'Built-in formations: each deploys with small random variations.', 16, HUE.inkDim, depth + 1)); + const cell = 19, cardW = 380, cardH = 196; + presets.forEach((pr, i) => { + const col = i % 3, row = Math.floor(i / 3); + const px = x + 50 + col * (cardW + 26), py = y + 130 + row * (cardH + 18); + const g = scene.add.graphics().setDepth(depth + 1); + g.fillStyle(0x0a1626, 1).fillRoundedRect(px, py, cardW, cardH, 10); + g.lineStyle(1, HUE.cyan, 0.35).strokeRoundedRect(px, py, cardW, cardH, 10); + objs.push(g); + objs.push(scene.add.text(px + 16, py + 12, pr.name, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: HUE.ink }).setDepth(depth + 2)); + objs.push(...drawLayoutPreview(scene, px + 16, py + 46, pr.layout, cell, depth + 2)); + objs.push(txt(scene, px + 222, py + 46, pr.blurb, 13, HUE.inkDim, depth + 2, { wordWrap: { width: cardW - 234 } })); + objs.push(new Button(scene, px + cardW - 80, py + cardH - 30, 'Deploy', () => { hRef.close(); onApply(randomize(pr.layout)); }, + { width: 130, height: 38, fontSize: 16, bg: BTN_GO }).setDepth(depth + 3)); + }); + // saved slots + const sy = y + 130 + Math.ceil(presets.length / 3) * (cardH + 18) + 14; + objs.push(txt(scene, x + 60, sy, 'Your saved formations', 18, HUE.ink, depth + 1)); + const canSave = layoutValid(current, variant); + const slots = loadSlots(variant); + const slotObjs = []; + const drawSlots = () => { + slotObjs.forEach((o) => o.destroy()); slotObjs.length = 0; + const list = loadSlots(variant); + for (let i = 0; i < SLOT_COUNT; i++) { + const px = x + 50 + i * (cardW + 26), py = sy + 34; + const g = scene.add.graphics().setDepth(depth + 1); + g.fillStyle(0x0a1626, 1).fillRoundedRect(px, py, cardW, 160, 10); + g.lineStyle(1, HUE.amber, 0.35).strokeRoundedRect(px, py, cardW, 160, 10); + slotObjs.push(g); + const e = list[i]; + slotObjs.push(scene.add.text(px + 16, py + 10, e ? e.name : `Slot ${i + 1} (empty)`, { fontFamily: DISPLAY_FONT, fontSize: '18px', color: e ? HUE.ink : HUE.inkDim }).setDepth(depth + 2)); + slotObjs.push(...drawLayoutPreview(scene, px + 16, py + 42, e?.layout ?? null, cell, depth + 2)); + if (e) { + slotObjs.push(new Button(scene, px + cardW - 74, py + 62, 'Load', () => { hRef.close(); onApply(e.layout); }, + { width: 120, height: 38, fontSize: 16, bg: BTN_GO }).setDepth(depth + 3)); + } + const sb = new Button(scene, px + cardW - 74, py + 112, e ? 'Overwrite' : 'Save here', () => { + if (!canSave) return; + saveSlot(variant, i, current, `Formation ${i + 1}`); + drawSlots(); + }, { width: 120, height: 38, fontSize: 15, bg: canSave ? BTN_ALT : 0x2a2a2a }).setDepth(depth + 3); + if (!canSave) sb.setAlpha(0.5); + slotObjs.push(sb); + } + }; + void slots; + drawSlots(); + if (!canSave) objs.push(txt(scene, x + w - 60, sy, 'Deploy every unit to save this formation.', 15, HUE.amberHex, depth + 1).setOrigin(1, 0)); + objs.push(new Button(scene, x + w / 2, y + h - 46, 'Close', () => hRef.close(), { width: 220, height: 46, fontSize: 18, bg: BTN }).setDepth(depth + 2)); + hRef = handle(objs, () => { slotObjs.forEach((o) => o.destroy()); onClose?.(); }); + return hRef; +} + +/** Guess tag picker for a hidden enemy unit, near (x, y). */ +export const GUESS_LABELS = ['B', 'F', 'S', '2', '3', '4', '5', '6', '7', '8', '9', 'M', '?', '≥7', '≤4']; +export function openGuessPicker(scene, { x, y, depth, current, onPick, onClose }) { + const objs = []; + const shield = scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.001).setDepth(depth - 1).setInteractive(); + objs.push(shield); + const cols = 5, bw = 50, bh = 40, pad = 10; + const w = cols * (bw + 6) + pad * 2 - 6, h = 3 * (bh + 6) + pad * 2 + 70; + const px = Math.min(Math.max(10, x - w / 2), GAME_WIDTH - w - 10), py = Math.min(Math.max(10, y + 46), GAME_HEIGHT - h - 10); + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x08111e, 0.97).fillRoundedRect(px, py, w, h, 10); + g.lineStyle(2, HUE.amber, 0.9).strokeRoundedRect(px, py, w, h, 10); + objs.push(g); + objs.push(txt(scene, px + w / 2, py + 16, 'Tag your guess', 15, HUE.amberHex, depth + 1).setOrigin(0.5)); + let hRef = null; + GUESS_LABELS.forEach((lab, i) => { + const cx = px + pad + (i % cols) * (bw + 6) + bw / 2, cy = py + 34 + pad + Math.floor(i / cols) * (bh + 6) + bh / 2; + objs.push(new Button(scene, cx, cy, lab, () => { hRef.close(); onPick(lab); }, { + width: bw, height: bh, fontSize: 16, bg: lab === current ? 0x7a5a12 : BTN, + }).setDepth(depth + 1)); + }); + objs.push(new Button(scene, px + w / 2, py + h - 26, 'Clear tag', () => { hRef.close(); onPick(null); }, { width: w - 30, height: 34, fontSize: 14, bg: BTN_WARN }).setDepth(depth + 1)); + shield.on('pointerdown', () => hRef.close()); + hRef = handle(objs, onClose); + return hRef; +} diff --git a/src/games/stratego/StrategoEndScreen.js b/src/games/stratego/StrategoEndScreen.js new file mode 100644 index 0000000..4dd32de --- /dev/null +++ b/src/games/stratego/StrategoEndScreen.js @@ -0,0 +1,85 @@ +// StrategoEndScreen.js: the after-action report. The scene flips every unit +// face-up across the board first; this panel then sums up the engagement. +// "Inspect Board" closes it (the rail keeps the same buttons). + +import { GAME_WIDTH } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { DISPLAY_FONT, UI_FONT, HUE } from './StrategoArt.js'; +import { frame, blocker, handle, BTN, BTN_GO, BTN_WARN, BTN_ALT } from './StrategoDialogs.js'; +import { FLAG, BOMB, rankName } from './StrategoData.js'; +import { BOARD_CX, BOARD_CY } from './StrategoLayout.js'; + +const REASONS = { + flag: (won) => (won ? 'You captured the enemy flag.' : 'The enemy captured your flag.'), + nomoves: (won) => (won ? 'The enemy has no units left that can move.' : 'You have no units left that can move.'), + resign: (won) => (won ? 'The enemy commander surrendered.' : 'You surrendered the sector.'), + ply: () => 'No unit was captured for too long: the front froze into a stalemate.', + immobile: () => 'Neither side has a unit that can move.', +}; + +/** Numbers for the report, from the finished state's log. */ +export function gameStats(state, human) { + const foe = 1 - human; + const st = { moves: 0, battles: 0, won: 0, lost: 0, traded: 0, longestRun: 0, bombsFound: 0, plies: state.ply }; + for (const e of state.log) { + if (e.seat === human) { st.moves++; if (!e.attack) st.longestRun = Math.max(st.longestRun, e.dist); } + if (!e.attack) continue; + st.battles++; + if (e.result === 'both') st.traded++; + else if ((e.result === 'attacker') === (e.seat === human)) st.won++; + else st.lost++; + if (e.seat === human && e.dRank === BOMB) st.bombsFound++; + } + st.killed = state.captured[foe].filter((r) => r !== FLAG).length; + st.casualties = state.captured[human].filter((r) => r !== FLAG).length; + const top = state.captured[foe].filter((r) => r !== FLAG && r !== BOMB).sort((a, b) => b - a)[0]; + st.bestKill = top != null ? rankName(top) : '—'; + return st; +} + +export function openEndScreen(scene, { state, human, depth, record, onReplay, onRematch, onNewGame, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.35)]; + const w = 720, h = 640; + const x = BOARD_CX - w / 2, y = BOARD_CY - h / 2; + const draw = state.winner == null; + const won = state.winner === human; + objs.push(...frame(scene, x, y, w, h, depth)); + const headline = draw ? 'STALEMATE' : won ? 'VICTORY' : 'DEFEAT'; + const color = draw ? HUE.amberHex : won ? '#8dffb4' : '#ff7d6b'; + objs.push(scene.add.image(x + w / 2, y + 86, `sg-crest-${draw ? human : state.winner}`).setDepth(depth + 1).setScale(0.62)); + objs.push(scene.add.text(x + w / 2, y + 170, headline, { + fontFamily: DISPLAY_FONT, fontSize: '58px', color, stroke: '#000000', strokeThickness: 6, + }).setOrigin(0.5).setDepth(depth + 1).setShadow(0, 0, color, 18, true, true)); + objs.push(scene.add.text(x + w / 2, y + 222, (REASONS[state.endReason] ?? REASONS.flag)(won), { + fontFamily: UI_FONT, fontSize: '19px', color: HUE.ink, + }).setOrigin(0.5).setDepth(depth + 1)); + + const st = gameStats(state, human); + const rows = [ + ['Your moves', st.moves], ['Battles', `${st.battles} (won ${st.won} · lost ${st.lost} · traded ${st.traded})`], + ['Enemy units destroyed', st.killed], ['Your casualties', st.casualties], + ['Highest rank you took', st.bestKill], ['Bombs you ran into', st.bombsFound], + ['Longest scout run', st.longestRun > 1 ? `${st.longestRun} squares` : '—'], + ]; + if (record) rows.push(['Record vs this commander', `${record.w}W · ${record.l}L · ${record.d}D`]); + rows.forEach(([k, v], i) => { + const ry = y + 266 + i * 34; + objs.push(scene.add.text(x + 90, ry, k, { fontFamily: UI_FONT, fontSize: '18px', color: HUE.inkDim }).setDepth(depth + 1)); + objs.push(scene.add.text(x + w - 90, ry, String(v), { fontFamily: DISPLAY_FONT, fontSize: '19px', color: HUE.ink }).setOrigin(1, 0).setDepth(depth + 1)); + }); + let hRef = null; + const by = y + h - 62, bw = 150; + const btns = [ + ['Replay', () => { hRef.close(); onReplay(); }, BTN], + ['Inspect Board', () => hRef.close(), BTN], + ['Rematch', () => { hRef.close(); onRematch(); }, BTN_GO], + ['New Game', () => { hRef.close(); onNewGame(); }, BTN_ALT], + ]; + btns.forEach(([label, fn, bg], i) => { + objs.push(new Button(scene, x + 56 + bw / 2 + i * (bw + 10), by, label, fn, { width: bw, height: 48, fontSize: 16, bg }).setDepth(depth + 2)); + }); + objs.push(new Button(scene, x + w - 24 - 20, y + 30, '✕', () => hRef.close(), { width: 40, height: 36, fontSize: 18, bg: BTN_WARN }).setDepth(depth + 2)); + void onLeave; void GAME_WIDTH; + hRef = handle(objs, onClose); + return hRef; +} diff --git a/src/games/stratego/StrategoEngine.js b/src/games/stratego/StrategoEngine.js new file mode 100644 index 0000000..1793cd0 --- /dev/null +++ b/src/games/stratego/StrategoEngine.js @@ -0,0 +1,76 @@ +// StrategoEngine.js: runs the opposing commander (StrategoAI) off the main +// thread so the command deck keeps animating while it thinks. +// +// handle(kind, payload) the actual work (shared by the worker and the +// inline fallback) +// class Engine main-thread client: request(kind, payload) → +// Promise. Uses a module Worker (StrategoWorker.js); +// if that can't start, runs the same code inline. +// +// Kinds (view = StrategoLogic.viewFor(state, seat): never the raw state): +// move { view, skill } → { fr, fc, tr, tc, score } +// hint { view, ms } → { fr, fc, tr, tc, score } +// belief { view, id } → [{ rank, p }] most likely first + +import * as AI from './StrategoAI.js'; + +export function handle(kind, p) { + switch (kind) { + case 'move': return AI.chooseMove(p.view, p.skill); + case 'hint': return AI.hint(p.view, { ms: p.ms ?? 900 }); + case 'belief': return AI.beliefFor(p.view, p.id); + default: return null; + } +} + +export class Engine { + constructor() { + this.seq = 0; + this.pending = new Map(); + this.worker = null; + try { + if (typeof Worker !== 'undefined') { + this.worker = new Worker(new URL('./StrategoWorker.js', import.meta.url), { type: 'module' }); + this.worker.onmessage = (e) => this.settle(e.data); + this.worker.onerror = (e) => { e?.preventDefault?.(); this.fallBack(); }; + } + } catch (_) { this.worker = null; } + } + + settle({ id, res, err }) { + const job = this.pending.get(id); + if (!job) return; + this.pending.delete(id); + if (err) job.reject(new Error(err)); else job.resolve(res); + } + + fallBack() { + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + for (const [id, job] of this.pending) this.runInline(id, job.kind, job.payload); + } + + runInline(id, kind, payload) { + setTimeout(() => { + let res = null, err = null; + try { res = handle(kind, payload); } catch (e) { err = String(e?.message ?? e); } + this.settle({ id, res, err }); + }, 0); + } + + request(kind, payload) { + const id = ++this.seq; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, kind, payload }); + if (this.worker) { + try { this.worker.postMessage({ id, kind, payload }); } catch (_) { this.fallBack(); } + } else this.runInline(id, kind, payload); + }); + } + + destroy() { + try { this.worker?.terminate(); } catch (_) { /* */ } + this.worker = null; + this.pending.clear(); + } +} diff --git a/src/games/stratego/StrategoGame.js b/src/games/stratego/StrategoGame.js index 2ffa8f0..3ce35a3 100644 --- a/src/games/stratego/StrategoGame.js +++ b/src/games/stratego/StrategoGame.js @@ -1,927 +1,1112 @@ +// StrategoGame.js: "Fog of War", Stratego rules on a starship's command deck. +// The scene only coordinates: rules in StrategoLogic, formations in +// StrategoSetups, the opposing commander in StrategoAI (run in a worker via +// StrategoEngine), geometry in StrategoLayout, art in StrategoArt, unit +// blocks in StrategoPieces, everything round the board in StrategoHud, +// engagements in StrategoBattle, pop-ups in StrategoDialogs, the report in +// StrategoEndScreen, talk in StrategoTalk, sound in StrategoSound. +// +// Flow: the briefing card (rules, reveal mode, battle speed, how to start +// deploying) → deployment (drag units from the Barracks onto your four rows, +// or pick a formation; the enemy is already deployed) → Deploy → play: +// click or drag a unit to move it; attacks play the engagement scene. +// Undo takes back quiet moves (never battles); Hint asks the engine. Right- +// click (or long-press) a hidden enemy unit to tag a guess. When the game +// ends every unit flips face-up and the report opens; Replay steps through +// the whole game with everything visible. Everything in progress is saved, +// so a reload resumes. +// +// Every async step carries the game's token: a new game, an undo or a resume +// bumps it, and anything still in flight from before is dropped. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; import { auth } from '../../services/auth.js'; -import { playSound, SFX, playScifiLaunch, playScifiExplode, playScifiRiser, playScifiReveal, playScifiWoosh } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { getGameSoundtrack } from '../../services/soundtrack.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { playSound, SFX } from '../../ui/Sounds.js'; import { - GRID, isLake, FLAG, BOMB, canMove, battleResult, - pieceFrame, rankLabel, rankName, RANKS, - PLAYER_COLORS, PLAYER_DARK, + GRID, FLAG, BOMB, SPY, MARSHAL, canMove, inSetupZone, rankName, RANK_NOTES, + PLAYER_COLORS, PLAYER_COLOR_HEX, variantOf, squareName, } from './StrategoData.js'; +import * as L from './StrategoLogic.js'; +import { aiLayout, randomLayout } from './StrategoSetups.js'; +import { clampSkill, nextThinkDelay, beliefFor } from './StrategoAI.js'; +import { Engine } from './StrategoEngine.js'; import { - createInitialState, startBattle, shuffleSetup, swapSetup, applyMove, - legalMovesFor, isGameOver, keyOf, -} from './StrategoLogic.js'; -import { chooseMove, nextThinkDelay } from './StrategoAI.js'; + W, H, TILE, PITCH, BX0, BY0, BOARD_W, FRAME, FOOTER, tileCenter, cellAt, +} from './StrategoLayout.js'; +import { prepareStrategoArt, DISPLAY_FONT, UI_FONT, HUE } from './StrategoArt.js'; +import { PieceView } from './StrategoPieces.js'; +import { Hud } from './StrategoHud.js'; +import { playBattle } from './StrategoBattle.js'; +import { + openNewGame, openPauseMenu, openFormations, openGuessPicker, confirmBox, + BTN_GO, BTN_WARN, BTN_ALT, +} from './StrategoDialogs.js'; +import { openEndScreen } from './StrategoEndScreen.js'; +import { tierOf, opponentLine, computerLine } from './StrategoTalk.js'; +import * as SND from './StrategoSound.js'; -// ── Layout ─────────────────────────────────────────────────────────────────── -const TILE = 84, GAP = 2, PITCH = TILE + GAP; -const BOARD_W = GRID * PITCH - GAP; // 858 -const BX0 = 120, BY0 = 130; // board top-left -const RAIL_X = BX0 + BOARD_W + 50; // ~1028 -const RAIL_W = GAME_WIDTH - RAIL_X - 30; // ~862 - -const DEPTH = { - bg: 0, board: 5, cell: 6, lake: 7, mark: 9, piece: 12, glyph: 13, - sel: 16, ui: 40, drag: 55, popup: 60, banner: 90, +const SETTINGS_KEY = 'stratego-settings'; +const SAVE_KEY = 'stratego-save-v2'; +const RECORD_KEY = 'stratego-record'; +const DEFAULT_SETTINGS = { + speed: 'full', showMoves: true, autoMarks: true, intel: true, ambience: true, + setup: { variant: 'classic', reveal: 'assisted', speed: 'full', deploy: 'last' }, + lastLayout: {}, }; - -// Unit reference panel — special ability notes per rank. -const REF_SPECIALS = { - 0: 'Capture the enemy Flag to win', - 1: 'Defeats the Marshal when attacking', - 2: 'Moves any number of squares in a straight line', - 3: 'Defuses Bombs', - 10: 'Highest rank · Vulnerable only to the Spy', - 11: 'Destroys all attackers except Miners', -}; - -// Battle cinematic stage layout -const STAGE_SIZE = Math.round(140 / 0.78); // ~179 — body size that makes sprite render at 140×140 -const STAGE_CX = BX0 + BOARD_W / 2; // 549 — horizontal center of board -const STAGE_CY = GAME_HEIGHT / 2; // 540 — vertical center of screen -const STAGE_OFFSET = 130; // px each piece sits from center +const D = { bg: 0, board: 2, fx: 4, mark: 6, piece: 12, sel: 20, hover: 22, ghost: 40, hud: 50, tip: 85, battle: 90, end: 110, modal: 130 }; +const HUMAN = 0, AI = 1; +const DRAG_PX = 9; export default class StrategoGame extends Phaser.Scene { constructor() { super('StrategoGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.humanSeat = 0; - this.aiSeat = 1; - this.gs = null; - this.busy = false; - this.selected = null; // {r,c} selected own piece (play) - this.legal = []; // legal destinations for selected piece - this.setupSel = null; // first-tapped piece during setup swap - this.dyn = []; - this.portraits = []; - this._endObjs = []; + this.initData = data ?? {}; + this.gameDef = this.initData.game; + this.opponents = this.initData.opponents ?? []; + this.opp = this.opponents[0] ?? { id: 'dominion-regular', name: 'Commander Vex', skill: 3 }; + this.oppName = this.opp.name ?? 'Opponent'; + this.skill = clampSkill(this.opp.skill ?? 3); + this.tier = tierOf(this.skill); + this.phase = 'boot'; // boot | setup | human | ai | anim | over | replay + this.token = 0; + this.gs = null; + this.start = null; + this.views = new Map(); + this.selected = null; + this.legal = []; + this.trayPick = null; + this.setupSel = null; + this.drag = null; + this.tags = {}; + this.undoStack = []; + this.modal = null; + this.battle = null; + this.hintMove = null; + this.saidFlagNear = false; + this.lastTalkPly = -99; + this.replay = null; + this.ended = false; + try { + const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + this.settings = { + ...DEFAULT_SETTINGS, ...s, + setup: { ...DEFAULT_SETTINGS.setup, ...(s.setup ?? {}) }, + lastLayout: { ...(s.lastLayout ?? {}) }, + }; + } catch (_) { this.settings = { ...DEFAULT_SETTINGS, setup: { ...DEFAULT_SETTINGS.setup }, lastLayout: {} }; } } create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* optional */ } - this.hasPieces = this.textures.exists('stratego-pieces'); - - const opp = this.opponents[0] ?? null; - this.aiSkill = Math.max(1, Math.min(5, opp?.skill ?? 3)); - const names = [auth.user?.username ?? 'You', opp?.name ?? 'Opponent']; - - this.gs = createInitialState({ names }); - - this.buildBackground(); - this.buildPortraits(); - this.buildCellZones(); - this.buildReferencePanel(); - this.render(); - } - - // ── static chrome ────────────────────────────────────────────────────────── - buildBackground() { - const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.bg); - } else { - const g = this.add.graphics().setDepth(DEPTH.bg); - g.fillGradientStyle(0x16140f, 0x16140f, 0x080706, 0x080706, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - } - this.add.text(GAME_WIDTH / 2, 22, 'Stratego', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui); - - new Button(this, GAME_WIDTH - 96, GAME_HEIGHT - 36, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 140, height: 42, fontSize: 18 }).setDepth(DEPTH.ui); - } - - buildPortraits() { - const r = 40; - const top = 150; - // Opponent (top of rail), You (below). - this.portraits[this.aiSeat] = createOpponentPortrait(this, this.opponents[0], RAIL_X + 52, top, r, DEPTH.ui + 1); - this.portraits[this.humanSeat] = createPlayerPortrait(this, RAIL_X + 52, top + 230, r, DEPTH.ui + 1, 'StrategoGame'); - } - - // Persistent invisible click targets, one per board cell. Created once. - buildCellZones() { - this.cellZones = []; - for (let r = 0; r < GRID; r++) { - this.cellZones[r] = []; - for (let c = 0; c < GRID; c++) { - const { x, y } = this.tileCenter(r, c); - const z = this.add.zone(x, y, TILE, TILE).setInteractive({ useHandCursor: true }); - z.setDepth(DEPTH.sel); - z._rc = { r, c }; - z.on('pointerdown', () => this.onCellDown(r, c)); - z.on('pointerup', () => this.onCellUp(r, c)); - this.cellZones[r][c] = z; - } - } - } - - buildReferencePanel() { - const panelY = 556; - const panelH = (GAME_HEIGHT - 120) - 26 - 14 - panelY; // ends 14px above Shuffle button top → 364 - const headerH = 36; - const contentY = panelY + headerH; - const contentH = panelH - headerH; // 328 - const ROW_H = 76; - const rankOrder = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; - const totalContentH = rankOrder.length * ROW_H; // 912 - - // Panel chrome (never destroyed — built once). - const chrome = this.add.graphics().setDepth(DEPTH.ui); - chrome.fillStyle(0x080810, 0.88).fillRoundedRect(RAIL_X, panelY, RAIL_W, panelH, 12); - chrome.lineStyle(1, COLORS.accent, 0.4).strokeRoundedRect(RAIL_X, panelY, RAIL_W, panelH, 12); - chrome.lineStyle(1, COLORS.accent, 0.2).lineBetween(RAIL_X + 8, contentY, RAIL_X + RAIL_W - 8, contentY); - - this.add.text(RAIL_X + 14, panelY + 9, 'Unit Reference', { - fontFamily: 'Righteous', fontSize: '18px', color: COLORS.textHex, - }).setDepth(DEPTH.ui + 1); - this.add.text(RAIL_X + RAIL_W - 14, panelY + 9, '↕ scroll', { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, - }).setOrigin(1, 0).setDepth(DEPTH.ui + 1); - - // Geometry mask clips content to the panel's inner area. - const maskGfx = this.add.graphics(); - maskGfx.fillStyle(0xffffff).fillRect(RAIL_X, contentY, RAIL_W, contentH); - const mask = maskGfx.createGeometryMask(); - - // Scrollable container — children use coords relative to container origin. - this._refCont = this.add.container(RAIL_X, contentY).setDepth(DEPTH.ui + 1); - this._refCont.setMask(mask); - this._refScrollY = 0; - this._refMaxScroll = Math.max(0, totalContentH - contentH); - this._refContentY = contentY; - this._refContentH = contentH; - - rankOrder.forEach((rank, i) => this._buildRefRow(rank, i * ROW_H)); - - // Wheel scrolling — only fires when pointer is over the content area. - this.input.on('wheel', (pointer, _gos, _dx, dy) => { - if (pointer.x < RAIL_X || pointer.x > RAIL_X + RAIL_W) return; - if (pointer.y < contentY || pointer.y > contentY + contentH) return; - this._refScrollY = Phaser.Math.Clamp( - this._refScrollY - dy * 0.5, - -this._refMaxScroll, 0, - ); - this._refCont.y = this._refContentY + this._refScrollY; + const { tracks, volume } = getGameSoundtrack(this); + if (tracks.length) new MusicPlayer(this, tracks, volume); + this.add.rectangle(W / 2, H / 2, W, H, 0x04060c).setDepth(-2); + prepareStrategoArt(this).then(() => { + if (!this.sys.isActive()) return; + this.build(); + this.begin(); }); } - _buildRefRow(rank, ry) { - const ICON = 50; - const textX = 70; - const info = RANKS[rank]; + // ── build ─────────────────────────────────────────────────────────────────── + build() { + this.add.image(0, 0, 'sg-deck').setOrigin(0).setDepth(D.bg); + this.add.image(FRAME.x, FRAME.y, 'sg-board').setOrigin(0).setDepth(D.board); + this.scan = this.add.tileSprite(BX0 - 10, BY0 - 10, BOARD_W + 20, BOARD_W + 20, 'sg-scan').setOrigin(0).setDepth(D.fx).setAlpha(0.8); + this.buildAsteroids(); + this.buildSweep(); + this.markG = this.add.graphics().setDepth(D.mark); + this.selG = this.add.graphics().setDepth(D.sel); + this.hoverG = this.add.graphics().setDepth(D.hover); + this.hintG = this.add.graphics().setDepth(D.sel + 1); + this.footer = this.add.text(FOOTER.x, FOOTER.y, '', { fontFamily: UI_FONT, fontSize: '15px', color: HUE.inkDim }).setOrigin(0.5).setDepth(D.hud); - if (ry > 0) { - const sep = this.add.graphics(); - sep.lineStyle(1, COLORS.accent, 0.12).lineBetween(8, ry, RAIL_W - 8, ry); - this._refCont.add(sep); - } + const name = auth.user?.username ?? 'You'; + this.hud = new Hud(this, D.hud, { + names: [name, this.oppName], skill: this.skill, opponent: this.opp, humanSeat: HUMAN, + onButton: (k) => this.onButton(k), + onTrayDown: (rank, p) => this.onTrayDown(rank, p), + }).build(); - // Icon tile. - const iconBg = this.add.graphics(); - iconBg.fillStyle(0x1a1a2e, 0.95).fillRoundedRect(8, ry + 13, ICON, ICON, 7); - iconBg.lineStyle(1, COLORS.accent, 0.35).strokeRoundedRect(8, ry + 13, ICON, ICON, 7); - this._refCont.add(iconBg); + this.engine = new Engine(); + this.ambience = new SND.Ambience(this); + if (this.settings.ambience) this.ambience.start(); - if (this.hasPieces) { - const img = this.add.image(8 + ICON / 2, ry + 13 + ICON / 2, 'stratego-pieces', pieceFrame(rank)) - .setDisplaySize(ICON * 0.78, ICON * 0.78); - this._refCont.add(img); - } else { - const lbl = this.add.text(8 + ICON / 2, ry + 13 + ICON / 2, rankLabel(rank), { - fontFamily: 'Righteous', fontSize: '17px', color: COLORS.textHex, - }).setOrigin(0.5); - this._refCont.add(lbl); - } - - // Name (left) + rank/count (right) on the same line. - this._refCont.add(this.add.text(textX, ry + 10, info.name, { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.textHex, - })); - const rankStr = info.canMove ? `Rank ${rankLabel(rank)}` : 'Immovable'; - const countStr = `${rankStr} · ×${info.count} per army`; - this._refCont.add(this.add.text(RAIL_W - 12, ry + 14, countStr, { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, - }).setOrigin(1, 0)); - - // Special ability (gold, larger). - const special = REF_SPECIALS[rank]; - if (special) { - this._refCont.add(this.add.text(textX, ry + 38, special, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.goldHex, - })); - } - } - - // ── geometry ──────────────────────────────────────────────────────────────── - tileCenter(r, c) { return { x: BX0 + c * PITCH + TILE / 2, y: BY0 + r * PITCH + TILE / 2 }; } - reg(o) { this.dyn.push(o); return o; } - clearDyn() { for (const o of this.dyn) { try { o.destroy(); } catch { /* */ } } this.dyn = []; } - - // What the human is allowed to see for a given piece. - faceUp(p) { return p.owner === this.humanSeat || p.revealed; } - - // ── render ───────────────────────────────────────────────────────────────── - render() { - this.clearDyn(); - this.drawBoard(); - this.drawMarks(); - this.drawPieces(); - this.drawSelection(); - this.drawRail(); - this.drawControls(); - this.drawStatus(); - } - - drawBoard() { - const g = this.reg(this.add.graphics().setDepth(DEPTH.board)); - g.fillStyle(0x000000, 0.5).fillRoundedRect(BX0 - 14, BY0 - 14, BOARD_W + 28, BOARD_W + 28, 14); - g.lineStyle(2, COLORS.accent, 0.55).strokeRoundedRect(BX0 - 14, BY0 - 14, BOARD_W + 28, BOARD_W + 28, 14); - - for (let r = 0; r < GRID; r++) { - for (let c = 0; c < GRID; c++) { - const { x, y } = this.tileCenter(r, c); - if (isLake(r, c)) { this.drawLake(x, y); continue; } - const cg = this.reg(this.add.graphics().setDepth(DEPTH.cell)); - const shade = (r + c) % 2 === 0 ? 0x586b46 : 0x4c5d3c; - cg.fillStyle(shade, 1).fillRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 6); - cg.lineStyle(1, 0x2c3624, 0.7).strokeRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 6); - } - } - } - - drawLake(x, y) { - const g = this.reg(this.add.graphics().setDepth(DEPTH.lake)); - g.fillStyle(0x2f6f8f, 1).fillRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 6); - g.fillStyle(0x3f88a8, 1); - for (let i = 0; i < 3; i++) { - const wy = y - TILE / 4 + i * (TILE / 4); - g.fillRoundedRect(x - TILE / 2 + 8, wy, TILE - 16, 4, 2); - } - g.lineStyle(1, 0x1d4a60, 0.8).strokeRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 6); - } - - // Last-move trail + battle flash. - drawMarks() { - const lm = this.gs.lastMove; - if (lm) { - const g = this.reg(this.add.graphics().setDepth(DEPTH.mark)); - g.lineStyle(3, COLORS.gold, 0.8); - for (const cell of [{ r: lm.fr, c: lm.fc }, { r: lm.tr, c: lm.tc }]) { - const { x, y } = this.tileCenter(cell.r, cell.c); - g.strokeRoundedRect(x - TILE / 2 + 2, y - TILE / 2 + 2, TILE - 4, TILE - 4, 5); - } - } - } - - drawPieces() { - for (let r = 0; r < GRID; r++) { - for (let c = 0; c < GRID; c++) { - const p = this.gs.board[r][c]; - if (!p) continue; - if (this._hidden && this._hidden.has(keyOf(r, c))) continue; // animating - - const { x, y } = this.tileCenter(r, c); - this.drawPiece(x, y, p, TILE - 8, this.faceUp(p)); - } - } - } - - // Draw a single piece. faceUp shows rank/character art; otherwise a coloured - // back. Used for the static board (adds via this.reg). - drawPiece(cx, cy, piece, size, faceUp) { - const objs = this.buildPieceObjects(piece, size, faceUp); - for (const o of objs) { o.x += cx; o.y += cy; this.reg(o.setDepth(o._depthBias + DEPTH.piece)); } - } - - // Returns an array of GameObjects positioned around (0,0) for a piece, each - // tagged with `_depthBias`. Shared by the board renderer and the move animator. - buildPieceObjects(piece, size, faceUp) { - const out = []; - const half = size / 2; - const color = PLAYER_COLORS[piece.owner]; - const dark = PLAYER_DARK[piece.owner]; - - // Body (medallion). - const body = this.add.graphics(); - body.fillStyle(dark, 1).fillRoundedRect(-half, -half, size, size, 8); - body.fillStyle(color, 1).fillRoundedRect(-half + 3, -half + 3, size - 6, size - 9, 7); - body.fillStyle(0xffffff, 0.08).fillRoundedRect(-half + 3, -half + 3, size - 6, (size - 9) * 0.4, 7); - body.lineStyle(2, 0x000000, 0.35).strokeRoundedRect(-half, -half, size, size, 8); - body._depthBias = 0; - out.push(body); - - if (!faceUp) { - // Face-down back: neutral insignia. - const g = this.add.graphics(); - g.lineStyle(2, 0x000000, 0.25); - for (let i = -2; i <= 2; i++) g.lineBetween(-half + 8, i * 10, half - 8, i * 10 - 22); - g.fillStyle(0x000000, 0.18).fillCircle(0, 0, size * 0.22); - g.lineStyle(2, 0xffffff, 0.4).strokeCircle(0, 0, size * 0.22); - g._depthBias = 1; - out.push(g); - return out; - } - - // Face-up: character art (spritesheet) or vector glyph, then corner number. - if (this.hasPieces) { - const img = this.add.image(0, 2, 'stratego-pieces', pieceFrame(piece.rank)) - .setDisplaySize(size * 0.78, size * 0.78); - img._depthBias = 1; - out.push(img); - // Rank number, upper-left (as in the real game). - out.push(this.cornerLabel(piece.rank, size)); - } else { - out.push(...this.vectorGlyph(piece.rank, size)); - } - return out; - } - - cornerLabel(rank, size) { - if (rank === FLAG || rank === BOMB) { - const t = this.add.text(-size / 2 + 6, -size / 2 + 4, rankLabel(rank), { - fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.2)}px`, color: '#ffffff', - }).setOrigin(0, 0); - t._depthBias = 2; return t; - } - const t = this.add.text(-size / 2 + 6, -size / 2 + 4, rankLabel(rank), { - fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.22)}px`, color: '#ffffff', - stroke: '#000000', strokeThickness: 3, - }).setOrigin(0, 0); - t._depthBias = 2; return t; - } - - // Code-drawn fallback when stratego-pieces.png isn't present yet. Big central - // glyph: a flag, a bomb, or the rank number. - vectorGlyph(rank, size) { - const out = []; - if (rank === FLAG) { - const g = this.add.graphics(); - g.lineStyle(3, 0xffffff, 0.95).lineBetween(-size * 0.16, -size * 0.3, -size * 0.16, size * 0.32); - g.fillStyle(0xffffff, 0.95).fillTriangle(-size * 0.16, -size * 0.3, size * 0.26, -size * 0.16, -size * 0.16, -size * 0.02); - g._depthBias = 1; out.push(g); - return out; - } - if (rank === BOMB) { - const g = this.add.graphics(); - g.fillStyle(0x161616, 0.92).fillCircle(0, size * 0.05, size * 0.28); - g.lineStyle(3, 0xffd27f, 0.95).lineBetween(size * 0.12, -size * 0.18, size * 0.24, -size * 0.32); - g.fillStyle(0xffd27f, 0.95).fillCircle(size * 0.24, -size * 0.32, 3.5); - g._depthBias = 1; out.push(g); - return out; - } - const t = this.add.text(0, 0, rankLabel(rank), { - fontFamily: 'Righteous', fontSize: `${Math.round(size * 0.5)}px`, color: '#ffffff', - stroke: '#000000', strokeThickness: 4, - }).setOrigin(0.5); - t._depthBias = 1; out.push(t); - // Tiny name under the number for readability without art. - const n = this.add.text(0, size * 0.32, rankName(rank).slice(0, 8), { - fontFamily: '"Julius Sans One"', fontSize: `${Math.round(size * 0.12)}px`, color: '#f2ead8', - }).setOrigin(0.5); - n._depthBias = 2; out.push(n); - return out; - } - - drawSelection() { - // Setup: highlight the first-tapped piece. Play: highlight selection + legal moves. - if (this.gs.phase === 'setup' && this.setupSel) { - const { x, y } = this.tileCenter(this.setupSel.r, this.setupSel.c); - this.reg(this.add.graphics().setDepth(DEPTH.sel)) - .lineStyle(4, COLORS.accent, 1).strokeRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 6); - } - if (this.selected) { - const { x, y } = this.tileCenter(this.selected.r, this.selected.c); - this.reg(this.add.graphics().setDepth(DEPTH.sel)) - .lineStyle(4, COLORS.gold, 1).strokeRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 6); - for (const m of this.legal) { - const ctr = this.tileCenter(m.r, m.c); - const g = this.reg(this.add.graphics().setDepth(DEPTH.sel)); - if (m.attack) { - g.lineStyle(4, COLORS.danger, 0.95).strokeRoundedRect(ctr.x - TILE / 2 + 2, ctr.y - TILE / 2 + 2, TILE - 4, TILE - 4, 5); - } else { - g.fillStyle(COLORS.gold, 0.45).fillCircle(ctr.x, ctr.y, TILE * 0.16); - } - } - } - } - - // ── right rail ─────────────────────────────────────────────────────────────── - drawRail() { - this.drawPlayerCard(this.aiSeat, RAIL_X, 96, false); - this.drawPlayerCard(this.humanSeat, RAIL_X, 326, true); - } - - drawPlayerCard(seat, x, y, isYou) { - const w = RAIL_W, h = 220; - const isCurrent = seat === this.gs.current && this.gs.phase === 'play' && !isGameOver(this.gs); - const g = this.reg(this.add.graphics().setDepth(DEPTH.ui)); - g.fillStyle(0x000000, 0.55).fillRoundedRect(x, y, w, h, 12); - g.lineStyle(isCurrent ? 3 : 1, isCurrent ? COLORS.gold : PLAYER_COLORS[seat], isCurrent ? 1 : 0.6) - .strokeRoundedRect(x, y, w, h, 12); - g.fillStyle(PLAYER_COLORS[seat], 1).fillCircle(x + 104, y + 26, 7); - - const name = this.gs.names[seat] + (isYou ? ' (you)' : ''); - this.reg(this.add.text(x + 120, y + 16, name, { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex, - }).setDepth(DEPTH.ui + 1)); - - const alive = this.aliveCount(seat); - const sub = this.gs.phase === 'setup' - ? (isYou ? 'Arrange your army' : 'Ready') - : (isCurrent ? 'Thinking…' : `${alive} pieces`); - this.reg(this.add.text(x + 120, y + 50, this.gs.phase === 'setup' ? sub : `${alive} pieces in play`, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setDepth(DEPTH.ui + 1)); - if (!isYou && this.gs.phase === 'play') { - this.reg(this.add.text(x + 120, y + 78, `Skill ${this.aiSkill}/5`, { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setDepth(DEPTH.ui + 1)); - } - - // Separator + captured pieces section. - g.lineStyle(1, COLORS.accent, 0.25).lineBetween(x + 12, y + 100, x + w - 12, y + 100); - this.reg(this.add.text(x + 14, y + 108, 'Captured', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex, - }).setDepth(DEPTH.ui + 1)); - - const ranks = this.gs.captured[seat]; - const sorted = [...ranks].sort((a, b) => (a === FLAG ? -1 : b === FLAG ? 1 : b - a)); - const S = 28, GAPX = 4, stride = S + GAPX; - const perRow = Math.floor((w - 28) / stride); - sorted.forEach((rank, i) => { - const col = i % perRow, row = Math.floor(i / perRow); - const px = x + 14 + col * stride, py = y + 126 + row * stride; - const tg = this.reg(this.add.graphics().setDepth(DEPTH.ui + 1)); - tg.fillStyle(0x000000, 0.4).fillRoundedRect(px, py, S, S, 4); - tg.lineStyle(1, COLORS.accent, 0.4).strokeRoundedRect(px, py, S, S, 4); - this.reg(this.add.text(px + S / 2, py + S / 2, rankLabel(rank), { - fontFamily: 'Righteous', fontSize: '14px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(DEPTH.ui + 2)); + this.input.mouse?.disableContextMenu(); + this.input.on('pointerdown', (p) => this.onPointerDown(p)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this.events.once('shutdown', () => { + this.ended = true; + this.token++; + this.ambience?.stop(); + this.engine?.destroy(); + this.replayTimer?.remove(); }); } - aliveCount(seat) { - let n = 0; - for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) - if (this.gs.board[r][c]?.owner === seat) n++; - return n; - } - - // ── controls (setup buttons / status) ───────────────────────────────────────── - drawControls() { - if (this._setupBtns) { for (const b of this._setupBtns) { try { b.destroy(); } catch { /* */ } } } - this._setupBtns = []; - if (this.gs.phase !== 'setup') return; - const y = GAME_HEIGHT - 120; - this._setupBtns.push(new Button(this, RAIL_X + 130, y, 'Shuffle', () => this.onShuffle(), - { width: 230, height: 52, fontSize: 22 }).setDepth(DEPTH.ui + 2)); - this._setupBtns.push(new Button(this, RAIL_X + 130, y + 64, 'Start Battle', () => this.onStartBattle(), - { width: 230, height: 52, fontSize: 22, variant: 'primary' }).setDepth(DEPTH.ui + 2)); - } - - drawStatus() { - let msg, color = COLORS.textHex; - if (isGameOver(this.gs)) { - msg = this.gs.winner == null ? 'Stalemate — a draw.' - : this.gs.winner === this.humanSeat ? 'You captured the flag — victory!' - : 'Your flag was captured.'; - color = COLORS.goldHex; - } else if (this.gs.phase === 'setup') { - msg = 'Drag/tap two of your pieces to swap them, then Start Battle.'; - } else if (this.busy || this.gs.current !== this.humanSeat) { - msg = `${this.gs.names[this.gs.current]} is moving…`; - } else { - msg = this.selected ? 'Tap a highlighted square to move, or tap your piece again to cancel.' - : 'Your turn — tap one of your pieces.'; + buildAsteroids() { + this.rocks = []; + for (const c0 of [2, 6]) { + const x0 = BX0 + c0 * PITCH, y0 = BY0 + 4 * PITCH, s = PITCH * 2 - 4; + for (let i = 0; i < 5; i++) { + const rock = this.add.image(x0 + 20 + Math.random() * (s - 40), y0 + 20 + Math.random() * (s - 40), `sg-rock-${i}`) + .setDepth(D.fx).setScale(0.35 + Math.random() * 0.45); + rock.spin = (Math.random() - 0.5) * 0.0012; + this.tweens.add({ + targets: rock, x: rock.x + (Math.random() - 0.5) * 40, y: rock.y + (Math.random() - 0.5) * 40, + duration: 5000 + Math.random() * 6000, yoyo: true, repeat: -1, ease: 'Sine.easeInOut', + }); + this.rocks.push(rock); + } } - this.reg(this.add.text(BX0 - 2, BY0 + BOARD_W + 24, msg, { - fontFamily: '"Julius Sans One"', fontSize: '20px', color, - }).setDepth(DEPTH.ui)); } - // ── input ──────────────────────────────────────────────────────────────────── - onCellDown(r, c) { - if (this.gs.phase === 'setup') { this._downKey = keyOf(r, c); return; } - if (this.gs.phase !== 'play' || this.busy || this.gs.current !== this.humanSeat) return; - this.handlePlayTap(r, c); + buildSweep() { + const line = this.add.rectangle(BX0 + BOARD_W / 2, BY0, BOARD_W + 10, 3, HUE.cyan, 0.3).setDepth(D.fx).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0); + const glow = this.add.image(BX0 + BOARD_W / 2, BY0, 'sg-glow').setDisplaySize(BOARD_W + 40, 40).setTint(HUE.cyan).setDepth(D.fx).setBlendMode(Phaser.BlendModes.ADD).setAlpha(0); + const sweep = () => { + if (this.ended) return; + line.y = BY0; glow.y = BY0; + this.tweens.add({ targets: [line, glow], alpha: { from: 0, to: 0.5 }, duration: 400, yoyo: true, hold: 2200 }); + this.tweens.add({ targets: [line, glow], y: BY0 + BOARD_W, duration: 3000, ease: 'Sine.easeInOut' }); + }; + this.time.addEvent({ delay: 11000, loop: true, callback: sweep, startAt: 8000 }); } - onCellUp(r, c) { - if (this.gs.phase !== 'setup') return; - const upKey = keyOf(r, c); - const a = this._downKey; - this._downKey = null; - if (a == null) return; - if (a === upKey) { this.handleSetupTap(r, c); return; } - // Drag from a→up: swap if both are your pieces. - this.trySetupSwap(a, upKey); + update(_t, dt) { + if (this.scan) this.scan.tilePositionY -= dt * 0.012; + if (this.rocks) for (const r of this.rocks) r.rotation += r.spin * dt; } - handleSetupTap(r, c) { - const p = this.gs.board[r][c]; - if (!p || p.owner !== this.humanSeat) { this.setupSel = null; this.render(); return; } - if (!this.setupSel) { this.setupSel = { r, c }; this.render(); return; } - const a = keyOf(this.setupSel.r, this.setupSel.c); - if (a === keyOf(r, c)) { this.setupSel = null; this.render(); return; } - this.trySetupSwap(a, keyOf(r, c)); + // ── settings / save ───────────────────────────────────────────────────────── + persistSettings() { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* */ } } + signature() { return `${this.opp.id ?? this.oppName}|${this.skill}`; } + loadSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 2 || s.sig !== this.signature() || !s.gs || s.gs.phase === 'over') return null; + return s; + } catch (_) { return null; } + } + save() { + if (!this.gs || this.gs.phase === 'over') return; + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ v: 2, sig: this.signature(), gs: this.gs, start: this.start, tags: this.tags, savedAt: Date.now() })); + } catch (_) { /* private mode */ } + } + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + readRecord() { try { return JSON.parse(localStorage.getItem(RECORD_KEY) || '{}'); } catch (_) { return {}; } } + bumpRecord(kind) { + const all = this.readRecord(); + const r = all[this.signature()] ?? { w: 0, l: 0, d: 0 }; + r[kind]++; + all[this.signature()] = r; + try { localStorage.setItem(RECORD_KEY, JSON.stringify(all)); } catch (_) { /* */ } + return r; } - trySetupSwap(k1, k2) { - const next = swapSetup(this.gs, k1, k2); - if (next !== this.gs) { this.gs = next; playSound(this, SFX.PIECE_CLICK); } - this.setupSel = null; - this.render(); + // ── start / resume ────────────────────────────────────────────────────────── + begin() { + const save = this.loadSave(); + if (save) { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Resume the engagement?', + text: `A game against ${this.oppName} is still in progress. Every unit is where you left it.`, + yes: 'Resume', no: 'Start Fresh', yesBg: BTN_GO, depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); this.resume(save); }, + onNo: () => { this.modal = null; this.clearSave(); this.openBriefing(); }, + }); + } else this.openBriefing(); } - handlePlayTap(r, c) { - const p = this.gs.board[r][c]; - // Tapping a legal destination of the current selection → move. - if (this.selected) { - const m = this.legal.find((q) => q.r === r && q.c === c); - if (m) { this.doHumanMove(this.selected.r, this.selected.c, r, c); return; } - // Tapping the same piece cancels; tapping another own piece reselects. - if (this.selected.r === r && this.selected.c === c) { this.clearSelection(); this.render(); return; } - } - if (p && p.owner === this.humanSeat && canMove(p.rank)) { - const moves = legalMovesFor(this.gs, r, c); - if (moves.length === 0) { this.clearSelection(); this.render(); return; } - this.selected = { r, c }; - this.legal = moves; - playSound(this, SFX.PIECE_CLICK); - this.render(); - return; - } - this.clearSelection(); - this.render(); - } - - clearSelection() { this.selected = null; this.legal = []; } - - // ── setup actions ───────────────────────────────────────────────────────────── - onShuffle() { - if (this.gs.phase !== 'setup') return; - this.gs = shuffleSetup(this.gs, this.humanSeat); - this.setupSel = null; - playSound(this, SFX.CARD_SHUFFLE); - this.render(); - } - - onStartBattle() { - if (this.gs.phase !== 'setup') return; - this.gs = startBattle(this.gs); - this.setupSel = null; - playSound(this, SFX.PIECE_CLICK); - this.render(); + resume(save) { + this.token++; + this.gs = save.gs; + this.start = save.start ?? null; + this.tags = save.tags ?? {}; + this.undoStack = []; + this.hud.say(computerLine('welcomeBack')); + if (this.gs.phase === 'setup') { this.enterSetup(false); return; } + this.clearViews(); this.advance(); } - // ── move execution (human + AI share the animation) ─────────────────────────── - doHumanMove(fr, fc, tr, tc) { - this.clearSelection(); - this.busy = true; - this.animateMove(fr, fc, tr, tc, () => { - this.gs = applyMove(this.gs, fr, fc, tr, tc); - this.busy = false; - this.advance(); - }); - } - - // Slide a ghost piece from source to destination; if it's an attack, briefly - // reveal both combatants with a clash flash before resolving. - animateMove(fr, fc, tr, tc, onDone, slideDuration = 230) { - const mover = this.gs.board[fr][fc]; - const target = this.gs.board[tr][tc]; - const from = this.tileCenter(fr, fc); - const to = this.tileCenter(tr, tc); - const size = TILE - 8; - - // Hide the static board piece(s) involved so they don't double the ghosts. - this._hidden = new Set([keyOf(fr, fc)]); - if (target) this._hidden.add(keyOf(tr, tc)); - this.render(); - - const finish = () => { this._hidden = null; onDone(); }; - - // Mover ghost: face-up if the human owns it or it's about to be revealed - // (any attack reveals it). Quiet AI moves stay face-down. - const moverFaceUp = this.faceUp(mover) || !!target; - const ghost = this.makeContainer(mover, size, moverFaceUp).setDepth(DEPTH.drag); - ghost.setPosition(from.x, from.y); - - this.tweens.add({ - targets: ghost, x: to.x, y: to.y, duration: slideDuration, ease: 'Cubic.easeInOut', - onComplete: () => { - if (!target) { ghost.destroy(); playSound(this, SFX.PIECE_CLICK); finish(); return; } - this.playBattle(ghost, mover, target, to, finish); + openBriefing() { + this.token++; + this.phase = 'boot'; + this.clearSel(); + this.hud.hidePortraits(); + this.hud.setStatus('Awaiting orders'); + this.hud.setControls([]); + this.modal = openNewGame(this, { + prefs: { ...this.settings.setup, speed: this.settings.speed }, depth: D.modal, opponentName: this.oppName, + onStart: (p) => { + this.modal = null; + this.hud.showPortraits(); + this.settings.setup = { ...p }; + this.settings.speed = p.speed; + this.persistSettings(); + this.startMatch(p); }, + onLeave: () => this.scene.start('GameMenu'), }); } - playBattle(ghost, mover, target, at, onDone) { - playSound(this, SFX.PIECE_CLICK); - const res = battleResult(mover.rank, target.rank); - const defenderWasHidden = !this.faceUp(target); - - // Destroy the small incoming ghost — replaced by larger stage containers. - ghost.destroy(); - - // Human piece is always left; AI piece always right. - const humanPiece = mover.owner === this.humanSeat ? mover : target; - const aiPiece = mover.owner === this.humanSeat ? target : mover; - const humanStageX = STAGE_CX - STAGE_OFFSET; - const aiStageX = STAGE_CX + STAGE_OFFSET; - - // Track all transient objects so we can clean up reliably. - const stageObjs = []; - - // ── Phase 0: dim + slide to stage ──────────────────────────────────────── - const dim = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0) - .setDepth(DEPTH.drag - 5); - stageObjs.push(dim); - this.tweens.add({ targets: dim, fillAlpha: 0.78, duration: 350 }); - - let humanCont = this.makeContainer(humanPiece, STAGE_SIZE, true) - .setPosition(at.x, at.y).setDepth(DEPTH.drag); - let aiCont = this.makeContainer(aiPiece, STAGE_SIZE, !defenderWasHidden) - .setPosition(at.x, at.y).setDepth(DEPTH.drag); - stageObjs.push(humanCont, aiCont); - - playScifiWoosh(this); - this.tweens.add({ targets: humanCont, x: humanStageX, y: STAGE_CY, duration: 2000, ease: 'Cubic.easeOut' }); - this.tweens.add({ - targets: aiCont, x: aiStageX, y: STAGE_CY, duration: 2000, ease: 'Cubic.easeOut', - onComplete: () => this._battleReveal( - aiCont, aiPiece, aiStageX, defenderWasHidden, stageObjs, - (resolvedAiCont) => { - aiCont = resolvedAiCont; - this._battleRankNumbers( - humanCont, aiCont, humanPiece, aiPiece, humanStageX, aiStageX, stageObjs, - (humanRankTxt, aiRankTxt) => { - this._battleResolve( - res, mover, humanCont, aiCont, humanPiece, aiPiece, - humanStageX, aiStageX, humanRankTxt, aiRankTxt, at, dim, stageObjs, onDone, - ); - }, - ); - }, - ), - }); + startMatch(p) { + this.token++; + const variant = p.variant; + let mine = null; + if (p.deploy === 'last') { + const last = this.settings.lastLayout?.[variant]; + mine = last && L.layoutValid(last, variant) ? last : null; + } else if (p.deploy === 'random') mine = randomLayout(variant); + const names = [auth.user?.username ?? 'You', this.oppName]; + this.gs = L.createInitialState({ names, variant, reveal: p.reveal, layouts: [mine, aiLayout(variant, this.skill)] }); + this.start = null; + this.tags = {}; + this.undoStack = []; + this.saidFlagNear = false; + this.replay = null; + this.clearViews(); + this.enterSetup(true); } - // ── Phase 1: shake + flip-reveal the AI piece if it was hidden ────────────── - _battleReveal(aiCont, aiPiece, aiStageX, defenderWasHidden, stageObjs, onDone) { - if (!defenderWasHidden) { onDone(aiCont); return; } - - playScifiRiser(this); - const prog = { t: 0 }; - this.tweens.add({ - targets: prog, t: 1, duration: 1500, ease: 'Linear', - onUpdate: () => { - const amp = prog.t * 22; - const freq = 7 + prog.t * 5; - aiCont.x = aiStageX + Math.sin(prog.t * freq * Math.PI * 2) * amp; - aiCont.y = STAGE_CY + Math.cos(prog.t * freq * Math.PI * 2 + 1) * amp * 0.25; - }, - onComplete: () => { - aiCont.x = aiStageX; - aiCont.y = STAGE_CY; - // Fold out (scaleX → 0). - this.tweens.add({ - targets: aiCont, scaleX: 0, duration: 250, ease: 'Sine.easeIn', - onComplete: () => { - // Swap to face-up container, fold in (scaleX 0 → 1). - playScifiReveal(this); - const idx = stageObjs.indexOf(aiCont); - try { aiCont.destroy(); } catch {} - const revealed = this.makeContainer(aiPiece, STAGE_SIZE, true) - .setPosition(aiStageX, STAGE_CY).setScale(0, 1).setDepth(DEPTH.drag); - if (idx >= 0) stageObjs[idx] = revealed; else stageObjs.push(revealed); - this.tweens.add({ - targets: revealed, scaleX: 1, duration: 250, ease: 'Sine.easeOut', - onComplete: () => onDone(revealed), - }); - }, - }); - }, - }); - } - - // ── Phase 2: rank numbers rise toward center ──────────────────────────────── - _battleRankNumbers(humanCont, aiCont, humanPiece, aiPiece, humanStageX, aiStageX, stageObjs, onDone) { - const mkRankTxt = (piece, x) => { - const px = 28 + piece.rank * 9; - return this.add.text(x, STAGE_CY, rankLabel(piece.rank), { - fontFamily: 'Righteous', fontSize: `${px}px`, color: '#ffffff', - stroke: '#000000', strokeThickness: Math.max(3, Math.round(px * 0.08)), - }).setOrigin(0.5).setDepth(DEPTH.drag + 2).setScale(0.2).setAlpha(0); - }; - - const humanTxt = mkRankTxt(humanPiece, humanStageX); - const aiTxt = mkRankTxt(aiPiece, aiStageX); - stageObjs.push(humanTxt, aiTxt); - - this.tweens.add({ - targets: humanTxt, scale: 1, alpha: 1, y: STAGE_CY - 120, x: humanStageX + 35, - duration: 750, ease: 'Cubic.easeOut', - }); - this.tweens.add({ - targets: aiTxt, scale: 1, alpha: 1, y: STAGE_CY - 120, x: aiStageX - 35, - duration: 750, ease: 'Cubic.easeOut', - onComplete: () => onDone(humanTxt, aiTxt), - }); - } - - // ── Phase 3 + 4: shoot, explode, fade loser; return winner ────────────────── - _battleResolve(res, mover, humanCont, aiCont, humanPiece, aiPiece, - humanStageX, aiStageX, humanRankTxt, aiRankTxt, at, dim, stageObjs, onDone) { - - // Map result to containers. - const attackerIsHuman = mover.owner === this.humanSeat; - let winnerCont, loserCont, winnerTxt, loserTxt; - - // Portrait emotion: AI upset when it loses a high-value piece; happy when it captures one. - const REACT_RANK = 6; - const aiLosesPiece = res === 'both' || - (res === 'attacker' && attackerIsHuman) || - (res === 'defender' && !attackerIsHuman); - const aiCapturesPiece = (res === 'attacker' && !attackerIsHuman) || - (res === 'defender' && attackerIsHuman); - const triggerEmotion = () => { - const ctrl = this.portraits[this.aiSeat]; - if (aiLosesPiece && aiPiece.rank >= REACT_RANK) ctrl?.playEmotion?.('upset'); - else if (aiCapturesPiece && humanPiece.rank >= REACT_RANK) ctrl?.playEmotion?.('happy'); - }; - if (res === 'attacker') { - [winnerCont, loserCont] = attackerIsHuman ? [humanCont, aiCont] : [aiCont, humanCont]; - [winnerTxt, loserTxt] = attackerIsHuman ? [humanRankTxt, aiRankTxt] : [aiRankTxt, humanRankTxt]; - } else if (res === 'defender') { - [winnerCont, loserCont] = attackerIsHuman ? [aiCont, humanCont] : [humanCont, aiCont]; - [winnerTxt, loserTxt] = attackerIsHuman ? [aiRankTxt, humanRankTxt] : [humanRankTxt, aiRankTxt]; - } - - // Outcome label — large yellow text centered above the rank numbers. - const humanWins = res === 'attacker' ? attackerIsHuman : !attackerIsHuman; - const outcomeStr = res === 'both' ? 'Both Lose' : humanWins ? 'Win' : 'Lose'; - const outcomeLabel = this.add.text(STAGE_CX, STAGE_CY - 200, outcomeStr, { - fontFamily: 'Righteous', fontSize: '72px', color: '#ffdd00', - stroke: '#000000', strokeThickness: 8, - }).setOrigin(0.5).setDepth(DEPTH.drag + 3).setAlpha(0); - stageObjs.push(outcomeLabel); - this.tweens.add({ targets: outcomeLabel, alpha: 1, duration: 300, ease: 'Power2' }); - - const fireShot = (srcX, srcY, dstX, dstY, onHit) => { - playScifiLaunch(this); - const shot = this.add.circle(srcX, STAGE_CY, 6, 0xff8800, 1).setDepth(DEPTH.drag + 3); - stageObjs.push(shot); - const prog = { t: 0 }; - this.tweens.add({ - targets: prog, t: 1, duration: 400, ease: 'Linear', - onUpdate: () => { - shot.x = srcX + (dstX - srcX) * prog.t; - shot.y = srcY + (dstY - srcY) * prog.t - 90 * Math.sin(prog.t * Math.PI); - }, - onComplete: () => { try { shot.destroy(); } catch {} onHit(); }, - }); - }; - - const fadeOut = (cont, txt) => { - this.tweens.add({ targets: cont, alpha: 0, duration: 450, delay: 120 }); - if (txt) this.tweens.add({ targets: txt, alpha: 0, duration: 300 }); - }; - - const finishWinner = () => { - this.time.delayedCall(1900, () => { - // Fade winning rank number and outcome label together with the undim. - if (winnerTxt) this.tweens.add({ targets: winnerTxt, alpha: 0, duration: 500 }); - this.tweens.add({ targets: outcomeLabel, alpha: 0, duration: 500 }); - // Return winner piece to its board position and undim simultaneously. - this.tweens.add({ - targets: winnerCont, x: at.x, y: at.y, duration: 500, ease: 'Cubic.easeInOut', - }); - this.tweens.add({ - targets: dim, fillAlpha: 0, duration: 500, - onComplete: () => { cleanup(); onDone(); }, - }); - }); - }; - - const cleanup = () => { for (const o of stageObjs) { try { o.destroy(); } catch {} } }; - - if (res === 'both') { - // Tie: both shoot simultaneously, both explode/fade. - let emotionFired = false; - fireShot(humanStageX, STAGE_CY, aiStageX, STAGE_CY, () => { - this._spawnExplosions(aiStageX, STAGE_CY); - fadeOut(aiCont, aiRankTxt); - if (!emotionFired) { emotionFired = true; triggerEmotion(); } - }); - fireShot(aiStageX, STAGE_CY, humanStageX, STAGE_CY, () => { - this._spawnExplosions(humanStageX, STAGE_CY); - fadeOut(humanCont, humanRankTxt); - if (!emotionFired) { emotionFired = true; triggerEmotion(); } - }); - // After both explosions settle, fade outcome label and undim. - this.time.delayedCall(2700, () => { - this.tweens.add({ targets: outcomeLabel, alpha: 0, duration: 400 }); - this.tweens.add({ - targets: dim, fillAlpha: 0, duration: 400, - onComplete: () => { cleanup(); onDone(); }, - }); - }); - } else { - // Winner shoots loser. - const winnerX = winnerCont === humanCont ? humanStageX : aiStageX; - const loserX = loserCont === humanCont ? humanStageX : aiStageX; - fireShot(winnerX, STAGE_CY, loserX, STAGE_CY, () => { - this._spawnExplosions(loserX, STAGE_CY); - fadeOut(loserCont, loserTxt); - triggerEmotion(); - finishWinner(); - }); + // ── setup phase ───────────────────────────────────────────────────────────── + enterSetup(greet) { + this.phase = 'setup'; + this.trayPick = null; + this.setupSel = null; + this.clearSel(); + this.renderAll(); + if (greet) { + this.time.delayedCall(500, () => this.hud.say(opponentLine('greet', this.tier))); } + this.save(); } - // Three staggered expanding rings at the explosion point. - _spawnExplosions(cx, cy) { - const jitters = [[0, 0], [-18, -12], [14, 20]]; - jitters.forEach(([jx, jy], i) => { - this.time.delayedCall(i * 90, () => { - if (i === 0) playScifiExplode(this); - const ring = this.add.circle(cx + jx, cy + jy, 10, 0xff5500, 0.9).setDepth(DEPTH.drag + 2); - this.tweens.add({ - targets: ring, scale: 7, alpha: 0, duration: 520, ease: 'Cubic.easeOut', - onComplete: () => { try { ring.destroy(); } catch {} }, - }); - }); - }); + setupChanged(sound = 'deploy') { + if (sound === 'deploy') SND.deploy(this); + else if (sound === 'pickup') SND.pickup(this); + this.renderAll(); + this.save(); } - // Build a tweenable container for a piece (origin centred). - makeContainer(piece, size, faceUp) { - const cont = this.add.container(0, 0); - const objs = this.buildPieceObjects(piece, size, faceUp); - objs.sort((a, b) => a._depthBias - b._depthBias); - for (const o of objs) cont.add(o); - return cont; + onTrayDown(rank, p) { + if (this.phase !== 'setup' || this.modal) return; + this.drag = { kind: 'tray', rank, x0: p.x, y0: p.y, moved: false, ghost: null }; } - // ── turn driver ──────────────────────────────────────────────────────────────── + deployNow() { + if (this.phase !== 'setup' || !L.setupComplete(this.gs, HUMAN)) { SND.deny(this); return; } + this.settings.lastLayout = { ...this.settings.lastLayout, [this.gs.variant]: L.readLayout(this.gs, HUMAN) }; + this.persistSettings(); + this.gs = L.startBattle(this.gs); + this.start = this.gs; + this.trayPick = null; this.setupSel = null; + this.clearViews(); + SND.ping(this); + this.hud.say(opponentLine('deploy', this.tier)); + this.advance(); + } + + // ── turn driver ───────────────────────────────────────────────────────────── advance() { - this.render(); - if (isGameOver(this.gs)) { this.busy = false; this.showWinner(); return; } - if (this.gs.current === this.humanSeat) { this.busy = false; return; } + this.clearSel(); + if (L.isGameOver(this.gs)) { this.endGame(); return; } + if (this.gs.current === HUMAN) { + this.phase = 'human'; + this.renderAll(); + this.save(); + return; + } this.aiTurn(); } aiTurn() { - this.busy = true; - this.render(); - this.time.delayedCall(nextThinkDelay(this.aiSkill), () => { - const mv = chooseMove(this.gs, this.aiSeat, this.aiSkill); - if (!mv) { this.busy = false; this.advance(); return; } - this.animateMove(mv.fr, mv.fc, mv.tr, mv.tc, () => { - this.gs = applyMove(this.gs, mv.fr, mv.fc, mv.tr, mv.tc); - this.busy = false; - this.advance(); - }, 1200); + const tok = this.token; + this.phase = 'ai'; + this.renderAll(); + this.save(); + const t0 = Date.now(); + const minWait = nextThinkDelay(this.skill); + this.engine.request('move', { view: L.viewFor(this.gs, AI), skill: this.skill }).then((mv) => { + if (tok !== this.token || this.ended) return; + const wait = Math.max(0, minWait - (Date.now() - t0)); + this.time.delayedCall(wait, () => { + if (tok !== this.token || this.ended) return; + if (!mv) { this.advance(); return; } + this.performMove(mv.fr, mv.fc, mv.tr, mv.tc); + }); + }).catch(() => { + if (tok !== this.token) return; + // engine failure: fall back to any legal move + const ms = L.allLegalMoves(this.gs, AI); + const m = ms[Math.floor(Math.random() * ms.length)]; + if (m) this.performMove(m.fr, m.fc, m.tr, m.tc); }); } - // ── end ────────────────────────────────────────────────────────────────────── - showWinner() { - const youWon = this.gs.winner === this.humanSeat; - const draw = this.gs.winner == null; - const accent = draw ? COLORS.accent : PLAYER_COLORS[this.gs.winner]; - const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6) - .setDepth(DEPTH.banner); - const panel = this.add.container(GAME_WIDTH / 2, GAME_HEIGHT / 2).setDepth(DEPTH.banner + 1); + async performMove(fr, fc, tr, tc) { + const tok = this.token; + const before = this.gs; + const mover = before.board[fr][fc], target = before.board[tr][tc]; + if (!mover) return; + const seat = mover.owner; + this.phase = 'anim'; + this.clearSel(); + this.hintMove = null; this.hintG.clear(); + this.renderStatus(); + const view = this.views.get(mover.id); + const dest = tileCenter(tr, tc); + const dist = Math.abs(tr - fr) + Math.abs(tc - fc); + if (view) { + view.setDepth(D.ghost); + SND.step(this, seat === AI); + const dur = (seat === AI ? 300 : 170) + dist * 55; + if (target) { + // stop just short of the defender + const back = { x: dest.x - Math.sign(tc - fc) * TILE * 0.42, y: dest.y - Math.sign(tr - fr) * TILE * 0.42 }; + await this.tweenP({ targets: view.c, x: back.x, y: back.y, duration: dur, ease: 'Cubic.easeInOut' }); + } else { + await this.tweenP({ targets: view.c, x: dest.x, y: dest.y, duration: dur, ease: 'Cubic.easeInOut' }); + } + } + if (tok !== this.token) return; + if (target) { + const tview = this.views.get(target.id); + const aiPiece = seat === AI ? mover : target; + const aiKnown = L.isKnownTo(before, HUMAN, aiPiece); + view?.c.setVisible(false); tview?.c.setVisible(false); + this.battle = playBattle(this, { + mover, target, at: dest, human: HUMAN, speed: this.settings.speed, depth: D.battle, aiKnown, + onImpact: (res) => this.reactToBattle(before, mover, target, res), + }); + this.renderStatus(); + await this.battle.done; + this.battle = null; + if (tok !== this.token) return; + } + const next = L.applyMove(before, fr, fc, tr, tc); + if (next === before) { this.advance(); return; } + if (target) this.undoStack = []; + else if (seat === HUMAN) this.undoStack.push(before); + if (this.undoStack.length > 60) this.undoStack.shift(); + this.gs = next; + this.flagNearCheck(next, seat, tr, tc); + this.advance(); + } + + tweenP(cfg) { return new Promise((res) => this.tweens.add({ ...cfg, onComplete: () => res() })); } + + reactToBattle(state, mover, target, res) { + const aiAttacked = mover.owner === AI; + const ai = aiAttacked ? mover : target, hu = aiAttacked ? target : mover; + const aiLost = res === 'both' || (res === 'attacker') !== aiAttacked; + const huLost = res === 'both' || (res === 'attacker') === aiAttacked; + let line = null, emo = null; + if (target.rank === FLAG) return; + if (hu.rank === MARSHAL && huLost && ai.rank === SPY) { line = 'spy'; emo = 'happy'; } + else if (ai.rank === SPY && aiLost) { line = 'lostSpy'; emo = 'upset'; } + else if (target.rank === BOMB && !aiAttacked && res === 'defender') { line = 'bomb'; emo = 'happy'; } + else if (target.rank === BOMB && aiAttacked && res === 'defender') { line = 'hitBomb'; emo = 'upset'; } + else if (aiLost && ai.rank >= 7 && ai.rank !== BOMB) { line = 'lostBig'; emo = 'upset'; } + else if (huLost && hu.rank >= 7 && hu.rank !== BOMB) { line = 'tookBig'; emo = 'happy'; } + if (emo) this.hud.emotion(emo); + if (line && (state.ply - this.lastTalkPly > 6 || Math.random() < 0.35)) { + this.lastTalkPly = state.ply; + this.hud.say(opponentLine(line, this.tier, { unit: rankName(line === 'tookBig' ? hu.rank : ai.rank) })); + } + } + + flagNearCheck(s, seat, tr, tc) { + if (seat !== HUMAN || this.saidFlagNear || s.phase !== 'play') return; + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = s.board[r][c]; + if (p && p.owner === AI && p.rank === FLAG && Math.abs(r - tr) + Math.abs(c - tc) <= 2) { + this.saidFlagNear = true; + this.time.delayedCall(400, () => this.hud.say(opponentLine('flagNear', this.tier))); + return; + } + } + } + + // ── rendering ─────────────────────────────────────────────────────────────── + shownState() { return this.phase === 'replay' && this.replay ? this.replay.states[this.replay.i] : this.gs; } + + faceUp(s, p) { + if (this.phase === 'replay') return true; + return p.owner === HUMAN || L.isKnownTo(s, HUMAN, p); + } + + clearViews() { for (const v of this.views.values()) v.destroy(); this.views.clear(); } + + syncPieces() { + const s = this.shownState(); + if (!s) return; + const setup = s.phase === 'setup'; + const seen = new Set(); + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = s.board[r][c]; + if (!p) continue; + const key = setup ? `s${r * GRID + c}:${p.owner}:${p.rank}` : p.id; + seen.add(key); + const { x, y } = tileCenter(r, c); + let v = this.views.get(key); + const up = setup ? p.owner === HUMAN : this.faceUp(s, p); + if (!v) { + v = new PieceView(this, p, { faceUp: up, depth: D.piece + r * 0.01, x, y }); + this.views.set(key, v); + } else { + v.c.setVisible(true); + this.tweens.killTweensOf(v.c); + v.setPosition(x, y).setDepth(D.piece + r * 0.01); + v.c.setScale(v.baseScale).setAlpha(1); + if (v.faceUp !== up) v.setFaceUp(up, true); + v.setRank(p.rank); + } + v.piece.id = p.id; + if (!setup) { + const hidden = !up; + v.setMarks(hidden && this.settings.autoMarks ? { moved: p.moved, scout: p.scout } : { moved: false, scout: false }); + v.setTag(hidden && this.phase !== 'replay' ? this.tags[p.id] ?? null : null); + } else { + v.setMarks({}); v.setTag(null); + } + if (this.drag?.kind === 'board' && this.drag.moved && this.drag.from.r === r && this.drag.from.c === c) v.setGhost(true); + else v.setGhost(false); + } + for (const [k, v] of this.views) if (!seen.has(k)) { v.destroy(); this.views.delete(k); } + // tags for units that are gone + if (!setup && this.phase !== 'replay') { + for (const id of Object.keys(this.tags)) if (!L.findPiece(this.gs, Number(id))) delete this.tags[id]; + } + } + + viewAt(r, c) { + const p = this.shownState()?.board[r][c]; + if (!p) return null; + if (this.shownState().phase === 'setup') return this.views.get(`s${r * GRID + c}:${p.owner}:${p.rank}`); + return this.views.get(p.id); + } + + renderAll() { + if (!this.gs) return; + this.syncPieces(); + this.drawMarks(); + this.drawSelection(); + const s = this.shownState(); + const setup = this.phase === 'setup'; + this.hud.refreshLeft(s, setup ? 'setup' : this.phase === 'replay' ? 'replay' : 'play', { + trayCounts: setup ? L.trayCounts(s, HUMAN) : null, pick: this.trayPick, + }); + this.hud.refreshCards(s, { current: this.phase === 'human' ? HUMAN : this.phase === 'ai' ? AI : (this.phase === 'anim' ? s.current : null), thinking: this.phase === 'ai', mode: setup ? 'setup' : 'play' }); + const log = this.phase === 'replay' ? s.log : this.gs.log; + this.hud.refreshLog(log, { showRanks: this.gs.reveal === 'assisted' || this.phase === 'replay' || this.phase === 'over', title: this.phase === 'replay' ? 'REPLAY LOG' : 'BATTLE LOG' }); + this.renderControls(); + this.renderStatus(); + } + + renderStatus() { + let msg = '', seat = null, color = HUE.ink; + const s = this.gs; + switch (this.phase) { + case 'setup': { + const left = L.trayTotal(s, HUMAN); + msg = left ? `Deploy your army: ${left} unit${left === 1 ? '' : 's'} left in the Barracks` : 'Army deployed. Press Deploy when ready.'; + if (this.trayPick != null) msg = `Placing: ${rankName(this.trayPick)} · click a square in your four rows`; + break; + } + case 'human': msg = this.selected ? 'Choose a destination · click the unit again to cancel' : 'Your move, Commander'; seat = HUMAN; break; + case 'ai': msg = `${this.oppName} is maneuvering…`; seat = AI; break; + case 'anim': msg = this.battle ? 'Engagement! (click or Space to skip)' : s.current === HUMAN ? 'Your move, Commander' : `${this.oppName} is maneuvering…`; seat = s.current; break; + case 'over': msg = s.winner == null ? 'Stalemate' : s.winner === HUMAN ? 'Victory: the enemy flag is yours' : 'Defeat: your flag has fallen'; color = s.winner === HUMAN ? '#8dffb4' : s.winner == null ? HUE.amberHex : '#ff7d6b'; break; + case 'replay': msg = `Replay · move ${this.replay.i} of ${this.replay.states.length - 1}`; break; + default: msg = ''; + } + if (this.statusOverride) msg = this.statusOverride; + this.hud.setStatus(msg, { seat, color }); + const variant = variantOf(s?.variant).name; + const rev = s?.reveal === 'classic' ? 'Classic memory' : 'Assisted'; + this.footer.setText(s ? `${variant} rules · ${rev} reveals · Space skip battle · Z undo · H hint · right-click to tag · Esc menu` : ''); + } + + flashStatus(text, ms = 2600) { + this.statusOverride = text; + this.renderStatus(); + this.statusTimer?.remove(); + this.statusTimer = this.time.delayedCall(ms, () => { this.statusOverride = null; this.renderStatus(); }); + } + + renderControls() { + const P = this.phase; + if (P === 'setup') { + const ready = L.setupComplete(this.gs, HUMAN); + this.hud.setControls([ + [{ key: 'formations', label: 'Formations…' }, { key: 'fill', label: 'Auto-fill' }, { key: 'clear', label: 'Clear', bg: BTN_WARN }], + [{ key: 'menu', label: 'Menu' }, { key: 'deploy', label: ready ? 'DEPLOY ▶' : 'Deploy (fill all rows)', bg: BTN_GO, enabled: ready, w: 2 }], + ]); + } else if (P === 'human' || P === 'ai' || P === 'anim') { + const canUndo = P === 'human' && this.undoStack.length > 0; + const speedLbl = { full: 'Battles: Full', quick: 'Battles: Quick', off: 'Battles: Off' }[this.settings.speed]; + this.hud.setControls([ + [{ key: 'undo', label: 'Undo (Z)', enabled: canUndo }, { key: 'hint', label: 'Hint (H)', enabled: P === 'human' }, { key: 'speed', label: speedLbl, fontSize: 16 }], + [{ key: 'menu', label: 'Menu (Esc)' }, { key: 'rules', label: 'How to Play' }], + ]); + } else if (P === 'over') { + this.hud.setControls([ + [{ key: 'report', label: 'Report' }, { key: 'replay', label: 'Replay' }, { key: 'rematch', label: 'Rematch', bg: BTN_GO }], + [{ key: 'newgame', label: 'New Game', bg: BTN_ALT }, { key: 'leave', label: 'Leave', bg: BTN_WARN }], + ]); + } else if (P === 'replay') { + this.hud.setControls([ + [{ key: 'r-first', label: '⏮' }, { key: 'r-prev', label: '◀' }, { key: 'r-play', label: this.replayTimer ? '❚❚' : '▶' }, { key: 'r-next', label: '▶|' }, { key: 'r-last', label: '⏭' }], + [{ key: 'r-exit', label: 'Exit Replay', bg: BTN_WARN }], + ]); + } else this.hud.setControls([]); + } + + drawMarks() { + const g = this.markG; g.clear(); + const s = this.shownState(); + if (!s) return; + if (s.phase === 'setup') { + // the deployment zone + const zoneY = BY0 + 6 * PITCH - 6; + g.lineStyle(2, PLAYER_COLORS[HUMAN], 0.8).strokeRoundedRect(BX0 - 6, zoneY, BOARD_W + 12, 4 * PITCH + 8, 10); + if (this.trayPick != null) { + for (let r = 6; r < 10; r++) for (let c = 0; c < GRID; c++) { + if (s.board[r][c]) continue; + const { x, y } = tileCenter(r, c); + g.fillStyle(HUE.amber, 0.16).fillRoundedRect(x - TILE / 2 + 3, y - TILE / 2 + 3, TILE - 6, TILE - 6, 6); + } + } + if (this.setupSel) { + const { x, y } = tileCenter(this.setupSel.r, this.setupSel.c); + g.lineStyle(4, HUE.amber, 1).strokeRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 8); + } + return; + } + const lm = s.lastMove; + if (lm) { + const col = PLAYER_COLORS[lm.seat]; + const a = tileCenter(lm.fr, lm.fc), b = tileCenter(lm.tr, lm.tc); + g.lineStyle(2, col, 0.75); + dashedRect(g, a.x - TILE / 2 + 3, a.y - TILE / 2 + 3, TILE - 6, TILE - 6); + g.lineStyle(3, col, 0.95).strokeRoundedRect(b.x - TILE / 2 + 1, b.y - TILE / 2 + 1, TILE - 2, TILE - 2, 7); + g.lineStyle(3, col, 0.35).lineBetween(a.x, a.y, b.x, b.y); + if (lm.attack) { + g.fillStyle(0xffb547, 0.9).fillCircle(b.x + TILE / 2 - 8, b.y - TILE / 2 + 8, 5); + } + } + } + + drawSelection() { + const g = this.selG; g.clear(); + for (const v of this.views.values()) v.setSelected(false); + if (this.phase !== 'human' || !this.selected) return; + this.viewAt(this.selected.r, this.selected.c)?.setSelected(true); + if (!this.settings.showMoves) return; + for (const m of this.allMovesSel ?? []) { + const { x, y } = tileCenter(m.r, m.c); + if (m.blocked) { + g.lineStyle(3, 0x7f8a96, 0.7); + g.lineBetween(x - 10, y - 10, x + 10, y + 10).lineBetween(x - 10, y + 10, x + 10, y - 10); + } else if (m.attack) { + g.lineStyle(4, 0xff5a4a, 1); + const h = TILE / 2 - 2, L2 = 16; + for (const [sx, sy] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) { + g.beginPath().moveTo(x + sx * h, y + sy * (h - L2)).lineTo(x + sx * h, y + sy * h).lineTo(x + sx * (h - L2), y + sy * h).strokePath(); + } + } else { + g.fillStyle(HUE.cyan, 0.22).fillCircle(x, y, 18); + g.fillStyle(HUE.cyan, 0.9).fillCircle(x, y, 7); + } + } + } + + clearSel() { + this.selected = null; this.legal = []; this.allMovesSel = []; + this.selG?.clear(); + if (this.views) for (const v of this.views.values()) v.setSelected(false); + } + + // ── input ─────────────────────────────────────────────────────────────────── + inputBlocked() { return !!this.modal || this.ended; } + + onPointerDown(p) { + if (this.inputBlocked()) return; + if (this.battle) { this.battle.skip(); return; } + if (this.drag) return; // a tray row already took this press + this.hideTip(); + const cell = cellAt(p.x, p.y); + const right = p.rightButtonDown(); + if (this.phase === 'setup') { + if (!cell) return; + const piece = this.gs.board[cell.r][cell.c]; + if (right) { + if (piece?.owner === HUMAN) { this.gs = L.setupRemove(this.gs, HUMAN, cell.r, cell.c); this.setupSel = null; this.setupChanged('pickup'); } + return; + } + if (piece?.owner === HUMAN) this.drag = { kind: 'board', rank: piece.rank, from: cell, x0: p.x, y0: p.y, moved: false }; + else if (!piece && inSetupZone(HUMAN, cell.r)) this.drag = { kind: 'empty', from: cell, x0: p.x, y0: p.y, moved: false }; + return; + } + if (this.phase === 'replay' || this.phase === 'over') return; + if (this.phase !== 'human' || !cell) { if (!cell && this.selected) { this.clearSel(); this.renderStatus(); } return; } + const piece = this.gs.board[cell.r][cell.c]; + if (piece && piece.owner === AI && !L.isKnownTo(this.gs, HUMAN, piece) && (right || !this.selected)) { + if (right) { this.openTagPicker(piece, cell); return; } + // long-press to tag on touch + this.longPress?.remove(); + this.longPress = this.time.delayedCall(550, () => { + if (this.drag?.kind === 'press' && !this.drag.moved) { this.drag = null; this.openTagPicker(piece, cell); } + }); + this.drag = { kind: 'press', from: cell, x0: p.x, y0: p.y, moved: false }; + return; + } + if (right) return; + // a destination for the selected unit? + if (this.selected) { + const m = this.allMovesSel.find((q) => q.r === cell.r && q.c === cell.c); + if (m && !m.blocked) { this.humanMove(this.selected, cell); return; } + if (m && m.blocked) { SND.deny(this); this.flashStatus(computerLine(m.blocked === 'chase' ? 'chase' : 'twoSquare'), 4200); return; } + } + if (piece && piece.owner === HUMAN && canMove(piece.rank)) { + const was = this.selected && this.selected.r === cell.r && this.selected.c === cell.c; + this.select(cell); + this.drag = { kind: 'move', from: cell, x0: p.x, y0: p.y, moved: false, toggle: was }; + return; + } + if (piece && piece.owner === HUMAN) { SND.deny(this); this.flashStatus(piece.rank === FLAG ? 'The Flag can\'t move.' : 'Bombs can\'t move.'); } + this.clearSel(); this.renderStatus(); + } + + select(cell) { + this.selected = cell; + this.allMovesSel = L.movesFor(this.gs, cell.r, cell.c); + this.legal = this.allMovesSel.filter((m) => !m.blocked); + SND.select(this); + this.drawSelection(); + this.renderStatus(); + } + + onPointerMove(p) { + if (this.inputBlocked()) return; + const d = this.drag; + if (d && p.isDown) { + if (!d.moved && Math.hypot(p.x - d.x0, p.y - d.y0) > DRAG_PX) { + if (d.kind === 'press') { d.moved = true; this.longPress?.remove(); this.drag = null; return; } + if (d.kind === 'empty') { this.drag = null; return; } + d.moved = true; + const owner = HUMAN; + d.ghost = new PieceView(this, { owner, rank: d.rank ?? this.gs.board[d.from.r][d.from.c]?.rank }, { faceUp: true, depth: D.ghost, scale: 1.08, x: p.x, y: p.y }); + d.ghost.c.setAlpha(0.92); + if (d.kind === 'board' || d.kind === 'move') this.viewAt(d.from.r, d.from.c)?.setGhost(true); + SND.pickup(this); + } + if (d.moved && d.ghost) { + d.ghost.setPosition(p.x, p.y - 6); + this.drawDropHover(p); + } + return; + } + this.updateHover(p); + } + + drawDropHover(p) { + const g = this.hoverG; g.clear(); + const cell = cellAt(p.x, p.y); + if (!cell) return; + const { x, y } = tileCenter(cell.r, cell.c); + let ok = false; + if (this.phase === 'setup') ok = inSetupZone(HUMAN, cell.r); + else if (this.drag?.kind === 'move') ok = this.legal.some((m) => m.r === cell.r && m.c === cell.c); + g.lineStyle(3, ok ? HUE.amber : 0x7f8a96, ok ? 1 : 0.6).strokeRoundedRect(x - TILE / 2, y - TILE / 2, TILE, TILE, 8); + } + + onPointerUp(p) { + const d = this.drag; + this.drag = null; + this.longPress?.remove(); + this.hoverG.clear(); + if (!d || this.inputBlocked()) { d?.ghost?.destroy(); return; } + d.ghost?.destroy(); + const cell = cellAt(p.x, p.y); + if (this.phase === 'setup') { this.setupRelease(d, cell, p); return; } + if (d.kind === 'move') { + if (d.moved) { + this.viewAt(d.from.r, d.from.c)?.setGhost(false); + if (cell && this.legal.some((m) => m.r === cell.r && m.c === cell.c)) { this.humanMove(d.from, cell); return; } + const m = cell && this.allMovesSel.find((q) => q.r === cell.r && q.c === cell.c); + if (m?.blocked) { SND.deny(this); this.flashStatus(computerLine(m.blocked === 'chase' ? 'chase' : 'twoSquare'), 4200); } + } else if (d.toggle) { this.clearSel(); this.renderStatus(); } + } + } + + setupRelease(d, cell, p) { + const s = this.gs; + if (d.kind === 'tray') { + if (!d.moved) { + this.trayPick = this.trayPick === d.rank ? null : d.rank; + this.setupSel = null; + SND.select(this); + this.renderAll(); + return; + } + if (cell && inSetupZone(HUMAN, cell.r)) this.placeFromTray(d.rank, cell); + else this.renderAll(); + return; + } + if (d.kind === 'empty') { + if (this.trayPick != null && cell && cell.r === d.from.r && cell.c === d.from.c) this.placeFromTray(this.trayPick, cell); + else if (this.setupSel && cell && cell.r === d.from.r && cell.c === d.from.c) { + this.gs = L.setupSwap(s, HUMAN, L.keyOf(this.setupSel.r, this.setupSel.c), L.keyOf(cell.r, cell.c)); + this.setupSel = null; + this.setupChanged(); + } + return; + } + if (d.kind === 'board') { + if (d.moved) { + if (this.hud.overLeft(p.x, p.y)) { + this.gs = L.setupRemove(s, HUMAN, d.from.r, d.from.c); this.setupSel = null; this.setupChanged('pickup'); return; + } + if (cell && inSetupZone(HUMAN, cell.r)) { + this.gs = L.setupSwap(s, HUMAN, L.keyOf(d.from.r, d.from.c), L.keyOf(cell.r, cell.c)); this.setupSel = null; this.setupChanged(); return; + } + this.renderAll(); + return; + } + // a click on one of your placed units + if (this.trayPick != null) { + const keepPick = this.trayPick; + this.gs = L.setupRemove(s, HUMAN, d.from.r, d.from.c); + this.placeFromTray(keepPick, d.from); + return; + } + if (!this.setupSel) { this.setupSel = d.from; SND.select(this); this.renderAll(); return; } + if (this.setupSel.r === d.from.r && this.setupSel.c === d.from.c) { this.setupSel = null; this.renderAll(); return; } + this.gs = L.setupSwap(s, HUMAN, L.keyOf(this.setupSel.r, this.setupSel.c), L.keyOf(d.from.r, d.from.c)); + this.setupSel = null; + this.setupChanged(); + } + } + + placeFromTray(rank, cell) { + let s = this.gs; + if (s.board[cell.r][cell.c]) s = L.setupRemove(s, HUMAN, cell.r, cell.c); + const n = L.setupPlace(s, HUMAN, cell.r, cell.c, rank); + if (n === s) { SND.deny(this); this.renderAll(); return; } + this.gs = n; + if ((L.trayCounts(n, HUMAN)[rank] ?? 0) <= 0) this.trayPick = null; + this.setupChanged(); + } + + humanMove(from, to) { + if (this.phase !== 'human') return; + this.performMove(from.r, from.c, to.r, to.c); + } + + openTagPicker(piece, cell) { + const { x, y } = tileCenter(cell.r, cell.c); + this.hud.hidePortraits(); + this.modal = openGuessPicker(this, { + x, y, depth: D.modal, current: this.tags[piece.id] ?? null, + onPick: (lab) => { + if (lab) this.tags[piece.id] = lab; else delete this.tags[piece.id]; + this.save(); + }, + onClose: () => { this.modal = null; this.hud.showPortraits(); this.syncPieces(); }, + }); + } + + // ── hover inspect ─────────────────────────────────────────────────────────── + updateHover(p) { + const cell = cellAt(p.x, p.y); + const key = cell ? `${cell.r},${cell.c}` : null; + if (key === this.hoverKey) return; + this.hoverKey = key; + this.hoverG.clear(); + this.hideTip(); + this.tipTimer?.remove(); + const s = this.shownState(); + if (!cell || !s || s.phase === 'setup' && !s.board[cell.r][cell.c]) return; + const piece = s.board[cell.r][cell.c]; + if (this.phase === 'human') { + const { x, y } = tileCenter(cell.r, cell.c); + const actionable = (piece?.owner === HUMAN && canMove(piece.rank)) || this.legal.some((m) => m.r === cell.r && m.c === cell.c); + if (actionable) this.hoverG.lineStyle(2, HUE.cyan, 0.9).strokeRoundedRect(x - TILE / 2 - 1, y - TILE / 2 - 1, TILE + 2, TILE + 2, 8); + } + if (!piece) return; + this.tipTimer = this.time.delayedCall(320, () => this.showTip(cell, piece)); + } + + showTip(cell, piece) { + this.hideTip(); + const s = this.shownState(); + const up = s.phase === 'setup' ? piece.owner === HUMAN : this.faceUp(s, piece); + const lines = []; + let title; + if (up) { + title = `${rankName(piece.rank)}${canMove(piece.rank) && piece.rank !== MARSHAL ? ` · rank ${piece.rank}` : ''}`; + lines.push(RANK_NOTES[piece.rank]); + lines.push(matchup(piece.rank)); + } else { + title = 'Unknown Dominion unit'; + lines.push(piece.scout ? 'Ran more than one square: a Scout.' : piece.moved ? 'Has moved: not a Bomb or the Flag.' : 'Hasn\'t moved yet: could be anything.'); + if (this.tags[piece.id]) lines.push(`Your tag: ${this.tags[piece.id]}`); + if (this.settings.intel && s.phase === 'play') { + try { + const b = beliefFor(L.viewFor(s, HUMAN), piece.id); + if (b && b.length) lines.push(`Intel estimate: ${b.slice(0, 3).map((e) => `${rankName(e.rank)} ${Math.round(e.p * 100)}%`).join(' · ')}`); + } catch (_) { /* */ } + } + lines.push('Right-click to tag a guess.'); + } + const { x, y } = tileCenter(cell.r, cell.c); + const w = 360; + const left = x + TILE / 2 + 12 + w > FRAME.x + FRAME.w + 40 ? x - TILE / 2 - 12 - w : x + TILE / 2 + 12; + const t1 = this.add.text(left + 14, 0, title, { fontFamily: DISPLAY_FONT, fontSize: '19px', color: PLAYER_COLOR_HEX[piece.owner] }); + const t2 = this.add.text(left + 14, 0, lines.join('\n'), { fontFamily: UI_FONT, fontSize: '14px', color: HUE.ink, wordWrap: { width: w - 28 }, lineSpacing: 4 }); + const h = t1.height + t2.height + 30; + const top = Math.max(10, Math.min(H - h - 10, y - h / 2)); + t1.setY(top + 10); t2.setY(top + 18 + t1.height); const g = this.add.graphics(); - g.fillStyle(0x14110b, 0.96).fillRoundedRect(-280, -120, 560, 240, 16); - g.lineStyle(3, accent, 1).strokeRoundedRect(-280, -120, 560, 240, 16); - panel.add(g); - panel.add(this.add.text(0, -50, draw ? 'Draw' : youWon ? 'Victory!' : 'Defeat', { - fontFamily: 'Righteous', fontSize: '46px', color: COLORS.textHex, - }).setOrigin(0.5)); - panel.add(this.add.text(0, 4, draw ? 'Neither army could force the flag.' - : youWon ? 'You captured the enemy flag.' : 'The enemy captured your flag.', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5)); + g.fillStyle(0x07101c, 0.96).fillRoundedRect(left, top, w, h, 10); + g.lineStyle(1.5, PLAYER_COLORS[piece.owner], 0.9).strokeRoundedRect(left, top, w, h, 10); + this.tip = this.add.container(0, 0, [g, t1, t2]).setDepth(D.tip).setAlpha(0); + this.tweens.add({ targets: this.tip, alpha: 1, duration: 120 }); + } - new Button(this, GAME_WIDTH / 2 - 130, GAME_HEIGHT / 2 + 74, 'Rematch', - () => this.scene.restart(), { width: 220, height: 50 }).setDepth(DEPTH.banner + 2); - new Button(this, GAME_WIDTH / 2 + 130, GAME_HEIGHT / 2 + 74, 'Back to menu', - () => this.scene.start('GameMenu'), { width: 220, height: 50, variant: 'ghost' }).setDepth(DEPTH.banner + 2); + hideTip() { this.tipTimer?.remove(); if (this.tip) { this.tweens.killTweensOf(this.tip); this.tip.destroy(); this.tip = null; } } - if (youWon) playSound(this, SFX.VICTORY_SHORT); - this._endObjs = [overlay, panel]; + // ── buttons & keys ────────────────────────────────────────────────────────── + onButton(k) { + if (this.inputBlocked() && k !== 'r-play') return; + switch (k) { + case 'formations': return this.openFormationsDlg(); + case 'fill': this.gs = L.setupFill(this.gs, HUMAN); this.trayPick = null; this.setupSel = null; return this.setupChanged(); + case 'clear': this.gs = L.setupClear(this.gs, HUMAN); this.trayPick = null; this.setupSel = null; return this.setupChanged('pickup'); + case 'deploy': return this.deployNow(); + case 'menu': return this.openMenu(); + case 'undo': return this.undo(); + case 'hint': return this.hint(); + case 'speed': { + const order = ['full', 'quick', 'off']; + this.settings.speed = order[(order.indexOf(this.settings.speed) + 1) % 3]; + this.persistSettings(); this.renderControls(); + return null; + } + case 'rules': return this.openRules(); + case 'report': return this.openReport(); + case 'replay': return this.enterReplay(); + case 'rematch': this.clearSave(); return this.startMatch(this.settings.setup); + case 'newgame': this.clearSave(); return this.openBriefing(); + case 'leave': return this.scene.start('GameMenu'); + case 'r-first': return this.replayGo(0); + case 'r-prev': return this.replayGo(this.replay.i - 1); + case 'r-next': return this.replayGo(this.replay.i + 1); + case 'r-last': return this.replayGo(this.replay.states.length - 1); + case 'r-play': return this.replayToggle(); + case 'r-exit': return this.exitReplay(); + default: return null; + } + } + + onKey(e) { + if (this.ended) return; + const k = e.key; + if (this.battle && (k === ' ' || k === 'Enter')) { this.battle.skip(); e.preventDefault?.(); return; } + if (this.modal) return; + if (k === 'Escape') { + if (this.drag) { this.drag.ghost?.destroy(); this.drag = null; this.renderAll(); return; } + if (this.selected || this.trayPick != null || this.setupSel) { this.clearSel(); this.trayPick = null; this.setupSel = null; this.renderAll(); return; } + this.openMenu(); + return; + } + if ((k === 'z' || k === 'Z') && this.phase === 'human') this.undo(); + if ((k === 'h' || k === 'H') && this.phase === 'human') this.hint(); + if (this.phase === 'replay') { + if (k === 'ArrowLeft') this.replayGo(this.replay.i - 1); + if (k === 'ArrowRight') this.replayGo(this.replay.i + 1); + } + } + + undo() { + if (this.phase !== 'human') return; + if (!this.undoStack.length) { SND.deny(this); this.flashStatus(computerLine('noUndo')); return; } + this.token++; + this.gs = this.undoStack.pop(); + this.clearSel(); + SND.pickup(this); + this.advance(); + } + + hint() { + if (this.phase !== 'human') return; + const tok = this.token; + this.flashStatus('Running tactical analysis…', 1500); + this.engine.request('hint', { view: L.viewFor(this.gs, HUMAN), ms: 900 }).then((mv) => { + if (tok !== this.token || this.phase !== 'human' || !mv) return; + this.hintMove = mv; + const g = this.hintG; g.clear(); + const a = tileCenter(mv.fr, mv.fc), b = tileCenter(mv.tr, mv.tc); + g.lineStyle(4, HUE.amber, 1).strokeRoundedRect(a.x - TILE / 2, a.y - TILE / 2, TILE, TILE, 8); + g.lineStyle(4, HUE.amber, 1).strokeRoundedRect(b.x - TILE / 2 + 4, b.y - TILE / 2 + 4, TILE - 8, TILE - 8, 8); + g.lineStyle(5, HUE.amber, 0.6).lineBetween(a.x, a.y, b.x, b.y); + g.setAlpha(1); + this.tweens.killTweensOf(g); + this.tweens.add({ targets: g, alpha: { from: 1, to: 0.35 }, duration: 500, yoyo: true, repeat: 5, onComplete: () => g.clear() }); + const attack = this.gs.board[mv.tr][mv.tc]; + this.flashStatus(`Suggestion: ${squareName(mv.fr, mv.fc)} ${attack ? '×' : '→'} ${squareName(mv.tr, mv.tc)}`, 5000); + }).catch(() => {}); + } + + openMenu() { + if (this.modal) return; + this.hud.hidePortraits(); + this.modal = openPauseMenu(this, { + settings: this.settings, match: this.phase === 'human' || this.phase === 'ai' ? 'play' : this.phase, depth: D.modal, + onChange: (k, v) => { + this.settings[k] = v; + this.persistSettings(); + if (k === 'ambience') this.ambience.setOn(v); + }, + onRules: () => this.openRules(), + onNewGame: () => this.confirmThen('Start a new game?', 'This engagement will be abandoned.', () => { this.clearSave(); this.openBriefing(); }), + onResign: () => this.confirmThen('Surrender?', 'The Dominion takes the sector. This counts as a loss.', () => { + this.token++; + this.gs = L.resign(this.gs, HUMAN); + this.advance(); + }), + onLeave: () => this.confirmThen('Leave the deck?', this.gs && this.gs.phase !== 'over' ? 'Your game is saved; you can resume next time.' : 'Back to the game menu.', () => this.scene.start('GameMenu')), + onClose: () => { this.modal = null; this.hud.showPortraits(); this.renderAll(); }, + }); + } + + openRules() { + try { new TutorialModal(this.gameDef).open(); } catch (_) { /* no tutorial */ } + } + + confirmThen(heading, text, fn) { + this.time.delayedCall(10, () => { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); fn(); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); }, + }); + }); + } + + openFormationsDlg() { + if (this.phase !== 'setup') return; + this.hud.hidePortraits(); + this.modal = openFormations(this, { + variant: this.gs.variant, current: L.readLayout(this.gs, HUMAN), depth: D.modal, + onApply: (layout) => { this.gs = L.applyLayout(this.gs, HUMAN, layout); this.trayPick = null; this.setupSel = null; this.setupChanged(); }, + onClose: () => { this.modal = null; this.hud.showPortraits(); }, + }); + } + + // ── the end ───────────────────────────────────────────────────────────────── + endGame() { + if (this.phase === 'over') return; + this.phase = 'over'; + this.clearSave(); + const s = this.gs; + const won = s.winner === HUMAN, draw = s.winner == null; + this.record = this.bumpRecord(draw ? 'd' : won ? 'w' : 'l'); + // flip everything face-up in a wave from your side to theirs + this.renderAll(); + const tok = this.token; + const views = [...this.views.values()].filter((v) => !v.faceUp).sort((a, b) => b.y - a.y || a.x - b.x); + views.forEach((v, i) => this.time.delayedCall(200 + i * 35, () => { if (tok === this.token) v.setFaceUp(true, true); })); + SND.sting(this, draw ? 'draw' : won ? 'win' : 'lose'); + if (won) playSound(this, SFX.VICTORY_SHORT); + if (!draw) this.hud.emotion(won ? 'upset' : 'happy'); + this.time.delayedCall(700, () => this.hud.say(opponentLine(draw ? 'draw' : won ? 'lose' : 'win', this.tier))); + this.time.delayedCall(450 + views.length * 35, () => { if (tok === this.token && this.phase === 'over') this.openReport(); }); + } + + openReport() { + if (this.modal || !this.gs || this.gs.phase !== 'over') return; + this.modal = openEndScreen(this, { + state: this.gs, human: HUMAN, depth: D.end, record: this.record, + onReplay: () => this.enterReplay(), + onRematch: () => this.startMatch(this.settings.setup), + onNewGame: () => this.openBriefing(), + onLeave: () => this.scene.start('GameMenu'), + onClose: () => { this.modal = null; }, + }); + } + + // ── replay ────────────────────────────────────────────────────────────────── + enterReplay() { + if (!this.start) return; + const states = L.replayStates(this.start, this.gs.log); + if (this.gs.endReason === 'resign') states.push(this.gs); + this.replay = { states, i: 0 }; + this.phase = 'replay'; + this.clearViews(); + this.renderAll(); + } + replayGo(i) { + if (!this.replay) return; + this.replay.i = Math.max(0, Math.min(this.replay.states.length - 1, i)); + this.syncPieces(); this.drawMarks(); + const s = this.shownState(); + this.hud.refreshLeft(s, 'replay', {}); + this.hud.refreshCards(s, { mode: 'play' }); + this.hud.logScroll = 0; + this.hud.refreshLog(s.log, { showRanks: true, title: 'REPLAY LOG' }); + this.renderStatus(); + } + replayToggle() { + if (this.replayTimer) { this.replayTimer.remove(); this.replayTimer = null; this.renderControls(); return; } + if (this.replay.i >= this.replay.states.length - 1) this.replay.i = 0; + this.replayTimer = this.time.addEvent({ + delay: 450, loop: true, callback: () => { + if (this.replay.i >= this.replay.states.length - 1) { this.replayTimer.remove(); this.replayTimer = null; this.renderControls(); return; } + this.replayGo(this.replay.i + 1); + }, + }); + this.renderControls(); + } + exitReplay() { + this.replayTimer?.remove(); this.replayTimer = null; + this.replay = null; + this.phase = 'over'; + this.clearViews(); + this.renderAll(); + for (const v of this.views.values()) v.setFaceUp(true); } } + +function dashedRect(g, x, y, w, h, dash = 8, gap = 6) { + const seg = (x1, y1, x2, y2) => { + const len = Math.hypot(x2 - x1, y2 - y1); + const dx = (x2 - x1) / len, dy = (y2 - y1) / len; + for (let t = 0; t < len; t += dash + gap) { + const e = Math.min(len, t + dash); + g.lineBetween(x1 + dx * t, y1 + dy * t, x1 + dx * e, y1 + dy * e); + } + }; + seg(x, y, x + w, y); seg(x + w, y, x + w, y + h); seg(x + w, y + h, x, y + h); seg(x, y + h, x, y); +} + +function matchup(rank) { + if (rank === FLAG) return 'Lose it and the battle is lost.'; + if (rank === BOMB) return 'Beats: everything that attacks it except a Miner.'; + if (rank === SPY) return 'Beats: the Marshal (when attacking). Loses to: everything else.'; + if (rank === MARSHAL) return 'Beats: every rank. Loses to: a Bomb, or a Spy that attacks it.'; + if (rank === 3) return 'Beats: Spy, Scout, Bombs. Ties: Miner. Loses to: 4 and up.'; + const below = rank === 2 ? 'Spy' : `ranks 1–${rank - 1}`; + return `Beats: ${below}. Ties: another ${rankName(rank)}. Loses to: ${rank + 1} and up, and Bombs.`; +} diff --git a/src/games/stratego/StrategoHud.js b/src/games/stratego/StrategoHud.js new file mode 100644 index 0000000..98966da --- /dev/null +++ b/src/games/stratego/StrategoHud.js @@ -0,0 +1,308 @@ +// StrategoHud.js: everything round the board on the command deck. +// +// left column setup: the Barracks (units still to deploy; press one to +// pick it up, then drop it on a square) +// play: Enemy Forces (each enemy rank, how many are left, +// how many you can currently see) +// right rail two commander cards (portrait, faction, units left, +// casualties), the Battle Log, and the control buttons +// header title and the one-line status + +import { Button } from '../../ui/Button.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { + RANK_ORDER, rankName, FACTIONS, variantOf, PLAYER_COLOR_HEX, PLAYER_COLORS, +} from './StrategoData.js'; +import { armyStatus, aliveCount, isKnownTo, moveNotation, battleText } from './StrategoLogic.js'; +import { + LEFT, LEFT_ROWS, leftRowRect, CARD_OPP, CARD_YOU, LOG, CONTROLS, TITLE, STATUS, PORTRAIT_R, portraitPos, +} from './StrategoLayout.js'; +import { DISPLAY_FONT, UI_FONT, HUE } from './StrategoArt.js'; +import { PieceView } from './StrategoPieces.js'; +import { BTN } from './StrategoDialogs.js'; + +const LOG_LINE = 27; + +export class Hud { + constructor(scene, depth, { names, skill, opponent, humanSeat = 0, onButton, onTrayDown }) { + this.scene = scene; + this.depth = depth; + this.names = names; + this.skill = skill; + this.opponent = opponent; + this.human = humanSeat; + this.onButton = onButton; + this.onTrayDown = onTrayDown; + this.leftObjs = []; + this.cardObjs = []; + this.logObjs = []; + this.buttons = []; + this.logScroll = 0; + this.bubble = null; + } + + build() { + const s = this.scene, d = this.depth; + this.title = s.add.text(TITLE.x, TITLE.y, 'FOG OF WAR', { + fontFamily: DISPLAY_FONT, fontSize: '44px', color: HUE.ink, letterSpacing: 6, + }).setOrigin(0.5, 0).setDepth(d).setShadow(0, 0, HUE.cyanHex, 18, true, true); + this.status = s.add.text(STATUS.x, STATUS.y, '', { + fontFamily: UI_FONT, fontSize: '20px', color: HUE.ink, align: 'center', + }).setOrigin(0.5).setDepth(d); + this.turnChip = s.add.graphics().setDepth(d); + + this.leftTitle = s.add.text(LEFT.x + 20, LEFT.y + 14, '', { fontFamily: DISPLAY_FONT, fontSize: '22px', color: HUE.ink }).setDepth(d); + this.leftSub = s.add.text(LEFT.x + LEFT.w - 18, LEFT.y + 20, '', { fontFamily: UI_FONT, fontSize: '14px', color: HUE.inkDim }).setOrigin(1, 0).setDepth(d); + this.logTitle = s.add.text(LOG.x + 20, LOG.y + 14, 'BATTLE LOG', { fontFamily: DISPLAY_FONT, fontSize: '20px', color: HUE.ink }).setDepth(d); + this.logSub = s.add.text(LOG.x + LOG.w - 18, LOG.y + 20, '', { fontFamily: UI_FONT, fontSize: '13px', color: HUE.inkDim }).setOrigin(1, 0).setDepth(d); + const maskG = s.make.graphics({ add: false }); + maskG.fillStyle(0xffffff).fillRect(LOG.x + 8, LOG.y + 58, LOG.w - 16, LOG.h - 66); + this.logMask = maskG.createGeometryMask(); + + // portraits + const po = portraitPos(CARD_OPP), py = portraitPos(CARD_YOU); + try { this.oppPortrait = createOpponentPortrait(s, this.opponent, po.x, po.y, PORTRAIT_R, d + 1); } catch (_) { this.oppPortrait = null; } + try { this.youPortrait = createPlayerPortrait(s, py.x, py.y, PORTRAIT_R, d + 1, 'StrategoGame'); } catch (_) { this.youPortrait = null; } + for (const [p, seat] of [[po, 1], [py, 0]]) { + const g = s.add.graphics().setDepth(d + 3); + g.lineStyle(3, PLAYER_COLORS[seat], 1).strokeCircle(p.x, p.y, PORTRAIT_R + 3); + g.lineStyle(1, 0xffffff, 0.25).strokeCircle(p.x, p.y, PORTRAIT_R + 7); + } + + s.input.on('wheel', (pointer, _o, _dx, dy) => { + if (pointer.x < LOG.x || pointer.x > LOG.x + LOG.w || pointer.y < LOG.y || pointer.y > LOG.y + LOG.h) return; + this.logScroll = Math.max(0, this.logScroll + (dy > 0 ? -2 : 2)); + if (this._lastLog) this.refreshLog(...this._lastLog); + }); + return this; + } + + // ── header ────────────────────────────────────────────────────────────────── + setStatus(text, { color = HUE.ink, seat = null } = {}) { + this.status.setText(text).setColor(color); + this.turnChip.clear(); + if (seat != null) { + const w = this.status.width + 50; + this.turnChip.fillStyle(PLAYER_COLORS[seat], 0.18).fillRoundedRect(STATUS.x - w / 2, STATUS.y - 20, w, 40, 20); + this.turnChip.lineStyle(1.5, PLAYER_COLORS[seat], 0.8).strokeRoundedRect(STATUS.x - w / 2, STATUS.y - 20, w, 40, 20); + } + } + + // ── left column ───────────────────────────────────────────────────────────── + clearLeft() { this.leftObjs.forEach((o) => (o.destroy ? o.destroy() : null)); this.leftObjs = []; } + + /** mode 'setup': tray counts; 'play'/'over'/'replay': enemy forces. */ + refreshLeft(state, mode, { trayCounts = null, pick = null } = {}) { + this.clearLeft(); + const s = this.scene, d = this.depth; + const counts = variantOf(state.variant).counts; + const ranks = RANK_ORDER.filter((k) => (counts[k] ?? 0) > 0); + const foe = 1 - this.human; + if (mode === 'setup') { + this.leftTitle.setText('BARRACKS'); + const left = Object.values(trayCounts).reduce((a, b) => a + Math.max(0, b), 0); + this.leftSub.setText(left ? `${left} to deploy` : 'all deployed'); + } else { + this.leftTitle.setText('ENEMY FORCES'); + this.leftSub.setText(`${aliveCount(state, foe)} of ${variantOf(state.variant).size} remain`); + } + const status = mode === 'setup' ? null : armyStatus(state, foe); + // visible-now counts (you can see these enemy units on the board) + const seen = {}; + if (mode !== 'setup') { + for (const row of state.board) for (const p of row) { + if (p && p.owner === foe && isKnownTo(state, this.human, p)) seen[p.rank] = (seen[p.rank] ?? 0) + 1; + } + } + const rowH = Math.min(LEFT_ROWS.rowH, Math.floor((LEFT.h - 80) / ranks.length)); + ranks.forEach((rank, i) => { + const r = { ...leftRowRect(0), y: LEFT_ROWS.y + i * rowH, h: rowH - 6 }; + const g = s.add.graphics().setDepth(d); + this.leftObjs.push(g); + const n = mode === 'setup' ? trayCounts[rank] ?? 0 : status[rank].alive; + const empty = n <= 0; + const picked = mode === 'setup' && pick === rank; + g.fillStyle(picked ? 0x3a2c0a : 0x0c1828, picked ? 0.95 : 0.7).fillRoundedRect(r.x, r.y, r.w, r.h, 8); + g.lineStyle(picked ? 2 : 1, picked ? HUE.amber : HUE.cyan, picked ? 1 : 0.22).strokeRoundedRect(r.x, r.y, r.w, r.h, 8); + const icon = new PieceView(s, { owner: mode === 'setup' ? this.human : foe, rank }, { faceUp: true, depth: d + 1, scale: 0.86, x: r.x + 40, y: r.y + r.h / 2 - 2 }); + icon.c.setAlpha(empty ? 0.3 : 1); + this.leftObjs.push(icon); + const nameT = s.add.text(r.x + 84, r.y + 12, rankName(rank), { fontFamily: DISPLAY_FONT, fontSize: '19px', color: empty ? HUE.inkDim : HUE.ink }).setDepth(d + 1); + this.leftObjs.push(nameT); + if (mode === 'setup') { + this.leftObjs.push(s.add.text(r.x + r.w - 16, r.y + r.h / 2, `×${Math.max(0, n)}`, { + fontFamily: DISPLAY_FONT, fontSize: '28px', color: empty ? '#41566a' : HUE.amberHex, + }).setOrigin(1, 0.5).setDepth(d + 1)); + this.leftObjs.push(s.add.text(r.x + 84, r.y + 38, empty ? 'deployed' : rank === 2 ? 'runs any distance' : rank === 3 ? 'defuses bombs' : rank === 1 ? 'kills the Marshal' : rank === 11 ? 'immovable' : rank === 0 ? 'protect it!' : 'drag to deploy', { + fontFamily: UI_FONT, fontSize: '13px', color: HUE.inkDim, + }).setDepth(d + 1)); + const z = s.add.zone(r.x, r.y, r.w, r.h).setOrigin(0).setDepth(d + 2); + if (!empty) z.setInteractive({ useHandCursor: true }); + z.on('pointerdown', (p) => this.onTrayDown?.(rank, p)); + this.leftObjs.push(z); + } else { + // pips: alive (lit) and lost (hollow) + const tot = status[rank].total; + const pipR = tot > 6 ? 6 : 7, gap = tot > 6 ? 15 : 18; + const pg = s.add.graphics().setDepth(d + 1); + for (let k = 0; k < tot; k++) { + const px = r.x + 90 + k * gap, py = r.y + r.h - 18; + if (k < status[rank].alive) pg.fillStyle(PLAYER_COLORS[foe], 1).fillCircle(px, py, pipR).lineStyle(1, 0xffffff, 0.5).strokeCircle(px, py, pipR); + else pg.lineStyle(1.5, 0x5a6a7a, 0.8).strokeCircle(px, py, pipR - 1); + } + this.leftObjs.push(pg); + this.leftObjs.push(s.add.text(r.x + r.w - 14, r.y + 12, `${status[rank].alive}/${tot}`, { + fontFamily: DISPLAY_FONT, fontSize: '20px', color: empty ? '#41566a' : HUE.ink, + }).setOrigin(1, 0).setDepth(d + 1)); + if (seen[rank] && !empty) { + this.leftObjs.push(s.add.text(r.x + r.w - 14, r.y + r.h - 26, `${seen[rank]} seen`, { + fontFamily: UI_FONT, fontSize: '13px', color: HUE.amberHex, + }).setOrigin(1, 0).setDepth(d + 1)); + } + } + }); + } + + /** Is (x, y) over the left column? (dropping a unit there returns it) */ + overLeft(x, y) { return x >= LEFT.x && x <= LEFT.x + LEFT.w && y >= LEFT.y && y <= LEFT.y + LEFT.h; } + + // ── commander cards ───────────────────────────────────────────────────────── + refreshCards(state, { current = null, thinking = false, mode = 'play' } = {}) { + this.cardObjs.forEach((o) => { this.scene.tweens.killTweensOf(o); o.destroy(); }); this.cardObjs = []; + const s = this.scene, d = this.depth; + for (const [card, seat] of [[CARD_OPP, 1 - this.human], [CARD_YOU, this.human]]) { + const x = card.x, y = card.y; + const active = current === seat; + const g = s.add.graphics().setDepth(d); + if (active) { + g.lineStyle(3, PLAYER_COLORS[seat], 1).strokeRoundedRect(x + 1, y + 1, card.w - 2, card.h - 2, 14); + } + this.cardObjs.push(g); + const tx = x + 146; + const name = seat === this.human ? `${this.names[seat]}` : this.names[seat]; + this.cardObjs.push(s.add.text(tx, y + 16, name, { fontFamily: DISPLAY_FONT, fontSize: '25px', color: HUE.ink }).setDepth(d + 1)); + this.cardObjs.push(s.add.text(tx, y + 50, FACTIONS[seat].name.toUpperCase(), { + fontFamily: UI_FONT, fontSize: '14px', color: PLAYER_COLOR_HEX[seat], letterSpacing: 2, + }).setDepth(d + 1)); + let sub; + if (mode === 'setup') sub = seat === this.human ? 'Deploying…' : 'Deployed and waiting'; + else sub = `${aliveCount(state, seat)} units in the field`; + this.cardObjs.push(s.add.text(tx, y + 74, sub, { fontFamily: UI_FONT, fontSize: '16px', color: HUE.inkDim }).setDepth(d + 1)); + if (seat !== this.human) { + const stars = '★'.repeat(this.skill) + '☆'.repeat(5 - this.skill); + this.cardObjs.push(s.add.text(x + card.w - 18, y + 20, stars, { fontFamily: UI_FONT, fontSize: '18px', color: HUE.amberHex }).setOrigin(1, 0).setDepth(d + 1)); + } + if (active && mode === 'play') { + const t = s.add.text(x + card.w - 18, y + 76, thinking ? 'THINKING' : 'TO MOVE', { + fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#0a0f18', backgroundColor: PLAYER_COLOR_HEX[seat], padding: { x: 8, y: 3 }, + }).setOrigin(1, 0).setDepth(d + 1); + this.cardObjs.push(t); + if (thinking) s.tweens.add({ targets: t, alpha: { from: 1, to: 0.35 }, duration: 520, yoyo: true, repeat: -1 }); + } + // casualties, grouped by rank + g.lineStyle(1, HUE.cyan, 0.2).lineBetween(x + 14, y + 124, x + card.w - 14, y + 124); + this.cardObjs.push(s.add.text(x + 18, y + 130, 'CASUALTIES', { fontFamily: UI_FONT, fontSize: '12px', color: HUE.inkDim, letterSpacing: 2 }).setDepth(d + 1)); + const lost = {}; + for (const r of state.captured[seat]) lost[r] = (lost[r] ?? 0) + 1; + const order = RANK_ORDER.filter((k) => lost[k]); + if (!order.length) { + this.cardObjs.push(s.add.text(x + 130, y + 130, 'none', { fontFamily: UI_FONT, fontSize: '12px', color: '#41566a' }).setDepth(d + 1)); + } + order.forEach((rank, i) => { + const col = i % 7, row = Math.floor(i / 7); + const cx = x + 34 + col * 76, cy = y + 160 + row * 30; + const icon = new PieceView(s, { owner: seat, rank }, { faceUp: true, depth: d + 1, scale: 0.36, x: cx, y: cy }); + this.cardObjs.push(icon.c); + this.cardObjs.push(s.add.text(cx + 20, cy + 2, `×${lost[rank]}`, { fontFamily: DISPLAY_FONT, fontSize: '16px', color: HUE.ink }).setOrigin(0, 0.5).setDepth(d + 1)); + }); + } + } + + // ── battle log ────────────────────────────────────────────────────────────── + refreshLog(log, { showRanks = true, title = 'BATTLE LOG' } = {}) { + this._lastLog = [log, { showRanks, title }]; + this.logObjs.forEach((o) => o.destroy()); this.logObjs = []; + const s = this.scene, d = this.depth; + this.logTitle.setText(title); + this.logSub.setText(log.length ? `${log.length} moves · scroll for more` : ''); + const visible = Math.floor((LOG.h - 66) / LOG_LINE); + const maxScroll = Math.max(0, log.length - visible); + this.logScroll = Math.min(this.logScroll, maxScroll); + const end = log.length - this.logScroll; + const start = Math.max(0, end - visible); + if (!log.length) { + this.logObjs.push(s.add.text(LOG.x + 22, LOG.y + 70, 'No contact yet.', { fontFamily: UI_FONT, fontSize: '16px', color: '#41566a' }).setDepth(d)); + return; + } + for (let i = start; i < end; i++) { + const e = log[i]; + const y = LOG.y + 62 + (i - start) * LOG_LINE; + const g = s.add.graphics().setDepth(d); + g.fillStyle(PLAYER_COLORS[e.seat], 1).fillCircle(LOG.x + 30, y + 11, 5); + if (e.attack) g.fillStyle(0xffffff, 0.04).fillRect(LOG.x + 12, y - 1, LOG.w - 24, LOG_LINE - 2); + this.logObjs.push(g); + this.logObjs.push(s.add.text(LOG.x + 44, y, `${e.ply}.`, { fontFamily: UI_FONT, fontSize: '14px', color: '#5d7a90' }).setDepth(d)); + this.logObjs.push(s.add.text(LOG.x + 96, y - 1, moveNotation(e), { fontFamily: DISPLAY_FONT, fontSize: '17px', color: HUE.ink }).setDepth(d)); + if (e.attack) { + const bt = battleText(e, this.human, showRanks); + const won = e.result === 'both' ? null : (e.result === 'attacker') === (e.seat === this.human); + this.logObjs.push(s.add.text(LOG.x + 196, y, bt, { + fontFamily: UI_FONT, fontSize: '15px', color: won == null ? HUE.amberHex : won ? '#7fe0a0' : '#ff8a7a', + }).setDepth(d)); + } else if (e.dist > 1) { + this.logObjs.push(s.add.text(LOG.x + 196, y, `scout run · ${e.dist}`, { fontFamily: UI_FONT, fontSize: '14px', color: '#5d7a90' }).setDepth(d)); + } + } + } + + // ── controls ──────────────────────────────────────────────────────────────── + /** rows: [[{ key, label, bg, enabled, w }...], ...] */ + setControls(rows) { + this.buttons.forEach((b) => b.destroy()); this.buttons = []; + const s = this.scene, d = this.depth; + const rowH = 64, top = CONTROLS.y + 22; + rows.forEach((row, ri) => { + const pad = 16; + const totalW = CONTROLS.w - pad * 2; + const units = row.reduce((a, b) => a + (b.w ?? 1), 0); + const gap = 10; + let x = CONTROLS.x + pad; + row.forEach((b) => { + const bw = ((totalW - gap * (row.length - 1)) * (b.w ?? 1)) / units; + const btn = new Button(s, x + bw / 2, top + ri * rowH + 26, b.label, () => this.onButton?.(b.key), { + width: bw, height: 52, fontSize: b.fontSize ?? 18, bg: b.bg ?? BTN, + }).setDepth(d + 2); + if (b.enabled === false) btn.setEnabled(false); + this.buttons.push(btn); + x += bw + gap; + }); + }); + } + + // ── comm line ─────────────────────────────────────────────────────────────── + say(text, dur = 3200) { + if (!text) return; + const s = this.scene; + this.bubble?.destroy(); + const bx = CARD_OPP.x + 140, by = CARD_OPP.y + 98, bw = CARD_OPP.w - 152; + const t = s.add.text(bx + 18, by + 12, `“${text}”`, { + fontFamily: UI_FONT, fontSize: '17px', color: '#eaf6ff', wordWrap: { width: bw - 36 }, + }); + const h = Math.max(50, t.height + 34); + const g = s.add.graphics(); + const col = PLAYER_COLORS[1 - this.human]; + g.fillStyle(0x0b2238, 0.98).fillRoundedRect(bx, by, bw, h, 10); + g.lineStyle(2, col, 1).strokeRoundedRect(bx, by, bw, h, 10); + g.fillStyle(0x0b2238, 1).fillTriangle(bx + 1, by + 10, bx + 1, by + 30, bx - 16, by + 4); + g.lineStyle(2, col, 1).lineBetween(bx - 16, by + 4, bx + 1, by + 10).lineBetween(bx - 16, by + 4, bx + 1, by + 30); + const tag = s.add.text(bx + bw - 12, by + h - 8, '◉ COMM', { fontFamily: UI_FONT, fontSize: '10px', color: PLAYER_COLOR_HEX[1 - this.human] }).setOrigin(1, 1); + const cont = s.add.container(0, 0, [g, t, tag]).setDepth(this.depth + 20).setAlpha(0); + this.bubble = cont; + s.tweens.add({ targets: cont, alpha: 1, duration: 160 }); + s.tweens.add({ targets: cont, alpha: 0, delay: dur, duration: 300, onComplete: () => { cont.destroy(); if (this.bubble === cont) this.bubble = null; } }); + } + + emotion(e) { this.oppPortrait?.playEmotion?.(e); } + hidePortraits() { this.oppPortrait?.setVideoVisible?.(false); this.youPortrait?.setVideoVisible?.(false); } + showPortraits() { this.oppPortrait?.setVideoVisible?.(true); this.youPortrait?.setVideoVisible?.(true); } +} diff --git a/src/games/stratego/StrategoLayout.js b/src/games/stratego/StrategoLayout.js new file mode 100644 index 0000000..22bafc6 --- /dev/null +++ b/src/games/stratego/StrategoLayout.js @@ -0,0 +1,55 @@ +// StrategoLayout.js: every rectangle on the command deck, in one place so the +// art, the HUD, the scene and the verify script agree. 1920×1080. + +import { GRID } from './StrategoData.js'; + +export const W = 1920, H = 1080; + +// Board: 10×10 tiles on the holo-table. +export const TILE = 80, GAP = 4, PITCH = TILE + GAP; +export const BOARD_W = GRID * PITCH - GAP; // 836 +export const BX0 = 420, BY0 = 150; // first tile's top-left +export const FRAME_PAD = 34; +export const FRAME = { x: BX0 - FRAME_PAD, y: BY0 - FRAME_PAD, w: BOARD_W + FRAME_PAD * 2, h: BOARD_W + FRAME_PAD * 2 }; +export const BOARD_CX = BX0 + BOARD_W / 2, BOARD_CY = BY0 + BOARD_W / 2; + +// Piece block on a tile: the face plus a darker lower edge for thickness. +export const PIECE = { w: 70, face: 66, edge: 6 }; + +// Header over the board. +export const TITLE = { x: BOARD_CX, y: 22 }; +export const STATUS = { x: BOARD_CX, y: 84, w: 900 }; +export const FOOTER = { x: BOARD_CX, y: 1048 }; + +// Left column: enemy-forces tracker in play, the barracks tray in setup. +export const LEFT = { x: 24, y: 24, w: 352, h: 1032 }; +export const LEFT_ROWS = { x: LEFT.x + 12, y: LEFT.y + 66, w: LEFT.w - 24, rowH: 77 }; + +// Right rail. +export const RAIL = { x: 1330, w: 566 }; +// (the rail starts below the music player's corner controls) +export const CARD_OPP = { x: RAIL.x, y: 96, w: RAIL.w, h: 202 }; +export const CARD_YOU = { x: RAIL.x, y: 308, w: RAIL.w, h: 202 }; +export const LOG = { x: RAIL.x, y: 520, w: RAIL.w, h: 318 }; +export const CONTROLS = { x: RAIL.x, y: 850, w: RAIL.w, h: 206 }; +export const PORTRAIT_R = 48; +export const portraitPos = (card) => ({ x: card.x + 24 + PORTRAIT_R, y: card.y + 18 + PORTRAIT_R }); + +// Battle stage (over the board). +export const STAGE = { cx: BOARD_CX, cy: BOARD_CY, offset: 150, size: 190 }; + +export function tileCenter(r, c) { return { x: BX0 + c * PITCH + TILE / 2, y: BY0 + r * PITCH + TILE / 2 }; } +export function cellAt(x, y) { + const c = Math.floor((x - BX0) / PITCH), r = Math.floor((y - BY0) / PITCH); + if (r < 0 || r >= GRID || c < 0 || c >= GRID) return null; + // ignore clicks in the gaps + const lx = x - BX0 - c * PITCH, ly = y - BY0 - r * PITCH; + if (lx > TILE + 1 || ly > TILE + 1) return null; + return { r, c }; +} +export function leftRowRect(i) { + return { x: LEFT_ROWS.x, y: LEFT_ROWS.y + i * LEFT_ROWS.rowH, w: LEFT_ROWS.w, h: LEFT_ROWS.rowH - 6 }; +} + +/** Named rectangles for the layout check in tools/verifyStratego.js. */ +export const HUD_RECTS = { FRAME, LEFT, CARD_OPP, CARD_YOU, LOG, CONTROLS }; diff --git a/src/games/stratego/StrategoLogic.js b/src/games/stratego/StrategoLogic.js index adc6d86..9560bfb 100644 --- a/src/games/stratego/StrategoLogic.js +++ b/src/games/stratego/StrategoLogic.js @@ -1,20 +1,36 @@ -// Stratego — pure game engine. No Phaser, no rendering, no timers. Mutators -// deep-clone the state and return the next one so the scene and AI can look -// ahead freely. A match has two phases: SETUP (arrange your 40 pieces) and PLAY -// (alternating single moves until a flag is captured or a side is stuck). +// Fog of War (Stratego rules): the pure rules engine. No Phaser, no timers. +// Every mutator deep-clones and returns the next state, so the scene, the +// undo stack, the replay and the AI can all hold states freely. States are +// plain JSON (no Sets or Maps) so they save to localStorage as they are. // -// Hidden information: every piece carries a `revealed` flag. Your own pieces are -// always known to you; an enemy piece is hidden until it fights and survives, -// after which it stays revealed (digital-standard). The engine never hides data -// from itself — the *renderer* decides what each viewer may see. +// A match has three phases: 'setup' (each side deploys its army in its four +// home rows), 'play' (alternate single moves) and 'over'. +// +// Hidden information. A piece's rank is always in the state; who may *see* +// it is decided by `known[viewer]`, a list of piece ids. In 'assisted' reveal +// mode the survivor of a battle joins its enemy's known list for good (the +// usual digital convention). In 'classic' mode it goes back face-down, as on +// the real board, and only the battle record in the log remembers it. Some +// facts are public: whether a piece has ever moved (so it is not a Bomb or +// the Flag), whether it has run more than one square (so it is a Scout), and +// where it started. +// +// Movement rules beyond the basics (ISF style): +// • Two-square rule: a piece may not move back and forth between the same +// two squares more than three times in a row. For a Scout the "squares" +// are the stretch of line its first move covered. +// • More-squares (chase) rule: a piece chasing one enemy piece that keeps +// running may not bring the pair back into a position they have already +// been in during that chase. The chaser has to break off. import { - GRID, isLake, FLAG, BOMB, SCOUT, RANKS, buildArmy, canMove, - battleResult, setupRows, backRow, PLAYER_COLORS, PLAYER_COLOR_HEX, + GRID, isLake, FLAG, BOMB, SCOUT, RANKS, buildArmy, canMove, battleResult, + inSetupZone, setupRows, variantOf, lineOf, rowOfLine, colOf, countOf, + rankCode, codeRank, squareName, rankName, VARIANTS, } from './StrategoData.js'; -// ── tiny seedable RNG (deterministic when a seed is supplied) ──────────────── -function makeRng(seed) { +// ── tiny seedable RNG ───────────────────────────────────────────────────────── +export function makeRng(seed) { if (seed == null) return Math.random; let a = seed >>> 0; return function () { @@ -24,7 +40,7 @@ function makeRng(seed) { return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } -function shuffle(arr, rng) { +export function shuffle(arr, rng = Math.random) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; @@ -33,181 +49,305 @@ function shuffle(arr, rng) { } export const keyOf = (r, c) => r * GRID + c; -const inBounds = (r, c) => r >= 0 && r < GRID && c >= 0 && c < GRID; +export const rcOf = (k) => ({ r: Math.floor(k / GRID), c: k % GRID }); +export const inBounds = (r, c) => r >= 0 && r < GRID && c >= 0 && c < GRID; +const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; +const adjacent = (k1, k2) => { + const a = rcOf(k1), b = rcOf(k2); + return Math.abs(a.r - b.r) + Math.abs(a.c - b.c) === 1; +}; -// ── piece + clone ───────────────────────────────────────────────────────────── -let _idSeq = 0; -function makePiece(owner, rank) { - return { id: ++_idSeq, owner, rank, revealed: false, lastSquare: null, bounceN: 0 }; -} -function clonePiece(p) { - return p ? { id: p.id, owner: p.owner, rank: p.rank, revealed: p.revealed, - lastSquare: p.lastSquare, bounceN: p.bounceN } : null; -} +// ── clone ───────────────────────────────────────────────────────────────────── +function clonePiece(p) { return p ? { ...p } : null; } export function cloneState(s) { return { + ...s, board: s.board.map((row) => row.map(clonePiece)), - phase: s.phase, - current: s.current, - winner: s.winner, names: [...s.names], - colors: [...s.colors], - colorHex: [...s.colorHex], captured: [s.captured[0].slice(), s.captured[1].slice()], + known: [s.known[0].slice(), s.known[1].slice()], + log: s.log.slice(), lastMove: s.lastMove ? { ...s.lastMove } : null, lastBattle: s.lastBattle ? { ...s.lastBattle } : null, - plySinceCapture: s.plySinceCapture, + rep: s.rep.map((t) => (t ? { ...t, span: t.span.slice() } : null)), + chase: s.chase.map((t) => (t ? { ...t, seen: t.seen.slice() } : null)), }; } -// ── heuristic auto-arrangement ─────────────────────────────────────────────── -// Produces a sensible 40-piece formation for one seat: flag in a back corner -// ringed by bombs, a couple of bombs salted along the front line, scouts/miners -// pushed forward, the spy tucked back, and the heavy ranks held off the very -// front so they aren't traded away cheaply. Returns Map. -// -// Lines run front→back: index 0 is the row facing the enemy, 3 is the home edge. -function arrangeArmy(seat, rng) { - const rows = setupRows(seat); // e.g. [6,7,8,9] (seat 0) - // Order front→back, where "front" is the row nearest the centre/enemy and - // "back" is the home edge. Seat 0 (bottom, rows 6–9): front=6 … back=9, so - // the natural order is already front→back. Seat 1 (top, rows 0–3): front=3 … - // back=0, so reverse it. - const lines = seat === 0 ? rows.slice() // [6,7,8,9] front→back - : rows.slice().reverse(); // [3,2,1,0] front→back - // lines[0] = front row (toward centre), lines[3] = back row (home edge). - const back = lines[3]; - const place = new Map(); - const taken = (r, c) => place.has(keyOf(r, c)); - const put = (r, c, rank) => place.set(keyOf(r, c), rank); +// ── creation ────────────────────────────────────────────────────────────────── +function emptyBoard() { return Array.from({ length: GRID }, () => new Array(GRID).fill(null)); } - const pool = []; // ranks still to place - for (const key of Object.keys(RANKS)) { - const rank = Number(key); - if (rank === FLAG || rank === BOMB) continue; // handled explicitly - for (let i = 0; i < RANKS[rank].count; i++) pool.push(rank); - } - - // 1) Flag in the back row, off-centre. - const flagCol = [0, 1, 2, 7, 8, 9][Math.floor(rng() * 6)]; - put(back, flagCol, FLAG); - - // 2) Ring the flag with up to 3 bombs (sides on the back row + the cell in - // front of it on line 2). - let bombsLeft = RANKS[BOMB].count; // 6 - const guard = [ - [back, flagCol - 1], [back, flagCol + 1], [lines[2], flagCol], - ]; - for (const [r, c] of guard) { - if (bombsLeft > 0 && inBounds(r, c) && !taken(r, c)) { put(r, c, BOMB); bombsLeft--; } - } - - // 3) Scatter the remaining bombs on the forward two lines as tripwires. - const fwdCols = shuffle([...Array(GRID).keys()], rng); - let fi = 0; - while (bombsLeft > 0 && fi < fwdCols.length) { - const line = bombsLeft % 2 === 0 ? lines[0] : lines[1]; - const c = fwdCols[fi++]; - if (!taken(line, c)) { put(line, c, BOMB); bombsLeft--; } - } - - // 4) Fill the rest. Pair each free cell (by line) with a rank whose preferred - // "frontness" matches, then assign forward-leaning ranks to forward cells. - const PREF = { 1: 3, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2, 10: 2 }; - const free = []; - for (let li = 0; li < 4; li++) { - const r = lines[li]; - for (let c = 0; c < GRID; c++) if (!taken(r, c)) free.push({ r, c, li }); - } - // Sort cells front→back with a little noise; sort ranks by preferred frontness. - free.sort((a, b) => (a.li - b.li) + (rng() - 0.5) * 0.9); - pool.sort((a, b) => (PREF[a] - PREF[b]) + (rng() - 0.5) * 0.9); - for (let i = 0; i < free.length; i++) put(free[i].r, free[i].c, pool[i]); - - return place; -} - -// ── setup ──────────────────────────────────────────────────────────────────── -export function createInitialState({ names = ['You', 'Opponent'], seed = null } = {}) { - const rng = makeRng(seed); - const board = Array.from({ length: GRID }, () => new Array(GRID).fill(null)); - - for (let seat = 0; seat < 2; seat++) { - const place = arrangeArmy(seat, rng); - for (const [k, rank] of place) { - const r = Math.floor(k / GRID), c = k % GRID; - board[r][c] = makePiece(seat, rank); - } - } - - return { - board, +/** + * opts: { names, variant, reveal, seed, layouts: [layout0|null, layout1|null] } + * A layout is a seat-relative 40-char string (see readLayout); null leaves + * that side's zone empty for the player to fill from the tray. + */ +export function createInitialState(opts = {}) { + const { names = ['You', 'Opponent'], variant = 'classic', reveal = 'assisted', layouts = [null, null] } = opts; + let s = { + v: 2, + variant: VARIANTS[variant] ? variant : 'classic', + reveal: reveal === 'classic' ? 'classic' : 'assisted', phase: 'setup', current: 0, winner: null, + endReason: null, names: [names[0] ?? 'You', names[1] ?? 'Opponent'], - colors: [...PLAYER_COLORS], - colorHex: [...PLAYER_COLOR_HEX], - captured: [[], []], // captured[seat] = ranks that seat LOST + board: emptyBoard(), + captured: [[], []], // captured[seat] = ranks that seat LOST + known: [[], []], // known[viewer] = enemy piece ids viewer can see + log: [], lastMove: null, lastBattle: null, + ply: 0, plySinceCapture: 0, + rep: [null, null], + chase: [null, null], }; + for (let seat = 0; seat < 2; seat++) if (layouts[seat]) s = applyLayout(s, seat, layouts[seat]); + return s; } -// Re-roll a seat's whole formation (setup only). -export function shuffleSetup(state, seat) { - const s = cloneState(state); - if (s.phase !== 'setup') return s; - const place = arrangeArmy(seat, Math.random); - for (let r = 0; r < GRID; r++) { - for (let c = 0; c < GRID; c++) if (s.board[r][c]?.owner === seat) s.board[r][c] = null; +// ── setup ───────────────────────────────────────────────────────────────────── +function setupPiece(owner, rank) { return { owner, rank }; } + +/** Ranks of `seat` not yet on the board: { rank: count }. */ +export function trayCounts(state, seat) { + const out = {}; + const counts = variantOf(state.variant).counts; + for (const k of Object.keys(counts)) out[k] = counts[k]; + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = state.board[r][c]; + if (p && p.owner === seat) out[p.rank] = (out[p.rank] ?? 0) - 1; } - for (const [k, rank] of place) { - s.board[Math.floor(k / GRID)][k % GRID] = makePiece(seat, rank); + return out; +} +export function trayTotal(state, seat) { + return Object.values(trayCounts(state, seat)).reduce((a, b) => a + Math.max(0, b), 0); +} +export function setupComplete(state, seat) { return trayTotal(state, seat) === 0; } + +/** Put a tray piece of `rank` on an empty square of seat's zone. */ +export function setupPlace(state, seat, r, c, rank) { + if (state.phase !== 'setup' || !inSetupZone(seat, r) || state.board[r][c]) return state; + if ((trayCounts(state, seat)[rank] ?? 0) <= 0) return state; + const s = cloneState(state); + s.board[r][c] = setupPiece(seat, rank); + return s; +} + +/** Send a placed piece back to the tray. */ +export function setupRemove(state, seat, r, c) { + const p = state.board[r]?.[c]; + if (state.phase !== 'setup' || !p || p.owner !== seat) return state; + const s = cloneState(state); + s.board[r][c] = null; + return s; +} + +/** Swap two cells of one seat's zone (either may be empty: that's a move). */ +export function setupSwap(state, seat, k1, k2) { + if (state.phase !== 'setup' || k1 === k2) return state; + const a = rcOf(k1), b = rcOf(k2); + if (!inSetupZone(seat, a.r) || !inSetupZone(seat, b.r)) return state; + const pa = state.board[a.r][a.c], pb = state.board[b.r][b.c]; + if (!pa && !pb) return state; + if ((pa && pa.owner !== seat) || (pb && pb.owner !== seat)) return state; + const s = cloneState(state); + s.board[a.r][a.c] = pb ? { ...pb } : null; + s.board[b.r][b.c] = pa ? { ...pa } : null; + return s; +} + +export function setupClear(state, seat) { + if (state.phase !== 'setup') return state; + const s = cloneState(state); + for (const r of setupRows(seat)) for (let c = 0; c < GRID; c++) s.board[r][c] = null; + return s; +} + +/** Seat-relative layout string: 4 lines front→back, each 10 columns from the + * owner's left, one char per square (F B S 2–9 M, '.' empty). */ +export function readLayout(state, seat) { + let out = ''; + for (let li = 0; li < 4; li++) { + const r = rowOfLine(seat, li); + for (let cc = 0; cc < GRID; cc++) { + const c = colOf(seat, cc); + const p = state.board[r][c]; + out += p && p.owner === seat ? rankCode(p.rank) : '.'; + } + } + return out; +} + +/** Is `layout` a complete, legal deployment for `variant`? */ +export function layoutValid(layout, variant = 'classic') { + if (typeof layout !== 'string' || layout.length !== 40) return false; + const counts = {}; + for (const ch of layout) { + if (ch === '.') continue; + const r = codeRank(ch); + if (r == null) return false; + counts[r] = (counts[r] ?? 0) + 1; + } + const want = variantOf(variant).counts; + const keys = new Set([...Object.keys(want), ...Object.keys(counts)]); + for (const k of keys) if ((want[k] ?? 0) !== (counts[k] ?? 0)) return false; + return true; +} + +/** Replace seat's whole zone with a layout. */ +export function applyLayout(state, seat, layout) { + if (state.phase !== 'setup') return state; + const s = setupClear(state, seat); + for (let i = 0; i < 40 && i < layout.length; i++) { + const rank = codeRank(layout[i]); + if (rank == null) continue; + const r = rowOfLine(seat, Math.floor(i / GRID)), c = colOf(seat, i % GRID); + s.board[r][c] = setupPiece(seat, rank); } return s; } -// Swap two of a seat's own pieces during setup (drag-swap). Keys are cell keys. -export function swapSetup(state, k1, k2) { +// Heuristic deployment for whatever squares are still empty: the flag in a +// back-row square (corners preferred) ringed by bombs, the remaining bombs +// salted forward as tripwires, Scouts and Miners pushed forward, the Spy +// tucked behind the line, heavy ranks held off the very front. +export function setupFill(state, seat, rng = Math.random) { + if (state.phase !== 'setup') return state; const s = cloneState(state); - if (s.phase !== 'setup' || k1 === k2) return s; - const r1 = Math.floor(k1 / GRID), c1 = k1 % GRID; - const r2 = Math.floor(k2 / GRID), c2 = k2 % GRID; - const a = s.board[r1][c1], b = s.board[r2][c2]; - if (!a || !b || a.owner !== b.owner) return s; - s.board[r1][c1] = b; s.board[r2][c2] = a; + const tray = trayCounts(s, seat); + const free = (r, c) => inSetupZone(seat, r) && !s.board[r][c]; + const put = (r, c, rank) => { s.board[r][c] = setupPiece(seat, rank); tray[rank]--; }; + const barrage = s.variant === 'barrage'; + + if ((tray[FLAG] ?? 0) > 0) { + const cols = shuffle([...Array(GRID).keys()], rng) + .sort((a, b) => (Math.min(a, 9 - a) - Math.min(b, 9 - b)) + (rng() - 0.5) * 3); + let spot = null; + for (const li of [3, 2, 1, 0]) { + const r = rowOfLine(seat, li); + const c = cols.find((cc) => free(r, cc)); + if (c != null) { spot = { r, c }; break; } + } + if (spot) { + put(spot.r, spot.c, FLAG); + const fwd = seat === 0 ? -1 : 1; + const ring = shuffle([[spot.r, spot.c - 1], [spot.r, spot.c + 1], [spot.r + fwd, spot.c]], rng); + const ringN = barrage ? 1 : 3; + let n = 0; + for (const [r, c] of ring) { + if (n >= ringN || (tray[BOMB] ?? 0) <= 0) break; + if (inBounds(r, c) && free(r, c)) { put(r, c, BOMB); n++; } + } + } + } + // Remaining bombs on the forward lines (or anywhere if those are full). + const fwdCols = shuffle([...Array(GRID).keys()], rng); + let fi = 0; + while ((tray[BOMB] ?? 0) > 0 && fi < fwdCols.length * 2) { + const li = fi < fwdCols.length ? (fi % 2) : 2 + (fi % 2); + const r = rowOfLine(seat, li), c = fwdCols[fi % fwdCols.length]; + if (free(r, c)) put(r, c, BOMB); + fi++; + } + // Everything else: pair cells (front→back, with noise) with ranks sorted by + // how far forward they like to stand. + const PREF = { 1: 2.4, 2: 0, 3: 1.2, 4: 0.8, 5: 0.9, 6: 1.3, 7: 1.4, 8: 1.6, 9: 1.7, 10: 1.6, [BOMB]: 2, [FLAG]: 3 }; + const pool = []; + for (const k of Object.keys(tray)) for (let i = 0; i < tray[k]; i++) pool.push(Number(k)); + const cells = []; + for (let li = 0; li < 4; li++) { + const r = rowOfLine(seat, li); + for (let c = 0; c < GRID; c++) if (free(r, c)) cells.push({ r, c, li }); + } + if (barrage) { + // Barrage: only eight units, so scatter them rather than filling lines. + shuffle(cells, rng); + cells.length = Math.min(cells.length, pool.length); + } + cells.sort((a, b) => (a.li - b.li) + (rng() - 0.5) * 1.2); + pool.sort((a, b) => (PREF[a] - PREF[b]) + (rng() - 0.5) * 1.1); + for (let i = 0; i < cells.length && i < pool.length; i++) put(cells[i].r, cells[i].c, pool[i]); return s; } -// Leave setup and begin the battle. The human (seat 0) moves first. +/** Leave setup and begin the battle. Assigns ids and origins; seat 0 (red) + * moves first. Both sides must be fully deployed. */ export function startBattle(state) { + if (state.phase !== 'setup' || !setupComplete(state, 0) || !setupComplete(state, 1)) return state; const s = cloneState(state); - if (s.phase !== 'setup') return s; + const n = [0, 0]; + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = s.board[r][c]; + if (!p) continue; + s.board[r][c] = { + id: p.owner * 100 + (++n[p.owner]), owner: p.owner, rank: p.rank, + moved: false, scout: false, origin: keyOf(r, c), + }; + } s.phase = 'play'; s.current = 0; + s.ply = 0; + s.plySinceCapture = 0; return s; } -// ── queries ────────────────────────────────────────────────────────────────── -export function pieceAt(state, r, c) { return state.board[r][c]; } +// ── queries ─────────────────────────────────────────────────────────────────── export function isGameOver(state) { return state.phase === 'over'; } -export function winner(state) { return state.winner; } -export function currentName(state) { return state.names[state.current]; } +export function findPiece(state, id) { + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = state.board[r][c]; + if (p && p.id === id) return { r, c, p }; + } + return null; +} +/** Can `viewer` see this piece's rank? */ +export function isKnownTo(state, viewer, p) { + if (!p) return false; + if (p.owner === viewer || state.phase === 'over') return true; + return p.rank != null && state.known[viewer].includes(p.id); +} -// Legal destinations for the piece at (r,c): a list of { r, c, attack }. -// Scouts (rank 2) slide any distance in a straight line over empty squares and -// may attack the first enemy they reach; everyone else steps one orthogonal -// square. Lakes and friendly pieces block. The two-square (anti-shuffle) rule -// forbids a piece from immediately bouncing back once it has already done so. -export function legalMovesFor(state, r, c) { - const p = state.board[r][c]; +function lineSpan(fk, tk) { + const a = rcOf(fk), b = rcOf(tk); + const out = []; + const dr = Math.sign(b.r - a.r), dc = Math.sign(b.c - a.c); + for (let r = a.r, c = a.c; ; r += dr, c += dc) { + out.push(keyOf(r, c)); + if (r === b.r && c === b.c) break; + } + return out; +} + +/** Why a geometrically possible move is forbidden, or null. */ +export function blockReason(state, fr, fc, tr, tc, attack) { + const p = state.board[fr][fc]; + if (!p) return null; + const seat = p.owner, fk = keyOf(fr, fc), tk = keyOf(tr, tc); + if (!attack) { + const t = state.rep?.[seat]; + if (t && t.id === p.id && t.at === fk && t.span.includes(tk) && t.count >= 3) return 'two-square'; + const ch = state.chase?.[seat]; + const lm = state.lastMove; + if (ch && ch.chaser === p.id && lm && lm.seat !== seat && lm.id === ch.target && !lm.attack + && adjacent(fk, keyOf(lm.fr, lm.fc))) { + const qk = keyOf(lm.tr, lm.tc); + if (adjacent(tk, qk) && ch.seen.includes(`${tk},${qk}`)) return 'chase'; + } + } + return null; +} + +// All geometrically possible moves for the piece at (r,c): { r, c, attack, +// blocked } where blocked is a rule name or null. Scouts slide any distance +// over empty squares and may attack the first enemy they reach; everyone else +// steps one square. Asteroid fields and friendly pieces block. +export function movesFor(state, r, c) { + const p = state.board[r]?.[c]; if (!p || !canMove(p.rank)) return []; const out = []; - const blockedReturn = (tr, tc) => p.bounceN >= 2 && p.lastSquare === keyOf(tr, tc); - - const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; for (const [dr, dc] of DIRS) { let nr = r + dr, nc = c + dc; const maxStep = p.rank === SCOUT ? GRID : 1; @@ -215,123 +355,220 @@ export function legalMovesFor(state, r, c) { if (!inBounds(nr, nc) || isLake(nr, nc)) break; const occ = state.board[nr][nc]; if (!occ) { - if (!blockedReturn(nr, nc)) out.push({ r: nr, c: nc, attack: false }); - continue; // scout keeps sliding + out.push({ r: nr, c: nc, attack: false, blocked: blockReason(state, r, c, nr, nc, false) }); + continue; } - if (occ.owner !== p.owner && !blockedReturn(nr, nc)) { - out.push({ r: nr, c: nc, attack: true }); // can attack the first enemy - } - break; // any piece blocks further travel + if (occ.owner !== p.owner) out.push({ r: nr, c: nc, attack: true, blocked: null }); + break; } } return out; } +export function legalMovesFor(state, r, c) { return movesFor(state, r, c).filter((m) => !m.blocked); } export function hasAnyLegalMove(state, seat) { - for (let r = 0; r < GRID; r++) { - for (let c = 0; c < GRID; c++) { - const p = state.board[r][c]; - if (p && p.owner === seat && canMove(p.rank) && legalMovesFor(state, r, c).length) return true; - } + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = state.board[r][c]; + if (p && p.owner === seat && canMove(p.rank) && legalMovesFor(state, r, c).length) return true; } return false; } export function allLegalMoves(state, seat) { const moves = []; - for (let r = 0; r < GRID; r++) { - for (let c = 0; c < GRID; c++) { - const p = state.board[r][c]; - if (!p || p.owner !== seat || !canMove(p.rank)) continue; - for (const m of legalMovesFor(state, r, c)) { - moves.push({ fr: r, fc: c, tr: m.r, tc: m.c, attack: m.attack }); - } - } + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) { + const p = state.board[r][c]; + if (!p || p.owner !== seat || !canMove(p.rank)) continue; + for (const m of legalMovesFor(state, r, c)) moves.push({ fr: r, fc: c, tr: m.r, tc: m.c, attack: m.attack }); } return moves; } -// Plies without a capture before we call a stalemate draw (prevents endless -// manoeuvring when neither side can force the flag). -const DRAW_PLY_LIMIT = 360; - -// ── the move ───────────────────────────────────────────────────────────────── -// Move (or attack) the piece at (fr,fc) to (tr,tc). Resolves combat, reveals, -// flag-capture / no-move wins, and the draw cap, then flips the turn. +// ── the move ────────────────────────────────────────────────────────────────── +// Move (or attack with) the piece at (fr,fc) to (tr,tc). Resolves combat, +// knowledge, the repetition trackers, wins and draws, then passes the turn. +// The log entry it appends is public: both players saw everything in it. export function applyMove(state, fr, fc, tr, tc) { + if (state.phase !== 'play') return state; + const mover0 = state.board[fr]?.[fc]; + if (!mover0 || mover0.owner !== state.current) return state; + const mv = movesFor(state, fr, fc).find((m) => m.r === tr && m.c === tc); + if (!mv || mv.blocked) return state; + const s = cloneState(state); - if (s.phase !== 'play') return s; + const seat = s.current, foe = 1 - seat; const mover = s.board[fr][fc]; - if (!mover || mover.owner !== s.current) return s; - if (!legalMovesFor(s, fr, fc).some((m) => m.r === tr && m.c === tc)) return s; - const target = s.board[tr][tc]; - // Two-square bookkeeping: a move is an oscillation step if it returns to the - // square the piece came from on its previous move. - const fromKey = keyOf(fr, fc); - mover.bounceN = (mover.lastSquare === keyOf(tr, tc)) ? mover.bounceN + 1 : 0; - mover.lastSquare = fromKey; + const fk = keyOf(fr, fc), tk = keyOf(tr, tc); + const dist = Math.abs(tr - fr) + Math.abs(tc - fc); + s.ply++; - s.lastMove = { fr, fc, tr, tc, attack: !!target }; - s.lastBattle = null; + // Repetition trackers (computed from the position before the move). + const lm = s.lastMove; + if (target) { + s.rep[seat] = null; + s.chase[seat] = null; + } else { + const t = s.rep[seat]; + if (t && t.id === mover.id && t.at === fk && t.span.includes(tk)) { t.count++; t.at = tk; } + else s.rep[seat] = { id: mover.id, span: lineSpan(fk, tk), count: 1, at: tk }; + + const ch = s.chase[seat]; + const fled = lm && lm.seat === foe && !lm.attack && adjacent(fk, keyOf(lm.fr, lm.fc)) ? lm.id : null; + const qk = lm ? keyOf(lm.tr, lm.tc) : -1; + if (ch && ch.chaser === mover.id && fled === ch.target && adjacent(tk, qk)) { + ch.seen.push(`${tk},${qk}`); + } else { + // A new chase starts when this move makes contact with an enemy piece + // that wasn't touching the mover before. + s.chase[seat] = null; + for (const [dr, dc] of DIRS) { + const nr = tr + dr, nc = tc + dc; + if (!inBounds(nr, nc)) continue; + const q = s.board[nr][nc]; + if (!q || q.owner !== foe || !canMove(q.rank) || adjacent(fk, keyOf(nr, nc))) continue; + s.chase[seat] = { chaser: mover.id, target: q.id, seen: [`${tk},${keyOf(nr, nc)}`] }; + break; + } + } + } + + mover.moved = true; + if (dist > 1) mover.scout = true; + + const entry = { ply: s.ply, seat, id: mover.id, fr, fc, tr, tc, dist, attack: !!target }; + s.board[fr][fc] = null; if (!target) { - // Quiet move. s.board[tr][tc] = mover; - s.board[fr][fc] = null; s.plySinceCapture++; } else { - // Combat. Both pieces are exposed; the survivor stays revealed. const res = battleResult(mover.rank, target.rank); - s.lastBattle = { - r: tr, c: tc, attacker: mover.rank, defender: target.rank, - attackerOwner: mover.owner, defenderOwner: target.owner, result: res, - }; + Object.assign(entry, { aRank: mover.rank, dRank: target.rank, defId: target.id, result: res }); s.plySinceCapture = 0; - s.board[fr][fc] = null; - - if (target.rank === FLAG) { - // Flag captured — immediate win for the attacker. - mover.revealed = true; - s.board[tr][tc] = mover; - s.captured[target.owner].push(FLAG); - s.phase = 'over'; - s.winner = mover.owner; - return s; - } + const learn = (viewer, p) => { + if (s.reveal === 'assisted' && !s.known[viewer].includes(p.id)) s.known[viewer].push(p.id); + }; if (res === 'attacker') { - mover.revealed = true; s.board[tr][tc] = mover; s.captured[target.owner].push(target.rank); + learn(foe, mover); } else if (res === 'defender') { - target.revealed = true; s.board[tr][tc] = target; s.captured[mover.owner].push(mover.rank); - } else { // both destroyed + learn(seat, target); + } else { s.board[tr][tc] = null; s.captured[mover.owner].push(mover.rank); s.captured[target.owner].push(target.rank); } + if (target.rank === FLAG) { + s.log.push(entry); + s.lastMove = entry; s.lastBattle = entry; + s.phase = 'over'; s.winner = seat; s.endReason = 'flag'; + return s; + } } + s.log.push(entry); + s.lastMove = entry; + s.lastBattle = target ? entry : null; - // Turn passes. If the next side can't move, the side that just moved wins. - const next = 1 - s.current; - if (!hasAnyLegalMove(s, next)) { + // End checks. A side that cannot move loses; if neither can, it's a draw. + const nextCan = hasAnyLegalMove(s, foe); + if (!nextCan) { s.phase = 'over'; - s.winner = s.current; + if (!hasAnyLegalMove({ ...s, lastMove: null }, seat)) { s.winner = null; s.endReason = 'immobile'; } + else { s.winner = seat; s.endReason = 'nomoves'; } return s; } - if (s.plySinceCapture >= DRAW_PLY_LIMIT) { - s.phase = 'over'; - s.winner = null; // draw + if (s.plySinceCapture >= variantOf(s.variant).drawPly) { + s.phase = 'over'; s.winner = null; s.endReason = 'ply'; return s; } - s.current = next; + s.current = foe; return s; } -// Uniform entry point for the AI driver. -export function applyAction(state, action) { - if (action.type === 'move') return applyMove(state, action.fr, action.fc, action.tr, action.tc); - return state; +/** Concede. */ +export function resign(state, seat) { + if (state.phase !== 'play') return state; + const s = cloneState(state); + s.phase = 'over'; s.winner = 1 - seat; s.endReason = 'resign'; + return s; } + +// ── viewer-safe snapshot (for the AI) ───────────────────────────────────────── +// Enemy ranks the viewer may not see are replaced by null. Everything else is +// public: the log (battle ranks were shown to both players), who has moved, +// known scouts, origins, and which of the viewer's own pieces the enemy knows. +export function viewFor(state, viewer) { + const foe = 1 - viewer; + const board = state.board.map((row) => row.map((p) => { + if (!p) return null; + const mine = p.owner === viewer; + return { + id: p.id, owner: p.owner, moved: !!p.moved, scout: !!p.scout, origin: p.origin, + rank: mine || isKnownTo(state, viewer, p) ? p.rank : null, + knownToFoe: mine ? state.known[foe].includes(p.id) : false, + }; + })); + return { + v: state.v, variant: state.variant, reveal: state.reveal, phase: state.phase, + viewer, current: state.current, ply: state.ply, plySinceCapture: state.plySinceCapture, + board, captured: [state.captured[0].slice(), state.captured[1].slice()], + log: state.log.slice(), lastMove: state.lastMove ? { ...state.lastMove } : null, + rep: state.rep.map((t) => (t ? { ...t, span: t.span.slice() } : null)), + chase: state.chase.map((t) => (t ? { ...t, seen: t.seen.slice() } : null)), + known: [[], []], + }; +} + +// ── army bookkeeping ────────────────────────────────────────────────────────── +/** For seat's army: { rank: { total, lost, alive } }. */ +export function armyStatus(state, seat) { + const out = {}; + const counts = variantOf(state.variant).counts; + for (const k of Object.keys(counts)) out[k] = { total: counts[k], lost: 0, alive: counts[k] }; + for (const rank of state.captured[seat]) { if (out[rank]) { out[rank].lost++; out[rank].alive--; } } + return out; +} +export function aliveCount(state, seat) { + let n = 0; + for (let r = 0; r < GRID; r++) for (let c = 0; c < GRID; c++) if (state.board[r][c]?.owner === seat) n++; + return n; +} + +// ── notation & descriptions ─────────────────────────────────────────────────── +export function moveNotation(e) { + return `${squareName(e.fr, e.fc)}${e.attack ? '×' : '–'}${squareName(e.tr, e.tc)}`; +} +/** A sentence about a battle, from `viewer`'s side. showRanks=false keeps + * ranks out of it (classic reveal mode). */ +export function battleText(e, viewer, showRanks = true) { + if (!e.attack) return ''; + const youAttacked = e.seat === viewer; + const mine = youAttacked ? e.aRank : e.dRank, theirs = youAttacked ? e.dRank : e.aRank; + const won = e.result === 'both' ? null : (e.result === 'attacker') === youAttacked; + if (!showRanks) return won == null ? 'both destroyed' : won ? 'you won' : 'you lost'; + const m = rankName(mine), t = rankName(theirs); + if (theirs === FLAG && won) return 'Flag captured!'; + if (won == null) return `${m} and ${t} destroyed`; + if (theirs === BOMB && !won) return `${m} hit a Bomb`; + if (mine === BOMB && won) return `${t} hit your Bomb`; + return won ? `${m} beat ${t}` : `${m} lost to ${t}`; +} + +// ── replay ──────────────────────────────────────────────────────────────────── +/** States after each ply of a finished game, from its starting state. */ +export function replayStates(start, log) { + const out = [start]; + let s = start; + for (const e of log) { + const n = applyMove(s, e.fr, e.fc, e.tr, e.tc); + if (n === s) break; + out.push(n); s = n; + } + return out; +} + +export { buildArmy, countOf }; diff --git a/src/games/stratego/StrategoPieces.js b/src/games/stratego/StrategoPieces.js new file mode 100644 index 0000000..9c8f3b2 --- /dev/null +++ b/src/games/stratego/StrategoPieces.js @@ -0,0 +1,138 @@ +// StrategoPieces.js: one unit block as a Phaser container. The front shows +// the pencil-sketch unit art (stratego-pieces.png) on a pale card in the +// faction's metal block, with the rank badge in the corner; the back shows +// the faction crest. Hidden enemy blocks can carry public marks (has moved, +// known Scout) and the player's own guess tag. +// +// new PieceView(scene, { owner, rank }, { faceUp, depth, scale }) +// .setFaceUp(up, animate) flip with a squash +// .setTag(label|null) the player's guess chip (bottom-right) +// .setMarks({ moved, scout }) +// .setSelected(on) pulsing glow under the block +// .setGhost(on) translucent (being dragged / in replay) + +import * as Phaser from 'phaser'; +import { FLAG, BOMB, SPY, MARSHAL, pieceFrame, rankLabel, PLAYER_DARK, PLAYER_LIGHT } from './StrategoData.js'; +import { PIECE } from './StrategoLayout.js'; +import { DISPLAY_FONT, RES, HUE } from './StrategoArt.js'; + +const FACE_H = PIECE.face, EDGE = PIECE.edge, PW = PIECE.w; + +export class PieceView { + constructor(scene, piece, { faceUp = true, depth = 12, scale = 1, x = 0, y = 0 } = {}) { + this.scene = scene; + this.piece = { owner: piece.owner, rank: piece.rank, id: piece.id }; + this.faceUp = faceUp; + this.c = scene.add.container(x, y).setDepth(depth).setScale(scale); + this.baseScale = scale; + + this.glow = scene.add.image(0, 2, 'sg-glow').setDisplaySize(PW * 1.9, PW * 1.9) + .setTint(piece.owner === 0 ? 0xff7a5a : 0x7ab0ff).setAlpha(0).setBlendMode(Phaser.BlendModes.ADD); + this.shadow = scene.add.ellipse(2, FACE_H / 2 + 2, PW * 0.95, 14, 0x000000, 0.45); + this.block = scene.add.image(0, EDGE / 2, `sg-back-${piece.owner}`).setScale(1 / RES); + this.art = scene.add.image(0, 0, 'stratego-pieces', 0).setDisplaySize(56, 56); + this.badge = scene.add.graphics(); + this.badgeText = scene.add.text(-PW / 2 + 12, -FACE_H / 2 + 12, '', { + fontFamily: DISPLAY_FONT, fontSize: '15px', color: '#ffffff', stroke: '#000000', strokeThickness: 3, + }).setOrigin(0.5); + this.marks = scene.add.graphics(); + this.tagBg = scene.add.graphics(); + this.tagText = scene.add.text(PW / 2 - 13, FACE_H / 2 - 12, '', { + fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#1a1206', + }).setOrigin(0.5); + this.c.add([this.glow, this.shadow, this.block, this.art, this.badge, this.badgeText, this.marks, this.tagBg, this.tagText]); + this.tag = null; + this.markState = { moved: false, scout: false }; + this.paint(); + } + + get x() { return this.c.x; } + get y() { return this.c.y; } + setPosition(x, y) { this.c.setPosition(x, y); return this; } + setDepth(d) { this.c.setDepth(d); return this; } + + paint() { + const { owner, rank } = this.piece; + const up = this.faceUp && rank != null; + this.block.setTexture(up ? `sg-face-${owner}` : `sg-back-${owner}`); + const hasArt = up && this.scene.textures.exists('stratego-pieces'); + this.art.setVisible(hasArt); + if (hasArt) this.art.setFrame(pieceFrame(rank)); + this.badge.clear(); + this.badgeText.setVisible(up); + if (up) { + const special = rank === FLAG || rank === BOMB || rank === SPY; + this.badge.fillStyle(PLAYER_DARK[owner], 0.95).fillCircle(-PW / 2 + 12, -FACE_H / 2 + 12, 11.5); + this.badge.lineStyle(1.5, special ? HUE.amber : PLAYER_LIGHT[owner], 1).strokeCircle(-PW / 2 + 12, -FACE_H / 2 + 12, 11.5); + this.badgeText.setText(rankLabel(rank)).setFontSize(rank === MARSHAL ? 12 : 15); + if (!hasArt) { + // no sheet loaded: a big rank in the middle of the card + this.badgeText.setPosition(0, 0).setFontSize(30); + } else this.badgeText.setPosition(-PW / 2 + 12, -FACE_H / 2 + 12); + } + this.drawMarks(); + this.drawTag(); + } + + setFaceUp(up, animate = false) { + if (up === this.faceUp) return Promise.resolve(); + if (!animate) { this.faceUp = up; this.paint(); return Promise.resolve(); } + return new Promise((resolve) => { + const sx = this.c.scaleX; + this.scene.tweens.add({ + targets: this.c, scaleX: 0, duration: 110, ease: 'Sine.easeIn', + onComplete: () => { + this.faceUp = up; this.paint(); + this.scene.tweens.add({ targets: this.c, scaleX: sx, duration: 130, ease: 'Sine.easeOut', onComplete: resolve }); + }, + }); + }); + } + + setRank(rank) { this.piece.rank = rank; this.paint(); return this; } + + setTag(label) { this.tag = label || null; this.drawTag(); return this; } + drawTag() { + this.tagBg.clear(); + const show = !!this.tag && !(this.faceUp && this.piece.rank != null); + this.tagText.setVisible(show); + if (!show) return; + const wide = this.tag.length > 1; + const w = wide ? 28 : 22; + this.tagBg.fillStyle(HUE.amber, 1).fillRoundedRect(PW / 2 - 13 - w / 2 + 2, FACE_H / 2 - 23, w, 22, 6); + this.tagBg.lineStyle(1.5, 0x1a1206, 0.8).strokeRoundedRect(PW / 2 - 13 - w / 2 + 2, FACE_H / 2 - 23, w, 22, 6); + this.tagText.setText(this.tag).setFontSize(wide ? 12 : 14).setPosition(PW / 2 - 11, FACE_H / 2 - 12); + } + + setMarks(m) { this.markState = { moved: !!m?.moved, scout: !!m?.scout }; this.drawMarks(); return this; } + drawMarks() { + this.marks.clear(); + if (this.faceUp && this.piece.rank != null) return; + const { moved, scout } = this.markState; + const x = -PW / 2 + 11, y = FACE_H / 2 - 11; + if (scout) { + // known Scout: a double chevron + this.marks.lineStyle(3, HUE.cyan, 1); + for (const dx of [0, 7]) this.marks.beginPath().moveTo(x - 4 + dx, y - 6).lineTo(x + 2 + dx, y).lineTo(x - 4 + dx, y + 6).strokePath(); + } else if (moved) { + this.marks.fillStyle(0x000000, 0.5).fillCircle(x, y, 6.5); + this.marks.fillStyle(HUE.cyan, 1).fillCircle(x, y, 4.5); + } + } + + setSelected(on) { + this.scene.tweens.killTweensOf(this.glow); + if (on) { + this.glow.setAlpha(0.55); + this.scene.tweens.add({ targets: this.glow, alpha: { from: 0.35, to: 0.8 }, duration: 600, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); + this.c.setScale(this.baseScale * 1.06); + } else { + this.glow.setAlpha(0); + this.c.setScale(this.baseScale); + } + return this; + } + + setGhost(on) { this.c.setAlpha(on ? 0.45 : 1); return this; } + destroy() { this.scene.tweens.killTweensOf(this.glow); this.scene.tweens.killTweensOf(this.c); this.c.destroy(); } +} diff --git a/src/games/stratego/StrategoSetups.js b/src/games/stratego/StrategoSetups.js new file mode 100644 index 0000000..a3bdee6 --- /dev/null +++ b/src/games/stratego/StrategoSetups.js @@ -0,0 +1,159 @@ +// Fog of War: deployment formations. Pure (no Phaser); the saved-slot +// helpers touch localStorage only when it exists. +// +// A layout is a 40-char string, seat-relative: four lines front→back, ten +// columns from the owner's left. F flag, B bomb, S spy, 2–9, M marshal, +// '.' empty. The same strings serve both sides (StrategoLogic mirrors them +// onto the board), the player's "Formations" picker and the AI. +// +// randomize() keeps a formation's skeleton (where the flag and bombs sit) +// but mirrors it half the time and reshuffles interchangeable ranks within +// a line, so a preset never deploys exactly the same way twice. + +import { FLAG, BOMB, codeRank, rankCode } from './StrategoData.js'; +import { makeRng, shuffle, layoutValid, createInitialState, setupFill, readLayout } from './StrategoLogic.js'; + +const L = (...lines) => lines.join(''); + +export const PRESETS = { + classic: [ + { + id: 'fortress', name: 'Corner Fortress', + blurb: 'Flag in a back corner behind a wall of bombs. Solid and patient.', + layout: L('262B542762', '5M432982B5', 'B736S43876', 'FB325B432B'), + }, + { + id: 'decoy', name: 'Decoy Bunker', + blurb: 'A bomb cluster with no flag in it, and the real flag further along the back row.', + layout: L('2725283624', '6M5S273942', '3B6758B463', '2BB34BFB52'), + }, + { + id: 'ridge', name: 'Ridge Flag', + blurb: 'The flag sits in the third line on the right edge. A bluff that rewards nerve.', + layout: L('2436257432', '2M4726582B', 'BS396285BF', 'BB2435736B'), + }, + { + id: 'screen', name: 'Scout Screen', + blurb: 'Scouts across the front to spot the enemy early; flag deep in the right corner.', + layout: L('22B223B223', '5B472846B5', '786SM9673B', '34564523BF'), + }, + { + id: 'shoreline', name: 'Shoreline Wall', + blurb: 'Bombs block the centre lane between the asteroid fields; flag in the middle of the home row.', + layout: L('2265BB4722', '3S82B24653', '685MB97342', '237BFB4356'), + }, + { + id: 'barricade', name: 'Barricade', + blurb: 'Flag one square in from the left corner, with bombs on three sides and Miners ready behind them.', + layout: L('26B2752B42', '394B827635', '3B8S7M6542', 'BFB3425632'), + }, + ], + barrage: [ + { + id: 'b-corner', name: 'Corner Hold', + blurb: 'Flag in a back corner next to the bomb; Marshal in the middle.', + layout: L('..2....2..', '.....M....', '...9...S..', 'FB....3...'), + }, + { + id: 'b-center', name: 'Centre Post', + blurb: 'Flag in the middle of the home row with the bomb in front of it.', + layout: L('.2......2.', '...M..9...', '....B..S..', '..3.F.....'), + }, + { + id: 'b-bluff', name: 'Forward Bluff', + blurb: 'Flag in the second line; the bomb guards an empty back corner.', + layout: L('2...9.....', '.......3F.', '..M....S..', 'B......2..'), + }, + ], +}; + +export function presetsFor(variant) { return PRESETS[variant] ?? PRESETS.classic; } + +/** Mirror a layout left↔right. */ +export function mirror(layout) { + let out = ''; + for (let li = 0; li < 4; li++) out += layout.slice(li * 10, li * 10 + 10).split('').reverse().join(''); + return out; +} + +/** A playable variation of a formation: maybe mirrored, interchangeable ranks + * reshuffled within their lines. Flag and bomb squares never move. */ +export function randomize(layout, rng = Math.random) { + let arr = (rng() < 0.5 ? mirror(layout) : layout).split(''); + const groups = [['4', '5', '6', '7'], ['2', '3'], ['8', '9', 'M']]; + for (let li = 0; li < 4; li++) { + for (const g of groups) { + if (g[0] === '8' && rng() < 0.5) continue; // heavy hitters move less often + const idx = []; + for (let c = 0; c < 10; c++) if (g.includes(arr[li * 10 + c])) idx.push(li * 10 + c); + const vals = shuffle(idx.map((i) => arr[i]), rng); + idx.forEach((i, j) => { arr[i] = vals[j]; }); + } + } + // Now and then trade a scout into the second line for a mid rank. + if (rng() < 0.5) { + const a = [], b = []; + for (let c = 0; c < 10; c++) { if (arr[c] === '2') a.push(c); if ('456'.includes(arr[10 + c])) b.push(10 + c); } + if (a.length && b.length) { + const i = a[Math.floor(rng() * a.length)], j = b[Math.floor(rng() * b.length)]; + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + } + return arr.join(''); +} + +/** A layout from the heuristic auto-deployer. */ +export function heuristicLayout(variant, rng = Math.random) { + const s = setupFill(createInitialState({ variant }), 0, rng); + return readLayout(s, 0); +} + +/** Any random good deployment: usually a randomized preset, sometimes the + * heuristic. */ +export function randomLayout(variant, rng = Math.random) { + const list = presetsFor(variant); + if (rng() < 0.25) return heuristicLayout(variant, rng); + return randomize(list[Math.floor(rng() * list.length)].layout, rng); +} + +/** The AI's deployment. Weaker commanders lean on the plain heuristic (their + * flag tends to sit where you'd expect); stronger ones pick formations, + * bluffs included. */ +export function aiLayout(variant, skill = 3, seed = null) { + const rng = makeRng(seed ?? Math.floor(Math.random() * 1e9)); + const heurP = [0, 0.7, 0.5, 0.3, 0.15, 0.1][Math.max(1, Math.min(5, skill))]; + if (rng() < heurP) return heuristicLayout(variant, rng); + return randomize(presetsFor(variant)[Math.floor(rng() * presetsFor(variant).length)].layout, rng); +} + +// ── saved slots ─────────────────────────────────────────────────────────────── +const STORE_KEY = 'stratego.setups.v1'; +export const SLOT_COUNT = 3; + +function readStore() { + try { return JSON.parse(globalThis.localStorage?.getItem(STORE_KEY) || '{}') || {}; } catch (_) { return {}; } +} +export function loadSlots(variant) { + const st = readStore(); + const list = Array.isArray(st[variant]) ? st[variant] : []; + const out = []; + for (let i = 0; i < SLOT_COUNT; i++) { + const e = list[i]; + out.push(e && layoutValid(e.layout, variant) ? e : null); + } + return out; +} +export function saveSlot(variant, i, layout, name = null) { + if (!layoutValid(layout, variant)) return false; + const st = readStore(); + const list = Array.isArray(st[variant]) ? st[variant] : []; + list[i] = { layout, name: name ?? `Formation ${i + 1}`, savedAt: Date.now() }; + st[variant] = list; + try { globalThis.localStorage?.setItem(STORE_KEY, JSON.stringify(st)); return true; } catch (_) { return false; } +} + +// Small helpers for drawing previews. +export function layoutCells(layout) { + return layout.split('').map((ch) => codeRank(ch)); +} +export { FLAG, BOMB, rankCode }; diff --git a/src/games/stratego/StrategoSound.js b/src/games/stratego/StrategoSound.js new file mode 100644 index 0000000..f77e225 --- /dev/null +++ b/src/games/stratego/StrategoSound.js @@ -0,0 +1,207 @@ +// StrategoSound.js: Web Audio synths for the command deck. No audio files; +// silent without Web Audio or when the game is muted. The battle effects +// (launch, explosion, riser, reveal, woosh) come from src/ui/Sounds.js. +// +// deploy(scene) a unit locked into place during deployment +// pickup(scene) a unit lifted from the barracks / a square +// step(scene, ai) a quiet move: a soft servo glide +// select(scene) a unit selected +// deny(scene) not allowed +// ping(scene) a radar ping (a unit revealed / your turn) +// alarm(scene) the flag is threatened +// sting(scene, kind) 'win' / 'lose' / 'draw' +// Ambience ship hum, air handlers, distant console chirps + +function ctxOf(scene) { + const sm = scene?.sound; + if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null; + return sm.context; +} +const noiseCache = new WeakMap(); +function noise(ac) { + if (noiseCache.has(ac)) return noiseCache.get(ac); + const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; + noiseCache.set(ac, buf); + return buf; +} +function out(scene, ac, gain) { + const sm = scene.sound; + const node = sm.masterVolumeNode ?? sm.destination ?? null; + const g = ac.createGain(); + g.gain.value = node ? gain : gain * (sm.volume ?? 1); + g.connect(node ?? ac.destination); + return g; +} +function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.004 } = {}) { + const o = ac.createOscillator(); o.type = type; + o.frequency.setValueAtTime(f, t0); + if (glide !== 1) o.frequency.exponentialRampToValueAtTime(Math.max(20, f * glide), t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + attack); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03); +} +function hiss(ac, dest, t0, f, vol, d, q = 1.2, sweep = 1) { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.Q.value = q; + bp.frequency.setValueAtTime(f, t0); + if (sweep !== 1) bp.frequency.exponentialRampToValueAtTime(f * sweep, t0 + d); + const g = ac.createGain(); g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(vol, t0 + Math.min(0.03, d / 3)); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02); +} +const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } }; + +export function deploy(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.09), t = ac.currentTime + 0.003; + tone(ac, dest, t, 180, { a: 0.9, d: 0.09, glide: 0.6 }); + hiss(ac, dest, t, 2400, 0.6, 0.04, 2); + tone(ac, dest, t + 0.05, 1320, { type: 'triangle', a: 0.25, d: 0.08 }); + }); +} +export function pickup(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003; + tone(ac, dest, t, 420, { type: 'triangle', a: 0.5, d: 0.09, glide: 1.6 }); + hiss(ac, dest, t, 1800, 0.4, 0.08, 1.5, 1.8); + }); +} +export function step(scene, ai = false) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.045), t = ac.currentTime + 0.003; + hiss(ac, dest, t, ai ? 700 : 900, 0.7, 0.22, 1.4, 1.7); + tone(ac, dest, t, ai ? 140 : 170, { type: 'sawtooth', a: 0.12, d: 0.2, glide: 1.3 }); + tone(ac, dest, t + 0.2, 90, { a: 0.6, d: 0.06, glide: 0.7 }); + }); +} +export function select(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003; + tone(ac, dest, t, 880, { type: 'square', a: 0.18, d: 0.05 }); + tone(ac, dest, t + 0.045, 1320, { type: 'square', a: 0.14, d: 0.06 }); + }); +} +export function deny(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003; + tone(ac, dest, t, 220, { type: 'square', a: 0.35, d: 0.09 }); + tone(ac, dest, t + 0.1, 165, { type: 'square', a: 0.35, d: 0.12 }); + }); +} +export function ping(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003; + tone(ac, dest, t, 1568, { a: 0.6, d: 0.9 }); + tone(ac, dest, t, 3136, { a: 0.1, d: 0.3 }); + tone(ac, dest, t + 0.32, 1568, { a: 0.18, d: 0.6 }); + }); +} +export function alarm(scene) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003; + for (let i = 0; i < 2; i++) { + tone(ac, dest, t + i * 0.32, 660, { type: 'sawtooth', a: 0.25, d: 0.26, glide: 0.75 }); + } + }); +} +export function sting(scene, kind = 'win') { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.02; + const pad = (at, freqs, d) => freqs.forEach((f) => { + tone(ac, dest, t + at, f, { type: 'sawtooth', a: 0.07, d, attack: 0.12 }); + tone(ac, dest, t + at, f * 2, { type: 'sine', a: 0.1, d: d * 0.8, attack: 0.05 }); + }); + if (kind === 'win') { + pad(0, [196, 247, 294], 0.7); pad(0.45, [220, 277, 330], 0.7); pad(0.9, [262, 330, 392, 523], 2.4); + } else if (kind === 'lose') { + pad(0, [220, 262, 330], 0.9); pad(0.7, [175, 208, 262], 2.2); + } else { + pad(0, [196, 262, 294], 1.8); + } + }); +} + +export class Ambience { + constructor(scene) { this.scene = scene; this.on = false; this.timer = null; this.beds = []; } + + start() { + if (this.on) return; + this.on = true; + const ac = ctxOf(this.scene); + if (ac) { + safe(() => { + // reactor hum: two low sines beating slowly + const g = out(this.scene, ac, 0); + g.gain.setValueAtTime(0, ac.currentTime); + g.gain.linearRampToValueAtTime(0.018, ac.currentTime + 3); + const oscs = [55, 55.6, 110.3].map((f, i) => { + const o = ac.createOscillator(); o.type = 'sine'; o.frequency.value = f; + const og = ac.createGain(); og.gain.value = i === 2 ? 0.25 : 0.6; + o.connect(og); og.connect(g); o.start(); + return o; + }); + // air handlers: low band of noise, breathing + const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true; + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 420; + const ng = ac.createGain(); ng.gain.value = 0.5; + const lfo = ac.createOscillator(); lfo.frequency.value = 0.08; + const lg = ac.createGain(); lg.gain.value = 0.25; + lfo.connect(lg); lg.connect(ng.gain); + src.connect(lp); lp.connect(ng); ng.connect(g); + src.start(); lfo.start(); + this.beds.push({ nodes: [...oscs, src, lfo], g }); + }); + } + const event = () => { + this.timer = setTimeout(event, 6000 + Math.random() * 9000); + const a = ctxOf(this.scene); if (!a) return; + safe(() => { + const dest = out(this.scene, a, 0.012), t = a.currentTime + 0.02; + const r = Math.random(); + if (r < 0.45) { + // console chirps + for (let i = 0; i < 3 + Math.floor(Math.random() * 4); i++) { + tone(a, dest, t + i * 0.07, 1200 + Math.floor(Math.random() * 6) * 220, { type: 'square', a: 0.25, d: 0.04 }); + } + } else if (r < 0.75) { + // distant sonar + tone(a, dest, t, 740, { a: 0.6, d: 1.6 }); + tone(a, dest, t + 0.6, 740, { a: 0.15, d: 1.2 }); + } else { + // hull settling + tone(a, dest, t, 70, { type: 'triangle', a: 0.6, d: 0.6, glide: 0.8 }); + hiss(a, dest, t, 300, 0.5, 0.5, 0.8); + } + }); + }; + this.timer = setTimeout(event, 2500); + } + + stop() { + this.on = false; + clearTimeout(this.timer); this.timer = null; + for (const { nodes, g } of this.beds) { + safe(() => { + const ac = g.context; + g.gain.cancelScheduledValues(ac.currentTime); + g.gain.setValueAtTime(g.gain.value, ac.currentTime); + g.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6); + for (const n of nodes) n.stop(ac.currentTime + 0.7); + }); + } + this.beds = []; + } + + setOn(on) { if (on) this.start(); else this.stop(); } +} diff --git a/src/games/stratego/StrategoTalk.js b/src/games/stratego/StrategoTalk.js new file mode 100644 index 0000000..267ff5f --- /dev/null +++ b/src/games/stratego/StrategoTalk.js @@ -0,0 +1,69 @@ +// StrategoTalk.js: what the opposing commander says over the comm line, and +// the flight computer's short status lines. {unit} and {name} are filled in. + +const pick = (list) => (list && list.length ? list[Math.floor(Math.random() * list.length)] : null); +const fill = (s, ctx) => s.replace(/\{(\w+)\}/g, (_, k) => (ctx[k] ?? '')); + +const OPP = { + rookie: { + greet: ['Uh, hi! Is this channel open? Good luck out there!', 'First real command. Go easy on me?', 'Helix Dominion, reporting for… battle. Yes.'], + deploy: ['Okay, everybody in position. I think.', 'Deployment locked! Probably.'], + tookBig: ['Wait, I got your {unit}? Nice!', 'Ha! Your {unit} is down!'], + lostBig: ['Oh no, not my {unit}!', 'My {unit}! I needed that.', 'Ow. That was my {unit}.'], + bomb: ['Boom! Didn\'t see that coming, did you?', 'Surprise! Mines!'], + hitBomb: ['A bomb?! Who puts a bomb there?', 'Ugh, a mine field.'], + spy: ['The Spy got the Marshal! I read about that!'], + lostSpy: ['My Spy! I forgot about the Spy…'], + flagNear: ['Hey, stay away from back there!', 'Nothing to see back here. Nope.'], + win: ['I won? I actually won!', 'Flag secured! Is that how it works?'], + lose: ['Good game! You\'re really good at this.', 'Well, I learned a lot.'], + draw: ['A draw? I\'ll take it!'], + }, + regular: { + greet: ['Dominion command online. Let\'s see your deployment.', 'Channel open. May the better tactician win.', 'Fog\'s thick today. Good.'], + deploy: ['Formation locked. Your move, Vanguard.', 'All units in position.'], + tookBig: ['Your {unit} is gone. Noted.', 'One {unit} fewer to worry about.'], + lostBig: ['Costly. I\'ll remember that {unit}.', 'You\'ll pay for my {unit}.'], + bomb: ['Mined approach. Shouldn\'t have pushed there.', 'That lane was wired.'], + hitBomb: ['Bomb. So that\'s where you put them.', 'Mapped one of your mines. Thanks.'], + spy: ['Spy strike confirmed. Your Marshal is down.'], + lostSpy: ['My Spy… exposed and gone.'], + flagNear: ['You\'re getting warm. Too warm.', 'Interesting route you\'re taking.'], + win: ['Flag captured. Good engagement.', 'Mission complete. You fought well.'], + lose: ['Well commanded. I concede the sector.', 'Your flag hunt was sharp. Well played.'], + draw: ['Stalemate. Neither of us could break through.'], + }, + shark: { + greet: ['I\'ve already modelled your formation.', 'Every unit you move tells me something.', 'Let\'s not waste each other\'s time.'], + deploy: ['Deployed. Read it if you can.', 'My formation has no tells.'], + tookBig: ['Your {unit}. Exactly where I expected.', 'Predictable. {unit} eliminated.'], + lostBig: ['An acceptable trade for the information.', 'The {unit} was bait. Probably.'], + bomb: ['That square was never empty.', 'I placed that bomb for you personally.'], + hitBomb: ['One bomb mapped. Five to go.', 'A mine. I\'ve learned more than I lost.'], + spy: ['The Spy waited forty moves for that.'], + lostSpy: ['…You found the Spy. Impressive.'], + flagNear: ['Bold. Are you sure that\'s the flag?', 'You\'re digging in the wrong place.'], + win: ['As modelled.', 'Sector secured. Again?'], + lose: ['…Recalculating. Well played.', 'You read me. That doesn\'t happen often.'], + draw: ['A standoff. Acceptable.'], + }, +}; + +const COMPUTER = { + welcome: 'Command deck online. Deploy your army.', + deployHelp: 'Drag units from the barracks into your four rows, or pick a formation.', + battle: 'Battle stations. You have the first move.', + yourTurn: 'Your move, Commander.', + theirTurn: 'Enemy maneuvering…', + twoSquare: 'Two-square rule: that unit can\'t shuttle between the same squares a fourth time in a row.', + chase: 'Chase rule: you can\'t keep chasing that unit back into a position you\'ve already forced.', + noUndo: 'Battles can\'t be taken back.', + welcomeBack: 'Session restored. The fog is as you left it.', +}; + +export function tierOf(skill) { return skill <= 2 ? 'rookie' : skill === 3 ? 'regular' : 'shark'; } +export function opponentLine(kind, tier, ctx = {}) { + const s = pick(OPP[tier]?.[kind]); + return s ? fill(s, ctx) : null; +} +export function computerLine(kind) { return COMPUTER[kind] ?? ''; } diff --git a/src/games/stratego/StrategoWorker.js b/src/games/stratego/StrategoWorker.js new file mode 100644 index 0000000..9ae9cd6 --- /dev/null +++ b/src/games/stratego/StrategoWorker.js @@ -0,0 +1,11 @@ +// StrategoWorker.js: the module worker the opposing commander thinks in. +// See StrategoEngine.js for the message kinds. + +import { handle } from './StrategoEngine.js'; + +self.onmessage = (e) => { + const { id, kind, payload } = e.data ?? {}; + let res = null, err = null; + try { res = handle(kind, payload); } catch (ex) { err = String(ex?.message ?? ex); } + self.postMessage({ id, res, err }); +}; diff --git a/src/games/stratego/tutorial.md b/src/games/stratego/tutorial.md new file mode 100644 index 0000000..0c7ff3b --- /dev/null +++ b/src/games/stratego/tutorial.md @@ -0,0 +1,105 @@ +# Welcome to Fog of War + +*Flight Computer, Terran Vanguard command deck. Briefing for incoming commanders.* + +--- + +*The holo-table flickers on. Two armies glow at either end of the grid, and between them, two drifting asteroid fields.* + +Commander. The Helix Dominion has dug in across the sector. You can see where every one of their units stands, but not **what** any of them are. They can't see yours either. Whoever reads the fog better wins. + +## The Goal + +**Capture the enemy Flag.** Move any unit onto it and the battle is won. + +You also win if the enemy has **no unit left that can move**. If neither side can move, or nobody is captured for a very long time, the battle ends in a **stalemate**. + +## The Board + +Ten by ten. You deploy in the **bottom four rows**; the Dominion holds the top four. The two **asteroid fields** in the middle (2×2 each) can't be entered or crossed by anything, so the front has three lanes. + +Squares are named like a map: a letter for the column (**A–J**, left to right) and a number for the row (**1–10**, from your edge up). + +## Your Army (Classic rules: 40 units) + +| Unit | Rank | How many | Notes | +|---|---|---|---| +| Marshal | 10 | 1 | Beats everything, but dies to a Bomb, or to a Spy that attacks it | +| General | 9 | 1 | | +| Colonel | 8 | 2 | | +| Major | 7 | 3 | | +| Captain | 6 | 4 | | +| Lieutenant | 5 | 4 | | +| Sergeant | 4 | 4 | | +| Miner | 3 | 5 | **The only unit that can defuse a Bomb** | +| Scout | 2 | 8 | **Moves any distance in a straight line** | +| Spy | S | 1 | Kills the Marshal **only when the Spy attacks** | +| Bomb | B | 6 | Can't move. Destroys anything that attacks it, except a Miner | +| Flag | F | 1 | Can't move. Protect it | + +**Barrage** is a quick variant with only eight units each: Marshal, General, Miner, two Scouts, Spy, one Bomb and the Flag. You can deploy them anywhere in your four rows. + +## Deploying + +The **Barracks** on the left holds every unit you haven't placed yet. + +- **Drag** a unit from the Barracks onto one of your squares, or **click** it to pick it up and then click the squares. +- Drag a placed unit onto another square to **swap** them. Drag it back to the Barracks (or right-click it) to take it off the board. +- **Formations…** offers six built-in deployments (each one varies a little every time) and three slots to **save your own**. +- **Auto-fill** places whatever is left; **Clear** empties your rows. + +When all your rows are filled, press **Deploy**. You move first. + +## Moving + +- On your turn, move **one** unit **one square** forwards, backwards or sideways. Never diagonally. +- **Click** a unit, then click where it should go. You can also **drag** it there. +- **Scouts** run any number of empty squares in a straight line, and can attack at the end of the run. +- **Bombs and the Flag never move.** +- Units can't move into the asteroid fields or onto a friendly unit. + +## Battles + +Move onto an enemy unit to **attack** it. Both units are revealed: + +- The **higher rank wins**; the loser is destroyed. +- **Equal ranks** destroy each other. +- Attack a **Bomb** and you're destroyed, unless you're a **Miner**, who defuses it. +- A **Spy that attacks the Marshal** wins. Every other fight, the Spy loses, even when the Marshal attacks it. +- Attack the **Flag** and you win. + +**Battle scenes** can be Full, Quick or Off (they just play out on the square). Change this with the button on the right. **Click or press Space** during a battle to skip ahead. + +## After a Battle: Assisted or Classic + +Chosen on the briefing card: + +- **Assisted** (default): the winner stays **face-up** for the rest of the game. +- **Classic**: the winner turns **back face-down**, as on a real board. You have to *remember* what you saw. In this mode the Battle Log records who won, not the ranks. The Dominion has to remember too, and weaker commanders forget. + +## Fair-Play Rules + +- **Two-square rule:** a unit may not move back and forth between the same two squares more than **three times in a row**. For a Scout, any square along the line it just ran counts. +- **Chase rule:** if you keep chasing one enemy unit and it keeps running, you can't bring the two of you back into a position you've already been in during that chase. You have to break off. + +A blocked move shows a grey **✕**; click it to see why. + +## Tools on the Deck + +- **Enemy Forces** (left): how many of each enemy rank are still alive, and how many you can currently see. +- **Tags:** right-click (or press and hold) a hidden enemy unit to mark your guess: B, F, 7, ≥7 and so on. +- **Marks:** a cyan dot means that unit has moved, so it can't be a Bomb or the Flag. A double chevron means it ran more than one square, so it's a Scout. (You can switch these off in the menu.) +- **Hover** any unit for details. On hidden units, the **Intel estimate** gives the likeliest ranks based on everything seen so far. +- **Undo (Z)** takes back your last move. Battles can't be taken back. +- **Hint (H)** asks the tactical computer for a move. +- Your game is **saved** after every move. Leave any time and resume later. + +## Field Advice + +- Put your Flag somewhere the enemy won't expect, and guard it with Bombs. But a bomb wall is a signpost too. +- Use **Scouts** to find out what you're facing before you send in officers. +- Keep **Miners** alive for the endgame. Without them, bombed-in flags can't be reached. +- Know where your **Spy** is. Their Marshal can't be everywhere, and a Spy next to your General is a nasty surprise for it. +- A unit that hasn't moved might be a Bomb. **Bluff** with that: leave strong units still and let weak ones look busy. + +*End of briefing. Good hunting, Commander.* diff --git a/tools/verifyStratego.js b/tools/verifyStratego.js new file mode 100644 index 0000000..e05caec --- /dev/null +++ b/tools/verifyStratego.js @@ -0,0 +1,297 @@ +#!/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);