Rewrite checkers as themed barbershop game with variants and strong AI

- Replace the single American-only implementation with five rule variants
  (American, Pool, Russian, Giveaway, Casual) on a flat 32-square board
  model with proper multi-jump, Turkish strike, flying kings, and
  mid-crown rules per variant
- Rework the AI: negamax alpha-beta with a Zobrist transposition table,
  iterative deepening inside a time budget, capture quiescence, and move
  ordering; skill 1–5 now shapes depth, scoring noise, and top-N slip
- Add tournament opening ballots, match play (best of 3/5 with colour
  swap), save/resume, and a move-by-move replay board on the end screen
- Build the "Gus's Back Room" presentation: fully procedural canvas art,
  Web Audio ambience (rain, percolator, radio), tiered character dialogue,
  and an in-character tutorial
- Add tools/verifyCheckers.js: headless checks for geometry, per-variant
  rules, notation round-trip, ballot legality, AI budget/correctness,
  self-play soak, skill ladder, and HUD layout collisions
This commit is contained in:
Brian Fertig 2026-12-01 13:34:29 -07:00
parent e61ec5e363
commit 50078661d2
14 changed files with 4037 additions and 688 deletions

View File

@ -1,127 +1,297 @@
// Checkers AI — alpha-beta minimax with a Nerts-style 1..5 skill model.
// CheckersAI.js — the opponents across the barrel.
//
// Skill controls four axes (mirrors NertsAI's delay/miss/quality idea):
// • depth — search depth in full turns (deeper = stronger)
// • blunder — chance to ignore the best move and play a random legal one
// • noise — random value added to root move scores (flattens decisions)
// • delay — "thinking" pause (ms range) before the move, for natural pacing
// The scene asks for ONE step at a time; multi-jumps come back across ticks
// because applyMove keeps the same side to move until the chain ends.
// Negamax alpha-beta over whole turns with iterative deepening inside a time
// budget, a transposition table (Zobrist hashes), capture quiescence (a
// position with a jump pending is never scored mid-exchange), and move
// ordering (table move, then the biggest jumps, crownings, the rest).
//
// Evaluation: material (kings worth more, flying kings far more), man
// advancement, the back-rank "bridge", the centre, and an endgame term — the
// side ahead wants trades and hunts with its kings, the side behind runs for a
// double corner. Giveaway turns the material sense upside-down.
//
// Skill 1‥5 sets search depth / time and how human the mistakes are: shallow
// horizons, scoring noise, and now and then settling for one of the top few
// moves instead of the best. Skill 5 plays straight.
import {
getValidMoves, applyMove, expandTurns, pieceCounts, SIZE,
generateMoves, applyBoard, rulesOf, other, sign, RC, N, BLACK, posKey, moveKey, counts, legalMoves,
} from './CheckersLogic.js';
import { mulberry32 } from '../../ui/cardtable/AITiming.js';
const SKILL_PROFILES = {
1: { depth: 1, blunder: 0.45, noise: 90, delay: [900, 1500] },
2: { depth: 2, blunder: 0.28, noise: 55, delay: [800, 1300] },
3: { depth: 3, blunder: 0.15, noise: 30, delay: [650, 1100] },
4: { depth: 5, blunder: 0.05, noise: 12, delay: [500, 900] },
5: { depth: 7, blunder: 0.00, noise: 0, delay: [400, 800] },
export const SKILL = {
1: { depth: 2, ms: 150, noise: 70, slip: 0.3, top: 4 },
2: { depth: 3, ms: 250, noise: 40, slip: 0.16, top: 3 },
3: { depth: 5, ms: 400, noise: 16, slip: 0.07, top: 2 },
4: { depth: 9, ms: 650, noise: 6, slip: 0.02, top: 2 },
5: { depth: 30, ms: 1100, noise: 0, slip: 0, top: 1 },
};
export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
const WIN = 100000;
const MAN = 100;
const KING = 175;
const INF = 1e9;
const TIMEOUT = Symbol('timeout');
function profileFor(skill) {
return SKILL_PROFILES[Math.max(1, Math.min(5, skill | 0))] ?? SKILL_PROFILES[3];
// ── zobrist ──────────────────────────────────────────────────────────────────
const zr = mulberry32(0xc0ffee);
const Z = Array.from({ length: N }, () => [0, 0, 0, 0, 0].map(() => (zr() * 0x100000000) >>> 0));
const ZSIDE = (zr() * 0x100000000) >>> 0;
const PI = { 1: 1, 2: 2, '-1': 3, '-2': 4 };
function hashOf(b, color) {
let h = color === BLACK ? ZSIDE : 0;
for (let i = 0; i < N; i++) if (b[i]) h ^= Z[i][PI[b[i]]];
return h >>> 0;
}
export function nextThinkDelay(skill) {
const [lo, hi] = profileFor(skill).delay;
return lo + Math.random() * (hi - lo);
}
// ── evaluation (from `color`'s point of view) ─────────────────────────────────
const ADV = [0, 0, 1, 3, 5, 8, 12, 0];
const DOUBLE_CORNERS = [0, 4, 27, 31];
function evaluate(state, aiColor) {
if (state.phase === 'game_over') {
if (state.winner === aiColor) return WIN;
if (state.winner === 'draw') return 0;
return -WIN;
}
let score = 0;
for (let r = 0; r < SIZE; r++) {
for (let c = 0; c < SIZE; c++) {
const p = state.board[r][c];
export function evaluate(b, color, rules) {
const flyKing = rules.flying ? 260 : 150;
let s = 0;
let matB = 0, matR = 0, nB = 0, nR = 0;
const kingsB = [], kingsR = [], piecesB = [], piecesR = [];
for (let i = 0; i < N; i++) {
const p = b[i];
if (!p) continue;
let v = p.king ? KING : MAN;
if (!p.king) {
// Reward advancement toward the crown row.
const adv = p.color === 'white' ? (7 - r) : r;
v += adv * 3;
// Reward holding the back row (blocks opponent promotion).
const homeRow = p.color === 'white' ? 7 : 0;
if (r === homeRow) v += 8;
const [r, c] = RC[i];
let v;
if (p === 1 || p === -1) {
const adv = p > 0 ? r : 7 - r;
v = 100 + ADV[adv];
if (c >= 2 && c <= 5 && r >= 2 && r <= 5) v += 3;
if (c === 0 || c === 7) v -= 2;
} else {
v = flyKing;
if (r >= 2 && r <= 5 && c >= 2 && c <= 5) v += 6;
else if (r === 0 || r === 7 || c === 0 || c === 7) v -= 4;
}
// Central files are worth slightly more than the edges.
v += (c >= 2 && c <= 5) ? 4 : 0;
score += (p.color === aiColor ? v : -v);
if (p > 0) { matB += v; nB++; piecesB.push(i); if (p === 2) kingsB.push(i); }
else { matR += v; nR++; piecesR.push(i); if (p === -2) kingsR.push(i); }
}
if (rules.giveaway) {
// fewer pieces is better; a king is a liability (hard to give away)
s = (nR - nB) * 100 + (kingsR.length - kingsB.length) * 30;
return color === BLACK ? s : -s;
}
// Small mobility term.
const moves = getValidMoves(state).length;
score += (state.turn === aiColor ? moves : -moves) * 1.5;
return score;
s = matB - matR;
// the bridge: holding squares 1 & 3 (or 30 & 32) keeps kings out
if (nB + nR > 12) {
if (b[0] === 1 && b[2] === 1) s += 12;
if (b[29] === -1 && b[31] === -1) s -= 12;
}
const total = nB + nR;
if (total <= 12 && matB !== matR) {
// ahead: trade down; hunt with kings. behind: run for a double corner.
const lead = matB > matR ? 1 : -1;
s += lead * (24 - total) * 4;
const hunters = lead > 0 ? kingsB : kingsR;
const prey = lead > 0 ? piecesR : piecesB;
for (const k of hunters) {
let best = 99;
for (const q of prey) best = Math.min(best, dist(k, q));
if (best < 99) s -= lead * best * 3;
}
const runners = lead > 0 ? kingsR : kingsB;
for (const k of runners) if (DOUBLE_CORNERS.includes(k)) s -= lead * 10;
}
return color === BLACK ? s : -s;
}
function dist(a, b) {
const [r1, c1] = RC[a], [r2, c2] = RC[b];
return Math.max(Math.abs(r1 - r2), Math.abs(c1 - c2));
}
function search(state, depth, alpha, beta, aiColor) {
if (state.phase === 'game_over' || depth <= 0) return evaluate(state, aiColor);
const outcomes = expandTurns(state);
if (outcomes.length === 0) return evaluate(state, aiColor);
// ── search ───────────────────────────────────────────────────────────────────
class Search {
constructor(rules, deadline) {
this.rules = rules;
this.deadline = deadline;
this.tt = new Map();
this.nodes = 0;
}
if (state.turn === aiColor) {
let value = -Infinity;
for (const o of outcomes) {
value = Math.max(value, search(o.state, depth - 1, alpha, beta, aiColor));
alpha = Math.max(alpha, value);
order(moves, ttKey) {
return moves
.map((m) => ({ m, k: (ttKey && moveKey(m) === ttKey ? 1e6 : 0) + m.caps.length * 100 + (m.crown ? 50 : 0) }))
.sort((a, b) => b.k - a.k)
.map((x) => x.m);
}
negamax(b, color, depth, alpha, beta, ply, qply = 0) {
if ((++this.nodes & 1023) === 0 && Date.now() > this.deadline) throw TIMEOUT;
let moves = generateMoves(b, color, this.rules);
if (!moves.length) return this.rules.giveaway ? WIN - ply : -(WIN - ply);
if (ply > 64) return evaluate(b, color, this.rules);
let standPat = -INF;
if (depth <= 0) {
const caps = moves.filter((m) => m.caps.length);
if (!caps.length || qply > 14) return evaluate(b, color, this.rules);
if (!this.rules.forced) {
standPat = evaluate(b, color, this.rules);
if (standPat >= beta) return standPat;
if (standPat > alpha) alpha = standPat;
}
moves = caps;
}
const h = hashOf(b, color);
const e = this.tt.get(h);
if (e && e.depth >= depth && depth > 0) {
if (e.flag === 0) return e.val;
if (e.flag === 1 && e.val >= beta) return e.val;
if (e.flag === -1 && e.val <= alpha) return e.val;
}
const a0 = alpha;
let best = standPat, bestKey = null;
for (const m of this.order(moves, e?.best)) {
const nb = applyBoard(b, m);
// a single forced reply isn't a real ply — don't let it eat the horizon
const d = depth <= 0 ? depth - 1 : moves.length === 1 ? depth : depth - 1;
const v = -this.negamax(nb, other(color), d, -beta, -alpha, ply + 1, depth <= 0 ? qply + 1 : qply);
if (v > best) { best = v; bestKey = moveKey(m); }
if (v > alpha) alpha = v;
if (alpha >= beta) break;
}
return value;
if (depth > 0) {
const flag = best <= a0 ? -1 : best >= beta ? 1 : 0;
this.tt.set(h, { depth, val: best, flag, best: bestKey });
}
let value = Infinity;
for (const o of outcomes) {
value = Math.min(value, search(o.state, depth - 1, alpha, beta, aiColor));
beta = Math.min(beta, value);
if (beta <= alpha) break;
}
return value;
}
// Return one step move for `aiColor`, or null if it cannot move.
export function chooseMove(state, aiColor, skill) {
const prof = profileFor(skill);
const steps = getValidMoves(state);
if (steps.length === 0) return null;
if (steps.length === 1) return steps[0];
if (Math.random() < prof.blunder) {
return steps[Math.floor(Math.random() * steps.length)];
}
// Score each legal first step by the best end-of-turn position it can reach.
const byStep = new Map();
for (const o of expandTurns(state)) {
const key = stepKey(o.firstStep);
let val;
if (o.state.turn === aiColor && o.state.phase !== 'game_over') {
val = search(o.state, prof.depth, -Infinity, Infinity, aiColor);
} else {
val = search(o.state, prof.depth - 1, -Infinity, Infinity, aiColor);
}
if (!byStep.has(key) || val > byStep.get(key).val) {
byStep.set(key, { step: o.firstStep, val });
return best;
}
}
let best = null;
let bestScore = -Infinity;
for (const { step, val } of byStep.values()) {
const noisy = val + (Math.random() * 2 - 1) * prof.noise;
if (noisy > bestScore) { bestScore = noisy; best = step; }
}
return best ?? steps[0];
// Unique root moves (two jump routes to the same result count once).
function rootMoves(gs) {
const seen = new Set();
return legalMoves(gs).filter((m) => { const k = moveKey(m); if (seen.has(k)) return false; seen.add(k); return true; });
}
function stepKey(step) {
return `${step.from[0]},${step.from[1]}->${step.to[0]},${step.to[1]}`;
// Score a root move's resulting state, treating draws the rules would call as 0.
function drawish(gs, m) {
const piece = gs.board[m.from];
const manMove = piece === 1 || piece === -1;
if (m.caps.length || manMove) return false;
const nb = applyBoard(gs.board, m);
const key = posKey(nb, other(gs.turn));
if ((gs.reps[key] ?? 0) >= 2) return true;
return gs.quiet + 1 >= gs.quietLimit * 2;
}
/**
* Score every root move for the side to move.
* opts: { depth, ms, exact (full window per move) } → [{ move, score }], best first.
*/
export function analyze(gs, { depth = 6, ms = 500, exact = true } = {}) {
const rules = rulesOf(gs.variant);
const color = gs.turn;
const moves = rootMoves(gs);
if (!moves.length) return [];
const S = new Search(rules, Date.now() + ms);
let done = moves.map((m) => ({ move: m, score: 0 }));
for (let d = 1; d <= depth; d++) {
try {
const res = [];
let alpha = -INF;
// best-so-far first helps the cut-offs
for (const { move } of done) {
let score;
if (drawish(gs, move)) score = 0;
else {
const nb = applyBoard(gs.board, move);
const lo = exact ? -INF : alpha;
score = -S.negamax(nb, other(color), d - 1, -INF, -lo, 1);
}
res.push({ move, score });
if (score > alpha) alpha = score;
}
res.sort((a, b) => b.score - a.score);
done = res;
if (Math.abs(done[0].score) > WIN - 500) break; // a forced result is found
} catch (err) {
if (err !== TIMEOUT) throw err;
break;
}
}
return done;
}
/** The AI's choice for the side to move. opts: { rng, ms } */
export function chooseMove(gs, skill, { rng = Math.random, ms = null } = {}) {
const prof = SKILL[clampSkill(skill)];
const legal = rootMoves(gs);
if (!legal.length) return null;
if (legal.length === 1) return legal[0];
const ranked = analyze(gs, { depth: prof.depth, ms: ms ?? prof.ms, exact: prof.top > 1 || prof.noise > 0 });
if (prof.noise === 0 && prof.slip === 0) return ranked[0].move;
const noisy = ranked
.map((r) => ({ ...r, n: r.score + (rng() * 2 - 1) * prof.noise }))
.sort((a, b) => b.n - a.n);
// never "slip" out of a won position or into a forced loss
if (rng() < prof.slip) {
const best = ranked[0].score;
const pool = noisy.slice(0, prof.top).filter((r) => r.score > -WIN + 500 && (best < WIN - 500 || r.score > WIN - 500));
if (pool.length) return pool[Math.floor(rng() * pool.length)].move;
}
return noisy[0].move;
}
/** A coaching hint for the side to move: { move, score, reason }. */
export function hint(gs, { ms = 700 } = {}) {
const ranked = analyze(gs, { depth: 30, ms, exact: false });
if (!ranked.length) return null;
const { move, score } = ranked[0];
return { move, score, reason: describeIdea(gs, move, score) };
}
export function describeIdea(gs, m, score) {
const rules = rulesOf(gs.variant);
const after = applyBoard(gs.board, m);
const opp = other(gs.turn);
if (score > WIN - 500) return rules.giveaway ? 'wins the race to give everything away' : 'wins by force';
if (m.caps.length >= 2) return `takes ${m.caps.length} pieces in one go`;
if (m.crown) return 'gets you a king';
if (m.caps.length === 1) return 'takes the piece that\'s on offer';
const replies = generateMoves(after, opp, rules);
if (replies.length && replies[0].caps.length && rules.forced) {
return score >= -20 ? 'forces a jump — and the trade comes back your way' : 'is the least painful way out';
}
const piece = gs.board[m.from];
if (piece === 1 || piece === -1) {
const toRow = RC[m.to][0];
const rowsLeft = piece > 0 ? 7 - toRow : toRow;
if (rowsLeft <= 2) return 'pushes toward the king row';
return 'keeps your men backed up and safe';
}
return 'puts your king to work';
}
/**
* Would `color` (the AI) agree to a draw? Positive eval = AI is ahead.
*/
export function drawDecision(gs, aiColor, skill, { ms = 300, rng = Math.random } = {}) {
const k = clampSkill(skill);
const ranked = analyze({ ...gs, turn: gs.turn }, { depth: 6, ms, exact: false });
let ev = ranked.length ? ranked[0].score : 0;
if (gs.turn !== aiColor) ev = -ev;
const c = counts(gs.board);
const material = (aiColor === BLACK ? 1 : -1) * ((c.black + c.blackKings * 0.5) - (c.red + c.redKings * 0.5));
if (gs.ply < 16) return { accept: false, ev, why: 'early' };
const tolerance = [0, 70, 50, 35, 25, 15][k];
const accept = ev <= tolerance && material <= 0.5 && (ev < -tolerance || rng() < 0.85);
return { accept, ev, why: accept ? (ev < -tolerance ? 'behind' : 'level') : 'ahead' };
}
/** Should the AI offer a draw now? (Only in level or slightly worse endings.) */
export function wantsDraw(gs, aiColor, skill, { ms = 250 } = {}) {
if (gs.ply < 40) return false;
const c = counts(gs.board);
if (c.black + c.red > 10 && gs.quiet < 30) return false;
const ranked = analyze(gs, { depth: 6, ms, exact: false });
let ev = ranked.length ? ranked[0].score : 0;
if (gs.turn !== aiColor) ev = -ev;
void skill;
return ev <= 15 && ev >= -120;
}
export const _internal = { WIN, hashOf, sign };

View File

@ -0,0 +1,727 @@
// CheckersArt.js — baked canvas textures for Gus's Back Room. All
// procedural: no image files.
//
// ck-room the barbershop back room after closing: pinstripe wallpaper,
// walnut wainscot, a checkered linoleum strip, the rainy
// front window (street, neon, the pole's housing), the price
// card, the shelf (cathedral radio, mantel clock, percolator),
// an oak barrel head under the board, a hanging lamp's pool
// ck-props the shelf + barrel alone (over a chosen playfield)
// ck-vignette lamp pool + vignette alone (over a chosen playfield)
// ck-board a worn painted board: cream and deep green squares, walnut
// frame with brass corner pins, scuffs, a coffee ring
// ck-man-<c>, ck-king-<c> ribbed composition checkers (2× bake);
// ck-man-<c>-s, ck-king-<c>-s the same with a colour-blind stamp
// ck-shadow, ck-glow, ck-ring, ck-dot, ck-spark, ck-steam, ck-rain
// ck-pole-stripes, ck-pole-glow the barber pole's spinning stripes
// ck-plate, ck-plate-glow, ck-card-status, ck-card-log, ck-ribbon
import { canvas, rr, noisePattern } from '../../ui/casino/CasinoArt.js';
import {
W, H, BX, BY, BOARD, FRAME, BOARD_TEX, BCX, BCY, SQ, PIECE_R, PLATE, STATUS, LOG, RIBBON,
WINDOW, POLE, SHELF, SIGN,
} from './CheckersLayout.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;
export const PIECE_TEX = (PIECE_R + 10) * 2 * RES;
export const INK = {
black: { body: '#1d1c22', rim: '#0c0b10', hi: '#5a5868', hex: 0x2a2830, text: '#1d1c22', light: '#8a889a' },
red: { body: '#b52a22', rim: '#6a120e', hi: '#ff8a70', hex: 0xc0302a, text: '#a0221c', light: '#ff9a84' },
};
export const BRASS = 0xd8b060;
export const CREAM = '#f3ead2';
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,8,2,0.35)', 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.6;
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 brassGrad(ctx, x0, y0, x1, y1) {
const g = ctx.createLinearGradient(x0, y0, x1, y1);
g.addColorStop(0, '#f6dc9a'); g.addColorStop(0.4, '#b98a34'); g.addColorStop(0.65, '#ecc878'); g.addColorStop(1, '#7a5418');
return g;
}
function chromeGrad(ctx, x0, x1) {
const g = ctx.createLinearGradient(x0, 0, x1, 0);
g.addColorStop(0, '#5a5f66'); g.addColorStop(0.25, '#e8eef4'); g.addColorStop(0.45, '#9aa2ab'); g.addColorStop(0.7, '#f4f8fc'); g.addColorStop(1, '#4a4e55');
return g;
}
// ── room ─────────────────────────────────────────────────────────────────────
const RAIL_Y = 770;
function wall(ctx, rnd) {
const g = ctx.createLinearGradient(0, 0, 0, RAIL_Y);
g.addColorStop(0, '#16302a'); g.addColorStop(1, '#1f3d34');
ctx.fillStyle = g; ctx.fillRect(0, 0, W, RAIL_Y);
// pinstripe paper with a tiny diamond motif between the stripes
for (let x = 0; x < W; x += 32) {
ctx.fillStyle = 'rgba(236,222,180,0.07)'; ctx.fillRect(x, 0, 3, RAIL_Y);
ctx.fillStyle = 'rgba(236,222,180,0.035)'; ctx.fillRect(x + 9, 0, 1, RAIL_Y);
}
ctx.fillStyle = 'rgba(236,222,180,0.06)';
for (let y = 22; y < RAIL_Y; y += 44) {
for (let x = 16; x < W; x += 32) {
const yy = y + ((x / 32) % 2) * 22;
ctx.beginPath(); ctx.moveTo(x + 2, yy - 4); ctx.lineTo(x + 6, yy); ctx.lineTo(x + 2, yy + 4); ctx.lineTo(x - 2, yy); ctx.closePath(); ctx.fill();
}
}
// age: water stains and fading toward the ceiling
for (let i = 0; i < 9; i++) {
const x = rnd() * W, y = rnd() * RAIL_Y, r = 60 + rnd() * 160;
const s = ctx.createRadialGradient(x, y, 0, x, y, r);
s.addColorStop(0, 'rgba(60,50,20,0.10)'); s.addColorStop(1, 'rgba(60,50,20,0)');
ctx.fillStyle = s; ctx.fillRect(x - r, y - r, r * 2, r * 2);
}
ctx.fillStyle = noisePattern(ctx, 96, 16); ctx.fillRect(0, 0, W, RAIL_Y);
}
function wainscot(ctx, rnd) {
const g = ctx.createLinearGradient(0, RAIL_Y, 0, H);
g.addColorStop(0, '#3a2414'); g.addColorStop(1, '#22140a');
ctx.fillStyle = g; ctx.fillRect(0, RAIL_Y, W, H - RAIL_Y);
grain(ctx, rnd, 0, RAIL_Y, W, H - RAIL_Y, { tone: 'rgba(10,4,0,0.35)', lines: 60, wave: 3 });
// raised panels
for (let x = 24; x < W; x += 240) {
ctx.strokeStyle = 'rgba(0,0,0,0.45)'; ctx.lineWidth = 3; ctx.strokeRect(x, RAIL_Y + 40, 200, 220);
ctx.strokeStyle = 'rgba(255,200,140,0.10)'; ctx.lineWidth = 2; ctx.strokeRect(x + 3, RAIL_Y + 43, 200, 220);
}
// chair rail
const rail = ctx.createLinearGradient(0, RAIL_Y - 14, 0, RAIL_Y + 14);
rail.addColorStop(0, '#6a4426'); rail.addColorStop(0.5, '#4a2e18'); rail.addColorStop(1, '#2a180c');
ctx.fillStyle = rail; ctx.fillRect(0, RAIL_Y - 12, W, 26);
ctx.fillStyle = 'rgba(255,210,150,0.18)'; ctx.fillRect(0, RAIL_Y - 12, W, 3);
}
function linoleum(ctx) {
// the checkered floor in perspective, peeking under the wainscot's toe-kick
const y0 = 1036, y1 = H;
ctx.save();
ctx.beginPath(); ctx.rect(0, y0, W, y1 - y0); ctx.clip();
const rows = 3, vx = BCX;
for (let r = 0; r < rows; r++) {
const ya = y0 + (y1 - y0) * (r / rows), yb = y0 + (y1 - y0) * ((r + 1) / rows);
const sa = 0.7 + r * 0.15, sb = 0.7 + (r + 1) * 0.15;
for (let i = -20; i < 20; i++) {
const tw = 90;
ctx.fillStyle = (i + r) % 2 === 0 ? '#d8d0bc' : '#1a1816';
ctx.beginPath();
ctx.moveTo(vx + i * tw * sa, ya); ctx.lineTo(vx + (i + 1) * tw * sa, ya);
ctx.lineTo(vx + (i + 1) * tw * sb, yb); ctx.lineTo(vx + i * tw * sb, yb); ctx.closePath(); ctx.fill();
}
}
const sh = ctx.createLinearGradient(0, y0, 0, y1);
sh.addColorStop(0, 'rgba(0,0,0,0.75)'); sh.addColorStop(1, 'rgba(0,0,0,0.35)');
ctx.fillStyle = sh; ctx.fillRect(0, y0, W, y1 - y0);
ctx.restore();
ctx.fillStyle = '#1a0e06'; ctx.fillRect(0, y0 - 6, W, 8);
}
function windowView(ctx, rnd) {
const { x, y, w, h } = WINDOW;
// outside: a wet night street
ctx.save();
rr(ctx, x, y, w, h, 4); ctx.clip();
const sky = ctx.createLinearGradient(0, y, 0, y + h);
sky.addColorStop(0, '#0b1426'); sky.addColorStop(0.55, '#16243a'); sky.addColorStop(1, '#0a0f18');
ctx.fillStyle = sky; ctx.fillRect(x, y, w, h);
// buildings across the street with a few lit windows
let bx = x - 10;
while (bx < x + w) {
const bw = 50 + rnd() * 70, bh = 90 + rnd() * 110;
ctx.fillStyle = '#070b12'; ctx.fillRect(bx, y + h * 0.62 - bh, bw, bh);
for (let wy = y + h * 0.62 - bh + 10; wy < y + h * 0.62 - 12; wy += 18) {
for (let wx = bx + 6; wx < bx + bw - 8; wx += 14) {
if (rnd() < 0.18) { ctx.fillStyle = rnd() < 0.5 ? 'rgba(255,214,140,0.75)' : 'rgba(255,190,110,0.5)'; ctx.fillRect(wx, wy, 6, 8); }
}
}
bx += bw + 4;
}
// a diner's neon across the street, smeared by rain
ctx.save();
ctx.shadowColor = 'rgba(255,80,120,0.9)'; ctx.shadowBlur = 18;
ctx.strokeStyle = 'rgba(255,110,150,0.9)'; ctx.lineWidth = 3;
ctx.font = `italic 26px ${SERIF}`; ctx.textAlign = 'left';
ctx.strokeText('Diner', x + 40, y + 86);
ctx.restore();
// street lamp
const lamp = ctx.createRadialGradient(x + 70, y + 120, 2, x + 70, y + 120, 120);
lamp.addColorStop(0, 'rgba(255,220,150,0.55)'); lamp.addColorStop(1, 'rgba(255,220,150,0)');
ctx.fillStyle = lamp; ctx.fillRect(x, y, w, h);
// wet street and reflections
const st = ctx.createLinearGradient(0, y + h * 0.62, 0, y + h);
st.addColorStop(0, '#101826'); st.addColorStop(1, '#06090e');
ctx.fillStyle = st; ctx.fillRect(x, y + h * 0.62, w, h * 0.38);
for (let i = 0; i < 26; i++) {
const rx = x + rnd() * w, ry = y + h * 0.64 + rnd() * h * 0.34;
ctx.fillStyle = rnd() < 0.4 ? 'rgba(255,120,150,0.18)' : 'rgba(255,214,150,0.16)';
ctx.fillRect(rx, ry, 1.5 + rnd() * 2, 6 + rnd() * 16);
}
// the pole's glow on the glass (the stripes themselves spin in the scene)
const pg = ctx.createRadialGradient(POLE.x + POLE.w / 2, POLE.y + POLE.h / 2, 10, POLE.x + POLE.w / 2, POLE.y + POLE.h / 2, 170);
pg.addColorStop(0, 'rgba(255,90,90,0.35)'); pg.addColorStop(0.5, 'rgba(255,120,140,0.10)'); pg.addColorStop(1, 'rgba(255,120,140,0)');
ctx.fillStyle = pg; ctx.fillRect(x, y, w, h);
// the pole's chrome cap and base
ctx.fillStyle = chromeGrad(ctx, POLE.x - 6, POLE.x + POLE.w + 6);
rr(ctx, POLE.x - 6, POLE.y - 22, POLE.w + 12, 22, 8); ctx.fill();
ctx.beginPath(); ctx.arc(POLE.x + POLE.w / 2, POLE.y - 24, 12, Math.PI, 0); ctx.fill();
rr(ctx, POLE.x - 6, POLE.y + POLE.h, POLE.w + 12, 20, 6); ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.08)'; ctx.fillRect(POLE.x, POLE.y, POLE.w, POLE.h);
// raindrops beaded on the glass
for (let i = 0; i < 140; i++) {
const dx = x + rnd() * w, dy = y + rnd() * h, r = 0.8 + rnd() * 2.6;
ctx.fillStyle = 'rgba(200,220,255,0.22)'; ctx.beginPath(); ctx.arc(dx, dy, r, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.35)'; ctx.beginPath(); ctx.arc(dx - r * 0.3, dy - r * 0.3, r * 0.35, 0, Math.PI * 2); ctx.fill();
}
// gold-leaf lettering on the glass, read from inside (mirrored)
ctx.save();
ctx.translate(x + w / 2, y + h - 56); ctx.scale(-1, 1);
ctx.font = `bold 30px ${DISPLAY_FONT}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fillText("GUS'S BARBER SHOP", 2, 2);
ctx.fillStyle = brassGrad(ctx, -150, -16, 150, 16); ctx.fillText("GUS'S BARBER SHOP", 0, 0);
ctx.font = `italic 15px ${SERIF}`; ctx.fillStyle = 'rgba(230,200,130,0.85)';
ctx.fillText('est. 1938 · hot towel shaves', 0, 30);
ctx.restore();
ctx.restore();
// painted sash frame and mullions
shadowed(ctx, () => {
ctx.strokeStyle = '#d9cfb4'; ctx.lineWidth = 16; rr(ctx, x - 8, y - 8, w + 16, h + 16, 6); ctx.stroke();
}, { blur: 14, dx: 4, dy: 8, alpha: 0.6 });
ctx.strokeStyle = '#bfb396'; ctx.lineWidth = 3; rr(ctx, x - 1, y - 1, w + 2, h + 2, 4); ctx.stroke();
ctx.fillStyle = '#d9cfb4'; ctx.fillRect(x, y + h * 0.42 - 5, w, 10);
// chipped paint
for (let i = 0; i < 18; i++) {
const side = Math.floor(rnd() * 4);
const px = side < 2 ? x - 12 + rnd() * (w + 24) : (side === 2 ? x - 14 : x + w + 6);
const py = side >= 2 ? y - 12 + rnd() * (h + 24) : (side === 0 ? y - 14 : y + h + 6);
ctx.fillStyle = 'rgba(90,70,50,0.6)'; ctx.fillRect(px, py, 2 + rnd() * 6, 2 + rnd() * 4);
}
// sill
ctx.fillStyle = '#c8bc9e'; ctx.fillRect(x - 24, y + h + 8, w + 48, 12);
ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(x - 24, y + h + 20, w + 48, 6);
}
function priceCard(ctx) {
const cx = SIGN.x, cy = SIGN.y;
ctx.save();
ctx.translate(cx, cy); ctx.rotate(-0.012);
shadowed(ctx, () => { ctx.fillStyle = '#efe6cc'; ctx.fillRect(-170, -14, 340, 28); }, { blur: 6, dx: 2, dy: 3, alpha: 0.5 });
ctx.fillStyle = '#b0241c'; ctx.fillRect(-170, -14, 340, 4);
ctx.fillStyle = '#1a3a6a'; ctx.fillRect(-170, 10, 340, 4);
ctx.font = `bold 13px ${SERIF}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillStyle = '#2a1a10';
ctx.fillText('HAIRCUT 75¢ · SHAVE 50¢ · CHECKERS FREE', 0, 1);
ctx.fillStyle = '#9a9488'; ctx.beginPath(); ctx.arc(0, -20, 3, 0, Math.PI * 2); ctx.fill();
ctx.restore();
}
function barrel(ctx, rnd) {
// an upturned oak barrel; the board rests on its head
const R = 468, cx = BCX, cy = BCY + 16;
shadowed(ctx, () => { ctx.fillStyle = '#2a1608'; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); }, { blur: 40, dx: 0, dy: 20, alpha: 0.7 });
ctx.save();
ctx.beginPath(); ctx.arc(cx, cy, R - 18, 0, Math.PI * 2); ctx.clip();
const n = 9, sw = (R * 2) / n;
for (let i = 0; i < n; i++) {
const g = ctx.createLinearGradient(cx - R + i * sw, 0, cx - R + (i + 1) * sw, 0);
const t = rnd() * 0.15;
g.addColorStop(0, `rgba(${110 + t * 80},${66 + t * 40},${30},1)`); g.addColorStop(1, `rgba(${92 + t * 60},${54 + t * 30},${24},1)`);
ctx.fillStyle = g; ctx.fillRect(cx - R + i * sw, cy - R, sw, R * 2);
ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fillRect(cx - R + i * sw, cy - R, 2, R * 2);
}
grain(ctx, rnd, cx - R, cy - R, R * 2, R * 2, { tone: 'rgba(30,14,4,0.35)', lines: 80, wave: 4, vertical: true });
// a burned brand on the head
ctx.font = `bold 34px ${SERIF}`; ctx.textAlign = 'center'; ctx.fillStyle = 'rgba(30,12,2,0.35)';
ctx.fillText('OLD No. 7 · KENTUCKY', cx, cy + R - 70);
ctx.restore();
// iron hoop
ctx.strokeStyle = '#1c1a18'; ctx.lineWidth = 22; ctx.beginPath(); ctx.arc(cx, cy, R - 10, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = 'rgba(200,200,210,0.18)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(cx, cy, R - 18, Math.PI * 1.1, Math.PI * 1.7); ctx.stroke();
for (let a = 0; a < Math.PI * 2; a += Math.PI / 9) {
ctx.fillStyle = '#3a3634'; ctx.beginPath(); ctx.arc(cx + Math.cos(a) * (R - 10), cy + Math.sin(a) * (R - 10), 3, 0, Math.PI * 2); ctx.fill();
}
}
function shelf(ctx, rnd) {
const { x, y, w } = SHELF;
const top = 968;
// brackets + plank
ctx.fillStyle = '#2a180c'; ctx.fillRect(x + 40, top + 18, 14, 60); ctx.fillRect(x + w - 60, top + 18, 14, 60);
shadowed(ctx, () => {
const g = ctx.createLinearGradient(0, top, 0, top + 22);
g.addColorStop(0, '#7a5232'); g.addColorStop(1, '#4a2e18');
ctx.fillStyle = g; ctx.fillRect(x, top, w, 22);
}, { blur: 16, dx: 0, dy: 10, alpha: 0.7 });
grain(ctx, rnd, x, top, w, 22, { tone: 'rgba(20,8,0,0.4)', lines: 6, wave: 1 });
void y;
// cathedral radio
const rx = 1462, rw = 150, rh = 150, ry = top - rh;
shadowed(ctx, () => {
const g = ctx.createLinearGradient(rx, 0, rx + rw, 0);
g.addColorStop(0, '#4a2a12'); g.addColorStop(0.5, '#8a5428'); g.addColorStop(1, '#3a200c');
ctx.fillStyle = g;
ctx.beginPath(); ctx.moveTo(rx, top); ctx.lineTo(rx, ry + 70); ctx.arc(rx + rw / 2, ry + 70, rw / 2, Math.PI, 0); ctx.lineTo(rx + rw, top); ctx.closePath(); ctx.fill();
}, { blur: 12, dx: 4, dy: 6, alpha: 0.6 });
ctx.fillStyle = '#2a1a0c';
ctx.beginPath(); ctx.moveTo(rx + 22, top - 50); ctx.lineTo(rx + 22, ry + 74); ctx.arc(rx + rw / 2, ry + 74, rw / 2 - 22, Math.PI, 0); ctx.lineTo(rx + rw - 22, top - 50); ctx.closePath(); ctx.fill();
// speaker cloth and fretwork
ctx.fillStyle = 'rgba(200,160,100,0.22)';
for (let i = 0; i < 8; i++) ctx.fillRect(rx + 30 + i * 12, ry + 30, 4, 74);
// dial
const dial = ctx.createRadialGradient(rx + rw / 2, top - 30, 2, rx + rw / 2, top - 30, 18);
dial.addColorStop(0, '#ffe8a8'); dial.addColorStop(1, '#c08030');
ctx.fillStyle = dial; ctx.beginPath(); ctx.arc(rx + rw / 2, top - 30, 14, Math.PI, 0); ctx.fill();
ctx.strokeStyle = '#3a2a10'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(rx + rw / 2, top - 30); ctx.lineTo(rx + rw / 2 + 8, top - 40); ctx.stroke();
for (const kx of [rx + 34, rx + rw - 34]) {
ctx.fillStyle = '#1a0e06'; ctx.beginPath(); ctx.arc(kx, top - 22, 8, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = 'rgba(255,220,160,0.3)'; ctx.beginPath(); ctx.arc(kx - 2, top - 24, 3, 0, Math.PI * 2); ctx.fill();
}
// mantel clock
const cx = 1700, cy = top - 56;
shadowed(ctx, () => {
ctx.fillStyle = '#3a2210';
ctx.beginPath(); ctx.moveTo(cx - 62, top); ctx.lineTo(cx - 56, cy + 6); ctx.quadraticCurveTo(cx, cy - 76, cx + 56, cy + 6); ctx.lineTo(cx + 62, top); ctx.closePath(); ctx.fill();
}, { blur: 10, dx: 3, dy: 5, alpha: 0.6 });
ctx.fillStyle = brassGrad(ctx, cx - 34, cy - 34, cx + 34, cy + 34); ctx.beginPath(); ctx.arc(cx, cy, 34, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#f4ecd6'; ctx.beginPath(); ctx.arc(cx, cy, 28, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = '#2a1a10';
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
ctx.fillRect(cx + Math.cos(a) * 23 - 1, cy + Math.sin(a) * 23 - 1, 2.5, 2.5);
}
// twenty past ten
ctx.strokeStyle = '#1a0e06'; ctx.lineCap = 'round';
ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(-2.4) * 14, cy + Math.sin(-2.4) * 14); ctx.stroke();
ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(0.52) * 21, cy + Math.sin(0.52) * 21); ctx.stroke();
ctx.lineCap = 'butt';
// percolator
const px = 1832, pw = 74, pt = top - 150;
shadowed(ctx, () => {
ctx.fillStyle = chromeGrad(ctx, px - pw / 2, px + pw / 2);
ctx.beginPath(); ctx.moveTo(px - pw / 2 + 6, pt + 26); ctx.lineTo(px - pw / 2, top - 4); ctx.lineTo(px + pw / 2, top - 4); ctx.lineTo(px + pw / 2 - 6, pt + 26); ctx.closePath(); ctx.fill();
}, { blur: 12, dx: 4, dy: 6, alpha: 0.6 });
ctx.fillStyle = chromeGrad(ctx, px - pw / 2 + 6, px + pw / 2 - 6);
ctx.beginPath(); ctx.ellipse(px, pt + 26, pw / 2 - 6, 10, 0, 0, Math.PI * 2); ctx.fill();
// glass knob with coffee in it
const kg = ctx.createRadialGradient(px - 3, pt + 4, 1, px, pt + 8, 14);
kg.addColorStop(0, 'rgba(255,240,220,0.9)'); kg.addColorStop(0.5, 'rgba(140,80,30,0.85)'); kg.addColorStop(1, 'rgba(60,30,10,0.9)');
ctx.fillStyle = kg; ctx.beginPath(); ctx.arc(px, pt + 10, 12, Math.PI, 0); ctx.fill();
// handle + spout
ctx.strokeStyle = '#1a0e06'; ctx.lineWidth = 8; ctx.beginPath(); ctx.moveTo(px + pw / 2 - 4, pt + 40); ctx.quadraticCurveTo(px + pw / 2 + 26, pt + 70, px + pw / 2 - 2, top - 30); ctx.stroke();
ctx.strokeStyle = chromeGrad(ctx, px - pw / 2 - 20, px - pw / 2); ctx.lineWidth = 7;
ctx.beginPath(); ctx.moveTo(px - pw / 2 + 6, pt + 52); ctx.quadraticCurveTo(px - pw / 2 - 16, pt + 40, px - pw / 2 - 18, pt + 24); ctx.stroke();
// a chipped mug
const mx = 1770;
ctx.fillStyle = '#e8e0cc'; rr(ctx, mx - 20, top - 44, 40, 42, 4); ctx.fill();
ctx.strokeStyle = '#e8e0cc'; ctx.lineWidth = 5; ctx.beginPath(); ctx.arc(mx - 22, top - 24, 10, Math.PI * 0.5, Math.PI * 1.5); ctx.stroke();
ctx.fillStyle = '#b0241c'; ctx.fillRect(mx - 20, top - 34, 40, 5);
ctx.fillStyle = '#3a2010'; ctx.beginPath(); ctx.ellipse(mx, top - 44, 18, 4, 0, 0, Math.PI * 2); ctx.fill();
}
function lampPool(ctx) {
const lamp = ctx.createRadialGradient(BCX, BCY - 80, 80, BCX, BCY, 820);
lamp.addColorStop(0, 'rgba(255,214,150,0.20)'); lamp.addColorStop(0.5, 'rgba(255,190,120,0.07)'); lamp.addColorStop(1, 'rgba(255,190,120,0)');
ctx.fillStyle = lamp; ctx.fillRect(0, 0, W, H);
// the pole's red wash on the left wall
const red = ctx.createRadialGradient(WINDOW.x + WINDOW.w * 0.8, WINDOW.y + WINDOW.h / 2, 20, WINDOW.x + WINDOW.w * 0.8, WINDOW.y + WINDOW.h / 2, 520);
red.addColorStop(0, 'rgba(255,80,80,0.10)'); red.addColorStop(1, 'rgba(255,80,80,0)');
ctx.fillStyle = red; ctx.fillRect(0, 0, W, H);
const v = ctx.createRadialGradient(BCX, BCY, H * 0.42, BCX, BCY, H * 1.1);
v.addColorStop(0, 'rgba(0,0,0,0)'); v.addColorStop(1, 'rgba(4,4,6,0.75)');
ctx.fillStyle = v; ctx.fillRect(0, 0, W, H);
}
function bakeRoom(scene) {
{
const c = canvas(W, H), ctx = c.getContext('2d'), rnd = seeded(1938);
wall(ctx, rnd); wainscot(ctx, rnd); linoleum(ctx);
windowView(ctx, rnd); priceCard(ctx);
barrel(ctx, rnd); shelf(ctx, rnd); lampPool(ctx);
addCanvas(scene, 'ck-room', c);
}
{
const c = canvas(W, H), ctx = c.getContext('2d'), rnd = seeded(1938);
barrel(ctx, rnd); shelf(ctx, rnd);
addCanvas(scene, 'ck-props', c);
}
{
const c = canvas(W, H), ctx = c.getContext('2d');
lampPool(ctx);
addCanvas(scene, 'ck-vignette', c);
}
}
// ── board ────────────────────────────────────────────────────────────────────
function bakeBoard(scene) {
const S = BOARD_TEX, c = canvas(S + 40, S + 40), ctx = c.getContext('2d'), rnd = seeded(77);
const o = 20; // shadow margin
shadowed(ctx, () => { ctx.fillStyle = '#2a1608'; rr(ctx, o, o, S, S, 14); ctx.fill(); }, { blur: 26, dx: 6, dy: 14, alpha: 0.75 });
// walnut frame
const fg = ctx.createLinearGradient(o, o, o + S, o + S);
fg.addColorStop(0, '#5a3418'); fg.addColorStop(0.5, '#6e4220'); fg.addColorStop(1, '#3e2210');
ctx.fillStyle = fg; rr(ctx, o, o, S, S, 14); ctx.fill();
grain(ctx, rnd, o, o, S, FRAME, { tone: 'rgba(20,8,0,0.45)', lines: 12, wave: 2 });
grain(ctx, rnd, o, o + S - FRAME, S, FRAME, { tone: 'rgba(20,8,0,0.45)', lines: 12, wave: 2 });
grain(ctx, rnd, o, o, FRAME, S, { tone: 'rgba(20,8,0,0.45)', lines: 12, wave: 2, vertical: true });
grain(ctx, rnd, o + S - FRAME, o, FRAME, S, { tone: 'rgba(20,8,0,0.45)', lines: 12, wave: 2, vertical: true });
// mitred corners
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 1.5;
for (const [x0, y0, x1, y1] of [[o, o, o + FRAME, o + FRAME], [o + S, o, o + S - FRAME, o + FRAME], [o, o + S, o + FRAME, o + S - FRAME], [o + S, o + S, o + S - FRAME, o + S - FRAME]]) {
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.stroke();
}
ctx.strokeStyle = 'rgba(255,210,150,0.22)'; ctx.lineWidth = 2; rr(ctx, o + 3, o + 3, S - 6, S - 6, 12); ctx.stroke();
// inner bead
ctx.strokeStyle = '#1e1008'; ctx.lineWidth = 5; ctx.strokeRect(o + FRAME - 4, o + FRAME - 4, BOARD + 8, BOARD + 8);
ctx.strokeStyle = brassGrad(ctx, o, o, o + S, o + S); ctx.lineWidth = 2; ctx.strokeRect(o + FRAME - 7, o + FRAME - 7, BOARD + 14, BOARD + 14);
// brass corner pins
for (const [px, py] of [[o + 18, o + 18], [o + S - 18, o + 18], [o + 18, o + S - 18], [o + S - 18, o + S - 18]]) {
ctx.fillStyle = brassGrad(ctx, px - 6, py - 6, px + 6, py + 6); ctx.beginPath(); ctx.arc(px, py, 6, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(60,40,10,0.7)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(px - 4, py); ctx.lineTo(px + 4, py); ctx.stroke();
}
// squares
const x0 = o + FRAME, y0 = o + FRAME;
for (let r = 0; r < 8; r++) {
for (let col = 0; col < 8; col++) {
const dark = (r + col) % 2 === 1;
const x = x0 + col * SQ, y = y0 + r * SQ;
const g = ctx.createLinearGradient(x, y, x + SQ, y + SQ);
if (dark) { g.addColorStop(0, '#2e5a3a'); g.addColorStop(1, '#244a2f'); }
else { g.addColorStop(0, '#efe2bf'); g.addColorStop(1, '#e2d2a8'); }
ctx.fillStyle = g; ctx.fillRect(x, y, SQ, SQ);
// brush strokes in the paint
ctx.strokeStyle = dark ? 'rgba(10,30,15,0.25)' : 'rgba(150,120,70,0.12)'; ctx.lineWidth = 1;
for (let k = 0; k < 7; k++) { const yy = y + 6 + rnd() * (SQ - 12); ctx.beginPath(); ctx.moveTo(x + 3, yy); ctx.lineTo(x + SQ - 3, yy + (rnd() - 0.5) * 4); ctx.stroke(); }
if (dark) {
// worn where pieces slide: centre squares more than edges
const wear = 0.04 + 0.1 * (1 - Math.abs(r - 3.5) / 3.5) * (1 - Math.abs(col - 3.5) / 3.5);
const wg = ctx.createRadialGradient(x + SQ / 2, y + SQ / 2, 4, x + SQ / 2, y + SQ / 2, SQ * 0.55);
wg.addColorStop(0, `rgba(190,200,160,${wear})`); wg.addColorStop(1, 'rgba(190,200,160,0)');
ctx.fillStyle = wg; ctx.fillRect(x, y, SQ, SQ);
}
}
}
// fine paint line between squares
ctx.strokeStyle = 'rgba(30,20,10,0.35)'; ctx.lineWidth = 1;
for (let i = 0; i <= 8; i++) {
ctx.beginPath(); ctx.moveTo(x0 + i * SQ, y0); ctx.lineTo(x0 + i * SQ, y0 + BOARD); ctx.stroke();
ctx.beginPath(); ctx.moveTo(x0, y0 + i * SQ); ctx.lineTo(x0 + BOARD, y0 + i * SQ); ctx.stroke();
}
// scuffs and chips
for (let i = 0; i < 60; i++) {
const x = x0 + rnd() * BOARD, y = y0 + rnd() * BOARD;
ctx.strokeStyle = `rgba(${rnd() < 0.5 ? '255,250,230' : '20,15,5'},${0.06 + rnd() * 0.1})`; ctx.lineWidth = 0.8 + rnd();
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + (rnd() - 0.5) * 30, y + (rnd() - 0.5) * 12); ctx.stroke();
}
// a coffee ring on a light square near the corner
const ringX = x0 + SQ * 6.55, ringY = y0 + SQ * 0.5;
ctx.strokeStyle = 'rgba(110,60,20,0.22)'; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(ringX, ringY, 30, 0.3, Math.PI * 1.85); ctx.stroke();
ctx.strokeStyle = 'rgba(110,60,20,0.12)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(ringX + 1, ringY + 1, 26, 0, Math.PI * 2); ctx.stroke();
// old varnish sheen
const sh = ctx.createLinearGradient(o, o, o + S, o + S);
sh.addColorStop(0, 'rgba(255,240,200,0.10)'); sh.addColorStop(0.35, 'rgba(255,240,200,0)'); sh.addColorStop(0.6, 'rgba(255,240,200,0.05)'); sh.addColorStop(1, 'rgba(0,0,0,0.12)');
ctx.fillStyle = sh; ctx.fillRect(x0, y0, BOARD, BOARD);
ctx.fillStyle = noisePattern(ctx, 96, 14); ctx.fillRect(o, o, S, S);
addCanvas(scene, 'ck-board', c);
}
// ── pieces ───────────────────────────────────────────────────────────────────
function stampSymbol(ctx, color, x, y, r) {
ctx.save();
ctx.fillStyle = color === 'red' ? 'rgba(255,230,210,0.85)' : 'rgba(220,220,235,0.8)';
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 1;
if (color === 'red') {
// a five-point star
ctx.beginPath();
for (let i = 0; i < 10; i++) {
const a = -Math.PI / 2 + (i * Math.PI) / 5, rad = i % 2 ? r * 0.42 : r;
ctx.lineTo(x + Math.cos(a) * rad, y + Math.sin(a) * rad);
}
ctx.closePath(); ctx.fill(); ctx.stroke();
} else {
// a ring
ctx.lineWidth = r * 0.35; ctx.strokeStyle = 'rgba(220,220,235,0.8)';
ctx.beginPath(); ctx.arc(x, y, r * 0.75, 0, Math.PI * 2); ctx.stroke();
}
ctx.restore();
}
function crown(ctx, x, y, s) {
ctx.save();
ctx.translate(x, y);
const w = s * 1.25, h = s * 0.8;
const pts = [[-w / 2, h / 2], [-w / 2, -h / 2], [-w / 4, 0], [0, -h * 0.62], [w / 4, 0], [w / 2, -h / 2], [w / 2, h / 2]];
ctx.beginPath(); pts.forEach(([px, py], i) => (i ? ctx.lineTo(px, py) : ctx.moveTo(px, py))); ctx.closePath();
ctx.fillStyle = brassGrad(ctx, -w / 2, -h / 2, w / 2, h / 2); ctx.fill();
ctx.strokeStyle = 'rgba(60,40,8,0.85)'; ctx.lineWidth = 1.5; ctx.stroke();
for (const [px, py] of [[-w / 2, -h / 2], [0, -h * 0.62], [w / 2, -h / 2]]) {
ctx.fillStyle = '#fff0b0'; ctx.beginPath(); ctx.arc(px, py, s * 0.09, 0, Math.PI * 2); ctx.fill();
}
ctx.fillStyle = 'rgba(60,40,8,0.5)'; ctx.fillRect(-w / 2, h * 0.22, w, h * 0.12);
ctx.restore();
}
// One disc (top face at cy, side thickness below).
function disc(ctx, color, cx, cy, R, thick) {
const C = INK[color];
// side wall
const side = ctx.createLinearGradient(cx - R, 0, cx + R, 0);
side.addColorStop(0, C.rim); side.addColorStop(0.35, C.body); side.addColorStop(1, C.rim);
ctx.fillStyle = side;
ctx.beginPath(); ctx.arc(cx, cy + thick, R, 0, Math.PI * 2); ctx.fill();
ctx.fillRect(cx - R, cy, R * 2, thick);
// milled ridges on the side
ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 1.2 * RES;
for (let a = 0.08; a < Math.PI; a += 0.13) {
const x = cx + Math.cos(a) * R;
ctx.beginPath(); ctx.moveTo(x, cy + Math.sin(a) * R * 0.15); ctx.lineTo(x, cy + thick + Math.sin(a) * R); ctx.stroke();
}
// top face
const top = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R);
top.addColorStop(0, C.hi); top.addColorStop(0.25, C.body); top.addColorStop(1, C.rim);
ctx.fillStyle = top; ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill();
// milled rim on the face
ctx.strokeStyle = 'rgba(0,0,0,0.4)'; ctx.lineWidth = 1 * RES;
for (let a = 0; a < Math.PI * 2; a += Math.PI / 30) {
ctx.beginPath(); ctx.moveTo(cx + Math.cos(a) * R * 0.86, cy + Math.sin(a) * R * 0.86); ctx.lineTo(cx + Math.cos(a) * R * 0.98, cy + Math.sin(a) * R * 0.98); ctx.stroke();
}
// concentric grooves
for (const [f, a] of [[0.78, 0.5], [0.56, 0.35], [0.34, 0.3]]) {
ctx.strokeStyle = `rgba(0,0,0,${a})`; ctx.lineWidth = 1.6 * RES; ctx.beginPath(); ctx.arc(cx, cy, R * f, 0, Math.PI * 2); ctx.stroke();
ctx.strokeStyle = `rgba(255,255,255,${a * 0.35})`; ctx.lineWidth = 1 * RES; ctx.beginPath(); ctx.arc(cx, cy + RES, R * f, Math.PI * 0.1, Math.PI * 0.9); ctx.stroke();
}
// sheen
ctx.strokeStyle = 'rgba(255,255,255,0.28)'; ctx.lineWidth = 3 * RES;
ctx.beginPath(); ctx.arc(cx, cy, R * 0.9, Math.PI * 1.1, Math.PI * 1.45); ctx.stroke();
}
function bakePieces(scene) {
const R = PIECE_R * RES, T = PIECE_TEX;
for (const color of ['black', 'red']) {
for (const sym of [false, true]) {
const suffix = sym ? '-s' : '';
{
const c = canvas(T, T), ctx = c.getContext('2d');
disc(ctx, color, T / 2, T / 2 - 4 * RES, R, 7 * RES);
if (sym) stampSymbol(ctx, color, T / 2, T / 2 - 4 * RES, R * 0.28);
addCanvas(scene, `ck-man-${color}${suffix}`, c);
}
{
// a king is two checkers stacked
const c = canvas(T, T), ctx = c.getContext('2d');
disc(ctx, color, T / 2, T / 2 + 2 * RES, R, 7 * RES);
disc(ctx, color, T / 2, T / 2 - 12 * RES, R * 0.97, 7 * RES);
crown(ctx, T / 2, T / 2 - 13 * RES, R * 0.62);
if (sym) stampSymbol(ctx, color, T / 2 + R * 0.55, T / 2 - 13 * RES + R * 0.5, R * 0.18);
addCanvas(scene, `ck-king-${color}${suffix}`, c);
}
}
}
{
const S = PIECE_TEX, c = canvas(S, S), ctx = c.getContext('2d');
const g = ctx.createRadialGradient(S / 2, S / 2, R * 0.5, S / 2, S / 2, R * 1.15);
g.addColorStop(0, 'rgba(0,0,0,0.6)'); g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = g; ctx.fillRect(0, 0, S, S);
addCanvas(scene, 'ck-shadow', c);
}
}
// ── HUD 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'), rnd = seeded(5);
shadowed(ctx, () => { ctx.fillStyle = '#1a0e06'; rr(ctx, pad, pad, w, h, 12); ctx.fill(); }, { blur: 14, dx: 5, dy: 8, alpha: 0.65 });
const g = ctx.createLinearGradient(0, pad, 0, pad + h);
g.addColorStop(0, '#4a2c16'); g.addColorStop(1, '#2c180a');
ctx.fillStyle = g; rr(ctx, pad + 4, pad + 4, w - 8, h - 8, 10); ctx.fill();
grain(ctx, rnd, pad + 4, pad + 4, w - 8, h - 8, { tone: 'rgba(10,4,0,0.35)', lines: 18, wave: 3 });
ctx.strokeStyle = brassGrad(ctx, pad, pad, pad + w, pad + h); ctx.lineWidth = 2.5; rr(ctx, pad + 2, pad + 2, w - 4, h - 4, 11); ctx.stroke();
// barber stripe along the top edge
ctx.save(); rr(ctx, pad + 4, pad + 4, w - 8, 8, 4); ctx.clip();
for (let x = pad - 20; x < pad + w; x += 24) {
ctx.fillStyle = '#b0241c'; ctx.beginPath(); ctx.moveTo(x, pad + 12); ctx.lineTo(x + 8, pad + 4); ctx.lineTo(x + 16, pad + 4); ctx.lineTo(x + 8, pad + 12); ctx.fill();
ctx.fillStyle = '#1a3a6a'; ctx.beginPath(); ctx.moveTo(x + 12, pad + 12); ctx.lineTo(x + 20, pad + 4); ctx.lineTo(x + 24, pad + 4); ctx.lineTo(x + 16, pad + 12); ctx.fill();
}
ctx.restore();
// brass screws
for (const [sx, sy] of [[pad + 14, pad + 24], [pad + w - 14, pad + 24], [pad + 14, pad + h - 14], [pad + w - 14, pad + h - 14]]) {
ctx.fillStyle = brassGrad(ctx, sx - 4, sy - 4, sx + 4, sy + 4); ctx.beginPath(); ctx.arc(sx, sy, 4, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(50,30,5,0.8)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(sx - 3, sy - 1); ctx.lineTo(sx + 3, sy + 1); ctx.stroke();
}
addCanvas(scene, 'ck-plate', c);
}
{
const P = 40, c = canvas(w + P * 2, h + P * 2), ctx = c.getContext('2d');
ctx.shadowColor = 'rgba(255,200,110,1)'; ctx.shadowBlur = 30;
ctx.strokeStyle = 'rgba(255,215,130,0.95)'; ctx.lineWidth = 5; rr(ctx, P, P, w, h, 12); ctx.stroke();
ctx.shadowBlur = 0;
addCanvas(scene, 'ck-plate-glow', c);
}
}
// a ruled card tacked up with a brass pin
function bakeCard(scene, key, w, h, { ruled = false, header = null } = {}) {
const pad = 14, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(w + h * 3);
shadowed(ctx, () => { ctx.fillStyle = CREAM; rr(ctx, pad, pad, w, h, 4); ctx.fill(); }, { blur: 16, dx: 5, dy: 9, alpha: 0.6 });
const paper = ctx.createLinearGradient(0, pad, 0, pad + h);
paper.addColorStop(0, '#f6eed8'); paper.addColorStop(1, '#e6d9b8');
ctx.fillStyle = paper; rr(ctx, pad, pad, w, h, 4); ctx.fill();
ctx.save(); rr(ctx, pad, pad, w, h, 4); ctx.clip();
if (ruled) {
ctx.strokeStyle = 'rgba(70,110,170,0.28)'; ctx.lineWidth = 1;
for (let y = pad + 80; y < pad + h - 10; y += 31) { ctx.beginPath(); ctx.moveTo(pad + 8, y); ctx.lineTo(pad + w - 8, y); ctx.stroke(); }
ctx.strokeStyle = 'rgba(190,50,40,0.35)';
ctx.beginPath(); ctx.moveTo(pad + 66, pad + 50); ctx.lineTo(pad + 66, pad + h); ctx.stroke();
ctx.beginPath(); ctx.moveTo(pad + 66 + (w - 66) / 2, pad + 50); ctx.lineTo(pad + 66 + (w - 66) / 2, pad + h); ctx.stroke();
}
if (header) {
ctx.fillStyle = header; ctx.fillRect(pad, pad, w, 6);
}
// age: foxing spots and a dog-eared corner
for (let i = 0; i < 14; i++) {
const x = pad + rnd() * w, y = pad + rnd() * h, r = 2 + rnd() * 8;
ctx.fillStyle = `rgba(150,110,50,${0.04 + rnd() * 0.06})`; ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
}
ctx.fillStyle = noisePattern(ctx, 64, 14); ctx.fillRect(pad, pad, w, h);
ctx.restore();
ctx.fillStyle = '#d4c49e';
ctx.beginPath(); ctx.moveTo(pad + w - 22, pad + h); ctx.lineTo(pad + w, pad + h - 22); ctx.lineTo(pad + w - 22, pad + h - 22); ctx.closePath(); ctx.fill();
// pin
ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.beginPath(); ctx.arc(pad + w / 2 + 2, pad + 16, 7, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = brassGrad(ctx, pad + w / 2 - 6, pad + 8, pad + w / 2 + 6, pad + 20); ctx.beginPath(); ctx.arc(pad + w / 2, pad + 14, 6, 0, Math.PI * 2); ctx.fill();
addCanvas(scene, key, c);
}
function bakeRibbon(scene) {
const { w, h } = RIBBON, pad = 12, c = canvas(w + pad * 2, h + pad * 2), ctx = c.getContext('2d'), rnd = seeded(12);
shadowed(ctx, () => { ctx.fillStyle = '#20140a'; rr(ctx, pad, pad, w, h, 10); ctx.fill(); }, { blur: 14, dx: 3, dy: 7, alpha: 0.6 });
const g = ctx.createLinearGradient(0, pad, 0, pad + h);
g.addColorStop(0, '#3a2414'); g.addColorStop(1, '#22140a');
ctx.fillStyle = g; rr(ctx, pad, pad, w, h, 10); ctx.fill();
grain(ctx, rnd, pad, pad, w, h, { tone: 'rgba(0,0,0,0.25)', lines: 10, wave: 2 });
ctx.setLineDash([6, 5]); ctx.strokeStyle = 'rgba(230,200,140,0.4)'; ctx.lineWidth = 1.5; rr(ctx, pad + 6, pad + 6, w - 12, h - 12, 7); ctx.stroke(); ctx.setLineDash([]);
// Gus's badge: comb and scissors on a brass disc
const bx = pad + 40, by = pad + h / 2;
ctx.fillStyle = brassGrad(ctx, bx - 24, by - 24, bx + 24, by + 24); ctx.beginPath(); ctx.arc(bx, by, 24, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#3a2408'; ctx.lineWidth = 2.5;
ctx.beginPath(); ctx.moveTo(bx - 12, by - 12); ctx.lineTo(bx + 10, by + 8); ctx.moveTo(bx + 12, by - 12); ctx.lineTo(bx - 10, by + 8); ctx.stroke();
ctx.beginPath(); ctx.arc(bx - 11, by + 11, 4, 0, Math.PI * 2); ctx.arc(bx + 11, by + 11, 4, 0, Math.PI * 2); ctx.stroke();
addCanvas(scene, 'ck-ribbon', 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('ck-glow', 128, [[0, 'rgba(255,226,140,0.9)'], [0.45, 'rgba(255,200,90,0.45)'], [1, 'rgba(255,190,80,0)']]);
radial('ck-spark', 24, [[0, 'rgba(255,255,255,1)'], [0.35, 'rgba(255,240,200,0.8)'], [1, 'rgba(255,220,150,0)']]);
radial('ck-steam', 64, [[0, 'rgba(255,255,255,0.5)'], [1, 'rgba(255,255,255,0)']]);
radial('ck-pole-glow', 220, [[0, 'rgba(255,110,110,0.55)'], [0.5, 'rgba(255,140,150,0.18)'], [1, 'rgba(255,140,150,0)']]);
{
const S = 96, c = canvas(S, S), ctx = c.getContext('2d');
ctx.strokeStyle = 'rgba(255,224,130,1)'; ctx.lineWidth = 5;
ctx.beginPath(); ctx.arc(S / 2, S / 2, S / 2 - 5, 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 - 10, 0, Math.PI * 2); ctx.stroke();
addCanvas(scene, 'ck-ring', c);
}
{
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(225,225,225,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, 'ck-dot', c);
}
{
const c = canvas(3, 26), ctx = c.getContext('2d');
const g = ctx.createLinearGradient(0, 0, 0, 26);
g.addColorStop(0, 'rgba(200,220,255,0)'); g.addColorStop(1, 'rgba(220,235,255,0.7)');
ctx.fillStyle = g; ctx.fillRect(0, 0, 3, 26);
addCanvas(scene, 'ck-rain', c);
}
{
// pole stripes: red, white, blue bands on a diagonal; tiles vertically
const w = POLE.w, h = 96, c = canvas(w, h), ctx = c.getContext('2d');
ctx.fillStyle = '#f6f2ea'; ctx.fillRect(0, 0, w, h);
const band = (col, off) => {
ctx.fillStyle = col;
for (let k = -2; k < 3; k++) {
const y = off + k * h;
ctx.beginPath(); ctx.moveTo(0, y + 22); ctx.lineTo(w, y); ctx.lineTo(w, y + 20); ctx.lineTo(0, y + 42); ctx.closePath(); ctx.fill();
}
};
band('#c8201c', 8); band('#1c3a8a', 56);
const sh = ctx.createLinearGradient(0, 0, w, 0);
sh.addColorStop(0, 'rgba(0,0,0,0.45)'); sh.addColorStop(0.35, 'rgba(255,255,255,0.15)'); sh.addColorStop(0.55, 'rgba(255,255,255,0)'); sh.addColorStop(1, 'rgba(0,0,0,0.5)');
ctx.fillStyle = sh; ctx.fillRect(0, 0, w, h);
addCanvas(scene, 'ck-pole-stripes', c);
}
}
let baked = false;
export async function prepareCheckersArt(scene) {
try {
if (document.fonts?.load) {
await Promise.race([
Promise.all([document.fonts.load('20px Righteous'), document.fonts.load('14px "Julius Sans One"')]),
new Promise((res) => setTimeout(res, 1200)),
]);
}
} catch (_) { /* fall back to Georgia */ }
if (!baked || !scene.textures.exists('ck-room')) {
bakeRoom(scene); bakeBoard(scene); bakePieces(scene); bakePlate(scene);
bakeCard(scene, 'ck-card-status', STATUS.w, STATUS.h, { header: '#b0241c' });
bakeCard(scene, 'ck-card-log', LOG.w, LOG.h, { ruled: true });
bakeRibbon(scene); bakeBits(scene);
baked = true;
}
}
export const BOARD_POS = { x: BX - FRAME - 20, y: BY - FRAME - 20 };

View File

@ -0,0 +1,36 @@
// CheckersData.js — the three-move ballot. Tournament checkers draws an
// opening at random so nobody can lean on a memorised line; Gus keeps a
// cigar box of ballot cards. Each card is Black's move, Red's reply and
// Black's second move, labelled with the opening family it belongs to.
// (American rules only — tools/verifyCheckers.js checks each is legal.)
export const BALLOTS = [
{ name: 'Edinburgh', moves: ['9-13', '22-18', '10-15'] },
{ name: 'Edinburgh', moves: ['9-13', '23-19', '11-16'] },
{ name: 'Double Corner', moves: ['9-14', '22-18', '5-9'] },
{ name: 'Double Corner', moves: ['9-14', '22-17', '11-15'] },
{ name: 'Denny', moves: ['10-14', '22-18', '11-16'] },
{ name: 'Denny', moves: ['10-14', '24-19', '6-10'] },
{ name: 'Kelso', moves: ['10-15', '21-17', '9-13'] },
{ name: 'Kelso Cross', moves: ['10-15', '23-18', '6-10'] },
{ name: 'Single Corner', moves: ['11-15', '22-18', '15x22'] },
{ name: 'Cross', moves: ['11-15', '23-18', '8-11'] },
{ name: 'Dyke', moves: ['11-15', '22-17', '15-19'] },
{ name: 'Old Fourteenth', moves: ['11-15', '23-19', '8-11'] },
{ name: 'Will o\' the Wisp', moves: ['11-15', '23-19', '9-13'] },
{ name: 'Souter', moves: ['11-15', '23-19', '9-14'] },
{ name: 'Second Double Corner', moves: ['11-15', '24-19', '15x24'] },
{ name: 'Ayrshire Lassie', moves: ['11-15', '24-20', '8-11'] },
{ name: 'Switcher', moves: ['11-15', '21-17', '9-13'] },
{ name: 'Bristol', moves: ['11-16', '24-20', '16-19'] },
{ name: 'Bristol Cross', moves: ['11-16', '23-18', '16-20'] },
{ name: 'Paisley', moves: ['11-16', '24-19', '8-11'] },
{ name: 'Dundee', moves: ['12-16', '24-20', '8-12'] },
{ name: 'Dundee', moves: ['12-16', '21-17', '9-13'] },
];
export function drawBallot(rng = Math.random, exclude = []) {
const pool = BALLOTS.map((b, i) => i).filter((i) => !exclude.includes(i));
const list = pool.length ? pool : BALLOTS.map((b, i) => i);
return list[Math.floor(rng() * list.length)];
}

View File

@ -0,0 +1,151 @@
// CheckersDialogs.js — back-room pop-ups: a cream card in a walnut frame
// with a barber-stripe header. 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 './CheckersArt.js';
import { VARIANTS, VARIANT_ORDER } from './CheckersLogic.js';
const INK = '#3a1a0c';
const BTN_BG = 0x4a2c16;
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, 14);
g.fillStyle(0x3a2212, 1).fillRoundedRect(x, y, w, h, 14);
g.lineStyle(3, 0xd8b060, 1).strokeRoundedRect(x + 5, y + 5, w - 10, h - 10, 11);
g.fillStyle(0xf3ead2, 1).fillRoundedRect(x + 14, y + 14, w - 28, h - 28, 6);
// barber stripe header
const sx = x + 14, sw = w - 28;
for (let i = 0; i < sw; i += 30) {
const ww = Math.min(30, sw - i);
g.fillStyle(0xb0241c, 1).fillRect(sx + i, y + 14, Math.min(10, ww), 8);
if (ww > 10) g.fillStyle(0xf3ead2, 1).fillRect(sx + i + 10, y + 14, Math.min(10, ww - 10), 8);
if (ww > 20) g.fillStyle(0x1c3a8a, 1).fillRect(sx + i + 20, y + 14, ww - 20, 8);
}
g.lineStyle(1.5, 0x8a6a3a, 0.6).strokeRoundedRect(x + 22, y + 30, w - 44, h - 52, 4);
return g;
}
export function blocker(scene, depth, alpha = 0) {
return scene.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x050302, alpha).setDepth(depth).setInteractive();
}
export function handle(objs, onClose) {
let closed = false;
return { objs, close() { if (closed) return; closed = true; objs.forEach((o) => o?.destroy?.()); onClose?.(); } };
}
const onOff = (v) => (v ? 'On' : 'Off');
const PACE = { relaxed: 'Relaxed', normal: 'Normal', fast: 'Fast' };
export function openPauseMenu(scene, { settings, depth, onChange, onRules, onNewMatch, onLeave, onClose }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 620, h = 820;
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, 'The Back Room', { 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)],
[() => `Show legal moves: ${onOff(settings.hints)}`, () => onChange('hints', !settings.hints)],
[() => `Gus warns before a bad move: ${onOff(settings.coach)}`, () => onChange('coach', !settings.coach)],
[() => `Show threatened pieces: ${onOff(settings.threats)}`, () => onChange('threats', !settings.threats)],
[() => `Square numbers: ${onOff(settings.numbers)}`, () => onChange('numbers', !settings.numbers)],
[() => `Colour-blind stamps on checkers: ${onOff(settings.symbols)}`, () => onChange('symbols', !settings.symbols)],
[() => `Rain & shop sounds: ${onOff(settings.ambience)}`, () => onChange('ambience', !settings.ambience)],
['How to Play', () => onRules()],
['New Match…', () => { hRef.close(); onNewMatch(); }, 0x6a4a1a],
['Leave the Shop', () => { hRef.close(); onLeave(); }, 0x7a1a14],
];
rows.forEach(([label, fn, bg], i) => {
const text = typeof label === 'function' ? label() : label;
const btn = new Button(scene, cx, y + 128 + i * 52, text, () => { fn(); if (typeof label === 'function') btn.setLabel(label()); }, {
width: 540, height: 44, fontSize: 16, bg: bg ?? BTN_BG,
}).setDepth(depth + 2);
objs.push(btn);
});
objs.push(scene.add.text(cx, y + h - 52, 'Keys: click or drag a checker · Z undo · H hint · F flip board\nArrows + Enter to move with the keyboard · Esc menu', {
fontFamily: SERIF, fontSize: '13px', fontStyle: 'italic', color: '#4a3a22', align: 'center',
}).setOrigin(0.5).setDepth(depth + 1));
hRef = handle(objs, onClose);
return hRef;
}
/**
* The match setup card. `prefs` = { variant, games, color, openings, quietLimit }.
*/
export function openSetup(scene, { prefs, depth, opponentName, onStart, onLeave }) {
const objs = [blocker(scene, depth - 1, 0.6)];
const w = 760, h = 720;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
const p = { ...prefs };
const cx = x + w / 2;
objs.push(scene.add.text(cx, y + 68, 'Set Up the Board', { fontFamily: DISPLAY_FONT, fontSize: '34px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(cx, y + 108, `You against ${opponentName}. Gus keeps score.`, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0.5).setDepth(depth + 1));
const labelX = x + 70, ctlX = x + 470;
const rowY = (i) => y + 172 + i * 84;
const rows = [];
const addRow = (i, title, get, fn) => {
objs.push(scene.add.text(labelX, rowY(i), title, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: INK }).setOrigin(0, 0.5).setDepth(depth + 1));
const btn = new Button(scene, ctlX, rowY(i), get(), () => { fn(); refresh(); }, { width: 360, height: 46, fontSize: 18, bg: BTN_BG }).setDepth(depth + 2);
objs.push(btn);
rows.push({ btn, get });
};
const cyc = (list, v) => list[(list.indexOf(v) + 1) % list.length];
addRow(0, 'Rules', () => VARIANTS[p.variant].name, () => { p.variant = cyc(VARIANT_ORDER, p.variant); });
addRow(1, 'Match', () => (p.games === 1 ? 'Single game' : `Best of ${p.games}`), () => { p.games = cyc([1, 3, 5], p.games); });
addRow(2, 'Your colour', () => {
if (p.color === 'random') return 'Toss a coin';
const first = VARIANTS[p.variant].first === p.color;
return `${p.color === 'red' ? 'Red' : 'Black'} (moves ${first ? 'first' : 'second'})`;
}, () => { p.color = cyc(['red', 'black', 'random'], p.color); });
addRow(3, 'Classic openings', () => (p.variant !== 'american' ? 'American only' : p.openings ? 'On — three-move ballot' : 'Off — free opening'), () => { if (p.variant === 'american') p.openings = !p.openings; });
addRow(4, 'Draw after', () => `${p.quietLimit} moves without progress`, () => { p.quietLimit = cyc([25, 40, 50], p.quietLimit); });
const blurb = scene.add.text(cx, y + 600, '', { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 120 } })
.setOrigin(0.5).setDepth(depth + 1);
objs.push(blurb);
function refresh() {
rows.forEach((r) => r.btn.setLabel(r.get()));
let b = VARIANTS[p.variant].blurb;
if (p.variant === 'american' && p.openings) b += ' A ballot card picks the first three moves; in a match each opening is played twice, colours swapped.';
if (p.games > 1) b += ' Colours alternate each game; a draw scores half.';
blurb.setText(b);
}
refresh();
let hRef = null;
objs.push(new Button(scene, cx - 130, y + h - 62, 'Rack \'Em Up', () => { hRef.close(); onStart(p); }, { width: 230, height: 50, fontSize: 20, bg: 0x1f6a3a }).setDepth(depth + 2));
objs.push(new Button(scene, cx + 130, y + h - 62, 'Leave', () => { hRef.close(); onLeave(); }, { width: 230, height: 50, fontSize: 20, bg: 0x7a1a14 }).setDepth(depth + 2));
hRef = handle(objs);
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 = 560, h = 290;
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 + 70, heading, { fontFamily: DISPLAY_FONT, fontSize: '26px', color: INK }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 138, 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 - 124, y + h - 62, yes, () => { hRef.close(); onYes?.(); }, { width: 220, height: 46, fontSize: 18, bg: 0x7a1a14 }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 124, y + h - 62, no, () => { hRef.close(); onNo?.(); }, { width: 220, 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 = 960, ms = 2200 } = {}) {
const t = scene.add.text(x, y, text, { fontFamily: SERIF, fontSize: '20px', color: '#2a1a10', backgroundColor: '#f3ead2', 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,191 @@
// CheckersEndScreen.js — after a game: the between-games card (result,
// match tally, Next Game); after a match: the full summary — result, every
// game of the match, the last game's stats, a material sparkline, your
// lifetime record against this opponent, and a replay board you can step
// through move by move.
import { Button } from '../../ui/Button.js';
import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js';
import { DISPLAY_FONT, SERIF, INK } from './CheckersArt.js';
import { frame, blocker, handle } from './CheckersDialogs.js';
import { boardAfter, materialTrace, stats, RC, rulesOf, VARIANTS } from './CheckersLogic.js';
const half = (x) => (x % 1 ? `${Math.floor(x) || ''}½` : String(x));
export const REASON = {
wiped: 'every piece was taken',
blocked: 'no legal move was left',
repetition: 'the same position came up three times',
quiet: 'nobody made progress (no jumps, no man moves)',
agreed: 'both sides agreed',
resign: 'resignation',
cap: 'the game ran out the clock',
};
export function resultLine(gs, humanColor, oppName) {
if (gs.winner === 'draw') return { title: 'A draw', good: null, why: `Drawn — ${REASON[gs.endReason] ?? ''}.` };
const won = gs.winner === humanColor;
const g = rulesOf(gs.variant).giveaway;
let why = REASON[gs.endReason] ?? '';
if (gs.endReason === 'resign') why = won ? `${oppName} resigned` : 'you resigned';
else if (g && (gs.endReason === 'wiped' || gs.endReason === 'blocked')) why = `giveaway — ${gs.endReason === 'wiped' ? 'every piece given away' : 'no move left'}, and that wins`;
return { title: won ? 'You win!' : `${oppName} wins`, good: won, why: `${why.charAt(0).toUpperCase()}${why.slice(1)}.` };
}
/** Between games of a match. */
export function openBetween(scene, { gs, humanColor, oppName, match, depth, onNext, onLeave }) {
const objs = [blocker(scene, depth - 1, 0.45)];
const w = 620, h = 360;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
const r = resultLine(gs, humanColor, oppName);
objs.push(scene.add.text(x + w / 2, y + 76, `Game ${match.results.length}: ${r.title}`, { fontFamily: DISPLAY_FONT, fontSize: '30px', color: r.good === null ? INK.black.text : r.good ? '#1f6a3a' : '#8e1c16' }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 122, r.why, { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#4a3a22', align: 'center', wordWrap: { width: w - 80 } }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 180, `Match — You ${half(match.human) || '0'} · ${oppName} ${half(match.ai) || '0'} (best of ${match.games})`, { fontFamily: DISPLAY_FONT, fontSize: '20px', color: '#3a1a0c' }).setOrigin(0.5).setDepth(depth + 1));
objs.push(scene.add.text(x + w / 2, y + 216, 'Colours swap for the next game.', { fontFamily: SERIF, fontSize: '15px', fontStyle: 'italic', color: '#5a4a32' }).setOrigin(0.5).setDepth(depth + 1));
let hRef = null;
objs.push(new Button(scene, x + w / 2 - 125, y + h - 62, 'Next Game', () => { hRef.close(); onNext(); }, { width: 220, height: 48, fontSize: 19, bg: 0x1f6a3a }).setDepth(depth + 2));
objs.push(new Button(scene, x + w / 2 + 125, y + h - 62, 'Leave', () => { hRef.close(); onLeave(); }, { width: 220, height: 48, fontSize: 19, bg: 0x7a1a14 }).setDepth(depth + 2));
hRef = handle(objs);
return hRef;
}
/** The match summary. */
export function openEndScreen(scene, { gs, humanColor, oppName, match, record, depth, symbols, onPlayAgain, onMenu }) {
const objs = [blocker(scene, depth - 1, 0.55)];
const w = 1240, h = 820;
const x = GAME_WIDTH / 2 - w / 2, y = GAME_HEIGHT / 2 - h / 2;
objs.push(frame(scene, x, y, w, h, depth));
const add = (o) => { objs.push(o); return o; };
const D1 = depth + 1;
// headline
let title, color;
const multi = match.games > 1;
if (multi) {
if (match.human > match.ai) { title = 'You take the match!'; color = '#1f6a3a'; }
else if (match.ai > match.human) { title = `${oppName} takes the match`; color = '#8e1c16'; }
else { title = 'The match is drawn'; color = '#3a1a0c'; }
} else {
const r = resultLine(gs, humanColor, oppName);
title = r.title; color = r.good === null ? '#3a1a0c' : r.good ? '#1f6a3a' : '#8e1c16';
}
add(scene.add.text(x + w / 2, y + 70, title, { fontFamily: DISPLAY_FONT, fontSize: '38px', color }).setOrigin(0.5).setDepth(D1));
const sub = multi
? `You ${half(match.human) || '0'} — ${oppName} ${half(match.ai) || '0'} · ${VARIANTS[gs.variant].name}`
: `${resultLine(gs, humanColor, oppName).why} · ${VARIANTS[gs.variant].name}${gs.ballot ? ` · ${gs.ballot.name}` : ''}`;
add(scene.add.text(x + w / 2, y + 114, sub, { fontFamily: SERIF, fontSize: '18px', fontStyle: 'italic', color: '#4a3a22' }).setOrigin(0.5).setDepth(D1));
// left: games list + stats
const lx = x + 70;
let ly = y + 168;
const g = add(scene.add.graphics().setDepth(D1));
if (multi) {
add(scene.add.text(lx, ly, 'THE MATCH', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#5a2a12' }).setOrigin(0, 0.5).setDepth(D1));
ly += 30;
match.results.forEach((r, i) => {
const res = r.result === 'human' ? 'You won' : r.result === 'ai' ? `${oppName} won` : 'Draw';
const col = r.result === 'human' ? '#1f6a3a' : r.result === 'ai' ? '#8e1c16' : '#3a2a1a';
add(scene.add.text(lx, ly, `Game ${i + 1} · you played ${r.humanColor} · ${res} · ${r.moves} moves${r.ballot ? ` · ${r.ballot}` : ''}`, { fontFamily: SERIF, fontSize: '16px', color: col }).setOrigin(0, 0.5).setDepth(D1));
ly += 28;
});
ly += 14;
}
add(scene.add.text(lx, ly, multi ? 'LAST GAME' : 'THE GAME', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#5a2a12' }).setOrigin(0, 0.5).setDepth(D1));
ly += 30;
const you = stats(gs, humanColor), them = stats(gs, humanColor === 'black' ? 'red' : 'black');
const rows = [
['Moves', you.moves, them.moves],
['Pieces taken', you.captures, them.captures],
['Longest jump', you.longest ? `${you.longest}` : '—', them.longest ? `${them.longest}` : '—'],
['Kings crowned', you.kings, them.kings],
];
const c1 = lx + 260, c2 = lx + 380;
add(scene.add.text(c1, ly, 'YOU', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#3a1a0c' }).setOrigin(0.5).setDepth(D1));
add(scene.add.text(c2, ly, oppName.toUpperCase().slice(0, 10), { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#3a1a0c' }).setOrigin(0.5).setDepth(D1));
rows.forEach(([label, a, b], i) => {
const yy = ly + 30 + i * 28;
if (i % 2 === 0) g.fillStyle(0x8a5a2a, 0.08).fillRect(lx - 10, yy - 13, 450, 26);
add(scene.add.text(lx, yy, label, { fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a' }).setOrigin(0, 0.5).setDepth(D1));
add(scene.add.text(c1, yy, String(a), { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D1));
add(scene.add.text(c2, yy, String(b), { fontFamily: SERIF, fontSize: '16px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D1));
});
ly += 30 + rows.length * 28 + 20;
// material sparkline (your side up)
const trace = materialTrace(gs).map((v) => (humanColor === 'black' ? v : -v));
const sw = 450, sh = 110, sx = lx - 10, sy = ly;
add(scene.add.text(lx, sy - 4, 'MATERIAL (your side above the line)', { fontFamily: DISPLAY_FONT, fontSize: '13px', color: '#5a2a12' }).setOrigin(0, 1).setDepth(D1));
g.fillStyle(0xffffff, 0.35).fillRect(sx, sy + 6, sw, sh);
const maxAbs = Math.max(2, ...trace.map(Math.abs));
const mid = sy + 6 + sh / 2;
g.lineStyle(1, 0x8a6a3a, 0.6).lineBetween(sx, mid, sx + sw, mid);
if (trace.length > 1) {
g.lineStyle(2.5, 0x8e1c16, 1);
g.beginPath();
trace.forEach((v, i) => {
const px = sx + (i / (trace.length - 1)) * sw, py = mid - (v / maxAbs) * (sh / 2 - 6);
if (i === 0) g.moveTo(px, py); else g.lineTo(px, py);
});
g.strokePath();
}
ly = sy + sh + 34;
if (record) {
add(scene.add.text(lx, ly, `Your record against ${oppName}: ${record.w} won · ${record.d} drawn · ${record.l} lost`, { fontFamily: SERIF, fontSize: '16px', fontStyle: 'italic', color: '#3a2a1a' }).setOrigin(0, 0.5).setDepth(D1));
}
// right: replay board
const RS = 46, rx = x + w - 70 - RS * 8, ry = y + 176;
add(scene.add.text(rx + RS * 4, ry - 22, 'REPLAY', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#5a2a12' }).setOrigin(0.5).setDepth(D1));
const bg = add(scene.add.graphics().setDepth(D1));
for (let r = 0; r < 8; r++) {
for (let c = 0; c < 8; c++) {
bg.fillStyle((r + c) % 2 ? 0x2e5a3a : 0xe9dcb8, 1).fillRect(rx + c * RS, ry + r * RS, RS, RS);
}
}
bg.lineStyle(4, 0x4a2c16, 1).strokeRect(rx - 2, ry - 2, RS * 8 + 4, RS * 8 + 4);
const pg = add(scene.add.graphics().setDepth(D1 + 1));
const flipped = humanColor === 'black';
const label = add(scene.add.text(rx + RS * 4, ry + RS * 8 + 30, '', { fontFamily: SERIF, fontSize: '17px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D1));
let n = gs.history.length;
const draw = () => {
pg.clear();
const b = boardAfter(gs, n);
const last = n > 0 ? gs.history[n - 1] : null;
if (last) {
for (const sq of [last.from, last.to]) {
const [r, c] = RC[sq];
const vr = flipped ? 7 - r : r, vc = flipped ? 7 - c : c;
pg.fillStyle(0xffd060, 0.35).fillRect(rx + vc * RS, ry + vr * RS, RS, RS);
}
}
b.forEach((p, sq) => {
if (!p) return;
const [r, c] = RC[sq];
const vr = flipped ? 7 - r : r, vc = flipped ? 7 - c : c;
const cx = rx + vc * RS + RS / 2, cy = ry + vr * RS + RS / 2;
pg.fillStyle(0x000000, 0.35).fillCircle(cx + 2, cy + 3, RS * 0.38);
pg.fillStyle(p > 0 ? 0x1d1c22 : 0xb52a22, 1).fillCircle(cx, cy, RS * 0.38);
pg.lineStyle(1.5, p > 0 ? 0x5a5868 : 0xff8a70, 0.8).strokeCircle(cx, cy, RS * 0.26);
if (p === 2 || p === -2) pg.fillStyle(0xe8c46a, 1).fillCircle(cx, cy, RS * 0.13);
});
const hist = last ? `${last.color === 'black' ? 'Black' : 'Red'} ${last.n}${last.ballot ? ' (ballot)' : ''}` : 'Starting position';
label.setText(`Move ${n} of ${gs.history.length} — ${hist}`);
void symbols;
};
draw();
const by = ry + RS * 8 + 76;
const step = (d) => { n = Math.max(0, Math.min(gs.history.length, n + d)); draw(); };
add(new Button(scene, rx + RS * 4 - 165, by, '|◀', () => { n = 0; draw(); }, { width: 70, height: 42, fontSize: 18, bg: 0x4a2c16 }).setDepth(D1 + 1));
add(new Button(scene, rx + RS * 4 - 80, by, '◀', () => step(-1), { width: 80, height: 42, fontSize: 18, bg: 0x4a2c16 }).setDepth(D1 + 1));
add(new Button(scene, rx + RS * 4 + 10, by, '▶', () => step(1), { width: 80, height: 42, fontSize: 18, bg: 0x4a2c16 }).setDepth(D1 + 1));
add(new Button(scene, rx + RS * 4 + 95, by, '▶|', () => { n = gs.history.length; draw(); }, { width: 70, height: 42, fontSize: 18, bg: 0x4a2c16 }).setDepth(D1 + 1));
const keys = (e) => { if (e.key === 'ArrowLeft') step(-1); else if (e.key === 'ArrowRight') step(1); };
scene.input.keyboard?.on('keydown', keys);
const bty = y + h - 64;
let hRef = null;
add(new Button(scene, x + w / 2 - 140, bty, multi ? 'New Match' : 'Play Again', () => { hRef.close(); onPlayAgain(); }, { width: 250, height: 52, fontSize: 20, bg: 0x1f6a3a }).setDepth(D1 + 1));
add(new Button(scene, x + w / 2 + 140, bty, 'Leave the Shop', () => { hRef.close(); onMenu(); }, { width: 250, height: 52, fontSize: 20, bg: 0x7a1a14 }).setDepth(D1 + 1));
hRef = handle(objs, () => scene.input.keyboard?.off('keydown', keys));
return hRef;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,225 @@
// CheckersHud.js — the furniture around the barrel: a walnut plaque per
// player (portrait, name, skill, a note line, pieces / kings / clock, the
// match tally, their colour), captured-checker trays, the status card, the
// move sheet, the buttons, the opponent's speech bubble and Gus's ribbon.
import { Button } from '../../ui/Button.js';
import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js';
import {
PLATES, PLATE, plateParts, TRAYS, BUBBLE, STATUS, LOG, LOG_ROWS, BUTTONS, BTN, RIBBON,
} from './CheckersLayout.js';
import { DISPLAY_FONT, SERIF, INK } from './CheckersArt.js';
import { counts, rulesOf, other } from './CheckersLogic.js';
const short = (s, n = 14) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
const clock = (ms) => { const s = Math.floor(ms / 1000); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
const half = (x) => (x % 1 ? `${Math.floor(x) || ''}½` : String(x));
export class Hud {
constructor(scene, depth, { names, skill, opponent, onButton }) {
this.scene = scene;
this.depth = depth;
this.names = names; // { top, bottom }
this.skill = skill;
this.opponent = opponent;
this.onButton = onButton;
this.plates = {};
this.buttons = {};
this.bubble = null;
this.trayObjs = { top: [], bottom: [] };
this.symbols = false;
}
build() {
const s = this.scene, D = this.depth;
for (const side of ['top', 'bottom']) {
const P = PLATES[side], parts = plateParts(side);
const glow = s.add.image(P.x - 40, P.y - 40, 'ck-plate-glow').setOrigin(0).setDepth(D - 1).setAlpha(0);
s.add.image(P.x - 14, P.y - 14, 'ck-plate').setOrigin(0).setDepth(D);
const pp = parts.portrait;
const ring = s.add.circle(pp.x, pp.y, pp.r + 5, 0xd8b060, 1).setDepth(D + 1);
const portrait = side === 'bottom'
? createPlayerPortrait(s, pp.x, pp.y, pp.r, D + 2, 'CheckersGame')
: createOpponentPortrait(s, this.opponent ?? { id: 'bot', spriteIndex: 0 }, pp.x, pp.y, pp.r, D + 2);
s.add.text(parts.name.x, parts.name.y, short(this.names[side], side === 'top' ? 13 : 16), {
fontFamily: DISPLAY_FONT, fontSize: '22px', color: '#f8ead0',
}).setOrigin(0, 0.5).setDepth(D + 1);
if (side === 'top') {
const k = this.skill;
s.add.text(parts.skill.x, parts.skill.y, '●'.repeat(k) + '○'.repeat(5 - k), { fontFamily: SERIF, fontSize: '13px', color: '#e8c46a' })
.setOrigin(1, 0.5).setDepth(D + 1);
}
const note = s.add.text(parts.note.x, parts.note.y, '', { fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#e0caa0' })
.setOrigin(0, 0.5).setDepth(D + 1);
const line = s.add.text(parts.line.x, parts.line.y, '', { fontFamily: SERIF, fontSize: '15px', color: '#d8c4a0' })
.setOrigin(0, 0.5).setDepth(D + 1);
const chip = s.add.image(parts.color.x, parts.color.y, 'ck-man-red').setScale(0.2).setDepth(D + 1).setVisible(false);
const chipText = s.add.text(parts.color.x + 20, parts.color.y, '', { fontFamily: SERIF, fontSize: '14px', color: '#d8c4a0' })
.setOrigin(0, 0.5).setDepth(D + 1);
const tally = s.add.text(parts.tally.x, parts.tally.y, '', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#f0d890' })
.setOrigin(1, 0.5).setDepth(D + 1);
this.plates[side] = { glow, ring, portrait, note, line, chip, chipText, tally, active: false };
}
// status card
s.add.image(STATUS.x - 14, STATUS.y - 14, 'ck-card-status').setOrigin(0).setDepth(D);
this.status = s.add.text(STATUS.x + STATUS.w / 2, STATUS.y + 66, '', {
fontFamily: DISPLAY_FONT, fontSize: '27px', color: '#3a1a0c', 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 + 136, '', {
fontFamily: SERIF, fontSize: '16px', color: '#3a2a1a', align: 'center', wordWrap: { width: STATUS.w - 56 }, lineSpacing: 3,
}).setOrigin(0.5).setDepth(D + 1);
// move sheet
s.add.image(LOG.x - 14, LOG.y - 14, 'ck-card-log').setOrigin(0).setDepth(D);
this.logTitle = s.add.text(LOG.x + 24, LOG.y + 34, 'MOVE SHEET', { fontFamily: DISPLAY_FONT, fontSize: '16px', color: '#5a2a12' }).setOrigin(0, 0.5).setDepth(D + 1);
this.logSub = s.add.text(LOG.x + LOG.w - 24, LOG.y + 34, '', { fontFamily: SERIF, fontSize: '14px', fontStyle: 'italic', color: '#5a2a12' }).setOrigin(1, 0.5).setDepth(D + 1);
const colA = LOG.x + 66 + (LOG.w - 66) / 4, colB = LOG.x + 66 + ((LOG.w - 66) * 3) / 4;
this.colHead = [
s.add.text(colA, LOG.y + 62, '', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#3a1a0c' }).setOrigin(0.5).setDepth(D + 1),
s.add.text(colB, LOG.y + 62, '', { fontFamily: DISPLAY_FONT, fontSize: '14px', color: '#3a1a0c' }).setOrigin(0.5).setDepth(D + 1),
];
this.rows = [];
for (let i = 0; i < LOG_ROWS; i++) {
const y = LOG.y + 96 + i * 31;
this.rows.push({
n: s.add.text(LOG.x + 50, y, '', { fontFamily: SERIF, fontSize: '15px', color: '#7a5a3a' }).setOrigin(1, 0.5).setDepth(D + 1),
a: s.add.text(colA, y, '', { fontFamily: SERIF, fontSize: '17px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D + 1),
b: s.add.text(colB, y, '', { fontFamily: SERIF, fontSize: '17px', color: '#2a1a10' }).setOrigin(0.5).setDepth(D + 1),
});
}
// buttons
const label = { undo: 'Undo (Z)', hint: 'Hint (H)', draw: 'Offer Draw', resign: 'Resign', flip: 'Flip (F)', menu: 'Menu (Esc)' };
const bg = { undo: 0x6a4a1a, hint: 0x2a4a6a, draw: 0x4a4a4a, resign: 0x7a1a14, flip: 0x4a2c16, menu: 0x3a2212 };
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: 15, bg: bg[k] }).setDepth(D + 3);
if (!['menu', 'flip'].includes(k)) this.buttons[k].setEnabled(false);
}
// Gus's ribbon
s.add.image(RIBBON.x - 12, RIBBON.y - 12, 'ck-ribbon').setOrigin(0).setDepth(D);
this.gus = s.add.text(RIBBON.x + 84, RIBBON.y + RIBBON.h / 2, '', {
fontFamily: SERIF, fontSize: '19px', fontStyle: 'italic', color: '#f3e4c0', wordWrap: { width: RIBBON.w - 110 },
}).setOrigin(0, 0.5).setDepth(D + 1);
return this;
}
setSymbols(on) { this.symbols = !!on; }
/** gs, ctx: { humanColor, thinking, clocks: {human, ai}, match: {human, ai} | null, captured: {top, bottom} } */
refresh(gs, ctx) {
const c = counts(gs.board);
const sides = { bottom: ctx.humanColor, top: other(ctx.humanColor) };
for (const side of ['top', 'bottom']) {
const pl = this.plates[side], col = sides[side];
const n = col === 'black' ? c.black : c.red, k = col === 'black' ? c.blackKings : c.redKings;
const active = gs.phase === 'playing' && gs.turn === col;
if (active !== pl.active) {
pl.active = active;
this.scene.tweens.killTweensOf(pl.glow);
if (active) {
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 pl.glow.setAlpha(0);
}
let note;
if (gs.phase !== 'playing') note = '';
else if (active) note = side === 'bottom' ? 'Your move' : (ctx.thinking ? 'Thinking…' : 'To play');
else note = side === 'bottom' ? 'Waiting' : 'Watching the board';
pl.note.setText(note).setColor(active ? '#ffe0a0' : '#c8b490');
const ms = side === 'bottom' ? ctx.clocks.human : ctx.clocks.ai;
pl.line.setText(`${n} on the board${k ? ` · ${k} king${k === 1 ? '' : 's'}` : ''} ⏱ ${clock(ms)}`);
pl.chip.setTexture(`ck-man-${col}${this.symbols ? '-s' : ''}`).setVisible(true);
pl.chipText.setText(col === 'black' ? 'Black' : 'Red');
const m = ctx.match;
pl.tally.setText(m && m.games > 1 ? `Match ${half(side === 'bottom' ? m.human : m.ai) || '0'}` : '');
pl.ring.setFillStyle(side === 'bottom' ? 0xd8b060 : (col === 'black' ? 0x5a5868 : 0xc0302a));
}
this.setTrays(ctx.captured);
this.setLog(gs);
}
setTrays(captured) {
const s = this.scene;
for (const side of ['top', 'bottom']) {
this.trayObjs[side].forEach((o) => o.destroy());
this.trayObjs[side] = [];
const T = TRAYS[side];
const list = captured[side] ?? [];
// stacks of up to four, side by side
list.forEach((p, i) => {
const stack = Math.floor(i / 4), h = i % 4;
const x = T.x + 24 + stack * 46, y = T.y + T.h / 2 + 6 - h * 6;
const tex = `ck-man-${p > 0 ? 'black' : 'red'}${this.symbols ? '-s' : ''}`;
const im = s.add.image(x, y, tex).setScale(0.22).setDepth(this.depth + 1 + i * 0.01);
this.trayObjs[side].push(im);
});
}
}
trayTarget(side, n) {
const T = TRAYS[side];
const stack = Math.floor(n / 4), h = n % 4;
return { x: T.x + 24 + stack * 46, y: T.y + T.h / 2 + 6 - h * 6 };
}
setLog(gs) {
const rules = rulesOf(gs.variant);
const first = rules.first;
const name = (c) => (c === 'black' ? 'BLACK' : 'RED');
this.colHead[0].setText(name(first)).setColor(first === 'black' ? '#1d1c22' : INK.red.text);
this.colHead[1].setText(name(other(first))).setColor(first === 'black' ? INK.red.text : '#1d1c22');
this.logSub.setText(gs.ballot ? `${rules.short} · ${gs.ballot.name}` : rules.short);
const pairs = [];
for (const h of gs.history) {
if (h.color === first || !pairs.length) pairs.push({ a: null, b: null });
const last = pairs[pairs.length - 1];
if (h.color === first) last.a = h; else last.b = h;
}
const start = Math.max(0, pairs.length - LOG_ROWS);
const lastH = gs.history[gs.history.length - 1];
this.rows.forEach((r, i) => {
const p = pairs[start + i];
if (!p) { r.n.setText(''); r.a.setText(''); r.b.setText(''); return; }
r.n.setText(`${start + i + 1}.`);
for (const [t, h] of [[r.a, p.a], [r.b, p.b]]) {
if (!h) { t.setText(''); continue; }
t.setText(h.n + (h.crown ? ' ♔' : '')).setColor(h.ballot ? '#8a7a62' : h === lastH ? '#a0221c' : '#2a1a10')
.setFontStyle(h.ballot ? 'italic' : h === lastH ? 'bold' : 'normal');
}
});
}
setStatus(main, sub = '') { this.status.setText(main); this.sub.setText(sub); }
setButton(k, on) { this.buttons[k]?.setEnabled(!!on); }
gusSays(text, { hold = 7000 } = {}) {
if (!text) return;
const t = this.gus;
this.scene.tweens.killTweensOf(t);
t.setText(`Gus: “${text}”`).setAlpha(0);
this.scene.tweens.add({ targets: t, alpha: 1, duration: 220 });
this.scene.tweens.add({ targets: t, alpha: 0.55, delay: hold, duration: 800 });
}
say(text, dur = 2600) {
if (!text) return;
const s = this.scene;
this.bubble?.destroy();
const b = BUBBLE;
const t = s.add.text(b.x + b.w / 2, b.y + b.h / 2, text, {
fontFamily: SERIF, fontSize: '17px', fontStyle: 'italic', color: '#2a1a10', align: 'center', wordWrap: { width: b.w - 36 },
}).setOrigin(0.5);
const g = s.add.graphics();
g.fillStyle(0x000000, 0.3).fillRoundedRect(b.x + 3, b.y + 4, b.w, b.h, 12);
g.fillStyle(0xf3ead2, 1).fillRoundedRect(b.x, b.y, b.w, b.h, 12);
g.lineStyle(2, 0x8a5a2a, 1).strokeRoundedRect(b.x, b.y, b.w, b.h, 12);
const tx = plateParts('top').portrait.x + 40;
g.fillStyle(0xf3ead2, 1).fillTriangle(tx - 10, b.y + 1, tx + 10, b.y + 1, tx, b.y - 14);
const cont = s.add.container(0, 0, [g, t]).setDepth(this.depth + 8).setAlpha(0);
this.bubble = cont;
s.tweens.add({ targets: cont, alpha: 1, duration: 160 });
s.tweens.add({ targets: cont, alpha: 0, delay: dur, duration: 300, onComplete: () => { cont.destroy(); if (this.bubble === cont) this.bubble = null; } });
}
emotion(e) { this.plates.top?.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,99 @@
// CheckersLayout.js — geometry for Gus's Back Room (1920 × 1080). No Phaser.
//
// left column opponent plaque · captured tray · speech bubble · the
// rainy window with the barber pole · your tray · your plaque
// centre the board on the barrel head, Gus's ribbon beneath
// right column status card · move sheet · buttons · the shelf (radio,
// mantel clock, percolator)
export const W = 1920;
export const H = 1080;
export const SQ = 100;
export const BX = 560; // board (playing squares) origin
export const BY = 132;
export const BOARD = SQ * 8; // 800
export const FRAME = 44;
export const BOARD_TEX = BOARD + FRAME * 2; // 888
export const BCX = BX + BOARD / 2; // 960
export const BCY = BY + BOARD / 2; // 532
export const PIECE_R = 40;
export const BOARD_RECT = { x: BX - FRAME, y: BY - FRAME, w: BOARD_TEX, h: BOARD_TEX };
// columns
const LX = 30, RX = 1430, CW = 460;
export const PLATE = { w: CW, h: 196 };
export const PLATES = {
top: { x: LX, y: 30 },
bottom: { x: LX, y: 854 },
};
export const TRAYS = {
top: { x: LX + 20, y: 240, w: CW - 40, h: 44 },
bottom: { x: LX + 20, y: 800, w: CW - 40, h: 44 },
};
export const BUBBLE = { x: LX, y: 296, w: CW, h: 84 };
export const WINDOW = { x: 70, y: 420, w: 380, h: 300 };
export const POLE = { x: 384, y: 452, w: 30, h: 236 };
export const SIGN = { x: LX + CW / 2, y: 396 };
export const STATUS = { x: RX, y: 30, w: CW, h: 196 };
export const LOG = { x: RX, y: 246, w: CW, h: 452 };
export const LOG_ROWS = 12;
export const BTN = { w: 146, h: 48 };
export const BUTTON_ROWS = [['undo', 'hint', 'draw'], ['resign', 'flip', 'menu']];
export const BUTTONS = {};
BUTTON_ROWS.forEach((row, ri) => row.forEach((k, ci) => {
BUTTONS[k] = { x: RX + BTN.w / 2 + ci * (BTN.w + 11), y: 736 + ri * 60 };
}));
export const SHELF = { x: RX - 10, y: 880, w: CW + 40, h: 200 };
export const PERCOLATOR = { x: 1832, y: 905 }; // spout top, for steam
export const RIBBON = { x: BX, y: 996, w: BOARD, h: 66 };
export const BANNER = { x: BCX, y: BCY - 40 };
export function plateParts(side) {
const P = PLATES[side];
return {
portrait: { x: P.x + 96, y: P.y + 98, r: 70 },
name: { x: P.x + 190, y: P.y + 46 },
skill: { x: P.x + PLATE.w - 24, y: P.y + 46 },
note: { x: P.x + 190, y: P.y + 90 },
line: { x: P.x + 190, y: P.y + 130 },
tally: { x: P.x + PLATE.w - 24, y: P.y + 158 },
color: { x: P.x + 190 + 12, y: P.y + 162 },
};
}
// For the verify harness: every HUD rectangle.
export function HUD_RECTS() {
const btns = Object.values(BUTTONS);
const bx0 = Math.min(...btns.map((b) => b.x)) - BTN.w / 2, by0 = Math.min(...btns.map((b) => b.y)) - BTN.h / 2;
const bx1 = Math.max(...btns.map((b) => b.x)) + BTN.w / 2, by1 = Math.max(...btns.map((b) => b.y)) + BTN.h / 2;
return {
plateTop: { ...PLATES.top, ...PLATE },
plateBottom: { ...PLATES.bottom, ...PLATE },
trayTop: TRAYS.top,
trayBottom: TRAYS.bottom,
bubble: BUBBLE,
window: WINDOW,
status: STATUS,
log: LOG,
buttons: { x: bx0, y: by0, w: bx1 - bx0, h: by1 - by0 },
ribbon: { x: RIBBON.x, y: RIBBON.y, w: RIBBON.w, h: RIBBON.h },
};
}
/** Screen centre of a square index (0‥31) given the view orientation. */
export function squareXY(rc, flipped) {
const [r, c] = rc;
const vr = flipped ? 7 - r : r, vc = flipped ? 7 - c : c;
return { x: BX + vc * SQ + SQ / 2, y: BY + vr * SQ + SQ / 2 };
}
/** View row/col under a screen point, or null. */
export function cellAt(x, y, flipped) {
const vc = Math.floor((x - BX) / SQ), vr = Math.floor((y - BY) / SQ);
if (vc < 0 || vc > 7 || vr < 0 || vr > 7) return null;
return flipped ? [7 - vr, 7 - vc] : [vr, vc];
}

View File

@ -1,166 +1,392 @@
// Pure game logic for American (English) draughts — no Phaser dependency.
// CheckersLogic.js — pure rules for Gus's Back Room. No Phaser.
//
// Board: 8×8 array, board[r][c] = null | { color: 'white'|'black', king: bool }.
// Row 0 is the top (Black's home); row 7 is the bottom (White's home).
// Only dark squares (where (r + c) is odd) are playable.
// White (the human) moves up the board (decreasing row) and crowns at row 0.
// Black (the AI) moves down the board (increasing row) and crowns at row 7.
// Captures are mandatory; a multi-jump continues with the same piece until no
// further jump exists. Reaching the crown row ends the turn even mid-chain.
// The 32 playable squares are indexed 0‥31 in standard checkers order:
// square n (1‥32 in notation) is index n − 1, read left → right, top →
// bottom on the dark squares ((r + c) odd). Black starts on 1‥12 (rows 0‥2)
// and moves down the board; Red starts on 21‥32 (rows 5‥7) and moves up.
//
// board[i]: 0 empty · 1 black man · 2 black king · −1 red man · −2 red king
//
// A move is a whole turn: { from, to, path: [from, …landings], caps: [squares
// jumped, in order], crown }. Jumped pieces stay on the board until the turn
// ends ("Turkish strike"): they block, and can't be jumped twice.
//
// Variants:
// american forced capture; men move and capture forward; kings step one
// square; a man crowned mid-jump stops there. Black moves first.
// pool men capture backwards too; kings fly; a man that reaches the far
// row mid-jump keeps jumping as a man if it can (crowned only if it
// finishes there). Black moves first.
// russian as pool, but a man crowned mid-jump continues as a flying king.
// White (our red) moves first.
// giveaway American moves; the side that loses every piece — or is left
// with no move — WINS.
// casual American, but captures are optional.
// Every variant draws on threefold repetition or `quietLimit` turns each with
// no capture and no man move (40 by default), and on agreement.
export const N = 32;
export const SIZE = 8;
export const BLACK = 'black';
export const RED = 'red';
export const COLORS = [BLACK, RED];
export const other = (c) => (c === BLACK ? RED : BLACK);
export const sign = (c) => (c === BLACK ? 1 : -1);
export const colorOf = (p) => (p > 0 ? BLACK : p < 0 ? RED : null);
export const isKing = (p) => p === 2 || p === -2;
const WHITE_DIRS = [[-1, -1], [-1, 1]];
const BLACK_DIRS = [[1, -1], [1, 1]];
const KING_DIRS = [[-1, -1], [-1, 1], [1, -1], [1, 1]];
// ── geometry ─────────────────────────────────────────────────────────────────
export const RC = []; // index → [row, col]
const IDX = Array.from({ length: SIZE }, () => Array(SIZE).fill(-1));
for (let r = 0; r < SIZE; r++) {
for (let c = 0; c < SIZE; c++) {
if ((r + c) % 2 === 1) { IDX[r][c] = RC.length; RC.push([r, c]); }
}
}
export function sqAt(r, c) { return r >= 0 && r < SIZE && c >= 0 && c < SIZE ? IDX[r][c] : -1; }
export const isDark = (r, c) => (r + c) % 2 === 1;
function inBounds(r, c) { return r >= 0 && r < SIZE && c >= 0 && c < SIZE; }
export function isDark(r, c) { return (r + c) % 2 === 1; }
function other(color) { return color === 'white' ? 'black' : 'white'; }
// RAYS[i][d] = squares along diagonal d from i (nearest first).
// d: 0 up-left · 1 up-right · 2 down-left · 3 down-right
const DIRS = [[-1, -1], [-1, 1], [1, -1], [1, 1]];
export const RAYS = RC.map(([r, c]) => DIRS.map(([dr, dc]) => {
const out = [];
for (let rr = r + dr, cc = c + dc; sqAt(rr, cc) >= 0; rr += dr, cc += dc) out.push(IDX[rr][cc]);
return out;
}));
const FORWARD = { [BLACK]: [2, 3], [RED]: [0, 1] };
const ALL = [0, 1, 2, 3];
export const CROWN_ROW = { [BLACK]: 7, [RED]: 0 };
export function cloneState(state) {
return {
board: state.board.map((row) => row.map((cell) => (cell ? { ...cell } : null))),
turn: state.turn,
mustContinueFrom: state.mustContinueFrom ? [...state.mustContinueFrom] : null,
winner: state.winner,
phase: state.phase,
// ── variants ─────────────────────────────────────────────────────────────────
export const VARIANTS = {
american: {
id: 'american', name: 'American Checkers', short: 'American',
blurb: 'The classic. Jumps are forced, men only go forward, kings step one square.',
forced: true, menBack: false, flying: false, midCrown: 'stop', giveaway: false, first: BLACK, ballot: true,
},
pool: {
id: 'pool', name: 'Pool Checkers', short: 'Pool',
blurb: 'Southern pool rules: men jump backwards too and kings fly the whole diagonal.',
forced: true, menBack: true, flying: true, midCrown: 'continueMan', giveaway: false, first: BLACK, ballot: false,
},
russian: {
id: 'russian', name: 'Russian Shashki', short: 'Russian',
blurb: 'Like pool, but a man crowned mid-jump keeps going as a flying king. Red (white) starts.',
forced: true, menBack: true, flying: true, midCrown: 'king', giveaway: false, first: RED, ballot: false,
},
giveaway: {
id: 'giveaway', name: 'Giveaway', short: 'Giveaway',
blurb: 'Losing is winning: get rid of every piece (or get stuck) first. Jumps are still forced.',
forced: true, menBack: false, flying: false, midCrown: 'stop', giveaway: true, first: BLACK, ballot: false,
},
casual: {
id: 'casual', name: 'Casual (jumps optional)', short: 'Casual',
blurb: 'Kitchen-table rules: American moves, but you never have to take a jump.',
forced: false, menBack: false, flying: false, midCrown: 'stop', giveaway: false, first: BLACK, ballot: false,
},
};
export const VARIANT_ORDER = ['american', 'pool', 'russian', 'giveaway', 'casual'];
export const rulesOf = (v) => VARIANTS[v] ?? VARIANTS.american;
// ── board ────────────────────────────────────────────────────────────────────
export function initialBoard() {
const b = new Array(N).fill(0);
for (let i = 0; i < 12; i++) b[i] = 1;
for (let i = 20; i < 32; i++) b[i] = -1;
return b;
}
export function createInitialState() {
const board = Array.from({ length: SIZE }, () => Array(SIZE).fill(null));
for (let r = 0; r < SIZE; r++) {
for (let c = 0; c < SIZE; c++) {
if (!isDark(r, c)) continue;
if (r <= 2) board[r][c] = { color: 'black', king: false };
else if (r >= 5) board[r][c] = { color: 'white', king: false };
export function counts(board) {
const o = { black: 0, red: 0, blackKings: 0, redKings: 0 };
for (const p of board) {
if (p > 0) { o.black++; if (p === 2) o.blackKings++; }
else if (p < 0) { o.red++; if (p === -2) o.redKings++; }
}
}
return { board, turn: 'white', mustContinueFrom: null, winner: null, phase: 'playing' };
return o;
}
function dirsFor(piece) {
if (piece.king) return KING_DIRS;
return piece.color === 'white' ? WHITE_DIRS : BLACK_DIRS;
// ── move generation ──────────────────────────────────────────────────────────
function capturesFrom(board, from, rules, out) {
const b = board.slice();
const piece = b[from];
b[from] = 0;
dfs(b, from, piece, piece, [from], [], 0, rules, out);
}
// Slides and jumps available to the single piece at [r, c].
function stepMovesFor(state, r, c) {
const piece = state.board[r][c];
const slides = [];
const jumps = [];
if (!piece) return { slides, jumps };
for (const [dr, dc] of dirsFor(piece)) {
const r1 = r + dr, c1 = c + dc;
if (!inBounds(r1, c1)) continue;
const adj = state.board[r1][c1];
if (adj === null) {
slides.push({ from: [r, c], to: [r1, c1], captures: [], isJump: false });
} else if (adj.color !== piece.color) {
const r2 = r1 + dr, c2 = c1 + dc;
if (inBounds(r2, c2) && state.board[r2][c2] === null) {
jumps.push({ from: [r, c], to: [r2, c2], captures: [[r1, c1]], isJump: true });
// Explore jumps from `at`. Returns true if at least one jump was found (and so
// moves were pushed); otherwise pushes nothing — the caller ends the turn.
function dfs(b, at, piece, orig, path, caps, taken, rules, out) {
const color = piece > 0 ? BLACK : RED;
const king = piece === 2 || piece === -2;
const dirs = king || rules.menBack ? ALL : FORWARD[color];
let any = false;
for (const d of dirs) {
const ray = RAYS[at][d];
if (king && rules.flying) {
let k = 0;
while (k < ray.length && b[ray[k]] === 0) k++;
if (k >= ray.length) continue;
const v = ray[k];
if (b[v] * piece > 0 || ((taken >>> v) & 1)) continue;
const lands = [];
for (let j = k + 1; j < ray.length && b[ray[j]] === 0; j++) lands.push(ray[j]);
if (!lands.length) continue;
any = true;
const t2 = (taken | (1 << v)) >>> 0;
const conts = [], ends = [];
for (const L of lands) {
const sub = [];
if (dfs(b, L, piece, orig, path.concat(L), caps.concat(v), t2, rules, sub)) conts.push(...sub);
else ends.push(finish(orig, piece, path.concat(L), caps.concat(v)));
}
// must keep capturing when you can: only landings that continue count
out.push(...(conts.length ? conts : ends));
} else {
if (ray.length < 2) continue;
const v = ray[0], L = ray[1];
if (b[v] === 0 || b[v] * piece > 0 || ((taken >>> v) & 1) || b[L] !== 0) continue;
any = true;
const t2 = (taken | (1 << v)) >>> 0;
const np = path.concat(L), nc = caps.concat(v);
const reachesCrown = !king && RC[L][0] === CROWN_ROW[color];
if (reachesCrown && rules.midCrown === 'stop') { out.push(finish(orig, piece, np, nc, true)); continue; }
if (reachesCrown && rules.midCrown === 'king') {
const kp = piece * 2;
if (!dfs(b, L, kp, orig, np, nc, t2, rules, out)) out.push(finish(orig, kp, np, nc, true));
continue;
}
if (!dfs(b, L, piece, orig, np, nc, t2, rules, out)) out.push(finish(orig, piece, np, nc));
}
}
}
return { slides, jumps };
return any;
}
// Legal moves for the side to move. Captures are forced: if any jump exists,
// only jumps are returned. When a multi-jump is in progress, only further
// jumps from the locked square are legal.
export function getValidMoves(state) {
if (state.phase === 'game_over') return [];
const player = state.turn;
if (state.mustContinueFrom) {
const [r, c] = state.mustContinueFrom;
return stepMovesFor(state, r, c).jumps;
function finish(orig, piece, path, caps, forceCrown = false) {
const to = path[path.length - 1];
const wasMan = !isKing(orig);
const color = orig > 0 ? BLACK : RED;
const crown = wasMan && (forceCrown || isKing(piece) || RC[to][0] === CROWN_ROW[color]);
return { from: path[0], to, path, caps, crown };
}
const allSlides = [];
const allJumps = [];
for (let r = 0; r < SIZE; r++) {
for (let c = 0; c < SIZE; c++) {
const piece = state.board[r][c];
if (!piece || piece.color !== player) continue;
const { slides, jumps } = stepMovesFor(state, r, c);
allSlides.push(...slides);
allJumps.push(...jumps);
function quietFrom(board, i, rules, out) {
const p = board[i];
const color = p > 0 ? BLACK : RED;
if (isKing(p)) {
for (const d of ALL) {
for (const s of RAYS[i][d]) {
if (board[s] !== 0) break;
out.push({ from: i, to: s, path: [i, s], caps: [], crown: false });
if (!rules.flying) break;
}
}
} else {
for (const d of FORWARD[color]) {
const s = RAYS[i][d][0];
if (s !== undefined && board[s] === 0) {
out.push({ from: i, to: s, path: [i, s], caps: [], crown: RC[s][0] === CROWN_ROW[color] });
}
}
}
return allJumps.length > 0 ? allJumps : allSlides;
}
function countPieces(board, color) {
let n = 0;
for (const row of board) for (const cell of row) if (cell && cell.color === color) n++;
return n;
/** All legal turns for `color` on `board`. */
export function generateMoves(board, color, rules) {
const s = sign(color);
const caps = [];
for (let i = 0; i < N; i++) if (board[i] * s > 0) capturesFrom(board, i, rules, caps);
if (caps.length && rules.forced) return caps;
const quiet = [];
for (let i = 0; i < N; i++) if (board[i] * s > 0) quietFrom(board, i, rules, quiet);
return caps.concat(quiet);
}
// Decide game over for the position with `state.turn` to move: that side loses
// if it has no pieces or no legal move.
function resolveEnd(state) {
const s = state;
if (countPieces(s.board, 'white') === 0) { s.winner = 'black'; s.phase = 'game_over'; return s; }
if (countPieces(s.board, 'black') === 0) { s.winner = 'white'; s.phase = 'game_over'; return s; }
if (getValidMoves(s).length === 0) { s.winner = other(s.turn); s.phase = 'game_over'; }
export function hasCapture(board, color, rules) {
const s = sign(color);
const out = [];
for (let i = 0; i < N; i++) {
if (board[i] * s > 0) { capturesFrom(board, i, rules, out); if (out.length) return true; }
}
return false;
}
export function applyBoard(board, m) {
const b = board.slice();
let p = b[m.from];
b[m.from] = 0;
for (const c of m.caps) b[c] = 0;
if (m.crown && !isKing(p)) p *= 2;
b[m.to] = p;
return b;
}
// ── notation ─────────────────────────────────────────────────────────────────
export function notate(m) {
return m.caps.length ? m.path.map((i) => i + 1).join('x') : `${m.from + 1}-${m.to + 1}`;
}
/** Find a legal move from text: "11-15", "22x15", "22x15x8" or "22x8". */
export function parseMove(state, text) {
const t = String(text).trim();
const moves = legalMoves(state);
const exact = moves.find((m) => notate(m) === t);
if (exact) return exact;
const parts = t.split(/[x-]/).map((n) => Number(n) - 1);
if (parts.length < 2) return null;
const from = parts[0], to = parts[parts.length - 1];
const hits = moves.filter((m) => m.from === from && m.to === to);
return hits.length === 1 ? hits[0] : null;
}
// Two moves are "the same" if they lead to the same board.
export function moveKey(m) {
return `${m.from}>${m.to}:${m.caps.slice().sort((a, b) => a - b).join(',')}${m.crown ? '+' : ''}`;
}
// ── game state ───────────────────────────────────────────────────────────────
const CH = { 0: '.', 1: 'b', 2: 'B', '-1': 'r', '-2': 'R' };
export function posKey(board, turn) {
let s = turn === BLACK ? 'b:' : 'r:';
for (const p of board) s += CH[p];
return s;
}
export function applyMove(state, move) {
const s = cloneState(state);
const [fr, fc] = move.from;
const [tr, tc] = move.to;
const piece = s.board[fr][fc];
s.board[fr][fc] = null;
for (const [cr, cc] of move.captures) s.board[cr][cc] = null;
let promoted = false;
if (!piece.king) {
if (piece.color === 'white' && tr === 0) { piece.king = true; promoted = true; }
if (piece.color === 'black' && tr === SIZE - 1) { piece.king = true; promoted = true; }
/**
* opts: { variant, quietLimit (turns each, default 40), ballot: { name, moves: ['11-15', …] } | null }
*/
export function createGame(opts = {}) {
const variant = VARIANTS[opts.variant] ? opts.variant : 'american';
const rules = rulesOf(variant);
const board = initialBoard();
const gs = {
v: 1,
variant,
quietLimit: opts.quietLimit ?? 40,
board,
turn: rules.first,
ply: 0,
quiet: 0,
reps: { [posKey(board, rules.first)]: 1 },
history: [],
phase: 'playing',
winner: null,
endReason: null,
ballot: null,
};
if (opts.ballot && rules.ballot) {
let s = gs;
for (const t of opts.ballot.moves) {
const m = parseMove(s, t);
if (!m) throw new Error(`ballot move ${t} is illegal`);
s = applyMove(s, m, { ballot: true });
}
s.board[tr][tc] = piece;
// Continue a multi-jump with the same piece unless it just crowned.
if (move.isJump && !promoted) {
const further = stepMovesFor(s, tr, tc).jumps;
if (further.length > 0) {
s.mustContinueFrom = [tr, tc];
return s; // same player keeps moving
s.ballot = { name: opts.ballot.name, moves: opts.ballot.moves.slice() };
return s;
}
return gs;
}
s.mustContinueFrom = null;
s.turn = other(s.turn);
return resolveEnd(s);
export function cloneState(gs) {
return JSON.parse(JSON.stringify(gs));
}
export function isGameOver(state) { return state.phase === 'game_over'; }
export function getWinner(state) { return state.winner; }
export function legalMoves(gs) {
if (gs.phase !== 'playing') return [];
return generateMoves(gs.board, gs.turn, rulesOf(gs.variant));
}
export function pieceCounts(state) {
/** Apply a whole turn. Returns a new state (the old one is untouched). */
export function applyMove(gs, m, { ballot = false } = {}) {
const rules = rulesOf(gs.variant);
const piece = gs.board[m.from];
const board = applyBoard(gs.board, m);
const turn = other(gs.turn);
const manMoved = !isKing(piece);
const s = {
...gs,
board,
turn,
ply: gs.ply + 1,
quiet: m.caps.length || manMoved ? 0 : gs.quiet + 1,
reps: { ...gs.reps },
history: gs.history.concat({
color: gs.turn, from: m.from, to: m.to, path: m.path.slice(), caps: m.caps.slice(), crown: !!m.crown,
king: isKing(piece), n: notate(m), ballot: ballot || undefined,
}),
};
// a capture or a man move can never be undone, so earlier positions can't recur
if (m.caps.length || manMoved) s.reps = {};
const key = posKey(board, turn);
s.reps[key] = (s.reps[key] ?? 0) + 1;
if (generateMoves(board, turn, rules).length === 0) {
const c = counts(board);
s.phase = 'game_over';
s.winner = rules.giveaway ? turn : other(turn);
s.endReason = (turn === BLACK ? c.black : c.red) === 0 ? 'wiped' : 'blocked';
} else if (s.reps[key] >= 3) {
s.phase = 'game_over'; s.winner = 'draw'; s.endReason = 'repetition';
} else if (s.quiet >= s.quietLimit * 2) {
s.phase = 'game_over'; s.winner = 'draw'; s.endReason = 'quiet';
} else if (s.ply >= 600) {
s.phase = 'game_over'; s.winner = 'draw'; s.endReason = 'cap';
}
return s;
}
export function resign(gs, color) {
return { ...gs, phase: 'game_over', winner: other(color), endReason: 'resign', resigned: color };
}
export function agreeDraw(gs) {
return { ...gs, phase: 'game_over', winner: 'draw', endReason: 'agreed' };
}
/** Turns (each) left before the no-progress draw. */
export function quietLeft(gs) { return Math.max(0, Math.ceil((gs.quietLimit * 2 - gs.quiet) / 2)); }
/** How many times the current position has occurred. */
export function repCount(gs) { return gs.reps[posKey(gs.board, gs.turn)] ?? 0; }
/** Rebuild the board after the first `n` history entries (for replays). */
export function boardAfter(gs, n) {
let b = initialBoard();
for (let i = 0; i < Math.min(n, gs.history.length); i++) b = applyBoard(b, gs.history[i]);
return b;
}
/** Squares of `color` pieces that the other side could capture right now. */
export function threatened(board, color, rules) {
const s = sign(color);
const out = new Set();
const moves = [];
for (let i = 0; i < N; i++) if (board[i] * s < 0) capturesFrom(board, i, rules, moves);
for (const m of moves) for (const c of m.caps) out.add(c);
return [...out];
}
export function stats(gs, color) {
const mine = gs.history.filter((h) => h.color === color && !h.ballot);
return {
white: countPieces(state.board, 'white'),
black: countPieces(state.board, 'black'),
moves: mine.length,
captures: mine.reduce((a, h) => a + h.caps.length, 0),
longest: mine.reduce((a, h) => Math.max(a, h.caps.length), 0),
kings: mine.filter((h) => h.crown).length,
};
}
// Enumerate complete turns for the side to move. Each entry is the first step
// of the turn paired with the resulting end-of-turn state (multi-jumps are
// expanded internally). Used by the AI search.
export function expandTurns(state) {
// Material (men 1, kings 1.5) per side after each history entry — the end
// screen's sparkline.
export function materialTrace(gs) {
const out = [];
const moves = getValidMoves(state);
for (const m of moves) {
const ns = applyMove(state, m);
if (ns.turn === state.turn && ns.phase !== 'game_over') {
for (const sub of expandTurns(ns)) out.push({ firstStep: m, state: sub.state });
} else {
out.push({ firstStep: m, state: ns });
}
}
let b = initialBoard();
const val = (bb) => {
let x = 0;
for (const p of bb) x += p === 1 ? 1 : p === 2 ? 1.5 : p === -1 ? -1 : p === -2 ? -1.5 : 0;
return x;
};
out.push(val(b));
for (const h of gs.history) { b = applyBoard(b, h); out.push(val(b)); }
return out;
}

View File

@ -0,0 +1,167 @@
// CheckersPieces.js — the checkers on the board. Each one is a shadow + a
// body image (man or stacked king), positioned by square and view
// orientation. Hops arc and squash; captured checkers are flicked into the
// capturer's tray; a crowning drops a second checker on top.
import { RC } from './CheckersLogic.js';
import { squareXY } from './CheckersLayout.js';
import { RES } from './CheckersArt.js';
const SCALE = 1 / RES;
export class PieceSet {
constructor(scene, depth, { symbols = false } = {}) {
this.scene = scene;
this.depth = depth;
this.symbols = symbols;
this.items = new Map(); // sq → item
this.flipped = false;
}
tex(p) {
const color = p > 0 ? 'black' : 'red';
const kind = p === 2 || p === -2 ? 'king' : 'man';
return `ck-${kind}-${color}${this.symbols ? '-s' : ''}`;
}
build(board, flipped) {
this.clear();
this.flipped = flipped;
board.forEach((p, sq) => { if (p) this.items.set(sq, this.make(sq, p)); });
return this;
}
make(sq, p) {
const s = this.scene;
const { x, y } = squareXY(RC[sq], this.flipped);
const shadow = s.add.image(x + 3, y + 7, 'ck-shadow').setScale(SCALE).setAlpha(0.8).setDepth(this.depth - 1);
const body = s.add.image(x, y, this.tex(p)).setScale(SCALE);
const it = { sq, p, shadow, body, x, y, lift: 0 };
this.place(it, x, y, 0);
return it;
}
clear() {
for (const it of this.items.values()) { it.shadow.destroy(); it.body.destroy(); }
this.items.clear();
}
get(sq) { return this.items.get(sq); }
all() { return [...this.items.values()]; }
place(it, x, y, lift = it.lift) {
it.x = x; it.y = y; it.lift = lift;
it.body.setPosition(x, y - lift);
it.shadow.setPosition(x + 3 + lift * 0.25, y + 7 + lift * 0.35).setScale(SCALE * (1 + lift / 120)).setAlpha(0.8 - Math.min(0.45, lift / 90));
it.body.setDepth(this.depth + (lift > 0 ? 20 : 0) + y / 2000);
}
home(sq) { return squareXY(RC[sq], this.flipped); }
setFlipped(f) {
this.flipped = f;
for (const it of this.items.values()) { const p = this.home(it.sq); this.place(it, p.x, p.y, 0); }
}
setSymbols(on) {
this.symbols = !!on;
for (const it of this.items.values()) it.body.setTexture(this.tex(it.p));
}
setVisible(v) { for (const it of this.items.values()) { it.body.setVisible(v); it.shadow.setVisible(v); } }
tween(cfg) { return new Promise((res) => this.scene.tweens.add({ ...cfg, onComplete: res })); }
async liftTo(it, lift, dur = 110) {
const o = { l: it.lift };
await this.tween({ targets: o, l: lift, duration: dur, ease: 'Quad.Out', onUpdate: () => this.place(it, it.x, it.y, o.l) });
}
/** Arc (jump) or glide (step) to a square. */
async moveTo(it, sq, { dur = 260, arc = 0 } = {}) {
const from = { x: it.x, y: it.y, l: it.lift };
const to = this.home(sq);
const o = { t: 0 };
await this.tween({
targets: o, t: 1, duration: dur, ease: arc ? 'Sine.InOut' : 'Cubic.InOut',
onUpdate: () => {
const t = o.t;
const lift = from.l * (1 - t) + Math.sin(Math.PI * t) * arc;
this.place(it, from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t, lift);
},
});
this.place(it, to.x, to.y, 0);
}
async squash(it, amt = 0.12, dur = 110) {
const sx = it.body.scaleX;
await this.tween({ targets: it.body, scaleX: sx * (1 + amt), scaleY: sx * (1 - amt), duration: dur / 2, yoyo: true, ease: 'Quad.Out' });
it.body.setScale(sx);
}
/** Re-key a moved item. */
rekey(it, sq) {
this.items.delete(it.sq);
it.sq = sq;
this.items.set(sq, it);
}
/** Mark a jumped checker (it stays until the turn ends). */
mark(sq, on = true) {
const it = this.items.get(sq);
if (it) it.body.setAlpha(on ? 0.45 : 1);
}
/** Flick a captured checker to (tx, ty), spinning, then remove it. */
async flick(sq, tx, ty, { dur = 420, delay = 0 } = {}) {
const it = this.items.get(sq);
if (!it) return;
this.items.delete(sq);
it.body.setAlpha(1).setDepth(this.depth + 40);
const from = { x: it.x, y: it.y };
const o = { t: 0 };
const spin = (Math.random() < 0.5 ? -1 : 1) * (2 + Math.random() * 2);
await this.tween({
targets: o, t: 1, delay, duration: dur, ease: 'Quad.In',
onUpdate: () => {
const t = o.t;
const x = from.x + (tx - from.x) * t, y = from.y + (ty - from.y) * t - Math.sin(Math.PI * t) * 90;
it.body.setPosition(x, y).setRotation(spin * t).setScale(SCALE * (1 - 0.6 * t));
it.shadow.setPosition(x + 3, y + 7 + Math.sin(Math.PI * t) * 90).setScale(SCALE * (1 - 0.6 * t)).setAlpha(0.5 * (1 - t));
},
});
it.body.destroy(); it.shadow.destroy();
}
/** Crown: drop a second checker onto this one. */
async crown(it, p) {
const s = this.scene;
const color = p > 0 ? 'black' : 'red';
const top = s.add.image(it.x, it.y - 160, `ck-man-${color}${this.symbols ? '-s' : ''}`).setScale(SCALE).setDepth(this.depth + 45).setAlpha(0);
await this.tween({ targets: top, y: it.y - 12, alpha: 1, duration: 300, ease: 'Bounce.Out' });
top.destroy();
it.p = p;
it.body.setTexture(this.tex(p));
await this.squash(it, 0.1, 140);
}
/** Bring every checker in from above, square by square (start of a game). */
async dropIn(k = 1, onLand = null) {
const list = this.all().sort((a, b) => a.sq - b.sq);
const jobs = list.map((it, i) => new Promise((res) => {
const { x, y } = it;
this.place(it, x, y, 220);
it.body.setAlpha(0); it.shadow.setAlpha(0);
this.scene.time.delayedCall(i * 26 * k, () => {
it.body.setAlpha(1);
const o = { l: 220 };
this.scene.tweens.add({
targets: o, l: 0, duration: 260, ease: 'Quad.In',
onUpdate: () => this.place(it, x, y, o.l),
onComplete: () => { onLand?.(i); this.squash(it, 0.1, 100).then(res); },
});
});
}));
await Promise.all(jobs);
}
}

View File

@ -0,0 +1,193 @@
// CheckersSound.js — little Web Audio synths for the back room. No audio
// files; silent without Web Audio or when muted.
//
// clack(scene, { k }) a checker landing on the board; the k-th hop of a
// multi-jump rings a step higher
// pick(scene) lifting a checker
// deny(scene) that one can't move
// flick(scene) a captured checker skittering off into the tray
// crown(scene) a checker stacked on top — the double clack
// sting(scene, kind) 'win' (a barbershop-quartet chord), 'lose', 'draw'
// Ambience rain on the window, and now and then a far-off
// radio murmur and a percolator burble
function ctxOf(scene) {
const sm = scene?.sound;
if (!sm || sm.mute || !sm.context || typeof sm.context.createOscillator !== 'function') return null;
return sm.context;
}
const noiseCache = new WeakMap();
function noise(ac) {
if (noiseCache.has(ac)) return noiseCache.get(ac);
const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * 2), ac.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
noiseCache.set(ac, buf);
return buf;
}
function out(scene, ac, gain) {
const sm = scene.sound;
const node = sm.masterVolumeNode ?? sm.destination ?? null;
const g = ac.createGain();
g.gain.value = node ? gain : gain * (sm.volume ?? 1);
g.connect(node ?? ac.destination);
return g;
}
function tone(ac, dest, t0, f, { type = 'sine', a = 1, d = 0.2, glide = 1, attack = 0.003, vib = 0 } = {}) {
const o = ac.createOscillator(); o.type = type;
o.frequency.setValueAtTime(f, t0);
if (glide !== 1) o.frequency.exponentialRampToValueAtTime(f * glide, t0 + d);
if (vib) {
const lfo = ac.createOscillator(); lfo.frequency.value = 5.2;
const lg = ac.createGain(); lg.gain.value = f * vib;
lfo.connect(lg); lg.connect(o.frequency); lfo.start(t0); lfo.stop(t0 + d + 0.05);
}
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, q = 3) {
const n = ac.createBufferSource(); n.buffer = noise(ac);
const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = f; bp.Q.value = q;
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 */ } };
const semi = (f, n) => f * Math.pow(2, n / 12);
const MAJOR = [0, 2, 4, 5, 7, 9, 11, 12, 14, 16];
export function clack(scene, { k = 0, vol = 0.12 } = {}) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, vol), t = ac.currentTime + 0.003;
// hard composition on painted wood: a dull thock and a bright knock
tone(ac, dest, t, semi(170, MAJOR[Math.min(k, MAJOR.length - 1)]), { a: 0.9, d: 0.09, glide: 0.7 });
tick(ac, dest, t, 1800 + k * 160, 0.9, 0.035, 2);
tick(ac, dest, t + 0.002, 4200, 0.35, 0.015);
});
}
export function pick(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, 3200, 0.8, 0.02);
tone(ac, dest, t, 520, { a: 0.3, d: 0.04, glide: 1.3 });
});
}
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, 150, { a: 0.8, d: 0.12, glide: 0.7 });
tick(ac, dest, t, 700, 0.5);
});
}
export function flick(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.003;
// skitter across the barrel head, then a drop into the pile
for (let i = 0; i < 4; i++) tick(ac, dest, t + i * 0.045, 2400 - i * 250, 0.6 - i * 0.12, 0.02);
tone(ac, dest, t + 0.22, 260, { a: 0.6, d: 0.08, glide: 0.75 });
tick(ac, dest, t + 0.22, 1500, 0.6, 0.03);
});
}
export function crown(scene) {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.13), t = ac.currentTime + 0.003;
tone(ac, dest, t, 220, { a: 0.9, d: 0.08, glide: 0.75 }); tick(ac, dest, t, 2000, 0.9, 0.03);
tone(ac, dest, t + 0.11, 260, { a: 0.9, d: 0.1, glide: 0.75 }); tick(ac, dest, t + 0.11, 2300, 0.9, 0.03);
// a little bell from the shop door
tone(ac, dest, t + 0.16, 1568, { type: 'triangle', a: 0.25, d: 0.9 });
tone(ac, dest, t + 0.16, 1568 * 2.76, { a: 0.06, d: 0.5 });
});
}
export function sting(scene, kind = 'win') {
const ac = ctxOf(scene); if (!ac) return;
safe(() => {
const dest = out(scene, ac, 0.07), t = ac.currentTime + 0.02;
const voice = (f, at, d) => {
tone(ac, dest, t + at, f, { type: 'sawtooth', a: 0.12, d, attack: 0.08, vib: 0.006 });
tone(ac, dest, t + at, f, { type: 'triangle', a: 0.5, d, attack: 0.06, vib: 0.006 });
};
if (kind === 'win') {
// the barbershop "ring": a dominant seventh resolving to the tonic
[196, 247, 294, 349].forEach((f) => voice(f, 0, 0.9));
[196, 262, 330, 392].forEach((f) => voice(f, 0.75, 1.8));
} else if (kind === 'lose') {
[220, 262, 330].forEach((f) => voice(f, 0, 0.7));
[196, 233, 294].forEach((f) => voice(f, 0.6, 1.4));
} else {
[220, 277, 330].forEach((f) => voice(f, 0, 0.6));
[220, 294, 370].forEach((f) => voice(f, 0.5, 1.2));
}
});
}
export class Ambience {
constructor(scene) { this.scene = scene; this.on = false; this.timer = null; this.rain = null; }
start() {
if (this.on) return;
this.on = true;
const ac = ctxOf(this.scene);
if (ac) {
safe(() => {
// steady rain: band-limited noise, slowly breathing
const src = ac.createBufferSource(); src.buffer = noise(ac); src.loop = true;
const hp = ac.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 900;
const lp = ac.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 5200;
const g = out(this.scene, ac, 0.0);
g.gain.setValueAtTime(0, ac.currentTime);
g.gain.linearRampToValueAtTime(0.018, ac.currentTime + 2.5);
const lfo = ac.createOscillator(); lfo.frequency.value = 0.07;
const lg = ac.createGain(); lg.gain.value = 0.006;
lfo.connect(lg); lg.connect(g.gain);
src.connect(hp); hp.connect(lp); lp.connect(g);
src.start(); lfo.start();
this.rain = { src, lfo, g };
});
}
const event = () => {
this.timer = setTimeout(event, 6000 + Math.random() * 9000);
const a = ctxOf(this.scene); if (!a) return;
safe(() => {
const dest = out(this.scene, a, 0.02), t = a.currentTime + 0.02;
if (Math.random() < 0.5) {
// a heavy drop off the awning
tone(a, dest, t, 900 + Math.random() * 600, { a: 0.6, d: 0.08, glide: 0.5 });
} else {
// the percolator burbles
for (let i = 0; i < 5; i++) tone(a, dest, t + i * 0.09 + Math.random() * 0.04, 300 + Math.random() * 200, { a: 0.4, d: 0.06, glide: 1.6 });
}
});
};
this.timer = setTimeout(event, 3000);
}
stop() {
this.on = false;
clearTimeout(this.timer); this.timer = null;
if (this.rain) {
const { src, lfo, g } = this.rain;
safe(() => {
const ac = src.context;
g.gain.cancelScheduledValues(ac.currentTime);
g.gain.setValueAtTime(g.gain.value, ac.currentTime);
g.gain.linearRampToValueAtTime(0, ac.currentTime + 0.6);
src.stop(ac.currentTime + 0.7); lfo.stop(ac.currentTime + 0.7);
});
this.rain = null;
}
}
setOn(on) { if (on) this.start(); else this.stop(); }
}

View File

@ -0,0 +1,132 @@
// CheckersTalk.js — table talk in Gus's back room. Two voices:
// gusLine(kind, ctx) Gus, the barber: your host and coach. Dry,
// warm, forty years of watching this board.
// opponentLine(kind, tier) whoever sits across the barrel — needling that
// depends on how good they are:
// 'rookie' (skill 1–2) · 'regular' (3) · 'shark' (4–5)
// Each returns a line or null (some moments only get a remark now and then).
const pick = (a) => a[Math.floor(Math.random() * a.length)];
const fill = (s, ctx = {}) => s.replace(/\{(\w+)\}/g, (_, k) => (ctx[k] ?? ''));
const GUS = {
welcome: [
'Flip the sign to CLOSED and pull up a crate. Board\'s set.',
'Last customer\'s gone. Coffee\'s on. Let\'s see what you\'ve got.',
'Rain\'s not letting up — might as well play.',
'Forty years I\'ve watched games on this barrel. Make it a good one.',
],
welcomeBack: [
'Pieces are right where you left \'em. Nobody touched a thing.',
'Back for the rest? Sit down, I kept the board warm.',
],
newGame: [
'Swap colours. Fresh board.',
'Next game. Shake hands, and mind the coffee.',
],
ballot: [
'Out of the cigar box: the {name}. Three moves are already down — play it from here.',
'Ballot says the {name}. Tournament men play \'em all, so you will too.',
],
humanCapture: ['There you go.', 'Clean.', 'Took that one off the board nice.', null, null],
humanMulti: ['Now THAT is checkers!', 'Ha! Didn\'t see that coming, did they?', '{n} in one go. Somebody\'s been practising.'],
humanCrown: ['Crown him! Put one on top.', 'King me — the oldest words in the shop.', 'A king. Now go to work with it.'],
aiCrown: ['They\'ve got a king. Watch your back row.', 'Uh-oh. Crowned.', null],
humanLostPiece: ['Hm.', 'Ouch.', 'That one hurt.', null, null, null],
hint: ['Look at {move} — it {reason}.', 'If it were me: {move}. It {reason}.', 'Try {move}. It {reason}.'],
warn: [
'Hold on — that leaves a man hanging. You sure?',
'I wouldn\'t. That drops a piece.',
],
missed: [
'There was a shot there: {move} would\'ve {reason}.',
'You had {move} — it {reason}. Next time.',
],
forced: ['A jump\'s on — you have to take it.', 'Jumps are forced, friend. Take it.'],
quiet: [
'{n} more moves without a jump or a man moving and I call it a draw.',
'Nobody\'s making progress. {n} moves left before it\'s a draw.',
],
repetition: ['Same position again. Once more and it\'s a draw.'],
drawOfferAI: ['Your opponent\'s offering a draw. Up to you.'],
drawYouAccepted: ['Draw. Shake on it.', 'Fair enough — half a point each.'],
drawDeclined: ['They want to play it out.', 'No dice. Keep going.'],
resign: ['Tipping your king? Next one, then.', 'No shame in it. Set \'em up again.'],
win: [
'That\'s a win! Your name goes on the corkboard.',
'Beautiful. I\'d put that one in the paper.',
'Well played. The house champ\'s got company.',
],
loss: [
'Tough one. Shake it off — we go again.',
'They had your number tonight. Rematch?',
'You\'ll get \'em. Watch those back-row men.',
],
draw: ['A draw. Nobody goes home sore.', 'Even. Fair\'s fair.'],
matchWin: ['Match is yours! I\'ll pour you a coffee.', 'You took the match. Not bad at all.'],
matchLoss: ['Match goes to them. Come back Thursday.', 'They took the match. Next time.'],
matchDraw: ['Dead even match. Somebody owes somebody a haircut.'],
giveaway: ['Remember — in giveaway you WANT to lose pieces.'],
undo: ['Take-backs. Don\'t tell the regulars.', 'Fine, fine — one more look.', null],
};
const OPP = {
rookie: {
greet: ['Go easy on me, OK?', 'I mostly play my nephew.', 'Which way do these go again? Kidding!'],
capture: ['Oh! I got one!', 'Is that allowed? It is? Great!', 'Gotcha!'],
multi: ['Wait — all of those?!', 'Whoa, I didn\'t even see that coming!'],
crown: ['King me! I\'ve always wanted to say that.', 'A crown! Fancy.'],
lostPiece: ['Hey, I needed that one.', 'Aw, man.', 'Oops.'],
lostMulti: ['Oh no, no, no…', 'That\'s just mean.'],
offerDraw: ['Draw? My brain hurts.'],
acceptDraw: ['Deal! Good game.'],
declineDraw: ['Nah, I think I\'ve almost got you.', 'Let\'s keep going, this is fun!'],
win: ['I won? I won!', 'Beginner\'s luck!'],
lose: ['Good game! You\'re really good.', 'I\'ll get you next time!'],
draw: ['A tie! That counts as not losing.'],
},
regular: {
greet: ['Thursday night again, eh?', 'Your move first? No — mine. Rules are rules.', 'Same stakes as always: nothing.'],
capture: ['Thank you kindly.', 'I\'ll take that.', 'Into the pile it goes.'],
multi: ['Now there\'s a combination.', 'Hop, hop.'],
crown: ['King me, Gus.', 'Crowned. Now we\'re cooking.'],
lostPiece: ['Hmph.', 'Saw it a second too late.', 'Fair trade… almost.'],
lostMulti: ['Well, that\'s embarrassing.', 'Should\'ve seen that.'],
offerDraw: ['Call it even?', 'I don\'t see a win here for either of us. Draw?'],
acceptDraw: ['Sure. Good game.', 'Even it is.'],
declineDraw: ['Not yet. I\'ve got ideas.', 'Let\'s play it out.'],
win: ['Good game. Rematch any time.', 'That one\'s mine.'],
lose: ['Well played. You earned it.', 'You got me fair and square.'],
draw: ['Honest result.'],
},
shark: {
greet: ['I\'ve played this barrel since before you were born.', 'Let\'s see if you know the openings.', 'Don\'t let the hat fool you.'],
capture: ['Expected.', 'Book move.', 'That was there all along.'],
multi: ['You walked right into that.', 'Textbook shot.'],
crown: ['King. It\'s over now.', 'And that\'s a king.'],
lostPiece: ['A sacrifice. Watch.', 'Interesting.', 'Calculated.'],
lostMulti: ['…Well found.', 'Hm. I underrated that.'],
offerDraw: ['It\'s a book draw. Shall we?', 'Neither of us breaks through. Draw.'],
acceptDraw: ['Agreed.', 'Reasonable.'],
declineDraw: ['No.', 'I\'m playing for the win.', 'Not in this position.'],
win: ['Study your endgames.', 'As expected. Again?'],
lose: ['Well played. Truly.', 'You saw further than me tonight.'],
draw: ['A fair result.'],
},
};
export function tierOf(skill) { return skill <= 2 ? 'rookie' : skill === 3 ? 'regular' : 'shark'; }
export function gusLine(kind, ctx = {}) {
const list = GUS[kind];
if (!list) return null;
const s = pick(list);
return s ? fill(s, ctx) : null;
}
export function opponentLine(kind, tier, ctx = {}) {
const list = OPP[tier]?.[kind];
if (!list) return null;
const s = pick(list);
return s ? fill(s, ctx) : null;
}

View File

@ -0,0 +1,98 @@
# Welcome to Checkers
*By Gus: barber, coffee-maker, and keeper of the board on the barrel since 1938*
---
*Wipes his hands on his apron and flips the sign to CLOSED*
Sit down, sit down. The last customer's gone, the percolator's going, and it's raining too hard to walk home. That makes it checkers weather. I've watched more games on this old barrel than I've given haircuts, and that's saying something. Here's how it goes.
## The Goal
Each side starts with **twelve checkers**: Black and Red. You win by **taking every one of your opponent's checkers**, or by leaving them **with no legal move**. That second one sneaks up on people.
## The Board
Sixty-four squares, but you only ever play on the **32 dark ones**. Black starts on the far three rows and Red on the near three. Whichever colour you pick sits at the bottom of the board, so you're always pushing "up". Press **F** or the **Flip** button if you'd rather see it the other way round.
In **American checkers, Black moves first.** In a match, colours swap every game, so nobody keeps the first-move edge.
## Moving
- A plain checker is called a **man**. It moves **one square diagonally forward** onto an empty dark square.
- **To jump**, a man hops over an enemy checker that's diagonally next to it, landing on the empty square just beyond. The jumped checker comes off the board and goes into your tray.
- **Jumps are forced.** If you have a jump anywhere on the board, you must take one. If you have several, pick whichever you like.
- **Keep jumping.** If your checker lands where it can jump again, it has to carry on. A long chain like that is called a *multi-jump*, and it's the prettiest thing in the game.
## Kings
Get a man all the way to the far row and it's **crowned**. In this shop that means I stack a second checker on top. A **king** moves and jumps diagonally **forward and backward**.
In American rules, a man that reaches the far row in the middle of a jump **stops there**. The crowning ends the turn.
## How to Play Here
| Do this | And this happens |
|---|---|
| **Click a checker** (or press the arrow keys and Enter) | It lifts up and its moves are marked. |
| **Click a marked square** | The move is played. Gold squares are jumps, and the ×2 or ×3 badge shows how many it takes. |
| **Drag a checker** | Drop it on a marked square instead of clicking. |
| **Hover a marked square** | Shows the full route of a multi-jump, numbered hop by hop. |
| **Click the hops one at a time** | Useful when two different routes end on the same square. |
| **Z / Undo** | Takes back your last turn (and your opponent's reply). |
| **H / Hint** | I'll point at a move and tell you why I like it. |
| **Offer Draw / Resign** | Exactly what they say. |
| **Esc / Menu** | Settings, these rules, a new match, or leaving the shop. |
Pieces that can move glow when it's your turn. If a jump is forced, they glow orange.
## Draws
A game is a **draw** when:
- **the same position comes up three times** with the same side to move,
- **40 moves go by for each side** with no jump and no man moving (just kings shuffling), or
- **both players agree.** Offer a draw from the button, and your opponent might offer one too.
The status card warns you when a no-progress draw is getting close. You can set the limit to 25, 40 or 50 moves when you set up.
## Setting Up a Match
When you sit down you get a card to fill in:
| Option | Choices |
|---|---|
| **Rules** | American, Pool, Russian, Giveaway, or Casual (see below). |
| **Match** | A single game, best of 3, or best of 5. A draw is worth half a point. |
| **Your colour** | Red, Black, or a coin toss. |
| **Classic openings** | **Off by default.** Switch it on and I pull a ballot card from the cigar box: the first three moves of a named tournament opening, like the *Single Corner*, the *Dyke* or the *Will o' the Wisp*. You play on from there. In a match, each opening is played twice so both of you get each side. American rules only. |
| **Draw after** | 25, 40 or 50 moves without progress. |
## The Variants
- **American Checkers.** Everything above. The one they play in tournaments.
- **Pool Checkers.** Men can **jump backwards** too, and **kings fly**: they slide any distance along a diagonal and can jump a checker from far away, landing on any empty square past it. If you can keep jumping from one of those landing squares, you must land there. A man that reaches the far row in the middle of a jump keeps going as a man if it can, and is only crowned if it finishes there.
- **Russian Shashki.** Like Pool, except a man crowned in the middle of a jump **becomes a flying king on the spot** and keeps jumping. In Russian, Red (white, over there) moves first.
- **Giveaway.** Everything is backwards: **you win by losing all your checkers**, or by being left with no move. Jumps are still forced, and that's the whole trick. Make them take your pieces.
- **Casual.** American rules with **optional jumps**, the way folks play at the kitchen table.
In every variant, a checker that's been jumped stays on the board until the turn is over. You can't jump the same checker twice, and you can't land on it.
## Notation
The move sheet on the right uses the old tournament numbers. The dark squares are numbered **1 to 32**, starting at Black's side. **11-15** means a checker moved from 11 to 15, and **22x15x8** means a jump from 22 over two checkers, landing on 15 and then 8. Switch on **Square numbers** in the menu to see them painted on the board.
## Gus's Coaching
With **Gus warns before a bad move** switched on (it is by default), I'll lean over before you make a move that drops a piece for nothing and tell you what I'd play instead. You can always play it anyway, since it's your game. Turn on **Show threatened pieces** and I'll circle your checkers that could be jumped right now.
## A Few Things I've Learned
1. **Keep your back row home** as long as you can, especially the squares at the corners of the bridge (1 and 3 for Black, 30 and 32 for Red). As long as they're there, nobody gets crowned.
2. **Control the centre.** Checkers in the middle have more places to go and are harder to trap.
3. **Trade when you're ahead.** Five against four is close. Two against one is a win.
4. **Watch for the shot.** Giving up one checker to force a jump that sets up a double for you is the oldest trick there is.
5. **Kings in the double corner are hard to catch.** If you're behind, run for one. If you're ahead, don't let them.
Now rack 'em up. Coffee's on me.

336
tools/verifyCheckers.js Normal file
View File

@ -0,0 +1,336 @@
#!/usr/bin/env node
// verifyCheckers.js — headless checks for Checkers ("Gus's Back Room"):
// • geometry: 32 squares, standard numbering, diagonal rays
// • rules on hand-built positions, per variant: steps, forced capture,
// multi-jumps, crowning stops a chain (American) / continues as a man
// (Pool) / continues as a flying king (Russian), flying kings, Turkish
// strike (no double jumps), giveaway wins, casual optional jumps
// • draws: threefold repetition, the 40-move no-progress rule, agreement,
// resignation
// • notation: every legal move round-trips through notate/parseMove
// • every ballot opening is legal from the start
// • AI: every skill returns a legal move in budget; finds short shots;
// draw decisions are sane
// • self-play soak per variant: games end, piece counts never grow, no
// piece on a light square
// • skill ladder (mirrored colours)
// • layout: HUD rectangles on screen and clear of the board
// Usage: node tools/verifyCheckers.js [--quick]
import * as L from '../src/games/checkers/CheckersLogic.js';
import * as AI from '../src/games/checkers/CheckersAI.js';
import { BALLOTS } from '../src/games/checkers/CheckersData.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.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 sq = (n) => n - 1;
// Build a state from { b: [squares], B: [kings], r: [...], R: [...] }.
function pos(spec, { variant = 'american', turn = 'black' } = {}) {
const gs = L.createGame({ variant });
const board = new Array(32).fill(0);
for (const n of spec.b ?? []) board[sq(n)] = 1;
for (const n of spec.B ?? []) board[sq(n)] = 2;
for (const n of spec.r ?? []) board[sq(n)] = -1;
for (const n of spec.R ?? []) board[sq(n)] = -2;
return { ...gs, board, turn, reps: { [L.posKey(board, turn)]: 1 } };
}
const names = (gs) => L.legalMoves(gs).map(L.notate).sort();
// ── geometry ─────────────────────────────────────────────────────────────────
section('geometry');
ok('32 squares', L.RC.length === 32);
ok('square 1 is row 0 col 1', L.RC[0][0] === 0 && L.RC[0][1] === 1);
ok('square 5 is row 1 col 0', L.RC[4][0] === 1 && L.RC[4][1] === 0);
ok('square 32 is row 7 col 6', L.RC[31][0] === 7 && L.RC[31][1] === 6);
ok('all dark', L.RC.every(([r, c]) => (r + c) % 2 === 1));
ok('ray from 1 down-right', L.RAYS[0][3].map((i) => i + 1).join(',') === '6,10,15,19,24,28', L.RAYS[0][3].map((i) => i + 1).join(','));
{
const b = L.initialBoard();
const c = L.counts(b);
ok('12 v 12 at start', c.black === 12 && c.red === 12);
}
// ── basic American rules ─────────────────────────────────────────────────────
section('american rules');
{
const gs = L.createGame();
ok('black moves first', gs.turn === 'black');
ok('7 opening moves', L.legalMoves(gs).length === 7, names(gs).join(' '));
ok('11-15 legal', names(gs).includes('11-15'));
const s2 = L.applyMove(gs, L.parseMove(gs, '11-15'));
ok('turn passes', s2.turn === 'red' && s2.ply === 1);
ok('history notated', s2.history[0].n === '11-15');
}
{
// forced capture: black 15, red 18 → 15x22 only (22 empty)
const gs = pos({ b: [15, 1], r: [18, 30] });
ok('capture forced', names(gs).join(' ') === '15x22', names(gs).join(' '));
}
{
// men don't capture backwards in American
const gs = pos({ b: [15], r: [11, 30] });
ok('no backward man jump', !names(gs).some((n) => n.includes('x')), names(gs).join(' '));
}
{
// double jump: black 6 over red 10 and 19 → 6x15x24
const gs = pos({ b: [6], r: [10, 19, 32] });
ok('double jump', names(gs).join(' ') === '6x15x24', names(gs).join(' '));
const s = L.applyMove(gs, L.legalMoves(gs)[0]);
ok('both captured', L.counts(s.board).red === 1);
}
{
// crowning stops the chain: black 22 over 26 to 31 (crown row), a red on 27 that a king could jump next
const gs = pos({ b: [22], r: [26, 27, 3] });
const ms = L.legalMoves(gs);
ok('crown ends turn (American)', ms.length === 1 && L.notate(ms[0]) === '22x31' && ms[0].crown, ms.map(L.notate).join(' '));
}
{
// king steps one square only
const gs = pos({ B: [18], r: [1] });
ok('king steps 4 ways', names(gs).length === 4, names(gs).join(' '));
}
{
// Turkish strike: a king can't jump the same piece twice.
// black king 19 (r4c5)… use a ring: B on 10, reds on 14,15,22,23 — loop 10x17x26x19x10 legal (4 caps) but not reusing
const gs = pos({ B: [10], r: [14, 15, 22, 23] });
const ms = L.legalMoves(gs);
ok('ring capture exists', ms.some((m) => m.caps.length === 4), ms.map(L.notate).join(' '));
ok('no piece jumped twice', ms.every((m) => new Set(m.caps).size === m.caps.length));
}
// ── pool / russian ───────────────────────────────────────────────────────────
section('pool & russian');
{
const gs = pos({ b: [15], r: [11, 30] }, { variant: 'pool' });
ok('pool man jumps backward', names(gs).join(' ') === '15x8', names(gs).join(' '));
}
{
// flying king on 1 sees red on 15 (ray 6,10,15,19,24,28): lands 19, 24 or 28
const gs = pos({ B: [1], r: [15, 4] }, { variant: 'pool' });
ok('flying king captures at range', names(gs).join(' ') === '1x19 1x24 1x28', names(gs).join(' '));
const q = pos({ B: [1], r: [4] }, { variant: 'pool' });
ok('flying king slides', names(q).length === 7, names(q).join(' '));
}
{
// must land where the capture continues: B on 1, red 10 and red 20 → from 15? (ray 1:6,10,15,19,24,28)
// red at 10: lands 15,19,24,28. From 15 (r3c4) down-left ray 18? put red 18: 15x22 continues → only 1x15x22
const gs = pos({ B: [1], r: [10, 18, 4] }, { variant: 'pool' });
ok('flying king must choose continuing landing', names(gs).every((n) => n.split('x').length === 3), names(gs).join(' '));
}
{
// a black man reaching row 7 mid-jump: 22 over 26 → 31 then 31 could jump 27? men backwards allowed in pool: 31 over 27 → 24? (31 r7c4, 27 r6c5 → 24? r5c6 is sq 24)
const pool = pos({ b: [22], r: [26, 27, 1] }, { variant: 'pool' });
const pm = L.legalMoves(pool);
ok('pool: continues as a man through the crown row', pm.length === 1 && L.notate(pm[0]) === '22x31x24' && !pm[0].crown, pm.map(L.notate).join(' '));
const rus = pos({ b: [22], r: [26, 27, 1] }, { variant: 'russian' });
const rm = L.legalMoves(rus);
ok('russian: crowns and continues as a king', rm.length >= 1 && rm.every((m) => m.crown && m.caps.length === 2), rm.map(L.notate).join(' '));
const am = L.legalMoves(pos({ b: [22], r: [26, 27, 1] }));
ok('american: stops on the crown', am.length === 1 && am[0].caps.length === 1 && am[0].crown);
}
{
const gs = L.createGame({ variant: 'russian' });
ok('russian: red (white) starts', gs.turn === 'red');
}
// ── giveaway / casual ────────────────────────────────────────────────────────
section('giveaway & casual');
{
const gs = pos({ b: [15], r: [18, 30] }, { variant: 'giveaway' });
const s = L.applyMove(gs, L.legalMoves(gs)[0]);
ok('giveaway capture still forced', L.legalMoves(gs).length === 1);
void s;
// black's last piece jumped → black has none → black WINS
const g2 = pos({ b: [18], r: [22, 1] }, { variant: 'giveaway', turn: 'red' });
const s2 = L.applyMove(g2, L.legalMoves(g2)[0]);
ok('giveaway: losing every piece wins', s2.phase === 'game_over' && s2.winner === 'black', `${s2.winner} ${L.legalMoves(g2).map(L.notate)}`);
const a2 = L.applyMove(pos({ b: [18], r: [22, 1] }, { turn: 'red' }), L.legalMoves(pos({ b: [18], r: [22, 1] }, { turn: 'red' }))[0]);
ok('american: losing every piece loses', a2.winner === 'red' && a2.endReason === 'wiped');
}
{
const gs = pos({ b: [15, 1], r: [18, 30] }, { variant: 'casual' });
const n = names(gs);
ok('casual: jump optional', n.includes('15x22') && n.some((x) => x.includes('-')), n.join(' '));
}
{
// blocked: black man on 29? black men move down; black on 32 (row 7) can't move as a man → no moves
const gs = pos({ b: [28], r: [32, 1] }, { turn: 'red' });
// red 32 → 27? leave black on 28 r6c7 needs 32 (r7c6) empty → after red moves 32-27, 32 free: let's instead block fully
void gs;
const g = pos({ b: [29], r: [5] }, { turn: 'red' }); // black man on 29 (row 7) can never move
const s = L.applyMove(g, L.legalMoves(g)[0]);
ok('no legal move loses', s.phase === 'game_over' && s.winner === 'red' && s.endReason === 'blocked', `${s.phase} ${s.winner} ${s.endReason}`);
}
// ── draws ────────────────────────────────────────────────────────────────────
section('draws');
{
let gs = pos({ B: [1], R: [32] });
const seq = ['1-6', '32-27', '6-1', '27-32', '1-6', '32-27', '6-1', '27-32'];
for (const t of seq) { if (gs.phase !== 'playing') break; gs = L.applyMove(gs, L.parseMove(gs, t)); }
ok('threefold repetition draws', gs.phase === 'game_over' && gs.winner === 'draw' && gs.endReason === 'repetition', `${gs.phase} ${gs.endReason} ply ${gs.ply}`);
}
{
let gs = { ...pos({ B: [1, 3], R: [30, 32] }), quietLimit: 5 };
const rng = mulberry32(7);
let n = 0;
while (gs.phase === 'playing' && n < 40) {
const ms = L.legalMoves(gs);
gs = L.applyMove(gs, ms[Math.floor(rng() * ms.length)]); n++;
}
ok('no-progress rule ends king shuffles', gs.phase === 'game_over' && gs.winner === 'draw', `${gs.endReason} after ${n}`);
ok('…by quiet or repetition', ['quiet', 'repetition'].includes(gs.endReason));
}
{
const gs = L.createGame();
ok('agreed draw', L.agreeDraw(gs).winner === 'draw');
const r = L.resign(gs, 'red');
ok('resign', r.winner === 'black' && r.endReason === 'resign');
ok('quietLeft at start', L.quietLeft(gs) === 40);
}
// ── notation round-trip ──────────────────────────────────────────────────────
section('notation');
{
const rng = mulberry32(11);
let bad = 0, tested = 0;
for (const variant of L.VARIANT_ORDER) {
let gs = L.createGame({ variant });
for (let i = 0; i < 120 && gs.phase === 'playing'; i++) {
const ms = L.legalMoves(gs);
const uniq = ms.filter((m) => ms.filter((x) => L.notate(x) === L.notate(m)).length === 1);
for (const m of uniq) { tested++; if (L.notate(L.parseMove(gs, L.notate(m)) ?? { caps: [], from: -1, to: -1 }) !== L.notate(m)) bad++; }
gs = L.applyMove(gs, ms[Math.floor(rng() * ms.length)]);
}
}
ok(`${tested} moves round-trip`, bad === 0, `${bad} bad`);
}
// ── ballots ──────────────────────────────────────────────────────────────────
section('ballots');
for (const b of BALLOTS) {
let g = null, err = '';
try { g = L.createGame({ ballot: b }); } catch (e) { err = e.message; }
ok(`${b.name} ${b.moves.join(' ')}`, g && g.ply === 3 && g.turn === 'red' && g.ballot?.name === b.name, err);
}
ok('ballot ignored outside American', L.createGame({ variant: 'pool', ballot: BALLOTS[0] }).ply === 0);
// ── AI ───────────────────────────────────────────────────────────────────────
section('AI');
{
const gs = L.createGame();
for (let k = 1; k <= 5; k++) {
const t0 = Date.now();
const m = AI.chooseMove(gs, k, { rng: mulberry32(k) });
const dt = Date.now() - t0;
ok(`skill ${k} legal`, m && L.legalMoves(gs).some((x) => L.moveKey(x) === L.moveKey(m)));
ok(`skill ${k} in budget (${dt}ms)`, dt < AI.SKILL[k].ms + 400);
}
}
{
// a shot: give one, take two. Black 18, red 23, 27? Simpler: forced win of material
// black to move: man on 15 with red on 19 & 26 — 15-18? Just require the AI takes a free double jump over a single.
const gs = pos({ b: [6, 12], r: [10, 19, 16, 32] }, { variant: 'casual' });
const m = AI.chooseMove(gs, 5);
ok('takes the double jump', m && m.caps.length === 2, m && L.notate(m));
}
{
// KvK vs KKvK: the side with two kings should not offer/accept losing; trivial: AI finds mate-in-few: black K on 28? (skip deep proof) — check eval sign
const gs = pos({ B: [14, 15], R: [32] });
const ev = AI.evaluate(gs.board, 'black', L.rulesOf('american'));
ok('two kings vs one is good for black', ev > 100, ev);
const gv = AI.evaluate(gs.board, 'black', L.rulesOf('giveaway'));
ok('giveaway inverts material', gv < 0, gv);
}
{
const h = AI.hint(L.createGame(), { ms: 200 });
ok('hint returns a legal move with a reason', h && h.reason && L.legalMoves(L.createGame()).some((m) => L.moveKey(m) === L.moveKey(h.move)));
const early = AI.drawDecision(L.createGame(), 'red', 3, { ms: 100 });
ok('no draws in the opening', !early.accept);
const ahead = pos({ B: [14, 15, 18], R: [32] });
const d = AI.drawDecision({ ...ahead, ply: 60 }, 'black', 5, { ms: 150 });
ok('won side declines a draw', !d.accept, JSON.stringify(d));
const behind = AI.drawDecision({ ...ahead, ply: 60, turn: 'red' }, 'red', 5, { ms: 150 });
ok('lost side accepts a draw', behind.accept, JSON.stringify(behind));
}
// ── soak ─────────────────────────────────────────────────────────────────────
section('self-play soak');
function play(variant, skillB, skillR, seed, { ballot = null, ms = null } = {}) {
const rng = mulberry32(seed);
let gs = L.createGame({ variant, ballot });
let errs = 0;
let prev = L.counts(gs.board);
while (gs.phase === 'playing') {
const k = gs.turn === 'black' ? skillB : skillR;
const m = AI.chooseMove(gs, k, { rng, ms });
if (!m) { errs++; break; }
gs = L.applyMove(gs, m);
const c = L.counts(gs.board);
if (c.black > prev.black || c.red > prev.red) errs++;
if (gs.board.some((p, i) => p && (L.RC[i][0] + L.RC[i][1]) % 2 === 0)) errs++;
prev = c;
}
return { gs, errs };
}
{
const per = QUICK ? 1 : 3;
for (const v of L.VARIANT_ORDER) {
let errs = 0, ended = 0, plies = 0;
const tally = { black: 0, red: 0, draw: 0 };
for (let i = 0; i < per; i++) {
const r = play(v, 1 + (i % 3), 2 + (i % 3), 100 + i, { ms: 30 });
errs += r.errs; if (r.gs.phase === 'game_over') ended++; plies += r.gs.ply; tally[r.gs.winner]++;
}
ok(`${v}: ${per} games end cleanly (avg ${Math.round(plies / per)} plies; ${JSON.stringify(tally)})`, errs === 0 && ended === per, `${errs} errs`);
}
}
// ── ladder ───────────────────────────────────────────────────────────────────
section('skill ladder');
{
const pairs = QUICK ? [[1, 5]] : [[1, 3], [2, 5], [3, 5]];
for (const [lo, hi] of pairs) {
let hiPts = 0, games = 0;
const n = QUICK ? 2 : 4;
for (let i = 0; i < n; i++) {
const hiBlack = i % 2 === 0;
const r = play('american', hiBlack ? hi : lo, hiBlack ? lo : hi, 900 + i * 7 + lo, { ms: hi === 5 ? 120 : 60 });
const w = r.gs.winner;
if (w === 'draw') hiPts += 0.5; else if ((w === 'black') === hiBlack) hiPts += 1;
games++;
}
ok(`skill ${hi} ≥ skill ${lo} (${hiPts}/${games})`, hiPts >= games / 2, `${hiPts}/${games}`);
}
}
// ── layout ───────────────────────────────────────────────────────────────────
section('layout');
try {
const Lay = await import('../src/games/checkers/CheckersLayout.js');
const rects = Lay.HUD_RECTS();
const B = Lay.BOARD_RECT;
const inter = (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;
for (const [name, r] of Object.entries(rects)) {
ok(`${name} on screen`, r.x >= 0 && r.y >= 0 && r.x + r.w <= 1920 && r.y + r.h <= 1080, JSON.stringify(r));
ok(`${name} clear of board`, !inter(r, B), 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`, !inter(rects[keys[i]], rects[keys[j]]));
}
}
} catch (e) {
ok('layout module loads', false, e.message);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);