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
This commit is contained in:
Brian Fertig 2026-11-25 14:09:55 -07:00
parent 43ca22b63a
commit ec09bb42f5
No known key found for this signature in database
17 changed files with 3478 additions and 1495 deletions

View File

@ -28,7 +28,7 @@ export function getGame(slug) {
// Built-in catalog so the menu has something to show. // 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: '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: '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: 'holdem', name: "Texas Hold 'Em", category: 'casino', cardGame: true, minPlayers: 2, maxPlayers: 8, minOpponents: 3, maxOpponents: 7, iconFrame: 3 });
registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 4 }); registerGame({ slug: 'yatzi', name: 'Zahtzee', category: 'cards', minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 4 });

View File

@ -31,7 +31,7 @@ import { bell, slam, tap, Waves } from './BackgammonSound.js';
const SETTINGS_KEY = 'backgammon-settings'; const SETTINGS_KEY = 'backgammon-settings';
const DEFAULT_SETTINGS = { const DEFAULT_SETTINGS = {
pace: 'normal', confirm: true, autoRoll: false, autoForced: true, hints: true, pips: true, 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 = { const D = {
bg: 0, case: 5, labels: 6, glow: 9, checker: 10, marker: 13, dice: 22, cube: 24, bg: 0, case: 5, labels: 6, glow: 9, checker: 10, marker: 13, dice: 22, cube: 24,

View File

@ -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 { import {
COLORS, ENTRY, HOME_ENTRY, TRACK_LEN, NEST, HOME, HOME_PATH0, LAST_TRACK, ENTRY, onTrack, trackIdx, progressAt, isSafeTrack,
cloneState, getValidMoves, applyMove, getValidMoves, applyMove, finishRoll, rollSpecificDice, pawnsInNest, pawnsHome, blockadeSquares,
blockadeSet, pawnsHome, pawnsInNest, isSafeTrack,
totalPipsRemaining, totalPipsRemaining,
} from './ParchisiLogic.js'; } from './ParchisiLogic.js';
// Returns an ordered array of moves for the AI player to execute this turn. const ROLLS = [];
// The caller should apply them one at a time (with animation), not all at once. for (let a = 1; a <= 6; a++) for (let b = a; b <= 6; b++) ROLLS.push({ a, b, w: a === b ? 1 : 2 });
export function chooseMoves(state) {
if (state.phase !== 'move') return [];
const sequences = generateSequences(state, 0);
if (sequences.length === 0) return [];
const player = state.currentPlayer; export const TUNE = {
let best = sequences[0]; leadW: 0.45, avgW: 0.15, threat: 1, threatBase: 22, safe: 2.5, blockade: 3, trapped: 2.2, shots: 2.5, nest: -9,
let bestScore = evaluateState(best.finalState, player); homeBonus: 26, pathBonus: 9,
for (let i = 1; i < sequences.length; i++) { };
const sc = evaluateState(sequences[i].finalState, player);
if (sc > bestScore) { bestScore = sc; best = sequences[i]; } // ── 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 // Probability that player `c`, rolling next, can land on track square `sq`.
const BRANCH_CAP = 24; // cap branches per node to keep search tractable export function hitProb(s, c, sq, blocked = null) {
const entryBop = sq === ENTRY[c] && pawnsInNest(s, c) > 0;
function generateSequences(state, depth) { if (isSafeTrack(sq) && !entryBop) return 0;
if (depth > MAX_DEPTH || state.phase !== 'move' || state.movesLeft.length === 0) { const k = progressAt(c, sq);
return [{ moves: [], finalState: state }]; const dists = [];
} if (k >= 0 && !isSafeTrack(sq)) {
const bl = blocked ?? new Set(blockadeSquares(s).map((b) => b.sq));
const moves = getValidMoves(state); for (const q of s.pawns[c]) {
if (moves.length === 0) { if (!onTrack(q) || q >= k || k - q > 24) continue;
// No legal move; apply a synthetic pass by clearing remaining dice. let ok = true;
const skipped = cloneState(state); for (let t = q + 1; t < k; t++) if (bl.has(trackIdx(c, t))) { ok = false; break; }
skipped.movesLeft = []; if (ok) dists.push(k - q);
return [{ moves: [], finalState: skipped }];
}
// 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);
const results = [];
const seen = new Set();
const player = state.currentPlayer;
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 });
}
continue;
}
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 });
} }
} }
if (!dists.length && !entryBop) return 0;
return results.length > 0 ? results : [{ moves: [], finalState: state }]; 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;
} }
function moveHeuristic(state, m) { // P(the pawn of `color` at progress p is captured before `color` moves again),
let h = 0; // treating each opponent's next roll as independent.
if (m.hit) h += 100; export function threatOf(s, color, p, blocked = null) {
if (m.to.loc === 'home') h += 70; if (!onTrack(p)) return 0;
if (m.to.home !== undefined) h += 20; const sq = trackIdx(color, p);
if (m.from.loc === 'nest') h += 15; if (s.pawns[color].filter((q) => onTrack(q) && trackIdx(color, q) === sq).length >= 2) return 0;
// Larger dice first slightly preferred to flush out 6s const bl = blocked ?? new Set(blockadeSquares(s).map((b) => b.sq));
h += (m.dieUsed ?? 0) * 0.5; let survive = 1;
return h; for (const c of s.players) if (c !== color) survive *= 1 - hitProb(s, c, sq, bl);
return 1 - survive;
} }
function boardHash(state) { // For the danger overlay: [{ pawnIdx, risk, by: [colors] }] for `color`'s exposed pawns.
const parts = []; export function dangerReport(s, color) {
for (const c of COLORS) { const bl = new Set(blockadeSquares(s).map((b) => b.sq));
const sorted = [...state.pawns[c]].map((p) => { const out = [];
if (p.loc === 'nest') return 'N'; s.pawns[color].forEach((p, i) => {
if (p.loc === 'home') return 'H'; if (!onTrack(p)) return;
if (p.home !== undefined) return `h${p.home}`; const sq = trackIdx(color, p);
return `t${p.track}`; if (s.pawns[color].filter((q) => onTrack(q) && trackIdx(color, q) === sq).length >= 2) return;
}).sort(); let survive = 1;
parts.push(`${c}:${sorted.join(',')}`); 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; }
} }
parts.push(`m:${[...state.movesLeft].sort().join(',')}`); if (by.length) out.push({ pawnIdx: i, risk: 1 - survive, by });
return parts.join('|'); });
return out;
} }
// ─── Evaluation ─────────────────────────────────────────────────────────── // ── 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;
}
function evaluateState(state, player) { export function evaluate(s, me, mode = 'full') {
let score = 0; if (s.winner) return s.winner === me ? 1e5 : -1e5;
const opps = COLORS.filter((c) => c !== player); 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;
// Pip progress if (mode === 'simple') {
const ownPips = totalPipsRemaining(state, player); score += pawnsHome(s, me) * 25 + (4 - pawnsInNest(s, me)) * 5;
score -= ownPips * 1.0; const bl = blockadeSquares(s);
for (const o of opps) score += totalPipsRemaining(state, o) * 0.25; score += bl.filter((b) => b.color === me).length * 14;
// exposed: alone, not safe, an enemy within 12 behind
// Pawns home for (const p of s.pawns[me]) {
score += pawnsHome(state, player) * 50; if (!onTrack(p)) continue;
for (const o of opps) score -= pawnsHome(state, o) * 25; const sq = trackIdx(me, p);
if (isSafeTrack(sq)) continue;
// Pawns out of nest (mobility) if (s.pawns[me].filter((q) => onTrack(q) && trackIdx(me, q) === sq).length >= 2) continue;
for (const c of COLORS) { let near = false;
const out = 4 - pawnsInNest(state, c); for (const c of others) {
if (c === player) score += out * 5; const k = progressAt(c, sq);
else score -= out * 2; if (k < 0) continue;
if (s.pawns[c].some((q) => onTrack(q) && k - q >= 1 && k - q <= 12)) { near = true; break; }
}
if (near) score -= 8;
}
return score;
} }
// Own blockades — strong positional value const blockList = blockadeSquares(s);
const myBlockades = countOwnBlockades(state, player); const bl = new Set(blockList.map((b) => b.sq));
score += myBlockades * 18; for (const p of s.pawns[me]) {
if (!onTrack(p)) continue;
// Blot exposure: own single pawns at risk from opponents behind them const sq = trackIdx(me, p);
score -= blotExposure(state, player) * 8; 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 score; return score;
} }
function countOwnBlockades(state, player) { // ── sequence search ──────────────────────────────────────────────────────────
const bset = blockadeSet(state); const MAX_DEPTH = 8;
let count = 0; const BRANCH_CAP = 18;
for (const idx of bset) {
const own = state.pawns[player].some((p) => p.track === idx); function keyOf(s) {
if (own) count++; return s.players.map((c) => s.pawns[c].slice().sort((a, b) => a - b).join(',')).join('|') + '#' + s.movesLeft.slice().sort().join(',');
}
return count;
} }
// Count of own pawns that sit alone on a non-safe square within 12 squares function quick(s, m) {
// in front of any opponent pawn (so an opponent could land on them). let h = 0;
function blotExposure(state, player) { if (m.hit) h += 100;
let expo = 0; if (m.to === HOME) h += 70;
for (let i = 0; i < 4; i++) { if (m.to >= HOME_PATH0) h += 20;
const p = state.pawns[player][i]; if (m.from === NEST) h += 15;
if (p.track === undefined) continue; return h + m.dieUsed * 0.5;
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; }
}
}
}
return expo;
} }
// Re-export for tests. // Past the node budget, finish a line greedily (best quick-heuristic move).
export { evaluateState }; 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 st;
}
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 };

View File

@ -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-<c> turned "beehive" pawns in coloured lacquer
// pc-pawn-shadow, pc-glow, pc-ring
// pc-petal-<c> 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;

View File

@ -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 };

View File

@ -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;
}

View File

@ -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 };
}

File diff suppressed because it is too large Load Diff

View File

@ -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)); }
}

View File

@ -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;
}

View File

@ -1,428 +1,416 @@
// Pure Parcheesi (American standard) rules. No Phaser dependency. // ParchisiLogic.js — pure Parcheesi (American standard) rules. No Phaser.
// //
// Board model: // Board model
// - 68-square outer track (indices 0..67), clockwise. // 68-square outer track (0..67); movement is counter-clockwise (index − 1).
// - 4 colors with fixed entry squares 17 apart: red=0, blue=17, yellow=34, green=51. // Entries (safe, coloured): red 11, blue 62, yellow 45, green 28.
// - Each color travels 67 outer steps from its entry to its own home-entry // Home-entry (last track square before the home path): red 16, blue 67,
// (which is the square immediately CCW from the entry: entry-1 mod 68), // yellow 50, green 33. Then 7 home-path squares, then HOME.
// then 7 squares up its home column, then 1 final step into home.
// - Total path from entry to home = 75 movement pips.
// //
// Pawn position is one of: // A pawn is one integer: its PROGRESS along its own path.
// 'nest' | { track: 0..67 } | { home: 0..6 } | 'home' // −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 // Rules (Hasbro): enter with a 5 on one die or the two dice totalling 5 (a
// at +7 and +12 from each entry. Pawns cannot be captured on a safe square, // pawn entering bops a lone opponent on its entry square); captures send a
// EXCEPT a pawn entering the board (leaving the nest with a 5) bops any // lone pawn on a non-safe square back to its nest (+20 bonus); reaching home
// single opponent occupying its entry square. // 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 COLORS = ['red', 'blue', 'yellow', 'green'];
export const ENTRY = { red: 11, blue: 62, yellow: 45, green: 28 }; 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 HOME_ENTRY = { red: 16, blue: 67, yellow: 50, green: 33 };
export const TRACK_LEN = 68; export const TRACK_LEN = 68;
export const HOME_COL_LEN = 7; export const HOME_COL_LEN = 7;
export const PAWNS_PER_PLAYER = 4; 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([ const SAFE_SET = new Set([4, 11, 16, 21, 28, 33, 38, 45, 50, 55, 62, 67]);
4, 11, 16, export const isSafeTrack = (idx) => SAFE_SET.has(idx);
21, 28, 33,
38, 45, 50,
55, 62, 67,
]);
export function isSafeTrack(idx) { // Seats for 2–4 players (opposite corners for two).
return SAFE_SET.has(idx); 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) { export const trackIdx = (color, p) => ((ENTRY[color] - p) % TRACK_LEN + TRACK_LEN) % TRACK_LEN;
const pawns = {}; export const onTrack = (p) => p >= 0 && p <= LAST_TRACK;
for (const c of COLORS) { export const onHomePath = (p) => p >= HOME_PATH0 && p < HOME;
pawns[c] = Array.from({ length: PAWNS_PER_PLAYER }, () => ({ loc: 'nest' }));
} // 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 { return {
players: [...playerOrder], players,
pawns, pawns,
currentPlayer: playerOrder[0], opts: { ...DEFAULT_OPTS, ...opts },
currentPlayer: players[0],
dice: null, dice: null,
movesLeft: [], // remaining die values: 1..6, plus bonus 10/20 movesLeft: [],
rolledDoubles: false,
consecutiveDoubles: 0, consecutiveDoubles: 0,
lastWasDoubles: false, // if true and dice exhausted, same player re-rolls rollMoves: [], // [{ pawnIdx, from, to }] this roll (blockade-on-doubles rule)
phase: 'roll', // 'roll' | 'move' | 'game_over' phase: 'roll', // roll | move | game_over
winner: null, 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) { export function cloneState(s) { return JSON.parse(JSON.stringify(s)); }
return JSON.parse(JSON.stringify(state));
}
// ─── Dice ────────────────────────────────────────────────────────────────── // ── opening: each player throws one die; highest starts (ties re-throw) ─────
export function rollOpening(state, rng = Math.random) {
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) {
const s = cloneState(state); const s = cloneState(state);
s.dice = [d1, d2]; const rounds = [];
const doubles = d1 === d2; let contenders = s.players.slice();
while (contenders.length > 1) {
if (doubles) { const faces = {};
s.consecutiveDoubles += 1; for (const c of contenders) faces[c] = 1 + Math.floor(rng() * 6);
s.lastWasDoubles = true; rounds.push(faces);
if (s.consecutiveDoubles >= 3) { const hi = Math.max(...Object.values(faces));
// Three-doubles penalty: furthest-from-home pawn of current player contenders = contenders.filter((c) => faces[c] === hi);
// 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; s.currentPlayer = contenders[0];
if (allOut) { s.opening = rounds;
// Bonus moves: also use the "back" of each die (1↔6, 2↔5, 3↔4) s.lastEvent = { type: 'opening', starter: contenders[0], rounds };
s.movesLeft = [d1, d2, 7 - d1, 7 - d2];
} else {
s.movesLeft = [d1, d2];
}
} else {
s.consecutiveDoubles = 0;
s.lastWasDoubles = false;
s.movesLeft = [d1, d2];
}
s.phase = 'move';
return s; return s;
} }
function applyThreeDoublesPenalty(s) { // ── occupancy ────────────────────────────────────────────────────────────────
const player = s.currentPlayer; // Map trackIdx → [{ color, pawnIdx }]
// Hasbro rule: "the pawn farthest along on its journey to Home" = function trackOcc(s) {
// 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<trackIdx, Array<{color, pawnIdx}>>
const m = new Map(); const m = new Map();
for (const c of COLORS) { for (const c of s.players) {
for (let i = 0; i < PAWNS_PER_PLAYER; i++) { const ps = s.pawns[c];
const p = s.pawns[c][i]; for (let i = 0; i < 4; i++) {
if (p.track !== undefined) { if (!onTrack(ps[i])) continue;
const arr = m.get(p.track) ?? []; const sq = trackIdx(c, ps[i]);
arr.push({ color: c, pawnIdx: i }); const a = m.get(sq);
m.set(p.track, arr); if (a) a.push({ color: c, pawnIdx: i }); else m.set(sq, [{ color: c, pawnIdx: i }]);
}
} }
} }
return m; return m;
} }
// A blockade is 2 same-color pawns on one outer-track square. const isBlockade = (occ) => occ && occ.length >= 2 && occ[0].color === occ[1].color;
// Returns Set of trackIdx that are blockades.
function blockadeSet(s) { export function blockadeSquares(s) {
const set = new Set(); const out = [];
const map = pawnsOnTrack(s); for (const [sq, occ] of trackOcc(s)) if (isBlockade(occ)) out.push({ sq, color: occ[0].color });
for (const [idx, arr] of map) { return out;
if (arr.length >= 2 && arr.every((p) => p.color === arr[0].color)) {
set.add(idx);
}
}
return set;
} }
// Returns occupant of a track square: null | {color, count}. function homeCount(s, color, p) {
function trackOccupants(s, idx) { let n = 0;
const arr = []; for (const q of s.pawns[color]) if (q === p) n++;
for (const c of COLORS) { return n;
for (let i = 0; i < PAWNS_PER_PLAYER; i++) {
if (s.pawns[c][i].track === idx) arr.push({ color: c, pawnIdx: i });
}
}
return arr;
} }
// Returns count of pawns of this color in this home-col index. export const pawnsInNest = (s, c) => s.pawns[c].filter((p) => p === NEST).length;
function homeColOccupants(s, color, hIdx) { export const pawnsHome = (s, c) => s.pawns[c].filter((p) => p === HOME).length;
return s.pawns[color].filter((p) => p.home === hIdx).length;
// ── dice ─────────────────────────────────────────────────────────────────────
export function rollDice(state, rng = Math.random) {
return rollSpecificDice(state, 1 + Math.floor(rng() * 6), 1 + Math.floor(rng() * 6));
} }
// ─── Move generation ─────────────────────────────────────────────────────── export function rollSpecificDice(state, d1, d2) {
const s = cloneState(state);
// Build the path squares a pawn would traverse moving `steps` from `from`. const c = s.currentPlayer;
// Returns an ORDERED array of positions for each step taken (length = steps). s.dice = [d1, d2];
// The final element is the landing square. Returns null if path is invalid s.turn++;
// (overshoots home). s.rollMoves = [];
function projectPath(from, color, steps) { s.stats[c].rolls++;
const path = []; const doubles = d1 === d2;
let pos = from; s.rolledDoubles = doubles;
for (let k = 0; k < steps; k++) { if (doubles) {
if (pos.loc === 'nest') return null; // nest exit handled separately s.stats[c].doubles++;
if (pos === 'home' || pos.loc === 'home') return null; s.consecutiveDoubles++;
if (pos.home !== undefined) { if (s.opts.threeDoubles && s.consecutiveDoubles >= 3) {
const next = pos.home + 1; // the most advanced pawn not already home goes back to the nest
if (next < HOME_COL_LEN) { pos = { home: next }; path.push(pos); } let best = -1, bestP = -1;
else if (next === HOME_COL_LEN) { pos = { loc: 'home' }; path.push(pos); } s.pawns[c].forEach((p, i) => { if (p !== HOME && p > bestP) { bestP = p; best = i; } });
else return null; // overshoot 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 { } else {
// On outer track s.consecutiveDoubles = 0;
if (pos.track === HOME_ENTRY[color]) { s.movesLeft = [d1, d2];
pos = { home: 0 };
path.push(pos);
} else {
const nextIdx = (pos.track - 1 + TRACK_LEN) % TRACK_LEN;
pos = { track: nextIdx };
path.push(pos);
} }
} s.phase = 'move';
} s.lastEvent = { type: 'roll', color: c, dice: [d1, d2], backs: s.movesLeft.length === 4 };
return path; if (!getValidMoves(s).length) s.stats[c].blocked++;
return s;
} }
// Check if a movement path is blocked by any blockade (track squares only). // ── move generation ──────────────────────────────────────────────────────────
// The first step's "from" is NOT included; we examine every square the pawn const isBase = (d) => d <= 6;
// 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 // Raw candidate moves for the current player (no full-roll filter).
// rule, you cannot land on or pass any blockade (your own or opponents'). function candidates(s) {
function pathBlocked(path, blockades) { if (s.phase !== 'move') return [];
for (const sq of path) { const c = s.currentPlayer;
if (sq.track !== undefined && blockades.has(sq.track)) return true; const ps = s.pawns[c];
const occ = trackOcc(s);
const out = [];
const dice = [...new Set(s.movesLeft)];
const share = s.opts.shareSafe;
// 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 false; }
}
}
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 out;
} }
// Build a Move object describing a pawn step. dieUsed is the die value const usedBase = (m) => (m.combine ? 2 : isBase(m.dieUsed) ? 1 : 0);
// consumed (1..6, or 10/20 for bonuses).
function makeMove(player, pawnIdx, from, to, dieUsed, hit = null) { // Most base dice the player can still use from here (bonuses ignored).
const move = { player, pawnIdx, from, to, dieUsed, hit }; function maxBase(s, memo) {
return move; 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. const validCache = new WeakMap();
// Returns flat array of single-die moves. Sum-of-5 nest entries are also
// included as special moves with `combineDice: [d1, d2]` (dieUsed=5). // Legal moves now: each keeps the most of the rolled dice still usable.
export function getValidMoves(s) { export function getValidMoves(s) {
if (s.phase !== 'move') return []; if (s.phase !== 'move') return [];
const player = s.currentPlayer; if (validCache.has(s)) return validCache.get(s);
const moves = []; const cand = candidates(s);
const blockades = blockadeSet(s); let out = cand;
const uniqueDice = [...new Set(s.movesLeft)]; if (cand.length > 1 && s.movesLeft.some(isBase)) {
const inNest = s.pawns[player].some((p) => p.loc === 'nest'); const memo = new Map();
const target = maxBase(s, memo);
// 1. Nest exits with a 5 on a single die out = cand.filter((m) => usedBase(m) + maxBase(applyRaw(s, m, true), memo) === target);
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)); validCache.set(s, out);
} return out;
}
// 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;
} }
function copyLoc(p) { export const hasAnyMove = (s) => getValidMoves(s).length > 0;
if (p.loc) return { loc: p.loc }; export const turnDone = (s) => s.phase === 'move' && getValidMoves(s).length === 0;
if (p.track !== undefined) return { track: p.track };
if (p.home !== undefined) return { home: p.home }; // The squares a move passes through, in order (for hop animations).
return p; 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 ───────────────────────────────────────────────────── // ── applying ─────────────────────────────────────────────────────────────────
function applyRaw(state, m, noBonus = false) {
// 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) {
const s = cloneState(state); const s = cloneState(state);
const player = move.player; const c = m.player;
s.pawns[c][m.pawnIdx] = m.to;
// Update pawn if (m.hit) {
s.pawns[player][move.pawnIdx] = locFromMove(move.to); s.pawns[m.hit.color][m.hit.pawnIdx] = NEST;
if (!noBonus && s.opts.captureBonus) s.movesLeft.push(20);
// Process capture
if (move.hit) {
s.pawns[move.hit.color][move.hit.pawnIdx] = { loc: 'nest' };
s.movesLeft.push(20);
} }
if (m.to === HOME && !noBonus && s.opts.homeBonus) s.movesLeft.push(10);
// Process home arrival for (const d of m.combine ?? [m.dieUsed]) {
const arrived = move.to.loc === 'home'; const k = s.movesLeft.indexOf(d);
if (arrived) { if (k >= 0) s.movesLeft.splice(k, 1);
s.movesLeft.push(10);
} }
s.rollMoves.push({ pawnIdx: m.pawnIdx, from: m.from, to: m.to });
// 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);
}
// Win check
if (pawnsHome(s, player) >= PAWNS_PER_PLAYER) {
s.winner = player;
s.phase = 'game_over';
return s; return s;
} }
// End-of-turn handling // Apply one move. Does NOT end the roll: call finishRoll() once turnDone().
if (s.movesLeft.length === 0 || !hasAnyMove(s)) { export function applyMove(state, m) {
if (s.lastWasDoubles && s.consecutiveDoubles < 3) { const s = applyRaw(state, m);
// Doubles → same player re-rolls 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++;
}
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';
s.movesLeft = [];
s.pipHistory.push(pipRow(s));
}
return s;
}
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.dice = null;
s.movesLeft = []; s.movesLeft = [];
s.lastWasDoubles = false; s.rollMoves = [];
s.phase = 'roll'; s.phase = 'roll';
} else { }
endTurn(s);
} // 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; return s;
} }
function locFromMove(to) { // ── helpers ──────────────────────────────────────────────────────────────────
if (to.loc === 'home') return { loc: 'home' }; // Steps still to travel (nest counts the five-to-enter as well).
if (to.track !== undefined) return { track: to.track }; export function pawnDistanceToHome(p) {
if (to.home !== undefined) return { home: to.home }; if (p === NEST) return HOME + 5;
return to; return HOME - p;
} }
export function hasAnyMove(s) {
return getValidMoves(s).length > 0;
}
// ─── Helpers exposed for AI / UI ──────────────────────────────────────────
export { pawnsHome, pawnsInNest, blockadeSet, trackOccupants };
// Compute total pip distance for a color (lower = better progress).
export function totalPipsRemaining(s, color) { export function totalPipsRemaining(s, color) {
let total = 0; return s.pawns[color].reduce((a, p) => a + pawnDistanceToHome(p), 0);
for (const p of s.pawns[color]) total += pawnDistanceToHome(p, color);
return total;
} }
// 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 };

View File

@ -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;
}
}

View File

@ -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(); }
}

View File

@ -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' });
}
}

View File

@ -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
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. - **You play red.** Your four pawns wait in the brass bowl in the bottom-left corner — your **nest**.
- Pawns travel **counterclockwise** around the outer ring of the board, then up the center column toward home. - Each player's coloured **entry square** sits right beside their nest. That's where pawns join the race.
- 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. - 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 ## 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 ### 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. 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!
- 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.
### 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 ### 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 ### 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 ## 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. 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 ## 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. 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.

View File

@ -415,7 +415,7 @@ export default class OpponentSelectScene extends Phaser.Scene {
// Skill control: pips always show the level; the +/- buttons appear only // 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. // 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'; bio.style.webkitLineClamp = '1';
const skillRow = document.createElement('div'); const skillRow = document.createElement('div');

310
tools/verifyParchisi.js Normal file
View File

@ -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);