Rewrite Cribbage as "The Keeper's Cottage" on the card-table kit

- 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
This commit is contained in:
Brian Fertig 2026-12-01 07:36:16 -07:00
parent d53171cccb
commit 5424a7e379
No known key found for this signature in database
13 changed files with 4304 additions and 1144 deletions

View File

@ -1,68 +1,267 @@
// Cribbage — heuristic opponent (skill 1-5). No Phaser, no state mutation. // Cribbage — opponent + Coach. No Phaser; never mutates the game state.
// 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. // 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 {
import { scoreHand, scorePlay } from './CribbageLogic.js'; 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) { /** Expected crib points of two cards laid away (before the other two + starter). */
const base = [1100, 950, 820, 700, 580][clampSkill(skill) - 1]; export function cribEV(a, b) {
return base + Math.random() * 400; 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). export const PROFILE = {
function cribPotential(a, b) { 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; let v = 0;
if (a.rank === b.rank) v += 2; // pair if (a.rank === b.rank) v += 2;
if (cribValue(a) + cribValue(b) === 15) v += 2; // a built-in fifteen if (a.val + b.val === 15) v += 2;
v += [a, b].filter((c) => cribValue(c) === 5).length * 1.5; // fives are gold in the crib v += [a, b].filter((c) => c.val === 5).length * 1.5;
if (Math.abs(runRank(a) - runRank(b)) <= 2 && a.rank !== b.rank) v += 1; // run potential if (Math.abs(a.run - b.run) <= 2 && a.rank !== b.rank) v += 1;
return v; return v;
} }
// ── Lay-away ─────────────────────────────────────────────────────────────────
/** /**
* Choose two cards to discard to the crib from a six-card hand. * Every way to lay two of six away, best first:
* @returns {Card[]} the two discards * [{ 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) { export function rankDiscards(hand6, isDealer, { cribW = 1, static: stat = false, guess = false } = {}) {
const sk = clampSkill(skill); const mine = new Set(hand6.map((c) => c.id));
const noise = (5 - sk) * 1.4; const starters = stat ? null : fullDeck().filter((c) => !mine.has(c.id));
let best = null, bestVal = -Infinity; const out = [];
for (let i = 0; i < hand6.length; i++) { for (let i = 0; i < hand6.length; i++) {
for (let j = i + 1; j < hand6.length; j++) { for (let j = i + 1; j < hand6.length; j++) {
const discard = [hand6[i], hand6[j]]; const discard = [hand6[i], hand6[j]];
const keep = hand6.filter((_, k) => k !== i && k !== j); const keep = hand6.filter((_, k) => k !== i && k !== j);
const handVal = scoreHand(keep, null).total; // static value, no starter let hand;
const crib = cribPotential(discard[0], discard[1]) * 0.5; if (stat) hand = scoreHand(keep, null).total;
let val = handVal + (isDealer ? crib : -crib); else {
val += (Math.random() * 2 - 1) * noise; let sum = 0;
if (val > bestVal) { bestVal = val; best = discard; } 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. * Value of laying `card` now, from `seat`'s view.
* @returns {Card} the card to play * 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) { export function evalPlay(gs, seat, card, mode = 'deep', w = DEEP) {
const sk = clampSkill(skill); const P = gs.play;
const noise = (5 - sk) * 1.2; const pile = P.pile.map((p) => cardFromId(p.id));
let best = null, bestVal = -Infinity; const after = [...pile, card];
const sc = scorePlay(after);
for (const c of legal) { const now = sc.points;
const pts = scorePlay([...pile, c]).points; const count = P.count + card.val;
const newCount = count + cribValue(c); const res = { card, now, reasons: sc.reasons, count, reply: 0, counter: 0, go: 0, value: now };
let val = pts * 4; const target = gs.rules.target;
if (newCount === 5 || newCount === 21) val -= 2; // hands opponent an easy ten for 15/31 if (gs.scores[seat] + now >= target) { res.value = 1000 + now; res.wins = true; return res; }
if (pile.length === 0 && cribValue(c) === 5) val -= 3; // never lead a five if (mode === 'greedy') return res;
if (pile.length === 0 && newCount === 21) val += 0; if (mode === 'safe') {
val += (Math.random() * 2 - 1) * noise; let pen = 0;
if (val > bestVal) { bestVal = val; best = c; } 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(' + ');
}

View File

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

View File

@ -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 = [];
}
}

View File

@ -1,118 +1,254 @@
// Cribbage — static data, scoring helpers and board geometry. No Phaser, no // Cribbage — cards, rules constants and scoring. Pure (no Phaser, no state):
// state: imported by the logic engine, the AI, the Phaser scene and the // shared by the engine, the AI, the scene and tools/verifyCribbage.js.
// headless verify harness alike. //
// Cards are plain JSON so a whole game can be autosaved:
import { Card, Deck } from '../cards/Deck.js'; // { id: 'Td', rank: 'T', suit: 'd', run: 10, val: 10 }
// run = rank order for runs (A = 1 … K = 13, ace low only)
export { Card, Deck }; // 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; export const ICON_FRAME = 64;
// ── Rules (standard 2-player, race to 121, muggins off) ───────────────────── export const HAND_SIZE = 6; // dealt to each player
export const WIN_SCORE = 121; export const KEEP = 4; // kept after laying two away
export const HAND_SIZE = 6; // cards dealt to each player export const PLAY_LIMIT = 31; // the running count never passes 31
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
// ── Card value helpers ────────────────────────────────────────────────────── export const SUITS = ['s', 'h', 'd', 'c'];
/** Pip value used for fifteens and the running count: A=1, face=10, else rank. */ export const RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
export function cribValue(card) { export const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣' };
if (card.rank === 'A') return 1; export const SUIT_NAME = { s: 'spades', h: 'hearts', d: 'diamonds', c: 'clubs' };
return Math.min(10, card.value); 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',
/** 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,
}; };
// ── Board geometry ────────────────────────────────────────────────────────── /**
// A traditional 3-street S-curve track. Each player owns one continuous track * Rules. Standard: 121 points, auto-counted (no muggins), skunk under 91.
// of 120 numbered holes laid out as three "streets" (rows), grouped in fives, * target 121 | 61 (once around the short board)
// plus a start hole (index 0) and a final game hole (index 121). The two * bestOf 1 | 3 | 5 | 7 — match play; a skunk counts two games
// players' tracks run as paired sub-rows inside each street so the colours sit * doubleSkunk loser under 61 (121 game) counts three games and gets a stamp
// side by side, exactly like a physical board. */
const STREETS = 3; export const DEFAULT_RULES = { target: 121, bestOf: 1, doubleSkunk: false };
const HOLES_PER_STREET = 40; // per player, per street (3 × 40 = 120)
const GROUP = 5; // holes per inlaid grouping /** 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. * Score a four-card hand (or the crib) with the starter (starter may be null
* Returns: * for a "static" count before the cut).
* tracks: [p0[], p1[]] each an array of {x,y} for indices 0..121 * @returns {{ total, fifteens, pairs, runs, flush, nobs }}
* holes: [{x,y}, ...] every drilled hole (both players, all indices) for rendering
* groupGaps, holeR, etc. handy render metrics
*/ */
export function buildBoardLayout(rect) { export function scoreHand(hand4, starter, isCrib = false) {
const { x, y, w, h } = rect; const all = starter ? [...hand4, starter] : hand4;
const padX = w * 0.045; const fifteens = fifteenCount(all) * 2;
const usableW = w - padX * 2; const pairs = pairPoints(all);
const runs = runPoints(all);
// Hole-to-hole spacing, with an extra gap inserted every GROUP holes. const flush = hand4.length === 4 ? flushPoints(hand4, starter, isCrib) : 0;
// width = (N-1)*s + (groups-1)*gap , gap = 0.6*s const nobs = nobsPoints(hand4, starter);
const groups = HOLES_PER_STREET / GROUP; // 8 return { total: fifteens + pairs + runs + flush + nobs, fifteens, pairs, runs, flush, nobs };
const s = usableW / ((HOLES_PER_STREET - 1) + (groups - 1) * 0.6); }
const groupGap = 0.6 * s;
const holeR = Math.max(5, s * 0.26); const NUM_WORD = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
// 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; * 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.
// Vertical bands: one street per band, two player sub-rows inside each band. * combos: [{ kind, ids, pts, running, say }]
const bandH = h / STREETS; * The total always equals scoreHand(...).total.
const subY = (street, player) => { */
const top = y + street * bandH; export function scoreHandDetailed(hand4, starter, isCrib = false) {
return top + bandH * (player === 0 ? 0.34 : 0.66); const all = starter ? [...hand4, starter] : hand4.slice();
}; const combos = [];
let running = 0;
// For track index n (1..120): which street, and column within (respecting the const push = (kind, cards, pts, say) => {
// serpentine direction — even streets L→R, odd streets R→L). running += pts;
const trackPoint = (player, n) => { combos.push({ kind, ids: cards.map((c) => c.id), pts, running, say });
const idx = n - 1; };
const street = Math.floor(idx / HOLES_PER_STREET); // fifteens
let within = idx % HOLES_PER_STREET; const n = all.length;
if (street % 2 === 1) within = HOLES_PER_STREET - 1 - within; for (let mask = 1; mask < (1 << n); mask++) {
return { x: colX(within), y: subY(street, player) }; let sum = 0;
}; const pick = [];
for (let k = 0; k < n; k++) if (mask & (1 << k)) { sum += all[k].val; pick.push(all[k]); }
const tracks = [[], []]; if (sum === 15) push('fifteen', pick, 2, null);
for (let p = 0; p < 2; p++) { }
// index 0 — start hole, just left of hole 1 on the top street // pairs, grouped by rank: a pair (2) · pair royal (6) · double pair royal (12)
tracks[p][0] = { x: colX(0) - s * 0.9, y: subY(0, p) }; const byR = new Map();
for (let n = 1; n <= 120; n++) tracks[p][n] = trackPoint(p, n); for (const c of all) byR.set(c.rank, [...(byR.get(c.rank) ?? []), c]);
// index 121 — game hole, just past hole 120 at the end of the bottom street for (const [, cs] of [...byR].sort((a, b) => a[1][0].run - b[1][0].run)) {
const last = trackPoint(p, 120); if (cs.length < 2) continue;
tracks[p][121] = { x: last.x + s * 0.9, y: last.y }; const pts = cs.length * (cs.length - 1);
} const kind = cs.length === 2 ? 'pair' : cs.length === 3 ? 'pairRoyal' : 'doublePairRoyal';
push(kind, cs, pts, null);
// Flat list of every drilled hole for the board face. }
const holes = []; // runs: every distinct run in the longest consecutive stretch of ranks
for (let p = 0; p < 2; p++) for (let n = 0; n <= 121; n++) holes.push(tracks[p][n]); const ranks = [...new Set(all.map((c) => c.run))].sort((a, b) => a - b);
let i = 0;
return { tracks, holes, holeR, s, groupGap }; 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(' + ');
} }

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,251 +1,379 @@
// Cribbage — pure, deterministic game engine. No Phaser, no timers. The scene // Cribbage — pure rules engine. No Phaser, no timers.
// and the headless harness both drive it through the same granular methods so //
// behaviour is identical on screen and under test. // 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) { const clone = (o) => (typeof structuredClone === 'function' ? structuredClone(o) : JSON.parse(JSON.stringify(o)));
let count = 0;
const n = cards.length; // mulberry32 on a state-held integer, so a saved game replays the same shuffles
for (let mask = 1; mask < (1 << n); mask++) { function rand(gs) {
let sum = 0; gs.rng = (gs.rng + 0x6d2b79f5) >>> 0;
for (let k = 0; k < n; k++) if (mask & (1 << k)) sum += cribValue(cards[k]); let t = gs.rng;
if (sum === 15) count++; t = Math.imul(t ^ (t >>> 15), t | 1);
} t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return count * 2; return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
} }
function scorePairs(cards) { function shuffle(gs, arr) {
let pts = 0; for (let i = arr.length - 1; i > 0; i--) {
for (let a = 0; a < cards.length; a++) const j = Math.floor(rand(gs) * (i + 1));
for (let b = a + 1; b < cards.length; b++) [arr[i], arr[j]] = [arr[j], arr[i]];
if (cards[a].rank === cards[b].rank) pts += 2; }
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; return pts;
} }
function scoreRuns(cards) { function endGame(g, winner) {
const cnt = new Map(); g.winner = winner;
for (const c of cards) { const r = runRank(c); cnt.set(r, (cnt.get(r) || 0) + 1); } g.phase = 'gameOver';
const ranks = [...cnt.keys()].sort((a, b) => a - b); pushHistory(g);
let total = 0, i = 0; const loser = 1 - winner;
while (i < ranks.length) { const lines = skunkLines(g.rules);
let j = i, mult = cnt.get(ranks[i]); const ls = g.scores[loser];
while (j + 1 < ranks.length && ranks[j + 1] === ranks[j] + 1) { j++; mult *= cnt.get(ranks[j]); } const skunk = ls < lines.skunk ? (lines.double != null && ls < lines.double ? 2 : 1) : 0;
const len = j - i + 1; const gamePts = g.rules.bestOf > 1 ? 1 + skunk : 1;
if (len >= 3) total += len * mult; g.games[winner] += gamePts;
i = j + 1; g.gameResult = { winner, scores: g.scores.slice(), skunk, gamePts };
} g.pastGames.push({ ...g.gameResult, gameNo: g.gameNo });
return total; if (g.games[winner] >= gamesNeeded(g.rules.bestOf)) g.matchWinner = winner;
g.log.push({ kind: 'win', seat: winner, skunk });
} }
function scoreFlush(hand4, starter, isCrib) { function pushHistory(g) {
const s0 = hand4[0].suit; if (g.history.some((h) => h.round === g.round)) return;
const all4 = hand4.every((c) => c.suit === s0); g.history.push({ round: g.round, dealer: g.dealer, ...clone(g.cur), after: g.scores.slice() });
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 scoreNobs(hand4, starter) { // ── The lay-away ─────────────────────────────────────────────────────────────
if (!starter) return 0; /** `seat` lays two of its six cards away to the crib. */
return hand4.some((c) => c.rank === 'J' && c.suit === starter.suit) ? 1 : 0; 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. * The pone cuts and the dealer turns the starter. `depth` (0..1, optional)
* @returns {{total, fifteens, pairs, runs, flush, nobs}} * is where the cut was made — cosmetic, the card is still random.
*/ */
export function scoreHand(hand4, starter, isCrib = false) { export function cutStarter(gs, depth = null) {
const all5 = starter ? [...hand4, starter] : [...hand4]; if (gs.phase !== 'cut') return gs;
const fifteens = scoreFifteens(all5); const g = clone(gs);
const pairs = scorePairs(all5); const lo = 4, hi = g.deck.length - 4;
const runs = scoreRuns(all5); const i = depth == null
const flush = scoreFlush(hand4, starter, isCrib); ? lo + Math.floor(rand(g) * (hi - lo))
const nobs = scoreNobs(hand4, starter); : Math.max(lo, Math.min(hi - 1, Math.floor(lo + depth * (hi - lo) + (rand(g) - 0.5) * 6)));
return { total: fifteens + pairs + runs + flush + nobs, fifteens, pairs, runs, flush, nobs }; 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. * Resolve every forced step until somebody has a legal card (or the play is
* @returns {{points, reasons:[], count}} * over): "go"s, the point for the go / last card, and the count resetting.
*/ */
export function scorePlay(pile) { function settle(g) {
const reasons = []; for (let guard = 0; guard < 40; guard++) {
let points = 0; if (g.phase !== 'play') return;
const count = pile.reduce((s, c) => s + cribValue(c), 0); const P = g.play;
const p = P.next, o = 1 - p;
if (count === 15) { points += 2; reasons.push('15'); } const can = (s) => P.hands[s].some((c) => P.count + c.val <= PLAY_LIMIT);
if (count === 31) { points += 2; reasons.push('31'); } if (can(p)) return;
if (can(o)) {
// Pairs / pair-royal: trailing equal ranks. // p is stuck: say "go" (a player who is simply out of cards says nothing)
const last = pile[pile.length - 1]; if (P.hands[p].length && !P.said[p]) {
let k = 1; P.said[p] = true;
for (let i = pile.length - 2; i >= 0 && pile[i].rank === last.rank; i--) k++; g.stats[p].gos++;
if (k >= 2) { points += { 2: 2, 3: 6, 4: 12 }[k]; reasons.push(k === 2 ? 'pair' : k === 3 ? 'pair-royal' : 'double-pair-royal'); } g.log.push({ kind: 'go', seat: p, count: P.count });
}
// Runs: longest suffix of the pile that forms consecutive ranks (any order). P.next = o;
for (let len = pile.length; len >= 3; len--) { continue;
const rr = pile.slice(pile.length - len).map(runRank).sort((a, b) => a - b); }
let ok = true; // nobody can play: the stuck player says "go", the last to play pegs 1
for (let i = 1; i < rr.length; i++) if (rr[i] !== rr[i - 1] + 1) { ok = false; break; } // for it (or for the last card), then the count resets
if (ok) { points += len; reasons.push(`run${len}`); break; } 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;
} }
throw new Error('cribbage settle loop');
return { points, reasons, count };
} }
// ── Game engine ───────────────────────────────────────────────────────────── // ── The show ─────────────────────────────────────────────────────────────────
function beginShow(g) {
export class CribbageLogic { g.phase = 'show';
/** @param {{rng?:()=>number, startDealer?:number}} opts */ const d = g.dealer, p = pone(g);
constructor(opts = {}) { g.show = {
this.rng = opts.rng || Math.random; order: [{ seat: p, kind: 'hand' }, { seat: d, kind: 'hand' }, { seat: d, kind: 'crib' }],
this.win = WIN_SCORE; i: 0,
this.dealer = opts.startDealer ?? Math.floor(this.rng() * 2); // 0=human, 1=ai items: [],
this.scores = [0, 0]; };
this.prev = [0, 0]; // previous front-peg position (for leapfrog rendering) g.log.push({ kind: 'show' });
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();
}
} }
/** 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 };

View File

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

View File

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

View File

@ -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 ## 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 ## 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 ### 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 ### 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) ### 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** - **Fifteen** — making the count exactly 15 → **2 points**
- **Thirty-one** — hitting 31 on the nose → **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**!) - **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, any order → **1 point per card** - **Run** — three or more in a row at the end of the 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** - **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 ### 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!) - **Fifteens** — *every* combination of cards adding to 15 → **2 each** (they stack up fast!)
- **Pairs** — **2** a pair - **Pairs** — **2** a pair
- **Runs** — **1 per card**, three or more - **Runs** — **1 per card**, three or more (a pair inside a run makes a *double run* — count it twice)
- **Flush** — four cards same suit in hand → **4** (five with the starter → **5**; the crib only counts a five-card flush) - **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** - **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 ## 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. - **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. - **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.
- **Don't lead a five** during the play — you're just handing me a fifteen. - **Keep your runs and pairs together** when you choose what to throw.
- **Count carefully near 121.** Non-dealer counts first in the show, so a trailing player can still nip in for the win. - **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.

View File

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

View File

@ -1,128 +1,435 @@
// Headless verification for Cribbage. #!/usr/bin/env node
// node server/scripts/verifyCribbage.js [--games=N] // verifyCribbage.js — headless checks for Cribbage ("The Keeper's Cottage"):
// Exits non-zero on any failure. // hand scoring (fixtures + an independent brute-force scorer), the counted-
// // aloud breakdown, pegging, the rules engine (deal, lay-away, cut / his
// 1. Fixture tests: canonical hands (perfect 29, flush, nobs) and pegging // heels, go / last card / 31, show order and stopping on a win, skunks,
// combinations (fifteen, pairs, runs) score the known values. // match play, the 61 game, saves), the AI (legal, exact lay-away EV, the
// 2. Self-play: full games driven by the heuristic AI on both seats, asserting // crib tables, the skill ladder on paired deals), the table + board layout,
// invariants (scores never pass 121 before a win, the play always terminates, // and an all-AI soak (52 cards conserved, points add up).
// a winner is reached) over many seeded games. // Usage: node tools/verifyCribbage.js [--quick]
import { Card } from '../src/games/cribbage/CribbageData.js'; import {
import { CribbageLogic, scoreHand, scorePlay } from '../src/games/cribbage/CribbageLogic.js'; makeCard, cardFromId, fullDeck, scoreHand, scoreHandDetailed, scorePlay, skunkLines, gamesNeeded, DEFAULT_RULES,
import { chooseDiscard, choosePlay } from '../src/games/cribbage/CribbageAI.js'; } 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; const QUICK = process.argv.includes('--quick');
function check(name, cond, detail = '') { let pass = 0, fail = 0;
if (cond) { console.log(` ok ${name}`); return; } function ok(label, cond, detail = '') {
failures++; if (cond) pass++;
console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`); 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) { // ── Hand scoring ─────────────────────────────────────────────────────────────
let a = seed >>> 0; section('Hand scoring');
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:');
{ {
// Perfect 29: J♥ + 5♠ 5♣ 5♦, cut 5♥. const r = scoreHand(C('Jh 5s 5c 5d'), cardFromId('5h'));
const hand = [C('J', 'h'), C('5', 's'), C('5', 'c'), C('5', 'd')]; ok('29 hand', r.total === 29, `got ${r.total}`);
const r = scoreHand(hand, C('5', 'h'), false); ok(' 16 in fifteens · 12 in pairs · 1 nobs', r.fifteens === 16 && r.pairs === 12 && r.nobs === 1);
check('perfect hand scores 29', r.total === 29, `got ${r.total}`); ok('double double run 4 4 5 5 + 6 = 24', scoreHand(C('4s 4h 5c 5d'), cardFromId('6h')).total === 24);
check(' → 16 in fifteens', r.fifteens === 16, `got ${r.fifteens}`); ok('3 4 4 5 + 6 = 14', scoreHand(C('3h 4d 4s 5c'), cardFromId('6c')).total === 14);
check(' → 12 in pairs', r.pairs === 12, `got ${r.pairs}`); ok('a "nineteen": 2 4 6 8 + Q (mixed suits) = 0', scoreHand(C('2h 4d 6s 8c'), cardFromId('Qh')).total === 0);
check(' → 1 for nobs', r.nobs === 1, `got ${r.nobs}`); 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);
// Four-card hand flush, starter off-suit → 4; on-suit → 5. ok('crib 5-flush counts 5', scoreHand(C('2s 4s 6s 9s'), cardFromId('Ks'), true).flush === 5);
const hand = [C('2', 's'), C('4', 's'), C('6', 's'), C('9', 's')]; 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);
check('4-card flush, off-suit cut → 4', scoreHand(hand, C('K', 'h')).flush === 4); ok('starter jack is not nobs', scoreHand(C('3d 3s 7c 9h'), cardFromId('Jd')).nobs === 0);
check('5-card flush, on-suit cut → 5', scoreHand(hand, C('K', 's')).flush === 5); 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);
{
// 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}`);
} }
// ── 2. Pegging fixtures ───────────────────────────────────────────────────── // An independent scorer: fifteens/pairs by subsets, runs = the largest run size
console.log('Pegging fixtures:'); // any subset makes, times how many subsets of that size are runs.
check('fifteen pegs 2', scorePlay([C('7', 's'), C('8', 'd')]).points === 2); function brute(hand4, starter, isCrib) {
check('thirty-one pegs 2', scorePlay([C('K', 's'), C('T', 'd'), C('6', 'c'), C('5', 'h')]).points === 2); const all = [...hand4, starter];
check('pair pegs 2', scorePlay([C('4', 's'), C('4', 'd')]).points === 2); let pts = 0;
check('pair-royal pegs 6', scorePlay([C('4', 's'), C('4', 'd'), C('4', 'c')]).points === 6); for (let m = 1; m < 32; m++) {
check('run of 3 pegs 3', scorePlay([C('3', 's'), C('5', 'd'), C('4', 'c')]).points === 3); const sub = all.filter((_, i) => m & (1 << i));
check('run of 4 pegs 4', scorePlay([C('3', 's'), C('5', 'd'), C('4', 'c'), C('6', 'h')]).points === 4); if (sub.reduce((s, c) => s + c.val, 0) === 15) pts += 2;
check('broken run scores no run', scorePlay([C('3', 's'), C('5', 'd'), C('8', 'c')]).points === 0); if (sub.length === 2 && sub[0].rank === sub[1].rank) pts += 2;
// ── 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)));
} }
} for (let k = 5; k >= 3; k--) {
let n = 0;
let wins = [0, 0], maxRounds = 0, overflow = false, exceptions = 0; for (let m = 1; m < 32; m++) {
for (let s = 1; s <= games; s++) { const sub = all.filter((_, i) => m & (1 << i));
try { if (sub.length !== k) continue;
const g = new CribbageLogic({ rng: mulberry32(s * 2654435761), startDealer: s % 2 }); const r = sub.map((c) => c.run).sort((a, b) => a - b);
let rounds = 0; if (r.every((v, i) => !i || v === r[i - 1] + 1)) n++;
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;
} }
wins[g.winner]++; if (n) { pts += n * k; break; }
maxRounds = Math.max(maxRounds, rounds);
} catch (e) {
exceptions++;
if (exceptions <= 3) console.error(` game ${s}: ${e.message}`);
} }
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.'); // ── Pegging ──────────────────────────────────────────────────────────────────
process.exit(failures ? 1 : 0); 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]; }