Rework Chinese Checkers into "Moonlit Tea Pavilion" with 2–6 player support

- Rewrite the AI (skill 1–5 ladder with lookahead, anti-blocking awareness) and rules engine to support variable seat counts, partner teams, boxed-in detection, and stalemate/turn-cap endings
- Add fully procedural art (room, board, glass marbles, HUD furniture), marble animator, Web Audio sound effects, pause/end dialogs, and a per-seat HUD with progress pips, speech bubbles, and medals
- Enable 1–5 opponent skill selection in OpponentSelectScene and map the game to the "chinese" soundtrack
- Add headless verification suite (topology, rules, AI legality, self-play soak, skill ladder, layout bounds) at tools/verifyChineseCheckers.js
This commit is contained in:
Brian Fertig 2026-11-25 22:57:14 -07:00
parent 98a6cd56d9
commit 40efc183fc
No known key found for this signature in database
18 changed files with 3305 additions and 799 deletions

Binary file not shown.

Binary file not shown.

View File

@ -312,6 +312,9 @@ export const MANIFEST = {
sheet('jello-items', 'assets/images/jello-items.png', 132, 132), sheet('jello-items', 'assets/images/jello-items.png', 132, 132),
image('bg-puddingmonsters-menu', 'assets/images/background-jello.png'), image('bg-puddingmonsters-menu', 'assets/images/background-jello.png'),
], ],
// Chinese Checkers art is all procedural (ChineseCheckersArt.js); only the
// chinese soundtrack (see services/soundtrack.js) needs lazy-loading.
chinesecheckers: [(scene) => musicFrom(scene, 'chinese-music')],
mahjong: [ mahjong: [
...MAHJONG_TILES, ...MAHJONG_TILES,
// chinese soundtrack (see services/soundtrack.js) — lazy-loaded here so // chinese soundtrack (see services/soundtrack.js) — lazy-loaded here so

View File

@ -34,7 +34,7 @@ registerGame({ slug: 'holdem', name: "Texas Hold 'Em", category: 'casino', cardG
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 });
registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 }); registerGame({ slug: 'skipbo', name: 'Skip-Bo', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 5 });
registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 }); registerGame({ slug: 'phase10', name: 'Phase 10', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 6 });
registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 6, maxPlayers: 6, minOpponents: 5, maxOpponents: 5, hasTutorial: true, iconFrame: 7 }); registerGame({ slug: 'chinesecheckers', name: 'Chinese Checkers', category: 'tabletop', minPlayers: 2, maxPlayers: 6, minOpponents: 1, maxOpponents: 5, defaultOpponents: 5, hasTutorial: true, iconFrame: 7 });
registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 8 }); registerGame({ slug: 'gofish', name: 'Go Fish', category: 'cards', cardGame: true, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 8 });
registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 9 }); registerGame({ slug: 'uno', name: 'Uno', category: 'cards', cardGame: false, minPlayers: 1, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, iconFrame: 9 });
registerGame({ slug: 'craps', name: 'Craps', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 10 }); registerGame({ slug: 'craps', name: 'Craps', category: 'casino', minPlayers: 1, maxPlayers: 7, minOpponents: 0, maxOpponents: 6, iconFrame: 10 });

View File

@ -1,83 +1,204 @@
import { // ChineseCheckersAI.js — skill 1–5 opponents. Phaser-free.
COLOR_TARGET, TRIANGLES, PEGS_PER_PLAYER, //
getAllValidMoves, hexDistance, triangleAt, // Evaluation (lower = better) for one colour, over its ten pegs:
} from './ChineseCheckersLogic.js'; // Σ rows still to travel (the race)
// + W.lag · Σ rows beyond the column's average (don't leave stragglers)
// + W.lat · Σ sideways drift off the centre line (stay in the jump lanes)
// + W.home · pegs still sitting in the home point (get everyone out)
//
// Ladder
// 1 noisy greedy, often settles for a short step
// 2 greedy with a little noise
// 3 greedy on the full evaluation
// 4 own two-move lookahead (best move given my best follow-up)
// 5 own three-move beam + "don't hand the next player a highway" + budget
//
// A move that simply undoes this colour's previous move is penalised so an
// AI with nothing useful to do can't ping-pong forever.
// Use the TIP of the target triangle as the goal point. Filling the deep import {
// cells first prevents the classic Chinese Checkers endgame where the last PEGS, CELLS, TARGET, HOME, ROWS, LATERAL, occupancy, pegMoves, currentColor,
// peg can't reach a target cell because the base of the triangle is full. isActive, targetFilled,
const TARGET_TIP = {}; } from './ChineseCheckersLogic.js';
for (const [tri, cells] of Object.entries(TRIANGLES)) { import { clampSkill, mulberry32 } from '../../ui/cardtable/AITiming.js';
// Triangle cell arrays are listed base-first; the last entry is the tip.
const tip = cells[cells.length - 1]; export const W = { lag: 0.35, lat: 0.12, home: 0.6 };
TARGET_TIP[tri] = { q: tip[0], r: tip[1] }; export const EVACUATE_ROUND = 12; // from this round on, stragglers at home get pushed out
export const SKILL = {
1: { depth: 1, noise: 4.0, stepBias: 0.35 },
2: { depth: 1, noise: 1.4, stepBias: 0 },
3: { depth: 1, noise: 0.15, stepBias: 0 },
4: { depth: 2, noise: 0.05, k1: 12, gamma: 0.6 },
5: { depth: 3, noise: 0, k1: 14, k2: 6, gamma: 0.8, gamma2: 0.5, block: 0.8, budgetMs: 300 },
};
// Evaluation of `pegs` (cell ids) for colour c.
export function evaluate(c, pegs) {
const t = TARGET[c], rows = ROWS[t], lat = LATERAL[t], home = HOME[c];
let sum = 0, drift = 0, inHome = 0;
for (let i = 0; i < PEGS; i++) {
const id = pegs[i];
sum += rows[id];
const tri = CELLS[id].tri;
if (tri !== t) drift += lat[id];
if (tri === home) inHome++;
}
const avg = sum / PEGS;
let lag = 0;
for (let i = 0; i < PEGS; i++) { const d = rows[pegs[i]] - avg; if (d > 0) lag += d; }
return sum + W.lag * lag + W.lat * drift + W.home * inHome;
} }
// Returns the single best move for the current player, or null if no moves. function genMoves(c, pegs, left, occ) {
// Single-ply: try every legal move, score the resulting position, pick the const out = [];
// best. Heuristic favors pulling the laggard peg forward and rewards landing for (let i = 0; i < PEGS; i++) pegMoves(c, i, pegs[i], left[i], occ, out);
// inside the target triangle. return out;
export function chooseMove(state, color) { }
const moves = getAllValidMoves(state, color);
if (moves.length === 0) return null;
const baseScore = scorePosition(state, color);
let best = null; // Apply/undo a move on (pegs, occ) in place.
let bestDelta = -Infinity; function doMove(pegs, occ, m, me) { occ[m.from] = 0; occ[m.to] = me; pegs[m.pegIdx] = m.to; }
function undoMove(pegs, occ, m, me) { occ[m.to] = 0; occ[m.from] = me; pegs[m.pegIdx] = m.from; }
for (const m of moves) { // After moving, a peg that was in home has left it.
const projected = projectMove(state, color, m); function leftAfter(left, m, c) {
const delta = baseScore - projected.score; if (left[m.pegIdx] || CELLS[m.to].tri === HOME[c]) return left;
const tiebreak = m.path.length * 0.01; // prefer longer jump chains const l = left.slice(); l[m.pegIdx] = true; return l;
const v = delta + tiebreak; }
if (v > bestDelta) { bestDelta = v; best = m; }
function finishBonus(state, c, pegs, occ) {
// Completing the target outright beats any evaluation detail.
const fake = { ...state, pegs: { ...state.pegs, [c]: pegs } };
return targetFilled(fake, c, occ) ? -1000 : 0;
}
// Best own follow-up value (min evaluation) at depth d from the current pegs.
function bestFollow(c, pegs, left, occ, me, d, cfg, deadline) {
const moves = genMoves(c, pegs, left, occ);
if (!moves.length) return evaluate(c, pegs);
let scored = moves.map((m) => {
doMove(pegs, occ, m, me);
const v = evaluate(c, pegs);
undoMove(pegs, occ, m, me);
return { m, v };
});
if (d <= 1) return Math.min(...scored.map((x) => x.v));
scored.sort((a, b) => a.v - b.v);
scored = scored.slice(0, cfg.k2 ?? 6);
let best = Infinity;
for (const { m, v } of scored) {
if (deadline && Date.now() > deadline) { best = Math.min(best, v); continue; }
doMove(pegs, occ, m, me);
const f = bestFollow(c, pegs, leftAfter(left, m, c), occ, me, d - 1, cfg, deadline);
undoMove(pegs, occ, m, me);
best = Math.min(best, v + (cfg.gamma2 ?? 0.35) * (f - v));
} }
return best; return best;
} }
// Cheap score (lower = better). We do not need to apply the move into a // The next player's best one-move gain (positive = how much they improve).
// full new state — just swap one peg's position and recompute the score function nextGain(state, occ) {
// contribution from that peg and the laggard metric. const n = state.seats.length;
function projectMove(state, color, move) { for (let k = 1; k < n; k++) {
const peg = state.pegs[color][move.pegIdx]; const o = state.seats[(state.current + k) % n];
const target = COLOR_TARGET[color]; if (!isActive(state, o)) continue;
const tip = TARGET_TIP[target]; const pegs = state.pegs[o].slice();
const me = state.seats.indexOf(o) + 1;
const base = evaluate(o, pegs);
let best = 0;
for (const m of genMoves(o, pegs, state.left[o], occ)) {
doMove(pegs, occ, m, me);
const v = base - evaluate(o, pegs);
undoMove(pegs, occ, m, me);
if (v > best) best = v;
}
return best;
}
return 0;
}
const pegBefore = pegScore(peg.q, peg.r, tip, target); /**
const pegAfter = pegScore(move.q, move.r, tip, target); * Pick a move for the side to play. Returns null when it has none.
* opts: { rng, budgetMs } — rng for repeatable tests; budgetMs overrides skill 5's.
*/
export function chooseMove(state, skill = 3, opts = {}) {
const c = currentColor(state);
if (state.phase !== 'play' || !isActive(state, c)) return null;
const cfg = SKILL[clampSkill(skill)];
const rng = opts.rng ?? Math.random;
const me = state.seats.indexOf(c) + 1;
const occ = occupancy(state);
const pegs = state.pegs[c].slice();
const left = state.left[c];
const moves = genMoves(c, pegs, left, occ);
if (!moves.length) return null;
if (moves.length === 1) return moves[0];
let worstBefore = 0, worstAfter = 0; const prev = [...state.lastMoves].reverse().find((m) => m.color === c);
for (let i = 0; i < PEGS_PER_PLAYER; i++) { let scored = moves.map((m) => {
const p = state.pegs[color][i]; doMove(pegs, occ, m, me);
const dPre = hexDistance(p.q, p.r, tip.q, tip.r); let v = evaluate(c, pegs) + finishBonus(state, c, pegs, occ);
if (dPre > worstBefore) worstBefore = dPre; undoMove(pegs, occ, m, me);
const d = (i === move.pegIdx) if (prev && prev.pegIdx === m.pegIdx && prev.from === m.to && prev.to === m.from) v += 2.5;
? hexDistance(move.q, move.r, tip.q, tip.r) return { m, v };
: dPre; });
if (d > worstAfter) worstAfter = d;
if (cfg.depth >= 2) {
scored.sort((a, b) => a.v - b.v);
const top = scored.slice(0, cfg.k1);
const budget = opts.budgetMs ?? cfg.budgetMs ?? 0;
const deadline = budget > 0 ? Date.now() + budget : 0;
const preGain = cfg.block ? nextGain(state, occ) : 0;
for (const x of top) {
if (x.v < -500) continue; // finishing move: take it
if (deadline && Date.now() > deadline) continue;
doMove(pegs, occ, x.m, me);
const f = bestFollow(c, pegs, leftAfter(left, x.m, c), occ, me, cfg.depth - 1, cfg, deadline);
let v = x.v + cfg.gamma * (f - x.v);
if (cfg.block) v += cfg.block * (nextGain(state, occ) - preGain);
undoMove(pegs, occ, x.m, me);
x.v = v;
}
scored = top;
} }
const baseScore = scorePosition(state, color); // Noise and (skill 1) the restless-conscript preference for small steps.
const score = baseScore - pegBefore + pegAfter + 0.7 * (worstAfter - worstBefore); // Even a beginner tidies up at the gate: with two or fewer marbles still
return { score }; // outside the target the noise fades, so every skill can close a game out.
} const outside = pegs.filter((id) => CELLS[id].tri !== TARGET[c]).length;
const noise = outside <= 2 ? cfg.noise * 0.15 : cfg.noise;
function pegScore(q, r, tip, targetTri) { const stepBias = outside <= 2 ? 0 : cfg.stepBias;
// Distance to the target tip — pulls pegs into the DEEPEST cell first, // Late in the game a marble still at home is in danger of being boxed in
// so the base of the triangle stays open for later pegs. // for good by the marbles arriving there: every skill feels a growing urge
let s = hexDistance(q, r, tip.q, tip.r); // to get it out.
// Big fixed bonus for landing inside the target triangle so the AI const round = Math.floor(state.turn / state.seats.length);
// strongly prefers entering target over loitering nearby. const urge = round >= EVACUATE_ROUND ? Math.min(8, (round - EVACUATE_ROUND + 2) * 0.6) : 0;
if (triangleAt(q, r) === targetTri) s -= 8; let best = null, bestV = Infinity;
return s; for (const x of scored) {
} let v = x.v + (noise ? (rng() - 0.5) * 2 * noise : 0);
if (stepBias && !x.m.isJump && rng() < stepBias) v -= 2;
function scorePosition(state, color) { if (urge && CELLS[x.m.from].tri === HOME[c] && CELLS[x.m.to].tri !== HOME[c]) v -= urge;
const target = COLOR_TARGET[color]; // tiebreak: longer chains, then forward progress
const tip = TARGET_TIP[target]; v -= (x.m.path.length - 1) * 0.001;
let total = 0; if (v < bestV) { bestV = v; best = x.m; }
for (const p of state.pegs[color]) {
total += pegScore(p.q, p.r, tip, target);
} }
return total; return best;
} }
// Hint for the human: the skill-5 move plus a short reason.
export function hint(state, opts = {}) {
const m = chooseMove(state, 5, { budgetMs: 400, ...opts });
if (!m) return null;
const c = m.color;
const gain = ROWS[TARGET[c]][m.from] - ROWS[TARGET[c]][m.to];
const hops = m.isJump ? m.path.length - 1 : 0;
let reason;
if (CELLS[m.to].tri === TARGET[c] && CELLS[m.from].tri !== TARGET[c]) reason = 'brings a marble into your target';
else if (hops >= 3) reason = `a ${hops}-hop chain`;
else if (CELLS[m.from].tri === HOME[c]) reason = 'gets a marble out of your home point';
else if (gain <= 0) reason = 'repositions to open a ladder for later';
else reason = `moves ${gain} row${gain === 1 ? '' : 's'} forward`;
return { move: m, reason, gain, hops };
}
export { mulberry32 };

View File

@ -0,0 +1,679 @@
// ChineseCheckersArt.js — baked canvas textures for the "Moonlit Tea Pavilion".
// All procedural: no image files.
//
// cc-room dark lacquered tea table at dusk: moonlight falling through a
// shoji lattice, warm lantern pools, a tray of mooncakes, a
// teapot and cup, a plum branch, hanging paper lanterns
// cc-props the props alone (over a chosen playfield)
// cc-vignette the light + vignette alone (over a chosen playfield)
// cc-board rosewood hexagon: gold-lipped black lacquer rim, an ebony
// star inlay, mother-of-pearl points (tinted for seated
// colours), a gold cloud medallion, 121 recessed holes.
// Re-baked per game (which points are seated changes).
// cc-m-<c> glass marble body (swirl core; rotated per marble)
// cc-ms-<c> the same with an etched colour-blind symbol
// cc-spec the shared specular glint drawn over every marble
// cc-shadow, cc-glow, cc-ring, cc-dot, cc-spark, cc-petal, cc-steam
// cc-plate, cc-plate-glow seat plaques
// cc-card-status, cc-card-log rice-paper cards in lacquer frames
// cc-medal-1‥6 finishing tokens (gold, silver, bronze, then jade)
// cc-lattice moonlight lattice that drifts over the table
// cc-lantern-glow warm pool that flickers under each lantern
import { canvas, rr, poly, noisePattern } from '../../ui/casino/CasinoArt.js';
import { TRI_CELLS, TARGET, OWNER } from './ChineseCheckersLogic.js';
import {
W, H, CX, CY, CELL_XY, HOLE_R, MARBLE_R, BOARD_R, BOARD_TEX, boardHex, triPolygon, centerPolygon,
PLATE, STATUS, LOG, MOON, LANTERNS, TEAPOT, CUP, BRANCH,
} from './ChineseCheckersLayout.js';
export const DISPLAY_FONT = '"Julius Sans One", Georgia, serif';
export const SERIF = 'Georgia, "Times New Roman", serif';
export const BOLD_FONT = 'Righteous, Georgia, serif';
export const RES = 2; // marbles bake at 2× and display at 0.5
export const MARBLE_TEX = Math.ceil((MARBLE_R + 3) * 2 * RES);
export const GLASS = {
red: { base: '#d1342b', light: '#ff9a7e', dark: '#6a0d0a', hex: 0xd1342b, ink: '#b0241c', pale: '#f3c2b6' },
yellow: { base: '#eeb11c', light: '#fff0a0', dark: '#8a5400', hex: 0xeeb11c, ink: '#9a6a00', pale: '#f6e2a8' },
green: { base: '#2f9e5a', light: '#9ff5bf', dark: '#0b4524', hex: 0x2f9e5a, ink: '#1f7a42', pale: '#bfe8cc' },
blue: { base: '#2f6fd0', light: '#a8d0ff', dark: '#0b2766', hex: 0x2f6fd0, ink: '#245cb0', pale: '#bcd4f4' },
orange: { base: '#ee7a1a', light: '#ffc894', dark: '#853200', hex: 0xee7a1a, ink: '#b85a0c', pale: '#f6cfa8' },
purple: { base: '#8a4fd8', light: '#dab8ff', dark: '#36136c', hex: 0x8a4fd8, ink: '#6a38b0', pale: '#d8c4f2' },
};
export const SYMBOL = { red: 'circle', yellow: 'triangle', green: 'square', blue: 'diamond', orange: 'star', purple: 'cross' };
export const LACQUER_RED = 0x8e1c16;
export const GOLD = 0xe8c46a;
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(20,6,2,0.4)', lines = 30, wave = 5, 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.003 + rnd() * 0.01, ph = rnd() * 6;
ctx.lineWidth = 0.6 + rnd() * 1.8;
ctx.beginPath();
for (let t = 0; t <= L; t += 8) {
const d = o + Math.sin(t * f + ph) * amp + Math.sin(t * f * 3.3 + 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 shadowed(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 goldGrad(ctx, x0, y0, x1, y1) {
const g = ctx.createLinearGradient(x0, y0, x1, y1);
g.addColorStop(0, '#f8e39a'); g.addColorStop(0.4, '#c8952c'); g.addColorStop(0.65, '#f0cf78'); g.addColorStop(1, '#8a6214');
return g;
}
// ── room ─────────────────────────────────────────────────────────────────────
function lacquerTable(ctx, rnd) {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, '#2a0f0c'); g.addColorStop(0.5, '#38140f'); g.addColorStop(1, '#22100b');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
grain(ctx, rnd, 0, 0, W, H, { tone: 'rgba(8,2,0,0.45)', lines: 110, wave: 7 });
grain(ctx, rnd, 0, 0, W, H, { tone: 'rgba(150,60,40,0.10)', lines: 60, wave: 4 });
// the lacquer's deep gloss: one long soft reflection
const sh = ctx.createLinearGradient(0, H * 0.15, W, H * 0.85);
sh.addColorStop(0, 'rgba(255,220,200,0)'); sh.addColorStop(0.45, 'rgba(255,220,200,0.05)'); sh.addColorStop(0.55, 'rgba(255,220,200,0)');
ctx.fillStyle = sh; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = noisePattern(ctx, 96, 18); ctx.fillRect(0, 0, W, H);
}
function lights(ctx) {
// cool moonlight from the upper left, shaped by a shoji lattice
const moon = ctx.createRadialGradient(260, 120, 40, 360, 260, 1300);
moon.addColorStop(0, 'rgba(170,190,255,0.20)'); moon.addColorStop(0.5, 'rgba(120,140,220,0.07)'); moon.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = moon; ctx.fillRect(0, 0, W, H);
// warm pools under the lanterns
for (const l of LANTERNS) {
const p = ctx.createRadialGradient(l.x, l.len + 60, 10, l.x, l.len + 80, 420);
p.addColorStop(0, 'rgba(255,150,70,0.22)'); p.addColorStop(1, 'rgba(255,150,70,0)');
ctx.fillStyle = p; ctx.fillRect(0, 0, W, H);
}
// a candle-warm halo around the board
const lamp = ctx.createRadialGradient(CX, CY, 200, CX, CY, 760);
lamp.addColorStop(0, 'rgba(255,190,120,0.10)'); lamp.addColorStop(1, 'rgba(255,190,120,0)');
ctx.fillStyle = lamp; ctx.fillRect(0, 0, W, H);
const v = ctx.createRadialGradient(CX, CY, H * 0.42, CX, CY, H * 1.08);
v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(4,2,8,0.72)');
ctx.fillStyle = v; ctx.fillRect(0, 0, W, H);
}
function mooncakes(ctx, rnd) {
const { x, y, r } = MOON;
// black lacquer tray with a red rim
shadowed(ctx, () => { ctx.fillStyle = '#120808'; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill(); }, { blur: 22, dx: 8, dy: 12, alpha: 0.6 });
ctx.strokeStyle = '#8e1c16'; ctx.lineWidth = 7; ctx.beginPath(); ctx.arc(x, y, r - 4, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(232,196,106,0.8)'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(x, y, r - 9, 0, Math.PI * 2); ctx.stroke();
const gl = ctx.createLinearGradient(x - r, y - r, x + r, y + r);
gl.addColorStop(0, 'rgba(255,255,255,0.10)'); gl.addColorStop(0.5, 'rgba(255,255,255,0)');
ctx.fillStyle = gl; ctx.beginPath(); ctx.arc(x, y, r - 10, 0, Math.PI * 2); ctx.fill();
// three mooncakes
const spots = [[-28, -20], [30, -14], [0, 32]];
spots.forEach(([dx, dy], k) => {
const cx = x + dx, cy = y + dy, cr = 27;
shadowed(ctx, () => {
const g = ctx.createRadialGradient(cx - 8, cy - 8, 4, cx, cy, cr);
g.addColorStop(0, '#e9b56a'); g.addColorStop(0.7, '#c07e32'); g.addColorStop(1, '#8a5018');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, cr, 0, Math.PI * 2); ctx.fill();
}, { blur: 8, dx: 3, dy: 4, alpha: 0.5 });
// scalloped edge + pressed pattern
ctx.strokeStyle = 'rgba(110,60,16,0.7)'; ctx.lineWidth = 1.4;
for (let i = 0; i < 14; i++) {
const a = (i / 14) * Math.PI * 2;
ctx.beginPath(); ctx.arc(cx + Math.cos(a) * (cr - 3), cy + Math.sin(a) * (cr - 3), 3.2, a - 1.2, a + 1.2); ctx.stroke();
}
ctx.beginPath(); ctx.arc(cx, cy, cr * 0.55, 0, Math.PI * 2); ctx.stroke();
ctx.save(); ctx.translate(cx, cy); ctx.rotate(k * 0.7 + rnd());
for (let i = 0; i < 4; i++) { ctx.rotate(Math.PI / 2); ctx.beginPath(); ctx.arc(0, -cr * 0.3, cr * 0.18, 0, Math.PI); ctx.stroke(); }
ctx.restore();
if (k === 2) { // one is cut: the salted yolk "moon" inside
ctx.fillStyle = '#6a2a10'; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.arc(cx, cy, cr - 1, -0.3, 0.9); ctx.closePath(); ctx.fill();
ctx.fillStyle = '#f0a020'; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.arc(cx, cy, cr * 0.42, -0.3, 0.9); ctx.closePath(); ctx.fill();
}
});
}
function teapot(ctx) {
const { x, y } = TEAPOT;
const R = 70;
shadowed(ctx, () => {
// body (seen from above): a celadon glaze
const g = ctx.createRadialGradient(x - 22, y - 24, 8, x, y, R);
g.addColorStop(0, '#d8eadf'); g.addColorStop(0.55, '#8fb8a2'); g.addColorStop(1, '#4a7462');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, y, R, 0, Math.PI * 2); ctx.fill();
// spout toward the board
ctx.fillStyle = '#6f9a86';
ctx.beginPath(); ctx.moveTo(x + R * 0.7, y - 20); ctx.quadraticCurveTo(x + R + 40, y - 44, x + R + 52, y - 66);
ctx.lineTo(x + R + 64, y - 58); ctx.quadraticCurveTo(x + R + 42, y - 18, x + R * 0.8, y + 14); ctx.closePath(); ctx.fill();
}, { blur: 26, dx: 10, dy: 16, alpha: 0.6 });
// cane handle over the top
ctx.strokeStyle = '#5a3a1a'; ctx.lineWidth = 9; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(x - R * 0.75, y - R * 0.45); ctx.quadraticCurveTo(x - 6, y - R * 1.35, x + R * 0.75, y - R * 0.45); ctx.stroke();
ctx.strokeStyle = 'rgba(230,190,130,0.5)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x - R * 0.72, y - R * 0.5); ctx.quadraticCurveTo(x - 6, y - R * 1.3, x + R * 0.72, y - R * 0.5); ctx.stroke();
// lid + knob
ctx.strokeStyle = 'rgba(40,70,58,0.7)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(x, y, R * 0.48, 0, Math.PI * 2); ctx.stroke();
const k = ctx.createRadialGradient(x - 4, y - 4, 2, x, y, 14);
k.addColorStop(0, '#eef6f0'); k.addColorStop(1, '#6f9a86');
ctx.fillStyle = k; ctx.beginPath(); ctx.arc(x, y, 13, 0, Math.PI * 2); ctx.fill();
// crackle glaze
ctx.strokeStyle = 'rgba(40,70,58,0.18)'; ctx.lineWidth = 1;
const rnd = seeded(31);
for (let i = 0; i < 26; i++) {
const a = rnd() * Math.PI * 2, d = 20 + rnd() * (R - 26);
ctx.beginPath(); ctx.moveTo(x + Math.cos(a) * d, y + Math.sin(a) * d);
ctx.lineTo(x + Math.cos(a + 0.2) * (d + 10), y + Math.sin(a + 0.2) * (d + 10)); ctx.stroke();
}
}
function teacup(ctx) {
const { x, y } = CUP;
shadowed(ctx, () => {
ctx.fillStyle = '#e9efe9'; ctx.beginPath(); ctx.arc(x, y, 38, 0, Math.PI * 2); ctx.fill();
}, { blur: 16, dx: 6, dy: 9, alpha: 0.55 });
ctx.strokeStyle = '#4e7d9a'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(x, y, 33, 0, Math.PI * 2); ctx.stroke();
const t = ctx.createRadialGradient(x - 6, y - 6, 3, x, y, 28);
t.addColorStop(0, '#d6b560'); t.addColorStop(1, '#8a6a1e');
ctx.fillStyle = t; ctx.beginPath(); ctx.arc(x, y, 28, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,255,240,0.55)'; ctx.beginPath(); ctx.ellipse(x - 9, y - 10, 9, 4, -0.6, 0, Math.PI * 2); ctx.fill();
// a floating chrysanthemum petal
ctx.fillStyle = '#f6e7a0'; ctx.beginPath(); ctx.ellipse(x + 8, y + 6, 6, 2.6, 0.5, 0, Math.PI * 2); ctx.fill();
}
function plumBranch(ctx, rnd) {
const { x, y } = BRANCH;
ctx.save();
ctx.lineCap = 'round';
const seg = (x0, y0, a, len, w, depth) => {
if (depth <= 0 || len < 10) return;
const x1 = x0 + Math.cos(a) * len, y1 = y0 + Math.sin(a) * len;
shadowed(ctx, () => {
ctx.strokeStyle = '#2a160e'; ctx.lineWidth = w;
ctx.beginPath(); ctx.moveTo(x0, y0);
ctx.quadraticCurveTo((x0 + x1) / 2 + (rnd() - 0.5) * 20, (y0 + y1) / 2 + (rnd() - 0.5) * 20, x1, y1); ctx.stroke();
}, { blur: 8, dx: 5, dy: 7, alpha: 0.5 });
const n = depth > 2 ? 2 : 1 + (rnd() < 0.5 ? 1 : 0);
for (let i = 0; i < n; i++) seg(x1, y1, a + (rnd() - 0.5) * 1.3, len * (0.6 + rnd() * 0.2), w * 0.66, depth - 1);
if (depth <= 3) for (let i = 0; i < 2; i++) blossom(ctx, x1 + (rnd() - 0.5) * 30, y1 + (rnd() - 0.5) * 30, 7 + rnd() * 5, rnd);
};
seg(x + 10, y - 30, -2.6, 180, 16, 5);
seg(x - 40, y + 10, -2.9, 140, 11, 4);
ctx.restore();
}
function blossom(ctx, x, y, r, rnd) {
shadowed(ctx, () => {
for (let i = 0; i < 5; i++) {
const a = (i / 5) * Math.PI * 2 + rnd();
const g = ctx.createRadialGradient(x + Math.cos(a) * r * 0.7, y + Math.sin(a) * r * 0.7, 1, x + Math.cos(a) * r * 0.7, y + Math.sin(a) * r * 0.7, r * 0.75);
g.addColorStop(0, '#fff2f6'); g.addColorStop(1, '#f2a2bc');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x + Math.cos(a) * r * 0.7, y + Math.sin(a) * r * 0.7, r * 0.7, 0, Math.PI * 2); ctx.fill();
}
}, { blur: 5, dx: 2, dy: 3, alpha: 0.35 });
ctx.fillStyle = '#c23a5a'; ctx.beginPath(); ctx.arc(x, y, r * 0.3, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#ffd86a';
for (let i = 0; i < 6; i++) { const a = i + rnd(); ctx.beginPath(); ctx.arc(x + Math.cos(a) * r * 0.42, y + Math.sin(a) * r * 0.42, 1.2, 0, Math.PI * 2); ctx.fill(); }
}
function lantern(ctx, { x, len }, scale = 1) {
const cy = len + 52 * scale, rw = 40 * scale, rh = 52 * scale;
ctx.strokeStyle = 'rgba(30,14,8,0.9)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, cy - rh); ctx.stroke();
// glow
const glow = ctx.createRadialGradient(x, cy, 10, x, cy, 150 * scale);
glow.addColorStop(0, 'rgba(255,160,80,0.45)'); glow.addColorStop(1, 'rgba(255,120,40,0)');
ctx.fillStyle = glow; ctx.fillRect(x - 160 * scale, cy - 160 * scale, 320 * scale, 320 * scale);
// paper body
const g = ctx.createRadialGradient(x - rw * 0.3, cy - rh * 0.2, 4, x, cy, rw * 1.1);
g.addColorStop(0, '#ffcf8a'); g.addColorStop(0.45, '#e0442a'); g.addColorStop(1, '#7a120c');
ctx.fillStyle = g; ctx.beginPath(); ctx.ellipse(x, cy, rw, rh, 0, 0, Math.PI * 2); ctx.fill();
// ribs
ctx.strokeStyle = 'rgba(90,10,6,0.55)'; ctx.lineWidth = 1.4;
for (let k = -3; k <= 3; k++) { ctx.beginPath(); ctx.ellipse(x, cy, Math.abs(k) * rw / 3.6 + 0.5, rh, 0, 0, Math.PI * 2); ctx.stroke(); }
for (let k = -4; k <= 4; k += 2) {
const yy = cy + (k / 5) * rh, ww = rw * Math.sqrt(1 - (k / 5) ** 2);
ctx.beginPath(); ctx.moveTo(x - ww, yy); ctx.lineTo(x + ww, yy); ctx.stroke();
}
// gold caps
ctx.fillStyle = goldGrad(ctx, x - rw * 0.5, 0, x + rw * 0.5, 0);
rr(ctx, x - rw * 0.5, cy - rh - 6 * scale, rw, 10 * scale, 3); ctx.fill();
rr(ctx, x - rw * 0.5, cy + rh - 4 * scale, rw, 10 * scale, 3); ctx.fill();
// tassel
ctx.strokeStyle = '#c22a1a'; ctx.lineWidth = 2;
for (let i = -3; i <= 3; i++) { ctx.beginPath(); ctx.moveTo(x, cy + rh + 6 * scale); ctx.lineTo(x + i * 1.6, cy + rh + 44 * scale); ctx.stroke(); }
ctx.fillStyle = goldGrad(ctx, x - 6, 0, x + 6, 0); ctx.beginPath(); ctx.arc(x, cy + rh + 8 * scale, 5 * scale, 0, Math.PI * 2); ctx.fill();
}
function props(ctx, rnd) {
mooncakes(ctx, rnd);
teapot(ctx);
teacup(ctx);
plumBranch(ctx, rnd);
// a few fallen petals
for (let i = 0; i < 9; i++) {
const px = 1500 + rnd() * 380, py = 880 + rnd() * 180;
ctx.save(); ctx.translate(px, py); ctx.rotate(rnd() * 6);
ctx.fillStyle = 'rgba(244,170,192,0.85)'; ctx.beginPath(); ctx.ellipse(0, 0, 6, 3.6, 0, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
LANTERNS.forEach((l, i) => lantern(ctx, l, i === 1 ? 1.1 : 0.9));
}
function bakeRoom(scene) {
const rnd = seeded(7);
{
const c = canvas(W, H), ctx = c.getContext('2d');
lacquerTable(ctx, rnd);
lights(ctx);
props(ctx, seeded(11));
addCanvas(scene, 'cc-room', c);
}
{
const c = canvas(W, H), ctx = c.getContext('2d');
props(ctx, seeded(11));
addCanvas(scene, 'cc-props', c);
}
{
const c = canvas(W, H), ctx = c.getContext('2d');
lights(ctx);
addCanvas(scene, 'cc-vignette', c);
}
}
// ── board ────────────────────────────────────────────────────────────────────
// Board texture is BOARD_TEX square, centred on (CX, CY): board-space p maps
// to texture (p.x − CX + BOARD_TEX/2, p.y − CY + BOARD_TEX/2).
const BO = (p) => ({ x: p.x - CX + BOARD_TEX / 2, y: p.y - CY + BOARD_TEX / 2 });
function nacre(ctx, rnd, pts, tint) {
ctx.save();
poly(ctx, pts); ctx.clip();
const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y);
const x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);
const g = ctx.createLinearGradient(x0, y0, x1, y1);
g.addColorStop(0, tint.pale); g.addColorStop(0.5, '#f4f0ea'); g.addColorStop(1, tint.pale);
ctx.fillStyle = g; ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
// iridescent flecks
const hues = ['rgba(255,170,200,0.22)', 'rgba(150,230,240,0.22)', 'rgba(255,230,150,0.2)', 'rgba(190,170,255,0.2)', 'rgba(255,255,255,0.35)'];
for (let i = 0; i < 140; i++) {
const x = x0 + rnd() * (x1 - x0), y = y0 + rnd() * (y1 - y0);
ctx.fillStyle = hues[i % hues.length];
ctx.beginPath(); ctx.ellipse(x, y, 6 + rnd() * 22, 3 + rnd() * 8, rnd() * Math.PI, 0, Math.PI * 2); ctx.fill();
}
// seat colour wash so the point reads at a glance
ctx.fillStyle = tint.wash; ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
ctx.restore();
}
function hole(ctx, x, y) {
// recessed: shadowed upper lip, lit lower lip, dark well
const r = HOLE_R;
const lip = ctx.createLinearGradient(x, y - r, x, y + r);
lip.addColorStop(0, 'rgba(0,0,0,0.55)'); lip.addColorStop(1, 'rgba(255,230,190,0.32)');
ctx.fillStyle = lip; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
const well = ctx.createRadialGradient(x, y + r * 0.35, 1, x, y, r - 3);
well.addColorStop(0, '#2a1a14'); well.addColorStop(0.7, '#120a08'); well.addColorStop(1, '#050302');
ctx.fillStyle = well; ctx.beginPath(); ctx.arc(x, y, r - 3.5, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(232,196,106,0.28)'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.arc(x, y, r - 0.5, 0.15 * Math.PI, 0.85 * Math.PI); ctx.stroke();
}
function cloudMedallion(ctx, cx, cy, R) {
ctx.save();
ctx.strokeStyle = 'rgba(232,196,106,0.22)';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.stroke();
ctx.lineWidth = 1;
ctx.beginPath(); ctx.arc(cx, cy, R - 10, 0, Math.PI * 2); ctx.stroke();
// eight ruyi cloud scrolls round the ring
ctx.lineWidth = 2;
for (let i = 0; i < 8; i++) {
const a = (i / 8) * Math.PI * 2 + Math.PI / 8;
const x = cx + Math.cos(a) * (R - 34), y = cy + Math.sin(a) * (R - 34);
ctx.beginPath(); ctx.arc(x, y, 14, a + 0.8, a + 0.8 + Math.PI * 1.6); ctx.stroke();
ctx.beginPath(); ctx.arc(x + Math.cos(a + 1.6) * 10, y + Math.sin(a + 1.6) * 10, 7, a, a + Math.PI * 1.5); ctx.stroke();
}
// a stylised moon at the heart
ctx.fillStyle = 'rgba(232,196,106,0.08)';
ctx.beginPath(); ctx.arc(cx, cy, R * 0.42, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
export function bakeBoard(scene, seats) {
const c = canvas(BOARD_TEX, BOARD_TEX), ctx = c.getContext('2d');
const rnd = seeded(23);
const hex = boardHex(BOARD_R).map(BO);
const roundHex = (pts, r) => {
ctx.beginPath();
pts.forEach((p, i) => {
const a = pts[(i + pts.length - 1) % pts.length], b = pts[(i + 1) % pts.length];
const ax = p.x + (a.x - p.x) * (r / BOARD_R), ay = p.y + (a.y - p.y) * (r / BOARD_R);
const bx = p.x + (b.x - p.x) * (r / BOARD_R), by = p.y + (b.y - p.y) * (r / BOARD_R);
if (i === 0) ctx.moveTo(ax, ay); else ctx.lineTo(ax, ay);
ctx.quadraticCurveTo(p.x, p.y, bx, by);
});
ctx.closePath();
};
// outer lacquer rim with a drop shadow
shadowed(ctx, () => { ctx.fillStyle = '#0c0606'; roundHex(hex, 40); ctx.fill(); }, { blur: 34, dx: 12, dy: 22, alpha: 0.7 });
ctx.strokeStyle = goldGrad(ctx, 0, 0, BOARD_TEX, BOARD_TEX); ctx.lineWidth = 4; roundHex(hex, 40); ctx.stroke();
// rosewood field
const inner = boardHex(BOARD_R - 22).map(BO);
ctx.save(); roundHex(inner, 34); ctx.clip();
const wood = ctx.createLinearGradient(0, 0, BOARD_TEX, BOARD_TEX);
wood.addColorStop(0, '#6a2a1a'); wood.addColorStop(0.5, '#7a321e'); wood.addColorStop(1, '#4e1c10');
ctx.fillStyle = wood; ctx.fillRect(0, 0, BOARD_TEX, BOARD_TEX);
grain(ctx, rnd, 0, 0, BOARD_TEX, BOARD_TEX, { tone: 'rgba(24,6,2,0.42)', lines: 90, wave: 9 });
grain(ctx, rnd, 0, 0, BOARD_TEX, BOARD_TEX, { tone: 'rgba(190,100,60,0.12)', lines: 40, wave: 5 });
ctx.fillStyle = noisePattern(ctx, 64, 16); ctx.fillRect(0, 0, BOARD_TEX, BOARD_TEX);
ctx.restore();
ctx.strokeStyle = 'rgba(232,196,106,0.75)'; ctx.lineWidth = 2; roundHex(inner, 34); ctx.stroke();
// corner cloud motifs in gold leaf
inner.forEach((p) => {
const dx = BOARD_TEX / 2 - p.x, dy = BOARD_TEX / 2 - p.y, len = Math.hypot(dx, dy);
const x = p.x + dx / len * 46, y = p.y + dy / len * 46;
ctx.strokeStyle = 'rgba(232,196,106,0.45)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(x, y, 9, 0, Math.PI * 1.6); ctx.stroke();
});
// ebony star inlay: gold border pass, then the ebony pass
const tris = Object.keys(TRI_CELLS);
const starPolys = (pad) => [...tris.map((t) => triPolygon(t, pad).map(BO)), centerPolygon(pad - 6).map(BO)];
ctx.fillStyle = goldGrad(ctx, 0, 0, BOARD_TEX, BOARD_TEX);
for (const p of starPolys(HOLE_R + 15)) { poly(ctx, p); ctx.fill(); }
ctx.fillStyle = '#160d0b';
for (const p of starPolys(HOLE_R + 12)) { poly(ctx, p); ctx.fill(); }
// mother-of-pearl points: seated homes & targets tinted; empty ones plain
const seated = new Set(seats);
for (const t of tris) {
const owner = OWNER[t];
const target = Object.keys(TARGET).find((c) => TARGET[c] === t && seated.has(c));
const c0 = seated.has(owner) ? owner : target ?? null;
const tint = c0
? { pale: GLASS[c0].pale, wash: hexA(GLASS[c0].base, seated.has(owner) ? 0.22 : 0.1) }
: { pale: '#e8e2d8', wash: 'rgba(40,30,20,0.18)' };
nacre(ctx, rnd, triPolygon(t, HOLE_R + 6).map(BO), tint);
ctx.strokeStyle = c0 ? hexA(GLASS[c0].base, 0.9) : 'rgba(232,196,106,0.5)';
ctx.lineWidth = 2.5; poly(ctx, triPolygon(t, HOLE_R + 6).map(BO)); ctx.stroke();
}
cloudMedallion(ctx, BOARD_TEX / 2, BOARD_TEX / 2, 196);
// faint carved lines between neighbouring holes (the lattice of the star)
ctx.strokeStyle = 'rgba(232,196,106,0.07)'; ctx.lineWidth = 1;
for (let id = 0; id < CELL_XY.length; id++) {
const a = BO(CELL_XY[id]);
for (let j = id + 1; j < CELL_XY.length; j++) {
const b = BO(CELL_XY[j]);
if (Math.abs(Math.hypot(a.x - b.x, a.y - b.y) - 58) < 1) { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); }
}
}
for (const p of CELL_XY) { const b = BO(p); hole(ctx, b.x, b.y); }
addCanvas(scene, 'cc-board', c);
}
function hexA(hex, a) {
const n = parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
}
// ── marbles ──────────────────────────────────────────────────────────────────
function symbolPath(ctx, kind, r) {
ctx.beginPath();
if (kind === 'circle') ctx.arc(0, 0, r * 0.75, 0, Math.PI * 2);
else if (kind === 'triangle') { ctx.moveTo(0, -r); ctx.lineTo(r * 0.9, r * 0.65); ctx.lineTo(-r * 0.9, r * 0.65); ctx.closePath(); }
else if (kind === 'square') ctx.rect(-r * 0.7, -r * 0.7, r * 1.4, r * 1.4);
else if (kind === 'diamond') { ctx.moveTo(0, -r); ctx.lineTo(r * 0.8, 0); ctx.lineTo(0, r); ctx.lineTo(-r * 0.8, 0); ctx.closePath(); }
else if (kind === 'star') {
for (let i = 0; i < 10; i++) { const a = -Math.PI / 2 + i * Math.PI / 5, d = i % 2 ? r * 0.45 : r; i ? ctx.lineTo(Math.cos(a) * d, Math.sin(a) * d) : ctx.moveTo(Math.cos(a) * d, Math.sin(a) * d); }
ctx.closePath();
} else if (kind === 'cross') {
const t = r * 0.3;
ctx.moveTo(-t, -r); ctx.lineTo(t, -r); ctx.lineTo(t, -t); ctx.lineTo(r, -t); ctx.lineTo(r, t); ctx.lineTo(t, t); ctx.lineTo(t, r);
ctx.lineTo(-t, r); ctx.lineTo(-t, t); ctx.lineTo(-r, t); ctx.lineTo(-r, -t); ctx.lineTo(-t, -t); ctx.closePath();
}
}
function marbleBody(color, withSymbol) {
const S = MARBLE_TEX, c = canvas(S, S), ctx = c.getContext('2d');
const R = MARBLE_R * RES, cx = S / 2, cy = S / 2;
const G = GLASS[color];
const rnd = seeded(color.length * 97 + color.charCodeAt(0));
ctx.save();
ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.clip();
// clear glass tinted body: bright where light passes through (lower right)
const body = ctx.createRadialGradient(cx + R * 0.3, cy + R * 0.35, R * 0.1, cx, cy, R * 1.05);
body.addColorStop(0, G.light); body.addColorStop(0.45, G.base); body.addColorStop(1, G.dark);
ctx.fillStyle = body; ctx.fillRect(0, 0, S, S);
// cat's-eye swirl core (the texture is rotated per marble)
ctx.translate(cx, cy);
for (let k = 0; k < 3; k++) {
ctx.rotate((Math.PI * 2) / 3 + (rnd() - 0.5) * 0.4);
const g = ctx.createLinearGradient(-R, 0, R, 0);
g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, k === 1 ? hexA(G.dark, 0.55) : 'rgba(255,255,255,0.38)'); g.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = g;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.bezierCurveTo(R * 0.3, -R * 0.35, R * 0.75, -R * 0.15, R * 0.95, R * 0.12);
ctx.bezierCurveTo(R * 0.7, R * 0.05, R * 0.35, R * 0.12, 0, 0);
ctx.fill();
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
if (withSymbol) {
ctx.save(); ctx.translate(cx, cy);
symbolPath(ctx, SYMBOL[color], R * 0.48);
ctx.fillStyle = 'rgba(255,255,255,0.78)'; ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = hexA(G.dark, 0.9); ctx.stroke();
ctx.restore();
}
// rim darkening (Fresnel)
const rim = ctx.createRadialGradient(cx, cy, R * 0.72, cx, cy, R);
rim.addColorStop(0, 'rgba(0,0,0,0)'); rim.addColorStop(1, 'rgba(0,0,0,0.45)');
ctx.fillStyle = rim; ctx.fillRect(0, 0, S, S);
ctx.restore();
return c;
}
function bakeMarbles(scene) {
for (const color of Object.keys(GLASS)) {
addCanvas(scene, `cc-m-${color}`, marbleBody(color, false));
addCanvas(scene, `cc-ms-${color}`, marbleBody(color, true));
}
// specular glint (never rotated)
{
const S = MARBLE_TEX, c = canvas(S, S), ctx = c.getContext('2d');
const R = MARBLE_R * RES, cx = S / 2, cy = S / 2;
const soft = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, 1, cx - R * 0.3, cy - R * 0.35, R * 0.6);
soft.addColorStop(0, 'rgba(255,255,255,0.55)'); soft.addColorStop(1, 'rgba(255,255,255,0)');
ctx.fillStyle = soft; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.95)';
ctx.beginPath(); ctx.ellipse(cx - R * 0.38, cy - R * 0.42, R * 0.2, R * 0.12, -0.7, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.beginPath(); ctx.arc(cx + R * 0.42, cy + R * 0.5, R * 0.07, 0, Math.PI * 2); ctx.fill();
// thin bright rim on the lit side
ctx.strokeStyle = 'rgba(255,255,255,0.25)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(cx, cy, R - 1.5, Math.PI * 1.05, Math.PI * 1.55); ctx.stroke();
addCanvas(scene, 'cc-spec', c);
}
{
const S = MARBLE_TEX + 20, c = canvas(S, S), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(S / 2, S / 2, 2, S / 2, S / 2, S / 2);
g.addColorStop(0, 'rgba(0,0,0,0.65)'); g.addColorStop(0.55, 'rgba(0,0,0,0.35)'); g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2, 0, Math.PI * 2); ctx.fill();
addCanvas(scene, 'cc-shadow', c);
}
}
// ── furniture ────────────────────────────────────────────────────────────────
function bakePlate(scene) {
const pad = 14, w = PLATE.w, h = PLATE.h;
{
const c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d');
shadowed(ctx, () => { ctx.fillStyle = '#100808'; rr(ctx, pad, pad, w, h, 14); ctx.fill(); }, { blur: 14, dx: 5, dy: 8, alpha: 0.6 });
const g = ctx.createLinearGradient(0, pad, 0, pad + h);
g.addColorStop(0, '#2c1210'); g.addColorStop(1, '#1a0a09');
ctx.fillStyle = g; rr(ctx, pad + 4, pad + 4, w - 8, h - 8, 11); ctx.fill();
ctx.strokeStyle = goldGrad(ctx, pad, pad, pad + w, pad + h); ctx.lineWidth = 2.5; rr(ctx, pad + 2, pad + 2, w - 4, h - 4, 12); ctx.stroke();
ctx.strokeStyle = 'rgba(232,196,106,0.3)'; ctx.lineWidth = 1; rr(ctx, pad + 8, pad + 8, w - 16, h - 16, 8); ctx.stroke();
const gl = ctx.createLinearGradient(0, pad, 0, pad + h * 0.5);
gl.addColorStop(0, 'rgba(255,230,210,0.10)'); gl.addColorStop(1, 'rgba(255,230,210,0)');
ctx.fillStyle = gl; rr(ctx, pad + 4, pad + 4, w - 8, h * 0.45, 11); ctx.fill();
addCanvas(scene, 'cc-plate', c);
}
{
const P = 40, c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
ctx.shadowColor = 'rgba(255,190,90,1)'; ctx.shadowBlur = 30;
ctx.strokeStyle = 'rgba(255,210,120,0.95)'; ctx.lineWidth = 5; rr(ctx, P, P, w, h, 14); ctx.stroke();
ctx.shadowBlur = 0;
addCanvas(scene, 'cc-plate-glow', c);
}
}
function bakeCard(scene, key, w, h) {
const pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d');
shadowed(ctx, () => { ctx.fillStyle = '#120808'; rr(ctx, pad, pad, w, h, 12); ctx.fill(); }, { blur: 18, dx: 6, dy: 10, alpha: 0.6 });
ctx.strokeStyle = goldGrad(ctx, pad, pad, pad + w, pad + h); ctx.lineWidth = 2; rr(ctx, pad + 3, pad + 3, w - 6, h - 6, 10); ctx.stroke();
const paper = ctx.createLinearGradient(0, pad, 0, pad + h);
paper.addColorStop(0, '#f6eedb'); paper.addColorStop(1, '#e8dcc0');
ctx.fillStyle = paper; rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 6); ctx.fill();
// rice-paper fibres
const rnd = seeded(w * 7 + h);
ctx.save(); rr(ctx, pad + 9, pad + 9, w - 18, h - 18, 6); ctx.clip();
ctx.strokeStyle = 'rgba(150,120,80,0.12)'; ctx.lineWidth = 1;
for (let i = 0; i < 90; i++) {
const x = pad + rnd() * w, y = pad + rnd() * h, a = rnd() * Math.PI, l = 8 + rnd() * 24;
ctx.beginPath(); ctx.moveTo(x, y); ctx.quadraticCurveTo(x + Math.cos(a) * l * 0.5 + 3, y + Math.sin(a) * l * 0.5, x + Math.cos(a) * l, y + Math.sin(a) * l); ctx.stroke();
}
ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(0, 0, w + pad * 2, h + pad * 2);
ctx.restore();
// a red seal in the corner
ctx.fillStyle = 'rgba(176,36,28,0.85)'; rr(ctx, pad + w - 40, pad + h - 40, 22, 22, 3); ctx.fill();
ctx.strokeStyle = 'rgba(246,238,219,0.9)'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(pad + w - 35, pad + h - 29); ctx.lineTo(pad + w - 23, pad + h - 29); ctx.moveTo(pad + w - 29, pad + h - 35); ctx.lineTo(pad + w - 29, pad + h - 23); ctx.stroke();
addCanvas(scene, key, c);
}
function bakeMedals(scene) {
const tones = [
['#fff0a8', '#e0b030', '#8a6208'], ['#ffffff', '#c4c8d0', '#6a707a'], ['#ffd2a0', '#c27a3a', '#6a3a10'],
['#d8f5e4', '#5fae86', '#1e5a3e'], ['#d8f5e4', '#5fae86', '#1e5a3e'], ['#d8f5e4', '#5fae86', '#1e5a3e'],
];
tones.forEach(([hi, mid, lo], i) => {
const S = 64, c = canvas(S, S + 18), ctx = c.getContext('2d');
// ribbon
ctx.fillStyle = i < 3 ? '#b0241c' : '#2a5a8a';
ctx.beginPath(); ctx.moveTo(S / 2 - 16, 0); ctx.lineTo(S / 2 - 4, 30); ctx.lineTo(S / 2 + 4, 30); ctx.lineTo(S / 2 + 16, 0); ctx.closePath(); ctx.fill();
shadowed(ctx, () => {
const g = ctx.createRadialGradient(S / 2 - 8, S / 2 + 4, 2, S / 2, S / 2 + 14, 28);
g.addColorStop(0, hi); g.addColorStop(0.6, mid); g.addColorStop(1, lo);
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(S / 2, S / 2 + 14, 26, 0, Math.PI * 2); ctx.fill();
}, { blur: 6, dx: 2, dy: 3, alpha: 0.5 });
ctx.strokeStyle = lo; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(S / 2, S / 2 + 14, 20, 0, Math.PI * 2); ctx.stroke();
ctx.fillStyle = lo; ctx.font = `bold 24px ${BOLD_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(String(i + 1), S / 2, S / 2 + 15);
addCanvas(scene, `cc-medal-${i + 1}`, c);
});
}
function bakeLattice(scene) {
// a shoji screen's shadow: moonlight panes between dark muntins
const S = 640, c = canvas(S, S), ctx = c.getContext('2d');
const cell = 80;
for (let y = 0; y < S; y += cell) {
for (let x = 0; x < S; x += cell) {
const g = ctx.createRadialGradient(x + cell / 2, y + cell / 2, 4, x + cell / 2, y + cell / 2, cell * 0.7);
g.addColorStop(0, 'rgba(200,215,255,0.9)'); g.addColorStop(1, 'rgba(200,215,255,0.35)');
ctx.fillStyle = g; ctx.fillRect(x + 5, y + 5, cell - 10, cell - 10);
}
}
addCanvas(scene, 'cc-lattice', c);
}
function bakeBits(scene) {
const radial = (key, S, stops) => {
const c = canvas(S, S), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(S / 2, S / 2, 0, S / 2, S / 2, S / 2);
stops.forEach(([o, col]) => g.addColorStop(o, col));
ctx.fillStyle = g; ctx.fillRect(0, 0, S, S);
addCanvas(scene, key, c);
};
radial('cc-glow', 96, [[0, 'rgba(255,226,140,0.9)'], [0.45, 'rgba(255,200,90,0.45)'], [1, 'rgba(255,190,80,0)']]);
radial('cc-spark', 24, [[0, 'rgba(255,255,255,1)'], [0.35, 'rgba(255,240,200,0.8)'], [1, 'rgba(255,220,150,0)']]);
radial('cc-steam', 64, [[0, 'rgba(255,255,255,0.55)'], [1, 'rgba(255,255,255,0)']]);
radial('cc-lantern-glow', 360, [[0, 'rgba(255,170,80,0.5)'], [1, 'rgba(255,140,60,0)']]);
{
const S = 64, c = canvas(S, S), ctx = c.getContext('2d');
ctx.strokeStyle = 'rgba(255,224,130,1)'; ctx.lineWidth = 4;
ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 4, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 8, 0, Math.PI * 2); ctx.stroke();
addCanvas(scene, 'cc-ring', c);
}
{
// destination marker: a white jade disc (tinted per move by the scene)
const S = 48, c = canvas(S, S), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(S / 2 - 5, S / 2 - 5, 2, S / 2, S / 2, S / 2 - 6);
g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(1, 'rgba(220,220,220,0.85)');
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 8, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(255,255,255,0.95)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 3, 0, Math.PI * 2); ctx.stroke();
addCanvas(scene, 'cc-dot', c);
}
{
const c = canvas(22, 16), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(8, 8, 1, 11, 8, 10);
g.addColorStop(0, '#fff4f8'); g.addColorStop(1, '#f090b0');
ctx.fillStyle = g; ctx.beginPath(); ctx.ellipse(11, 8, 10, 6.5, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(200,60,100,0.5)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(3, 8); ctx.lineTo(14, 8); ctx.stroke();
addCanvas(scene, 'cc-petal', c);
}
}
let baked = false;
export async function prepareChineseCheckersArt(scene, seats) {
try {
if (document.fonts?.load) {
await Promise.race([
Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]),
new Promise((res) => setTimeout(res, 1200)),
]);
}
} catch (_) { /* fall back to Georgia */ }
if (!baked || !scene.textures.exists('cc-room')) {
bakeRoom(scene); bakeMarbles(scene); bakePlate(scene);
bakeCard(scene, 'cc-card-status', STATUS.w, STATUS.h);
bakeCard(scene, 'cc-card-log', LOG.w, LOG.h);
bakeMedals(scene); bakeLattice(scene); bakeBits(scene);
baked = true;
}
bakeBoard(scene, seats);
}

View File

@ -0,0 +1,96 @@
// ChineseCheckersDialogs.js — pavilion pop-ups on rice paper in a black
// lacquer frame. Each opener returns { close() } and swallows clicks beneath.
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { DISPLAY_FONT, SERIF } from './ChineseCheckersArt.js';
const INK = '#5a1a12';
export function frame(scene, x, y, w, h, depth) {
const g = scene.add.graphics().setDepth(depth);
g.fillStyle(0x000000, 0.5).fillRoundedRect(x + 6, y + 10, w, h, 16);
g.fillStyle(0x120808, 1).fillRoundedRect(x, y, w, h, 16);
g.lineStyle(3, 0xe8c46a, 1).strokeRoundedRect(x + 5, y + 5, w - 10, h - 10, 13);
g.fillStyle(0xf4ecd8, 1).fillRoundedRect(x + 14, y + 14, w - 28, h - 28, 10);
g.lineStyle(2, 0x8e1c16, 1).strokeRoundedRect(x + 22, y + 22, w - 44, h - 44, 8);
// cloud-scroll corners
g.lineStyle(2, 0x8e1c16, 0.8);
for (const [cx, cy] of [[x + 40, y + 40], [x + w - 40, y + 40], [x + 40, y + h - 40], [x + w - 40, y + h - 40]]) {
g.beginPath(); g.arc(cx, cy, 8, 0, Math.PI * 1.6); g.strokePath();
}
return g;
}
export function blocker(scene, depth, alpha = 0) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x05030a, 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, sixPlayers, onChange, onRules, onNewGame, onLeave, onClose }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 600, h = 760;
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 Pavilion', { fontFamily: DISPLAY_FONT, fontSize: '32px', color: INK }).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(), 0x2a4a6a],
[() => `Opponent speed: ${PACE[settings.pace]}`, () => cycle('pace', ['relaxed', 'normal', 'fast'])],
[() => `Skip opponent animations: ${onOff(settings.skipAI)}`, () => onChange('skipAI', !settings.skipAI)],
[() => `Path previews & row gains: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)],
[() => `Colour-blind symbols on marbles: ${onOff(settings.symbols)}`, () => onChange('symbols', !settings.symbols)],
[() => `Wind chimes: ${onOff(settings.chimes)}`, () => onChange('chimes', !settings.chimes)],
[() => `House rule — anti-blocking: ${onOff(settings.antiBlock)}`, () => onChange('antiBlock', !settings.antiBlock)],
[() => `House rule — partner teams (6 players): ${onOff(settings.teams)}`, () => onChange('teams', !settings.teams)],
['How to Play', () => onRules()],
['New Game', () => { hRef.close(); onNewGame(); }, 0x6a4a1a],
['Leave Table', () => { hRef.close(); onLeave(); }, 0x7a1a14],
];
rows.forEach(([label, fn, bg], i) => {
const text = typeof label === 'function' ? label() : label;
const btn = new Button(scene, cx, y + 124 + i * 50, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, {
width: 520, height: 42, fontSize: 15, bg: bg ?? 0x3a1a14,
}).setDepth(depth + 2);
objs.push(btn);
});
const note = sixPlayers
? 'House rules apply from the next game.'
: 'House rules apply from the next game. Partner teams need all six seats.';
objs.push(scene.add.text(cx, y + h - 50, `${note}\nKeys: click or drag a marble · 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.55)];
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 + 66, heading, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 134, text, { fontFamily: SERIF, fontSize: '18px', color: '#2a1a10', 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: 0x7a1a14 }).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: 0x2a4a6a }).setDepth(depth + 2));
hRef = handle(objs);
return hRef;
}
export function toast(scene, text, { depth, x = GAME_WIDTH / 2, y = 1030, ms = 2200 } = {}) {
const t = scene.add.text(x, y, text, { fontFamily: SERIF, fontSize: '20px', color: '#2a1a10', backgroundColor: '#f4ecd8', 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,100 @@
// ChineseCheckersEndScreen.js — the finishing podium (everyone ranked), the
// team result when partners played, and a stats table per seat.
import { Button } from '../../ui/Button.js';
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { DISPLAY_FONT, SERIF, GLASS } from './ChineseCheckersArt.js';
import { frame } from './ChineseCheckersDialogs.js';
import { rankings, teamRankings, rowsToGo, pegsHome } from './ChineseCheckersLogic.js';
const PLACE = ['1st', '2nd', '3rd', '4th', '5th', '6th'];
const REASON = {
stalemate: 'The board locked up — nobody could make progress. Ranked by rows still to travel.',
cap: 'The candles burned down — ranked by rows still to travel.',
boxed: 'A marble was boxed in for good — the last places went by rows still to travel.',
};
export function openEndScreen(scene, { gs, names, human, depth, symbols, onPlayAgain, onMenu }) {
const objs = [];
const w = 1100, h = 780;
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, 0x05030a, 0.55).setDepth(depth - 1).setInteractive());
objs.push(frame(scene, x, y, w, h, depth));
const order = rankings(gs);
const nm = (c) => (c === human ? 'You' : names[c]);
let title, good;
if (gs.winningTeam) {
good = gs.winningTeam.includes(human);
const [a, b] = gs.winningTeam;
title = good ? `You and ${nm(a === human ? b : a)} win as a team!` : `${nm(a)} & ${nm(b)} win as a team`;
} else {
good = order[0] === human;
title = good ? 'All ten home — you win!' : `${nm(order[0])} wins`;
}
objs.push(scene.add.text(x + w / 2, y + 64, title, { fontFamily: DISPLAY_FONT, fontSize: '34px', color: good ? '#1f6a3a' : '#8e1c16' }).setOrigin(0.5).setDepth(depth + 1));
const sub = REASON[gs.endReason] ?? (gs.teams ? 'A pair is home when both partners have filled their points.' : `Your place: ${PLACE[order.indexOf(human)]}`);
objs.push(scene.add.text(x + w / 2, y + 104, sub, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#4a3a22' }).setOrigin(0.5).setDepth(depth + 1));
// podium — 1st in the middle, then alternating outward
const n = order.length;
const heights = [150, 118, 94, 74, 58, 46];
const slotW = 132;
const slots = [];
for (let r = 0; r < n; r++) slots.push(r);
const arranged = []; // left → right ranks
slots.forEach((r) => (r % 2 ? arranged.unshift(r) : arranged.push(r)));
const podX = x + w / 2 - (n * slotW) / 2 + 8, podY = y + 362;
const g = scene.add.graphics().setDepth(depth + 1);
objs.push(g);
const team = teamRankings(gs);
arranged.forEach((rank, k) => {
const c = order[rank];
const bx = podX + k * slotW, bh = heights[rank];
const G = GLASS[c];
g.fillStyle(0x000000, 0.25).fillRoundedRect(bx + 4, podY - bh + 6, slotW - 16, bh, 6);
g.fillStyle(0x1a0c0a, 1).fillRoundedRect(bx, podY - bh, slotW - 16, bh, 6);
g.lineStyle(2, 0xe8c46a, 0.9).strokeRoundedRect(bx, podY - bh, slotW - 16, bh, 6);
g.fillStyle(G.hex, 1).fillRect(bx + 6, podY - bh + 6, slotW - 28, 6);
const mx = bx + (slotW - 16) / 2;
objs.push(scene.add.image(mx, podY - bh - 32, `cc-medal-${rank + 1}`).setScale(0.9).setDepth(depth + 2));
objs.push(scene.add.image(mx, podY - bh + 34, symbols ? `cc-ms-${c}` : `cc-m-${c}`).setScale(0.5).setDepth(depth + 2));
objs.push(scene.add.text(mx, podY - bh + 66, PLACE[rank], { fontFamily: DISPLAY_FONT, fontSize: '18px', color: '#f8ead0' }).setOrigin(0.5).setDepth(depth + 2));
const name = nm(c);
objs.push(scene.add.text(mx, podY + 18, name.length > 11 ? name.slice(0, 10) + '…' : name, { fontFamily: SERIF, fontSize: '16px', color: G.ink }).setOrigin(0.5).setDepth(depth + 2));
if (team) {
const ti = team.findIndex((t) => t.includes(c));
objs.push(scene.add.text(mx, podY + 38, `team ${['A', 'B', 'C'][ti] ?? ''}`, { fontFamily: SERIF, fontSize: '12px', fontStyle: 'italic', color: '#4a3a22' }).setOrigin(0.5).setDepth(depth + 2));
}
});
// stats table
const rows = [
['Marbles home', (c) => `${pegsHome(gs, c)}/10`],
['Rows still to travel', (c) => rowsToGo(gs, c)],
['Moves', (c) => gs.stats[c].moves],
['Steps', (c) => gs.stats[c].steps],
['Jump moves', (c) => gs.stats[c].jumps],
['Total hops', (c) => gs.stats[c].hops],
['Longest chain', (c) => (gs.stats[c].longest ? `${gs.stats[c].longest} hops` : '—')],
['Passes', (c) => gs.stats[c].passes],
];
const tx = x + 90, ty = y + 438;
const colW = Math.min(128, (w - 420) / n);
const col0 = tx + 270;
order.forEach((c, k) => {
objs.push(scene.add.text(col0 + k * colW, ty, nm(c).toUpperCase().slice(0, 9), { fontFamily: DISPLAY_FONT, fontSize: '13px', color: GLASS[c].ink }).setOrigin(0.5).setDepth(depth + 1));
});
rows.forEach(([label, fn], i) => {
const yy = ty + 30 + i * 30;
if (i % 2 === 0) g.fillStyle(0x8e1c16, 0.06).fillRect(tx - 10, yy - 14, 270 + n * colW, 28);
objs.push(scene.add.text(tx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a' }).setOrigin(0, 0.5).setDepth(depth + 1));
order.forEach((c, k) => objs.push(scene.add.text(col0 + k * colW, yy, String(fn(c)), { fontFamily: SERIF, fontSize: '16px', color: GLASS[c].ink }).setOrigin(0.5).setDepth(depth + 1)));
});
const by = y + h - 64;
objs.push(new Button(scene, x + w / 2 - 130, by, 'Play Again', () => { close(); onPlayAgain(); }, { width: 230, height: 50, fontSize: 20, bg: 0x1f6a3a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 130, by, 'Leave Table', () => { close(); onMenu(); }, { width: 230, height: 50, fontSize: 20, bg: 0x7a1a14 }).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,180 @@
// ChineseCheckersHud.js — the furniture round the star: a lacquer plaque per
// seated colour (portrait, name, skill, ten progress pips, a note line, the
// finishing medal, a lantern glow on the seat to play), the status card, the
// tea-house ledger of recent moves, the buttons and speech bubbles.
import { Button } from '../../ui/Button.js';
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
import { PLATES, PLATE, plateParts, STATUS, BUTTONS, BTN, LOG, LOG_LINES } from './ChineseCheckersLayout.js';
import { DISPLAY_FONT, SERIF, GLASS } from './ChineseCheckersArt.js';
import { pegsHome, currentColor, isFinished, isStuck, partnerOf, PEGS } from './ChineseCheckersLogic.js';
const PLACE = ['1st', '2nd', '3rd', '4th', '5th', '6th'];
const short = (s, n = 13) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
export class Hud {
constructor(scene, depth, { seats, human, names, skills, opponents, symbols, onButton }) {
this.scene = scene;
this.depth = depth;
this.seats = seats;
this.human = human;
this.names = names;
this.skills = skills;
this.opponents = opponents;
this.symbols = symbols;
this.onButton = onButton;
this.plates = {};
this.buttons = {};
this.bubbles = {};
}
build() {
const s = this.scene, D = this.depth;
for (const c of this.seats) {
const P = PLATES[c], parts = plateParts(c), G = GLASS[c];
const glow = s.add.image(P.x - 40, P.y - 40, 'cc-plate-glow').setOrigin(0).setDepth(D - 1).setAlpha(0);
s.add.image(P.x - 14, P.y - 14, 'cc-plate').setOrigin(0).setDepth(D);
const band = s.add.graphics().setDepth(D + 1);
band.fillStyle(G.hex, 1).fillRoundedRect(P.x + 6, P.y + 14, 6, PLATE.h - 28, 3);
const pp = parts.portrait;
s.add.circle(pp.x, pp.y, pp.r + 4, G.hex, 1).setDepth(D + 1);
const portrait = c === this.human
? createPlayerPortrait(s, pp.x, pp.y, pp.r, D + 2, 'ChineseCheckersGame')
: createOpponentPortrait(s, this.opponents[c] ?? { id: 'bot', spriteIndex: 0 }, pp.x, pp.y, pp.r, D + 2);
s.add.text(parts.name.x, parts.name.y, short(this.names[c], c === this.human ? 15 : 10), {
fontFamily: DISPLAY_FONT, fontSize: '19px', color: '#f8ead0',
}).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: '12px', color: '#e8c46a' })
.setOrigin(1, 0.5).setDepth(D + 1);
}
const pips = [];
for (let i = 0; i < PEGS; i++) {
pips.push(s.add.image(parts.pips.x + i * parts.pips.dx, parts.pips.y, this.pipTex(c)).setScale(0.2).setDepth(D + 1).setAlpha(0.25));
}
const note = s.add.text(parts.note.x, parts.note.y, '', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#d8c4a0' })
.setOrigin(0, 0.5).setDepth(D + 1);
const medal = s.add.image(parts.medal.x, parts.medal.y, 'cc-medal-1').setOrigin(0.5, 0).setDepth(D + 3).setVisible(false);
this.plates[c] = { parts, glow, portrait, pips, note, medal, place: 0, home: -1 };
}
// status card
s.add.image(STATUS.x - 14, STATUS.y - 14, 'cc-card-status').setOrigin(0).setDepth(D);
this.status = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 52, '', {
fontFamily: DISPLAY_FONT, fontSize: '27px', color: '#5a1a12', align: 'center', wordWrap: { width: STATUS.w - 50 },
}).setOrigin(0.5).setDepth(D + 1);
this.sub = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 126, '', {
fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a', align: 'center', wordWrap: { width: STATUS.w - 56 }, lineSpacing: 3,
}).setOrigin(0.5).setDepth(D + 1);
// buttons
const label = { undo: 'Undo (Z)', hint: 'Hint (H)', menu: 'Menu (Esc)' };
const bg = { undo: 0x6a4a1a, hint: 0x2a4a6a, menu: 0x6e1a14 };
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: 16, bg: bg[k] }).setDepth(D + 3);
if (k !== 'menu') this.buttons[k].setEnabled(false);
}
// ledger
s.add.image(LOG.x - 14, LOG.y - 14, 'cc-card-log').setOrigin(0).setDepth(D);
s.add.text(LOG.x + 24, LOG.y + 26, 'TEA HOUSE LEDGER', { fontFamily: DISPLAY_FONT, fontSize: '15px', color: '#6a3a22' }).setOrigin(0, 0.5).setDepth(D + 1);
this.turnText = s.add.text(LOG.x + LOG.w - 52, LOG.y + 26, '', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#6a3a22' }).setOrigin(1, 0.5).setDepth(D + 1);
this.logG = s.add.graphics().setDepth(D + 1);
this.logLines = [];
for (let i = 0; i < LOG_LINES; i++) {
this.logLines.push(s.add.text(LOG.x + 44, LOG.y + 60 + i * 31, '', {
fontFamily: SERIF, fontSize: '15px', color: '#3a2a1a', wordWrap: { width: LOG.w - 80 },
}).setOrigin(0, 0.5).setDepth(D + 1));
}
return this;
}
pipTex(c) { return this.symbols ? `cc-ms-${c}` : `cc-m-${c}`; }
setSymbols(on) {
this.symbols = !!on;
for (const c of this.seats) for (const p of this.plates[c].pips) p.setTexture(this.pipTex(c));
}
refresh(gs, { thinking = null } = {}) {
const cur = gs.phase === 'play' ? currentColor(gs) : null;
for (const c of this.seats) {
const pl = this.plates[c];
const home = pegsHome(gs, c);
pl.pips.forEach((im, i) => im.setAlpha(i < home ? 1 : 0.22));
if (home !== pl.home && pl.home >= 0 && home > pl.home) {
const im = pl.pips[home - 1];
this.scene.tweens.add({ targets: im, scale: { from: im.scale * 1.8, to: im.scale }, duration: 320, ease: 'Back.Out' });
}
pl.home = home;
const active = c === cur;
if (active && pl.glow.alpha === 0) {
this.scene.tweens.killTweensOf(pl.glow);
pl.glow.setAlpha(0.9);
this.scene.tweens.add({ targets: pl.glow, alpha: { from: 0.95, to: 0.45 }, duration: 900, yoyo: true, repeat: -1, ease: 'Sine.InOut' });
} else if (!active && pl.glow.alpha > 0) {
this.scene.tweens.killTweensOf(pl.glow);
pl.glow.setAlpha(0);
}
let note;
const place = gs.finished.indexOf(c);
if (isFinished(gs, c) && place >= 0) note = `${gs.phase === 'play' ? 'Finished' : 'Placed'} ${PLACE[place]}`;
else if (isStuck(gs, c)) note = 'Boxed in for good';
else if (active) note = c === this.human ? 'Your move' : (thinking === c ? 'Thinking…' : 'To play');
else note = `${home}/10 home`;
const partner = partnerOf(gs, c);
if (partner) note += ` · with ${partner === this.human ? 'you' : short(this.names[partner], 9)}`;
pl.note.setText(note).setColor(active ? '#ffe0a0' : '#d8c4a0');
}
this.turnText.setText(`turn ${Math.floor(gs.turn / gs.seats.length) + 1}`);
}
showMedal(c, place) {
const pl = this.plates[c];
if (!pl || pl.place) return;
pl.place = place;
pl.medal.setTexture(`cc-medal-${Math.min(6, place)}`).setVisible(true).setScale(0.2).setAlpha(0);
this.scene.tweens.add({ targets: pl.medal, scale: 1, alpha: 1, duration: 520, ease: 'Back.Out' });
}
setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); }
setButton(k, on) { this.buttons[k]?.setEnabled(!!on); }
setLog(entries) {
const g = this.logG;
g.clear();
const list = entries.slice(-LOG_LINES);
this.logLines.forEach((t, i) => {
const e = list[i];
if (!e) { t.setText(''); return; }
t.setText(e.text).setColor(e.color ? GLASS[e.color].ink : '#3a2a1a').setAlpha(0.55 + 0.45 * ((i + 1) / list.length));
if (e.color) g.fillStyle(GLASS[e.color].hex, 1).fillCircle(LOG.x + 30, t.y, 6);
});
}
plateCenter(c) { const P = PLATES[c]; return { x: P.x + PLATE.w * 0.62, y: P.y + PLATE.h * 0.57 }; }
say(c, text, dur = 2400) {
const pl = this.plates[c];
if (!pl || c === this.human) return;
const s = this.scene;
this.bubbles[c]?.destroy();
const b = pl.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: '#2a1a10', align: 'center', wordWrap: { width: b.w - 30 },
}).setOrigin(0.5);
const g = s.add.graphics();
const below = b.y > PLATES[c].y;
g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + 4, b.w, b.h, 12);
g.fillStyle(0xf6eedb, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 12);
g.lineStyle(2, GLASS[c].hex, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 12);
const tx = Math.max(b.x + 24, Math.min(b.x + b.w - 24, pl.parts.portrait.x + 30));
if (below) g.fillStyle(0xf6eedb, 1).fillTriangle(tx - 10, b.y + 1, tx + 10, b.y + 1, tx, b.y - 13);
else g.fillStyle(0xf6eedb, 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.plates[c]?.portrait?.playEmotion?.(e); }
hidePortraits() { Object.values(this.plates).forEach((p) => p.portrait?.setVideoVisible?.(false)); }
showPortraits() { Object.values(this.plates).forEach((p) => p.portrait?.setVideoVisible?.(true)); }
}

View File

@ -0,0 +1,119 @@
// ChineseCheckersLayout.js — screen geometry for the "Moonlit Tea Pavilion"
// table. Phaser-free (tools/verifyChineseCheckers.js checks bounds/overlaps).
//
// moon window · ┌── red plaque lantern
// purple plaque ╱‾‾‾‾‾‾╲ yellow plaque
// table log │ star │ status card + buttons
// orange plaque ╲______╱ green plaque
// teapot · blue (you) plaque ──┘ plum branch
//
// The rosewood board is a pointy-top hexagon whose six vertices sit just
// beyond the six star points.
import { CELLS, TRI_CELLS } from './ChineseCheckersLogic.js';
export const W = 1920;
export const H = 1080;
export const CX = 960;
export const CY = 540;
export const CELL = 58; // centre-to-centre hole spacing
export const ROW_H = CELL * Math.sqrt(3) / 2; // ≈ 50.2
export const HOLE_R = 21;
export const MARBLE_R = 19;
export const BOARD_R = 478; // hexagon circumradius
export const BOARD_TEX = 1000; // board texture size (square)
export function cellXY(id) {
const { q, r } = CELLS[id];
return { x: CX + CELL * (q + r / 2), y: CY + ROW_H * r };
}
export const CELL_XY = CELLS.map((_, id) => cellXY(id));
// Hexagon corners (pointy top), clockwise from the top vertex.
export function boardHex(R = BOARD_R, cx = CX, cy = CY) {
return [0, 1, 2, 3, 4, 5].map((k) => {
const a = -Math.PI / 2 + k * Math.PI / 3;
return { x: cx + R * Math.cos(a), y: cy + R * Math.sin(a) };
});
}
// The nearest cell to (x, y) within `r` px, or −1.
export function cellAt(x, y, r = CELL * 0.48) {
let best = -1, bd = r * r;
for (let id = 0; id < CELL_XY.length; id++) {
const p = CELL_XY[id];
const d = (p.x - x) ** 2 + (p.y - y) ** 2;
if (d < bd) { bd = d; best = id; }
}
return best;
}
// ── Seat plaques, one beside each star point ────────────────────────────────
export const PLATE = { w: 300, h: 100 };
export const PLATES = {
red: { x: 1100, y: 28 },
yellow: { x: 1420, y: 210 },
green: { x: 1420, y: 770 },
blue: { x: 520, y: 952 },
orange: { x: 200, y: 770 },
purple: { x: 200, y: 210 },
};
export function plateRect(c) { const p = PLATES[c]; return { x: p.x, y: p.y, w: PLATE.w, h: PLATE.h }; }
export function plateParts(c) {
const { x, y } = PLATES[c];
return {
portrait: { x: x + 50, y: y + 50, r: 36 },
name: { x: x + 100, y: y + 25 },
skill: { x: x + PLATE.w - 14, y: y + 25 },
pips: { x: x + 108, y: y + 57, dx: 19 },
note: { x: x + 100, y: y + 82 },
medal: { x: x + PLATE.w - 6, y: y + 6 },
// speech bubbles open toward the screen centre
bubble: {
x: x + (x + PLATE.w / 2 < CX ? 40 : -60), y: y < CY ? y + PLATE.h + 12 : y - 76, w: 320, h: 64,
},
};
}
// ── Side panels ─────────────────────────────────────────────────────────────
export const STATUS = { x: 1440, y: 340, w: 440, h: 196 };
export const BTN = { w: 136, h: 44 };
export const BUTTONS = {
undo: { x: 1440 + 68, y: 574 },
hint: { x: 1440 + 220, y: 574 },
menu: { x: 1440 + 372, y: 574 },
};
export const LOG = { x: 40, y: 340, w: 440, h: 380 };
export const LOG_LINES = 10;
// Props baked into the room.
export const MOON = { x: 330, y: 110, r: 86 };
export const LANTERNS = [{ x: 1600, y: 0, len: 92 }, { x: 1830, y: 0, len: 150 }, { x: 92, y: 0, len: 120 }];
export const TEAPOT = { x: 170, y: 975 };
export const CUP = { x: 408, y: 1000 };
export const BRANCH = { x: 1920, y: 1080 };
export const BANNER = { x: CX, y: CY - 40 };
// Outline of a star point (padded outward from its centroid by `pad` px).
export function triPolygon(tri, pad = HOLE_R + 8) {
const cells = TRI_CELLS[tri];
const pts = [cells[0], cells[3], cells[9]].map((id) => CELL_XY[id]);
const cx = (pts[0].x + pts[1].x + pts[2].x) / 3, cy = (pts[0].y + pts[1].y + pts[2].y) / 3;
return pts.map((p) => {
const dx = p.x - cx, dy = p.y - cy, len = Math.hypot(dx, dy) || 1;
return { x: p.x + (dx / len) * pad, y: p.y + (dy / len) * pad };
});
}
export function triCentroid(tri) {
const ps = TRI_CELLS[tri].map((id) => CELL_XY[id]);
return { x: ps.reduce((a, p) => a + p.x, 0) / ps.length, y: ps.reduce((a, p) => a + p.y, 0) / ps.length };
}
// The inner hexagon (61 holes), padded outward.
export function centerPolygon(pad = HOLE_R + 8) {
const R = 4 * CELL; // corner cells sit 4 holes from the centre
return [0, 1, 2, 3, 4, 5].map((k) => {
const a = k * Math.PI / 3; // flat sides top/bottom: corners at 0°, 60°…
return { x: CX + (R + pad) * Math.cos(a), y: CY + (R + pad) * Math.sin(a) };
});
}

View File

@ -1,34 +1,56 @@
// Pure Chinese Checkers rules. No Phaser dependency. // ChineseCheckersLogic.js — pure Chinese Checkers rules. No Phaser.
// //
// Board model: // Board model
// - 121 holes on a 6-pointed star, addressed in axial hex coords (q, r). // 121 holes on a six-pointed star in axial hex coords (q, r), s = −q−r.
// - Inner hexagon of radius 4 (61 cells) + 6 triangular points of side 4 // The inner hexagon (radius 4, 61 cells) plus six triangular points of side 4
// (10 cells each), one per hex direction. // (10 cells each), one per hex direction. Every cell has a stable integer id
// - 6 colors, one per triangle. Each player has 10 pegs starting in their // (0‥120); pegs are stored as cell ids. CELLS[id] = { q, r, tri }.
// home triangle and must fill the OPPOSITE triangle (their target).
// //
// A cell (q, r) is on the board iff at least 2 of {|q|, |r|, |s|} // Screen orientation (pointy-top, +q east, +r south-east):
// (where s = -q-r) are ≤ 4. Equivalently the inner hex plus 6 points where // 'r-' north (red) 'q+' north-east (yellow) 's-' south-east (green)
// one axis is in (4, 8]. // 'r+' south (blue) 'q-' south-west (orange) 's+' north-west (purple)
// Each colour starts in its home point and must fill the OPPOSITE point.
// //
// Move types per turn (mutually exclusive): // Seatings (clockwise on screen from the south / human seat)
// 1. Step — one hex to an adjacent empty cell. // 2 players blue · red (opposite points)
// 2. Jump chain — over one or more adjacent pegs (own or opponent) to the // 3 players blue · purple · yellow (alternating points; targets empty)
// empty cell directly on the other side, repeatable from each landing. // 4 players blue · orange · red · yellow (two opposite pairs)
// 5 players the 6-seat star with the south-east point left empty
// 6 players blue · orange · purple · red · yellow · green
// //
// Enforced rules: // A turn moves ONE peg, either
// - A peg may never come to REST in another player's home or target triangle // a step — to an adjacent empty hole, or
// (jumping THROUGH is allowed). // a jump chain — over an adjacent peg (any colour) into the empty hole right
// - Once a peg has left its own home triangle, it may not re-enter it. // behind it, repeatable from each landing.
// - A peg in its own target triangle may only move within the target. //
// Laws
// • A peg may never come to REST in a point other than its own home or target
// (passing through mid-chain is fine).
// • Once a peg has left its home point it may never re-enter it.
// • A peg inside its target may only move to another target hole.
//
// House rules (opts)
// antiBlock — your target counts as filled once every hole in it is taken
// and at least one is yours: an opponent who never leaves home
// can't spoil your finish. Default ON.
// teams — six players only: opposite seats are partners; the first
// pair with BOTH partners finished wins the game. Default OFF.
//
// Boxed in: a player with a marble outside their target walled in for good by
// finished players' marbles (which never move again) can never finish — it is
// marked `stuck`, its turns are skipped, and it ranks behind everyone still
// racing. (Typical cause: a straggler left at home that anti-blocking let an
// opponent finish around.)
//
// The game ends when every seat but one has finished (no teams), when a team
// completes (teams), when at most one player can still finish, when nobody
// can move for a full round or nobody has made
// new progress for STALL_ROUNDS rounds (a spoiler deadlock), or at a hard turn
// cap (a safety valve). Early ends rank by rows still to travel.
export const COLORS = ['red', 'yellow', 'green', 'blue', 'orange', 'purple']; export const COLORS = ['red', 'yellow', 'green', 'blue', 'orange', 'purple'];
export const PEGS = 10;
// Triangle ids correspond to which axis-extreme defines the point.
// Pointy-top hex coords with +q east, +r south-east:
// r- = top/north, r+ = south
// q+ = NE, q- = SW
// s- = SE, s+ = NW
export const TRIANGLES = { export const TRIANGLES = {
'r-': [[1,-5],[2,-5],[3,-5],[4,-5],[2,-6],[3,-6],[4,-6],[3,-7],[4,-7],[4,-8]], 'r-': [[1,-5],[2,-5],[3,-5],[4,-5],[2,-6],[3,-6],[4,-6],[3,-7],[4,-7],[4,-8]],
'r+': [[-1,5],[-2,5],[-3,5],[-4,5],[-2,6],[-3,6],[-4,6],[-3,7],[-4,7],[-4,8]], 'r+': [[-1,5],[-2,5],[-3,5],[-4,5],[-2,6],[-3,6],[-4,6],[-3,7],[-4,7],[-4,8]],
@ -38,305 +60,415 @@ export const TRIANGLES = {
's-': [[1,4],[2,3],[3,2],[4,1],[2,4],[3,3],[4,2],[3,4],[4,3],[4,4]], 's-': [[1,4],[2,3],[3,2],[4,1],[2,4],[3,3],[4,2],[3,4],[4,3],[4,4]],
}; };
export const COLOR_HOME = { export const HOME = { red: 'r-', yellow: 'q+', green: 's-', blue: 'r+', orange: 'q-', purple: 's+' };
red: 'r-', export const TARGET = { red: 'r+', yellow: 'q-', green: 's+', blue: 'r-', orange: 'q+', purple: 's-' };
yellow: 'q+', export const OPPOSITE = { red: 'blue', blue: 'red', yellow: 'orange', orange: 'yellow', green: 'purple', purple: 'green' };
green: 's-', // The colour whose home is a given point.
blue: 'r+', export const OWNER = Object.fromEntries(Object.entries(HOME).map(([c, t]) => [t, c]));
orange: 'q-',
purple: 's+', export const SEATINGS = {
2: ['blue', 'red'],
3: ['blue', 'purple', 'yellow'],
4: ['blue', 'orange', 'red', 'yellow'],
5: ['blue', 'orange', 'purple', 'red', 'yellow'],
6: ['blue', 'orange', 'purple', 'red', 'yellow', 'green'],
}; };
export const HUMAN = 'blue';
export const DEFAULT_OPTS = { antiBlock: true, teams: false };
export const TURN_CAP = 400; // full rounds before the safety valve
export const STALL_ROUNDS = 25; // full rounds with no new best total → stalemate
export const COLOR_TARGET = { export function seatColors(n) {
red: 'r+', return [...SEATINGS[Math.max(2, Math.min(6, n | 0))]];
yellow: 'q-', }
green: 's+',
blue: 'r-',
orange: 'q+',
purple: 's-',
};
export const PEGS_PER_PLAYER = 10; // ── Static topology ─────────────────────────────────────────────────────────
export const CELLS = []; // id → { q, r, tri }
const ID = new Map(); // 'q,r' → id
const key = (q, r) => `${q},${r}`;
export const cellKey = (q, r) => `${q},${r}`; (function build() {
for (let r = -8; r <= 8; r++) {
// ── Static board topology ─────────────────────────────────────────────────── for (let q = -8; q <= 8; q++) {
const s = -q - r;
const BOARD_CELLS = new Set(); const a = Math.abs(q), b = Math.abs(r), c = Math.abs(s);
const TRIANGLE_OF = new Map(); // key -> 'center' | triangle id let tri = null;
if (Math.max(a, b, c) <= 4) tri = 'center';
(function buildBoard() { else {
// Inner hexagon (radius 4): max(|q|,|r|,|s|) ≤ 4. for (const [t, cells] of Object.entries(TRIANGLES)) {
for (let q = -4; q <= 4; q++) { if (cells.some(([cq, cr]) => cq === q && cr === r)) { tri = t; break; }
const rMin = Math.max(-4, -q - 4); }
const rMax = Math.min(4, -q + 4); }
for (let r = rMin; r <= rMax; r++) { if (!tri) continue;
BOARD_CELLS.add(cellKey(q, r)); ID.set(key(q, r), CELLS.length);
TRIANGLE_OF.set(cellKey(q, r), 'center'); CELLS.push({ q, r, tri });
}
}
for (const [tri, cells] of Object.entries(TRIANGLES)) {
for (const [q, r] of cells) {
BOARD_CELLS.add(cellKey(q, r));
TRIANGLE_OF.set(cellKey(q, r), tri);
} }
} }
})(); })();
export function isOnBoard(q, r) { export const NUM_CELLS = CELLS.length; // 121
return BOARD_CELLS.has(cellKey(q, r)); export const cellId = (q, r) => ID.get(key(q, r)) ?? -1;
} export const triOf = (id) => CELLS[id].tri;
export function triangleAt(q, r) { // Cells of each point, in TRIANGLES order (base row first, tip last).
return TRIANGLE_OF.get(cellKey(q, r)) ?? null; export const TRI_CELLS = Object.fromEntries(
} Object.entries(TRIANGLES).map(([t, cells]) => [t, cells.map(([q, r]) => cellId(q, r))]),
);
export function allCells() { // Six axial directions. NEIGH[id*6+d] = neighbour or −1; JUMP[id*6+d] = landing
return [...BOARD_CELLS].map((k) => { // two away or −1 (mid cell = NEIGH).
const [q, r] = k.split(',').map(Number); export const DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
return { q, r }; export const NEIGH = new Int16Array(NUM_CELLS * 6).fill(-1);
export const JUMP = new Int16Array(NUM_CELLS * 6).fill(-1);
for (let id = 0; id < NUM_CELLS; id++) {
const { q, r } = CELLS[id];
DIRS.forEach(([dq, dr], d) => {
NEIGH[id * 6 + d] = cellId(q + dq, r + dr);
const mid = cellId(q + dq, r + dr);
if (mid >= 0) JUMP[id * 6 + d] = cellId(q + 2 * dq, r + 2 * dr);
}); });
} }
// Six axial neighbor offsets. export function hexDistance(a, b) {
const NEIGHBOR_OFFSETS = [ const A = CELLS[a], B = CELLS[b];
[ 1, 0], [-1, 0], return (Math.abs(A.q - B.q) + Math.abs(A.r - B.r) + Math.abs(A.q + A.r - B.q - B.r)) / 2;
[ 0, 1], [ 0, -1], }
[ 1, -1], [-1, 1],
];
const NEIGHBORS = new Map(); // Rows still to travel: how many rows a cell lies from the TIP row of a point
for (const k of BOARD_CELLS) { // (0 at the tip, 16 at the opposite tip). This is the classic race metric.
const [q, r] = k.split(',').map(Number); const AXIS = {
const arr = []; 'r-': (q, r) => r + 8, 'r+': (q, r) => 8 - r,
for (const [dq, dr] of NEIGHBOR_OFFSETS) { 'q+': (q, r) => 8 - q, 'q-': (q, r) => q + 8,
if (isOnBoard(q + dq, r + dr)) arr.push([q + dq, r + dr]); 's+': (q, r) => 8 + q + r, 's-': (q, r) => 8 - q - r,
};
// ROWS[tri][id] — rows from that point's tip. LATERAL[tri][id] — sideways
// distance from the point's centre line (0 on the line).
export const ROWS = {};
export const LATERAL = {};
for (const t of Object.keys(TRIANGLES)) {
ROWS[t] = new Int8Array(NUM_CELLS);
LATERAL[t] = new Float32Array(NUM_CELLS);
for (let id = 0; id < NUM_CELLS; id++) {
const { q, r } = CELLS[id];
ROWS[t][id] = AXIS[t](q, r);
// The two other axes measure sideways drift; on the centre line they match.
const s = -q - r;
const vals = { 'r-': [q, s], 'r+': [q, s], 'q+': [r, s], 'q-': [r, s], 's+': [q, r], 's-': [q, r] }[t];
LATERAL[t][id] = Math.abs(vals[0] - vals[1]) / 2;
} }
NEIGHBORS.set(k, arr);
} }
export const rowsLeft = (color, id) => ROWS[TARGET[color]][id];
// The ideal finish (every target hole filled) totals 0+1+1+2+2+2+3+3+3+3 = 20.
export const MIN_ROWS = TRI_CELLS['r-'].reduce((a, id) => a + ROWS['r-'][id], 0);
// Triangle centroid (for AI heuristic). // ── State ───────────────────────────────────────────────────────────────────
export const TRIANGLE_CENTROID = {}; function freshStats() { return { moves: 0, steps: 0, jumps: 0, hops: 0, longest: 0, passes: 0 }; }
for (const [id, cells] of Object.entries(TRIANGLES)) {
let sq = 0, sr = 0;
for (const [q, r] of cells) { sq += q; sr += r; }
TRIANGLE_CENTROID[id] = { q: sq / cells.length, r: sr / cells.length };
}
export function hexDistance(q1, r1, q2, r2) { export function createInitialState(seats = SEATINGS[6], opts = {}) {
return (Math.abs(q1 - q2) seats = [...seats];
+ Math.abs(r1 - r2) if (seats.length < 2 || seats.length > 6) throw new Error('Chinese Checkers seats 2–6 players.');
+ Math.abs((q1 + r1) - (q2 + r2))) / 2; const o = { ...DEFAULT_OPTS, ...opts };
} if (seats.length !== 6) o.teams = false;
const pegs = {}, left = {}, stats = {};
// ── State ────────────────────────────────────────────────────────────────── for (const c of seats) {
pegs[c] = TRI_CELLS[HOME[c]].slice();
export function createInitialState(seatColors = COLORS) { left[c] = Array(PEGS).fill(false);
if (seatColors.length !== 6) { stats[c] = freshStats();
throw new Error('Chinese Checkers requires exactly 6 seats.');
}
const pegs = {};
const leftHome = {};
for (const color of seatColors) {
const home = TRIANGLES[COLOR_HOME[color]];
pegs[color] = home.map(([q, r]) => ({ q, r }));
leftHome[color] = Array(PEGS_PER_PLAYER).fill(false);
} }
return { return {
seatColors: [...seatColors], seats,
opts: o,
teams: o.teams ? teamPairs(seats) : null,
pegs, pegs,
leftHome, left,
currentSeat: 0, current: 0,
phase: 'play', // 'play' | 'game_over' phase: 'play', // 'play' | 'game_over'
winner: null, finished: [], // colours in finishing order
finishedOrder: [], // colors in finishing order stuck: [], // colours that can never finish (boxed in for good)
lastMove: null, winner: null, // first colour to finish
winningTeam: null, // [a, b] when teams decide the game
endReason: null, // 'finished' | 'team' | 'stalemate' | 'cap'
turn: 0, // moves + passes made so far
passStreak: 0,
bestTotal: Infinity, // lowest Σ rows-to-go seen (progress detector)
stall: 0, // turns since bestTotal last improved
lastMoves: [], // most recent moves, newest last (≤ seats.length)
stats,
}; };
} }
export function cloneState(state) { function teamPairs(seats) {
const seen = new Set(), out = [];
for (const c of seats) {
if (seen.has(c)) continue;
const p = OPPOSITE[c];
if (!seats.includes(p)) continue;
seen.add(c); seen.add(p);
out.push([c, p]);
}
return out;
}
export const partnerOf = (state, c) => state.teams?.find((t) => t.includes(c))?.find((x) => x !== c) ?? null;
export function cloneState(s) {
return { return {
seatColors: [...state.seatColors], ...s,
pegs: Object.fromEntries( seats: [...s.seats],
state.seatColors.map((c) => [c, state.pegs[c].map((p) => ({ q: p.q, r: p.r }))]), opts: { ...s.opts },
), teams: s.teams ? s.teams.map((t) => [...t]) : null,
leftHome: Object.fromEntries( pegs: Object.fromEntries(s.seats.map((c) => [c, s.pegs[c].slice()])),
state.seatColors.map((c) => [c, [...state.leftHome[c]]]), left: Object.fromEntries(s.seats.map((c) => [c, s.left[c].slice()])),
), finished: [...s.finished],
currentSeat: state.currentSeat, stuck: [...(s.stuck ?? [])],
phase: state.phase, newlyStuck: [],
winner: state.winner, winningTeam: s.winningTeam ? [...s.winningTeam] : null,
finishedOrder: [...state.finishedOrder], lastMoves: s.lastMoves.map((m) => ({ ...m, path: m.path.slice() })),
lastMove: state.lastMove stats: Object.fromEntries(s.seats.map((c) => [c, { ...s.stats[c] }])),
? { ...state.lastMove, path: state.lastMove.path.map((p) => ({ ...p })) }
: null,
}; };
} }
export const currentColor = (state) => state.seatColors[state.currentSeat]; export const currentColor = (s) => s.seats[s.current];
export const isFinished = (s, c) => s.finished.includes(c);
export const isStuck = (s, c) => !!s.stuck?.includes(c);
// Still racing: neither finished nor boxed in for good.
export const isActive = (s, c) => !isFinished(s, c) && !isStuck(s, c);
export function pegAt(state, q, r) { // Occupancy: Int8Array(121) of seat index + 1 (0 = empty).
for (const color of state.seatColors) { export function occupancy(s) {
const arr = state.pegs[color]; const occ = new Int8Array(NUM_CELLS);
for (let i = 0; i < arr.length; i++) { s.seats.forEach((c, i) => { for (const id of s.pegs[c]) occ[id] = i + 1; });
if (arr[i].q === q && arr[i].r === r) return { color, pegIdx: i }; return occ;
} }
export function pegAt(s, id) {
for (const c of s.seats) {
const i = s.pegs[c].indexOf(id);
if (i >= 0) return { color: c, pegIdx: i };
} }
return null; return null;
} }
function buildOccupiedSet(state) { // ── Move generation ─────────────────────────────────────────────────────────
const occ = new Set(); // A move: { color, pegIdx, from, to, isJump, path: [cellId …] } — path[0] is
for (const color of state.seatColors) { // the start, the last entry the landing; each jump hop is one entry.
for (const p of state.pegs[color]) occ.add(cellKey(p.q, p.r));
}
return occ;
}
// ── Move generation ──────────────────────────────────────────────────────── export function canRest(color, inTarget, hasLeft, id) {
const t = CELLS[id].tri;
// All legal destinations for one peg. Each move: const target = TARGET[color];
// { color, pegIdx, q, r, isJump, path: [{q,r}, ...] } if (inTarget) return t === target;
// where path[0] is the peg's start and the last entry is the landing. if (t === 'center' || t === target) return true;
export function getMovesForPeg(state, color, pegIdx) { if (t === HOME[color]) return !hasLeft;
if (state.phase !== 'play') return [];
if (state.finishedOrder.includes(color)) return [];
const peg = state.pegs[color][pegIdx];
const startKey = cellKey(peg.q, peg.r);
const startTri = triangleAt(peg.q, peg.r);
const targetTri = COLOR_TARGET[color];
const homeTri = COLOR_HOME[color];
const pegInTarget = startTri === targetTri;
// Treat the peg's own start square as empty when projecting jumps —
// it has vacated for the duration of the move.
const occ = buildOccupiedSet(state);
occ.delete(startKey);
const isLegalRest = (q, r) => {
if (pegInTarget) {
// Pegs already in target may only land in target.
return triangleAt(q, r) === targetTri;
}
const tri = triangleAt(q, r);
if (tri === 'center') return true;
if (tri === targetTri) return true;
if (tri === homeTri) {
// Once peg has left home, can't return.
return !state.leftHome[color][pegIdx];
}
// Any other player's home/target.
return false;
};
const moves = [];
// 1. Single step.
for (const [nq, nr] of NEIGHBORS.get(startKey)) {
if (occ.has(cellKey(nq, nr))) continue;
if (!isLegalRest(nq, nr)) continue;
moves.push({
color, pegIdx,
q: nq, r: nr,
isJump: false,
path: [{ q: peg.q, r: peg.r }, { q: nq, r: nr }],
});
}
// 2. Jump chain — BFS over reachable empty landings via jump-over-occupied.
const visited = new Set([startKey]);
const queue = [{ q: peg.q, r: peg.r, path: [{ q: peg.q, r: peg.r }] }];
while (queue.length) {
const node = queue.shift();
for (const [dq, dr] of NEIGHBOR_OFFSETS) {
const midQ = node.q + dq, midR = node.r + dr;
const landQ = node.q + 2 * dq, landR = node.r + 2 * dr;
if (!isOnBoard(landQ, landR)) continue;
const midKey = cellKey(midQ, midR);
const landKey = cellKey(landQ, landR);
if (!occ.has(midKey)) continue; // need a peg to jump over
if (occ.has(landKey)) continue; // landing must be empty
if (visited.has(landKey)) continue; // avoid loops
visited.add(landKey);
const newPath = [...node.path, { q: landQ, r: landR }];
if (isLegalRest(landQ, landR)) {
moves.push({
color, pegIdx,
q: landQ, r: landR,
isJump: true,
path: newPath,
});
}
// Continue BFS even if this landing can't be a rest — chain may exit
// back into legal territory.
queue.push({ q: landQ, r: landR, path: newPath });
}
}
return moves;
}
export function getAllValidMoves(state, color = currentColor(state)) {
const out = [];
for (let i = 0; i < PEGS_PER_PLAYER; i++) {
for (const m of getMovesForPeg(state, color, i)) out.push(m);
}
return out;
}
export function hasAnyMove(state, color = currentColor(state)) {
for (let i = 0; i < PEGS_PER_PLAYER; i++) {
if (getMovesForPeg(state, color, i).length > 0) return true;
}
return false; return false;
} }
// ── Move application ─────────────────────────────────────────────────────── // Moves for one peg given a precomputed occupancy array (fast path for the AI).
// `occ` must include the moving peg; it is treated as vacated during the move.
export function applyMove(state, move) { export function pegMoves(color, pegIdx, from, hasLeft, occ, out = []) {
const s = cloneState(state); const target = TARGET[color];
const peg = s.pegs[move.color][move.pegIdx]; const inTarget = CELLS[from].tri === target;
peg.q = move.q; for (let d = 0; d < 6; d++) {
peg.r = move.r; const n = NEIGH[from * 6 + d];
if (n < 0 || occ[n]) continue;
if (triangleAt(peg.q, peg.r) !== COLOR_HOME[move.color]) { if (!canRest(color, inTarget, hasLeft, n)) continue;
s.leftHome[move.color][move.pegIdx] = true; out.push({ color, pegIdx, from, to: n, isJump: false, path: [from, n] });
} }
s.lastMove = { // jump chains: BFS from `from`, the start counts as empty
color: move.color, const saved = occ[from];
pegIdx: move.pegIdx, occ[from] = 0;
path: move.path.map((p) => ({ q: p.q, r: p.r })), const seen = new Uint8Array(NUM_CELLS);
}; seen[from] = 1;
const queue = [[from]];
if (isColorFinished(s, move.color) && !s.finishedOrder.includes(move.color)) { for (let qi = 0; qi < queue.length; qi++) {
s.finishedOrder.push(move.color); const path = queue[qi];
if (s.winner === null) s.winner = move.color; const at = path[path.length - 1];
for (let d = 0; d < 6; d++) {
const land = JUMP[at * 6 + d];
if (land < 0 || seen[land]) continue;
const mid = NEIGH[at * 6 + d];
if (!occ[mid] || occ[land]) continue;
seen[land] = 1;
const np = path.concat(land);
if (canRest(color, inTarget, hasLeft, land)) out.push({ color, pegIdx, from, to: land, isJump: true, path: np });
queue.push(np);
}
} }
occ[from] = saved;
if (s.finishedOrder.length >= s.seatColors.length - 1) { return out;
s.phase = 'game_over';
return s;
}
// Advance turn, skipping any seats that have already finished.
do {
s.currentSeat = (s.currentSeat + 1) % s.seatColors.length;
} while (s.finishedOrder.includes(s.seatColors[s.currentSeat]));
return s;
} }
export function isColorFinished(state, color) { export function getMovesForPeg(s, color, pegIdx, occ = occupancy(s)) {
const target = COLOR_TARGET[color]; if (s.phase !== 'play' || !isActive(s, color)) return [];
return state.pegs[color].every((p) => triangleAt(p.q, p.r) === target); return pegMoves(color, pegIdx, s.pegs[color][pegIdx], s.left[color][pegIdx], occ);
}
export function getAllValidMoves(s, color = currentColor(s)) {
if (s.phase !== 'play' || !isActive(s, color)) return [];
const occ = occupancy(s);
const out = [];
for (let i = 0; i < PEGS; i++) pegMoves(color, i, s.pegs[color][i], s.left[color][i], occ, out);
return out;
}
export function hasAnyMove(s, color = currentColor(s)) {
return getAllValidMoves(s, color).length > 0;
}
// ── Finishing ───────────────────────────────────────────────────────────────
// `occ` optional. Strict: all ten pegs in the target. antiBlock: every target
// hole taken and at least one by you.
export function targetFilled(s, color, occ = occupancy(s)) {
const cells = TRI_CELLS[TARGET[color]];
const me = s.seats.indexOf(color) + 1;
let mine = 0;
for (const id of cells) {
if (!occ[id]) return false;
if (occ[id] === me) mine++;
}
if (mine === PEGS) return true;
return !!s.opts.antiBlock && mine > 0;
}
export const pegsHome = (s, c) => s.pegs[c].filter((id) => CELLS[id].tri === TARGET[c]).length;
export const totalRows = (s, c) => s.pegs[c].reduce((a, id) => a + rowsLeft(c, id), 0);
// Rows still to travel above the ideal finish (0 = done).
export const rowsToGo = (s, c) => Math.max(0, totalRows(s, c) - MIN_ROWS);
// ── Applying moves ──────────────────────────────────────────────────────────
function advance(s) {
const n = s.seats.length;
for (let k = 0; k < n; k++) {
s.current = (s.current + 1) % n;
if (isActive(s, s.seats[s.current])) return;
}
}
// A marble is boxed in for good when every neighbour is off the board or a
// finished player's marble (those never move again) and every jump over
// those lands off the board or on another finished marble. A player with
// such a marble outside their target can never finish.
function permanentlyTrapped(fixed, id) {
for (let d = 0; d < 6; d++) {
const n = NEIGH[id * 6 + d];
if (n < 0) continue;
if (!fixed[n]) return false;
const j = JUMP[id * 6 + d];
if (j >= 0 && !fixed[j]) return false;
}
return true;
}
function markStuck(s) {
if (!s.finished.length) return;
const fixed = new Uint8Array(NUM_CELLS);
for (const c of s.finished) for (const id of s.pegs[c]) fixed[id] = 1;
for (const c of s.seats) {
if (!isActive(s, c)) continue;
const t = TARGET[c];
if (s.pegs[c].some((id) => CELLS[id].tri !== t && permanentlyTrapped(fixed, id))) {
s.stuck.push(c);
s.newlyStuck.push(c);
}
}
}
function checkEnd(s) {
const n = s.seats.length;
if (s.teams) {
const done = s.teams.find((t) => t.every((c) => isFinished(s, c)));
if (done) { s.phase = 'game_over'; s.winningTeam = [...done]; s.endReason = 'team'; return true; }
// no pair can complete any more (a partner is boxed in)
if (!s.teams.some((t) => t.every((c) => !isStuck(s, c)))) { endByRows(s, 'boxed'); return true; }
}
if (s.finished.length >= n - 1) {
const last = s.seats.find((c) => !isFinished(s, c));
if (last && !s.teams) s.finished.push(last);
s.phase = 'game_over';
s.endReason = 'finished';
return true;
}
// everyone left but (at most) one is boxed in: the placings are settled
if (!s.teams && s.seats.filter((c) => isActive(s, c)).length <= 1 && s.stuck.length) { endByRows(s, 'boxed'); return true; }
return false;
}
export function applyMove(state, m) {
const s = cloneState(state);
const c = m.color;
s.pegs[c][m.pegIdx] = m.to;
if (CELLS[m.to].tri !== HOME[c]) s.left[c][m.pegIdx] = true;
const st = s.stats[c];
const hops = m.isJump ? m.path.length - 1 : 0;
st.moves++;
if (m.isJump) { st.jumps++; st.hops += hops; st.longest = Math.max(st.longest, hops); } else st.steps++;
s.lastMoves.push({ color: c, pegIdx: m.pegIdx, from: m.from, to: m.to, isJump: m.isJump, path: m.path.slice(), turn: s.turn });
if (s.lastMoves.length > s.seats.length) s.lastMoves.shift();
s.turn++;
s.passStreak = 0;
s.lastEvent = null;
if (!isFinished(s, c) && targetFilled(s, c)) {
s.finished.push(c);
if (!s.winner) s.winner = c;
s.lastEvent = { type: 'finished', color: c, place: s.finished.length };
}
markStuck(s);
if (checkEnd(s)) return s;
if (s.turn >= TURN_CAP * s.seats.length) return endByRows(s, 'cap');
// A spoiler deadlock (strict rules: a marble that never leaves home sits in
// someone's target and gets boxed in) still lets players shuffle, so passes
// never pile up. If nobody has made new progress for many rounds, stop.
const total = s.seats.reduce((a, col) => a + rowsToGo(s, col), 0);
if (total < s.bestTotal) { s.bestTotal = total; s.stall = 0; }
else if (++s.stall >= STALL_ROUNDS * Math.max(1, s.seats.filter((col) => isActive(s, col)).length)) return endByRows(s, 'stalemate');
advance(s);
return s;
} }
export function passTurn(state) { export function passTurn(state) {
// Used when a player has zero legal moves (extremely rare in CC).
const s = cloneState(state); const s = cloneState(state);
if (s.phase !== 'play') return s; if (s.phase !== 'play') return s;
do { s.stats[currentColor(s)].passes++;
s.currentSeat = (s.currentSeat + 1) % s.seatColors.length; s.turn++;
} while (s.finishedOrder.includes(s.seatColors[s.currentSeat])); s.passStreak++;
s.lastEvent = { type: 'pass', color: currentColor(s) };
const active = s.seats.filter((c) => isActive(s, c)).length;
if (s.passStreak >= active) return endByRows(s, 'stalemate');
if (++s.stall >= STALL_ROUNDS * active) return endByRows(s, 'stalemate');
if (s.turn >= TURN_CAP * s.seats.length) return endByRows(s, 'cap');
advance(s);
return s; return s;
} }
// End early: everyone unfinished is ranked by rows still to travel — those
// still able to finish ahead of those boxed in.
function endByRows(s, reason) {
const rest = s.seats.filter((c) => !isFinished(s, c))
.sort((a, b) => (isStuck(s, a) - isStuck(s, b)) || (rowsToGo(s, a) - rowsToGo(s, b)));
if (!s.winner && rest.length) s.winner = rest[0];
s.finished.push(...rest);
s.phase = 'game_over';
s.endReason = reason;
return s;
}
// Final ranking: finishing order (finishers, then by rows to go). With teams,
// the winning pair comes first.
export function rankings(s) {
const order = [...s.finished];
const rest = s.seats.filter((c) => !order.includes(c))
.sort((a, b) => (isStuck(s, a) - isStuck(s, b)) || (rowsToGo(s, a) - rowsToGo(s, b)));
const all = [...order, ...rest];
if (s.winningTeam) return [...s.winningTeam.slice().sort((a, b) => all.indexOf(a) - all.indexOf(b)), ...all.filter((c) => !s.winningTeam.includes(c))];
return all;
}
// Team standings: pairs ordered by (both finished first, then combined rows).
export function teamRankings(s) {
if (!s.teams) return null;
const score = (t) => (s.winningTeam && t.includes(s.winningTeam[0]) ? -1e6 : 0)
- t.filter((c) => isFinished(s, c)).length * 1000 + t.reduce((a, c) => a + rowsToGo(s, c), 0);
return s.teams.map((t) => [...t]).sort((a, b) => score(a) - score(b));
}
// Rows gained by a move for its colour (positive = forward).
export const moveGain = (m) => rowsLeft(m.color, m.from) - rowsLeft(m.color, m.to);
export const moveHops = (m) => (m.isJump ? m.path.length - 1 : 0);
export const sameMove = (a, b) => a && b && a.color === b.color && a.pegIdx === b.pegIdx && a.to === b.to;

View File

@ -0,0 +1,153 @@
// ChineseCheckersMarbles.js — the marbles as persistent sprites (shadow, body,
// specular glint — plain Images, no Containers, so depth works) and the hop
// animator.
//
// A marble's identity is (colour, peg index) in the state, so sync() never
// reassigns sprites: it just slides any marble whose cell changed.
import { CELL_XY, MARBLE_R } from './ChineseCheckersLayout.js';
import { RES } from './ChineseCheckersArt.js';
import { clack } from './ChineseCheckersSound.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);
const BASE = 1 / RES;
export class MarbleSet {
constructor(scene, seats, depth, { symbols = false } = {}) {
this.scene = scene;
this.seats = seats;
this.depth = depth;
this.symbols = symbols;
this.items = {};
}
build(state) {
const s = this.scene;
for (const c of this.seats) {
this.items[c] = state.pegs[c].map((id, i) => {
const shadow = s.add.image(0, 0, 'cc-shadow').setScale(BASE).setAlpha(0.8);
const body = s.add.image(0, 0, this.tex(c)).setScale(BASE).setRotation(Math.random() * Math.PI * 2);
const spec = s.add.image(0, 0, 'cc-spec').setScale(BASE);
const it = { color: c, idx: i, cell: id, body, shadow, spec, x: 0, y: 0, h: 0, sx: 1, sy: 1, flying: false, busy: false };
const p = CELL_XY[id];
this.place(it, p.x, p.y, 0);
return it;
});
}
return this;
}
tex(c) { return this.symbols ? `cc-ms-${c}` : `cc-m-${c}`; }
setSymbols(on) {
this.symbols = !!on;
for (const it of this.all()) it.body.setTexture(this.tex(it.color));
}
get(c, i) { return this.items[c][i]; }
all() { return this.seats.flatMap((c) => this.items[c]); }
// h = height above the board (px); sx/sy = squash.
place(it, x, y, h = 0, sx = 1, sy = 1) {
it.x = x; it.y = y; it.h = h; it.sx = sx; it.sy = sy;
const lift = 1 + h / 260;
const dy = (1 - sy) * MARBLE_R; // squash stays grounded
it.body.setPosition(x, y - h + dy).setScale(BASE * lift * sx, BASE * lift * sy);
it.spec.setPosition(x, y - h + dy).setScale(BASE * lift * sx, BASE * lift * sy);
it.shadow.setPosition(x + 3 + h * 0.22, y + 4 + h * 0.3).setScale(BASE * (1 + h / 90) * sx, BASE * (1 + h / 90) * 0.92)
.setAlpha(Math.max(0.2, 0.8 - h / 110));
const d = it.flying ? this.depth + 20 : this.depth + y * 0.0005;
it.shadow.setDepth(it.flying ? this.depth + 19 : this.depth - 1);
it.body.setDepth(d); it.spec.setDepth(d + 0.0001);
}
sync(state, { dur = 0 } = {}) {
const jobs = [];
for (const c of this.seats) {
this.items[c].forEach((it, i) => {
const id = state.pegs[c][i];
it.cell = id;
const p = CELL_XY[id];
if (Math.abs(it.x - p.x) < 0.5 && Math.abs(it.y - p.y) < 0.5 && it.h === 0) return;
if (dur <= 0 || it.busy) { this.place(it, p.x, p.y, 0); return; }
jobs.push(this.arc(it, p, dur, 10));
});
}
return Promise.all(jobs);
}
arc(it, to, dur, height = 30, { roll = 0 } = {}) {
const from = { x: it.x, y: it.y, h: it.h };
const p = { t: 0 };
it.flying = true;
return new Promise((res) => {
this.scene.tweens.add({
targets: p, t: 1, duration: Math.max(1, dur), ease: 'Linear',
onUpdate: () => {
const k = easeInOut(p.t);
const h = lerp(from.h, 0, k) + Math.sin(Math.PI * p.t) * height;
// a touch of stretch while airborne
const st = 1 + Math.sin(Math.PI * p.t) * Math.min(0.08, height / 600);
this.place(it, lerp(from.x, to.x, k), lerp(from.y, to.y, k), h, 1 / st, st);
if (roll) it.body.rotation += roll / 30;
},
onComplete: () => { it.flying = false; this.place(it, to.x, to.y, 0); res(); },
});
});
}
// A quick squash-and-settle on landing.
squash(it, amt = 0.16, dur = 150) {
const p = { t: 0 };
return new Promise((res) => {
this.scene.tweens.add({
targets: p, t: 1, duration: dur, ease: 'Linear',
onUpdate: () => {
const w = Math.sin(Math.PI * p.t) * (1 - p.t * 0.4);
const s = 1 - amt * w;
this.place(it, it.x, it.y, 0, 1 + (1 - s) * 0.8, s);
},
onComplete: () => { this.place(it, it.x, it.y, 0); res(); },
});
});
}
// Hop along a move's path (cell ids). onHop(k, cellId) fires on each landing.
async hopAlong(move, { per = 230, fast = false, onHop } = {}) {
const it = this.get(move.color, move.pegIdx);
it.busy = true;
const path = move.path;
for (let k = 1; k < path.length; k++) {
const to = CELL_XY[path[k]];
const height = move.isJump ? 46 : 14;
const dur = fast ? Math.min(per, 90) : (move.isJump ? per : per * 0.85);
await this.arc(it, to, dur, height, { roll: move.isJump ? 0.25 : 0.1 });
clack(this.scene, { k: k - 1, jump: move.isJump });
onHop?.(k, path[k]);
if (!fast) await this.squash(it, move.isJump ? 0.14 : 0.08, k === path.length - 1 ? 160 : 80);
}
it.cell = path[path.length - 1];
it.busy = false;
}
setLifted(it, on) {
if (!it) return;
if (on) { it.flying = true; this.place(it, it.x, it.y, 12); }
else { it.flying = false; const p = CELL_XY[it.cell]; this.place(it, p.x, p.y, 0); }
}
// Follow the pointer while dragging (lifted high, centre under the cursor).
dragTo(it, x, y) { it.flying = true; this.place(it, x, y + 18, 18); }
// The marble of `color` nearest (x, y) within r.
pick(color, x, y, r = 26) {
let best = null, bd = r;
for (const it of this.items[color] ?? []) {
const d = Math.hypot(it.x - x, it.y - it.h - y);
if (d < bd) { bd = d; best = it; }
}
return best;
}
setVisible(on) { for (const it of this.all()) { it.body.setVisible(on); it.spec.setVisible(on); it.shadow.setVisible(on); } }
}

View File

@ -0,0 +1,140 @@
// ChineseCheckersSound.js — tiny Web Audio synths for the tea pavilion. No
// audio files; silent without Web Audio or when muted.
//
// clack(scene, { k, jump }) a glass marble landing in a wooden hole; chain
// landings walk up a pentatonic scale (k = hop no.)
// tap(scene) picking a marble up
// deny(scene) that marble can't move
// chime(scene) a point filled (small bronze bell chord)
// gong(scene) the game is decided
// sparkle(scene) a marble reaches its target
// WindChimes a soft ambient chime now and then
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.2), ac.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ac, buf);
return buf;
}
function out(scene, ac, gain) {
const sm = scene.sound;
const node = sm.masterVolumeNode ?? sm.destination ?? null;
const g = ac.createGain();
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
g.connect(node ?? ac.destination);
return g;
}
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003 } = {}) {
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 + attack);
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, d = 0.03) {
const n = ac.createBufferSource(); n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = f; bp.Q.value = 3;
const g = ac.createGain(); g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + d);
n.connect(bp); bp.connect(g); g.connect(dest); n.start(t0, Math.random()); n.stop(t0 + d + 0.02);
}
const safe = (fn) => { try { fn(); } catch (_) { /* audio is decoration */ } };
// Major pentatonic steps (semitones) for chain landings.
const PENTA = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24, 26, 28, 31, 33, 36];
const semi = (f, n) => f * Math.pow(2, n / 12);
export function clack(scene, { k = 0, jump = false, vol = 0.09 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
// the wood thock
tone(ac, dest, t, 190, { type: 'sine', a: 0.7, d: 0.07, glide: 0.6 });
tick(ac, dest, t, 2600, 0.6);
// the glass ring — musical on chains
const f = jump ? semi(784, PENTA[Math.min(k, PENTA.length - 1)]) : 1900;
tone(ac, dest, t + 0.002, f, { type: 'triangle', a: jump ? 0.45 : 0.25, d: jump ? 0.22 : 0.06 });
if (jump) tone(ac, dest, t + 0.002, f * 2.01, { a: 0.12, d: 0.14 });
});
}
export function tap(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.05), t = ac.currentTime + 0.003;
tick(ac, dest, t, 4200, 0.7, 0.02);
tone(ac, dest, t, 2400, { type: 'triangle', a: 0.3, d: 0.05 });
});
}
export function deny(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.08), t = ac.currentTime + 0.003;
tone(ac, dest, t, 160, { a: 0.8, d: 0.12, glide: 0.7 });
tick(ac, dest, t, 900, 0.5);
});
}
export function sparkle(scene, { vol = 0.05 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
[0, 4, 7, 12].forEach((n, i) => tone(ac, dest, t + i * 0.05, semi(1568, n), { a: 0.6, d: 0.5 }));
});
}
export function chime(scene, { vol = 0.08 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
// a small bronze bell: inharmonic partials
for (const [m, a, d, dt] of [[1, 1, 2.2, 0], [2.76, 0.5, 1.4, 0], [5.4, 0.25, 0.8, 0], [1.5, 0.6, 1.8, 0.18], [4.1, 0.2, 0.7, 0.18]]) {
tone(ac, dest, t + dt, 523 * m, { a, d });
}
});
}
export function gong(scene, { vol = 0.18 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.01;
for (const [f, a, d] of [[98, 1, 3.4], [147.5, 0.5, 2.8], [216, 0.35, 2.2], [302, 0.2, 1.6]]) {
tone(ac, dest, t, f, { a, d, attack: 0.02, glide: 0.985 });
}
tick(ac, dest, t, 600, 0.6, 0.12);
});
}
export class WindChimes {
constructor(scene) { this.scene = scene; this.timer = null; }
start() {
if (this.timer) return;
const ring = () => {
this.timer = setTimeout(ring, 5000 + Math.random() * 7000);
const ac = ctxOf(this.scene); if (!ac) return;
safe(() => {
const dest = out(this.scene, ac, 0.022), t = ac.currentTime + 0.02;
const notes = [0, 2, 4, 7, 9, 12, 14];
const n = 2 + Math.floor(Math.random() * 3);
for (let i = 0; i < n; i++) {
const f = semi(1046, notes[Math.floor(Math.random() * notes.length)]);
tone(ac, dest, t + i * (0.12 + Math.random() * 0.25), f, { a: 0.8, d: 2.4, attack: 0.004 });
}
});
};
this.timer = setTimeout(ring, 2500);
}
stop() { clearTimeout(this.timer); this.timer = null; }
setOn(on) { if (on) this.start(); else this.stop(); }
}

View File

@ -18,6 +18,20 @@ The first warrior to fill their target triangle completely claims victory. But t
In my day we crossed mountains to reach the enemy's gate. Here, you cross a star. The principle is the same. In my day we crossed mountains to reach the enemy's gate. Here, you cross a star. The principle is the same.
## Gathering at the Table
Two, three, four or six may sit at this table. You always take the southern point, nearest the teapot. Where the others sit is not chance. It is tradition:
| Players | Who sits where |
|---|---|
| **2** | You and one rival, at opposite points. A pure duel. |
| **3** | Every other point. Your targets are all empty, so no one starts in your way. |
| **4** | Two pairs facing each other across the star. |
| **5** | The full star with one point left empty. |
| **6** | Every point taken. A crowded, glorious mess. |
Turns pass **clockwise** from you.
## The Battlefield ## The Battlefield
The board is a **six-pointed star** of 121 holes: a wide central hexagon ringed by six triangular points. Each point is the home of one color. The board is a **six-pointed star** of 121 holes: a wide central hexagon ringed by six triangular points. Each point is the home of one color.
@ -55,6 +69,28 @@ A warrior who ignores the rules of engagement brings shame upon the dojo. Three
3. **Once a peg enters your own target triangle, it may only move within the target.** Having arrived at the gate, it does not wander back into the field. It settles, and holds the ground. 3. **Once a peg enters your own target triangle, it may only move within the target.** Having arrived at the gate, it does not wander back into the field. It settles, and holds the ground.
## The Spoiler's Shame (Anti-Blocking)
*Frowns.* There is a dishonorable trick. A warrior leaves one peg sitting in their home forever. That home is *your* target, so you can never fill it.
The pavilion does not allow this. With **anti-blocking** on (the house default), your target counts as filled once every hole in it is taken and at least one holds your peg. The spoiler's peg counts for you.
And the spoiler pays. A peg that stays home too long gets walled in by the arriving pegs. Once a finished army has sealed it in, it can never move again. That warrior is **boxed in for good**. They cannot finish, their turns are skipped, and they place behind everyone still racing. If you see a peg still lingering in your home point, the board will warn you. Get it out early.
You may turn anti-blocking off in the menu if you prefer the strict old way. Be warned: then the board itself can lock up. If no one makes any progress for many rounds, the game ends and places are judged by the rows each army still has to travel.
## Sworn Brothers (Partner Teams)
With all six seats filled, you may choose **partner teams** from the menu. Opposite points become allies: you and the warrior across the star from you. Each of you marches into the other's home. Your partnership wins when *both* of you are home. Help your partner, and use their pegs as your ladders.
## Reading the Board
- **Click a marble or drag it.** The holes it can reach glow. Gold holes gain the most ground, jade holes gain a little, and pale holes go sideways.
- **Hover a glowing hole** to see the marble's whole jump route, every hop numbered, and how many rows it gains.
- **Fading trails** show each player's most recent move, so you can see what your rivals just did.
- **Hint (H)** shows the move a skill-5 master would play. **Undo (Z)** takes back your last move.
- A seat's plaque shows how many of its ten marbles are home. A medal appears when that seat finishes.
## Strategy From a Warrior Who Has Walked Many Roads ## Strategy From a Warrior Who Has Walked Many Roads
**1. Build ladders, do not waste steps.** **1. Build ladders, do not waste steps.**
@ -78,7 +114,7 @@ Skill 1–2 warriors advance like restless conscripts — eager, but blind to th
Skill 3–4 warriors march with purpose, seek their jump chains, and contest the center. Treat them with respect. Skill 3–4 warriors march with purpose, seek their jump chains, and contest the center. Treat them with respect.
Skill 5 warriors are old samurai like myself — they read the board many moves deep, build chains you did not see coming, and exploit your own pegs as bridges. Against these, every careless step is punished. Earn your victory. Skill 5 warriors are old samurai like myself. They read three of their own moves deep and build chains you did not see coming. They also refuse to leave the next player a highway, so expect your favourite ladders to be blocked. Against these, every careless step is punished. Earn your victory.
--- ---

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', 'parchisi', 'mexicantrain'].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', 'mexicantrain', 'chinesecheckers'].includes(this.gameDef.slug)) {
bio.style.webkitLineClamp = '1'; bio.style.webkitLineClamp = '1';
const skillRow = document.createElement('div'); const skillRow = document.createElement('div');

View File

@ -35,6 +35,7 @@ export const GAME_SOUNDTRACK_OVERRIDES = {
spireclimb: 'adventure', spireclimb: 'adventure',
mahjong: 'chinese', mahjong: 'chinese',
mahjongmatch: 'chinese', mahjongmatch: 'chinese',
chinesecheckers: 'chinese',
zuma: 'zuma', zuma: 'zuma',
mastervega: 'masterofvega', mastervega: 'masterofvega',
}; };

View File

@ -0,0 +1,422 @@
#!/usr/bin/env node
// verifyChineseCheckers.js — headless checks for Chinese Checkers ("Moonlit
// Tea Pavilion"):
// • topology: 121 holes, six 10-hole points, neighbour / jump tables, the
// rows-to-travel metric
// • seatings for 2–6 players (opposite / alternating / pairs)
// • rules on hand-built positions: steps, multi-hop chains (path
// continuity), passing through forbidden points, no re-entering home,
// target pegs stay in the target, strict vs anti-blocking finishes, turn
// order skipping finishers, game end, partner teams, boxed-in players,
// stalemate passes and the no-progress detector
// • AI: every skill returns a legal move, takes a finishing move, null
// when boxed in
// • self-play soak at every player count (and teams / no anti-block):
// games finish, no two marbles share a hole, nobody rests where they
// mayn't, home flags never un-set
// • skill ladder (mirrored seats, two players)
// • layout: plaques, cards and buttons on screen, clear of each other and
// of the board
// Usage: node tools/verifyChineseCheckers.js [--quick]
import * as L from '../src/games/chinesecheckers/ChineseCheckersLogic.js';
import * as AI from '../src/games/chinesecheckers/ChineseCheckersAI.js';
import * as Lay from '../src/games/chinesecheckers/ChineseCheckersLayout.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 id = (q, r) => { const v = L.cellId(q, r); if (v < 0) throw new Error(`no cell ${q},${r}`); return v; };
AI.SKILL[5].budgetMs = 0;
// A position: pegs given per colour (cell ids, padded from an unused pool far
// from the action when fewer than 10 are listed).
function pos(seats, pegs, { current = 0, left = null, opts = {} } = {}) {
const s = L.createInitialState(seats, opts);
const used = new Set(Object.values(pegs).flat());
for (const c of seats) {
if (pegs[c]) {
const list = pegs[c].slice();
// pad with home cells not otherwise used
for (const h of L.TRI_CELLS[L.HOME[c]]) if (list.length < L.PEGS && !used.has(h)) { list.push(h); used.add(h); }
s.pegs[c] = list;
}
for (const h of s.pegs[c]) used.add(h);
}
if (left) for (const [c, arr] of Object.entries(left)) s.left[c] = arr.slice();
s.current = current;
return s;
}
const dests = (s, c, i) => L.getMovesForPeg(s, c, i).map((m) => m.to).sort((a, b) => a - b);
// ── topology ────────────────────────────────────────────────────────────────
section('Topology');
{
ok('121 holes', L.NUM_CELLS === 121);
const byTri = {};
for (const c of L.CELLS) byTri[c.tri] = (byTri[c.tri] ?? 0) + 1;
ok('61 centre holes', byTri.center === 61);
ok('six points of ten', Object.keys(L.TRIANGLES).every((t) => byTri[t] === 10));
let sym = true, jumps = true;
for (let a = 0; a < L.NUM_CELLS; a++) {
for (let d = 0; d < 6; d++) {
const b = L.NEIGH[a * 6 + d];
if (b >= 0 && L.NEIGH[b * 6 + ((d + 3) % 6)] !== a) sym = false;
const j = L.JUMP[a * 6 + d];
if (j >= 0 && (b < 0 || L.NEIGH[b * 6 + d] !== j)) jumps = false;
}
}
ok('neighbour table symmetric', sym);
ok('jump = neighbour of neighbour, same direction', jumps);
for (const t of Object.keys(L.TRIANGLES)) {
const tip = L.TRI_CELLS[t][9];
ok(`${t}: tip is row 0`, L.ROWS[t][tip] === 0);
}
ok('ideal finish totals 20 rows', L.MIN_ROWS === 20);
const s = L.createInitialState(L.seatColors(6));
ok('every colour starts 120 rows above the ideal', s.seats.every((c) => L.rowsToGo(s, c) === 120));
ok('far tip is 16 rows', L.rowsLeft('blue', L.TRI_CELLS['r+'][9]) === 16);
ok('lateral 0 on the centre line', L.LATERAL['r-'][id(0, 0)] === 0 && L.LATERAL['r-'][id(2, -4)] === 0);
}
// ── seatings ────────────────────────────────────────────────────────────────
section('Seatings');
{
ok('2 → opposite points', L.seatColors(2).join() === 'blue,red' && L.OPPOSITE.blue === 'red');
const three = L.seatColors(3);
ok('3 → alternating, every target empty', three.every((c) => !three.includes(L.OWNER[L.TARGET[c]])));
const four = L.seatColors(4);
ok('4 → two opposite pairs', four.every((c) => four.includes(L.OPPOSITE[c])));
ok('5 → six-star minus one', L.seatColors(5).length === 5 && !L.seatColors(5).includes('green'));
ok('6 → all', L.seatColors(6).length === 6);
ok('human always seat 0 (south)', [2, 3, 4, 5, 6].every((n) => L.seatColors(n)[0] === L.HUMAN && L.HOME[L.HUMAN] === 'r+'));
ok('clamps', L.seatColors(1).length === 2 && L.seatColors(9).length === 6);
ok('teams only with six', L.createInitialState(L.seatColors(4), { teams: true }).teams === null);
const t6 = L.createInitialState(L.seatColors(6), { teams: true });
ok('six → three opposite pairs', t6.teams.length === 3 && t6.teams.every(([a, b]) => L.OPPOSITE[a] === b));
ok('partnerOf', L.partnerOf(t6, 'blue') === 'red' && L.partnerOf(L.createInitialState(L.seatColors(6)), 'blue') === null);
let threw = false;
try { L.createInitialState(['blue']); } catch (_) { threw = true; }
ok('rejects one seat', threw);
}
// ── rules ───────────────────────────────────────────────────────────────────
section('Rules');
{
const seats = L.seatColors(2);
// opening: only the front row and jumps over it move
const s0 = L.createInitialState(seats);
const opening = L.getAllValidMoves(s0, 'blue');
ok('opening has moves', opening.length > 0);
ok('opening: every move lands in the centre', opening.every((m) => L.CELLS[m.to].tri === 'center'));
ok('opening: back-row marbles can jump out', opening.some((m) => m.isJump));
// a three-hop ladder through the centre
const a = id(0, 2);
const s1 = pos(seats, { blue: [a, id(0, 1), id(0, -1), id(0, -3)], red: [] });
const m1 = L.getMovesForPeg(s1, 'blue', 0);
const far = m1.find((m) => m.to === id(0, -4));
ok('chain: 3-hop ladder reaches (0,-4)', !!far && far.path.length === 4, JSON.stringify(m1.map((m) => m.to)));
let cont = true;
for (const m of m1.filter((x) => x.isJump)) {
for (let k = 1; k < m.path.length; k++) {
const p = L.CELLS[m.path[k - 1]], q = L.CELLS[m.path[k]];
const mid = L.cellId((p.q + q.q) / 2, (p.r + q.r) / 2);
if (L.hexDistance(m.path[k - 1], m.path[k]) !== 2 || !s1.pegs.blue.includes(mid)) cont = false;
}
}
ok('chain paths hop over a marble every time', cont);
ok('no duplicate landings', new Set(m1.map((m) => m.to)).size === m1.length);
ok('steps listed', m1.filter((m) => !m.isJump).every((m) => L.hexDistance(m.from, m.to) === 1));
// passing through a forbidden point (q+ = yellow home, empty in 2p)
// peg at (4,-1) jumps over (5,-2)… → (6,-3) is in q+ (forbidden rest), then back out over (5,-3)? build:
const p0 = id(3, 0), over1 = id(4, -1), land1 = id(5, -2); // land1 in q+
const over2 = id(4, -2), land2 = id(3, -2); // back into centre
const s2 = pos(seats, { blue: [p0, over1, over2], red: [] });
const m2 = L.getMovesForPeg(s2, 'blue', 0).map((m) => m.to);
ok('may not rest in a foreign point', L.CELLS[land1].tri === 'q+' && !m2.includes(land1));
ok('may pass through it mid-chain', m2.includes(land2), JSON.stringify(m2));
// no re-entering home once left: a marble just outside the front row
const homeCell = L.TRI_CELLS['r+'][0]; // (-1,5)
const s3 = L.createInitialState(seats);
s3.pegs.blue[0] = id(-1, 4); // stepped out
ok('home cell free for the test', !s3.pegs.blue.includes(homeCell));
s3.left.blue[0] = true;
ok('left home: can\'t step back in', !dests(s3, 'blue', 0).includes(homeCell));
s3.left.blue[0] = false;
ok('never left: may step back in', dests(s3, 'blue', 0).includes(homeCell));
const s3b = L.applyMove(s3, L.getMovesForPeg(s3, 'blue', 0).find((m) => L.CELLS[m.to].tri === 'center'));
ok('applyMove marks home as left', s3b.left.blue[0] === true);
// inside the target only target moves (red has cleared out of the way)
const tgtCell = L.TRI_CELLS['r-'][0]; // (1,-5) base row
const s4 = L.createInitialState(seats);
s4.pegs.blue = [tgtCell, id(0, 0), id(1, 0), id(2, 0), id(-1, 0), id(-2, 0), id(0, 1), id(0, 2), id(1, 1), id(2, 1)];
s4.pegs.red = [id(-3, 3), id(-2, 3), id(-1, 3), id(-3, 2), id(-2, 2), id(-1, 2), id(-4, 3), id(-4, 2), id(-4, 4), id(-3, 4)];
s4.left.blue = Array(10).fill(true);
s4.left.red = Array(10).fill(true);
const d4 = L.getMovesForPeg(s4, 'blue', 0);
ok('target marble only moves within the target', d4.length > 0 && d4.every((m) => L.CELLS[m.to].tri === 'r-'), JSON.stringify(d4.map((m) => L.CELLS[m.to].tri)));
}
// ── finishing ───────────────────────────────────────────────────────────────
section('Finishing');
{
const seats = L.seatColors(2);
const tgt = L.TRI_CELLS['r-'];
// nine in the target, the tenth one step from the last hole
const last = tgt[1]; // (2,-5)
const start = id(2, -4);
const pegs = { blue: [...tgt.filter((t) => t !== last), start], red: [id(0, 0), id(1, 0), id(2, 0), id(3, 0), id(-1, 0), id(-2, 0), id(-3, 0), id(0, 1), id(1, 1), id(-1, 1)] };
const s = pos(seats, pegs, { left: { blue: Array(10).fill(true) } });
const win = L.getMovesForPeg(s, 'blue', 9).find((m) => m.to === last);
ok('finishing step exists', !!win);
const s2 = L.applyMove(s, win);
ok('strict fill finishes', L.isFinished(s2, 'blue') && s2.winner === 'blue' && s2.lastEvent?.type === 'finished');
ok('2 players: game over at the first finisher', s2.phase === 'game_over' && s2.finished.join() === 'blue,red' && s2.endReason === 'finished');
ok('AI takes the finishing move', L.sameMove(AI.chooseMove(s, 5), win) && L.sameMove(AI.chooseMove(s, 3), win));
// anti-blocking: one red marble never left its home (= blue's target)
const blocker = tgt[9];
const sb = (antiBlock) => {
const st = pos(seats, {
blue: [...tgt.filter((t) => t !== blocker && t !== last), start, id(0, 0)],
red: [blocker, id(-3, 3), id(-2, 3), id(-1, 3), id(-3, 2), id(-2, 2), id(-1, 2), id(-4, 3), id(-4, 2), id(-4, 4)],
}, { opts: { antiBlock }, left: { blue: Array(10).fill(true) } });
return L.applyMove(st, L.getMovesForPeg(st, 'blue', 8).find((m) => m.to === last));
};
ok('anti-block: 9 + a blocker counts as filled', L.isFinished(sb(true), 'blue'));
ok('strict: a blocker spoils the fill', !L.isFinished(sb(false), 'blue'));
// four players: finishers skipped, game ends when three are home
const s4 = L.createInitialState(L.seatColors(4));
s4.finished = ['orange', 'red'];
s4.current = 0;
const m = L.getAllValidMoves(s4, 'blue')[0];
const after = L.applyMove(s4, m);
ok('turn order skips finished seats', L.currentColor(after) === 'yellow');
const s5 = L.createInitialState(L.seatColors(4));
s5.finished = ['orange', 'red'];
s5.pegs.blue = [...L.TRI_CELLS['r-'].filter((x) => x !== id(2, -5)), id(2, -4)];
s5.left.blue = Array(10).fill(true);
s5.pegs.red = L.TRI_CELLS['r+'].slice(); // red parked at home is fine for the test
const fin = L.getMovesForPeg(s5, 'blue', 9).find((x) => L.CELLS[x.to].tri === 'r-');
const e5 = fin && L.applyMove(s5, fin);
ok('4 players: ends when three are home, last seat placed', e5 && e5.phase === 'game_over' && e5.finished.length === 4 && e5.finished[3] === 'yellow');
ok('rankings = finishing order', e5 && L.rankings(e5).join() === e5.finished.join());
// teams: first pair home wins
const t = L.createInitialState(L.seatColors(6), { teams: true });
t.finished = ['red'];
t.pegs.blue = [...L.TRI_CELLS['r-'].filter((x) => x !== id(2, -5)), id(2, -4)];
t.left.blue = Array(10).fill(true);
t.pegs.red = L.TRI_CELLS['r+'].slice();
const tf = L.getMovesForPeg(t, 'blue', 9).find((x) => L.CELLS[x.to].tri === 'r-');
const te = tf && L.applyMove(t, tf);
ok('teams: pair home ends the game', te && te.phase === 'game_over' && te.endReason === 'team' && te.winningTeam.slice().sort().join() === 'blue,red');
ok('teams: winners rank first', te && L.rankings(te).slice(0, 2).sort().join() === 'blue,red');
ok('teamRankings puts the winners first', te && L.teamRankings(te)[0].sort().join() === 'blue,red');
// stalemate: everyone passes in a row
let st = L.createInitialState(L.seatColors(3));
for (let k = 0; k < 3; k++) st = L.passTurn(st);
ok('a full round of passes ends the game', st.phase === 'game_over' && st.endReason === 'stalemate' && st.finished.length === 3);
ok('passes counted', st.stats.blue.passes === 1);
// boxed in for good: blue's never-moved tip marble walled in by finished red
const boxed = (n) => {
const st = L.createInitialState(L.seatColors(n));
const tip = id(-4, 8);
st.pegs.blue = [tip, id(0, 0), id(1, 0), id(2, 0), id(-1, 0), id(-2, 0), id(0, 1), id(1, 1), id(-1, 1), id(2, -1)];
st.left.blue = [false, ...Array(9).fill(true)];
st.pegs.red = [...L.TRI_CELLS['r+'].filter((x) => x !== tip), id(3, -3)];
st.left.red = Array(10).fill(true);
st.finished = ['red'];
st.winner = 'red';
st.current = 1; // orange (4p) / purple (3p has no red — skip)
const mv = L.getAllValidMoves(st)[0];
return L.applyMove(st, mv);
};
const b4 = boxed(4);
ok('boxed in: detected after the next move', b4.stuck.includes('blue') && b4.newlyStuck.includes('blue'));
ok('boxed in: no moves offered', L.getAllValidMoves({ ...b4, current: 0 }, 'blue').length === 0);
ok('boxed in: game plays on with two racing', b4.phase === 'play' && L.isActive(b4, 'orange') && L.isActive(b4, 'yellow'));
// walk the turn order once: blue is never on move
let w = b4, sawBlue = false;
for (let k = 0; k < 6 && w.phase === 'play'; k++) { if (L.currentColor(w) === 'blue') sawBlue = true; const m = L.getAllValidMoves(w)[0]; w = m ? L.applyMove(w, m) : L.passTurn(w); }
ok('boxed in: turns skipped', !sawBlue);
const b5 = (() => { const st = L.cloneState(b4); st.finished.push('orange'); st.current = 3; return L.applyMove(st, L.getAllValidMoves(st, 'yellow')[0]); })();
ok('boxed in: one racer left → game over', b5.phase === 'game_over' && b5.endReason === 'boxed', `${b5.phase} ${b5.endReason}`);
ok('boxed in: ranks last', L.rankings(b5).at(-1) === 'blue' && L.rankings(b5).join() === 'red,orange,yellow,blue', L.rankings(b5).join());
// no progress: two seats shuffling forever end as a stalemate
let np = L.createInitialState(L.seatColors(2));
np.bestTotal = -1; // pretend we've already done better
let steps = 0;
while (np.phase === 'play' && steps++ < 1000) np = L.applyMove(np, L.getAllValidMoves(np)[0]);
ok('no new progress for STALL_ROUNDS rounds → stalemate', np.phase === 'game_over' && np.endReason === 'stalemate' && steps === L.STALL_ROUNDS * 2, `${np.endReason} after ${steps}`);
// clone independence
const c0 = L.createInitialState(L.seatColors(2));
const c1 = L.cloneState(c0);
c1.pegs.blue[0] = 0; c1.left.blue[0] = true; c1.stats.blue.moves = 9;
ok('cloneState is deep', c0.pegs.blue[0] !== 0 && !c0.left.blue[0] && c0.stats.blue.moves === 0);
ok('stats: hops and longest', (() => {
const s = L.createInitialState(L.seatColors(2));
const j = L.getAllValidMoves(s).find((x) => x.isJump);
const a2 = L.applyMove(s, j);
return a2.stats.blue.jumps === 1 && a2.stats.blue.hops === j.path.length - 1 && a2.stats.blue.longest === j.path.length - 1 && a2.lastMoves.length === 1;
})());
}
// ── AI legality ─────────────────────────────────────────────────────────────
section('AI');
{
const rng = AI.mulberry32(9);
let legal = true;
for (let g = 0; g < (QUICK ? 6 : 20); g++) {
let s = L.createInitialState(L.seatColors(2 + (g % 5)));
for (let k = 0; k < 40 + g * 3 && s.phase === 'play'; k++) {
const all = L.getAllValidMoves(s);
const mv = all[Math.floor(rng() * all.length)];
s = mv ? L.applyMove(s, mv) : L.passTurn(s);
}
if (s.phase !== 'play') continue;
const all = L.getAllValidMoves(s);
for (let k = 1; k <= 5; k++) {
const m = AI.chooseMove(s, k, { rng });
if (all.length ? !all.some((x) => L.sameMove(x, m)) : m !== null) legal = false;
}
}
ok('every skill picks a legal move', legal);
// boxed in: a marble with no move → null
const s = L.createInitialState(L.seatColors(2));
s.phase = 'game_over';
ok('no move after the game', AI.chooseMove(s, 3) === null);
const h = AI.hint(L.createInitialState(L.seatColors(2)));
ok('hint returns a move and a reason', h && h.move && typeof h.reason === 'string');
}
// ── soak ────────────────────────────────────────────────────────────────────
section('Self-play soak');
{
const plans = [];
for (const n of [2, 3, 4, 5, 6]) plans.push({ n, opts: {} });
plans.push({ n: 6, opts: { teams: true } }, { n: 6, opts: { antiBlock: false } }, { n: 2, opts: { antiBlock: false } });
const reps = QUICK ? 1 : 3;
let games = 0, worstMs = 0, stalemates = 0;
for (const { n, opts } of plans) {
for (let r = 0; r < reps; r++) {
const rng = AI.mulberry32(100 + r * 7 + n);
let s = L.createInitialState(L.seatColors(n), opts);
const skill = Object.fromEntries(s.seats.map((c, i) => [c, 1 + ((i + r) % 5)]));
let okRest = true, okOcc = true, okLeft = true;
const t0 = Date.now();
let guard = 0;
while (s.phase === 'play' && guard++ < 20000) {
const c = L.currentColor(s);
const prevLeft = s.left[c].slice();
const m = AI.chooseMove(s, skill[c], { rng });
s = m ? L.applyMove(s, m) : L.passTurn(s);
const occ = new Set();
for (const col of s.seats) {
s.pegs[col].forEach((cell, i) => {
if (occ.has(cell)) okOcc = false;
occ.add(cell);
const tri = L.CELLS[cell].tri;
const allowed = tri === 'center' || tri === L.TARGET[col] || (tri === L.HOME[col] && !s.left[col][i]);
if (!allowed) okRest = false;
});
}
if (prevLeft.some((v, i) => v && !s.left[c][i])) okLeft = false;
}
const ms = Date.now() - t0;
worstMs = Math.max(worstMs, ms);
games++;
const label = `${n}p${opts.teams ? ' teams' : ''}${opts.antiBlock === false ? ' strict' : ''} #${r}`;
// strict rules can spoiler-deadlock (the no-progress detector ends those);
// with anti-blocking every game must be played out
const fine = opts.antiBlock === false ? ['finished', 'team', 'boxed', 'stalemate'] : ['finished', 'team', 'boxed'];
ok(`${label}: ends normally`, s.phase === 'game_over' && fine.includes(s.endReason), `${s.endReason} after ${s.turn}`);
if (s.endReason === 'stalemate') stalemates++;
ok(`${label}: one marble per hole`, okOcc);
ok(`${label}: rests only where allowed`, okRest);
ok(`${label}: home flags never reset`, okLeft);
ok(`${label}: everyone ranked`, L.rankings(s).length === n);
}
}
console.log(` ${games} games, slowest ${worstMs} ms, ${stalemates} strict-rule stalemates`);
}
// ── ladder ──────────────────────────────────────────────────────────────────
section('Skill ladder (2 players, mirrored seats)');
{
const pairs = QUICK ? 8 : 25;
for (const [hi, lo] of [[2, 1], [3, 2], [4, 3], [5, 4]]) {
let wins = 0, n = 0;
for (let g = 0; g < pairs; g++) {
for (const hiSeat of [0, 1]) {
const rng = AI.mulberry32(4000 + g);
let s = L.createInitialState(L.seatColors(2));
const hc = s.seats[hiSeat];
let guard = 0;
while (s.phase === 'play' && guard++ < 5000) {
const c = L.currentColor(s);
let m;
if (s.turn < 4) { const ms = L.getAllValidMoves(s).filter((x) => L.moveGain(x) > 0); m = ms[Math.floor(rng() * ms.length)]; }
else m = AI.chooseMove(s, c === hc ? hi : lo, { rng });
s = m ? L.applyMove(s, m) : L.passTurn(s);
}
if (s.finished[0] === hc) wins++;
n++;
}
}
const pct = (100 * wins) / n;
console.log(` ${hi} beats ${lo}: ${pct.toFixed(1)}% of ${n}`);
ok(`skill ${hi} beats ${lo} most of the time`, pct > 55);
}
}
// ── layout ──────────────────────────────────────────────────────────────────
section('Layout');
{
const inScreen = (r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= Lay.W && r.y + r.h <= Lay.H;
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 hex = Lay.boardHex();
const inHex = (p) => {
let inside = true;
for (let i = 0; i < 6; i++) {
const a = hex[i], b = hex[(i + 1) % 6];
if ((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) < 0) inside = false;
}
return inside;
};
ok('every hole inside the board', Lay.CELL_XY.every((p) => inHex({ x: p.x, y: p.y }) && Lay.cellAt(p.x, p.y) >= 0));
ok('cellAt round-trips', Lay.CELL_XY.every((p, i) => Lay.cellAt(p.x, p.y) === i));
ok('hole spacing', Math.abs(Math.hypot(Lay.CELL_XY[L.cellId(1, 0)].x - Lay.CELL_XY[L.cellId(0, 0)].x, 0) - Lay.CELL) < 0.01);
const rects = {
...Object.fromEntries(Object.keys(Lay.PLATES).map((c) => [`plate ${c}`, Lay.plateRect(c)])),
status: Lay.STATUS, log: Lay.LOG,
...Object.fromEntries(Object.entries(Lay.BUTTONS).map(([k, b]) => [`btn ${k}`, { x: b.x - Lay.BTN.w / 2, y: b.y - Lay.BTN.h / 2, w: Lay.BTN.w, h: Lay.BTN.h }])),
};
for (const [k, r] of Object.entries(rects)) {
ok(`${k} on screen`, inScreen(r));
const corners = [{ x: r.x, y: r.y }, { x: r.x + r.w, y: r.y }, { x: r.x, y: r.y + r.h }, { x: r.x + r.w, y: r.y + r.h }];
ok(`${k} clear of the board`, corners.every((p) => !inHex(p)), JSON.stringify(r));
}
const keys = Object.keys(rects);
for (let i = 0; i < keys.length; i++) for (let j = i + 1; j < keys.length; j++) {
ok(`${keys[i]} / ${keys[j]} don't overlap`, !overlap(rects[keys[i]], rects[keys[j]]));
}
for (const c of Object.keys(Lay.PLATES)) ok(`bubble ${c} on screen`, inScreen(Lay.plateParts(c).bubble));
for (const t of Object.keys(L.TRIANGLES)) ok(`${t} outline inside the board`, Lay.triPolygon(t).every(inHex));
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);