From ec09bb42f5e855d9464eee1237bcc8027bfa753e Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Wed, 25 Nov 2026 14:09:55 -0700 Subject: [PATCH] Rewrite Parchisi as "Monsoon Veranda" with full rules and AI - Rework game logic to integer progress model (nest/track/home-path/home), add opening throw, doubles backs, third-doubles penalty, blockades on the home path, capture/home bonuses, share-safe house rule, and stats/history - Replace AI with a skill 1-5 ladder: exact threat odds, lookahead at skill 5, noise/loose play at lower skills, plus hint/explain for the UI - Split the monolithic scene into focused modules (Board, Layout, Art, Pawns, Tray, Hud, Dialogs, EndScreen, Sound) and a thin orchestrating ParchisiGame - Add procedural "Monsoon Veranda" art (rosewood board, lacquered pawns, brass tray/cup, room/props), Web Audio synths, rain loop, dice-cup shake-to-roll, 3D dice throws, danger rings, opponent chat, and a podium/stats/race-chart end screen - Allow 2-4 players (minOpponents 1) with per-opponent skill selection, update tutorial copy, and add tools/verifyParchisi.js headless rule/AI/layout checks --- src/data/gamesRegistry.js | 2 +- src/games/backgammon/BackgammonGame.js | 2 +- src/games/parchisi/ParchisiAI.js | 445 ++++-- src/games/parchisi/ParchisiArt.js | 594 ++++++++ src/games/parchisi/ParchisiBoard.js | 125 ++ src/games/parchisi/ParchisiDialogs.js | 92 ++ src/games/parchisi/ParchisiEndScreen.js | 95 ++ src/games/parchisi/ParchisiGame.js | 1762 ++++++++++------------- src/games/parchisi/ParchisiHud.js | 179 +++ src/games/parchisi/ParchisiLayout.js | 96 ++ src/games/parchisi/ParchisiLogic.js | 700 +++++---- src/games/parchisi/ParchisiPawns.js | 148 ++ src/games/parchisi/ParchisiSound.js | 134 ++ src/games/parchisi/ParchisiTray.js | 226 +++ src/games/parchisi/tutorial.md | 61 +- src/scenes/OpponentSelectScene.js | 2 +- tools/verifyParchisi.js | 310 ++++ 17 files changed, 3478 insertions(+), 1495 deletions(-) create mode 100644 src/games/parchisi/ParchisiArt.js create mode 100644 src/games/parchisi/ParchisiBoard.js create mode 100644 src/games/parchisi/ParchisiDialogs.js create mode 100644 src/games/parchisi/ParchisiEndScreen.js create mode 100644 src/games/parchisi/ParchisiHud.js create mode 100644 src/games/parchisi/ParchisiLayout.js create mode 100644 src/games/parchisi/ParchisiPawns.js create mode 100644 src/games/parchisi/ParchisiSound.js create mode 100644 src/games/parchisi/ParchisiTray.js create mode 100644 tools/verifyParchisi.js diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index bae5bc2..81461c8 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -28,7 +28,7 @@ export function getGame(slug) { // Built-in catalog so the menu has something to show. registerGame({ slug: 'backgammon', name: 'Backgammon', category: 'tabletop', minPlayers: 2, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, hasTutorial: true, iconFrame: 0 }); -registerGame({ slug: 'parchisi', name: 'Parchisi', category: 'tabletop', minPlayers: 1, maxPlayers: 4, minOpponents: 3, maxOpponents: 3, hasTutorial: true, iconFrame: 1 }); +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 }); diff --git a/src/games/backgammon/BackgammonGame.js b/src/games/backgammon/BackgammonGame.js index 0bc02d4..8d2fd93 100644 --- a/src/games/backgammon/BackgammonGame.js +++ b/src/games/backgammon/BackgammonGame.js @@ -31,7 +31,7 @@ import { bell, slam, tap, Waves } from './BackgammonSound.js'; const SETTINGS_KEY = 'backgammon-settings'; const DEFAULT_SETTINGS = { pace: 'normal', confirm: true, autoRoll: false, autoForced: true, hints: true, pips: true, - cube: true, match: 0, jacoby: false, mirror: false, slam: true, waves: true, skipAI: false, + cube: true, match: 0, jacoby: false, mirror: false, slam: true, waves: false, skipAI: false, }; const D = { bg: 0, case: 5, labels: 6, glow: 9, checker: 10, marker: 13, dice: 22, cube: 24, diff --git a/src/games/parchisi/ParchisiAI.js b/src/games/parchisi/ParchisiAI.js index a0c554b..26908cc 100644 --- a/src/games/parchisi/ParchisiAI.js +++ b/src/games/parchisi/ParchisiAI.js @@ -1,167 +1,330 @@ +// ParchisiAI.js — skill 1–5 Parcheesi opponents. Phaser-free. +// +// A turn (one roll) is searched as every sequence of legal moves (capped +// branching), and the final positions are scored: +// +// simple progress, pawns home / out, own blockades, a flat "exposed" count +// full progress against the leading opponent, EXACT threat odds for each +// pawn (how many of the 36 rolls let some opponent land on it — +// direct, combined, doubles with backs, entry bops), blockades +// valued by the opponents trapped behind them, safe squares, and +// the shots we keep at their pawns +// +// Ladder +// 5 full + lookahead: the top candidates are replayed against all 21 rolls +// of the next player (who answers greedily) +// 4 full +// 3 simple +// 2 simple + noise +// 1 simple + heavy noise + loose plays + import { - COLORS, ENTRY, HOME_ENTRY, TRACK_LEN, - cloneState, getValidMoves, applyMove, - blockadeSet, pawnsHome, pawnsInNest, isSafeTrack, + NEST, HOME, HOME_PATH0, LAST_TRACK, ENTRY, onTrack, trackIdx, progressAt, isSafeTrack, + getValidMoves, applyMove, finishRoll, rollSpecificDice, pawnsInNest, pawnsHome, blockadeSquares, totalPipsRemaining, } from './ParchisiLogic.js'; -// Returns an ordered array of moves for the AI player to execute this turn. -// The caller should apply them one at a time (with animation), not all at once. -export function chooseMoves(state) { - if (state.phase !== 'move') return []; - const sequences = generateSequences(state, 0); - if (sequences.length === 0) return []; +const ROLLS = []; +for (let a = 1; a <= 6; a++) for (let b = a; b <= 6; b++) ROLLS.push({ a, b, w: a === b ? 1 : 2 }); - const player = state.currentPlayer; - let best = sequences[0]; - let bestScore = evaluateState(best.finalState, player); - for (let i = 1; i < sequences.length; i++) { - const sc = evaluateState(sequences[i].finalState, player); - if (sc > bestScore) { bestScore = sc; best = sequences[i]; } +export const TUNE = { + leadW: 0.45, avgW: 0.15, threat: 1, threatBase: 22, safe: 2.5, blockade: 3, trapped: 2.2, shots: 2.5, nest: -9, + homeBonus: 26, pathBonus: 9, +}; + +// ── threat odds ────────────────────────────────────────────────────────────── +function sumsFor(a, b, backs) { + if (a !== b) return [a, b, a + b]; + const vals = backs ? [a, a, 7 - a, 7 - a] : [a, a]; + const set = new Set(); + const n = vals.length; + for (let mask = 1; mask < 1 << n; mask++) { + let s = 0; + for (let i = 0; i < n; i++) if (mask & (1 << i)) s += vals[i]; + set.add(s); } - return best.moves; + return [...set]; } -const MAX_DEPTH = 8; // typical doubles-with-bonus turn = 4 base + 2 bonuses -const BRANCH_CAP = 24; // cap branches per node to keep search tractable - -function generateSequences(state, depth) { - if (depth > MAX_DEPTH || state.phase !== 'move' || state.movesLeft.length === 0) { - return [{ moves: [], finalState: state }]; +// Probability that player `c`, rolling next, can land on track square `sq`. +export function hitProb(s, c, sq, blocked = null) { + const entryBop = sq === ENTRY[c] && pawnsInNest(s, c) > 0; + if (isSafeTrack(sq) && !entryBop) return 0; + const k = progressAt(c, sq); + const dists = []; + if (k >= 0 && !isSafeTrack(sq)) { + const bl = blocked ?? new Set(blockadeSquares(s).map((b) => b.sq)); + for (const q of s.pawns[c]) { + if (!onTrack(q) || q >= k || k - q > 24) continue; + let ok = true; + for (let t = q + 1; t < k; t++) if (bl.has(trackIdx(c, t))) { ok = false; break; } + if (ok) dists.push(k - q); + } } - - const moves = getValidMoves(state); - if (moves.length === 0) { - // No legal move; apply a synthetic pass by clearing remaining dice. - const skipped = cloneState(state); - skipped.movesLeft = []; - return [{ moves: [], finalState: skipped }]; + if (!dists.length && !entryBop) return 0; + const backs = pawnsInNest(s, c) === 0; + let hits = 0; + for (const { a, b, w } of ROLLS) { + let hit = false; + if (entryBop && (a === 5 || b === 5 || (a !== b && a + b === 5))) hit = true; + if (!hit && dists.length) { + const sums = sumsFor(a, b, backs); + for (const d of dists) if (sums.includes(d)) { hit = true; break; } + } + if (hit) hits += w; } + return hits / 36; +} - // Prioritize promising moves first, cap branching. - const ranked = moves - .map((m) => ({ m, h: moveHeuristic(state, m) })) - .sort((a, b) => b.h - a.h) - .slice(0, BRANCH_CAP); +// P(the pawn of `color` at progress p is captured before `color` moves again), +// treating each opponent's next roll as independent. +export function threatOf(s, color, p, blocked = null) { + if (!onTrack(p)) return 0; + const sq = trackIdx(color, p); + if (s.pawns[color].filter((q) => onTrack(q) && trackIdx(color, q) === sq).length >= 2) return 0; + const bl = blocked ?? new Set(blockadeSquares(s).map((b) => b.sq)); + let survive = 1; + for (const c of s.players) if (c !== color) survive *= 1 - hitProb(s, c, sq, bl); + return 1 - survive; +} - const results = []; - const seen = new Set(); - const player = state.currentPlayer; +// For the danger overlay: [{ pawnIdx, risk, by: [colors] }] for `color`'s exposed pawns. +export function dangerReport(s, color) { + const bl = new Set(blockadeSquares(s).map((b) => b.sq)); + const out = []; + s.pawns[color].forEach((p, i) => { + if (!onTrack(p)) return; + const sq = trackIdx(color, p); + if (s.pawns[color].filter((q) => onTrack(q) && trackIdx(color, q) === sq).length >= 2) return; + let survive = 1; + const by = []; + for (const c of s.players) { + if (c === color) continue; + const h = hitProb(s, c, sq, bl); + if (h > 0) { by.push({ color: c, p: h }); survive *= 1 - h; } + } + if (by.length) out.push({ pawnIdx: i, risk: 1 - survive, by }); + }); + return out; +} - for (const { m } of ranked) { - const next = applyMove(state, m); - // If turn changed or game over, sequence ends. - if (next.currentPlayer !== player || next.phase !== 'move') { - const key = boardHash(next); - if (!seen.has(key)) { - seen.add(key); - results.push({ moves: [m], finalState: next }); +// ── evaluation ─────────────────────────────────────────────────────────────── +function progressValue(p) { + if (p === NEST) return TUNE.nest; + if (p === HOME) return HOME + TUNE.homeBonus; + if (p >= HOME_PATH0) return p + TUNE.pathBonus; + return p; +} + +export function evaluate(s, me, mode = 'full') { + if (s.winner) return s.winner === me ? 1e5 : -1e5; + const T = TUNE; + const totals = {}; + for (const c of s.players) totals[c] = s.pawns[c].reduce((a, p) => a + progressValue(p), 0); + const others = s.players.filter((c) => c !== me); + const lead = Math.max(...others.map((c) => totals[c])); + const avg = others.reduce((a, c) => a + totals[c], 0) / others.length; + let score = totals[me] - lead * T.leadW - avg * T.avgW; + + if (mode === 'simple') { + score += pawnsHome(s, me) * 25 + (4 - pawnsInNest(s, me)) * 5; + const bl = blockadeSquares(s); + score += bl.filter((b) => b.color === me).length * 14; + // exposed: alone, not safe, an enemy within 12 behind + for (const p of s.pawns[me]) { + if (!onTrack(p)) continue; + const sq = trackIdx(me, p); + if (isSafeTrack(sq)) continue; + if (s.pawns[me].filter((q) => onTrack(q) && trackIdx(me, q) === sq).length >= 2) continue; + let near = false; + for (const c of others) { + const k = progressAt(c, sq); + if (k < 0) continue; + if (s.pawns[c].some((q) => onTrack(q) && k - q >= 1 && k - q <= 12)) { near = true; break; } } - continue; + if (near) score -= 8; } - const subs = generateSequences(next, depth + 1); - for (const sub of subs) { - const key = boardHash(sub.finalState); - if (seen.has(key)) continue; - seen.add(key); - results.push({ moves: [m, ...sub.moves], finalState: sub.finalState }); + return score; + } + + const blockList = blockadeSquares(s); + const bl = new Set(blockList.map((b) => b.sq)); + for (const p of s.pawns[me]) { + if (!onTrack(p)) continue; + const sq = trackIdx(me, p); + if (isSafeTrack(sq)) score += T.safe; + const t = threatOf(s, me, p, bl); + if (t > 0) score -= t * T.threat * (p + T.threatBase - T.nest); + } + // own blockades, worth more with opponents stuck behind them + for (const b of blockList) { + if (b.color !== me) continue; + let trapped = 0; + for (const c of others) { + const k = progressAt(c, b.sq); + if (k < 0) continue; + trapped += s.pawns[c].filter((q) => onTrack(q) && k - q >= 1 && k - q <= 12).length; + } + score += T.blockade + T.trapped * trapped; + } + // shots we keep at lone opponent pawns (they move first, so worth a little) + for (const c of others) { + for (const q of s.pawns[c]) { + if (!onTrack(q)) continue; + const sq = trackIdx(c, q); + if (s.pawns[c].filter((x) => onTrack(x) && trackIdx(c, x) === sq).length >= 2) continue; + const h = hitProb(s, me, sq, bl); + if (h) score += h * T.shots * (1 + q / 32); } } - - return results.length > 0 ? results : [{ moves: [], finalState: state }]; -} - -function moveHeuristic(state, m) { - let h = 0; - if (m.hit) h += 100; - if (m.to.loc === 'home') h += 70; - if (m.to.home !== undefined) h += 20; - if (m.from.loc === 'nest') h += 15; - // Larger dice first slightly preferred to flush out 6s - h += (m.dieUsed ?? 0) * 0.5; - return h; -} - -function boardHash(state) { - const parts = []; - for (const c of COLORS) { - const sorted = [...state.pawns[c]].map((p) => { - if (p.loc === 'nest') return 'N'; - if (p.loc === 'home') return 'H'; - if (p.home !== undefined) return `h${p.home}`; - return `t${p.track}`; - }).sort(); - parts.push(`${c}:${sorted.join(',')}`); - } - parts.push(`m:${[...state.movesLeft].sort().join(',')}`); - return parts.join('|'); -} - -// ─── Evaluation ─────────────────────────────────────────────────────────── - -function evaluateState(state, player) { - let score = 0; - const opps = COLORS.filter((c) => c !== player); - - // Pip progress - const ownPips = totalPipsRemaining(state, player); - score -= ownPips * 1.0; - for (const o of opps) score += totalPipsRemaining(state, o) * 0.25; - - // Pawns home - score += pawnsHome(state, player) * 50; - for (const o of opps) score -= pawnsHome(state, o) * 25; - - // Pawns out of nest (mobility) - for (const c of COLORS) { - const out = 4 - pawnsInNest(state, c); - if (c === player) score += out * 5; - else score -= out * 2; - } - - // Own blockades — strong positional value - const myBlockades = countOwnBlockades(state, player); - score += myBlockades * 18; - - // Blot exposure: own single pawns at risk from opponents behind them - score -= blotExposure(state, player) * 8; - return score; } -function countOwnBlockades(state, player) { - const bset = blockadeSet(state); - let count = 0; - for (const idx of bset) { - const own = state.pawns[player].some((p) => p.track === idx); - if (own) count++; - } - return count; +// ── sequence search ────────────────────────────────────────────────────────── +const MAX_DEPTH = 8; +const BRANCH_CAP = 18; + +function keyOf(s) { + return s.players.map((c) => s.pawns[c].slice().sort((a, b) => a - b).join(',')).join('|') + '#' + s.movesLeft.slice().sort().join(','); } -// Count of own pawns that sit alone on a non-safe square within 12 squares -// in front of any opponent pawn (so an opponent could land on them). -function blotExposure(state, player) { - let expo = 0; - for (let i = 0; i < 4; i++) { - const p = state.pawns[player][i]; - if (p.track === undefined) continue; - if (isSafeTrack(p.track)) continue; - // Is there an own partner on the same square? then not a blot - const own = state.pawns[player].filter((q) => q.track === p.track).length; - if (own >= 2) continue; - // Check opponent threats - for (const opp of COLORS) { - if (opp === player) continue; - for (const q of state.pawns[opp]) { - if (q.track === undefined) continue; - const dist = (p.track - q.track + TRACK_LEN) % TRACK_LEN; - if (dist >= 1 && dist <= 12) { expo++; break; } - } +function quick(s, m) { + let h = 0; + if (m.hit) h += 100; + if (m.to === HOME) h += 70; + if (m.to >= HOME_PATH0) h += 20; + if (m.from === NEST) h += 15; + return h + m.dieUsed * 0.5; +} + +// Past the node budget, finish a line greedily (best quick-heuristic move). +function completeGreedy(state) { + let st = state; + const moves = []; + for (let k = 0; k < 10 && st.phase === 'move'; k++) { + const ms = getValidMoves(st); + if (!ms.length) break; + let best = ms[0], bh = -Infinity; + for (const m of ms) { const h = quick(st, m); if (h > bh) { bh = h; best = m; } } + moves.push(best); + st = applyMove(st, best); + } + return { moves, final: st }; +} + +export function generateSequences(state, depth = 0, seen = new Set(), ctx = { nodes: 0, budget: 700 }) { + const moves = state.phase === 'move' ? getValidMoves(state) : []; + if (!moves.length || depth > MAX_DEPTH) { + const k = keyOf(state); + if (seen.has(k)) return []; + seen.add(k); + return [{ moves: [], final: state }]; + } + if (++ctx.nodes > ctx.budget) { + const g = completeGreedy(state); + const k = keyOf(g.final); + if (seen.has(k)) return []; + seen.add(k); + return [g]; + } + const cap = depth >= 2 ? 6 : BRANCH_CAP; + const ranked = moves.map((m) => ({ m, h: quick(state, m) })).sort((a, b) => b.h - a.h).slice(0, cap); + const out = []; + for (const { m } of ranked) { + for (const sub of generateSequences(applyMove(state, m), depth + 1, seen, ctx)) out.push({ moves: [m, ...sub.moves], final: sub.final }); + } + return out; +} + +// ── lookahead (skill 5) ────────────────────────────────────────────────────── +function greedyTurn(s) { + let st = s; + for (let k = 0; k < 8 && st.phase === 'move'; k++) { + const ms = getValidMoves(st); + if (!ms.length) break; + const c = st.currentPlayer; + let best = null, bv = -Infinity; + for (const m of ms) { + const v = evaluate(applyMove(st, m), c, 'simple') + (m.hit ? 30 : 0); + if (v > bv) { bv = v; best = m; } } + st = applyMove(st, best); } - return expo; + return st; } -// Re-export for tests. -export { evaluateState }; +function lookahead(final, me) { + const after = finishRoll(final); + if (after.phase !== 'roll' || after.currentPlayer === me) return evaluate(final, me, 'full'); + let sum = 0; + for (const { a, b, w } of ROLLS) { + const r = rollSpecificDice(after, a, b); + const end = r.phase === 'move' ? greedyTurn(r) : r; + sum += w * evaluate(end, me, 'full'); + } + return sum / 36; +} + +// ── choose ─────────────────────────────────────────────────────────────────── +export const SKILL = { + 1: { mode: 'simple', noise: 26, loose: 0.3 }, + 2: { mode: 'simple', noise: 10, loose: 0.05 }, + 3: { mode: 'simple', noise: 0, loose: 0 }, + 4: { mode: 'full', noise: 5, loose: 0.03 }, + 5: { mode: 'full', noise: 0, loose: 0 }, +}; + +function gauss(rng) { + const u = Math.max(1e-9, rng()), v = rng(); + return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); +} + +/** Moves to play this roll, in order. */ +export function chooseMoves(state, skill = 3, rng = Math.random) { + if (state.phase !== 'move') return []; + const me = state.currentPlayer; + const seqs = generateSequences(state); + if (seqs.length <= 1) return seqs[0]?.moves ?? []; + const prof = SKILL[Math.max(1, Math.min(5, Math.round(skill)))]; + const scored = seqs.map((q) => ({ q, v: evaluate(q.final, me, prof.mode) + (prof.noise ? gauss(rng) * prof.noise : 0) })); + scored.sort((a, b) => b.v - a.v); + let pick = scored[0]; + if (prof.loose && rng() < prof.loose) pick = scored[Math.floor(rng() * Math.max(1, Math.ceil(scored.length / 2)))]; + if (prof.look) { + let best = null; + for (const x of scored.slice(0, prof.look)) { + const v = lookahead(x.q.final, me); + if (!best || v > best.v2) best = { ...x, v2: v }; + } + pick = best; + } + return pick.q.moves; +} + +// One-line reason for a suggested sequence (the Hint button). +export function explain(state, moves) { + const me = state.currentPlayer; + const bits = []; + const caps = moves.filter((m) => m.hit).length; + if (caps) bits.push(caps > 1 ? `captures ${caps} pawns` : 'captures a pawn'); + const homes = moves.filter((m) => m.to === HOME).length; + if (homes) bits.push(homes > 1 ? `brings ${homes} pawns home` : 'brings a pawn home'); + const enters = moves.filter((m) => m.from === NEST).length; + if (enters) bits.push(enters > 1 ? `enters ${enters} pawns` : 'enters a pawn'); + let s = state; + for (const m of moves) s = applyMove(s, m); + const before = blockadeSquares(state).filter((b) => b.color === me).length; + const after = blockadeSquares(s).filter((b) => b.color === me).length; + if (after > before) bits.push('builds a blockade'); + const risk = dangerReport(s, me).reduce((a, d) => Math.max(a, d.risk), 0); + bits.push(risk < 0.01 ? 'leaves nothing exposed' : `worst exposure ${Math.round(risk * 100)}%`); + const t = bits.join(' · '); + return t.charAt(0).toUpperCase() + t.slice(1); +} + +export function hint(state) { + const moves = chooseMoves(state, 5, () => 0.5); + return { moves, reason: moves.length ? explain(state, moves) : 'No legal move' }; +} + +export { totalPipsRemaining }; diff --git a/src/games/parchisi/ParchisiArt.js b/src/games/parchisi/ParchisiArt.js new file mode 100644 index 0000000..d559be9 --- /dev/null +++ b/src/games/parchisi/ParchisiArt.js @@ -0,0 +1,594 @@ +// ParchisiArt.js — baked canvas textures for the "Monsoon Veranda". All +// procedural: no image files. +// +// pc-room oiled teak table under grey monsoon light, chai on a brass +// saucer, a marigold garland, scattered petals +// pc-vignette the light + vignette alone (over a chosen playfield) +// pc-props the props alone (over a chosen playfield) +// pc-board carved rosewood board: bone-inlay track, brass safety +// lotuses, lacquered entries / home paths / nests with +// block-print borders and brass bowls, the four HOME +// triangles round a carved lotus medallion +// pc-pawn- turned "beehive" pawns in coloured lacquer +// pc-pawn-shadow, pc-glow, pc-ring +// pc-petal- a lotus petal (blooms when a pawn comes home) +// pc-chip / pc-chip-gold move tokens (dice values / bonuses) +// pc-tray brass dice tray with a red felt well +// pc-cup an engraved brass dice cup +// pc-plate a carved sheesham seat plaque +// pc-card block-printed cotton card (status / talk / chips) +// pc-jali jali-lattice light drifting over the table +// pc-coin, pc-spark, pc-steam + +import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js'; +import { + CELL, GRID, BOARD, ORIGIN_X, ORIGIN_Y, PAWN_R, trackXY, homeXY, NEST_RECT, nestCenter, BOWL_R, homeTriangle, cellWorld, +} from './ParchisiBoard.js'; +import { ENTRY, isSafeTrack, COLORS } from './ParchisiLogic.js'; +import { + W, H, BOARD_RECT, PLATES, STATUS, TRAY, TRAY_WALL, CHAI, GARLAND, CUP, +} from './ParchisiLayout.js'; + +export const DISPLAY_FONT = 'Righteous, Georgia, serif'; +export const SERIF = 'Georgia, "Times New Roman", serif'; +export const HAND_FONT = 'YummyCupcakes, "Comic Sans MS", cursive'; +export const PRINT_FONT = '"Julius Sans One", Georgia, serif'; +export const BOARD_PAD = 30; + +export const LACQUER = { + red: { base: '#b8322a', light: '#e2614f', dark: '#6e140f', hex: 0xb8322a, ring: 0xffa08a, ink: '#9c2a22' }, + blue: { base: '#2a5d9f', light: '#5c8fd0', dark: '#112d55', hex: 0x2a5d9f, ring: 0x9cc3f2, ink: '#244f8a' }, + yellow: { base: '#dc9f1e', light: '#f6cb5a', dark: '#7a5208', hex: 0xdc9f1e, ring: 0xffe08a, ink: '#9a6a08' }, + green: { base: '#2f7d4a', light: '#5fb37a', dark: '#123f22', hex: 0x2f7d4a, ring: 0xa4e2b6, ink: '#26683c' }, +}; + +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 grain(ctx, rnd, x, y, w, h, { tone = 'rgba(30,12,4,0.28)', lines = 16, wave = 4, vertical = false } = {}) { + ctx.save(); + ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); + ctx.strokeStyle = tone; + const L = vertical ? h : w, S = vertical ? w : h; + for (let i = 0; i < lines; i++) { + const o = rnd() * S, amp = wave * (0.4 + rnd()), f = 0.004 + rnd() * 0.012, ph = rnd() * 6; + ctx.lineWidth = 0.6 + rnd() * 1.6; + ctx.beginPath(); + for (let t = 0; t <= L; t += 6) { + const d = o + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.1 + ph) * amp * 0.3; + const px = vertical ? x + d : x + t, py = vertical ? y + t : y + d; + if (t === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.stroke(); + } + ctx.restore(); +} + +function dropShadow(ctx, fn, { blur = 24, dx = 8, dy = 14, alpha = 0.55 } = {}) { + ctx.save(); + ctx.shadowColor = `rgba(0,0,0,${alpha})`; + ctx.shadowBlur = blur; ctx.shadowOffsetX = dx; ctx.shadowOffsetY = dy; + fn(); + ctx.restore(); +} + +function brassGrad(ctx, x0, y0, x1, y1) { + const g = ctx.createLinearGradient(x0, y0, x1, y1); + g.addColorStop(0, '#f6dc8c'); g.addColorStop(0.45, '#c9962e'); g.addColorStop(0.7, '#e8c46a'); g.addColorStop(1, '#8a6418'); + return g; +} + +// Rosewood: deep red-brown with dark streaks. +function rosewood(ctx, rnd, x, y, w, h, vertical = false) { + const g = ctx.createLinearGradient(x, y, x + (vertical ? w : 0), y + (vertical ? 0 : h)); + g.addColorStop(0, '#5a2414'); g.addColorStop(0.5, '#6e2e1a'); g.addColorStop(1, '#4a1c0e'); + ctx.fillStyle = g; ctx.fillRect(x, y, w, h); + grain(ctx, rnd, x, y, w, h, { tone: 'rgba(20,6,2,0.45)', lines: Math.max(6, (vertical ? w : h) / 4), wave: 5, vertical }); + grain(ctx, rnd, x, y, w, h, { tone: 'rgba(160,80,40,0.18)', lines: Math.max(4, (vertical ? w : h) / 8), wave: 3, vertical }); + ctx.fillStyle = noisePattern(ctx, 64, 20); ctx.fillRect(x, y, w, h); +} + +// ── room ───────────────────────────────────────────────────────────────────── +function teakTable(ctx, rnd) { + const plankW = 160; + const tones = ['#5d3a1e', '#53331a', '#664222', '#5a381d']; + for (let x = 0, i = 0; x < W; x += plankW, i++) { + ctx.fillStyle = tones[i % tones.length]; + ctx.fillRect(x, 0, plankW, H); + grain(ctx, rnd, x, 0, plankW, H, { vertical: true, lines: 22, tone: 'rgba(20,8,2,0.32)', wave: 5 }); + ctx.fillStyle = 'rgba(10,4,0,0.6)'; ctx.fillRect(x + plankW - 2, 0, 2, H); + ctx.fillStyle = 'rgba(255,220,170,0.06)'; ctx.fillRect(x, 0, 1.5, H); + } + // an oiled sheen + const sh = ctx.createLinearGradient(0, 0, W, H); + sh.addColorStop(0, 'rgba(255,230,190,0.07)'); sh.addColorStop(0.5, 'rgba(255,230,190,0)'); sh.addColorStop(1, 'rgba(255,230,190,0.05)'); + ctx.fillStyle = sh; ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 96, 22); ctx.fillRect(0, 0, W, H); +} + +function monsoonLight(ctx) { + // cool grey-green daylight from the open veranda, warm lamp in the middle + const g = ctx.createLinearGradient(0, 0, W, 0); + g.addColorStop(0, 'rgba(120,150,150,0.16)'); g.addColorStop(0.35, 'rgba(0,0,0,0)'); g.addColorStop(1, 'rgba(110,140,150,0.12)'); + ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); + const lamp = ctx.createRadialGradient(W / 2, H / 2, 80, W / 2, H / 2, 760); + lamp.addColorStop(0, 'rgba(255,200,120,0.14)'); lamp.addColorStop(1, 'rgba(255,200,120,0)'); + ctx.fillStyle = lamp; ctx.fillRect(0, 0, W, H); + const v = ctx.createRadialGradient(W / 2, H / 2, H * 0.45, W / 2, H / 2, H * 1.05); + v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(6,10,12,0.62)'); + ctx.fillStyle = v; ctx.fillRect(0, 0, W, H); +} + +function chai(ctx, r) { + const cx = r.x + r.w / 2, cy = r.y + r.h / 2 + 6; + // brass saucer + dropShadow(ctx, () => { ctx.fillStyle = brassGrad(ctx, cx - 60, cy - 50, cx + 60, cy + 50); ctx.beginPath(); ctx.ellipse(cx, cy, 64, 50, 0, 0, Math.PI * 2); ctx.fill(); }, { blur: 14, dx: 6, dy: 8, alpha: 0.5 }); + ctx.strokeStyle = 'rgba(90,60,10,0.6)'; ctx.lineWidth = 1.5; + for (const k of [0.92, 0.78]) { ctx.beginPath(); ctx.ellipse(cx, cy, 64 * k, 50 * k, 0, 0, Math.PI * 2); ctx.stroke(); } + for (let i = 0; i < 16; i++) { + const a = (i / 16) * Math.PI * 2; + ctx.fillStyle = 'rgba(90,60,10,0.45)'; + ctx.beginPath(); ctx.arc(cx + Math.cos(a) * 56, cy + Math.sin(a) * 43, 1.6, 0, Math.PI * 2); ctx.fill(); + } + // a clay kulhad of chai + ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.beginPath(); ctx.ellipse(cx + 6, cy + 4, 30, 24, 0, 0, Math.PI * 2); ctx.fill(); + const clay = ctx.createRadialGradient(cx - 8, cy - 8, 4, cx, cy, 32); + clay.addColorStop(0, '#d2805a'); clay.addColorStop(1, '#8e4426'); + ctx.fillStyle = clay; ctx.beginPath(); ctx.ellipse(cx, cy, 30, 25, 0, 0, Math.PI * 2); ctx.fill(); + const tea = ctx.createRadialGradient(cx - 4, cy - 4, 2, cx, cy, 23); + tea.addColorStop(0, '#e9c79a'); tea.addColorStop(1, '#b8875a'); + ctx.fillStyle = tea; ctx.beginPath(); ctx.ellipse(cx, cy, 23, 19, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(255,240,220,0.5)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.ellipse(cx, cy, 16, 12, 0.3, Math.PI * 1.1, Math.PI * 1.6); ctx.stroke(); + // a cardamom pod and two cloves + ctx.fillStyle = '#9aa85a'; ctx.beginPath(); ctx.ellipse(cx + 46, cy + 18, 7, 4, 0.6, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#4a2812'; + for (const [dx, dy] of [[-44, 20], [-50, 8]]) { ctx.fillRect(cx + dx, cy + dy, 7, 2); ctx.beginPath(); ctx.arc(cx + dx + 8, cy + dy + 1, 2.5, 0, Math.PI * 2); ctx.fill(); } +} + +function marigold(ctx, x, y, r, rnd) { + for (let k = 0; k < 3; k++) { + const rr2 = r * (1 - k * 0.28); + const n = 14 - k * 3; + for (let i = 0; i < n; i++) { + const a = (i / n) * Math.PI * 2 + rnd() * 0.3; + ctx.fillStyle = k === 0 ? '#e07a10' : k === 1 ? '#f29a1c' : '#ffc23a'; + ctx.beginPath(); ctx.ellipse(x + Math.cos(a) * rr2 * 0.55, y + Math.sin(a) * rr2 * 0.55, rr2 * 0.42, rr2 * 0.26, a, 0, Math.PI * 2); ctx.fill(); + } + } + ctx.fillStyle = '#c45a08'; ctx.beginPath(); ctx.arc(x, y, r * 0.18, 0, Math.PI * 2); ctx.fill(); +} + +function garland(ctx, rnd, r) { + const n = Math.floor(r.w / 21); + ctx.strokeStyle = 'rgba(40,60,20,0.8)'; ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(r.x, r.y + r.h / 2); ctx.lineTo(r.x + r.w, r.y + r.h / 2); ctx.stroke(); + for (let i = 0; i < n; i++) { + const x = r.x + 10 + i * 21, y = r.y + r.h / 2 + Math.sin(i * 0.7) * 2; + ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.beginPath(); ctx.arc(x + 2, y + 3, 10, 0, Math.PI * 2); ctx.fill(); + marigold(ctx, x, y, 11, rnd); + if (i % 5 === 2) { ctx.fillStyle = '#3c7a2a'; ctx.beginPath(); ctx.ellipse(x + 10, y - 9, 7, 3, -0.6, 0, Math.PI * 2); ctx.fill(); } + } +} + +function petals(ctx, rnd, n) { + for (let i = 0; i < n; i++) { + const x = rnd() * W, y = rnd() * H; + if (x > BOARD_RECT.x - 20 && x < BOARD_RECT.x + BOARD_RECT.w + 20) continue; + ctx.save(); ctx.translate(x, y); ctx.rotate(rnd() * 6); + ctx.fillStyle = rnd() < 0.5 ? 'rgba(240,140,20,0.9)' : 'rgba(255,190,50,0.9)'; + ctx.beginPath(); ctx.ellipse(0, 0, 6, 3.5, 0, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + } +} + +function bakeRoom(scene) { + const rnd = seeded(31); + const c = canvas(W, H), ctx = c.getContext('2d'); + teakTable(ctx, rnd); + petals(ctx, seeded(8), 70); + chai(ctx, CHAI); + garland(ctx, seeded(4), GARLAND); + monsoonLight(ctx); + addCanvas(scene, 'pc-room', c); + + const v = canvas(W, H), vx = v.getContext('2d'); + monsoonLight(vx); + addCanvas(scene, 'pc-vignette', v); + const p = canvas(W, H), px = p.getContext('2d'); + petals(px, seeded(8), 70); + chai(px, CHAI); + garland(px, seeded(4), GARLAND); + addCanvas(scene, 'pc-props', p); +} + +// ── board ──────────────────────────────────────────────────────────────────── +function lotusMotif(ctx, cx, cy, r, fill, line) { + for (let k = 0; k < 8; k++) { + const a = (k / 8) * Math.PI * 2 - Math.PI / 2; + ctx.save(); ctx.translate(cx, cy); ctx.rotate(a); + ctx.fillStyle = fill; + ctx.beginPath(); ctx.moveTo(0, 0); ctx.quadraticCurveTo(r * 0.45, -r * 0.35, r, 0); ctx.quadraticCurveTo(r * 0.45, r * 0.35, 0, 0); ctx.fill(); + if (line) { ctx.strokeStyle = line; ctx.lineWidth = 1; ctx.stroke(); } + ctx.restore(); + } + ctx.fillStyle = line ?? 'rgba(0,0,0,0.3)'; + ctx.beginPath(); ctx.arc(cx, cy, r * 0.2, 0, Math.PI * 2); ctx.fill(); +} + +function boneTile(ctx, x, y, s, rnd) { + const g = ctx.createLinearGradient(x, y, x + s, y + s); + g.addColorStop(0, '#f6ecd4'); g.addColorStop(1, '#e2d2ad'); + ctx.fillStyle = g; ctx.fillRect(x, y, s, s); + ctx.strokeStyle = 'rgba(140,110,60,0.18)'; ctx.lineWidth = 0.8; + for (let k = 0; k < 3; k++) { const yy = y + rnd() * s; ctx.beginPath(); ctx.moveTo(x, yy); ctx.lineTo(x + s, yy + (rnd() - 0.5) * 4); ctx.stroke(); } + ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1; ctx.strokeRect(x + 1.5, y + 1.5, s - 3, s - 3); +} + +function lacquerTile(ctx, x, y, s, col) { + const g = ctx.createLinearGradient(x, y, x + s, y + s); + g.addColorStop(0, col.light); g.addColorStop(0.5, col.base); g.addColorStop(1, col.dark); + ctx.fillStyle = g; ctx.fillRect(x, y, s, s); + ctx.fillStyle = 'rgba(255,255,255,0.16)'; ctx.fillRect(x + 3, y + 3, s - 6, 4); +} + +function blockPrintBorder(ctx, x, y, w, h, col) { + ctx.save(); + ctx.strokeStyle = 'rgba(255,240,210,0.75)'; ctx.lineWidth = 2; + ctx.strokeRect(x + 10, y + 10, w - 20, h - 20); + ctx.strokeRect(x + 22, y + 22, w - 44, h - 44); + // a row of tiny buti flowers between the lines + const step = 18; + ctx.fillStyle = 'rgba(255,240,210,0.8)'; + const dot = (px, py) => { + for (let k = 0; k < 4; k++) { const a = k * Math.PI / 2; ctx.beginPath(); ctx.arc(px + Math.cos(a) * 3, py + Math.sin(a) * 3, 1.8, 0, Math.PI * 2); ctx.fill(); } + }; + for (let px = x + 24; px < x + w - 20; px += step) { dot(px, y + 16); dot(px, y + h - 16); } + for (let py = y + 24; py < y + h - 20; py += step) { dot(x + 16, py); dot(x + w - 16, py); } + // paisleys in the corners + for (const [cx, cy, a] of [[x + 50, y + 50, 0.8], [x + w - 50, y + 50, 2.3], [x + 50, y + h - 50, -0.8], [x + w - 50, y + h - 50, -2.3]]) { + ctx.save(); ctx.translate(cx, cy); ctx.rotate(a); + ctx.fillStyle = 'rgba(255,240,210,0.55)'; + ctx.beginPath(); ctx.arc(0, 0, 11, 0, Math.PI * 2); ctx.fill(); + ctx.beginPath(); ctx.moveTo(-11, 0); ctx.quadraticCurveTo(-6, -24, 12, -26); ctx.quadraticCurveTo(4, -14, 11, 0); ctx.fill(); + ctx.fillStyle = col.dark; ctx.beginPath(); ctx.arc(0, 0, 5, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + } + ctx.restore(); +} + +function brassBowl(ctx, cx, cy, r) { + dropShadow(ctx, () => { ctx.fillStyle = brassGrad(ctx, cx - r, cy - r, cx + r, cy + r); ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill(); }, { blur: 16, dx: 4, dy: 8, alpha: 0.55 }); + // inner well + const inner = ctx.createRadialGradient(cx - r * 0.25, cy - r * 0.3, r * 0.1, cx, cy, r * 0.86); + inner.addColorStop(0, '#f0cf78'); inner.addColorStop(0.6, '#b48226'); inner.addColorStop(1, '#6e4a10'); + ctx.fillStyle = inner; ctx.beginPath(); ctx.arc(cx, cy, r * 0.86, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(70,45,8,0.5)'; ctx.lineWidth = 1.5; + for (const k of [0.86, 0.7, 0.5]) { ctx.beginPath(); ctx.arc(cx, cy, r * k, 0, Math.PI * 2); ctx.stroke(); } + // engraved petals on the rim + for (let i = 0; i < 24; i++) { + const a = (i / 24) * Math.PI * 2; + ctx.strokeStyle = 'rgba(80,50,10,0.45)'; ctx.lineWidth = 1; + ctx.beginPath(); ctx.arc(cx + Math.cos(a) * r * 0.93, cy + Math.sin(a) * r * 0.93, r * 0.05, 0, Math.PI * 2); ctx.stroke(); + } + ctx.strokeStyle = 'rgba(255,245,200,0.6)'; ctx.lineWidth = 3; + ctx.beginPath(); ctx.arc(cx, cy, r * 0.97, Math.PI * 1.05, Math.PI * 1.6); ctx.stroke(); +} + +function bakeBoard(scene) { + const rnd = seeded(17); + const P = BOARD_PAD; + const BR = BOARD_RECT; + const c = canvas(BR.w + P * 2, BR.h + P * 2), ctx = c.getContext('2d'); + const X = (x) => x - BR.x + P, Y = (y) => y - BR.y + P; + dropShadow(ctx, () => { ctx.fillStyle = '#4a1c0e'; rr(ctx, P, P, BR.w, BR.h, 18); ctx.fill(); }, { blur: 34, dx: 14, dy: 20, alpha: 0.65 }); + ctx.save(); rr(ctx, P, P, BR.w, BR.h, 18); ctx.clip(); + rosewood(ctx, rnd, P, P, BR.w, BR.h); + ctx.restore(); + // brass inlay line round the frame + ctx.strokeStyle = brassGrad(ctx, P, P, P + BR.w, P + BR.h); ctx.lineWidth = 3; + rr(ctx, P + 6, P + 6, BR.w - 12, BR.h - 12, 14); ctx.stroke(); + + const ox = X(ORIGIN_X), oy = Y(ORIGIN_Y); + // nests + for (const col of COLORS) { + const r = NEST_RECT[col], L = LACQUER[col]; + const x = ox + r.col0 * CELL + 6, y = oy + r.row0 * CELL + 6; + const w = (r.col1 - r.col0 + 1) * CELL - 12, h = (r.row1 - r.row0 + 1) * CELL - 12; + dropShadow(ctx, () => { ctx.fillStyle = L.base; rr(ctx, x, y, w, h, 16); ctx.fill(); }, { blur: 8, dx: 0, dy: 3, alpha: 0.6 }); + const g = ctx.createRadialGradient(x + w / 2, y + h / 2, 30, x + w / 2, y + h / 2, w * 0.75); + g.addColorStop(0, L.light); g.addColorStop(1, L.dark); + ctx.fillStyle = g; rr(ctx, x, y, w, h, 16); ctx.fill(); + ctx.fillStyle = noisePattern(ctx, 64, 16); rr(ctx, x, y, w, h, 16); ctx.fill(); + blockPrintBorder(ctx, x, y, w, h, L); + const nc = nestCenter(col); + brassBowl(ctx, X(nc.x), Y(nc.y), BOWL_R); + } + // track + for (let i = 0; i < 68; i++) { + const { col, row } = trackXY(i); + const x = ox + col * CELL + 2, y = oy + row * CELL + 2, s = CELL - 4; + const entry = Object.keys(ENTRY).find((k) => ENTRY[k] === i); + if (entry) { + lacquerTile(ctx, x, y, s, LACQUER[entry]); + lotusMotif(ctx, x + s / 2, y + s / 2, s * 0.34, 'rgba(255,240,200,0.85)', null); + } else { + boneTile(ctx, x, y, s, rnd); + if (isSafeTrack(i)) { + ctx.fillStyle = 'rgba(200,150,40,0.18)'; ctx.fillRect(x + 3, y + 3, s - 6, s - 6); + lotusMotif(ctx, x + s / 2, y + s / 2, s * 0.36, brassGrad(ctx, x, y, x + s, y + s), 'rgba(90,60,10,0.6)'); + } + } + ctx.strokeStyle = 'rgba(40,14,4,0.85)'; ctx.lineWidth = 2; ctx.strokeRect(x, y, s, s); + } + // home paths + for (const colr of COLORS) { + for (let k = 0; k < 7; k++) { + const { col, row } = homeXY(colr, k); + const x = ox + col * CELL + 2, y = oy + row * CELL + 2, s = CELL - 4; + lacquerTile(ctx, x, y, s, LACQUER[colr]); + ctx.fillStyle = 'rgba(255,240,200,0.5)'; + ctx.beginPath(); ctx.arc(x + s / 2, y + s / 2, 4 + k * 0.6, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = 'rgba(40,14,4,0.85)'; ctx.lineWidth = 2; ctx.strokeRect(x, y, s, s); + } + } + // centre: four HOME triangles round a carved lotus medallion + for (const colr of COLORS) { + const tri = homeTriangle(colr).map((p) => ({ x: X(p.x), y: Y(p.y) })); + const L = LACQUER[colr]; + const g = ctx.createLinearGradient(tri[0].x, tri[0].y, tri[2].x, tri[2].y); + g.addColorStop(0, L.dark); g.addColorStop(1, L.light); + ctx.fillStyle = g; + ctx.beginPath(); ctx.moveTo(tri[0].x, tri[0].y); ctx.lineTo(tri[1].x, tri[1].y); ctx.lineTo(tri[2].x, tri[2].y); ctx.closePath(); ctx.fill(); + ctx.strokeStyle = 'rgba(40,14,4,0.9)'; ctx.lineWidth = 2; ctx.stroke(); + } + const cc = cellWorld(9, 9); + ctx.fillStyle = 'rgba(30,10,4,0.55)'; ctx.beginPath(); ctx.arc(X(cc.x), Y(cc.y), 30, 0, Math.PI * 2); ctx.fill(); + lotusMotif(ctx, X(cc.x), Y(cc.y), 28, brassGrad(ctx, X(cc.x) - 30, Y(cc.y) - 30, X(cc.x) + 30, Y(cc.y) + 30), 'rgba(80,50,10,0.7)'); + // carved border round the centre + ctx.strokeStyle = brassGrad(ctx, ox + 8 * CELL, oy + 8 * CELL, ox + 11 * CELL, oy + 11 * CELL); ctx.lineWidth = 3; + ctx.strokeRect(ox + 8 * CELL + 1, oy + 8 * CELL + 1, 3 * CELL - 2, 3 * CELL - 2); + void GRID; void BOARD; + addCanvas(scene, 'pc-board', c); +} + +// ── pawns ──────────────────────────────────────────────────────────────────── +export const PAWN_TEX = { w: PAWN_R * 2 + 10, h: PAWN_R * 2 + 26 }; +function bakePawns(scene) { + const { w, h } = PAWN_TEX; + const cx = w / 2, baseY = h - 10, R = PAWN_R; + for (const col of COLORS) { + const L = LACQUER[col]; + const c = canvas(w, h), ctx = c.getContext('2d'); + // base disc + ctx.fillStyle = L.dark; + ctx.beginPath(); ctx.ellipse(cx, baseY, R, R * 0.46, 0, 0, Math.PI * 2); ctx.fill(); + const bg = ctx.createLinearGradient(cx - R, 0, cx + R, 0); + bg.addColorStop(0, L.dark); bg.addColorStop(0.4, L.light); bg.addColorStop(1, L.dark); + ctx.fillStyle = bg; + ctx.beginPath(); ctx.ellipse(cx, baseY - 4, R, R * 0.44, 0, 0, Math.PI * 2); ctx.fill(); + // beehive body + const body = ctx.createLinearGradient(cx - R, 0, cx + R, 0); + body.addColorStop(0, L.dark); body.addColorStop(0.35, L.light); body.addColorStop(0.6, L.base); body.addColorStop(1, L.dark); + ctx.fillStyle = body; + ctx.beginPath(); + ctx.moveTo(cx - R * 0.82, baseY - 6); + ctx.bezierCurveTo(cx - R * 0.95, baseY - R * 1.2, cx - R * 0.45, baseY - R * 1.55, cx, baseY - R * 1.58); + ctx.bezierCurveTo(cx + R * 0.45, baseY - R * 1.55, cx + R * 0.95, baseY - R * 1.2, cx + R * 0.82, baseY - 6); + ctx.closePath(); ctx.fill(); + // turned rings + ctx.strokeStyle = 'rgba(0,0,0,0.25)'; ctx.lineWidth = 1.2; + for (const k of [0.45, 0.9]) { ctx.beginPath(); ctx.ellipse(cx, baseY - R * k - 4, R * (0.86 - k * 0.25), R * 0.16, 0, 0, Math.PI); ctx.stroke(); } + // knob + const kn = ctx.createRadialGradient(cx - 3, baseY - R * 1.82, 1, cx, baseY - R * 1.72, R * 0.42); + kn.addColorStop(0, '#ffffff'); kn.addColorStop(0.25, L.light); kn.addColorStop(1, L.dark); + ctx.fillStyle = kn; ctx.beginPath(); ctx.arc(cx, baseY - R * 1.72, R * 0.4, 0, Math.PI * 2); ctx.fill(); + // gloss + ctx.fillStyle = 'rgba(255,255,255,0.35)'; + ctx.beginPath(); ctx.ellipse(cx - R * 0.38, baseY - R * 0.95, R * 0.14, R * 0.42, 0.1, 0, Math.PI * 2); ctx.fill(); + addCanvas(scene, `pc-pawn-${col}`, c); + + // lotus petal + const pc = canvas(26, 44), px = pc.getContext('2d'); + const pg = px.createLinearGradient(0, 44, 0, 0); + pg.addColorStop(0, L.dark); pg.addColorStop(0.6, L.light); pg.addColorStop(1, '#fff3e0'); + px.fillStyle = pg; + px.beginPath(); px.moveTo(13, 44); px.quadraticCurveTo(-2, 22, 13, 2); px.quadraticCurveTo(28, 22, 13, 44); px.fill(); + addCanvas(scene, `pc-petal-${col}`, pc); + } + const s = canvas(60, 30), sx = s.getContext('2d'); + const sg = sx.createRadialGradient(30, 15, 4, 30, 15, 28); + sg.addColorStop(0, 'rgba(0,0,0,0.6)'); sg.addColorStop(1, 'rgba(0,0,0,0)'); + sx.fillStyle = sg; sx.fillRect(0, 0, 60, 30); + addCanvas(scene, 'pc-pawn-shadow', s); + const gS = 80, gc = canvas(gS, gS), gx = gc.getContext('2d'); + const gg = gx.createRadialGradient(gS / 2, gS / 2, 18, gS / 2, gS / 2, 38); + gg.addColorStop(0, 'rgba(255,214,90,0)'); gg.addColorStop(0.35, 'rgba(255,214,90,0.95)'); gg.addColorStop(1, 'rgba(255,214,90,0)'); + gx.fillStyle = gg; gx.fillRect(0, 0, gS, gS); + addCanvas(scene, 'pc-glow', gc); + const rc = canvas(gS, gS), rx = rc.getContext('2d'); + const rg = rx.createRadialGradient(gS / 2, gS / 2, 18, gS / 2, gS / 2, 38); + rg.addColorStop(0, 'rgba(255,60,40,0)'); rg.addColorStop(0.4, 'rgba(255,60,40,0.95)'); rg.addColorStop(1, 'rgba(255,60,40,0)'); + rx.fillStyle = rg; rx.fillRect(0, 0, gS, gS); + addCanvas(scene, 'pc-ring', rc); +} + +// ── chips, tray, cup, plates, cards ────────────────────────────────────────── +function bakeChips(scene) { + for (const [key, gold] of [['pc-chip', false], ['pc-chip-gold', true]]) { + const w = 74, h = 56, c = canvas(w + 8, h + 10), ctx = c.getContext('2d'); + ctx.fillStyle = 'rgba(0,0,0,0.4)'; rr(ctx, 5, 7, w, h, 12); ctx.fill(); + ctx.fillStyle = gold ? brassGrad(ctx, 2, 2, w, h) : (() => { const g = ctx.createLinearGradient(2, 2, w, h); g.addColorStop(0, '#fbf3df'); g.addColorStop(1, '#dccaa2'); return g; })(); + rr(ctx, 2, 2, w, h, 12); ctx.fill(); + ctx.strokeStyle = gold ? 'rgba(90,60,10,0.8)' : brassGrad(ctx, 2, 2, w, h); ctx.lineWidth = 3; rr(ctx, 4, 4, w - 4, h - 4, 10); ctx.stroke(); + addCanvas(scene, key, c); + } + const co = canvas(48, 48), cx = co.getContext('2d'); + cx.fillStyle = brassGrad(cx, 0, 0, 48, 48); cx.beginPath(); cx.arc(24, 24, 22, 0, Math.PI * 2); cx.fill(); + cx.strokeStyle = 'rgba(90,60,10,0.8)'; cx.lineWidth = 2; cx.beginPath(); cx.arc(24, 24, 18, 0, Math.PI * 2); cx.stroke(); + lotusMotif(cx, 24, 24, 12, 'rgba(255,245,200,0.7)', null); + addCanvas(scene, 'pc-coin', co); +} + +function bakeTray(scene) { + const P = 20, c = canvas(TRAY.w + P * 2, TRAY.h + P * 2), ctx = c.getContext('2d'); + dropShadow(ctx, () => { ctx.fillStyle = '#8a6418'; rr(ctx, P, P, TRAY.w, TRAY.h, 26); ctx.fill(); }, { blur: 22, dx: 8, dy: 12, alpha: 0.55 }); + ctx.fillStyle = brassGrad(ctx, P, P, P + TRAY.w, P + TRAY.h); rr(ctx, P, P, TRAY.w, TRAY.h, 26); ctx.fill(); + // engraved rim + ctx.strokeStyle = 'rgba(80,50,10,0.5)'; ctx.lineWidth = 1.2; + for (let i = 0; i < 40; i++) { + const t = i / 40; + ctx.beginPath(); ctx.arc(P + 13 + t * (TRAY.w - 26), P + 13, 3, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.arc(P + 13 + t * (TRAY.w - 26), P + TRAY.h - 13, 3, 0, Math.PI * 2); ctx.stroke(); + } + const fx = P + TRAY_WALL, fy = P + TRAY_WALL, fw = TRAY.w - TRAY_WALL * 2, fh = TRAY.h - TRAY_WALL * 2; + const fg = ctx.createRadialGradient(fx + fw / 2, fy + fh / 2, 20, fx + fw / 2, fy + fh / 2, fw * 0.8); + fg.addColorStop(0, '#9e2a22'); fg.addColorStop(1, '#5a120e'); + ctx.fillStyle = fg; rr(ctx, fx, fy, fw, fh, 12); ctx.fill(); + ctx.fillStyle = noisePattern(ctx, 64, 30); rr(ctx, fx, fy, fw, fh, 12); ctx.fill(); + ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 4; rr(ctx, fx, fy, fw, fh, 12); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,220,150,0.25)'; ctx.lineWidth = 1.5; + ctx.setLineDash([6, 5]); rr(ctx, fx + 10, fy + 10, fw - 20, fh - 20, 8); ctx.stroke(); ctx.setLineDash([]); + addCanvas(scene, 'pc-tray', c); +} + +function bakeCup(scene) { + const P = 14, cw = CUP.w, ch = CUP.h; + const c = canvas(cw + P * 2, ch + P * 2), ctx = c.getContext('2d'); + const top = P + 16, bot = P + ch - 10, lt = P + 6, rt = P + cw - 6, lb = P + 18, rb = P + cw - 18, cxm = P + cw / 2; + ctx.fillStyle = 'rgba(0,0,0,0.45)'; ctx.beginPath(); ctx.ellipse(cxm + 8, bot + 2, cw * 0.42, 12, 0, 0, Math.PI * 2); ctx.fill(); + ctx.save(); + ctx.beginPath(); ctx.moveTo(lt, top); ctx.lineTo(rt, top); ctx.lineTo(rb, bot); + ctx.ellipse(cxm, bot, (rb - lb) / 2, 10, 0, 0, Math.PI, false); ctx.lineTo(lt, top); ctx.closePath(); + const g = ctx.createLinearGradient(lt, 0, rt, 0); + g.addColorStop(0, '#7a5412'); g.addColorStop(0.3, '#f2d47e'); g.addColorStop(0.55, '#c9962e'); g.addColorStop(1, '#6a4610'); + ctx.fillStyle = g; ctx.fill(); + ctx.clip(); + // engraved bands with a vine pattern + for (const yy of [top + 26, bot - 24]) { + ctx.strokeStyle = 'rgba(70,45,8,0.65)'; ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(lt, yy - 8); ctx.lineTo(rt, yy - 8); ctx.moveTo(lt, yy + 8); ctx.lineTo(rt, yy + 8); ctx.stroke(); + ctx.beginPath(); + for (let x = lt; x <= rt; x += 4) { const y = yy + Math.sin((x - lt) / 6) * 4; if (x === lt) ctx.moveTo(x, y); else ctx.lineTo(x, y); } + ctx.stroke(); + } + lotusMotif(ctx, cxm, (top + bot) / 2, 17, 'rgba(90,60,10,0.4)', null); + ctx.restore(); + ctx.fillStyle = '#2a1a06'; ctx.beginPath(); ctx.ellipse(cxm, top, (rt - lt) / 2, 16, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#e8c46a'; ctx.lineWidth = 5; ctx.beginPath(); ctx.ellipse(cxm, top, (rt - lt) / 2 - 2, 14, 0, 0, Math.PI * 2); ctx.stroke(); + addCanvas(scene, 'pc-cup', c); +} + +function bakePlate(scene) { + const rnd = seeded(51); + const r = PLATES.red, P = 16; + const c = canvas(r.w + P * 2, r.h + P * 2), ctx = c.getContext('2d'); + dropShadow(ctx, () => { ctx.fillStyle = '#3a200e'; rr(ctx, P, P, r.w, r.h, 18); ctx.fill(); }, { blur: 18, dx: 6, dy: 10, alpha: 0.55 }); + ctx.save(); rr(ctx, P, P, r.w, r.h, 18); ctx.clip(); + const g = ctx.createLinearGradient(P, P, P, P + r.h); + g.addColorStop(0, '#7a4a26'); g.addColorStop(1, '#5a341a'); + ctx.fillStyle = g; ctx.fillRect(P, P, r.w, r.h); + grain(ctx, rnd, P, P, r.w, r.h, { lines: 26, tone: 'rgba(20,8,2,0.35)', wave: 4 }); + ctx.restore(); + // carved inner border with a bead row + ctx.strokeStyle = 'rgba(20,8,2,0.6)'; ctx.lineWidth = 3; rr(ctx, P + 8, P + 8, r.w - 16, r.h - 16, 12); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,220,170,0.25)'; ctx.lineWidth = 1; rr(ctx, P + 11, P + 11, r.w - 22, r.h - 22, 10); ctx.stroke(); + for (const [x, y] of [[P + 20, P + 20], [P + r.w - 20, P + 20], [P + 20, P + r.h - 20], [P + r.w - 20, P + r.h - 20]]) { + ctx.fillStyle = brassGrad(ctx, x - 6, y - 6, x + 6, y + 6); ctx.beginPath(); ctx.arc(x, y, 6, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, 'pc-plate', c); +} + +function bakeCard(scene, key, w, h) { + const rnd = seeded(w + h); + const P = 14, c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d'); + dropShadow(ctx, () => { ctx.fillStyle = '#f4ead2'; rr(ctx, P, P, w, h, 12); ctx.fill(); }, { blur: 16, dx: 5, dy: 9, alpha: 0.5 }); + const g = ctx.createLinearGradient(P, P, P, P + h); + g.addColorStop(0, '#f8f0dc'); g.addColorStop(1, '#ecdfc0'); + ctx.fillStyle = g; rr(ctx, P, P, w, h, 12); ctx.fill(); + ctx.fillStyle = noisePattern(ctx, 64, 14); rr(ctx, P, P, w, h, 12); ctx.fill(); + // indigo block-print border + ctx.strokeStyle = '#2b3f7a'; ctx.lineWidth = 4; rr(ctx, P + 6, P + 6, w - 12, h - 12, 9); ctx.stroke(); + ctx.fillStyle = '#2b3f7a'; + for (let x = P + 18; x < P + w - 12; x += 16) { + for (const y of [P + 15, P + h - 15]) { ctx.beginPath(); ctx.arc(x, y, 2.4, 0, Math.PI * 2); ctx.fill(); } + } + for (let i = 0; i < 6; i++) { + ctx.fillStyle = `rgba(43,63,122,${0.03 + rnd() * 0.03})`; + ctx.beginPath(); ctx.arc(P + rnd() * w, P + rnd() * h, 10 + rnd() * 30, 0, Math.PI * 2); ctx.fill(); + } + addCanvas(scene, key, c); +} + +function bakeJali(scene) { + // light falling through a carved stone screen: dark with star-shaped holes + const w = 1200, h = 750; + const c = canvas(w, h), ctx = c.getContext('2d'); + ctx.fillStyle = 'rgba(8,10,14,1)'; ctx.fillRect(0, 0, w, h); + ctx.globalCompositeOperation = 'destination-out'; + try { ctx.filter = 'blur(6px)'; } catch (_) { /* older canvas */ } + const s = 64; + for (let y = -s; y < h + s; y += s) { + for (let x = -s; x < w + s; x += s) { + const ox = (Math.floor(y / s) % 2) * s / 2; + ctx.fillStyle = 'rgba(0,0,0,0.95)'; + ctx.beginPath(); + for (let k = 0; k < 16; k++) { + const r = k % 2 ? 11 : 24, a = (k / 16) * Math.PI * 2; + const px = x + ox + Math.cos(a) * r, py = y + Math.sin(a) * r * 0.8; + if (k) ctx.lineTo(px, py); else ctx.moveTo(px, py); + } + ctx.closePath(); ctx.fill(); + } + } + try { ctx.filter = 'none'; } catch (_) { /* older canvas */ } + ctx.globalCompositeOperation = 'source-over'; + addCanvas(scene, 'pc-jali', c); +} + +function bakeBits(scene) { + const s = canvas(32, 32), sx = s.getContext('2d'); + const g = sx.createRadialGradient(16, 16, 0, 16, 16, 16); + g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.4, 'rgba(255,230,170,0.7)'); g.addColorStop(1, 'rgba(255,230,170,0)'); + sx.fillStyle = g; sx.fillRect(0, 0, 32, 32); + addCanvas(scene, 'pc-spark', s); + const st = canvas(64, 64), tx = st.getContext('2d'); + const g2 = tx.createRadialGradient(32, 32, 0, 32, 32, 32); + g2.addColorStop(0, 'rgba(255,255,255,0.5)'); g2.addColorStop(1, 'rgba(255,255,255,0)'); + tx.fillStyle = g2; tx.fillRect(0, 0, 64, 64); + addCanvas(scene, 'pc-steam', st); +} + +let baked = false; +export async function prepareParchisiArt(scene) { + try { + if (document.fonts?.load) { + await Promise.race([ + Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"'), document.fonts.load('30px YummyCupcakes')]), + new Promise((res) => setTimeout(res, 1200)), + ]); + } + } catch (_) { /* fall back to Georgia */ } + if (!baked || !scene.textures.exists('pc-room')) { + bakeRoom(scene); bakeBoard(scene); bakePawns(scene); bakeChips(scene); bakeTray(scene); bakeCup(scene); bakePlate(scene); + bakeCard(scene, 'pc-card-status', STATUS.w, STATUS.h); + bakeCard(scene, 'pc-card-talk', STATUS.w, 160); + bakeCard(scene, 'pc-card-chips', STATUS.w, 96); + bakeJali(scene); bakeBits(scene); + baked = true; + } +} +void H; diff --git a/src/games/parchisi/ParchisiBoard.js b/src/games/parchisi/ParchisiBoard.js new file mode 100644 index 0000000..64b45ae --- /dev/null +++ b/src/games/parchisi/ParchisiBoard.js @@ -0,0 +1,125 @@ +// ParchisiBoard.js — board geometry for the 19×19 cross board. Phaser-free. +// +// cols/rows 0–18. The four arms are three cells wide: the outer two columns +// are the track, the middle one the home path. Nests fill the four 8×8 +// corners; HOME is the 3×3 centre. + +import { ENTRY, HOME_ENTRY, HOME, NEST, LAST_TRACK, HOME_PATH0, trackIdx } from './ParchisiLogic.js'; + +export const CELL = 54; +export const GRID = 19; +export const BOARD = CELL * GRID; // 1026 +export const ORIGIN_X = Math.round((1920 - BOARD) / 2); // 447 +export const ORIGIN_Y = Math.round((1080 - BOARD) / 2); // 27 +export const PAWN_R = 19; + +// Track square → cell. +export function trackXY(idx) { + if (idx <= 7) return { col: 8, row: 18 - idx }; + if (idx <= 15) return { col: 7 - (idx - 8), row: 10 }; + if (idx === 16) return { col: 0, row: 9 }; + if (idx <= 24) return { col: idx - 17, row: 8 }; + if (idx <= 32) return { col: 8, row: 7 - (idx - 25) }; + if (idx === 33) return { col: 9, row: 0 }; + if (idx <= 41) return { col: 10, row: idx - 34 }; + if (idx <= 49) return { col: 11 + (idx - 42), row: 8 }; + if (idx === 50) return { col: 18, row: 9 }; + if (idx <= 58) return { col: 18 - (idx - 51), row: 10 }; + if (idx <= 66) return { col: 10, row: 11 + (idx - 59) }; + if (idx === 67) return { col: 9, row: 18 }; + throw new Error(`bad track idx ${idx}`); +} + +// Home-path square k (0..6) → cell. +export function homeXY(color, k) { + if (color === 'red') return { col: 1 + k, row: 9 }; + if (color === 'blue') return { col: 9, row: 17 - k }; + if (color === 'yellow') return { col: 17 - k, row: 9 }; + return { col: 9, row: 1 + k }; // green +} + +// The colour's HOME triangle inside the 3×3 centre (its apex points inwards). +export function homeTriangle(color) { + const c = cellWorld(9, 9); + const h = CELL * 1.5; + const tri = { + red: [[-h, -h], [-h, h]], + blue: [[-h, h], [h, h]], + yellow: [[h, h], [h, -h]], + green: [[h, -h], [-h, -h]], + }[color]; + return [{ x: c.x + tri[0][0], y: c.y + tri[0][1] }, { x: c.x + tri[1][0], y: c.y + tri[1][1] }, { x: c.x, y: c.y }]; +} + +export function cellWorld(col, row) { + return { x: ORIGIN_X + col * CELL + CELL / 2, y: ORIGIN_Y + row * CELL + CELL / 2 }; +} + +export const NEST_RECT = { + red: { col0: 0, row0: 11, col1: 7, row1: 18 }, + yellow: { col0: 11, row0: 0, col1: 18, row1: 7 }, + blue: { col0: 11, row0: 11, col1: 18, row1: 18 }, + green: { col0: 0, row0: 0, col1: 7, row1: 7 }, +}; + +export function nestCenter(color) { + const r = NEST_RECT[color]; + return { x: ORIGIN_X + ((r.col0 + r.col1 + 1) / 2) * CELL, y: ORIGIN_Y + ((r.row0 + r.row1 + 1) / 2) * CELL }; +} +export const BOWL_R = 118; + +// Four seats in the nest bowl. +export function nestSlot(color, i) { + const c = nestCenter(color); + const o = 44; + return [{ x: c.x - o, y: c.y - o }, { x: c.x + o, y: c.y - o }, { x: c.x - o, y: c.y + o }, { x: c.x + o, y: c.y + o }][i]; +} + +// Four spots inside the colour's HOME triangle. +export function homeSlot(color, i) { + const [a, b, apex] = homeTriangle(color); + const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + const along = { x: (b.x - a.x), y: (b.y - a.y) }; + const inward = { x: apex.x - mid.x, y: apex.y - mid.y }; + const f = [[-0.22, 0.2], [0.22, 0.2], [-0.1, 0.48], [0.1, 0.48]][i]; + return { x: mid.x + along.x * f[0] + inward.x * f[1], y: mid.y + along.y * f[0] + inward.y * f[1] }; +} + +// Centre of the cell a progress value stands on (track / home path); null for nest / home. +export function cellOf(color, p) { + if (p >= 0 && p <= LAST_TRACK) { const { col, row } = trackXY(trackIdx(color, p)); return cellWorld(col, row); } + if (p >= HOME_PATH0 && p < HOME) { const { col, row } = homeXY(color, p - HOME_PATH0); return cellWorld(col, row); } + return null; +} + +// Screen spot for a pawn (slot = nest/home seat; share = 0/1 when two share a cell). +export function pawnSpot(color, p, slot = 0, share = -1) { + if (p === NEST) return nestSlot(color, slot); + if (p === HOME) return homeSlot(color, slot); + const c = cellOf(color, p); + if (share < 0) return c; + // side by side across the direction of travel + const horiz = isVerticalCell(color, p); + const d = share === 0 ? -11 : 11; + return horiz ? { x: c.x + d, y: c.y } : { x: c.x, y: c.y + d }; +} + +// Does the cell under this progress lie in a vertical arm (north / south)? +function isVerticalCell(color, p) { + const c = cellOf(color, p); + const col = Math.round((c.x - ORIGIN_X - CELL / 2) / CELL); + return col >= 8 && col <= 10; +} + +// Every progress value of `color`'s path whose cell is (col,row): for hit-tests. +export function cellToTrack(col, row) { + for (let i = 0; i < 68; i++) { const t = trackXY(i); if (t.col === col && t.row === row) return i; } + return -1; +} +export function worldToCell(x, y) { + const col = Math.floor((x - ORIGIN_X) / CELL), row = Math.floor((y - ORIGIN_Y) / CELL); + if (col < 0 || row < 0 || col >= GRID || row >= GRID) return null; + return { col, row }; +} + +export { ENTRY, HOME_ENTRY }; diff --git a/src/games/parchisi/ParchisiDialogs.js b/src/games/parchisi/ParchisiDialogs.js new file mode 100644 index 0000000..8e2bb9b --- /dev/null +++ b/src/games/parchisi/ParchisiDialogs.js @@ -0,0 +1,92 @@ +// ParchisiDialogs.js — veranda pop-ups on a block-printed cotton card. Each +// opener returns { close() } and swallows clicks beneath it. + +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { Button } from '../../ui/Button.js'; +import { DISPLAY_FONT, SERIF } from './ParchisiArt.js'; + +const INDIGO = 0x2b3f7a; + +export function frame(scene, x, y, w, h, depth) { + const g = scene.add.graphics().setDepth(depth); + g.fillStyle(0x000000, 0.45).fillRoundedRect(x + 6, y + 10, w, h, 16); + g.fillStyle(0x5a2414, 1).fillRoundedRect(x, y, w, h, 16); + g.lineStyle(3, 0xe8c46a, 1).strokeRoundedRect(x + 5, y + 5, w - 10, h - 10, 13); + g.fillStyle(0xf8f0dc, 1).fillRoundedRect(x + 14, y + 14, w - 28, h - 28, 10); + g.lineStyle(4, INDIGO, 1).strokeRoundedRect(x + 22, y + 22, w - 44, h - 44, 8); + g.fillStyle(INDIGO, 1); + for (let xx = x + 36; xx < x + w - 30; xx += 16) { g.fillCircle(xx, y + 31, 2.2); g.fillCircle(xx, y + h - 31, 2.2); } + return g; +} + +export function blocker(scene, depth, alpha = 0) { + return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x0a0604, 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 onOff = (v) => (v ? 'On' : 'Off'); +const PACE = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' }; + +export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewGame, onLeave, onClose }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 600, h = 960; + 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, 'The Veranda', { fontFamily: DISPLAY_FONT, fontSize: '32px', color: '#2b3f7a' }).setOrigin(0.5).setDepth(depth + 1)); + const cx = x + w / 2; + let hRef = null; + const cycle = (k, order) => onChange(k, order[(order.indexOf(settings[k]) + 1) % order.length]); + const rows = [ + ['Resume', () => hRef.close(), 0x2b3f7a], + [() => `Opponent speed: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])], + [() => `Confirm each roll (Done / tap the tray): ${onOff(settings.confirm)}`, () => onChange('confirm', !settings.confirm)], + [() => `Auto-roll: ${onOff(settings.autoRoll)}`, () => onChange('autoRoll', !settings.autoRoll)], + [() => `Auto-play forced moves: ${onOff(settings.autoForced)}`, () => onChange('autoForced', !settings.autoForced)], + [() => `Path previews on hover: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)], + [() => `Danger rings (capture odds): ${onOff(settings.danger)}`, () => onChange('danger', !settings.danger)], + [() => `House rule — capture bonus +20: ${onOff(settings.captureBonus)}`, () => onChange('captureBonus', !settings.captureBonus)], + [() => `House rule — home bonus +10: ${onOff(settings.homeBonus)}`, () => onChange('homeBonus', !settings.homeBonus)], + [() => `House rule — third-doubles penalty: ${onOff(settings.threeDoubles)}`, () => onChange('threeDoubles', !settings.threeDoubles)], + [() => `House rule — share safe squares: ${onOff(settings.shareSafe)}`, () => onChange('shareSafe', !settings.shareSafe)], + [() => `Monsoon rain: ${onOff(settings.rain)}`, () => onChange('rain', !settings.rain)], + [() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)], + ['How to Play', () => onRules()], + ['New Game', () => { hRef.close(); onNewGame(); }, 0x6a4a1a], + ['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a2a1a], + ]; + rows.forEach(([label, fn, bg], i) => { + const text = typeof label === 'function' ? label() : label; + const btn = new Button(scene, cx, y + 124 + i * 48, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, { width: 520, height: 40, fontSize: 15, bg: bg ?? 0x5a3418 }).setDepth(depth + 2); + objs.push(btn); + }); + objs.push(scene.add.text(cx, y + h - 46, 'House rules apply from the next game. Keys: Space roll / done · 1–6 pick a move chip · Z undo · H hint · Esc menu', { + fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 80 }, + }).setOrigin(0.5).setDepth(depth + 1)); + hRef = handle(objs, onClose); + return hRef; +} + +export function confirmBox(scene, { heading, text, yes = 'Yes', no = 'Cancel', depth, onYes, onNo }) { + const objs = [blocker(scene, depth - 1, 0.5)]; + const w = 540, h = 280; + 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 + 64, heading, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#2b3f7a' }).setOrigin(0.5).setDepth(depth + 1)); + objs.push(scene.add.text(x + w / 2, y + 132, text, { fontFamily: SERIF, fontSize: '18px', color: '#2a1a08', align: 'center', wordWrap: { width: w - 90 } }).setOrigin(0.5).setDepth(depth + 1)); + let hRef = null; + objs.push(new Button(scene, x + w / 2 - 118, y + h - 62, yes, () => { hRef.close(); onYes?.(); }, { width: 210, height: 46, fontSize: 18, bg: 0x7a2a1a }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 118, y + h - 62, no, () => { hRef.close(); onNo?.(); }, { width: 210, height: 46, fontSize: 18, bg: 0x2b3f7a }).setDepth(depth + 2)); + hRef = handle(objs); + return hRef; +} + +export function toast(scene, text, { depth, x = GAME_WIDTH / 2, y = 90, ms = 2200 } = {}) { + const t = scene.add.text(x, y, text, { fontFamily: SERIF, fontSize: '20px', color: '#2a1a08', backgroundColor: '#f8f0dc', padding: { x: 18, y: 10 } }).setOrigin(0.5).setDepth(depth).setAlpha(0); + scene.tweens.add({ targets: t, alpha: 1, duration: 200 }); + scene.tweens.add({ targets: t, alpha: 0, delay: ms, duration: 400, onComplete: () => t.destroy() }); + return t; +} diff --git a/src/games/parchisi/ParchisiEndScreen.js b/src/games/parchisi/ParchisiEndScreen.js new file mode 100644 index 0000000..a4b1bd7 --- /dev/null +++ b/src/games/parchisi/ParchisiEndScreen.js @@ -0,0 +1,95 @@ +// ParchisiEndScreen.js — the podium (everyone ranked: the winner, then pawns +// home, then steps left), a stats table per seat and a race chart of the steps +// each seat still had to travel, turn by turn. + +import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; +import { DISPLAY_FONT, SERIF, PRINT_FONT, LACQUER } from './ParchisiArt.js'; +import { frame } from './ParchisiDialogs.js'; +import { rankings, pawnsHome, totalPipsRemaining } from './ParchisiLogic.js'; + +const PLACE = ['1st', '2nd', '3rd', '4th']; + +export function openEndScreen(scene, { gs, names, human, depth, onPlayAgain, onMenu }) { + const objs = []; + const w = 1060, h = 800; + const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2; + objs.push(scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x0a0604, 0.5).setDepth(depth - 1).setInteractive()); + objs.push(frame(scene, x, y, w, h, depth)); + const order = rankings(gs); + const won = order[0] === human; + objs.push(scene.add.text(x + w / 2, y + 66, won ? 'All four home — you win!' : `${names[order[0]]} wins`, { + fontFamily: DISPLAY_FONT, fontSize: '36px', color: won ? '#2f7d4a' : '#9c2a22', + }).setOrigin(0.5).setDepth(depth + 1)); + + // podium + const podX = x + 70, podY = y + 270; + const heights = [120, 90, 66, 46]; + const slot = [1, 0, 2, 3]; // draw order: 2nd, 1st, 3rd, 4th + const g = scene.add.graphics().setDepth(depth + 1); + objs.push(g); + slot.slice(0, order.length).forEach((rank, k) => { + const c = order[rank]; + if (!c) return; + const bx = podX + k * 118, bh = heights[rank]; + const L = LACQUER[c]; + g.fillStyle(L.hex, 1).fillRoundedRect(bx, podY - bh, 104, bh, 6); + g.lineStyle(2, 0x2a1a08, 0.6).strokeRoundedRect(bx, podY - bh, 104, bh, 6); + objs.push(scene.add.text(bx + 52, podY - bh + 22, PLACE[rank], { fontFamily: DISPLAY_FONT, fontSize: '22px', color: '#ffffff' }).setOrigin(0.5).setDepth(depth + 2)); + objs.push(scene.add.image(bx + 52, podY - bh - 6, `pc-pawn-${c}`).setOrigin(0.5, 0.85).setScale(1.2).setDepth(depth + 2)); + const nm = c === human ? 'You' : names[c]; + objs.push(scene.add.text(bx + 52, podY + 16, nm.length > 10 ? nm.slice(0, 9) + '…' : nm, { fontFamily: SERIF, fontSize: '15px', color: L.ink }).setOrigin(0.5).setDepth(depth + 2)); + objs.push(scene.add.text(bx + 52, podY + 36, `${pawnsHome(gs, c)} home · ${totalPipsRemaining(gs, c)} left`, { fontFamily: SERIF, fontSize: '12px', color: '#4a3a22' }).setOrigin(0.5).setDepth(depth + 2)); + }); + + // stats table + const rows = [ + ['Captures', (s) => s.captures], + ['Sent back to the nest', (s) => s.captured], + ['Doubles rolled', (s) => s.doubles], + ['Third-doubles penalties', (s) => s.penalties], + ['Blockades formed', (s) => s.blockades], + ['Rolls with no move', (s) => s.blocked], + ['Bonuses earned (+20 / +10)', (s) => `${s.bonus20} / ${s.bonus10}`], + ['Bonuses forfeited', (s) => s.forfeits], + ]; + const tx = x + 60, ty = y + 352; + const colW = 104; + order.forEach((c, k) => { + objs.push(scene.add.text(tx + 290 + k * colW, ty, (c === human ? 'YOU' : names[c].toUpperCase()).slice(0, 9), { fontFamily: PRINT_FONT, fontSize: '13px', color: LACQUER[c].ink }).setOrigin(0.5).setDepth(depth + 1)); + }); + rows.forEach(([label, fn], i) => { + const yy = ty + 30 + i * 30; + objs.push(scene.add.text(tx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#3a3022' }).setOrigin(0, 0.5).setDepth(depth + 1)); + order.forEach((c, k) => objs.push(scene.add.text(tx + 290 + k * colW, yy, String(fn(gs.stats[c])), { fontFamily: SERIF, fontSize: '16px', color: LACQUER[c].ink }).setOrigin(0.5).setDepth(depth + 1))); + }); + + // race chart + const cx0 = x + 690, cy0 = y + 130, cw = 310, ch = 470; + const cg = scene.add.graphics().setDepth(depth + 1); + objs.push(cg); + cg.fillStyle(0xffffff, 0.55).fillRect(cx0, cy0, cw, ch); + cg.lineStyle(1, 0x2b3f7a, 0.25); + for (let k = 1; k < 4; k++) cg.lineBetween(cx0, cy0 + (ch * k) / 4, cx0 + cw, cy0 + (ch * k) / 4); + cg.lineStyle(1.5, 0x2a1a08, 0.6).strokeRect(cx0, cy0, cw, ch); + const hist = gs.pipHistory; + const maxP = Math.max(1, ...hist.flatMap((r) => Object.values(r))); + const n = Math.max(2, hist.length); + for (const c of gs.players) { + cg.lineStyle(3, LACQUER[c].hex, 0.95); + cg.beginPath(); + hist.forEach((r, i) => { + const px = cx0 + (i / (n - 1)) * cw, py = cy0 + ch - (r[c] / maxP) * ch; + if (i) cg.lineTo(px, py); else cg.moveTo(px, py); + }); + cg.strokePath(); + } + objs.push(scene.add.text(cx0 + cw / 2, cy0 - 16, 'Steps still to travel', { fontFamily: PRINT_FONT, fontSize: '13px', color: '#3a3022' }).setOrigin(0.5).setDepth(depth + 1)); + + const by = y + h - 72; + objs.push(new Button(scene, x + w / 2 - 130, by, 'Play Again', () => { close(); onPlayAgain(); }, { width: 230, height: 50, fontSize: 20, bg: 0x2f7d4a }).setDepth(depth + 2)); + objs.push(new Button(scene, x + w / 2 + 130, by, 'Leave Table', () => { close(); onMenu(); }, { width: 230, height: 50, fontSize: 20, bg: 0x2b3f7a }).setDepth(depth + 2)); + let closed = false; + function close() { if (closed) return; closed = true; objs.forEach((o) => o.destroy()); } + return { close, objs }; +} diff --git a/src/games/parchisi/ParchisiGame.js b/src/games/parchisi/ParchisiGame.js index 4fe8118..92c918b 100644 --- a/src/games/parchisi/ParchisiGame.js +++ b/src/games/parchisi/ParchisiGame.js @@ -1,1054 +1,870 @@ +// ParchisiGame.js — "Monsoon Veranda". The scene only orchestrates: rules in +// ParchisiLogic, the AI in ParchisiAI, geometry in ParchisiBoard / Layout, +// pieces in ParchisiPawns, dice in ParchisiTray, furniture in ParchisiHud. +// +// Flow: opening throw (highest die starts) → roll → [third-doubles penalty] → +// move (click a pawn, pick a marker — or a chip first; undo; hint) → Done → +// doubles roll again / next seat … → someone brings all four home. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS as UI } from '../../config.js'; -import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { auth } from '../../services/auth.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { - createInitialState, rollDice, getValidMoves, - applyMove, hasAnyMove, isSafeTrack, - COLORS as PCOLORS, ENTRY, HOME_ENTRY, HOME_COL_LEN, -} from './ParchisiLogic.js'; -import { chooseMoves } from './ParchisiAI.js'; +import { api } from '../../services/api.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { aiTiming, clampSkill, PACE } from '../../ui/cardtable/AITiming.js'; +import * as L from './ParchisiLogic.js'; +import { chooseMoves, hint, dangerReport } from './ParchisiAI.js'; +import { BOARD_RECT, CUP, BANNER } from './ParchisiLayout.js'; +import { cellOf, homeSlot, homeTriangle } from './ParchisiBoard.js'; +import { prepareParchisiArt, BOARD_PAD, DISPLAY_FONT, LACQUER } from './ParchisiArt.js'; +import { PawnSet } from './ParchisiPawns.js'; +import { DiceTray, BrassCup } from './ParchisiTray.js'; +import { Hud } from './ParchisiHud.js'; +import { openPauseMenu, confirmBox, toast } from './ParchisiDialogs.js'; +import { openEndScreen } from './ParchisiEndScreen.js'; +import { bonk, coin, chime, thud, tap, Rain } from './ParchisiSound.js'; -// ── Layout constants ──────────────────────────────────────────────────────── -const CELL = 50; -const GRID = 19; -const BOARD = CELL * GRID; // 950 -const ORIGIN_X = (GAME_WIDTH - BOARD) / 2; // 485 -const ORIGIN_Y = (GAME_HEIGHT - BOARD) / 2; // 65 -const PAWN_R = 18; -const DEPTH = { felt: -1, board: 0, square: 1, label: 2, pawn: 10, highlight: 20, moving: 30, dice: 40, ui: 50, banner: 60 }; - -const COLOR_HEX = { - red: { fill: 0xc92a2a, ring: 0xff6b6b, dark: 0x7a1010 }, - blue: { fill: 0x1864ab, ring: 0x4dabf7, dark: 0x0a3a6b }, - yellow: { fill: 0xe6b800, ring: 0xffd43b, dark: 0x8a6d00 }, - green: { fill: 0x2f9e44, ring: 0x69db7c, dark: 0x155724 }, +const SETTINGS_KEY = 'parchisi-settings'; +const DEFAULT_SETTINGS = { + pace: 'normal', confirm: true, autoRoll: false, autoForced: true, hints: true, danger: true, + captureBonus: true, homeBonus: true, threeDoubles: true, shareSafe: false, rain: false, skipAI: false, }; +const D = { bg: 0, board: 5, mark: 8, glow: 9, pawn: 10, dice: 30, jali: 40, hud: 50, cup: 56, fx: 70, banner: 80, end: 95, modal: 110 }; +const HUMAN = 'red'; -const BOARD_BG = 0x1d2630; -const NEST_BORDER = 0x000000; -const TRACK_FILL = 0xeae3d0; -const TRACK_STROKE = 0x32281a; -const SAFE_FILL = 0xcfe6f7; -const CENTER_FILL = 0xeae3d0; -const HOME_GOAL = 0xffd700; - -// ── Track index → (col, row) ──────────────────────────────────────────────── -function trackXY(idx) { - if (idx <= 7) return { col: 8, row: 18 - idx }; - if (idx <= 15) return { col: 7 - (idx - 8), row: 10 }; - if (idx === 16) return { col: 0, row: 9 }; - if (idx <= 24) return { col: idx - 17, row: 8 }; - if (idx <= 32) return { col: 8, row: 7 - (idx - 25) }; - if (idx === 33) return { col: 9, row: 0 }; - if (idx <= 41) return { col: 10, row: idx - 34 }; - if (idx <= 49) return { col: 11 + (idx - 42), row: 8 }; - if (idx === 50) return { col: 18, row: 9 }; - if (idx <= 58) return { col: 18 - (idx - 51), row: 10 }; - if (idx <= 66) return { col: 10, row: 11 + (idx - 59) }; - if (idx === 67) return { col: 9, row: 18 }; - throw new Error(`bad track idx ${idx}`); -} - -function homeXY(color, idx) { - if (color === 'red') return { col: 1 + idx, row: 9 }; // west spoke - if (color === 'blue') return { col: 9, row: 17 - idx }; // south spoke - if (color === 'yellow') return { col: 17 - idx, row: 9 }; // east spoke - if (color === 'green') return { col: 9, row: 1 + idx }; // north spoke - throw new Error(`bad color ${color}`); -} - -// Final "home" cell at the center boundary per color. -function homeFinalXY(color) { - if (color === 'red') return { col: 8, row: 9 }; // west spoke - if (color === 'blue') return { col: 9, row: 10 }; // south spoke - if (color === 'yellow') return { col: 10, row: 9 }; // east spoke - if (color === 'green') return { col: 9, row: 8 }; // north spoke -} - -function cellWorld(col, row) { - return { x: ORIGIN_X + col * CELL + CELL / 2, y: ORIGIN_Y + row * CELL + CELL / 2 }; -} - -// Per-color nest layout: 4 pawn slot positions in WORLD coords. -const NEST_RECT = { - red: { col0: 0, row0: 11, col1: 7, row1: 18 }, - yellow: { col0: 11, row0: 0, col1: 18, row1: 7 }, - blue: { col0: 11, row0: 11, col1: 18, row1: 18 }, - green: { col0: 0, row0: 0, col1: 7, row1: 7 }, +const SPEECH = { + capture: ['Back to the nest with you!', 'Twenty steps for me, thank you.', 'Bop!', 'Sorry — not sorry.'], + captured: ['Arre! My poor pawn…', 'You will regret that.', 'Hai, hai…', 'That was my best one!'], + home: ['One more home!', 'Safe and sound.', 'Home for chai.'], + doubles: ['Doubles! Again!', 'The dice like me.', 'Once more!'], + penalty: ['Three doubles… ruined!', 'Too lucky — the dice took it back.'], + blockade: ['Nobody passes here.', 'A wall, my friend.'], + win: ['All four home! Shall we play again?', 'A good game on a rainy day.'], + lose: ['Well played!', 'You earned that one.'], }; +const pick = (a) => a[Math.floor(Math.random() * a.length)]; -function nestSlotsWorld(color) { - const r = NEST_RECT[color]; - const cx = ORIGIN_X + ((r.col0 + r.col1 + 1) / 2) * CELL; - const cy = ORIGIN_Y + ((r.row0 + r.row1 + 1) / 2) * CELL; - const off = 75; - return [ - { x: cx - off, y: cy - off }, - { x: cx + off, y: cy - off }, - { x: cx - off, y: cy + off }, - { x: cx + off, y: cy + off }, - ]; -} - -// Final "home" stacking slot — 4 positions clustered near the color's center -// boundary cell so all 4 pawns are visible once home. -function homeStackSlots(color) { - const { col, row } = homeFinalXY(color); - const base = cellWorld(col, row); - const o = 14; - return [ - { x: base.x - o, y: base.y - o }, - { x: base.x + o, y: base.y - o }, - { x: base.x - o, y: base.y + o }, - { x: base.x + o, y: base.y + o }, - ]; -} - -// Convert a pawn's logical loc into a WORLD position (used for non-nest/home). -function pawnLocWorld(loc, color, slotIdx = 0) { - if (loc === 'nest' || loc?.loc === 'nest') { - return nestSlotsWorld(color)[slotIdx]; - } - if (loc === 'home' || loc?.loc === 'home') { - return homeStackSlots(color)[slotIdx]; - } - if (loc.track !== undefined) { - const { col, row } = trackXY(loc.track); - return cellWorld(col, row); - } - if (loc.home !== undefined) { - const { col, row } = homeXY(color, loc.home); - return cellWorld(col, row); - } - return { x: 0, y: 0 }; -} - -// ── Scene ─────────────────────────────────────────────────────────────────── export default class ParchisiGame extends Phaser.Scene { constructor() { super('ParchisiGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.gs = null; - this.animating = false; - this.pawnObjs = {}; // color → [container, ...] (4 each) - this.highlightObjs = []; - this.selectedPawnIdx = null; - this.diceContainers = []; - this.diceGraphics = []; - this.rollBtn = null; - this.statusText = null; - this.opponentPortraits = {}; // color → portrait controller - this.turnIndicator = null; - this.turnIndicatorGfx = null; - this.turnIndicatorPulseTween = null; - this.turnIndicatorMoveTween = null; - this.bonusChip20 = null; - this._bonusChip20Visible = false; + this.initData = data ?? {}; + this.gameDef = this.initData.game; + this.opponents = (this.initData.opponents ?? []).slice(0, 3); + this.playfield = this.initData.playfield ?? null; + this.ended = false; + this.busy = true; + this.modal = null; + this.phase = 'setup'; // setup | opening | roll | move | ai | over + this.sel = null; // { pawnIdx, moves } + this.chip = null; // selected chip index + this.undoStack = []; + this.shaking = false; + this.markers = []; + try { this.settings = { ...DEFAULT_SETTINGS, ...JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') }; } + catch (_) { this.settings = { ...DEFAULT_SETTINGS }; } } + get k() { return PACE[this.settings.pace] ?? 1; } + create() { new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildPlayfield(); - this.buildBoard(); - this.buildDice(); - this.buildUI(); - this.buildBonusChip(); - this.buildPlayerCards(); - this.buildTurnIndicator(); - this.buildPawns(); - this.initGame(); - this.buildDismissHandler(); + this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x1a0f08).setDepth(-2); + const n = Math.max(2, Math.min(4, 1 + Math.max(1, this.opponents.length))); + const players = L.seatColors(n); + this.names = {}; this.skills = {}; this.oppOf = {}; + players.forEach((c, i) => { + if (i === 0) { this.names[c] = auth.user?.username ?? 'You'; return; } + const o = this.opponents[i - 1] ?? { id: `bot${i}`, name: `Guest ${i}` }; + this.oppOf[c] = o; + this.names[c] = o.name ?? o.id ?? c; + this.skills[c] = clampSkill(o.skill ?? 3); + }); + const s = this.settings; + this.gs = L.createInitialState(players, { captureBonus: s.captureBonus, homeBonus: s.homeBonus, threeDoubles: s.threeDoubles, shareSafe: s.shareSafe }); + prepareParchisiArt(this).then(() => { + if (!this.sys.isActive()) return; + this.build(); + this.time.delayedCall(400, () => this.openingPrompt()); + }); } - buildPlayfield() { + // ── build ─────────────────────────────────────────────────────────────────── + build() { const pf = this.playfield; - if (!pf) return; - 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.felt); - } else if (pf.fallbackColor) { - const color = parseInt(pf.fallbackColor.replace('#', ''), 16); - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, color).setDepth(DEPTH.felt); + 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(D.bg); + this.add.image(0, 0, 'pc-props').setOrigin(0).setDepth(D.bg + 1); + this.add.image(0, 0, 'pc-vignette').setOrigin(0).setDepth(D.bg + 2); + } else { + this.add.image(0, 0, 'pc-room').setOrigin(0).setDepth(D.bg); } + this.add.image(BOARD_RECT.x - BOARD_PAD, BOARD_RECT.y - BOARD_PAD, 'pc-board').setOrigin(0).setDepth(D.board); + + this.pawns = new PawnSet(this, this.gs.players, D.pawn).build(); + this.pawns.sync(this.gs); + this.tray = new DiceTray(this, D.dice, { onClick: () => this.onTrayClick() }).build(); + this.cup = new BrassCup(this, D.cup, CUP, { onPress: () => this.beginShake() }).build(); + this.hud = new Hud(this, D.hud, { + players: this.gs.players, human: HUMAN, names: this.names, skills: this.skills, opponents: this.oppOf, + onButton: (k) => this.onButton(k), onChip: (i) => this.onChip(i), + }).build(); + this.markG = this.add.graphics().setDepth(D.mark + 3); + this.pathG = this.add.graphics().setDepth(D.mark); + this.markTexts = []; + this.glows = []; + this.rings = []; + this.hintG = this.add.graphics().setDepth(D.mark + 4); + this.blockG = this.add.graphics().setDepth(D.pawn - 2); + this.hintTexts = []; + + // jali light drifting over the board + const j = this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, 'pc-jali').setScale(2.3).setDepth(D.jali).setAlpha(0.13).setRotation(0.12); + this.tweens.add({ targets: j, x: { from: GAME_WIDTH / 2 - 70, to: GAME_WIDTH / 2 + 70 }, duration: 26000, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.tweens.add({ targets: j, alpha: { from: 0.09, to: 0.16 }, duration: 11000, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.time.addEvent({ delay: 560, loop: true, callback: () => { + if (this.ended) return; + const st = this.add.image(1583 + Math.random() * 10, 752, 'pc-steam').setDepth(D.hud - 1).setAlpha(0).setScale(0.4); + this.tweens.add({ targets: st, y: 660 - Math.random() * 30, x: st.x + (Math.random() - 0.5) * 40, alpha: { from: 0.45, to: 0 }, scale: 1.4, duration: 2600, ease: 'Sine.Out', onComplete: () => st.destroy() }); + } }); + this.rain = new Rain(this); + if (this.settings.rain) this.rain.start(); + + this.refreshHud(); + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', () => this.releaseShake()); + this.input.keyboard?.on('keydown', (e) => this.onKey(e, true)); + this.input.keyboard?.on('keyup', (e) => this.onKey(e, false)); + this.events.once('shutdown', () => { this.ended = true; this.cup?.stopShake(); this.rain?.stop(); }); } - buildBoard() { - const g = this.add.graphics().setDepth(DEPTH.board); - // Board base - g.fillStyle(BOARD_BG, 1); - g.fillRoundedRect(ORIGIN_X - 6, ORIGIN_Y - 6, BOARD + 12, BOARD + 12, 12); - - // Nests - for (const c of PCOLORS) this.drawNest(c); - - // Outer track squares - for (let i = 0; i < 68; i++) this.drawTrackSquare(i); - - // Home columns - for (const c of PCOLORS) this.drawHomeColumn(c); - - // Center home triangle area - this.drawCenter(); + // ── HUD ───────────────────────────────────────────────────────────────────── + refreshHud() { + const gs = this.gs; + this.hud.refreshSeats(gs); + this.hud.setTalk(gs.log); + const human = !this.busy && !this.modal && gs.currentPlayer === HUMAN; + const moving = human && this.phase === 'move'; + const done = moving && L.turnDone(gs); + this.hud.setButton('done', done); + this.hud.setButton('undo', moving && this.undoStack.length > 0); + this.hud.setButton('hint', moving && !done); + const showChips = gs.phase === 'move' && gs.movesLeft.length; + this.hud.setChips(showChips ? gs.movesLeft : [], this.chip, moving && !done, moving && !done ? 'tap one to filter' : ''); + this.tray.setGlow(done && this.settings.confirm ? 0.9 : 0); + this.tray.setClickable(done); + this.drawDanger(); + this.drawBlockades(); } - drawNest(color) { - const r = NEST_RECT[color]; - const c = COLOR_HEX[color]; - const x = ORIGIN_X + r.col0 * CELL; - const y = ORIGIN_Y + r.row0 * CELL; - const w = (r.col1 - r.col0 + 1) * CELL; - const h = (r.row1 - r.row0 + 1) * CELL; - const g = this.add.graphics().setDepth(DEPTH.square); - g.fillStyle(c.fill, 0.95); - g.fillRoundedRect(x + 4, y + 4, w - 8, h - 8, 14); - g.lineStyle(3, c.dark, 1); - g.strokeRoundedRect(x + 4, y + 4, w - 8, h - 8, 14); - - // Inner circle indicating nest area - g.fillStyle(0xffffff, 0.55); - g.fillCircle(x + w / 2, y + h / 2, Math.min(w, h) * 0.36); - g.lineStyle(2, c.dark, 0.8); - g.strokeCircle(x + w / 2, y + h / 2, Math.min(w, h) * 0.36); - } - - drawTrackSquare(idx) { - const { col, row } = trackXY(idx); - const wp = cellWorld(col, row); - const g = this.add.graphics().setDepth(DEPTH.square); - // Determine fill: colored entry, safe, or normal - const entryColor = Object.keys(ENTRY).find((c) => ENTRY[c] === idx); - let fill = TRACK_FILL; - if (entryColor) fill = COLOR_HEX[entryColor].fill; - else if (isSafeTrack(idx)) fill = SAFE_FILL; - g.fillStyle(fill, 1); - g.fillRoundedRect(wp.x - CELL / 2 + 2, wp.y - CELL / 2 + 2, CELL - 4, CELL - 4, 6); - g.lineStyle(1.5, TRACK_STROKE, 0.8); - g.strokeRoundedRect(wp.x - CELL / 2 + 2, wp.y - CELL / 2 + 2, CELL - 4, CELL - 4, 6); - - // Safety star marker - if (isSafeTrack(idx) && !entryColor) { - this.drawStar(g, wp.x, wp.y, 5, 10, 5, 0x2b5d80, 0.7); - } - - } - - drawHomeColumn(color) { - const c = COLOR_HEX[color]; - for (let i = 0; i < HOME_COL_LEN; i++) { - const { col, row } = homeXY(color, i); - const wp = cellWorld(col, row); - const g = this.add.graphics().setDepth(DEPTH.square); - g.fillStyle(c.fill, 0.85); - g.fillRoundedRect(wp.x - CELL / 2 + 3, wp.y - CELL / 2 + 3, CELL - 6, CELL - 6, 5); - g.lineStyle(1.5, c.dark, 0.9); - g.strokeRoundedRect(wp.x - CELL / 2 + 3, wp.y - CELL / 2 + 3, CELL - 6, CELL - 6, 5); - } - // Final goal cell at center boundary - const { col, row } = homeFinalXY(color); - const wp = cellWorld(col, row); - const g = this.add.graphics().setDepth(DEPTH.square); - g.fillStyle(HOME_GOAL, 0.4); - g.fillCircle(wp.x, wp.y, CELL * 0.42); - g.lineStyle(2, c.dark, 0.9); - g.strokeCircle(wp.x, wp.y, CELL * 0.42); - } - - drawCenter() { - // Big center triangle motif - const cx = ORIGIN_X + 9.5 * CELL; - const cy = ORIGIN_Y + 9.5 * CELL; - const r = CELL * 0.6; - const g = this.add.graphics().setDepth(DEPTH.square); - g.fillStyle(CENTER_FILL, 1); - g.fillCircle(cx, cy, r); - g.lineStyle(2, TRACK_STROKE, 0.9); - g.strokeCircle(cx, cy, r); - this.add.text(cx, cy, 'HOME', { - fontFamily: '"Julius Sans One"', - fontSize: '16px', - color: '#3a2010', - fontStyle: 'bold', - }).setOrigin(0.5).setDepth(DEPTH.label); - } - - drawStar(g, cx, cy, points, outer, inner, color, alpha) { - g.fillStyle(color, alpha); - g.beginPath(); - for (let i = 0; i < points * 2; i++) { - const r = i % 2 === 0 ? outer : inner; - const a = (i / (points * 2)) * Math.PI * 2 - Math.PI / 2; - const x = cx + Math.cos(a) * r; - const y = cy + Math.sin(a) * r; - if (i === 0) g.moveTo(x, y); else g.lineTo(x, y); - } - g.closePath(); - g.fillPath(); - } - - // ── Dice ────────────────────────────────────────────────────────────────── - buildDice() { - const baseX = ORIGIN_X - 80; - const baseY = GAME_HEIGHT / 2 - 80; - for (let i = 0; i < 2; i++) { - const g = this.add.graphics(); - const container = this.add.container(baseX, baseY + i * 80).setDepth(DEPTH.dice); - container.add(g); - this.diceContainers.push(container); - this.diceGraphics.push(g); - this.renderDieFace(i, 1); - container.setAlpha(0.25); - } - } - - renderDieFace(idx, value) { - const g = this.diceGraphics[idx]; - const s = 28; + // A woven gold cord under every pair of same-colour pawns (a blockade). + drawBlockades() { + const g = this.blockG; + if (!g) return; g.clear(); - g.fillStyle(0xf0e8d0, 1); - g.fillRoundedRect(-s, -s, s * 2, s * 2, 7); - g.lineStyle(2, 0x2c1a0e, 1); - g.strokeRoundedRect(-s, -s, s * 2, s * 2, 7); - const layouts = { - 1: [[0, 0]], - 2: [[-0.6, -0.6], [0.6, 0.6]], - 3: [[-0.6, -0.6], [0, 0], [0.6, 0.6]], - 4: [[-0.6, -0.6], [0.6, -0.6], [-0.6, 0.6], [0.6, 0.6]], - 5: [[-0.6, -0.6], [0.6, -0.6], [0, 0], [-0.6, 0.6], [0.6, 0.6]], - 6: [[-0.6, -0.6], [0.6, -0.6], [-0.6, 0], [0.6, 0], [-0.6, 0.6], [0.6, 0.6]], - }; - g.fillStyle(0x1a1a1a, 1); - for (const [px, py] of layouts[value] ?? layouts[1]) { - g.fillCircle(px * 16, py * 16, 4); - } - } - - animateDiceRoll(finalValues, onComplete) { - playSound(this, SFX.DICE_ROLL); - this.diceContainers.forEach((c) => c.setAlpha(1)); - let elapsed = 0; - const totalMs = 650; - const tick = () => { - const interval = elapsed < 400 ? 60 : 110; - for (let i = 0; i < 2; i++) this.renderDieFace(i, Phaser.Math.Between(1, 6)); - elapsed += interval; - if (elapsed < totalMs) { - this.time.delayedCall(interval, tick); - } else { - this.renderDieFace(0, finalValues[0]); - this.renderDieFace(1, finalValues[1]); - for (const c of this.diceContainers) { - this.tweens.add({ targets: c, scaleX: 1.2, scaleY: 1.2, duration: 80, yoyo: true }); + const sp = this.pawns.spots(this.gs); + for (const c of this.gs.players) { + const ps = this.gs.pawns[c]; + const seen = new Set(); + ps.forEach((p, i) => { + if (p < 0 || p >= L.HOME || seen.has(p)) return; + const j = ps.findIndex((q, k) => k !== i && q === p); + if (j < 0) return; + seen.add(p); + const a = sp[c][i], b = sp[c][j]; + const ang = Math.atan2(b.y - a.y, b.x - a.x); + const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2; + const len = Math.hypot(b.x - a.x, b.y - a.y) + 30; + const ux = Math.cos(ang), uy = Math.sin(ang), vx = -uy, vy = ux; + const corner = (s1, s2) => ({ x: mx + ux * s1 * len / 2 + vx * s2 * 7, y: my + 4 + uy * s1 * len / 2 + vy * s2 * 7 }); + g.fillStyle(LACQUER[c].hex, 0.9).fillPoints([corner(-1, -1), corner(1, -1), corner(1, 1), corner(-1, 1)], true); + g.lineStyle(2, 0xf0c96a, 1).strokePoints([corner(-1, -1), corner(1, -1), corner(1, 1), corner(-1, 1)], true); + // the weave + g.lineStyle(2, 0xf0c96a, 0.85); + for (let t = -0.8; t <= 0.8; t += 0.2) { + const p1 = { x: mx + ux * t * len / 2 + vx * -6, y: my + 4 + uy * t * len / 2 + vy * -6 }; + const p2 = { x: mx + ux * (t + 0.12) * len / 2 + vx * 6, y: my + 4 + uy * (t + 0.12) * len / 2 + vy * 6 }; + g.lineBetween(p1.x, p1.y, p2.x, p2.y); } - this.time.delayedCall(120, onComplete); - } - }; - tick(); - } - - updateDiceDisplay() { - this.updateBonusChip(); - if (!this.gs.dice) { - this.diceContainers.forEach((c) => c.setAlpha(0.25)); - return; - } - this.diceContainers.forEach((c) => c.setAlpha(1)); - this.renderDieFace(0, this.gs.dice[0]); - this.renderDieFace(1, this.gs.dice[1]); - // Dim used base-dice - const remaining = [...this.gs.movesLeft]; - for (let i = 0; i < 2; i++) { - const v = this.gs.dice[i]; - const idx = remaining.indexOf(v); - if (idx === -1) this.diceContainers[i].setAlpha(0.35); - else { this.diceContainers[i].setAlpha(1); remaining.splice(idx, 1); } - } - } - - // ── UI / Portraits ──────────────────────────────────────────────────────── - buildUI() { - const xLeft = ORIGIN_X - 80; - const yRoll = GAME_HEIGHT / 2 + 80; - this.rollBtn = new Button(this, xLeft, yRoll, 'Roll', () => this.onRollClick(), { - width: 110, height: 44, fontSize: 22, - }); - this.rollBtn.setDepth(DEPTH.ui); - - new Button(this, 80, GAME_HEIGHT - 70, 'New', () => this.initGame(), { - variant: 'ghost', width: 110, height: 40, fontSize: 18, - }).setDepth(DEPTH.ui); - - new Button(this, 80, GAME_HEIGHT - 25, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 110, height: 40, fontSize: 18, - }).setDepth(DEPTH.ui); - - this.statusText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT - 30, '', { - fontFamily: '"Julius Sans One"', - fontSize: '22px', - color: UI.textHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - } - - buildBonusChip() { - const x = ORIGIN_X - 155; - const y = GAME_HEIGHT / 2 - 40; - const R = 26; - const gfx = this.add.graphics(); - gfx.fillStyle(0xffffff, 1); - gfx.fillCircle(0, 0, R); - gfx.lineStyle(3, 0x222222, 1); - gfx.strokeCircle(0, 0, R); - const label = this.add.text(0, 0, '20', { - fontFamily: '"Julius Sans One"', - fontSize: '20px', - fontStyle: 'bold', - color: '#111111', - }).setOrigin(0.5); - this.bonusChip20 = this.add.container(x, y, [gfx, label]) - .setDepth(DEPTH.ui + 3) - .setAlpha(0) - .setScale(0.3); - } - - updateBonusChip() { - const should = !!(this.gs?.movesLeft?.includes(20)); - if (should === this._bonusChip20Visible) return; - this._bonusChip20Visible = should; - this.tweens.killTweensOf(this.bonusChip20); - if (should) { - this.tweens.add({ - targets: this.bonusChip20, alpha: 1, scale: 1, - duration: 250, ease: 'Back.easeOut', - }); - } else { - this.tweens.add({ - targets: this.bonusChip20, alpha: 0, scale: 0.3, - duration: 180, ease: 'Cubic.easeIn', }); } } - buildPlayerCards() { - const portraitR = 56; - // Left nests (red, green): col0=0, so left edge is ORIGIN_X - // Right nests (blue, yellow): col1=18, so right edge is ORIGIN_X + BOARD - const xLeft = ORIGIN_X - portraitR - 20; - const xRight = ORIGIN_X + BOARD + portraitR + 20; + setStatus(a, b = '') { this.hud.setStatus(a, b); } + nameOf(c) { return c === HUMAN ? 'You' : this.names[c]; } - // Red (human) — left side, bottom-left nest - const plY = this.nestCenterY('red'); - this.add.circle(xLeft, plY, portraitR + 5, COLOR_HEX.red.fill, 0.6).setDepth(DEPTH.ui); - createPlayerPortrait(this, xLeft, plY, portraitR, DEPTH.ui + 1, 'ParchisiGame'); - this.add.text(xLeft, plY + portraitR + 14, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: UI.textHex, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui + 2); - - // AI opponents: blue (right/bottom), yellow (right/top), green (left/top) - const aiColors = ['blue', 'yellow', 'green']; - aiColors.forEach((color, i) => { - const opp = this.opponents[i]; - if (!opp) return; - const x = color === 'green' ? xLeft : xRight; - const y = this.nestCenterY(color); - this.add.circle(x, y, portraitR + 5, COLOR_HEX[color].fill, 0.6).setDepth(DEPTH.ui); - this.opponentPortraits[color] = createOpponentPortrait(this, opp, x, y, portraitR, DEPTH.ui + 1); - this.add.text(x, y + portraitR + 12, opp.name ?? color, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: UI.textHex, - }).setOrigin(0.5, 0).setDepth(DEPTH.ui + 2); - }); + // ── opening ───────────────────────────────────────────────────────────────── + openingPrompt() { + if (this.ended) return; + this.phase = 'opening'; + this.busy = false; + this.cup.setEnabled(true); + this.setStatus('Who goes first?', 'Everyone throws one die — highest starts. Shake your cup: press and hold it (or Space), then let go.'); + this.refreshHud(); + if (this.settings.autoRoll) this.time.delayedCall(500 * this.k, () => { if (this.phase === 'opening' && !this.busy && !this.shaking) this.throwNow(); }); } - playEmotion(color, emotion) { - this.opponentPortraits[color]?.playEmotion(emotion); - } - - nestCenterY(color) { - const r = NEST_RECT[color]; - return ORIGIN_Y + ((r.row0 + r.row1 + 1) / 2) * CELL; - } - - // ── Turn indicator ──────────────────────────────────────────────────────── - buildTurnIndicator() { - const g = this.add.graphics(); - this.turnIndicatorGfx = g; - this.turnIndicator = this.add.container(0, 0, [g]).setDepth(DEPTH.ui + 3).setAlpha(0); - } - - _indicatorPos(color) { - const isLeft = color === 'red' || color === 'green'; - const portR = 56; - const portBgR = portR + 5; // matches the bg circle radius in buildPlayerCards - const portX = isLeft ? ORIGIN_X - portR - 20 : ORIGIN_X + BOARD + portR + 20; - return { - x: isLeft ? portX - portBgR - 20 : portX + portBgR + 20, - y: this.nestCenterY(color), - side: isLeft ? 'left' : 'right', - }; - } - - _drawTurnTriangle(side) { - const g = this.turnIndicatorGfx; - g.clear(); - const h = 16; // half-height - const d = 20; // depth from center to tip - g.fillStyle(0xffd700, 1); - g.lineStyle(2, 0xb8860b, 1); - g.beginPath(); - if (side === 'left') { - // Points right →, sits to the left of the portrait - g.moveTo(d, 0); - g.lineTo(-10, -h); - g.lineTo(-10, h); - } else { - // Points left ←, sits to the right of the portrait - g.moveTo(-d, 0); - g.lineTo(10, -h); - g.lineTo(10, h); + async doOpening() { + this.busy = true; + this.cup.setEnabled(false); + const next = L.rollOpening(this.gs); + for (let r = 0; r < next.opening.length; r++) { + const faces = next.opening[r]; + await this.tray.throwOpening(faces, { speed: this.k }); + if (this.ended) return; + for (const [c, f] of Object.entries(faces)) this.hud.showOpeningDie(c, f); + const tied = r < next.opening.length - 1; + if (tied) { + const hi = Math.max(...Object.values(faces)); + const who = Object.keys(faces).filter((c) => faces[c] === hi).map((c) => this.nameOf(c)); + this.banner(`Tie on ${hi}!`, 0xffe9a8, 0.6, true); + this.setStatus('A tie', `${who.join(' and ')} throw again.`); + await this.wait(1300 * this.k); + for (const c of this.gs.players) this.hud.showOpeningDie(c, null); + await this.tray.clear(); + } } - g.closePath(); - g.fillPath(); - g.strokePath(); + this.gs = next; + const starter = next.currentPlayer; + this.gs = L.logTurn(this.gs, starter, 'starts the game'); + this.banner(starter === HUMAN ? 'You go first!' : `${this.names[starter]} goes first`, LACQUER[starter].hex, 0.62, true); + await this.wait(1300 * this.k); + for (const c of this.gs.players) this.hud.showOpeningDie(c, null); + await this.tray.clear(); + this.startTurn(); } - _startIndicatorPulse() { - if (this.turnIndicatorPulseTween) this.turnIndicatorPulseTween.stop(); - this.turnIndicatorPulseTween = this.tweens.add({ - targets: this.turnIndicator, - scaleX: { from: 1, to: 1.35 }, - scaleY: { from: 1, to: 1.35 }, - alpha: { from: 1, to: 0.55 }, - duration: 560, - ease: 'Sine.easeInOut', - yoyo: true, - repeat: -1, - }); + // ── turns ─────────────────────────────────────────────────────────────────── + startTurn() { + if (this.ended) return; + this.clearSelection(); + this.clearHint(); + this.refreshHud(); + if (this.gs.currentPlayer === HUMAN) this.humanRollPrompt(); + else this.aiTurn(); } - moveTurnIndicator(color, immediately = false, onArrive = null) { - const { x, y, side } = this._indicatorPos(color); - // Stop both running tweens before starting new ones - if (this.turnIndicatorPulseTween) { - this.turnIndicatorPulseTween.stop(); - this.turnIndicatorPulseTween = null; - } - if (this.turnIndicatorMoveTween) { - this.turnIndicatorMoveTween.stop(); - this.turnIndicatorMoveTween = null; - } - this.turnIndicator.setScale(1); + humanRollPrompt() { + this.phase = 'roll'; + this.busy = false; + this.cup.setEnabled(true); + const again = this.gs.consecutiveDoubles > 0; + this.setStatus(again ? 'Doubles — roll again!' : 'Your roll', 'Shake the brass cup: press and hold it (or Space), then let go.'); + this.refreshHud(); + if (this.settings.autoRoll) this.time.delayedCall(450 * this.k, () => { if (this.phase === 'roll' && !this.busy && !this.modal && !this.shaking) this.throwNow(); }); + } - if (immediately || this.turnIndicator.alpha === 0) { - this._drawTurnTriangle(side); - this.turnIndicator.setPosition(x, y).setAlpha(1); - this._startIndicatorPulse(); - onArrive?.(); + canShake() { + return !this.ended && !this.busy && !this.modal && !this.shaking + && (this.phase === 'opening' || (this.phase === 'roll' && this.gs.currentPlayer === HUMAN)); + } + beginShake() { + if (!this.canShake()) return; + this.shaking = true; + this.cup.startShake(); + } + releaseShake() { + if (!this.shaking) return; + const held = this.cup.shakeTime(); + const go = () => { this.shaking = false; this.throwNow(); }; + if (held < 260) this.time.delayedCall(260 - held, go); else go(); + } + + async throwNow() { + if (this.ended || this.busy || this.modal) return; + if (this.phase !== 'opening' && !(this.phase === 'roll' && this.gs.currentPlayer === HUMAN)) return; + this.shaking = false; + this.cup.pour(); + if (this.phase === 'opening') { this.doOpening(); return; } + this.busy = true; + this.cup.setEnabled(false); + this.refreshHud(); + await this.rollFor(HUMAN); + } + + // Roll, animate, and route the result (shared by you and the AI). + async rollFor(c) { + this.gs = L.rollDice(this.gs); + const ev = this.gs.lastEvent; + const [d1, d2] = this.gs.dice ?? ev?.dice ?? [1, 1]; + const fast = c !== HUMAN && this.settings.skipAI; + await this.tray.throwRoll(c, d1, d2, ev?.type === 'roll' && ev.backs, { speed: this.k, fast }); + if (this.ended) return; + if (ev?.type === 'threeDoubles') { await this.penalty(ev); return; } + if (d1 === d2) { + this.banner(ev.backs ? `Doubles! ${d1}s and ${7 - d1}s` : `Doubles! ${d1}–${d2}`, 0xffe9a8, 0.55, true); + if (c !== HUMAN && Math.random() < 0.4) this.hud.say(c, pick(SPEECH.doubles)); + } + this.tray.setUsage(this.gs.movesLeft); + if (c === HUMAN) this.humanMovePhase(); + else this.aiMoves(); + } + + async penalty(ev) { + thud(this); + this.tray.setGlow(1, 0xe0402a); + this.banner('Third doubles!', 0xf08a70, 0.75, true); + this.setStatus(`${this.nameOf(ev.color)} rolled doubles three times`, ev.pawnIdx >= 0 ? 'The pawn closest to home goes back to the nest.' : 'Nothing on the board to lose — lucky!'); + if (ev.color !== HUMAN) this.hud.say(ev.color, pick(SPEECH.penalty)); + this.hud.emotion(ev.color, 'upset'); + await this.wait(900 * this.k); + if (ev.pawnIdx >= 0) { + const it = this.pawns.get(ev.color, ev.pawnIdx); + await this.pawns.arc(it, { x: it.x, y: it.y - 50, scale: 1.2 }, 300, 20); + await this.pawns.knockHome(ev.color, ev.pawnIdx, 700); + } + this.pawns.sync(this.gs); + this.tray.setGlow(0); + await this.wait(400 * this.k); + await this.tray.clear(); + this.startTurn(); + } + + // ── your move ─────────────────────────────────────────────────────────────── + async humanMovePhase() { + if (this.ended) return; + this.phase = 'move'; + this.undoStack = []; + this.chip = null; + if (!L.hasAnyMove(this.gs)) { + this.busy = true; + this.setStatus('No legal move', this.gs.pawns[HUMAN].includes(L.NEST) && !this.gs.pawns[HUMAN].some((p) => p >= 0 && p < L.HOME) ? 'You need a 5 (or two dice making 5) to leave the nest.' : 'Nothing can move with this roll.'); + this.refreshHud(); + await this.wait(1500 * this.k); + this.endRoll(); return; } - - this.turnIndicatorMoveTween = this.tweens.add({ - targets: this.turnIndicator, - x, y, - duration: 400, - ease: 'Cubic.easeInOut', - onComplete: () => { - this.turnIndicatorMoveTween = null; - this._drawTurnTriangle(side); - this._startIndicatorPulse(); - onArrive?.(); - }, - }); + this.busy = false; + this.prompt(); } - // ── Pawn rendering ──────────────────────────────────────────────────────── - buildPawns() { - for (const color of PCOLORS) { - this.pawnObjs[color] = []; - for (let i = 0; i < 4; i++) { - const slot = nestSlotsWorld(color)[i]; - const c = this.makePawn(color, slot.x, slot.y); - c.setDepth(DEPTH.pawn); - c.setInteractive({ useHandCursor: true, hitArea: new Phaser.Geom.Circle(0, 0, PAWN_R + 4), hitAreaCallback: Phaser.Geom.Circle.Contains }); - c.on('pointerdown', () => this.onPawnClick(color, i)); - this.pawnObjs[color].push(c); - } - } - } - - makePawn(color, x, y) { - const c = COLOR_HEX[color]; - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.3); - g.fillCircle(2, 3, PAWN_R); - g.fillStyle(c.dark, 1); - g.fillCircle(0, 0, PAWN_R); - g.fillStyle(c.fill, 1); - g.fillCircle(0, 0, PAWN_R - 4); - g.lineStyle(2, c.ring, 0.9); - g.strokeCircle(0, 0, PAWN_R - 2); - return this.add.container(x, y, [g]); - } - - buildDismissHandler() { - this.input.on('pointerdown', (_ptr, gameObjects) => { - if (this.selectedPawnIdx === null || this.animating) return; - const hitRelevant = gameObjects.some((o) => - this.highlightObjs.includes(o) || - PCOLORS.some((c) => this.pawnObjs[c]?.includes(o)) - ); - if (!hitRelevant) { - this.clearHighlights(); - this.showMovablePawnHints(); - } - }); - } - - // ── Game flow ───────────────────────────────────────────────────────────── - initGame() { - this.clearHighlights(); - this.animating = false; - this.selectedPawnIdx = null; - // Player order: red (human) first, then opponents. - this.gs = createInitialState(['red', 'blue', 'yellow', 'green']); - this.refreshAllPawns(); - this.updateDiceDisplay(); - this.updateButtons(); - this.moveTurnIndicator('red', true); - this.setStatus('Your turn — roll the dice'); - } - - refreshAllPawns() { - // Track stack offsets when multiple pawns share a track cell - const stackCounts = new Map(); - for (const color of PCOLORS) { - for (let i = 0; i < 4; i++) { - const p = this.gs.pawns[color][i]; - const obj = this.pawnObjs[color][i]; - let { x, y } = this.pawnPositionForRender(p, color, i, stackCounts); - obj.setPosition(x, y); - obj.setScale(this.pawnScaleAt(p)); - } - } - } - - pawnPositionForRender(p, color, slotIdx, stackCounts) { - if (p.loc === 'nest') return nestSlotsWorld(color)[slotIdx]; - if (p.loc === 'home') return homeStackSlots(color)[Math.min(slotIdx, 3)]; - if (p.track !== undefined) { - const { col, row } = trackXY(p.track); - const base = cellWorld(col, row); - const key = `t${p.track}`; - const n = stackCounts.get(key) ?? 0; - stackCounts.set(key, n + 1); - // Side-by-side micro-offset for shared squares - const dx = (n % 2 === 0) ? -7 : 7; - const dy = n < 2 ? -3 : 6; - return { x: base.x + dx, y: base.y + dy }; - } - if (p.home !== undefined) { - const { col, row } = homeXY(color, p.home); - return cellWorld(col, row); - } - return { x: 0, y: 0 }; - } - - pawnScaleAt(p) { - if (p.loc === 'nest') return 0.85; - if (p.loc === 'home') return 0.75; - return 1; - } - - // ── Roll handling ───────────────────────────────────────────────────────── - onRollClick() { - if (this.animating || this.gs.phase !== 'roll' || this.gs.currentPlayer !== 'red') return; - this.rollDiceFlow(); - } - - rollDiceFlow() { - this.animating = true; - this.updateButtons(); - const next = rollDice(this.gs); - const [d1, d2] = next.dice; - - this.animateDiceRoll([d1, d2], () => { - this.gs = next; - this.updateDiceDisplay(); - - // Three-doubles penalty path (logic already moved pawn to nest, ended turn) - if (this.gs.consecutiveDoubles === 0 && this.gs.phase === 'roll' - && this.gs.movesLeft.length === 0 && d1 === d2) { - // We rolled doubles but penalty triggered — refresh and continue - this.refreshAllPawns(); - this.setStatus('Three doubles — penalty applied!'); - this.animating = false; - this.afterTurn(); - return; - } - - if (this.gs.phase === 'move' && !hasAnyMove(this.gs)) { - this.setStatus('No legal moves — turn passed'); - this.time.delayedCall(1200, () => { - // Skip remaining dice; force turn end. - this.gs.movesLeft = []; - this.gs.lastWasDoubles = false; - this.endCurrentTurn(); - this.animating = false; - this.afterTurn(); - }); - return; - } - - this.animating = false; - this.updateButtons(); - if (this.gs.currentPlayer !== 'red') { - this.time.delayedCall(600, () => this.runAITurnMoves()); - } else { - this.setStatus('Choose a pawn to move'); - this.showMovablePawnHints(); - } - }); - } - - endCurrentTurn() { - // Advance turn manually when applyMove won't (no moves played). - const players = this.gs.players; - const idx = players.indexOf(this.gs.currentPlayer); - this.gs.currentPlayer = players[(idx + 1) % players.length]; - this.gs.consecutiveDoubles = 0; - this.gs.dice = null; - this.gs.movesLeft = []; - this.gs.lastWasDoubles = false; - this.gs.phase = 'roll'; - } - - // ── Pawn input (human) ──────────────────────────────────────────────────── - onPawnClick(color, pawnIdx) { - if (this.animating) return; - if (this.gs.phase !== 'move') return; - if (color !== 'red' || this.gs.currentPlayer !== 'red') return; - - const moves = getValidMoves(this.gs).filter((m) => m.pawnIdx === pawnIdx); - if (moves.length === 0) { - this.flashPawn(color, pawnIdx); + async prompt() { + const gs = this.gs; + this.clearSelection(); + if (L.turnDone(gs)) { + const forfeit = gs.movesLeft.filter((d) => d > 6); + if (!this.settings.confirm) { this.busy = true; await this.wait(350 * this.k); this.endRoll(); return; } + this.setStatus('Roll finished', `${forfeit.length ? `The +${forfeit.join(' +')} can't be used and is forfeited. ` : ''}Done (Space) or tap the dice tray — or Undo (Z).`); + this.showMovable([]); + this.refreshHud(); return; } - this.clearHighlights(); - this.selectedPawnIdx = pawnIdx; - this.pulsePawn(color, pawnIdx); - this.showDestinationHighlights(moves); + const valid = L.getValidMoves(gs); + if (this.settings.autoForced && valid.length === 1) { + this.busy = true; + this.setStatus('Forced move', L.moveText(valid[0])); + this.refreshHud(); + await this.wait(450 * this.k); + await this.execute(valid[0], true); + return; + } + this.setStatus('Your move', 'Click a glowing pawn, then a marker. Or tap a move chip first to choose which number to play.'); + this.showMovable(this.filtered(valid)); + this.refreshHud(); } - showDestinationHighlights(moves) { - // Group by destination world position - const groups = new Map(); + filtered(moves) { + if (this.chip === null) return moves; + const v = this.gs.movesLeft[this.chip]; + return moves.filter((m) => !m.combine && m.dieUsed === v); + } + + showMovable(moves) { + for (const g of this.glows) g.destroy(); + this.glows = []; + const seen = new Set(); for (const m of moves) { - const wp = this.destWorld(m.to, m.player); - const key = `${Math.round(wp.x)}_${Math.round(wp.y)}`; - if (!groups.has(key)) groups.set(key, { wp, moves: [] }); - groups.get(key).moves.push(m); - } - for (const { wp, moves: ms } of groups.values()) { - const dot = this.add.graphics().setDepth(DEPTH.highlight); - dot.fillStyle(UI.accent, 0.85); - dot.fillCircle(wp.x, wp.y, 18); - dot.lineStyle(3, 0xffffff, 0.6); - dot.strokeCircle(wp.x, wp.y, 18); - this.tweens.add({ targets: dot, alpha: { from: 0.85, to: 0.25 }, duration: 600, yoyo: true, repeat: -1 }); - const zone = this.add.zone(wp.x, wp.y, CELL, CELL) - .setInteractive({ useHandCursor: true }) - .setDepth(DEPTH.highlight); - zone.on('pointerdown', () => this.onDestinationClick(ms)); - this.highlightObjs.push(dot, zone); + const key = m.from === L.NEST ? 'nest' : m.pawnIdx; + if (seen.has(key)) continue; + seen.add(key); + const it = this.pawns.get(HUMAN, m.pawnIdx); + const g = this.add.image(it.x, it.y - 12, 'pc-glow').setDepth(D.glow).setScale(m.from === L.NEST ? 0.95 : 1.05); + this.tweens.add({ targets: g, alpha: { from: 0.3, to: 0.9 }, duration: 760, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.glows.push(g); } } - destWorld(to, color) { - if (to.loc === 'home') return homeStackSlots(color)[0]; - if (to.track !== undefined) { - const { col, row } = trackXY(to.track); - return cellWorld(col, row); - } - if (to.home !== undefined) { - const { col, row } = homeXY(color, to.home); - return cellWorld(col, row); - } - return { x: 0, y: 0 }; + canMoveNow() { return !this.ended && !this.busy && !this.modal && this.phase === 'move' && this.gs.currentPlayer === HUMAN; } + + movesForPawn(it) { + const valid = this.filtered(L.getValidMoves(this.gs)); + const p = this.gs.pawns[HUMAN][it.idx]; + if (p === L.NEST) return valid.filter((m) => m.from === L.NEST); + return valid.filter((m) => m.pawnIdx === it.idx); } - onDestinationClick(candidateMoves) { - if (this.animating) return; - // Prefer the move that uses the SMALLEST die (preserves flexibility), - // but prefer bonus 10/20 last so base dice get used first. - const sorted = [...candidateMoves].sort((a, b) => { - const av = a.combineDice ? 100 : a.dieUsed; - const bv = b.combineDice ? 100 : b.dieUsed; - return av - bv; - }); - const move = sorted[0]; - this.clearHighlights(); - this.executeMove(move, () => this.afterMove()); - } - - afterMove() { - if (this.gs.phase === 'game_over') { this.onGameOver(); return; } - if (this.gs.currentPlayer === 'red' && this.gs.phase === 'move') { - if (!hasAnyMove(this.gs)) { - this.setStatus('No more legal moves — turn passes'); - this.time.delayedCall(900, () => { - this.gs.movesLeft = []; - this.gs.lastWasDoubles = false; - this.endCurrentTurn(); - this.afterTurn(); - }); - return; - } - this.setStatus('Choose a pawn'); - this.updateButtons(); - this.showMovablePawnHints(); + onPointerDown(p, over) { + if (over?.length) return; + if (!this.canMoveNow()) return; + // a marker of the current selection? + if (this.sel) { + const mk = this.markers.find((q) => Math.hypot(q.x - p.x, q.y - p.y) < 26); + if (mk) { this.execute(mk.move); return; } + } + const it = this.pawns.pick(HUMAN, p.x, p.y); + if (!it) { this.clearSelection(); return; } + const moves = this.movesForPawn(it); + if (!moves.length) { + this.tweens.add({ targets: it.img, x: { from: it.x - 4, to: it.x + 4 }, duration: 50, yoyo: true, repeat: 2, onComplete: () => it.img.setX(it.x) }); return; } - if (this.gs.phase === 'roll') { - this.afterTurn(); - } else { - // AI continues - this.time.delayedCall(450, () => this.runAITurnMoves()); - } - } - - afterTurn() { - this.updateButtons(); - if (this.gs.currentPlayer === 'red') { - this.moveTurnIndicator('red'); - this.setStatus('Your turn — roll the dice'); - } else { - const opp = this.opponents[['blue', 'yellow', 'green'].indexOf(this.gs.currentPlayer)]; - this.setStatus(`${opp?.name ?? this.gs.currentPlayer}'s turn`); - // Start AI dice roll only after the indicator has finished travelling - this.moveTurnIndicator(this.gs.currentPlayer, false, () => { - this.time.delayedCall(250, () => this.runAITurn()); - }); - } - } - - // ── AI turn ─────────────────────────────────────────────────────────────── - runAITurn() { - if (this.animating) return; - if (this.gs.currentPlayer === 'red') return; - if (this.gs.phase !== 'roll') return; - this.animating = true; - this.updateButtons(); - - const next = rollDice(this.gs); - const [d1, d2] = next.dice; - this.animateDiceRoll([d1, d2], () => { - this.gs = next; - this.updateDiceDisplay(); - - if (this.gs.phase === 'roll') { - // Three-doubles penalty triggered inside rollDice - this.refreshAllPawns(); - this.animating = false; - this.afterTurn(); - return; - } - - if (!hasAnyMove(this.gs)) { - this.time.delayedCall(900, () => { - this.gs.movesLeft = []; - this.gs.lastWasDoubles = false; - this.endCurrentTurn(); - this.animating = false; - this.afterTurn(); - }); - return; - } - this.runAITurnMoves(); - }); - } - - runAITurnMoves() { - if (this.gs.phase !== 'move') { this.animating = false; this.afterTurn(); return; } - this.animating = true; - const moves = chooseMoves(this.gs); - if (moves.length === 0) { - // Force turn end if AI somehow returns no moves - this.gs.movesLeft = []; - this.gs.lastWasDoubles = false; - this.endCurrentTurn(); - this.animating = false; - this.afterTurn(); + // double-tap: play this pawn's longest move + if (this.lastTapped === it && this.time.now - this.lastTapAt < 320) { + this.lastTapped = null; + this.execute(moves.reduce((a, b) => ((b.to - b.from) > (a.to - a.from) ? b : a))); return; } - this.playAIMoves(moves, 0); + this.lastTapped = it; this.lastTapAt = this.time.now; + if (this.sel && this.sel.it === it) { this.clearSelection(); return; } + this.select(it, moves); } - playAIMoves(moves, i) { - if (i >= moves.length || this.gs.phase === 'game_over') { - this.animating = false; - if (this.gs.phase === 'game_over') { this.onGameOver(); return; } - this.afterTurn(); + select(it, moves) { + this.clearSelection(); + this.sel = { it, moves }; + this.pawns.setLifted(it, true); + tap(this); + this.drawMarkers(moves); + } + + clearSelection() { + if (this.sel?.it) this.pawns.setLifted(this.sel.it, false); + this.sel = null; + this.markers = []; + this.markG?.clear(); + this.pathG?.clear(); + for (const t of this.markTexts ?? []) t.setVisible(false); + } + + landingOf(m) { + if (m.to === L.HOME) return homeSlot(HUMAN, m.pawnIdx); + return cellOf(m.player, m.to); + } + + drawMarkers(moves, alpha = 1) { + const g = this.markG; + g.clear(); + this.markers = []; + for (const t of this.markTexts) t.setVisible(false); + moves.forEach((m, i) => { + const pos = this.landingOf(m); + const col = m.hit ? 0xe8553c : m.to === L.HOME ? 0xf5c542 : 0x3fd0a0; + g.fillStyle(col, 0.38 * alpha).fillCircle(pos.x, pos.y, 22); + g.lineStyle(3, col, 0.95 * alpha).strokeCircle(pos.x, pos.y, 22); + const label = (m.combine ? `${m.combine[0]}+${m.combine[1]}` : m.dieUsed > 6 ? `+${m.dieUsed}` : String(m.dieUsed)) + (m.hit ? '✶' : ''); + while (this.markTexts.length <= i) this.markTexts.push(this.add.text(0, 0, '', { fontFamily: DISPLAY_FONT, fontSize: '18px', color: '#ffffff', stroke: '#1a0c04', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.mark + 3.2)); + this.markTexts[i].setText(label).setPosition(pos.x, pos.y).setAlpha(alpha).setVisible(true); + this.markers.push({ x: pos.x, y: pos.y, move: m }); + this.drawPath(m, alpha * 0.8); + }); + } + + drawPath(m, alpha) { + const g = this.pathG; + const pts = L.movePath(m).map((p) => (p === L.HOME ? homeSlot(HUMAN, m.pawnIdx) : cellOf(m.player, p))); + g.fillStyle(m.hit ? 0xe8553c : 0xfff1c2, 0.7 * alpha); + pts.slice(0, -1).forEach((q) => g.fillCircle(q.x, q.y, 5)); + } + + onPointerMove(p) { + if (!this.settings.hints || this.sel || !this.canMoveNow()) { if (this.hoverIt && !this.sel) { this.hoverIt = null; this.markG.clear(); this.pathG.clear(); for (const t of this.markTexts) t.setVisible(false); } this.dangerHover(p); return; } + const it = this.pawns.pick(HUMAN, p.x, p.y); + this.dangerHover(p); + if (it === this.hoverIt) return; + this.hoverIt = it; + this.markG.clear(); this.pathG.clear(); + for (const t of this.markTexts) t.setVisible(false); + if (!it) return; + const moves = this.movesForPawn(it); + if (moves.length) { this.drawMarkers(moves, 0.45); this.markers = []; } + } + + onChip(i) { + if (!this.canMoveNow() || L.turnDone(this.gs)) return; + this.chip = this.chip === i ? null : i; + tap(this); + const valid = this.filtered(L.getValidMoves(this.gs)); + if (this.chip !== null && !valid.length) { + toast(this, `No pawn can play the ${this.gs.movesLeft[i] > 6 ? '+' : ''}${this.gs.movesLeft[i]} right now.`, { depth: D.modal }); + this.chip = null; + } + this.clearSelection(); + this.showMovable(this.filtered(L.getValidMoves(this.gs))); + this.refreshHud(); + } + + async execute(m, forced = false) { + if (!forced && !this.canMoveNow()) return; + this.busy = true; + this.clearSelection(); + this.clearHint(); + this.showMovable([]); + this.undoStack.push({ gs: this.gs, chip: this.chip }); + this.chip = null; + await this.playMove(m); + if (this.ended) return; + if (this.gs.phase === 'game_over') { this.endGame(); return; } + this.busy = false; + this.prompt(); + } + + // Animate one move (hops, capture, homecoming) and commit it. + async playMove(m) { + const before = this.gs; + const after = L.applyMove(before, m); + const c = m.player; + const fast = c !== HUMAN && this.settings.skipAI; + const path = L.movePath(m); + const spots = this.pawns.spots(after); + const per = fast ? 45 : Math.max(62, 150 - path.length * 5) * Math.min(1.25, this.k); + await this.pawns.hopAlong(c, m.pawnIdx, path, spots[c][m.pawnIdx], { per }); + if (this.ended) return; + if (m.hit) { + bonk(this); + if (!fast) this.cameras.main.shake(130, 0.003); + const v = this.pawns.get(m.hit.color, m.hit.pawnIdx); + this.spark(v.x, v.y - 10, 0xffd27a); + await this.pawns.knockHome(m.hit.color, m.hit.pawnIdx, fast ? 260 : 560); + if (after.opts.captureBonus) this.flyCoin(v.x, v.y, c, '+20'); + this.hud.emotion(m.hit.color, 'upset'); + if (c !== HUMAN) { this.hud.emotion(c, 'happy'); if (Math.random() < 0.6) this.hud.say(c, pick(SPEECH.capture)); } + else if (Math.random() < 0.6) this.hud.say(m.hit.color, pick(SPEECH.captured)); + } + if (m.to === L.HOME) { + chime(this); + this.bloom(c); + if (after.opts.homeBonus) this.flyCoin(spots[c][m.pawnIdx].x, spots[c][m.pawnIdx].y, c, '+10'); + if (c !== HUMAN && Math.random() < 0.5) this.hud.say(c, pick(SPEECH.home)); + } + if (after.stats[c].blockades > before.stats[c].blockades && c !== HUMAN && Math.random() < 0.3) this.hud.say(c, pick(SPEECH.blockade)); + this.gs = L.logTurn(after, c, L.moveText(m)); + this.tray.setUsage(this.gs.movesLeft); + await this.pawns.sync(this.gs, { dur: 140 }); + this.refreshHud(); + } + + async undo() { + if (!this.canMoveNow() || !this.undoStack.length) return; + this.busy = true; + this.clearSelection(); + this.clearHint(); + this.showMovable([]); + const snap = this.undoStack.pop(); + this.gs = snap.gs; + this.chip = null; + this.tray.setUsage(this.gs.movesLeft); + tap(this); + await this.pawns.sync(this.gs, { dur: 240 }); + if (this.ended) return; + this.busy = false; + await this.promptNoForce(); + } + + async promptNoForce() { + // don't instantly re-play a forced move you just undid + const keep = this.settings.autoForced; + this.settings.autoForced = false; + await this.prompt(); + this.settings.autoForced = keep; + } + + onTrayClick() { if (this.canMoveNow() && L.turnDone(this.gs)) this.endRoll(); } + + async endRoll() { + if (this.ended) return; + if (this.gs.phase === 'game_over') { this.endGame(); return; } + this.busy = true; + this.clearSelection(); + this.clearHint(); + this.showMovable([]); + const c = this.gs.currentPlayer; + this.gs = L.finishRoll(this.gs); + this.undoStack = []; + this.chip = null; + this.phase = 'between'; + this.refreshHud(); + await this.tray.clear({ fast: c !== HUMAN && this.settings.skipAI }); + if (this.gs.currentPlayer === c && this.gs.phase === 'roll' && c === HUMAN) { this.humanRollPrompt(); return; } + this.startTurn(); + } + + // ── hint ──────────────────────────────────────────────────────────────────── + showHint() { + if (!this.canMoveNow() || L.turnDone(this.gs)) return; + this.clearSelection(); + this.clearHint(); + const h = hint(this.gs); + let s = this.gs; + h.moves.forEach((m, i) => { + const it = this.pawns.get(HUMAN, m.pawnIdx); + const from = s.pawns[HUMAN][m.pawnIdx] === L.NEST ? { x: it.x, y: it.y } : cellOf(HUMAN, s.pawns[HUMAN][m.pawnIdx]); + const to = m.to === L.HOME ? homeSlot(HUMAN, m.pawnIdx) : cellOf(HUMAN, m.to); + this.arrow(from ?? { x: it.x, y: it.y }, to, i + 1); + s = L.applyMove(s, m); + }); + this.setStatus('Hint', `${h.moves.map((m) => L.moveText(m)).join('; ')} — ${h.reason}.`); + } + + arrow(a, b, n) { + const g = this.hintG; + const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2 - Math.min(80, Math.hypot(b.x - a.x, b.y - a.y) * 0.3); + const curve = new Phaser.Curves.QuadraticBezier(new Phaser.Math.Vector2(a.x, a.y), new Phaser.Math.Vector2(mx, my), new Phaser.Math.Vector2(b.x, b.y)); + const pts = curve.getPoints(18); + for (const [w, col, al] of [[7, 0x1a0c04, 0.5], [4, 0xffd54a, 1]]) { + g.lineStyle(w, col, al); + g.beginPath(); g.moveTo(a.x, a.y); pts.forEach((q) => g.lineTo(q.x, q.y)); g.strokePath(); + } + const end = pts[pts.length - 1], prev = pts[pts.length - 3] ?? a; + const ea = Math.atan2(end.y - prev.y, end.x - prev.x); + g.fillStyle(0xffd54a, 1).fillTriangle(end.x, end.y, end.x - Math.cos(ea - 0.45) * 20, end.y - Math.sin(ea - 0.45) * 20, end.x - Math.cos(ea + 0.45) * 20, end.y - Math.sin(ea + 0.45) * 20); + this.hintTexts.push(this.add.text(a.x, a.y - 30, String(n), { fontFamily: DISPLAY_FONT, fontSize: '18px', color: '#1a0c04', backgroundColor: '#ffd54a', padding: { x: 6, y: 1 } }).setOrigin(0.5).setDepth(D.mark + 5)); + } + clearHint() { this.hintG?.clear(); for (const t of this.hintTexts ?? []) t.destroy(); this.hintTexts = []; } + + // ── danger overlay ────────────────────────────────────────────────────────── + drawDanger() { + for (const r of this.rings) r.destroy(); + this.rings = []; + this.dangerList = []; + if (!this.settings.danger || this.gs.phase === 'game_over' || !this.pawns) return; + const rep = dangerReport(this.gs, HUMAN); + this.dangerList = rep; + for (const d of rep) { + if (d.risk < 0.04) continue; + const it = this.pawns.get(HUMAN, d.pawnIdx); + const r = this.add.image(it.x, it.y - 10, 'pc-ring').setDepth(D.glow - 0.5).setScale(0.75 + d.risk * 0.6).setAlpha(0.25 + d.risk); + this.tweens.add({ targets: r, alpha: { from: 0.2 + d.risk * 0.6, to: 0.05 }, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + this.rings.push(r); + } + } + + dangerHover(p) { + if (!this.settings.danger || !this.dangerList?.length || this.sel) return; + const it = this.pawns.pick(HUMAN, p.x, p.y); + const d = it && this.dangerList.find((q) => q.pawnIdx === it.idx); + if (d && this.dangerShown !== it.idx) { + this.dangerShown = it.idx; + this.prevStatus = [this.hud.status.text, this.hud.sub.text]; + this.dangerText = `At risk: ${Math.round(d.risk * 100)}%`; + this.setStatus(this.dangerText, d.by.map((b) => `${this.nameOf(b.color)} ${Math.round(b.p * 100)}%`).join(' · ') + ' — chance of being captured before your next turn.'); + } else if (!d && this.dangerShown !== undefined && this.dangerShown !== null) { + this.dangerShown = null; + // only restore if nothing else has written to the card meanwhile + if (this.prevStatus && this.hud.status.text === this.dangerText) this.setStatus(...this.prevStatus); + } + } + + // ── AI ────────────────────────────────────────────────────────────────────── + async aiTurn() { + if (this.ended) return; + const c = this.gs.currentPlayer; + this.phase = 'ai'; + this.busy = true; + const fast = this.settings.skipAI; + const t = aiTiming(this.skills[c], fast ? 0.4 : this.k); + this.setStatus(`${this.names[c]}'s roll`, this.gs.consecutiveDoubles ? 'Doubles — rolling again…' : 'Shaking the dice…'); + this.refreshHud(); + await this.wait(t.think); + if (this.ended) return; + await this.rollFor(c); + } + + async aiMoves() { + if (this.ended) return; + const c = this.gs.currentPlayer; + const fast = this.settings.skipAI; + const t = aiTiming(this.skills[c], fast ? 0.4 : this.k); + this.phase = 'ai'; + if (!L.hasAnyMove(this.gs)) { + this.setStatus(`${this.names[c]} can't move`, 'Nothing legal with that roll.'); + await this.wait(900 * this.k); + this.endRoll(); return; } - this.executeMove(moves[i], () => { - this.time.delayedCall(280, () => this.playAIMoves(moves, i + 1)); + this.setStatus(`${this.names[c]} is thinking…`, `Playing ${this.gs.movesLeft.join(' · ')}`); + await this.wait(40); + const plan = chooseMoves(this.gs, this.skills[c]); + await this.wait(t.think * 0.5); + for (const m of plan) { + if (this.ended) return; + // re-validate (plans are built on the same state, but stay safe) + const legal = L.getValidMoves(this.gs).find((q) => q.pawnIdx === m.pawnIdx && q.to === m.to && q.dieUsed === m.dieUsed && !!q.combine === !!m.combine); + if (!legal) break; + await this.playMove(legal); + if (this.gs.phase === 'game_over') { this.endGame(); return; } + await this.wait(fast ? 60 : t.between); + } + // play anything the plan left (should be nothing) + let guard = 0; + while (!L.turnDone(this.gs) && guard++ < 6) { + const more = chooseMoves(this.gs, this.skills[c]); + if (!more.length) break; + await this.playMove(more[0]); + if (this.gs.phase === 'game_over') { this.endGame(); return; } + } + await this.wait(fast ? 80 : 300 * this.k); + this.endRoll(); + } + + // ── end ───────────────────────────────────────────────────────────────────── + async endGame() { + if (this.phase === 'over') return; + this.phase = 'over'; + this.busy = true; + this.clearSelection(); + this.clearHint(); + this.showMovable([]); + this.cup.setEnabled(false); + this.refreshHud(); + const w = this.gs.winner; + const human = w === HUMAN; + this.banner(human ? 'ALL FOUR HOME!' : `${this.names[w].toUpperCase()} WINS`, LACQUER[w].hex, 0.9, false); + if (human) { playSound(this, SFX.CASINO_WIN); this.confetti(140); } + else playSound(this, SFX.CASINO_LOSE); + for (const c of this.gs.players) { + if (c === HUMAN) continue; + this.hud.emotion(c, c === w ? 'happy' : 'upset'); + } + if (!human) this.hud.say(w, pick(SPEECH.win)); + else this.hud.say(this.gs.players[1], pick(SPEECH.lose)); + this.setStatus(human ? 'You win!' : `${this.names[w]} wins`, 'All four pawns are home.'); + this.postHistory().catch(() => {}); + await this.wait(2000); + if (this.ended) return; + this.hud.hidePortraits(); + this.modal = openEndScreen(this, { + gs: this.gs, names: this.names, human: HUMAN, depth: D.end, + onPlayAgain: () => this.scene.restart(this.initData), + onMenu: () => this.scene.start('GameMenu'), }); } - // ── Move execution + animation ──────────────────────────────────────────── - executeMove(move, onComplete) { - playSound(this, SFX.PIECE_CLICK); - const obj = this.pawnObjs[move.player][move.pawnIdx]; - const from = this.locWorld(move.from, move.player); - const to = this.locWorld(move.to, move.player); - - // Hit animation (opponent pawn slides back to nest) - if (move.hit) { - const oppObj = this.pawnObjs[move.hit.color][move.hit.pawnIdx]; - const oppHome = nestSlotsWorld(move.hit.color)[move.hit.pawnIdx]; - this.tweens.add({ targets: oppObj, x: oppHome.x, y: oppHome.y, duration: 380, ease: 'Quad.easeIn' }); - this.playEmotion(move.hit.color, 'upset'); - } - - obj.setDepth(DEPTH.moving); - const midX = (from.x + to.x) / 2; - const midY = Math.min(from.y, to.y) - 80; - const prog = { t: 0 }; - this.tweens.add({ - targets: prog, t: 1, duration: 380, ease: 'Cubic.easeInOut', - onUpdate: () => { - const t = prog.t; - const inv = 1 - t; - obj.x = inv * inv * from.x + 2 * inv * t * midX + t * t * to.x; - obj.y = inv * inv * from.y + 2 * inv * t * midY + t * t * to.y; - }, - onComplete: () => { - obj.setDepth(DEPTH.pawn); - this.gs = applyMove(this.gs, move); - this.refreshAllPawns(); - this.updateDiceDisplay(); - // Happy emotion when AI captures or homes - if (move.player !== 'red' && (move.hit || move.to.loc === 'home')) { - this.playEmotion(move.player, 'happy'); - } - onComplete?.(); - }, + async postHistory() { + const others = this.gs.players.filter((c) => c !== HUMAN); + await api.post('/history/single-player', { + slug: 'parchisi', score: L.pawnsHome(this.gs, HUMAN), opponentScores: others.map((c) => L.pawnsHome(this.gs, c)), + result: this.gs.winner === HUMAN ? 'win' : 'loss', }); } - locWorld(loc, color) { - if (loc.loc === 'nest') { - // Use a representative nest slot (slot 0) - return nestSlotsWorld(color)[0]; + // ── input ─────────────────────────────────────────────────────────────────── + onButton(k) { + if (this.ended || this.modal) return; + if (k === 'done') this.onTrayClick(); + else if (k === 'undo') this.undo(); + else if (k === 'hint') this.showHint(); + else if (k === 'menu') this.openMenu(); + } + + onKey(e, down) { + if (this.ended) return; + const key = e.key; + if (key === ' ' || e.code === 'Space') { + e.preventDefault?.(); + if (this.modal) return; + if (this.phase === 'move') { if (down && !e.repeat) this.onTrayClick(); return; } + if (down && !e.repeat) this.beginShake(); + else if (!down) this.releaseShake(); + return; } - if (loc.loc === 'home') return homeStackSlots(color)[0]; - if (loc.track !== undefined) { - const { col, row } = trackXY(loc.track); - return cellWorld(col, row); + if (!down || e.repeat) return; + if (key === 'Escape') { if (this.modal) this.closeModal(); else this.openMenu(); return; } + if (this.modal) return; + if (key >= '1' && key <= '6') this.onChip(Number(key) - 1); + else if (key === 'Enter') this.onTrayClick(); + else if (key === 'z' || key === 'Z') this.undo(); + else if (key === 'h' || key === 'H') this.showHint(); + } + + openMenu() { + if (this.modal || this.ended || this.shaking) return; + this.hud.hidePortraits(); + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => new TutorialModal(this.gameDef).open(), + onNewGame: () => this.confirmThen('New game?', 'Abandon this game and set the pawns back in their nests?', () => this.scene.restart(this.initData)), + onLeave: () => this.confirmThen('Leave the veranda?', 'This game will be abandoned.', () => this.scene.start('GameMenu')), + onClose: () => { this.modal = null; this.hud.showPortraits(); this.refreshHud(); }, + }); + } + + confirmThen(heading, text, onYes) { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, depth: D.modal + 5, + onYes: () => { this.modal = null; this.hud.showPortraits(); onYes(); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); }, + }); + } + + closeModal() { this.modal?.close?.(); this.modal = null; this.hud.showPortraits(); } + + changeSetting(key, value) { + this.settings[key] = value; + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + if (key === 'rain') this.rain.setOn(value); + if (key === 'danger') this.drawDanger(); + if (['captureBonus', 'homeBonus', 'threeDoubles', 'shareSafe'].includes(key)) toast(this, 'House rules change from the next game.', { depth: D.modal + 20 }); + } + + // ── flourishes ────────────────────────────────────────────────────────────── + flyCoin(x, y, c, label) { + coin(this); + const img = this.add.image(x, y, 'pc-coin').setDepth(D.fx).setScale(0.3); + const t = this.add.text(x, y - 34, label, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: '#ffe08a', stroke: '#3a2208', strokeThickness: 5 }).setOrigin(0.5).setDepth(D.fx + 1); + const to = this.hud.plateCenter(c); + this.tweens.add({ targets: img, scale: 1.1, duration: 200, ease: 'Back.Out' }); + this.tweens.add({ targets: img, x: to.x, y: to.y, scale: 0.5, delay: 380, duration: 620, ease: 'Cubic.InOut', onComplete: () => { img.destroy(); this.spark(to.x, to.y, 0xffe08a); } }); + this.tweens.add({ targets: t, y: y - 70, alpha: 0, delay: 500, duration: 700, onComplete: () => t.destroy() }); + } + + // a ring of lotus petals opens in the colour's HOME triangle + bloom(c) { + const tri = homeTriangle(c); + const cx = (tri[0].x + tri[1].x + tri[2].x) / 3, cy = (tri[0].y + tri[1].y + tri[2].y) / 3; + for (let i = 0; i < 8; i++) { + const a = (i / 8) * Math.PI * 2; + const pe = this.add.image(cx, cy, `pc-petal-${c}`).setDepth(D.fx).setOrigin(0.5, 1).setRotation(a + Math.PI / 2).setScale(0.1).setAlpha(0.95); + this.tweens.add({ targets: pe, scale: 1, duration: 420, delay: i * 30, ease: 'Back.Out' }); + this.tweens.add({ targets: pe, alpha: 0, delay: 1400, duration: 700, onComplete: () => pe.destroy() }); } - if (loc.home !== undefined) { - const { col, row } = homeXY(color, loc.home); - return cellWorld(col, row); - } - return { x: 0, y: 0 }; + this.spark(cx, cy, 0xfff1c2); } - // ── Highlights and pulsing ──────────────────────────────────────────────── - pulsePawn(color, pawnIdx) { - const obj = this.pawnObjs[color][pawnIdx]; - const ring = this.add.graphics().setDepth(DEPTH.highlight); - ring.lineStyle(3, 0xffd700, 1); - ring.strokeCircle(obj.x, obj.y, PAWN_R + 6); - this.tweens.add({ targets: ring, alpha: { from: 1, to: 0.3 }, duration: 500, yoyo: true, repeat: -1 }); - this.highlightObjs.push(ring); - } - - flashPawn(color, pawnIdx) { - const obj = this.pawnObjs[color][pawnIdx]; - this.tweens.add({ targets: obj, alpha: { from: 1, to: 0.2 }, duration: 100, yoyo: true, repeat: 2 }); - } - - clearHighlights() { - for (const o of this.highlightObjs) o.destroy(); - this.highlightObjs = []; - this.selectedPawnIdx = null; - } - - showMovablePawnHints() { - const moves = getValidMoves(this.gs); - const movable = [...new Set(moves.map((m) => m.pawnIdx))]; - for (const pawnIdx of movable) { - const obj = this.pawnObjs['red'][pawnIdx]; - const px = obj.x; - const py = obj.y; - - // Static glow ring — pulses alpha - const glow = this.add.graphics().setDepth(DEPTH.highlight); - glow.lineStyle(2.5, 0x00e5b0, 0.9); - glow.strokeCircle(px, py, PAWN_R + 6); - this.tweens.add({ targets: glow, alpha: { from: 0.9, to: 0.25 }, duration: 550, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' }); - - // Expanding ripple ring - const ripple = this.add.graphics().setDepth(DEPTH.highlight); - ripple.setPosition(px, py); - ripple.lineStyle(2, 0x00e5b0, 0.75); - ripple.strokeCircle(0, 0, PAWN_R + 6); - this.tweens.add({ targets: ripple, scaleX: 2.0, scaleY: 2.0, alpha: 0, duration: 950, repeat: -1, ease: 'Cubic.easeOut' }); - - this.highlightObjs.push(glow, ripple); + spark(x, y, tint = 0xffe1a0) { + for (let i = 0; i < 10; i++) { + const s = this.add.image(x, y, 'pc-spark').setDepth(D.fx).setScale(0.6 + Math.random() * 0.5).setTint(tint); + const a = Math.random() * Math.PI * 2, r = 30 + Math.random() * 45; + this.tweens.add({ targets: s, x: x + Math.cos(a) * r, y: y + Math.sin(a) * r, alpha: 0, scale: 0.1, duration: 420 + Math.random() * 200, ease: 'Quad.Out', onComplete: () => s.destroy() }); } } - // ── UI updates ──────────────────────────────────────────────────────────── - updateButtons() { - const canRoll = !this.animating - && this.gs.phase === 'roll' - && this.gs.currentPlayer === 'red'; - this.rollBtn?.setEnabled(canRoll); + banner(text, color, scale = 1, small = false) { + this.bannerObj?.destroy(); + const hex = Phaser.Display.Color.IntegerToColor(color).rgba; + const t = this.add.text(0, 0, text, { + fontFamily: DISPLAY_FONT, fontSize: small ? '60px' : '96px', color: hex, stroke: '#1a0c04', strokeThickness: small ? 9 : 13, + shadow: { offsetX: 0, offsetY: 6, color: '#000', blur: 14, fill: true }, + }).setOrigin(0.5); + const cont = this.add.container(BANNER.x, BANNER.y - 120, [t]).setDepth(D.banner).setScale(scale * 0.4).setAlpha(0); + this.bannerObj = cont; + this.tweens.add({ targets: cont, y: BANNER.y, scale, alpha: 1, duration: 380, ease: 'Back.Out' }); + this.tweens.add({ targets: cont, alpha: 0, y: BANNER.y - 40, delay: small ? 900 : 1700, duration: 420, onComplete: () => { cont.destroy(); if (this.bannerObj === cont) this.bannerObj = null; } }); } - setStatus(msg) { this.statusText?.setText(msg); } - - // ── Game over ───────────────────────────────────────────────────────────── - onGameOver() { - const winner = this.gs.winner; - const isHuman = winner === 'red'; - if (!isHuman) this.playEmotion(winner, 'happy'); - else { - for (const c of ['blue', 'yellow', 'green']) this.playEmotion(c, 'upset'); + confetti(count = 100) { + const colors = [0xb8322a, 0x2a5d9f, 0xdc9f1e, 0x2f7d4a, 0xffffff, 0xf29a1c]; + for (let i = 0; i < count; i++) { + const x = BOARD_RECT.x + Math.random() * BOARD_RECT.w; + const r = this.add.rectangle(x, -20 - Math.random() * 120, 8 + Math.random() * 6, 5 + Math.random() * 4, pick(colors)).setDepth(D.fx).setRotation(Math.random() * 6); + this.tweens.add({ targets: r, y: GAME_HEIGHT + 60, x: x + Phaser.Math.Between(-120, 120), rotation: r.rotation + Phaser.Math.FloatBetween(-8, 8), duration: 1700 + Math.random() * 1200, ease: 'Sine.In', onComplete: () => r.destroy() }); } - - const overlay = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, 720, 320, 0x0a0e14, 0.92) - .setStrokeStyle(3, UI.accent).setDepth(DEPTH.banner); - const oppName = (() => { - const i = ['blue', 'yellow', 'green'].indexOf(winner); - return i >= 0 ? (this.opponents[i]?.name ?? winner) : 'You'; - })(); - const msg = isHuman - ? '🎉 You Win!\nAll four pawns home!' - : `${oppName} wins this round.\nBetter luck next game!`; - const txt = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2 - 50, msg, { - fontFamily: '"Julius Sans One"', - fontSize: '32px', - color: isHuman ? '#ffd700' : UI.textHex, - align: 'center', - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); - - new Button(this, GAME_WIDTH / 2 - 100, GAME_HEIGHT / 2 + 80, 'Play Again', () => { - overlay.destroy(); txt.destroy(); this.initGame(); - }, { width: 170, fontSize: 22 }).setDepth(DEPTH.banner + 1); - - new Button(this, GAME_WIDTH / 2 + 100, GAME_HEIGHT / 2 + 80, 'Leave', () => { - this.scene.start('GameMenu'); - }, { variant: 'ghost', width: 170, fontSize: 22 }).setDepth(DEPTH.banner + 1); } + + wait(ms) { return new Promise((r) => this.time.delayedCall(Math.max(0, ms), r)); } } - - - diff --git a/src/games/parchisi/ParchisiHud.js b/src/games/parchisi/ParchisiHud.js new file mode 100644 index 0000000..0304198 --- /dev/null +++ b/src/games/parchisi/ParchisiHud.js @@ -0,0 +1,179 @@ +// ParchisiHud.js — around the board: a carved seat plaque per player +// (portrait, name, skill, pawns home, nest / board counts, captures, active +// lamp, opening die), the status card, the move chips, the buttons, the +// table-talk card and speech bubbles. + +import { Button } from '../../ui/Button.js'; +import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { PLATES, plateParts, STATUS, CHIPS, BUTTONS, BTN, TALK, chipRect } from './ParchisiLayout.js'; +import { DISPLAY_FONT, SERIF, PRINT_FONT, LACQUER } from './ParchisiArt.js'; +import { pawnsHome, pawnsInNest } from './ParchisiLogic.js'; + +export class Hud { + constructor(scene, depth, { players, human, names, skills, opponents, onButton, onChip }) { + this.scene = scene; + this.depth = depth; + this.players = players; + this.human = human; + this.names = names; + this.skills = skills; + this.opponents = opponents; + this.onButton = onButton; + this.onChip = onChip; + this.seats = {}; + this.buttons = {}; + this.chips = []; + this.bubbles = {}; + } + + build() { + const s = this.scene, D = this.depth; + for (const c of ['green', 'yellow', 'red', 'blue']) { + const P = PLATES[c]; + const img = s.add.image(P.x - 16, P.y - 16, 'pc-plate').setOrigin(0).setDepth(D); + if (!this.players.includes(c)) { + img.setAlpha(0.45); + s.add.text(P.x + P.w / 2, P.y + P.h / 2, 'empty seat', { fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: '#e8d3b0' }).setOrigin(0.5).setDepth(D + 1).setAlpha(0.6); + continue; + } + const parts = plateParts(c); + const L = LACQUER[c]; + const band = s.add.graphics().setDepth(D + 1); + band.fillStyle(L.hex, 1).fillRoundedRect(P.x + 14, P.y + 14, 10, P.h - 28, 4); + const ring = s.add.graphics().setDepth(D + 1); + const pp = parts.portrait; + s.add.circle(pp.x, pp.y, pp.r + 5, L.hex, 1).setDepth(D + 1); + const portrait = c === this.human + ? createPlayerPortrait(s, pp.x, pp.y, pp.r, D + 2, 'ParchisiGame') + : createOpponentPortrait(s, this.opponents[c] ?? { id: 'bot', spriteIndex: 0 }, pp.x, pp.y, pp.r, D + 2); + const nm = this.names[c].length > 13 ? this.names[c].slice(0, 12) + '…' : this.names[c]; + s.add.text(parts.name.x, parts.name.y, nm, { fontFamily: DISPLAY_FONT, fontSize: '24px', color: '#fbeed6' }).setOrigin(0, 0.5).setDepth(D + 1); + if (c !== this.human) { + const k = this.skills[c]; + s.add.text(parts.skill.x, parts.skill.y, '●'.repeat(k) + '○'.repeat(5 - k), { fontFamily: SERIF, fontSize: '13px', color: '#f0c96a' }).setOrigin(1, 0.5).setDepth(D + 1); + } + const icons = [0, 1, 2, 3].map((i) => s.add.image(parts.pawns.x + i * 34, parts.pawns.y + 14, `pc-pawn-${c}`).setScale(0.62).setOrigin(0.5, 0.8).setDepth(D + 1)); + const counts = s.add.text(parts.counts.x, parts.counts.y, '', { fontFamily: SERIF, fontSize: '15px', color: '#f3e2c4' }).setOrigin(0, 0.5).setDepth(D + 1); + const caps = s.add.text(parts.counts.x, parts.counts.y + 26, '', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#e8c88a' }).setOrigin(0, 0.5).setDepth(D + 1); + const dieText = s.add.text(parts.dice.x, parts.dice.y, '', { fontFamily: DISPLAY_FONT, fontSize: '30px', color: '#ffffff', backgroundColor: L.base, padding: { x: 10, y: 2 } }).setOrigin(0.5).setDepth(D + 2).setVisible(false); + this.seats[c] = { parts, ring, portrait, icons, counts, caps, dieText }; + } + // status card + s.add.image(STATUS.x - 14, STATUS.y - 14, 'pc-card-status').setOrigin(0).setDepth(D); + this.status = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 52, '', { fontFamily: DISPLAY_FONT, fontSize: '30px', color: '#2b3f7a', align: 'center', wordWrap: { width: STATUS.w - 40 } }).setOrigin(0.5).setDepth(D + 1); + this.sub = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 128, '', { fontFamily: SERIF, fontSize: '16px', color: '#3a3022', align: 'center', wordWrap: { width: STATUS.w - 44 }, lineSpacing: 3 }).setOrigin(0.5).setDepth(D + 1); + // chips + s.add.image(CHIPS.x - 14, CHIPS.y - 14, 'pc-card-chips').setOrigin(0).setDepth(D); + s.add.text(CHIPS.x + 18, CHIPS.y + 16, 'MOVES TO PLAY', { fontFamily: PRINT_FONT, fontSize: '12px', color: '#6a5a40' }).setOrigin(0, 0.5).setDepth(D + 1); + this.chipHint = s.add.text(CHIPS.x + CHIPS.w - 18, CHIPS.y + 16, '', { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#6a5a40' }).setOrigin(1, 0.5).setDepth(D + 1); + for (let i = 0; i < 6; i++) { + const img = s.add.image(0, 0, 'pc-chip').setOrigin(0).setDepth(D + 1).setVisible(false); + const txt = s.add.text(0, 0, '', { fontFamily: DISPLAY_FONT, fontSize: '28px', color: '#2a1a08' }).setOrigin(0.5).setDepth(D + 2).setVisible(false); + const zone = s.add.zone(0, 0, 74, 56).setDepth(D + 3); + zone.on('pointerdown', () => this.onChip(i)); + this.chips.push({ img, txt, zone, value: null }); + } + this.chipSel = s.add.graphics().setDepth(D + 2); + // buttons + const label = { done: 'Done (Space)', undo: 'Undo (Z)', hint: 'Hint (H)', menu: 'Menu (Esc)' }; + const bg = { done: 0x2f6e3a, undo: 0x7a5212, hint: 0x2b3f7a, menu: 0x4a2a14 }; + for (const [k, b] of Object.entries(BUTTONS)) { + this.buttons[k] = new Button(s, b.x, b.y, label[k], () => this.onButton(k), { width: BTN.w, height: BTN.h, fontSize: 17, bg: bg[k] }).setDepth(D + 3); + if (k !== 'menu') this.buttons[k].setEnabled(false); + } + // table talk + s.add.image(TALK.x - 14, TALK.y - 14, 'pc-card-talk').setOrigin(0).setDepth(D); + s.add.text(TALK.x + 18, TALK.y + 18, 'ON THE VERANDA', { fontFamily: PRINT_FONT, fontSize: '12px', color: '#6a5a40' }).setOrigin(0, 0.5).setDepth(D + 1); + this.talk = [0, 1, 2, 3, 4].map((i) => s.add.text(TALK.x + 20, TALK.y + 44 + i * 23, '', { fontFamily: SERIF, fontSize: '15px', color: '#3a3022', wordWrap: { width: TALK.w - 40 } }).setOrigin(0, 0.5).setDepth(D + 1)); + return this; + } + + refreshSeats(gs) { + for (const c of this.players) { + const st = this.seats[c]; + const home = pawnsHome(gs, c), nest = pawnsInNest(gs, c); + st.icons.forEach((im, i) => im.setAlpha(i < home ? 1 : 0.22)); + st.counts.setText(`Nest ${nest} · Board ${4 - home - nest} · Home ${home}`); + const sx = gs.stats[c]; + st.caps.setText(`Captures ${sx.captures} · Sent home ${sx.captured}`); + st.ring.clear(); + if (gs.currentPlayer === c && gs.phase !== 'game_over') { + const P = PLATES[c], pp = st.parts.portrait; + st.ring.lineStyle(5, 0xf5c542, 1).strokeRoundedRect(P.x - 4, P.y - 4, P.w + 8, P.h + 8, 20); + st.ring.lineStyle(4, 0xf5c542, 1).strokeCircle(pp.x, pp.y, pp.r + 9); + } + } + } + + showOpeningDie(c, face) { + const t = this.seats[c]?.dieText; + if (!t) return; + if (face == null) { t.setVisible(false); return; } + t.setText(String(face)).setVisible(true).setScale(0.3); + this.scene.tweens.add({ targets: t, scale: 1, duration: 260, ease: 'Back.Out' }); + } + + setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); } + + // chips: values = movesLeft; sel = selected chip index (or null); enabled + setChips(values, sel, enabled, hint = '') { + const n = Math.min(6, values.length); + this.chipSel.clear(); + this.chips.forEach((ch, i) => { + const on = i < n; + ch.value = on ? values[i] : null; + ch.img.setVisible(on); ch.txt.setVisible(on); + if (!on) { ch.zone.disableInteractive(); return; } + const r = chipRect(i, n); + const bonus = values[i] > 6; + ch.img.setTexture(bonus ? 'pc-chip-gold' : 'pc-chip').setPosition(r.x, r.y).setScale(r.w / 74, 1).setAlpha(enabled ? 1 : 0.7); + ch.zone.setSize(r.w, r.h); + ch.txt.setText(bonus ? `+${values[i]}` : String(values[i])).setPosition(r.x + r.w / 2 + 2, r.y + r.h / 2 + 2).setFontSize(bonus ? 24 : 30); + ch.zone.setPosition(r.x + r.w / 2, r.y + r.h / 2); + if (enabled) ch.zone.setInteractive({ useHandCursor: true }); else ch.zone.disableInteractive(); + if (sel === i) this.chipSel.lineStyle(4, 0xf5c542, 1).strokeRoundedRect(r.x - 3, r.y - 3, r.w + 8, r.h + 8, 14); + }); + this.chipHint.setText(hint); + } + chipCenter(i, n) { const r = chipRect(i, n); return { x: r.x + r.w / 2, y: r.y + r.h / 2 }; } + + setButton(k, on) { this.buttons[k]?.setEnabled(!!on); } + + setTalk(log) { + const lines = log.slice(-this.talk.length); + this.talk.forEach((t, i) => { + const e = lines[i]; + if (!e) { t.setText(''); return; } + const who = e.color === this.human ? 'You' : this.names[e.color]; + t.setText(`${who}: ${e.text}`).setColor(LACQUER[e.color]?.ink ?? '#3a3022'); + }); + } + + plateCenter(c) { const P = PLATES[c]; return { x: P.x + P.w * 0.7, y: P.y + P.h / 2 }; } + + say(c, text, dur = 2400) { + const st = this.seats[c]; + if (!st || c === this.human) return; + const s = this.scene; + this.bubbles[c]?.destroy(); + const b = st.parts.bubble; + const t = s.add.text(b.x + b.w / 2, b.y + b.h / 2, text, { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#2a1a08', align: 'center', wordWrap: { width: b.w - 30 } }).setOrigin(0.5); + const g = s.add.graphics(); + const up = b.y > PLATES[c].y; + g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + 4, b.w, b.h, 12); + g.fillStyle(0xfbf3df, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 12); + g.lineStyle(2, LACQUER[c].hex, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 12); + const tx = b.x + 70; + if (up) g.fillStyle(0xfbf3df, 1).fillTriangle(tx - 10, b.y + 1, tx + 10, b.y + 1, tx, b.y - 13); + else g.fillStyle(0xfbf3df, 1).fillTriangle(tx - 10, b.y + b.h - 1, tx + 10, b.y + b.h - 1, tx, b.y + b.h + 13); + const cont = s.add.container(0, 0, [g, t]).setDepth(this.depth + 8).setAlpha(0); + this.bubbles[c] = 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.bubbles[c] === cont) delete this.bubbles[c]; } }); + } + + emotion(c, e) { this.seats[c]?.portrait?.playEmotion?.(e); } + hidePortraits() { Object.values(this.seats).forEach((s) => s.portrait?.setVideoVisible?.(false)); } + showPortraits() { Object.values(this.seats).forEach((s) => s.portrait?.setVideoVisible?.(true)); } +} + diff --git a/src/games/parchisi/ParchisiLayout.js b/src/games/parchisi/ParchisiLayout.js new file mode 100644 index 0000000..dd3a735 --- /dev/null +++ b/src/games/parchisi/ParchisiLayout.js @@ -0,0 +1,96 @@ +// ParchisiLayout.js — screen rects for the monsoon-veranda table. Phaser-free +// (tools/verifyParchisi.js checks bounds and overlaps). +// +// ┌ green plate ┐ ┌──────────── rosewood board ────────────┐ ┌ yellow plate ┐ +// │ status card │ │ nests in the corners, lotus HOME in │ │ brass dice │ +// │ move chips │ │ the middle │ │ tray │ +// │ buttons │ │ │ │ chai · cup │ +// │ table talk │ │ │ │ │ +// └ red (you) ┘ └─────────────────────────────────────────┘ └ blue plate ┘ + +import { ORIGIN_X, ORIGIN_Y, BOARD } from './ParchisiBoard.js'; + +export const W = 1920; +export const H = 1080; +export const FRAME = 14; +export const BOARD_RECT = { x: ORIGIN_X - FRAME, y: ORIGIN_Y - FRAME + 2, w: BOARD + FRAME * 2, h: BOARD + FRAME * 2 - 4 }; + +const LX = 22, RX = 1498, CW = 400; +export const PLATE_H = 196; +export const PLATES = { + green: { x: LX, y: 22, w: CW, h: PLATE_H }, + red: { x: LX, y: H - 22 - PLATE_H, w: CW, h: PLATE_H }, + yellow: { x: RX, y: 22, w: CW, h: PLATE_H }, + blue: { x: RX, y: H - 22 - PLATE_H, w: CW, h: PLATE_H }, +}; +export const STATUS = { x: LX, y: 236, w: CW, h: 196 }; +export const CHIPS = { x: LX, y: 444, w: CW, h: 96 }; +export const BTN = { w: 192, h: 46 }; +export const BUTTONS = { + done: { x: LX + 100, y: 576 }, + undo: { x: LX + 300, y: 576 }, + hint: { x: LX + 100, y: 632 }, + menu: { x: LX + 300, y: 632 }, +}; +export const TALK = { x: LX, y: 670, w: CW, h: 160 }; +export const GARLAND = { x: LX, y: 836, w: CW, h: 24 }; +export const TRAY = { x: RX, y: 236, w: CW, h: 430 }; +export const TRAY_WALL = 26; +export const TRAY_FELT = { x: TRAY.x + TRAY_WALL, y: TRAY.y + TRAY_WALL, w: TRAY.w - TRAY_WALL * 2, h: TRAY.h - TRAY_WALL * 2 }; +export const TRAY_WORLD = { w: TRAY_FELT.w, h: TRAY_FELT.h }; +export const DIE_SIZE = 56; +export const CHAI = { x: RX + 10, y: 690, w: 150, h: 140 }; +export const CUP = { x: RX + 290, y: 768, w: 120, h: 150 }; // centre +export const BANNER = { x: ORIGIN_X + BOARD / 2, y: ORIGIN_Y + BOARD / 2 - 60 }; + +export function plateParts(color) { + const P = PLATES[color]; + const top = color === 'green' || color === 'yellow'; + return { + rect: P, + portrait: { x: P.x + 82, y: P.y + P.h / 2, r: 62 }, + name: { x: P.x + 164, y: P.y + 38 }, + skill: { x: P.x + P.w - 18, y: P.y + 38 }, + pawns: { x: P.x + 170, y: P.y + 86 }, + counts: { x: P.x + 164, y: P.y + 130 }, + dice: { x: P.x + P.w - 44, y: P.y + 94 }, + // speech bubble hangs off the board side of the plate + bubble: top ? { x: P.x + 12, y: P.y + P.h + 8, w: P.w - 24, h: 64 } : { x: P.x + 12, y: P.y - 72, w: P.w - 24, h: 64 }, + }; +} + +// Throw origin in tray-world coords for each seat (dice come from their side). +export function throwOrigin(color) { + const w = TRAY_WORLD.w, h = TRAY_WORLD.h; + return { + red: { u: w * 0.85, v: h + 90, h: 140 }, // from your cup below the tray + blue: { u: w * 0.6, v: h + 90, h: 140 }, + yellow: { u: w * 0.6, v: -90, h: 140 }, + green: { u: -60, v: h * 0.2, h: 140 }, + }[color]; +} +export function groundTray(u, v) { return { x: TRAY_FELT.x + u, y: TRAY_FELT.y + v, s: 1 }; } +// Resting spots for n dice: 2 = the roll; 4 = roll (top row) + backs (bottom row). +export function diceRest(n) { + if (n === 4) return [[0.33, 0.4], [0.67, 0.4], [0.33, 0.65], [0.67, 0.65]].map(([u, v]) => ({ u: TRAY_WORLD.w * u, v: TRAY_WORLD.h * v })); + const us = { 1: [0.5], 2: [0.36, 0.64], 3: [0.25, 0.5, 0.75] }[n] ?? [0.36, 0.64]; + return us.map((u) => ({ u: TRAY_WORLD.w * u, v: TRAY_WORLD.h * 0.5 })); +} + +export function chipRect(i, n) { + const w = n <= 4 ? 74 : 58, gap = n <= 4 ? 10 : 6; + const total = n * w + (n - 1) * gap; + const x0 = CHIPS.x + (CHIPS.w - total) / 2; + return { x: x0 + i * (w + gap), y: CHIPS.y + 30, w, h: 56 }; +} + +export function hudFurniture() { + const f = { + board: BOARD_RECT, + status: STATUS, chips: CHIPS, talk: TALK, garland: GARLAND, tray: TRAY, chai: CHAI, + cup: { x: CUP.x - CUP.w / 2, y: CUP.y - CUP.h / 2, w: CUP.w, h: CUP.h }, + }; + for (const [k, P] of Object.entries(PLATES)) f[`plate_${k}`] = P; + for (const [k, b] of Object.entries(BUTTONS)) f[`btn_${k}`] = { x: b.x - BTN.w / 2, y: b.y - BTN.h / 2, w: BTN.w, h: BTN.h }; + return f; +} diff --git a/src/games/parchisi/ParchisiLogic.js b/src/games/parchisi/ParchisiLogic.js index a0d2c60..7b06074 100644 --- a/src/games/parchisi/ParchisiLogic.js +++ b/src/games/parchisi/ParchisiLogic.js @@ -1,428 +1,416 @@ -// Pure Parcheesi (American standard) rules. No Phaser dependency. +// ParchisiLogic.js — pure Parcheesi (American standard) rules. No Phaser. // -// Board model: -// - 68-square outer track (indices 0..67), clockwise. -// - 4 colors with fixed entry squares 17 apart: red=0, blue=17, yellow=34, green=51. -// - Each color travels 67 outer steps from its entry to its own home-entry -// (which is the square immediately CCW from the entry: entry-1 mod 68), -// then 7 squares up its home column, then 1 final step into home. -// - Total path from entry to home = 75 movement pips. +// Board model +// 68-square outer track (0..67); movement is counter-clockwise (index − 1). +// Entries (safe, coloured): red 11, blue 62, yellow 45, green 28. +// Home-entry (last track square before the home path): red 16, blue 67, +// yellow 50, green 33. Then 7 home-path squares, then HOME. // -// Pawn position is one of: -// 'nest' | { track: 0..67 } | { home: 0..6 } | 'home' +// A pawn is one integer: its PROGRESS along its own path. +// −1 in the nest +// 0 … 63 on the track (0 = its entry square, 63 = its home-entry square) +// 64 … 70 on its home path (squares 0 … 6) +// 71 home // -// Safe squares: 12 total. The 4 colored entries + 8 white safeties spaced -// at +7 and +12 from each entry. Pawns cannot be captured on a safe square, -// EXCEPT a pawn entering the board (leaving the nest with a 5) bops any -// single opponent occupying its entry square. +// Rules (Hasbro): enter with a 5 on one die or the two dice totalling 5 (a +// pawn entering bops a lone opponent on its entry square); captures send a +// lone pawn on a non-safe square back to its nest (+20 bonus); reaching home +// earns +10; bonuses are used whole by one pawn or forfeited. Two pawns of one +// colour on a square form a blockade nobody passes or lands on — including +// on the home path, where only the owner can be stuck behind it. A blockade +// can't be moved forward together with one doubles roll. Doubles roll again; +// with all pawns out of the nest doubles also give the dice "backs" (7 − d). +// Third doubles in a row: the most advanced pawn not yet home returns to the +// nest and the turn ends. You must use as much of the roll as possible. +// +// House rules (opts): captureBonus, homeBonus, threeDoubles, shareSafe (an +// opponent may share a safe square — Spanish parchís). export const COLORS = ['red', 'blue', 'yellow', 'green']; - export const ENTRY = { red: 11, blue: 62, yellow: 45, green: 28 }; -// Home-entry = the LAST outer-track square a pawn occupies before turning -// into its home column. Movement is CCW (track index decrements). export const HOME_ENTRY = { red: 16, blue: 67, yellow: 50, green: 33 }; - export const TRACK_LEN = 68; export const HOME_COL_LEN = 7; export const PAWNS_PER_PLAYER = 4; +export const NEST = -1; +export const LAST_TRACK = 63; +export const HOME_PATH0 = 64; +export const HOME = 71; +export const DEFAULT_OPTS = { captureBonus: true, homeBonus: true, threeDoubles: true, shareSafe: false }; -const SAFE_SET = new Set([ - 4, 11, 16, - 21, 28, 33, - 38, 45, 50, - 55, 62, 67, -]); +const SAFE_SET = new Set([4, 11, 16, 21, 28, 33, 38, 45, 50, 55, 62, 67]); +export const isSafeTrack = (idx) => SAFE_SET.has(idx); -export function isSafeTrack(idx) { - return SAFE_SET.has(idx); +// Seats for 2–4 players (opposite corners for two). +export function seatColors(n) { + if (n <= 2) return ['red', 'yellow']; + if (n === 3) return ['red', 'blue', 'yellow']; + return COLORS.slice(); } -export function createInitialState(playerOrder = COLORS) { - const pawns = {}; - for (const c of COLORS) { - pawns[c] = Array.from({ length: PAWNS_PER_PLAYER }, () => ({ loc: 'nest' })); - } +export const trackIdx = (color, p) => ((ENTRY[color] - p) % TRACK_LEN + TRACK_LEN) % TRACK_LEN; +export const onTrack = (p) => p >= 0 && p <= LAST_TRACK; +export const onHomePath = (p) => p >= HOME_PATH0 && p < HOME; + +// Progress index at which `color` stands on track square `sq` (0..63) or −1. +export function progressAt(color, sq) { + const p = ((ENTRY[color] - sq) % TRACK_LEN + TRACK_LEN) % TRACK_LEN; + return p <= LAST_TRACK ? p : -1; +} + +// ── state ───────────────────────────────────────────────────────────────────── +function freshStats() { + return { rolls: 0, doubles: 0, captures: 0, captured: 0, home: 0, penalties: 0, blocked: 0, bonus20: 0, bonus10: 0, forfeits: 0, blockades: 0, moved: 0 }; +} + +export function createInitialState(playerOrder = COLORS, opts = {}) { + const players = [...playerOrder]; + const pawns = {}, stats = {}; + for (const c of players) { pawns[c] = [NEST, NEST, NEST, NEST]; stats[c] = freshStats(); } return { - players: [...playerOrder], + players, pawns, - currentPlayer: playerOrder[0], + opts: { ...DEFAULT_OPTS, ...opts }, + currentPlayer: players[0], dice: null, - movesLeft: [], // remaining die values: 1..6, plus bonus 10/20 + movesLeft: [], + rolledDoubles: false, consecutiveDoubles: 0, - lastWasDoubles: false, // if true and dice exhausted, same player re-rolls - phase: 'roll', // 'roll' | 'move' | 'game_over' + rollMoves: [], // [{ pawnIdx, from, to }] this roll (blockade-on-doubles rule) + phase: 'roll', // roll | move | game_over winner: null, - log: [], // optional, for surfaces — capped + lastEvent: null, + turn: 0, + stats, + pipHistory: [Object.fromEntries(players.map((c) => [c, totalPipsRemaining({ players, pawns }, c)]))], + log: [], }; } -export function cloneState(state) { - return JSON.parse(JSON.stringify(state)); -} +export function cloneState(s) { return JSON.parse(JSON.stringify(s)); } -// ─── Dice ────────────────────────────────────────────────────────────────── - -export function rollDice(state) { - const d1 = Math.ceil(Math.random() * 6); - const d2 = Math.ceil(Math.random() * 6); - return rollSpecificDice(state, d1, d2); -} - -export function rollSpecificDice(state, d1, d2) { +// ── opening: each player throws one die; highest starts (ties re-throw) ───── +export function rollOpening(state, rng = Math.random) { const s = cloneState(state); - s.dice = [d1, d2]; - const doubles = d1 === d2; - - if (doubles) { - s.consecutiveDoubles += 1; - s.lastWasDoubles = true; - if (s.consecutiveDoubles >= 3) { - // Three-doubles penalty: furthest-from-home pawn of current player - // goes back to the nest; turn ends. No moves played. - applyThreeDoublesPenalty(s); - s.dice = [d1, d2]; // endTurn nulled dice; restore for animation/display - return s; - } - const allOut = pawnsInNest(s, s.currentPlayer) === 0; - if (allOut) { - // Bonus moves: also use the "back" of each die (1↔6, 2↔5, 3↔4) - s.movesLeft = [d1, d2, 7 - d1, 7 - d2]; - } else { - s.movesLeft = [d1, d2]; - } - } else { - s.consecutiveDoubles = 0; - s.lastWasDoubles = false; - s.movesLeft = [d1, d2]; + const rounds = []; + let contenders = s.players.slice(); + while (contenders.length > 1) { + const faces = {}; + for (const c of contenders) faces[c] = 1 + Math.floor(rng() * 6); + rounds.push(faces); + const hi = Math.max(...Object.values(faces)); + contenders = contenders.filter((c) => faces[c] === hi); } - s.phase = 'move'; + s.currentPlayer = contenders[0]; + s.opening = rounds; + s.lastEvent = { type: 'opening', starter: contenders[0], rounds }; return s; } -function applyThreeDoublesPenalty(s) { - const player = s.currentPlayer; - // Hasbro rule: "the pawn farthest along on its journey to Home" = - // the MOST ADVANCED pawn (smallest remaining distance, but >0). - let bestIdx = -1; - let bestDist = Infinity; - for (let i = 0; i < PAWNS_PER_PLAYER; i++) { - const p = s.pawns[player][i]; - if (p.loc === 'nest' || p.loc === 'home') continue; - const dist = pawnDistanceToHome(p, player); - if (dist < bestDist) { bestDist = dist; bestIdx = i; } - } - if (bestIdx >= 0) s.pawns[player][bestIdx] = { loc: 'nest' }; - endTurn(s, true); -} - -// Mutates state in place — used during sequencing. -export function endTurn(s, fromPenalty = false) { - s.dice = null; - s.movesLeft = []; - s.lastWasDoubles = false; - if (fromPenalty) s.consecutiveDoubles = 0; - const idx = s.players.indexOf(s.currentPlayer); - s.currentPlayer = s.players[(idx + 1) % s.players.length]; - s.consecutiveDoubles = 0; - s.phase = 'roll'; - return s; -} - -// ─── Geometry helpers ────────────────────────────────────────────────────── - -// Steps remaining from a pawn's current position to its home circle (>=0). -// nest = 76 (5 to enter + 75 from entry to home). -export function pawnDistanceToHome(pawn, color) { - if (pawn.loc === 'nest') return 76; - if (pawn.loc === 'home') return 0; - if (pawn.home !== undefined) return (HOME_COL_LEN - pawn.home); // home: 0..6 → 7..1 then home → 0 - if (pawn.track !== undefined) { - // Distance from track t to home-entry, then +7 (cols) + 1 (home circle) = +8. - const homeEntry = HOME_ENTRY[color]; - const d = (pawn.track - homeEntry + TRACK_LEN) % TRACK_LEN; - return d + 8; - } - return 0; -} - -function pawnsInNest(s, color) { - return s.pawns[color].filter((p) => p.loc === 'nest').length; -} - -function pawnsHome(s, color) { - return s.pawns[color].filter((p) => p.loc === 'home').length; -} - -function pawnsOnTrack(s) { - // returns Map> +// ── occupancy ──────────────────────────────────────────────────────────────── +// Map trackIdx → [{ color, pawnIdx }] +function trackOcc(s) { const m = new Map(); - for (const c of COLORS) { - for (let i = 0; i < PAWNS_PER_PLAYER; i++) { - const p = s.pawns[c][i]; - if (p.track !== undefined) { - const arr = m.get(p.track) ?? []; - arr.push({ color: c, pawnIdx: i }); - m.set(p.track, arr); - } + for (const c of s.players) { + const ps = s.pawns[c]; + for (let i = 0; i < 4; i++) { + if (!onTrack(ps[i])) continue; + const sq = trackIdx(c, ps[i]); + const a = m.get(sq); + if (a) a.push({ color: c, pawnIdx: i }); else m.set(sq, [{ color: c, pawnIdx: i }]); } } return m; } -// A blockade is 2 same-color pawns on one outer-track square. -// Returns Set of trackIdx that are blockades. -function blockadeSet(s) { - const set = new Set(); - const map = pawnsOnTrack(s); - for (const [idx, arr] of map) { - if (arr.length >= 2 && arr.every((p) => p.color === arr[0].color)) { - set.add(idx); +const isBlockade = (occ) => occ && occ.length >= 2 && occ[0].color === occ[1].color; + +export function blockadeSquares(s) { + const out = []; + for (const [sq, occ] of trackOcc(s)) if (isBlockade(occ)) out.push({ sq, color: occ[0].color }); + return out; +} + +function homeCount(s, color, p) { + let n = 0; + for (const q of s.pawns[color]) if (q === p) n++; + return n; +} + +export const pawnsInNest = (s, c) => s.pawns[c].filter((p) => p === NEST).length; +export const pawnsHome = (s, c) => s.pawns[c].filter((p) => p === HOME).length; + +// ── dice ───────────────────────────────────────────────────────────────────── +export function rollDice(state, rng = Math.random) { + return rollSpecificDice(state, 1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)); +} + +export function rollSpecificDice(state, d1, d2) { + const s = cloneState(state); + const c = s.currentPlayer; + s.dice = [d1, d2]; + s.turn++; + s.rollMoves = []; + s.stats[c].rolls++; + const doubles = d1 === d2; + s.rolledDoubles = doubles; + if (doubles) { + s.stats[c].doubles++; + s.consecutiveDoubles++; + if (s.opts.threeDoubles && s.consecutiveDoubles >= 3) { + // the most advanced pawn not already home goes back to the nest + let best = -1, bestP = -1; + s.pawns[c].forEach((p, i) => { if (p !== HOME && p > bestP) { bestP = p; best = i; } }); + const ev = { type: 'threeDoubles', color: c, pawnIdx: best, from: best >= 0 ? s.pawns[c][best] : null, dice: [d1, d2] }; + if (best >= 0 && bestP >= 0) s.pawns[c][best] = NEST; + else ev.pawnIdx = -1; + s.stats[c].penalties++; + s.lastEvent = ev; + s.log.push({ color: c, text: `rolled ${d1}-${d2}: third doubles — ${ev.pawnIdx >= 0 ? 'a pawn goes back to the nest' : 'nothing to lose'}` }); + s.movesLeft = []; + s.rolledDoubles = false; + endTurnMut(s); + return s; } + s.movesLeft = pawnsInNest(s, c) === 0 ? [d1, d2, 7 - d1, 7 - d2] : [d1, d2]; + } else { + s.consecutiveDoubles = 0; + s.movesLeft = [d1, d2]; } - return set; + s.phase = 'move'; + s.lastEvent = { type: 'roll', color: c, dice: [d1, d2], backs: s.movesLeft.length === 4 }; + if (!getValidMoves(s).length) s.stats[c].blocked++; + return s; } -// Returns occupant of a track square: null | {color, count}. -function trackOccupants(s, idx) { - const arr = []; - for (const c of COLORS) { - for (let i = 0; i < PAWNS_PER_PLAYER; i++) { - if (s.pawns[c][i].track === idx) arr.push({ color: c, pawnIdx: i }); - } - } - return arr; -} +// ── move generation ────────────────────────────────────────────────────────── +const isBase = (d) => d <= 6; -// Returns count of pawns of this color in this home-col index. -function homeColOccupants(s, color, hIdx) { - return s.pawns[color].filter((p) => p.home === hIdx).length; -} +// Raw candidate moves for the current player (no full-roll filter). +function candidates(s) { + if (s.phase !== 'move') return []; + const c = s.currentPlayer; + const ps = s.pawns[c]; + const occ = trackOcc(s); + const out = []; + const dice = [...new Set(s.movesLeft)]; + const share = s.opts.shareSafe; -// ─── Move generation ─────────────────────────────────────────────────────── - -// Build the path squares a pawn would traverse moving `steps` from `from`. -// Returns an ORDERED array of positions for each step taken (length = steps). -// The final element is the landing square. Returns null if path is invalid -// (overshoots home). -function projectPath(from, color, steps) { - const path = []; - let pos = from; - for (let k = 0; k < steps; k++) { - if (pos.loc === 'nest') return null; // nest exit handled separately - if (pos === 'home' || pos.loc === 'home') return null; - if (pos.home !== undefined) { - const next = pos.home + 1; - if (next < HOME_COL_LEN) { pos = { home: next }; path.push(pos); } - else if (next === HOME_COL_LEN) { pos = { loc: 'home' }; path.push(pos); } - else return null; // overshoot - } else { - // On outer track - if (pos.track === HOME_ENTRY[color]) { - pos = { home: 0 }; - path.push(pos); - } else { - const nextIdx = (pos.track - 1 + TRACK_LEN) % TRACK_LEN; - pos = { track: nextIdx }; - path.push(pos); + // entering from the nest + const nestIdx = ps.indexOf(NEST); + if (nestIdx >= 0) { + const e = ENTRY[c]; + const o = occ.get(e) ?? []; + const own = o.filter((x) => x.color === c).length; + const opp = o.filter((x) => x.color !== c); + if (own < 2 && opp.length < 2) { + const hit = opp.length === 1 ? { color: opp[0].color, pawnIdx: opp[0].pawnIdx, sq: e } : null; + if (own + (hit ? 0 : opp.length) < 2) { + if (s.movesLeft.includes(5)) out.push({ player: c, pawnIdx: nestIdx, from: NEST, to: 0, dieUsed: 5, hit }); + const [a, b] = s.dice ?? [0, 0]; + if (a !== b && a + b === 5 && s.movesLeft.includes(a) && s.movesLeft.includes(b) && s.movesLeft.length === 2) { + out.push({ player: c, pawnIdx: nestIdx, from: NEST, to: 0, dieUsed: 5, combine: [a, b], hit }); + } } } } - return path; -} -// Check if a movement path is blocked by any blockade (track squares only). -// The first step's "from" is NOT included; we examine every square the pawn -// would *enter*. A blockade on the destination also blocks unless it's the -// final square AND a same-color blockade isn't an issue — for the standard -// rule, you cannot land on or pass any blockade (your own or opponents'). -function pathBlocked(path, blockades) { - for (const sq of path) { - if (sq.track !== undefined && blockades.has(sq.track)) return true; + for (let i = 0; i < 4; i++) { + const p = ps[i]; + if (p === NEST || p === HOME) continue; + for (const d of dice) { + const q = p + d; + if (q > HOME) continue; + let blocked = false; + for (let t = p + 1; t <= q && !blocked; t++) { + if (t <= LAST_TRACK) { + const o = occ.get(trackIdx(c, t)); + if (isBlockade(o)) blocked = true; + } else if (t < HOME) { + if (homeCount(s, c, t) >= 2) blocked = true; + } + } + if (blocked) continue; + let hit = null; + if (q <= LAST_TRACK) { + const sq = trackIdx(c, q); + const o = occ.get(sq) ?? []; + const own = o.filter((x) => x.color === c).length; + const opp = o.filter((x) => x.color !== c); + if (own >= 2 || o.length >= 2) continue; + if (opp.length === 1) { + if (isSafeTrack(sq)) { if (!share) continue; } + else hit = { color: opp[0].color, pawnIdx: opp[0].pawnIdx, sq }; + } + } else if (q < HOME) { + if (homeCount(s, c, q) >= 2) continue; + } + // a blockade can't move forward together on one doubles roll + if (s.rolledDoubles && s.rollMoves.some((r) => r.pawnIdx !== i && r.from === p && r.to === q)) continue; + out.push({ player: c, pawnIdx: i, from: p, to: q, dieUsed: d, hit }); + } } - return false; + return out; } -// Build a Move object describing a pawn step. dieUsed is the die value -// consumed (1..6, or 10/20 for bonuses). -function makeMove(player, pawnIdx, from, to, dieUsed, hit = null) { - const move = { player, pawnIdx, from, to, dieUsed, hit }; - return move; +const usedBase = (m) => (m.combine ? 2 : isBase(m.dieUsed) ? 1 : 0); + +// Most base dice the player can still use from here (bonuses ignored). +function maxBase(s, memo) { + if (!s.movesLeft.some(isBase)) return 0; + const key = s.players.map((c) => s.pawns[c].join(',')).join('|') + '#' + s.movesLeft.filter(isBase).sort().join('') + '#' + (s.rolledDoubles ? JSON.stringify(s.rollMoves) : ''); + if (memo.has(key)) return memo.get(key); + let best = 0; + for (const m of candidates(s)) { + const u = usedBase(m); + if (!u) continue; + const v = u + maxBase(applyRaw(s, m, true), memo); + if (v > best) best = v; + if (best >= s.movesLeft.filter(isBase).length) break; + } + memo.set(key, best); + return best; } -// All legal moves for the current player with currently remaining dice. -// Returns flat array of single-die moves. Sum-of-5 nest entries are also -// included as special moves with `combineDice: [d1, d2]` (dieUsed=5). +const validCache = new WeakMap(); + +// Legal moves now: each keeps the most of the rolled dice still usable. export function getValidMoves(s) { if (s.phase !== 'move') return []; - const player = s.currentPlayer; - const moves = []; - const blockades = blockadeSet(s); - const uniqueDice = [...new Set(s.movesLeft)]; - const inNest = s.pawns[player].some((p) => p.loc === 'nest'); - - // 1. Nest exits with a 5 on a single die - if (inNest && s.movesLeft.includes(5)) { - const entryIdx = ENTRY[player]; - const occ = trackOccupants(s, entryIdx); - // Blocked if opponent has 2+ on entry - const oppCount = occ.filter((o) => o.color !== player).length; - const ownCount = occ.filter((o) => o.color === player).length; - const blockedByOppPair = oppCount >= 2; - const blockedByOwnTriple = ownCount >= 2; // can't make a 3-stack with own pawns - if (!blockedByOppPair && !blockedByOwnTriple) { - // Pick the lowest-index pawn still in nest - const pawnIdx = s.pawns[player].findIndex((p) => p.loc === 'nest'); - // Bop on entry: if exactly one opponent pawn sits on the entry, capture - let hit = null; - if (oppCount === 1) { - const opp = occ.find((o) => o.color !== player); - hit = { color: opp.color, pawnIdx: opp.pawnIdx, sq: { track: entryIdx } }; - } - moves.push(makeMove(player, pawnIdx, { loc: 'nest' }, { track: entryIdx }, 5, hit)); - } + if (validCache.has(s)) return validCache.get(s); + const cand = candidates(s); + let out = cand; + if (cand.length > 1 && s.movesLeft.some(isBase)) { + const memo = new Map(); + const target = maxBase(s, memo); + out = cand.filter((m) => usedBase(m) + maxBase(applyRaw(s, m, true), memo) === target); } - - // 2. Nest exit using BOTH dice summing to 5 (not 5+5 doubles) - if (inNest && s.dice && s.dice[0] + s.dice[1] === 5 && s.dice[0] !== s.dice[1] - && s.movesLeft.includes(s.dice[0]) && s.movesLeft.includes(s.dice[1])) { - const entryIdx = ENTRY[player]; - const occ = trackOccupants(s, entryIdx); - const oppCount = occ.filter((o) => o.color !== player).length; - const ownCount = occ.filter((o) => o.color === player).length; - if (oppCount < 2 && ownCount < 2) { - const pawnIdx = s.pawns[player].findIndex((p) => p.loc === 'nest'); - let hit = null; - if (oppCount === 1) { - const opp = occ.find((o) => o.color !== player); - hit = { color: opp.color, pawnIdx: opp.pawnIdx, sq: { track: entryIdx } }; - } - const mv = makeMove(player, pawnIdx, { loc: 'nest' }, { track: entryIdx }, 5, hit); - mv.combineDice = [s.dice[0], s.dice[1]]; - moves.push(mv); - } - } - - // 3. Track / home-column pawn movements for each remaining die - for (let pawnIdx = 0; pawnIdx < PAWNS_PER_PLAYER; pawnIdx++) { - const p = s.pawns[player][pawnIdx]; - if (p.loc === 'nest' || p.loc === 'home') continue; - - for (const die of uniqueDice) { - const path = projectPath(p, player, die); - if (!path) continue; - if (pathBlocked(path, blockades)) continue; - - const dest = path[path.length - 1]; - // Validate landing - let hit = null; - if (dest.track !== undefined) { - const occ = trackOccupants(s, dest.track); - const own = occ.filter((o) => o.color === player); - const opp = occ.filter((o) => o.color !== player); - // Cannot land on opponent's blockade — already filtered by pathBlocked. - // Cannot land creating 3-stack of own color. - if (own.length >= 2) continue; - // Capture: exactly one opponent on a non-safe square - if (opp.length === 1 && !isSafeTrack(dest.track)) { - hit = { color: opp[0].color, pawnIdx: opp[0].pawnIdx, sq: { track: dest.track } }; - } - // Cannot land on safe square already occupied by opponent (mutual safety) - if (opp.length >= 1 && isSafeTrack(dest.track)) continue; - if (opp.length >= 2) continue; - } else if (dest.home !== undefined) { - // Home column squares are safe; can't share with own pawn (max 1 per square in column). - if (homeColOccupants(s, player, dest.home) >= 1) continue; - } - // Landing in 'home' has no occupancy constraint - moves.push(makeMove(player, pawnIdx, copyLoc(p), dest, die, hit)); - } - } - - return moves; + validCache.set(s, out); + return out; } -function copyLoc(p) { - if (p.loc) return { loc: p.loc }; - if (p.track !== undefined) return { track: p.track }; - if (p.home !== undefined) return { home: p.home }; - return p; +export const hasAnyMove = (s) => getValidMoves(s).length > 0; +export const turnDone = (s) => s.phase === 'move' && getValidMoves(s).length === 0; + +// The squares a move passes through, in order (for hop animations). +export function movePath(m) { + if (m.from === NEST) return [0]; + const out = []; + for (let t = m.from + 1; t <= m.to; t++) out.push(t); + return out; } -// ─── Move application ───────────────────────────────────────────────────── - -// Apply a single move. Returns a NEW state. Handles capture (+20), home (+10), -// dice consumption, and end-of-turn (with doubles re-roll handling). -export function applyMove(state, move) { +// ── applying ───────────────────────────────────────────────────────────────── +function applyRaw(state, m, noBonus = false) { const s = cloneState(state); - const player = move.player; - - // Update pawn - s.pawns[player][move.pawnIdx] = locFromMove(move.to); - - // Process capture - if (move.hit) { - s.pawns[move.hit.color][move.hit.pawnIdx] = { loc: 'nest' }; - s.movesLeft.push(20); + const c = m.player; + s.pawns[c][m.pawnIdx] = m.to; + if (m.hit) { + s.pawns[m.hit.color][m.hit.pawnIdx] = NEST; + if (!noBonus && s.opts.captureBonus) s.movesLeft.push(20); } - - // Process home arrival - const arrived = move.to.loc === 'home'; - if (arrived) { - s.movesLeft.push(10); + if (m.to === HOME && !noBonus && s.opts.homeBonus) s.movesLeft.push(10); + for (const d of m.combine ?? [m.dieUsed]) { + const k = s.movesLeft.indexOf(d); + if (k >= 0) s.movesLeft.splice(k, 1); } + s.rollMoves.push({ pawnIdx: m.pawnIdx, from: m.from, to: m.to }); + return s; +} - // Consume die(s) - if (move.combineDice) { - for (const d of move.combineDice) { - const idx = s.movesLeft.indexOf(d); - if (idx !== -1) s.movesLeft.splice(idx, 1); - } - } else { - const idx = s.movesLeft.indexOf(move.dieUsed); - if (idx !== -1) s.movesLeft.splice(idx, 1); +// Apply one move. Does NOT end the roll: call finishRoll() once turnDone(). +export function applyMove(state, m) { + const s = applyRaw(state, m); + const c = m.player; + const st = s.stats[c]; + st.moved++; + if (m.hit) { + st.captures++; + s.stats[m.hit.color].captured++; + if (s.opts.captureBonus) st.bonus20++; } - - // Win check - if (pawnsHome(s, player) >= PAWNS_PER_PLAYER) { - s.winner = player; + if (m.to === HOME) { st.home++; if (s.opts.homeBonus) st.bonus10++; } + if (onTrack(m.to)) { + const sq = trackIdx(c, m.to); + if (s.pawns[c].filter((p) => onTrack(p) && trackIdx(c, p) === sq).length === 2) st.blockades++; + } + s.lastEvent = { type: 'move', move: m }; + if (pawnsHome(s, c) === PAWNS_PER_PLAYER) { + s.winner = c; s.phase = 'game_over'; - return s; - } - - // End-of-turn handling - if (s.movesLeft.length === 0 || !hasAnyMove(s)) { - if (s.lastWasDoubles && s.consecutiveDoubles < 3) { - // Doubles → same player re-rolls - s.dice = null; - s.movesLeft = []; - s.lastWasDoubles = false; - s.phase = 'roll'; - } else { - endTurn(s); - } + s.movesLeft = []; + s.pipHistory.push(pipRow(s)); } return s; } -function locFromMove(to) { - if (to.loc === 'home') return { loc: 'home' }; - if (to.track !== undefined) return { track: to.track }; - if (to.home !== undefined) return { home: to.home }; - return to; +function pipRow(s) { return Object.fromEntries(s.players.map((c) => [c, totalPipsRemaining(s, c)])); } + +function endTurnMut(s) { + s.pipHistory.push(pipRow(s)); + const i = s.players.indexOf(s.currentPlayer); + s.currentPlayer = s.players[(i + 1) % s.players.length]; + s.consecutiveDoubles = 0; + s.rolledDoubles = false; + s.dice = null; + s.movesLeft = []; + s.rollMoves = []; + s.phase = 'roll'; } -export function hasAnyMove(s) { - return getValidMoves(s).length > 0; +// End of a roll: doubles roll again (unused bonuses are forfeited), otherwise +// the turn passes on. +export function finishRoll(state) { + const s = cloneState(state); + if (s.phase === 'game_over') return s; + const c = s.currentPlayer; + if (s.movesLeft.some((d) => d > 6)) s.stats[c].forfeits += s.movesLeft.filter((d) => d > 6).length; + if (s.rolledDoubles) { + s.dice = null; + s.movesLeft = []; + s.rollMoves = []; + s.rolledDoubles = false; + s.phase = 'roll'; + s.lastEvent = { type: 'again', color: c }; + return s; + } + endTurnMut(s); + s.lastEvent = { type: 'pass', color: c, next: s.currentPlayer }; + return s; +} +export const passTurn = finishRoll; + +export function logTurn(state, color, text) { + const s = cloneState(state); + s.log.push({ color, text }); + if (s.log.length > 120) s.log.splice(0, s.log.length - 120); + return s; } -// ─── Helpers exposed for AI / UI ────────────────────────────────────────── - -export { pawnsHome, pawnsInNest, blockadeSet, trackOccupants }; - -// Compute total pip distance for a color (lower = better progress). +// ── helpers ────────────────────────────────────────────────────────────────── +// Steps still to travel (nest counts the five-to-enter as well). +export function pawnDistanceToHome(p) { + if (p === NEST) return HOME + 5; + return HOME - p; +} export function totalPipsRemaining(s, color) { - let total = 0; - for (const p of s.pawns[color]) total += pawnDistanceToHome(p, color); - return total; + return s.pawns[color].reduce((a, p) => a + pawnDistanceToHome(p), 0); } + +// Final order: winner first, then by pawns home, then by steps remaining. +export function rankings(s) { + return s.players.slice().sort((a, b) => { + if (a === s.winner) return -1; + if (b === s.winner) return 1; + const h = pawnsHome(s, b) - pawnsHome(s, a); + return h || totalPipsRemaining(s, a) - totalPipsRemaining(s, b); + }); +} + +export function moveText(m) { + const where = (p) => (p === NEST ? 'nest' : p === HOME ? 'HOME' : p >= HOME_PATH0 ? `home path ${p - HOME_PATH0 + 1}` : `square ${p + 1}`); + const die = m.combine ? `${m.combine[0]}+${m.combine[1]}` : String(m.dieUsed); + return `${m.from === NEST ? 'enters' : `${where(m.from)} → ${where(m.to)}`} (${die})${m.hit ? ' — capture!' : ''}`; +} + +export { trackOcc, candidates }; diff --git a/src/games/parchisi/ParchisiPawns.js b/src/games/parchisi/ParchisiPawns.js new file mode 100644 index 0000000..e36d377 --- /dev/null +++ b/src/games/parchisi/ParchisiPawns.js @@ -0,0 +1,148 @@ +// ParchisiPawns.js — the pawns as persistent sprites (shadow + body Image, no +// Containers so depth works) and the hop animator. +// +// A pawn's identity is (colour, index) in the state, so there is nothing to +// reassign: sync() just slides any pawn whose spot changed. Two pawns sharing +// a square stand side by side across the direction of travel. + +import { NEST, HOME, onTrack, trackIdx } from './ParchisiLogic.js'; +import { pawnSpot, cellOf, homeSlot, nestSlot } from './ParchisiBoard.js'; +import { PAWN_TEX } from './ParchisiArt.js'; +import { hop } from './ParchisiSound.js'; + +const lerp = (a, b, t) => a + (b - a) * t; +const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2); + +export class PawnSet { + constructor(scene, players, depth) { + this.scene = scene; + this.players = players; + this.depth = depth; + this.items = {}; + } + + build() { + const s = this.scene; + const oy = (PAWN_TEX.h - 14) / PAWN_TEX.h; + for (const c of this.players) { + this.items[c] = [0, 1, 2, 3].map((i) => { + const shadow = s.add.image(0, 0, 'pc-pawn-shadow').setDepth(this.depth - 1).setAlpha(0.75); + const img = s.add.image(0, 0, `pc-pawn-${c}`).setOrigin(0.5, oy).setDepth(this.depth); + return { color: c, idx: i, img, shadow, x: 0, y: 0, h: 0, scale: 1, busy: false }; + }); + } + return this; + } + + get(c, i) { return this.items[c][i]; } + all() { return this.players.flatMap((c) => this.items[c]); } + + // Target spot for every pawn in `state`. + spots(state) { + const groups = new Map(); + for (const c of this.players) { + state.pawns[c].forEach((p, i) => { + if (p === NEST || p === HOME) return; + const key = onTrack(p) ? `t${trackIdx(c, p)}` : `h${c}${p}`; + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push({ c, i }); + }); + } + const out = {}; + for (const c of this.players) { + out[c] = state.pawns[c].map((p, i) => { + if (p === NEST || p === HOME) return { ...pawnSpot(c, p, i), scale: p === HOME ? 0.72 : 0.9 }; + const key = onTrack(p) ? `t${trackIdx(c, p)}` : `h${c}${p}`; + const g = groups.get(key); + const share = g.length > 1 ? g.findIndex((q) => q.c === c && q.i === i) : -1; + return { ...pawnSpot(c, p, i, share), scale: 1 }; + }); + } + return out; + } + + place(it, x, y, h = 0, scale = it.scale) { + it.x = x; it.y = y; it.h = h; it.scale = scale; + it.img.setPosition(x, y - h).setScale(scale * (1 + h / 220)); + it.shadow.setPosition(x + 3 + h * 0.15, y + 2 + h * 0.1).setScale(scale * (1 - h / 160)).setAlpha(Math.max(0.25, 0.75 - h / 120)); + if (!it.flying) { it.img.setDepth(this.depth + y * 0.001); it.shadow.setDepth(this.depth - 1); } + } + + sync(state, { dur = 0 } = {}) { + const sp = this.spots(state); + const jobs = []; + for (const c of this.players) { + this.items[c].forEach((it, i) => { + const t = sp[c][i]; + if (Math.abs(it.x - t.x) < 0.5 && Math.abs(it.y - t.y) < 0.5 && Math.abs(it.scale - t.scale) < 0.01) return; + if (dur <= 0 || it.busy) { this.place(it, t.x, t.y, 0, t.scale); return; } + jobs.push(this.arc(it, t, dur, 8)); + }); + } + return Promise.all(jobs); + } + + arc(it, to, dur, height = 30, { spin = 0, scaleTo = to.scale ?? it.scale } = {}) { + const from = { x: it.x, y: it.y, s: it.scale }; + const p = { t: 0 }; + it.flying = true; + it.img.setDepth(this.depth + 20); it.shadow.setDepth(this.depth + 19); + return new Promise((res) => { + this.scene.tweens.add({ + targets: p, t: 1, duration: dur, ease: 'Linear', + onUpdate: () => { + const k = easeInOut(p.t); + this.place(it, lerp(from.x, to.x, k), lerp(from.y, to.y, k), Math.sin(Math.PI * p.t) * height, lerp(from.s, scaleTo, k)); + if (spin) it.img.setRotation(spin * Math.PI * 2 * p.t); + }, + onComplete: () => { + it.img.setRotation(0); + it.flying = false; + this.place(it, to.x, to.y, 0, scaleTo); + res(); + }, + }); + }); + } + + // Hop square by square along `path` (progress values); the last hop lands on + // `final` (the spot in the after-state). onStep(k, p) fires on each landing. + async hopAlong(c, i, path, final, { per = 120, onStep } = {}) { + const it = this.get(c, i); + it.busy = true; + for (let k = 0; k < path.length; k++) { + const p = path[k]; + const last = k === path.length - 1; + const to = last ? final : (p === HOME ? { ...homeSlot(c, i), scale: 0.72 } : { ...cellOf(c, p), scale: 1 }); + const first = k === 0 && it.scale !== 1; + await this.arc(it, to, first ? per * 2.2 : per, first ? 60 : 16, { scaleTo: to.scale ?? 1 }); + onStep?.(k, p); + hop(this.scene, { k, home: p >= 64 }); + } + it.busy = false; + } + + // A captured pawn tumbles back to its nest bowl. + knockHome(c, i, dur = 520) { + const it = this.get(c, i); + const to = { ...nestSlot(c, i), scale: 0.9 }; + return this.arc(it, to, dur, 140, { spin: 1.5, scaleTo: 0.9 }); + } + + // Lift (selection) / bob. + setLifted(it, on) { + if (!it) return; + if (on) { it.flying = true; it.img.setDepth(this.depth + 18); this.place(it, it.x, it.y, 10); } + else { it.flying = false; this.place(it, it.x, it.y, 0); } + } + + // Nearest pawn of `color` to (x, y) within r. + pick(color, x, y, r = 28) { + let best = null, bd = r; + for (const it of this.items[color] ?? []) { + const d = Math.hypot(it.x - x, it.y - 10 - y); + if (d < bd) { bd = d; best = it; } + } + return best; + } +} diff --git a/src/games/parchisi/ParchisiSound.js b/src/games/parchisi/ParchisiSound.js new file mode 100644 index 0000000..836d770 --- /dev/null +++ b/src/games/parchisi/ParchisiSound.js @@ -0,0 +1,134 @@ +// ParchisiSound.js — tiny Web Audio synths for the veranda. No audio files; +// silent without Web Audio or when muted. +// +// hop(scene, { k, home }) a lacquered pawn tapping a square (k = step no.; +// the home path climbs in pitch) +// bonk(scene) a capture +// coin(scene) a bonus token +// chime(scene) a pawn comes home (small temple-bell chord) +// thud(scene) third doubles: a low drum +// tap(scene) pick-up tick +// Rain a soft monsoon rain loop (start / stop / setOn) + +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 * 1.5), 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 } = {}) { + const o = ac.createOscillator(); o.type = type; + o.frequency.setValueAtTime(f, t0); + if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d); + const g = ac.createGain(); + g.gain.setValueAtTime(0, t0); + g.gain.linearRampToValueAtTime(a, t0 + 0.004); + g.gain.exponentialRampToValueAtTime(0.0005, t0 + d); + o.connect(g); g.connect(dest); o.start(t0); o.stop(t0 + d + 0.03); +} +function tick(ac, dest, t0, f, vol = 1) { + const n = ac.createBufferSource(); n.buffer = noise(ac); + const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = f; bp.Q.value = 2; + const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + 0.03); + n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + 0.05); +} +const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } }; + +export function hop(scene, { k = 0, home = false, vol = 0.08 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + const f = home ? 700 * Math.pow(1.09, k) : 820 + (k % 3) * 40; + tone(ac, dest, t, f, { type: 'triangle', a: 0.6, d: 0.06, glide: 0.7 }); + tick(ac, dest, t, f * 2.4, 0.5); + }); +} +export function tap(scene) { hop(scene, { vol: 0.05 }); } + +export function bonk(scene, { vol = 0.2 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + tone(ac, dest, t, 220, { type: 'sine', a: 1, d: 0.22, glide: 0.45 }); + tone(ac, dest, t, 660, { type: 'triangle', a: 0.4, d: 0.08, glide: 0.6 }); + tick(ac, dest, t, 1800, 0.8); + }); +} + +export function coin(scene, { vol = 0.07 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.003; + tone(ac, dest, t, 1568, { a: 0.8, d: 0.25 }); + tone(ac, dest, t + 0.07, 2093, { a: 0.7, d: 0.4 }); + }); +} + +export function chime(scene, { vol = 0.07 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.01; + for (const [f, a, d, dt] of [[784, 1, 1.6, 0], [988, 0.7, 1.4, 0.08], [1175, 0.6, 1.3, 0.16], [1568, 0.35, 1.0, 0.24]]) tone(ac, dest, t + dt, f, { a, d }); + }); +} + +export function thud(scene, { vol = 0.25 } = {}) { + const ac = ctxOf(scene); if (!ac) return; + safe(() => { + const dest = out(scene, ac, vol), t = ac.currentTime + 0.005; + tone(ac, dest, t, 110, { a: 1, d: 0.5, glide: 0.5 }); + tone(ac, dest, t + 0.18, 90, { a: 0.8, d: 0.6, glide: 0.5 }); + }); +} + +export class Rain { + constructor(scene) { this.scene = scene; this.nodes = null; } + start(vol = 0.03) { + const ac = ctxOf(this.scene); if (!ac || this.nodes) return; + try { + const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true; + const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 900; + const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 5200; + const g = ac.createGain(); g.gain.value = 0; + const base = out(this.scene, ac, 1); + g.gain.linearRampToValueAtTime(vol, ac.currentTime + 3); + src.connect(hp); hp.connect(lp); lp.connect(g); g.connect(base); + src.start(); + // the odd heavier drip off the eaves + const drip = setInterval(() => { + if (!this.nodes) return; + try { const t = ac.currentTime + 0.01; tone(ac, base, t, 1400 + Math.random() * 900, { a: vol * 1.4, d: 0.08, glide: 0.6 }); } catch (_) { /* gone */ } + }, 1700); + this.nodes = { src, g, base, drip }; + } catch (_) { this.nodes = null; } + } + stop() { + if (!this.nodes) return; + const n = this.nodes; this.nodes = null; + clearInterval(n.drip); + try { + const ac = n.src.context; + n.g.gain.cancelScheduledValues(ac.currentTime); + n.g.gain.setValueAtTime(n.g.gain.value, ac.currentTime); + n.g.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6); + setTimeout(() => { try { n.src.stop(); n.base.disconnect(); } catch (_) { /* gone */ } }, 700); + } catch (_) { /* gone */ } + } + setOn(on) { if (on) this.start(); else this.stop(); } +} diff --git a/src/games/parchisi/ParchisiTray.js b/src/games/parchisi/ParchisiTray.js new file mode 100644 index 0000000..bc6a123 --- /dev/null +++ b/src/games/parchisi/ParchisiTray.js @@ -0,0 +1,226 @@ +// ParchisiTray.js — the brass dice tray with real 3D dice, and your brass cup. +// +// Fairness: the engine rolls first; planTrayThrow (src/ui/dice/Dice3D.js) +// then relabels the flight so each die lands on the rolled face. +// +// Dice 0–1 are the roll. With doubles and every pawn out of the nest, dice +// 2–3 appear showing the same numbers and flip over to their "backs" (7 − d). +// Every die is lacquered in its thrower's colour — one per player in the +// opening throw, then the roller's pair (and backs) on each turn. + +import { Die3D, planTrayThrow, poseFromPlan, restingQ, qslerp } from '../../ui/dice/Dice3D.js'; +import { playSound, playSoundEx, SFX } from '../../ui/Sounds.js'; +import { TRAY, TRAY_WORLD, DIE_SIZE, groundTray, diceRest, throwOrigin } from './ParchisiLayout.js'; + +const IVORY = [244, 236, 214]; +const LAC = { red: [184, 50, 42], blue: [42, 93, 159], yellow: [220, 159, 30], green: [47, 125, 74] }; +// pips: ivory on the dark lacquers, dark on turmeric yellow so they stay readable +const LAC_PIP = { red: 0xfbf4e2, blue: 0xfbf4e2, yellow: 0x2a1a08, green: 0xfbf4e2 }; +const YAW = [0.14, -0.1, 0.06, -0.16]; +const lerp = (a, b, t) => a + (b - a) * t; +const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2); + +export class DiceTray { + constructor(scene, depth, { onClick } = {}) { + this.scene = scene; + this.depth = depth; + this.onClick = onClick; + this.poses = []; + this.faces = [1, 1, 1, 1]; + this.count = 0; + } + + build() { + const s = this.scene; + s.add.image(TRAY.x - 20, TRAY.y - 20, 'pc-tray').setOrigin(0).setDepth(this.depth - 2); + this.dice = [0, 1, 2, 3].map(() => new Die3D(s, this.depth, { size: DIE_SIZE, body: IVORY, pip: 0x1c1410, sin: 0.86, cos: 0.5, ground: groundTray })); + this.zone = s.add.zone(TRAY.x + TRAY.w / 2, TRAY.y + TRAY.h / 2, TRAY.w, TRAY.h).setDepth(this.depth + 5); + this.zone.on('pointerdown', () => this.onClick?.()); + for (let i = 0; i < 4; i++) { this.poses[i] = { u: 0, v: 0, h: 0, q: restingQ(1, YAW[i]), alpha: 1 }; this.dice[i].setVisible(false); } + return this; + } + + setClickable(on) { if (on) this.zone.setInteractive({ useHandCursor: true }); else this.zone.disableInteractive(); } + + style(i, body, pip) { this.dice[i].opts.body = body; this.dice[i].opts.pip = pip; } + + apply(i) { + const p = this.poses[i], d = this.dice[i]; + d.setDepth(this.depth + p.v * 0.0002 + (p.h > 4 ? 0.3 : 0)); + d.g.setAlpha(p.alpha); d.shadow.setAlpha(p.alpha); + d.set(p.u, p.v, p.h, p.q); + } + + hideAll() { this.count = 0; for (const d of this.dice) { d.glow = 0; d.setVisible(false); } } + + tweenDie(i, to, dur, { arc = 0, alphaTo = null, q = null } = {}) { + const p = this.poses[i]; + const from = { u: p.u, v: p.v, h: p.h, q: p.q, alpha: p.alpha }; + const qTo = q ?? p.q; + if (dur <= 0) { + Object.assign(p, { u: to.u, v: to.v, h: to.h ?? 0, q: qTo }); + if (alphaTo !== null) p.alpha = alphaTo; + this.apply(i); + return Promise.resolve(); + } + const prox = { t: 0 }; + return new Promise((resolve) => { + this.scene.tweens.add({ + targets: prox, t: 1, duration: dur, ease: 'Linear', + onUpdate: () => { + const t = easeInOut(prox.t); + p.u = lerp(from.u, to.u, t); p.v = lerp(from.v, to.v, t); + p.h = lerp(from.h, to.h ?? 0, t) + arc * Math.sin(Math.PI * prox.t); + p.q = qslerp(from.q, qTo, t); + if (alphaTo !== null) p.alpha = lerp(from.alpha, alphaTo, t); + this.apply(i); + }, + onComplete: resolve, + }); + }); + } + + async playThrow(indices, faces, origin, { speed = 1, fast = false } = {}) { + const s = this.scene; + indices.forEach((i) => { this.dice[i].setVisible(true); this.poses[i].alpha = 1; }); + const rest = diceRest(indices.length); + if (fast) { + indices.forEach((i, k) => { Object.assign(this.poses[i], { ...rest[k], h: 0, q: restingQ(faces[k], YAW[i]) }); this.apply(i); }); + playSoundEx(s, SFX.DICE_ROLL, { volume: 0.4 }); + return; + } + const plan = planTrayThrow(TRAY_WORLD, origin, faces, Math.random, DIE_SIZE, { + spread: indices.length > 2 ? 1.8 : 1.4, sep: 1.5, aim: { u0: 0.2, u1: 0.8, v0: 0.3, v1: 0.7 }, + }); + playSound(s, SFX.DICE_ROLL); + const step = (t) => indices.forEach((i, k) => { + const p = poseFromPlan(plan, k, t); + Object.assign(this.poses[i], { u: p.u, v: p.v, h: p.h, q: p.q }); + this.apply(i); + }); + step(0); + const prox = { t: 0 }; + await new Promise((resolve) => { + s.tweens.add({ targets: prox, t: 1, duration: Math.max(620, plan.duration * 1000) * speed, ease: 'Linear', onUpdate: () => step(prox.t), onComplete: () => { step(1); resolve(); } }); + }); + await this.wait(110 * speed); + } + + // Opening: one die per contender, in their colours. faces: { color: face }. + async throwOpening(faces, { speed = 1, fast = false } = {}) { + this.hideAll(); + const colors = Object.keys(faces); + colors.forEach((c, i) => this.style(i, LAC[c], LAC_PIP[c])); + const idx = colors.map((_, i) => i); + const origin = { u: TRAY_WORLD.w * 0.5, v: TRAY_WORLD.h + 80, h: 150 }; + await this.playThrow(idx, colors.map((c) => faces[c]), origin, { speed, fast }); + this.count = colors.length; + this.openingColors = colors; + } + + // A roll. backs = show the dice backs as two extra dice. + async throwRoll(color, d1, d2, backs, { speed = 1, fast = false } = {}) { + this.hideAll(); + // every roll is thrown in the roller's own lacquer colour (backs included) + for (let i = 0; i < 4; i++) this.style(i, LAC[color] ?? IVORY, LAC_PIP[color] ?? 0x1c1410); + await this.playThrow([0, 1], [d1, d2], throwOrigin(color), { speed, fast }); + if (backs) { + const rest = diceRest(4); + await Promise.all([ + this.tweenDie(0, { ...rest[0], h: 0 }, fast ? 0 : 240, { q: restingQ(d1, YAW[0]) }), + this.tweenDie(1, { ...rest[1], h: 0 }, fast ? 0 : 240, { q: restingQ(d2, YAW[1]) }), + ]); + // twins of the dice appear, then flip over onto their backs + for (const i of [2, 3]) { + Object.assign(this.poses[i], { ...rest[i], h: 30, q: restingQ(i === 2 ? d1 : d2, YAW[i]), alpha: 0 }); + this.dice[i].setVisible(true); + this.apply(i); + } + await Promise.all([2, 3].map((i) => this.tweenDie(i, { ...rest[i], h: 30 }, fast ? 0 : 160, { alphaTo: 0.95 }))); + await Promise.all([2, 3].map((i) => this.tweenDie(i, { ...rest[i], h: 0 }, fast ? 0 : 360, { arc: fast ? 0 : 40, q: restingQ(7 - (i === 2 ? d1 : d2), YAW[i]) }))); + if (!fast) playSoundEx(this.scene, SFX.PIECE_CLICK, { volume: 0.3, rate: 1.4 }); + this.faces = [d1, d2, 7 - d1, 7 - d2]; + this.count = 4; + } else { + const rest = diceRest(2); + await Promise.all([0, 1].map((i) => this.tweenDie(i, { ...rest[i], h: 0 }, fast ? 0 : 260, { q: restingQ(i ? d2 : d1, YAW[i]) }))); + this.faces = [d1, d2, 1, 1]; + this.count = 2; + } + } + + // Dim the dice already played (greedy multiset match on the values left). + setUsage(movesLeft) { + if (!this.count || this.openingColors) return; + const left = movesLeft.filter((d) => d <= 6); + for (let i = 0; i < this.count; i++) { + const k = left.indexOf(this.faces[i]); + const used = k < 0; + if (!used) left.splice(k, 1); + const target = used ? 0.35 : 1; + if (Math.abs(this.poses[i].alpha - target) > 0.01) this.tweenDie(i, { u: this.poses[i].u, v: this.poses[i].v, h: 0 }, 160, { alphaTo: target }); + } + } + + setGlow(amount, color = 0xf5d020) { + for (let i = 0; i < this.count; i++) { this.dice[i].glow = amount; this.dice[i].opts.glowColor = color; this.dice[i].draw(); } + } + + async clear({ fast = false } = {}) { + this.openingColors = null; + if (!this.count) return; + const n = this.count; + await Promise.all([...Array(n).keys()].map((i) => this.tweenDie(i, { u: this.poses[i].u, v: this.poses[i].v - 20, h: 30 }, fast ? 0 : 200, { alphaTo: 0 }))); + this.hideAll(); + } + + wait(ms) { return new Promise((r) => this.scene.time.delayedCall(Math.max(0, ms), r)); } +} + +// ── the brass cup ──────────────────────────────────────────────────────────── +export class BrassCup { + constructor(scene, depth, rect, { onPress } = {}) { + this.scene = scene; this.depth = depth; this.rect = rect; this.onPress = onPress; this.enabled = false; + } + build() { + const s = this.scene, R = this.rect; + this.glow = s.add.graphics().setDepth(this.depth - 1); + this.glow.fillStyle(0xf5d020, 0.22).fillEllipse(R.x, R.y + R.h / 2 - 12, R.w * 1.3, 40); + this.glow.lineStyle(3, 0xf5d020, 0.85).strokeEllipse(R.x, R.y + R.h / 2 - 12, R.w * 1.15, 32); + this.glow.setAlpha(0); + this.img = s.add.image(R.x, R.y + R.h / 2 - 4, 'pc-cup').setOrigin(0.5, 1 - 18 / (R.h + 28)).setDepth(this.depth); + this.home = { x: this.img.x, y: this.img.y }; + this.img.setInteractive({ useHandCursor: true }); + this.img.on('pointerdown', () => { if (this.enabled) this.onPress?.(); }); + this.img.on('pointerover', () => { if (this.enabled) this.img.setScale(1.04); }); + this.img.on('pointerout', () => this.img.setScale(1)); + this.pulse = s.tweens.add({ targets: this.glow, alpha: { from: 0.25, to: 0.95 }, duration: 750, yoyo: true, repeat: -1, paused: true }); + return this; + } + setEnabled(on) { + this.enabled = !!on; + if (on) { if (this.pulse.isPaused()) this.pulse.resume(); } + else { this.pulse.pause(); this.glow.setAlpha(0); this.img.setScale(1); } + } + startShake() { + const s = this.scene; + this.stopShake(); + this.shakeT = 0; + this.shakeTimer = s.time.addEvent({ delay: 16, loop: true, callback: () => { + this.shakeT += 16; + const k = Math.min(1, this.shakeT / 400); + this.img.rotation = Math.sin(this.shakeT / 38) * (0.12 + 0.1 * k); + this.img.x = this.home.x + Math.sin(this.shakeT / 55) * 6 * k; + this.img.y = this.home.y - 10 - Math.abs(Math.sin(this.shakeT / 45)) * 10 * k; + } }); + this.rattle = s.time.addEvent({ delay: 95, loop: true, callback: () => playSoundEx(s, SFX.PIECE_CLICK, { volume: 0.16 + Math.random() * 0.14, rate: 1.4 + Math.random() * 0.8 }) }); + } + stopShake() { this.shakeTimer?.remove(); this.shakeTimer = null; this.rattle?.remove(); this.rattle = null; } + shakeTime() { return this.shakeT ?? 0; } + async pour() { + this.stopShake(); + const s = this.scene; + await new Promise((res) => s.tweens.add({ targets: this.img, rotation: -0.6, x: this.home.x - 40, y: this.home.y - 46, duration: 140, ease: 'Quad.Out', onComplete: res })); + s.tweens.add({ targets: this.img, rotation: 0, x: this.home.x, y: this.home.y, duration: 380, delay: 160, ease: 'Back.Out' }); + } +} diff --git a/src/games/parchisi/tutorial.md b/src/games/parchisi/tutorial.md index 9315c9b..1793ebc 100644 --- a/src/games/parchisi/tutorial.md +++ b/src/games/parchisi/tutorial.md @@ -20,51 +20,66 @@ Think of it like me trying to get back to my den after a big salmon run. I gotta ## The Board -The board is shaped like a **plus sign** (+), with a big square in the very center called the **home** or **castle**. Each arm of the plus is your lane to get around. +We're playing on a rainy-season veranda today — rain drumming on the roof, light coming through a carved stone lattice, a cup of chai steaming on a brass saucer. The board is carved rosewood with a **plus sign** (+) shape, and in the very middle is the **HOME** lotus. -- Each player starts in their **starting yard** in the corner of the board. -- Pawns travel **counterclockwise** around the outer ring of the board, then up the center column toward home. -- Certain spaces are marked as **safe squares**. On a safe square, nobody can eat your pawn. It's like finding a nice hollow tree — nobody bothers you in there. +- **You play red.** Your four pawns wait in the brass bowl in the bottom-left corner — your **nest**. +- Each player's coloured **entry square** sits right beside their nest. That's where pawns join the race. +- Pawns travel **counterclockwise** around the outer track, then turn up their own coloured **home path** toward the lotus. +- The squares with a brass lotus (and every coloured entry square) are **safety squares**. Nobody can capture a pawn sitting on one. It's like finding a nice hollow tree — nobody bothers you in there. + +Play with one, two or three opponents. With just one, you sit across the board from each other. ## How to Play -### Rolling the Dice (or Shells, or Whatever!) +### Who Goes First? -Traditionally, Pachisi was played with **cowrie shells**. We're playing on a screen though, so we just roll dice. Same energy. More bear-friendly. +Everybody throws **one die** into the brass tray — each die is lacquered in its player's colour. Highest goes first. Ties throw again. Fair's fair, even for bears. -On your turn, roll the dice and move one of your pawns the number of spaces shown. +### Rolling the Dice + +Traditionally, Pachisi was played with **cowrie shells**. Here you get two real dice and a brass cup: **press and hold the cup** (or the Space bar) to shake it, then let go to throw. + +Each die is a separate move. You can move one pawn with both dice, or two pawns with one die each. **You have to use as much of your roll as you possibly can** — the game only offers moves that keep that possible. + +### The Move Chips + +The little ivory **chips** on the left show every number you still have to play. Click a **pawn** and coloured markers show where it can go (the marker says which number it uses). Or click a **chip** first to play just that number. Double-click a pawn to send it on its longest move. Changed your mind? **Undo (Z)** takes back moves until you press **Done**. ### Getting Your Pawns Out -Your pawns start in your home yard and don't go anywhere until you roll a specific number to enter the board. Once they're out, they start racing! +Your pawns can only leave the nest with a **5** — either one die showing 5, or **both dice adding up to 5** (like 1 and 4, or 2 and 3). Roll 5 and 5 and two pawns can come out! -### Moving Around the Board +If an opponent is sitting alone on *your* entry square when you come out, you **bop** them right back to their nest. Even though it's a safety square! Your door, your rules. -Once your pawn is on the board: +### Doubles -- Move it **counterclockwise** around the outer ring. -- After going all the way around, your pawn heads **up the center column** toward the home square. -- A pawn that reaches the home square is **finished** — safe, happy, and home for dinner. Just like me after a long winter. +Roll doubles and you **roll again** after moving. Even better: once **all four of your pawns are out of the nest**, doubles also give you the numbers on the **bottom** of the dice (they always add up to 7). Two ghostly dice flip over in the tray to show you. Roll 6 and 6 and you also get 1 and 1 — that's 14 steps! -### Capturing Other Pawns +**BUT** — roll doubles **three times in a row** and the dice get suspicious. Your pawn that's closest to home goes **all the way back to the nest**, and your turn ends. Too lucky is still too lucky. -Here's where it gets SPICY. If you land on a space occupied by an **opponent's pawn**, you **capture it** — it gets sent back to their starting yard and has to begin the journey all over again. +### Capturing -Capturing is satisfying. Very bear-like. It's like when I swipe a salmon right out of the river. *Swipe.* Gone. +Land exactly on a square with **one** opponent pawn (not on a safety square) and you **capture it** — it tumbles back to its nest. *Swipe.* Gone. And you earn a **+20 bonus**: a gold chip worth 20 steps for any one pawn to use right away. -**BUT** — you CANNOT capture a pawn on a **safe square**. Those are neutral zones. Even I respect the safe squares. I'm a big bear, but I'm not a MONSTER. +Bringing a pawn all the way **HOME** earns a **+10 bonus** chip too. If a bonus can't be used by any single pawn, it's lost. ### Blockades -If you have **two of your own pawns** on the same space, they form a **blockade**. Other players cannot pass through or land on a blockade. You've basically built a bear dam across the river and nothing gets through. +Two of your pawns on the same square make a **blockade** — a little woven barrier. **Nobody** can pass or land there, not even your own pawns. Blockades work on your home path too. -Blockades are a great strategy — but remember, your OWN pawns can't pass through your OWN blockade either. Don't block yourself in. I did that once with some logs in front of my cave. Very embarrassing. Took three hours to get out. +One catch: you can't march a blockade forward together using one roll of doubles. Bears tried. It's not allowed. ### Getting Home -Once a pawn travels the full loop and enters the **center column**, it's heading home. Navigate it up the column and into the center square to finish that pawn. +Pawns need the **exact** number to step into the HOME lotus. Get all **four pawns** home and you WIN — and the lotus blooms for every one of them. -Get all **four pawns** home and you WIN. The whole forest celebrates. Probably. I'll celebrate with some honey. +## The Comforts of the Veranda + +- **Danger rings:** a pulsing red ring means one of your pawns could be captured before your next turn. Hover over it and the card tells you exactly how likely, and who's coming for you. +- **Hint (H)** shows the best move with arrows and a little reason ("captures a pawn · leaves nothing exposed"). +- **Skill:** pick each opponent's skill from 1 (a sleepy cub) to 5 (a very sharp bear). +- **House rules** in the menu (Esc): switch off the +20 / +10 bonuses or the third-doubles penalty, or let opponents **share safety squares** like in Spanish parchís. They start with the next game. +- You can also turn off the rain, the confirm step, or speed the opponents up. ## Tips from a Bear Who Just Woke Up @@ -78,9 +93,11 @@ Get all **four pawns** home and you WIN. The whole forest celebrates. Probably. 5. **Race home with your lead pawns.** Once a pawn gets ahead, push it toward the center. Don't dawdle. I spent too long sniffing wildflowers last spring and missed the best part of the salmon run. Don't be me. +6. **Watch the red rings.** If a pawn is glowing red, it's in someone's sights. Hop it to a safety square, pair it up into a blockade, or race it out of reach. + ## About Your Opponents -Whether you're playing against friends or the computer, everyone has the same goal: get your four pawns home before the others. The computer opponent knows the rules and will absolutely try to eat your pawns if it gets the chance. Don't take it personally. It's just nature. +Everyone has the same goal: get four pawns home before the others. The computer opponents know the rules, chat a little across the table, and will absolutely try to eat your pawns if they get the chance. Don't take it personally. It's just nature. Much like how I, Brad, do not take it personally when the salmon swim away. They're just doing their salmon thing. I respect it. Then I catch them anyway. diff --git a/src/scenes/OpponentSelectScene.js b/src/scenes/OpponentSelectScene.js index faea1b9..180b952 100644 --- a/src/scenes/OpponentSelectScene.js +++ b/src/scenes/OpponentSelectScene.js @@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene { // Skill control: pips always show the level; the +/- buttons appear only // when this opponent is selected. Enabled for games with a 1–5 AI skill. - if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride', 'backgammon'].includes(this.gameDef.slug)) { + if (['nerts', 'phase10', 'uno', 'skipbo', 'hearts', 'gofish', 'oldmaid', 'checkers', 'chess', 'wordle', 'scrabble', 'ghost', 'wordladder', 'othello', 'go', 'mastermind', 'connect4', 'boggle', 'forbiddenisland', 'labyrinth', 'stratego', 'triominoes', 'mahjong', 'geniussquare', 'azul', 'dungeonboss', 'swdbg', 'tickettoride', 'backgammon', 'parchisi'].includes(this.gameDef.slug)) { bio.style.webkitLineClamp = '1'; const skillRow = document.createElement('div'); diff --git a/tools/verifyParchisi.js b/tools/verifyParchisi.js new file mode 100644 index 0000000..4c240bf --- /dev/null +++ b/tools/verifyParchisi.js @@ -0,0 +1,310 @@ +#!/usr/bin/env node +// verifyParchisi.js — headless checks for Parchisi ("Monsoon Veranda"): +// • rules on hand-built positions: entering (a 5 / dice totalling 5 / 5-5), +// the entry bop, captures (+20), safety squares (and the share-safe house +// rule), blockades (passing, landing, home path, not moved together on +// doubles), exact count home (+10), doubles backs, third doubles, the +// full-roll rule, bonus forfeits, finishRoll / re-rolls, opening, ranks +// • threat odds: exact roll counts on textbook positions +// • AI soak at 2, 3 and 4 players: games finish, invariants hold, every AI +// plan uses the whole roll +// • skill ladder (mirrored seeds, two players) +// • dice throws land on the rolled faces inside the tray +// • board geometry: path continuity for every colour, nests / home slots, +// layout bounds and overlaps +// Usage: node tools/verifyParchisi.js [--quick] + +import * as L from '../src/games/parchisi/ParchisiLogic.js'; +import * as AI from '../src/games/parchisi/ParchisiAI.js'; +import * as B from '../src/games/parchisi/ParchisiBoard.js'; +import * as Lay from '../src/games/parchisi/ParchisiLayout.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { planTrayThrow, topFace } from '../src/ui/dice/Dice3D.js'; + +const QUICK = process.argv.includes('--quick'); +let pass = 0, fail = 0; +function ok(label, cond, detail = '') { + if (cond) pass++; + else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } +} +const section = (n) => console.log(`\n${n}`); +const N = L.NEST, H = L.HOME; + +// A state with given pawns (progress arrays), current player and dice. +function pos(pawns, { player = 'red', dice = null, opts = {}, players = null } = {}) { + const ps = players ?? Object.keys(pawns); + let s = L.createInitialState(ps, opts); + for (const c of ps) s.pawns[c] = (pawns[c] ?? [N, N, N, N]).slice(); + s.currentPlayer = player; + if (dice) s = L.rollSpecificDice(s, dice[0], dice[1]); + return s; +} +const mv = (m) => `${m.pawnIdx}:${m.from}>${m.to}/${m.combine ? m.combine.join('+') : m.dieUsed}${m.hit ? '*' : ''}`; +const moves = (s) => L.getValidMoves(s).map(mv).sort(); +// progress for colour c standing on track square sq +const at = (c, sq) => L.progressAt(c, sq); + +section('Rules'); +{ + ok('seats: 2 → opposite corners', L.seatColors(2).join() === 'red,yellow'); + ok('seats: 3 and 4', L.seatColors(3).length === 3 && L.seatColors(4).length === 4); + ok('progress 0 is the entry, 63 the home-entry', L.trackIdx('red', 0) === L.ENTRY.red && L.trackIdx('red', 63) === L.HOME_ENTRY.red); + for (const c of L.COLORS) ok(`${c}: home-entry is the square behind its entry`, L.trackIdx(c, 63) === (L.ENTRY[c] + 5) % 68); + + // entering + let s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [5, 2] }); + ok('a 5 enters a pawn', moves(s).includes('0:-1>0/5')); + ok('no other move with everything in the nest', moves(s).length === 1, moves(s).join(' ')); + s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [1, 4] }); + ok('two dice totalling 5 enter a pawn', moves(s).includes('0:-1>0/1+4')); + s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [3, 3] }); + ok('3-3 does not enter (no 5, and doubles never combine)', moves(s).length === 0); + s = pos({ red: [N, N, N, N], yellow: [N, N, N, N] }, { dice: [5, 5] }); + let a = L.applyMove(s, L.getValidMoves(s)[0]); + ok('5-5 enters two pawns', L.getValidMoves(a).some((m) => m.from === N) && L.getValidMoves(a).length >= 1); + // entry bop + s = pos({ red: [N, N, N, N], yellow: [at('yellow', L.ENTRY.red), N, N, N] }, { dice: [5, 1] }); + const bop = L.getValidMoves(s).find((m) => m.from === N); + ok('entering bops a lone opponent on your entry (even though it is safe)', bop?.hit?.color === 'yellow'); + a = L.applyMove(s, bop); + ok('the bopped pawn goes home to its nest, +20 to you', a.pawns.yellow[0] === N && a.movesLeft.includes(20)); + s = pos({ red: [N, N, N, N], yellow: [at('yellow', L.ENTRY.red), at('yellow', L.ENTRY.red), N, N] }, { dice: [5, 1] }); + ok('an opponent blockade on your entry keeps you in', !L.getValidMoves(s).some((m) => m.from === N)); + + // capture & safety + s = pos({ red: [10, N, N, N], yellow: [at('yellow', L.trackIdx('red', 13)), N, N, N] }, { dice: [3, 6] }); + const cap = L.getValidMoves(s).find((m) => m.to === 13); + ok('landing on a lone opponent (not safe) captures', cap?.hit?.color === 'yellow'); + a = L.applyMove(s, cap); + ok('capture: +20 bonus chip and stats', a.movesLeft.includes(20) && a.stats.red.captures === 1 && a.stats.yellow.captured === 1); + ok('the +20 is used whole by one pawn', L.getValidMoves(a).filter((m) => m.dieUsed === 20).every((m) => m.to - m.from === 20)); + const noBonus = L.applyMove(pos({ red: [10, N, N, N], yellow: [at('yellow', L.trackIdx('red', 13)), N, N, N] }, { dice: [3, 6], opts: { captureBonus: false } }), cap); + ok('house rule: no capture bonus', !noBonus.movesLeft.includes(20)); + const safeSq = 4; // a white safety square + const pr = at('red', safeSq); + s = pos({ red: [pr - 2, N, N, N], yellow: [at('yellow', safeSq), N, N, N] }, { dice: [2, 6] }); + ok('cannot land on a safety square held by an opponent', !L.getValidMoves(s).some((m) => m.to === pr)); + s = pos({ red: [pr - 2, N, N, N], yellow: [at('yellow', safeSq), N, N, N] }, { dice: [2, 6], opts: { shareSafe: true } }); + const share = L.getValidMoves(s).find((m) => m.to === pr); + ok('house rule share-safe: may share it, without capturing', share && !share.hit); + + // blockades + const bq = at('yellow', L.trackIdx('red', 14)); + s = pos({ red: [10, N, N, N], yellow: [bq, bq, N, N] }, { dice: [6, 2] }); + ok('cannot pass an opponent blockade', !L.getValidMoves(s).some((m) => m.to > 13 && m.pawnIdx === 0 && m.from === 10)); + s = pos({ red: [10, 14, 14, N], yellow: [N, N, N, N] }, { dice: [6, 3] }); + ok('cannot pass your own blockade either', !L.getValidMoves(s).some((m) => m.pawnIdx === 0 && m.to > 14)); + s = pos({ red: [66, 68, 68, N], yellow: [N, N, N, N] }, { dice: [3, 1] }); + ok('a blockade on your home path blocks your own pawns', !L.getValidMoves(s).some((m) => m.pawnIdx === 0 && m.to > 68)); + ok('two pawns may share a home-path square', L.getValidMoves(pos({ red: [66, 68, N, N], yellow: [N, N, N, N] }, { dice: [2, 5] })).some((m) => m.pawnIdx === 0 && m.to === 68)); + s = pos({ red: [20, 20, 30, 40], yellow: [N, N, N, N] }, { dice: [3, 3] }); + a = L.applyMove(s, L.getValidMoves(s).find((m) => m.pawnIdx === 0 && m.dieUsed === 3)); + ok('doubles: the second pawn of a blockade may not follow to the same square', !L.getValidMoves(a).some((m) => m.pawnIdx === 1 && m.to === 23)); + ok('…but it may use a back (4) instead', L.getValidMoves(a).some((m) => m.pawnIdx === 1 && m.to === 24)); + + // home + s = pos({ red: [69, N, N, N], yellow: [N, N, N, N] }, { dice: [2, 6] }); + ok('exact count into HOME', L.getValidMoves(s).some((m) => m.to === H) && !L.getValidMoves(s).some((m) => m.dieUsed === 6 && m.pawnIdx === 0)); + a = L.applyMove(s, L.getValidMoves(s).find((m) => m.to === H)); + ok('reaching HOME earns +10', a.movesLeft.includes(10) && a.stats.red.home === 1); + const fin = pos({ red: [H, H, H, 70], yellow: [N, N, N, N] }, { dice: [1, 3] }); + const won = L.applyMove(fin, L.getValidMoves(fin).find((m) => m.to === H)); + ok('fourth pawn home wins', won.phase === 'game_over' && won.winner === 'red'); + ok('rankings put the winner first', L.rankings(won)[0] === 'red'); + + // doubles & backs + s = pos({ red: [10, 20, 30, H], yellow: [N, N, N, N] }, { dice: [2, 2] }); + ok('doubles with every pawn out add the backs (5 and 5)', s.movesLeft.slice().sort().join() === '2,2,5,5'); + s = pos({ red: [10, 20, 30, N], yellow: [N, N, N, N] }, { dice: [2, 2] }); + ok('no backs while a pawn is still in the nest', s.movesLeft.join() === '2,2'); + let r = L.finishRoll(L.applyMove(L.applyMove(s, L.getValidMoves(s)[0]), L.getValidMoves(L.applyMove(s, L.getValidMoves(s)[0]))[0])); + ok('after doubles the same player rolls again', r.currentPlayer === 'red' && r.phase === 'roll' && r.lastEvent.type === 'again'); + // three doubles + let t3 = pos({ red: [10, 50, 66, N], yellow: [N, N, N, N] }); + t3.consecutiveDoubles = 2; + const pen = L.rollSpecificDice(t3, 4, 4); + ok('third doubles: most advanced pawn back to the nest, turn over', pen.pawns.red[2] === N && pen.currentPlayer === 'yellow' && pen.lastEvent.type === 'threeDoubles' && pen.lastEvent.pawnIdx === 2 && pen.lastEvent.dice.join() === '4,4'); + t3 = pos({ red: [10, 50, 66, N], yellow: [N, N, N, N] }, { opts: { threeDoubles: false } }); + t3.consecutiveDoubles = 2; + ok('house rule: no third-doubles penalty', L.rollSpecificDice(t3, 4, 4).phase === 'move'); + // full-roll rule + { + // yellow blockade 6 ahead of pawn 0; pawn 1 near home. 5 then 6 (pawn 0 then 1) + // or 6 with pawn 1 first both use the whole roll; pawn 1 taking the 5 first + // strands the 6, so it is not offered. + const blk = at('yellow', L.trackIdx('red', 16)); + const st = pos({ red: [10, 62, H, H], yellow: [blk, blk, N, N] }, { dice: [5, 6] }); + const v = moves(st); + ok('full-roll rule: a first move that strands the other die is not offered', v.join(' ') === '0:10>15/5 1:62>68/6', v.join(' ')); + const st2 = pos({ red: [65, H, H, H], yellow: [N, N, N, N] }, { dice: [6, 1] }); + ok('no higher-die rule: with one die usable either may be played', moves(st2).join(' ') === '0:65>66/1 0:65>71/6', moves(st2).join(' ')); + const st3 = pos({ red: [69, N, N, N], yellow: [N, N, N, N] }, { dice: [2, 3] }); + ok('full-roll rule: 2+3 must enter a pawn rather than spend the 2 going home', moves(st3).join(' ') === '1:-1>0/2+3', moves(st3).join(' ')); + } + // forfeits and passing + s = pos({ red: [69, N, N, N], yellow: [N, N, N, N] }, { dice: [2, 4] }); + a = L.applyMove(s, L.getValidMoves(s).find((m) => m.to === H)); + ok('with nothing able to use them, leftover dice and the +10 end the roll', L.turnDone(a)); + r = L.finishRoll(a); + ok('finishRoll passes the turn and counts the forfeited bonus', r.currentPlayer === 'yellow' && r.stats.red.forfeits === 1); + // opening + const op = L.rollOpening(L.createInitialState(L.seatColors(4)), mulberry32(4)); + const last = op.opening[op.opening.length - 1]; + ok('opening: the starter threw the highest die of the last round', last[op.currentPlayer] === Math.max(...Object.values(last)) && Object.values(last).filter((f) => f === last[op.currentPlayer]).length === 1); + ok('moveText reads well', /enters \(5\)/.test(L.moveText({ from: N, to: 0, dieUsed: 5 })) && /capture/.test(L.moveText({ from: 3, to: 8, dieUsed: 5, hit: {} }))); +} + +section('Threat odds'); +{ + const sq = L.trackIdx('red', 20); + // one yellow pawn 3 squares behind a lone red pawn, yellow still has nest pawns + let s = pos({ red: [20, N, N, N], yellow: [at('yellow', sq) - 3, N, N, N] }); + ok('3 behind: 13/36 (any 3, or 1+2)', Math.abs(AI.hitProb(s, 'yellow', sq) - 13 / 36) < 1e-9, `${AI.hitProb(s, 'yellow', sq) * 36}`); + s = pos({ red: [20, N, N, N], yellow: [at('yellow', sq) - 3, at('yellow', sq) - 30, at('yellow', sq) - 40, H] }); + ok('3 behind with every yellow pawn out: 4-4 backs add one roll → 14/36', Math.abs(AI.hitProb(s, 'yellow', sq) - 14 / 36) < 1e-9, `${AI.hitProb(s, 'yellow', sq) * 36}`); + s = pos({ red: [20, N, N, N], yellow: [at('yellow', sq) - 8, N, N, N] }); + ok('8 behind: 5/36 (2+6, 3+5, 4+4)', Math.abs(AI.hitProb(s, 'yellow', sq) - 5 / 36) < 1e-9, `${AI.hitProb(s, 'yellow', sq) * 36}`); + const safeP = L.progressAt('red', 21); + s = pos({ red: [safeP, N, N, N], yellow: [at('yellow', 21) - 3, N, N, N] }); + ok('a pawn on a safety square is never at risk', AI.threatOf(s, 'red', safeP) === 0); + s = pos({ red: [L.progressAt('red', L.ENTRY.yellow), N, N, N], yellow: [N, N, N, N] }); + ok('sitting on an opponent\'s entry while they have nest pawns: 15/36 (a 5 or a total of 5)', Math.abs(AI.threatOf(s, 'red', s.pawns.red[0]) - 15 / 36) < 1e-9); + s = pos({ red: [20, 20, N, N], yellow: [at('yellow', sq) - 3, N, N, N] }); + ok('a blockade is never at risk', AI.threatOf(s, 'red', 20) === 0); + const blk = at('yellow', L.trackIdx('red', 22)); + s = pos({ red: [20, 22, 22, N], yellow: [at('yellow', sq) - 6, N, N, N], green: [blk, N, N, N] }, { players: ['red', 'yellow', 'green'] }); + ok('dangerReport lists exposed pawns with who threatens them', AI.dangerReport(s, 'red').some((d) => d.pawnIdx === 0 && d.by.some((b) => b.color === 'yellow'))); +} + +section('AI soak'); +AI.SKILL[5] = { ...AI.SKILL[5] }; +function play(skills, seed, n = 2, { check = false } = {}) { + const dice = mulberry32(seed), noise = mulberry32(seed * 13 + 5); + let s = L.rollOpening(L.createInitialState(L.seatColors(n)), dice); + const sk = Object.fromEntries(s.players.map((c, i) => [c, skills[i % skills.length]])); + let guard = 0, bad = 0, partial = 0; + while (s.phase !== 'game_over' && guard++ < 5000) { + if (s.phase === 'roll') { s = L.rollDice(s, dice); continue; } + const plan = AI.chooseMoves(s, sk[s.currentPlayer], noise); + for (const m of plan) { + if (check && !L.getValidMoves(s).some((q) => q.pawnIdx === m.pawnIdx && q.to === m.to && q.dieUsed === m.dieUsed)) bad++; + s = L.applyMove(s, m); + if (s.phase === 'game_over') break; + } + if (s.phase === 'game_over') break; + if (!L.turnDone(s)) partial++; + if (check) { + const occ = new Map(); + for (const c of s.players) s.pawns[c].forEach((p) => { + if (p < -1 || p > H) bad++; + if (L.onTrack(p)) { const k = L.trackIdx(c, p); occ.set(k, (occ.get(k) ?? 0) + 1); } + }); + for (const v of occ.values()) if (v > 2) bad++; + for (const c of s.players) for (let h = L.HOME_PATH0; h < H; h++) if (s.pawns[c].filter((p) => p === h).length > 2) bad++; + } + s = L.finishRoll(s); + } + return { winner: s.winner, players: s.players, guard, bad, partial }; +} +{ + const G = QUICK ? 18 : 90; + let fin = 0, bad = 0, partial = 0; + for (let g = 0; g < G; g++) { + const r = play([1 + (g % 5), 1 + ((g + 2) % 5), 1 + ((g + 4) % 5), 3], 500 + g, 2 + (g % 3), { check: true }); + if (r.winner) fin++; + bad += r.bad; partial += r.partial; + } + ok(`${G} all-AI games at 2–4 players all finish`, fin === G, `${fin}/${G}`); + ok('board invariants hold (≤ 2 per square, legal moves only)', bad === 0, `${bad}`); + ok('every AI plan uses the whole roll', partial === 0, `${partial}`); + const t0 = Date.now(); + let st = L.rollOpening(L.createInitialState(L.seatColors(4)), mulberry32(8)); + st.pawns.red = [10, 20, 30, 40]; + st.currentPlayer = 'red'; + st = L.rollSpecificDice(st, 6, 6); + AI.chooseMoves(st, 5, () => 0.5); + ok('a skill-5 search on doubles-with-backs stays quick', Date.now() - t0 < 1200, `${Date.now() - t0} ms`); + const h = AI.hint(L.rollSpecificDice(pos({ red: [10, N, N, N], yellow: [at('yellow', L.trackIdx('red', 13)), N, N, N] }), 3, 6)); + ok('hint takes the capture', h.moves.some((m) => m.hit), h.reason); + ok('hint explains itself', /captures a pawn/i.test(h.reason), h.reason); +} + +section('Skill ladder (mirrored seeds, 2 players)'); +{ + const pairs = (a, b, n, off) => { + let w = 0; + for (let i = 0; i < n; i++) { + const r1 = play([a, b], 9000 + off + i), r2 = play([b, a], 9000 + off + i); + if (r1.winner === r1.players[0]) w++; + if (r2.winner === r2.players[1]) w++; + } + return w / (2 * n); + }; + const n = QUICK ? 20 : 150; + for (const [a, b, need] of [[2, 1, 0.6], [3, 2, 0.58], [4, 3, 0.52], [5, 4, 0.52]]) { + const r = pairs(a, b, n, a * 1000); + console.log(` skill ${a} vs ${b}: ${(r * 100).toFixed(1)}% over ${2 * n} games`); + if (!QUICK) ok(`skill ${a} beats skill ${b}`, r > need, `${(r * 100).toFixed(1)}%`); + } +} + +section('Dice throws'); +{ + const rng = mulberry32(3); + let badFace = 0, outside = 0; + for (let k = 0; k < (QUICK ? 40 : 160); k++) { + const c = L.COLORS[k % 4]; + const faces = [1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6)]; + const plan = planTrayThrow(Lay.TRAY_WORLD, Lay.throwOrigin(c), faces, rng, Lay.DIE_SIZE, { spread: 1.4, sep: 1.5, aim: { u0: 0.2, u1: 0.8, v0: 0.3, v1: 0.7 } }); + plan.dice.forEach((d, i) => { + const f = d.frames[d.frames.length - 1]; + if (topFace(f.q) !== faces[i]) badFace++; + if (f.u < 0 || f.u > Lay.TRAY_WORLD.w || f.v < 0 || f.v > Lay.TRAY_WORLD.h) outside++; + }); + } + ok('throws land on the rolled faces', badFace === 0, `${badFace}`); + ok('dice stay in the tray', outside === 0, `${outside}`); + const r4 = Lay.diceRest(4); + ok('four resting dice (roll + backs) are apart', r4.every((a, i) => r4.every((b, j) => i === j || Math.hypot(a.u - b.u, a.v - b.v) > Lay.DIE_SIZE * 1.3))); +} + +section('Board & layout'); +{ + for (const c of L.COLORS) { + let okPath = true; + for (let p = 0; p < H - 1; p++) { + const a = B.cellOf(c, p), b = B.cellOf(c, p + 1); + if (!a || !b || Math.hypot(a.x - b.x, a.y - b.y) > B.CELL * 1.5) okPath = false; + } + ok(`${c}: every step of the path is to a neighbouring cell`, okPath); + const last = B.cellOf(c, H - 1), hs = B.homeSlot(c, 0); + ok(`${c}: the last home-path square touches its HOME triangle`, Math.hypot(last.x - hs.x, last.y - hs.y) < B.CELL * 1.9); + const r = B.NEST_RECT[c]; + ok(`${c}: nest seats inside the nest`, [0, 1, 2, 3].every((i) => { + const q = B.nestSlot(c, i); + return q.x > B.ORIGIN_X + r.col0 * B.CELL && q.x < B.ORIGIN_X + (r.col1 + 1) * B.CELL && q.y > B.ORIGIN_Y + r.row0 * B.CELL && q.y < B.ORIGIN_Y + (r.row1 + 1) * B.CELL; + })); + const ent = B.cellOf(c, 0), nc = B.nestCenter(c); + ok(`${c}: entry square sits beside its nest`, Math.hypot(ent.x - nc.x, ent.y - nc.y) < B.CELL * 5.5); + } + const cells = new Set(); + for (let i = 0; i < 68; i++) { const t = B.trackXY(i); cells.add(`${t.col},${t.row}`); } + for (const c of L.COLORS) for (let k = 0; k < 7; k++) { const t = B.homeXY(c, k); cells.add(`${t.col},${t.row}`); } + ok('68 track + 28 home-path cells are all distinct', cells.size === 96); + const F = Lay.hudFurniture(); + const inScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= Lay.W && r.y + r.h <= Lay.H; + for (const [k, r] of Object.entries(F)) ok(`${k} on screen`, inScreen(r), JSON.stringify(r)); + const keys = Object.keys(F); + const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; + const ov = []; + for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) if (overlap(F[keys[i]], F[keys[j]])) ov.push(`${keys[i]}×${keys[j]}`); + ok('HUD furniture never overlaps', ov.length === 0, ov.join(', ')); + for (const c of L.COLORS) { + const b = Lay.plateParts(c).bubble; + ok(`${c} speech bubble on screen and off the board`, inScreen(b) && !overlap(b, Lay.BOARD_RECT)); + } + ok('six move chips fit on the chip card', [0, 5].every((i) => { const r = Lay.chipRect(i, 6); return r.x >= Lay.CHIPS.x && r.x + r.w <= Lay.CHIPS.x + Lay.CHIPS.w; })); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0);