From 1afdd75a6104da96aa733125f89b4744136de169 Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Mon, 30 Nov 2026 22:20:46 -0700 Subject: [PATCH] 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 --- src/data/gamesRegistry.js | 2 +- src/games/ginrummy/GinRummyAI.js | 353 ++-- src/games/ginrummy/GinRummyArt.js | 490 +++++ src/games/ginrummy/GinRummyData.js | 434 +++-- src/games/ginrummy/GinRummyGame.js | 2710 ++++++++++++++++----------- src/games/ginrummy/GinRummyLogic.js | 607 +++--- src/games/ginrummy/GinRummyTable.js | 160 ++ src/games/ginrummy/tutorial.md | 140 ++ tools/verifyGinRummy.js | 710 ++++--- 9 files changed, 3721 insertions(+), 1885 deletions(-) create mode 100644 src/games/ginrummy/GinRummyArt.js create mode 100644 src/games/ginrummy/GinRummyTable.js create mode 100644 src/games/ginrummy/tutorial.md diff --git a/src/data/gamesRegistry.js b/src/data/gamesRegistry.js index 463811c..de850c5 100644 --- a/src/data/gamesRegistry.js +++ b/src/data/gamesRegistry.js @@ -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 }); diff --git a/src/games/ginrummy/GinRummyAI.js b/src/games/ginrummy/GinRummyAI.js index 6a7a726..c6d87e8 100644 --- a/src/games/ginrummy/GinRummyAI.js +++ b/src/games/ginrummy/GinRummyAI.js @@ -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 }); } diff --git a/src/games/ginrummy/GinRummyArt.js b/src/games/ginrummy/GinRummyArt.js new file mode 100644 index 0000000..baf443d --- /dev/null +++ b/src/games/ginrummy/GinRummyArt.js @@ -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) }); +} diff --git a/src/games/ginrummy/GinRummyData.js b/src/games/ginrummy/GinRummyData.js index 67a8b5a..a2ca454 100644 --- a/src/games/ginrummy/GinRummyData.js +++ b/src/games/ginrummy/GinRummyData.js @@ -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' }; } diff --git a/src/games/ginrummy/GinRummyGame.js b/src/games/ginrummy/GinRummyGame.js index f2ba989..a366902 100644 --- a/src/games/ginrummy/GinRummyGame.js +++ b/src/games/ginrummy/GinRummyGame.js @@ -1,1171 +1,1717 @@ import * as Phaser from 'phaser'; -import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js'; -import { Button } from '../../ui/Button.js'; -import { MusicPlayer } from '../../ui/MusicPlayer.js'; -import { playSound, SFX } from '../../ui/Sounds.js'; -import { createPlayerPortrait, createOpponentPortrait } from '../../ui/Portrait.js'; import { - THEME, CARD_W, CARD_H, CARD_R, HAND_SPREAD, AI_SPREAD, - WIN_SCORE, MAX_DEADWOOD_TO_KNOCK, - seatPositions, pilePositions, - sortBySuit, sortByRank, - allCandidateMelds, bestMeldGroups, canLayoff, ginDeadwoodValue, + CardTableScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { jitterFor } from '../../ui/casino/CasinoCards.js'; +import { CARD_W, CARD_H, inPose, inRect, stackLift, fanZone, PLATE } from '../../ui/cardtable/TableGeometry.js'; +import { + DEFAULT_RULES, HAND_SIZE, SUITS, RANKS, SUIT_SYM, cardName, bestMelds, meldOrder, canLayoff, bySuit, byRank, } from './GinRummyData.js'; -import { GinRummyLogic } from './GinRummyLogic.js'; +import * as G from './GinRummyLogic.js'; +import { chooseDraw, chooseAction, chooseLayoffs, coachDraw, coachAction, coachLayoffs } from './GinRummyAI.js'; import { - chooseDrawSource, chooseDiscard, shouldKnock, findLayoffs, thinkDelay, -} from './GinRummyAI.js'; + SQ, SEAT_COLORS, SEAT_HEX, MELD_COLORS, METER, ROW, + layoutFor, handPose, blockSlots, handHome, handBadge, spotFor, rowPoses, blockRect, +} from './GinRummyTable.js'; +import { prepareGinArt } from './GinRummyArt.js'; -const CX = GAME_WIDTH / 2; -const CY = GAME_HEIGHT / 2; -const PLAYER_HAND_Y = 920; +// ─── Gin Rummy — "The Juniper Still" ────────────────────────────────────────── +// A distillery tasting room on the shared card-table kit (src/ui/cardtable/). +// Rules live in GinRummyLogic.js (pure JSON state), opponents + Coach in +// GinRummyAI.js; this file is flow, animation and input. Every card is a +// persistent sprite keyed by its id ('Td', 'As', …). -const D = { - felt: -2, rail: -1, pile: 2, card: 10, glow: 9, cardText: 11, - ui: 30, toast: 50, overlay: 60, overlayUI: 62, +const SETTINGS_KEY = 'ginrummy-settings'; +const SAVE_KEY = 'ginrummy-save-v1'; +const RULE_KEYS = ['target', 'undercutBonus', 'bigGin', 'upcard', 'oklahoma', 'bonuses']; +const DEFAULTS = { + pace: 'normal', hints: true, sort: 'melds', + rules: Object.fromEntries(RULE_KEYS.map(k => [k, DEFAULT_RULES[k]])), }; +const KIND_WORD = { knock: 'Knock!', gin: 'GIN!', biggin: 'BIG GIN!' }; +const INK = '#f2ead8'; +const MUTED = '#b9a98a'; +const GREEN = '#8ce99a'; +const RED = '#ff8a7a'; +const AMBER = '#ffc861'; -const SUIT_RED = '#c92a2a'; -const SUIT_BLK = '#1a1208'; - -export default class GinRummyGame extends Phaser.Scene { +export default class GinRummyGame extends CardTableScene { constructor() { super('GinRummyGame'); } init(data) { - this.gameDef = data.game ?? { slug: 'ginrummy', name: 'Gin Rummy' }; - this.opponents = data.opponents ?? []; - this.playfield = data.playfield ?? null; - this.nPlayers = 1 + this.opponents.length; - - this.logic = new GinRummyLogic(this.nPlayers); - - this.humanCards = []; // card containers for seat 0 (hand order matches logic.players[0].hand) - this.aiCardObjs = []; // aiCardObjs[seat] = array of containers - this.pileObjs = {}; // { stock, discard } - this.revealObjs = []; // containers during knock reveal / layoff - - this.selectedCard = null; // { key, container } during discard phase - this.layoffSelected = null; // card key selected during layoff - this.humanMode = 'idle'; // 'idle'|'draw'|'discard'|'layoff' - this.busy = false; - - // Drag state (Phase 10 pattern) + this.initTable(data, { settingsKey: SETTINGS_KEY, defaults: DEFAULTS }); + this.settings.rules = { ...DEFAULTS.rules, ...(this.settings.rules ?? {}) }; + this.initData = data; + this.L = layoutFor(this.playerCount); + this.backKey = 'gin-back'; + this.gs = null; + this.selectedId = null; + this.hoverId = null; this.potentialDrag = null; - this.dragState = null; + this.dragState = null; + this.dragPreview = null; + this.layoffUndo = []; + this.newIds = new Set(); + this.cache = { key: '', choices: null, coach: null, dw: null }; + this.rowTexts = []; + this.ended = false; } - create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch (_) {} + faceFrame(card) { return { key: 'casino-cards', frame: card.id }; } - this._seatPos = seatPositions(this.nPlayers); - this._pilePos = pilePositions(); + async create() { + this.createTableBase(); + const key = await prepareGinArt(this, this.playerCount); + if (!this.alive()) return; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildSpot(); + this.buildStillGlow(); + this.slabG = this.add.graphics().setDepth(D.cards - 1); + this.pileG = this.add.graphics().setDepth(D.slots); + this.rowG = this.add.graphics().setDepth(D.cards - 0.5); + this.targetG = this.add.graphics().setDepth(D.glow); + this.stockTxt = this.add.text(this.L.stock.x, this.L.stock.y + 82, '', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#e8d8b0', stroke: '#0c1a14', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels); + this.limitTxt = this.add.text(CX, this.L.stock.y - 92, '', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: AMBER, stroke: '#0c1a14', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels); + this.buildMeter(); + this.buildDropSlot(); + this.buildPlates(this.L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'GIN!' }); + this.plateG = this.add.graphics().setDepth(D.plates + 2); + this.buildBadges(); + this.buildGhostHands(this.L.seats.map((_, s) => (s ? handHome(this.L, s) : null)), SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Rules: () => this.openRules(), + }, 'Click a card to pick it, again (or Enter) to discard · drag to sort · D draw · T take · K knock · G gin\nP pass the upcard · A lay off best · U undo · H hint · M cards seen · S sort · Esc menu'); + this.buildDock(); + this.buildSortRow([['melds', 'Melds'], ['suit', 'Suit'], ['rank', 'Rank']], () => { this.sortHand(); this.layout(); }); + this.buildTooltips(); + this.setupInput(); + const save = this.readSave(); + if (save) this.offerResume(save); + else this.newMatch(); + } - this.buildBackdrop(); - this.buildScorePanel(); - this.buildPortraits(); - this.buildPiles(); - this.buildActionBar(); - this.buildSortButtons(); - this.setupDragHandlers(); + // The copper still glows and flickers at the left of the room. + buildStillGlow() { + this.still = this.add.image(120, 520, 'ct-spot').setDisplaySize(760, 900).setTint(0xff9a4a) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.16).setDepth(D.spot); + const flicker = () => { + if (!this.alive()) return; + this.tweens.add({ targets: this.still, alpha: 0.12 + Math.random() * 0.1, duration: 260 + Math.random() * 380, ease: 'Sine.easeInOut', onComplete: flicker }); + }; + flicker(); + } - this.logic.newGame(); + buildBadges() { + this.badges = []; + for (let seat = 1; seat < this.playerCount; seat++) { + const p = handBadge(this.L, seat); + const c = this.add.container(p.x, p.y).setDepth(D.oppHand + 2); + const g = this.add.graphics(); + g.fillStyle(0x0c1a14, 0.92); + g.fillCircle(0, 0, 16); + g.lineStyle(2.5, SEAT_COLORS[seat], 1); + g.strokeCircle(0, 0, 16); + const t = this.add.text(0, 1, '10', { fontFamily: 'Righteous', fontSize: '16px', color: INK }).setOrigin(0.5); + c.add([g, t]); + this.badges[seat] = { c, t }; + } + } + + // ── Deadwood meter ───────────────────────────────────────────────────────── + buildMeter() { + const M = METER; + this.meterG = this.add.graphics().setDepth(D.labels + 1); + const style = (size, color) => ({ fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, stroke: '#0a1410', strokeThickness: 4 }); + this.meterNum = this.add.text(M.x - M.w / 2 - 14, M.y, '', { ...style(30, INK), fontFamily: 'Righteous' }).setOrigin(1, 0.5).setDepth(D.labels + 2); + this.meterCap = this.add.text(M.x - M.w / 2 - 14, M.y - 26, 'DEADWOOD', style(11, MUTED)).setOrigin(1, 0.5).setDepth(D.labels + 2); + this.meterTxt = this.add.text(M.x, M.y - 24, '', style(16, INK)).setOrigin(0.5).setDepth(D.labels + 2); + this.meterKnock = this.add.text(0, M.y + 20, 'KNOCK', style(10, AMBER)).setOrigin(0.5, 0).setDepth(D.labels + 2); + this.meterGin = this.add.text(M.x - M.w / 2, M.y + 20, 'GIN', style(10, GREEN)).setOrigin(0.5, 0).setDepth(D.labels + 2); + this.meterObjs = [this.meterG, this.meterNum, this.meterCap, this.meterTxt, this.meterKnock, this.meterGin]; + } + + drawMeter() { + const M = METER; + const gs = this.gs; + const show = gs && !['deal', 'showdown', 'summary'].includes(this.mode) && gs.hands[0].length && !(gs.showdown && gs.showdown.knocker === 0); + for (const o of this.meterObjs) o.setVisible(!!show); + if (!show) return; + const info = this.meterInfo(); + const g = this.meterG; + g.clear(); + const MAX = 50; + const x0 = M.x - M.w / 2; + const xAt = (v) => x0 + (Math.min(MAX, v) / MAX) * M.w; + g.fillStyle(0x0a1410, 0.78); + g.fillRoundedRect(x0 - 6, M.y - M.h / 2 - 6, M.w + 12, M.h + 12, 10); + g.fillStyle(0x2a3a32, 1); + g.fillRoundedRect(x0, M.y - M.h / 2, M.w, M.h, 7); + const dw = info.value; + const col = dw === 0 ? 0x5ee0a0 : dw <= this.gs.knockLimit ? 0xffc861 : dw <= 25 ? 0xe0a060 : 0xd0605a; + if (dw > 0) { + g.fillStyle(col, 1); + g.fillRoundedRect(x0, M.y - M.h / 2, Math.max(14, xAt(dw) - x0), M.h, 7); + } else { + g.fillStyle(col, 1); + g.fillCircle(x0 + 7, M.y, 9); + } + // the knock line and the gin end + const kx = xAt(this.gs.knockLimit); + g.lineStyle(3, 0xffc861, 1); + g.lineBetween(kx, M.y - M.h / 2 - 8, kx, M.y + M.h / 2 + 8); + g.lineStyle(3, 0x5ee0a0, 1); + g.lineBetween(x0, M.y - M.h / 2 - 8, x0, M.y + M.h / 2 + 8); + this.meterKnock.setX(kx).setText(`KNOCK ≤${this.gs.knockLimit}`); + this.meterNum.setText(String(dw)).setColor(dw === 0 ? GREEN : dw <= this.gs.knockLimit ? AMBER : INK); + this.meterCap.setText(info.cap); + this.meterTxt.setText(info.text).setColor(info.color ?? INK); + } + + /** What the meter says right now. */ + meterInfo() { + const gs = this.gs; + const lim = gs.knockLimit; + if (this.mode === 'layoff' && gs.showdown) { + const dw = bestMelds(gs.hands[0]).deadwood; + const k = gs.showdown.knockerDW; + const safe = dw <= k; + return { + value: dw, cap: 'YOUR DEADWOOD', + text: safe ? `${dw} vs ${this.shortName(gs.showdown.knocker)}'s ${k} — that's an UNDERCUT!` : `${dw} vs ${this.shortName(gs.showdown.knocker)}'s ${k} — lay off cards to cut it`, + color: safe ? GREEN : INK, + }; + } + if (gs.phase === 'discard' && gs.current === 0 && gs.hands[0].length === HAND_SIZE + 1) { + const ch = this.choices(); + const focus = ch.find(o => o.card.id === (this.dragState?.id ?? this.hoverId ?? this.selectedId)); + const best = ch.filter(o => !o.banned).sort((a, b) => a.deadwood - b.deadwood || b.card.pts - a.card.pts)[0]; + if (G.canBigGin(gs, 0)) return { value: 0, cap: 'AFTER DISCARD', text: 'All eleven cards meld — call BIG GIN!', color: GREEN }; + const o = focus ?? best; + if (!o) return { value: bestMelds(gs.hands[0]).deadwood, cap: 'DEADWOOD', text: '' }; + if (o.banned) return { value: o.deadwood, cap: 'AFTER DISCARD', text: `You just took the ${cardName(o.card)} — you can't throw it back`, color: RED }; + const verb = focus ? `Discard ${cardName(o.card)}` : `Best: discard ${cardName(o.card)}`; + const tail = o.gin ? ' → GIN!' : o.canKnock ? ` → ${o.deadwood} — you can KNOCK` : ` → ${o.deadwood} deadwood`; + return { value: o.deadwood, cap: 'AFTER DISCARD', text: verb + tail, color: o.gin ? GREEN : o.canKnock ? AMBER : INK }; + } + const dw = this.myDeadwood(); + const need = dw - lim; + const text = dw === 0 ? 'Gin hand! Draw, then discard the extra card' : need <= 0 ? `Low enough to knock after your next draw` : `${need} more to shed before you can knock (≤${lim})`; + return { value: dw, cap: 'DEADWOOD', text, color: need <= 0 ? AMBER : MUTED }; + } + + // ── Tooltips ─────────────────────────────────────────────────────────────── + buildTooltips() { + for (let seat = 1; seat < this.playerCount; seat++) { + const pl = this.L.seats[seat].plate; + this.hoverZone(pl.x, pl.y, PLATE.w, PLATE.h, () => this.seatTip(seat)); + } + const d = this.L.discard, s = this.L.stock; + this.hoverZone(d.x, d.y, CARD_W * d.s + 20, CARD_H * d.s * SQ + 20, () => this.pileTip('discard')); + this.hoverZone(s.x, s.y, CARD_W * s.s + 20, CARD_H * s.s * SQ + 20, () => this.pileTip('stock')); + } + + seatTip(seat) { + const gs = this.gs; + if (!gs) return null; + const took = gs.pickups[seat].filter(id => !gs.discard.some(c => c.id === id)); + const threw = gs.discards[seat].slice(-6); + const lines = [ + { text: `${gs.scores[seat]} of ${gs.rules.target} proof · ${gs.boxes[seat]} hand${gs.boxes[seat] === 1 ? '' : 's'} won`, color: INK }, + { text: took.length ? `Took from the pile: ${took.map(id => cardName(G_card(id))).join(' ')}` : 'Hasn\'t taken from the pile this hand', color: took.length ? AMBER : MUTED }, + { text: threw.length ? `Threw: ${threw.map(id => cardName(G_card(id))).join(' ')}` : 'No discards yet', color: MUTED }, + { text: `${gs.hands[seat].length} cards · skill ${this.skillFor(seat)} / 5${seat === gs.dealer ? ' · dealer' : ''}`, color: COLORS.mutedHex }, + ]; + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; + } + + pileTip(which) { + const gs = this.gs; + if (!gs || gs.showdown) return null; + if (which === 'stock') { + const n = gs.stock.length; + return { + title: `Stock — ${n} card${n === 1 ? '' : 's'}`, + lines: [ + { text: 'Draw the top card blind.' }, + { text: gs.maxReshuffles > gs.reshuffles ? `At ${G.WASH_AT} left the discards are reshuffled in (once).` : `When a discard leaves ${G.WASH_AT}, the hand is void.`, color: n <= 6 ? RED : MUTED }, + ], + }; + } + const top = G.topDiscard(gs); + if (!top) return null; + const lines = [{ text: 'Take it to add it to your hand — everyone sees you take it.' }]; + lines.push({ text: 'You can\'t discard a card in the same turn you took it.', color: MUTED }); + if (gs.stockOnly) lines.push({ text: 'Everyone passed the upcard — draw from the stock this turn.', color: AMBER }); + lines.push({ text: `${gs.discard.length} card${gs.discard.length === 1 ? '' : 's'} in the pile · M shows every card seen`, color: COLORS.mutedHex }); + return { title: `Top card: ${cardName(top)}`, lines }; + } + + // ── Save / resume ────────────────────────────────────────────────────────── + signature() { + return JSON.stringify({ n: this.playerCount, opp: this.opponents.map(o => o?.id ?? o?.name ?? '?') }); + } + + readSave() { + try { + const s = JSON.parse(localStorage.getItem(SAVE_KEY) || 'null'); + if (!s || s.v !== 1 || s.sig !== this.signature() || !G.isValidSave(s.gs, this.playerCount)) return null; + return s; + } catch (_) { return null; } + } + + saveGame() { + if (!this.gs || !['upcard', 'draw'].includes(this.gs.phase)) return; + try { localStorage.setItem(SAVE_KEY, JSON.stringify({ v: 1, sig: this.signature(), gs: this.gs, savedAt: Date.now() })); } catch (_) { /* private mode */ } + } + + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + offerResume(save) { + const when = new Date(save.savedAt).toLocaleDateString(); + const sc = save.gs.scores.map((v, s) => `${this.shortName(s, 10)} ${v}`).join(' · '); + this.confirm('Resume your game?', `A game from ${when} is still on the table — hand ${save.gs.round}, ${sc} (to ${save.gs.rules.target}).`, 'Resume', () => { + this.gs = save.gs; + this.startRound({ resumed: true }); + }, { no: 'New game', onNo: () => { this.clearSave(); this.newMatch(); } }); + } + + // ── Match / round lifecycle ──────────────────────────────────────────────── + newMatch() { + const seed = (Math.random() * 2 ** 32) >>> 0; + this.gs = G.createGame({ players: this.playerCount, rules: this.settings.rules, seed }); this.startRound(); } - // ── Backdrop ─────────────────────────────────────────────────────────────── + async startRound({ resumed = false } = {}) { + this.clearSprites(); + this.closeModal(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + this.selectedId = null; + this.hoverId = null; + this.layoffUndo = []; + this.newIds = new Set(); + this.ended = false; + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } + const gs = this.gs; + const from = { ...this.L.stock, y: this.L.stock.y - 10 }; + const dealOrder = new Map(); + for (let s = 0; s < gs.n; s++) { + gs.hands[s].forEach((c, i) => dealOrder.set(c.id, i * gs.n + ((s - gs.first + gs.n) % gs.n))); + for (const c of gs.hands[s]) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + } + for (const c of gs.discard) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); + this.sortHand(); + this.updatePlates(); + this.updateDock(); + playSound(this, SFX.CARD_SHUFFLE); + const step = resumed ? 10 : 34; + const total = gs.n * HAND_SIZE; + this.layout({ duration: 300, delayFor: (v) => (v.kind === 'discard' ? 320 + (total + 2) * step : 300 + (dealOrder.get(v.card.id) ?? 0) * step) }); + for (let i = 0; i < total; i += 2) this.time.delayedCall(320 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.35 })); + await this.wait(300 + (total + 4) * step + 500); + if (!this.alive() || token !== this.turnToken) return; + const up = G.topDiscard(gs); + if (!resumed && gs.rules.oklahoma) { + this.floatText({ x: CX, y: this.L.discard.y - 120 }, `Oklahoma: knock with ${gs.knockLimit} or less${gs.doubled ? ' — a spade: this hand counts DOUBLE' : ''}`, AMBER, { size: 24, ms: 2600, rise: 20 }); + await this.wait(900); + } else if (!resumed && gs.phase === 'upcard') { + this.floatText({ x: CX, y: this.L.discard.y - 120 }, `The upcard is the ${cardName(up)}`, '#e8d8b0', { size: 22, ms: 1600, rise: 16 }); + } + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } - buildBackdrop() { - const pf = this.playfield; - if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.felt); - } else if (pf?.fallbackColor) { - const color = parseInt(pf.fallbackColor.replace('#', ''), 16); - this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, color).setDepth(D.felt); + advance() { + if (!this.alive() || !this.gs) return; + const gs = this.gs; + if (G.isOver(gs)) { this.onRoundOver(); return; } + if (gs.phase === 'layoff') { + const seat = gs.showdown.layoffSeat; + if (seat === 0) this.beginHumanLayoff(); + else this.runAILayoff(seat); + return; + } + const seat = gs.current; + this.saveGame(); + this.setSpot(spotFor(this.L, seat)); + if (seat === 0) { + this.mode = 'human'; + this.layout(); + this.updateDock(); + this.updatePlates(); } else { - const g = this.add.graphics().setDepth(D.felt); - g.fillGradientStyle(THEME.feltTop, THEME.feltTop, THEME.feltBottom, THEME.feltBottom, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); + this.mode = 'ai'; + this.selectedId = null; + this.layout(); + this.updateDock(); + this.updatePlates(); + this.runAITurn(seat); } - - // Table rail border - const r = this.add.graphics().setDepth(D.rail); - r.fillStyle(THEME.tableRail, 1); - r.fillRoundedRect(30, 30, GAME_WIDTH - 60, GAME_HEIGHT - 60, 40); - r.fillStyle(THEME.feltTop, 1); - r.fillRoundedRect(50, 50, GAME_WIDTH - 100, GAME_HEIGHT - 100, 30); - - r.lineStyle(3, THEME.gold, 0.4); - r.strokeRoundedRect(50, 50, GAME_WIDTH - 100, GAME_HEIGHT - 100, 30); - - // Table title - this.add.text(CX, 30, 'GIN RUMMY', { - fontFamily: 'Righteous', fontSize: '20px', color: THEME.goldHex, - }).setOrigin(0.5, 0.5).setDepth(D.ui).setAlpha(0.7); } - // ── Portraits ────────────────────────────────────────────────────────────── + /** Apply a new state and animate everything to it. */ + commit(next, { carry = null, carrySeat = null } = {}) { + const prev = this.gs; + this.gs = next; + this.cache.key = ''; + const prevMine = new Set(prev.hands[0].map(c => c.id)); + const fresh = next.hands[0].filter(c => !prevMine.has(c.id)); + this.sortHand(); + if (fresh.length) this.newIds = new Set(fresh.map(c => c.id)); + this.layout({ durationFor: (v) => (carry != null && v.card.id === carry ? this.timing(carrySeat).carry : null) }); + for (const e of next.log.slice(prev.round === next.round ? prev.log.length : 0)) this.logEffect(e); + this.updatePlates(); + this.updateDock(); + for (const id of this.newIds) this.flashGlow(id, 0x7cf0a0, { delay: 250, hold: 900 }); + this.newIds.clear(); + } - buildPortraits() { - const R = 36; - const n = 10; // HAND_SIZE — used to compute spread extents for portrait placement + logEffect(e) { + if (e.kind === 'take' && e.seat !== 0) { + const pl = this.plates[e.seat]; + this.floatText({ x: pl.x, y: pl.y + 64 }, `took the ${cardName(G_card(e.card))}`, SEAT_HEX[e.seat], { size: 20, ms: 1700, rise: 18 }); + } else if (e.kind === 'passUpcard') { + const pl = this.plates[e.seat]; + this.floatText({ x: pl.x, y: pl.y + (e.seat === 0 ? -70 : 64) }, 'passes', MUTED, { size: 20, ms: 1200, rise: 16 }); + } else if (e.kind === 'reshuffle') { + this.floatText({ x: CX, y: this.L.stock.y - 110 }, 'Stock nearly gone — the discards are reshuffled in (once)', AMBER, { size: 22, ms: 2200, rise: 18 }); + playSound(this, SFX.CARD_SHUFFLE); + } + } - this.turnRings = []; - - for (let seat = 0; seat < this.nPlayers; seat++) { - const sp = this._seatPos[seat]; - let px, py; - - if (sp.axis === 'h') { - // Horizontal spread: portrait sits to the left of the hand - const handY = seat === 0 ? PLAYER_HAND_Y : sp.y; - const spread = seat === 0 ? HAND_SPREAD : AI_SPREAD; - const leftmostX = sp.x + (0 - (n - 1) / 2) * spread; - px = leftmostX - R - 16 - (seat === 0 ? 100 : 0); - py = handY + (seat === 0 ? 50 : 0); - } else { - // Vertical spread: portrait sits above the hand - const topmostY = sp.y + (0 - (n - 1) / 2) * AI_SPREAD; - px = sp.x; - py = topmostY - R - 16; + // ── AI turns ─────────────────────────────────────────────────────────────── + async runAITurn(seat) { + const token = ++this.turnToken; + const T0 = this.timing(seat); + const opt = { skill: this.skillFor(seat) }; + const live = () => this.alive() && token === this.turnToken && !this.ended; + await this.wait(T0.think); + if (!live() || this.gs.current !== seat) return; + let gs = this.gs; + if (gs.phase === 'upcard' || gs.phase === 'draw') { + const src = chooseDraw(gs, seat, opt); + const takeTop = src === 'discard'; + const top = G.topDiscard(gs); + const pilePose = takeTop ? this.poseOf(top.id) ?? this.L.discard : this.deckTop(); + this.moveHand(seat, pilePose, T0.reach); + await this.wait(T0.reach); + if (!live()) return; + let next; + if (gs.phase === 'upcard') next = takeTop ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat); + else next = takeTop ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat); + if (next === gs) return; + const moved = takeTop ? top.id : (gs.phase === 'draw' ? gs.stock[0].id : null); + if (moved) { + this.moveHand(seat, handHome(this.L, seat), T0.carry, 'Cubic.easeOut'); + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.5 }); } + this.handRest(seat, T0.carry * 0.7, T0.carry); + this.commit(next, { carry: moved, carrySeat: seat }); + await this.wait(T0.carry + T0.between); + if (!live()) return; + if (next.phase !== 'discard' || next.current !== seat) { this.advance(); return; } + await this.wait(T0.think * 0.8); + if (!live()) return; + } + gs = this.gs; + if (gs.phase !== 'discard' || gs.current !== seat) return; + const a = chooseAction(gs, seat, opt); + if (a.kind === 'biggin') { + const next = G.bigGin(gs, seat); + if (next !== gs) { this.commit(next); this.onShowdown(); } + return; + } + const pose = this.poseOf(a.id) ?? handHome(this.L, seat); + this.moveHand(seat, pose, T0.reach * 0.7); + await this.wait(T0.reach * 0.7); + if (!live()) return; + const next = a.kind === 'discard' ? G.discard(gs, seat, a.id) : G.knock(gs, seat, a.id); + if (next === gs) return; + this.moveHand(seat, this.L.discard, T0.carry, 'Cubic.easeOut'); + this.handRest(seat, T0.carry * 0.7, T0.carry); + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.55 }); + this.commit(next, { carry: a.id, carrySeat: seat }); + if (next.showdown) { await this.wait(T0.carry); if (this.alive()) this.onShowdown(); return; } + await this.wait(T0.carry + 120); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } - if (seat === 0) { - createPlayerPortrait(this, px, py, R, D.ui, 'GinRummyGame'); - } else { - createOpponentPortrait(this, this.opponents[seat - 1], px, py, R, D.ui); - } + async runAILayoff(seat) { + const token = ++this.turnToken; + this.mode = 'showdown'; + this.updateDock(); + this.setSpot(spotFor(this.L, seat), 0.18); + const T0 = this.timing(seat); + await this.wait(Math.max(500, T0.think)); + if (!this.alive() || token !== this.turnToken) return; + const plan = chooseLayoffs(this.gs, seat, { skill: this.skillFor(seat) }); + for (const l of plan) { + const next = G.layoff(this.gs, seat, l.id, l.meldIdx); + if (next === this.gs) continue; + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.5 }); + this.commit(next); + const p = this.poseOf(l.id); + if (p) this.floatText(p, 'laid off', SEAT_HEX[seat], { size: 18, ms: 1100, rise: 24 }); + await this.wait(Math.max(380, T0.between * 1.4)); + if (!this.alive() || token !== this.turnToken) return; + } + if (!plan.length) { + const pl = this.plates[seat]; + this.floatText({ x: pl.x, y: pl.y + 64 }, 'nothing to lay off', MUTED, { size: 18, ms: 1300, rise: 16 }); + await this.wait(500); + } + const next = G.endLayoff(this.gs, seat); + if (next === this.gs) return; + this.commit(next); + await this.wait(380); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } - // Turn ring — bright yellow pulsing stroke, hidden until it's this seat's turn - const ring = this.add.graphics().setDepth(D.ui + 1).setAlpha(0); - ring.lineStyle(4, 0xffee00, 1); - ring.strokeCircle(px, py, R + 5); - this.turnRings.push(ring); + // ── Showdown ─────────────────────────────────────────────────────────────── + async onShowdown() { + const token = ++this.turnToken; + this.mode = 'showdown'; + this.selectedId = null; + this.hoverId = null; + this.cancelDrag(); + this.input.setDefaultCursor('default'); + for (let s = 1; s < this.playerCount; s++) this.handRest(s, 300); + this.setSpot({ x: CX, y: 520, w: 1500, h: 760 }, 0.22); + const sd = this.gs.showdown; + const k = sd.knocker; + this.updateDock(); + if (sd.kind === 'knock') { + this.knockFx(k); + playSoundEx(this, SFX.PIECE_CLICK, { volume: 0.9, rate: 0.8 }); + this.time.delayedCall(140, () => playSoundEx(this, SFX.PIECE_CLICK, { volume: 0.9, rate: 0.75 })); + } else { + this.seal(sd.kind === 'gin' ? 'GIN!' : 'BIG GIN!', k === 0 ? 'You go gin' : `${this.shortName(k, 14)} goes gin`, 'gin-seal', '#1f5a52'); + playSound(this, SFX.CASINO_WIN); + } + this.portraits[k]?.playEmotion?.('happy'); + await this.wait(1100); + if (!this.alive() || token !== this.turnToken) return; + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.5, rate: 1.3 }); + this.layout({ duration: 520 }); + await this.wait(1000); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } + + knockFx(seat) { + const pl = this.plates[seat]; + const at = seat === 0 ? { x: CX, y: 640 } : { x: pl.x, y: pl.y + 90 }; + const burst = this.add.image(at.x, at.y, 'gin-knuckle').setDepth(D.stamp).setScale(0.3).setAlpha(0.9); + this.tweens.add({ targets: burst, scale: 1.1, alpha: 0, duration: 520, ease: 'Cubic.easeOut', onComplete: () => burst.destroy() }); + this.stamp('KNOCK!', { x: at.x, y: at.y }, SEAT_HEX[seat], { size: 70, hold: 900, sub: `${seat === 0 ? 'You knock' : `${this.shortName(seat, 14)} knocks`} with ${this.gs.showdown.knockerDW}` }); + this.cameras.main.shake(160, 0.004); + } + + /** A bottle-label / wax seal badge with text, centre table. */ + seal(text, sub, tex, color, { at = { x: CX, y: CY - 40 }, hold = 1300 } = {}) { + const img = this.add.image(0, 0, tex).setScale(tex === 'gin-wax' ? 1.0 : 0.95); + const t = this.add.text(0, -6, text, { + fontFamily: 'Righteous', fontSize: text.length > 6 ? '52px' : '74px', color: tex === 'gin-wax' ? '#fff2e8' : color, + stroke: tex === 'gin-wax' ? '#4a0008' : '#f2e8cf', strokeThickness: 4, + }).setOrigin(0.5); + const objs = [img, t]; + if (sub) objs.push(this.add.text(0, 58, sub, { fontFamily: '"Julius Sans One"', fontSize: '17px', color: tex === 'gin-wax' ? '#ffd8d0' : '#2a4a40' }).setOrigin(0.5)); + const c = this.add.container(at.x, at.y, objs).setDepth(D.stamp).setScale(2.4).setAlpha(0).setRotation(-0.08); + this.tweens.add({ targets: c, scale: 1, alpha: 1, duration: 260, ease: 'Back.easeOut' }); + this.tweens.add({ targets: c, alpha: 0, scale: 0.9, delay: hold, duration: 360, onComplete: () => c.destroy() }); + this.burst(at, tex === 'gin-wax' ? 0xe0505a : 0x5ee0c0, { n: 12, r: 190 }); + } + + // ── Human lay-offs ───────────────────────────────────────────────────────── + beginHumanLayoff() { + this.mode = 'layoff'; + this.layoffUndo = []; + this.selectedId = null; + this.setSpot(spotFor(this.L, 0)); + this.layout(); + this.updateDock(); + if (this.settings.hints && !coachLayoffs(this.gs, 0).length) { + this.floatText({ x: CX, y: 760 }, 'Nothing of yours fits the knocker\'s melds — click Done', MUTED, { size: 20, ms: 2200, rise: 14 }); } } - setTurnRing(seat) { - this.turnRings?.forEach((ring, i) => { - if (i !== seat) { - this.tweens.killTweensOf(ring); - ring.setAlpha(0); - } - }); - const ring = this.turnRings?.[seat]; - if (!ring) return; - ring.setAlpha(1); - this.tweens.killTweensOf(ring); - this.tweens.add({ - targets: ring, - alpha: { from: 1, to: 0.25 }, - duration: 600, - yoyo: true, - repeat: -1, - ease: 'Sine.easeInOut', - }); + layoffCard(id, meldIdx = null) { + if (this.mode !== 'layoff' || this.modal) return false; + const mi = meldIdx ?? G.layoffTarget(this.gs, id); + if (mi < 0) { this.nudge(id); this.floatText({ x: CX, y: 760 }, 'That card doesn\'t fit any of the knocker\'s melds', RED, { size: 20 }); return false; } + const next = G.layoff(this.gs, 0, id, mi); + if (next === this.gs) { this.nudge(id); return false; } + this.layoffUndo.push(this.gs); + playSound(this, SFX.CARD_PLACE); + this.commit(next); + return true; } - // ── Score panel ──────────────────────────────────────────────────────────── - - buildScorePanel() { - const px = GAME_WIDTH - 370, py = 120; - const panelH = 60 + this.nPlayers * 68; - const g = this.add.graphics().setDepth(D.ui - 1); - g.fillStyle(0x000000, 0.35); - g.fillRoundedRect(px - 10, py - 10, 160, panelH, 12); - g.lineStyle(1.5, THEME.gold, 0.4); - g.strokeRoundedRect(px - 10, py - 10, 160, panelH, 12); - - this.add.text(px + 70, py, 'SCORES', { - fontFamily: 'Righteous', fontSize: '16px', color: THEME.goldHex, - }).setOrigin(0.5, 0).setDepth(D.ui).setAlpha(0.8); - - this.scoreTexts = []; - const names = ['You', ...this.opponents.map(o => o.name?.split(' ')[0] ?? 'AI')]; - for (let s = 0; s < this.nPlayers; s++) { - const ry = py + 36 + s * 68; - const col = s === 0 ? '#f07a6d' : THEME.ivoryHex; - this.add.text(px, ry, names[s], { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: THEME.mutedHex, - }).setDepth(D.ui); - this.scoreTexts.push(this.add.text(px + 140, ry + 24, '0', { - fontFamily: 'Righteous', fontSize: '36px', color: col, - }).setOrigin(1, 0).setDepth(D.ui)); - } - - // Round indicator - this.roundText = this.add.text(px + 70, py + 36 + this.nPlayers * 68 + 8, 'Round 1', { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: THEME.mutedHex, - }).setOrigin(0.5, 0).setDepth(D.ui); + layoffBest() { + if (this.mode !== 'layoff' || this.modal) return; + // start from the hand as it was dealt into the showdown, then apply the optimum + while (this.layoffUndo.length) this.gs = this.layoffUndo.shift(); + const plan = coachLayoffs(this.gs, 0); + let g = this.gs; + for (const l of plan) { const n = G.layoff(g, 0, l.id, l.meldIdx); if (n !== g) { this.layoffUndo.push(g); g = n; } } + if (g === this.gs) { this.floatText({ x: CX, y: 760 }, 'No lay-off would help you', MUTED, { size: 20 }); this.layout(); this.updateDock(); return; } + playSound(this, SFX.CARD_PLACE); + this.commit(g); } - refreshScores() { - for (let s = 0; s < this.nPlayers; s++) { - this.scoreTexts[s].setText(String(this.logic.players[s].score)); - } - this.roundText.setText(`Round ${this.logic.round}`); + undoLayoff() { + if (this.mode !== 'layoff' || !this.layoffUndo.length || this.modal) return; + this.gs = this.layoffUndo.pop(); + this.cache.key = ''; + playSoundEx(this, SFX.UI_PICK, { volume: 0.4 }); + this.sortHand(); + this.layout(); + this.updateDock(); } - // ── Pile placeholders ────────────────────────────────────────────────────── - - buildPiles() { - const { stock, discard } = this._pilePos; - - this._drawCardBack(stock.x, stock.y, 0.6).setDepth(D.pile - 1); - this._drawCardBack(discard.x, discard.y, 0.6).setDepth(D.pile - 1); - - this.add.text(stock.x, stock.y + CARD_H / 2 + 14, 'STOCK', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: THEME.mutedHex }).setOrigin(0.5, 0).setDepth(D.ui); - this.add.text(discard.x, discard.y + CARD_H / 2 + 14, 'DISCARD', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: THEME.mutedHex }).setOrigin(0.5, 0).setDepth(D.ui); - - // Stock count text - this.stockCountText = this.add.text(stock.x, stock.y - CARD_H / 2 - 14, '', { - fontFamily: '"Julius Sans One"', fontSize: '13px', color: THEME.mutedHex, - }).setOrigin(0.5, 1).setDepth(D.ui); + finishLayoff() { + if (this.mode !== 'layoff' || this.modal) return; + const next = G.endLayoff(this.gs, 0); + if (next === this.gs) return; + this.mode = 'showdown'; + this.layoffUndo = []; + this.commit(next); + this.time.delayedCall(350, () => this.advance()); } - _drawCardBack(x, y, alpha = 1) { - const g = this.add.graphics(); - g.fillStyle(THEME.cardBack, alpha); - g.fillRoundedRect(x - CARD_W / 2, y - CARD_H / 2, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, THEME.cardBackHi, alpha * 0.5); - g.strokeRoundedRect(x - CARD_W / 2 + 4, y - CARD_H / 2 + 4, CARD_W - 8, CARD_H - 8, CARD_R - 2); - return g; - } - - // ── Action bar ───────────────────────────────────────────────────────────── - - buildActionBar() { - this.statusText = this.add.text(CX, 1000, '', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: THEME.textHex, - }).setOrigin(0.5).setDepth(D.ui); - - this.knockBtn = new Button(this, CX - 80, PLAYER_HAND_Y - CARD_H / 2 - 34, 'Knock', () => this.onKnock(), { - width: 130, height: 46, fontSize: 20, - }).setDepth(D.ui).setVisible(false); - - this.ginBtn = new Button(this, CX + 80, 1008, 'Gin!', () => this.onGin(), { - width: 130, height: 46, fontSize: 20, variant: 'accent', - }).setDepth(D.ui).setVisible(false); - - this.layoffDoneBtn = new Button(this, CX, 1008, 'Done Laying Off', () => this.onLayoffDone(), { - width: 200, height: 46, fontSize: 18, - }).setDepth(D.ui).setVisible(false); - - new Button(this, GAME_WIDTH - 80, 1054, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 130, height: 40, fontSize: 16, - }).setDepth(D.ui); - } - - // ── Sort buttons ─────────────────────────────────────────────────────────── - - buildSortButtons() { - new Button(this, 80, 1008, 'By Suit', () => this.sortHandBySuit(), { - variant: 'ghost', width: 110, height: 40, fontSize: 16, - }).setDepth(D.ui); - - new Button(this, 200, 1008, 'By Rank', () => this.sortHandByRank(), { - variant: 'ghost', width: 110, height: 40, fontSize: 16, - }).setDepth(D.ui); - } - - sortHandBySuit() { - this.logic.players[0].hand = sortBySuit(this.logic.players[0].hand); - this.renderHand(0); - this.updateActionButtons(); - } - - sortHandByRank() { - this.logic.players[0].hand = sortByRank(this.logic.players[0].hand); - this.renderHand(0); - this.updateActionButtons(); - } - - // ── Drag-to-reorder (adapted from Phase10Game.js) ───────────────────────── - - setupDragHandlers() { - this.input.on('pointermove', (pointer) => { - if (this.potentialDrag && !this.dragState) { - const dx = pointer.x - this.potentialDrag.startX; - const dy = pointer.y - this.potentialDrag.startY; - if (Math.sqrt(dx * dx + dy * dy) >= 8) { - const pd = this.potentialDrag; - this.potentialDrag = null; - this.startCardDrag(pd.handIdx, pd.offsetX, pd.offsetY); + // ── End of round ─────────────────────────────────────────────────────────── + async onRoundOver() { + if (this.mode === 'summary' || this.ended) return; + this.mode = 'summary'; + this.ended = true; + const token = ++this.turnToken; + this.cancelDrag(); + this.selectedId = null; + this.hoverId = null; + this.input.setDefaultCursor('default'); + this.updateDock(); + this.layout({ duration: 420 }); + const gs = this.gs; + const r = gs.result; + await this.wait(500); + if (!this.alive() || token !== this.turnToken) return; + if (r.kind === 'wash') { + this.stamp('Void hand', { x: CX, y: CY - 40 }, '#e8d8b0', { size: 76, hold: 1400, sub: `Only ${gs.stock.length} cards left and nobody knocked — no score, same dealer` }); + playSoundEx(this, SFX.CARD_SHUFFLE, { volume: 0.5 }); + await this.wait(1900); + } else { + // each defender's line, one at a time + for (const l of r.lines) { + const at = this.lineAnchor(l.seat); + const who = l.to === 'knocker' ? r.knocker : l.seat; + let txt; + if (l.why === 'gin') txt = `${l.deadwood} + ${gs.rules.ginBonus} gin bonus`; + else if (l.why === 'biggin') txt = `${l.deadwood} + ${gs.rules.bigGinBonus} big gin`; + else if (l.why === 'knock') txt = `${l.deadwood} − ${r.knockerDW}`; + else txt = `undercut! ${r.knockerDW} − ${l.deadwood} + ${gs.rules.undercutBonus}`; + if (r.doubled) txt += ' ×2'; + this.floatText(at, `${txt} = ${l.pts} to ${this.shortName(who, 12)}`, l.why === 'undercut' ? RED : SEAT_HEX[who], { size: 24, ms: 2400, rise: 22 }); + if (l.why === 'undercut') { + this.seal('UNDERCUT!', `${l.seat === 0 ? 'You' : this.shortName(l.seat, 14)} beat the knock`, 'gin-wax', '#fff', { hold: 1500 }); + playSound(this, SFX.CASINO_LOSE); + this.portraits[l.seat]?.playEmotion?.('happy'); + this.portraits[r.knocker]?.playEmotion?.('upset'); } + playSoundEx(this, SFX.PENCIL_WRITE, { volume: 0.45 }); + await this.wait(l.why === 'undercut' ? 1900 : 1200); + if (!this.alive() || token !== this.turnToken) return; } - if (this.dragState) this.updateCardDrag(pointer); - }); + for (let s = 0; s < gs.n; s++) { + if (!r.deltas[s]) continue; + const pl = this.plates[s]; + this.floatText({ x: pl.x, y: pl.y + (s === 0 ? -70 : 70) }, `+${r.deltas[s]}`, SEAT_HEX[s], { size: 34, ms: 1800, rise: 28 }); + } + await this.wait(900); + } + if (!this.alive() || token !== this.turnToken) return; + this.updatePlates(); + if (gs.phase === 'gameOver') { + const won = gs.winner === 0; + this.clearSave(); + const fin = gs.final; + this.recordResult('ginrummy', { score: fin[0].total, opponentScores: fin.slice(1).map(f => f.total), won }); + playSound(this, won ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < gs.n; s++) this.portraits[s]?.playEmotion?.(gs.winner === s ? 'win' : 'loss'); + this.openScorePad({ result: true }); + return; + } + // save the next deal, so leaving from the summary resumes at the new hand + if (gs.phase === 'roundOver') { + try { localStorage.setItem(SAVE_KEY, JSON.stringify({ v: 1, sig: this.signature(), gs: G.nextRound(gs), savedAt: Date.now() })); } catch (_) { /* */ } + } + this.openScorePad({ result: true }); + } - this.input.on('pointerup', () => { - if (this.potentialDrag) { - const pd = this.potentialDrag; - this.potentialDrag = null; - // Re-resolve the index from the card container at event time. No reorder - // can happen between pointerdown and a plain pointerup, but resolving from - // the (stable) container is the safest way to stay correct. - const idx = this.humanCards.indexOf(pd.card); - this.onHandClick(idx === -1 ? pd.handIdx : idx); + /** Where a defender's score line floats up from. */ + lineAnchor(seat) { + if (seat === 0) return { x: CX, y: 760 }; + const row = this.rowsInfo?.find(r => r.seat === seat); + if (row) return { x: row.x1 + 180, y: row.y }; + const pl = this.plates[seat]; + return { x: pl.x, y: pl.y + 70 }; + } + + async nextRound() { + this.closeModal(); + if (this.gs.phase !== 'roundOver') return; + this.mode = 'deal'; + this.updateDock(); + this.rowG.clear(); + this.hideRowTexts(); + await this.sweepCards(this.L.stock); + if (!this.alive()) return; + this.gs = G.nextRound(this.gs); + this.startRound(); + } + + // ── Layout ───────────────────────────────────────────────────────────────── + deckTop() { + const n = this.gs.stock.length; + const base = this.gs.showdown ? this.L.sdStock : this.L.stock; + return { ...base, y: base.y - stackLift(n, base.s, 0.1, 10) }; + } + + /** Cached per-state numbers for the human (discard options, coach, deadwood). */ + stateKey() { + const gs = this.gs; + return `${gs.round}|${gs.turn}|${gs.phase}|${gs.current}|${gs.hands[0].map(c => c.id).join('')}|${gs.discard.length}`; + } + + refreshCache() { + const key = this.stateKey(); + if (this.cache.key === key) return; + this.cache = { key, choices: null, coach: null, dw: null }; + } + + choices() { + this.refreshCache(); + if (!this.cache.choices) this.cache.choices = G.discardChoices(this.gs, 0); + return this.cache.choices; + } + + myDeadwood() { + this.refreshCache(); + if (this.cache.dw == null) this.cache.dw = bestMelds(this.gs.hands[0]).deadwood; + return this.cache.dw; + } + + coach() { + this.refreshCache(); + const gs = this.gs; + if (this.cache.coach) return this.cache.coach; + if (gs.current !== 0 || !['upcard', 'draw', 'discard'].includes(gs.phase)) return null; + this.cache.coach = gs.phase === 'discard' ? coachAction(gs, 0) : coachDraw(gs, 0); + return this.cache.coach; + } + + isMyTurn() { return this.mode === 'human' && this.gs?.current === 0 && ['upcard', 'draw', 'discard'].includes(this.gs.phase); } + canAct() { return this.isMyTurn() && !this.modal && !this.paused; } + + sortHand() { + const gs = this.gs; + if (!gs) return; + const hand = gs.hands[0]; + const mode = this.settings.sort; + if (mode === 'manual') return; + let order; + if (mode === 'melds') order = meldOrder(hand).order; + else order = hand.slice().sort(mode === 'rank' ? byRank : bySuit); + hand.splice(0, hand.length, ...order); + } + + /** Meld groups for the human hand: id → meld index, plus gap blocks for the Melds sort. */ + meldInfo() { + const hand = this.gs.hands[0]; + const mo = meldOrder(hand); + const groupOf = new Map(); + mo.melds.forEach((m, i) => m.forEach(c => groupOf.set(c.id, i))); + let slots = null; + if (this.settings.sort === 'melds' && !this.dragPreview && hand.map(c => c.id).join() === mo.order.map(c => c.id).join()) { + slots = blockSlots([...mo.melds.map(m => m.length), mo.loose.length]); + } + return { groupOf, slots, loose: new Set(mo.loose.map(c => c.id)) }; + } + + /** Lift for each card of the human hand (shared by layout + hit-tests). */ + humanLift(id) { + if (id === this.selectedId) return 40; + if (id === this.hoverId) return 22; + if (this.mode === 'layoff' && this.settings.hints && G.layoffTarget(this.gs, id) >= 0) return 10; + return 0; + } + + humanPoses() { + const hand = this.gs.hands[0]; + const ids = this.dragPreview ?? hand.map(c => c.id); + const info = this.meldInfoCache ?? this.meldInfo(); + const slots = info.slots; + return ids.map((id, i) => ({ + id, idx: i, + pose: handPose(this.L, 0, i, ids.length, this.humanLift(id), slots?.slots, slots?.total), + })); + } + + /** Showdown rows: [{ seat, blocks: [[card]], kinds: ['meld'|'loose'], row }] */ + showdownRows() { + const gs = this.gs; + const sd = gs.showdown; + if (!sd) return []; + const k = sd.knocker; + const seats = [k, ...sd.order.filter(s => s !== 0)]; + if (k !== 0 && !seats.includes(0)) { /* the human defends from their fan */ } + const rows = []; + const n = seats.length; + seats.forEach((seat, r) => { + let blocks, kinds; + if (seat === k) { + const loose = sd.loose.map(id => gs.hands[k].find(c => c.id === id)).filter(Boolean); + blocks = [...sd.melds, ...(loose.length ? [loose] : [])]; + kinds = [...sd.melds.map(() => 'meld'), ...(loose.length ? ['loose'] : [])]; + } else { + const line = gs.result?.lines?.find(l => l.seat === seat); + const bm = line ? { melds: line.melds, loose: line.loose.map(id => gs.hands[seat].find(c => c.id === id)).filter(Boolean) } : bestMelds(gs.hands[seat]); + blocks = [...bm.melds, ...(bm.loose.length ? [bm.loose.slice().sort(bySuit)] : [])]; + kinds = [...bm.melds.map(() => 'meld'), ...(bm.loose.length ? ['loose'] : [])]; + } + const row = rowPoses(r, n, blocks); + rows.push({ seat, blocks, kinds, row, y: row.y, x1: row.x1, knocker: seat === k }); + }); + return rows; + } + + computeLayout() { + const L = this.L, gs = this.gs; + const visible = new Map(), loc = new Map(); + const put = (card, v) => { visible.set(card.id, { card, ...v }); loc.set(card.id, v); }; + const sd = gs.showdown; + // stock + const dn = gs.stock.length; + const deckPose = this.deckTop(); + gs.stock.forEach((card, i) => { + if (i === 0) put(card, { kind: 'stock', pose: deckPose, faceUp: false, depth: D.cards + 1 }); + else loc.set(card.id, { pose: deckPose, faceUp: false, depth: D.cards }); + }); + // discard pile: the last few show, slightly askew + const pn = gs.discard.length; + const dBase = sd ? L.sdDiscard : L.discard; + gs.discard.forEach((card, i) => { + const j = jitterFor(`gin-${card.id}`); + const lift = stackLift(Math.min(pn, 30), dBase.s, 0.1, 7) * ((i + 1) / pn); + const pose = { ...dBase, x: dBase.x + j.x * 5, y: dBase.y - lift + j.y * 4, rot: j.rot * 6 }; + if (i >= pn - 3) put(card, { kind: 'discard', pose, faceUp: true, depth: D.cards + 1 + (i - pn + 3) * 0.01, top: i === pn - 1 }); + else loc.set(card.id, { pose, faceUp: true, depth: D.cards }); + }); + // showdown rows + const rows = this.showdownRows(); + this.rowsInfo = rows; + const inRow = new Set(); + rows.forEach((r) => { + r.blocks.forEach((b, bi) => b.forEach((card, i) => { + inRow.add(card.id); + put(card, { + kind: 'row', seat: r.seat, block: bi, blockKind: r.kinds[bi], knockerRow: r.knocker, laidBy: card.laidBy ?? null, + pose: r.row.poses[bi][i], faceUp: true, depth: D.cards + 3 + bi * 0.02 + i * 0.001, + }); + })); + }); + // hands + this.meldInfoCache = gs.hands[0].length ? this.meldInfo() : null; + for (let seat = 0; seat < gs.n; seat++) { + const hand = gs.hands[seat]; + if (seat === 0) { + if (sd && sd.knocker === 0) continue; + const byId = new Map(hand.map(c => [c.id, c])); + for (const h of this.humanPoses()) { + const card = byId.get(h.id); + if (!card || inRow.has(card.id)) continue; + put(card, { kind: 'hand', seat: 0, idx: h.idx, pose: h.pose, faceUp: true, depth: D.hand + h.idx * 0.01 }); + } + } else { + hand.forEach((card, i) => { + if (inRow.has(card.id)) return; + put(card, { kind: 'hand', seat, idx: i, pose: handPose(L, seat, i, hand.length), faceUp: false, depth: D.oppHand + i * 0.01 }); + }); + } + } + this.meldInfoCache = null; + return { visible, loc }; + } + + beforeLayout() { + this.meldInfoCache = null; + this.layoutMeld = this.gs.hands[0].length ? this.meldInfo() : null; + this.knockable = null; + this.suggested = null; + const mine = (this.mode === 'human' || this.mode === 'knockpick') && this.gs.current === 0 && this.gs.phase === 'discard'; + if (mine) { + this.knockable = new Set(this.choices().filter(o => o.canKnock).map(o => o.card.id)); + if (this.settings.hints) this.suggested = this.coach()?.id ?? null; + } + } + + decorate(c, v) { + const mine = v.kind === 'hand' && v.seat === 0; + let mark = '', markColor = '#ffd35a'; + let chip = ''; + let glow = false, tint = 0xffd35a, glowA = 1; + let dim = false; + if (mine) { + const info = this.layoutMeld; + const g = info?.groupOf.get(v.card.id); + if (this.settings.hints && g != null) { glow = true; tint = MELD_COLORS[g % MELD_COLORS.length]; glowA = 0.75; } + if (this.settings.hints && g == null) chip = String(v.card.pts); + if (this.suggested === v.card.id) mark = '★'; + if (this.mode === 'knockpick') { + if (this.knockable?.has(v.card.id)) { glow = true; tint = 0xffc861; glowA = 1; mark = '✓'; } + else dim = true; + } + if (this.mode === 'layoff') { + const t = G.layoffTarget(this.gs, v.card.id); + if (t >= 0) { glow = true; tint = 0x7cf0a0; glowA = 1; mark = '+'; markColor = '#7cf0a0'; } + } + if (v.card.id === this.gs.takenFrom && this.gs.phase === 'discard' && this.gs.current === 0) { mark = '⟲'; markColor = '#ff9a7a'; } + if (v.card.id === this.selectedId) { glow = true; tint = 0xffffff; glowA = 1; } + } else if (v.kind === 'row') { + if (v.blockKind === 'loose') chip = String(v.card.pts); + if (v.laidBy != null) { mark = '+'; markColor = SEAT_HEX[v.laidBy]; glow = true; tint = SEAT_COLORS[v.laidBy]; glowA = 0.8; } + } + c.mark.setText(mark).setColor(markColor).setVisible(!!mark && v.faceUp); + c.chip.setText(chip).setFontSize(19).setVisible(!!chip && v.faceUp); + c.glow.setVisible(glow).setTint(tint).setAlpha(glowA); + c.faceImg.setTint(dim ? 0x8a8478 : 0xffffff); + } + + afterLayout() { + this.drawSlabs(); + this.drawPileHints(); + this.drawRows(); + this.drawMeter(); + this.updateBadges(); + const n = this.gs.stock.length; + const sd = this.gs.showdown; + const sp = sd ? this.L.sdStock : this.L.stock; + this.stockTxt.setPosition(sp.x, sp.y + (sd ? 52 : 82)).setText(n ? `${n} left` : '').setColor(n <= G.WASH_AT + 3 ? '#ff9a7a' : '#e8d8b0'); + const lim = this.gs.knockLimit; + this.limitTxt.setText(sd ? '' : `${lim !== 10 ? `Knock with ${lim} or less` : ''}${this.gs.doubled ? `${lim !== 10 ? ' · ' : ''}this hand counts double` : ''}`); + } + + drawSlabs() { + const g = this.slabG; + g.clear(); + const n = this.gs.stock.length; + if (n <= 1) return; + const base = this.gs.showdown ? this.L.sdStock : this.L.stock; + const lift = stackLift(n, base.s, 0.1, 10); + const layers = Math.max(1, Math.min(8, Math.ceil(lift / 1.6))); + for (let j = 0; j < layers; j++) { + const y = base.y - (lift * j) / layers; + const hw = (CARD_W / 2) * base.s, hh = (CARD_H / 2) * base.s * SQ; + g.fillStyle(j % 2 ? 0x1c4a44 : 0x123630, 1); + g.fillRoundedRect(base.x - hw, y - hh, hw * 2, hh * 2, 8 * base.s); + } + } + + /** Coach glow on the pile it suggests drawing from (upcard / draw phase). */ + drawPileHints() { + const g = this.pileG; + g.clear(); + if (!this.isMyTurn() || this.gs.phase === 'discard') return; + const ring = (p, color, a) => { + const hw = (CARD_W / 2) * p.s + 12, hh = (CARD_H / 2) * p.s * SQ + 12; + g.lineStyle(4, color, a); + g.strokeRoundedRect(p.x - hw, p.y - hh, hw * 2, hh * 2, 14); + }; + const canTake = !this.gs.stockOnly && this.gs.discard.length; + if (this.gs.phase !== 'upcard') ring(this.deckTop(), 0xe8d8b0, 0.55); + if (canTake) ring(this.L.discard, 0xe8d8b0, 0.55); + if (!this.settings.hints) return; + const tip = this.coach(); + if (!tip) return; + ring(tip.source === 'discard' ? this.L.discard : this.deckTop(), 0x7cf0a0, 0.95); + } + + hideRowTexts() { for (const t of this.rowTexts) t.setVisible(false); } + + rowText(i) { + if (!this.rowTexts[i]) { + this.rowTexts[i] = this.add.text(0, 0, '', { + fontFamily: '"Julius Sans One"', fontSize: '16px', color: INK, align: 'right', stroke: '#0a1410', strokeThickness: 4, lineSpacing: 2, + }).setOrigin(1, 0.5).setDepth(D.labels + 2); + } + return this.rowTexts[i]; + } + + drawRows() { + const g = this.rowG; + g.clear(); + this.targetG.clear(); + const rows = this.rowsInfo ?? []; + let ti = 0; + const sd = this.gs.showdown; + for (const r of rows) { + const t = this.rowText(ti++); + const who = r.seat === 0 ? 'You' : this.shortName(r.seat, 12); + const line = this.gs.result?.lines?.find(l => l.seat === r.seat); + let sub; + if (r.knocker) sub = sd.kind === 'knock' ? `knocked · deadwood ${sd.knockerDW}` : sd.kind === 'gin' ? 'GIN — no deadwood' : 'BIG GIN — all 11'; + else { + const dw = line ? line.deadwood : bestMelds(this.gs.hands[r.seat]).deadwood; + sub = `deadwood ${dw}${line?.laid?.length ? ` · laid off ${line.laid.length}` : ''}`; + } + t.setText(`${who}\n${sub}`).setPosition(ROW.labelX, r.y).setColor(SEAT_HEX[r.seat]).setVisible(true); + // brackets under each block + let mi = 0; + r.kinds.forEach((kind, bi) => { + const rect = blockRect(r.row, bi); + const col = kind === 'meld' ? MELD_COLORS[(mi++) % MELD_COLORS.length] : 0xb9a98a; + g.lineStyle(3, col, kind === 'meld' ? 0.9 : 0.6); + g.lineBetween(rect.x0 + 4, rect.y1 + 7, rect.x1 - 4, rect.y1 + 7); + g.lineBetween(rect.x0 + 4, rect.y1 + 2, rect.x0 + 4, rect.y1 + 7); + g.lineBetween(rect.x1 - 4, rect.y1 + 2, rect.x1 - 4, rect.y1 + 7); + }); + } + for (let i = ti; i < this.rowTexts.length; i++) this.rowTexts[i].setVisible(false); + // lay-off targets for the card you're dragging / hovering + if (this.mode === 'layoff' && sd) { + const kr = rows.find(r => r.knocker); + const id = this.dragState?.id ?? this.hoverId; + const card = id ? this.gs.hands[0].find(c => c.id === id) : null; + if (kr && card) { + sd.melds.forEach((m, mi) => { + if (!canLayoff(card, m)) return; + const rect = blockRect(kr.row, mi); + const hot = this.dragState?.target?.type === 'meld' && this.dragState.target.meldIdx === mi; + this.targetG.lineStyle(hot ? 5 : 3, 0x7cf0a0, hot ? 1 : 0.85); + this.targetG.strokeRoundedRect(rect.x0 - 8, rect.y0 - 8, rect.x1 - rect.x0 + 16, rect.y1 - rect.y0 + 16, 10); + }); + } + } + } + + updateBadges() { + for (let s = 1; s < this.playerCount; s++) { + const b = this.badges[s]; + if (!b) continue; + const n = this.gs.hands[s].length; + const hide = !!this.gs.showdown; + b.c.setVisible(!hide); + b.t.setText(String(n)); + } + } + + // ── Plates: name · score · proof bottle ──────────────────────────────────── + updatePlates() { + if (!this.gs) return; + const gs = this.gs; + const g = this.plateG; + g.clear(); + for (let s = 0; s < gs.n; s++) { + const pl = this.plates[s]; + if (!pl) continue; + pl.scoreTxt.setText(`${gs.scores[s]}`); + const took = gs.pickups[s].filter(id => gs.hands[s].some(c => c.id === id)); + let info = ''; + if (s === 0) info = `${gs.boxes[0]} hand${gs.boxes[0] === 1 ? '' : 's'} won`; + else info = took.length ? `took ${took.slice(-3).map(id => cardName(G_card(id))).join(' ')}` : `${gs.hands[s].length} cards`; + pl.infoTxt.setText(info).setColor(took.length && s ? AMBER : COLORS.goldHex); + const status = gs.showdown?.knocker === s ? (gs.showdown.kind === 'knock' ? 'knocked' : 'gin!') : s === gs.dealer ? 'dealer' : ''; + pl.statusTxt.setText(status).setColor(status === 'dealer' ? MUTED : GREEN); + const active = !G.isOver(gs) && G.actor(gs) === s && (this.mode === 'human' || this.mode === 'ai' || this.mode === 'layoff' || this.mode === 'knockpick'); + this.setPlateActive(s, active); + this.drawBottle(g, pl, s, Math.min(1, gs.scores[s] / gs.rules.target)); + } + } + + /** A gin bottle lying in the plate's bottom row, filling toward 100 proof. */ + drawBottle(g, pl, seat, f) { + const x0 = pl.tx, x1 = seat === 0 ? pl.rx - 4 : pl.rx - 58; + const y = pl.y + 29; + const neck = 22, h = 13; + const bodyX1 = x1 - neck; + g.fillStyle(0x0a1410, 0.6); + g.fillRoundedRect(x0, y - h / 2, bodyX1 - x0, h, 5); + g.fillRect(bodyX1 - 2, y - 3.5, neck - 4, 7); + g.fillStyle(0x2a2a2a, 1); + g.fillRect(x1 - 6, y - 4.5, 6, 9); + // the liquid + const fillX = x0 + (x1 - 6 - x0) * f; + if (f > 0) { + g.fillStyle(SEAT_COLORS[seat], 0.85); + g.fillRoundedRect(x0 + 1.5, y - h / 2 + 1.5, Math.max(4, Math.min(fillX, bodyX1) - x0 - 3), h - 3, 4); + if (fillX > bodyX1) g.fillRect(bodyX1 - 2, y - 2.5, fillX - bodyX1 + 2, 5); + } + g.lineStyle(1.5, 0xd9cfb8, 0.75); + g.strokeRoundedRect(x0, y - h / 2, bodyX1 - x0, h, 5); + g.strokeRect(bodyX1 - 2, y - 3.5, neck - 4, 7); + // a little label at the middle + g.fillStyle(0xf2e8cf, 0.5); + g.fillRect(x0 + (bodyX1 - x0) * 0.42, y - h / 2 + 2, 16, h - 4); + } + + // ── Dock ─────────────────────────────────────────────────────────────────── + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const seen = { label: 'Cards seen (M)', act: () => this.openMemory() }; + if (this.mode === 'deal') { this.setDock('Shuffling and dealing…'); return; } + if (this.mode === 'showdown') { + const sd = gs.showdown; + if (sd && gs.phase === 'layoff') this.setDock(`${this.nameForSeat(sd.layoffSeat)} is laying off on ${sd.knocker === 0 ? 'your' : `${this.shortName(sd.knocker)}'s`} melds…`); + else this.setDock(sd ? `${sd.knocker === 0 ? 'You' : this.nameForSeat(sd.knocker)} ${sd.kind === 'knock' ? 'knocked' : 'went gin'} — laying the hands down…` : '…'); + return; + } + if (this.mode === 'summary') { this.setDock('Hand over — counting it up.'); return; } + if (this.mode === 'layoff') { + const sd = gs.showdown; + const n = sd.laid[0]?.length ?? 0; + this.setDock(`Lay off cards that extend ${this.shortName(sd.knocker)}'s melds: click a glowing card, or drag it onto a meld. Then Done.`, [ + { label: 'Done (Enter)', act: () => this.finishLayoff(), hot: true }, + { label: 'Lay off best (A)', act: () => this.layoffBest() }, + { label: 'Undo (U)', act: () => this.undoLayoff(), enabled: n > 0 }, + seen, + ]); + return; + } + if (this.mode === 'knockpick') { + const c = this.selectedId && this.knockable?.has(this.selectedId) ? gs.hands[0].find(x => x.id === this.selectedId) : null; + this.setDock('Pick the card to discard as you knock (gold cards keep you at or under the limit).', [ + { label: c ? `Knock: ${cardName(c)}` : 'Knock', act: () => c && this.doKnock(c.id), enabled: !!c, hot: !!c }, + { label: 'Cancel', act: () => { this.mode = 'human'; this.layout(); this.updateDock(); } }, + ]); + return; + } + if (this.mode === 'human' && gs.current === 0) { + const top = G.topDiscard(gs); + if (gs.phase === 'upcard') { + this.setDock(`First turn: take the upcard ${cardName(top)}, or pass${gs.upcardPassed.length ? ` (${this.shortName(gs.upcardPassed[gs.upcardPassed.length - 1])} passed)` : ''}.`, [ + { label: `Take ${cardName(top)} (T)`, act: () => this.humanTake(), hot: this.settings.hints && this.coach()?.source === 'discard' }, + { label: 'Pass (P)', act: () => this.humanPass(), hot: this.settings.hints && this.coach()?.source === 'stock' }, + { label: 'Hint (H)', act: () => this.flashHint() }, + seen, + ]); return; } - if (this.dragState) this.endCardDrag(); - }); + if (gs.phase === 'draw') { + this.setDock(gs.stockOnly ? 'Everyone passed the upcard — draw from the stock.' : `Your turn: draw from the stock or take the ${cardName(top)}.`, [ + { label: 'Draw stock (D)', act: () => this.humanDrawStock() }, + { label: top ? `Take ${cardName(top)} (T)` : 'Take', act: () => this.humanTake(), enabled: !!top && !gs.stockOnly }, + { label: 'Hint (H)', act: () => this.flashHint() }, + seen, + ]); + return; + } + if (gs.phase === 'discard') { + const ch = this.choices(); + const gin = ch.some(o => o.gin) || G.canBigGin(gs, 0); + const knock = ch.some(o => o.canKnock && !o.gin); + const sel = this.selectedId ? gs.hands[0].find(c => c.id === this.selectedId) : null; + const banned = gs.takenFrom ? ` You can't throw back the ${cardName(G_card(gs.takenFrom))}.` : ''; + const prompt = gin ? 'You have GIN!' : knock ? 'You can knock — or keep playing for a lower hand.' : `Pick a card to discard.${banned}`; + this.setDock(prompt, [ + { label: sel ? `Discard ${cardName(sel)}` : 'Discard (Enter)', act: () => this.discardSelected(), enabled: !!sel && sel.id !== gs.takenFrom, hot: !!sel && !gin }, + gin ? { label: G.canBigGin(gs, 0) ? 'BIG GIN! (G)' : 'GIN! (G)', act: () => this.doGin(), hot: true } + : { label: 'Knock (K)', act: () => this.startKnock(), enabled: knock, hot: knock }, + { label: 'Hint (H)', act: () => this.flashHint() }, + seen, + ]); + return; + } + } + if (this.mode === 'ai') { + const s = gs.current; + const verb = gs.phase === 'upcard' ? 'is deciding on the upcard' : gs.phase === 'draw' ? 'is drawing' : 'is thinking'; + this.setDock(`${this.nameForSeat(s)} ${verb}…`, [seen]); + return; + } + this.setDock(''); } - onHandPointerDown(card, pointer) { - // Drag-to-arrange works in both the draw and discard phases (Phase 10 pattern); - // dropping onto the discard pile only takes effect in the discard phase. - if (this.humanMode !== 'discard' && this.humanMode !== 'draw') return; - if (this.dragState) return; - if (!card) return; - // Resolve the card's index NOW, from the container. The container is stable - // across reorders, but an index captured when the handlers were bound would go - // stale after the hand is rearranged (the "wrong card on second drag" bug). - const handIdx = this.humanCards.indexOf(card); - if (handIdx === -1) return; - this.potentialDrag = { - card, handIdx, startX: pointer.x, startY: pointer.y, - offsetX: pointer.x - card.x, offsetY: pointer.y - card.y, - }; + // ── Human actions ────────────────────────────────────────────────────────── + notYet() { + if (this.mode === 'ai') this.floatText({ x: CX, y: 760 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); } - _humanHandX(n, i) { - return CX + (i - (n - 1) / 2) * HAND_SPREAD; + humanTake() { + if (!this.canAct()) { this.notYet(); return; } + const gs = this.gs; + let next = gs; + if (gs.phase === 'upcard') next = G.takeUpcard(gs, 0); + else if (gs.phase === 'draw') { + if (gs.stockOnly) { this.floatText({ x: CX, y: 760 }, 'Everyone passed the upcard — draw from the stock', AMBER, { size: 20 }); return; } + next = G.drawDiscard(gs, 0); + } + if (next === gs) return; + playSound(this, SFX.CARD_DEAL); + this.selectedId = null; + this.commit(next); } - startCardDrag(handIdx, offsetX, offsetY) { - const card = this.humanCards[handIdx]; - if (!card) return; - const n = this.logic.players[0].hand.length; - const insertIdx = Phaser.Math.Clamp( - Math.round((card.x - (CX - (n - 1) / 2 * HAND_SPREAD)) / HAND_SPREAD), 0, n - 1, - ); - - const shadow = this.add.graphics(); - shadow.fillStyle(0x000000, 0.35); - shadow.fillEllipse(0, 0, CARD_W * 1.1, 26); - shadow.setPosition(card.x + 5, card.y + 14).setDepth(D.card + 9); - - const slotIndicator = this.add.graphics(); - slotIndicator.lineStyle(3, 0x22cc66, 0.8); - slotIndicator.strokeRoundedRect(-CARD_W / 2 - 4, -CARD_H / 2 - 4, CARD_W + 8, CARD_H + 8, 10); - slotIndicator.fillStyle(0x22cc66, 0.1); - slotIndicator.fillRoundedRect(-CARD_W / 2 - 4, -CARD_H / 2 - 4, CARD_W + 8, CARD_H + 8, 10); - slotIndicator.setPosition(this._humanHandX(n, insertIdx), PLAYER_HAND_Y).setDepth(D.card - 1); - - this.dragState = { cardIdx: handIdx, offsetX, offsetY, prevX: card.x, shadow, slotIndicator, insertIdx, dropTarget: null }; - card.setDepth(D.card + 10); - this.tweens.add({ targets: card, scaleX: 1.08, scaleY: 1.08, duration: 120, ease: 'Cubic.easeOut' }); + humanPass() { + if (!this.canAct() || this.gs.phase !== 'upcard') return; + const next = G.passUpcard(this.gs, 0); + if (next === this.gs) return; + playSoundEx(this, SFX.UI_PICK, { volume: 0.4 }); + this.mode = 'idle'; + this.commit(next); + this.time.delayedCall(260, () => this.advance()); } - updateCardDrag(pointer) { - const ds = this.dragState; - const card = this.humanCards[ds.cardIdx]; - const n = this.logic.players[0].hand.length; + humanDrawStock() { + if (!this.canAct()) { this.notYet(); return; } + const gs = this.gs; + if (gs.phase === 'upcard') { this.floatText({ x: CX, y: 760 }, 'First turn: take the upcard or pass', AMBER, { size: 20 }); return; } + const next = G.drawStock(gs, 0); + if (next === gs) return; + playSound(this, SFX.CARD_DEAL); + this.selectedId = null; + this.commit(next); + } - card.x = pointer.x - ds.offsetX; - card.y = pointer.y - ds.offsetY; - ds.shadow.setPosition(card.x + 5, card.y + 14); - - const tiltRad = Phaser.Math.Clamp((pointer.x - ds.prevX) * 0.008, -0.17, 0.17); - card.setRotation(tiltRad); - ds.prevX = pointer.x; - - const newDrop = this._getDropTarget(card.x, card.y); - if (newDrop !== ds.dropTarget) { - ds.dropTarget = newDrop; - if (newDrop) { - this.tweens.killTweensOf(ds.slotIndicator); - ds.slotIndicator.setAlpha(0); - this._settleNonDraggedCards(); + selectCard(id) { + if (this.mode === 'knockpick') { + if (this.knockable?.has(id)) { + if (this.selectedId === id) { this.doKnock(id); return; } + this.selectedId = id; + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + this.updateDock(); } else { - ds.slotIndicator.setAlpha(1); - this._updateNonDraggedCards(); + this.nudge(id); + this.floatText({ x: CX, y: 760 }, `Discarding that leaves more than ${this.gs.knockLimit}`, RED, { size: 20 }); } + return; } - - if (!newDrop) { - const newInsert = Phaser.Math.Clamp( - Math.round((card.x - (CX - (n - 1) / 2 * HAND_SPREAD)) / HAND_SPREAD), 0, n - 1, - ); - if (newInsert !== ds.insertIdx) { - ds.insertIdx = newInsert; - this.tweens.killTweensOf(ds.slotIndicator); - this.tweens.add({ targets: ds.slotIndicator, x: this._humanHandX(n, newInsert), duration: 100, ease: 'Cubic.easeOut' }); - this._updateNonDraggedCards(); - } + if (this.mode === 'layoff') { this.layoffCard(id); return; } + if (!this.canAct()) { this.notYet(); return; } + const gs = this.gs; + if (gs.phase !== 'discard') { + this.floatText({ x: CX, y: 760 }, gs.phase === 'upcard' ? 'First, take the upcard or pass' : 'Draw a card first — the stock or the discard pile', AMBER, { size: 20 }); + return; } + if (id === gs.takenFrom) { + this.nudge(id); + this.floatText({ x: CX, y: 760 }, 'You just took that card — you can\'t throw it back this turn', RED, { size: 20 }); + return; + } + if (this.selectedId === id) { this.discardSelected(); return; } + this.selectedId = id; + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + this.updateDock(); } - _getDropTarget(x, y) { - if (this.humanMode !== 'discard') return null; - const { discard } = this._pilePos; - if (Math.abs(x - discard.x) < 80 && Math.abs(y - discard.y) < 100) return 'discard'; + discardSelected() { + const id = this.selectedId; + if (!id || !this.canAct() || this.gs.phase !== 'discard') return false; + return this.humanDiscard(id); + } + + humanDiscard(id) { + const gs = this.gs; + const next = G.discard(gs, 0, id); + if (next === gs) { this.nudge(id); return false; } + // throwing away a gin or a knock? say so once — it's legal, just worth knowing + playSound(this, SFX.CARD_PLACE); + this.selectedId = null; + this.mode = 'idle'; + this.commit(next); + this.time.delayedCall(320, () => this.advance()); + return true; + } + + startKnock() { + if (!this.canAct() || this.gs.phase !== 'discard') return; + const ch = this.choices().filter(o => o.canKnock); + if (!ch.length) { this.floatText({ x: CX, y: 760 }, `You need ${this.gs.knockLimit} or less deadwood after your discard to knock`, RED, { size: 20 }); return; } + if (this.selectedId && ch.some(o => o.card.id === this.selectedId)) { this.doKnock(this.selectedId); return; } + const best = ch.sort((a, b) => a.deadwood - b.deadwood || b.card.pts - a.card.pts)[0]; + this.mode = 'knockpick'; + this.selectedId = best.card.id; + this.layout({ duration: 160 }); + this.updateDock(); + } + + doKnock(id) { + const gs = this.gs; + const next = G.knock(gs, 0, id); + if (next === gs) { this.nudge(id); return; } + playSound(this, SFX.CARD_PLACE); + this.selectedId = null; + this.mode = 'showdown'; + this.commit(next); + this.onShowdown(); + } + + doGin() { + if (!this.canAct() || this.gs.phase !== 'discard') return; + const gs = this.gs; + let next = gs; + if (G.canBigGin(gs, 0)) next = G.bigGin(gs, 0); + else { + const o = this.choices().filter(x => x.gin).sort((a, b) => b.card.pts - a.card.pts)[0]; + if (o) next = G.knock(gs, 0, o.card.id); + } + if (next === gs) return; + this.selectedId = null; + this.mode = 'showdown'; + this.commit(next); + this.onShowdown(); + } + + flashHint() { + if (!this.gs) return; + if (this.mode === 'layoff') { + const plan = coachLayoffs(this.gs, 0); + if (!plan.length) { this.floatText({ x: CX, y: 760 }, 'Nothing to lay off that helps — click Done', '#7cf0a0', { size: 22, ms: 2000, rise: 16 }); return; } + this.floatText({ x: CX, y: 760 }, `Lay off: ${plan.map(l => cardName(G_card(l.id))).join(' ')}`, '#7cf0a0', { size: 22, ms: 2200, rise: 16 }); + for (const l of plan) this.flashGlow(l.id, 0x7cf0a0, { delay: 0, hold: 900 }); + return; + } + if (!this.isMyTurn()) return; + const tip = this.coach(); + if (!tip) return; + this.floatText({ x: CX, y: 760 }, tip.reason, '#7cf0a0', { size: 22, ms: 2800, rise: 16 }); + if (tip.id) this.flashGlow(tip.id, 0x7cf0a0, { delay: 0, hold: 1100 }); + } + + // ── Input ────────────────────────────────────────────────────────────────── + setupInput() { + this.input.on('pointerdown', (p, over) => this.onPointerDown(p, over)); + this.input.on('pointermove', (p) => this.onPointerMove(p)); + this.input.on('pointerup', (p) => this.onPointerUp(p)); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + } + + handIdAt(pt) { + if (!this.gs || (this.gs.showdown && this.gs.showdown.knocker === 0)) return null; + const poses = this.humanPoses(); + for (let i = poses.length - 1; i >= 0; i--) if (inPose(pt, poses[i].pose)) return poses[i].id; return null; } - _updateNonDraggedCards() { - const ds = this.dragState; - const n = this.humanCards.length; - for (let j = 0; j < n; j++) { - if (j === ds.cardIdx) continue; - const k = j < ds.cardIdx ? j : j - 1; - const finalPos = k < ds.insertIdx ? k : k + 1; - const targetX = this._humanHandX(n, finalPos); - const distFromGap = Math.abs(finalPos - ds.insertIdx); - const leanDir = finalPos < ds.insertIdx ? -1 : 1; - const targetRot = leanDir * Math.max(0, 2 - distFromGap) * 0.04; - const targetScale = distFromGap <= 1 ? 0.95 : 1.0; - this.tweens.killTweensOf(this.humanCards[j]); - this.tweens.add({ targets: this.humanCards[j], x: targetX, rotation: targetRot, scaleX: targetScale, scaleY: targetScale, duration: 100, ease: 'Cubic.easeOut' }); + busyMode() { return ['deal', 'showdown', 'summary'].includes(this.mode); } + + onPointerDown(pointer, over) { + if (this.modal || this.paused || !this.gs || this.dragState || this.overUI(over) || this.busyMode()) return; + const id = this.handIdAt(pointer); + if (id != null) { this.potentialDrag = { id, x: pointer.x, y: pointer.y }; return; } + if (this.gs.showdown) return; + if (inPose(pointer, this.deckTop(), 10)) { this.isMyTurn() ? this.humanDrawStock() : this.notYet(); return; } + if (inPose(pointer, this.L.discard, 10)) { + if (!this.isMyTurn()) { this.notYet(); return; } + if (this.gs.phase === 'discard') { if (this.selectedId) this.discardSelected(); else this.floatText({ x: CX, y: 760 }, 'Pick a card from your hand first (or drag one here)', AMBER, { size: 20 }); } + else this.humanTake(); } } - _settleNonDraggedCards() { + onPointerMove(pointer) { + if (this.dragState) { this.updateDrag(pointer); return; } + if (this.potentialDrag && pointer.isDown) { + const dx = pointer.x - this.potentialDrag.x, dy = pointer.y - this.potentialDrag.y; + if (dx * dx + dy * dy > 64) this.startDrag(pointer); + return; + } + if (pointer.isDown || this.modal || !this.gs || this.busyMode()) return; + const id = this.handIdAt(pointer); + if (id !== this.hoverId) { + this.hoverId = id; + this.layout({ duration: 120 }); + } + let cursor = id != null ? 'pointer' : 'default'; + if (id == null && this.isMyTurn() && this.gs.phase !== 'discard' && (inPose(pointer, this.deckTop(), 10) || inPose(pointer, this.L.discard, 10))) cursor = 'pointer'; + if (id == null && this.isMyTurn() && this.gs.phase === 'discard' && this.selectedId && inPose(pointer, this.L.discard, 10)) cursor = 'pointer'; + this.input.setDefaultCursor(cursor); + } + + onPointerUp(pointer) { + if (this.dragState) { this.endDrag(pointer); return; } + const pd = this.potentialDrag; + if (!pd) return; + this.potentialDrag = null; + this.selectCard(pd.id); + } + + startDrag(pointer) { + const pd = this.potentialDrag; + this.potentialDrag = null; + const c = this.sprites.get(pd.id); + if (!c) return; + c._tw?.stop(); + c._tw = null; + c.setDepth(D.drag); + this.dragState = { id: pd.id, offX: c.pose.x - pd.x, offY: c.pose.y - pd.y, sprite: c, target: null, previewKey: '' }; + this.hoverId = null; + this.input.setDefaultCursor('grabbing'); + this.updateDrag(pointer); + } + + dropTargetAt(pt) { + const gs = this.gs; + if (this.mode === 'layoff' && gs.showdown) { + const kr = this.rowsInfo?.find(r => r.knocker); + if (kr) { + for (let mi = 0; mi < gs.showdown.melds.length; mi++) { + const r = blockRect(kr.row, mi); + if (inRect(pt, { x0: r.x0 - 30, x1: r.x1 + 30, y0: r.y0 - 40, y1: r.y1 + 40 })) return { type: 'meld', meldIdx: mi }; + } + } + } + if (!gs.showdown && inPose(pt, this.L.discard, 50) && (this.isMyTurn() && gs.phase === 'discard')) return { type: 'discard' }; + const n = gs.hands[0].length; + if (inRect(pt, fanZone(this.L.seats[0].fan, n, 40))) { + const poses = this.humanPoses().filter(p => p.id !== this.dragState?.id); + let at = poses.filter(p => p.pose.x < pt.x).length; + // map "position among the others" back to an insertion index in the full order + const ids = gs.hands[0].map(c => c.id); + const from = ids.indexOf(this.dragState?.id); + if (from >= 0 && at >= from) at += 1; + return { type: 'hand', at }; + } + return null; + } + + updateDrag(pointer) { const ds = this.dragState; - const n = this.humanCards.length; - let k = 0; - for (let j = 0; j < n; j++) { - if (j === ds.cardIdx) continue; - this.tweens.killTweensOf(this.humanCards[j]); - this.tweens.add({ targets: this.humanCards[j], x: this._humanHandX(n, k), y: PLAYER_HAND_Y, rotation: 0, scaleX: 1, scaleY: 1, duration: 100, ease: 'Cubic.easeOut' }); - k++; + const x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const t = Math.max(0, Math.min(1, (y - 560) / 380)); + const s = 0.7 + 0.3 * t; + this.applyPose(ds.sprite, { x, y, rot: 0, s, q: SQ + (1 - SQ) * t }, 1); + const prevT = ds.target; + ds.target = this.dropTargetAt(pointer); + const order = ds.target?.type === 'hand' ? CardTableScene.reorderPreview(this.gs.hands[0].map(c => c.id), ds.id, ds.target.at) : null; + const key = order ? order.join(',') : ''; + if (key !== ds.previewKey) { + ds.previewKey = key; + this.dragPreview = order; + this.layout({ duration: 150 }); + } else if (JSON.stringify(prevT) !== JSON.stringify(ds.target)) this.drawRows(); + if (order) { + const idx = order.indexOf(ds.id); + this.drawDropSlot(handPose(this.L, 0, idx, order.length), D.hand + idx * 0.01 - 0.004); + } else this.drawDropSlot(null); + // discard target glow + if (ds.target?.type === 'discard' || (this.isMyTurn() && this.gs.phase === 'discard' && !this.gs.showdown)) { + const g = this.pileG; + g.clear(); + const d = this.L.discard; + const hot = ds.target?.type === 'discard'; + const legal = ds.id !== this.gs.takenFrom; + const hw = (CARD_W / 2) * d.s + 16, hh = (CARD_H / 2) * d.s * SQ + 16; + const col = legal ? 0x7cf0a0 : 0xff7a6a; + g.fillStyle(col, hot ? 0.22 : 0.08); + g.fillRoundedRect(d.x - hw, d.y - hh, hw * 2, hh * 2, 14); + g.lineStyle(hot ? 4 : 2.5, col, hot ? 1 : 0.7); + g.strokeRoundedRect(d.x - hw, d.y - hh, hw * 2, hh * 2, 14); } } - endCardDrag() { - const ds = this.dragState; - const card = this.humanCards[ds.cardIdx]; + cancelDrag() { + if (!this.dragState) return; this.dragState = null; + this.dragPreview = null; + this.drawDropSlot(null); + this.targetG?.clear(); + this.input.setDefaultCursor('default'); + this.layout(); + } - ds.shadow.destroy(); - ds.slotIndicator.destroy(); + endDrag(pointer) { + const ds = this.dragState; + this.dragState = null; + this.input.setDefaultCursor('default'); + this.drawDropSlot(null); + this.targetG.clear(); + const t = ds.target ?? this.dropTargetAt(pointer); + this.dragPreview = null; + if (t?.type === 'hand') { + const hand = this.gs.hands[0]; + const order = CardTableScene.reorderPreview(hand.map(c => c.id), ds.id, t.at); + const byId = new Map(hand.map(c => [c.id, c])); + const changed = order.join(',') !== hand.map(c => c.id).join(','); + hand.splice(0, hand.length, ...order.map(id => byId.get(id))); + if (changed && this.settings.sort !== 'manual') { + this.settings.sort = 'manual'; + this.saveSettings(); + this.refreshSortButtons(); + } + this.cache.key = ''; + this.layout(); + return; + } + if (t?.type === 'discard') { + if (this.mode === 'knockpick') { if (this.knockable?.has(ds.id)) { this.doKnock(ds.id); return; } } + else if (ds.id === this.gs.takenFrom) this.floatText({ x: CX, y: 760 }, 'You just took that card — you can\'t throw it back this turn', RED, { size: 20 }); + else if (this.canAct() && this.humanDiscard(ds.id)) return; + } + if (t?.type === 'meld' && this.layoffCard(ds.id, canLayoff(this.gs.hands[0].find(c => c.id === ds.id), this.gs.showdown.melds[t.meldIdx]) ? t.meldIdx : -1)) return; + this.layout(); + } - if (ds.dropTarget === 'discard') { - // Discard this card - const n = this.humanCards.length; - this._settleNonDraggedCardsExcept(ds.cardIdx); - const { discard } = this._pilePos; - this.tweens.killTweensOf(card); - this.tweens.add({ - targets: card, x: discard.x, y: discard.y, rotation: 0, scaleX: 1, scaleY: 1, - duration: 180, ease: 'Cubic.easeOut', - onComplete: () => { card.destroy(); this.commitDiscard(ds.cardIdx); }, + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (this.mode === 'knockpick') { this.mode = 'human'; this.layout(); this.updateDock(); } + else if (!this.modal) this.openPause(); + return; + } + if (this.modal) { if (e.code === 'Enter') this.modal.onEnter?.(); return; } + if (this.dragState) return; + const k = e.key?.toLowerCase(); + if (k === 's') { this.cycleSort(); return; } + if (k === 'h') { this.flashHint(); return; } + if (k === 'm') { this.openMemory(); return; } + if (this.mode === 'layoff') { + if (e.code === 'Enter') this.finishLayoff(); + else if (k === 'a') this.layoffBest(); + else if (k === 'u') this.undoLayoff(); + return; + } + if (this.mode === 'knockpick') { + if (e.code === 'Enter' && this.selectedId) this.doKnock(this.selectedId); + return; + } + if (!this.canAct()) return; + const ph = this.gs.phase; + if (k === 't') this.humanTake(); + else if (k === 'p' && ph === 'upcard') this.humanPass(); + else if (k === 'd') this.humanDrawStock(); + else if (k === 'k' && ph === 'discard') this.startKnock(); + else if (k === 'g' && ph === 'discard') this.doGin(); + else if (e.code === 'Enter' && ph === 'discard') this.discardSelected(); + } + + cycleSort() { + const order = ['melds', 'suit', 'rank']; + const i = order.indexOf(this.settings.sort); + this.settings.sort = order[(i + 1) % order.length]; + this.saveSettings(); + this.refreshSortButtons(); + this.sortHand(); + this.layout(); + } + + // ── Panels ───────────────────────────────────────────────────────────────── + /** Every card, marked: in your hand · in the pile · picked up by someone · unseen. */ + openMemory() { + const gs = this.gs; + if (!gs || this.modal) return; + const mine = new Set(gs.hands[0].map(c => c.id)); + const pile = new Set(gs.discard.map(c => c.id)); + const heldBy = new Map(); + for (let s = 1; s < gs.n; s++) for (const id of gs.pickups[s]) if (gs.hands[s].some(c => c.id === id)) heldBy.set(id, s); + const h = 560; + this.openModal({ w: 940, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 44, 'Cards seen this hand', { fontFamily: 'Righteous', fontSize: '30px', color: COLORS.goldHex }); + this.modalText(CX, top + 78, 'gold = your hand · struck = in the discard pile · coloured = an opponent picked it up · bright = unseen', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex }); + SUITS.forEach((suit, r) => { + const y = top + 130 + r * 58; + this.addToModal(this.add.text(CX - 410, y, SUIT_SYM[suit], { + fontFamily: 'sans-serif', fontSize: '34px', color: suit === 'h' || suit === 'd' ? '#ff6a6a' : INK, + }).setOrigin(0.5).setDepth(D.modal + 1)); + RANKS.forEach((rank, i) => { + const id = `${rank}${suit}`; + const x = CX - 350 + i * 58; + const held = mine.has(id), gone = pile.has(id), opp = heldBy.get(id); + const color = held ? '#ffd35a' : opp != null ? SEAT_HEX[opp] : gone ? '#6a6050' : INK; + this.addToModal(this.add.text(x, y, rank === 'T' ? '10' : rank, { fontFamily: 'Righteous', fontSize: '24px', color }) + .setOrigin(0.5).setDepth(D.modal + 1).setAlpha(gone ? 0.65 : 1)); + if (gone) { + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 2)); + g.lineStyle(2, 0x8a7e66, 0.8); + g.lineBetween(x - 16, y + 2, x + 16, y - 2); + } + if (opp != null) { + const g = this.addToModal(this.add.graphics().setDepth(D.modal + 1)); + g.lineStyle(2, SEAT_COLORS[opp], 0.9); + g.strokeCircle(x, y, 19); + } }); - return; - } - - // Reorder - const n = this.logic.players[0].hand.length; - const finalIdx = Phaser.Math.Clamp( - Math.round((card.x - (CX - (n - 1) / 2 * HAND_SPREAD)) / HAND_SPREAD), 0, n - 1, - ); - this.tweens.killTweensOf(card); - this.tweens.add({ targets: card, x: this._humanHandX(n, finalIdx), y: PLAYER_HAND_Y, rotation: 0, scaleX: 1, scaleY: 1, duration: 220, ease: 'Back.easeOut' }); - - for (let j = 0; j < n; j++) { - if (j === ds.cardIdx) continue; - const k = j < ds.cardIdx ? j : j - 1; - const finalPos = k < finalIdx ? k : k + 1; - this.tweens.killTweensOf(this.humanCards[j]); - this.tweens.add({ targets: this.humanCards[j], x: this._humanHandX(n, finalPos), rotation: 0, scaleX: 1, scaleY: 1, duration: 120, ease: 'Cubic.easeOut' }); - } - - const hand = this.logic.players[0].hand; - const [moved] = hand.splice(ds.cardIdx, 1); - hand.splice(finalIdx, 0, moved); - const [movedObj] = this.humanCards.splice(ds.cardIdx, 1); - this.humanCards.splice(finalIdx, 0, movedObj); - - card.setDepth(D.card); - this.time.delayedCall(250, () => { - this.updateActionButtons(); - this._applyMeldGlows(); }); - } - - _settleNonDraggedCardsExcept(exceptIdx) { - const n = this.humanCards.length; - let k = 0; - for (let j = 0; j < n; j++) { - if (j === exceptIdx) continue; - this.tweens.killTweensOf(this.humanCards[j]); - this.tweens.add({ targets: this.humanCards[j], x: this._humanHandX(n - 1, k), y: PLAYER_HAND_Y, rotation: 0, scaleX: 1, scaleY: 1, duration: 120, ease: 'Cubic.easeOut' }); - k++; + const lines = []; + for (let s = 1; s < gs.n; s++) { + const took = gs.pickups[s].map(id => cardName(G_card(id))); + const threw = gs.discards[s].map(id => cardName(G_card(id))); + lines.push(`${this.shortName(s, 12)} — took: ${took.length ? took.join(' ') : 'nothing'} · threw: ${threw.length ? threw.slice(-8).join(' ') : 'nothing'}`); } + lines.forEach((l, i) => this.modalText(CX, top + 380 + i * 28, l, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: SEAT_HEX[i + 1] })); + this.modalText(CX, top + h - 92, 'What an opponent picks up tells you what they\'re collecting — don\'t feed them those ranks or suits.', { fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex }); + this.modalButton(CX, top + h - 44, 'Back to the table', () => this.closeModal(), { width: 260, height: 44, fontSize: 18 }); } - // ── Card rendering ───────────────────────────────────────────────────────── + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); this.openSettings(); } }, + { label: 'Score sheet', act: () => { this.closeModal(); this.openScorePad({ readOnly: true }); } }, + { label: 'How to play', act: () => { this.closeModal(); this.openRules(); } }, + { label: 'New game', ghost: true, act: () => this.confirm('Start a new game?', 'This match will be thrown out.', 'New game', () => { this.clearSave(); this.restart(); }) }, + { label: 'Leave table', ghost: true, act: () => this.onLeave() }, + ]); + } - drawFace(container, card, faceUp) { - const x = -CARD_W / 2, y = -CARD_H / 2; - const g = this.add.graphics(); - if (!faceUp) { - g.fillStyle(THEME.cardBack, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2.5, THEME.cardBackHi, 0.6); g.strokeRoundedRect(x + 5, y + 5, CARD_W - 10, CARD_H - 10, CARD_R - 2); - g.lineStyle(1, THEME.cardBackHi, 0.25); g.strokeRoundedRect(x + 9, y + 9, CARD_W - 18, CARD_H - 18, CARD_R - 3); - container.add(g); - container.add(this.add.text(0, 0, '♦', { fontFamily: 'serif', fontSize: '32px', color: '#7050a0' }).setOrigin(0.5).setAlpha(0.4)); - return; + openSettings(onDone = null) { + const s = this.settings; + const R = s.rules; + this.openSettingsModal([ + { label: 'Opponent pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } }, + { label: 'Hints (meld colours · ★ coach · pile glow)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; this.layout(); this.updateDock(); } }, + { label: 'Play to', options: [[100, '100'], [150, '150'], [250, '250']], get: () => R.target, set: (v) => { R.target = v; } }, + { label: 'Undercut bonus', options: [[25, '25'], [10, '10']], get: () => R.undercutBonus, set: (v) => { R.undercutBonus = v; } }, + { label: 'Big Gin (11 melded, +31)', options: [[true, 'On'], [false, 'Off']], get: () => R.bigGin, set: (v) => { R.bigGin = v; } }, + { label: 'First-turn upcard offer', options: [[true, 'On'], [false, 'Off']], get: () => R.upcard, set: (v) => { R.upcard = v; } }, + { label: 'Oklahoma (upcard sets the knock limit)', options: [[false, 'Off'], [true, 'On']], get: () => R.oklahoma, set: (v) => { R.oklahoma = v; } }, + { label: 'Game, box & shutout bonuses', options: [[true, 'On'], [false, 'Off']], get: () => R.bonuses, set: (v) => { R.bonuses = v; } }, + ], { note: 'Rule changes start with the next game (Menu → New game).', onDone }); + } + + openRules() { + const h = 760; + this.openModal({ w: 1000, h, onEscape: () => this.closeModal() }); + const top = CY - h / 2; + this.modalText(CX, top + 50, 'How to play Gin Rummy', { fontFamily: 'Righteous', fontSize: '36px', color: COLORS.goldHex }); + const r = this.gs?.rules ?? { ...DEFAULT_RULES, ...this.settings.rules }; + const lines = [ + ['Goal', `Be first to ${r.target} points ("proof").`], + ['Melds', 'Sets: 3–4 of a rank. Runs: 3+ in a row of one suit (ace is low: A-2-3, never Q-K-A).'], + ['Deadwood', 'Cards not in melds. Aces 1, number cards face value, J Q K 10.'], + ['Your turn', 'Draw (the stock, or the top discard), then discard one. Not the card you just took.'], + ['Knock', `Discard and knock when your deadwood is ${r.oklahoma ? 'at or under the upcard\'s value' : '10 or less'}. Everyone lays down.`], + ['Lay off', 'Opponents add their loose cards to the knocker\'s melds to cut their deadwood.'], + ['Score', 'Knocker scores the difference in deadwood.'], + ['Undercut', `If a defender's deadwood is equal or lower, the DEFENDER scores the difference + ${r.undercutBonus}.`], + ['Gin', `Knock with 0 deadwood: no lay-offs, +${r.ginBonus ?? 25}.${r.bigGin ? ' Big Gin (all 11 melded): +31.' : ''}`], + ['Void hand', 'If a discard leaves 2 cards in the stock and nobody knocked, nobody scores.'], + ['Upcard', r.upcard ? 'First turn: the upcard is offered to the first player, then the others; if all pass, draw the stock.' : 'Off — the first player just draws.'], + ['Bonuses', r.bonuses ? 'At the end: winner +100, +25 per hand won, doubled if nobody else scored.' : 'Off — the points are the score.'], + ]; + lines.forEach(([k, v], i) => { + const y = top + 118 + i * 46; + this.addToModal(this.add.text(CX - 450, y, k, { fontFamily: 'Righteous', fontSize: '19px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + this.addToModal(this.add.text(CX - 300, y, v, { fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.textHex, wordWrap: { width: 740 } }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + }); + this.modalButton(CX, top + h - 44, 'Back to the table', () => this.closeModal(), { width: 280, height: 46, fontSize: 18 }); + } + + onLeave() { + if (!this.gs || this.gs.phase === 'gameOver') { this.scene.start('GameMenu'); return; } + this.confirm('Leave the table?', 'Your game is saved at the start of each turn — you can resume it next time.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay' }); + } + + restart() { + this.closeModal(); + this.scene.restart({ ...this.initData }); + } + + roundSummary() { + const gs = this.gs; + const r = gs.result; + if (!r) return ''; + if (r.kind === 'wash') return 'Void hand — the stock ran down to 2 with no knock. Same dealer deals again.'; + const k = r.knocker; + const kn = k === 0 ? 'You' : this.shortName(k, 12); + const parts = r.lines.map(l => { + const dn = l.seat === 0 ? 'you' : this.shortName(l.seat, 12); + if (l.why === 'undercut') return `${l.seat === 0 ? 'You' : dn} undercut (${l.deadwood} vs ${r.knockerDW}) +${l.pts}`; + return `${dn} ${l.deadwood} → +${l.pts}`; + }); + const head = r.kind === 'knock' ? `${kn} knocked with ${r.knockerDW}` : r.kind === 'gin' ? `${kn} went gin` : `${kn} went BIG GIN`; + return `${head}: ${parts.join(' · ')}${r.doubled ? ' (doubled)' : ''}`; + } + + openScorePad({ result = null, readOnly = false } = {}) { + if (!this.gs) return; + const gs = this.gs; + const over = gs.phase === 'gameOver' && !readOnly; + const fin = gs.final; + let title; + if (readOnly) title = `Score sheet — first to ${gs.rules.target}`; + else if (over) title = gs.winner === 0 ? 'You win the match!' : `${this.nameForSeat(gs.winner)} wins the match`; + else if (gs.result?.kind === 'wash') title = `Hand ${gs.round}: void`; + else { + const r = gs.result; + const who = r.knocker === 0 ? 'You' : this.shortName(r.knocker, 14); + title = r.undercut ? `Hand ${gs.round}: undercut!` : `Hand ${gs.round}: ${who} ${r.kind === 'knock' ? 'knocked' : r.kind === 'gin' ? 'went gin' : 'went BIG GIN'}`; } - g.fillStyle(THEME.cardFace, 1); g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(1.5, 0xc8a060, 0.4); g.strokeRoundedRect(x + 2, y + 2, CARD_W - 4, CARD_H - 4, CARD_R - 1); - container.add(g); - const col = card.isRed ? SUIT_RED : SUIT_BLK; - container.add(this.add.text(x + 7, y + 4, card.label, { fontFamily: 'Righteous', fontSize: '21px', color: col })); - container.add(this.add.text(x + 8, y + 29, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '19px', color: col })); - container.add(this.add.text(0, 4, card.suitSymbol, { fontFamily: 'sans-serif', fontSize: '40px', color: col }).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 4, card.label, { fontFamily: 'Righteous', fontSize: '21px', color: col }).setOrigin(1, 1)); - } - - makeCard(card, x, y, { faceUp = true, depth = D.card } = {}) { - const c = this.add.container(x, y).setDepth(depth); - c.cardRef = card; - this.drawFace(c, card, faceUp); - return c; - } - - setCardInteractive(container, handler) { - container.setSize(CARD_W, CARD_H); - container.setInteractive({ useHandCursor: true }); - container.on('pointerdown', handler); - } - - // ── Round lifecycle ──────────────────────────────────────────────────────── - - startRound() { - this.busy = false; - this.humanMode = 'idle'; - this.selectedCard = null; - this.layoffSelected = null; - this.knockBtn.setVisible(false); - this.ginBtn.setVisible(false); - this.layoffDoneBtn.setVisible(false); - this.clearReveal(); - - playSound(this, SFX.CARD_SHUFFLE); - this.refreshScores(); - this.renderAll(); - this.advance(); - } - - clearCards() { - for (const c of this.humanCards) c.destroy(); - this.humanCards = []; - for (const arr of this.aiCardObjs) { for (const c of arr) c?.destroy(); } - this.aiCardObjs = Array.from({ length: this.nPlayers }, () => []); - this.clearPileObjs(); - } - - clearPileObjs() { - this.pileObjs.stock?.destroy(); - this.pileObjs.discard?.destroy(); - this.pileObjs.stock = null; - this.pileObjs.discard = null; - } - - clearReveal() { - for (const o of this.revealObjs) o?.destroy(); - this.revealObjs = []; - } - - renderAll() { - this.clearCards(); - this.renderPiles(); - for (let s = 0; s < this.nPlayers; s++) this.renderHand(s); - } - - renderPiles() { - const { stock, discard } = this._pilePos; - if (this.logic.stockCount > 0) { - // Must be a Container (not raw Graphics) so setSize/setInteractive work correctly - this.pileObjs.stock = this.makeCard(null, stock.x, stock.y, { faceUp: false, depth: D.pile }); + const markFor = (h, s) => { + if (h.kind === 'wash') return ''; + if (h.knocker === s) return h.kind === 'gin' ? 'gin' : h.kind === 'biggin' ? 'BIG' : 'knock'; + return h.undercut && h.deltas[s] > 0 ? 'under' : ''; + }; + const leader = Math.max(...gs.scores); + const rows = gs.scores.map((score, s) => ({ + seat: s, color: SEAT_COLORS[s], name: this.shortName(s, 14), + cells: gs.history.map(h => ({ + text: h.kind === 'wash' ? '–' : h.deltas[s] ? `+${h.deltas[s]}` : '·', + color: h.deltas[s] ? '#1e7a3b' : '#8a8270', mark: markFor(h, s), markColor: '#5a3a8a', + })), + extra: over && fin && gs.rules.bonuses ? `+${fin[s].total - score}` : null, + total: over && fin ? fin[s].total : score, + totalColor: score === leader && score > 0 ? '#1e7a3b' : '#22201a', + circled: over && s === gs.winner, + })); + let sub = readOnly ? `Hands: knock / gin marked under the knocker · "under" = an undercut` : this.roundSummary(); + if (over && fin && gs.rules.bonuses) { + const w = fin[gs.winner]; + sub = `${this.roundSummary()} · Final: points + 100 game bonus + 25 per hand won${w.shutout ? ' — SHUTOUT, doubled!' : ''}`; } - this.stockCountText?.setText(`${this.logic.stockCount}`); - - if (this.logic.discardTop) { - const c = this.makeCard(this.logic.discardTop, discard.x, discard.y, { depth: D.pile }); - this.pileObjs.discard = c; - } - } - - renderHand(seat) { - const player = this.logic.players[seat]; - const sp = this._seatPos[seat]; - const faceUp = seat === 0; - const spread = faceUp ? HAND_SPREAD : AI_SPREAD; - const n = player.hand.length; - - if (faceUp) { - this.humanCards = []; - for (let i = 0; i < n; i++) { - const x = this._humanHandX(n, i); - const c = this.makeCard(player.hand[i], x, PLAYER_HAND_Y); - c.baseY = PLAYER_HAND_Y; - this.humanCards.push(c); - } - this._applyMeldGlows(); + const buttons = []; + if (readOnly) buttons.push({ label: 'Back to the table', act: () => this.closeModal() }); + else if (over) { + buttons.push({ label: 'Play again', act: () => this.restart(), hot: true }); + buttons.push({ label: 'Match stats', ghost: true, act: () => this.openStats() }); + buttons.push({ label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }); } else { - this.aiCardObjs[seat] = []; - for (let i = 0; i < n; i++) { - let x = sp.x, y = sp.y; - if (sp.axis === 'h') x = sp.x + (i - (n - 1) / 2) * spread; - else y = sp.y + (i - (n - 1) / 2) * spread; - const c = this.makeCard(null, x, y, { faceUp: false, depth: D.card + i }); - this.aiCardObjs[seat].push(c); - } - // Name + count label - const name = seat === 0 ? 'You' : (this.opponents[seat - 1]?.name?.split(' ')[0] ?? `AI ${seat}`); - const lbl = this.add.text(sp.nameX, sp.nameY, `${name} (${n})`, { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: THEME.mutedHex, - }).setOrigin(...sp.nameAnchor).setDepth(D.ui); - this.aiCardObjs[seat].push(lbl); + buttons.push({ label: 'Next hand', act: () => this.nextRound(), hot: true }); + buttons.push({ label: 'Settings', ghost: true, act: () => { this.closeModal(); this.openSettings(() => this.openScorePad({ result })); } }); + buttons.push({ label: 'Leave', ghost: true, act: () => this.confirm('Leave the table?', 'The next hand is saved — you can resume the match next time.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay', onNo: () => this.openScorePad({}) }) }); } - } - - _applyMeldGlows() { - // Remove old glows - this.humanCards.forEach(c => { - const old = c.getByName?.('glow'); - if (old) { c.remove(old, true); } + this.openScorePadModal({ + title, titleColor: over && gs.winner === 0 ? '#1e7a3b' : '#22201a', sub, + columns: gs.history.map((_, i) => `H${i + 1}`), + rows, extraLabel: over && gs.rules.bonuses ? 'Bonus' : null, + writeLast: !!result, buttons, readOnly, + onEnter: !readOnly ? (over ? () => this.restart() : () => this.nextRound()) : null, }); + // the summary sits over the table — let the laid-down hands show through a little + if (!readOnly && this.modal) this.modal.objs[0].setAlpha(0.35); + } - const hand = this.logic.players[0].hand; - const melds = allCandidateMelds(hand); - const inMeld = new Set(melds.flat().map(c => c.key)); - - this.humanCards.forEach((container, i) => { - const card = hand[i]; - if (!card || !inMeld.has(card.key)) return; - const glow = this.add.graphics(); - glow.lineStyle(3, THEME.meldGlow, 0.7); - glow.strokeRoundedRect(-CARD_W / 2 - 3, -CARD_H / 2 - 3, CARD_W + 6, CARD_H + 6, CARD_R + 2); - glow.setName('glow'); - container.addAt(glow, 0); + openStats() { + const gs = this.gs; + if (!gs) return; + const h = 260 + gs.n * 54; + this.openModal({ w: 1000, h, onEscape: () => this.openScorePad({}) }); + const top = CY - h / 2; + this.modalText(CX, top + 50, 'Match stats', { fontFamily: 'Righteous', fontSize: '34px', color: COLORS.goldHex }); + const cols = ['Hands won', 'Gins', 'Knocks', 'Avg knock', 'Undercuts', 'Best hand']; + cols.forEach((c, i) => this.modalText(CX - 200 + i * 120, top + 110, c, { fontFamily: '"Julius Sans One"', fontSize: '14px', color: COLORS.mutedHex })); + gs.stats.forEach((st, s) => { + const y = top + 160 + s * 54; + this.modalText(CX - 380, y, this.shortName(s, 14), { fontFamily: 'Righteous', fontSize: '20px', color: SEAT_HEX[s] }); + const vals = [st.won, st.gins + st.bigGins, st.knocks, st.knocks ? (st.knockDW / st.knocks).toFixed(1) : '–', st.undercuts, st.best || '–']; + vals.forEach((v, i) => this.modalText(CX - 200 + i * 120, y, String(v), { fontFamily: 'Righteous', fontSize: '22px', color: INK })); }); - } - - // ── Turn flow ────────────────────────────────────────────────────────────── - - advance() { - if (this.busy) return; - const p = this.logic.phase; - if (p === 'gameover') { this.showGameOver(this.logic.winner); return; } - if (p === 'roundover') { this.showRoundScores(); return; } - - const cur = this.logic.currentPlayer; - this.setTurnRing(cur); - if (cur === 0) { - this.beginHumanTurn(); - } else { - this.busy = true; - this.runAiTurn(cur); - } - } - - // ── Human turn ───────────────────────────────────────────────────────────── - - beginHumanTurn() { - if (this.logic.phase === 'draw') { - this.humanMode = 'draw'; - this.setStatus('Drag cards to arrange your hand, then draw from the stock or discard'); - this.knockBtn.setVisible(false); - this.ginBtn.setVisible(false); - - // Hand is interactive so the player can arrange cards before drawing - // (Phase 10 pattern — drag reorders; drop targets are inactive until discard phase) - this._setupHandInteraction(); - - // Make stock clickable - if (this.pileObjs.stock) { - this._setupPileClick(this.pileObjs.stock, () => this.onDrawStock()); - } - - // Make discard pile clickable - if (this.pileObjs.discard) { - this._setupPileClick(this.pileObjs.discard, () => this.onDrawDiscard()); - } - } else if (this.logic.phase === 'discard') { - this.humanMode = 'discard'; - this.setStatus('Select a card to discard, or Knock / Gin'); - this.updateActionButtons(); - this._setupHandInteraction(); - - // Clicking the discard pile discards the currently selected card - if (this.pileObjs.discard) { - this._setupPileClick(this.pileObjs.discard, () => this.onDiscardPileClick()); - } - } - } - - _setupPileClick(pile, handler) { - pile.setSize(CARD_W, CARD_H); - pile.setInteractive({ useHandCursor: true }); - pile.on('pointerdown', handler); - pile.on('pointerover', () => pile.setAlpha(0.8)); - pile.on('pointerout', () => pile.setAlpha(1)); - } - - _setupHandInteraction() { - this.humanCards.forEach((c) => { - c.setSize(CARD_W, CARD_H); - c.setInteractive({ useHandCursor: true }); - // Pass the card container (stable identity), not the captured index — the - // index is resolved at event time so it stays correct after a reorder. - c.on('pointerdown', (pointer) => this.onHandPointerDown(c, pointer)); - c.on('pointerover', () => { if (!this.dragState) c.setAlpha(0.85); }); - c.on('pointerout', () => { c.setAlpha(1); }); - }); - } - - updateActionButtons() { - if (this.humanMode !== 'discard') { - this.knockBtn.setVisible(false); - this.ginBtn.setVisible(false); - return; - } - const hand = this.logic.players[0].hand; - let canKn = false, canGin = false; - for (const c of hand) { - const rest = hand.filter(x => x.key !== c.key); - const { deadwood } = bestMeldGroups(rest); - if (deadwood === 0) { canGin = true; canKn = true; break; } - if (deadwood <= MAX_DEADWOOD_TO_KNOCK) canKn = true; - } - this.knockBtn.setVisible(canKn && !canGin); - this.ginBtn.setVisible(canGin); - } - - onHandClick(handIdx) { - if (this.humanMode === 'draw') { - this.setStatus('Draw a card first, then you can discard'); - return; - } - if (this.humanMode !== 'discard') return; - if (this.selectedCard) { - // Deselect previous - const prev = this.humanCards.find(c => c.cardRef?.key === this.selectedCard); - if (prev) this.tweens.add({ targets: prev, y: PLAYER_HAND_Y, duration: 120 }); - } - const card = this.logic.players[0].hand[handIdx]; - if (this.selectedCard === card.key) { - this.selectedCard = null; - this.setStatus('Select a card to discard, or Knock / Gin'); - } else { - this.selectedCard = card.key; - const obj = this.humanCards[handIdx]; - this.tweens.add({ targets: obj, y: PLAYER_HAND_Y - 24, duration: 120 }); - this.setStatus('Click the discard pile to discard this card'); - } - } - - onDiscardPileClick() { - if (this.humanMode !== 'discard') return; - if (!this.selectedCard) { - this.setStatus('Select a card to discard first, or drag one onto the pile'); - return; - } - const hand = this.logic.players[0].hand; - const handIdx = hand.findIndex(c => c.key === this.selectedCard); - if (handIdx === -1) { - this.selectedCard = null; - return; - } - this.commitDiscard(handIdx); - } - - onDrawStock() { - if (this.humanMode !== 'draw') return; - if (!this.logic.drawStock(0)) return; - playSound(this, SFX.CARD_DEAL); - this.renderAll(); - this.beginHumanTurn(); - } - - onDrawDiscard() { - if (this.humanMode !== 'draw') return; - if (!this.logic.drawDiscard(0)) return; - playSound(this, SFX.CARD_DEAL); - this.renderAll(); - this.beginHumanTurn(); - } - - commitDiscard(handIdx) { - const hand = this.logic.players[0].hand; - const key = hand[handIdx]?.key; - if (!key) return; - if (!this.logic.discardCard(0, key)) return; - playSound(this, SFX.CARD_PLACE); - this.humanMode = 'idle'; - this.selectedCard = null; - this.humanCards.splice(handIdx, 1); - this.renderPiles(); - this.renderHand(0); - this.advance(); - } - - onKnock() { - if (this.humanMode !== 'discard') return; - const hand = this.logic.players[0].hand; - let bestDiscard = null, bestDW = Infinity, bestMelds = []; - for (const c of hand) { - const rest = hand.filter(x => x.key !== c.key); - const { deadwood, melds } = bestMeldGroups(rest); - if (deadwood < bestDW) { bestDW = deadwood; bestDiscard = c; bestMelds = melds; } - } - if (!bestDiscard || bestDW > MAX_DEADWOOD_TO_KNOCK) return; - if (!this.logic.knock(0, bestDiscard.key, bestMelds)) return; - playSound(this, SFX.CARD_PLACE); - this.humanMode = 'idle'; - this.renderAll(); - this.doKnockReveal(false); - } - - onGin() { - if (this.humanMode !== 'discard') return; - const hand = this.logic.players[0].hand; - let bestDiscard = null, bestMelds = []; - for (const c of hand) { - const rest = hand.filter(x => x.key !== c.key); - const { deadwood, melds } = bestMeldGroups(rest); - if (deadwood === 0) { bestDiscard = c; bestMelds = melds; break; } - } - if (!bestDiscard) return; - if (!this.logic.gin(0, bestDiscard.key, bestMelds)) return; - playSound(this, SFX.CARD_SHOW); - this.humanMode = 'idle'; - this.renderAll(); - this.doKnockReveal(true); - } - - // ── AI turn ──────────────────────────────────────────────────────────────── - - async runAiTurn(seat) { - const delay = (ms) => new Promise(r => this.time.delayedCall(ms, r)); - const skill = this.opponents[seat - 1]?.skill ?? 3; - const hand = this.logic.players[seat].hand; - const discardTop = this.logic.discardTop; - - // Draw - const src = chooseDrawSource(hand, discardTop, skill); - await delay(thinkDelay(skill)); - if (src === 'discard' && discardTop) { - this.logic.drawDiscard(seat); - } else { - this.logic.drawStock(seat); - } - playSound(this, SFX.CARD_DEAL); - this.renderHand(seat); - this.renderPiles(); - - await delay(thinkDelay(skill) * 0.6); - - // Decide knock/gin/discard - const handNow = this.logic.players[seat].hand; - const { melds, deadwood } = bestMeldGroups(handNow); - - if (deadwood === 0) { - // Gin — find best discard - let bestDiscard = null, bestMelds2 = []; - for (const c of handNow) { - const rest = handNow.filter(x => x.key !== c.key); - const { deadwood: dw2, melds: m2 } = bestMeldGroups(rest); - if (dw2 === 0) { bestDiscard = c; bestMelds2 = m2; break; } - } - if (bestDiscard && this.logic.gin(seat, bestDiscard.key, bestMelds2)) { - playSound(this, SFX.CARD_SHOW); - this.busy = false; - this.renderAll(); - this.doKnockReveal(true); - return; - } - } - - if (shouldKnock(handNow, skill)) { - let bestDiscard = null, bestDW = Infinity, bestMelds2 = []; - for (const c of handNow) { - const rest = handNow.filter(x => x.key !== c.key); - const { deadwood: dw2, melds: m2 } = bestMeldGroups(rest); - if (dw2 < bestDW) { bestDW = dw2; bestDiscard = c; bestMelds2 = m2; } - } - if (bestDiscard && bestDW <= MAX_DEADWOOD_TO_KNOCK && this.logic.knock(seat, bestDiscard.key, bestMelds2)) { - playSound(this, SFX.CARD_PLACE); - this.busy = false; - this.renderAll(); - this.doKnockReveal(false); - return; - } - } - - // Normal discard - const discardCard = chooseDiscard(handNow, skill); - if (discardCard) { - this.logic.discardCard(seat, discardCard.key); - playSound(this, SFX.CARD_PLACE); - } - this.renderAll(); - this.busy = false; - this.advance(); - } - - // ── Knock / Gin reveal ───────────────────────────────────────────────────── - - async doKnockReveal(isGin) { - const delay = (ms) => new Promise(r => this.time.delayedCall(ms, r)); - this.busy = true; - const k = this.logic.knocker; - const kMelds = this.logic.knockerMelds; - const kName = k === 0 ? 'You' : (this.opponents[k - 1]?.name?.split(' ')[0] ?? `AI ${k}`); - const verb = isGin ? 'Gin!' : 'Knock!'; - - this.setStatus(`${kName} called ${verb}`); - playSound(this, SFX.CARD_SHOW); - await delay(600); - - // Reveal knocker's melds in center - this.clearReveal(); - this._renderRevealZone(k, kMelds, isGin); - - await delay(1200); - - if (isGin) { - // No layoffs — go straight to scoring - this.showRoundScores(); - return; - } - - // Layoff phase: each opponent of knocker in order - const order = []; - let s = (k + 1) % this.nPlayers; - while (s !== k) { order.push(s); s = (s + 1) % this.nPlayers; } - - for (const seat of order) { - if (seat === 0) { - await this.runHumanLayoff(); - } else { - await this.runAiLayoffAuto(seat); - } - } - - this.showRoundScores(); - } - - _renderRevealZone(knockerSeat, meldGroups, isGin) { - const revealY = 420; - const revealStartX = CX - 400; - let cx = revealStartX; - - // Meld groups - for (let mi = 0; mi < meldGroups.length; mi++) { - const meld = meldGroups[mi]; - const groupLabel = this.add.text(cx + meld.length * 44 / 2, revealY - 70, - mi === 0 ? 'MELDS' : '', { fontFamily: '"Julius Sans One"', fontSize: '13px', color: THEME.mutedHex }) - .setOrigin(0.5, 0).setDepth(D.overlay); - this.revealObjs.push(groupLabel); - - for (let j = 0; j < meld.length; j++) { - const c = this.makeCard(meld[j], cx + j * 44, revealY, { depth: D.overlay + j }); - c.setScale(0.55); - // Green outline glow for meld cards - const glow = this.add.graphics(); - glow.lineStyle(3, THEME.meldGlow, 0.8); - glow.strokeRoundedRect(-CARD_W / 2 * 0.55 - 3, -CARD_H / 2 * 0.55 - 3, CARD_W * 0.55 + 6, CARD_H * 0.55 + 6, 6); - c.addAt(glow, 0); - this.revealObjs.push(c); - } - cx += meld.length * 44 + 20; - } - - // Deadwood cards from knocker's hand - const kHand = this.logic.players[knockerSeat].hand; - const meldedKeys = new Set(meldGroups.flat().map(c => c.key)); - const deadwood = kHand.filter(c => !meldedKeys.has(c.key)); - - if (deadwood.length > 0) { - const dwLabel = this.add.text(cx, revealY - 70, isGin ? '' : 'DEADWOOD', - { fontFamily: '"Julius Sans One"', fontSize: '13px', color: THEME.mutedHex }) - .setOrigin(0, 0).setDepth(D.overlay); - this.revealObjs.push(dwLabel); - - for (let j = 0; j < deadwood.length; j++) { - const c = this.makeCard(deadwood[j], cx + j * 44, revealY, { depth: D.overlay + j }); - c.setScale(0.55); - const dwVal = this.add.text(cx + j * 44, revealY + 36, String(ginDeadwoodValue(deadwood[j])), - { fontFamily: 'Righteous', fontSize: '11px', color: THEME.goldHex }) - .setOrigin(0.5).setDepth(D.overlay + 10); - this.revealObjs.push(c, dwVal); - } - } - } - - // ── Human layoff ─────────────────────────────────────────────────────────── - - runHumanLayoff() { - return new Promise((resolve) => { - this._layoffResolve = resolve; - this.humanMode = 'layoff'; - this.layoffSelected = null; - this.setStatus('Lay off cards on the knocker\'s melds, then click Done'); - this.knockBtn.setVisible(false); - this.ginBtn.setVisible(false); - this.layoffDoneBtn.setVisible(true); - - this._setupLayoffHandInteraction(); - }); - } - - _setupLayoffHandInteraction() { - this.humanCards.forEach((c, i) => { - c.setSize(CARD_W, CARD_H); - c.setInteractive({ useHandCursor: true }); - c.on('pointerdown', () => this.onLayoffCardClick(i)); - }); - this._refreshLayoffHighlights(); - } - - onLayoffCardClick(handIdx) { - if (this.humanMode !== 'layoff') return; - const card = this.logic.players[0].hand[handIdx]; - - // Check which melds it can go on - const validMelds = []; - for (let mi = 0; mi < this.logic.knockerMelds.length; mi++) { - if (canLayoff(card, this.logic.knockerMelds[mi])) validMelds.push(mi); - } - if (validMelds.length === 0) return; - - // Auto-apply the layoff (take first valid meld) - this.logic.layoff(0, [{ cardKey: card.key, meldIdx: validMelds[0] }]); - playSound(this, SFX.CARD_PLACE); - this.renderHand(0); - this._setupLayoffHandInteraction(); - this._refreshLayoffHighlights(); - } - - _refreshLayoffHighlights() { - const hand = this.logic.players[0].hand; - this.humanCards.forEach((c, i) => { - if (!hand[i]) return; - const card = hand[i]; - const canLay = this.logic.knockerMelds.some(m => canLayoff(card, m)); - c.setAlpha(canLay ? 1.0 : 0.55); - }); - } - - onLayoffDone() { - if (this.humanMode !== 'layoff') return; - this.logic.passLayoff(0); - this.layoffDoneBtn.setVisible(false); - this.humanMode = 'idle'; - const resolve = this._layoffResolve; - this._layoffResolve = null; - resolve?.(); - } - - // ── AI layoff (auto) ─────────────────────────────────────────────────────── - - async runAiLayoffAuto(seat) { - const delay = (ms) => new Promise(r => this.time.delayedCall(ms, r)); - await delay(700); - const skill = this.opponents[seat - 1]?.skill ?? 3; - const hand = this.logic.players[seat].hand; - const layoffs = findLayoffs(hand, this.logic.knockerMelds, skill); - if (layoffs.length > 0) { - this.logic.layoff(seat, layoffs); - playSound(this, SFX.CARD_PLACE); - } - this.logic.passLayoff(seat); - await delay(400); - } - - // ── Status text ──────────────────────────────────────────────────────────── - - setStatus(text) { - this.statusText?.setText(text); - } - - // ── Round scores overlay ─────────────────────────────────────────────────── - - async showRoundScores() { - this.busy = true; - const delay = (ms) => new Promise(r => this.time.delayedCall(ms, r)); - - const ovBg = this.add.graphics().setDepth(D.overlay); - ovBg.fillStyle(0x000000, 0.62); - ovBg.fillRoundedRect(CX - 320, CY - 220, 640, 440, 22); - ovBg.lineStyle(2, THEME.gold, 0.6); - ovBg.strokeRoundedRect(CX - 320, CY - 220, 640, 440, 22); - - const title = this.add.text(CX, CY - 185, 'Round Results', { - fontFamily: 'Righteous', fontSize: '32px', color: THEME.goldHex, - }).setOrigin(0.5).setDepth(D.overlayUI); - - const k = this.logic.knocker; - const kName = k === 0 ? 'You' : (this.opponents[k - 1]?.name?.split(' ')[0] ?? `AI ${k}`); - const scores = this.logic.roundScores; - - const names = ['You', ...this.opponents.map(o => o.name?.split(' ')[0] ?? 'AI')]; - const textObjs = [title]; - - for (let s = 0; s < this.nPlayers; s++) { - const ry = CY - 120 + s * 68; - const delta = scores[s]; - const col = delta > 0 ? '#55dd88' : delta < 0 ? '#ff6666' : THEME.ivoryHex; - const t1 = this.add.text(CX - 200, ry, names[s], { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: THEME.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.overlayUI); - const t2 = this.add.text(CX + 200, ry, delta > 0 ? `+${delta}` : String(delta), { - fontFamily: 'Righteous', fontSize: '28px', color: col, - }).setOrigin(1, 0.5).setDepth(D.overlayUI); - textObjs.push(t1, t2); - } - - await delay(3800); - - for (const o of textObjs) o?.destroy(); - ovBg.destroy(); - - if (this.logic.phase === 'gameover') { - this.showGameOver(this.logic.winner); - } else { - this.clearReveal(); - this.logic.newRound(); - this.startRound(); - } - } - - // ── Game over ────────────────────────────────────────────────────────────── - - showGameOver(winnerSeat) { - const names = ['You', ...this.opponents.map(o => o.name?.split(' ')[0] ?? 'AI')]; - const winner = names[winnerSeat ?? 0]; - const youWon = winnerSeat === 0; - - const ovBg = this.add.graphics().setDepth(D.overlay); - ovBg.fillStyle(0x000000, 0.75); - ovBg.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - - this.add.text(CX, CY - 100, youWon ? 'You Win!' : `${winner} Wins!`, { - fontFamily: 'Righteous', fontSize: '72px', color: youWon ? '#55dd88' : THEME.ivoryHex, - }).setOrigin(0.5).setDepth(D.overlayUI); - - const finalScores = this.logic.players.map((p, s) => `${names[s]}: ${p.score}`).join(' '); - this.add.text(CX, CY + 20, finalScores, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: THEME.mutedHex, - }).setOrigin(0.5).setDepth(D.overlayUI); - - new Button(this, CX - 100, CY + 130, 'Play Again', () => { - this.logic.newGame(); - this.clearReveal(); - this.startRound(); - }, { width: 180, height: 56, fontSize: 22 }).setDepth(D.overlayUI); - - new Button(this, CX + 100, CY + 130, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', width: 180, height: 56, fontSize: 22, - }).setDepth(D.overlayUI); - } - - // ── Utility ──────────────────────────────────────────────────────────────── - - delay(ms) { - return new Promise(r => this.time.delayedCall(ms, r)); + this.modalButton(CX - 130, top + h - 46, 'Back', () => this.openScorePad({}), { width: 220, height: 46, fontSize: 18 }); + this.modalButton(CX + 130, top + h - 46, 'Play again', () => this.restart(), { width: 220, height: 46, fontSize: 18 }); } } + +// a card object from its id, for names in text +function G_card(id) { + const rank = id.slice(0, -1), suit = id.slice(-1); + return { id, rank, suit, run: RANKS.indexOf(rank) + 1, pts: Math.min(10, RANKS.indexOf(rank) + 1) }; +} + diff --git a/src/games/ginrummy/GinRummyLogic.js b/src/games/ginrummy/GinRummyLogic.js index 35a0582..0baf84a 100644 --- a/src/games/ginrummy/GinRummyLogic.js +++ b/src/games/ginrummy/GinRummyLogic.js @@ -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 }; diff --git a/src/games/ginrummy/GinRummyTable.js b/src/games/ginrummy/GinRummyTable.js new file mode 100644 index 0000000..d16fc1b --- /dev/null +++ b/src/games/ginrummy/GinRummyTable.js @@ -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 }; diff --git a/src/games/ginrummy/tutorial.md b/src/games/ginrummy/tutorial.md new file mode 100644 index 0000000..ab3e0c0 --- /dev/null +++ b/src/games/ginrummy/tutorial.md @@ -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. diff --git a/tools/verifyGinRummy.js b/tools/verifyGinRummy.js index f00bb27..17b5024 100644 --- a/tools/verifyGinRummy.js +++ b/tools/verifyGinRummy.js @@ -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);