Rewrite Gin Rummy as "The Juniper Still" with full ruleset and AI

- Replace the class-based engine with a pure, JSON-state logic module supporting upcard offers, Big Gin, Oklahoma, wash/reshuffle, undercut, bonuses, and save/resume
- Swap heuristic AI for per-skill profiles that track opponent pickups/discards, weigh danger, and time knocks; add a human-facing Coach with explanations
- Add an exact memoised meld solver and exhaustive lay-off search to GinRummyData.js
- Build the new distillery-themed scene on the shared card-table kit, with custom baked art, deadwood meter, showdown rows, tooltips, and settings
- Enable the tutorial in the game registry and add a themed how-to guide
- Expand tools/verifyGinRummy.js into a full test suite: solver vs brute force, engine edge cases, regressions, AI legality, layout collisions, soak matches, and a skill ladder
This commit is contained in:
Brian Fertig 2026-11-30 22:20:46 -07:00
parent 60021f197b
commit 1afdd75a61
No known key found for this signature in database
9 changed files with 3721 additions and 1885 deletions

View File

@ -95,7 +95,7 @@ registerGame({ slug: 'canasta', name: 'Canasta', category: 'cards', cardGame: tr
registerGame({ slug: 'dotlink', name: 'Dot Link', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 66 });
registerGame({ slug: '2048', name: '2048', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 67 });
registerGame({ slug: 'rummikub', name: 'Rummikub', category: 'cards', cardGame: true, minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 68 });
registerGame({ slug: 'ginrummy', name: 'Gin Rummy', category: 'cards', cardGame: true, minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: false, iconFrame: 69 });
registerGame({ slug: 'ginrummy', name: 'Gin Rummy', category: 'cards', cardGame: true, minPlayers: 2, maxPlayers: 4, minOpponents: 1, maxOpponents: 3, hasTutorial: true, iconFrame: 69 });
registerGame({ slug: 'risk', name: 'Risk', category: 'tabletop', minPlayers: 2, maxPlayers: 6, minOpponents: 1, maxOpponents: 5, defaultOpponents: 3, hasTutorial: true, iconFrame: 54, defaultPlayfield: 'combat' });
registerGame({ slug: 'geniussquare', name: 'Genius Square', category: 'logic', minPlayers: 1, maxPlayers: 2, minOpponents: 1, maxOpponents: 1, iconFrame: 70 });
registerGame({ slug: 'katamino', name: 'Katamino', category: 'logic', minPlayers: 1, maxPlayers: 1, minOpponents: 0, maxOpponents: 0, iconFrame: 71 });

View File

@ -1,131 +1,254 @@
// Gin Rummy — heuristic AI (skill 1-5). No Phaser, no state mutation.
// Gin Rummy — opponents (skill 1–5) and the human's Coach. Pure; never mutates.
//
// Every decision only uses what a real player at the table could know: your
// own hand, the discard pile, and which cards each opponent picked up from
// (or threw onto) the pile. Skill changes how much of that is used:
// 1 takes the discard only when it obviously melds; discards high junk; noisy
// 2 as 1, steadier
// 3 minimises deadwood + keeps live partial melds
// 4 + remembers the pile and avoids feeding opponents' picked-up suits/ranks
// 5 + weighs the discard against the expected stock card, times the knock
// against undercut risk
import {
bestMeldGroups,
allCandidateMelds,
canLayoff,
ginDeadwoodValue,
ginRunRank,
MAX_DEADWOOD_TO_KNOCK,
} from './GinRummyData.js';
import { meldSolver, bestMelds, bestDefense, canLayoff, cardName, SUIT_SYM, rankLabel } from './GinRummyData.js';
import { discardChoices, topDiscard, canBigGin } from './GinRummyLogic.js';
const clampSkill = (s) => Math.max(1, Math.min(5, s | 0)) || 3;
export const clampSkill = (s) => Math.max(1, Math.min(5, Math.round(s ?? 3)));
export function thinkDelay(skill) {
const base = [1100, 950, 820, 680, 540][clampSkill(skill) - 1];
return base + Math.random() * 400;
}
// Per-skill play profile (tuned with the self-play ladder in tools/verifyGinRummy.js).
// noise random spread on discard costs (deadwood points)
// pot weight on live partial melds kept
// danger weight on feeding opponents; track = use pickups/discards
// draw 'novice' | 'meld' | 'threshold' | 'expect'; take = threshold gain
// knock 'random' | 'asap' | 'estimate'
export const PROFILE = {
1: { noise: 8, pot: 0, danger: 0, track: false, draw: 'novice', takeP: 0.6, knock: 'random', knockP: 0.8 },
2: { noise: 5, pot: 0, danger: 0, track: false, draw: 'novice', takeP: 0.85, knock: 'random', knockP: 0.95 },
3: { noise: 2.2, pot: 1.1, danger: 0.25, track: false, draw: 'meld', take: 6, knock: 'asap' },
4: { noise: 1.0, pot: 1.3, danger: 0.4, track: true, draw: 'expect', reveal: [0.6, 1.4], knock: 'asap' },
5: { noise: 0.4, pot: 1.5, danger: 0.3, track: true, draw: 'expect', reveal: [0.6, 1.4], knock: 'estimate', est: [46, 5, 8], late: 0.35 },
};
/**
* Decide whether to draw from stock or take the discard.
* @returns {'stock'|'discard'}
*/
export function chooseDrawSource(hand, discardCard, skill = 3) {
const sk = clampSkill(skill);
if (!discardCard) return 'stock';
if (sk <= 2) return Math.random() < 0.25 ? 'discard' : 'stock';
// Would taking the discard improve our best deadwood?
const { deadwood: currentDW } = bestMeldGroups(hand);
const { deadwood: withDW } = bestMeldGroups([...hand, discardCard]);
// Only take discard if it reduces deadwood (or completes a meld)
const improvement = currentDW - withDW;
const threshold = sk >= 4 ? 1 : 5; // skilled AI is more willing to take
return improvement >= threshold ? 'discard' : 'stock';
}
/**
* Choose which card to discard after drawing.
* @returns {Card} card to discard
*/
export function chooseDiscard(hand, skill = 3) {
const sk = clampSkill(skill);
const noise = (5 - sk) * 2.5;
let bestCard = null;
let bestVal = -Infinity;
for (const candidate of hand) {
const rest = hand.filter(c => c.key !== candidate.key);
const { deadwood: dw } = bestMeldGroups(rest);
// Lower deadwood after removal = better discard
let val = -dw;
val += (Math.random() * 2 - 1) * noise;
if (val > bestVal) { bestVal = val; bestCard = candidate; }
// ── What a seat knows ────────────────────────────────────────────────────────
function knowledge(gs, seat) {
const mine = new Set(gs.hands[seat].map(c => c.id));
const pile = new Set(gs.discard.map(c => c.id));
const oppHeld = new Set(); // cards we saw an opponent pick up (and not throw back since)
for (let s = 0; s < gs.n; s++) {
if (s === seat) continue;
for (const id of gs.pickups[s]) if (!pile.has(id) && !mine.has(id)) oppHeld.add(id);
}
return bestCard;
const all = [];
for (const s of ['s', 'h', 'd', 'c']) for (const r of ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']) all.push(`${r}${s}`);
const unseen = new Set(all.filter(id => !mine.has(id) && !pile.has(id) && !oppHeld.has(id)));
return { mine, pile, oppHeld, unseen };
}
/**
* Decide whether to knock given current hand.
* @returns {boolean}
*/
export function shouldKnock(hand, skill = 3) {
const sk = clampSkill(skill);
const { deadwood: dw } = bestMeldGroups(hand);
if (dw > MAX_DEADWOOD_TO_KNOCK) return false;
if (dw === 0) return true; // always gin
const RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
const idOf = (run, suit) => (run >= 1 && run <= 13 ? `${RANKS[run - 1]}${suit}` : null);
// Skill-based knock threshold
const thresholds = [10, 8, 6, 4, 2]; // skill 1..5: knock at or below this deadwood
return dw <= thresholds[sk - 1];
}
/**
* Find all valid layoffs an opponent can make on the knocker's melds.
* @param {Card[]} hand - opponent's hand
* @param {Card[][]} knockerMelds - knocker's declared meld groups
* @returns {{ cardKey: string, meldIdx: number }[]}
*/
export function findLayoffs(hand, knockerMelds, skill = 3) {
const results = [];
const usedKeys = new Set();
for (const card of hand) {
if (usedKeys.has(card.key)) continue;
for (let mi = 0; mi < knockerMelds.length; mi++) {
// Simulate the meld after previous layoffs
const meld = [...knockerMelds[mi]];
for (const r of results.filter(r => r.meldIdx === mi)) {
// add layoff card to simulated meld
const lc = hand.find(c => c.key === r.cardKey);
if (lc) meld.push(lc);
}
if (canLayoff(card, meld)) {
results.push({ cardKey: card.key, meldIdx: mi });
usedKeys.add(card.key);
break;
/** Live partial melds among the loose cards: expected deadwood the next draws could fix. */
function potential(cards, unseen) {
const { loose } = bestMelds(cards);
let pot = 0;
for (let i = 0; i < loose.length; i++) {
for (let j = i + 1; j < loose.length; j++) {
const a = loose[i], b = loose[j];
let outs = 0;
if (a.rank === b.rank) {
for (const s of ['s', 'h', 'd', 'c']) if (s !== a.suit && s !== b.suit && unseen.has(`${a.rank}${s}`)) outs++;
} else if (a.suit === b.suit) {
const lo = Math.min(a.run, b.run), hi = Math.max(a.run, b.run);
if (hi - lo === 1) outs = (unseen.has(idOf(lo - 1, a.suit)) ? 1 : 0) + (unseen.has(idOf(hi + 1, a.suit)) ? 1 : 0);
else if (hi - lo === 2) outs = unseen.has(idOf(lo + 1, a.suit)) ? 1 : 0;
}
pot += outs * (a.pts + b.pts) / 20;
}
}
return results;
return pot;
}
/** How likely an opponent wants `card` (0 = dead safe). */
function danger(gs, seat, card, K, track) {
// raw liveness: unseen cards that would combine with it
let live = 0;
for (const s of ['s', 'h', 'd', 'c']) if (s !== card.suit && K.unseen.has(`${card.rank}${s}`)) live++;
for (const dr of [-2, -1, 1, 2]) if (K.unseen.has(idOf(card.run + dr, card.suit))) live += Math.abs(dr) === 1 ? 1 : 0.5;
let d = live * 0.5;
if (!track) return d;
for (let s = 0; s < gs.n; s++) {
if (s === seat) continue;
for (const id of gs.pickups[s]) {
if (!K.oppHeld.has(id)) continue;
const r = id.slice(0, -1), su = id.slice(-1);
const run = RANKS.indexOf(r) + 1;
if (r === card.rank) d += 6;
else if (su === card.suit && Math.abs(run - card.run) <= 2) d += Math.abs(run - card.run) === 1 ? 6 : 4;
}
for (const id of gs.discards[s]) {
const r = id.slice(0, -1), su = id.slice(-1);
const run = RANKS.indexOf(r) + 1;
if (r === card.rank) d -= 1.5;
else if (su === card.suit && Math.abs(run - card.run) === 1) d -= 1;
}
}
return Math.max(0, d);
}
// ── Discard ──────────────────────────────────────────────────────────────────
/** Score every legal discard for `seat` (lower = better). */
export function rankDiscards(gs, seat, { skill = 3, rng = Math.random } = {}) {
const P = PROFILE[clampSkill(skill)];
const K = knowledge(gs, seat);
const hand = gs.hands[seat];
const S = meldSolver(hand);
const out = [];
hand.forEach((card, i) => {
if (card.id === gs.takenFrom) return;
const dw = S.solve(S.full & ~(1 << i));
let cost = dw;
if (P.pot) cost -= P.pot * potential(hand.filter((_, j) => j !== i), K.unseen);
else cost -= card.pts * 0.15; // novices dump the high card
if (P.danger) cost += P.danger * danger(gs, seat, card, K, P.track);
cost += (rng() * 2 - 1) * P.noise;
out.push({ card, deadwood: dw, cost });
});
return out.sort((a, b) => a.cost - b.cost);
}
// ── Draw ─────────────────────────────────────────────────────────────────────
function bestAfter(hand, extra, banned) {
const h = [...hand, extra];
const S = meldSolver(h);
let best = Infinity;
h.forEach((c, i) => { if (c.id !== banned) best = Math.min(best, S.solve(S.full & ~(1 << i))); });
return best;
}
/** Expected 10-card deadwood after a blind stock draw + best discard. */
function stockExpectation(gs, seat, K) {
const hand = gs.hands[seat];
let sum = 0, n = 0;
for (const id of K.unseen) {
const r = id.slice(0, -1), s = id.slice(-1);
const run = RANKS.indexOf(r) + 1;
sum += bestAfter(hand, { id, rank: r, suit: s, run, pts: Math.min(10, run) }, null);
n++;
}
return n ? sum / n : bestMelds(hand).deadwood;
}
/** 'discard' (take the top card) or 'stock'. Works for the upcard offer too. */
export function chooseDraw(gs, seat, { skill = 3, rng = Math.random } = {}) {
const P = PROFILE[clampSkill(skill)];
const top = topDiscard(gs);
if (!top || gs.stockOnly) return 'stock';
const hand = gs.hands[seat];
const now = bestMelds(hand).deadwood;
const take = bestAfter(hand, top, top.id);
const melds = bestMelds([...hand, top]).melds.some(m => m.some(c => c.id === top.id));
if (P.draw === 'novice') return melds && take < now - 2 && rng() < P.takeP ? 'discard' : 'stock';
if (P.draw === 'meld' || P.draw === 'threshold') return (melds && take < now) || take <= now - P.take ? 'discard' : 'stock';
// 'expect': compare with the expected stock card; taking reveals information
const exp = stockExpectation(gs, seat, knowledge(gs, seat));
return take + P.reveal[melds ? 0 : 1] < exp ? 'discard' : 'stock';
}
// ── Knock timing ─────────────────────────────────────────────────────────────
/** Should `seat` knock with `dw` deadwood now? (gin is always taken separately) */
export function wantsKnock(gs, seat, dw, { skill = 3, rng = Math.random } = {}) {
const P = PROFILE[clampSkill(skill)];
if (dw > gs.knockLimit) return false;
if (P.knock === 'random') return rng() < P.knockP;
if (P.knock === 'asap') return true;
// estimate the lowest opponent deadwood from how far the hand has gone and what they took
let low = Infinity;
for (let s = 0; s < gs.n; s++) {
if (s === seat) continue;
const turns = Math.floor(gs.turn / gs.n);
low = Math.min(low, Math.max(4, P.est[0] - turns * P.est[1] - gs.pickups[s].length * P.est[2]));
}
if (dw <= 2) return true;
return dw <= low * P.late || gs.stock.length <= 6;
}
// ── A whole turn ─────────────────────────────────────────────────────────────
/**
* Full AI turn: returns the sequence of actions to take.
* @returns {{ drawSource: 'stock'|'discard', discardKey: string, knock: boolean, gin: boolean, meldGroups: Card[][] }}
* After drawing: { kind: 'biggin' } | { kind: 'gin' | 'knock' | 'discard', id }.
*/
export function planTurn(hand, discardCard, skill = 3) {
const drawSource = chooseDrawSource(hand, discardCard, skill);
// Simulate drawing
const handAfterDraw = drawSource === 'discard' && discardCard
? [...hand, discardCard]
: [...hand, null]; // null = placeholder for stock card (unknown)
// We can't know stock card, so just plan based on current + discard scenario
const { melds, deadwood } = bestMeldGroups(handAfterDraw.filter(Boolean));
const knock = shouldKnock(handAfterDraw.filter(Boolean), skill);
const gin = deadwood === 0;
const discardCard2 = chooseDiscard(handAfterDraw.filter(Boolean), skill);
return {
drawSource,
discardKey: discardCard2?.key ?? null,
knock: knock && !gin,
gin,
meldGroups: melds,
};
export function chooseAction(gs, seat, { skill = 3, rng = Math.random } = {}) {
if (canBigGin(gs, seat)) return { kind: 'biggin' };
const opts = discardChoices(gs, seat);
const gin = opts.filter(o => o.gin).sort((a, b) => b.card.pts - a.card.pts)[0];
if (gin) return { kind: 'gin', id: gin.card.id };
const ranked = rankDiscards(gs, seat, { skill, rng });
const knockable = opts.filter(o => o.canKnock);
if (knockable.length) {
const minDW = Math.min(...knockable.map(o => o.deadwood));
if (wantsKnock(gs, seat, minDW, { skill, rng })) {
const pick = ranked.find(r => r.deadwood === minDW) ?? knockable.find(o => o.deadwood === minDW);
return { kind: 'knock', id: pick.card.id };
}
}
return { kind: 'discard', id: ranked[0].card.id };
}
/** The defender's lay-offs: [{ id, meldIdx }] in order (optimal for every skill ≥ 2). */
export function chooseLayoffs(gs, seat, { skill = 3, rng = Math.random } = {}) {
const sk = clampSkill(skill);
const hand = gs.hands[seat];
if (sk === 1) {
// a novice lays off whatever fits, even out of their own melds
const out = [];
const melds = gs.showdown.melds.map(m => m.slice());
for (const c of hand) {
const mi = melds.findIndex(m => canLayoff(c, m));
if (mi >= 0 && rng() < 0.85) { out.push({ id: c.id, meldIdx: mi }); melds[mi].push(c); }
}
return out;
}
return bestDefense(hand, gs.showdown.melds).layoffs.map(l => ({ id: l.card.id, meldIdx: l.meldIdx }));
}
// ── Coach (the human's hints) ────────────────────────────────────────────────
const meldWords = (m) => (m.every(c => c.rank === m[0].rank)
? `three ${rankLabel(m[0])}s`.replace('three', m.length === 4 ? 'four' : 'three')
: `${rankLabel(m[0])}–${rankLabel(m[m.length - 1])}${SUIT_SYM[m[0].suit]}`);
/** { source: 'discard'|'stock', reason } */
export function coachDraw(gs, seat) {
const top = topDiscard(gs);
const src = chooseDraw(gs, seat, { skill: 5, rng: () => 0.5 });
if (!top || gs.stockOnly) return { source: 'stock', reason: 'Draw from the stock.' };
const hand = gs.hands[seat];
const now = bestMelds(hand).deadwood;
if (src === 'discard') {
const bm = bestMelds([...hand, top]);
const m = bm.melds.find(g => g.some(c => c.id === top.id));
const after = bestAfter(hand, top, top.id);
return {
source: 'discard',
reason: m ? `Take the ${cardName(top)} — it makes ${meldWords(m)} (deadwood ${now} → ${after}).`
: `Take the ${cardName(top)} — deadwood ${now} → ${after}.`,
};
}
return { source: 'stock', reason: `The ${cardName(top)} doesn't help enough — draw from the stock.` };
}
/** { kind, id?, deadwood, reason } for the discard phase. */
export function coachAction(gs, seat) {
const a = chooseAction(gs, seat, { skill: 5, rng: () => 0.5 });
if (a.kind === 'biggin') return { ...a, deadwood: 0, reason: 'All eleven cards meld — call Big Gin!' };
const opt = discardChoices(gs, seat).find(o => o.card.id === a.id);
const c = opt.card;
if (a.kind === 'gin') return { ...a, deadwood: 0, reason: `Discard the ${cardName(c)} and go GIN!` };
if (a.kind === 'knock') return { ...a, deadwood: opt.deadwood, reason: `Discard the ${cardName(c)} and knock with ${opt.deadwood}.` };
const knockable = discardChoices(gs, seat).filter(o => o.canKnock);
const tail = knockable.length ? ' (you could knock, but the risk of an undercut is high)' : '';
return { ...a, deadwood: opt.deadwood, reason: `Discard the ${cardName(c)} — deadwood ${opt.deadwood}${tail}.` };
}
/** Coach for the human's lay-offs. */
export function coachLayoffs(gs, seat) {
return chooseLayoffs(gs, seat, { skill: 5 });
}

View File

@ -0,0 +1,490 @@
// Gin Rummy art — "The Juniper Still", a distillery tasting room at night.
// Baked once per page load into canvas textures (no image files). Card faces
// are the shared casino deck ('casino-cards', keyed 'As', 'Td', …).
//
// gin-table brick wall, a glowing copper pot still (left), shelves of
// botanical jars and bottles (right), Edison bulbs, the sign;
// an oak tasting-bar table with a brass inlay and a bottle-green
// baize top, pile spots, a G&T on a coaster, a dish of juniper
// gin-back teal card back with an engraved juniper-sprig gin label
// gin-seal cream bottle-label badge (GIN! / BIG GIN!)
// gin-wax red wax seal (UNDERCUT!)
// gin-knuckle a little knock-burst (KNOCK)
import { prepareCasinoArt } from '../../ui/casino/CasinoArt.js';
import {
bakeRoom, canvas, rr, poly, mix, noisePattern, frontBands, rimBand, lampPool, rimShadow, pileSpot, ring, CARD_TEX,
} from '../../ui/cardtable/TableArt.js';
import { W, H } from '../../ui/cardtable/TableGeometry.js';
import { T, layoutFor } from './GinRummyTable.js';
const CW = CARD_TEX.W, CH = CARD_TEX.H;
const SERIF = 'Georgia, "Times New Roman", serif';
const GOLD = '#d9b45a';
function seeded(seed) {
let s = seed;
return () => { s = (s * 16807) % 2147483647; return s / 2147483647; };
}
// ── Room ─────────────────────────────────────────────────────────────────────
function bricks(ctx) {
ctx.fillStyle = '#26140c';
ctx.fillRect(0, 0, W, H);
const rnd = seeded(11);
const bw = 86, bh = 34;
for (let row = 0; row * bh < H; row++) {
const off = (row % 2) * (bw / 2);
for (let x = -bw; x < W + bw; x += bw) {
const t = rnd();
ctx.fillStyle = mix('#5a2a18', '#3a1a0e', t);
ctx.fillRect(x + off + 2, row * bh + 2, bw - 4, bh - 4);
ctx.fillStyle = 'rgba(255,190,140,0.05)';
ctx.fillRect(x + off + 2, row * bh + 2, bw - 4, 3);
}
}
ctx.fillStyle = noisePattern(ctx, 128, 26);
ctx.fillRect(0, 0, W, H);
}
function copperStill(ctx) {
// the pot: a big copper onion on a brick firebox, top-left, swan neck to the right
const cx = 120, cy = 300;
ctx.save();
ctx.fillStyle = '#2a120a';
ctx.fillRect(cx - 120, cy + 120, 240, 420);
const pot = ctx.createRadialGradient(cx - 40, cy - 40, 20, cx, cy, 170);
pot.addColorStop(0, '#ffd09a'); pot.addColorStop(0.25, '#e08a4a'); pot.addColorStop(0.7, '#9a4a1c'); pot.addColorStop(1, '#4a1e0a');
ctx.beginPath();
ctx.ellipse(cx, cy, 150, 140, 0, 0, Math.PI * 2);
ctx.fillStyle = pot;
ctx.fill();
// rivets
for (let a = 0; a < Math.PI * 2; a += Math.PI / 14) {
ctx.beginPath();
ctx.arc(cx + Math.cos(a) * 118, cy + Math.sin(a) * 34 + 30, 3, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255,220,170,0.55)';
ctx.fill();
}
// helmet + swan neck
const helm = ctx.createLinearGradient(cx - 50, 0, cx + 50, 0);
helm.addColorStop(0, '#6a2c10'); helm.addColorStop(0.45, '#f0a868'); helm.addColorStop(1, '#5a240c');
ctx.fillStyle = helm;
ctx.beginPath();
ctx.moveTo(cx - 46, cy - 120);
ctx.quadraticCurveTo(cx - 60, cy - 220, cx, cy - 232);
ctx.quadraticCurveTo(cx + 60, cy - 220, cx + 46, cy - 120);
ctx.closePath();
ctx.fill();
ctx.lineCap = 'round';
ctx.strokeStyle = '#b86a32';
ctx.lineWidth = 16;
ctx.beginPath();
ctx.moveTo(cx, cy - 226);
ctx.quadraticCurveTo(cx + 140, cy - 300, 330, cy - 250);
ctx.lineTo(560, cy - 236);
ctx.stroke();
ctx.strokeStyle = 'rgba(255,210,160,0.45)';
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(cx + 4, cy - 232);
ctx.quadraticCurveTo(cx + 140, cy - 306, 330, cy - 256);
ctx.lineTo(560, cy - 242);
ctx.stroke();
// firebox glow
const fire = ctx.createRadialGradient(cx, cy + 230, 10, cx, cy + 230, 260);
fire.addColorStop(0, 'rgba(255,150,60,0.6)'); fire.addColorStop(1, 'rgba(255,120,40,0)');
ctx.fillStyle = fire;
ctx.fillRect(0, 0, 500, 900);
ctx.restore();
}
function shelves(ctx) {
const x0 = 1640, rnd = seeded(23);
const glass = ['rgba(150,210,200,0.55)', 'rgba(200,230,240,0.5)', 'rgba(120,170,110,0.55)', 'rgba(230,200,140,0.5)', 'rgba(180,160,220,0.45)'];
for (let k = 0; k < 4; k++) {
const y = 120 + k * 150;
// shelf board
const g = ctx.createLinearGradient(0, y, 0, y + 14);
g.addColorStop(0, '#6a4220'); g.addColorStop(1, '#2a160a');
ctx.fillStyle = g;
ctx.fillRect(x0 - 20, y, W - x0 + 40, 14);
let x = x0 - 10 + rnd() * 20;
while (x < W - 20) {
const tall = rnd() < 0.45;
const w = tall ? 30 : 42, h = tall ? 96 + rnd() * 20 : 54 + rnd() * 16;
ctx.save();
ctx.fillStyle = glass[Math.floor(rnd() * glass.length)];
if (tall) {
// a gin bottle: body, shoulder, neck, cap
rr(ctx, x, y - h, w, h, 6);
ctx.fill();
ctx.fillRect(x + w / 2 - 5, y - h - 26, 10, 28);
ctx.fillStyle = '#2a2a2a';
ctx.fillRect(x + w / 2 - 6, y - h - 32, 12, 8);
ctx.fillStyle = 'rgba(250,240,215,0.85)';
ctx.fillRect(x + 4, y - h * 0.62, w - 8, h * 0.28);
ctx.fillStyle = 'rgba(40,90,80,0.9)';
ctx.fillRect(x + 6, y - h * 0.55, w - 12, 3);
} else {
// a botanical jar with a cork
rr(ctx, x, y - h, w, h, 8);
ctx.fill();
ctx.fillStyle = '#b08a5a';
ctx.fillRect(x + 6, y - h - 10, w - 12, 12);
const dots = ['#2a3a6a', '#d98a2a', '#5a7a3a', '#c8b070'][Math.floor(rnd() * 4)];
ctx.fillStyle = dots;
for (let i = 0; i < 14; i++) {
ctx.beginPath();
ctx.arc(x + 6 + rnd() * (w - 12), y - 6 - rnd() * (h * 0.55), 3 + rnd() * 2, 0, Math.PI * 2);
ctx.fill();
}
}
ctx.fillStyle = 'rgba(255,255,255,0.22)';
ctx.fillRect(x + 4, y - h + 6, 4, h - 14);
ctx.restore();
x += w + 8 + rnd() * 14;
}
}
}
function bulbs(ctx) {
const rnd = seeded(5);
for (let x = 420; x < 1600; x += 170) {
const len = 18 + rnd() * 26;
ctx.strokeStyle = 'rgba(20,10,6,0.9)';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, len); ctx.stroke();
const glow = ctx.createRadialGradient(x, len + 12, 2, x, len + 12, 120);
glow.addColorStop(0, 'rgba(255,200,120,0.55)'); glow.addColorStop(1, 'rgba(255,170,80,0)');
ctx.fillStyle = glow;
ctx.fillRect(x - 130, 0, 260, 200);
ctx.fillStyle = '#ffe2a8';
ctx.beginPath(); ctx.ellipse(x, len + 12, 8, 12, 0, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = 'rgba(255,150,40,0.9)';
ctx.lineWidth = 1.2;
ctx.beginPath(); ctx.moveTo(x - 3, len + 8); ctx.lineTo(x, len + 16); ctx.lineTo(x + 3, len + 8); ctx.stroke();
}
}
function sign(ctx) {
const x = 1760, y = 34;
ctx.save();
rr(ctx, x - 150, y - 26, 300, 52, 10);
ctx.fillStyle = '#142a24';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = GOLD;
ctx.stroke();
ctx.fillStyle = GOLD;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = `bold 21px ${SERIF}`;
ctx.fillText('THE JUNIPER STILL', x, y - 5);
ctx.font = `11px ${SERIF}`;
ctx.fillStyle = 'rgba(217,180,90,0.8)';
ctx.fillText('DISTILLERY · TASTING ROOM · EST. 1923', x, y + 14);
ctx.restore();
}
function wall(ctx) {
bricks(ctx);
copperStill(ctx);
shelves(ctx);
// the room is dark: a warm wash from the still (left) and the bulbs (top)
ctx.fillStyle = 'rgba(8,4,2,0.38)';
ctx.fillRect(0, 0, W, H);
bulbs(ctx);
sign(ctx);
// oak floor strip below the table
const f = ctx.createLinearGradient(0, 990, 0, H);
f.addColorStop(0, '#2a180c'); f.addColorStop(1, '#140a04');
ctx.fillStyle = f;
ctx.fillRect(0, 990, W, H - 990);
}
function front(ctx, Tb) {
frontBands(ctx, Tb, ['#9a6a3a', '#80542a', '#6a4220', '#523218', '#3a2210'], { grooves: [0.35, 0.72] });
}
function rim(ctx, Tb) {
rimBand(ctx, Tb, { base: '#8a5a2b', dark: '#3a210c', light: '#e0aa6a', grain: ['#2a1606', '#f0c088'], gloss: 1.4 });
// brass inlay line around the baize
ring(ctx, Tb, Tb.feltK + 0.012, 2.4, 'rgba(230,190,110,0.75)');
}
function baize(ctx, Tb) {
ctx.fillStyle = '#1d4a39';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = noisePattern(ctx, 200, 26);
ctx.fillRect(0, 0, W, H);
ring(ctx, Tb, Tb.feltK * 0.95, 2.2, 'rgba(217,180,90,0.5)');
ring(ctx, Tb, Tb.feltK * 0.935, 1, 'rgba(217,180,90,0.35)');
lampPool(ctx, Tb, { color: '255,214,160', alpha: 0.28, vignette: 0.55, at: { u: 0, v: 0.44 } });
// the still warms the left of the table
const f = Tb.P.project(-1.1, 0.3);
const g = ctx.createRadialGradient(f.x, f.y, 20, f.x, f.y, 800);
g.addColorStop(0, 'rgba(255,140,60,0.18)'); g.addColorStop(1, 'rgba(255,140,60,0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
rimShadow(ctx, Tb, 0.4);
}
/** A juniper sprig: a stem with needles and a few berries (local coords). */
function sprig(ctx, x, y, s, color, berry) {
ctx.save();
ctx.translate(x, y);
ctx.scale(s, s);
ctx.strokeStyle = color;
ctx.lineWidth = 2.4;
ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(-40, 26); ctx.quadraticCurveTo(0, 4, 42, -24); ctx.stroke();
ctx.lineWidth = 1.6;
for (let i = 0; i < 9; i++) {
const t = i / 8;
const px = -38 + t * 78, py = 24 - t * 46 - Math.sin(t * Math.PI) * 6;
ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px - 6, py - 14); ctx.stroke();
ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px + 10, py + 9); ctx.stroke();
}
for (const [bx, by] of [[-6, 22], [6, 20], [0, 30], [22, 4]]) {
ctx.beginPath();
ctx.arc(bx, by, 6, 0, Math.PI * 2);
ctx.fillStyle = berry;
ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.35)';
ctx.beginPath(); ctx.arc(bx - 2, by - 2, 2, 0, Math.PI * 2); ctx.fill();
}
ctx.restore();
}
function emblem(ctx) {
// faint tooled emblem under the piles
const c = T.P.project(0, 0.63);
ctx.save();
ctx.translate(c.x, c.y);
ctx.scale(1, 0.9);
ctx.globalAlpha = 0.22;
ctx.strokeStyle = GOLD;
ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(0, 0, 170, 62, 0, 0, Math.PI * 2); ctx.stroke();
ctx.beginPath(); ctx.ellipse(0, 0, 160, 54, 0, 0, Math.PI * 2); ctx.stroke();
ctx.fillStyle = GOLD;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = `bold 30px ${SERIF}`;
ctx.fillText('THE JUNIPER STILL', 0, -6);
ctx.font = `14px ${SERIF}`;
ctx.fillText('— first to 100 proof —', 0, 24);
ctx.restore();
ctx.save();
ctx.globalAlpha = 0.3;
sprig(ctx, c.x - 205, c.y, 0.8, GOLD, GOLD);
ctx.translate(c.x + 205, c.y);
ctx.scale(-1, 1);
sprig(ctx, 0, 0, 0.8, GOLD, GOLD);
ctx.restore();
}
function ginAndTonic(ctx) {
const p = T.P.project(0.8, 0.27);
const s = p.s;
ctx.save();
ctx.translate(p.x, p.y);
ctx.scale(s, s);
// coaster
ctx.beginPath(); ctx.ellipse(0, 26, 58, 22, 0, 0, Math.PI * 2);
ctx.fillStyle = '#e8dcc0'; ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = '#8a6a3a'; ctx.stroke();
ctx.fillStyle = 'rgba(40,90,80,0.85)';
ctx.font = `bold 11px ${SERIF}`;
ctx.textAlign = 'center';
ctx.fillText('JUNIPER', 0, 42);
// glass shadow + glass
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.beginPath(); ctx.ellipse(8, 28, 34, 11, 0, 0, Math.PI * 2); ctx.fill();
const g = ctx.createLinearGradient(-30, 0, 30, 0);
g.addColorStop(0, 'rgba(210,235,240,0.35)'); g.addColorStop(0.5, 'rgba(230,250,255,0.18)'); g.addColorStop(1, 'rgba(190,220,230,0.4)');
ctx.fillStyle = g;
ctx.beginPath();
ctx.moveTo(-30, -60); ctx.lineTo(-26, 24); ctx.quadraticCurveTo(0, 34, 26, 24); ctx.lineTo(30, -60); ctx.closePath();
ctx.fill();
// tonic, ice, lime
ctx.fillStyle = 'rgba(220,245,235,0.45)';
ctx.beginPath(); ctx.moveTo(-28, -30); ctx.lineTo(-26, 22); ctx.quadraticCurveTo(0, 31, 26, 22); ctx.lineTo(28, -30); ctx.closePath(); ctx.fill();
for (const [ix, iy] of [[-12, -18], [8, -10], [-2, 4]]) {
rr(ctx, ix - 9, iy - 9, 18, 18, 4);
ctx.fillStyle = 'rgba(255,255,255,0.4)'; ctx.fill();
}
ctx.beginPath(); ctx.arc(20, -58, 16, Math.PI * 0.9, Math.PI * 2.1);
ctx.fillStyle = '#9ad46a'; ctx.fill();
ctx.strokeStyle = '#4a7a20'; ctx.lineWidth = 3; ctx.stroke();
ctx.beginPath(); ctx.ellipse(0, -60, 30, 8, 0, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 1.5; ctx.stroke();
ctx.restore();
}
function berryDish(ctx) {
const p = T.P.project(0.8, 0.72);
const rnd = seeded(77);
ctx.save();
ctx.translate(p.x, p.y);
ctx.scale(p.s, p.s * 0.9);
ctx.fillStyle = 'rgba(0,0,0,0.35)';
ctx.beginPath(); ctx.ellipse(6, 10, 58, 24, 0, 0, Math.PI * 2); ctx.fill();
const d = ctx.createLinearGradient(0, -20, 0, 20);
d.addColorStop(0, '#d0a060'); d.addColorStop(1, '#7a4e20');
ctx.fillStyle = d;
ctx.beginPath(); ctx.ellipse(0, 0, 54, 22, 0, 0, Math.PI * 2); ctx.fill();
for (let i = 0; i < 26; i++) {
const a = rnd() * Math.PI * 2, r = Math.sqrt(rnd()) * 40;
const bx = Math.cos(a) * r, by = Math.sin(a) * r * 0.36 - 4;
ctx.beginPath(); ctx.arc(bx, by, 5, 0, Math.PI * 2);
ctx.fillStyle = mix('#2a3a6a', '#4a5a8a', rnd()); ctx.fill();
ctx.fillStyle = 'rgba(255,255,255,0.3)';
ctx.beginPath(); ctx.arc(bx - 1.5, by - 1.5, 1.6, 0, Math.PI * 2); ctx.fill();
}
ctx.restore();
}
function marks(L) {
return (ctx) => {
emblem(ctx);
pileSpot(ctx, L.stock, 'STOCK', { color: '217,190,120', alpha: 0.45 });
pileSpot(ctx, L.discard, 'DISCARD', { color: '217,190,120', alpha: 0.45 });
ginAndTonic(ctx);
berryDish(ctx);
};
}
// ── Card back ────────────────────────────────────────────────────────────────
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, '#1f5a52'); g.addColorStop(1, '#0c2a26');
ctx.fillStyle = g;
ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.stroke();
rr(ctx, 10, 10, CW - 20, CH - 20, 12);
ctx.lineWidth = 3; ctx.strokeStyle = GOLD; ctx.stroke();
rr(ctx, 16, 16, CW - 32, CH - 32, 9);
ctx.lineWidth = 1.2; ctx.strokeStyle = 'rgba(217,180,90,0.6)'; ctx.stroke();
// engraved diamond lattice
ctx.save();
rr(ctx, 18, 18, CW - 36, CH - 36, 8);
ctx.clip();
ctx.strokeStyle = 'rgba(217,180,90,0.13)';
ctx.lineWidth = 1.5;
for (let k = -CH; k < CW + CH; k += 16) {
ctx.beginPath(); ctx.moveTo(k, 0); ctx.lineTo(k + CH, CH); ctx.stroke();
ctx.beginPath(); ctx.moveTo(k, CH); ctx.lineTo(k + CH, 0); ctx.stroke();
}
ctx.restore();
// the oval gin label
const cx = CW / 2, cy = CH / 2;
ctx.beginPath(); ctx.ellipse(cx, cy, 64, 88, 0, 0, Math.PI * 2);
ctx.fillStyle = '#f2e8cf'; ctx.fill();
ctx.lineWidth = 4; ctx.strokeStyle = GOLD; ctx.stroke();
ctx.beginPath(); ctx.ellipse(cx, cy, 56, 80, 0, 0, Math.PI * 2);
ctx.lineWidth = 1.2; ctx.strokeStyle = '#1f5a52'; ctx.stroke();
ctx.fillStyle = '#1f4a42';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = `bold 15px ${SERIF}`;
ctx.fillText('JUNIPER', cx, cy - 50);
ctx.font = `bold 13px ${SERIF}`;
ctx.fillText('STILL', cx, cy + 56);
sprig(ctx, cx, cy + 2, 0.75, '#2a5a40', '#2a3a6a');
ctx.font = `9px ${SERIF}`;
ctx.fillStyle = '#8a6a3a';
ctx.fillText('LONDON DRY', cx, cy + 72);
scene.textures.addCanvas('gin-back', c);
}
// ── Badges ───────────────────────────────────────────────────────────────────
function bakeSeal(scene) {
const S = 320;
const c = canvas(S, S);
const ctx = c.getContext('2d');
const cx = S / 2, cy = S / 2;
// scalloped edge
ctx.beginPath();
for (let i = 0; i <= 64; i++) {
const a = (i / 64) * Math.PI * 2;
const r = 150 + (i % 2 ? -7 : 0);
ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);
}
ctx.closePath();
ctx.fillStyle = GOLD;
ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 6;
ctx.fill();
ctx.shadowColor = 'transparent';
ctx.beginPath(); ctx.arc(cx, cy, 128, 0, Math.PI * 2);
const g = ctx.createRadialGradient(cx - 30, cy - 40, 10, cx, cy, 130);
g.addColorStop(0, '#fffaf0'); g.addColorStop(1, '#e8d8b0');
ctx.fillStyle = g; ctx.fill();
ctx.lineWidth = 3; ctx.strokeStyle = '#1f5a52'; ctx.stroke();
ctx.beginPath(); ctx.arc(cx, cy, 116, 0, Math.PI * 2);
ctx.lineWidth = 1.2; ctx.stroke();
ctx.globalAlpha = 0.5;
sprig(ctx, cx - 70, cy + 72, 0.6, '#2a5a40', '#2a3a6a');
ctx.save(); ctx.translate(cx + 70, cy + 72); ctx.scale(-1, 1); sprig(ctx, 0, 0, 0.6, '#2a5a40', '#2a3a6a'); ctx.restore();
ctx.globalAlpha = 1;
scene.textures.addCanvas('gin-seal', c);
}
function bakeWax(scene) {
const S = 300;
const c = canvas(S, S);
const ctx = c.getContext('2d');
const cx = S / 2, cy = S / 2;
const rnd = seeded(31);
ctx.beginPath();
for (let i = 0; i <= 40; i++) {
const a = (i / 40) * Math.PI * 2;
const r = 132 + rnd() * 14;
ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);
}
ctx.closePath();
const g = ctx.createRadialGradient(cx - 40, cy - 40, 10, cx, cy, 150);
g.addColorStop(0, '#e0505a'); g.addColorStop(0.6, '#a8141e'); g.addColorStop(1, '#5a0810');
ctx.fillStyle = g;
ctx.shadowColor = 'rgba(0,0,0,0.5)'; ctx.shadowBlur = 14; ctx.shadowOffsetY = 5;
ctx.fill();
ctx.shadowColor = 'transparent';
ctx.beginPath(); ctx.arc(cx, cy, 100, 0, Math.PI * 2);
ctx.lineWidth = 6; ctx.strokeStyle = 'rgba(60,0,6,0.55)'; ctx.stroke();
ctx.beginPath(); ctx.arc(cx, cy, 92, 0, Math.PI * 2);
ctx.lineWidth = 2; ctx.strokeStyle = 'rgba(255,170,170,0.35)'; ctx.stroke();
scene.textures.addCanvas('gin-wax', c);
}
function bakeKnuckle(scene) {
const S = 260;
const c = canvas(S, S);
const ctx = c.getContext('2d');
const cx = S / 2, cy = S / 2;
ctx.strokeStyle = '#ffe2a8';
ctx.lineCap = 'round';
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2 + 0.13;
const r0 = 54, r1 = i % 2 ? 100 : 122;
ctx.lineWidth = i % 2 ? 6 : 10;
ctx.beginPath();
ctx.moveTo(cx + Math.cos(a) * r0, cy + Math.sin(a) * r0 * 0.8);
ctx.lineTo(cx + Math.cos(a) * r1, cy + Math.sin(a) * r1 * 0.8);
ctx.stroke();
}
scene.textures.addCanvas('gin-knuckle', c);
}
export async function prepareGinArt(scene, playerCount) {
await prepareCasinoArt(scene);
if (!scene.textures.exists('gin-back')) bakeBack(scene);
if (!scene.textures.exists('gin-seal')) bakeSeal(scene);
if (!scene.textures.exists('gin-wax')) bakeWax(scene);
if (!scene.textures.exists('gin-knuckle')) bakeKnuckle(scene);
const L = layoutFor(playerCount);
return bakeRoom(scene, 'gin-table', T, { wall, front, rim, top: baize, onTop: marks(L) });
}

View File

@ -1,223 +1,257 @@
// Gin Rummy — static data, card helpers, layout geometry. No Phaser, no state.
// Imported by the logic engine, AI, Phaser scene and headless verify harness.
import { Card, Deck, SUITS, RANKS } from '../cards/Deck.js';
export { Card, Deck, SUITS, RANKS };
// Gin Rummy — cards, melds and rules. Pure (no Phaser, no state) so the
// engine, AI, scene and tools/verifyGinRummy.js all share it.
//
// Cards are plain JSON objects so a whole game state can be autosaved:
// { id: 'Td', rank: 'T', suit: 'd', run: 10, pts: 10 }
// run = position in a run (A = 1 low only … K = 13), pts = deadwood value.
//
// The meld solver is exact: a memoised search over bitmasks of the hand
// (≤ 11 cards → ≤ 2048 states), so "best melds" never guesses.
export const ICON_FRAME = 69;
export const WIN_SCORE = 100;
export const HAND_SIZE = 10;
export const MAX_DEADWOOD_TO_KNOCK = 10;
export const GIN_BONUS = 25;
export const UNDERCUT_BONUS = 10;
export const SUITS = ['s', 'h', 'd', 'c'];
export const RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
export const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣' };
export const SUIT_NAME = { s: 'spades', h: 'hearts', d: 'diamonds', c: 'clubs' };
const SUIT_ORDER = { s: 0, h: 1, c: 2, d: 3 }; // alternating colours when sorted by suit
// ── Card value helpers ──────────────────────────────────────────────────────
/** Standard rules (Hoyle). Every key is a Settings toggle except knockMax / ginBonus. */
export const DEFAULT_RULES = {
target: 100, // first to this many points ("proof") ends the match
knockMax: 10, // most deadwood you may knock with
ginBonus: 25,
undercutBonus: 25,
bigGin: true, // all 11 cards melded after drawing: no discard, +31
bigGinBonus: 31,
upcard: true, // first-turn upcard offer
oklahoma: false, // the first upcard sets the knock limit; a spade upcard doubles the hand
bonuses: true, // game bonus 100, box bonus 25 per hand won, shutout doubles (match end)
gameBonus: 100,
boxBonus: 25,
};
/** Deadwood point value for a card in Gin Rummy: A=1, 2-9=pip, T/J/Q/K=10. */
export function ginDeadwoodValue(card) {
if (card.rank === 'A') return 1;
return Math.min(10, card.value); // card.value is 2-14, so A=14 → ignored above
// ── Cards ────────────────────────────────────────────────────────────────────
export function makeCard(rank, suit) {
const run = RANKS.indexOf(rank) + 1;
return { id: `${rank}${suit}`, rank, suit, run, pts: Math.min(10, run) };
}
/** Run-order rank for Gin Rummy: A=1 (low only), 2=2 … K=13. */
export function ginRunRank(card) {
return card.rank === 'A' ? 1 : card.value; // card.value: T=10,J=11,Q=12,K=13,A=14
export function fullDeck() {
const out = [];
for (const s of SUITS) for (const r of RANKS) out.push(makeCard(r, s));
return out;
}
// ── Meld detection ──────────────────────────────────────────────────────────
/** 'T♦' style → '10♦'. */
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';
export const cardFromId = (id) => makeCard(id.slice(0, -1), id.slice(-1));
/** All valid melds (length ≥ 3) that can be formed from a subset of hand. */
export function allCandidateMelds(hand) {
const melds = [];
export const deadwoodOf = (cards) => cards.reduce((s, c) => s + c.pts, 0);
// Sets: 3–4 cards of same rank
const byRank = {};
for (const c of hand) {
if (!byRank[c.rank]) byRank[c.rank] = [];
byRank[c.rank].push(c);
}
for (const cards of Object.values(byRank)) {
if (cards.length < 3) continue;
// All 3-card combinations
for (let i = 0; i < cards.length - 2; i++)
for (let j = i + 1; j < cards.length - 1; j++)
for (let k = j + 1; k < cards.length; k++)
melds.push([cards[i], cards[j], cards[k]]);
// 4-card set
if (cards.length === 4) melds.push([...cards]);
}
// ── Melds ────────────────────────────────────────────────────────────────────
export function isSet(cards) {
return cards.length >= 3 && cards.length <= 4 && cards.every(c => c.rank === cards[0].rank)
&& new Set(cards.map(c => c.suit)).size === cards.length;
}
// Runs: 3+ consecutive ranks, same suit
const bySuit = {};
for (const c of hand) {
if (!bySuit[c.suit]) bySuit[c.suit] = [];
bySuit[c.suit].push(c);
export function isRun(cards) {
if (cards.length < 3 || !cards.every(c => c.suit === cards[0].suit)) return false;
const r = cards.map(c => c.run).sort((a, b) => a - b);
for (let i = 1; i < r.length; i++) if (r[i] !== r[i - 1] + 1) return false;
return true;
}
export const isMeld = (cards) => isSet(cards) || isRun(cards);
/** Display order inside a meld: runs low → high, sets by suit. */
export function orderMeld(cards) {
const m = cards.slice();
if (m.length && m.every(c => c.rank === m[0].rank)) return m.sort((a, b) => SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit]);
return m.sort((a, b) => a.run - b.run);
}
/** Every meld (as bitmask over `hand` indices) the hand can form. */
export function candidateMasks(hand) {
const out = [];
const byRank = new Map(), bySuit = new Map();
hand.forEach((c, i) => {
if (!byRank.has(c.rank)) byRank.set(c.rank, []);
byRank.get(c.rank).push(i);
if (!bySuit.has(c.suit)) bySuit.set(c.suit, []);
bySuit.get(c.suit).push(i);
});
for (const idx of byRank.values()) {
if (idx.length < 3) continue;
const n = idx.length;
for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) for (let c = b + 1; c < n; c++) {
out.push((1 << idx[a]) | (1 << idx[b]) | (1 << idx[c]));
}
if (n === 4) out.push(idx.reduce((m, i) => m | (1 << i), 0));
}
for (const cards of Object.values(bySuit)) {
const sorted = cards.slice().sort((a, b) => ginRunRank(a) - ginRunRank(b));
for (let start = 0; start < sorted.length; start++) {
for (let end = start + 2; end < sorted.length; end++) {
if (ginRunRank(sorted[end]) !== ginRunRank(sorted[end - 1]) + 1) break;
melds.push(sorted.slice(start, end + 1));
for (const idx of bySuit.values()) {
const s = idx.slice().sort((a, b) => hand[a].run - hand[b].run);
for (let a = 0; a < s.length; a++) {
let mask = 1 << s[a];
for (let b = a + 1; b < s.length; b++) {
if (hand[s[b]].run !== hand[s[b - 1]].run + 1) break;
mask |= 1 << s[b];
if (b - a >= 2) out.push(mask);
}
}
}
return melds;
return out;
}
/**
* Find the meld grouping that minimises deadwood.
* @returns {{ melds: Card[][], deadwood: number }}
* Exact meld solver for one hand. solve(mask) → minimum deadwood of the cards
* in `mask`; melds(mask) → the meld groups achieving it (arrays of cards).
*/
export function bestMeldGroups(hand) {
const possible = allCandidateMelds(hand).sort((a, b) => b.length - a.length);
const totalDW = hand.reduce((s, c) => s + ginDeadwoodValue(c), 0);
let bestDeadwood = totalDW;
let bestMelds = [];
function bt(meldIdx, usedKeys, chosenMelds) {
const dw = hand.filter(c => !usedKeys.has(c.key)).reduce((s, c) => s + ginDeadwoodValue(c), 0);
if (dw < bestDeadwood) {
bestDeadwood = dw;
bestMelds = chosenMelds.map(m => [...m]);
export function meldSolver(hand) {
const cands = candidateMasks(hand);
const pts = hand.map(c => c.pts);
const memo = new Map();
const choice = new Map();
const solve = (mask) => {
if (mask === 0) return 0;
const hit = memo.get(mask);
if (hit !== undefined) return hit;
let low = 0;
while (!(mask & (1 << low))) low++;
const bit = 1 << low;
let best = pts[low] + solve(mask & ~bit);
let pick = 0;
for (const m of cands) {
if (!(m & bit) || (m & mask) !== m) continue;
const v = solve(mask & ~m);
if (v < best) { best = v; pick = m; }
}
if (bestDeadwood === 0) return;
for (let i = meldIdx; i < possible.length; i++) {
const m = possible[i];
if (!m.every(c => !usedKeys.has(c.key))) continue;
const next = new Set([...usedKeys, ...m.map(c => c.key)]);
bt(i + 1, next, [...chosenMelds, m]);
}
}
bt(0, new Set(), []);
return { melds: bestMelds, deadwood: bestDeadwood };
}
/** Deadwood total given a hand and declared meld groups. */
export function deadwoodTotal(hand, melds) {
const melded = new Set(melds.flat().map(c => c.key));
return hand.filter(c => !melded.has(c.key)).reduce((s, c) => s + ginDeadwoodValue(c), 0);
}
/** True if card can be legally laid off onto an existing meld. */
export function canLayoff(card, meld) {
if (!meld || meld.length === 0) return false;
const isSet = meld.every(c => c.rank === meld[0].rank);
if (isSet) {
return meld.length < 4
&& card.rank === meld[0].rank
&& !meld.some(c => c.suit === card.suit);
}
// Run
const sorted = meld.slice().sort((a, b) => ginRunRank(a) - ginRunRank(b));
if (card.suit !== sorted[0].suit) return false;
const minR = ginRunRank(sorted[0]);
const maxR = ginRunRank(sorted[sorted.length - 1]);
return ginRunRank(card) === minR - 1 || ginRunRank(card) === maxR + 1;
}
// ── Sorting helpers ─────────────────────────────────────────────────────────
/** Sort by suit order (s,h,d,c) then by run-rank ascending. */
export function sortBySuit(hand) {
const SUIT_ORDER = { s: 0, h: 1, d: 2, c: 3 };
return hand.slice().sort((a, b) =>
(SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit]) || (ginRunRank(a) - ginRunRank(b))
);
}
/** Sort by run-rank ascending then by suit. */
export function sortByRank(hand) {
const SUIT_ORDER = { s: 0, h: 1, d: 2, c: 3 };
return hand.slice().sort((a, b) =>
(ginRunRank(a) - ginRunRank(b)) || (SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit])
);
}
// ── Theme ───────────────────────────────────────────────────────────────────
export const THEME = {
feltTop: 0x1a2d1a,
feltBottom: 0x0d1a0d,
tableRail: 0x2d1f10,
railEdge: 0x1a1208,
cardFace: 0xfdf8ee,
cardBack: 0x3a1a6e,
cardBackHi: 0x5a2e9e,
gold: 0xd4a017,
goldHex: '#d4a017',
ivory: 0xf2ead8,
ivoryHex: '#f2ead8',
meldGlow: 0x22cc66,
knockGlow: 0xe8a020,
discardHi: 0x5588ff,
stockHi: 0x44aa66,
textHex: '#f2ead8',
mutedHex: '#9e9080',
};
// ── Layout ──────────────────────────────────────────────────────────────────
export const CARD_W = 80;
export const CARD_H = 112;
export const CARD_R = 8;
export const HAND_SPREAD = 88; // px between card centres in human hand
export const AI_SPREAD = 28; // compact fan for face-down AI hands
// Canvas dimensions
const GW = 1920;
const GH = 1080;
/**
* Per-seat display info for nPlayers (2–4).
* seat 0 = human (bottom), others = AI.
* Returns array of { x, y, axis:'h'|'v', nameX, nameY, nameAnchor:[ox,oy] }
*/
export function seatPositions(nPlayers) {
// Portrait layout constants (must match buildPortraits in GinRummyGame.js):
// R=36, gap=16, n=10 cards at AI_SPREAD=28 → spread half = 126
// horizontal portrait x offset from seat centre = -(126+R+16) = -178
// vertical portrait y = seat.y - 126 - R - 16 = seat.y - 178
// name below portrait (h): py = seat.y + R + 8 = seat.y + 44
// name above portrait (v): py = portrait_y - R - 8 = (seat.y-178) - 44 = seat.y - 222
// Human seat is always bottom-centre (no portrait name used)
const human = { x: GW / 2, y: GH - 140, axis: 'h', nameX: GW / 2, nameY: GH - 56, nameAnchor: [0.5, 0.5] };
if (nPlayers === 2) {
return [
human,
// top-centre: name below portrait
{ x: GW / 2, y: 140, axis: 'h', nameX: GW / 2 - 178, nameY: 184, nameAnchor: [0.5, 0] },
];
}
if (nPlayers === 3) {
return [
human,
// top-left: name below portrait
{ x: 440, y: 140, axis: 'h', nameX: 440 - 178, nameY: 184, nameAnchor: [0.5, 0] },
// top-right: name below portrait
{ x: GW - 440, y: 140, axis: 'h', nameX: GW - 440 - 178, nameY: 184, nameAnchor: [0.5, 0] },
];
}
// 4 players
return [
human,
// left: name above portrait
{ x: 100, y: GH / 2, axis: 'v', nameX: 100, nameY: GH / 2 - 222, nameAnchor: [0.5, 1] },
// top-centre: name below portrait
{ x: GW / 2, y: 140, axis: 'h', nameX: GW / 2 - 178, nameY: 184, nameAnchor: [0.5, 0] },
// right: name above portrait
{ x: GW - 100, y: GH / 2, axis: 'v', nameX: GW - 100, nameY: GH / 2 - 222, nameAnchor: [0.5, 1] },
];
}
/** Center positions of stock and discard piles. */
export function pilePositions() {
return {
stock: { x: GW / 2 - 90, y: GH / 2 },
discard: { x: GW / 2 + 90, y: GH / 2 },
memo.set(mask, best);
choice.set(mask, pick);
return best;
};
const melds = (mask) => {
solve(mask);
const out = [];
let m = mask;
while (m) {
solve(m);
const pick = choice.get(m);
let low = 0;
while (!(m & (1 << low))) low++;
if (pick) {
const g = [];
for (let i = 0; i < hand.length; i++) if (pick & (1 << i)) g.push(hand[i]);
out.push(orderMeld(g));
m &= ~pick;
} else m &= ~(1 << low);
}
return out;
};
const full = (1 << hand.length) - 1;
return { hand, full, solve, melds };
}
/** { melds, deadwood, loose } for a whole hand. */
export function bestMelds(hand) {
const S = meldSolver(hand);
const melds = S.melds(S.full);
const used = new Set(melds.flat().map(c => c.id));
const loose = hand.filter(c => !used.has(c.id));
return { melds, deadwood: deadwoodOf(loose), loose };
}
export const deadwoodValue = (hand) => meldSolver(hand).solve((1 << hand.length) - 1);
/**
* For an 11-card hand: the deadwood left after each possible discard.
* Returns [{ card, deadwood }] in hand order (one solver, shared memo).
*/
export function discardOptions(hand, banned = null) {
const S = meldSolver(hand);
return hand.map((card, i) => ({ card, deadwood: S.solve(S.full & ~(1 << i)), banned: card.id === banned }));
}
/** Best discard (lowest deadwood after, then the highest card dumped). */
export function bestDiscard(hand, banned = null) {
let best = null;
for (const o of discardOptions(hand, banned)) {
if (o.banned) continue;
if (!best || o.deadwood < best.deadwood || (o.deadwood === best.deadwood && o.card.pts > best.card.pts)) best = o;
}
return best;
}
// ── Lay-offs ─────────────────────────────────────────────────────────────────
/** Can `card` extend `meld` (a set or a run, already including earlier lay-offs)? */
export function canLayoff(card, meld) {
if (!meld?.length || meld.some(c => c.id === card.id)) return false;
if (meld.every(c => c.rank === meld[0].rank)) {
return meld.length < 4 && card.rank === meld[0].rank && !meld.some(c => c.suit === card.suit);
}
if (card.suit !== meld[0].suit) return false;
let lo = 99, hi = 0;
for (const c of meld) { lo = Math.min(lo, c.run); hi = Math.max(hi, c.run); }
return card.run === lo - 1 || card.run === hi + 1;
}
/**
* The defender's best response to a knock: which cards to lay off (and where)
* and how to meld the rest, minimising deadwood. Exhaustive (lay-off chains
* like 8♥ then 9♥ onto 5-6-7♥ included); the candidate set is tiny.
* Returns { layoffs: [{ card, meldIdx }], melds, deadwood, loose }.
*/
export function bestDefense(hand, knockerMelds) {
let best = null;
const melds0 = knockerMelds.map(m => m.slice());
const seen = new Set();
const visit = (remaining, melds, layoffs) => {
const key = remaining.map(c => c.id).sort().join(',') + '|' + melds.map(m => m.length).join(',');
if (seen.has(key)) return;
seen.add(key);
const r = bestMelds(remaining);
if (!best || r.deadwood < best.deadwood || (r.deadwood === best.deadwood && layoffs.length < best.layoffs.length)) {
best = { layoffs: layoffs.slice(), melds: r.melds, deadwood: r.deadwood, loose: r.loose };
}
for (let i = 0; i < remaining.length; i++) {
const c = remaining[i];
for (let mi = 0; mi < melds.length; mi++) {
if (!canLayoff(c, melds[mi])) continue;
const nm = melds.map((m, j) => (j === mi ? [...m, c] : m));
visit(remaining.filter((_, j) => j !== i), nm, [...layoffs, { card: c, meldIdx: mi }]);
}
}
};
visit(hand.slice(), melds0, []);
return best;
}
// ── Sorting ──────────────────────────────────────────────────────────────────
export const bySuit = (a, b) => SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit] || a.run - b.run;
export const byRank = (a, b) => a.run - b.run || SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit];
/**
* Melds first (each run/set together, longest first), then the deadwood by
* suit. Returns { order: cards, groups: [n, n, …, loose] } — groups gives the
* size of each meld block; the loose block is last.
*/
export function meldOrder(hand) {
const { melds, loose } = bestMelds(hand);
const ms = melds.slice().sort((a, b) => {
const sa = a.every(c => c.rank === a[0].rank), sb = b.every(c => c.rank === b[0].rank);
return (sa - sb) || (a[0].suit === b[0].suit ? a[0].run - b[0].run : SUIT_ORDER[a[0].suit] - SUIT_ORDER[b[0].suit]) || (a[0].run - b[0].run);
});
const rest = loose.slice().sort(bySuit);
return { order: [...ms.flat(), ...rest], melds: ms, loose: rest };
}
// ── Scoring helpers ──────────────────────────────────────────────────────────
/** Points a single defender result is worth (before the Oklahoma doubling). */
export function pairScore(kind, knockerDW, defenderDW, rules) {
if (kind === 'gin') return { to: 'knocker', pts: defenderDW + rules.ginBonus, why: 'gin' };
if (kind === 'biggin') return { to: 'knocker', pts: defenderDW + rules.bigGinBonus, why: 'biggin' };
if (knockerDW < defenderDW) return { to: 'knocker', pts: defenderDW - knockerDW, why: 'knock' };
return { to: 'defender', pts: knockerDW - defenderDW + rules.undercutBonus, why: 'undercut' };
}

File diff suppressed because it is too large Load Diff

View File

@ -1,258 +1,363 @@
// Gin Rummy — pure, deterministic game engine. No Phaser, no timers.
// Scene and headless harness drive it identically.
// Gin Rummy — pure rules engine. No Phaser, no timers.
//
// State is plain JSON (autosaved between turns). 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/verifyGinRummy.js all drive it.
//
// Round flow
// upcard (rules.upcard) the first player, then each other player in turn,
// may take the face-up card; if everyone passes, the first player
// must draw from the stock
// draw take the stock top or the discard top
// discard discard (not the card you just took from the pile), knock
// (discard + deadwood ≤ knock limit), gin (knock on 0) or Big Gin
// (all 11 melded, no discard)
// layoff each defender in turn lays cards off on the knocker's melds
// roundOver / gameOver
// The hand is void ("wash") when a discard leaves 2 cards in the stock
// without a knock — after one reshuffle of the discard pile at 3–4 players.
import {
Deck,
HAND_SIZE,
WIN_SCORE,
MAX_DEADWOOD_TO_KNOCK,
GIN_BONUS,
UNDERCUT_BONUS,
bestMeldGroups,
deadwoodTotal,
canLayoff,
DEFAULT_RULES, HAND_SIZE, fullDeck, bestMelds, canLayoff, orderMeld, deadwoodOf, pairScore, meldSolver,
} from './GinRummyData.js';
export class GinRummyLogic {
constructor(nPlayers = 4, rng = null) {
this.nPlayers = nPlayers;
this.rng = rng ?? Math.random;
this.players = null; // [{ hand, score }]
this.stock = [];
this.discard = [];
this.currentPlayer = 0;
this.phase = 'draw'; // 'draw' | 'discard' | 'gameover'
this.knocker = null;
this.knockerMelds = [];
this.layoffPlayer = -1; // seat currently doing layoff (-1 = not in layoff)
this.roundScores = []; // delta per player for the current round
this.round = 1;
this.firstPlayer = 0; // who goes first each round (rotates)
}
export const VERSION = 1;
export const WASH_AT = 2;
// ── Round setup ────────────────────────────────────────────────────────────
const clone = (o) => (typeof structuredClone === 'function' ? structuredClone(o) : JSON.parse(JSON.stringify(o)));
newGame() {
this.players = Array.from({ length: this.nPlayers }, () => ({ hand: [], score: 0 }));
this.round = 1;
this.firstPlayer = 0;
this.phase = 'draw';
this._dealRound();
}
newRound() {
this.round++;
this.firstPlayer = (this.firstPlayer + 1) % this.nPlayers;
this._dealRound();
}
_dealRound() {
const deck = new Deck();
// Fisher-Yates using injected rng
const cards = deck.cards;
for (let i = cards.length - 1; i > 0; i--) {
const j = Math.floor(this.rng() * (i + 1));
[cards[i], cards[j]] = [cards[j], cards[i]];
}
for (const p of this.players) p.hand = [];
// Deal HAND_SIZE cards to each player (rotating from firstPlayer)
let idx = 0;
for (let c = 0; c < HAND_SIZE; c++) {
for (let s = 0; s < this.nPlayers; s++) {
const seat = (this.firstPlayer + s) % this.nPlayers;
this.players[seat].hand.push(cards[idx++]);
}
}
this.stock = cards.slice(idx + 1); // remaining stock after top card to discard
this.discard = [cards[idx]]; // initial discard card
this.currentPlayer = this.firstPlayer;
this.phase = 'draw';
this.knocker = null;
this.knockerMelds = [];
this.layoffPlayer = -1;
this.roundScores = new Array(this.nPlayers).fill(0);
}
// ── Draw ───────────────────────────────────────────────────────────────────
drawStock(seat) {
if (this.phase !== 'draw' || this.currentPlayer !== seat) return false;
if (this.stock.length === 0) {
// Reshuffle discard pile (minus the top card) back into stock
if (this.discard.length <= 1) {
// True impasse — end round with no scoring (rare)
this.phase = 'roundover';
this.winner = null;
return true;
}
const top = this.discard.pop();
this.stock = this.discard.reverse();
for (let i = this.stock.length - 1; i > 0; i--) {
const j = Math.floor(this.rng() * (i + 1));
[this.stock[i], this.stock[j]] = [this.stock[j], this.stock[i]];
}
this.discard = [top];
}
this.players[seat].hand.push(this.stock.shift());
this.phase = 'discard';
return true;
}
drawDiscard(seat) {
if (this.phase !== 'draw' || this.currentPlayer !== seat) return false;
if (this.discard.length === 0) return false;
this.players[seat].hand.push(this.discard.pop());
this.phase = 'discard';
return true;
}
// ── Discard ────────────────────────────────────────────────────────────────
discardCard(seat, cardKey) {
if (this.phase !== 'discard' || this.currentPlayer !== seat) return false;
const idx = this.players[seat].hand.findIndex(c => c.key === cardKey);
if (idx === -1) return false;
const [card] = this.players[seat].hand.splice(idx, 1);
this.discard.push(card);
this.currentPlayer = (this.currentPlayer + 1) % this.nPlayers;
this.phase = 'draw';
return true;
}
// ── Knock / Gin ────────────────────────────────────────────────────────────
// Both methods discard the given card internally (hand goes 11→10), then
// validate the remaining 10-card hand before committing.
/**
* Knock: discard `discardKey`, then declare melds on remaining 10 cards.
* Validates deadwood ≤ MAX_DEADWOOD_TO_KNOCK. Returns false if illegal.
*/
knock(seat, discardKey, meldGroups) {
if (this.phase !== 'discard' || this.currentPlayer !== seat) return false;
const idx = this.players[seat].hand.findIndex(c => c.key === discardKey);
if (idx === -1) return false;
const [discarded] = this.players[seat].hand.splice(idx, 1);
const dw = deadwoodTotal(this.players[seat].hand, meldGroups);
if (dw > MAX_DEADWOOD_TO_KNOCK) {
this.players[seat].hand.splice(idx, 0, discarded); // rollback
return false;
}
this.discard.push(discarded);
this.knocker = seat;
this.knockerMelds = meldGroups.map(m => [...m]);
this.phase = 'layoff';
this.layoffPlayer = (seat + 1) % this.nPlayers;
return true;
}
/** Gin: discard `discardKey`, validate 0 deadwood, trigger immediate scoring. */
gin(seat, discardKey, meldGroups) {
if (this.phase !== 'discard' || this.currentPlayer !== seat) return false;
const idx = this.players[seat].hand.findIndex(c => c.key === discardKey);
if (idx === -1) return false;
const [discarded] = this.players[seat].hand.splice(idx, 1);
const dw = deadwoodTotal(this.players[seat].hand, meldGroups);
if (dw !== 0) {
this.players[seat].hand.splice(idx, 0, discarded); // rollback
return false;
}
this.discard.push(discarded);
this.knocker = seat;
this.knockerMelds = meldGroups.map(m => [...m]);
this.phase = 'roundover';
this._computeRoundScores(true);
return true;
}
// ── Layoff ─────────────────────────────────────────────────────────────────
/**
* Lay off cards from `seat` onto knocker's melds.
* layoffs: [{ cardKey, meldIdx }]
* Returns false if any layoff is illegal.
*/
layoff(seat, layoffs) {
if (this.phase !== 'layoff' || seat !== this.layoffPlayer) return false;
const player = this.players[seat];
// Validate and apply each layoff in sequence
for (const { cardKey, meldIdx } of layoffs) {
const cardIdx = player.hand.findIndex(c => c.key === cardKey);
if (cardIdx === -1) return false;
const meld = this.knockerMelds[meldIdx];
if (!meld || !canLayoff(player.hand[cardIdx], meld)) return false;
meld.push(player.hand[cardIdx]);
player.hand.splice(cardIdx, 1);
}
return true;
}
/**
* Pass layoff for `seat` (or explicitly end their layoff turn).
* Advances to next opponent, or triggers scoring when all done.
*/
passLayoff(seat) {
if (this.phase !== 'layoff' || seat !== this.layoffPlayer) return false;
const next = (seat + 1) % this.nPlayers;
if (next === this.knocker) {
// All opponents have had their turn
this.phase = 'roundover';
this._computeRoundScores(false);
} else {
this.layoffPlayer = next;
}
return true;
}
// ── Scoring ────────────────────────────────────────────────────────────────
_computeRoundScores(isGin) {
const k = this.knocker;
const { melds: kMelds, deadwood: kDW } = bestMeldGroups(this.players[k].hand);
// Use declared melds if they're better (they should be equal or declared was manual)
const knockerDW = Math.min(kDW, deadwoodTotal(this.players[k].hand, this.knockerMelds));
for (let s = 0; s < this.nPlayers; s++) {
if (s === k) continue;
const { deadwood: oppDW } = bestMeldGroups(this.players[s].hand);
if (isGin) {
// Gin: knocker earns oppDW + GIN_BONUS, no undercut possible
this.roundScores[k] += oppDW + GIN_BONUS;
} else if (knockerDW < oppDW) {
// Normal knock win
this.roundScores[k] += oppDW - knockerDW;
} else {
// Undercut or tie: opponent wins
this.roundScores[s] += knockerDW - oppDW + UNDERCUT_BONUS;
}
}
// Apply to cumulative scores
for (let s = 0; s < this.nPlayers; s++) {
this.players[s].score += this.roundScores[s];
}
// Check win
const winner = this.players.findIndex(p => p.score >= WIN_SCORE);
this.phase = winner >= 0 ? 'gameover' : 'roundover';
this.winner = winner >= 0 ? winner : null;
}
// ── Helpers ────────────────────────────────────────────────────────────────
get discardTop() {
return this.discard.length > 0 ? this.discard[this.discard.length - 1] : null;
}
get stockCount() {
return this.stock.length;
}
/** Compute best meld grouping for a seat (for AI and UI hints). */
bestMelds(seat) {
return bestMeldGroups(this.players[seat].hand);
}
// mulberry32 on a state-held integer, so a saved game replays the same shuffles
function rand(gs) {
gs.rng = (gs.rng + 0x6d2b79f5) >>> 0;
let t = gs.rng;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
function shuffle(gs, arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(rand(gs) * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
const emptyStats = () => ({ won: 0, gins: 0, bigGins: 0, knocks: 0, undercuts: 0, undercutBy: 0, best: 0, knockDW: 0 });
// ── Setup ────────────────────────────────────────────────────────────────────
export function createGame({ players = 2, rules = {}, seed = (Date.now() >>> 0), dealer = null } = {}) {
const n = Math.max(2, Math.min(4, players | 0));
const gs = {
version: VERSION,
n,
rules: { ...DEFAULT_RULES, ...rules },
rng: seed >>> 0,
scores: new Array(n).fill(0),
boxes: new Array(n).fill(0),
stats: Array.from({ length: n }, emptyStats),
history: [],
round: 0,
dealer: 0,
winner: null,
final: null,
log: [],
};
gs.dealer = dealer ?? Math.floor(rand(gs) * n);
return deal(gs);
}
/** Deal a fresh round onto `gs` (mutates the given clone). */
function deal(gs) {
gs.round++;
const n = gs.n;
const cards = shuffle(gs, fullDeck());
gs.hands = Array.from({ length: n }, () => []);
const first = (gs.dealer + 1) % n;
let k = 0;
for (let c = 0; c < HAND_SIZE; c++) for (let s = 0; s < n; s++) gs.hands[(first + s) % n].push(cards[k++]);
const up = cards[k++];
gs.discard = [up];
gs.stock = cards.slice(k);
gs.first = first;
gs.current = first;
gs.phase = gs.rules.upcard ? 'upcard' : 'draw';
gs.upcardPassed = [];
gs.stockOnly = false;
gs.takenFrom = null; // id of the card just taken from the discard pile
gs.knockLimit = gs.rules.oklahoma ? up.pts : gs.rules.knockMax;
gs.doubled = !!gs.rules.oklahoma && up.suit === 's';
gs.reshuffles = 0;
gs.maxReshuffles = n > 2 ? 1 : 0;
gs.pickups = Array.from({ length: n }, () => []); // ids each seat took from the discard pile
gs.discards = Array.from({ length: n }, () => []); // ids each seat discarded
gs.turn = 0;
gs.showdown = null;
gs.result = null;
gs.log = [{ kind: 'deal', round: gs.round, dealer: gs.dealer, upcard: up.id }];
return gs;
}
export function nextRound(gs) {
if (gs.phase !== 'roundOver') return gs;
const g = clone(gs);
if (g.result?.kind !== 'wash') g.dealer = (g.dealer + 1) % g.n; // a void hand is redealt by the same dealer
return deal(g);
}
// ── Queries ──────────────────────────────────────────────────────────────────
export const topDiscard = (gs) => gs.discard[gs.discard.length - 1] ?? null;
export const handOf = (gs, seat) => gs.hands[seat];
export const isOver = (gs) => gs.phase === 'roundOver' || gs.phase === 'gameOver';
export const actor = (gs) => (gs.phase === 'layoff' ? gs.showdown.layoffSeat : gs.current);
/** In the discard phase: [{ card, deadwood, canKnock, gin, banned }] for every card. */
export function discardChoices(gs, seat) {
const hand = gs.hands[seat];
const S = meldSolver(hand);
return hand.map((card, i) => {
const dw = S.solve(S.full & ~(1 << i));
const banned = card.id === gs.takenFrom;
return { card, deadwood: dw, banned, canKnock: !banned && dw <= gs.knockLimit, gin: !banned && dw === 0 };
});
}
export function canBigGin(gs, seat) {
return gs.rules.bigGin && gs.phase === 'discard' && gs.current === seat
&& gs.hands[seat].length === HAND_SIZE + 1 && bestMelds(gs.hands[seat]).deadwood === 0;
}
export function cardsInPlay(gs) {
let n = gs.stock.length + gs.discard.length;
for (const h of gs.hands) n += h.length;
if (gs.showdown) for (const m of gs.showdown.melds) n += m.filter(c => c.laidBy != null).length;
return n;
}
// ── Upcard offer ─────────────────────────────────────────────────────────────
export function takeUpcard(gs, seat) {
if (gs.phase !== 'upcard' || gs.current !== seat || !gs.discard.length) return gs;
const g = clone(gs);
const c = g.discard.pop();
g.hands[seat].push(c);
g.takenFrom = c.id;
g.pickups[seat].push(c.id);
g.phase = 'discard';
g.turn++;
g.log.push({ kind: 'take', seat, card: c.id, upcard: true });
return g;
}
export function passUpcard(gs, seat) {
if (gs.phase !== 'upcard' || gs.current !== seat) return gs;
const g = clone(gs);
g.upcardPassed.push(seat);
g.log.push({ kind: 'passUpcard', seat });
if (g.upcardPassed.length >= g.n) {
g.current = g.first;
g.phase = 'draw';
g.stockOnly = true;
} else g.current = (seat + 1) % g.n;
return g;
}
// ── Draw ─────────────────────────────────────────────────────────────────────
export function drawStock(gs, seat) {
if (gs.phase !== 'draw' || gs.current !== seat || !gs.stock.length) return gs;
const g = clone(gs);
const c = g.stock.shift();
g.hands[seat].push(c);
g.takenFrom = null;
g.stockOnly = false;
g.phase = 'discard';
g.turn++;
g.log.push({ kind: 'draw', seat, card: c.id });
return g;
}
export function drawDiscard(gs, seat) {
if (gs.phase !== 'draw' || gs.current !== seat || gs.stockOnly || !gs.discard.length) return gs;
const g = clone(gs);
const c = g.discard.pop();
g.hands[seat].push(c);
g.takenFrom = c.id;
g.pickups[seat].push(c.id);
g.phase = 'discard';
g.turn++;
g.log.push({ kind: 'take', seat, card: c.id });
return g;
}
// ── Discard / knock ──────────────────────────────────────────────────────────
function removeFromHand(g, seat, id) {
const i = g.hands[seat].findIndex(c => c.id === id);
return i < 0 ? null : g.hands[seat].splice(i, 1)[0];
}
export function discard(gs, seat, id) {
if (gs.phase !== 'discard' || gs.current !== seat || id === gs.takenFrom) return gs;
if (!gs.hands[seat].some(c => c.id === id)) return gs;
const g = clone(gs);
const c = removeFromHand(g, seat, id);
g.discard.push(c);
g.discards[seat].push(c.id);
g.takenFrom = null;
g.log.push({ kind: 'discard', seat, card: c.id });
if (g.stock.length <= WASH_AT) {
if (g.reshuffles < g.maxReshuffles && g.discard.length > 1) {
const top = g.discard.pop();
g.stock = [...g.stock, ...shuffle(g, g.discard)];
g.discard = [top];
g.reshuffles++;
g.log.push({ kind: 'reshuffle', count: g.stock.length });
} else {
g.phase = 'roundOver';
g.result = { kind: 'wash', knocker: null, lines: [], deltas: new Array(g.n).fill(0), doubled: false };
g.history.push({ round: g.round, kind: 'wash', knocker: null, deltas: g.result.deltas.slice() });
g.log.push({ kind: 'wash' });
return g;
}
}
g.current = (seat + 1) % g.n;
g.phase = 'draw';
return g;
}
/** Discard `id` and knock (or go gin automatically when the rest melds completely). */
export function knock(gs, seat, id) {
if (gs.phase !== 'discard' || gs.current !== seat || id === gs.takenFrom) return gs;
const hand = gs.hands[seat];
if (!hand.some(c => c.id === id)) return gs;
const rest = hand.filter(c => c.id !== id);
const bm = bestMelds(rest);
if (bm.deadwood > gs.knockLimit) return gs;
const g = clone(gs);
const c = removeFromHand(g, seat, id);
g.discard.push(c);
g.discards[seat].push(c.id);
g.takenFrom = null;
return startShowdown(g, seat, bm.deadwood === 0 ? 'gin' : 'knock', bm);
}
/** All 11 cards melded right after drawing: Big Gin, no discard. */
export function bigGin(gs, seat) {
if (!canBigGin(gs, seat)) return gs;
const g = clone(gs);
return startShowdown(g, seat, 'biggin', bestMelds(g.hands[seat]));
}
function startShowdown(g, seat, kind, bm) {
const order = [];
for (let s = (seat + 1) % g.n; s !== seat; s = (s + 1) % g.n) order.push(s);
g.showdown = {
knocker: seat,
kind,
knockerDW: bm.deadwood,
melds: bm.melds.map(m => orderMeld(m)),
loose: bm.loose.map(c => c.id),
order,
layoffSeat: kind === 'knock' ? order[0] : null,
laid: Object.fromEntries(order.map(s => [s, []])),
};
// the knocker's cards stay in their hand array (melds reference copies)
g.log.push({ kind, seat, deadwood: bm.deadwood });
const st = g.stats[seat];
if (kind === 'knock') { st.knocks++; st.knockDW += bm.deadwood; }
if (kind === 'gin') st.gins++;
if (kind === 'biggin') st.bigGins++;
if (kind === 'knock') { g.phase = 'layoff'; return g; }
return score(g);
}
// ── Lay-offs ─────────────────────────────────────────────────────────────────
export function layoff(gs, seat, id, meldIdx) {
if (gs.phase !== 'layoff' || gs.showdown.layoffSeat !== seat) return gs;
const card = gs.hands[seat].find(c => c.id === id);
const meld = gs.showdown.melds[meldIdx];
if (!card || !canLayoff(card, meld)) return gs;
const g = clone(gs);
const c = removeFromHand(g, seat, id);
const sd = g.showdown;
sd.melds[meldIdx] = orderMeld([...sd.melds[meldIdx], { ...c, laidBy: seat }]);
sd.laid[seat].push({ id: c.id, meldIdx });
g.log.push({ kind: 'layoff', seat, card: c.id, meldIdx });
return g;
}
/** The first meld `id` can be laid off on (or -1). */
export function layoffTarget(gs, id) {
const card = gs.hands[gs.showdown?.layoffSeat]?.find(c => c.id === id);
if (!card) return -1;
return gs.showdown.melds.findIndex(m => canLayoff(card, m));
}
export function endLayoff(gs, seat) {
if (gs.phase !== 'layoff' || gs.showdown.layoffSeat !== seat) return gs;
const g = clone(gs);
const sd = g.showdown;
const i = sd.order.indexOf(seat);
g.log.push({ kind: 'endLayoff', seat });
if (i < sd.order.length - 1) { sd.layoffSeat = sd.order[i + 1]; return g; }
sd.layoffSeat = null;
return score(g);
}
// ── Scoring ──────────────────────────────────────────────────────────────────
function score(g) {
const sd = g.showdown;
const k = sd.knocker;
const deltas = new Array(g.n).fill(0);
const mult = g.doubled ? 2 : 1;
const lines = sd.order.map(seat => {
const bm = bestMelds(g.hands[seat]);
const r = pairScore(sd.kind, sd.knockerDW, bm.deadwood, g.rules);
const pts = r.pts * mult;
if (r.to === 'knocker') deltas[k] += pts; else deltas[seat] += pts;
if (r.why === 'undercut') { g.stats[seat].undercuts++; g.stats[k].undercutBy++; }
return {
seat, deadwood: bm.deadwood, melds: bm.melds, loose: bm.loose.map(c => c.id),
laid: sd.laid[seat]?.map(l => l.id) ?? [], to: r.to, pts, why: r.why,
};
});
for (let s = 0; s < g.n; s++) {
g.scores[s] += deltas[s];
if (deltas[s] > 0) { g.boxes[s]++; g.stats[s].won++; g.stats[s].best = Math.max(g.stats[s].best, deltas[s]); }
}
const undercut = lines.some(l => l.why === 'undercut');
g.result = { kind: sd.kind, knocker: k, knockerDW: sd.knockerDW, lines, deltas, doubled: g.doubled, undercut };
g.history.push({ round: g.round, kind: sd.kind, knocker: k, deltas: deltas.slice(), undercut });
g.log.push({ kind: 'score', deltas: deltas.slice() });
const top = Math.max(...g.scores);
if (top >= g.rules.target) {
g.phase = 'gameOver';
// highest score wins; a tie goes to whoever won this hand (else the lower seat)
const tied = g.scores.map((v, s) => (v === top ? s : -1)).filter(s => s >= 0);
g.winner = tied.find(s => deltas[s] > 0) ?? tied[0];
g.final = finalTally(g);
} else g.phase = 'roundOver';
return g;
}
/**
* Match-end tally: points + game bonus (winner) + box bonus per hand won;
* a shutout (no opponent scored at all) doubles the winner's total.
*/
export function finalTally(gs) {
const r = gs.rules;
return gs.scores.map((pts, s) => {
if (!r.bonuses) return { seat: s, points: pts, game: 0, box: 0, shutout: false, total: pts };
const game = s === gs.winner ? r.gameBonus : 0;
const box = gs.boxes[s] * r.boxBonus;
const shutout = s === gs.winner && gs.scores.every((v, t) => t === s || v === 0);
const total = (pts + game + box) * (shutout ? 2 : 1);
return { seat: s, points: pts, game, box, shutout, total };
});
}
// ── Save / load ──────────────────────────────────────────────────────────────
export function isValidSave(gs, players) {
return !!gs && gs.version === VERSION && gs.n === players && Array.isArray(gs.hands)
&& ['upcard', 'draw', 'discard'].includes(gs.phase) && cardsInPlay(gs) === 52;
}
export { deadwoodOf };

View File

@ -0,0 +1,160 @@
// Gin Rummy table layout — Phaser-free so tools/verifyGinRummy.js can test it.
//
// "The Juniper Still": an oak tasting-bar table with a bottle-green baize
// inlay, on the shared card-table kit. Seats are the Uno arrangement
// (2: across · 3: far corners · 4: left / across / right). The stock and the
// discard pile sit in the middle.
//
// The showdown (after a knock / gin) needs the middle: the piles slide to the
// left end of the table and the hands are laid out as ROWS — the knocker's
// melds on top, each opponent's hand under it, grouped into melds with the
// deadwood at the end. The human, when defending, keeps their cards in their
// own fan (so they can drag lay-offs up onto the knocker's melds).
import {
makeTable, CARD_W, CARD_H, fanPose, fanPoint, HUMAN_PLATE, PLATE,
} from '../../ui/cardtable/TableGeometry.js';
export const VIEW = { cx: 960, yFar: 92, yNear: 1000, sFar: 0.76, halfW: 940, squash: 0.9 };
export const T = makeTable(VIEW, { shape: 'rect', corner: 0.17, feltK: 0.94, faceH: 38 });
export const SQ = VIEW.squash;
// seat colours: gold (you) · juniper blue · tonic lime · bitters red
export const SEAT_COLORS = [0xf2c14e, 0x6fa8dc, 0x9ad46a, 0xe0707a];
export const SEAT_HEX = ['#f2c14e', '#6fa8dc', '#9ad46a', '#e0707a'];
// meld group tints (hand glow + showdown brackets)
export const MELD_COLORS = [0x5ee0c0, 0xffc861, 0xc58cff, 0x7cc8ff];
export const MELD_HEX = ['#5ee0c0', '#ffc861', '#c58cff', '#7cc8ff'];
const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 80, curve: 1.2, tilt: 0.03, q: 1, maxSpan: 860, maxDrop: 30, maxTilt: 0.18 };
const opp = (x, y, rot, k = 0.55) => ({ x, y, rot, k, spread: 34, curve: 0.5, tilt: 0.03, q: 1, maxSpan: 420, maxDrop: 14, maxTilt: 0.16 });
const SEATS = {
2: [
{ fan: HUMAN_FAN, plate: HUMAN_PLATE },
{ fan: opp(960, 80, Math.PI), plate: { x: 1420, y: 86 } },
],
3: [
{ fan: HUMAN_FAN, plate: HUMAN_PLATE },
{ fan: opp(620, 82, Math.PI - 0.1), plate: { x: 190, y: 150 } },
{ fan: opp(1300, 82, Math.PI + 0.1), plate: { x: 1730, y: 150 } },
],
4: [
{ fan: HUMAN_FAN, plate: HUMAN_PLATE },
{ fan: opp(84, 540, Math.PI / 2, 0.5), plate: { x: 190, y: 150 } },
{ fan: opp(960, 80, Math.PI, 0.52), plate: { x: 1400, y: 86 } },
{ fan: opp(1836, 540, -Math.PI / 2, 0.5), plate: { x: 1730, y: 150 } },
],
};
export const PILE_K = 1.0;
export const STOCK_UV = { u: -0.105, v: 0.43 };
export const DISCARD_UV = { u: 0.105, v: 0.43 };
// during the showdown the piles retire to the left end of the table
export const SD_STOCK_UV = { u: -0.84, v: 0.5 };
export const SD_DISCARD_UV = { u: -0.84, v: 0.78 };
export const SD_PILE_K = 0.62;
// showdown rows (screen space)
export const ROW = { x0: 640, k: 0.78, step: 37, gap: 26, top: 300, pitch: 136, labelX: 620 };
export const METER = { x: 960, y: 806, w: 470, h: 16 };
const cache = new Map();
export function layoutFor(playerCount) {
if (cache.has(playerCount)) return cache.get(playerCount);
const defs = SEATS[playerCount];
if (!defs) throw new Error(`Gin Rummy layout supports 2..4 players, got ${playerCount}`);
const L = {
playerCount,
seats: defs.map((d, seat) => ({ seat, fan: d.fan, plate: d.plate })),
stock: T.flat(STOCK_UV.u, STOCK_UV.v, PILE_K),
discard: T.flat(DISCARD_UV.u, DISCARD_UV.v, PILE_K),
sdStock: T.flat(SD_STOCK_UV.u, SD_STOCK_UV.v, SD_PILE_K),
sdDiscard: T.flat(SD_DISCARD_UV.u, SD_DISCARD_UV.v, SD_PILE_K),
};
cache.set(playerCount, L);
return L;
}
/**
* Human hand pose with optional meld gaps: `slots[i]` is card i's (possibly
* fractional) position along the fan, `total` the fan length in slots.
*/
export function handPose(L, seat, i, n, lift = 0, slots = null, total = null) {
if (slots) return fanPose(L.seats[seat].fan, slots[i], total, lift);
return fanPose(L.seats[seat].fan, i, n, lift);
}
/** Slot positions for a hand split into blocks (sizes), `gap` slots between blocks. */
export function blockSlots(sizes, gap = 0.42) {
const slots = [];
let x = 0;
sizes.forEach((n, b) => {
if (b > 0 && n > 0) x += gap;
for (let i = 0; i < n; i++) slots.push(x++);
});
return { slots, total: Math.max(1, x) };
}
/** Where an opponent's ghost hand rests. */
export function handHome(L, seat) {
const f = L.seats[seat].fan;
const p = fanPoint(f, 0, -CARD_H * 0.95);
return { ...p, rot: f.rot, k: f.k };
}
/** Card-count badge at the end of an opponent's fan. */
export function handBadge(L, seat) {
const f = L.seats[seat].fan;
return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 46), 0);
}
export function spotFor(L, seat) {
const f = L.seats[seat].fan;
if (seat === 0) return { x: f.x, y: 820, w: 1300, h: 420 };
const c = fanPoint(f, 0, -CARD_H * 0.9);
const side = Math.abs(Math.sin(f.rot)) > 0.7;
return side ? { x: c.x, y: c.y, w: 420, h: 620 } : { x: c.x, y: c.y + 30, w: 640, h: 320 };
}
// ── Showdown rows ────────────────────────────────────────────────────────────
/** Row r's baseline y for `rows` rows (centred in the table's middle band). */
export function rowY(r, rows) {
const span = (rows - 1) * ROW.pitch;
const mid = rows <= 2 ? 470 : 500;
return mid - span / 2 + r * ROW.pitch;
}
/**
* Card poses for one row: blocks = [[card, …], …] (melds, then loose last).
* Returns { poses: [[pose…]…], blockX: [{ x0, x1 }], x1 }.
*/
export function rowPoses(r, rows, blocks) {
const y = rowY(r, rows);
const s = ROW.k * T.P.unproject(960, y).s;
const poses = [];
const blockX = [];
let x = ROW.x0 + (CARD_W * s) / 2;
blocks.forEach((b, bi) => {
if (bi > 0) x += ROW.gap;
const ps = [];
const x0 = x;
b.forEach((_, i) => {
if (i > 0) x += ROW.step;
ps.push({ x, y, rot: 0, s, q: SQ });
});
poses.push(ps);
blockX.push({ x0: x0 - (CARD_W * s) / 2, x1: x + (CARD_W * s) / 2 });
x += b.length ? 0 : -ROW.gap;
});
return { poses, blockX, y, s, x1: blockX.length ? blockX[blockX.length - 1].x1 : ROW.x0 };
}
/** Screen rect of a row block (for brackets, hit tests and drop targets). */
export function blockRect(row, bi) {
const b = row.blockX[bi];
const hh = (CARD_H / 2) * row.s * SQ;
return { x0: b.x0, x1: b.x1, y0: row.y - hh, y1: row.y + hh };
}
export { PLATE };

View File

@ -0,0 +1,140 @@
# Pull Up a Stool — Welcome to The Juniper Still
*By Mags Calloway — head distiller, keeper of the copper pot, and undefeated at this table since the Coolidge administration (allegedly)*
---
Evening, friend. Shake the rain off, hang your coat by the barrels, and mind the still — she runs hot. The tasting's done for the night, which means the cards come out. We play **Gin Rummy** here. Of course we do. What else would you play in a gin house?
I'll teach you the way my old master taught me: short, honest, and with a drink in reach. Making gin and playing gin are the same craft, really. You start with a mess of botanicals, you keep what belongs together, and you throw out what doesn't. Whatever's left over at the end is what spoils the batch.
## The Goal
Be the first to reach **100 points** — we call it **100 proof** in here, and you'll see your bottle fill up on your nameplate as you go. You score by getting your hand tidy faster than everybody else.
## The Cards and What They're Worth
You get **10 cards**. Your job is to arrange them into **melds**:
- **Sets** — three or four of the same rank. `7♠ 7♥ 7♦`
- **Runs** — three or more in a row, same suit. `4♣ 5♣ 6♣ 7♣`
The **ace is low only**: `A-2-3` is a run, `Q-K-A` is not.
Any card that isn't in a meld is **deadwood**, and deadwood is what you're trying to get rid of:
| Card | Deadwood points |
|---|---|
| Ace | 1 |
| 2 through 10 | face value |
| Jack, Queen, King | 10 |
A card can only be in one meld at a time. Don't worry about juggling that in your head — the table does it for you (more on that below).
## Your Turn
Every turn is two steps.
### 1. Draw
Take **one** card — either the blind top card of the **stock**, or the face-up top card of the **discard pile**. Click the pile, or press **D** (stock) or **T** (take the discard).
Taking from the discard pile is public. Everyone at the table sees what you took, and the good ones remember.
### 2. Discard
Put one card face-up on the discard pile. Click a card to lift it, then click it again (or press **Enter**, or click the pile). You can also drag it onto the pile.
One rule trips up newcomers: **you can't throw back the card you just took from the discard pile.** That card shows a little ⟲ mark until your next turn.
### The First Turn: the Upcard
After the deal, one card is turned face-up. The player to the dealer's left gets first refusal on it — **Take** it (T) or **Pass** (P). If they pass, it's offered round the table. If everybody passes, the first player has to draw from the stock.
## Knocking — Closing the Barrel
When your deadwood is **10 or less** after your discard, you may **knock** (K). You discard as usual, then everyone lays their hands down.
- Pick which card to discard as you knock — the cards that keep you at 10 or under glow gold, and the best one is picked for you.
- Your cards go up on the table, sorted into melds, with your deadwood at the end.
### Laying Off
When someone knocks, every other player gets to **lay off**: add their own loose cards to the knocker's melds. Got the `8♥` and the knocker has `5♥ 6♥ 7♥`? Stick it on the end. It's no longer your deadwood.
When it's your turn to lay off, the cards that fit glow green. Click one, or drag it onto the meld you want. **Lay off best (A)** does the sums for you, and **Undo (U)** takes one back. Press **Done** when you're finished.
### Scoring the Knock
The knocker scores the **difference** between the two deadwood counts. Knocked with 4, opponent held 19 after laying off? That's **15 points** to the knocker.
### The Undercut — My Favourite Words in the English Language
If the defender's deadwood is **equal to or lower than** the knocker's, the knocker has been **undercut**. The defender scores the difference **plus a 25-point bonus**. Knock too early and the table will happily take your money. You'll see the red wax seal come down when it happens.
## Gin!
Knock with **zero** deadwood — every card melded — and you've gone **Gin**. Nobody gets to lay off, and you score everyone else's deadwood **plus 25**. When the gin button lights up, press it (G). Don't be shy.
**Big Gin:** if all **eleven** cards in your hand meld right after you draw, you don't even discard. That's worth deadwood **plus 31**.
## When the Stock Runs Dry
If a discard leaves only **2 cards** in the stock and nobody has knocked, the hand is **void**: nobody scores, and the same dealer deals again. Watch the little count under the stock — it turns red when you're close.
With three or four at the table the stock is thin, so the discard pile gets **reshuffled in once** before that rule kicks in.
## End of the Match
First to 100 wins. Then we settle up the house way:
| Bonus | Points |
|---|---|
| Winning the game | +100 |
| Each hand you won (a "box") | +25 |
| Shutout — nobody else scored at all | the winner's total is doubled |
You can turn the bonuses off in Settings if you'd rather keep it to plain points.
## Reading the Table
I keep a teaching table. Everything on it is there to help you:
- **The deadwood meter** sits above your hand. The gold line marks the knock limit; the green end is gin. In your discard step it tells you the best card to throw and what you'd have left — hover any card to see what discarding *that* one would do.
- **Meld colours** — cards already in melds glow teal, amber, violet or blue, one colour per meld. Loose cards show their point value in a little gold chip.
- **Sort: Melds / Suit / Rank** — *Melds* lines your hand up meld by meld with gaps between, deadwood on the right. Drag cards to arrange them your own way any time.
- **★** marks the Coach's suggested discard, and a green ring shows which pile it would draw from. **H** explains why.
- **Cards seen (M)** shows every card that's gone by, and which cards each opponent picked up. If an opponent keeps taking hearts, stop feeding them hearts.
- **Hover a nameplate** to see what that player has taken and thrown this hand.
Hints can be switched off in Settings once you've got your sea legs.
## Mags's Distilling Wisdom
- **Low cards are cheap to hold.** A loose ace costs you 1. A loose king costs you 10. When in doubt, throw the face card.
- **Keep your options open.** `6♦ 7♦` can become a run two ways; `6♦ 8♦` only one. Pairs can become sets with either of two cards.
- **Knock early, knock often** — in the first half of a hand an early knock is usually right. Late in the hand, when your opponents have had time to tidy up, a high knock is asking to be undercut.
- **Watch the discard pile.** If someone picks up the `9♣`, they want clubs near nine or other nines. Don't hand them the `10♣`.
- **A card they threw is a card they don't want.** Discarding next to it is usually safe.
- **Lay off before you count.** Every card you lay off is deadwood you don't pay for — but don't break up one of your own melds to do it.
## House Rules (Settings)
| Rule | What it does |
|---|---|
| Play to 100 / 150 / 250 | Length of the match |
| Undercut bonus 25 / 10 | Some old-timers play 10 |
| Big Gin | All 11 melded after drawing, +31 |
| First-turn upcard | Turn the upcard offer on or off |
| **Oklahoma** | The first upcard's value is the knock limit for the hand (an ace means you need gin or a 1). A **spade** upcard doubles the hand. |
| Bonuses | Game, box and shutout bonuses at the end |
Rule changes start with the next game.
## The Regulars
There's always somebody at my table, and they play from **skill 1** (just learning, takes whatever melds, throws high cards) up to **skill 5** (remembers every card, never feeds you, and knows exactly when to hold off on a knock). The dots on their nameplate tell you who you're sitting with.
Your game is saved at the start of every turn, so if you have to step away, the cards will be right where you left them when you come back.
Now — sit down, cut the deck, and let's see what you're made of. Last one to knock buys the next round.

View File

@ -1,261 +1,499 @@
// Headless verification for Gin Rummy.
// node server/scripts/verifyGinRummy.js
// Exits non-zero on any failure.
//
// 1. Unit tests: deadwood values, meld detection, canLayoff, sort helpers.
// 2. Logic engine: deal, draw, discard, knock, gin, layoff, scoring.
// 3. Self-play: 4-player and 2-player games driven by the AI until completion.
#!/usr/bin/env node
// verifyGinRummy.js — headless checks for Gin Rummy ("The Juniper Still"):
// cards + meld solver (exact, vs brute force), lay-off search, the rules
// engine (upcard offer, no throw-back, wash at 2 cards / one reshuffle at
// 3–4p, knock/gin/Big Gin, undercut, Oklahoma, bonuses, save validity),
// regressions from the old build (AI missed gins on 11 cards, knocked on 0),
// the AI (always legal, optimal lay-offs, skill ladder), the table layout
// and an all-AI soak (every match ends, 52 cards conserved).
// Usage: node tools/verifyGinRummy.js [--quick]
import {
Card, ginDeadwoodValue, ginRunRank, allCandidateMelds, bestMeldGroups,
canLayoff, sortBySuit, sortByRank, HAND_SIZE, MAX_DEADWOOD_TO_KNOCK,
makeCard, cardFromId, fullDeck, bestMelds, meldSolver, deadwoodValue, discardOptions, bestDiscard, canLayoff,
bestDefense, isMeld, meldOrder, pairScore, DEFAULT_RULES,
} from '../src/games/ginrummy/GinRummyData.js';
import { GinRummyLogic } from '../src/games/ginrummy/GinRummyLogic.js';
import * as G from '../src/games/ginrummy/GinRummyLogic.js';
import { chooseDraw, chooseAction, chooseLayoffs, coachDraw, coachAction, rankDiscards } from '../src/games/ginrummy/GinRummyAI.js';
import { mulberry32 } from '../src/ui/cardtable/AITiming.js';
import {
chooseDrawSource, chooseDiscard, shouldKnock, findLayoffs,
} from '../src/games/ginrummy/GinRummyAI.js';
W, H as SCREEN_H, CARD_W, CARD_H, cardBounds, inPose, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect,
} from '../src/ui/cardtable/TableGeometry.js';
import {
T, layoutFor, handPose, blockSlots, handBadge, handHome, rowPoses, blockRect, METER, ROW,
} from '../src/games/ginrummy/GinRummyTable.js';
let failures = 0;
function check(name, cond, detail = '') {
if (cond) { console.log(` ok ${name}`); return; }
failures++;
console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`);
const QUICK = process.argv.includes('--quick');
let pass = 0, fail = 0;
function ok(label, cond, detail = '') {
if (cond) pass++;
else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; }
}
const section = (n) => console.log(`\n${n}`);
const H = (s) => s.split(' ').filter(Boolean).map(cardFromId);
const ids = (cards) => cards.map(c => c.id).sort().join(' ');
// ── Card helpers ──────────────────────────────────────────────────────────────
// ── Cards ────────────────────────────────────────────────────────────────────
section('Cards');
ok('52 unique cards', new Set(fullDeck().map(c => c.id)).size === 52);
ok('A = 1 point', makeCard('A', 's').pts === 1);
ok('9 = 9 points', makeCard('9', 'h').pts === 9);
ok('T J Q K = 10 points', ['T', 'J', 'Q', 'K'].every(r => makeCard(r, 'c').pts === 10));
ok('ace is low in runs', isMeld(H('As 2s 3s')) && !isMeld(H('Qs Ks As')));
ok('set needs different suits', isMeld(H('7s 7h 7d')) && !isMeld(H('7s 7s 7d')));
console.log('\nCard value helpers:');
check('A deadwood = 1', ginDeadwoodValue(new Card('A', 's')) === 1);
check('9 deadwood = 9', ginDeadwoodValue(new Card('9', 'h')) === 9);
check('T deadwood = 10', ginDeadwoodValue(new Card('T', 'd')) === 10);
check('J deadwood = 10', ginDeadwoodValue(new Card('J', 'c')) === 10);
check('K deadwood = 10', ginDeadwoodValue(new Card('K', 's')) === 10);
check('A run rank = 1', ginRunRank(new Card('A', 's')) === 1);
check('2 run rank = 2', ginRunRank(new Card('2', 'h')) === 2);
check('K run rank = 13', ginRunRank(new Card('K', 'd')) === 13);
// ── Meld detection ────────────────────────────────────────────────────────────
console.log('\nMeld detection:');
const c = (r, s) => new Card(r, s);
const set3 = [c('7','s'), c('7','h'), c('7','d')];
check('3-card set found', allCandidateMelds(set3).length >= 1);
check('3-card set has length 3', allCandidateMelds(set3)[0].length === 3);
const set4 = ['s','h','d','c'].map(s => c('Q', s));
check('4-card set found', allCandidateMelds(set4).some(m => m.length === 4));
const run3 = [c('A','h'), c('2','h'), c('3','h')];
check('A-2-3 run found', allCandidateMelds(run3).some(m => m.length === 3));
const runJQK = [c('J','s'), c('Q','s'), c('K','s')];
check('J-Q-K run found', allCandidateMelds(runJQK).some(m => m.length === 3));
const noMeld = [c('2','s'), c('5','s'), c('9','s')];
check('non-consecutive same-suit not a meld', allCandidateMelds(noMeld).length === 0);
const longRun = ['A','2','3','4','5'].map(r => c(r,'d'));
const longMelds = allCandidateMelds(longRun);
check('A-2-3-4-5 yields multiple sub-runs', longMelds.length >= 3);
// bestMeldGroups: gin hand (0 deadwood)
// A-2-3-4 spades run (4) + 5-6-7 hearts run (3) + Q♥Q♦Q♣ set (3) = 10 cards, 0 deadwood
const ginHand = [
...['A','2','3','4'].map(r => c(r,'s')),
...['5','6','7'].map(r => c(r,'h')),
c('Q','h'), c('Q','d'), c('Q','c'),
];
check('gin hand: deadwood = 0', bestMeldGroups(ginHand).deadwood === 0);
// High-deadwood hand
const deadwoodHand = ['2','5','8','J','Q'].map(r => c(r,'s')).concat(['3','6','9','K'].map(r => c(r,'h'))).slice(0, HAND_SIZE);
const { deadwood: mixedDW } = bestMeldGroups(deadwoodHand);
check('mixed hand has positive deadwood', mixedDW > 0);
// ── canLayoff ─────────────────────────────────────────────────────────────────
console.log('\nLayoff validation:');
const run456h = ['4','5','6'].map(r => c(r,'h'));
check('6h extends run at high end', canLayoff(c('7','h'), run456h));
check('3h extends run at low end', canLayoff(c('3','h'), run456h));
check('wrong suit rejected', !canLayoff(c('7','s'), run456h));
check('non-consecutive rejected', !canLayoff(c('8','h'), run456h));
const setAAA = ['s','h','d'].map(s => c('A', s));
check('Ac extends AAA set', canLayoff(c('A','c'), setAAA));
check('duplicate suit rejected', !canLayoff(c('A','s'), setAAA));
check('wrong rank rejected', !canLayoff(c('2','c'), setAAA));
const fullSet = ['s','h','d','c'].map(s => c('K', s));
check('5th card on full set rejected', !canLayoff(c('K','s'), fullSet));
// ── Sort helpers ──────────────────────────────────────────────────────────────
console.log('\nSort helpers:');
const mixedHand = [c('3','h'), c('A','s'), c('2','h'), c('K','s'), c('5','d')];
const byS = sortBySuit(mixedHand);
check('sortBySuit: first two are spades', byS[0].suit === 's' && byS[1].suit === 's');
check('sortBySuit: within suit sorted by rank', ginRunRank(byS[0]) <= ginRunRank(byS[1]));
const byR = sortByRank(mixedHand);
check('sortByRank: first card is Ace (rank 1)', byR[0].rank === 'A');
check('sortByRank: last card is King (rank 13)', byR[byR.length-1].rank === 'K');
// ── Logic engine ──────────────────────────────────────────────────────────────
console.log('\nGinRummyLogic:');
function newLogic(n = 4) { const l = new GinRummyLogic(n, Math.random); l.newGame(); return l; }
const l1 = newLogic(4);
check('newGame: 4 players each get 10 cards', l1.players.every(p => p.hand.length === HAND_SIZE));
check('newGame: initial phase is draw', l1.phase === 'draw');
check('newGame: stock non-empty', l1.stockCount > 0);
check('newGame: discard top exists', l1.discardTop !== null);
const l2 = newLogic(2);
const firstSeat = l2.currentPlayer;
l2.drawStock(firstSeat);
check('drawStock: hand becomes 11', l2.players[firstSeat].hand.length === HAND_SIZE + 1);
check('drawStock: phase becomes discard', l2.phase === 'discard');
const l3 = newLogic(2);
const firstSeat3 = l3.currentPlayer;
const topCard = l3.discardTop;
l3.drawDiscard(firstSeat3);
check('drawDiscard: hand becomes 11', l3.players[firstSeat3].hand.length === HAND_SIZE + 1);
check('drawDiscard: discard pile shortened', l3.discard.length === 0);
const l4 = newLogic(2);
const fs4 = l4.currentPlayer;
l4.drawStock(fs4);
const hand4 = l4.players[fs4].hand;
const discKey = hand4[0].key;
l4.discardCard(fs4, discKey);
check('discardCard: hand returns to 10', l4.players[fs4].hand.length === HAND_SIZE);
check('discardCard: turn advances', l4.currentPlayer !== fs4);
check('discardCard: phase back to draw', l4.phase === 'draw');
// Knock validation
const l5 = newLogic(2);
const fs5 = l5.currentPlayer;
l5.drawStock(fs5);
const { melds: m5 } = bestMeldGroups(l5.players[fs5].hand);
// knock(seat, discardKey, meldGroups) now includes discard internally
let knocked5 = false;
for (const cx of l5.players[fs5].hand) {
const rest = l5.players[fs5].hand.filter(x => x.key !== cx.key);
const { melds: rm, deadwood: rdw } = bestMeldGroups(rest);
if (rdw <= MAX_DEADWOOD_TO_KNOCK) {
const ok = l5.knock(fs5, cx.key, rm);
check('knock: accepted when deadwood ≤ 10', ok);
check('knock: phase becomes layoff', l5.phase === 'layoff');
knocked5 = true;
break;
// ── Meld solver ──────────────────────────────────────────────────────────────
section('Meld solver');
// Independent brute force: try every way to split the hand into disjoint melds.
function brute(hand) {
const n = hand.length;
let best = Infinity;
const rec = (used, meldedPts) => {
let i = 0;
while (i < n && (used & (1 << i))) i++;
if (i >= n) { best = Math.min(best, hand.reduce((s, c) => s + c.pts, 0) - meldedPts); return; }
rec(used | (1 << i), meldedPts); // card i stays loose
const free = [];
for (let k = i + 1; k < n; k++) if (!(used & (1 << k))) free.push(k);
for (let mask = 0; mask < (1 << free.length); mask++) {
const pick = [i];
for (let b = 0; b < free.length; b++) if (mask & (1 << b)) pick.push(free[b]);
if (pick.length < 3 || !isMeld(pick.map(k => hand[k]))) continue;
let u = used, pts = 0;
for (const k of pick) { u |= 1 << k; pts += hand[k].pts; }
rec(u, meldedPts + pts);
}
};
rec(0, 0);
return best;
}
{
const rng = mulberry32(42);
let agree = true, bad = '';
for (let t = 0; t < (QUICK ? 150 : 600); t++) {
const deck = fullDeck();
for (let i = deck.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [deck[i], deck[j]] = [deck[j], deck[i]]; }
// bias toward meld-rich hands: half the time draw from two suits only
const pool = t % 2 ? deck : deck.filter(c => c.suit === 's' || c.suit === 'h' || c.rank === '7');
const hand = pool.slice(0, 10 + (t % 2));
const a = deadwoodValue(hand), b = brute(hand);
if (a !== b) { agree = false; bad = `${ids(hand)}: solver ${a}, brute ${b}`; break; }
const bm = bestMelds(hand);
if (!bm.melds.every(isMeld) || bm.deadwood !== a) { agree = false; bad = `melds wrong for ${ids(hand)}`; break; }
}
ok('solver matches brute force on random hands', agree, bad);
}
ok('gin hand: 0 deadwood', deadwoodValue(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd')) === 0);
ok('overlap: 7♠ used once', deadwoodValue(H('5s 6s 7s 7h 7d')) === 5 + 6 || deadwoodValue(H('5s 6s 7s 7h 7d')) === 14);
ok('overlap chooses the cheaper loose cards', deadwoodValue(H('5s 6s 7s 7h 7d')) === 11);
ok('4-run + set sharing a card → split it', deadwoodValue(H('4h 5h 6h 7h 7s 7d')) === 0);
{
const opts = discardOptions(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd 9c'));
ok('discard options: dropping the 9♣ leaves gin', opts.find(o => o.card.id === '9c').deadwood === 0);
ok('best discard is the 9♣', bestDiscard(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd 9c')).card.id === '9c');
ok('best discard respects the banned card', bestDiscard(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd 9c'), '9c').card.id !== '9c');
}
{
const mo = meldOrder(H('Kd 2s 7h Jd 3s 7c As 9c Qd 7d'));
ok('meld order: melds first, loose last', mo.loose.map(c => c.id).join() === '9c' && mo.order.length === 10 && mo.melds.length === 3);
}
if (!knocked5) check('knock test skipped (hand not knockable)', true);
// ── AI helpers ────────────────────────────────────────────────────────────────
// ── Lay-offs ─────────────────────────────────────────────────────────────────
section('Lay-offs');
ok('extend a run low and high', canLayoff(cardFromId('4h'), H('5h 6h 7h')) && canLayoff(cardFromId('8h'), H('5h 6h 7h')));
ok('no gap in a run', !canLayoff(cardFromId('9h'), H('5h 6h 7h')));
ok('fourth card of a set', canLayoff(cardFromId('7c'), H('7s 7h 7d')) && !canLayoff(cardFromId('7c'), H('7s 7h 7d 7c')));
ok('no ace above king', !canLayoff(cardFromId('As'), H('Js Qs Ks')));
{
const d = bestDefense(H('8h 9h Ks Qd 2c 3c 4c Jh 5d 6d'), [H('5h 6h 7h'), H('Js Jd Jc')]);
ok('chain: 8♥ then 9♥ both laid off', ['8h', '9h'].every(id => d.layoffs.some(l => l.card.id === id)), JSON.stringify(d.layoffs.map(l => l.card.id)));
ok('J♥ laid on the jacks', d.layoffs.some(l => l.card.id === 'Jh' && l.meldIdx === 1));
ok('own run 2-3-4♣ kept', d.melds.some(m => ids(m) === ids(H('2c 3c 4c'))));
ok('defense deadwood', d.deadwood === 10 + 10 + 5 + 6, String(d.deadwood));
// laying the 7♣ off would break 7♣ 8♣ 9♣ — the search keeps the run
const d2 = bestDefense(H('7c 8c 9c Kd'), [H('7s 7h 7d')]);
ok('never lays off out of a better own meld', d2.deadwood === 10 && !d2.layoffs.length);
}
console.log('\nAI helpers:');
// ── Engine ───────────────────────────────────────────────────────────────────
section('Engine');
// A rigged 2p round: set hands / stock / discard directly.
function rig({ hands, upcard = 'Kc', stock = null, n = 2, rules = {}, phase = 'draw', current = 0, takenFrom = null }) {
let gs = G.createGame({ players: n, rules, seed: 7, dealer: n - 1 });
gs = structuredClone(gs);
hands = hands.map(h => (typeof h === 'string' ? h.split(' ') : h));
const used = new Set([...hands.flat(), upcard]);
gs.hands = hands.map(h => h.map(cardFromId));
gs.discard = [cardFromId(upcard)];
gs.stock = stock ? stock.map(cardFromId) : fullDeck().filter(c => !used.has(c.id));
gs.phase = phase;
gs.current = current;
gs.takenFrom = takenFrom;
return gs;
}
{
const gs = G.createGame({ players: 2, seed: 1 });
ok('deal: 10 cards each, 1 up, 31 in stock', gs.hands.every(h => h.length === 10) && gs.discard.length === 1 && gs.stock.length === 31);
ok('deal: starts with the upcard offer to the non-dealer', gs.phase === 'upcard' && gs.current === (gs.dealer + 1) % 2);
ok('52 cards in play', G.cardsInPlay(gs) === 52);
const p1 = G.passUpcard(gs, gs.current);
ok('pass moves the offer to the dealer', p1.phase === 'upcard' && p1.current === gs.dealer);
const p2 = G.passUpcard(p1, p1.current);
ok('both pass: first player must draw from the stock', p2.phase === 'draw' && p2.current === gs.first && p2.stockOnly);
ok('…and may not take the upcard', G.drawDiscard(p2, p2.current) === p2);
const t = G.takeUpcard(gs, gs.current);
ok('take the upcard → discard phase', t.phase === 'discard' && t.hands[gs.current].length === 11 && t.takenFrom === gs.discard[0].id);
ok('can\'t throw the upcard straight back', G.discard(t, gs.current, gs.discard[0].id) === t);
ok('wrong seat can\'t act', G.takeUpcard(gs, gs.dealer) === gs);
const s3 = G.createGame({ players: 3, seed: 2 });
ok('3p: 21 in stock', s3.stock.length === 21);
const s4 = G.createGame({ players: 4, seed: 3 });
ok('4p: 11 in stock', s4.stock.length === 11);
const nu = G.createGame({ players: 2, seed: 4, rules: { upcard: false } });
ok('upcard rule off: straight to draw', nu.phase === 'draw' && !nu.stockOnly);
}
{
const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd 5c', '2h 3h 9s 9d Ts Th 5h 6d 8c Kh'], upcard: 'Kd' });
const d = G.drawDiscard(gs, 0);
ok('take the discard', d.hands[0].length === 11 && d.takenFrom === 'Kd' && d.pickups[0].includes('Kd'));
ok('no throw-back of the taken card', G.discard(d, 0, 'Kd') === d);
ok('no knocking with the taken card either', G.knock(d, 0, 'Kd') === d);
const g = G.knock(d, 0, '5c');
ok('knock on 0 is gin automatically', g.phase === 'roundOver' && g.result.kind === 'gin');
const opp = bestMelds(g.hands[1]).deadwood;
ok('gin scores deadwood + 25', g.result.deltas[0] === opp + 25, `${g.result.deltas[0]} vs ${opp}+25`);
ok('gin: no lay-offs happened', g.result.lines[0].laid.length === 0);
ok('box counted', g.boxes[0] === 1 && g.stats[0].gins === 1);
}
{
// knock with 5 (5♣ loose), defender lays off
const gs = rig({ hands: ['2s 3s 4s 7h 7d 7c Jd Qd Kd 5c', '5s 8h 9s 9d Ts Td As 6d 8c Kh'], upcard: 'Qh', stock: ['Kc', '4h', '3d', '6h', '4d', '6c'] });
const d = G.drawStock(gs, 0);
ok('draw stock', d.hands[0].length === 11 && d.takenFrom === null && d.stock.length === 5);
ok('knock over the limit refused', G.knock(d, 0, '2s') === d);
const k = G.knock(d, 0, 'Kc');
ok('knock with 5 → lay-off phase for the defender', k.phase === 'layoff' && k.showdown.layoffSeat === 1 && k.showdown.knockerDW === 5, k.phase);
const mi = k.showdown.melds.findIndex(m => m.some(c => c.id === '4s'));
const l = G.layoff(k, 1, '5s', mi);
ok('lay 5♠ on 2-4♠', l !== k && l.showdown.melds[mi].length === 4 && !l.hands[1].some(c => c.id === '5s'));
const l1 = G.layoff(l, 1, 'As', mi);
ok('…and the A♠ below it', l1 !== l && l1.showdown.melds[mi][0].id === 'As');
ok('illegal lay-off refused', G.layoff(l1, 1, 'Kh', mi) === l1);
ok('no card lost or doubled during lay-offs', G.cardsInPlay(l1) === G.cardsInPlay(k));
const kdIdx = l1.showdown.melds.findIndex(m => m.some(c => c.id === 'Jd'));
const l2 = G.layoff(l1, 1, 'Td', kdIdx);
ok('T♦ onto J-Q-K♦', l2 !== l1);
const e = G.endLayoff(l2, 1);
const dDW = bestMelds(e.hands[1]).deadwood;
ok('scored after the last defender', e.phase === 'roundOver' && e.result.lines[0].deadwood === dDW);
ok('knock win = difference', e.result.deltas[0] === dDW - 5, `${e.result.deltas[0]} vs ${dDW}-5`);
ok('lay-offs recorded', e.result.lines[0].laid.length === 3);
}
{
// undercut: knocker 1 (A♥), defender 1 (A♣) → tie is an undercut
const gs = rig({ hands: ['2s 3s 4s 7h 7d 7c Jd Qd Kd 9c', '4c 5c 6c 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Ah', '5h', '9h', 'Qc', 'Jc', 'Th'] });
const k = G.knock(G.drawStock(gs, 0), 0, '9c');
ok('knocking with 1', k.showdown?.knockerDW === 1);
const e = G.endLayoff(k, 1);
ok('undercut: defender gets 0 + 25', e.result.deltas[1] === 25 && e.result.deltas[0] === 0 && e.result.undercut, JSON.stringify(e.result.deltas));
ok('undercut stats', e.stats[1].undercuts === 1 && e.stats[0].undercutBy === 1);
ok('pairScore undercut on a tie', pairScore('knock', 6, 6, DEFAULT_RULES).to === 'defender' && pairScore('knock', 6, 6, DEFAULT_RULES).pts === 25);
ok('undercut bonus setting', pairScore('knock', 8, 3, { ...DEFAULT_RULES, undercutBonus: 10 }).pts === 15);
}
{
// Big Gin
const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['5s', '4h', '3c', '6c'] });
const d = G.drawStock(gs, 0);
ok('Big Gin available', G.canBigGin(d, 0));
const b = G.bigGin(d, 0);
ok('Big Gin scores deadwood + 31', b.result.kind === 'biggin' && b.result.deltas[0] === bestMelds(b.hands[1]).deadwood + 31);
const off = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['5s', '4h'], rules: { bigGin: false } });
ok('Big Gin off by rule', !G.canBigGin(G.drawStock(off, 0), 0));
}
{
// wash: 2p, a discard leaving 2 in the stock voids the hand
const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Kc', 'Qc', 'Jc'] });
const d = G.drawStock(gs, 0);
const w = G.discard(d, 0, 'Kc');
ok('2p: wash when 2 cards remain', w.phase === 'roundOver' && w.result.kind === 'wash' && w.scores.every(s => s === 0));
const nr = G.nextRound(w);
ok('wash: same dealer redeals', nr.dealer === w.dealer && nr.round === w.round + 1);
const k = G.knock(d, 0, 'Kc');
ok('a knock on the last turn still counts', k === d || k.phase === 'layoff' || k.phase === 'roundOver');
// 3p: one reshuffle first
const g3 = rig({ n: 3, hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac', '2c 3c 4c 5c 6c 7c 9h Th Jh Qh'], upcard: 'Kh', stock: ['Kc', 'Qc', 'Jc'] });
g3.discard = ['Kh', '8h', '5d'].map(cardFromId);
// stock 3 + discard 3 + hands 30 = 36, fine for this test (not 52)
const d3 = G.drawStock(g3, 0);
const r3 = G.discard(d3, 0, 'Kc');
ok('3p: first time → reshuffle, play goes on', r3.phase === 'draw' && r3.reshuffles === 1 && r3.discard.length === 1 && r3.stock.length === 2 + 3);
ok('3p: the top discard stays up', r3.discard[0].id === 'Kc');
}
{
// Oklahoma: knock limit from the upcard; spade doubles
const gs = G.createGame({ players: 2, seed: 99, rules: { oklahoma: true } });
const up = gs.discard[0];
ok('Oklahoma knock limit = upcard value', gs.knockLimit === up.pts);
ok('Oklahoma spade doubles', gs.doubled === (up.suit === 's'));
const s = rig({ hands: ['2s 3s 4s 7h 7d 7c Jd Qd Kd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: '3h', stock: ['5c', '4h', '3c', '6c', '4c', '6d'], rules: { oklahoma: true } });
s.knockLimit = 3;
const d = G.drawStock(s, 0);
ok('Oklahoma: can\'t knock with 5 when the limit is 3', G.knock(d, 0, '9c') === d);
}
{
// match end, bonuses
const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd 5c', '2h 3h 9s 9d Ts Th 5h 6d 8c Kh'], upcard: 'Kd' });
gs.scores = [90, 0];
const g = G.knock(G.drawDiscard(gs, 0), 0, '5c');
ok('reaching 100 ends the match', g.phase === 'gameOver' && g.winner === 0);
const f = g.final[0];
ok('final: game bonus + box bonus', f.game === 100 && f.box === 25 * g.boxes[0]);
ok('shutout doubles the winner', f.shutout && f.total === (f.points + f.game + f.box) * 2);
const nb = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd 5c', '2h 3h 9s 9d Ts Th 5h 6d 8c Kh'], upcard: 'Kd', rules: { bonuses: false } });
nb.scores = [90, 0];
const g2 = G.knock(G.drawDiscard(nb, 0), 0, '5c');
ok('bonuses off: total = points', g2.final[0].total === g2.scores[0]);
ok('target setting', G.createGame({ players: 2, rules: { target: 250 } }).rules.target === 250);
}
{
const gs = G.createGame({ players: 3, seed: 5 });
ok('save is valid', G.isValidSave(JSON.parse(JSON.stringify(gs)), 3));
ok('save checks seat count', !G.isValidSave(gs, 2));
}
const testHand = ginHand; // gin hand
check('shouldKnock: gin hand → true at any skill', shouldKnock(testHand, 3));
check('chooseDiscard returns a card', chooseDiscard([...testHand, c('2','c')], 3) !== null);
// ── Regressions from the old build ───────────────────────────────────────────
section('Regressions');
{
// old AI judged knock/gin on all 11 cards: this gin-after-discard hand read as 10 deadwood
const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Kc', '4h', '3c', '6c', '4c', '6d'] });
const d = G.drawStock(gs, 0);
for (let sk = 1; sk <= 5; sk++) {
const a = chooseAction(d, 0, { skill: sk, rng: mulberry32(sk) });
ok(`skill ${sk} goes gin when the discard leaves 0`, a.kind === 'gin' && a.id === 'Kc', JSON.stringify(a));
}
const bg = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['5s', '4h', '3c', '6c'] });
ok('AI calls Big Gin', chooseAction(G.drawStock(bg, 0), 0, { skill: 3 }).kind === 'biggin');
// old AI laid off out of its own melds
const k = rig({ hands: ['2s 3s 4s 7h 7d 7s Jd Qd Kd 9c', '7c 8c 9h Kc 5c 6c 5d 5h Th Jh'], upcard: 'Ks', stock: ['Ac', '4h', '3c', '2c', '4c', '6d'] });
const kk = G.knock(G.drawStock(k, 0), 0, '9c');
if (kk.phase === 'layoff') {
const ls = chooseLayoffs(kk, 1, { skill: 4 });
ok('AI keeps its own clubs run instead of laying the 7♣ off', !ls.some(l => l.id === '7c'), JSON.stringify(ls));
} else ok('knock fixture', false, kk.phase);
}
const aiHand = [...'23456'.split('').map(r => c(r,'h')), ...['K','K','K'].map((r,i) => c(r,['s','d','c'][i])), c('Q','s'), c('J','s')];
check('findLayoffs: finds valid layoff on matching run',
findLayoffs([c('7','h')], [['4','5','6'].map(r => c(r,'h'))], 3).length > 0
);
check('findLayoffs: rejects invalid card',
findLayoffs([c('7','s')], [['4','5','6'].map(r => c(r,'h'))], 3).length === 0
);
// ── Self-play simulation ──────────────────────────────────────────────────────
console.log('\nSelf-play (4-player, up to 40 rounds):');
function runGame(nPlayers) {
const logic = new GinRummyLogic(nPlayers, Math.random);
logic.newGame();
let turns = 0, maxTurns = 2000;
while (logic.phase !== 'gameover' && turns < maxTurns) {
turns++;
if (logic.phase === 'roundover') { logic.newRound(); continue; }
const seat = logic.currentPlayer;
if (logic.phase === 'draw') {
const hand = logic.players[seat].hand;
const discardTop = logic.discardTop;
const src = chooseDrawSource(hand, discardTop, 3);
if (src === 'discard' && discardTop) logic.drawDiscard(seat);
else logic.drawStock(seat);
// ── AI + Coach ───────────────────────────────────────────────────────────────
section('AI');
{
let legal = true, why = '';
for (let t = 0; t < 120 && legal; t++) {
let gs = G.createGame({ players: 2 + (t % 3), seed: 1000 + t });
for (let step = 0; step < 6 && legal; step++) {
const seat = G.actor(gs);
const sk = 1 + (t % 5);
const r = mulberry32(t * 31 + step);
if (gs.phase === 'upcard') {
const src = chooseDraw(gs, seat, { skill: sk, rng: r });
gs = src === 'discard' ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat);
continue;
}
if (gs.phase === 'draw') {
const src = chooseDraw(gs, seat, { skill: sk, rng: r });
const nx = src === 'discard' ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat);
if (nx === gs) { legal = false; why = `draw ${src}`; }
gs = nx;
continue;
}
if (gs.phase === 'discard') {
const a = chooseAction(gs, seat, { skill: sk, rng: r });
const nx = a.kind === 'biggin' ? G.bigGin(gs, seat) : a.kind === 'discard' ? G.discard(gs, seat, a.id) : G.knock(gs, seat, a.id);
if (nx === gs) { legal = false; why = `${a.kind} ${a.id}`; }
gs = nx;
}
if (G.isOver(gs) || gs.phase === 'layoff') break;
}
}
ok('AI moves are always legal', legal, why);
const gs = G.drawDiscard(rig({ hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: '7c' }), 0);
ok('AI never ranks the taken card as a discard', !rankDiscards(gs, 0, { skill: 5 }).some(r => r.card.id === '7c'));
const cd = coachDraw(rig({ hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: '7c' }), 0);
ok('coach takes the card that makes a set', cd.source === 'discard' && /7♣/.test(cd.reason), cd.reason);
const ca = coachAction(G.drawStock(rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Kc', '4h', '3c', '6c', '4c'] }), 0), 0);
ok('coach says gin', ca.kind === 'gin' && /GIN/.test(ca.reason), JSON.stringify(ca));
}
if (logic.phase === 'discard') {
const handNow = logic.players[seat].hand;
let acted = false;
// Try gin
for (const cx of handNow) {
const rest = handNow.filter(x => x.key !== cx.key);
const { deadwood: dw, melds: rm } = bestMeldGroups(rest);
if (dw === 0) { acted = logic.gin(seat, cx.key, rm); break; }
}
// Try knock
if (!acted) {
let best = null, bestDW = Infinity, bestMelds = [];
for (const cx of handNow) {
const rest = handNow.filter(x => x.key !== cx.key);
const { deadwood: dw, melds: m } = bestMeldGroups(rest);
if (dw < bestDW) { bestDW = dw; best = cx; bestMelds = m; }
}
if (best && bestDW <= MAX_DEADWOOD_TO_KNOCK) {
acted = logic.knock(seat, best.key, bestMelds);
}
}
// Normal discard
if (!acted) {
const d = chooseDiscard(handNow, 3);
if (d) logic.discardCard(seat, d.key);
}
// ── Layout ───────────────────────────────────────────────────────────────────
section('Layout');
for (const n of [2, 3, 4]) {
const L = layoutFor(n);
const furn = hudFurniture();
for (let s = 1; s < n; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) });
for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) {
ok(`${n}p: ${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r));
}
const stockB = cardBounds({ ...L.stock, y: L.stock.y - 10 }), discB = cardBounds(L.discard);
const sdS = cardBounds(L.sdStock), sdD = cardBounds(L.sdDiscard);
ok(`${n}p: piles apart`, !rectsOverlap(stockB, discB) && !rectsOverlap(sdS, sdD));
ok(`${n}p: piles on the baize`, [stockB, discB, sdS, sdD].every(b => T.onFelt({ x: b.x0, y: b.y0 }) && T.onFelt({ x: b.x1, y: b.y1 })));
const meter = { x0: METER.x - METER.w / 2 - 70, x1: METER.x + METER.w / 2 + 12, y0: METER.y - 36, y1: METER.y + 34 };
for (const f of furn) ok(`${n}p: meter clear of ${f.name}`, !rectsOverlap(meter, f.r));
ok(`${n}p: meter clear of the piles`, !rectsOverlap(meter, stockB) && !rectsOverlap(meter, discB));
for (let s = 0; s < n; s++) {
for (const cards of [10, 11]) {
const fb = fanBounds(L.seats[s].fan, cards, s === 0 ? 40 : 0);
ok(`${n}p seat ${s} (${cards}): hand on screen`, onScreen(fb, s === 0 ? 50 : 10), JSON.stringify(fb));
for (const f of furn) ok(`${n}p seat ${s} (${cards}): hand clear of ${f.name}`, !rectsOverlap(fb, f.r), `${JSON.stringify(fb)} vs ${JSON.stringify(f.r)}`);
ok(`${n}p seat ${s} (${cards}): hand clear of piles`, !rectsOverlap(fb, stockB) && !rectsOverlap(fb, discB));
if (s === 0) ok(`${n}p (${cards}): hand clear of the meter`, !rectsOverlap(fb, meter));
}
if (logic.phase === 'layoff') {
const ls = logic.layoffPlayer;
if (ls !== logic.knocker) {
const lHand = logic.players[ls].hand;
const layoffs = findLayoffs(lHand, logic.knockerMelds, 3);
if (layoffs.length > 0) logic.layoff(ls, layoffs);
logic.passLayoff(ls);
if (s > 0) {
const b = handBadge(L, s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 };
ok(`${n}p seat ${s}: badge on screen`, onScreen(br));
for (const f of furn) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r));
const hh = handHome(L, s);
ok(`${n}p seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < W && hh.y > 0 && hh.y < SCREEN_H);
}
}
// showdown rows: knocker + up to 3 opponents, a long row (16 cards in 5 blocks)
const human = fanBounds(L.seats[0].fan, 10, 40);
const blocks = [[1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1, 2]];
for (let rows = 1; rows <= n; rows++) {
for (let r = 0; r < rows; r++) {
const row = rowPoses(r, rows, blocks);
let rb = null;
row.poses.flat().forEach(p => { const b = cardBounds(p); rb = rb ? { x0: Math.min(rb.x0, b.x0), x1: Math.max(rb.x1, b.x1), y0: Math.min(rb.y0, b.y0), y1: Math.max(rb.y1, b.y1) } : b; });
rb = { ...rb, y1: rb.y1 + 10 }; // brackets
const label = { x0: ROW.labelX - 170, x1: ROW.labelX, y0: row.y - 22, y1: row.y + 22 };
const tag = `${n}p rows ${rows}/${r}`;
ok(`${tag}: on the baize`, T.onFelt({ x: rb.x0, y: rb.y0 }) && T.onFelt({ x: rb.x1, y: rb.y1 }), JSON.stringify(rb));
for (const f of furn) ok(`${tag}: clear of ${f.name}`, !rectsOverlap(rb, f.r) && !rectsOverlap(label, f.r));
ok(`${tag}: clear of your hand`, !rectsOverlap(rb, human));
ok(`${tag}: clear of the retired piles`, !rectsOverlap(rb, sdS) && !rectsOverlap(rb, sdD) && !rectsOverlap(label, sdS) && !rectsOverlap(label, sdD));
ok(`${tag}: label clear of the cards`, label.x1 < rb.x0);
if (r > 0) {
const prev = rowPoses(r - 1, rows, blocks);
ok(`${tag}: rows don't overlap`, blockRect(prev, 0).y1 + 12 < blockRect(row, 0).y0);
}
}
}
return { phase: logic.phase, winner: logic.winner, turns };
// hand hit-tests with meld gaps (the Melds sort)
for (const sizes of [[3, 3, 4], [4, 3, 3, 1], [3, 0, 8]]) {
const { slots, total } = blockSlots(sizes);
const cards = slots.length;
let rt = true;
for (let i = 0; i < cards; i++) {
const p = handPose(L, 0, i, cards, 0, slots, total);
// the topmost card under a point on card i's left strip is i
const pt = { x: p.x - CARD_W / 2 + 8, y: p.y };
let hit = -1;
for (let j = cards - 1; j >= 0; j--) if (inPose(pt, handPose(L, 0, j, cards, 0, slots, total))) { hit = j; break; }
if (hit !== i) rt = false;
}
ok(`${n}p: gapped hand hit-tests (${sizes})`, rt);
const fb = (() => { let b = null; for (let i = 0; i < cards; i++) { const c = cardBounds(handPose(L, 0, i, cards, 40, slots, total)); b = b ? { x0: Math.min(b.x0, c.x0), x1: Math.max(b.x1, c.x1), y0: Math.min(b.y0, c.y0), y1: Math.max(b.y1, c.y1) } : c; } return b; })();
for (const f of furn) ok(`${n}p: gapped hand clear of ${f.name}`, !rectsOverlap(fb, f.r));
}
}
const res4 = runGame(4);
check('4-player: game ends with gameover', res4.phase === 'gameover', `phase=${res4.phase}`);
check('4-player: winner index is 0-3', res4.winner >= 0 && res4.winner < 4, `winner=${res4.winner}`);
// ── Soak + skill ladder ──────────────────────────────────────────────────────
section('Soak');
export function playMatch(n, skills, seed, rules = {}) {
const r = mulberry32(seed * 7 + 1);
let gs = G.createGame({ players: n, seed, rules });
let rounds = 0, conserve = true, illegal = 0;
for (let guard = 0; guard < 6000; guard++) {
if (gs.phase === 'gameOver') return { gs, rounds, conserve, illegal };
if (gs.phase === 'roundOver') { rounds++; gs = G.nextRound(gs); continue; }
const seat = G.actor(gs);
const opt = { skill: skills[seat], rng: r };
let nx = gs;
if (gs.phase === 'upcard') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat);
else if (gs.phase === 'draw') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat);
else if (gs.phase === 'discard') {
const a = chooseAction(gs, seat, opt);
nx = a.kind === 'biggin' ? G.bigGin(gs, seat) : a.kind === 'discard' ? G.discard(gs, seat, a.id) : G.knock(gs, seat, a.id);
} else if (gs.phase === 'layoff') {
let g = gs;
for (const l of chooseLayoffs(gs, seat, opt)) { const y = G.layoff(g, seat, l.id, l.meldIdx); if (y === g) illegal++; g = y; }
nx = G.endLayoff(g, seat);
}
if (nx === gs) { illegal++; break; }
gs = nx;
if (G.cardsInPlay(gs) !== 52) conserve = false;
}
return { gs, rounds, conserve, illegal, stuck: gs.phase !== 'gameOver' };
}
{
const M = QUICK ? 6 : 24;
for (const rules of [{}, { upcard: false, bonuses: false }, { oklahoma: true, undercutBonus: 10, bigGin: false }]) {
for (const n of [2, 3, 4]) {
let ended = 0, illegal = 0, conserve = true, rounds = 0, scoreOk = true;
for (let i = 0; i < M; i++) {
const skills = Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5));
const res = playMatch(n, skills, 400 + i * 13 + n, rules);
if (!res.stuck) ended++;
illegal += res.illegal;
if (!res.conserve) conserve = false;
rounds += res.rounds;
if (res.gs.phase === 'gameOver') {
const w = res.gs.winner;
if (res.gs.scores[w] < res.gs.rules.target || res.gs.scores[w] < Math.max(...res.gs.scores)) scoreOk = false;
}
}
const tag = `${n}p ${JSON.stringify(rules)}`;
ok(`${tag}: every match ends`, ended === M, `${ended}/${M}`);
ok(`${tag}: no illegal AI moves`, illegal === 0, String(illegal));
ok(`${tag}: 52 cards conserved`, conserve);
ok(`${tag}: the winner has the top score ≥ target`, scoreOk);
if (!Object.keys(rules).length) console.log(` ${n}p: ${M} matches, avg ${(rounds / M).toFixed(1)} hands`);
}
}
}
const res2 = runGame(2);
check('2-player: game ends with gameover', res2.phase === 'gameover', `phase=${res2.phase}`);
check('2-player: winner index is 0-1', res2.winner >= 0 && res2.winner < 2, `winner=${res2.winner}`);
section('Skill ladder (2p, points per hand)');
{
// play single hands both ways round; measure average net points per hand for A
function duel(a, b, hands) {
let net = 0;
for (let i = 0; i < hands; i++) {
const seatA = i % 2;
const skills = seatA === 0 ? [a, b] : [b, a];
const r = mulberry32(77 + i * 5);
let gs = G.createGame({ players: 2, seed: 5000 + Math.floor(i / 2), dealer: 1 });
for (let guard = 0; guard < 400 && !G.isOver(gs); guard++) {
const seat = G.actor(gs);
const opt = { skill: skills[seat], rng: r };
let nx = gs;
if (gs.phase === 'upcard') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat);
else if (gs.phase === 'draw') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat);
else if (gs.phase === 'discard') {
const ac = chooseAction(gs, seat, opt);
nx = ac.kind === 'biggin' ? G.bigGin(gs, seat) : ac.kind === 'discard' ? G.discard(gs, seat, ac.id) : G.knock(gs, seat, ac.id);
} else if (gs.phase === 'layoff') {
let g = gs;
for (const l of chooseLayoffs(gs, seat, opt)) g = G.layoff(g, seat, l.id, l.meldIdx);
nx = G.endLayoff(g, seat);
}
gs = nx;
}
if (gs.result) net += gs.result.deltas[seatA] - gs.result.deltas[1 - seatA];
}
return net / hands;
}
const N = QUICK ? 300 : 2000;
const t0 = Date.now();
const pairs = [[2, 1], [3, 2], [4, 3], [5, 4], [5, 3], [5, 1]];
const res = {};
for (const [a, b] of pairs) res[`${a}v${b}`] = duel(a, b, N);
console.log(` ${Object.entries(res).map(([k, v]) => `${k} ${v >= 0 ? '+' : ''}${v.toFixed(1)}`).join(' · ')} (${N} hands each, ${((Date.now() - t0) / 1000).toFixed(1)}s)`);
ok('skill 2 beats 1', res['2v1'] > 0, res['2v1'].toFixed(2));
ok('skill 3 beats 2', res['3v2'] > 0, res['3v2'].toFixed(2));
// measured over 5000 paired hands: 4v3 ≈ +1.0, 5v4 ≈ +2.1, 5v3 ≈ +3.0 (± 0.33)
ok('skill 4 beats 3', res['4v3'] > (QUICK ? -2 : 0), res['4v3'].toFixed(2));
ok('skill 5 beats 4', res['5v4'] > (QUICK ? -2 : 0), res['5v4'].toFixed(2));
ok('skill 5 beats 3', res['5v3'] > (QUICK ? 0 : 1), res['5v3'].toFixed(2));
ok('skill 5 clearly beats 1', res['5v1'] > 4, res['5v1'].toFixed(2));
}
const res3 = runGame(3);
check('3-player: game ends with gameover', res3.phase === 'gameover', `phase=${res3.phase}`);
check('3-player: winner index is 0-2', res3.winner >= 0 && res3.winner < 3, `winner=${res3.winner}`);
// ── Summary ────────────────────────────────────────────────────────────────────
console.log(`\n── ${failures === 0 ? 'All tests passed' : `${failures} test(s) FAILED`} ──\n`);
if (failures > 0) process.exit(1);
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);