From 50078661d2b4950797194fb317051fdbbaacdaaf Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Tue, 1 Dec 2026 13:34:29 -0700 Subject: [PATCH] Rewrite checkers as themed barbershop game with variants and strong AI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- src/games/checkers/CheckersAI.js | 362 ++++-- src/games/checkers/CheckersArt.js | 727 +++++++++++ src/games/checkers/CheckersData.js | 36 + src/games/checkers/CheckersDialogs.js | 151 +++ src/games/checkers/CheckersEndScreen.js | 191 +++ src/games/checkers/CheckersGame.js | 1530 ++++++++++++++++------- src/games/checkers/CheckersHud.js | 225 ++++ src/games/checkers/CheckersLayout.js | 99 ++ src/games/checkers/CheckersLogic.js | 478 +++++-- src/games/checkers/CheckersPieces.js | 167 +++ src/games/checkers/CheckersSound.js | 193 +++ src/games/checkers/CheckersTalk.js | 132 ++ src/games/checkers/tutorial.md | 98 ++ tools/verifyCheckers.js | 336 +++++ 14 files changed, 4037 insertions(+), 688 deletions(-) create mode 100644 src/games/checkers/CheckersArt.js create mode 100644 src/games/checkers/CheckersData.js create mode 100644 src/games/checkers/CheckersDialogs.js create mode 100644 src/games/checkers/CheckersEndScreen.js create mode 100644 src/games/checkers/CheckersHud.js create mode 100644 src/games/checkers/CheckersLayout.js create mode 100644 src/games/checkers/CheckersPieces.js create mode 100644 src/games/checkers/CheckersSound.js create mode 100644 src/games/checkers/CheckersTalk.js create mode 100644 src/games/checkers/tutorial.md create mode 100644 tools/verifyCheckers.js diff --git a/src/games/checkers/CheckersAI.js b/src/games/checkers/CheckersAI.js index bc4c3d3..6cf8891 100644 --- a/src/games/checkers/CheckersAI.js +++ b/src/games/checkers/CheckersAI.js @@ -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]; - 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; - } - // Central files are worth slightly more than the edges. - v += (c >= 2 && c <= 5) ? 4 : 0; - score += (p.color === aiColor ? v : -v); +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; + 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; } + 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); } } - // Small mobility term. - const moves = getValidMoves(state).length; - score += (state.turn === aiColor ? moves : -moves) * 1.5; - return score; + 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; + } + 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 }); + } + return best; } - 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]; +// 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; }); +} - if (Math.random() < prof.blunder) { - return steps[Math.floor(Math.random() * steps.length)]; - } +// 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 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 }); +/** + * 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; +} - 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; } +/** 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 best ?? steps[0]; + return noisy[0].move; } -function stepKey(step) { - return `${step.from[0]},${step.from[1]}->${step.to[0]},${step.to[1]}`; +/** 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 }; diff --git a/src/games/checkers/CheckersArt.js b/src/games/checkers/CheckersArt.js new file mode 100644 index 0000000..2e51077 --- /dev/null +++ b/src/games/checkers/CheckersArt.js @@ -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-, ck-king- ribbed composition checkers (2× bake); +// ck-man--s, ck-king--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 }; diff --git a/src/games/checkers/CheckersData.js b/src/games/checkers/CheckersData.js new file mode 100644 index 0000000..21bb724 --- /dev/null +++ b/src/games/checkers/CheckersData.js @@ -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)]; +} diff --git a/src/games/checkers/CheckersDialogs.js b/src/games/checkers/CheckersDialogs.js new file mode 100644 index 0000000..9c51f33 --- /dev/null +++ b/src/games/checkers/CheckersDialogs.js @@ -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; +} diff --git a/src/games/checkers/CheckersEndScreen.js b/src/games/checkers/CheckersEndScreen.js new file mode 100644 index 0000000..f9646a3 --- /dev/null +++ b/src/games/checkers/CheckersEndScreen.js @@ -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; +} diff --git a/src/games/checkers/CheckersGame.js b/src/games/checkers/CheckersGame.js index 04411a9..6eb07ec 100644 --- a/src/games/checkers/CheckersGame.js +++ b/src/games/checkers/CheckersGame.js @@ -1,532 +1,1130 @@ +// CheckersGame.js — "Gus's Back Room". The scene only orchestrates: rules in +// CheckersLogic, the opponents in CheckersAI, geometry in CheckersLayout, art +// in CheckersArt, checkers in CheckersPieces, furniture in CheckersHud, talk +// in CheckersTalk, sound in CheckersSound. +// +// Flow: the setup card (rules, match length, colour, ballot openings, draw +// rule) → each game: checkers drop onto the board, the side with the move +// plays. On your turn click or drag a checker, then a marked square; a +// multi-jump can be played in one click on its landing square or hop by hop. +// Undo rewinds your last turn; Hint asks Gus. Offer a draw or resign from +// the buttons. Between games of a match colours swap; at the end, a summary +// with a replay board. Everything in progress is saved, so a reload resumes. + import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; +import { GAME_WIDTH, GAME_HEIGHT } from '../../config.js'; import { auth } from '../../services/auth.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { api } from '../../services/api.js'; import { playSound, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { getGameSoundtrack } from '../../services/soundtrack.js'; +import { TutorialModal } from '../../ui/TutorialModal.js'; +import { aiTiming, PACE } from '../../ui/cardtable/AITiming.js'; +import * as L from './CheckersLogic.js'; +import { chooseMove, hint, analyze, drawDecision, wantsDraw, clampSkill, describeIdea } from './CheckersAI.js'; +import { BALLOTS, drawBallot } from './CheckersData.js'; import { - createInitialState, getValidMoves, applyMove, isGameOver, getWinner, pieceCounts, SIZE, -} from './CheckersLogic.js'; -import { chooseMove, nextThinkDelay } from './CheckersAI.js'; + BX, BY, SQ, BOARD, BCX, BANNER, WINDOW, POLE, PERCOLATOR, squareXY, cellAt, +} from './CheckersLayout.js'; +import { prepareCheckersArt, DISPLAY_FONT, BOLD_FONT, SERIF, BOARD_POS } from './CheckersArt.js'; +import { PieceSet } from './CheckersPieces.js'; +import { Hud } from './CheckersHud.js'; +import { openPauseMenu, openSetup, confirmBox, toast } from './CheckersDialogs.js'; +import { openEndScreen, openBetween, resultLine } from './CheckersEndScreen.js'; +import { gusLine, opponentLine, tierOf } from './CheckersTalk.js'; +import { clack, pick as pickSnd, deny, flick, crown as crownSnd, sting, Ambience } from './CheckersSound.js'; -// ── Layout ────────────────────────────────────────────────────────────────── -const SQ = 104; -const BOARD = SQ * SIZE; // 832 -const BX = Math.round(GAME_WIDTH / 2 - BOARD / 2); // centered -const BY = Math.round(GAME_HEIGHT / 2 - BOARD / 2); -const FRAME = 30; -const CR = SQ * 0.38; // checker radius - -const DEPTH = { board: 0, piece: 10, overlay: 20, moving: 30, ui: 50, banner: 60 }; - -const C = { - light: 0xebe6c8, - dark: 0x6f9c5a, - frame: 0x3a2414, - frameLt: 0x6b4423, - frameLn: 0x8b5c2a, - wRing: 0xfffaf0, - wFill: 0xe6d8b8, - wEdge: 0xb8a679, - bRing: 0x4a4654, - bFill: 0x201e26, - bEdge: 0x12111a, - kingGold: 0xffd54a, - selGold: 0xffd700, +const SETTINGS_KEY = 'checkers-settings'; +const SAVE_KEY = 'checkers-save-v1'; +const RECORD_KEY = 'checkers-record'; +const DEFAULT_SETTINGS = { + pace: 'normal', skipAI: false, hints: true, coach: true, threats: false, numbers: false, symbols: false, ambience: true, + setup: { variant: 'american', games: 1, color: 'red', openings: false, quietLimit: 40 }, }; +const D = { bg: 0, board: 5, number: 6, trail: 7, mark: 8, glow: 9, piece: 10, path: 40, cursor: 42, hud: 50, fx: 70, banner: 80, end: 95, modal: 110 }; export default class CheckersGame extends Phaser.Scene { constructor() { super('CheckersGame'); } init(data) { - this.gameDef = data.game; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; + this.initData = data ?? {}; + this.gameDef = this.initData.game; + this.opponents = this.initData.opponents ?? []; + this.playfield = this.initData.playfield ?? null; + this.opp = this.opponents[0] ?? { id: 'gus-regular', name: 'Old Walt', skill: 3 }; + this.oppName = this.opp.name ?? 'Opponent'; + this.skill = clampSkill(this.opp.skill ?? 3); + this.tier = tierOf(this.skill); + this.ended = false; + this.busy = true; + this.modal = null; + this.phase = 'setup'; // setup | human | ai | over + this.sel = null; // { sq, it, moves, prefix: [sq…] } + this.drag = null; + this.markers = []; + this.glows = []; + this.undoStack = []; this.gs = null; - this.animating = false; - this.selected = null; // [r, c] of selected piece - this.pieceObjs = []; // [{ r, c, container }] - this.overlayObjs = []; // transient highlights / hints / selection ring - this.opponentPortrait = null; - this.turnText = null; + this.match = null; + this.manualFlip = false; + this.cursor = null; + this.clocks = { human: 0, ai: 0 }; + this.turnStart = 0; + this.turnAnalysis = null; + this.lastOfferPly = -99; + this.aiOfferPly = -99; + this.saidQuiet = 99; + this.captured = { top: [], bottom: [] }; + try { + const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + this.settings = { ...DEFAULT_SETTINGS, ...s, setup: { ...DEFAULT_SETTINGS.setup, ...(s.setup ?? {}) } }; + } catch (_) { this.settings = { ...DEFAULT_SETTINGS, setup: { ...DEFAULT_SETTINGS.setup } }; } } + get k() { return PACE[this.settings.pace] ?? 1; } + get humanColor() { return this.match?.humanColor ?? 'red'; } + get aiColor() { return L.other(this.humanColor); } + get flipped() { return (this.humanColor === L.BLACK) !== this.manualFlip; } + get rules() { return L.rulesOf(this.gs?.variant); } + create() { - new MusicPlayer(this, this.cache.json.get('music').tracks); - this.buildParticleTexture(); - this.buildPlayfield(); - this.buildBoard(); - this.buildUI(); - this.buildPlayerCards(); - this.initGame(); + const { tracks, volume } = getGameSoundtrack(this); + if (tracks.length) new MusicPlayer(this, tracks, volume); + this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x0c0906).setDepth(-2); + prepareCheckersArt(this).then(() => { + if (!this.sys.isActive()) return; + this.build(); + this.begin(); + }); } - // ── Construction ──────────────────────────────────────────────────────────── - - buildParticleTexture() { - const g = this.make.graphics({ x: 0, y: 0, add: false }); - g.fillStyle(0xffffff, 1); - g.fillCircle(5, 5, 5); - g.generateTexture('checkersParticle', 10, 10); - g.destroy(); - } - - buildPlayfield() { + // ── build ─────────────────────────────────────────────────────────────────── + build() { const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(DEPTH.board - 2); - } else if (pf?.fallbackColor) { - const color = parseInt(pf.fallbackColor.replace('#', ''), 16); - this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, color) - .setDepth(DEPTH.board - 2); + this.fullRoom = !(pf?.key && this.textures.exists(pf.key) && !pf.key.startsWith('playfield-colored-')); + if (!this.fullRoom) { + this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.bg); + this.add.image(0, 0, 'ck-vignette').setOrigin(0).setDepth(D.bg + 1); + this.add.image(0, 0, 'ck-props').setOrigin(0).setDepth(D.bg + 2); + } else { + this.add.image(0, 0, 'ck-room').setOrigin(0).setDepth(D.bg); + } + this.add.image(BOARD_POS.x, BOARD_POS.y, 'ck-board').setOrigin(0).setDepth(D.board); + + this.numberTexts = []; + for (let sq = 0; sq < L.N; sq++) { + this.numberTexts.push(this.add.text(0, 0, String(sq + 1), { + fontFamily: SERIF, fontSize: '13px', color: '#d8e8c8', + }).setAlpha(0.55).setDepth(D.number).setVisible(false)); + } + this.trailG = this.add.graphics().setDepth(D.trail); + this.markG = this.add.graphics().setDepth(D.mark); + this.pathG = this.add.graphics().setDepth(D.path); + this.cursorG = this.add.graphics().setDepth(D.cursor); + this.threatG = this.add.graphics().setDepth(D.mark); + this.pathTexts = []; + + this.pieces = new PieceSet(this, D.piece, { symbols: this.settings.symbols }); + const name = auth.user?.username ?? 'You'; + this.hud = new Hud(this, D.hud, { + names: { top: this.oppName, bottom: name }, skill: this.skill, opponent: this.opp, + onButton: (k) => this.onButton(k), + }).build(); + this.hud.setSymbols(this.settings.symbols); + + this.ambienceFx(); + this.ambience = new Ambience(this); + if (this.settings.ambience) this.ambience.start(); + + this.input.on('pointerdown', (p) => this.onPointerDown(p)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.on('pointerupoutside', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this.time.addEvent({ delay: 1000, loop: true, callback: () => { if (this.gs && this.phase !== 'over' && this.phase !== 'setup') this.refreshHud(); } }); + this.events.once('shutdown', () => { + this.ended = true; + this.ambience?.stop(); + this.setCursor('default'); + }); + } + + ambienceFx() { + if (!this.fullRoom) return; + // the barber pole turning in the rain + this.pole = this.add.tileSprite(POLE.x + POLE.w / 2, POLE.y + POLE.h / 2, POLE.w, POLE.h, 'ck-pole-stripes').setDepth(D.bg + 1); + const glow = this.add.image(POLE.x + POLE.w / 2, POLE.y + POLE.h / 2, 'ck-pole-glow').setScale(1.4, 2).setDepth(D.bg + 2) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.5); + this.tweens.add({ targets: glow, alpha: { from: 0.38, to: 0.6 }, duration: 1800, yoyo: true, repeat: -1, ease: 'Sine.InOut' }); + // rain streaking down the glass + this.time.addEvent({ delay: 90, loop: true, callback: () => { + if (this.ended) return; + const x = WINDOW.x + 6 + Math.random() * (WINDOW.w - 12); + const y = WINDOW.y + Math.random() * WINDOW.h * 0.5; + const len = 40 + Math.random() * 120; + const d = this.add.image(x, y, 'ck-rain').setDepth(D.bg + 3).setAlpha(0.15 + Math.random() * 0.35).setScale(1, 0.6 + Math.random() * 0.8); + this.tweens.add({ targets: d, y: Math.min(WINDOW.y + WINDOW.h - 14, y + len), alpha: 0, duration: 380 + Math.random() * 500, ease: 'Quad.In', onComplete: () => d.destroy() }); + } }); + // steam off the percolator + this.time.addEvent({ delay: 700, loop: true, callback: () => { + if (this.ended) return; + const st = this.add.image(PERCOLATOR.x + (Math.random() - 0.5) * 10, PERCOLATOR.y - 70, 'ck-steam').setDepth(D.bg + 3).setAlpha(0).setScale(0.35); + this.tweens.add({ targets: st, y: st.y - 110 - Math.random() * 30, x: st.x + (Math.random() - 0.5) * 50, alpha: { from: 0.35, to: 0 }, scale: 1.4, duration: 2800, ease: 'Sine.Out', onComplete: () => st.destroy() }); + } }); + } + + update(_t, dt) { + if (this.pole) this.pole.tilePositionY -= dt * 0.025; + } + + // ── start / resume / save ─────────────────────────────────────────────────── + begin() { + const save = this.loadSave(); + if (save) { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: 'Pick up where you left off?', + text: `There's a game in progress against ${this.oppName}. The pieces are where you left them.`, + yes: 'Resume', no: 'Start Fresh', depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); this.resume(save); }, + onNo: () => { this.modal = null; this.clearSave(); this.openSetupCard(); }, + }); + } else this.openSetupCard(); + } + + signature() { return `${this.opp.id ?? this.oppName}|${this.skill}`; } + + loadSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || s.sig !== this.signature() || !s.gs || !s.match) return null; + return s; + } catch (_) { return null; } + } + + save(between = false) { + if (!this.gs || !this.match) return; + try { + localStorage.setItem(SAVE_KEY, JSON.stringify({ + v: 1, sig: this.signature(), gs: this.gs, match: this.match, clocks: this.clocks, between, captured: this.captured, savedAt: Date.now(), + })); + } catch (_) { /* private mode */ } + } + + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + resume(save) { + this.match = save.match; + this.gs = save.gs; + this.clocks = save.clocks ?? { human: 0, ai: 0 }; + this.captured = save.captured ?? { top: [], bottom: [] }; + this.pieces.build(this.gs.board, this.flipped); + this.layoutNumbers(); + this.hud.gusSays(gusLine('welcomeBack')); + if (save.between) { this.phase = 'over'; this.betweenGames(); return; } + this.refreshHud(); + this.nextTurn(); + } + + openSetupCard() { + this.phase = 'setup'; + this.busy = true; + this.hud.hidePortraits(); + this.hud.setStatus('Gus\'s Back Room', 'Pick the rules and sit down.'); + this.hud.gusSays(gusLine('welcome')); + this.modal = openSetup(this, { + prefs: this.settings.setup, depth: D.modal, opponentName: this.oppName, + onStart: (p) => { + this.modal = null; + this.hud.showPortraits(); + this.settings.setup = { ...p }; + this.persistSettings(); + this.startMatch(p); + }, + onLeave: () => this.scene.start('GameMenu'), + }); + } + + startMatch(p) { + const color = p.color === 'random' ? (Math.random() < 0.5 ? L.RED : L.BLACK) : p.color; + this.match = { + games: p.games, variant: p.variant, openings: p.openings && p.variant === 'american', quietLimit: p.quietLimit, + firstColor: color, humanColor: color, results: [], ballots: [], human: 0, ai: 0, + }; + this.hud.say(opponentLine('greet', this.tier)); + this.startGame(); + } + + async startGame() { + const m = this.match; + const idx = m.results.length; + m.humanColor = idx % 2 === 0 ? m.firstColor : L.other(m.firstColor); + let ballot = null; + if (m.openings) { + const pair = Math.floor(idx / 2); + if (m.ballots[pair] == null) m.ballots[pair] = drawBallot(Math.random, m.ballots); + ballot = BALLOTS[m.ballots[pair]]; + } + this.gs = L.createGame({ variant: m.variant, quietLimit: m.quietLimit, ballot }); + this.undoStack = []; + this.clocks = { human: 0, ai: 0 }; + this.captured = { top: [], bottom: [] }; + this.pendingFlicks = { top: 0, bottom: 0 }; + this.lastOfferPly = -99; this.aiOfferPly = -99; this.saidQuiet = 99; + this.manualFlip = false; + this.clearSelection(); + this.trailG.clear(); + this.pieces.build(this.gs.board, this.flipped); + this.layoutNumbers(); + this.phase = 'intro'; + this.busy = true; + this.refreshHud(); + this.hud.setStatus('Setting up', `${L.VARIANTS[m.variant].name}${m.games > 1 ? ` · game ${idx + 1} of up to ${m.games}` : ''}`); + if (idx > 0) this.hud.gusSays(gusLine('newGame')); + await this.pieces.dropIn(this.k * 0.8, (i) => { if (i % 4 === 0) clack(this, { k: 0, vol: 0.06 }); }); + if (this.ended) return; + const you = this.humanColor === L.BLACK ? 'Black' : 'Red'; + const first = this.rules.first === this.humanColor; + this.banner(`You play ${you}`, this.humanColor === L.BLACK ? 0xc8c4d8 : 0xff8a70, 0.6, true); + await this.wait(900 * this.k); + if (this.gs.ballot) { + this.hud.gusSays(gusLine('ballot', { name: this.gs.ballot.name }), { hold: 9000 }); + this.drawTrail(); + this.banner(`Ballot: ${this.gs.ballot.name}`, 0xf0d890, 0.55, true); + await this.wait(1200 * this.k); + } else if (this.rules.giveaway) { + this.hud.gusSays(gusLine('giveaway')); + } else if (idx === 0) { + this.hud.gusSays(first ? 'You\'ve got the first move.' : `${this.oppName} moves first.`); + } + this.save(); + this.nextTurn(); + } + + // ── HUD ───────────────────────────────────────────────────────────────────── + refreshHud(thinking = false) { + if (!this.gs) return; + const live = { ...this.clocks }; + if (this.phase === 'human') live.human += Date.now() - this.turnStart; + else if (this.phase === 'ai') live.ai += Date.now() - this.turnStart; + this.hud.refresh(this.gs, { + humanColor: this.humanColor, thinking: thinking || this.phase === 'ai', clocks: live, + match: this.match ? { games: this.match.games, human: this.match.human, ai: this.match.ai } : null, + captured: this.shownCaptured(), + }); + const mine = this.canMoveNow(); + this.hud.setButton('undo', mine && this.undoStack.length > 0); + this.hud.setButton('hint', mine); + this.hud.setButton('draw', mine && this.gs.ply - this.lastOfferPly >= 10 && this.gs.ply >= 8); + this.hud.setButton('resign', mine); + } + + setStatus(a, b = '') { this.hud?.setStatus(a, b); } + + layoutNumbers() { + for (let sq = 0; sq < L.N; sq++) { + const { x, y } = squareXY(L.RC[sq], this.flipped); + this.numberTexts[sq].setPosition(x - SQ / 2 + 6, y - SQ / 2 + 4).setVisible(this.settings.numbers); } } - buildBoard() { - const g = this.add.graphics().setDepth(DEPTH.board); + drawTrail() { + const g = this.trailG; + g.clear(); + const h = this.gs?.history[this.gs.history.length - 1]; + if (!h) return; + const col = h.color === L.BLACK ? 0xc8c4e0 : 0xff9a84; + const pts = h.path.map((sq) => squareXY(L.RC[sq], this.flipped)); + g.fillStyle(col, 0.16).fillRect(pts[0].x - SQ / 2, pts[0].y - SQ / 2, SQ, SQ); + g.lineStyle(3, col, 0.55).strokeRect(pts[0].x - SQ / 2 + 3, pts[0].y - SQ / 2 + 3, SQ - 6, SQ - 6); + for (let i = 1; i < pts.length; i++) { + const a = pts[i - 1], b = pts[i]; + for (let t = 0.12; t < 0.92; t += 0.1) g.fillStyle(col, 0.6).fillCircle(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, 3); + } + for (const c of h.caps) { + const p = squareXY(L.RC[c], this.flipped); + g.lineStyle(4, 0xe05040, 0.55); + g.lineBetween(p.x - 14, p.y - 14, p.x + 14, p.y + 14); + g.lineBetween(p.x + 14, p.y - 14, p.x - 14, p.y + 14); + } + } - // Wood frame - g.fillStyle(C.frame, 1); - g.fillRoundedRect(BX - FRAME, BY - FRAME, BOARD + FRAME * 2, BOARD + FRAME * 2, 12); - g.lineStyle(3, C.frameLt, 1); - g.strokeRoundedRect(BX - FRAME + 5, BY - FRAME + 5, BOARD + FRAME * 2 - 10, BOARD + FRAME * 2 - 10, 9); - g.lineStyle(1, C.frameLn, 0.6); - g.strokeRect(BX - 2, BY - 2, BOARD + 4, BOARD + 4); + drawThreats() { + const g = this.threatG; + g.clear(); + if (!this.settings.threats || this.phase !== 'human') return; + for (const sq of L.threatened(this.gs.board, this.humanColor, this.rules)) { + const p = squareXY(L.RC[sq], this.flipped); + g.lineStyle(4, 0xff5040, 0.85).strokeCircle(p.x, p.y, 46); + g.lineStyle(1.5, 0xffffff, 0.5).strokeCircle(p.x, p.y, 50); + } + } - // Squares - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - const dark = (r + c) % 2 === 1; - g.fillStyle(dark ? C.dark : C.light, 1); - g.fillRect(BX + c * SQ, BY + r * SQ, SQ, SQ); + // ── turns ─────────────────────────────────────────────────────────────────── + nextTurn() { + if (this.ended) return; + this.clearSelection(); + if (this.gs.phase === 'game_over') { this.endGame(); return; } + this.turnStart = Date.now(); + if (this.gs.turn === this.humanColor) this.humanTurn(); + else this.aiTurn(); + } + + canMoveNow() { return this.phase === 'human' && !this.busy && !this.modal && this.gs?.phase === 'playing'; } + + humanTurn() { + this.phase = 'human'; + this.busy = false; + this.turnAnalysis = null; + const moves = L.legalMoves(this.gs); + const forced = moves[0]?.caps.length && this.rules.forced; + let tip = 'Click or drag a checker, then a marked square.'; + if (forced) tip = moves.some((m) => m.caps.length > 1) ? 'A jump is on — and it keeps going. Click the landing square, or each hop.' : 'A jump is on, and jumps are forced.'; + const left = L.quietLeft(this.gs); + if (left <= 10 && left < this.saidQuiet) { this.saidQuiet = left; this.hud.gusSays(gusLine('quiet', { n: left })); } + if (L.repCount(this.gs) === 2) this.hud.gusSays(gusLine('repetition')); + this.setStatus('Your move', tip + (left <= 10 ? `\nDraw in ${left} move${left === 1 ? '' : 's'} without a jump or a man move.` : '')); + this.refreshHud(); + this.drawTrail(); + this.drawThreats(); + this.pulseMovable(); + this.drawCursor(); + // Gus looks the position over while you think (for the coach's warnings) + if (this.settings.coach && !this.rules.giveaway && moves.length > 1) { + this.time.delayedCall(60, () => { + if (this.phase !== 'human' || this.ended) return; + this.turnAnalysis = analyze(this.gs, { depth: 7, ms: 260, exact: true }); + }); + } + } + + pulseMovable() { + for (const g of this.glows) g.destroy(); + this.glows = []; + if (!this.settings.hints || this.phase !== 'human') return; + const moves = L.legalMoves(this.gs); + const froms = [...new Set(moves.map((m) => m.from))]; + const capture = moves[0]?.caps.length > 0 && this.rules.forced; + froms.forEach((sq, i) => { + const p = squareXY(L.RC[sq], this.flipped); + const g = this.add.image(p.x, p.y, 'ck-glow').setDepth(D.glow).setScale(0.95).setAlpha(0); + if (capture) g.setTint(0xff8050); + this.tweens.add({ targets: g, alpha: { from: 0, to: capture ? 0.9 : 0.65 }, duration: 420, yoyo: true, delay: i * 30, repeat: capture ? 1 : 0, onComplete: () => g.destroy() }); + this.glows.push(g); + }); + } + + // ── input ─────────────────────────────────────────────────────────────────── + setCursor(c) { const cv = this.game?.canvas; if (cv && cv.style.cursor !== c) cv.style.cursor = c; } + + sqUnder(x, y) { + const rc = cellAt(x, y, this.flipped); + if (!rc) return -1; + return L.sqAt(rc[0], rc[1]); + } + + movesFrom(sq) { return L.legalMoves(this.gs).filter((m) => m.from === sq); } + + onPointerDown(p) { + if (!this.canMoveNow()) return; + const sq = this.sqUnder(p.x, p.y); + this.clickSquare(sq, p); + } + + clickSquare(sq, p = null) { + if (sq < 0) { if (!this.sel?.prefix || this.sel.prefix.length <= 1) this.clearSelection(); return; } + if (this.sel && this.targetsOf().has(sq)) { this.chooseTarget(sq); return; } + const piece = this.gs.board[sq]; + if (piece && L.colorOf(piece) === this.humanColor) { + const moves = this.movesFrom(sq); + if (!moves.length) { + deny(this); + const it = this.pieces.get(sq); + if (it) this.tweens.add({ targets: it.body, x: it.x + 6, duration: 50, yoyo: true, repeat: 2 }); + const all = L.legalMoves(this.gs); + if (all[0]?.caps.length && this.rules.forced) this.hud.gusSays(gusLine('forced')); + return; + } + if (this.sel?.sq === sq && this.sel.prefix.length === 1) { if (!p) this.clearSelection(); else this.beginDrag(sq, p); return; } + this.select(sq, moves); + if (p) this.beginDrag(sq, p); + return; + } + if (!this.sel || this.sel.prefix.length <= 1) this.clearSelection(); + } + + beginDrag(sq, p) { this.drag = { sq, x0: p.x, y0: p.y, moved: false }; } + + onPointerMove(p) { + if (this.drag && this.sel) { + if (!this.drag.moved && Math.hypot(p.x - this.drag.x0, p.y - this.drag.y0) > 10) this.drag.moved = true; + if (this.drag.moved) { + const it = this.sel.it; + this.pieces.place(it, p.x, p.y + 14, 14); } } - - // Coordinate labels (a–h bottom, 8–1 left) - for (let c = 0; c < SIZE; c++) { - this.add.text(BX + c * SQ + SQ / 2, BY + BOARD + 16, String.fromCharCode(97 + c), { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.board); - } - for (let r = 0; r < SIZE; r++) { - this.add.text(BX - 16, BY + r * SQ + SQ / 2, String(SIZE - r), { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.board); + if (this.sel && this.canMoveNow()) { + const sq = this.sqUnder(p.x, p.y); + const t = this.targetsOf(); + this.previewRoute(t.has(sq) ? sq : -1); + this.setCursor(t.has(sq) || (sq >= 0 && this.movesFrom(sq).length) ? 'pointer' : 'default'); + } else if (this.canMoveNow()) { + const sq = this.sqUnder(p.x, p.y); + this.setCursor(sq >= 0 && this.movesFrom(sq).length ? 'pointer' : 'default'); } } - buildUI() { - const cx = BX + BOARD / 2; - - this.turnText = this.add.text(cx, BY + BOARD + 52, '', { - fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(DEPTH.ui); - - new Button(this, BX + BOARD + FRAME + 90, BY + 60, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 150, height: 46, fontSize: 20, - }).setDepth(DEPTH.ui); - - new Button(this, BX + BOARD + FRAME + 90, BY + 124, 'New', () => this.initGame(), { - variant: 'ghost', width: 150, height: 46, fontSize: 20, - }).setDepth(DEPTH.ui); + onPointerUp(p) { + const d = this.drag; + this.drag = null; + if (!d || !d.moved || !this.sel) return; + const sq = this.sqUnder(p.x, p.y); + if (this.targetsOf().has(sq)) { this.chooseTarget(sq, { dragged: true }); return; } + // snap back + const it = this.sel.it; + const at = this.pieces.home(this.sel.prefix[this.sel.prefix.length - 1]); + this.pieces.place(it, at.x, at.y, 8); } - buildPlayerCards() { - const opp = this.opponents[0]; - const r = 78; - const depth = DEPTH.ui; - const avatarX = BX / 2; - - const oppAY = BY + r + 20; - this.add.circle(avatarX, oppAY, r + 5, C.frame).setDepth(depth); - this.opponentPortrait = createOpponentPortrait(this, opp, avatarX, oppAY, r, depth + 1); - this.add.text(avatarX, oppAY + r + 14, opp?.name ?? 'CPU', { - fontFamily: '"Julius Sans One"', fontSize: '18px', - color: COLORS.textHex, wordWrap: { width: 230 }, align: 'center', - }).setOrigin(0.5, 0).setDepth(depth + 2); - this.oppTrayY = oppAY + r + 64; - - const plrAY = BY + BOARD - r - 20; - this.add.circle(avatarX, plrAY, r + 5, COLORS.accent, 0.5).setDepth(depth); - createPlayerPortrait(this, avatarX, plrAY, r, depth + 1, 'CheckersGame'); - this.add.text(avatarX, plrAY - r - 14, auth.user?.username ?? 'You', { - fontFamily: '"Julius Sans One"', fontSize: '18px', - color: COLORS.textHex, wordWrap: { width: 230 }, align: 'center', - }).setOrigin(0.5, 1).setDepth(depth + 2); - this.plrTrayY = plrAY - r - 56; - - this.trayObjs = []; + select(sq, moves) { + this.clearSelection(); + const it = this.pieces.get(sq); + this.sel = { sq, it, moves, prefix: [sq] }; + pickSnd(this); + this.pieces.liftTo(it, 8); + this.drawMarkers(); } - playOpponentEmotion(emotion) { this.opponentPortrait?.playEmotion(emotion); } - - // ── Game flow ───────────────────────────────────────────────────────────── - - initGame() { - this.clearOverlays(); - this.clearPieces(); - this.animating = false; - this.selected = null; - this.gs = createInitialState(); - this.renderAll(); - this.showTurnBanner('Your Turn'); - } - - renderAll() { - this.clearPieces(); - this.renderPieces(); - this.renderTrays(); - this.clearOverlays(); - this.updateTurnText(); - if (this.gs.phase === 'playing' && this.gs.turn === 'white' - && !this.animating && !this.gs.mustContinueFrom) { - this.showMovableHints(); - } - } - - updateTurnText() { - if (!this.turnText) return; - if (this.gs.phase === 'game_over') { this.turnText.setText(''); return; } - this.turnText.setText(this.gs.turn === 'white' ? 'Your move' : 'Opponent thinking…'); - } - - // ── Pieces ────────────────────────────────────────────────────────────────── - - sqToWorld(r, c) { - return { x: BX + c * SQ + SQ / 2, y: BY + r * SQ + SQ / 2 }; - } - - clearPieces() { - for (const o of this.pieceObjs) o.container.destroy(); - this.pieceObjs = []; - } - - renderPieces() { - for (let r = 0; r < SIZE; r++) { - for (let c = 0; c < SIZE; c++) { - const p = this.gs.board[r][c]; - if (!p) continue; - const { x, y } = this.sqToWorld(r, c); - const cont = this.makeDisc(p.color, p.king, x, y); - cont.setDepth(DEPTH.piece); - cont.setInteractive({ - useHandCursor: true, - hitArea: new Phaser.Geom.Circle(0, 0, CR), - hitAreaCallback: Phaser.Geom.Circle.Contains, - }); - cont.on('pointerdown', () => this.onPieceClick(r, c)); - this.pieceObjs.push({ r, c, container: cont }); + clearSelection() { + if (this.sel) { + const { it, prefix } = this.sel; + // undo any partial hops + if (prefix.length > 1 && it) { + const home = this.pieces.home(prefix[0]); + this.pieces.place(it, home.x, home.y, 0); + for (const m of this.sel.moves) for (const c of m.caps) this.pieces.mark(c, false); + } else if (it?.body?.active) { + const home = this.pieces.home(this.sel.sq); + this.pieces.place(it, home.x, home.y, 0); } } + this.sel = null; + this.drag = null; + this.markG?.clear(); + for (const m of this.markers) m.destroy(); + this.markers = []; + this.clearPreview(); + this.clearHint(); } - makeDisc(color, king, x, y) { - const g = this.add.graphics(); - const ring = color === 'white' ? C.wRing : C.bRing; - const fill = color === 'white' ? C.wFill : C.bFill; - const edge = color === 'white' ? C.wEdge : C.bEdge; - // Shadow - g.fillStyle(0x000000, 0.28); - g.fillCircle(3, 5, CR); - // Outer ring + edge ridge - g.fillStyle(edge, 1); - g.fillCircle(0, 0, CR); - g.fillStyle(ring, 1); - g.fillCircle(0, 0, CR - 3); - // Inner face - g.fillStyle(fill, 1); - g.fillCircle(0, 0, CR - 8); - // Concentric ridge groove - g.lineStyle(2, edge, 0.5); - g.strokeCircle(0, 0, CR - 13); - // Top-left sheen - g.lineStyle(3, color === 'white' ? 0xffffff : 0x7a7690, 0.5); - g.beginPath(); - g.arc(0, 0, CR - 11, Phaser.Math.DegToRad(200), Phaser.Math.DegToRad(320)); - g.strokePath(); + // Moves still consistent with the hops chosen so far. + candidates() { + const { moves, prefix } = this.sel; + return moves.filter((m) => prefix.every((s, i) => m.path[i] === s)); + } - const items = [g]; - if (king) { - const ringG = this.add.graphics(); - ringG.lineStyle(3, C.kingGold, 0.95); - ringG.strokeCircle(0, 0, CR - 4); - const crown = this.add.graphics(); - this.drawCrown(crown, C.kingGold); - items.push(ringG, crown); + targetsOf() { + if (!this.sel) return new Set(); + const k = this.sel.prefix.length; + const out = new Set(); + for (const m of this.candidates()) { + out.add(m.to); + if (m.path.length > k) out.add(m.path[k]); } - return this.add.container(x, y, items); + out.delete(this.sel.prefix[k - 1]); + return out; } - drawCrown(g, color) { - const w = CR * 1.15, h = CR * 0.78; - const peakY = -h * 0.5, valleyY = -h * 0.02, baseY = h * 0.5; - const pts = [ - { x: -w / 2, y: baseY }, { x: -w / 2, y: peakY }, - { x: -w / 4, y: valleyY }, { x: 0, y: peakY }, - { x: w / 4, y: valleyY }, { x: w / 2, y: peakY }, - { x: w / 2, y: baseY }, - ]; - g.fillStyle(color, 1); - g.fillPoints(pts, true); - g.lineStyle(1.5, 0x8a6a12, 0.8); - g.strokePoints(pts, true); - } - - // ── Interaction ─────────────────────────────────────────────────────────── - - onPieceClick(r, c) { - if (this.animating || this.gs.phase !== 'playing' || this.gs.turn !== 'white') return; - const piece = this.gs.board[r][c]; - if (!piece || piece.color !== 'white') return; - if (this.gs.mustContinueFrom) { - const [mr, mc] = this.gs.mustContinueFrom; - if (mr !== r || mc !== c) return; + drawMarkers() { + this.markG.clear(); + for (const m of this.markers) m.destroy(); + this.markers = []; + if (!this.sel) return; + const k = this.sel.prefix.length; + const cands = this.candidates(); + const finals = new Map(), hops = new Set(); + for (const m of cands) { + finals.set(m.to, (finals.get(m.to) ?? 0) + 1); + if (m.path.length > k + 1) hops.add(m.path[k]); } - const moves = getValidMoves(this.gs).filter((m) => m.from[0] === r && m.from[1] === c); - if (moves.length === 0) { this.flashNoMove(r, c); return; } - this.selectPiece(r, c, moves); - } - - selectPiece(r, c, moves) { - this.clearOverlays(); - this.selected = [r, c]; - const { x, y } = this.sqToWorld(r, c); - const ring = this.add.graphics().setDepth(DEPTH.overlay); - ring.lineStyle(4, C.selGold, 1); - ring.strokeCircle(x, y, CR + 5); - this.tweens.add({ targets: ring, alpha: { from: 1, to: 0.35 }, duration: 520, yoyo: true, repeat: -1 }); - this.overlayObjs.push(ring); - this.showDestinations(moves); - } - - showDestinations(moves) { - const seen = new Set(); - for (const m of moves) { - const key = `${m.to[0]},${m.to[1]}`; - if (seen.has(key)) continue; - seen.add(key); - const { x, y } = this.sqToWorld(m.to[0], m.to[1]); - const dot = this.add.graphics().setDepth(DEPTH.overlay); - const cap = m.isJump; - dot.fillStyle(cap ? C.selGold : COLORS.accent, cap ? 0.9 : 0.8); - dot.fillCircle(x, y, cap ? 24 : 18); - dot.lineStyle(3, 0xffffff, 0.4); - dot.strokeCircle(x, y, cap ? 24 : 18); - this.tweens.add({ targets: dot, alpha: { from: 0.9, to: 0.25 }, duration: 600, yoyo: true, repeat: -1 }); - const zone = this.add.zone(x, y, SQ, SQ) - .setInteractive({ useHandCursor: true }).setDepth(DEPTH.overlay); - zone.on('pointerdown', () => this.onDestinationClick(m.to[0], m.to[1])); - this.overlayObjs.push(dot, zone); + const g = this.markG; + // dim the jumped-so-far checkers + const here = this.sel.prefix; + if (here.length > 1) { + const m0 = cands[0]; + for (let i = 0; i < here.length - 1; i++) this.pieces.mark(m0.caps[i], true); } - } - - showMovableHints() { - const froms = new Set(getValidMoves(this.gs).map((m) => `${m.from[0]},${m.from[1]}`)); - for (const key of froms) { - const [r, c] = key.split(',').map(Number); - const { x, y } = this.sqToWorld(r, c); - const ring = this.add.graphics().setDepth(DEPTH.overlay - 1); - ring.lineStyle(3, C.selGold, 0.5); - ring.strokeCircle(x, y, CR + 3); - this.tweens.add({ targets: ring, alpha: { from: 0.5, to: 0.12 }, duration: 900, yoyo: true, repeat: -1 }); - this.overlayObjs.push(ring); - } - } - - onDestinationClick(r, c) { - if (this.animating || !this.selected) return; - const [sr, sc] = this.selected; - const move = getValidMoves(this.gs).find( - (m) => m.from[0] === sr && m.from[1] === sc && m.to[0] === r && m.to[1] === c - ); - if (!move) return; - this.clearOverlays(); - this.executeMove(move, 'white'); - } - - flashNoMove(r, c) { - const obj = this.pieceObjs.find((o) => o.r === r && o.c === c); - if (!obj) return; - this.tweens.add({ targets: obj.container, alpha: { from: 1, to: 0.3 }, duration: 110, yoyo: true, repeat: 2 }); - } - - clearOverlays() { - for (const o of this.overlayObjs) o.destroy(); - this.overlayObjs = []; - this.selected = null; - } - - // ── Move execution + animation ────────────────────────────────────────────── - - executeMove(move, mover) { - this.animating = true; - this.updateTurnText(); - const obj = this.pieceObjs.find((o) => o.r === move.from[0] && o.c === move.from[1]); - const fromPos = this.sqToWorld(move.from[0], move.from[1]); - const toPos = this.sqToWorld(move.to[0], move.to[1]); - const container = obj ? obj.container : this.makeDisc( - mover, this.gs.board[move.from[0]][move.from[1]].king, fromPos.x, fromPos.y); - container.setDepth(DEPTH.moving); - - // Fade out captured discs alongside the hop. - for (const [cr, cc] of move.captures) this.animateCapture(cr, cc); - - this.animateArc(container, fromPos, toPos, () => { - this.gs = applyMove(this.gs, move); - this.renderAll(); - this.animating = false; - - if (move.captures.length > 0) { - this.playOpponentEmotion(mover === 'white' ? 'upset' : 'happy'); - } - - if (this.gs.phase === 'game_over') { this.onGameOver(); return; } - - if (this.gs.turn === 'white') { - if (this.gs.mustContinueFrom) { - // Human must keep jumping with the same piece. - const [cr, cc] = this.gs.mustContinueFrom; - this.selectPiece(cr, cc, getValidMoves(this.gs)); + for (const [sq] of finals) { + const p = squareXY(L.RC[sq], this.flipped); + const cap = cands.some((m) => m.to === sq && m.caps.length); + g.fillStyle(cap ? 0xffc040 : 0xfff4d8, cap ? 0.28 : 0.18).fillRect(p.x - SQ / 2 + 4, p.y - SQ / 2 + 4, SQ - 8, SQ - 8); + const dot = this.add.image(p.x, p.y, 'ck-dot').setDepth(D.mark + 1).setScale(cap ? 0.9 : 0.7).setTint(cap ? 0xffc040 : 0xfff4d8).setAlpha(0.9); + this.tweens.add({ targets: dot, alpha: { from: 0.95, to: 0.45 }, duration: 640, yoyo: true, repeat: -1 }); + this.markers.push(dot); + if (cap) { + const n = Math.max(...cands.filter((m) => m.to === sq).map((m) => m.caps.length)); + if (n > 1) { + const t = this.add.text(p.x + 26, p.y - 28, `×${n}`, { fontFamily: BOLD_FONT, fontSize: '20px', color: '#ffe8a8', stroke: '#1a0c08', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.mark + 2); + this.markers.push(t); } - } else if (this.gs.mustContinueFrom) { - // AI mid multi-jump — continue the chain quickly. - this.time.delayedCall(360, () => this.aiStep()); - } else { - // Fresh AI turn. - this.startAITurn(); } - }); + } + for (const sq of hops) { + if (finals.has(sq)) continue; + const p = squareXY(L.RC[sq], this.flipped); + const dot = this.add.image(p.x, p.y, 'ck-dot').setDepth(D.mark + 1).setScale(0.45).setTint(0xffc040).setAlpha(0.75); + this.markers.push(dot); + } } - startAITurn() { - const name = this.opponents[0]?.name ?? 'Opponent'; - this.showTurnBanner(`${name}'s Turn`); - this.time.delayedCall(nextThinkDelay(this.opponents[0]?.skill ?? 3), () => this.aiStep(false)); + previewRoute(sq) { + this.clearPreview(); + if (sq < 0 || !this.sel) return; + const k = this.sel.prefix.length; + const routes = this.candidates().filter((m) => m.to === sq || m.path[k] === sq); + const g = this.pathG; + for (const m of routes) { + if (!m.caps.length && m.path.length === 2) continue; + const pts = m.path.slice(k - 1).map((s) => squareXY(L.RC[s], this.flipped)); + g.lineStyle(5, 0xffc040, 0.75); + for (let i = 1; i < pts.length; i++) g.lineBetween(pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y); + pts.slice(1).forEach((p, i) => { + const t = this.add.text(p.x, p.y - 30, String(k + i), { fontFamily: BOLD_FONT, fontSize: '18px', color: '#ffe8a8', stroke: '#1a0c08', strokeThickness: 4 }).setOrigin(0.5).setDepth(D.path + 1); + this.pathTexts.push(t); + }); + for (const c of m.caps.slice(k - 1)) { + const p = squareXY(L.RC[c], this.flipped); + g.lineStyle(4, 0xff5040, 0.8).strokeCircle(p.x, p.y, 34); + } + } } - aiStep() { - if (this.gs.phase !== 'playing' || this.gs.turn !== 'black') return; - const skill = this.opponents[0]?.skill ?? 3; - const move = chooseMove(this.gs, 'black', skill); - if (!move) return; - this.executeMove(move, 'black'); + clearPreview() { + this.pathG?.clear(); + for (const t of this.pathTexts) t.destroy(); + this.pathTexts = []; } - animateCapture(r, c) { - const obj = this.pieceObjs.find((o) => o.r === r && o.c === c); - if (!obj) return; - obj.container.setDepth(DEPTH.moving - 1); - this.tweens.add({ - targets: obj.container, - scaleX: 0, scaleY: 0, alpha: 0, - angle: 90, - duration: 240, ease: 'Back.easeIn', - }); + async chooseTarget(sq, { dragged = false } = {}) { + const k = this.sel.prefix.length; + const cands = this.candidates(); + const ending = cands.filter((m) => m.to === sq); + const distinct = new Map(ending.map((m) => [L.moveKey(m), m])); + if (distinct.size === 1) { await this.commit([...distinct.values()][0], { dragged }); return; } + const via = cands.filter((m) => m.path[k] === sq); + if (via.length) { + // play one hop now; the rest of the route stays open + this.busy = true; + const it = this.sel.it; + this.clearPreview(); + if (dragged) this.pieces.place(it, this.pieces.home(sq).x, this.pieces.home(sq).y, 8); + else await this.pieces.moveTo(it, sq, { dur: 220 * this.k, arc: 40 }); + clack(this, { k: k - 1 }); + this.sel.prefix.push(sq); + this.busy = false; + const left = this.candidates(); + const done = new Map(left.filter((m) => m.path.length === this.sel.prefix.length).map((m) => [L.moveKey(m), m])); + if (done.size === 1 && left.every((m) => m.path.length === this.sel.prefix.length)) { await this.commit([...done.values()][0], { partial: true }); return; } + this.drawMarkers(); + return; + } + if (distinct.size > 1) toast(this, 'More than one route lands there — click the hops one at a time.', { depth: D.modal }); } - animateArc(container, from, to, onComplete) { - if (!container) { onComplete(); return; } - const midX = (from.x + to.x) / 2; - const midY = Math.min(from.y, to.y) - 80; - const prog = { t: 0 }; - this.tweens.add({ - targets: prog, t: 1, duration: 330, ease: 'Cubic.easeInOut', - onUpdate: () => { - const t = prog.t, inv = 1 - t; - container.x = inv * inv * from.x + 2 * inv * t * midX + t * t * to.x; - container.y = inv * inv * from.y + 2 * inv * t * midY + t * t * to.y; - }, - onComplete: () => { - container.x = to.x; container.y = to.y; - this.tweens.add({ - targets: container, scaleX: 1.25, scaleY: 0.78, duration: 60, yoyo: true, ease: 'Quad.easeOut', - onComplete: () => { playSound(this, SFX.PIECE_CLICK); onComplete(); }, + async commit(move, { dragged = false, partial = false } = {}) { + // the coach's look before you leap + if (this.settings.coach && this.turnAnalysis && !partial && !this.sel?.warned) { + const ranked = this.turnAnalysis; + const mine = ranked.find((r) => L.moveKey(r.move) === L.moveKey(move)); + const best = ranked[0]; + if (mine && best && best.score - mine.score >= 90 && mine.score < 600) { + this.busy = true; + const bestN = L.notate(best.move); + this.hud.hidePortraits(); + this.sel.warned = true; + const sel = this.sel; + this.modal = confirmBox(this, { + heading: 'Gus leans over…', text: `${gusLine('warn')}\n\nI'd look at ${bestN} — it ${describeIdea(this.gs, best.move, best.score)}.`, + yes: 'Play it anyway', no: 'Let me look again', depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); this.busy = false; if (this.sel === sel) this.commit(move, { dragged }); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); this.busy = false; this.clearSelection(); this.pulseMovable(); }, }); - }, + return; + } + } + const done = this.sel ? this.sel.prefix.length - 1 : 0; + this.undoStack.push({ gs: this.gs, clocks: { ...this.clocks }, captured: { top: this.captured.top.slice(), bottom: this.captured.bottom.slice() } }); + if (this.undoStack.length > 40) this.undoStack.shift(); + this.clocks.human += Date.now() - this.turnStart; + const it = this.sel?.it; + this.markG.clear(); + for (const m of this.markers) m.destroy(); + this.markers = []; + this.clearPreview(); + this.clearHint(); + this.threatG.clear(); + this.sel = null; + this.busy = true; + this.phase = 'animating'; + this.setCursor('default'); + await this.playMove(move, { it, done, dragged }); + if (this.ended) return; + this.nextTurn(); + } + + // ── move animation & bookkeeping ──────────────────────────────────────────── + async playMove(m, { it = null, done = 0, dragged = false, fast = false } = {}) { + const mover = this.gs.turn; + const human = mover === this.humanColor; + const side = human ? 'bottom' : 'top'; + it = it ?? this.pieces.get(m.from); + const k = this.k * (fast ? 0.35 : 1); + if (dragged) { + // a dragged checker lands straight on its square; jumped ones fly off together + this.pieces.place(it, this.pieces.home(m.to).x, this.pieces.home(m.to).y, 0); + clack(this, { k: m.caps.length }); + m.caps.forEach((c, i) => this.flickCaptured(c, side, i * 70 * k)); + await this.pieces.squash(it, 0.12, 120); + } else { + for (let i = done + 1; i < m.path.length; i++) { + const jump = m.caps.length > 0; + await this.pieces.moveTo(it, m.path[i], { dur: (jump ? 260 : 300) * k, arc: jump ? 46 : 10 }); + clack(this, { k: i - 1 }); + if (jump && !fast && m.caps.length >= 2) this.hopNumber(m.path[i], i); + await this.pieces.squash(it, 0.1, 90 * k); + } + m.caps.forEach((c, i) => this.flickCaptured(c, side, i * 90 * k)); + if (m.caps.length) await this.wait(Math.min(400, 160 + m.caps.length * 70) * k); + } + this.pieces.rekey(it, m.to); + if (m.crown) { + crownSnd(this); + await this.pieces.crown(it, this.gs.board[m.from] * 2); + this.sparks(it.x, it.y, 10); + } + const before = this.gs; + this.gs = L.applyMove(before, m); + // talk + const n = m.caps.length; + if (human) { + if (n >= 2) { this.callout(`${n} in one!`, it.x, it.y - 60, 0xffe8a8); this.hud.gusSays(gusLine('humanMulti', { n })); this.hud.say(opponentLine('lostMulti', this.tier)); this.hud.emotion('upset'); } + else if (n === 1) { const l = gusLine('humanCapture'); if (l) this.hud.gusSays(l); if (Math.random() < 0.35) this.hud.say(opponentLine('lostPiece', this.tier)); this.hud.emotion('upset'); } + if (m.crown) this.hud.gusSays(gusLine('humanCrown')); + } else { + if (n >= 2) { this.callout(`${n} in one!`, it.x, it.y - 60, 0xff9a84); this.hud.say(opponentLine('multi', this.tier)); this.hud.emotion('happy'); } + else if (n === 1) { if (Math.random() < 0.4) this.hud.say(opponentLine('capture', this.tier)); const l = gusLine('humanLostPiece'); if (l) this.hud.gusSays(l); this.hud.emotion('happy'); } + if (m.crown) { if (Math.random() < 0.6) this.hud.say(opponentLine('crown', this.tier)); else { const l = gusLine('aiCrown'); if (l) this.hud.gusSays(l); } } + } + this.drawTrail(); + this.refreshHud(); + if (this.gs.phase === 'playing') this.save(); + } + + // Captured checkers in each tray, less the ones still in the air. + shownCaptured() { + const pend = this.pendingFlicks ?? { top: 0, bottom: 0 }; + return { top: this.captured.top.slice(0, this.captured.top.length - pend.top), bottom: this.captured.bottom.slice(0, this.captured.bottom.length - pend.bottom) }; + } + + flickCaptured(sq, side, delay) { + const p = this.gs.board[sq]; + const n = this.captured[side].length; + this.captured[side].push(p); + this.pendingFlicks = this.pendingFlicks ?? { top: 0, bottom: 0 }; + this.pendingFlicks[side]++; + const t = this.hud.trayTarget(side, n); + this.time.delayedCall(delay, () => flick(this)); + this.pieces.flick(sq, t.x, t.y, { dur: 420 * this.k, delay }).then(() => { + this.pendingFlicks[side] = Math.max(0, this.pendingFlicks[side] - 1); + if (!this.ended) this.hud.setTrays(this.shownCaptured()); }); } - // ── Captured trays ────────────────────────────────────────────────────────── - - renderTrays() { - for (const o of this.trayObjs) o.destroy(); - this.trayObjs = []; - const counts = pieceCounts(this.gs); - const avatarX = BX / 2; - // Opponent (black) captured white discs. - this.drawTray(avatarX, this.oppTrayY, 12 - counts.white, 'white'); - // Player (white) captured black discs. - this.drawTray(avatarX, this.plrTrayY, 12 - counts.black, 'black'); + hopNumber(sq, k) { + const p = squareXY(L.RC[sq], this.flipped); + const t = this.add.text(p.x, p.y - 34, String(k), { fontFamily: BOLD_FONT, fontSize: `${18 + k * 3}px`, color: '#ffe8a8', stroke: '#1a0c08', strokeThickness: 4 }) + .setOrigin(0.5).setDepth(D.fx); + this.tweens.add({ targets: t, y: p.y - 70, alpha: 0, duration: 700, ease: 'Quad.Out', onComplete: () => t.destroy() }); } - drawTray(cx, cy, n, color) { - const ring = color === 'white' ? C.wRing : C.bRing; - const fill = color === 'white' ? C.wFill : C.bFill; - const per = 6, mr = 13, gap = 5; + // ── undo / hint ───────────────────────────────────────────────────────────── + undo() { + if (!this.canMoveNow() || !this.undoStack.length) return; + const snap = this.undoStack.pop(); + this.clearSelection(); + this.gs = snap.gs; + this.clocks = snap.clocks; + this.captured = snap.captured; + this.pieces.build(this.gs.board, this.flipped); + pickSnd(this); + const l = gusLine('undo'); + if (l) this.hud.gusSays(l); + this.save(); + this.nextTurn(); + } + + showHint() { + if (!this.canMoveNow()) return; + this.clearSelection(); + const h = hint(this.gs, { ms: 650 }); + if (!h) return; + this.hintObjs = []; + const from = squareXY(L.RC[h.move.from], this.flipped); + const ring = this.add.image(from.x, from.y, 'ck-ring').setDepth(D.path + 1).setScale(1.05); + this.tweens.add({ targets: ring, scale: { from: 1.2, to: 0.95 }, alpha: { from: 1, to: 0.5 }, duration: 620, yoyo: true, repeat: -1 }); + this.hintObjs.push(ring); + const g = this.add.graphics().setDepth(D.path); + const pts = h.move.path.map((s) => squareXY(L.RC[s], this.flipped)); + g.lineStyle(5, 0xffc040, 0.8); + for (let i = 1; i < pts.length; i++) g.lineBetween(pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y); + const end = pts[pts.length - 1]; + g.fillStyle(0xffc040, 0.3).fillRect(end.x - SQ / 2 + 4, end.y - SQ / 2 + 4, SQ - 8, SQ - 8); + this.hintObjs.push(g); + this.hud.gusSays(gusLine('hint', { move: L.notate(h.move), reason: h.reason }), { hold: 10000 }); + this.setStatus('Gus\'s hint', `${L.notate(h.move)} — it ${h.reason}. Play it or anything else.`); + } + + clearHint() { + for (const o of this.hintObjs ?? []) o.destroy(); + this.hintObjs = []; + } + + // ── AI ────────────────────────────────────────────────────────────────────── + async aiTurn() { + if (this.ended) return; + this.phase = 'ai'; + this.busy = true; + const fast = this.settings.skipAI; + const t = aiTiming(this.skill, fast ? 0.25 : this.k); + this.setStatus(`${this.oppName} is thinking…`, this.gs.ballot && this.gs.ply === 3 ? `The ballot: ${this.gs.ballot.name}.` : ''); + this.refreshHud(true); + await this.wait(fast ? 60 : t.think * 0.5); + if (this.ended || this.gs.phase !== 'playing') return; + // a draw offer from across the barrel? + if (this.gs.ply - this.aiOfferPly >= 24 && !this.rules.giveaway && wantsDraw(this.gs, this.aiColor, this.skill)) { + this.aiOfferPly = this.gs.ply; + const accepted = await this.askDraw(); + if (this.ended) return; + if (accepted) { this.gs = L.agreeDraw(this.gs); this.hud.gusSays(gusLine('drawYouAccepted')); this.endGame(); return; } + this.phase = 'ai'; + this.busy = true; + } + const m = chooseMove(this.gs, this.skill); + if (!m || this.ended) return; + const it = this.pieces.get(m.from); + if (!fast) { + await this.pieces.liftTo(it, 10, 140); + await this.wait(t.hesitate * 0.4); + } + this.clocks.ai += Date.now() - this.turnStart; + this.phase = 'animating'; + await this.playMove(m, { it, fast }); + if (this.ended) return; + await this.wait(fast ? 40 : Math.min(200, t.between * 0.5)); + this.nextTurn(); + } + + askDraw() { + return new Promise((res) => { + this.hud.say(opponentLine('offerDraw', this.tier), 4000); + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading: `${this.oppName} offers a draw`, text: `${gusLine('drawOfferAI')}\nAccepting ends this game as a draw (half a point each).`, + yes: 'Accept the draw', no: 'Play on', depth: D.modal, + onYes: () => { this.modal = null; this.hud.showPortraits(); res(true); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); res(false); }, + }); + }); + } + + async offerDraw() { + if (!this.canMoveNow()) return; + this.lastOfferPly = this.gs.ply; + this.busy = true; + this.clearSelection(); + this.setStatus('You offer a draw…', `${this.oppName} considers it.`); + this.refreshHud(); + await this.wait(900 * this.k); + if (this.ended) return; + const d = drawDecision(this.gs, this.aiColor, this.skill); + if (d.accept) { + this.hud.say(opponentLine('acceptDraw', this.tier)); + this.hud.gusSays(gusLine('drawYouAccepted')); + this.gs = L.agreeDraw(this.gs); + this.endGame(); + return; + } + this.hud.say(d.why === 'early' ? 'We\'ve barely started!' : opponentLine('declineDraw', this.tier)); + this.hud.gusSays(gusLine('drawDeclined')); + this.busy = false; + this.humanTurn(); + } + + resign() { + if (!this.canMoveNow()) return; + this.confirmThen('Resign this game?', `${this.oppName} gets the point.`, () => { + this.hud.gusSays(gusLine('resign')); + this.gs = L.resign(this.gs, this.humanColor); + this.endGame(); + }); + } + + // ── end of a game / match ─────────────────────────────────────────────────── + async endGame() { + if (this.phase === 'over') return; + this.phase = 'over'; + this.busy = true; + this.clearSelection(); + for (const g of this.glows) g.destroy(); + this.threatG.clear(); + this.cursorG.clear(); + const gs = this.gs; + const m = this.match; + const result = gs.winner === 'draw' ? 'draw' : gs.winner === this.humanColor ? 'human' : 'ai'; + if (result === 'human') m.human += 1; else if (result === 'ai') m.ai += 1; else { m.human += 0.5; m.ai += 0.5; } + m.results.push({ + result, humanColor: this.humanColor, moves: Math.ceil(gs.history.filter((h) => !h.ballot).length / 2), + reason: gs.endReason, ballot: gs.ballot?.name ?? null, + }); + this.recordLifetime(result); + const r = resultLine(gs, this.humanColor, this.oppName); + this.refreshHud(); + this.setStatus(r.title, r.why); + if (result === 'human') { + sting(this, 'win'); playSound(this, SFX.CASINO_WIN); + this.banner('YOU WIN', 0xf0d890, 0.8); + this.confetti(); + this.hud.say(opponentLine('lose', this.tier)); this.hud.emotion('upset'); + this.hud.gusSays(gusLine('win')); + } else if (result === 'ai') { + sting(this, 'lose'); + this.banner(`${this.oppName} WINS`.toUpperCase(), 0xff9a84, 0.7); + this.hud.say(opponentLine('win', this.tier)); this.hud.emotion('happy'); + if (gs.endReason !== 'resign') this.hud.gusSays(gusLine('loss')); + } else { + sting(this, 'draw'); + this.banner('DRAW', 0xe8dcc0, 0.8); + this.hud.say(opponentLine('draw', this.tier)); + if (gs.endReason !== 'agreed') this.hud.gusSays(gusLine('draw')); + } + const over = m.human > m.games / 2 || m.ai > m.games / 2 || m.results.length >= m.games; + if (over) { + this.clearSave(); + this.postHistory().catch(() => {}); + } else this.save(true); + await this.wait(2400); + if (this.ended) return; + if (over) this.matchOver(); + else this.betweenGames(); + } + + betweenGames() { + this.hud.hidePortraits(); + this.modal = openBetween(this, { + gs: this.gs, humanColor: this.humanColor, oppName: this.oppName, match: this.match, depth: D.end, + onNext: () => { this.modal = null; this.hud.showPortraits(); this.startGame(); }, + onLeave: () => this.scene.start('GameMenu'), + }); + } + + matchOver() { + const m = this.match; + if (m.games > 1) { + if (m.human > m.ai) this.hud.gusSays(gusLine('matchWin')); + else if (m.ai > m.human) this.hud.gusSays(gusLine('matchLoss')); + else this.hud.gusSays(gusLine('matchDraw')); + } + this.hud.hidePortraits(); + this.modal = openEndScreen(this, { + gs: this.gs, humanColor: this.humanColor, oppName: this.oppName, match: m, depth: D.end, + record: this.lifetime()?.vs?.[this.opp.id ?? this.oppName] ?? null, symbols: this.settings.symbols, + onPlayAgain: () => { this.modal = null; this.hud.showPortraits(); this.openSetupCard(); }, + onMenu: () => this.scene.start('GameMenu'), + }); + } + + lifetime() { + try { return JSON.parse(localStorage.getItem(RECORD_KEY) || '{}'); } catch (_) { return {}; } + } + + recordLifetime(result) { + try { + const rec = this.lifetime(); + const key = result === 'human' ? 'w' : result === 'ai' ? 'l' : 'd'; + rec.variants = rec.variants ?? {}; + rec.vs = rec.vs ?? {}; + const v = (rec.variants[this.gs.variant] = rec.variants[this.gs.variant] ?? { w: 0, d: 0, l: 0 }); + const o = (rec.vs[this.opp.id ?? this.oppName] = rec.vs[this.opp.id ?? this.oppName] ?? { w: 0, d: 0, l: 0 }); + v[key]++; o[key]++; + localStorage.setItem(RECORD_KEY, JSON.stringify(rec)); + } catch (_) { /* private mode */ } + } + + async postHistory() { + const m = this.match; + const result = m.human > m.ai ? 'win' : m.ai > m.human ? 'loss' : 'draw'; + await api.post('/history/single-player', { + slug: 'checkers', score: Math.round(m.human * 100), opponentScores: [Math.round(m.ai * 100)], result, + }); + } + + // ── buttons / keys / menu ─────────────────────────────────────────────────── + onButton(k) { + if (this.ended || this.modal) return; + if (k === 'undo') this.undo(); + else if (k === 'hint') this.showHint(); + else if (k === 'draw') this.offerDraw(); + else if (k === 'resign') this.resign(); + else if (k === 'flip') this.flip(); + else if (k === 'menu') this.openMenu(); + } + + flip() { + if (!this.gs || this.modal || ['animating', 'intro', 'setup'].includes(this.phase)) return; + this.manualFlip = !this.manualFlip; + const keepSel = this.sel && this.sel.prefix.length === 1 ? this.sel.sq : null; + this.clearSelection(); + this.pieces.setFlipped(this.flipped); + this.layoutNumbers(); + this.drawTrail(); + this.drawThreats(); + this.drawCursor(); + if (keepSel != null && this.canMoveNow()) this.select(keepSel, this.movesFrom(keepSel)); + } + + onKey(e) { + if (this.ended || e.repeat) return; + const key = e.key; + if (key === 'Escape') { + if (this.modal) { if (this.escClosable) this.closeModal(); return; } + if (this.sel) { this.clearSelection(); this.pulseMovable(); return; } + this.openMenu(); + return; + } + if (this.modal) return; + const lower = key.toLowerCase(); + if (lower === 'z') this.undo(); + else if (lower === 'h') this.showHint(); + else if (lower === 'f') this.flip(); + else if (key.startsWith('Arrow')) this.moveCursor(key); + else if ((key === 'Enter' || key === ' ') && this.cursor && this.canMoveNow()) { + const sq = L.sqAt(...this.cursorRC()); + if (sq >= 0) this.clickSquare(sq); + } + } + + // Keyboard cursor lives in view space (so arrows match the screen). + cursorRC() { + const [vr, vc] = this.cursor; + return this.flipped ? [7 - vr, 7 - vc] : [vr, vc]; + } + + moveCursor(key) { + if (!this.canMoveNow()) return; + if (!this.cursor) { + const first = L.legalMoves(this.gs)[0]; + const [r, c] = first ? L.RC[first.from] : [7, 0]; + this.cursor = this.flipped ? [7 - r, 7 - c] : [r, c]; + } else { + const d = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }[key]; + this.cursor = [Math.max(0, Math.min(7, this.cursor[0] + d[0])), Math.max(0, Math.min(7, this.cursor[1] + d[1]))]; + } + this.drawCursor(); + } + + drawCursor() { + const g = this.cursorG; + g.clear(); + if (!this.cursor || this.phase !== 'human') return; + const [vr, vc] = this.cursor; + const x = BX + vc * SQ, y = BY + vr * SQ; + g.lineStyle(4, 0xd8b060, 1).strokeRect(x + 3, y + 3, SQ - 6, SQ - 6); + g.lineStyle(1.5, 0xffffff, 0.6).strokeRect(x + 8, y + 8, SQ - 16, SQ - 16); + } + + openMenu() { + if (this.modal || this.ended || this.phase === 'over' || this.phase === 'setup') return; + this.clearSelection(); + this.hud.hidePortraits(); + this.escClosable = true; + this.modal = openPauseMenu(this, { + settings: this.settings, depth: D.modal, + onChange: (key, value) => this.changeSetting(key, value), + onRules: () => new TutorialModal(this.gameDef).open(), + onNewMatch: () => this.confirmThen('Start a new match?', 'This game will be abandoned.', () => { this.clearSave(); this.openSetupCard(); }), + onLeave: () => this.confirmThen('Leave the shop?', 'Your game is saved — you can pick it up next time.', () => this.scene.start('GameMenu')), + onClose: () => { this.modal = null; this.escClosable = false; this.hud.showPortraits(); this.refreshHud(); if (this.phase === 'human') this.pulseMovable(); }, + }); + } + + confirmThen(heading, text, onYes) { + this.hud.hidePortraits(); + this.modal = confirmBox(this, { + heading, text, depth: D.modal + 5, + onYes: () => { this.modal = null; this.hud.showPortraits(); onYes(); }, + onNo: () => { this.modal = null; this.hud.showPortraits(); this.refreshHud(); }, + }); + } + + closeModal() { this.modal?.close?.(); this.modal = null; this.escClosable = false; this.hud.showPortraits(); } + + persistSettings() { + try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings)); } catch (_) { /* private mode */ } + } + + changeSetting(key, value) { + this.settings[key] = value; + this.persistSettings(); + if (key === 'symbols') { this.pieces.setSymbols(value); this.hud.setSymbols(value); this.refreshHud(); } + if (key === 'ambience') this.ambience.setOn(value); + if (key === 'numbers') this.layoutNumbers(); + if (key === 'threats') this.drawThreats(); + } + + // ── flourishes ────────────────────────────────────────────────────────────── + sparks(x, y, n = 10) { for (let i = 0; i < n; i++) { - const col = i % per, row = Math.floor(i / per); - const x = cx - (per - 1) * (mr + gap) / 2 + col * (mr + gap); - const y = cy + row * (mr + gap); - const g = this.add.graphics().setDepth(DEPTH.ui); - g.fillStyle(0x000000, 0.3); g.fillCircle(x + 1, y + 1, mr); - g.fillStyle(ring, 1); g.fillCircle(x, y, mr); - g.fillStyle(fill, 1); g.fillCircle(x, y, mr - 3); - this.trayObjs.push(g); + const s = this.add.image(x, y, 'ck-spark').setDepth(D.fx).setScale(0.6 + Math.random() * 0.8).setTint(0xffe8a8); + const a = Math.random() * Math.PI * 2, r = 30 + Math.random() * 60; + this.tweens.add({ targets: s, x: x + Math.cos(a) * r, y: y + Math.sin(a) * r, alpha: 0, scale: 0.1, duration: 480 + Math.random() * 240, ease: 'Quad.Out', onComplete: () => s.destroy() }); } } - // ── Banners / overlays ────────────────────────────────────────────────────── - - showTurnBanner(text) { - const cx = BX + BOARD / 2; - const banner = this.add.text(cx, BY - 70, text, { - fontFamily: 'Righteous', fontSize: '36px', color: COLORS.textHex, - backgroundColor: '#111923ee', padding: { x: 28, y: 12 }, - }).setOrigin(0.5).setDepth(DEPTH.banner); - this.tweens.add({ - targets: banner, y: BY - 14, duration: 320, ease: 'Back.easeOut', - onComplete: () => { - this.time.delayedCall(1100, () => { - this.tweens.add({ targets: banner, y: BY - 70, alpha: 0, duration: 220, onComplete: () => banner.destroy() }); - }); - }, - }); - } - - onGameOver() { - const winner = getWinner(this.gs); - const isHuman = winner === 'white'; - const name = this.opponents[0]?.name ?? 'Opponent'; - this.playOpponentEmotion(isHuman ? 'upset' : 'happy'); - const cx = BX + BOARD / 2, cy = BY + BOARD / 2; - - if (isHuman) { - const emitter = this.add.particles(cx, cy, 'checkersParticle', { - speed: { min: 150, max: 500 }, lifespan: 1400, - scale: { start: 1.5, end: 0 }, alpha: { start: 1, end: 0 }, - quantity: 5, frequency: 25, angle: { min: 0, max: 360 }, - tint: [C.selGold, 0xffffff, COLORS.accent], - }).setDepth(DEPTH.banner); - this.time.delayedCall(2000, () => emitter.destroy()); + confetti() { + const cols = [0xc8201c, 0xf6f2ea, 0x1c3a8a, 0xf0d890]; + for (let i = 0; i < 90; i++) { + const x = BCX + (Math.random() - 0.5) * BOARD, y = BY - 40 - Math.random() * 200; + const r = this.add.rectangle(x, y, 8, 14, cols[i % cols.length]).setDepth(D.fx).setRotation(Math.random() * 6); + this.tweens.add({ + targets: r, y: y + 700 + Math.random() * 300, x: x + (Math.random() - 0.5) * 200, rotation: r.rotation + (Math.random() - 0.5) * 12, + alpha: { from: 1, to: 0 }, duration: 1800 + Math.random() * 1400, ease: 'Sine.In', onComplete: () => r.destroy(), + }); } - - this.time.delayedCall(450, () => { - const msg = isHuman - ? '🎉 You Win!\nEvery opposing piece captured or trapped.' - : `${name} wins this time.\nBetter luck next game!`; - const overlay = this.add.rectangle(cx, cy, 720, 300, 0x0a0e14, 0.9) - .setStrokeStyle(3, COLORS.accent).setDepth(DEPTH.banner); - const txt = this.add.text(cx, cy - 40, msg, { - fontFamily: '"Julius Sans One"', fontSize: '30px', - color: isHuman ? '#ffd700' : COLORS.textHex, align: 'center', - }).setOrigin(0.5).setDepth(DEPTH.banner + 1); - new Button(this, cx - 90, cy + 80, 'Play Again', () => { - overlay.destroy(); txt.destroy(); this.initGame(); - }, { width: 160, fontSize: 22 }).setDepth(DEPTH.banner + 1); - new Button(this, cx + 90, cy + 80, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 160, fontSize: 22 }).setDepth(DEPTH.banner + 1); - }); } + + callout(text, x, y, color) { + const hex = Phaser.Display.Color.IntegerToColor(color).rgba; + const t = this.add.text(x, y, text, { + fontFamily: BOLD_FONT, fontSize: '34px', color: hex, stroke: '#1a0c08', strokeThickness: 7, + shadow: { offsetX: 0, offsetY: 4, color: '#000', blur: 10, fill: true }, + }).setOrigin(0.5).setDepth(D.fx + 2).setScale(0.3).setAlpha(0); + this.tweens.add({ targets: t, scale: 1, alpha: 1, duration: 260, ease: 'Back.Out' }); + this.tweens.add({ targets: t, y: y - 50, alpha: 0, delay: 900, duration: 500, onComplete: () => t.destroy() }); + } + + banner(text, color, scale = 1, small = false) { + this.bannerObj?.destroy(); + const hex = Phaser.Display.Color.IntegerToColor(color).rgba; + const t = this.add.text(0, 0, text, { + fontFamily: DISPLAY_FONT, fontSize: small ? '60px' : '92px', color: hex, stroke: '#140806', strokeThickness: small ? 9 : 12, + shadow: { offsetX: 0, offsetY: 6, color: '#000', blur: 16, fill: true }, + }).setOrigin(0.5); + const cont = this.add.container(BANNER.x, BANNER.y - 110, [t]).setDepth(D.banner).setScale(scale * 0.4).setAlpha(0); + this.bannerObj = cont; + this.tweens.add({ targets: cont, y: BANNER.y, scale, alpha: 1, duration: 380, ease: 'Back.Out' }); + this.tweens.add({ targets: cont, alpha: 0, y: BANNER.y - 40, delay: small ? 1000 : 1900, duration: 420, onComplete: () => { cont.destroy(); if (this.bannerObj === cont) this.bannerObj = null; } }); + } + + wait(ms) { return new Promise((r) => this.time.delayedCall(Math.max(0, ms), r)); } } + diff --git a/src/games/checkers/CheckersHud.js b/src/games/checkers/CheckersHud.js new file mode 100644 index 0000000..90b565c --- /dev/null +++ b/src/games/checkers/CheckersHud.js @@ -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)); } +} diff --git a/src/games/checkers/CheckersLayout.js b/src/games/checkers/CheckersLayout.js new file mode 100644 index 0000000..3bb7c61 --- /dev/null +++ b/src/games/checkers/CheckersLayout.js @@ -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]; +} diff --git a/src/games/checkers/CheckersLogic.js b/src/games/checkers/CheckersLogic.js index ae3f042..659e88b 100644 --- a/src/games/checkers/CheckersLogic.js +++ b/src/games/checkers/CheckersLogic.js @@ -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 o; +} + +// ── 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); +} + +// 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 { board, turn: 'white', mustContinueFrom: null, winner: null, phase: 'playing' }; + return any; } -function dirsFor(piece) { - if (piece.king) return KING_DIRS; - return piece.color === 'white' ? WHITE_DIRS : BLACK_DIRS; +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 }; } -// 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 }); +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 { slides, jumps }; } -// 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; +/** 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); +} - if (state.mustContinueFrom) { - const [r, c] = state.mustContinueFrom; - return stepMovesFor(state, r, c).jumps; +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; } } - - 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); - } - } - return allJumps.length > 0 ? allJumps : allSlides; + return false; } -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; +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; } -// 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'; } +// ── 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; } - } - 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 +/** + * 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.ballot = { name: opts.ballot.name, moves: opts.ballot.moves.slice() }; + return s; } - - s.mustContinueFrom = null; - s.turn = other(s.turn); - return resolveEnd(s); + return gs; } -export function isGameOver(state) { return state.phase === 'game_over'; } -export function getWinner(state) { return state.winner; } +export function cloneState(gs) { + return JSON.parse(JSON.stringify(gs)); +} -export function pieceCounts(state) { +export function legalMoves(gs) { + if (gs.phase !== 'playing') return []; + return generateMoves(gs.board, gs.turn, rulesOf(gs.variant)); +} + +/** 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; } diff --git a/src/games/checkers/CheckersPieces.js b/src/games/checkers/CheckersPieces.js new file mode 100644 index 0000000..460c43b --- /dev/null +++ b/src/games/checkers/CheckersPieces.js @@ -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); + } +} diff --git a/src/games/checkers/CheckersSound.js b/src/games/checkers/CheckersSound.js new file mode 100644 index 0000000..8e63505 --- /dev/null +++ b/src/games/checkers/CheckersSound.js @@ -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(); } +} diff --git a/src/games/checkers/CheckersTalk.js b/src/games/checkers/CheckersTalk.js new file mode 100644 index 0000000..f7e8d0f --- /dev/null +++ b/src/games/checkers/CheckersTalk.js @@ -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; +} diff --git a/src/games/checkers/tutorial.md b/src/games/checkers/tutorial.md new file mode 100644 index 0000000..c3fe053 --- /dev/null +++ b/src/games/checkers/tutorial.md @@ -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. diff --git a/tools/verifyCheckers.js b/tools/verifyCheckers.js new file mode 100644 index 0000000..c1cdc4f --- /dev/null +++ b/tools/verifyCheckers.js @@ -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);