From 5424a7e37996b3a00a79664d799a8c360274e769 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Tue, 1 Dec 2026 07:36:16 -0700 Subject: [PATCH] Rewrite Cribbage as "The Keeper's Cottage" on the card-table kit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New art: baked lighthouse-keeper's kitchen room, walnut board with inlaid skunk lines and a lighthouse for 121, compass-rose card backs, pegs, gauge - PegBoard: animated leapfrogging pegs (lift, hop, walk hole-by-hole, tock) - Rules engine: pure JSON state, cut-for-deal, go/last-card settle, skunks and double skunk, match play (best of 3/5/7), 61-point board, save/resume - AI: exact lay-away EV over all starters + precomputed crib tables (new tools/genCribbageCribTable.js), reply-aware pegging, skill ladder 1–5 and a Coach with plain-English advice - Scene flow: deal animation, cutting, coach hints/previews, the show counted aloud via ShowCaption, end screen with score-race chart, rules/settings/ lifetime-record dialogs, ambience (rain, lamp flicker, lighthouse beam) - verifyCribbage.js: brute-force scorer cross-check, engine edge cases, AI legality and skill-ladder paired deals, layout collision checks, soak --- src/games/cribbage/CribbageAI.js | 289 +++- src/games/cribbage/CribbageArt.js | 862 ++++++++++ src/games/cribbage/CribbageBoard.js | 207 +++ src/games/cribbage/CribbageData.js | 352 ++-- src/games/cribbage/CribbageDialogs.js | 115 ++ src/games/cribbage/CribbageEndScreen.js | 124 ++ src/games/cribbage/CribbageGame.js | 1998 ++++++++++++++++------- src/games/cribbage/CribbageLogic.js | 582 ++++--- src/games/cribbage/CribbageShow.js | 71 + src/games/cribbage/CribbageTable.js | 194 +++ src/games/cribbage/tutorial.md | 68 +- tools/genCribbageCribTable.js | 47 + tools/verifyCribbage.js | 539 ++++-- 13 files changed, 4304 insertions(+), 1144 deletions(-) create mode 100644 src/games/cribbage/CribbageArt.js create mode 100644 src/games/cribbage/CribbageBoard.js create mode 100644 src/games/cribbage/CribbageDialogs.js create mode 100644 src/games/cribbage/CribbageEndScreen.js create mode 100644 src/games/cribbage/CribbageShow.js create mode 100644 src/games/cribbage/CribbageTable.js create mode 100644 tools/genCribbageCribTable.js diff --git a/src/games/cribbage/CribbageAI.js b/src/games/cribbage/CribbageAI.js index f769d6c..e9f1a18 100644 --- a/src/games/cribbage/CribbageAI.js +++ b/src/games/cribbage/CribbageAI.js @@ -1,68 +1,267 @@ -// Cribbage — heuristic opponent (skill 1-5). No Phaser, no state mutation. -// Two decisions: which two cards to lay away to the crib, and which card to -// play during the pegging. Both are greedy with skill-scaled noise. +// Cribbage — opponent + Coach. No Phaser; never mutates the game state. +// +// Lay-away: for each of the 15 ways to keep four of six, the EXACT expected +// hand value over the 46 possible starters, plus (dealer) or minus (pone) the +// expected crib value of the two cards laid away — from exact tables built by +// tools/genCribbageCribTable.js (opponent's two cards and the starter averaged +// over every possibility). +// +// Pegging: each legal card scores what it pegs now, minus what the opponent +// can be expected to peg back (each unseen rank weighted by the chance they +// hold it, assuming they take their best reply), plus what you can peg back +// in turn. Weaker skills drop the look-ahead and add noise. +// +// Skill ladder (PROFILE): 1 static counts + heavy noise … 5 full evaluation +// (measured on paired deals by tools/verifyCribbage.js; each level beats the +// one below). The Coach is skill 5. -import { cribValue, runRank } from './CribbageData.js'; -import { scoreHand, scorePlay } from './CribbageLogic.js'; +import { + fullDeck, scoreHand, scorePlay, cardFromId, cardName, rankLabel, PLAY_LIMIT, +} from './CribbageData.js'; -const clampSkill = (s) => Math.max(1, Math.min(5, s | 0)) || 3; +// Expected crib points for a two-card lay-away (rank index A=0 … K=12), +// off-suit and suited. Generated by tools/genCribbageCribTable.js. +const CRIB_EV = [ + [ 5.53, 4.43, 4.55, 5.46, 5.73, 4.25, 4.07, 4.12, 4.03, 3.95, 4.19, 3.85, 3.74], + [ 4.43, 5.83, 6.83, 4.84, 5.76, 4.36, 4.28, 4.23, 4.13, 4.06, 4.30, 3.96, 3.85], + [ 4.55, 6.83, 6.16, 5.49, 6.42, 4.27, 4.35, 4.28, 4.11, 4.14, 4.38, 4.04, 3.93], + [ 5.46, 4.84, 5.49, 6.14, 6.99, 4.96, 4.17, 4.30, 4.20, 4.14, 4.37, 4.03, 3.93], + [ 5.73, 5.76, 6.42, 6.99, 8.99, 7.09, 6.41, 5.75, 5.73, 7.02, 7.26, 6.92, 6.81], + [ 4.25, 4.36, 4.27, 4.96, 7.09, 6.29, 5.53, 4.89, 5.57, 3.83, 4.07, 3.73, 3.62], + [ 4.07, 4.28, 4.35, 4.17, 6.41, 5.53, 6.11, 6.76, 4.35, 3.72, 4.02, 3.68, 3.57], + [ 4.12, 4.23, 4.28, 4.30, 5.75, 4.89, 6.76, 5.63, 4.93, 4.30, 3.94, 3.66, 3.55], + [ 4.03, 4.13, 4.11, 4.20, 5.73, 5.57, 4.35, 4.93, 5.53, 4.84, 4.48, 3.55, 3.50], + [ 3.95, 4.06, 4.14, 4.14, 7.02, 3.83, 3.72, 4.30, 4.84, 5.46, 5.04, 4.11, 3.41], + [ 4.19, 4.30, 4.38, 4.37, 7.26, 4.07, 4.02, 3.94, 4.48, 5.04, 5.93, 5.01, 4.30], + [ 3.85, 3.96, 4.04, 4.03, 6.92, 3.73, 3.68, 3.66, 3.55, 4.11, 5.01, 5.25, 3.96], + [ 3.74, 3.85, 3.93, 3.93, 6.81, 3.62, 3.57, 3.55, 3.50, 3.41, 4.30, 3.96, 5.03], +]; +const CRIB_EV_SUITED = [ + [ 0.00, 4.48, 4.60, 5.51, 5.77, 4.30, 4.12, 4.16, 4.08, 3.99, 4.21, 3.89, 3.78], + [ 4.48, 0.00, 6.87, 4.88, 5.80, 4.40, 4.32, 4.27, 4.17, 4.11, 4.32, 4.00, 3.90], + [ 4.60, 6.87, 0.00, 5.53, 6.46, 4.31, 4.39, 4.33, 4.15, 4.18, 4.40, 4.08, 3.97], + [ 5.51, 4.88, 5.53, 0.00, 7.03, 5.00, 4.22, 4.34, 4.24, 4.18, 4.40, 4.08, 3.97], + [ 5.77, 5.80, 6.46, 7.03, 0.00, 7.13, 6.45, 5.79, 5.77, 7.06, 7.28, 6.96, 6.85], + [ 4.30, 4.40, 4.31, 5.00, 7.13, 0.00, 5.57, 4.94, 5.61, 3.88, 4.09, 3.77, 3.67], + [ 4.12, 4.32, 4.39, 4.22, 6.45, 5.57, 0.00, 6.80, 4.39, 3.76, 4.04, 3.72, 3.61], + [ 4.16, 4.27, 4.33, 4.34, 5.79, 4.94, 6.80, 0.00, 4.97, 4.34, 3.96, 3.70, 3.60], + [ 4.08, 4.17, 4.15, 4.24, 5.77, 5.61, 4.39, 4.97, 0.00, 4.88, 4.51, 3.59, 3.54], + [ 3.99, 4.11, 4.18, 4.18, 7.06, 3.88, 3.76, 4.34, 4.88, 0.00, 5.07, 4.15, 3.45], + [ 4.21, 4.32, 4.40, 4.40, 7.28, 4.09, 4.04, 3.96, 4.51, 5.07, 0.00, 5.03, 4.33], + [ 3.89, 4.00, 4.08, 4.08, 6.96, 3.77, 3.72, 3.70, 3.59, 4.15, 5.03, 0.00, 4.01], + [ 3.78, 3.90, 3.97, 3.97, 6.85, 3.67, 3.61, 3.60, 3.54, 3.45, 4.33, 4.01, 0.00], +]; -export function thinkDelay(skill) { - const base = [1100, 950, 820, 700, 580][clampSkill(skill) - 1]; - return base + Math.random() * 400; +/** Expected crib points of two cards laid away (before the other two + starter). */ +export function cribEV(a, b) { + const t = a.suit === b.suit && a.rank !== b.rank ? CRIB_EV_SUITED : CRIB_EV; + return t[a.run - 1][b.run - 1]; } -// Rough expected value of the two cards laid into the crib (before the cut). -function cribPotential(a, b) { +export const PROFILE = { + 1: { discard: 'static', cribW: 0, noiseD: 3.0, peg: 'greedy', pegW: 0.5, noiseP: 2.6 }, + 2: { discard: 'static', cribW: 0.5, noiseD: 1.4, peg: 'greedy', pegW: 1, noiseP: 1.1 }, + 3: { discard: 'ev', cribW: 0.5, noiseD: 0.8, peg: 'safe', pegW: 1, noiseP: 0.5 }, + 4: { discard: 'ev', cribW: 0.85, noiseD: 0.55, peg: 'reply', pegW: 1, noiseP: 0.3 }, + 5: { discard: 'ev', cribW: 1, noiseD: 0, peg: 'deep', pegW: 1, noiseP: 0 }, +}; +// look-ahead weights for 'deep' pegging: your counter-reply, the chance they can't follow +export const DEEP = { counter: 0.6, go: 0.8, low: 0.01 }; +const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3))); +const noise = (rng, amt) => (amt ? (rng() * 2 - 1) * amt : 0); + +// A rough crib guess for the weaker skills (no tables). +function cribGuess(a, b) { let v = 0; - if (a.rank === b.rank) v += 2; // pair - if (cribValue(a) + cribValue(b) === 15) v += 2; // a built-in fifteen - v += [a, b].filter((c) => cribValue(c) === 5).length * 1.5; // fives are gold in the crib - if (Math.abs(runRank(a) - runRank(b)) <= 2 && a.rank !== b.rank) v += 1; // run potential + if (a.rank === b.rank) v += 2; + if (a.val + b.val === 15) v += 2; + v += [a, b].filter((c) => c.val === 5).length * 1.5; + if (Math.abs(a.run - b.run) <= 2 && a.rank !== b.rank) v += 1; return v; } +// ── Lay-away ───────────────────────────────────────────────────────────────── /** - * Choose two cards to discard to the crib from a six-card hand. - * @returns {Card[]} the two discards + * Every way to lay two of six away, best first: + * [{ discard: [c, c], keep: [c×4], hand, crib, total }] + * hand = expected hand points over the 46 unseen starters (or the static + * count when opts.static); crib = expected crib points (signed: + to the + * dealer, − to the pone, scaled by opts.cribW). */ -export function chooseDiscard(hand6, isDealer, skill = 3) { - const sk = clampSkill(skill); - const noise = (5 - sk) * 1.4; - let best = null, bestVal = -Infinity; - +export function rankDiscards(hand6, isDealer, { cribW = 1, static: stat = false, guess = false } = {}) { + const mine = new Set(hand6.map((c) => c.id)); + const starters = stat ? null : fullDeck().filter((c) => !mine.has(c.id)); + const out = []; for (let i = 0; i < hand6.length; i++) { for (let j = i + 1; j < hand6.length; j++) { const discard = [hand6[i], hand6[j]]; const keep = hand6.filter((_, k) => k !== i && k !== j); - const handVal = scoreHand(keep, null).total; // static value, no starter - const crib = cribPotential(discard[0], discard[1]) * 0.5; - let val = handVal + (isDealer ? crib : -crib); - val += (Math.random() * 2 - 1) * noise; - if (val > bestVal) { bestVal = val; best = discard; } + let hand; + if (stat) hand = scoreHand(keep, null).total; + else { + let sum = 0; + for (const s of starters) sum += scoreHand(keep, s).total; + hand = sum / starters.length; + } + const cv = (guess ? cribGuess(discard[0], discard[1]) : cribEV(discard[0], discard[1])) * cribW; + const crib = isDealer ? cv : -cv; + out.push({ discard, keep, hand, crib, total: hand + crib }); } } - return best; + return out.sort((a, b) => b.total - a.total); +} + +/** The opponent's lay-away: two card ids. */ +export function chooseDiscard(gs, seat, { skill = 3, rng = Math.random } = {}) { + const pr = PROFILE[clampSkill(skill)]; + const isDealer = gs.dealer === seat; + const opts = rankDiscards(gs.hands[seat], isDealer, { + cribW: pr.cribW || 0, static: pr.discard === 'static', guess: pr.discard === 'static', + }); + let best = opts[0], bestV = -Infinity; + for (const o of opts) { + const v = o.total + noise(rng, pr.noiseD); + if (v > bestV) { bestV = v; best = o; } + } + return best.discard.map((c) => c.id); +} + +/** Coach advice for a lay-away: the full ranking (skill-5 evaluation). */ +export function coachDiscard(gs, seat) { + const options = rankDiscards(gs.hands[seat], gs.dealer === seat); + return { best: options[0], options }; +} + +// ── Pegging ────────────────────────────────────────────────────────────────── +const REP = Array.from({ length: 14 }, (_, r) => (r ? cardFromId(`${['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'][r - 1]}x`) : null)); + +/** Ranks the opponent might still hold, as counts by run (1..13), from `seat`'s view. */ +export function unseenFor(gs, seat) { + const known = new Set(gs.hands[seat].map((c) => c.id)); + if (gs.starter) known.add(gs.starter.id); + const P = gs.play; + if (P) { + for (const p of P.pile) known.add(p.id); + for (const s of P.series) for (const p of s) known.add(p.id); + } + const counts = new Array(14).fill(0); + let n = 0; + for (const c of fullDeck()) if (!known.has(c.id)) { counts[c.run]++; n++; } + return { counts, n }; +} + +// P(a hand of h cards drawn from n unseen holds at least one of the k of a rank) +function pHas(k, n, h) { + if (!k || !h) return 0; + let miss = 1; + for (let i = 0; i < h; i++) miss *= Math.max(0, (n - k - i)) / (n - i); + return 1 - miss; } /** - * Choose which legal card to play during the pegging. - * @returns {Card} the card to play + * Value of laying `card` now, from `seat`'s view. + * now points it pegs + * reply expected points the opponent pegs straight back + * counter expected points you then peg back (deep only) + * go chance the opponent can't follow at all */ -export function choosePlay(legal, pile, count, skill = 3) { - const sk = clampSkill(skill); - const noise = (5 - sk) * 1.2; - let best = null, bestVal = -Infinity; - - for (const c of legal) { - const pts = scorePlay([...pile, c]).points; - const newCount = count + cribValue(c); - let val = pts * 4; - if (newCount === 5 || newCount === 21) val -= 2; // hands opponent an easy ten for 15/31 - if (pile.length === 0 && cribValue(c) === 5) val -= 3; // never lead a five - if (pile.length === 0 && newCount === 21) val += 0; - val += (Math.random() * 2 - 1) * noise; - if (val > bestVal) { bestVal = val; best = c; } +export function evalPlay(gs, seat, card, mode = 'deep', w = DEEP) { + const P = gs.play; + const pile = P.pile.map((p) => cardFromId(p.id)); + const after = [...pile, card]; + const sc = scorePlay(after); + const now = sc.points; + const count = P.count + card.val; + const res = { card, now, reasons: sc.reasons, count, reply: 0, counter: 0, go: 0, value: now }; + const target = gs.rules.target; + if (gs.scores[seat] + now >= target) { res.value = 1000 + now; res.wins = true; return res; } + if (mode === 'greedy') return res; + if (mode === 'safe') { + let pen = 0; + if (count === 5 || count === 21) pen += 1.2; + if (!pile.length && card.val === 5) pen += 1.5; + if (count === PLAY_LIMIT) pen = 0; + res.value = now - pen; + return res; } - return best; + const opp = 1 - seat; + const h = P.hands[opp].length; + if (count === PLAY_LIMIT || !h) { res.value = now; return res; } + const { counts, n } = unseenFor(gs, seat); + const mine = P.hands[seat].filter((c) => c.id !== card.id); + const options = []; + for (let r = 1; r <= 13; r++) { + if (!counts[r]) continue; + const rc = REP[r]; + if (count + rc.val > PLAY_LIMIT) continue; + const pts = scorePlay([...after, rc]).points; + let counter = 0; + if (mode === 'deep') { + const c2 = count + rc.val; + if (c2 < PLAY_LIMIT) { + for (const m of mine) { + if (c2 + m.val > PLAY_LIMIT) continue; + counter = Math.max(counter, scorePlay([...after, rc, m]).points); + } + } + } + options.push({ r, pts, counter, p: pHas(counts[r], n, h) }); + } + // the opponent takes their best reply (ties: the one that leaves you least) + options.sort((a, b) => b.pts - a.pts || a.counter - b.counter); + let none = 1, reply = 0, counter = 0; + for (const o of options) { + const w = none * o.p; + reply += w * o.pts; + counter += w * o.counter; + none *= 1 - o.p; + } + res.reply = reply; + res.counter = counter; + res.go = none; + res.value = mode === 'deep' ? now - reply + w.counter * counter + w.go * none : now - reply; + return res; } + +/** The opponent's pegging card id. */ +export function choosePlay(gs, seat, { skill = 3, rng = Math.random } = {}) { + const pr = PROFILE[clampSkill(skill)]; + const P = gs.play; + const legal = P.hands[seat].filter((c) => P.count + c.val <= PLAY_LIMIT); + if (!legal.length) return null; + let best = legal[0], bestV = -Infinity; + for (const c of legal) { + const w = pr.deep ?? DEEP; + const e = evalPlay(gs, seat, c, pr.peg, w); + // keep low cards for the end of a series (a small, steady preference) + const v = (e.wins ? e.value : e.value * pr.pegW) + (pr.peg === 'deep' ? -c.val * w.low : 0) + noise(rng, pr.noiseP); + if (v > bestV) { bestV = v; best = c; } + } + return best.id; +} + +/** Coach advice for the human's pegging card: { id, reason, evals }. */ +export function coachPlay(gs, seat) { + const P = gs.play; + const legal = P.hands[seat].filter((c) => P.count + c.val <= PLAY_LIMIT); + if (!legal.length) return null; + const evals = legal.map((c) => evalPlay(gs, seat, c, 'deep')).sort((a, b) => b.value - a.value || a.card.val - b.card.val); + const b = evals[0]; + const name = cardName(b.card); + let reason; + if (b.wins) reason = `Play the ${name} — it pegs out and wins!`; + else if (b.now) reason = `Play the ${name}: ${words(b.reasons)} for ${b.now}`; + else if (!P.pile.length) { + reason = b.card.val <= 4 + ? `Lead the ${name} — nothing makes fifteen off a ${rankLabel(b.card)}` + : `Lead the ${name} — the safest lead you have`; + } else if (b.count === 5 || b.count === 21) reason = `Play the ${name} (careful — any ten-card answers it)`; + else reason = `Play the ${name} — the least for them to peg back${b.reply >= 0.05 ? ` (≈${b.reply.toFixed(1)})` : ''}`; + return { id: b.card.id, reason, evals }; +} + +function words(reasons) { + return reasons.map((r) => (r === '15' ? 'fifteen' : r === '31' ? 'thirty-one' : r === 'pair' ? 'a pair' + : r === 'pairRoyal' ? 'pair royal' : r === 'doublePairRoyal' ? 'double pair royal' : r.startsWith('run') ? `a run of ${r.slice(3)}` : r)).join(' + '); +} + diff --git a/src/games/cribbage/CribbageArt.js b/src/games/cribbage/CribbageArt.js new file mode 100644 index 0000000..9598909 --- /dev/null +++ b/src/games/cribbage/CribbageArt.js @@ -0,0 +1,862 @@ +// Cribbage art — "The Keeper's Cottage": Old Murph's lighthouse-keeper's +// kitchen on a stormy night. Baked once per page load into canvas textures +// (no image files). Card faces are the shared casino deck ('casino-cards'). +// +// crib-room plank wall, storm window (the light on the point, the cat +// on the sill), pot-belly stove, oilskin, barometer, ship in +// a bottle, life ring; a scrubbed oak table with a mug, +// pipe and oil lamp +// crib-board-* the walnut board (per target / match), holes and inlay +// crib-back navy card back, compass rose and rope border +// crib-peg-0/1 pegs (red = you, blue = Murph) + crib-peg-shadow +// crib-dial the brass count gauge (needle drawn live) +// crib-beam a soft band of light — the lighthouse sweeping past + +import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js'; +import { + bakeRoom, canvas, rr, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, pileSpot, CARD_TEX, +} from '../../ui/cardtable/TableArt.js'; +import { W, H } from '../../ui/cardtable/TableGeometry.js'; +import { T, L, boardGeometry, boardOutline, boardRect, boardPoint, skunkLinesFor } from './CribbageTable.js'; + +const CW = CARD_TEX.W, CH = CARD_TEX.H; +const SERIF = 'Georgia, "Times New Roman", serif'; +const BRASS = '#d9b45a'; +export const WINDOW = { x0: 1694, x1: 1904, y0: 16, y1: 292 }; +export const STOVE = { x: 104, y: 520 }; +export const LAMP = (() => { const p = T.P.project(0.9, 0.66); return { x: p.x, y: p.y, s: p.s }; })(); +export const LIGHTHOUSE = { x: WINDOW.x0 + 46, y: WINDOW.y0 + 132 }; + +function seeded(seed) { + let s = seed; + return () => { s = (s * 16807) % 2147483647; return s / 2147483647; }; +} + +// ── The room ───────────────────────────────────────────────────────────────── +function planks(ctx) { + const rnd = seeded(7); + const ph = 44; + for (let y = 0, i = 0; y < 700; y += ph, i++) { + ctx.fillStyle = mix('#6d6250', '#5a4f40', rnd()); + ctx.fillRect(0, y, W, ph); + ctx.fillStyle = 'rgba(255,240,210,0.05)'; + ctx.fillRect(0, y + 2, W, 3); + ctx.fillStyle = 'rgba(20,12,6,0.55)'; + ctx.fillRect(0, y + ph - 2, W, 2); + // butt joints and a few nail heads + for (let k = 0; k < 4; k++) { + const x = ((i * 377 + k * 523) % W); + ctx.fillStyle = 'rgba(20,12,6,0.5)'; + ctx.fillRect(x, y, 2, ph); + ctx.fillStyle = 'rgba(30,22,14,0.7)'; + ctx.beginPath(); ctx.arc(x + 9, y + 10, 1.6, 0, Math.PI * 2); ctx.arc(x + 9, y + ph - 10, 1.6, 0, Math.PI * 2); ctx.fill(); + } + } + ctx.fillStyle = noisePattern(ctx, 160, 18); + ctx.fillRect(0, 0, W, 700); +} + +function stormWindow(ctx) { + const { x0, x1, y0, y1 } = WINDOW; + // deep reveal + ctx.fillStyle = '#2a2219'; + rr(ctx, x0 - 16, y0 - 12, x1 - x0 + 32, y1 - y0 + 30, 6); + ctx.fill(); + // the night outside + const sky = ctx.createLinearGradient(0, y0, 0, y1); + sky.addColorStop(0, '#0b1424'); sky.addColorStop(0.55, '#16253a'); sky.addColorStop(0.62, '#0d1a28'); sky.addColorStop(1, '#060c16'); + ctx.fillStyle = sky; + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + // storm clouds + const rnd = seeded(23); + for (let i = 0; i < 14; i++) { + const cx = x0 + rnd() * (x1 - x0), cy = y0 + 20 + rnd() * 90; + const g = ctx.createRadialGradient(cx, cy, 2, cx, cy, 40 + rnd() * 40); + g.addColorStop(0, 'rgba(70,86,110,0.35)'); g.addColorStop(1, 'rgba(70,86,110,0)'); + ctx.fillStyle = g; + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + } + // the sea and the headland with the lighthouse + const horizon = y0 + (y1 - y0) * 0.6; + ctx.fillStyle = '#0a1520'; + ctx.fillRect(x0, horizon, x1 - x0, y1 - horizon); + ctx.strokeStyle = 'rgba(140,170,200,0.18)'; + ctx.lineWidth = 1.2; + for (let i = 0; i < 9; i++) { + const y = horizon + 8 + i * 12; + ctx.beginPath(); + for (let x = x0; x <= x1; x += 8) ctx.lineTo(x, y + Math.sin(x * 0.09 + i) * 2); + ctx.stroke(); + } + ctx.fillStyle = '#05090f'; + ctx.beginPath(); + ctx.moveTo(x0, horizon + 4); + ctx.quadraticCurveTo(x0 + 40, horizon - 22, x0 + 92, horizon + 2); + ctx.lineTo(x0, horizon + 10); + ctx.closePath(); + ctx.fill(); + const lx = LIGHTHOUSE.x, ly = LIGHTHOUSE.y; + ctx.fillStyle = '#d8d2c4'; + ctx.beginPath(); ctx.moveTo(lx - 6, ly + 40); ctx.lineTo(lx - 4, ly + 6); ctx.lineTo(lx + 4, ly + 6); ctx.lineTo(lx + 6, ly + 40); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#a8322a'; + ctx.fillRect(lx - 5.2, ly + 16, 10.4, 6); + ctx.fillRect(lx - 5.8, ly + 30, 11.6, 6); + ctx.fillStyle = '#ffe9a8'; + ctx.fillRect(lx - 3, ly, 6, 6); + ctx.fillStyle = '#1a1a1a'; + ctx.beginPath(); ctx.moveTo(lx - 5, ly); ctx.lineTo(lx, ly - 6); ctx.lineTo(lx + 5, ly); ctx.closePath(); ctx.fill(); + // rain already on the glass + for (let i = 0; i < 70; i++) { + const x = x0 + rnd() * (x1 - x0), y = y0 + rnd() * (y1 - y0); + ctx.fillStyle = `rgba(190,210,235,${0.12 + rnd() * 0.2})`; + ctx.beginPath(); ctx.ellipse(x, y, 1.2, 1.8 + rnd() * 2, 0, 0, Math.PI * 2); ctx.fill(); + } + // sash and mullions + ctx.strokeStyle = '#3e3326'; + ctx.lineWidth = 7; + ctx.strokeRect(x0, y0, x1 - x0, y1 - y0); + ctx.lineWidth = 5; + ctx.beginPath(); + ctx.moveTo((x0 + x1) / 2, y0); ctx.lineTo((x0 + x1) / 2, y1); + ctx.moveTo(x0, (y0 + y1) / 2); ctx.lineTo(x1, (y0 + y1) / 2); + ctx.stroke(); + ctx.strokeStyle = 'rgba(255,230,180,0.12)'; + ctx.lineWidth = 1; + ctx.strokeRect(x0 + 4, y0 + 4, x1 - x0 - 8, y1 - y0 - 8); + // the sill and the cat asleep on it + ctx.fillStyle = '#4a3c2a'; + ctx.fillRect(x0 - 22, y1 + 10, x1 - x0 + 44, 14); + ctx.fillStyle = 'rgba(255,230,180,0.12)'; + ctx.fillRect(x0 - 22, y1 + 10, x1 - x0 + 44, 2); + sleepingCat(ctx, x0 + 128, y1 + 10); +} + +function sleepingCat(ctx, x, y) { + ctx.save(); + ctx.translate(x, y); + ctx.fillStyle = '#17120d'; + // body loaf + ctx.beginPath(); ctx.ellipse(0, -16, 44, 18, 0, Math.PI, 0); ctx.lineTo(44, 0); ctx.lineTo(-44, 0); ctx.closePath(); ctx.fill(); + // head tucked at the left, ears + ctx.beginPath(); ctx.ellipse(-38, -14, 15, 13, 0, 0, Math.PI * 2); ctx.fill(); + ctx.beginPath(); ctx.moveTo(-50, -20); ctx.lineTo(-47, -36); ctx.lineTo(-40, -24); ctx.closePath(); ctx.fill(); + ctx.beginPath(); ctx.moveTo(-36, -24); ctx.lineTo(-30, -37); ctx.lineTo(-26, -21); ctx.closePath(); ctx.fill(); + // tail curled round the front and hanging over the sill + ctx.strokeStyle = '#17120d'; + ctx.lineWidth = 7; + ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(40, -6); ctx.quadraticCurveTo(54, 6, 48, 26); ctx.quadraticCurveTo(46, 34, 52, 38); ctx.stroke(); + // rim light from the lamp + ctx.strokeStyle = 'rgba(255,200,130,0.35)'; + ctx.lineWidth = 1.6; + ctx.beginPath(); ctx.ellipse(0, -16, 44, 18, 0, Math.PI * 1.05, Math.PI * 1.6); ctx.stroke(); + ctx.beginPath(); ctx.ellipse(-38, -14, 15, 13, 0, Math.PI * 0.9, Math.PI * 1.5); ctx.stroke(); + ctx.restore(); +} + +function stove(ctx) { + const { x, y } = STOVE; + ctx.save(); + // flue pipe up the wall + ctx.fillStyle = '#1c1a18'; + ctx.fillRect(x - 14, 80, 28, y - 170); + ctx.fillStyle = 'rgba(255,255,255,0.06)'; + ctx.fillRect(x - 10, 80, 5, y - 170); + // pot-belly + const g = ctx.createRadialGradient(x - 20, y - 30, 10, x, y, 110); + g.addColorStop(0, '#3a3530'); g.addColorStop(1, '#0f0d0b'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(x, y, 72, 96, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#26221e'; + rr(ctx, x - 62, y - 120, 124, 26, 8); ctx.fill(); + rr(ctx, x - 70, y + 78, 140, 22, 6); ctx.fill(); + // glowing grate + const fg = ctx.createRadialGradient(x, y + 20, 4, x, y + 20, 46); + fg.addColorStop(0, '#ffdd8a'); fg.addColorStop(0.4, '#ff8a2a'); fg.addColorStop(1, '#5a1a04'); + ctx.fillStyle = fg; + rr(ctx, x - 34, y - 4, 68, 46, 10); ctx.fill(); + ctx.strokeStyle = '#140f0a'; + ctx.lineWidth = 4; + for (let i = -2; i <= 2; i++) { ctx.beginPath(); ctx.moveTo(x + i * 12, y - 4); ctx.lineTo(x + i * 12, y + 42); ctx.stroke(); } + ctx.restore(); +} + +function oilskin(ctx) { + // a yellow oilskin and sou'wester on a peg + ctx.save(); + ctx.fillStyle = '#3a2c1c'; + ctx.fillRect(36, 96, 150, 10); + ctx.fillStyle = '#c7a032'; + ctx.beginPath(); + ctx.moveTo(84, 104); ctx.lineTo(132, 104); ctx.lineTo(164, 300); ctx.lineTo(54, 300); ctx.closePath(); ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.25)'; + ctx.beginPath(); ctx.moveTo(108, 112); ctx.lineTo(116, 112); ctx.lineTo(122, 300); ctx.lineTo(104, 300); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#b08a26'; + ctx.beginPath(); ctx.ellipse(108, 102, 40, 12, 0, 0, Math.PI * 2); ctx.fill(); + ctx.beginPath(); ctx.ellipse(108, 92, 22, 14, 0, Math.PI, 0); ctx.fill(); + ctx.restore(); +} + +function barometer(ctx, x, y) { + ctx.save(); + ctx.fillStyle = '#3a2814'; + ctx.beginPath(); ctx.arc(x, y, 50, 0, Math.PI * 2); ctx.fill(); + const g = ctx.createLinearGradient(x - 44, y - 44, x + 44, y + 44); + g.addColorStop(0, '#f2d58a'); g.addColorStop(0.5, '#b8862e'); g.addColorStop(1, '#6a4a14'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.arc(x, y, 44, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#efe6cf'; + ctx.beginPath(); ctx.arc(x, y, 36, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#3a2a14'; + ctx.lineWidth = 1; + for (let i = 0; i <= 20; i++) { + const a = Math.PI * 0.8 + (i / 20) * Math.PI * 1.4; + ctx.beginPath(); + ctx.moveTo(x + Math.cos(a) * 30, y + Math.sin(a) * 30); + ctx.lineTo(x + Math.cos(a) * (i % 5 ? 33 : 35), y + Math.sin(a) * (i % 5 ? 33 : 35)); + ctx.stroke(); + } + ctx.fillStyle = '#3a2a14'; + ctx.font = `8px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.fillText('STORMY', x - 16, y + 18); + ctx.fillText('FAIR', x + 18, y + 18); + ctx.strokeStyle = '#8a1a14'; + ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x - 22, y + 12); ctx.stroke(); + ctx.fillStyle = '#2a1a0a'; + ctx.beginPath(); ctx.arc(x, y, 3, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); +} + +function shipInBottle(ctx, x, y) { + ctx.save(); + // shelf + ctx.fillStyle = '#3e2e1c'; + ctx.fillRect(x - 90, y + 26, 200, 10); + ctx.fillStyle = 'rgba(0,0,0,0.35)'; + ctx.fillRect(x - 90, y + 36, 200, 6); + // bottle + ctx.fillStyle = 'rgba(150,190,170,0.22)'; + rr(ctx, x - 70, y - 12, 120, 38, 16); ctx.fill(); + ctx.fillRect(x + 46, y - 2, 30, 16); + ctx.fillStyle = '#6a4a2a'; + ctx.fillRect(x + 74, y - 1, 10, 14); + // the ship + ctx.fillStyle = '#4a2a14'; + ctx.beginPath(); ctx.moveTo(x - 46, y + 14); ctx.lineTo(x + 26, y + 14); ctx.lineTo(x + 18, y + 22); ctx.lineTo(x - 40, y + 22); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#e8dfc8'; + for (const [sx, h] of [[-30, 22], [-8, 26], [12, 20]]) { + ctx.beginPath(); ctx.moveTo(sx, y + 12); ctx.lineTo(sx, y + 12 - h); ctx.lineTo(sx + 12, y + 12 - h * 0.3); ctx.closePath(); ctx.fill(); + } + ctx.strokeStyle = 'rgba(255,255,255,0.35)'; + ctx.lineWidth = 1.5; + ctx.beginPath(); ctx.moveTo(x - 62, y - 6); ctx.lineTo(x + 30, y - 6); ctx.stroke(); + ctx.restore(); +} + +function lifeRing(ctx, x, y) { + ctx.save(); + ctx.lineWidth = 26; + for (let i = 0; i < 8; i++) { + ctx.strokeStyle = i % 2 ? '#e8e0d0' : '#b3322a'; + ctx.beginPath(); ctx.arc(x, y, 44, (i / 8) * Math.PI * 2, ((i + 1) / 8) * Math.PI * 2); ctx.stroke(); + } + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(0,0,0,0.4)'; + ctx.beginPath(); ctx.arc(x, y, 57, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.arc(x, y, 31, 0, Math.PI * 2); ctx.stroke(); + ctx.strokeStyle = '#c9b28a'; + ctx.lineWidth = 3; + ctx.beginPath(); ctx.arc(x, y, 50, Math.PI * 0.15, Math.PI * 0.85); ctx.stroke(); + ctx.restore(); +} + +function wall(ctx) { + planks(ctx); + stove(ctx); + oilskin(ctx); + barometer(ctx, 560, 78); + shipInBottle(ctx, 700, 96); + stormWindow(ctx); + lifeRing(ctx, 1842, 430); + // night: everything dim, warmer by the stove + ctx.fillStyle = 'rgba(8,6,4,0.42)'; + ctx.fillRect(0, 0, W, 700); + const sg = ctx.createRadialGradient(STOVE.x, STOVE.y, 20, STOVE.x, STOVE.y, 520); + sg.addColorStop(0, 'rgba(255,140,60,0.28)'); sg.addColorStop(1, 'rgba(255,140,60,0)'); + ctx.fillStyle = sg; + ctx.fillRect(0, 0, W, 900); + // the floor (dark boards below the table) + const f = ctx.createLinearGradient(0, 640, 0, H); + f.addColorStop(0, '#2a1d12'); f.addColorStop(1, '#120b06'); + ctx.fillStyle = f; + ctx.fillRect(0, 640, W, H - 640); + ctx.fillStyle = '#1a120a'; + ctx.fillRect(0, 628, W, 14); +} + +function front(ctx, Tb) { + frontBands(ctx, Tb, ['#b08250', '#946a3e', '#7a5530', '#5e4024', '#422c18'], { grooves: [0.4] }); +} + +function rim(ctx, Tb) { + rimBand(ctx, Tb, { base: '#9a6c3e', dark: '#4a3018', light: '#e8c08a', grain: ['#5a3a1c', '#f0cc98'], gloss: 1.5 }); +} + +// Scrubbed oak: planks running the length of the table. +function oakTop(ctx, Tb) { + ctx.fillStyle = '#b88c58'; + ctx.fillRect(0, 0, W, H); + const rnd = seeded(41); + const n = 9; + for (let i = 0; i < n; i++) { + const v0 = i / n, v1 = (i + 1) / n; + const a = Tb.P.project(-1.1, v0), b = Tb.P.project(1.1, v0), c = Tb.P.project(1.1, v1), d = Tb.P.project(-1.1, v1); + ctx.fillStyle = mix('#c49a64', '#a87c4a', rnd()); + poly(ctx, [a, b, c, d]); + ctx.fill(); + // grain streaks along the plank + ctx.lineWidth = 1; + for (let k = 0; k < 26; k++) { + const vv = v0 + (v1 - v0) * rnd(); + const u0 = -1.1 + rnd() * 2.2, len = 0.15 + rnd() * 0.5; + ctx.strokeStyle = rnd() < 0.5 ? 'rgba(110,70,30,0.22)' : 'rgba(240,210,160,0.16)'; + ctx.beginPath(); + for (let t = 0; t <= 10; t++) { + const p = Tb.P.project(u0 + len * (t / 10), vv + Math.sin(t * 0.9 + k) * 0.002); + if (t) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); + } + ctx.stroke(); + } + // the seam + ctx.strokeStyle = 'rgba(60,36,14,0.55)'; + ctx.lineWidth = 1.6; + ctx.beginPath(); ctx.moveTo(d.x, d.y); ctx.lineTo(c.x, c.y); ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 200, 20); + ctx.fillRect(0, 0, W, H); + // knife marks and rings from a lifetime of mugs + ctx.strokeStyle = 'rgba(90,58,26,0.18)'; + ctx.lineWidth = 2; + for (const [u, v, r] of [[0.45, 0.82, 34], [-0.52, 0.86, 28], [0.15, 0.93, 30]]) { + const p = Tb.P.project(u, v); + ctx.beginPath(); ctx.ellipse(p.x, p.y, r * p.s, r * p.s * 0.8, 0, 0.3, Math.PI * 1.7); ctx.stroke(); + } + lampPool(ctx, Tb, { color: '255,206,140', alpha: 0.3, vignette: 0.6, at: { u: 0.35, v: 0.58 } }); + const st = Tb.P.project(-1.2, 0.5); + const g = ctx.createRadialGradient(st.x, st.y, 20, st.x, st.y, 760); + g.addColorStop(0, 'rgba(255,140,60,0.16)'); g.addColorStop(1, 'rgba(255,140,60,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + rimShadow(ctx, Tb, 0.36); +} + +function mugAndPipe(ctx) { + const p = T.P.project(-0.86, 0.75); + ctx.save(); + ctx.translate(p.x, p.y); + ctx.scale(p.s, p.s); + // enamel mug + ctx.fillStyle = 'rgba(0,0,0,0.35)'; + ctx.beginPath(); ctx.ellipse(10, 34, 40, 13, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = '#e8e4da'; + rr(ctx, -28, -26, 56, 60, 8); ctx.fill(); + ctx.strokeStyle = '#e8e4da'; ctx.lineWidth = 8; + ctx.beginPath(); ctx.arc(30, 4, 14, -Math.PI / 2, Math.PI / 2); ctx.stroke(); + ctx.fillStyle = '#1e3a5a'; + ctx.fillRect(-28, -26, 56, 6); + ctx.beginPath(); ctx.ellipse(0, -26, 28, 8, 0, 0, Math.PI * 2); + ctx.fillStyle = '#d8d2c4'; ctx.fill(); + ctx.beginPath(); ctx.ellipse(0, -25, 23, 6, 0, 0, Math.PI * 2); + ctx.fillStyle = '#3a2010'; ctx.fill(); + ctx.fillStyle = 'rgba(0,0,0,0.12)'; + ctx.fillRect(10, -20, 18, 54); + // pipe + ctx.translate(70, 30); + ctx.rotate(-0.25); + ctx.fillStyle = 'rgba(0,0,0,0.3)'; + ctx.beginPath(); ctx.ellipse(30, 10, 46, 7, 0, 0, Math.PI * 2); ctx.fill(); + ctx.strokeStyle = '#2a1a0e'; ctx.lineWidth = 5; ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(58, 2); ctx.stroke(); + ctx.fillStyle = '#5a3418'; + rr(ctx, 54, -16, 22, 22, 6); ctx.fill(); + ctx.fillStyle = '#1a0e06'; + ctx.beginPath(); ctx.ellipse(65, -16, 9, 3, 0, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); +} + +/** The oil lamp's base and glass chimney (the flame glow is live). */ +function oilLamp(ctx) { + const { x, y, s } = LAMP; + ctx.save(); + ctx.translate(x, y); + ctx.scale(s, s); + ctx.fillStyle = 'rgba(0,0,0,0.4)'; + ctx.beginPath(); ctx.ellipse(14, 10, 60, 16, 0, 0, Math.PI * 2); ctx.fill(); + const b = ctx.createLinearGradient(-40, 0, 40, 0); + b.addColorStop(0, '#6a4a14'); b.addColorStop(0.4, '#f0d080'); b.addColorStop(1, '#5a3a0c'); + ctx.fillStyle = b; + ctx.beginPath(); ctx.ellipse(0, 0, 42, 12, 0, 0, Math.PI * 2); ctx.fill(); + ctx.beginPath(); ctx.moveTo(-36, -2); ctx.quadraticCurveTo(-46, -40, -14, -54); ctx.lineTo(14, -54); ctx.quadraticCurveTo(46, -40, 36, -2); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#2a1a08'; + ctx.fillRect(-12, -62, 24, 10); + // chimney + const g = ctx.createLinearGradient(-20, 0, 20, 0); + g.addColorStop(0, 'rgba(255,240,210,0.35)'); g.addColorStop(0.5, 'rgba(255,250,235,0.12)'); g.addColorStop(1, 'rgba(255,240,210,0.4)'); + ctx.fillStyle = g; + ctx.beginPath(); + ctx.moveTo(-12, -62); ctx.quadraticCurveTo(-30, -92, -14, -118); ctx.lineTo(-10, -160); ctx.lineTo(10, -160); ctx.lineTo(14, -118); ctx.quadraticCurveTo(30, -92, 12, -62); ctx.closePath(); + ctx.fill(); + ctx.strokeStyle = 'rgba(255,240,210,0.5)'; ctx.lineWidth = 1.2; ctx.stroke(); + // the flame + const f = ctx.createRadialGradient(0, -88, 1, 0, -88, 16); + f.addColorStop(0, '#fffbe0'); f.addColorStop(0.5, '#ffc861'); f.addColorStop(1, 'rgba(255,140,40,0)'); + ctx.fillStyle = f; + ctx.beginPath(); ctx.ellipse(0, -88, 7, 16, 0, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); +} + +function marks(ctx) { + pileSpot(ctx, L.deck, 'DECK', { color: '90,60,28', alpha: 0.5 }); + pileSpot(ctx, L.cribMine, '', { color: '90,60,28', alpha: 0.28 }); + pileSpot(ctx, L.cribTheirs, '', { color: '90,60,28', alpha: 0.28 }); + mugAndPipe(ctx); +} + +// ── The board ──────────────────────────────────────────────────────────────── +function boardPainter(geo, { match, doubleSkunk }) { + return (ctx) => { + const top = boardOutline(); + const thick = 15; + // shadow on the table + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; + ctx.shadowBlur = 22; + ctx.shadowOffsetY = 16; + poly(ctx, top.map((p) => ({ x: p.x, y: p.y + thick * p.s }))); + ctx.fillStyle = '#000'; + ctx.fill(); + ctx.restore(); + // front edge + for (let i = thick; i >= 0; i -= 1.5) { + poly(ctx, top.map((p) => ({ x: p.x, y: p.y + i * p.s }))); + ctx.fillStyle = mix('#3a2212', '#24150a', i / thick); + ctx.fill(); + } + // top face: walnut + const ys = top.map((p) => p.y); + const y0 = Math.min(...ys), y1 = Math.max(...ys); + const xs = top.map((p) => p.x); + const x0 = Math.min(...xs), x1 = Math.max(...xs); + ctx.save(); + poly(ctx, top); + ctx.clip(); + const g = ctx.createLinearGradient(0, y0, 0, y1); + g.addColorStop(0, '#6e4426'); g.addColorStop(0.5, '#5a361c'); g.addColorStop(1, '#4a2c16'); + ctx.fillStyle = g; + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + const rnd = seeded(97); + for (let i = 0; i < 90; i++) { + const yy = y0 + rnd() * (y1 - y0); + const xa = x0 + rnd() * (x1 - x0), len = 80 + rnd() * 380; + ctx.strokeStyle = rnd() < 0.55 ? 'rgba(30,16,6,0.28)' : 'rgba(170,110,60,0.14)'; + ctx.lineWidth = 0.8 + rnd() * 1.4; + ctx.beginPath(); + for (let t = 0; t <= 12; t++) { + const x = xa + len * (t / 12); + const y = yy + Math.sin(t * 0.7 + i) * 1.6; + if (t) ctx.lineTo(x, y); else ctx.moveTo(x, y); + } + ctx.stroke(); + } + ctx.fillStyle = noisePattern(ctx, 128, 16); + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + // lamp sheen + const sh = ctx.createRadialGradient(LAMP.x - 200, y0, 20, LAMP.x - 200, y0, 700); + sh.addColorStop(0, 'rgba(255,214,150,0.16)'); sh.addColorStop(1, 'rgba(255,214,150,0)'); + ctx.fillStyle = sh; + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + ctx.restore(); + // bevel + brass inlay border + poly(ctx, top); + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(255,210,150,0.35)'; + ctx.stroke(); + poly(ctx, boardOutline(-0.012)); + ctx.lineWidth = 1.6; + ctx.strokeStyle = 'rgba(217,180,90,0.75)'; + ctx.stroke(); + + // inlay between the streets + const lineAt = (by, color, w) => { + ctx.strokeStyle = color; + ctx.lineWidth = w; + ctx.beginPath(); + for (let t = 0; t <= 20; t++) { + const bx = 0.03 + 0.94 * (t / 20); + const p = boardPoint(bx, by); + if (t) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); + } + ctx.stroke(); + }; + for (let st = 1; st < geo.streets; st++) { + const by = geo.edgeY + st * geo.bandH; + lineAt(by, 'rgba(217,180,90,0.7)', 2.2); + lineAt(by + 0.012, 'rgba(0,0,0,0.25)', 1); + } + // each player's track tinted faintly + for (let st = 0; st < geo.streets; st++) { + for (let seat = 0; seat < 2; seat++) { + const by = geo.rowBy(st, seat); + const a = boardPoint(geo.colBx(0) - 0.006, by), b = boardPoint(geo.colBx(geo.per - 1) + 0.006, by); + ctx.strokeStyle = seat === 0 ? 'rgba(216,71,58,0.32)' : 'rgba(79,155,216,0.32)'; + ctx.lineWidth = 9 * a.s; + ctx.lineCap = 'round'; + ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); + } + // mother-of-pearl dots between groups of five + for (let gi = 1; gi < geo.per / 5; gi++) { + const bx = (geo.colBx(gi * 5 - 1) + geo.colBx(gi * 5)) / 2; + const p = boardPoint(bx, geo.edgeY + (st + 0.5) * geo.bandH); + const pg = ctx.createRadialGradient(p.x - 1, p.y - 1, 0.5, p.x, p.y, 4 * p.s); + pg.addColorStop(0, '#ffffff'); pg.addColorStop(0.6, '#d8e4ec'); pg.addColorStop(1, '#9ab0c0'); + ctx.fillStyle = pg; + ctx.beginPath(); ctx.ellipse(p.x, p.y, 3.6 * p.s, 3 * p.s, 0, 0, Math.PI * 2); ctx.fill(); + } + } + // numbers every ten + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + for (const nmb of geo.numbers) { + ctx.font = `bold ${Math.round(10 * nmb.s + 1)}px ${SERIF}`; + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.fillText(String(nmb.n), nmb.x + 0.8, nmb.y + 0.8); + ctx.fillStyle = 'rgba(230,196,120,0.8)'; + ctx.fillText(String(nmb.n), nmb.x, nmb.y); + } + // skunk lines + const lines = skunkLinesFor(geo.target, doubleSkunk); + for (const { line, label } of lines) { + const segs = geo.skunk(line); + for (const { a, b } of segs) { + const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2; + const dx = b.x - a.x, dy = b.y - a.y, len = Math.hypot(dx, dy) || 1; + const nx = -dy / len, ny = dx / len; + const h = 11 * a.s; + ctx.strokeStyle = 'rgba(217,180,90,0.9)'; + ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(mx - nx * h, my - ny * h); ctx.lineTo(mx + nx * h, my + ny * h); ctx.stroke(); + } + const a = segs[0].a, b = segs[0].b; + const vertical = Math.abs(b.y - a.y) > Math.abs(b.x - a.x); + const lx = vertical ? Math.max(a.x, b.x) + 18 * a.s : (a.x + b.x) / 2; + const ly = vertical ? (a.y + b.y) / 2 : Math.max(a.y, b.y) + 14 * a.s; + ctx.font = `italic bold ${Math.round(12 * a.s + 2)}px ${SERIF}`; + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.fillText(label, lx + 1, ly + 1); + ctx.fillStyle = 'rgba(240,206,130,0.95)'; + ctx.fillText(label, lx, ly); + } + // the holes + const hole = (p, ring = null) => { + const r = geo.holeR * p.s; + ctx.fillStyle = 'rgba(255,220,170,0.16)'; + ctx.beginPath(); ctx.ellipse(p.x, p.y + 1.2, r + 1.4, (r + 1.4) * 0.84, 0, 0, Math.PI * 2); ctx.fill(); + const hg = ctx.createRadialGradient(p.x, p.y - r * 0.4, 0.5, p.x, p.y, r); + hg.addColorStop(0, '#050302'); hg.addColorStop(1, '#2a180a'); + ctx.fillStyle = hg; + ctx.beginPath(); ctx.ellipse(p.x, p.y, r, r * 0.84, 0, 0, Math.PI * 2); ctx.fill(); + if (ring) { + ctx.strokeStyle = ring; + ctx.lineWidth = 1.8; + ctx.beginPath(); ctx.ellipse(p.x, p.y, r + 3, (r + 3) * 0.84, 0, 0, Math.PI * 2); ctx.stroke(); + } + }; + const last = geo.holes[0].length - 1; + for (let seat = 0; seat < 2; seat++) { + geo.holes[seat].forEach((p, n) => hole(p, n === 0 || n === last ? 'rgba(240,206,130,0.95)' : null)); + hole(geo.alt[seat], 'rgba(240,206,130,0.6)'); + if (match) geo.gameHoles[seat].forEach((p) => hole(p, 'rgba(200,220,235,0.7)')); + } + // labels: START, the game hole, GAMES + const lab = (text, x, y, s, color = 'rgba(240,206,130,0.9)') => { + ctx.font = `bold ${Math.round(9 * s + 2)}px ${SERIF}`; + ctx.fillStyle = 'rgba(0,0,0,0.5)'; + ctx.fillText(text, x + 0.8, y + 0.8); + ctx.fillStyle = color; + ctx.fillText(text, x, y); + }; + const s0 = geo.holes[1][0], a0 = geo.alt[1]; + lab('START', (s0.x + a0.x) / 2, s0.y - 15 * s0.s, s0.s); + const f0 = geo.holes[0][last], f1 = geo.holes[1][last]; + lab(String(geo.target), f0.x, f0.y + 16 * f0.s, f0.s); + lab('GAME', f1.x, f1.y - 15 * f1.s, f1.s); + if (match) { + const gh = geo.gameHoles[1]; + const cx = (gh[0].x + gh[1].x) / 2; + lab('GAMES', cx, gh[0].y - 14 * gh[0].s, gh[0].s, 'rgba(200,220,235,0.9)'); + } + if (geo.target === 121) lighthouseInlay(ctx, geo); + }; +} + +/** A little white-and-red lighthouse inlaid at the free end of the board. */ +function lighthouseInlay(ctx, geo) { + const bx = (geo.endA + geo.endB) / 2 + 0.004; + const top = boardPoint(bx, 0.1), bot = boardPoint(bx, 0.6); + const s = top.s; + const x = top.x, h = bot.y - top.y; + ctx.save(); + ctx.globalAlpha = 0.85; + ctx.fillStyle = '#e8e0cc'; + ctx.beginPath(); ctx.moveTo(x - 7 * s, top.y + h); ctx.lineTo(x - 4 * s, top.y + 10 * s); ctx.lineTo(x + 4 * s, top.y + 10 * s); ctx.lineTo(x + 7 * s, top.y + h); ctx.closePath(); ctx.fill(); + ctx.fillStyle = '#b3322a'; + for (const f of [0.35, 0.65]) ctx.fillRect(x - (4.6 + f * 2.4) * s, top.y + 10 * s + (h - 10 * s) * f, (9.2 + f * 4.8) * s, 7 * s); + ctx.fillStyle = '#f0ce82'; + ctx.fillRect(x - 3.5 * s, top.y + 3 * s, 7 * s, 7 * s); + ctx.fillStyle = '#2a1a0a'; + ctx.beginPath(); ctx.moveTo(x - 5 * s, top.y + 3 * s); ctx.lineTo(x, top.y - 3 * s); ctx.lineTo(x + 5 * s, top.y + 3 * s); ctx.closePath(); ctx.fill(); + ctx.strokeStyle = 'rgba(240,206,130,0.6)'; + ctx.lineWidth = 1; + for (const d of [-1, 1]) { + ctx.beginPath(); ctx.moveTo(x + d * 6 * s, top.y + 6 * s); ctx.lineTo(x + d * 22 * s, top.y + 1 * s); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(x + d * 6 * s, top.y + 7 * s); ctx.lineTo(x + d * 22 * s, top.y + 12 * s); ctx.stroke(); + } + ctx.restore(); +} + +/** Bake (once) the board texture for a variant; returns { key, x, y }. */ +export function ensureBoard(scene, target, { match = false, doubleSkunk = false } = {}) { + const key = `crib-board-${target}${match ? '-m' : ''}${doubleSkunk ? '-ds' : ''}`; + const r = boardRect(); + const x = Math.floor(r.x0), y = Math.floor(r.y0); + if (!scene.textures.exists(key)) { + const c = canvas(Math.ceil(r.x1 - x), Math.ceil(r.y1 - y)); + const ctx = c.getContext('2d'); + ctx.translate(-x, -y); + boardPainter(boardGeometry(target), { match, doubleSkunk })(ctx); + scene.textures.addCanvas(key, c); + } + return { key, x, y }; +} + +// ── Card back ──────────────────────────────────────────────────────────────── +function compassRose(ctx, cx, cy, r) { + ctx.save(); + ctx.translate(cx, cy); + ctx.strokeStyle = BRASS; + ctx.lineWidth = 2; + ctx.beginPath(); ctx.arc(0, 0, r, 0, Math.PI * 2); ctx.stroke(); + ctx.lineWidth = 1; + ctx.beginPath(); ctx.arc(0, 0, r * 0.82, 0, Math.PI * 2); ctx.stroke(); + for (let i = 0; i < 32; i++) { + const a = (i / 32) * Math.PI * 2; + ctx.beginPath(); + ctx.moveTo(Math.cos(a) * r * 0.82, Math.sin(a) * r * 0.82); + ctx.lineTo(Math.cos(a) * r * (i % 4 ? 0.9 : 0.98), Math.sin(a) * r * (i % 4 ? 0.9 : 0.98)); + ctx.stroke(); + } + const point = (a, len, w, light) => { + ctx.save(); + ctx.rotate(a); + ctx.fillStyle = light ? '#f2dc9a' : '#a87a26'; + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, -len); ctx.lineTo(w, -w); ctx.closePath(); ctx.fill(); + ctx.fillStyle = light ? '#a87a26' : '#f2dc9a'; + ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, -len); ctx.lineTo(-w, -w); ctx.closePath(); ctx.fill(); + ctx.restore(); + }; + for (let i = 0; i < 4; i++) point(Math.PI / 4 + (i * Math.PI) / 2, r * 0.6, r * 0.12, false); + for (let i = 0; i < 4; i++) point((i * Math.PI) / 2, r * 0.95, r * 0.17, true); + ctx.fillStyle = '#1d2f4a'; + ctx.beginPath(); ctx.arc(0, 0, r * 0.1, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = BRASS; + ctx.font = `bold ${Math.round(r * 0.26)}px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText('N', 0, -r * 1.16); + ctx.restore(); +} + +function ropeRect(ctx, x, y, w, h, r) { + ctx.save(); + rr(ctx, x, y, w, h, r); + ctx.lineWidth = 7; + ctx.strokeStyle = '#b8955a'; + ctx.stroke(); + ctx.setLineDash([5, 5]); + ctx.lineWidth = 7; + ctx.strokeStyle = '#7a5a2a'; + ctx.stroke(); + ctx.setLineDash([]); + ctx.lineWidth = 1; + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; + rr(ctx, x - 4, y - 4, w + 8, h + 8, r + 3); ctx.stroke(); + rr(ctx, x + 4, y + 4, w - 8, h - 8, Math.max(1, r - 3)); ctx.stroke(); + ctx.restore(); +} + +function anchor(ctx, x, y, s) { + ctx.save(); + ctx.translate(x, y); + ctx.scale(s, s); + ctx.strokeStyle = BRASS; + ctx.lineWidth = 2.4; + ctx.lineCap = 'round'; + ctx.beginPath(); ctx.arc(0, -10, 3, 0, Math.PI * 2); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(0, -7); ctx.lineTo(0, 10); ctx.stroke(); + ctx.beginPath(); ctx.moveTo(-6, -3); ctx.lineTo(6, -3); ctx.stroke(); + ctx.beginPath(); ctx.arc(0, 2, 9, Math.PI * 0.15, Math.PI * 0.85); ctx.stroke(); + ctx.restore(); +} + +function bakeBack(scene) { + const c = canvas(CW, CH); + const ctx = c.getContext('2d'); + rr(ctx, 1, 1, CW - 2, CH - 2, 18); + const g = ctx.createLinearGradient(0, 0, CW, CH); + g.addColorStop(0, '#24395a'); g.addColorStop(1, '#101c30'); + ctx.fillStyle = g; + ctx.fill(); + ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(0,0,0,0.6)'; ctx.stroke(); + // fine wave engraving + ctx.save(); + rr(ctx, 14, 14, CW - 28, CH - 28, 10); + ctx.clip(); + ctx.strokeStyle = 'rgba(217,180,90,0.12)'; + ctx.lineWidth = 1.2; + for (let y = 10; y < CH; y += 9) { + ctx.beginPath(); + for (let x = 0; x <= CW; x += 6) ctx.lineTo(x, y + Math.sin(x * 0.09 + y * 0.05) * 2.4); + ctx.stroke(); + } + ctx.restore(); + ropeRect(ctx, 14, 14, CW - 28, CH - 28, 10); + compassRose(ctx, CW / 2, CH / 2 + 4, 54); + anchor(ctx, 34, 36, 0.9); + anchor(ctx, CW - 34, 36, 0.9); + anchor(ctx, 34, CH - 34, 0.9); + anchor(ctx, CW - 34, CH - 34, 0.9); + scene.textures.addCanvas('crib-back', c); +} + +// ── Pegs, gauge, beam ──────────────────────────────────────────────────────── +const PEG = [ + { body: ['#ff9a86', '#d8473a', '#7a1a12'], head: '#ffb8a8' }, + { body: ['#a8d8ff', '#4f9bd8', '#173a5e'], head: '#d0ecff' }, +]; + +function bakePegs(scene) { + PEG.forEach((p, seat) => { + const key = `crib-peg-${seat}`; + if (scene.textures.exists(key)) return; + const w = 28, h = 60; + const c = canvas(w, h); + const ctx = c.getContext('2d'); + const cx = w / 2; + const g = ctx.createLinearGradient(cx - 9, 0, cx + 9, 0); + g.addColorStop(0, p.body[2]); g.addColorStop(0.35, p.body[0]); g.addColorStop(0.6, p.body[1]); g.addColorStop(1, p.body[2]); + // tapered stem down into the hole + ctx.fillStyle = g; + ctx.beginPath(); + ctx.moveTo(cx - 8, 18); ctx.lineTo(cx + 8, 18); ctx.lineTo(cx + 5, h - 3); ctx.quadraticCurveTo(cx, h, cx - 5, h - 3); ctx.closePath(); + ctx.fill(); + // brass collar + const b = ctx.createLinearGradient(cx - 10, 0, cx + 10, 0); + b.addColorStop(0, '#7a5a1a'); b.addColorStop(0.4, '#f2d58a'); b.addColorStop(1, '#6a4a14'); + ctx.fillStyle = b; + rr(ctx, cx - 10, 16, 20, 6, 2); ctx.fill(); + // domed head + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(cx, 12, 11, 11, 0, 0, Math.PI * 2); ctx.fill(); + ctx.fillStyle = p.head; + ctx.globalAlpha = 0.85; + ctx.beginPath(); ctx.ellipse(cx - 4, 8, 3.6, 3, -0.4, 0, Math.PI * 2); ctx.fill(); + ctx.globalAlpha = 1; + ctx.strokeStyle = 'rgba(0,0,0,0.45)'; + ctx.lineWidth = 1; + ctx.beginPath(); ctx.ellipse(cx, 12, 11, 11, 0, 0, Math.PI * 2); ctx.stroke(); + scene.textures.addCanvas(key, c); + }); + if (!scene.textures.exists('crib-peg-shadow')) { + const c = canvas(40, 20); + const ctx = c.getContext('2d'); + const g = ctx.createRadialGradient(20, 10, 1, 20, 10, 18); + g.addColorStop(0, 'rgba(0,0,0,0.7)'); g.addColorStop(1, 'rgba(0,0,0,0)'); + ctx.fillStyle = g; + ctx.beginPath(); ctx.ellipse(20, 10, 19, 9, 0, 0, Math.PI * 2); ctx.fill(); + scene.textures.addCanvas('crib-peg-shadow', c); + } +} + +export const DIAL_A0 = Math.PI * 0.75; // 0 at the lower left… +export const DIAL_SWEEP = Math.PI * 1.5; // …31 at the lower right +export const dialAngle = (count) => DIAL_A0 + (Math.min(31, count) / 31) * DIAL_SWEEP; + +function bakeDial(scene) { + const R = 64, S = (R + 12) * 2 * 2; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + ctx.scale(2, 2); + const cx = R + 12, cy = R + 12; + ctx.save(); + ctx.shadowColor = 'rgba(0,0,0,0.6)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 6; + const bz = ctx.createLinearGradient(cx - R, cy - R, cx + R, cy + R); + bz.addColorStop(0, '#f6dc94'); bz.addColorStop(0.45, '#b8862e'); bz.addColorStop(1, '#5a3c0c'); + ctx.fillStyle = bz; + ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.fill(); + ctx.restore(); + ctx.fillStyle = '#7a5418'; + ctx.beginPath(); ctx.arc(cx, cy, R - 7, 0, Math.PI * 2); ctx.fill(); + const face = ctx.createRadialGradient(cx - 14, cy - 18, 4, cx, cy, R); + face.addColorStop(0, '#fbf3dc'); face.addColorStop(1, '#d8c9a0'); + ctx.fillStyle = face; + ctx.beginPath(); ctx.arc(cx, cy, R - 10, 0, Math.PI * 2); ctx.fill(); + // red arc from 28..31, green tick at 15 + const arcAt = (from, to, color, w, rad) => { + ctx.strokeStyle = color; ctx.lineWidth = w; + ctx.beginPath(); ctx.arc(cx, cy, rad, dialAngle(from), dialAngle(to)); ctx.stroke(); + }; + arcAt(26, 31, 'rgba(170,40,30,0.55)', 6, R - 16); + arcAt(14.6, 15.4, 'rgba(30,110,60,0.9)', 8, R - 16); + ctx.strokeStyle = '#2a1a0a'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + for (let i = 0; i <= 31; i++) { + const a = dialAngle(i); + const major = i % 5 === 0 || i === 31; + ctx.lineWidth = major ? 1.8 : 1; + const r0 = R - (major ? 24 : 20), r1 = R - 13; + ctx.beginPath(); ctx.moveTo(cx + Math.cos(a) * r0, cy + Math.sin(a) * r0); ctx.lineTo(cx + Math.cos(a) * r1, cy + Math.sin(a) * r1); ctx.stroke(); + if (major) { + ctx.font = `bold ${i === 15 || i === 31 ? 11 : 9}px ${SERIF}`; + ctx.fillStyle = i === 15 ? '#1e6a3c' : i === 31 ? '#8a1a14' : '#2a1a0a'; + ctx.fillText(String(i), cx + Math.cos(a) * (R - 32), cy + Math.sin(a) * (R - 32)); + } + } + ctx.font = `bold 8px ${SERIF}`; + ctx.fillStyle = '#6a4a20'; + ctx.fillText('THE COUNT', cx, cy - 20); + scene.textures.addCanvas('crib-dial', c); +} + +function bakeBeam(scene) { + const c = canvas(256, 8); + const ctx = c.getContext('2d'); + const g = ctx.createLinearGradient(0, 0, 256, 0); + g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(0.5, 'rgba(255,255,255,1)'); g.addColorStop(1, 'rgba(255,255,255,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, 256, 8); + scene.textures.addCanvas('crib-beam', c); +} + +export async function prepareCribArt(scene) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('crib-back')) bakeBack(scene); + bakePegs(scene); + if (!scene.textures.exists('crib-dial')) bakeDial(scene); + if (!scene.textures.exists('crib-beam')) bakeBeam(scene); + return bakeRoom(scene, 'crib-room', T, { wall, front, rim, top: oakTop, onTop: marks, after: oilLamp }); +} + +export { W, H }; diff --git a/src/games/cribbage/CribbageBoard.js b/src/games/cribbage/CribbageBoard.js new file mode 100644 index 0000000..22f6835 --- /dev/null +++ b/src/games/cribbage/CribbageBoard.js @@ -0,0 +1,207 @@ +// Cribbage board — the baked walnut board plus the four live pegs (and the +// game pegs in match play). +// +// A score moves the BACK peg: it lifts out of its hole, hops over the front +// peg, walks hole by hole to its new place (each hole it counts glows and +// ticks) and drops in with a wooden "tock". Moves queue so a quick run of +// scores plays out in order; snap() jumps straight to a state (resume, new +// game). + +import { playSoundEx, SFX } from '../../ui/Sounds.js'; +import { boardGeometry, boardRect, SEAT_COLORS } from './CribbageTable.js'; +import { ensureBoard } from './CribbageArt.js'; + +const PEG_SCALE = 0.5; // texture is baked at 2× +const LIFT = 20; // px (at s = 1) a peg rises when lifted + +export class PegBoard { + /** + * @param scene the Phaser scene + * @param opts { target, match, doubleSkunk, depth, speed: () => number, onLand(seat, score) } + */ + constructor(scene, { target = 121, match = false, doubleSkunk = false, depth = 0, speed = () => 1, onLand = null }) { + this.scene = scene; + this.depth = depth; + this.speed = speed; + this.onLand = onLand; + this.queue = Promise.resolve(); + this.pending = 0; + this.objs = []; + this.rect = boardRect(); + this.build(target, match, doubleSkunk); + } + + build(target, match, doubleSkunk) { + for (const o of this.objs) o.destroy(); + this.objs = []; + this.target = target; + this.match = match; + this.geo = boardGeometry(target); + const b = ensureBoard(this.scene, target, { match, doubleSkunk }); + this.img = this.scene.add.image(b.x, b.y, b.key).setOrigin(0, 0).setDepth(this.depth); + this.objs.push(this.img); + this.pegs = [0, 1].map((seat) => [-1, 0].map((at) => this.makePeg(seat, at))); + this.gamePeg = [0, 1].map((seat) => { + const p = this.makePeg(seat, null, 0.8); + p.img.setVisible(false); p.shadow.setVisible(false); + return p; + }); + this.glows = []; + this.shown = [0, 0]; + } + + makePeg(seat, at, k = 1) { + const shadow = this.scene.add.image(0, 0, 'crib-peg-shadow').setDepth(this.depth + 0.5).setAlpha(0.8); + const img = this.scene.add.image(0, 0, `crib-peg-${seat}`).setOrigin(0.5, 0.94).setDepth(this.depth + 1); + this.objs.push(shadow, img); + const peg = { seat, at, img, shadow, k }; + if (at != null) this.setPeg(peg, this.holeAt(seat, at), 0); + return peg; + } + + holeAt(seat, n) { + return n < 0 ? this.geo.alt[seat] : this.geo.holes[seat][Math.min(n, this.geo.holes[seat].length - 1)]; + } + + /** Place a peg at screen point p, lifted by `lift` (0..1.5). */ + setPeg(peg, p, lift) { + const s = p.s * peg.k; + peg.img.setPosition(p.x, p.y - lift * LIFT * s).setScale(PEG_SCALE * s * (1 + lift * 0.06)); + peg.img.setDepth(this.depth + 1 + p.y * 0.0001 + lift * 0.05); + peg.shadow.setPosition(p.x + 3 * s + lift * 6 * s, p.y + 1.5 * s + lift * 3 * s) + .setScale(0.5 * s * (1 - lift * 0.25), 0.5 * s * (1 - lift * 0.25)) + .setAlpha(0.8 - lift * 0.35); + } + + /** Jump straight to a position (no animation). */ + snap(scores, backs, games = [0, 0]) { + this.queue = Promise.resolve(); + this.pending = 0; + for (let seat = 0; seat < 2; seat++) { + const [a, b] = this.pegs[seat]; + for (const p of [a, b]) this.scene.tweens.killTweensOf(p.img); + a.at = backs[seat]; + b.at = scores[seat]; + if (a.at === b.at) a.at = -1; + this.setPeg(a, this.holeAt(seat, a.at), 0); + this.setPeg(b, this.holeAt(seat, b.at), 0); + this.shown[seat] = scores[seat]; + } + this.setGames(games); + } + + setGames(games) { + for (let seat = 0; seat < 2; seat++) { + const g = this.gamePeg[seat]; + const n = Math.min(games[seat] ?? 0, this.geo.gameHoles[seat].length); + const on = this.match && n > 0; + g.img.setVisible(on); g.shadow.setVisible(on); + if (on) this.setPeg(g, this.geo.gameHoles[seat][n - 1], 0); + } + } + + /** Front peg's screen point for a seat (for float texts). */ + frontPoint(seat) { + return this.holeAt(seat, this.shown[seat]); + } + + /** Queue a scoring move: the peg that isn't at `from` moves to `to`. */ + move(seat, from, to) { + this.pending++; + const run = () => this.animate(seat, from, to).finally(() => { this.pending--; }); + this.queue = this.queue.then(run, run); + return this.queue; + } + + /** Resolves once every queued move has landed. */ + idle() { return this.queue; } + + animate(seat, from, to) { + const scene = this.scene; + const [a, b] = this.pegs[seat]; + const peg = a.at === from && b.at !== from ? b : b.at === from && a.at !== from ? a : (a.at < b.at ? a : b); + const sp = Math.max(0.2, this.speed()); + if (!scene.sys.isActive()) return Promise.resolve(); + const start = this.holeAt(seat, peg.at); + const over = this.holeAt(seat, Math.max(0, from)); + const steps = Math.max(1, to - Math.max(0, from)); + const hopMs = 170 * sp, walkMs = Math.min(1150, 90 + steps * 40) * sp, dropMs = 120 * sp; + return new Promise((resolve) => { + const st = { t: 0 }; + const done = () => { + peg.at = to; + this.setPeg(peg, this.holeAt(seat, to), 0); + this.shown[seat] = to; + playSoundEx(scene, SFX.PIECE_CLICK, { volume: 0.75, rate: 0.85 + Math.random() * 0.1 }); + this.onLand?.(seat, to); + resolve(); + }; + // 1) lift and hop over the front peg + scene.tweens.add({ + targets: st, t: 1, duration: hopMs, ease: 'Sine.easeInOut', + onUpdate: () => { + const t = st.t; + const p = { x: start.x + (over.x - start.x) * t, y: start.y + (over.y - start.y) * t, s: start.s + (over.s - start.s) * t }; + this.setPeg(peg, p, Math.min(1, t * 3) * (1 + Math.sin(Math.PI * t) * 0.5)); + }, + onComplete: () => { + // 2) walk the holes, counting + const w = { t: 0 }; + let lastHole = Math.max(0, from); + scene.tweens.add({ + targets: w, t: 1, duration: walkMs, ease: steps > 6 ? 'Sine.easeInOut' : 'Linear', + onUpdate: () => { + const f = Math.max(0, from) + w.t * steps; + const i = Math.min(to - 1, Math.floor(f)); + const pa = this.holeAt(seat, i), pb = this.holeAt(seat, Math.min(to, i + 1)); + const k = f - i; + this.setPeg(peg, { x: pa.x + (pb.x - pa.x) * k, y: pa.y + (pb.y - pa.y) * k, s: pa.s + (pb.s - pa.s) * k }, 1); + const hole = Math.floor(f + 0.5); + if (hole > lastHole && hole <= to) { + for (let h = lastHole + 1; h <= hole; h++) this.tick(seat, h, steps); + lastHole = hole; + } + }, + onComplete: () => { + // 3) drop in + const end = this.holeAt(seat, to); + const d = { t: 0 }; + scene.tweens.add({ + targets: d, t: 1, duration: dropMs, ease: 'Quad.easeIn', + onUpdate: () => this.setPeg(peg, end, 1 - d.t), + onComplete: done, + }); + }, + }); + }, + }); + }); + } + + /** A counted hole glows briefly (and clicks, for small counts). */ + tick(seat, n, steps) { + const p = this.holeAt(seat, n); + let g = this.glows.find((x) => !x.visible); + if (!g) { + g = this.scene.add.image(0, 0, 'ct-spot').setBlendMode('ADD').setDepth(this.depth + 0.6); + this.objs.push(g); + this.glows.push(g); + } + g.setVisible(true).setPosition(p.x, p.y).setDisplaySize(30 * p.s, 26 * p.s).setTint(SEAT_COLORS[seat]).setAlpha(0.9); + this.scene.tweens.add({ targets: g, alpha: 0, duration: 520, onComplete: () => g.setVisible(false) }); + if (steps <= 12 || n % 2 === 0) playSoundEx(this.scene, SFX.CLICK, { volume: 0.16, rate: 1.5 + (n % 5) * 0.06 }); + } + + /** A soft pulse on a hole (hover hints, the skunk line…). */ + pulse(seat, n, color = 0xffe2a0) { + const p = this.holeAt(seat, n); + const g = this.scene.add.image(p.x, p.y, 'ct-spot').setBlendMode('ADD').setDepth(this.depth + 0.6) + .setDisplaySize(40 * p.s, 34 * p.s).setTint(color).setAlpha(0); + this.scene.tweens.add({ targets: g, alpha: 0.9, duration: 260, yoyo: true, repeat: 1, onComplete: () => g.destroy() }); + } + + destroy() { + for (const o of this.objs) o.destroy(); + this.objs = []; + } +} diff --git a/src/games/cribbage/CribbageData.js b/src/games/cribbage/CribbageData.js index 860a9a3..fdb7880 100644 --- a/src/games/cribbage/CribbageData.js +++ b/src/games/cribbage/CribbageData.js @@ -1,118 +1,254 @@ -// Cribbage — static data, scoring helpers and board geometry. No Phaser, no -// state: imported by the logic engine, the AI, the Phaser scene and the -// headless verify harness alike. - -import { Card, Deck } from '../cards/Deck.js'; - -export { Card, Deck }; +// Cribbage — cards, rules constants and scoring. Pure (no Phaser, no state): +// shared by the engine, the AI, the scene and tools/verifyCribbage.js. +// +// Cards are plain JSON so a whole game can be autosaved: +// { id: 'Td', rank: 'T', suit: 'd', run: 10, val: 10 } +// run = rank order for runs (A = 1 … K = 13, ace low only) +// val = pip value for fifteens and the count (A = 1, faces = 10) +// Ids match the shared casino deck frames ('As', 'Td', …). export const ICON_FRAME = 64; -// ── Rules (standard 2-player, race to 121, muggins off) ───────────────────── -export const WIN_SCORE = 121; -export const HAND_SIZE = 6; // cards dealt to each player -export const KEEP = 4; // cards kept after discarding to the crib -export const CRIB = 2; // cards each player lays away to the crib -export const PLAY_LIMIT = 31; // running-count ceiling during the play +export const HAND_SIZE = 6; // dealt to each player +export const KEEP = 4; // kept after laying two away +export const PLAY_LIMIT = 31; // the running count never passes 31 -// ── Card value helpers ────────────────────────────────────────────────────── -/** Pip value used for fifteens and the running count: A=1, face=10, else rank. */ -export function cribValue(card) { - if (card.rank === 'A') return 1; - return Math.min(10, card.value); -} - -/** Rank order for runs: ace is always low (A=1 … K=13), no wrap-around. */ -export function runRank(card) { - return card.rank === 'A' ? 1 : card.value; // value: T=10,J=11,Q=12,K=13 -} - -// ── Theme (carved-wood board, brass accents) ──────────────────────────────── -export const THEME = { - feltTop: 0x14241b, // dark green baize backdrop - feltBottom: 0x0a160f, - woodLight: 0xb5803f, // maple highlight - woodMid: 0x8a5a2b, // walnut field - woodDark: 0x5a3618, // grain shadow - woodEdge: 0x3a2412, // bevelled rim - grain: 0x70451f, // grain streak - holeDark: 0x241405, // drilled hole shadow - holeRim: 0xc99a55, // lit rim around a hole - inlay: 0xd9b779, // five-hole grouping inlay - brass: 0xc9a227, - brassHi: 0xf0d77a, - pegHuman: 0xc0392b, // crimson pegs (you) - pegHumanHi: 0xf07a6d, - pegAi: 0xe9e1cf, // ivory pegs (opponent) - pegAiHi: 0xffffff, - cardFace: 0xfbf6e7, - cardBack: 0x6b3f1c, - gold: 0xd4a017, - text: 0xf2ead8, +export const SUITS = ['s', 'h', 'd', 'c']; +export const RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']; +export const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣' }; +export const SUIT_NAME = { s: 'spades', h: 'hearts', d: 'diamonds', c: 'clubs' }; +export const RANK_WORD = { + A: 'ace', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', + T: 'ten', J: 'jack', Q: 'queen', K: 'king', }; -// ── Board geometry ────────────────────────────────────────────────────────── -// A traditional 3-street S-curve track. Each player owns one continuous track -// of 120 numbered holes laid out as three "streets" (rows), grouped in fives, -// plus a start hole (index 0) and a final game hole (index 121). The two -// players' tracks run as paired sub-rows inside each street so the colours sit -// side by side, exactly like a physical board. -const STREETS = 3; -const HOLES_PER_STREET = 40; // per player, per street (3 × 40 = 120) -const GROUP = 5; // holes per inlaid grouping +/** + * Rules. Standard: 121 points, auto-counted (no muggins), skunk under 91. + * target 121 | 61 (once around the short board) + * bestOf 1 | 3 | 5 | 7 — match play; a skunk counts two games + * doubleSkunk loser under 61 (121 game) counts three games and gets a stamp + */ +export const DEFAULT_RULES = { target: 121, bestOf: 1, doubleSkunk: false }; + +/** The skunk line (loser below it is skunked) and the double-skunk line, or null. */ +export function skunkLines(rules) { + if (rules.target === 61) return { skunk: 31, double: null }; + return { skunk: 91, double: rules.doubleSkunk ? 61 : null }; +} + +/** Game points needed to win a match of `bestOf`. */ +export const gamesNeeded = (bestOf) => Math.floor((bestOf ?? 1) / 2) + 1; + +// ── Cards ──────────────────────────────────────────────────────────────────── +export function makeCard(rank, suit) { + const run = RANKS.indexOf(rank) + 1; + return { id: `${rank}${suit}`, rank, suit, run, val: Math.min(10, run) }; +} + +export function fullDeck() { + const out = []; + for (const s of SUITS) for (const r of RANKS) out.push(makeCard(r, s)); + return out; +} + +export const cardFromId = (id) => makeCard(id.slice(0, -1), id.slice(-1)); +export const rankLabel = (c) => (c.rank === 'T' ? '10' : c.rank); +export const cardName = (c) => (c ? `${rankLabel(c)}${SUIT_SYM[c.suit]}` : ''); +export const isRed = (c) => c.suit === 'h' || c.suit === 'd'; + +/** Pip value used for fifteens and the running count. */ +export const cribValue = (c) => c.val; +/** Rank order for runs (ace low, no wrap). */ +export const runRank = (c) => c.run; + +const SUIT_ORDER = { s: 0, h: 1, c: 2, d: 3 }; +export const byRank = (a, b) => a.run - b.run || SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit]; + +// ── Hand scoring ───────────────────────────────────────────────────────────── +function fifteenCount(cards) { + let count = 0; + const n = cards.length; + for (let mask = 1; mask < (1 << n); mask++) { + let sum = 0; + for (let k = 0; k < n; k++) if (mask & (1 << k)) sum += cards[k].val; + if (sum === 15) count++; + } + return count; +} + +function pairPoints(cards) { + let pts = 0; + for (let a = 0; a < cards.length; a++) + for (let b = a + 1; b < cards.length; b++) + if (cards[a].rank === cards[b].rank) pts += 2; + return pts; +} + +function runPoints(cards) { + const cnt = new Array(15).fill(0); + for (const c of cards) cnt[c.run]++; + let total = 0; + let r = 1; + while (r <= 13) { + if (!cnt[r]) { r++; continue; } + let len = 0, mult = 1; + while (r <= 13 && cnt[r]) { len++; mult *= cnt[r]; r++; } + if (len >= 3) total += len * mult; + } + return total; +} + +function flushPoints(hand4, starter, isCrib) { + const s0 = hand4[0].suit; + if (!hand4.every((c) => c.suit === s0)) return 0; + if (starter && starter.suit === s0) return 5; + return isCrib ? 0 : 4; // a four-card flush never counts in the crib +} + +function nobsPoints(hand4, starter) { + if (!starter) return 0; + return hand4.some((c) => c.rank === 'J' && c.suit === starter.suit) ? 1 : 0; +} /** - * Build hole coordinates for both players inside a board rectangle. - * Returns: - * tracks: [p0[], p1[]] each an array of {x,y} for indices 0..121 - * holes: [{x,y}, ...] every drilled hole (both players, all indices) for rendering - * groupGaps, holeR, etc. handy render metrics + * Score a four-card hand (or the crib) with the starter (starter may be null + * for a "static" count before the cut). + * @returns {{ total, fifteens, pairs, runs, flush, nobs }} */ -export function buildBoardLayout(rect) { - const { x, y, w, h } = rect; - const padX = w * 0.045; - const usableW = w - padX * 2; - - // Hole-to-hole spacing, with an extra gap inserted every GROUP holes. - // width = (N-1)*s + (groups-1)*gap , gap = 0.6*s - const groups = HOLES_PER_STREET / GROUP; // 8 - const s = usableW / ((HOLES_PER_STREET - 1) + (groups - 1) * 0.6); - const groupGap = 0.6 * s; - const holeR = Math.max(5, s * 0.26); - - // x for the i-th hole (0-based 0..39) within a street, measured left edge. - const colX = (i) => x + padX + i * s + Math.floor(i / GROUP) * groupGap; - - // Vertical bands: one street per band, two player sub-rows inside each band. - const bandH = h / STREETS; - const subY = (street, player) => { - const top = y + street * bandH; - return top + bandH * (player === 0 ? 0.34 : 0.66); - }; - - // For track index n (1..120): which street, and column within (respecting the - // serpentine direction — even streets L→R, odd streets R→L). - const trackPoint = (player, n) => { - const idx = n - 1; - const street = Math.floor(idx / HOLES_PER_STREET); - let within = idx % HOLES_PER_STREET; - if (street % 2 === 1) within = HOLES_PER_STREET - 1 - within; - return { x: colX(within), y: subY(street, player) }; - }; - - const tracks = [[], []]; - for (let p = 0; p < 2; p++) { - // index 0 — start hole, just left of hole 1 on the top street - tracks[p][0] = { x: colX(0) - s * 0.9, y: subY(0, p) }; - for (let n = 1; n <= 120; n++) tracks[p][n] = trackPoint(p, n); - // index 121 — game hole, just past hole 120 at the end of the bottom street - const last = trackPoint(p, 120); - tracks[p][121] = { x: last.x + s * 0.9, y: last.y }; - } - - // Flat list of every drilled hole for the board face. - const holes = []; - for (let p = 0; p < 2; p++) for (let n = 0; n <= 121; n++) holes.push(tracks[p][n]); - - return { tracks, holes, holeR, s, groupGap }; +export function scoreHand(hand4, starter, isCrib = false) { + const all = starter ? [...hand4, starter] : hand4; + const fifteens = fifteenCount(all) * 2; + const pairs = pairPoints(all); + const runs = runPoints(all); + const flush = hand4.length === 4 ? flushPoints(hand4, starter, isCrib) : 0; + const nobs = nobsPoints(hand4, starter); + return { total: fifteens + pairs + runs + flush + nobs, fifteens, pairs, runs, flush, nobs }; +} + +const NUM_WORD = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']; + +/** + * The hand counted out loud, one call per scoring combination, in the order a + * player says them: fifteens, pairs (grouped by rank), runs, flush, nobs. + * combos: [{ kind, ids, pts, running, say }] + * The total always equals scoreHand(...).total. + */ +export function scoreHandDetailed(hand4, starter, isCrib = false) { + const all = starter ? [...hand4, starter] : hand4.slice(); + const combos = []; + let running = 0; + const push = (kind, cards, pts, say) => { + running += pts; + combos.push({ kind, ids: cards.map((c) => c.id), pts, running, say }); + }; + // fifteens + const n = all.length; + for (let mask = 1; mask < (1 << n); mask++) { + let sum = 0; + const pick = []; + for (let k = 0; k < n; k++) if (mask & (1 << k)) { sum += all[k].val; pick.push(all[k]); } + if (sum === 15) push('fifteen', pick, 2, null); + } + // pairs, grouped by rank: a pair (2) · pair royal (6) · double pair royal (12) + const byR = new Map(); + for (const c of all) byR.set(c.rank, [...(byR.get(c.rank) ?? []), c]); + for (const [, cs] of [...byR].sort((a, b) => a[1][0].run - b[1][0].run)) { + if (cs.length < 2) continue; + const pts = cs.length * (cs.length - 1); + const kind = cs.length === 2 ? 'pair' : cs.length === 3 ? 'pairRoyal' : 'doublePairRoyal'; + push(kind, cs, pts, null); + } + // runs: every distinct run in the longest consecutive stretch of ranks + const ranks = [...new Set(all.map((c) => c.run))].sort((a, b) => a - b); + let i = 0; + while (i < ranks.length) { + let j = i; + while (j + 1 < ranks.length && ranks[j + 1] === ranks[j] + 1) j++; + const len = j - i + 1; + if (len >= 3) { + const groups = ranks.slice(i, j + 1).map((r) => all.filter((c) => c.run === r)); + const runs = [[]]; + for (const g of groups) { + const next = []; + for (const partial of runs) for (const c of g) next.push([...partial, c]); + runs.splice(0, runs.length, ...next); + } + runs.forEach((cards) => push('run', cards, len, null)); + } + i = j + 1; + } + // flush + const fl = hand4.length === 4 ? flushPoints(hand4, starter, isCrib) : 0; + if (fl) push('flush', fl === 5 ? [...hand4, starter] : hand4, fl, null); + // nobs + if (nobsPoints(hand4, starter)) { + const jack = hand4.find((c) => c.rank === 'J' && c.suit === starter.suit); + push('nobs', [jack, starter], 1, null); + } + // the words + let fifteens = 0, runsSeen = 0; + for (const c of combos) { + if (c.kind === 'fifteen') { fifteens++; c.say = `fifteen ${c.running}`; } + else if (c.kind === 'pair') c.say = `a pair is ${c.running}`; + else if (c.kind === 'pairRoyal') c.say = `pair royal, ${c.running}`; + else if (c.kind === 'doublePairRoyal') c.say = `double pair royal, ${c.running}`; + else if (c.kind === 'run') { + c.say = `${runsSeen ? 'another' : 'a'} run of ${NUM_WORD[c.pts] ?? c.pts}, ${c.running}`; + runsSeen++; + } else if (c.kind === 'flush') c.say = `a ${c.pts}-card flush, ${c.running}`; + else if (c.kind === 'nobs') c.say = `and one for his nobs, ${c.running}`; + } + if (combos.length && combos[0].kind === 'nobs') combos[0].say = combos[0].say.replace(/^and /, ''); + // "Fifteen two, fifteen four, a pair is six" — capitalise the opener + if (combos.length) combos[0].say = combos[0].say[0].toUpperCase() + combos[0].say.slice(1); + return { total: running, combos, fifteens }; +} + +// ── Pegging ────────────────────────────────────────────────────────────────── +/** + * Score the card just laid on the pile (the cards since the last reset). + * @returns {{ points, reasons: string[], count, scoreIds: string[] }} + * scoreIds: the cards that made the points (for highlighting) + */ +export function scorePlay(pile) { + const reasons = []; + let points = 0; + const count = pile.reduce((s, c) => s + c.val, 0); + const hi = new Set(); + if (count === 15) { points += 2; reasons.push('15'); pile.forEach((c) => hi.add(c.id)); } + if (count === 31) { points += 2; reasons.push('31'); pile.forEach((c) => hi.add(c.id)); } + // pairs: trailing cards of the same rank + const last = pile[pile.length - 1]; + let k = 1; + for (let i = pile.length - 2; i >= 0 && pile[i].rank === last.rank; i--) k++; + if (k >= 2) { + points += k * (k - 1); + reasons.push(k === 2 ? 'pair' : k === 3 ? 'pairRoyal' : 'doublePairRoyal'); + pile.slice(-k).forEach((c) => hi.add(c.id)); + } + // runs: the longest tail of the pile that is a run in any order + for (let len = pile.length; len >= 3; len--) { + const tail = pile.slice(pile.length - len); + const rr = tail.map((c) => c.run).sort((a, b) => a - b); + let ok = true; + for (let i = 1; i < rr.length; i++) if (rr[i] !== rr[i - 1] + 1) { ok = false; break; } + if (ok) { points += len; reasons.push(`run${len}`); tail.forEach((c) => hi.add(c.id)); break; } + } + return { points, reasons, count, scoreIds: [...hi] }; +} + +/** Short words for pegging reasons ("Fifteen", "Pair royal", "Run of 4"…). */ +export function reasonWords(reasons) { + return (reasons ?? []).map((r) => { + if (r === '15') return 'fifteen'; + if (r === '31') return 'thirty-one'; + if (r === 'pair') return 'a pair'; + if (r === 'pairRoyal') return 'pair royal'; + if (r === 'doublePairRoyal') return 'double pair royal'; + if (r.startsWith('run')) return `run of ${r.slice(3)}`; + if (r === 'go') return 'go'; + if (r === 'last') return 'last card'; + if (r === 'heels') return 'his heels'; + return r; + }).join(' + '); } diff --git a/src/games/cribbage/CribbageDialogs.js b/src/games/cribbage/CribbageDialogs.js new file mode 100644 index 0000000..f006900 --- /dev/null +++ b/src/games/cribbage/CribbageDialogs.js @@ -0,0 +1,115 @@ +// Cribbage dialogs — How to play, Settings, and your lifetime record. Each +// takes the scene (a CardTableScene) and builds its modal with the kit. + +import { COLORS } from '../../config.js'; +import { DEPTH as D, CX, CY } from '../../ui/cardtable/CardTableScene.js'; +import { DEFAULT_RULES, skunkLines, gamesNeeded, cardFromId, cardName } from './CribbageData.js'; + +export const STATS_KEY = 'cribbage-stats'; + +const emptyLifetime = () => ({ + games: 0, wins: 0, skunksGiven: 0, skunksTaken: 0, matches: 0, matchWins: 0, + deals: 0, hands: 0, handPts: 0, cribs: 0, cribPts: 0, pegPts: 0, + best: 0, bestIds: null, bestDate: null, twentyNines: 0, nineteens: 0, +}); + +export function loadLifetime() { + try { return { ...emptyLifetime(), ...JSON.parse(localStorage.getItem(STATS_KEY) || '{}') }; } catch (_) { return emptyLifetime(); } +} + +/** Fold a finished game (your seat 0) into the lifetime record. */ +export function recordLifetime(gs) { + const L = loadLifetime(); + const prevBest = L.best; + const st = gs.stats[0]; + const won = gs.winner === 0; + const skunk = gs.gameResult?.skunk ?? 0; + L.games++; + if (won) L.wins++; + if (skunk && won) L.skunksGiven++; + if (skunk && !won) L.skunksTaken++; + if (gs.matchWinner != null && gs.rules.bestOf > 1) { L.matches++; if (gs.matchWinner === 0) L.matchWins++; } + L.deals += gs.history.length; + L.hands += st.hands; + L.handPts += st.hand; + L.cribs += st.cribs; + L.cribPts += st.crib; + L.pegPts += st.peg; + L.twentyNines += st.twentyNines; + L.nineteens += st.nineteens; + if (st.best > L.best) { L.best = st.best; L.bestIds = st.bestIds; L.bestDate = new Date().toISOString().slice(0, 10); } + try { localStorage.setItem(STATS_KEY, JSON.stringify(L)); } catch (_) { /* private mode */ } + return { lifetime: L, newBest: st.best > prevBest && st.best > 0 }; +} + +const avg = (pts, n) => (n ? (pts / n).toFixed(1) : '–'); + +export function openRules(scene) { + const h = 790; + scene.openModal({ w: 1060, h, onEscape: () => scene.closeModal() }); + const top = CY - h / 2; + scene.modalText(CX, top + 48, 'How to play Cribbage', { fontFamily: 'Righteous', fontSize: '36px', color: COLORS.goldHex }); + const r = scene.gs?.rules ?? { ...DEFAULT_RULES, ...scene.settings.rules }; + const sk = skunkLines(r); + const lines = [ + ['Goal', `First to peg ${r.target} wins.${r.bestOf > 1 ? ` Match: first to ${gamesNeeded(r.bestOf)} games (best of ${r.bestOf}).` : ''}`], + ['The deal', 'Six cards each. Lay two away to the crib — the dealer\'s extra hand. The deal alternates.'], + ['The cut', 'The pone cuts and the top card is turned: the starter, shared by every hand. A jack? "His heels" — 2 to the dealer.'], + ['The play', 'Take turns laying a card and calling the running count. It can never pass 31.'], + ['Pegging', '15 or 31: 2 · a pair: 2 · three of a kind: 6 · four: 12 · a run of 3+ (any order): 1 a card.'], + ['Go', 'Can\'t play without passing 31? Say "Go". The other player plays on; the last card before the reset pegs 1.'], + ['Last card', 'The very last card of the play pegs 1 (or 2 if it makes 31).'], + ['The show', 'Pone counts first, then the dealer, then the dealer\'s crib — each with the starter.'], + ['Counting', 'Fifteens 2 each · pairs 2 · runs 1 a card (double runs count twice) · a jack of the starter\'s suit: "nobs", 1.'], + ['Flush', 'Four in hand of one suit: 4 (5 with the starter). The crib needs all five.'], + ['Skunk', `Win before your opponent passes ${sk.skunk - 1}: a skunk${r.bestOf > 1 ? ' (2 games)' : ''}.${sk.double ? ` Before ${sk.double - 1}: a double skunk${r.bestOf > 1 ? ' (3 games)' : ''}.` : ''}`], + ['Pegs', 'Two pegs each: the back peg leapfrogs the front one, so you can see what you just scored.'], + ]; + lines.forEach(([k, v], i) => { + const y = top + 112 + i * 50; + scene.addToModal(scene.add.text(CX - 470, y, k, { fontFamily: 'Righteous', fontSize: '19px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + scene.addToModal(scene.add.text(CX - 320, y, v, { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, wordWrap: { width: 780 } }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + }); + scene.modalButton(CX, top + h - 44, 'Back to the table', () => scene.closeModal(), { width: 280, height: 46, fontSize: 18 }); +} + +export function openSettings(scene, onDone = null) { + const s = scene.settings; + const R = s.rules; + scene.openSettingsModal([ + { label: 'Murph\'s pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } }, + { label: 'Counting the show', options: [['slow', 'Slow'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.countSpeed, set: (v) => { s.countSpeed = v; } }, + { label: 'Coach (lay-away odds · ★ best card · previews)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; scene.refreshAll?.(); } }, + { label: 'Deal the next hand automatically', options: [[false, 'Off'], [true, 'On']], get: () => s.autoNext, set: (v) => { s.autoNext = v; } }, + { label: 'Game length', options: [[121, '121'], [61, '61']], get: () => R.target, set: (v) => { R.target = v; } }, + { label: 'Match play', options: [[1, 'Single'], [3, 'Best of 3'], [5, 'Best of 5'], [7, 'Best of 7']], get: () => R.bestOf, set: (v) => { R.bestOf = v; } }, + { label: 'Double skunk (loser under 61)', options: [[false, 'Off'], [true, 'On']], get: () => R.doubleSkunk, set: (v) => { R.doubleSkunk = v; } }, + ], { note: 'Game length, match play and skunk rules start with the next game (Menu → New game).', onDone }); +} + +export function openLifetime(scene, onBack = null) { + const L = loadLifetime(); + const h = 560; + const back = () => { scene.closeModal(); onBack?.(); }; + scene.openModal({ w: 900, h, onEscape: back }); + const top = CY - h / 2; + scene.modalText(CX, top + 48, 'Your record at Murph\'s table', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.goldHex }); + const best = L.bestIds ? L.bestIds.map((id) => cardName(cardFromId(id))).join(' ') : ''; + const rows = [ + ['Games', L.games ? `${L.wins} won of ${L.games} (${Math.round((L.wins / L.games) * 100)}%)` : 'none yet'], + ['Matches', L.matches ? `${L.matchWins} won of ${L.matches}` : '—'], + ['Skunks', `${L.skunksGiven} given · ${L.skunksTaken} taken`], + ['Average hand', avg(L.handPts, L.hands)], + ['Average crib', avg(L.cribPts, L.cribs)], + ['Pegging a deal', avg(L.pegPts, L.deals)], + ['Best hand', L.best ? `${L.best}${best ? ` (${best})` : ''}` : '—'], + ['29 hands', `${L.twentyNines}${L.twentyNines ? ' — a perfect hand!' : ' — the one everyone waits for'}`], + ['"Nineteens"', `${L.nineteens} hands that counted nothing`], + ]; + rows.forEach(([k, v], i) => { + const y = top + 112 + i * 40; + scene.addToModal(scene.add.text(CX - 360, y, k, { fontFamily: 'Righteous', fontSize: '19px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + scene.addToModal(scene.add.text(CX - 130, y, v, { fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + }); + scene.modalButton(CX, top + h - 44, 'Back', back, { width: 220, height: 46, fontSize: 18 }); +} diff --git a/src/games/cribbage/CribbageEndScreen.js b/src/games/cribbage/CribbageEndScreen.js new file mode 100644 index 0000000..fc44a43 --- /dev/null +++ b/src/games/cribbage/CribbageEndScreen.js @@ -0,0 +1,124 @@ +// Cribbage — the end-of-game card: who won (and any skunk), the score race +// deal by deal, where the points came from, the match tally and your record. + +import { COLORS } from '../../config.js'; +import { DEPTH as D, CX, CY } from '../../ui/cardtable/CardTableScene.js'; +import { skunkLines, gamesNeeded, cardFromId, cardName } from './CribbageData.js'; +import { SEAT_COLORS, SEAT_HEX } from './CribbageTable.js'; + +/** + * buttons: [{ label, act, hot?, ghost? }] + * note: { newBest, lifetime } from recordLifetime() + */ +export function openEndScreen(scene, { gs, names, buttons, note = null }) { + const w = 1220, h = 820; + // not frozen: the skunk stamp animates in (a frozen modal pauses every tween) + scene.openModal({ w, h, onEscape: null, freeze: false }); + const top = CY - h / 2, left = CX - w / 2; + const won = gs.winner === 0; + const res = gs.gameResult; + const matchOver = gs.matchWinner != null; + const inMatch = gs.rules.bestOf > 1; + let head; + if (inMatch && matchOver) head = gs.matchWinner === 0 ? 'You win the match!' : `${names[1]} wins the match`; + else head = won ? 'You win!' : `${names[1]} wins`; + scene.modalText(CX, top + 52, head, { fontFamily: 'Righteous', fontSize: '50px', color: won ? '#f0d77a' : COLORS.textHex }); + const skunkWord = res.skunk === 2 ? 'DOUBLE SKUNK!' : res.skunk === 1 ? 'SKUNK!' : ''; + scene.modalText(CX, top + 108, `${gs.scores[0]} – ${gs.scores[1]}${inMatch ? ` Game ${gs.gameNo}` : ''}`, { + fontFamily: 'Righteous', fontSize: '30px', color: COLORS.textHex, + }); + if (skunkWord) { + const st = scene.modalText(CX + 330, top + 70, skunkWord, { + fontFamily: 'Righteous', fontSize: '40px', color: '#ff6b4a', stroke: '#2a0c04', strokeThickness: 6, + }).setRotation(-0.12).setScale(2).setAlpha(0); + scene.tweens.add({ targets: st, scale: 1, alpha: 1, delay: 300, duration: 260, ease: 'Back.easeOut' }); + } + + // ── the score race ── + const gx = left + 70, gy = top + 170, gw = 560, gh = 300; + const g = scene.addToModal(scene.add.graphics().setDepth(D.modal + 1)); + g.fillStyle(0x0c0806, 0.55); + g.fillRoundedRect(gx - 12, gy - 12, gw + 24, gh + 40, 10); + const target = gs.rules.target; + const pts = [[0, 0], ...gs.history.map((hh) => hh.after)]; + const n = Math.max(1, pts.length - 1); + const X = (i) => gx + (i / n) * gw; + const Y = (v) => gy + gh - (v / target) * gh; + g.lineStyle(1, 0x9e9080, 0.25); + for (let v = 0; v <= target; v += target === 61 ? 10 : 20) g.lineBetween(gx, Y(v), gx + gw, Y(v)); + const sk = skunkLines(gs.rules); + const dash = (v, color, label) => { + for (let x = gx; x < gx + gw; x += 14) { g.lineStyle(2, color, 0.8); g.lineBetween(x, Y(v), Math.min(gx + gw, x + 7), Y(v)); } + scene.addToModal(scene.add.text(gx + gw + 6, Y(v), label, { fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#c9b08a' }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + }; + dash(sk.skunk - 1, 0xd9b45a, 'skunk'); + if (sk.double) dash(sk.double - 1, 0xb86a3a, 'double'); + g.lineStyle(2, 0xf0d77a, 0.9); + g.lineBetween(gx, Y(target), gx + gw, Y(target)); + scene.addToModal(scene.add.text(gx + gw + 6, Y(target), String(target), { fontFamily: 'Righteous', fontSize: '14px', color: '#f0d77a' }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + for (let seat = 1; seat >= 0; seat--) { + g.lineStyle(4, SEAT_COLORS[seat], 1); + g.beginPath(); + pts.forEach((p, i) => (i ? g.lineTo(X(i), Y(p[seat])) : g.moveTo(X(i), Y(p[seat])))); + g.strokePath(); + g.fillStyle(SEAT_COLORS[seat], 1); + pts.forEach((p, i) => g.fillCircle(X(i), Y(p[seat]), i === pts.length - 1 ? 6 : 3.5)); + } + scene.addToModal(scene.add.text(gx, gy + gh + 16, `the race, deal by deal (${pts.length - 1} deal${pts.length === 2 ? '' : 's'})`, { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + + // ── where the points came from ── + const tx = left + 720, ty = top + 170; + const cols = [tx + 170, tx + 330]; + [0, 1].forEach((seat) => scene.modalText(cols[seat], ty, names[seat], { fontFamily: 'Righteous', fontSize: '22px', color: SEAT_HEX[seat] })); + const st = gs.stats; + const best = (s) => (st[s].best ? `${st[s].best}` : '–'); + const rows = [ + ['Pegging', (s) => st[s].peg], + ['Hands', (s) => st[s].hand], + ['Cribs', (s) => st[s].crib], + ['His heels', (s) => st[s].heels], + ['Best hand', best], + ['Avg hand', (s) => (st[s].hands ? (st[s].hand / st[s].hands).toFixed(1) : '–')], + ['Gos called', (s) => st[s].gos], + ]; + rows.forEach(([k, fn], i) => { + const y = ty + 44 + i * 38; + scene.addToModal(scene.add.text(tx, y, k, { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + [0, 1].forEach((seat) => scene.modalText(cols[seat], y, String(fn(seat)), { fontFamily: 'Righteous', fontSize: '22px', color: COLORS.textHex })); + }); + const bestSeat = st[0].best >= st[1].best ? 0 : 1; + if (st[bestSeat].bestIds) { + const cards = st[bestSeat].bestIds.map((id) => cardName(cardFromId(id))).join(' '); + scene.modalText(tx + 220, ty + 44 + rows.length * 38 + 8, `Hand of the game: ${cards} — ${st[bestSeat].best} (${bestSeat === 0 ? 'you' : names[1]})`, { + fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#f0d77a', align: 'center', wordWrap: { width: 460 }, + }); + } + + // ── match tally and your record ── + let y = top + 560; + if (inMatch) { + const need = gamesNeeded(gs.rules.bestOf); + const list = gs.pastGames.map((pg) => `G${pg.gameNo}: ${pg.winner === 0 ? 'you' : names[1]}${pg.skunk ? (pg.skunk === 2 ? ' (double skunk)' : ' (skunk)') : ''}`).join(' · '); + scene.modalText(CX, y, `Match (best of ${gs.rules.bestOf}, first to ${need}): You ${gs.games[0]} – ${gs.games[1]} ${names[1]}`, { + fontFamily: 'Righteous', fontSize: '24px', color: '#f0d77a', + }); + scene.modalText(CX, y + 34, list, { fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex }); + y += 76; + } + if (note?.lifetime) { + const L = note.lifetime; + const line = `Your record: ${L.wins} of ${L.games} games · best hand ${L.best}${note.newBest ? ' (NEW!)' : ''} · 29s: ${L.twentyNines}`; + scene.modalText(CX, y + 6, line, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: note.newBest ? '#8ce99a' : COLORS.mutedHex }); + } + + const nb = buttons.length; + buttons.forEach((b, i) => { + const x = CX + (i - (nb - 1) / 2) * 250; + const opts = b.ghost ? { variant: 'ghost' } : b.hot ? { bg: COLORS.accent, textColor: COLORS.textDarkHex } : {}; + scene.modalButton(x, top + h - 52, b.label, b.act, { width: 230, ...opts }); + }); + const hot = buttons.find((b) => b.hot); + if (hot) scene.modal.onEnter = hot.act; +} diff --git a/src/games/cribbage/CribbageGame.js b/src/games/cribbage/CribbageGame.js index 4a65e73..d9fe222 100644 --- a/src/games/cribbage/CribbageGame.js +++ b/src/games/cribbage/CribbageGame.js @@ -1,658 +1,1404 @@ import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { api } from '../../services/api.js'; -import { THEME, buildBoardLayout } from './CribbageData.js'; -import { CribbageLogic, scoreHand } from './CribbageLogic.js'; -import { chooseDiscard, choosePlay, thinkDelay } from './CribbageAI.js'; +import { + CardTableScene, DEPTH as D, CX, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { jitterFor } from '../../ui/casino/CasinoCards.js'; +import { CARD_W, CARD_H, inPose, PLATE, stackLift } from '../../ui/cardtable/TableGeometry.js'; +import { + DEFAULT_RULES, byRank, cardName, cardFromId, fullDeck, reasonWords, skunkLines, gamesNeeded, PLAY_LIMIT, +} from './CribbageData.js'; +import * as G from './CribbageLogic.js'; +import { + chooseDiscard, choosePlay, coachDiscard as adviseDiscard, coachPlay as advisePlay, evalPlay, +} from './CribbageAI.js'; +import { + L, SQ, SEAT_COLORS, SEAT_HEX, cribPose, rowPose, prevPose, showPose, handPose, handHome, spotFor, boardRect, +} from './CribbageTable.js'; +import { prepareCribArt, WINDOW, STOVE, LAMP, LIGHTHOUSE, dialAngle } from './CribbageArt.js'; +import { PegBoard } from './CribbageBoard.js'; +import { ShowCaption } from './CribbageShow.js'; +import { openRules, openSettings, openLifetime, recordLifetime } from './CribbageDialogs.js'; +import { openEndScreen } from './CribbageEndScreen.js'; -// ── Layout ────────────────────────────────────────────────────────────────── -const BOARD = { x: 210, y: 44, w: 1500, h: 330 }; +// ─── Cribbage — "The Keeper's Cottage" ──────────────────────────────────────── +// Old Murph's lighthouse-keeper's kitchen on a stormy night, on the shared +// card-table kit (src/ui/cardtable/). Rules live in CribbageLogic.js (pure +// JSON state), the opponent + Coach in CribbageAI.js, the walnut board and +// its pegs in CribbageBoard.js; this file is flow, animation and input. +// Every card is a persistent sprite keyed by its id ('Td', 'As', …). -const CARD_W = 80; -const CARD_H = 112; -const CARD_R = 8; -const HAND_GAP = 14; +const SETTINGS_KEY = 'cribbage-settings'; +const SAVE_KEY = 'cribbage-save-v1'; +const DEFAULTS = { + pace: 'normal', countSpeed: 'normal', hints: true, autoNext: false, + rules: { ...DEFAULT_RULES }, +}; +const COUNT_SPEED = { slow: 1.45, normal: 1, fast: 0.55 }; +const INK = '#f2ead8'; +const MUTED = '#b9a98a'; +const GREEN = '#8ce99a'; +const AMBER = '#ffc861'; +const HOVER_LIFT = 18; -const OPP_HAND_Y = 470; -const PEG_ROW_Y = 628; -const PEG_ROW_X = 470; // left edge of the running play row -const PLAY_GAP = 64; -const PLAYER_HAND_Y = 902; - -const STARTER_X = 1430; -const CRIB_X = 1610; -const CENTER_X = 760; - -const D = { felt: -2, board: 0, holes: 1, inlay: 2, peg: 6, card: 10, cardText: 11, ui: 30, toast: 50, modal: 70, modalUI: 72 }; - -const SUIT_RED = '#c0392b'; -const SUIT_BLK = '#1a1208'; - -export default class CribbageGame extends Phaser.Scene { +export default class CribbageGame extends CardTableScene { constructor() { super('CribbageGame'); } init(data) { - this.gameDef = data.game ?? { slug: 'cribbage', name: 'Cribbage' }; - this.opponents = data.opponents ?? []; - this.aiSkill = this.opponents[0]?.skill ?? 3; - this.aiName = this.opponents[0]?.name ?? 'Opponent'; - - this.logic = new CribbageLogic(); - this.recorded = false; - this.busy = false; - - this.handSprites = [[], []]; // card containers per player - this.pegSprites = []; // cards in the current play row - this.cribSprites = []; - this.starterSprite = null; - this.selected = new Set(); // keys selected for discard - this.pegObjs = [[], []]; // peg game objects per player + this.initTable(data, { settingsKey: SETTINGS_KEY, defaults: DEFAULTS, maxPlayers: 2, minPlayers: 2 }); + this.settings.rules = { ...DEFAULT_RULES, ...(this.settings.rules ?? {}) }; + this.initData = data; + this.backKey = 'crib-back'; + this.gs = null; + this.board = null; + this.boardKey = ''; + this.pending = []; + this.hoverId = null; + this.potentialDrag = null; + this.dragState = null; + this.hintIds = new Set(); + this.ended = false; + this.view = { cutdeal: null, rowHold: false, showing: null, hi: new Set(), skip: false, cutting: null }; + this.holdPromise = null; + this.coachCache = { key: '', discard: null, play: null }; } - create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* optional */ } + faceFrame(card) { return { key: 'casino-cards', frame: card.id }; } - this.buildBackdrop(); - this.buildBoard(); - this.buildHud(); - - this.confirmBtn = new Button(this, CENTER_X, 1018, 'Discard to Crib', () => this.onConfirmDiscard(), - { width: 320, height: 58, fontSize: 24 }).setDepth(D.ui).setVisible(false); - this.nextBtn = new Button(this, CENTER_X, 1018, 'Next Deal', () => this.onNextDeal(), - { width: 280, height: 58, fontSize: 24 }).setDepth(D.ui).setVisible(false); - this.leaveBtn = new Button(this, GAME_WIDTH - 110, 1042, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 160, height: 50, fontSize: 22 }).setDepth(D.ui); - - this.logic.newDeal(); - this.beginDiscard(); + async create() { + this.createTableBase(); + const key = await prepareCribArt(this); + if (!this.alive()) return; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildAmbience(); + this.buildSpot(); + this.slabG = this.add.graphics().setDepth(D.cards - 0.5); + this.cutG = this.add.graphics().setDepth(D.cards + 4); + this.buildDial(); + this.buildPlates(L.plates, SEAT_COLORS, SEAT_HEX, { stampText: 'GO' }); + this.plateG = this.add.graphics().setDepth(D.plates + 2); + this.buildGhostHands([null, handHome()], SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad(), Rules: () => openRules(this), + }, 'Click a card (or 1–6) to lay it away / play it · drag works too · Enter lay away · Space cut / continue / skip\nBackspace take back · H hint · Esc menu'); + this.buildDock(); + const lab = (size, color) => ({ fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, stroke: '#1a0e06', strokeThickness: 4, align: 'center' }); + this.cribLabel = this.add.text(0, 0, '', lab(14, '#e8d8b0')).setOrigin(0.5).setDepth(D.labels); + this.readout = this.add.text(CX, L.readoutY, '', { ...lab(18, INK), lineSpacing: 6 }).setOrigin(0.5).setDepth(D.labels + 2); + this.pendingLabel = this.add.text(1236, 820, 'TO THE CRIB', lab(13, AMBER)).setOrigin(0.5).setDepth(D.labels + 2).setVisible(false); + this.preview = this.add.text(L.dial.x, L.dial.y + 96, '', { ...lab(16, INK), wordWrap: { width: 300 } }).setOrigin(0.5, 0).setDepth(D.labels + 2); + this.caption = new ShowCaption(this, { x: CX, y: L.captionY, depth: D.ui - 2 }); + this.buildTooltips(); + this.setupInput(); + const save = this.readSave(); + if (save) this.offerResume(save); + else this.newMatch(); } - // ── Background & board art ───────────────────────────────────────────────── - buildBackdrop() { - const g = this.add.graphics().setDepth(D.felt); - g.fillGradientStyle(THEME.feltTop, THEME.feltTop, THEME.feltBottom, THEME.feltBottom, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - // vignette ring - g.lineStyle(6, 0x000000, 0.25); - g.strokeRoundedRect(16, 16, GAME_WIDTH - 32, GAME_HEIGHT - 32, 22); - } - - buildBoard() { - const { x, y, w, h } = BOARD; - const g = this.add.graphics().setDepth(D.board); - - // drop shadow - g.fillStyle(0x000000, 0.45); - g.fillRoundedRect(x + 10, y + 14, w, h, 26); - - // bevelled outer frame - g.fillStyle(THEME.woodEdge, 1); - g.fillRoundedRect(x - 8, y - 8, w + 16, h + 16, 28); - - // wood field with a vertical grain gradient - g.fillGradientStyle(THEME.woodLight, THEME.woodLight, THEME.woodDark, THEME.woodDark, 1); - g.fillRoundedRect(x, y, w, h, 22); - - // grain streaks - g.lineStyle(2, THEME.grain, 0.18); - for (let i = 0; i < 26; i++) { - const gy = y + 14 + (i / 26) * (h - 28) + Math.sin(i) * 3; - g.beginPath(); - g.moveTo(x + 12, gy); - for (let sx = x + 12; sx <= x + w - 12; sx += 40) g.lineTo(sx, gy + Math.sin(sx * 0.02 + i) * 2.5); - g.strokePath(); - } - // inner highlight bevel - g.lineStyle(3, THEME.woodLight, 0.35); - g.strokeRoundedRect(x + 5, y + 5, w - 10, h - 10, 18); - - // title plaque - this.add.text(x + w / 2, y + 12, 'CRIBBAGE', { - fontFamily: 'Righteous', fontSize: '22px', color: '#f0d77a', - }).setOrigin(0.5, 0).setDepth(D.inlay).setAlpha(0.85); - - // ── holes ── - this.layout = buildBoardLayout(BOARD); - const { tracks, holeR } = this.layout; - const holes = this.add.graphics().setDepth(D.holes); - const inlay = this.add.graphics().setDepth(D.inlay); - - for (let p = 0; p < 2; p++) { - // five-hole grouping inlays (faint rounded capsules behind each group of 5) - for (let start = 1; start <= 120; start += 5) { - const a = tracks[p][start], b = tracks[p][Math.min(start + 4, 120)]; - inlay.lineStyle(1.5, THEME.inlay, 0.18); - inlay.strokeRoundedRect( - Math.min(a.x, b.x) - holeR - 3, a.y - holeR - 3, - Math.abs(b.x - a.x) + holeR * 2 + 6, holeR * 2 + 6, holeR + 3, - ); - } - for (let n = 0; n <= 121; n++) { - const pt = tracks[p][n]; - // drilled recess - holes.fillStyle(THEME.holeDark, 1); - holes.fillCircle(pt.x, pt.y + 1, holeR); - // lit rim - holes.lineStyle(1.5, THEME.holeRim, n === 121 ? 0.9 : 0.5); - holes.strokeCircle(pt.x, pt.y, holeR); - } - // accent the start (0) and game (121) holes - inlay.lineStyle(2, THEME.brassHi, 0.8); - inlay.strokeCircle(tracks[p][0].x, tracks[p][0].y, holeR + 3); - inlay.strokeCircle(tracks[p][121].x, tracks[p][121].y, holeR + 3); - } - this.add.text(tracks[0][121].x + 6, (tracks[0][121].y + tracks[1][121].y) / 2, '121', { - fontFamily: 'Righteous', fontSize: '18px', color: '#f0d77a', - }).setOrigin(0, 0.5).setDepth(D.inlay); - - // pegs (two per player, start in the start hole) - for (let p = 0; p < 2; p++) { - const col = p === 0 ? THEME.pegHuman : THEME.pegAi; - const hi = p === 0 ? THEME.pegHumanHi : THEME.pegAiHi; - for (let k = 0; k < 2; k++) this.pegObjs[p][k] = this.makePeg(col, hi).setDepth(D.peg); - } - this.placePegs(0, true); - this.placePegs(1, true); - } - - makePeg(color, hi) { - const c = this.add.container(0, 0); - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.35); g.fillEllipse(1, 3, 16, 8); // shadow - g.fillStyle(color, 1); g.fillCircle(0, -2, 7); // head - g.fillStyle(color, 1); g.fillRoundedRect(-3, -4, 6, 10, 3); // stem - g.fillStyle(hi, 0.9); g.fillCircle(-2, -4, 2.4); // highlight - c.add(g); - return c; - } - - placePegs(player, snap = false) { - const { tracks } = this.layout; - const front = this.logic.scores[player]; - const back = this.logic.prev[player]; - const targets = [ - { x: tracks[player][back].x + (back === front ? -5 : 0), y: tracks[player][back].y }, - { x: tracks[player][front].x + (back === front ? 5 : 0), y: tracks[player][front].y }, - ]; - this.pegObjs[player].forEach((peg, i) => { - if (snap) peg.setPosition(targets[i].x, targets[i].y); - else this.tweens.add({ targets: peg, x: targets[i].x, y: targets[i].y, duration: 380, ease: 'Cubic.easeOut' }); - }); - } - - // ── HUD ──────────────────────────────────────────────────────────────────── - buildHud() { - this.add.text(40, OPP_HAND_Y - 70, this.aiName.toUpperCase(), { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui); - this.oppScoreText = this.add.text(40, OPP_HAND_Y - 36, '0', { - fontFamily: 'Righteous', fontSize: '40px', color: '#e9e1cf', - }).setOrigin(0, 0.5).setDepth(D.ui); - this.oppDealer = this.add.text(180, OPP_HAND_Y - 70, '◆ deals', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.goldHex, - }).setOrigin(0, 0.5).setDepth(D.ui); - - this.add.text(40, PLAYER_HAND_Y - 4, 'YOU', { - fontFamily: 'Righteous', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.ui); - this.playerScoreText = this.add.text(40, PLAYER_HAND_Y + 34, '0', { - fontFamily: 'Righteous', fontSize: '40px', color: '#f07a6d', - }).setOrigin(0, 0.5).setDepth(D.ui); - this.playerDealer = this.add.text(150, PLAYER_HAND_Y - 4, '◆ deals', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.goldHex, - }).setOrigin(0, 0.5).setDepth(D.ui); - - this.countText = this.add.text(CENTER_X, PEG_ROW_Y + 96, '', { - fontFamily: 'Righteous', fontSize: '30px', color: '#f0d77a', - }).setOrigin(0.5).setDepth(D.ui); - - this.statusText = this.add.text(CENTER_X, PLAYER_HAND_Y - 100, '', { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - this.add.text(STARTER_X, OPP_HAND_Y - 70, 'STARTER', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.cribLabel = this.add.text(CRIB_X, OPP_HAND_Y - 70, 'CRIB', { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - - this.refreshScores(); - } - - refreshScores() { - this.oppScoreText.setText(String(this.logic.scores[1])); - this.playerScoreText.setText(String(this.logic.scores[0])); - this.oppDealer.setVisible(this.logic.dealer === 1); - this.playerDealer.setVisible(this.logic.dealer === 0); - this.cribLabel.setText(this.logic.dealer === 0 ? 'YOUR CRIB' : 'THEIR CRIB'); - } - - // ── Card rendering ─────────────────────────────────────────────────────── - drawFace(container, card, faceUp) { - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - if (!faceUp) { - g.fillStyle(THEME.cardBack, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(3, THEME.brass, 0.8); g.strokeRoundedRect(x + 5, y + 5, CARD_W - 10, CARD_H - 10, CARD_R - 2); - g.lineStyle(1.5, THEME.brassHi, 0.4); g.strokeRoundedRect(x + 9, y + 9, CARD_W - 18, CARD_H - 18, CARD_R - 3); - container.add(g); - container.add(this.add.text(0, 0, '♣', { fontFamily: 'serif', fontSize: '34px', color: '#f0d77a' }).setOrigin(0.5).setAlpha(0.5)); - return; - } - g.fillStyle(THEME.cardFace, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xcc803a, 0.5); g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - const col = card.isRed ? SUIT_RED : SUIT_BLK; - container.add(this.add.text(x + 8, y + 5, card.label, { fontFamily: 'Righteous', fontSize: '22px', color: col })); - container.add(this.add.text(x + 9, y + 31, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '20px', color: col })); - container.add(this.add.text(0, 5, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '42px', color: col }).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 8, y + CARD_H - 5, card.label, { fontFamily: 'Righteous', fontSize: '22px', color: col }).setOrigin(1, 1)); - } - - makeCard(card, x, y, { faceUp = true } = {}) { - const c = this.add.container(x, y).setDepth(D.card); - c.cardRef = card; - this.drawFace(c, card, faceUp); - return c; - } - - setHandInteractive(container, handler) { - // A Container's displayOrigin is width/2, which Phaser adds during hit-testing, - // so the auto-generated Rectangle(0,0,w,h) lands centered. Passing a manual - // (-w/2,-h/2,w,h) rect double-shifts the hitbox up-left — so don't. - container.setSize(CARD_W, CARD_H); - container.setInteractive({ useHandCursor: true }); - container.on('pointerdown', handler); - } - - handX(count, i) { - const total = count * CARD_W + (count - 1) * HAND_GAP; - return CENTER_X - total / 2 + CARD_W / 2 + i * (CARD_W + HAND_GAP); - } - - // ── Discard phase ────────────────────────────────────────────────────────── - beginDiscard() { - this.clearTable(); - this.selected.clear(); - this.refreshScores(); - this.statusText.setText('Choose two cards to lay away to the ' + (this.logic.dealer === 0 ? 'crib (yours)' : 'crib (theirs)')); - this.countText.setText(''); - playSound(this, SFX.CARD_SHUFFLE); - - // opponent six cards face down - const opp = this.logic.hands[1]; - opp.forEach((card, i) => { - const c = this.makeCard(card, this.handX(6, i), OPP_HAND_Y, { faceUp: false }); - this.handSprites[1].push(c); - }); - // player six cards, selectable - const me = this.logic.hands[0]; - me.forEach((card, i) => { - const c = this.makeCard(card, this.handX(6, i), PLAYER_HAND_Y); - c.baseY = PLAYER_HAND_Y; - this.setHandInteractive(c, () => this.toggleDiscard(c)); - this.handSprites[0].push(c); - }); - - // AI picks its discard now (revealed only at the show) - this.aiDiscard = chooseDiscard(this.logic.hands[1], this.logic.dealer === 1, this.aiSkill); - - this.confirmBtn.setVisible(true); - this.confirmBtn.setAlpha(0.5); - this.nextBtn.setVisible(false); - } - - toggleDiscard(c) { - if (this.busy || this.logic.phase !== 'discard') return; - const key = c.cardRef.key; - if (this.selected.has(key)) { - this.selected.delete(key); - this.tweens.add({ targets: c, y: c.baseY, duration: 120 }); - } else { - if (this.selected.size >= 2) return; - this.selected.add(key); - this.tweens.add({ targets: c, y: c.baseY - 22, duration: 120 }); - } - playSound(this, SFX.PIECE_CLICK); - this.confirmBtn.setAlpha(this.selected.size === 2 ? 1 : 0.5); - } - - async onConfirmDiscard() { - if (this.selected.size !== 2 || this.busy) return; - this.busy = true; - this.confirmBtn.setVisible(false); - - const myDiscards = this.logic.hands[0].filter((c) => this.selected.has(c.key)); - this.logic.discard(0, myDiscards); - this.logic.discard(1, this.aiDiscard); - playSound(this, SFX.CARD_PLACE); - - // animate discards flying to the crib pile, remove kept-card extras - this.animateDiscardsToCrib(); - await this.delay(450); - - // re-layout kept hands (4 cards) - this.relayoutKeptHands(); - await this.delay(200); - this.doCut(); - } - - animateDiscardsToCrib() { - const toCrib = []; - this.handSprites[0] = this.handSprites[0].filter((c) => { - if (this.selected.has(c.cardRef.key)) { toCrib.push(c); return false; } - return true; - }); - // opponent: just drop two face-down sprites toward the crib - const oppGoing = this.handSprites[1].splice(4, 2); - [...toCrib, ...oppGoing].forEach((c, i) => { - c.disableInteractive?.(); - this.cribSprites.push(c); - this.tweens.add({ - targets: c, x: CRIB_X, y: OPP_HAND_Y, angle: (i - 2) * 6, duration: 400, ease: 'Cubic.easeIn', - onComplete: () => { c.setDepth(D.card); }, - }); - }); - } - - relayoutKeptHands() { - this.logic.keep[0].forEach((card, i) => { - const c = this.handSprites[0][i]; - if (!c) return; - c.cardRef = card; - this.tweens.add({ targets: c, x: this.handX(4, i), y: PLAYER_HAND_Y, duration: 250 }); - c.baseY = PLAYER_HAND_Y; - }); - this.handSprites[1].forEach((c, i) => { - // re-key the (still face-down) opponent sprites to the kept cards so the - // pegging phase can locate the right sprite when the AI plays one. - if (this.logic.keep[1][i]) c.cardRef = this.logic.keep[1][i]; - this.tweens.add({ targets: c, x: this.handX(4, i), y: OPP_HAND_Y, duration: 250 }); - }); - } - - // ── Cut ──────────────────────────────────────────────────────────────────── - async doCut() { - const { starter, heels } = this.logic.cut(); - this.starterSprite = this.makeCard(starter, STARTER_X, OPP_HAND_Y, { faceUp: false }); - playSound(this, SFX.CARD_SHOW); - await this.delay(300); - // flip - this.tweens.add({ - targets: this.starterSprite, scaleX: 0, duration: 140, yoyo: true, - onYoyo: () => { this.starterSprite.removeAll(true); this.drawFace(this.starterSprite, starter, true); } - }); - await this.delay(360); - if (heels) { - this.floatScore(this.logic.dealer, 2, 'His Heels!'); - this.placePegs(this.logic.dealer); - this.refreshScores(); - await this.delay(700); - } - if (this.logic.winner !== null) return this.gameOver(); - this.beginPlay(); - } - - // ── The play (pegging) ───────────────────────────────────────────────────── - beginPlay() { - this.busy = false; - this.pegSprites = []; - this.countText.setText('Count: 0'); - this.step(); - } - - async step() { - if (this.logic.winner !== null) return this.gameOver(); - if (this.logic.phase !== 'play') return this.beginShow(); - - const p = this.logic.turn; - const legal = this.logic.legalPlays(p); - - if (legal.length === 0) { - this.statusText.setText(p === 0 ? 'You say “Go”' : `${this.aiName} says “Go”`); - await this.delay(650); - const res = this.logic.go(p); - this.applyEvents(res.events); - if (res.reset) await this.resetPegRow(); - return this.step(); - } - - if (p === 0) { - this.statusText.setText('Your play'); - this.enableHumanPlay(legal); - return; - } - - // AI turn - this.statusText.setText(`${this.aiName} is thinking…`); - await this.delay(thinkDelay(this.aiSkill)); - const card = choosePlay(legal, this.logic.pile, this.logic.count, this.aiSkill); - await this.doPlay(1, card); - return this.step(); - } - - enableHumanPlay(legal) { - const legalKeys = new Set(legal.map((c) => c.key)); - this.handSprites[0].forEach((c) => { - const ok = legalKeys.has(c.cardRef.key); - c.setAlpha(ok ? 1 : 0.4); - c.off('pointerdown'); - if (ok) { - this.setHandInteractive(c, async () => { - if (this.busy) return; - this.busy = true; - this.handSprites[0].forEach((x) => x.off('pointerdown')); - await this.doPlay(0, c.cardRef); - this.busy = false; - this.step(); - }); - } else { - c.disableInteractive?.(); - } - }); - } - - async doPlay(player, card) { - // pull the matching sprite out of the hand - const arr = this.handSprites[player]; - const idx = arr.findIndex((c) => c.cardRef.key === card.key); - let sprite = idx >= 0 ? arr.splice(idx, 1)[0] : this.makeCard(card, CENTER_X, player === 0 ? PLAYER_HAND_Y : OPP_HAND_Y); - if (!sprite.cardRef) sprite.cardRef = card; - // reveal if it was face down (opponent) - if (player === 1) { sprite.removeAll(true); this.drawFace(sprite, card, true); } - - const slot = this.pegSprites.length; - const tx = PEG_ROW_X + slot * PLAY_GAP; - sprite.setDepth(D.card + slot); - this.pegSprites.push(sprite); - playSound(this, SFX.CARD_PLACE); - this.tweens.add({ targets: sprite, x: tx, y: PEG_ROW_Y, angle: 0, alpha: 1, duration: 260, ease: 'Cubic.easeOut' }); - await this.delay(280); - - const res = this.logic.play(player, card); - this.countText.setText(`Count: ${res.count === 0 ? 31 : res.count}`); - this.applyEvents(res.events); - - // a reset means we just hit 31 (or finished) — sweep the row - if (res.count === 0 && !res.ended) await this.resetPegRow(); - else await this.delay(220); - } - - async resetPegRow() { - this.countText.setText('Count: 0'); - const going = this.pegSprites; - this.pegSprites = []; - going.forEach((c) => this.tweens.add({ - targets: c, y: PEG_ROW_Y + 120, alpha: 0, duration: 300, - onComplete: () => c.destroy() - })); - await this.delay(340); - } - - applyEvents(events) { - for (const ev of events || []) { - this.placePegs(ev.player); - this.floatScore(ev.player, ev.points, this.labelFor(ev.reasons)); - playSound(this, SFX.PIECE_CLICK); - } - this.refreshScores(); - } - - labelFor(reasons) { - const map = { - '15': 'Fifteen', '31': 'Thirty-one', pair: 'Pair', 'pair-royal': 'Three!', 'double-pair-royal': 'Four!', - run3: 'Run', run4: 'Run', run5: 'Run', run6: 'Run', run7: 'Run', go: 'Go', 'last-card': 'Last card' + // ── Ambience: stove, lamp, rain on the window, the lighthouse sweeping ───── + buildAmbience() { + const add = (x, y, w, h, tint, alpha, depth = D.spot) => this.add.image(x, y, 'ct-spot').setDisplaySize(w, h) + .setTint(tint).setBlendMode(Phaser.BlendModes.ADD).setAlpha(alpha).setDepth(depth); + const stove = add(STOVE.x, STOVE.y, 560, 680, 0xff8a3a, 0.2, D.table + 0.1); + const lamp = add(LAMP.x, LAMP.y - 88 * LAMP.s, 980, 760, 0xffc070, 0.12); + const flicker = (img, lo, hi) => { + if (!this.alive()) return; + this.tweens.add({ targets: img, alpha: lo + Math.random() * (hi - lo), duration: 220 + Math.random() * 420, ease: 'Sine.easeInOut', onComplete: () => flicker(img, lo, hi) }); }; - return (reasons || []).map((r) => map[r] || r).join(' + '); + flicker(stove, 0.14, 0.3); + flicker(lamp, 0.09, 0.15); + // rain running down the storm window + const W0 = WINDOW; + this.rainG = this.add.graphics().setDepth(D.table + 0.2); + this.drops = Array.from({ length: 34 }, () => ({ + x: W0.x0 + Math.random() * (W0.x1 - W0.x0), y: W0.y0 + Math.random() * (W0.y1 - W0.y0), + v: 60 + Math.random() * 160, len: 5 + Math.random() * 10, a: 0.18 + Math.random() * 0.3, + })); + const onUpdate = (_t, dt) => this.updateRain(dt); + this.events.on('update', onUpdate); + this.events.once('shutdown', () => this.events.off('update', onUpdate)); + // the light on the point, and its beam sweeping through the room + this.lightFlash = add(LIGHTHOUSE.x, LIGHTHOUSE.y + 3, 130, 110, 0xfff0c0, 0, D.table + 0.3); + this.beam = this.add.image(2300, 540, 'crib-beam').setDisplaySize(560, 1700).setRotation(0.2) + .setBlendMode(Phaser.BlendModes.ADD).setTint(0xfff2cc).setAlpha(0.055).setDepth(D.float - 2); + const sweep = () => { + if (!this.alive()) return; + this.tweens.add({ targets: this.lightFlash, alpha: 0.95, duration: 260, yoyo: true, hold: 140 }); + this.beam.setX(2300); + this.tweens.add({ targets: this.beam, x: -500, duration: 2100, ease: 'Sine.easeInOut', delay: 380 }); + this.time.delayedCall(7600 + Math.random() * 1200, sweep); + }; + this.time.delayedCall(2500, sweep); } - floatScore(player, points, label) { - const { tracks } = this.layout; - const pt = tracks[player][this.logic.scores[player]]; - const txt = this.add.text(pt.x, pt.y - 18, `+${points}${label ? ' ' + label : ''}`, { - fontFamily: 'Righteous', fontSize: '24px', color: player === 0 ? '#f07a6d' : '#fff4d8', - }).setOrigin(0.5).setDepth(D.toast).setShadow(0, 0, 'rgba(255,207,74,0.85)', 12); - this.tweens.add({ - targets: txt, y: pt.y - 64, alpha: 0, duration: 1100, ease: 'Cubic.easeOut', - onComplete: () => txt.destroy() - }); - } - - // ── The show ──────────────────────────────────────────────────────────────── - async beginShow() { - this.busy = true; - this.statusText.setText('The Show'); - this.countText.setText(''); - await this.resetPegRow(); - - // reveal opponent's kept hand - this.handSprites[1].forEach((c, i) => { - const card = this.logic.keep[1][i]; - if (!card) return; - c.cardRef = card; - this.tweens.add({ - targets: c, scaleX: 0, duration: 120, yoyo: true, - onYoyo: () => { c.removeAll(true); this.drawFace(c, card, true); } - }); - }); - await this.delay(500); - - const nd = this.logic.nonDealer, d = this.logic.dealer; - const order = [ - { player: nd, cards: this.logic.keep[nd], isCrib: false, title: nd === 0 ? 'Your hand' : `${this.aiName}'s hand` }, - { player: d, cards: this.logic.keep[d], isCrib: false, title: d === 0 ? 'Your hand' : `${this.aiName}'s hand` }, - { player: d, cards: this.logic.crib, isCrib: true, title: d === 0 ? 'Your crib' : `${this.aiName}'s crib` }, - ]; - - for (const o of order) { - const r = scoreHand(o.cards, this.logic.starter, o.isCrib); - this.showCountPanel(o, r); - await this.delay(700); - const got = this.logic.addPoints(o.player, r.total); - if (got > 0) { this.floatScore(o.player, got, ''); this.placePegs(o.player); } - this.refreshScores(); - await this.delay(1100); - this.clearCountPanel(); - if (this.logic.winner !== null) break; + updateRain(dt) { + const g = this.rainG; + if (!g || !this.alive()) return; + const W0 = WINDOW; + g.clear(); + for (const d of this.drops) { + d.y += (d.v * dt) / 1000; + if (d.y > W0.y1 - 4) { d.y = W0.y0 + Math.random() * 30; d.x = W0.x0 + 4 + Math.random() * (W0.x1 - W0.x0 - 8); } + g.lineStyle(1.4, 0xc8daf0, d.a); + g.lineBetween(d.x, d.y - d.len, d.x + 0.6, d.y); } - - if (this.logic.winner !== null) return this.gameOver(); - this.statusText.setText(''); - this.nextBtn.setVisible(true); - this.busy = false; } - showCountPanel(o, r) { - this.clearCountPanel(); - const parts = []; - if (r.fifteens) parts.push(`Fifteens ${r.fifteens}`); - if (r.pairs) parts.push(`Pairs ${r.pairs}`); - if (r.runs) parts.push(`Runs ${r.runs}`); - if (r.flush) parts.push(`Flush ${r.flush}`); - if (r.nobs) parts.push(`Nobs ${r.nobs}`); - const body = parts.length ? parts.join(' ') : 'Nothing'; - - const w = 560, h = 130, cx = CENTER_X, cy = PEG_ROW_Y - 30; - const g = this.add.graphics().setDepth(D.modal); - g.fillStyle(THEME.woodDark, 0.96); g.fillRoundedRect(cx - w / 2, cy - h / 2, w, h, 14); - g.lineStyle(3, THEME.brass, 0.9); g.strokeRoundedRect(cx - w / 2, cy - h / 2, w, h, 14); - const t1 = this.add.text(cx, cy - 34, `${o.title} — ${o.isCrib ? 'CRIB' : 'HAND'}`, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.goldHex - }).setOrigin(0.5).setDepth(D.modalUI); - const t2 = this.add.text(cx, cy + 2, body, { - fontFamily: 'Righteous', fontSize: '24px', color: COLORS.textHex - }).setOrigin(0.5).setDepth(D.modalUI); - const t3 = this.add.text(cx, cy + 40, `${r.total} point${r.total === 1 ? '' : 's'}`, { - fontFamily: 'Righteous', fontSize: '30px', color: '#f0d77a' - }).setOrigin(0.5).setDepth(D.modalUI) - .setShadow(0, 0, 'rgba(255,207,74,0.8)', 12); - this.countPanel = [g, t1, t2, t3]; + // ── The count gauge ──────────────────────────────────────────────────────── + buildDial() { + const { x, y } = L.dial; + this.dialImg = this.add.image(x, y, 'crib-dial').setScale(0.5).setDepth(D.labels); + this.needleG = this.add.graphics().setDepth(D.labels + 0.5); + this.dialNum = this.add.text(x, y + 26, '0', { + fontFamily: 'Righteous', fontSize: '28px', color: '#2a1a0a', + }).setOrigin(0.5).setDepth(D.labels + 0.6); + this.needle = { a: dialAngle(0) }; + this.dialCount = 0; + this.drawNeedle(); } - clearCountPanel() { - (this.countPanel || []).forEach((o) => o.destroy()); - this.countPanel = null; + drawNeedle() { + const { x, y } = L.dial; + const g = this.needleG; + const a = this.needle.a; + g.clear(); + g.lineStyle(4, 0x000000, 0.25); + g.lineBetween(x + 2, y + 3, x + 2 + Math.cos(a) * 46, y + 3 + Math.sin(a) * 46); + g.lineStyle(3.2, 0x8a1a14, 1); + g.lineBetween(x - Math.cos(a) * 10, y - Math.sin(a) * 10, x + Math.cos(a) * 48, y + Math.sin(a) * 48); + g.fillStyle(0x3a2a14, 1); + g.fillCircle(x, y, 6); + g.fillStyle(0xf2d58a, 1); + g.fillCircle(x - 1.5, y - 1.5, 2); } - // ── Round / game transitions ──────────────────────────────────────────────── - onNextDeal() { - this.nextBtn.setVisible(false); - this.logic.nextRound(); - this.beginDiscard(); + displayCount() { + const P = this.gs?.play; + if (!P) return 0; + if (this.view.rowHold && P.series.length) return P.series[P.series.length - 1].reduce((s, p) => s + cardFromId(p.id).val, 0); + return P.count; } - clearTable() { - [...this.handSprites[0], ...this.handSprites[1], ...this.pegSprites, ...this.cribSprites].forEach((c) => c?.destroy()); - this.starterSprite?.destroy(); - this.clearCountPanel(); - this.handSprites = [[], []]; - this.pegSprites = []; - this.cribSprites = []; - this.starterSprite = null; + drawDial() { + if (!this.needleG || !this.gs) return; + const n = this.displayCount(); + const live = !!this.gs.play && !this.gs.show; + this.dialImg.setAlpha(live ? 1 : 0.6); + this.dialNum.setText(String(n)).setColor(n === 31 ? '#8a1a14' : n === 15 ? '#1e6a3c' : '#2a1a0a'); + if (n === this.dialCount && this.needleTw) return; + this.dialCount = n; + this.needleTw?.stop(); + this.needleTw = this.tweens.add({ + targets: this.needle, a: dialAngle(n), duration: 380, ease: n === 0 ? 'Sine.easeInOut' : 'Back.easeOut', + onUpdate: () => this.drawNeedle(), onComplete: () => this.drawNeedle(), + }); } - gameOver() { - this.clearCountPanel(); - this.nextBtn.setVisible(false); - this.confirmBtn.setVisible(false); - const won = this.logic.winner === 0; - const skunk = this.logic.scores[1 - this.logic.winner] < 91; - playSound(this, won ? SFX.CASINO_WIN : SFX.CASINO_LOSE); - this.postHistory(won ? 'win' : 'loss'); - - const g = this.add.graphics().setDepth(D.modal); - g.fillStyle(0x000000, 0.7); g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - g.fillStyle(THEME.woodMid, 1); g.fillRoundedRect(GAME_WIDTH / 2 - 360, 360, 720, 360, 24); - g.lineStyle(4, THEME.brass, 1); g.strokeRoundedRect(GAME_WIDTH / 2 - 360, 360, 720, 360, 24); - - this.add.text(GAME_WIDTH / 2, 450, won ? 'You Win!' : `${this.aiName} Wins`, { - fontFamily: 'Righteous', fontSize: '60px', color: won ? '#f0d77a' : '#e9e1cf' - }) - .setOrigin(0.5).setDepth(D.modalUI); - this.add.text(GAME_WIDTH / 2, 530, `${this.logic.scores[0]} – ${this.logic.scores[1]}${skunk ? ' (Skunk!)' : ''}`, { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex - }) - .setOrigin(0.5).setDepth(D.modalUI); - new Button(this, GAME_WIDTH / 2, 650, 'Back to Menu', () => this.scene.start('GameMenu'), - { width: 300, fontSize: 26 }).setDepth(D.modalUI); + // ── Tooltips ─────────────────────────────────────────────────────────────── + buildTooltips() { + const r = boardRect(); + this.hoverZone((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2 - 10, r.x1 - r.x0 - 60, r.y1 - r.y0 - 50, () => this.boardTip()); + const d = L.deck; + this.hoverZone(d.x, d.y, CARD_W * d.s + 24, CARD_H * d.s * SQ + 24, () => this.deckTip()); + this.hoverZone(L.dial.x, L.dial.y, 140, 140, () => this.dialTip()); + for (const cp of [L.cribMine, L.cribTheirs]) this.hoverZone(cp.x, cp.y, CARD_W * cp.s + 30, CARD_H * cp.s * SQ + 20, () => this.cribTip()); + const pl = L.plates[1]; + this.hoverZone(pl.x, pl.y, PLATE.w, PLATE.h, () => this.seatTip()); } - async postHistory(result) { - if (this.recorded) return; - this.recorded = true; + boardTip() { + const gs = this.gs; + if (!gs || !this.board) return null; + const sh = this.board.shown, t = gs.rules.target; + const lead = sh[0] - sh[1]; + const sk = skunkLines(gs.rules); + const lines = [ + { text: `You: ${sh[0]} (${t - sh[0]} to go)`, color: SEAT_HEX[0] }, + { text: `${this.shortName(1, 14)}: ${sh[1]} (${t - sh[1]} to go)`, color: SEAT_HEX[1] }, + { text: lead === 0 ? 'All square.' : lead > 0 ? `You lead by ${lead}.` : `You trail by ${-lead}.`, color: INK }, + { text: `Skunk line at ${sk.skunk}${sk.double ? `, double skunk at ${sk.double}` : ''} — win before the loser crosses it.`, color: MUTED }, + ]; + if (gs.rules.bestOf > 1) lines.push({ text: `Match: you ${gs.games[0]} – ${gs.games[1]} (first to ${gamesNeeded(gs.rules.bestOf)})`, color: AMBER }); + lines.push({ text: 'Back peg leapfrogs the front one — the gap is what was just scored.', color: COLORS.mutedHex }); + return { title: `The board — first to ${t}`, lines }; + } + + deckTip() { + const gs = this.gs; + if (!gs) return null; + const lines = [{ text: `${gs.deck.length} cards left in the deck.` }]; + if (gs.starter) lines.push({ text: `The starter is the ${cardName(gs.starter)} — it counts in every hand and the crib.`, color: AMBER }); + else lines.push({ text: `After the lay-away ${gs.dealer === 0 ? this.shortName(1, 14) : 'you'} cut${gs.dealer === 0 ? 's' : ''}; the top card is the starter. A jack: "his heels", 2 to the dealer.`, color: MUTED }); + return { title: 'The deck', lines }; + } + + dialTip() { + const gs = this.gs; + if (!gs?.play || gs.show) return { title: 'The count', lines: [{ text: 'During the play, the running total of the cards laid — never past 31.', color: MUTED }] }; + const P = gs.play; + const cards = P.pile.map((p) => cardName(cardFromId(p.id))).join(' '); + return { + title: `The count: ${P.count}`, + lines: [ + { text: P.count ? `${PLAY_LIMIT - P.count} more to 31 · on the row: ${cards}` : 'A fresh count — the next card leads.' }, + { text: '15 or 31: 2 · pair 2 · three of a kind 6 · four 12 · runs 1 a card', color: MUTED }, + { text: 'Can\'t play? It\'s a "go": the other player plays on, the last card pegs 1.', color: MUTED }, + ], + }; + } + + cribTip() { + const gs = this.gs; + if (!gs) return null; + const mine = gs.dealer === 0; + const lines = [{ text: `${mine ? 'Your' : `${this.shortName(1, 14)}'s`} crib — counted last, by the dealer, with the starter.` }]; + if (gs.layaway[0]) lines.push({ text: `You laid away ${gs.layaway[0].map((id) => cardName(cardFromId(id))).join(' ')}.`, color: AMBER }); + lines.push({ text: 'Flush in the crib needs all five cards of one suit.', color: MUTED }); + return { title: `The crib (${gs.crib.length} card${gs.crib.length === 1 ? '' : 's'})`, lines }; + } + + seatTip() { + const gs = this.gs; + if (!gs) return null; + const P = gs.play; + const played = P ? [...P.series.flat(), ...P.pile].filter((p) => p.seat === 1).map((p) => cardName(cardFromId(p.id))) : []; + return { + title: this.nameForSeat(1), titleColor: SEAT_HEX[1], + lines: [ + { text: `${this.board?.shown[1] ?? 0} of ${gs.rules.target} · skill ${this.skillFor(1)} / 5${gs.dealer === 1 ? ' · dealing' : ''}`, color: INK }, + { text: played.length ? `Played this hand: ${played.join(' ')}` : 'Hasn\'t played a card this hand.', color: MUTED }, + ], + }; + } + + // ── Save / resume ────────────────────────────────────────────────────────── + signature() { + return JSON.stringify({ opp: this.opponents.map((o) => o?.id ?? o?.name ?? '?') }); + } + + readSave() { try { - await api.post('/history/single-player', { - slug: 'cribbage', - score: this.logic.scores[0], - opponentScores: [this.logic.scores[1]], - result, - }); - } catch { /* non-fatal */ } + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || s.sig !== this.signature() || !G.isValidSave(s.gs)) return null; + return s; + } catch (_) { return null; } } - delay(ms) { return new Promise((resolve) => this.time.delayedCall(ms, resolve)); } + saveGame(gs = this.gs) { + if (!gs || !['discard', 'play'].includes(gs.phase) || gs.winner != null) return; + try { localStorage.setItem(SAVE_KEY, JSON.stringify({ v: 1, sig: this.signature(), gs, savedAt: Date.now() })); } catch (_) { /* private mode */ } + } + + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + offerResume(save) { + const when = new Date(save.savedAt).toLocaleDateString(); + const g = save.gs; + const match = g.rules.bestOf > 1 ? ` · match ${g.games[0]}–${g.games[1]}` : ''; + this.confirm('Resume your game?', `A game from ${when} is still on the table — you ${g.scores[0]}, ${this.shortName(1, 14)} ${g.scores[1]} (to ${g.rules.target})${match}.`, 'Resume', () => { + this.gs = save.gs; + this.ensureBoard(); + this.board.snap(this.gs.scores, this.gs.back, this.gs.games); + this.startDeal({ resumed: true }); + }, { no: 'New game', onNo: () => { this.clearSave(); this.newMatch(); } }); + } + + // ── Match / game / deal lifecycle ────────────────────────────────────────── + ensureBoard() { + const r = this.gs.rules; + const want = `${r.target}|${r.bestOf > 1}|${!!r.doubleSkunk}`; + if (this.board && this.boardKey === want) return; + this.board?.destroy(); + this.boardKey = want; + this.board = new PegBoard(this, { + target: r.target, match: r.bestOf > 1, doubleSkunk: !!r.doubleSkunk && r.target === 121, depth: D.table + 0.5, + speed: () => (this.view.skip ? 0.3 : COUNT_SPEED[this.settings.countSpeed] ?? 1), + onLand: () => this.updatePlates(), + }); + } + + newMatch() { + const seed = (Math.random() * 2 ** 32) >>> 0; + this.gs = G.createGame({ rules: this.settings.rules, seed }); + this.ended = false; + this.ensureBoard(); + this.board.snap(this.gs.scores, this.gs.back, this.gs.games); + this.runCutForDeal(); + } + + /** Each player cuts; low card deals (ties cut again). */ + async runCutForDeal() { + const token = ++this.turnToken; + const live = () => this.alive() && token === this.turnToken; + this.mode = 'cutdeal'; + this.clearSprites(); + for (const c of fullDeck()) this.lastLoc.set(c.id, { pose: L.deck, faceUp: false, depth: D.cards }); + this.updatePlates(); + this.setDock('Cutting for the deal — low card deals.'); + this.drawDial(); + for (const pair of this.gs.cuts) { + this.view.cutdeal = { pair, up: false }; + this.layout({ duration: 380 }); + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.5 }); + await this.wait(600); + if (!live()) return; + this.view.cutdeal.up = true; + this.layout({ duration: 300 }); + playSound(this, SFX.CARD_SHOW); + await this.wait(650); + if (!live()) return; + const [a, b] = pair.map(cardFromId); + if (a.run === b.run) { + this.floatText({ x: CX, y: L.cutMine.y - 150 }, 'A tie — cut again', AMBER, { size: 28, ms: 1300, rise: 18 }); + await this.wait(900); + } else { + const d = this.gs.dealer; + this.stamp(d === 0 ? 'You deal' : `${this.shortName(1, 12)} deals`, { x: CX + 120, y: (L.cutMine.y + L.cutTheirs.y) / 2 }, SEAT_HEX[d], { + size: 60, sub: `${cardName(d === 0 ? a : b)} is the low card`, hold: 1300, + }); + await this.wait(1700); + } + if (!live()) return; + this.view.cutdeal = { pair: null, up: false }; + this.layout({ duration: 300 }); + await this.wait(320); + if (!live()) return; + } + this.view.cutdeal = null; + this.startDeal({ fromDeck: true }); + } + + async startDeal({ resumed = false, fromDeck = false } = {}) { + const token = ++this.turnToken; + const live = () => this.alive() && token === this.turnToken; + this.closeModal(); + this.mode = 'deal'; + this.pending = []; + this.hintIds = new Set(); + this.hoverId = null; + this.view = { cutdeal: null, rowHold: false, showing: null, hi: new Set(), skip: false, cutting: null }; + this.aiDiscarding = false; + this.caption.hide(0); + this.preview.setText(''); + this.readout.setText(''); + for (const pl of this.plates) pl.stamp.setVisible(false); + if (!resumed && !fromDeck && this.sprites.size) { + await this.sweepCards(L.deck); + if (!live()) return; + } + this.clearSprites(); + for (const c of fullDeck()) this.lastLoc.set(c.id, { pose: L.deck, faceUp: false, depth: D.fly }); + this.updatePlates(); + this.updateDock(); + this.drawDial(); + playSound(this, SFX.CARD_SHUFFLE); + const gs = this.gs; + const step = resumed ? 14 : 70; + const pone = 1 - gs.dealer; + this.layout({ + duration: 300, + delayFor: (v) => (v.kind === 'hand' || v.kind === 'pending' ? 260 + ((v.idx ?? 0) * 2 + (v.seat === pone ? 0 : 1)) * step : 0), + }); + for (let i = 0; i < 12; i += 2) this.time.delayedCall(260 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.4 })); + await this.wait(260 + 12 * step + 380); + if (!live()) return; + this.advance(); + } + + async advance() { + if (!this.alive() || !this.gs) return; + if (this.view.rowHold && this.holdPromise) { + const token = this.turnToken; + await this.holdPromise; + if (!this.alive() || token !== this.turnToken) return; + } + const gs = this.gs; + if (gs.phase === 'gameOver') { this.onGameOver(); return; } + if (gs.phase === 'discard') { + this.saveGame(); + if (gs.layaway[1] == null && !this.aiDiscarding) this.runAIDiscard(); + this.mode = gs.layaway[0] == null ? 'discard' : 'waitAI'; + this.setSpot(spotFor(0), 0.22); + this.setPlateActive(0, this.mode === 'discard'); + this.refreshAll(); + return; + } + if (gs.phase === 'cut') { if (this.mode !== 'cut' && this.mode !== 'cutting') this.beginCut(); return; } + if (gs.phase === 'play') { + this.saveGame(); + const seat = gs.play.next; + this.setSpot(spotFor(seat)); + if (seat === 0) { + this.mode = 'play'; + this.refreshAll(); + } else { + this.mode = 'ai'; + this.refreshAll(); + this.runAIPlay(); + } + return; + } + if (gs.phase === 'show') { this.runShow(); return; } + if (gs.phase === 'roundOver') this.onRoundOver(); + } + + refreshAll() { + if (!this.gs) return; + this.coachCache.key = ''; + this.layout(); + this.updatePlates(); + this.updateDock(); + this.updateReadout(); + this.updatePreview(); + this.drawDial(); + } + + /** Apply a new state and animate everything to it. */ + commit(next, { carry = null, carrySeat = null, deferPegs = false } = {}) { + const prev = this.gs; + this.gs = next; + this.coachCache.key = ''; + const same = prev && prev.round === next.round && prev.gameNo === next.gameNo; + const fresh = same ? next.log.slice(prev.log.length) : next.log.slice(); + if (fresh.some((e) => e.kind === 'reset') && next.play) this.holdRow(); + const carryIds = carry == null ? null : new Set([].concat(carry)); + this.layout({ durationFor: (v) => (carryIds?.has(v.card.id) ? this.timing(carrySeat ?? 1).carry : null) }); + const pegs = []; + for (const e of fresh) { + if (deferPegs && e.kind === 'peg') pegs.push(e); + else this.logEffect(e); + } + this.updatePlates(); + this.updateDock(); + this.updateReadout(); + this.updatePreview(); + this.drawDial(); + return pegs; + } + + /** Keep a finished series on the row for a moment (the "31!" / "go" beat). */ + holdRow() { + this.view.rowHold = true; + const ms = 1000 * this.pace(); + this.holdPromise = new Promise((res) => this.time.delayedCall(ms, () => { + this.view.rowHold = false; + if (this.alive() && this.gs) { this.layout({ duration: 340 }); this.drawDial(); this.updateDock(); } + res(); + })); + } + + logEffect(e) { + if (e.kind === 'peg') this.pegEffect(e); + else if (e.kind === 'play') { + if (e.seat === 1) playSoundEx(this, SFX.CARD_PLACE, { volume: 0.6 }); + if (e.pts) { + const p = this.poseOf(e.id) ?? rowPose(0); + this.time.delayedCall(240, () => { + this.floatText({ x: p.x, y: p.y - 70 }, `${reasonWords(e.reasons)} — ${e.pts}`, SEAT_HEX[e.seat], { size: 24, ms: 1500, rise: 26 }); + for (const id of e.scoreIds) this.flashGlow(id, e.seat === 0 ? 0xff9a86 : 0x8ccaf8, { delay: 0, hold: 700 }); + }); + } + if (e.count === PLAY_LIMIT) this.time.delayedCall(260, () => this.stamp('31!', { x: L.dial.x, y: L.dial.y - 10 }, '#f0d77a', { size: 64, hold: 700 })); + } else if (e.kind === 'go') { + this.plateStamp(e.seat, 'GO', AMBER, 1300); + const pl = L.plates[e.seat]; + const at = e.seat === 0 ? { x: CX, y: 800 } : { x: pl.x - 230, y: pl.y + 40 }; + this.floatText(at, e.seat === 0 ? 'You can\'t play — "Go"' : `${this.shortName(1, 12)}: "Go"`, AMBER, { size: 24, ms: 1400, rise: 16 }); + playSoundEx(this, SFX.CLICK, { volume: 0.5 }); + } else if (e.kind === 'cut') { + const st = cardFromId(e.starter); + if (st.rank === 'J') { + this.time.delayedCall(500, () => { + this.stamp('His Heels!', { x: L.deck.x + 140, y: L.deck.y - 110 }, '#f0d77a', { size: 54, sub: `a jack — 2 to ${this.gs.dealer === 0 ? 'you' : this.shortName(1, 12)}`, hold: 1500 }); + playSound(this, SFX.CASINO_WIN); + }); + } + } + } + + pegEffect(e) { + this.board.move(e.seat, e.from, e.to); + const hole = this.board.geo.holes[e.seat][Math.min(e.to, this.board.geo.holes[e.seat].length - 1)]; + if (e.why === 'go' || e.why === 'last') { + const word = e.why === 'go' ? '1 for the go' : '1 for last card'; + const p = e.seat === 0 ? { x: CX - 200, y: 760 } : { x: L.plates[1].x - 230, y: L.plates[1].y + 40 }; + this.floatText(p, word, SEAT_HEX[e.seat], { size: 22, ms: 1400, rise: 16 }); + } + this.time.delayedCall(140, () => this.floatText({ x: hole.x, y: hole.y - 8 }, `+${e.pts}`, SEAT_HEX[e.seat], { size: 22, ms: 1300, rise: 30 })); + } + + // ── The lay-away ─────────────────────────────────────────────────────────── + async runAIDiscard() { + this.aiDiscarding = true; + const token = this.turnToken; + const live = () => this.alive() && token === this.turnToken; + const T0 = this.timing(1); + await this.wait(T0.think * 2 + 500); + if (!live() || this.gs.phase !== 'discard' || this.gs.layaway[1] != null) { this.aiDiscarding = false; return; } + const ids = chooseDiscard(this.gs, 1, { skill: this.skillFor(1) }); + this.moveHand(1, this.poseOf(ids[0]) ?? handHome(), T0.reach); + await this.wait(T0.reach); + if (!live()) { this.aiDiscarding = false; return; } + const next = G.discard(this.gs, 1, ids); + this.aiDiscarding = false; + if (next === this.gs) return; + this.moveHand(1, cribPose(this.gs.dealer), T0.carry, 'Cubic.easeOut'); + this.handRest(1, T0.carry * 0.7, T0.carry); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.5 }); + this.commit(next, { carry: ids, carrySeat: 1 }); + const pl = L.plates[1]; + this.floatText({ x: pl.x - 230, y: pl.y + 40 }, `lays two away to ${this.gs.dealer === 0 ? 'your' : 'his'} crib`, SEAT_HEX[1], { size: 18, ms: 1500, rise: 14 }); + await this.wait(T0.carry + 250); + if (!live()) return; + if (this.gs.phase === 'cut') this.advance(); + } + + /** Human: move a card into (or out of) the pair going to the crib. */ + togglePending(id) { + const gs = this.gs; + if (this.mode !== 'discard' || gs.phase !== 'discard' || gs.layaway[0] != null) { this.notYet(); return; } + const i = this.pending.indexOf(id); + if (i >= 0) this.pending.splice(i, 1); + else if (this.pending.length >= 2) { + this.nudge(id); + this.floatText({ x: CX, y: 790 }, 'Two are already going to the crib — click one to take it back', AMBER, { size: 20 }); + return; + } else this.pending.push(id); + this.hintIds = new Set(); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.4, rate: 1.15 }); + this.layout({ duration: 200 }); + this.updateDock(); + this.updateReadout(); + } + + async confirmDiscard() { + const gs = this.gs; + if (this.mode !== 'discard' || this.pending.length !== 2) return; + const next = G.discard(gs, 0, this.pending.slice()); + if (next === gs) return; + const ids = this.pending.slice(); + this.pending = []; + this.mode = 'busy'; + playSound(this, SFX.CARD_PLACE); + this.commit(next, { carry: ids, carrySeat: 0 }); + this.setPlateActive(0, false); + await this.wait(420); + if (!this.alive()) return; + if (this.gs.phase === 'cut') this.advance(); + else { this.mode = 'waitAI'; this.updateDock(); this.updateReadout(); } + } + + coachDiscard() { + const key = `d${this.gs.round}-${this.gs.gameNo}`; + if (this.coachCache.key !== key || !this.coachCache.discard) { + this.coachCache = { key, discard: adviseDiscard(this.gs, 0), play: null }; + } + return this.coachCache.discard; + } + + /** The Coach line under the board during the lay-away. */ + updateReadout() { + const gs = this.gs; + const show = gs && gs.phase === 'discard' && gs.layaway[0] == null && this.mode === 'discard'; + this.pendingLabel.setVisible(!!show && this.pending.length > 0); + if (!show) { this.readout.setText(''); return; } + const whose = gs.dealer === 0 ? 'your' : `${this.shortName(1, 12)}'s`; + if (!this.settings.hints) { + this.readout.setText(this.pending.length === 2 ? 'Press Enter (or "Lay away") to send them to the crib.' : `Pick two cards to lay away to ${whose} crib.`).setColor(INK); + return; + } + const C = this.coachDiscard(); + const best = C.best; + const fmt = (o) => `keep ≈ ${o.hand.toFixed(1)} · crib ${o.crib >= 0 ? '+' : '−'}${Math.abs(o.crib).toFixed(1)}`; + const names = (cs) => cs.map(cardName).join(' '); + if (this.pending.length === 2) { + const set = new Set(this.pending); + const mine = C.options.find((o) => o.discard.every((c) => set.has(c.id))); + const isBest = mine === best; + const line1 = `Keeping ${names(mine.keep)}: ${fmt(mine)} = ${mine.total.toFixed(1)}`; + const line2 = isBest ? '✓ That\'s the Coach\'s choice too.' : `Coach: lay away ${names(best.discard)} instead (${best.total.toFixed(1)}, +${(best.total - mine.total).toFixed(1)})`; + this.readout.setText(`${line1}\n${line2}`).setColor(isBest ? GREEN : INK); + } else { + this.readout.setText(`Pick two cards for ${whose} crib (${gs.dealer === 0 ? 'feed it — it\'s yours' : 'starve it — it\'s his'}).\nCoach: lay away ${names(best.discard)} — ${fmt(best)}`).setColor(INK); + } + } + + // ── The cut ──────────────────────────────────────────────────────────────── + beginCut() { + this.mode = 'cut'; + this.setSpot({ x: L.deck.x, y: L.deck.y, w: 420, h: 360 }, 0.3); + this.refreshAll(); + if (this.gs.dealer === 0) this.aiCut(); + } + + async aiCut() { + const token = ++this.turnToken; + const T0 = this.timing(1); + await this.wait(T0.think); + if (!this.alive() || token !== this.turnToken) return; + this.moveHand(1, L.deck, T0.reach); + await this.wait(T0.reach); + if (!this.alive() || token !== this.turnToken) return; + this.handRest(1, T0.carry, 500); + this.doCut(0.3 + Math.random() * 0.4); + } + + /** Lift the top half, turn the starter, put the deck back together. */ + async doCut(depth = null) { + if (this.mode !== 'cut' || this.gs.phase !== 'cut') return; + const token = ++this.turnToken; + const live = () => this.alive() && token === this.turnToken; + this.mode = 'cutting'; + this.updateDock(); + const frac = depth ?? 0.5; + const top = this.sprites.get(this.gs.deck[0].id); + const half = { x: 0, y: 0, k: Math.max(0.2, Math.min(0.8, frac)) }; + this.view.cutting = half; + top?.setVisible(false); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.4, rate: 1.4 }); + await new Promise((res) => this.tweens.add({ targets: half, x: 128, y: -36, duration: 300, ease: 'Cubic.easeOut', onUpdate: () => this.drawSlabs(), onComplete: res })); + if (!live()) return; + const next = G.cutStarter(this.gs, depth); + this.commit(next); + playSound(this, SFX.CARD_SHOW); + await this.wait(460); + if (!live()) return; + await new Promise((res) => this.tweens.add({ targets: half, x: 0, y: 0, duration: 260, ease: 'Cubic.easeIn', onUpdate: () => this.drawSlabs(), onComplete: res })); + this.view.cutting = null; + this.sprites.get(this.gs.deck[0]?.id)?.setVisible(true); + this.drawSlabs(); + if (!live()) return; + this.layout(); + await this.wait(this.gs.starter?.rank === 'J' ? 1500 : 450); + if (!live()) return; + this.advance(); + } + + drawSlabs() { + const g = this.slabG, cg = this.cutG; + g.clear(); + cg.clear(); + if (!this.gs) return; + const base = L.deck; + const n = this.view.cutdeal ? 52 : this.gs.deck.length; + const hw = (CARD_W / 2) * base.s, hh = (CARD_H / 2) * base.s * SQ; + const slab = (gr, x, y, cards, color = 0x1d2f4a) => { + const lift = stackLift(cards, base.s, 0.12, 9); + const layers = Math.max(1, Math.min(7, Math.ceil(lift / 1.5))); + for (let j = 0; j < layers; j++) { + const yy = y - (lift * j) / layers; + gr.fillStyle(j % 2 ? 0x24395a : 0x15233a, 1); + gr.fillRoundedRect(x - hw, yy - hh, hw * 2, hh * 2, 8 * base.s); + } + return lift; + }; + const cut = this.view.cutting; + if (cut) { + const lower = Math.round(n * (1 - cut.k)); + slab(g, base.x, base.y, lower); + const ly = base.y - stackLift(lower, base.s, 0.12, 9); + const upLift = slab(cg, base.x + cut.x, ly + cut.y - 4, n - lower); + // the upper half's top card (a back) + cg.fillStyle(0x24395a, 1); + cg.fillRoundedRect(base.x + cut.x - hw, ly + cut.y - 4 - upLift - hh, hw * 2, hh * 2, 8 * base.s); + cg.lineStyle(2, 0xd9b45a, 0.8); + cg.strokeRoundedRect(base.x + cut.x - hw + 5, ly + cut.y - 4 - upLift - hh + 5, hw * 2 - 10, hh * 2 - 10, 6 * base.s); + return; + } + if (n > 1) slab(g, base.x, base.y, n); + } + + /** Pose of the deck's top card (sits on the slab stack). */ + deckTop() { + const n = this.view.cutdeal ? 52 : this.gs.deck.length; + return { ...L.deck, y: L.deck.y - stackLift(n, L.deck.s, 0.12, 9) }; + } + + // ── The play ─────────────────────────────────────────────────────────────── + async runAIPlay() { + const token = ++this.turnToken; + const live = () => this.alive() && token === this.turnToken; + const T0 = this.timing(1); + await this.wait(T0.think); + if (!live() || this.gs.phase !== 'play' || this.gs.play.next !== 1) return; + const id = choosePlay(this.gs, 1, { skill: this.skillFor(1) }); + if (!id) return; + this.moveHand(1, this.poseOf(id) ?? handHome(), T0.reach); + await this.wait(T0.reach); + if (!live()) return; + const slot = this.gs.play.pile.length; + const next = G.play(this.gs, 1, id); + if (next === this.gs) return; + this.moveHand(1, rowPose(slot), T0.carry, 'Cubic.easeOut'); + this.handRest(1, T0.carry * 0.7, T0.carry); + this.commit(next, { carry: id, carrySeat: 1 }); + await this.wait(T0.carry + 200); + if (!live()) return; + this.advance(); + } + + legalIds() { + const gs = this.gs; + if (!gs || gs.phase !== 'play' || gs.play.next !== 0) return new Set(); + return new Set(G.legalPlays(gs, 0).map((c) => c.id)); + } + + async humanPlay(id) { + const gs = this.gs; + if (this.mode !== 'play' || gs.phase !== 'play' || gs.play.next !== 0) { this.notYet(); return; } + const card = gs.play.hands[0].find((c) => c.id === id); + if (!card) return; + if (gs.play.count + card.val > PLAY_LIMIT) { + this.nudge(id); + this.floatText({ x: CX, y: 790 }, `The ${cardName(card)} would take the count past 31`, AMBER, { size: 20 }); + return; + } + const next = G.play(gs, 0, id); + if (next === gs) return; + this.mode = 'busy'; + this.hoverId = null; + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.6 }); + this.commit(next, { carry: id, carrySeat: 0 }); + await this.wait(320); + if (!this.alive()) return; + this.advance(); + } + + coachPlay() { + const gs = this.gs; + if (!gs?.play || gs.play.next !== 0) return null; + const key = `p${gs.round}-${gs.play.pile.length}-${gs.play.series.length}-${gs.play.hands[0].length}`; + if (this.coachCache.key !== key) this.coachCache = { key, discard: this.coachCache.discard, play: advisePlay(gs, 0) }; + return this.coachCache.play; + } + + /** The line under the gauge: what the hovered card would do. */ + updatePreview() { + const gs = this.gs; + if (!gs || this.mode !== 'play' || !this.settings.hints || gs.play?.next !== 0) { this.preview.setText(''); return; } + const id = this.hoverId; + const card = id ? gs.play.hands[0].find((c) => c.id === id) : null; + if (!card) { this.preview.setText(`Count ${gs.play.count} — your play`).setColor(MUTED); return; } + if (gs.play.count + card.val > PLAY_LIMIT) { this.preview.setText(`${cardName(card)}: ${gs.play.count + card.val} — past 31`).setColor('#ff8a7a'); return; } + const e = evalPlay(gs, 0, card, 'deep'); + let t = `${cardName(card)} → ${e.count}`; + if (e.now) t += `\n${reasonWords(e.reasons)} for ${e.now}`; + if (!e.wins && e.reply >= 0.6) t += `\nrisky: ≈${e.reply.toFixed(1)} back to them`; + else if (!e.now && e.reply < 0.3 && e.count !== 31) t += '\nsafe'; + this.preview.setText(t).setColor(e.now ? GREEN : e.reply >= 0.6 ? AMBER : INK); + } + + // ── The show ─────────────────────────────────────────────────────────────── + async runShow() { + const token = ++this.turnToken; + const live = () => this.alive() && token === this.turnToken; + if (this.view.rowHold && this.holdPromise) await this.holdPromise; + if (!live()) return; + this.mode = 'show'; + this.view.skip = false; + this.setSpot({ x: CX, y: 620, w: 1400, h: 600 }, 0.24); + this.setPlateActive(0, false); + this.setPlateActive(1, false); + this.handRest(1, 300); + this.refreshAll(); + const cs = () => (this.view.skip ? 0.15 : COUNT_SPEED[this.settings.countSpeed] ?? 1); + await this.wait(650 * cs()); + while (live() && this.gs.phase === 'show') { + const next = G.showStep(this.gs); + const item = next.show.items[next.show.items.length - 1]; + this.view.showing = item; + this.view.hi = new Set(); + const pegs = this.commit(next, { deferPegs: true }); + playSoundEx(this, SFX.CARD_SHOW, { volume: 0.6 }); + const who = item.seat === 0 ? 'Your' : `${this.shortName(1, 14)}'s`; + const role = item.seat === this.gs.dealer ? 'dealer' : 'pone'; + this.caption.open(`${who} ${item.kind === 'crib' ? 'crib' : 'hand'} · ${role} · with the ${cardName(this.gs.starter)}`, SEAT_HEX[item.seat]); + await this.wait(700 * cs()); + if (!live()) return; + for (const c of item.combos) { + this.view.hi = new Set(c.ids); + this.layout({ duration: 140 }); + this.caption.call(c.say, c.running); + playSoundEx(this, SFX.CLICK, { volume: 0.35, rate: 0.9 + Math.min(0.8, c.running * 0.03) }); + await this.wait(640 * cs()); + if (!live()) return; + } + this.view.hi = new Set(); + this.layout({ duration: 160 }); + const note = item.total === 29 ? 'the perfect hand!' : item.total === 0 ? '"nineteen" — nothing at all' : null; + this.caption.finish(item.total, note); + for (const e of pegs) this.pegEffect(e); + if (item.total === 29) { + this.stamp('TWENTY-NINE!', { x: CX, y: L.showY - 40 }, '#f0d77a', { size: 84, sub: 'the perfect cribbage hand', hold: 2400 }); + this.burst({ x: CX, y: L.showY }, 0xf0d77a, { n: 16, r: 160 }); + playSound(this, SFX.VICTORY_SHORT); + } else if (item.total === 0) { + this.stamp('Nineteen!', { x: CX, y: L.showY - 30 }, '#c9b08a', { size: 56, sub: 'cribbage talk for nothing', hold: 1300 }); + } else if (item.total >= 16) { + this.floatText({ x: CX, y: L.showY - 100 }, item.total >= 20 ? 'What a hand!' : 'A fine hand', '#f0d77a', { size: 30, ms: 1500, rise: 20 }); + } + await this.board.idle(); + if (!live()) return; + await this.wait((item.total === 29 ? 1800 : 800) * cs()); + if (!live()) return; + this.view.showing = null; + this.caption.hide(); + this.layout({ duration: 300 }); + await this.wait(300 * cs()); + } + if (!live()) return; + this.view.skip = false; + this.advance(); + } + + onRoundOver() { + this.mode = 'roundOver'; + this.saveGame(G.nextRound(this.gs)); + this.setSpot({ x: CX, y: 620, w: 1400, h: 600 }, 0.12); + this.refreshAll(); + if (this.settings.autoNext) { + const token = this.turnToken; + this.time.delayedCall(2200, () => { if (this.alive() && token === this.turnToken && this.mode === 'roundOver' && !this.modal) this.nextDeal(); }); + } + } + + nextDeal() { + if (this.mode !== 'roundOver' || this.gs.phase !== 'roundOver') return; + this.gs = G.nextRound(this.gs); + this.startDeal(); + } + + // ── Game over ────────────────────────────────────────────────────────────── + async onGameOver() { + if (this.ended) return; + this.ended = true; + const token = ++this.turnToken; + this.mode = 'gameOver'; + this.caption.hide(); + this.updateDock(); + this.clearSave(); + await this.board.idle(); + if (!this.alive() || token !== this.turnToken) return; + const gs = this.gs; + const won = gs.winner === 0; + const res = gs.gameResult; + const hole = this.board.frontPoint(gs.winner); + this.burst(hole, SEAT_COLORS[gs.winner], { n: 14, r: 90 }); + this.stamp(won ? 'You peg out!' : `${this.shortName(1, 12)} pegs out`, { x: CX, y: 520 }, SEAT_HEX[gs.winner], { + size: 72, sub: res.skunk ? (res.skunk === 2 ? 'a DOUBLE SKUNK' : 'and that\'s a SKUNK') : null, hold: 1600, + }); + playSound(this, won ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + this.portraits[1]?.playEmotion?.(won ? 'sad' : 'happy'); + this.recordResult('cribbage', { score: gs.scores[0], opponentScores: [gs.scores[1]], won }); + const note = recordLifetime(gs); + await this.wait(2000); + if (!this.alive() || token !== this.turnToken) return; + this.showEnd(note); + } + + showEnd(note = null) { + const gs = this.gs; + const matchLeft = gs.rules.bestOf > 1 && gs.matchWinner == null; + const buttons = matchLeft + ? [ + { label: `Game ${gs.gameNo + 1}`, act: () => this.nextGame(), hot: true }, + { label: 'Score sheet', ghost: true, act: () => this.openScorePad({ back: () => this.showEnd(note) }) }, + { label: 'Leave', ghost: true, act: () => this.onLeave() }, + ] + : [ + { label: 'Play again', act: () => this.restart(), hot: true }, + { label: 'Score sheet', ghost: true, act: () => this.openScorePad({ back: () => this.showEnd(note) }) }, + { label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }, + ]; + openEndScreen(this, { gs, names: ['You', this.shortName(1, 14)], buttons, note }); + } + + nextGame() { + this.closeModal(); + const next = G.nextGame(this.gs); + if (next === this.gs) return; + this.gs = next; + this.ended = false; + this.board.snap(next.scores, next.back, next.games); + this.stamp(`Game ${next.gameNo}`, { x: CX, y: 520 }, '#f0d77a', { size: 70, sub: `${next.dealer === 0 ? 'You deal' : `${this.shortName(1, 12)} deals`} — loser of the last game`, hold: 1400 }); + this.startDeal(); + } + + // ── Layout ───────────────────────────────────────────────────────────────── + displayPhase() { + const gs = this.gs; + if (this.view.cutdeal) return 'cutdeal'; + if (this.view.rowHold && gs.play) return 'play'; + if (gs.show) return 'show'; + if (gs.play) return 'play'; + return 'discard'; + } + + /** The human's cards in hand, in fan order. */ + humanCards() { + const gs = this.gs; + const dp = this.displayPhase(); + let cards; + if (dp === 'play') cards = gs.play.hands[0]; + else if (dp === 'show') cards = gs.kept[0]; + else if (gs.layaway[0] == null) cards = gs.hands[0].filter((c) => !this.pending.includes(c.id)); + else cards = gs.kept[0]; + return cards.slice().sort(byRank); + } + + humanPoses() { + const cards = this.humanCards(); + const n = cards.length; + const shift = this.pending.length && this.gs.layaway[0] == null && this.displayPhase() === 'discard' ? -110 : 0; + const legal = this.mode === 'play' ? this.legalIds() : null; + return cards.map((card, i) => { + let lift = card.id === this.hoverId ? HOVER_LIFT : 0; + if (legal?.has(card.id) && card.id !== this.hoverId) lift = 6; + const p = handPose(0, i, n, lift); + return { id: card.id, card, idx: i, pose: { ...p, x: p.x + shift } }; + }); + } + + pendingPose(i) { + return { x: 1190 + i * 92, y: 918 - (this.hoverId === this.pending[i] ? HOVER_LIFT : 0), rot: 0.07 + i * 0.05, s: 1, q: 1 }; + } + + computeLayout() { + const gs = this.gs; + const visible = new Map(), loc = new Map(); + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + const hide = (card, v) => loc.set(card.id, v); + const deckTop = this.deckTop(); + const dp = this.displayPhase(); + if (dp === 'cutdeal') { + const cd = this.view.cutdeal; + const pair = cd.pair ?? []; + const all = fullDeck(); + let shown = false; + for (const c of all) { + const i = pair.indexOf(c.id); + if (i >= 0) { + put(c, { kind: 'cut', seat: i, pose: i === 0 ? L.cutMine : L.cutTheirs, faceUp: cd.up, depth: D.cards + 3 }); + } else if (!shown) { + shown = true; + put(c, { kind: 'deck', pose: deckTop, faceUp: false, depth: D.cards + 1 }); + } else hide(c, { pose: deckTop, faceUp: false, depth: D.cards }); + } + return { visible, loc }; + } + // the deck (top card only) + gs.deck.forEach((c, i) => { + const v = { kind: 'deck', pose: deckTop, faceUp: false, depth: D.cards + 1 }; + if (i === 0) put(c, v); else hide(c, { ...v, depth: D.cards }); + }); + const showing = this.view.showing; + const items = gs.show?.items ?? []; + const counted = (seat, kind) => items.some((it) => it.seat === seat && it.kind === kind && it !== showing); + const inShow = new Set(showing ? [...showing.ids, gs.starter.id] : []); + // starter on top of the deck + if (gs.starter && !inShow.has(gs.starter.id)) { + put(gs.starter, { kind: 'starter', pose: { ...deckTop, x: deckTop.x + 4, y: deckTop.y - 4, rot: 0.06 }, faceUp: true, depth: D.cards + 5 }); + } + // the crib + const cp = cribPose(gs.dealer); + const cribUp = counted(gs.dealer, 'crib'); + gs.crib.forEach((c, i) => { + if (inShow.has(c.id)) return; + const j = jitterFor(`crib-${c.id}`); + const pose = cribUp + ? { ...cp, x: cp.x + (i - 1.5) * 26, y: cp.y + Math.abs(i - 1.5) * 3, rot: (i - 1.5) * 0.08, s: cp.s * 0.82 } + : { ...cp, x: cp.x + j.x * 4, y: cp.y - i * 1.4 + j.y * 3, rot: j.rot * 5 }; + put(c, { kind: 'crib', pose, faceUp: cribUp, depth: D.cards + 1 + i * 0.01 }); + }); + // your hand (+ the pair going to the crib) + for (const h of this.humanPoses()) { + if (inShow.has(h.id)) continue; + put(h.card, { kind: 'hand', seat: 0, idx: h.idx, pose: h.pose, faceUp: true, depth: D.hand + h.idx * 0.01 }); + } + if (dp === 'discard' && gs.layaway[0] == null) { + this.pending.forEach((id, i) => { + const card = gs.hands[0].find((c) => c.id === id); + if (card) put(card, { kind: 'pending', seat: 0, idx: 4 + i, pose: this.pendingPose(i), faceUp: true, depth: D.hand + 1 + i * 0.01 }); + }); + } + // Murph's hand + let opp; + if (dp === 'play') opp = gs.play.hands[1]; + else if (dp === 'show') opp = gs.kept[1]; + else opp = gs.layaway[1] == null ? gs.hands[1] : gs.kept[1]; + const oppUp = dp === 'show' && counted(1, 'hand'); + const oppCards = oppUp ? opp.slice().sort(byRank) : opp; + oppCards.forEach((c, i) => { + if (inShow.has(c.id)) return; + put(c, { kind: 'hand', seat: 1, idx: i, pose: handPose(1, i, oppCards.length, 0, oppUp), faceUp: oppUp, depth: D.oppHand + i * 0.01 }); + }); + // the play row and the earlier series + if (dp === 'play') { + const P = gs.play; + const held = this.view.rowHold && P.series.length ? P.series[P.series.length - 1] : null; + const row = held ?? P.pile; + const prev = (held ? P.series.slice(0, -1) : P.series).flat(); + row.forEach((p, i) => put(cardFromId(p.id), { kind: 'row', seat: p.seat, idx: i, pose: rowPose(i), faceUp: true, depth: D.cards + 3 + i * 0.01 })); + prev.forEach((p, i) => put(cardFromId(p.id), { kind: 'prev', seat: p.seat, idx: i, pose: prevPose(i), faceUp: true, depth: D.cards + 0.6 + i * 0.01 })); + } + // the hand being counted + if (showing) { + const ids = [...showing.ids, gs.starter.id]; + ids.forEach((id, i) => { + const p = showPose(i, showing.ids.length); + const up = this.view.hi.has(id) ? 22 : 0; + put(cardFromId(id), { kind: 'show', idx: i, pose: { ...p, y: p.y - up }, faceUp: true, depth: D.cards + 6 + i * 0.01 }); + }); + } + return { visible, loc }; + } + + beforeLayout() { + this.layoutLegal = this.mode === 'play' ? this.legalIds() : null; + this.layoutCoach = this.mode === 'play' && this.settings.hints ? this.coachPlay()?.id ?? null : null; + } + + decorate(c, v) { + if (!v?.card) return; + let mark = '', markColor = '#ffd35a'; + let glow = false, tint = 0xffd35a, glowA = 1; + let dim = false; + const id = v.card.id; + if (v.kind === 'hand' && v.seat === 0) { + if (this.layoutLegal) { + if (!this.layoutLegal.has(id)) dim = true; + if (this.layoutCoach === id) mark = '★'; + } + if (this.hintIds.has(id)) { glow = true; tint = 0x7cf0a0; } + if (this.hoverId === id && !dim) { glow = true; tint = 0xffffff; glowA = 0.55; } + } else if (v.kind === 'pending') { + glow = true; tint = 0xffc861; glowA = 0.85; + } else if (v.kind === 'row') { + mark = '●'; markColor = SEAT_HEX[v.seat]; + } else if (v.kind === 'prev') { + dim = true; + } else if (v.kind === 'show') { + if (this.view.hi.has(id)) { glow = true; tint = 0xffe28a; } + if (id === this.gs.starter?.id) { mark = '✦'; markColor = '#f0d77a'; } + } else if (v.kind === 'starter') { + mark = '✦'; markColor = '#f0d77a'; + } + c.mark.setText(mark).setColor(markColor).setVisible(!!mark && v.faceUp); + c.chip.setVisible(false); + c.glow.setVisible(glow).setTint(tint).setAlpha(glowA); + c.faceImg.setTint(dim ? 0x8a8478 : 0xffffff); + if (v.kind === 'deck' && this.view.cutting && id === this.gs.deck[0]?.id) c.setVisible(false); + else if (!c.visible) c.setVisible(true); + } + + afterLayout() { + this.drawSlabs(); + const cp = cribPose(this.gs.dealer); + const showCrib = this.gs.crib.length || this.pending.length; + this.cribLabel.setPosition(cp.x, cp.y + 74 * cp.s).setText(showCrib ? (this.gs.dealer === 0 ? 'YOUR CRIB' : `${this.shortName(1, 10).toUpperCase()}'S CRIB`) : ''); + this.pendingLabel.setVisible(this.mode === 'discard' && this.pending.length > 0); + } + + // ── Plates ───────────────────────────────────────────────────────────────── + updatePlates() { + if (!this.gs || !this.board) return; + const gs = this.gs; + const g = this.plateG; + g.clear(); + const t = gs.rules.target; + const sk = skunkLines(gs.rules); + for (let s = 0; s < 2; s++) { + const pl = this.plates[s]; + if (!pl) continue; + const shown = this.board.shown[s]; + pl.scoreTxt.setText(String(shown)); + const role = gs.dealer === s ? 'dealer · crib' : 'pone'; + pl.infoTxt.setText(gs.rules.bestOf > 1 ? `${role} · games ${gs.games[s]}` : role); + pl.statusTxt.setText(`${t - shown} to go`).setColor(t - shown <= 10 ? AMBER : '#8ce99a'); + const active = (this.mode === 'play' && s === 0) || (this.mode === 'ai' && s === 1) || (this.mode === 'discard' && s === 0); + this.setPlateActive(s, active); + // progress bar with the skunk tick + const x0 = pl.tx, x1 = s === 0 ? pl.rx : pl.rx - 58, y = pl.y + 29; + g.fillStyle(0x0a0604, 0.7); + g.fillRoundedRect(x0, y - 5, x1 - x0, 10, 4); + g.fillStyle(SEAT_COLORS[s], 0.9); + g.fillRoundedRect(x0 + 1, y - 4, Math.max(4, (x1 - x0 - 2) * (shown / t)), 8, 3); + const sx = x0 + (x1 - x0) * ((sk.skunk - 1) / t); + g.lineStyle(2, 0xd9b45a, 0.9); + g.lineBetween(sx, y - 8, sx, y + 8); + } + } + + // ── Dock ─────────────────────────────────────────────────────────────────── + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const opp = this.shortName(1, 14); + const hint = { label: 'Hint (H)', act: () => this.flashHint() }; + const sheet = { label: 'Score sheet', act: () => this.openScorePad() }; + switch (this.mode) { + case 'cutdeal': this.setDock('Cutting for the deal — low card deals.'); return; + case 'deal': this.setDock(`${gs.dealer === 0 ? 'You deal' : `${opp} deals`} — six cards each.`); return; + case 'discard': { + const n = this.pending.length; + this.setDock(n === 2 ? 'Send these two to the crib?' : `Lay two cards away to ${gs.dealer === 0 ? 'your' : `${opp}'s`} crib (${2 - n} more).`, [ + { label: 'Lay away (Enter)', act: () => this.confirmDiscard(), enabled: n === 2, hot: n === 2 }, + hint, + { label: 'Take back', act: () => { this.pending = []; this.refreshAll(); }, enabled: n > 0 }, + sheet, + ]); + return; + } + case 'waitAI': this.setDock(`${opp} is choosing what to lay away…`, [sheet]); return; + case 'cut': + if (gs.dealer === 1) this.setDock('You\'re the pone — cut the deck: click it (or Space).', [{ label: 'Cut (Space)', act: () => this.doCut(0.5), hot: true }, sheet]); + else this.setDock(`${opp} cuts the deck…`); + return; + case 'cutting': this.setDock('The starter is turned…'); return; + case 'play': { + const P = gs.play; + this.setDock(`Your play — the count is ${P.count}.${P.said[1] ? ` ${opp} said "Go": play on if you can.` : ''}`, [hint, sheet]); + return; + } + case 'ai': this.setDock(`${opp} is thinking…${gs.play?.said[0] ? ' (you said "Go")' : ''}`, [sheet]); return; + case 'busy': this.setDock(''); return; + case 'show': this.setDock('The show — pone counts first, then the dealer, then the crib.', [{ label: 'Skip (Space)', act: () => { this.view.skip = true; } }]); return; + case 'roundOver': { + const h = gs.history[gs.history.length - 1]; + const line = h ? `This deal: you +${h.peg[0] + h.hand[0] + h.crib[0] + h.heels[0]}, ${opp} +${h.peg[1] + h.hand[1] + h.crib[1] + h.heels[1]}.` : ''; + this.setDock(`${line} The deal passes to ${gs.dealer === 0 ? opp : 'you'}.`, [ + { label: 'Next deal (Space)', act: () => this.nextDeal(), hot: true }, sheet, + ]); + return; + } + case 'gameOver': this.setDock(`${gs.winner === 0 ? 'You' : opp} pegged out!`); return; + default: this.setDock(''); + } + } + + // ── Hints ────────────────────────────────────────────────────────────────── + flashHint() { + const gs = this.gs; + if (!gs) return; + if (this.mode === 'discard') { + const C = this.coachDiscard(); + const b = C.best; + this.hintIds = new Set(b.discard.map((c) => c.id)); + this.layout({ duration: 120 }); + this.floatText({ x: CX, y: 780 }, `Lay away ${b.discard.map(cardName).join(' ')} — keep ${b.keep.map(cardName).join(' ')} (≈${b.hand.toFixed(1)}, crib ${b.crib >= 0 ? '+' : '−'}${Math.abs(b.crib).toFixed(1)})`, GREEN, { size: 21, ms: 3200, rise: 14 }); + return; + } + if (this.mode === 'play') { + const tip = this.coachPlay(); + if (!tip) return; + this.floatText({ x: CX, y: 780 }, tip.reason, GREEN, { size: 22, ms: 2800, rise: 14 }); + this.flashGlow(tip.id, 0x7cf0a0, { delay: 0, hold: 1100 }); + return; + } + if (this.mode === 'cut') this.floatText({ x: L.deck.x + 60, y: L.deck.y - 120 }, 'Click the deck to cut it', AMBER, { size: 22 }); + } + + notYet() { + if (['ai', 'waitAI', 'busy', 'cutting', 'show'].includes(this.mode)) this.floatText({ x: CX, y: 790 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); + } + + // ── Input ────────────────────────────────────────────────────────────────── + setupInput() { + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + } + + /** The card of yours (hand or the pair to the crib) under a point. */ + myCardAt(pt) { + if (!this.gs) return null; + if (this.mode === 'discard') { + for (let i = this.pending.length - 1; i >= 0; i--) if (inPose(pt, this.pendingPose(i))) return this.pending[i]; + } + const poses = this.humanPoses(); + for (let i = poses.length - 1; i >= 0; i--) if (inPose(pt, poses[i].pose)) return poses[i].id; + return null; + } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState || this.overUI(over)) return; + if (this.mode === 'show') { this.view.skip = true; return; } + if (this.mode === 'cut' && this.gs.dealer === 1 && inPose(pointer, this.deckTop(), 16)) { + const d = this.deckTop(); + this.doCut(Math.max(0, Math.min(1, 0.5 + (pointer.y - d.y) / (CARD_H * d.s)))); + return; + } + if (this.mode !== 'discard' && this.mode !== 'play') { + if (this.myCardAt(pointer)) this.notYet(); + return; + } + const id = this.myCardAt(pointer); + if (id) this.potentialDrag = { id, x: pointer.x, y: pointer.y }; + } + + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.x, dy = pointer.y - this.potentialDrag.y; + if (dx * dx + dy * dy > 81) this.startDrag(pointer); + return; + } + if (pointer.isDown || this.modal || !this.gs) return; + const active = this.mode === 'discard' || this.mode === 'play'; + const id = active ? this.myCardAt(pointer) : null; + if (id !== this.hoverId) { + this.hoverId = id; + this.layout({ duration: 110 }); + this.updatePreview(); + } + let cursor = id ? 'pointer' : 'default'; + if (this.mode === 'cut' && this.gs.dealer === 1 && inPose(pointer, this.deckTop(), 16)) cursor = 'pointer'; + this.input.setDefaultCursor(cursor); + } + + onPointerUp(pointer) { + if (this.dragState) { this.endDrag(pointer); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + this.clickCard(pd.id); + } + + clickCard(id) { + if (this.mode === 'discard') this.togglePending(id); + else if (this.mode === 'play') this.humanPlay(id); + else this.notYet(); + } + + startDrag(pointer) { + const pd = this.potentialDrag; + this.potentialDrag = null; + const c = this.sprites.get(pd.id); + if (!c) return; + c._tw?.stop(); + c._tw = null; + c.setDepth(D.drag); + this.dragState = { id: pd.id, offX: c.pose.x - pd.x, offY: c.pose.y - pd.y, sprite: c, pending: this.pending.includes(pd.id) }; + this.hoverId = null; + this.input.setDefaultCursor('grabbing'); + this.updateDrag(pointer); + } + + updateDrag(pointer) { + const ds = this.dragState; + const c = ds.sprite; + this.applyPose(c, { ...c.pose, x: pointer.x + ds.offX, y: pointer.y + ds.offY, rot: c.pose.rot * 0.8 }, 0.7); + } + + cancelDrag() { + if (!this.dragState) return; + this.dragState = null; + this.input.setDefaultCursor('default'); + if (this.gs) this.layout({ duration: 160 }); + } + + endDrag(pointer) { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + const y = pointer.y; + if (this.mode === 'discard') { + const cp = cribPose(this.gs.dealer); + const nearCrib = Math.hypot(pointer.x - cp.x, pointer.y - cp.y) < 200; + const toCribSide = nearCrib || y < 780 || pointer.x > 1130; + if (ds.pending ? !toCribSide : toCribSide) { this.togglePending(ds.id); return; } + } else if (this.mode === 'play' && y < 800) { + this.humanPlay(ds.id); + if (this.mode !== 'busy') this.layout({ duration: 160 }); + return; + } + this.layout({ duration: 160 }); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (!this.modal) this.openPause(); + return; + } + if (this.modal) { if (e.code === 'Enter') this.modal.onEnter?.(); return; } + if (this.dragState || !this.gs) return; + const k = e.key?.toLowerCase(); + if (k === 'h') { this.flashHint(); return; } + if (e.code === 'Space') { + e.preventDefault?.(); + if (this.mode === 'cut' && this.gs.dealer === 1) this.doCut(0.5); + else if (this.mode === 'show') this.view.skip = true; + else if (this.mode === 'roundOver') this.nextDeal(); + return; + } + if (e.code === 'Enter') { + if (this.mode === 'discard') this.confirmDiscard(); + else if (this.mode === 'roundOver') this.nextDeal(); + return; + } + if (e.code === 'Backspace' && this.mode === 'discard' && this.pending.length) { + this.togglePending(this.pending[this.pending.length - 1]); + return; + } + const digit = /^Digit([1-6])$/.exec(e.code) ?? /^Numpad([1-6])$/.exec(e.code); + if (digit && (this.mode === 'discard' || this.mode === 'play')) { + // lay-away: 1–6 always name the six dealt cards (left to right, by rank) + const cards = this.mode === 'discard' ? this.gs.hands[0].slice().sort(byRank) : this.humanCards(); + const card = cards[Number(digit[1]) - 1]; + if (card) this.clickCard(card.id); + } + } + + // ── Panels ───────────────────────────────────────────────────────────────── + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); openSettings(this); } }, + { label: 'Score sheet', act: () => { this.closeModal(); this.openScorePad(); } }, + { label: 'Your record', act: () => { this.closeModal(); openLifetime(this); } }, + { label: 'How to play', act: () => { this.closeModal(); openRules(this); } }, + { label: 'New game', ghost: true, act: () => this.confirm('Start a new game?', 'This game will be thrown out.', 'New game', () => { this.clearSave(); this.restart(); }) }, + { label: 'Leave table', ghost: true, act: () => this.onLeave() }, + ]); + } + + onLeave() { + if (!this.gs || this.ended) { this.scene.start('GameMenu'); return; } + this.confirm('Leave the table?', 'Your game is saved at each lay-away and every turn of the play — you can resume it next time.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay' }); + } + + restart() { + this.closeModal(); + this.scene.restart({ ...this.initData }); + } + + openScorePad({ back = null } = {}) { + const gs = this.gs; + if (!gs) return; + const opp = this.shortName(1, 14); + const rows = [0, 1].map((s) => ({ + seat: s, color: SEAT_COLORS[s], name: s === 0 ? 'You' : opp, + cells: gs.history.map((h) => { + const tot = h.peg[s] + h.hand[s] + h.crib[s] + h.heels[s]; + const bits = [`p${h.peg[s]}`, `h${h.hand[s]}`]; + if (h.dealer === s) bits.push(`c${h.crib[s]}`); + return { text: `+${tot}`, color: tot ? '#1e7a3b' : '#8a8270', mark: bits.join(' '), markColor: h.dealer === s ? '#5a3a8a' : '#6c6450' }; + }), + extra: gs.rules.bestOf > 1 ? String(gs.games[s]) : null, + total: gs.scores[s], + totalColor: gs.scores[s] >= gs.scores[1 - s] && gs.scores[s] > 0 ? '#1e7a3b' : '#22201a', + circled: gs.winner === s, + })); + const close = () => { this.closeModal(); back?.(); }; + this.openScorePadModal({ + title: `Score sheet — first to ${gs.rules.target}${gs.rules.bestOf > 1 ? ` · game ${gs.gameNo}` : ''}`, + sub: 'Each deal: total, then p = pegging · h = hand · c = crib (purple: that player dealt)', + columns: gs.history.map((_, i) => `D${i + 1}`), + rows, extraLabel: gs.rules.bestOf > 1 ? 'Games' : null, + buttons: [{ label: back ? 'Back' : 'Back to the table', act: close }], + readOnly: true, + }); + if (this.modal) this.modal.onEscape = close; + } } + diff --git a/src/games/cribbage/CribbageLogic.js b/src/games/cribbage/CribbageLogic.js index 82ce47f..3d1d382 100644 --- a/src/games/cribbage/CribbageLogic.js +++ b/src/games/cribbage/CribbageLogic.js @@ -1,251 +1,379 @@ -// Cribbage — pure, deterministic game engine. No Phaser, no timers. The scene -// and the headless harness both drive it through the same granular methods so -// behaviour is identical on screen and under test. +// Cribbage — pure rules engine. No Phaser, no timers. +// +// State is plain JSON (autosaved). Every action returns a NEW state, or the +// SAME object when the move is illegal — callers test `next === gs`. The +// scene, the AI and tools/verifyCribbage.js all drive it. +// +// Flow of one deal +// discard both players lay two cards away to the dealer's crib +// cut the pone cuts; the starter is turned (a jack: "his heels", +2 dealer) +// play the pegging: alternate cards, count ≤ 31; 15s / 31s / pairs / runs +// score; "go" when you can't play; 1 for the go / last card +// show pone's hand, dealer's hand, then the crib (stops the moment +// someone reaches the target) +// roundOver → nextRound (the deal passes) +// A game ends the instant a player pegs out (gameOver). In match play +// (rules.bestOf > 1) nextGame() starts the next game: the loser deals first. +// +// Pegs: the front peg is scores[seat]; the back peg is back[seat] (-1 = the +// second start hole). Every score moves the back peg past the front one. -import { Deck, WIN_SCORE, HAND_SIZE, PLAY_LIMIT, cribValue, runRank } from './CribbageData.js'; +import { + DEFAULT_RULES, HAND_SIZE, PLAY_LIMIT, fullDeck, cardFromId, scoreHand, scoreHandDetailed, scorePlay, + skunkLines, gamesNeeded, +} from './CribbageData.js'; -// ── Standalone scoring (also used by the AI) ──────────────────────────────── +export const VERSION = 1; -function scoreFifteens(cards) { - let count = 0; - const n = cards.length; - for (let mask = 1; mask < (1 << n); mask++) { - let sum = 0; - for (let k = 0; k < n; k++) if (mask & (1 << k)) sum += cribValue(cards[k]); - if (sum === 15) count++; - } - return count * 2; +const clone = (o) => (typeof structuredClone === 'function' ? structuredClone(o) : JSON.parse(JSON.stringify(o))); + +// mulberry32 on a state-held integer, so a saved game replays the same shuffles +function rand(gs) { + gs.rng = (gs.rng + 0x6d2b79f5) >>> 0; + let t = gs.rng; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; } -function scorePairs(cards) { - let pts = 0; - for (let a = 0; a < cards.length; a++) - for (let b = a + 1; b < cards.length; b++) - if (cards[a].rank === cards[b].rank) pts += 2; +function shuffle(gs, arr) { + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(rand(gs) * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; +} + +export const emptyStats = () => ({ + peg: 0, hand: 0, crib: 0, heels: 0, + hands: 0, cribs: 0, best: 0, bestIds: null, bestKind: null, + twentyNines: 0, nineteens: 0, gos: 0, thirtyOnes: 0, fifteens: 0, +}); +const emptyDeal = () => ({ peg: [0, 0], hand: [0, 0], crib: [0, 0], heels: [0, 0] }); + +// ── Setup ──────────────────────────────────────────────────────────────────── +/** + * A new game (or match). The first dealer is found by cutting: each player + * cuts a card, low card deals (ace low), ties cut again — recorded in + * gs.cuts for the scene to replay. Pass `dealer` to skip the cut. + */ +export function createGame({ rules = {}, seed = (Date.now() >>> 0), dealer = null } = {}) { + const gs = { + version: VERSION, + rules: { ...DEFAULT_RULES, ...rules }, + rng: seed >>> 0, + scores: [0, 0], + back: [-1, -1], + games: [0, 0], + gameNo: 1, + pastGames: [], + stats: [emptyStats(), emptyStats()], + history: [], + round: 0, + dealer: 0, + winner: null, + matchWinner: null, + gameResult: null, + cuts: [], + log: [], + }; + if (dealer == null) { + for (;;) { + const deck = shuffle(gs, fullDeck()); + const a = deck[Math.floor(rand(gs) * 20) + 4]; + const rest = deck.filter((c) => c.id !== a.id); + const b = rest[Math.floor(rand(gs) * 20) + 20]; + gs.cuts.push([a.id, b.id]); + if (a.run !== b.run) { gs.dealer = a.run < b.run ? 0 : 1; break; } + } + } else gs.dealer = dealer; + return deal(gs); +} + +/** Deal a fresh hand onto `gs` (mutates the given clone). */ +function deal(gs) { + gs.round++; + const cards = shuffle(gs, fullDeck()); + const pone = 1 - gs.dealer; + gs.hands = [[], []]; + let k = 0; + for (let i = 0; i < HAND_SIZE; i++) { gs.hands[pone].push(cards[k++]); gs.hands[gs.dealer].push(cards[k++]); } + gs.deck = cards.slice(k); + gs.crib = []; + gs.layaway = [null, null]; // ids each seat laid away (its own knowledge) + gs.kept = [null, null]; // the four cards each seat kept (for the show) + gs.starter = null; + gs.phase = 'discard'; + gs.play = null; + gs.show = null; + gs.cur = emptyDeal(); + gs.log = [{ kind: 'deal', round: gs.round, dealer: gs.dealer }]; + return gs; +} + +export function nextRound(gs) { + if (gs.phase !== 'roundOver') return gs; + const g = clone(gs); + g.dealer = 1 - g.dealer; + return deal(g); +} + +/** After a game in an unfinished match: fresh pegs, the loser deals first. */ +export function nextGame(gs) { + if (gs.phase !== 'gameOver' || gs.matchWinner != null) return gs; + const g = clone(gs); + g.gameNo++; + g.scores = [0, 0]; + g.back = [-1, -1]; + g.stats = [emptyStats(), emptyStats()]; + g.history = []; + g.round = 0; + g.dealer = 1 - g.winner; + g.winner = null; + g.gameResult = null; + g.cuts = []; + return deal(g); +} + +// ── Queries ────────────────────────────────────────────────────────────────── +export const pone = (gs) => 1 - gs.dealer; +export const isGameOver = (gs) => gs.phase === 'gameOver'; +export const cardsOf = (gs, seat) => (gs.phase === 'play' ? gs.play.hands[seat] : gs.kept[seat] ?? gs.hands[seat]); + +/** Cards `seat` may lay on the pile now (empty when it isn't their turn). */ +export function legalPlays(gs, seat) { + if (gs.phase !== 'play' || gs.play.next !== seat) return []; + return gs.play.hands[seat].filter((c) => gs.play.count + c.val <= PLAY_LIMIT); +} + +/** Who must act: the seat to lay away / play, or null. */ +export function actor(gs) { + if (gs.phase === 'discard') return gs.layaway[0] == null ? 0 : gs.layaway[1] == null ? 1 : null; + if (gs.phase === 'play') return gs.play.next; + return null; +} + +export const pileCards = (gs) => (gs.play ? gs.play.pile.map((p) => cardFromId(p.id)) : []); + +// ── Points ─────────────────────────────────────────────────────────────────── +/** Peg `pts` for `seat` (clamped at the target; latches the winner). */ +function addPoints(g, seat, pts, why, extra = {}) { + if (pts <= 0 || g.winner != null) return 0; + const from = g.scores[seat]; + const to = Math.min(g.rules.target, from + pts); + g.back[seat] = from; + g.scores[seat] = to; + const cat = why === 'hand' || why === 'crib' || why === 'heels' ? why : 'peg'; + g.cur[cat][seat] += to - from; + g.stats[seat][cat] += to - from; + g.log.push({ kind: 'peg', seat, pts, from, to, why, ...extra }); + if (to >= g.rules.target) endGame(g, seat); return pts; } -function scoreRuns(cards) { - const cnt = new Map(); - for (const c of cards) { const r = runRank(c); cnt.set(r, (cnt.get(r) || 0) + 1); } - const ranks = [...cnt.keys()].sort((a, b) => a - b); - let total = 0, i = 0; - while (i < ranks.length) { - let j = i, mult = cnt.get(ranks[i]); - while (j + 1 < ranks.length && ranks[j + 1] === ranks[j] + 1) { j++; mult *= cnt.get(ranks[j]); } - const len = j - i + 1; - if (len >= 3) total += len * mult; - i = j + 1; - } - return total; +function endGame(g, winner) { + g.winner = winner; + g.phase = 'gameOver'; + pushHistory(g); + const loser = 1 - winner; + const lines = skunkLines(g.rules); + const ls = g.scores[loser]; + const skunk = ls < lines.skunk ? (lines.double != null && ls < lines.double ? 2 : 1) : 0; + const gamePts = g.rules.bestOf > 1 ? 1 + skunk : 1; + g.games[winner] += gamePts; + g.gameResult = { winner, scores: g.scores.slice(), skunk, gamePts }; + g.pastGames.push({ ...g.gameResult, gameNo: g.gameNo }); + if (g.games[winner] >= gamesNeeded(g.rules.bestOf)) g.matchWinner = winner; + g.log.push({ kind: 'win', seat: winner, skunk }); } -function scoreFlush(hand4, starter, isCrib) { - const s0 = hand4[0].suit; - const all4 = hand4.every((c) => c.suit === s0); - if (!all4) return 0; - if (starter && starter.suit === s0) return 5; - return isCrib ? 0 : 4; // a 4-card flush never counts in the crib +function pushHistory(g) { + if (g.history.some((h) => h.round === g.round)) return; + g.history.push({ round: g.round, dealer: g.dealer, ...clone(g.cur), after: g.scores.slice() }); } -function scoreNobs(hand4, starter) { - if (!starter) return 0; - return hand4.some((c) => c.rank === 'J' && c.suit === starter.suit) ? 1 : 0; +// ── The lay-away ───────────────────────────────────────────────────────────── +/** `seat` lays two of its six cards away to the crib. */ +export function discard(gs, seat, ids) { + if (gs.phase !== 'discard' || gs.layaway[seat] != null) return gs; + if (!Array.isArray(ids) || ids.length !== 2 || ids[0] === ids[1]) return gs; + const hand = gs.hands[seat]; + if (!ids.every((id) => hand.some((c) => c.id === id))) return gs; + const g = clone(gs); + g.layaway[seat] = ids.slice(); + g.kept[seat] = g.hands[seat].filter((c) => !ids.includes(c.id)); + g.crib.push(...g.hands[seat].filter((c) => ids.includes(c.id))); + g.log.push({ kind: 'discard', seat, ids: ids.slice() }); + if (g.layaway[0] != null && g.layaway[1] != null) g.phase = 'cut'; + return g; } /** - * Score a 4-card hand (or crib) with the cut starter. - * @returns {{total, fifteens, pairs, runs, flush, nobs}} + * The pone cuts and the dealer turns the starter. `depth` (0..1, optional) + * is where the cut was made — cosmetic, the card is still random. */ -export function scoreHand(hand4, starter, isCrib = false) { - const all5 = starter ? [...hand4, starter] : [...hand4]; - const fifteens = scoreFifteens(all5); - const pairs = scorePairs(all5); - const runs = scoreRuns(all5); - const flush = scoreFlush(hand4, starter, isCrib); - const nobs = scoreNobs(hand4, starter); - return { total: fifteens + pairs + runs + flush + nobs, fifteens, pairs, runs, flush, nobs }; +export function cutStarter(gs, depth = null) { + if (gs.phase !== 'cut') return gs; + const g = clone(gs); + const lo = 4, hi = g.deck.length - 4; + const i = depth == null + ? lo + Math.floor(rand(g) * (hi - lo)) + : Math.max(lo, Math.min(hi - 1, Math.floor(lo + depth * (hi - lo) + (rand(g) - 0.5) * 6))); + const starter = g.deck.splice(i, 1)[0]; + g.starter = starter; + g.log.push({ kind: 'cut', starter: starter.id, depth: i / g.deck.length }); + g.phase = 'play'; + g.play = { + hands: [g.kept[0].slice(), g.kept[1].slice()], + pile: [], // { id, seat } since the last reset + count: 0, + next: pone(g), + last: null, + said: [false, false], // "go" already announced in this series + series: [], // completed series: [[{ id, seat }…]…] + }; + if (starter.rank === 'J') { + addPoints(g, g.dealer, 2, 'heels'); + if (g.phase === 'gameOver') return g; + } + settle(g); + return g; +} + +// ── The play ───────────────────────────────────────────────────────────────── +/** `seat` lays card `id` on the pile. */ +export function play(gs, seat, id) { + if (gs.phase !== 'play' || gs.play.next !== seat) return gs; + const card = gs.play.hands[seat].find((c) => c.id === id); + if (!card || gs.play.count + card.val > PLAY_LIMIT) return gs; + const g = clone(gs); + const P = g.play; + P.hands[seat] = P.hands[seat].filter((c) => c.id !== id); + P.pile.push({ id, seat }); + P.count += card.val; + P.last = seat; + const sc = scorePlay(P.pile.map((p) => cardFromId(p.id))); + g.log.push({ kind: 'play', seat, id, count: P.count, pts: sc.points, reasons: sc.reasons, scoreIds: sc.scoreIds }); + if (sc.reasons.includes('15')) g.stats[seat].fifteens++; + if (sc.reasons.includes('31')) g.stats[seat].thirtyOnes++; + if (sc.points) addPoints(g, seat, sc.points, 'play', { reasons: sc.reasons }); + if (g.phase === 'gameOver') return g; + if (P.count === PLAY_LIMIT) endSeries(g); + P.next = 1 - seat; + settle(g); + return g; +} + +function endSeries(g) { + const P = g.play; + if (P.pile.length) P.series.push(P.pile); + P.pile = []; + P.count = 0; + P.said = [false, false]; + g.log.push({ kind: 'reset' }); } /** - * Score the just-played card given the pile since the last reset. - * @returns {{points, reasons:[], count}} + * Resolve every forced step until somebody has a legal card (or the play is + * over): "go"s, the point for the go / last card, and the count resetting. */ -export function scorePlay(pile) { - const reasons = []; - let points = 0; - const count = pile.reduce((s, c) => s + cribValue(c), 0); - - if (count === 15) { points += 2; reasons.push('15'); } - if (count === 31) { points += 2; reasons.push('31'); } - - // Pairs / pair-royal: trailing equal ranks. - const last = pile[pile.length - 1]; - let k = 1; - for (let i = pile.length - 2; i >= 0 && pile[i].rank === last.rank; i--) k++; - if (k >= 2) { points += { 2: 2, 3: 6, 4: 12 }[k]; reasons.push(k === 2 ? 'pair' : k === 3 ? 'pair-royal' : 'double-pair-royal'); } - - // Runs: longest suffix of the pile that forms consecutive ranks (any order). - for (let len = pile.length; len >= 3; len--) { - const rr = pile.slice(pile.length - len).map(runRank).sort((a, b) => a - b); - let ok = true; - for (let i = 1; i < rr.length; i++) if (rr[i] !== rr[i - 1] + 1) { ok = false; break; } - if (ok) { points += len; reasons.push(`run${len}`); break; } +function settle(g) { + for (let guard = 0; guard < 40; guard++) { + if (g.phase !== 'play') return; + const P = g.play; + const p = P.next, o = 1 - p; + const can = (s) => P.hands[s].some((c) => P.count + c.val <= PLAY_LIMIT); + if (can(p)) return; + if (can(o)) { + // p is stuck: say "go" (a player who is simply out of cards says nothing) + if (P.hands[p].length && !P.said[p]) { + P.said[p] = true; + g.stats[p].gos++; + g.log.push({ kind: 'go', seat: p, count: P.count }); + } + P.next = o; + continue; + } + // nobody can play: the stuck player says "go", the last to play pegs 1 + // for it (or for the last card), then the count resets + if (P.hands[p].length && !P.said[p]) { + P.said[p] = true; + g.stats[p].gos++; + g.log.push({ kind: 'go', seat: p, count: P.count }); + } + const out = !P.hands[0].length && !P.hands[1].length; + if (P.pile.length && P.count < PLAY_LIMIT && P.last != null) { + addPoints(g, P.last, 1, out ? 'last' : 'go', { reasons: [out ? 'last' : 'go'] }); + if (g.phase === 'gameOver') return; + } + endSeries(g); + if (out) { beginShow(g); return; } + P.next = 1 - P.last; } - - return { points, reasons, count }; + throw new Error('cribbage settle loop'); } -// ── Game engine ───────────────────────────────────────────────────────────── - -export class CribbageLogic { - /** @param {{rng?:()=>number, startDealer?:number}} opts */ - constructor(opts = {}) { - this.rng = opts.rng || Math.random; - this.win = WIN_SCORE; - this.dealer = opts.startDealer ?? Math.floor(this.rng() * 2); // 0=human, 1=ai - this.scores = [0, 0]; - this.prev = [0, 0]; // previous front-peg position (for leapfrog rendering) - this.winner = null; - this.phase = 'idle'; // idle | discard | play | show | roundover | gameover - } - - get nonDealer() { return 1 - this.dealer; } - - /** Award points; clamps at the win line and latches the winner. */ - addPoints(player, pts) { - if (pts <= 0 || this.winner !== null) return 0; - this.prev[player] = this.scores[player]; - this.scores[player] = Math.min(this.win, this.scores[player] + pts); - if (this.scores[player] >= this.win) { this.winner = player; this.phase = 'gameover'; } - return pts; - } - - /** Shuffle, deal six to each, ready for discards. */ - newDeal() { - const deck = new Deck(); - // Fisher-Yates with the injected rng (Deck.shuffle uses Math.random directly). - const a = deck.cards; - for (let i = a.length - 1; i > 0; i--) { - const j = Math.floor(this.rng() * (i + 1)); - [a[i], a[j]] = [a[j], a[i]]; - } - this.deck = deck; - this.hands = [deck.deal(HAND_SIZE), deck.deal(HAND_SIZE)]; // working 6-card hands - this.keep = [null, null]; // 4-card kept hands (set at discard) - this.crib = []; - this.starter = null; - this.toPlay = [null, null]; // unplayed cards during the play - this.pile = []; // cards since last reset - this.count = 0; - this.lastPlayer = null; - this.said = [false, false]; // "go" declared since last reset - this.turn = this.nonDealer; // non-dealer always leads the play - this.phase = 'discard'; - return { dealer: this.dealer, hands: this.hands }; - } - - /** Lay two cards from a player into the crib. Returns true once both have. */ - discard(player, cards) { - const set = new Set(cards.map((c) => c.key)); - this.keep[player] = this.hands[player].filter((c) => !set.has(c.key)); - this.crib.push(...this.hands[player].filter((c) => set.has(c.key))); - return this.keep[0] && this.keep[1]; - } - - /** Cut the starter from the rest of the deck. Handles "his heels" (+2). */ - cut() { - const i = Math.floor(this.rng() * this.deck.remaining); - this.starter = this.deck.cards[i]; - this.toPlay = [this.keep[0].slice(), this.keep[1].slice()]; - this.phase = 'play'; - let heels = 0; - if (this.starter.rank === 'J') heels = this.addPoints(this.dealer, 2); - return { starter: this.starter, heels, dealer: this.dealer }; - } - - // ── The play (pegging) ──────────────────────────────────────────────────── - legalPlays(player) { - return this.toPlay[player].filter((c) => this.count + cribValue(c) <= PLAY_LIMIT); - } - - playEnded() { return this.toPlay[0].length === 0 && this.toPlay[1].length === 0; } - - /** Play one card. Advances the turn, scores pegs, handles 31/last-card resets. */ - play(player, card) { - this.toPlay[player] = this.toPlay[player].filter((c) => c.key !== card.key); - this.pile.push(card); - this.count += cribValue(card); - this.lastPlayer = player; - - const sc = scorePlay(this.pile); - const events = []; - if (sc.points) { this.addPoints(player, sc.points); events.push({ player, points: sc.points, reasons: sc.reasons }); } - - const ended = this.playEnded(); - if (this.count === PLAY_LIMIT) { - this._resetPile(); - } else if (ended) { - // Last card of the deal pegs 1 (unless it just made 31, handled above). - const got = this.addPoints(player, 1); - if (got) events.push({ player, points: 1, reasons: ['last-card'] }); - } - this.turn = 1 - player; - - if (this.playEnded()) this.phase = 'show'; - return { events, count: this.count, ended: this.playEnded(), pile: this.pile.slice() }; - } - - /** Current player cannot play. Passes or, if neither can, pegs the go. */ - go(player) { - const opp = 1 - player; - this.said[player] = true; - // Opponent can still play → simply pass the turn to them. - if (this.legalPlays(opp).length > 0 && this.toPlay[opp].length > 0) { - this.turn = opp; - return { pass: true }; - } - // Neither can play: last player to lay a card pegs 1 for the go. - const events = []; - if (this.lastPlayer != null) { - const got = this.addPoints(this.lastPlayer, 1); - if (got) events.push({ player: this.lastPlayer, points: 1, reasons: ['go'] }); - } - const leader = this.lastPlayer != null ? 1 - this.lastPlayer : opp; - this._resetPile(); - this.turn = leader; - if (this.playEnded()) this.phase = 'show'; - return { goPoint: true, events, reset: true }; - } - - _resetPile() { - this.pile = []; - this.count = 0; - this.said = [false, false]; - } - - // ── The show ──────────────────────────────────────────────────────────── - /** Count non-dealer hand, dealer hand, then the crib (dealer's). */ - show() { - const results = []; - const order = [ - { player: this.nonDealer, cards: this.keep[this.nonDealer], type: 'hand', isCrib: false }, - { player: this.dealer, cards: this.keep[this.dealer], type: 'hand', isCrib: false }, - { player: this.dealer, cards: this.crib, type: 'crib', isCrib: true }, - ]; - for (const o of order) { - const r = scoreHand(o.cards, this.starter, o.isCrib); - this.addPoints(o.player, r.total); - results.push({ ...o, score: r }); - if (this.winner !== null) break; - } - if (this.phase !== 'gameover') this.phase = 'roundover'; - return results; - } - - /** Pass the deal and prepare the next hand. */ - nextRound() { - this.dealer = 1 - this.dealer; - return this.newDeal(); - } +// ── The show ───────────────────────────────────────────────────────────────── +function beginShow(g) { + g.phase = 'show'; + const d = g.dealer, p = pone(g); + g.show = { + order: [{ seat: p, kind: 'hand' }, { seat: d, kind: 'hand' }, { seat: d, kind: 'crib' }], + i: 0, + items: [], + }; + g.log.push({ kind: 'show' }); } + +/** Count the next hand of the show (pone, dealer, crib). */ +export function showStep(gs) { + if (gs.phase !== 'show') return gs; + const g = clone(gs); + const S = g.show; + const o = S.order[S.i]; + const cards = o.kind === 'crib' ? g.crib : g.kept[o.seat]; + const det = scoreHandDetailed(cards, g.starter, o.kind === 'crib'); + const item = { seat: o.seat, kind: o.kind, ids: cards.map((c) => c.id), combos: det.combos, total: det.total }; + S.items.push(item); + S.i++; + const st = g.stats[o.seat]; + if (o.kind === 'crib') st.cribs++; else st.hands++; + if (det.total > st.best) { st.best = det.total; st.bestIds = [...item.ids, g.starter.id]; st.bestKind = o.kind; } + if (det.total === 29) st.twentyNines++; + if (det.total === 0) st.nineteens++; + g.log.push({ kind: 'count', ...item }); + addPoints(g, o.seat, det.total, o.kind); + if (g.phase === 'gameOver') return g; + if (S.i >= S.order.length) { + g.phase = 'roundOver'; + pushHistory(g); + g.log.push({ kind: 'roundOver' }); + } + return g; +} + +/** Score every remaining show step at once (headless play). */ +export function finishShow(gs) { + let g = gs; + while (g.phase === 'show') g = showStep(g); + return g; +} + +// ── Save validity ──────────────────────────────────────────────────────────── +export function cardsInPlay(gs) { + const ids = new Set(); + const add = (c) => ids.add(c.id ?? c); + gs.deck.forEach(add); + if (gs.starter) add(gs.starter); + gs.crib.forEach(add); + for (let s = 0; s < 2; s++) (gs.kept[s] ?? gs.hands[s]).forEach(add); + if (gs.phase === 'discard') for (let s = 0; s < 2; s++) gs.hands[s].forEach(add); + return ids.size; +} + +export function isValidSave(gs) { + return !!gs && gs.version === VERSION && Array.isArray(gs.hands) && Array.isArray(gs.scores) + && ['discard', 'play'].includes(gs.phase) && gs.winner == null && cardsInPlay(gs) === 52; +} + +export { scoreHand, scoreHandDetailed, scorePlay }; diff --git a/src/games/cribbage/CribbageShow.js b/src/games/cribbage/CribbageShow.js new file mode 100644 index 0000000..f2bdc1a --- /dev/null +++ b/src/games/cribbage/CribbageShow.js @@ -0,0 +1,71 @@ +// Cribbage — the show's caption: a leather plaque under the cards being +// counted. The title says whose hand it is; the calls build up one at a time +// ("Fifteen 2, fifteen 4, a pair is 6…") while a big running total ticks up +// at the right. + +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; +import { COLORS } from '../../config.js'; + +const W = 1180, H = 150; + +export class ShowCaption { + constructor(scene, { x, y, depth }) { + this.scene = scene; + this.x = x; + this.y = y; + const key = ensureLeatherPanel(scene, 'crib-caption', W, H, { radius: 18 }); + this.bg = scene.add.image(x, y, key).setDepth(depth); + this.title = scene.add.text(x - W / 2 + 34, y - H / 2 + 26, '', { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.goldHex, + }).setOrigin(0, 0.5).setDepth(depth + 1); + this.calls = scene.add.text(x - W / 2 + 34, y + 14, '', { + fontFamily: 'Righteous', fontSize: '25px', color: COLORS.textHex, wordWrap: { width: W - 260 }, lineSpacing: 4, + }).setOrigin(0, 0.5).setDepth(depth + 1); + this.totalCap = scene.add.text(x + W / 2 - 104, y - H / 2 + 26, 'POINTS', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(depth + 1); + this.total = scene.add.text(x + W / 2 - 104, y + 14, '', { + fontFamily: 'Righteous', fontSize: '64px', color: '#f0d77a', stroke: '#1a0e06', strokeThickness: 6, + }).setOrigin(0.5).setDepth(depth + 1); + this.objs = [this.bg, this.title, this.calls, this.totalCap, this.total]; + this.said = []; + this.setVisible(false); + } + + setVisible(on) { + for (const o of this.objs) o.setVisible(on); + } + + open(title, color = COLORS.goldHex) { + this.scene.tweens.killTweensOf(this.objs); + this.said = []; + this.title.setText(title).setColor(color); + this.calls.setText('').setColor(COLORS.textHex); + this.total.setText('0').setColor('#f0d77a').setScale(1); + this.setVisible(true); + for (const o of this.objs) o.setAlpha(0); + this.scene.tweens.add({ targets: this.objs, alpha: 1, duration: 180 }); + } + + /** Add one call ("fifteen 4") and set the running total. */ + call(say, running) { + this.said.push(say); + this.calls.setText(this.said.join(', ')); + this.total.setText(String(running)); + this.scene.tweens.killTweensOf(this.total); + this.total.setScale(1.25); + this.scene.tweens.add({ targets: this.total, scale: 1, duration: 220, ease: 'Back.easeOut' }); + } + + /** The final word: "…and that's 12." / "Nineteen — not a sausage." */ + finish(total, note = null) { + if (!this.said.length) this.calls.setText(note ?? 'Nothing to count.').setColor(COLORS.mutedHex); + else if (note) this.calls.setText(`${this.said.join(', ')} — ${note}`); + this.total.setText(String(total)); + } + + hide(ms = 200) { + this.scene.tweens.killTweensOf(this.objs); + this.scene.tweens.add({ targets: this.objs, alpha: 0, duration: ms, onComplete: () => this.setVisible(false) }); + } +} diff --git a/src/games/cribbage/CribbageTable.js b/src/games/cribbage/CribbageTable.js new file mode 100644 index 0000000..18f059f --- /dev/null +++ b/src/games/cribbage/CribbageTable.js @@ -0,0 +1,194 @@ +// Cribbage table layout — Phaser-free so tools/verifyCribbage.js can test it. +// +// "The Keeper's Cottage": a scrubbed oak kitchen table, the long walnut board +// lying across the far side (Murph sits behind it), the deck · the play row · +// the count gauge · the crib across the middle, your hand at the bottom. +// +// The board is defined in board space (bx across 0..1, by far→near 0..1), +// mapped onto the table (u, v) and pushed through the table projection, so +// holes, pegs and the baked board art all agree. + +import { + makeTable, CARD_W, CARD_H, fanPose, fanPoint, HUMAN_PLATE, PLATE, +} from '../../ui/cardtable/TableGeometry.js'; + +export const VIEW = { cx: 960, yFar: 150, yNear: 1010, sFar: 0.74, halfW: 900, squash: 0.9 }; +export const T = makeTable(VIEW, { shape: 'rect', corner: 0.17, feltK: 0.94, faceH: 38 }); +export const SQ = VIEW.squash; + +// you: lighthouse red · Murph: harbour blue +export const SEAT_COLORS = [0xd8473a, 0x4f9bd8]; +export const SEAT_HEX = ['#ff7a68', '#7cc0f0']; + +// ── The board ──────────────────────────────────────────────────────────────── +export const BOARD = { u0: -0.86, u1: 0.86, v0: 0.072, v1: 0.352 }; +const M_LEFT = 3.4; // hole units left of hole 1 (start holes / game holes) +const M_RIGHT = 2.6; // hole units right of the last column (finish / game holes) +const GROUP_GAP = 0.6; // extra units between groups of five +const EDGE_Y = 0.075; // board-space margin above the first / below the last street + +/** Track shape for a target: 121 → 3 streets × 40; 61 → 2 streets × 30. */ +export function trackSpec(target) { + return target === 61 ? { streets: 2, per: 30 } : { streets: 3, per: 40 }; +} + +/** Board space (bx across, by far → near, both 0..1) → screen {x, y, s}. */ +export function boardPoint(bx, by) { + const u = BOARD.u0 + bx * (BOARD.u1 - BOARD.u0); + const v = BOARD.v0 + by * (BOARD.v1 - BOARD.v0); + return T.P.project(u, v); +} +const project = boardPoint; + +/** Engraved skunk lines for a board: [{ line, label }] (the loser below `line`). */ +export function skunkLinesFor(target, doubleSkunk = false) { + if (target === 61) return [{ line: 31, label: 'S' }]; + return doubleSkunk ? [{ line: 91, label: 'S' }, { line: 61, label: 'SS' }] : [{ line: 91, label: 'S' }]; +} + +const geoCache = new Map(); + +/** + * Board geometry for a target: + * holes[seat][n] screen {x, y, s} for n = 0..target (0 = start hole) + * alt[seat] the second start hole (the back peg's home, "-1") + * gameHoles[seat] up to four match holes + * skunk(line) [{ a, b }] per seat — the gap between hole line-1 and line + * numbers [{ n, x, y, s }] engraved every 10 + * holeR base hole radius at s = 1 + */ +export function boardGeometry(target = 121) { + if (geoCache.has(target)) return geoCache.get(target); + const { streets, per } = trackSpec(target); + const groups = per / 5; + const units = M_LEFT + (per - 1) + (groups - 1) * GROUP_GAP + M_RIGHT; + const colBx = (i) => (M_LEFT + i + Math.floor(i / 5) * GROUP_GAP) / units; + const lastBx = colBx(per - 1); + const bandH = (1 - EDGE_Y * 2) / streets; + const rowBy = (street, seat) => EDGE_Y + street * bandH + bandH * (seat === 0 ? 0.7 : 0.3); + const startA = (M_LEFT - 1.25) / units, startB = (M_LEFT - 2.3) / units; + const endA = lastBx + 1.25 / units, endB = lastBx + 2.3 / units; + + const holes = [[], []], alt = [], gameHoles = [[], []], bxy = [[], []]; + for (let seat = 0; seat < 2; seat++) { + const put = (n, bx, by) => { bxy[seat][n] = { bx, by }; holes[seat][n] = project(bx, by); }; + put(0, startA, rowBy(0, seat)); + for (let n = 1; n <= per * streets; n++) { + const idx = n - 1; + const street = Math.floor(idx / per); + let within = idx % per; + if (street % 2 === 1) within = per - 1 - within; + put(n, colBx(within), rowBy(street, seat)); + } + // the game hole: past the end of the last street + const lastStreet = streets - 1; + const endsRight = lastStreet % 2 === 0; + put(per * streets + 1, endsRight ? endA : startA, rowBy(lastStreet, seat)); + alt[seat] = project(startB, rowBy(0, seat)); + // match holes: a 2 × 2 cluster in whichever end margin is free + const gx = endsRight ? [startB, startA] : [endA, endB]; + const gs = endsRight ? [1, 2] : [0, 1]; + for (const st of gs) for (const x of gx) gameHoles[seat].push(project(x, rowBy(st, seat))); + } + // 121 = 120 holes + the game hole; 61 = 60 + 1 + const skunk = (line) => [0, 1].map((seat) => ({ a: holes[seat][line - 1], b: holes[seat][line] })); + const numbers = []; + for (let n = 10; n <= per * streets; n += 10) { + const p = bxy[1][n]; + numbers.push({ n, ...project(p.bx, p.by - bandH * 0.27) }); + } + const geo = { + target, streets, per, units, holes, alt, gameHoles, skunk, numbers, bxy, + holeR: 7.4, colBx, rowBy, bandH, edgeY: EDGE_Y, startA, startB, endA, endB, + outline: boardOutline(), + }; + geoCache.set(target, geo); + return geo; +} + +/** The board slab's top face (rounded rect, board space → screen). */ +export function boardOutline(pad = 0) { + const pts = []; + const r = 0.035, rv = 0.16; // corner radius in bx / by + const arc = (cx, cy, a0) => { + for (let i = 0; i <= 8; i++) { + const a = a0 + (Math.PI / 2) * (i / 8); + pts.push(project(cx + Math.cos(a) * r, cy + Math.sin(a) * rv)); + } + }; + const x0 = -pad, x1 = 1 + pad, y0 = -pad * 3, y1 = 1 + pad * 3; + arc(x1 - r, y1 - rv, 0); + arc(x0 + r, y1 - rv, Math.PI / 2); + arc(x0 + r, y0 + rv, Math.PI); + arc(x1 - r, y0 + rv, Math.PI * 1.5); + return pts; +} + +/** Screen rect of the whole board (with its front edge and shadow). */ +export function boardRect() { + const o = boardOutline(0.01); + const xs = o.map((p) => p.x), ys = o.map((p) => p.y); + return { x0: Math.min(...xs) - 30, x1: Math.max(...xs) + 30, y0: Math.min(...ys) - 24, y1: Math.max(...ys) + 40 }; +} + +// ── Cards on the table ─────────────────────────────────────────────────────── +const MID_V = 0.56; +export const L = { + deck: T.flat(-0.66, MID_V), + cribMine: T.flat(0.66, 0.62), // your crib sits on your side… + cribTheirs: T.flat(0.66, 0.5), // …Murph's on his + rowU0: -0.3, rowStep: 0.072, rowV: MID_V, + prevU0: -0.475, prevStep: 0.017, prevK: 0.78, + dial: (() => { const p = T.P.project(0.37, MID_V); return { x: p.x, y: p.y, r: 62 }; })(), + cutMine: T.flat(-0.12, 0.71), + cutTheirs: T.flat(-0.12, 0.45), + showY: T.P.project(0, MID_V).y, + plates: [HUMAN_PLATE, { x: 1460, y: 82 }], + fans: [ + { x: 960, y: 994, rot: 0, k: 1, spread: 104, curve: 1.1, tilt: 0.03, q: 1, maxSpan: 600, maxDrop: 26, maxTilt: 0.14 }, + { x: 960, y: 78, rot: Math.PI, k: 0.55, spread: 40, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 260, maxDrop: 12, maxTilt: 0.14 }, + ], + readoutY: 846, + captionY: 722, +}; + +/** The crib pile for the current dealer. */ +export const cribPose = (dealer) => (dealer === 0 ? L.cribMine : L.cribTheirs); + +/** Card i of the current series on the play row. */ +export function rowPose(i) { + return T.flat(L.rowU0 + i * L.rowStep, L.rowV); +} + +/** Card i of the previous series' tidy stack (left of the row). */ +export function prevPose(i) { + return T.flat(L.prevU0 + i * L.prevStep, L.rowV + 0.004, L.prevK); +} + +/** The show: four cards and the starter laid out to be counted. */ +export function showPose(i, n = 4) { + const k = 1.08; + const s = T.P.unproject(960, L.showY).s * k; + const step = 102; + const x = i < n ? 960 + (i - (n - 1) / 2) * step - 60 : 960 + ((n - 1) / 2) * step - 60 + step + 40; + return { x, y: L.showY, rot: 0, s, q: SQ }; +} + +/** Hand fan pose (seat 1's fan is upright when revealed for the show). */ +export function handPose(seat, i, n, lift = 0, upright = false) { + const f = L.fans[seat]; + return fanPose(upright && seat === 1 ? { ...f, rot: 0 } : f, i, n, lift); +} + +/** Where Murph's ghost hand rests. */ +export function handHome() { + const f = L.fans[1]; + const p = fanPoint(f, 0, -CARD_H * 0.95); + return { ...p, rot: f.rot, k: f.k }; +} + +export function spotFor(seat) { + return seat === 0 ? { x: 960, y: 870, w: 1100, h: 380 } : { x: 960, y: 110, w: 760, h: 280 }; +} + +export { CARD_W, CARD_H, PLATE }; diff --git a/src/games/cribbage/tutorial.md b/src/games/cribbage/tutorial.md index ee3af0b..8a3061f 100644 --- a/src/games/cribbage/tutorial.md +++ b/src/games/cribbage/tutorial.md @@ -4,61 +4,85 @@ --- -Evening to ya. Mind the cat. Sit down by the fire there — yes, on the good stool — and let me pour you something warm. You see that long wooden board on the table with all the little holes drilled in it? That, my friend, is a cribbage board, and it has settled more arguments out here on the point than the harbourmaster ever has. Three hundred years sailors have played this game. Tonight you learn it. +Evening to ya. Mind the cat — she's on the windowsill tonight, watching the storm. Sit down by the stove there and let me pour you something warm. Every eight seconds or so the light on the point sweeps past that window and across this table. Forty years I've kept that light. And forty years I've kept *this* — the long walnut board with all the little holes drilled in it. A cribbage board has settled more arguments out here than the harbourmaster ever has. Tonight you learn it. ## The Goal -First one to peg **121 points** wins. You move two little pegs up the board as you score — back peg leapfrogs the front peg each time, so you can always see how many you just earned. Get all the way up one side and back down the other and you're home. +First one to peg **121 points** wins. You move two little pegs along the board as you score — red ones are yours, blue are mine, each of us on our own track down every street. Your **back peg leapfrogs the front one** every time you score, so the gap between them is always what you just made. Watch them hop: the peg lifts out, jumps the front one, and counts its way along, hole by hole, until it drops in with a good wooden *tock*. -If you beat me before I round the corner at 90, that's a **skunk**, and I'll have to buy the next round. It won't happen. But you can try. +See the little brass **S** across the last street, at 91? If you beat me before I get past it, that's a **skunk**, and I'll have to buy the next round. It won't happen. But you can try. ## A Hand, Start to Finish -### 1. The Deal +### 1. The Cut and the Deal -You each get **six cards**. One of us is the **dealer** — watch for the little "deals" mark by the name. The dealer changes every hand, so it evens out. +First game of the night we each **cut a card — low card deals** (aces are low; a tie, cut again). After that the deal goes back and forth. You'll see the word **dealer** on the nameplate of whoever has it. + +You each get **six cards**. ### 2. The Crib -Here's the wrinkle that makes cribbage cribbage. You each throw **two cards** away into a little extra hand called the **crib**. The crib belongs to the *dealer*, and it gets counted at the end like a second hand. So when it's your crib, toss in cards that might score together. When it's mine? Don't do me any favours — feed it junk. +Here's the wrinkle that makes cribbage cribbage. You each lay **two cards** away into a little extra hand called the **crib**. The crib belongs to the *dealer*, and it gets counted at the end like a second hand. So when it's your crib, toss in cards that might score together. When it's mine? Don't do me any favours — starve it. -Pick your two and hit **Discard to Crib**. +Click two cards (or drag them toward the crib, or press **1–6**) and they slide over to the right, marked **TO THE CRIB**. Your four keepers close up so you can see the hand you're keeping. Change your mind? Click one to take it back (or **Backspace**). Happy? **Lay away** (or **Enter**). + +**The Coach** sits under the board while you choose. It's done the sums on every one of the fifteen ways to split your six — what your four will average over all forty-six starters, and what the two will be worth in the crib (plus for yours, minus for mine). Pick a pair and it tells you how your choice stacks up, and whether there's a better one. Press **H** and it glows the two it would throw. You can switch the Coach off in Settings once you're feeling brave. ### 3. The Cut -We cut the deck for a **starter card**. It sits face-up and counts for *everybody's* hand and the crib. And if it's a **Jack** — "his heels" — the dealer pegs **2 points** right off the top. Lucky devils. +The non-dealer — the **pone** — cuts the deck. When that's you, just **click the deck** (or press **Space**). The top half lifts away, the **starter** is turned face up, and it sits on the deck for everyone to share — it counts in your hand, my hand *and* the crib. If it's a **Jack** — "his heels" — the dealer pegs **2** right off the top. Lucky devils. ### 4. The Play (this is where the pegging happens) -Now we take turns laying cards down, calling out a running total. You can't go over **31**. While we play, you score on the spot for: +Now we take turns laying cards in a row in the middle of the table, the pone first. Keep an eye on the **brass gauge** to the right of the row — that's the running count, and the needle can never pass **31**. You score on the spot for: - **Fifteen** — making the count exactly 15 → **2 points** - **Thirty-one** — hitting 31 on the nose → **2 points** -- **Pair** — matching the rank just played → **2** (three of a kind is **6**, four is **12**!) -- **Run** — three or more in a row, any order → **1 point per card** -- **Go / Last card** — when the other fella can't play without busting 31, the last to lay a card pegs **1** +- **Pair** — matching the rank just played → **2** (three of a kind is a **pair royal, 6**; four is a **double pair royal, 12**!) +- **Run** — three or more in a row at the end of the row, any order → **1 point per card** +- **Go / Last card** — when neither of us can play without busting 31, whoever laid the last card pegs **1** -Can't play without going over 31? You say **"Go."** When neither of us can, we sweep the cards, reset the count to zero, and carry on until all the cards are spent. (Aces are low and worth 1; all the face cards are worth 10.) +Can't play without going over 31? You say **"Go"** — the game says it for you, and a **GO** stamp lands on your nameplate. The other player plays on if they can. When nobody can, the count goes back to zero and the cards from that round tuck away in a dimmed stack to the left of the row, so you can still see what's been played. The very last card of the hand pegs **1** too (or **2** if it makes 31). Aces are low and worth 1; all the face cards are worth 10. + +Click a glowing card to play it (dimmed ones would bust 31). With the Coach on, hover a card and the gauge tells you what it would make — "→ 15, fifteen for 2", or "risky" when you'd be handing me points — and a little ★ marks the card it likes best. ### 5. The Show -Now we count what's in our hands — **non-dealer first** (that matters in a close game!), then the dealer, then the dealer counts the **crib**. Add the starter card to each. Here's the scoring: +Now we count what's in our hands — **pone first** (that matters in a close game!), then the dealer, then the dealer counts the **crib**. Each hand is laid out in the middle with the starter, and counted out loud the old way, one combination at a time, the cards lifting as they're called: + +*"Fifteen 2, fifteen 4, a pair is 6, a run of three, 9… and one for his nobs, 10."* - **Fifteens** — *every* combination of cards adding to 15 → **2 each** (they stack up fast!) - **Pairs** — **2** a pair -- **Runs** — **1 per card**, three or more -- **Flush** — four cards same suit in hand → **4** (five with the starter → **5**; the crib only counts a five-card flush) +- **Runs** — **1 per card**, three or more (a pair inside a run makes a *double run* — count it twice) +- **Flush** — four cards the same suit in hand → **4** (five with the starter → **5**; the crib only counts a five-card flush) - **Nobs** — holding the **Jack of the starter's suit** → **1** -The board counts it all up for you and walks the pegs along — no need to do the arithmetic in your head like we did in the old days. +When the count's done, the peg walks the total along the board. Too slow for you? **Space** or a click hurries it along, and Settings has a faster counting speed. A hand that scores nothing is a **"nineteen"** — there's no way to make 19, see, so that's what we call nothing at all. + +## Keeping Score + +The **Scores** button shows the score sheet: every deal, what each of us made, split into **p**egging, **h**and and **c**rib. Hover the board for the standings, the deck for the starter, the gauge for the count, and the crib for whose it is. Your game is saved at every lay-away and every turn of the play, so you can leave the table and pick it up again later. + +When someone pegs out you'll see how the race went, deal by deal, with the skunk line marked, and where the points came from. **Your record** in the menu keeps your wins, your skunks, your best hand ever and every 29 you've been lucky enough to hold. + +## House Rules (Settings) + +- **Game length** — 121 is the proper game. **61** is once around a short two-street board, for when the kettle's nearly boiled (skunk under 31). +- **Match play** — best of 3, 5 or 7. Little game pegs keep the tally at the end of the board. A **skunk counts as two games**. +- **Double skunk** — win before the loser passes 60 and it's a double skunk: **three games** in a match. + +Rule changes start with your next game. ## A Few Words of Wisdom - **Fives are gold.** A five plus any ten, jack, queen, or king makes fifteen — and there are sixteen of those big cards in the deck. -- **Keep your runs and pairs together** when you choose what to throw to the crib. -- **Don't lead a five** during the play — you're just handing me a fifteen. -- **Count carefully near 121.** Non-dealer counts first in the show, so a trailing player can still nip in for the win. +- **Feed your own crib, starve mine.** A pair of fives in your own crib is worth about nine points on average. In mine, it's a gift. +- **Keep your runs and pairs together** when you choose what to throw. +- **Don't lead a five** during the play — you're just handing me a fifteen. A four or lower is a safe lead: nothing makes fifteen off it. +- **Mind 21.** Leave the count at 21 and any ten-card gives me 31. +- **Count carefully near 121.** The pone counts first in the show, so a trailing player can still nip in for the win. -That's the whole game. Deceptively simple, isn't it? You'll think you've got it, and then one hand the cards line up just so and you peg a fistful of points and laugh like a fool. The perfect hand is **29** — I've only had it twice in forty years. +That's the whole game. Deceptively simple, isn't it? You'll think you've got it, and then one hand the cards line up just so and you peg a fistful of points and laugh like a fool. The perfect hand is **29** — three fives and the jack, with the fourth five cut for the starter. I've only had it twice in forty years. -Now then. Deal the cards. And don't touch the cat's stool again. +Now then. Cut for the deal. And don't touch the cat. diff --git a/tools/genCribbageCribTable.js b/tools/genCribbageCribTable.js new file mode 100644 index 0000000..0565e1a --- /dev/null +++ b/tools/genCribbageCribTable.js @@ -0,0 +1,47 @@ +#!/usr/bin/env node +// genCribbageCribTable.js — exact expected crib value for every two-card +// lay-away, used by CribbageAI.js (CRIB_EV / CRIB_EV_SUITED). +// +// For each rank pair (and suited / off-suit), averages scoreHand(crib, starter, +// true) over EVERY other two cards the opponent could lay away (from the 50 +// unseen) and every starter (from the 48 left). Prints the two 13×13 tables. +// Usage: node tools/genCribbageCribTable.js (≈ 30 s) + +import { makeCard, fullDeck, scoreHand, RANKS } from '../src/games/cribbage/CribbageData.js'; + +function expectedCrib(a, b) { + const rest = fullDeck().filter(c => c.id !== a.id && c.id !== b.id); + let sum = 0, n = 0; + for (let i = 0; i < rest.length; i++) { + for (let j = i + 1; j < rest.length; j++) { + const crib = [a, b, rest[i], rest[j]]; + for (let k = 0; k < rest.length; k++) { + if (k === i || k === j) continue; + sum += scoreHand(crib, rest[k], true).total; + n++; + } + } + } + return sum / n; +} + +const off = [], suited = []; +for (let r1 = 0; r1 < 13; r1++) { + off.push(new Array(13).fill(0)); + suited.push(new Array(13).fill(0)); +} +for (let r1 = 0; r1 < 13; r1++) { + for (let r2 = r1; r2 < 13; r2++) { + const v = expectedCrib(makeCard(RANKS[r1], 's'), makeCard(RANKS[r2], 'h')); + off[r1][r2] = off[r2][r1] = +v.toFixed(2); + if (r2 !== r1) { + const s = expectedCrib(makeCard(RANKS[r1], 's'), makeCard(RANKS[r2], 's')); + suited[r1][r2] = suited[r2][r1] = +s.toFixed(2); + } + } + process.stderr.write(`${RANKS[r1]} `); +} +process.stderr.write('\n'); +const fmt = (t) => '[\n' + t.map(row => ' [' + row.map(v => v.toFixed(2).padStart(5)).join(',') + '],').join('\n') + '\n]'; +console.log(`export const CRIB_EV = ${fmt(off)};`); +console.log(`export const CRIB_EV_SUITED = ${fmt(suited)};`); diff --git a/tools/verifyCribbage.js b/tools/verifyCribbage.js index bb9e334..baa270b 100644 --- a/tools/verifyCribbage.js +++ b/tools/verifyCribbage.js @@ -1,128 +1,435 @@ -// Headless verification for Cribbage. -// node server/scripts/verifyCribbage.js [--games=N] -// Exits non-zero on any failure. -// -// 1. Fixture tests: canonical hands (perfect 29, flush, nobs) and pegging -// combinations (fifteen, pairs, runs) score the known values. -// 2. Self-play: full games driven by the heuristic AI on both seats, asserting -// invariants (scores never pass 121 before a win, the play always terminates, -// a winner is reached) over many seeded games. +#!/usr/bin/env node +// verifyCribbage.js — headless checks for Cribbage ("The Keeper's Cottage"): +// hand scoring (fixtures + an independent brute-force scorer), the counted- +// aloud breakdown, pegging, the rules engine (deal, lay-away, cut / his +// heels, go / last card / 31, show order and stopping on a win, skunks, +// match play, the 61 game, saves), the AI (legal, exact lay-away EV, the +// crib tables, the skill ladder on paired deals), the table + board layout, +// and an all-AI soak (52 cards conserved, points add up). +// Usage: node tools/verifyCribbage.js [--quick] -import { Card } from '../src/games/cribbage/CribbageData.js'; -import { CribbageLogic, scoreHand, scorePlay } from '../src/games/cribbage/CribbageLogic.js'; -import { chooseDiscard, choosePlay } from '../src/games/cribbage/CribbageAI.js'; +import { + makeCard, cardFromId, fullDeck, scoreHand, scoreHandDetailed, scorePlay, skunkLines, gamesNeeded, DEFAULT_RULES, +} from '../src/games/cribbage/CribbageData.js'; +import * as G from '../src/games/cribbage/CribbageLogic.js'; +import { + chooseDiscard, choosePlay, rankDiscards, coachDiscard, coachPlay, cribEV, evalPlay, +} from '../src/games/cribbage/CribbageAI.js'; +import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; +import { + W, H as SCREEN_H, cardBounds, fanBounds, rectsOverlap, onScreen, hudFurniture, pointInPoly, DOCK, plateRect, +} from '../src/ui/cardtable/TableGeometry.js'; +import { + L, boardGeometry, boardOutline, boardRect, rowPose, prevPose, showPose, cribPose, handPose, skunkLinesFor, +} from '../src/games/cribbage/CribbageTable.js'; -let failures = 0; -function check(name, cond, detail = '') { - if (cond) { console.log(` ok ${name}`); return; } - failures++; - console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`); +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 C = (s) => s.split(' ').filter(Boolean).map(cardFromId); +const clone = (o) => JSON.parse(JSON.stringify(o)); + +function shuffled(rng) { + const d = fullDeck(); + for (let i = d.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [d[i], d[j]] = [d[j], d[i]]; } + return d; } -function mulberry32(seed) { - let a = seed >>> 0; - return () => { - a |= 0; a = (a + 0x6D2B79F5) | 0; - let t = Math.imul(a ^ (a >>> 15), 1 | a); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} -const C = (rank, suit) => new Card(rank, suit); - -// ── 1. Scoring fixtures ───────────────────────────────────────────────────── -console.log('Scoring fixtures:'); +// ── Hand scoring ───────────────────────────────────────────────────────────── +section('Hand scoring'); { - // Perfect 29: J♥ + 5♠ 5♣ 5♦, cut 5♥. - const hand = [C('J', 'h'), C('5', 's'), C('5', 'c'), C('5', 'd')]; - const r = scoreHand(hand, C('5', 'h'), false); - check('perfect hand scores 29', r.total === 29, `got ${r.total}`); - check(' → 16 in fifteens', r.fifteens === 16, `got ${r.fifteens}`); - check(' → 12 in pairs', r.pairs === 12, `got ${r.pairs}`); - check(' → 1 for nobs', r.nobs === 1, `got ${r.nobs}`); -} -{ - // Four-card hand flush, starter off-suit → 4; on-suit → 5. - const hand = [C('2', 's'), C('4', 's'), C('6', 's'), C('9', 's')]; - check('4-card flush, off-suit cut → 4', scoreHand(hand, C('K', 'h')).flush === 4); - check('5-card flush, on-suit cut → 5', scoreHand(hand, C('K', 's')).flush === 5); -} -{ - // Crib needs all five suited; a 4-card crib flush does not count. - const crib = [C('2', 's'), C('4', 's'), C('6', 's'), C('9', 's')]; - check('crib 4-flush off-suit → 0', scoreHand(crib, C('K', 'h'), true).flush === 0); - check('crib 5-flush on-suit → 5', scoreHand(crib, C('K', 's'), true).flush === 5); -} -{ - // Nobs: Jack matching the starter suit. - const hand = [C('J', 'd'), C('3', 's'), C('7', 'c'), C('9', 'h')]; - check('nobs when J matches starter suit', scoreHand(hand, C('A', 'd')).nobs === 1); - check('no nobs when J off-suit', scoreHand(hand, C('A', 'c')).nobs === 0); -} -{ - // A double run of three with a pair = 8 (run 3×2 + pair 2) plus fifteens. - const r = scoreHand([C('3', 's'), C('4', 's'), C('5', 'c'), C('5', 'd')], C('6', 'h')); - // runs: 3-4-5-6 doubled (two 5s) = 8; pair of 5s = 2; fifteens: (4+5+6),(4+5+6),(5+5+... ) - check('double run + pair runs = 8', r.runs === 8, `got ${r.runs}`); - check('double run pair = 2', r.pairs === 2, `got ${r.pairs}`); + const r = scoreHand(C('Jh 5s 5c 5d'), cardFromId('5h')); + ok('29 hand', r.total === 29, `got ${r.total}`); + ok(' 16 in fifteens · 12 in pairs · 1 nobs', r.fifteens === 16 && r.pairs === 12 && r.nobs === 1); + ok('double double run 4 4 5 5 + 6 = 24', scoreHand(C('4s 4h 5c 5d'), cardFromId('6h')).total === 24); + ok('3 4 4 5 + 6 = 14', scoreHand(C('3h 4d 4s 5c'), cardFromId('6c')).total === 14); + ok('a "nineteen": 2 4 6 8 + Q (mixed suits) = 0', scoreHand(C('2h 4d 6s 8c'), cardFromId('Qh')).total === 0); + ok('4-card hand flush off-suit = 4', scoreHand(C('2s 4s 6s 9s'), cardFromId('Kh')).flush === 4); + ok('5-card hand flush = 5', scoreHand(C('2s 4s 6s 9s'), cardFromId('Ks')).flush === 5); + ok('crib 4-flush does not count', scoreHand(C('2s 4s 6s 9s'), cardFromId('Kh'), true).flush === 0); + ok('crib 5-flush counts 5', scoreHand(C('2s 4s 6s 9s'), cardFromId('Ks'), true).flush === 5); + ok('nobs needs the starter\'s suit', scoreHand(C('Jd 3s 7c 9h'), cardFromId('Ad')).nobs === 1 && scoreHand(C('Jd 3s 7c 9h'), cardFromId('Ac')).nobs === 0); + ok('starter jack is not nobs', scoreHand(C('3d 3s 7c 9h'), cardFromId('Jd')).nobs === 0); + ok('ace is low only: Q K A no run', scoreHand(C('Qs Kh Ad 7c'), cardFromId('2c')).runs === 0); + ok('A 2 3 is a run', scoreHand(C('As 2h 3d 9c'), cardFromId('Kc')).runs === 3); } -// ── 2. Pegging fixtures ───────────────────────────────────────────────────── -console.log('Pegging fixtures:'); -check('fifteen pegs 2', scorePlay([C('7', 's'), C('8', 'd')]).points === 2); -check('thirty-one pegs 2', scorePlay([C('K', 's'), C('T', 'd'), C('6', 'c'), C('5', 'h')]).points === 2); -check('pair pegs 2', scorePlay([C('4', 's'), C('4', 'd')]).points === 2); -check('pair-royal pegs 6', scorePlay([C('4', 's'), C('4', 'd'), C('4', 'c')]).points === 6); -check('run of 3 pegs 3', scorePlay([C('3', 's'), C('5', 'd'), C('4', 'c')]).points === 3); -check('run of 4 pegs 4', scorePlay([C('3', 's'), C('5', 'd'), C('4', 'c'), C('6', 'h')]).points === 4); -check('broken run scores no run', scorePlay([C('3', 's'), C('5', 'd'), C('8', 'c')]).points === 0); - -// ── 3. Self-play ──────────────────────────────────────────────────────────── -const games = Number((process.argv.find((a) => a.startsWith('--games=')) || '').split('=')[1]) || 500; -console.log(`Self-play (${games} games):`); - -function runPlay(g) { - let guard = 0; - while (g.phase === 'play') { - if (++guard > 200) throw new Error('pegging did not terminate'); - const p = g.turn; - const legal = g.legalPlays(p); - if (legal.length === 0) g.go(p); - else g.play(p, choosePlay(legal, g.pile, g.count, 3 + (p % 2))); +// An independent scorer: fifteens/pairs by subsets, runs = the largest run size +// any subset makes, times how many subsets of that size are runs. +function brute(hand4, starter, isCrib) { + const all = [...hand4, starter]; + let pts = 0; + for (let m = 1; m < 32; m++) { + const sub = all.filter((_, i) => m & (1 << i)); + if (sub.reduce((s, c) => s + c.val, 0) === 15) pts += 2; + if (sub.length === 2 && sub[0].rank === sub[1].rank) pts += 2; } -} - -let wins = [0, 0], maxRounds = 0, overflow = false, exceptions = 0; -for (let s = 1; s <= games; s++) { - try { - const g = new CribbageLogic({ rng: mulberry32(s * 2654435761), startDealer: s % 2 }); - let rounds = 0; - while (g.winner === null) { - if (++rounds > 300) throw new Error('game did not terminate'); - g.newDeal(); - for (const p of [0, 1]) g.discard(p, chooseDiscard(g.hands[p], p === g.dealer, p === 0 ? 4 : 3)); - g.cut(); - if (g.scores[0] > 121 || g.scores[1] > 121) overflow = true; - if (g.winner !== null) break; - runPlay(g); - if (g.scores[0] > 121 || g.scores[1] > 121) overflow = true; - if (g.winner !== null) break; - g.show(); - if (g.scores[0] > 121 || g.scores[1] > 121) overflow = true; - if (g.winner !== null) break; - g.dealer = 1 - g.dealer; + for (let k = 5; k >= 3; k--) { + let n = 0; + for (let m = 1; m < 32; m++) { + const sub = all.filter((_, i) => m & (1 << i)); + if (sub.length !== k) continue; + const r = sub.map((c) => c.run).sort((a, b) => a - b); + if (r.every((v, i) => !i || v === r[i - 1] + 1)) n++; } - wins[g.winner]++; - maxRounds = Math.max(maxRounds, rounds); - } catch (e) { - exceptions++; - if (exceptions <= 3) console.error(` game ${s}: ${e.message}`); + if (n) { pts += n * k; break; } } + const suit = hand4[0].suit; + if (hand4.every((c) => c.suit === suit)) pts += starter.suit === suit ? 5 : isCrib ? 0 : 4; + if (hand4.some((c) => c.rank === 'J' && c.suit === starter.suit)) pts += 1; + return pts; +} +{ + const rng = mulberry32(7); + let agree = true, detailOk = true, bad = ''; + const N = QUICK ? 4000 : 30000; + for (let t = 0; t < N; t++) { + // bias toward rich hands: a third of the time draw from a narrow band of ranks + let d = shuffled(rng); + if (t % 3 === 0) d = d.filter((c) => c.run >= 3 && c.run <= 8 || c.rank === 'J'); + const hand = d.slice(0, 4), st = d[4], crib = t % 2 === 1; + const a = scoreHand(hand, st, crib).total, b = brute(hand, st, crib); + if (a !== b) { agree = false; bad = `${hand.map((c) => c.id)} + ${st.id}: ${a} vs ${b}`; break; } + const det = scoreHandDetailed(hand, st, crib); + const ids = new Set([...hand, st].map((c) => c.id)); + const sumPts = det.combos.reduce((s, c) => s + c.pts, 0); + if (det.total !== a || sumPts !== a || det.combos.some((c, i) => !c.ids.every((id) => ids.has(id)) + || c.running !== det.combos.slice(0, i + 1).reduce((s, x) => s + x.pts, 0) || !c.say)) { + detailOk = false; bad = `detail ${hand.map((c) => c.id)} + ${st.id}`; break; + } + } + ok(`scoreHand agrees with brute force (${N} hands)`, agree, bad); + ok('counted-aloud breakdown adds up, cards belong to the hand', detailOk, bad); + const det = scoreHandDetailed(C('Jh 5s 5c 5d'), cardFromId('5h')); + ok('29 is said "Fifteen 2 … and one for his nobs, 29"', det.combos[0].say === 'Fifteen 2' && /nobs, 29$/.test(det.combos[det.combos.length - 1].say)); + ok('four fives call "double pair royal"', det.combos.some((c) => c.kind === 'doublePairRoyal' && c.pts === 12)); + const dr = scoreHandDetailed(C('3h 4d 4s 5c'), cardFromId('6c')); + ok('a double run is two calls of four', dr.combos.filter((c) => c.kind === 'run' && c.pts === 4).length === 2); } -check('no exceptions during self-play', exceptions === 0, `${exceptions} games threw`); -check('scores never exceed 121', !overflow); -check('both seats win some games', wins[0] > 0 && wins[1] > 0, `wins ${wins[0]}/${wins[1]}`); -console.log(` results: human ${wins[0]} / ai ${wins[1]}, longest game ${maxRounds} deals`); -console.log(failures ? `\n${failures} check(s) FAILED` : '\nAll checks passed.'); -process.exit(failures ? 1 : 0); +// ── Pegging ────────────────────────────────────────────────────────────────── +section('Pegging'); +{ + const sp = (s) => scorePlay(C(s)); + ok('15 pegs 2', sp('7s 8d').points === 2); + ok('31 pegs 2', sp('Ks Td 6c 5h').points === 2); + ok('pair 2 · pair royal 6 · double pair royal 12', sp('4s 4d').points === 2 && sp('4s 4d 4c').points === 6 && sp('4s 4d 4c 4h').points === 12); + ok('run of 3 in any order', sp('3s 5d 4c').points === 3); + ok('run of 4', sp('3s 5d 4c 6h').points === 4); + ok('a pair breaks the run', sp('3s 4d 4c 5h').points === 0 && sp('3s 4d 4c').points === 2); + ok('run is the newest cards only', sp('2s 9d 3c 4h').points === 0 && sp('9d 2s 3c 4h').points === 3); + ok('15 + run together', sp('4s 6d 5c').points === 5); + ok('score ids: pair royal lights three cards', sp('4s 4d 4c').scoreIds.length === 3); +} + +// ── Rules engine ───────────────────────────────────────────────────────────── +section('Rules engine'); +/** A play-phase state with given kept hands; pone (seat 1 - dealer) leads. */ +function playState({ dealer = 0, h0, h1, scores = [0, 0], rules = {} }) { + let gs = G.createGame({ seed: 1, dealer, rules }); + const used = new Set([...h0, ...h1].map((c) => c.id)); + const rest = fullDeck().filter((c) => !used.has(c.id)); + gs = clone(gs); + gs.hands = [[...h0, rest[0], rest[1]], [...h1, rest[2], rest[3]]]; + gs.kept = [h0, h1]; + gs.layaway = [[rest[0].id, rest[1].id], [rest[2].id, rest[3].id]]; + gs.crib = rest.slice(0, 4); + gs.starter = rest.find((c) => c.rank !== 'J' && !used.has(c.id) && c.id !== rest[0].id && c.id !== rest[1].id && c.id !== rest[2].id && c.id !== rest[3].id && c.rank !== '5'); + gs.deck = rest.slice(4).filter((c) => c.id !== gs.starter.id); + gs.scores = scores.slice(); + gs.back = scores.map((s) => (s ? s - 1 : -1)); + gs.phase = 'cut'; + return gs; +} +{ + const gs = G.createGame({ seed: 5, dealer: 0 }); + ok('six cards each, 40 in the deck', gs.hands[0].length === 6 && gs.hands[1].length === 6 && gs.deck.length === 40); + ok('52 cards in play', G.cardsInPlay(gs) === 52); + ok('bad lay-away is refused', G.discard(gs, 0, [gs.hands[0][0].id]) === gs && G.discard(gs, 0, [gs.hands[1][0].id, gs.hands[0][0].id]) === gs); + const a = G.discard(gs, 0, gs.hands[0].slice(0, 2).map((c) => c.id)); + ok('one lay-away: still in discard', a.phase === 'discard' && a.crib.length === 2 && G.discard(a, 0, a.hands[0].slice(2, 4).map((c) => c.id)) === a); + const b = G.discard(a, 1, a.hands[1].slice(0, 2).map((c) => c.id)); + ok('both: phase cut, crib of four', b.phase === 'cut' && b.crib.length === 4); + const c = G.cutStarter(b); + ok('the cut turns a starter and starts the play', c.phase === 'play' && c.starter && !c.deck.some((x) => x.id === c.starter.id) && c.play.next === 1); + ok('still 52 cards after the cut', G.cardsInPlay(c) === 52); + // his heels + let heels = null; + for (let s = 1; s < 400 && !heels; s++) { + let g = G.createGame({ seed: s, dealer: 1 }); + g = G.discard(g, 0, g.hands[0].slice(0, 2).map((x) => x.id)); + g = G.discard(g, 1, g.hands[1].slice(0, 2).map((x) => x.id)); + g = G.cutStarter(g); + if (g.starter.rank === 'J') heels = g; + } + ok('his heels: 2 to the dealer', heels && heels.scores[1] === 2 && heels.scores[0] === 0 && heels.history.length === 0 && heels.stats[1].heels === 2); + // cut for deal + const cg = G.createGame({ seed: 77 }); + const last = cg.cuts[cg.cuts.length - 1].map(cardFromId); + ok('cut for deal: low card deals', last[0].run !== last[1].run && cg.dealer === (last[0].run < last[1].run ? 0 : 1)); + ok('cut for deal: ties recut', cg.cuts.slice(0, -1).every(([x, y]) => cardFromId(x).run === cardFromId(y).run)); +} +{ + // Go: pone (seat 1) leads K; dealer plays Q (20); pone plays T (30); dealer + // can't play 9 → go; pone can't either (has 5) → pone pegs 1 for the go. + let gs = G.cutStarter(playState({ dealer: 0, h0: C('Qs 9h 9d 9c'), h1: C('Kh Td 5s 5c') })); + gs = G.play(gs, 1, 'Kh'); + gs = G.play(gs, 0, 'Qs'); + ok('a play out of turn is refused', G.play(gs, 0, '9h') === gs); + gs = G.play(gs, 1, 'Td'); + ok('count 30', gs.play.count === 0 || gs.play.series.length === 1); + const goEv = gs.log.filter((e) => e.kind === 'go'); + const goPt = gs.log.find((e) => e.kind === 'peg' && e.why === 'go'); + ok('dealer says go', goEv.length === 1 && goEv[0].seat === 0); + ok('pone pegs 1 for the go', goPt && goPt.seat === 1 && goPt.pts === 1); + ok('count resets; dealer (who didn\'t play last) leads', gs.play.count === 0 && gs.play.next === 0 && gs.play.series.length === 1); + // play out: dealer 9h, pone 5s (14)… finish and check last card + let guard = 0; + while (gs.phase === 'play' && guard++ < 20) { + const s = gs.play.next; + gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); + } + ok('play ends in the show', gs.phase === 'show'); + ok('exactly one "last card" point', gs.log.filter((e) => e.kind === 'peg' && e.why === 'last').length === 1 || gs.log.some((e) => e.kind === 'play' && e.count === 31)); +} +{ + // Running out of cards is not a "go": pone plays its only... dealer holds + // the last two and plays them on alone without any "go" from the empty hand. + let gs = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('As Ah Ad Ac') })); + let guard = 0; + while (gs.phase === 'play' && guard++ < 20) { const s = gs.play.next; gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); } + ok('no "go" when a hand is simply empty', !gs.log.some((e) => e.kind === 'go')); +} +{ + // 31 on the very last card: 2 for 31, no extra point for last card. + let gs = G.cutStarter(playState({ dealer: 0, h0: C('Ts 5h Th 6c'), h1: C('Ks 6s Kh 5c') })); + const seq = [[1, 'Ks'], [0, 'Ts'], [1, '6s'], [0, '5h'], [1, 'Kh'], [0, 'Th'], [1, '5c'], [0, '6c']]; + for (const [s, id] of seq) { + const nx = G.play(gs, s, id); + if (nx === gs) { ok(`scripted play ${id}`, false, `count ${gs.play.count}, next ${gs.play.next}`); break; } + gs = nx; + } + const pts = gs.log.filter((e) => e.kind === 'peg'); + ok('31 pegs 2 on the last card, no "last card" point', pts.some((e) => e.why === 'play' && e.reasons.includes('31')) && !pts.some((e) => e.why === 'last')); +} +{ + // The show: pone counts first and the game ends the moment they peg out. + let gs = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('5s 5h Ts Kd'), scores: [100, 118] })); + let guard = 0; + while (gs.phase === 'play' && guard++ < 20) { const s = gs.play.next; gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); } + if (gs.phase === 'show') gs = G.finishShow(gs); + ok('pone pegs out first in the show', gs.phase === 'gameOver' && gs.winner === 1); + ok('the dealer\'s hand is never counted', !gs.show || gs.show.items.length === 1); + ok('the winner stops at the target', gs.scores[1] === 121); + ok('a game won is recorded', gs.history.length === 1 && gs.gameResult.winner === 1); +} +{ + // Skunks and match play. + const finish = (scores, rules) => { + let gs = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('5s 5h Ts Kd'), scores, rules })); + let guard = 0; + while (gs.phase === 'play' && guard++ < 20) { const s = gs.play.next; gs = G.play(gs, s, G.legalPlays(gs, s)[0].id); } + return G.finishShow(gs); + }; + ok('skunk lines: 91 / 61 (with the rule) / 31 for 61', skunkLines({ target: 121 }).skunk === 91 && skunkLines({ target: 121, doubleSkunk: true }).double === 61 && skunkLines({ target: 61 }).skunk === 31); + ok('games needed: best of 1/3/5/7', [1, 3, 5, 7].map(gamesNeeded).join() === '1,2,3,4'); + const single = finish([80, 118], {}); + ok('single game: a skunk is marked, 1 game', single.gameResult.skunk === 1 && single.games[1] === 1 && single.matchWinner === 1); + const m3 = finish([80, 118], { bestOf: 3 }); + ok('best of 3: a skunk counts 2 games and wins it', m3.games[1] === 2 && m3.matchWinner === 1); + const ds = finish([50, 118], { bestOf: 5, doubleSkunk: true }); + ok('double skunk counts 3 games', ds.gameResult.skunk === 2 && ds.games[1] === 3 && ds.matchWinner === 1); + const noDs = finish([50, 118], { bestOf: 5 }); + ok('double skunk off: just a skunk', noDs.gameResult.skunk === 1 && noDs.games[1] === 2 && noDs.matchWinner == null); + const ng = G.nextGame(noDs); + ok('next game: fresh pegs, the loser deals', ng.scores.join() === '0,0' && ng.dealer === 0 && ng.gameNo === 2 && ng.phase === 'discard' && ng.games[1] === 2); + ok('nextGame refused once the match is won', G.nextGame(m3) === m3); + const plain = finish([95, 118], { bestOf: 3 }); + ok('no skunk past 90: 1 game', plain.gameResult.skunk === 0 && plain.games[1] === 1 && plain.matchWinner == null); +} +{ + // Saves + const gs = G.createGame({ seed: 3 }); + ok('a fresh deal is a valid save', G.isValidSave(gs)); + ok('a tampered save is refused', !G.isValidSave({ ...gs, deck: gs.deck.slice(1) }) && !G.isValidSave({ ...gs, version: 0 })); + ok('a save survives JSON', G.isValidSave(JSON.parse(JSON.stringify(gs)))); +} + +// ── AI ─────────────────────────────────────────────────────────────────────── +section('AI'); +{ + let sym = true, suitedUp = true; + for (let a = 0; a < 13; a++) for (let b = 0; b < 13; b++) { + const x = cribEV(makeCard(DEFAULT_RANK(a), 's'), makeCard(DEFAULT_RANK(b), 'h')); + const y = cribEV(makeCard(DEFAULT_RANK(b), 'd'), makeCard(DEFAULT_RANK(a), 'c')); + if (Math.abs(x - y) > 1e-9) sym = false; + if (a !== b && cribEV(makeCard(DEFAULT_RANK(a), 's'), makeCard(DEFAULT_RANK(b), 's')) < x - 1e-9) suitedUp = false; + } + ok('crib table symmetric', sym); + ok('suited lay-aways never worth less', suitedUp); + ok('5-5 is the best crib pair', cribEV(cardFromId('5s'), cardFromId('5h')) > 8.5); + // exact hand EV for one keep, by hand + const hand = C('5s 5h Jd Qc 9s Kh'); + const opts = rankDiscards(hand, true); + const keep = C('5s 5h Jd Qc'); + const unseen = fullDeck().filter((c) => !hand.some((h) => h.id === c.id)); + const ev = unseen.reduce((s, st) => s + scoreHand(keep, st).total, 0) / unseen.length; + const o = opts.find((x) => x.keep.map((c) => c.id).sort().join() === keep.map((c) => c.id).sort().join()); + ok('lay-away EV is exact over the 46 starters', Math.abs(o.hand - ev) < 1e-9, `${o.hand} vs ${ev}`); + ok('15 options, best first', opts.length === 15 && opts.every((x, i) => !i || opts[i - 1].total >= x.total)); + ok('dealer: a five + 9 to its own crib beats keeping 5 5 J Q', opts[0].discard.some((c) => c.rank === '5')); + ok('pone never gives away a five here', rankDiscards(hand, false)[0].keep.filter((c) => c.rank === '5').length === 2); + const coach = coachDiscard({ hands: [hand, []], dealer: 0 }, 0); + ok('the Coach agrees with the ranking', coach.best === coach.options[0]); +} +{ + // legality + taking the win + const rng = mulberry32(11); + let legal = true, steps = 0; + for (let g = 0; g < (QUICK ? 30 : 120); g++) { + let gs = G.createGame({ seed: 500 + g }); + while (gs.phase !== 'gameOver' && steps++ < 1e6) { + if (gs.phase === 'discard') for (const s of [0, 1]) { + const ids = chooseDiscard(gs, s, { skill: 1 + ((g + s) % 5), rng }); + const nx = G.discard(gs, s, ids); + if (nx === gs) legal = false; + gs = nx; + } else if (gs.phase === 'cut') gs = G.cutStarter(gs); + else if (gs.phase === 'play') { + const s = gs.play.next; + const nx = G.play(gs, s, choosePlay(gs, s, { skill: 1 + ((g + s) % 5), rng })); + if (nx === gs) { legal = false; break; } + gs = nx; + } else if (gs.phase === 'show') gs = G.showStep(gs); + else gs = G.nextRound(gs); + } + } + ok('every AI move is legal (all skills)', legal); + let gs = G.cutStarter(playState({ dealer: 0, h0: C('7s 2h 9d Kc'), h1: C('8s 3h 3d 4c'), scores: [119, 60] })); + gs = G.play(gs, 1, '8s'); + ok('pegging AI takes the winning fifteen', choosePlay(gs, 0, { skill: 3 }) === '7s'); + const tip = coachPlay(gs, 0); + ok('the Coach finds it too', tip.id === '7s' && /pegs out|wins/.test(tip.reason)); + let lead = G.cutStarter(playState({ dealer: 0, h0: C('2s 3h 4d 6c'), h1: C('5s 4h Ts Kd') })); + ok('skill 5 never leads a five here', choosePlay(lead, 1, { skill: 5 }) !== '5s'); + const e = evalPlay(lead, 1, cardFromId('4h')); + ok('evalPlay: a 4 lead can\'t be fifteened', e.reply < 1.5); +} +{ + // Skill ladder: paired deals (same cards, seats swapped), points per deal. + const N = QUICK ? 250 : 1500; + const dealDiff = (skA, skB) => { + let diff = 0; + for (let i = 0; i < N; i++) { + for (const swap of [false, true]) { + const sk = swap ? [skB, skA] : [skA, skB]; + const rng = mulberry32(9000 + i); + let gs = G.createGame({ seed: 31337 + i, dealer: i % 2 }); + while (!['roundOver', 'gameOver'].includes(gs.phase)) { + if (gs.phase === 'discard') for (const s of [0, 1]) gs = G.discard(gs, s, chooseDiscard(gs, s, { skill: sk[s], rng })); + else if (gs.phase === 'cut') gs = G.cutStarter(gs); + else if (gs.phase === 'play') gs = G.play(gs, gs.play.next, choosePlay(gs, gs.play.next, { skill: sk[gs.play.next], rng })); + else if (gs.phase === 'show') gs = G.showStep(gs); + } + const a = swap ? 1 : 0; + diff += gs.scores[a] - gs.scores[1 - a]; + } + } + return diff / (2 * N); + }; + const ladder = [[2, 1], [3, 2], [4, 3], [5, 4], [5, 3]].map(([a, b]) => ({ a, b, d: dealDiff(a, b) })); + for (const { a, b, d } of ladder) ok(`skill ${a} ≥ skill ${b} (${d >= 0 ? '+' : ''}${d.toFixed(2)} pts/deal)`, d >= (QUICK ? -0.15 : 0)); + console.log(` ladder (points per deal): ${ladder.map(({ a, b, d }) => `${a}v${b} ${d >= 0 ? '+' : ''}${d.toFixed(2)}`).join(' · ')}`); +} + +// ── Layout ─────────────────────────────────────────────────────────────────── +section('Layout'); +for (const target of [121, 61]) { + const geo = boardGeometry(target); + const outline = boardOutline(); + const all = []; + for (let s = 0; s < 2; s++) { + ok(`${target}: ${target + 1} holes per player`, geo.holes[s].length === target + 1); + all.push(...geo.holes[s], geo.alt[s], ...geo.gameHoles[s]); + } + ok(`${target}: every hole on the board`, all.every((p) => pointInPoly(p, outline))); + let minD = Infinity; + for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) minD = Math.min(minD, Math.hypot(all[i].x - all[j].x, all[i].y - all[j].y)); + ok(`${target}: holes never touch (min gap ${minD.toFixed(1)}px)`, minD > geo.holeR * 2 * 0.75); + // consecutive holes are neighbours (the track never jumps) + let maxStep = 0; + for (let s = 0; s < 2; s++) for (let n = 1; n <= target; n++) maxStep = Math.max(maxStep, Math.hypot(geo.holes[s][n].x - geo.holes[s][n - 1].x, geo.holes[s][n].y - geo.holes[s][n - 1].y)); + ok(`${target}: the track walks hole to hole (max step ${maxStep.toFixed(0)}px)`, maxStep < 100); + for (const { line } of skunkLinesFor(target, true)) ok(`${target}: skunk line ${line} sits between holes`, geo.skunk(line).every(({ a, b }) => a && b)); +} +{ + const br = boardRect(); + const furn = hudFurniture(); + ok('board on screen', onScreen(br)); + ok('board clear of the top buttons and plates', !furn.some((f) => f.name.startsWith('button') && rectsOverlap(f.r, br)) && !rectsOverlap(plateRect(L.plates[1]), { ...br, y0: br.y0 + 20 })); + const row8 = cardBounds(rowPose(7)); + const dial = { x0: L.dial.x - 76, x1: L.dial.x + 76, y0: L.dial.y - 76, y1: L.dial.y + 76 }; + ok('8 cards on the row stay clear of the gauge', !rectsOverlap(row8, dial)); + ok('the earlier series stack stays clear of the deck', !rectsOverlap(cardBounds(prevPose(0)), cardBounds(L.deck))); + ok('the earlier series stack stays left of the row', cardBounds(prevPose(7)).x1 < cardBounds(rowPose(0)).x1); + for (const d of [0, 1]) ok(`crib (${d ? 'Murph' : 'yours'}) clear of the gauge and the board`, !rectsOverlap(cardBounds(cribPose(d)), dial) && cardBounds(cribPose(d)).y0 > br.y1 - 40); + const show = [0, 1, 2, 3, 4].map((i) => cardBounds(showPose(i, 4))); + ok('the show row is on screen and clear of the deck', show.every((r) => onScreen(r)) && !show.some((r) => rectsOverlap(r, cardBounds(L.deck)))); + const fan6 = (() => { let b = null; for (let i = 0; i < 6; i++) { const r = cardBounds(handPose(0, i, 6, 18)); b = b ? { x0: Math.min(b.x0, r.x0), x1: Math.max(b.x1, r.x1), y0: Math.min(b.y0, r.y0), y1: Math.max(b.y1, r.y1) } : r; } return b; })(); + ok('your six-card fan clears the dock and your plate', !rectsOverlap(fan6, DOCK) && !rectsOverlap(fan6, plateRect(L.plates[0]))); + ok('Murph\'s fan on screen, clear of his plate', [0, 1, 2, 3, 4, 5].every((i) => onScreen(cardBounds(handPose(1, i, 6)), 4)) && !rectsOverlap(fanBounds(L.fans[1], 6), plateRect(L.plates[1]))); + const pend = [0, 1].map((i) => cardBounds({ x: 1190 + i * 92, y: 918 - 18, rot: 0.07 + i * 0.05, s: 1, q: 1 })); + ok('the pair going to the crib clears the dock', pend.every((r) => !rectsOverlap(r, DOCK) && r.y1 <= SCREEN_H + 30)); + void W; +} + +// ── Soak ───────────────────────────────────────────────────────────────────── +section('Soak'); +{ + const games = QUICK ? 60 : 400; + let okCards = true, okSum = true, okMono = true, okEnd = true, bad = ''; + const wins = [0, 0]; + for (let g = 0; g < games; g++) { + const rng = mulberry32(70000 + g); + const rules = { target: g % 5 === 0 ? 61 : 121, bestOf: g % 7 === 0 ? 3 : 1, doubleSkunk: g % 3 === 0 }; + let gs = G.createGame({ seed: 123 + g, rules }); + let prev = gs.scores.slice(), steps = 0; + for (;;) { + if (++steps > 20000) { okEnd = false; bad = `game ${g} did not end`; break; } + if (!['gameOver'].includes(gs.phase) && G.cardsInPlay(gs) !== 52) { okCards = false; bad = `game ${g} ${gs.phase}: ${G.cardsInPlay(gs)} cards`; } + if (gs.scores.some((v, i) => v < prev[i] && gs.round > 1) || gs.scores.some((v) => v > gs.rules.target)) { okMono = false; bad = `scores ${prev} → ${gs.scores}`; } + prev = gs.scores.slice(); + if (gs.phase === 'gameOver') { + const st = gs.stats; + for (const s of [0, 1]) { + const fromStats = st[s].peg + st[s].hand + st[s].crib + st[s].heels; + const fromHist = gs.history.reduce((a, h) => a + h.peg[s] + h.hand[s] + h.crib[s] + h.heels[s], 0); + if (fromStats !== gs.scores[s] || fromHist !== gs.scores[s]) { okSum = false; bad = `game ${g} seat ${s}: ${fromStats}/${fromHist} vs ${gs.scores[s]}`; } + } + if (gs.matchWinner != null) { wins[gs.matchWinner]++; break; } + gs = G.nextGame(gs); + prev = [0, 0]; + continue; + } + if (gs.phase === 'discard') for (const s of [0, 1]) gs = G.discard(gs, s, chooseDiscard(gs, s, { skill: 1 + (g % 5), rng })); + else if (gs.phase === 'cut') gs = G.cutStarter(gs, rng()); + else if (gs.phase === 'play') gs = G.play(gs, gs.play.next, choosePlay(gs, gs.play.next, { skill: 1 + ((g + 2) % 5), rng })); + else if (gs.phase === 'show') gs = G.showStep(gs); + else if (gs.phase === 'roundOver') gs = G.nextRound(gs); + } + } + ok(`${games} matches all end`, okEnd, bad); + ok('52 cards at every step', okCards, bad); + ok('scores only climb, never past the target', okMono, bad); + ok('pegging + hands + cribs + heels = the score', okSum, bad); + ok('both seats win some', wins[0] > 0 && wins[1] > 0, `${wins}`); +} + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); + +function DEFAULT_RANK(i) { return ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'][i]; }