// Canasta — 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/verifyCanasta.js all drive it. // // Hand flow // draw draw from the stock (red threes are laid out and replaced), or // take the whole discard pile by melding its top card. Before a // side's first meld the top card + cards from hand (never the rest // of the pile) must reach the minimum, so the take and that first // meld are ONE atomic action. When the stock is empty the player // must take the pile if its top card goes onto one of their side's // melds, may take it otherwise, and the hand ends if they don't. // play meld (each call is atomic — a side's first meld must reach the // minimum in one go), then discard. Emptying the hand is going // out: it needs the side's canasta(s) (and, with the askPartner // house rule, a 'yes' from partner). Without that you may never // meld down to fewer than two cards. // ask (askPartner) waiting for partner's answer to "May I go out?" // handOver / gameOver // // Discarding a wild freezes the pile (until it is taken); a black three on top // only blocks the next player. A red three or wild turned as the first upcard // is covered by another card and freezes the pile. import { DEFAULT_RULES, HAND_SIZE, PLAYER_COUNT, CANASTA_SIZE, TEAM_OF_SEAT, SEATS_OF_TEAM, PARTNER, NATURAL_CANASTA, MIXED_CANASTA, RED_THREE, ALL_RED_THREES, GO_OUT, CONCEALED_GO_OUT, fullShoe, isWild, isRedThree, isBlackThree, isMeldable, cardScore, valueOf, minimumMeld, meldProblem, isCanasta, isNaturalCanasta, wildsIn, rankWord, cardName, solveInitialMeld, } from './CanastaData.js'; export const VERSION = 1; const clone = (o) => (typeof structuredClone === 'function' ? structuredClone(o) : JSON.parse(JSON.stringify(o))); // mulberry32 on a state-held integer, so a saved game replays the same shuffles function rand(gs) { gs.rng = (gs.rng + 0x6d2b79f5) >>> 0; let t = gs.rng; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; } function 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 = () => ({ canastas: 0, naturals: 0, piles: 0, bigPile: 0, outs: 0, concealed: 0, redThrees: 0 }); const freshTurn = (gs) => ({ startMelded: gs.teams[TEAM_OF_SEAT[gs.current]].melded, tookPile: false, asked: null, drew: null, }); // ── Setup ──────────────────────────────────────────────────────────────────── export function createGame({ rules = {}, seed = (Date.now() >>> 0), dealer = null } = {}) { const gs = { version: VERSION, rules: { ...DEFAULT_RULES, ...rules }, rng: seed >>> 0, scores: [0, 0], history: [], stats: Array.from({ length: PLAYER_COUNT }, emptyStats), handNo: 0, dealer: 0, cut: null, winner: null, log: [], }; if (dealer == null) { // cut for deal: the high card deals (ties re-cut; jokers count low) const order = 'A K Q J T 9 8 7 6 5 4 3 2'.split(' '); for (let tries = 0; tries < 20; tries++) { const shoe = shuffle(gs, fullShoe()); const cut = shoe.slice(0, PLAYER_COUNT); const w = cut.map((c) => (c.rank === 'JK' ? 99 : order.indexOf(c.rank))); const best = Math.min(...w); if (w.filter((x) => x === best).length === 1) { gs.cut = cut.map((c) => c.id); gs.dealer = w.indexOf(best); break; } } } else { gs.dealer = dealer; } return deal(gs); } /** Deal a fresh hand onto `gs` (mutates the given clone). */ function deal(gs) { gs.handNo++; const cards = shuffle(gs, fullShoe()); gs.hands = [[], [], [], []]; const first = (gs.dealer + 1) % PLAYER_COUNT; let k = 0; for (let c = 0; c < HAND_SIZE; c++) for (let s = 0; s < PLAYER_COUNT; s++) gs.hands[(first + s) % PLAYER_COUNT].push(cards[k++]); gs.stock = cards.slice(k); gs.teams = [0, 1].map(() => ({ melds: [], redThrees: [], melded: false })); gs.discard = []; gs.frozen = false; gs.log = [{ kind: 'deal', hand: gs.handNo, dealer: gs.dealer }]; // Red threes dealt to a player are laid out and replaced, in turn order. for (let i = 0; i < PLAYER_COUNT; i++) { const seat = (first + i) % PLAYER_COUNT; let reds = gs.hands[seat].filter(isRedThree); while (reds.length) { gs.hands[seat] = gs.hands[seat].filter((c) => !isRedThree(c)); for (const r of reds) { gs.teams[TEAM_OF_SEAT[seat]].redThrees.push(r); gs.stats[seat].redThrees++; gs.log.push({ kind: 'redThree', seat, id: r.id, dealt: true }); } const repl = gs.stock.splice(0, reds.length); gs.hands[seat].push(...repl); reds = repl.filter(isRedThree); } } // The upcard: a wild or red three is covered by another card and freezes the pile. let up = gs.stock.shift(); gs.discard.push(up); while (isWild(up) || isRedThree(up)) { gs.frozen = true; up = gs.stock.shift(); gs.discard.push(up); } gs.log.push({ kind: 'upcard', ids: gs.discard.map((c) => c.id) }); gs.pickups = [[], [], [], []]; // ids each seat took into hand from the pile (public) gs.discards = [[], [], [], []]; // ids each seat discarded gs.current = first; gs.phase = 'draw'; gs.turn = freshTurn(gs); gs.turnNo = 0; gs.ask = null; gs.result = null; return gs; } export function nextHand(gs) { if (gs.phase !== 'handOver') return gs; const g = clone(gs); g.dealer = (g.dealer + 1) % PLAYER_COUNT; return deal(g); } // ── Queries ────────────────────────────────────────────────────────────────── export const topDiscard = (gs) => gs.discard[gs.discard.length - 1] ?? null; export const teamOf = (gs, seat) => gs.teams[TEAM_OF_SEAT[seat]]; export const teamMeld = (gs, seat, rank) => teamOf(gs, seat).melds.find((m) => m.rank === rank) ?? null; export const canastaCount = (gs, team) => gs.teams[team].melds.filter(isCanasta).length; export const minimumFor = (gs, seat) => minimumMeld(gs.scores[TEAM_OF_SEAT[seat]], gs.rules); export const isOver = (gs) => gs.phase === 'handOver' || gs.phase === 'gameOver'; /** Whose decision the game is waiting on (partner answers during 'ask'). */ export const actor = (gs) => (gs.phase === 'ask' ? gs.ask.partner : gs.current); /** Is the pile frozen for this seat (a wild in it, their side unmelded, or the house rule)? */ export function frozenFor(gs, seat) { return gs.frozen || !teamOf(gs, seat).melded || !!gs.rules.alwaysFrozen; } /** Could the seat empty their hand once their side holds `canastas` canastas? */ function goOutOk(gs, canastas) { if (canastas < (gs.rules.goOutCanastas ?? 1)) return false; if (gs.rules.askPartner && gs.turn.asked !== 'yes') return false; return true; } /** Has the current player's side the canastas to go out (ignoring the ask)? */ export function hasGoOutCanastas(gs, seat = gs.current) { return canastaCount(gs, TEAM_OF_SEAT[seat]) >= (gs.rules.goOutCanastas ?? 1); } export function canGoOut(gs, seat = gs.current) { return goOutOk(gs, canastaCount(gs, TEAM_OF_SEAT[seat])); } function findIds(hand, ids) { const out = []; const seen = new Set(); for (const id of ids) { if (seen.has(id)) return null; seen.add(id); const c = hand.find((x) => x.id === id); if (!c) return null; out.push(c); } return out; } /** Combine groups of the same rank; returns [{ rank, cards }] or a problem string. */ function resolveGroups(gs, seat, groups) { const hand = gs.hands[seat]; const all = findIds(hand, groups.flatMap((g) => g.ids)); if (!all) return 'Those cards aren\'t all in your hand'; const byRank = new Map(); for (const g of groups) { if (!g.ids.length) continue; const cards = g.ids.map((id) => hand.find((c) => c.id === id)); if (!byRank.has(g.rank)) byRank.set(g.rank, []); byRank.get(g.rank).push(...cards); } return [...byRank.entries()].map(([rank, cards]) => ({ rank, cards })); } /** * Check a meld action for the current player. Returns * { problem, value, left, goingOut, canastasAfter, newCanastas: [rank…] } * where problem is null when legal. */ export function checkMelds(gs, groups) { const seat = gs.current; const out = { problem: null, value: 0, left: gs.hands[seat].length, goingOut: false, canastasAfter: 0, newCanastas: [] }; if (gs.phase !== 'play') { out.problem = 'Draw first'; return out; } const team = teamOf(gs, seat); const resolved = resolveGroups(gs, seat, groups); if (typeof resolved === 'string') { out.problem = resolved; return out; } if (!resolved.length) { out.problem = 'No cards selected'; return out; } let used = 0; let canastas = canastaCount(gs, TEAM_OF_SEAT[seat]); let threes = false; for (const { rank, cards } of resolved) { const existing = rank === '3' ? null : team.melds.find((m) => m.rank === rank) ?? null; if (!existing && !team.melded && cards.every(isWild)) { out.problem = 'Wild cards need a meld to join'; return out; } const p = meldProblem(rank, existing, cards); if (p) { out.problem = p; return out; } if (rank === '3') threes = true; used += cards.length; out.value += valueOf(cards); const before = existing ? existing.cards.length : 0; if (before < CANASTA_SIZE && before + cards.length >= CANASTA_SIZE) { canastas++; out.newCanastas.push(rank); } } out.left = gs.hands[seat].length - used; out.canastasAfter = canastas; out.goingOut = out.left <= 1; if (out.goingOut && !goOutOk(gs, canastas)) { if (canastas < (gs.rules.goOutCanastas ?? 1)) { const n = gs.rules.goOutCanastas ?? 1; out.problem = `Keep two cards — your side needs ${n === 1 ? 'a canasta' : 'two canastas'} to go out`; } else { out.problem = gs.turn.asked === 'no' ? 'Partner said no — keep two cards this turn' : 'Ask your partner before going out'; } return out; } if (threes && !out.goingOut) { out.problem = 'Black threes only meld when you go out'; return out; } if (!team.melded) { const need = minimumFor(gs, seat); // Going out concealed (the whole hand in one turn) waives the minimum. const concealed = out.goingOut && !gs.turn.startMelded; if (out.value < need && !concealed) { out.problem = `Your side's first meld needs ${need} points (this is ${out.value})`; return out; } } return out; } /** * Why can't the seat take the pile with `plan`? null when legal. * plan = { ids: [hand ids melded with the top card], extra: [{ rank, ids }] } * `extra` (hand cards only) lets an unmelded side reach its minimum in the same action. */ export function takeProblem(gs, seat, plan) { if (gs.phase !== 'draw' || seat !== gs.current) return 'Not your draw'; const top = topDiscard(gs); if (!top) return 'The pile is empty'; if (isWild(top)) return 'A wild card is on top — the pile can\'t be taken'; if (isBlackThree(top)) return 'A black three blocks the pile this turn'; const team = teamOf(gs, seat); const hand = gs.hands[seat]; const ids = plan?.ids ?? []; const extra = (plan?.extra ?? []).filter((g) => g.ids.length); const cards = findIds(hand, [...ids, ...extra.flatMap((g) => g.ids)]); if (!cards) return 'Those cards aren\'t all in your hand'; const mine = ids.map((id) => hand.find((c) => c.id === id)); const rank = top.rank; const existing = team.melds.find((m) => m.rank === rank) ?? null; const pairCount = mine.filter((c) => c.rank === rank).length; if (frozenFor(gs, seat) && pairCount < 2) { const why = !team.melded ? 'your side hasn\'t melded yet' : gs.rules.alwaysFrozen ? 'the pile is always frozen' : 'the pile is frozen'; return `Needs a natural pair of ${rankWord(rank, 2)} — ${why}`; } const p = meldProblem(rank, existing, [top, ...mine]); if (p) { if (!existing && !frozenFor(gs, seat)) return `Needs two ${rankWord(rank, 2)}, or one and a wild card`; return p; } if (extra.length && team.melded) return 'Take the pile first, then meld'; if (extra.some((g) => g.rank === rank || g.rank === '3')) return 'That meld can\'t go with the pickup'; let value = valueOf([top, ...mine]); let canastas = canastaCount(gs, TEAM_OF_SEAT[seat]); if ((existing?.cards.length ?? 0) + 1 + mine.length >= CANASTA_SIZE && (existing?.cards.length ?? 0) < CANASTA_SIZE) canastas++; const ranks = new Set(); for (const g of extra) { if (ranks.has(g.rank)) return 'One meld per rank'; ranks.add(g.rank); const gc = g.ids.map((id) => hand.find((c) => c.id === id)); const gp = meldProblem(g.rank, null, gc); if (gp) return gp; value += valueOf(gc); if (gc.length >= CANASTA_SIZE) canastas++; } if (!team.melded) { const need = minimumFor(gs, seat); if (value < need) return `The top card and your hand make ${value} — your side's first meld needs ${need}`; } const left = hand.length - cards.length + gs.discard.length - 1; if (left <= 1 && !goOutOk(gs, canastas)) return 'That would leave you no card to keep — you can\'t go out yet'; return null; } /** * The cheapest legal way for `seat` to take the pile, or { plan: null, problem }. * Uses the exact first-meld solver when the side hasn't melded. */ export function takeOption(gs, seat) { if (gs.phase !== 'draw' || seat !== gs.current) return { plan: null, problem: 'Not your draw' }; const top = topDiscard(gs); const quick = takeProblem(gs, seat, { ids: [] }); if (!top || isWild(top) || isBlackThree(top)) return { plan: null, problem: quick }; const team = teamOf(gs, seat); const hand = gs.hands[seat]; const rank = top.rank; const nats = hand.filter((c) => c.rank === rank && !isWild(c)); const wilds = hand.filter(isWild).sort((a, b) => cardScore(a) - cardScore(b)); const tries = []; if (!team.melded) { const sol = solveInitialMeld(hand, { need: minimumFor(gs, seat), forced: { card: top, rank, minNat: 2 }, keep: 2, extraIn: gs.discard.length - 1, }); if (sol) { const main = sol.groups.find((g) => g.rank === rank); tries.push({ ids: main ? main.ids : [], extra: sol.groups.filter((g) => g.rank !== rank) }); } // even when the solver fails, keep the nicest explanation if (!tries.length) { if (nats.length < 2) return { plan: null, problem: `Needs a natural pair of ${rankWord(rank, 2)} — your side hasn't melded yet` }; return { plan: null, problem: `Your hand can't reach the ${minimumFor(gs, seat)}-point first meld with the ${cardName(top)}` }; } } else { if (!frozenFor(gs, seat) && teamMeld(gs, seat, rank)) tries.push({ ids: [] }); if (nats.length >= 2) tries.push({ ids: nats.slice(0, 2).map((c) => c.id) }); if (!frozenFor(gs, seat) && nats.length === 1 && wilds.length) tries.push({ ids: [nats[0].id, wilds[0].id] }); } for (const plan of tries) { if (!takeProblem(gs, seat, plan)) return { plan, problem: null }; } const plan = tries[0]; return { plan: null, problem: plan ? takeProblem(gs, seat, plan) : quick }; } /** With the stock exhausted: must the seat take the pile (top card fits their side's meld)? */ export function mustTake(gs, seat = gs.current) { if (gs.stock.length || gs.phase !== 'draw') return false; const top = topDiscard(gs); if (!top || !isMeldable(top) || frozenFor(gs, seat) || !teamMeld(gs, seat, top.rank)) return false; return !takeProblem(gs, seat, { ids: [] }); } // ── Actions ────────────────────────────────────────────────────────────────── export function drawStock(gs) { if (gs.phase !== 'draw' || !gs.stock.length) return gs; const g = clone(gs); const seat = g.current; for (;;) { const c = g.stock.shift(); if (isRedThree(c)) { teamOf(g, seat).redThrees.push(c); g.stats[seat].redThrees++; g.log.push({ kind: 'redThree', seat, id: c.id }); if (!g.stock.length) { // A red three as the last card of the stock: no meld, no discard — the hand ends. g.log.push({ kind: 'stockOut', seat }); return endHand(g, null); } continue; } g.hands[seat].push(c); g.turn.drew = c.id; g.log.push({ kind: 'draw', seat, id: c.id }); break; } g.phase = 'play'; return g; } export function takePile(gs, plan) { const seat = gs.current; const opt = plan ?? takeOption(gs, seat).plan; if (!opt || takeProblem(gs, seat, opt)) return gs; const g = clone(gs); const team = teamOf(g, seat); const hand = g.hands[seat]; const top = g.discard.pop(); const pull = (ids) => ids.map((id) => hand.splice(hand.findIndex((c) => c.id === id), 1)[0]); const mine = pull(opt.ids); let m = team.melds.find((x) => x.rank === top.rank); const before = m ? m.cards.length : 0; if (!m) { m = { rank: top.rank, cards: [] }; team.melds.push(m); } m.cards.push(top, ...mine); const newCanastas = []; if (before < CANASTA_SIZE && m.cards.length >= CANASTA_SIZE) newCanastas.push(m.rank); const extra = []; for (const grp of (opt.extra ?? []).filter((x) => x.ids.length)) { const cards = pull(grp.ids); team.melds.push({ rank: grp.rank, cards }); extra.push({ rank: grp.rank, ids: cards.map((c) => c.id) }); if (cards.length >= CANASTA_SIZE) newCanastas.push(grp.rank); } team.melded = true; // The rest of the pile goes into the hand; any red three in it (a turned upcard) is laid out. const rest = g.discard.splice(0); for (const c of rest) { if (isRedThree(c)) { team.redThrees.push(c); g.stats[seat].redThrees++; g.log.push({ kind: 'redThree', seat, id: c.id, fromPile: true }); } else { hand.push(c); } } g.pickups[seat].push(...rest.filter((c) => !isRedThree(c)).map((c) => c.id)); g.frozen = false; g.turn.tookPile = true; g.stats[seat].piles++; g.stats[seat].bigPile = Math.max(g.stats[seat].bigPile, rest.length + 1); countCanastas(g, seat, newCanastas); g.log.push({ kind: 'take', seat, top: top.id, rank: top.rank, ids: mine.map((c) => c.id), extra, gained: rest.map((c) => c.id), count: rest.length + 1, newCanastas, }); g.phase = 'play'; if (!hand.length) return goOut(g, seat); return g; } /** Stock exhausted and the player won't (or can't) take the pile: the hand ends. */ export function passStock(gs) { if (gs.phase !== 'draw' || gs.stock.length || mustTake(gs)) return gs; const g = clone(gs); g.log.push({ kind: 'stockOut', seat: g.current }); return endHand(g, null); } export function meldCards(gs, groups) { const chk = checkMelds(gs, groups); if (chk.problem) return gs; const g = clone(gs); const seat = g.current; const team = teamOf(g, seat); const hand = g.hands[seat]; const resolved = resolveGroups(g, seat, groups); const laid = []; for (const { rank, cards } of resolved) { for (const c of cards) hand.splice(hand.findIndex((x) => x.id === c.id), 1); let m = rank === '3' ? null : team.melds.find((x) => x.rank === rank); if (!m) { m = { rank, cards: [] }; team.melds.push(m); } m.cards.push(...cards); laid.push({ rank, ids: cards.map((c) => c.id) }); } team.melded = true; countCanastas(g, seat, chk.newCanastas); g.log.push({ kind: 'meld', seat, groups: laid, newCanastas: chk.newCanastas, value: chk.value }); if (!hand.length) return goOut(g, seat); return g; } function countCanastas(g, seat, ranks) { for (const r of ranks) { const m = teamOf(g, seat).melds.find((x) => x.rank === r); g.stats[seat].canastas++; if (m && isNaturalCanasta(m)) g.stats[seat].naturals++; } } /** Why can't the current player discard this card? null when legal. */ export function discardProblem(gs, id) { if (gs.phase !== 'play') return 'Draw first'; const hand = gs.hands[gs.current]; if (!hand.some((c) => c.id === id)) return 'Not in your hand'; if (hand.length === 1 && !canGoOut(gs)) return 'You can\'t go out yet'; return null; } export function discardCard(gs, id) { if (discardProblem(gs, id)) return gs; const g = clone(gs); const seat = g.current; const hand = g.hands[seat]; const [c] = hand.splice(hand.findIndex((x) => x.id === id), 1); g.discard.push(c); g.discards[seat].push(c.id); const freeze = isWild(c) && !g.frozen; if (isWild(c)) g.frozen = true; g.log.push({ kind: 'discard', seat, id: c.id, freeze, block: isBlackThree(c) }); if (!hand.length) return goOut(g, seat); g.current = (seat + 1) % PLAYER_COUNT; g.phase = 'draw'; g.turn = freshTurn(g); g.turnNo++; return g; } /** askPartner rule: "Partner, may I go out?" */ export function askGoOut(gs) { // (asking is allowed before the canasta that will let you out is on the table) if (gs.phase !== 'play' || !gs.rules.askPartner || gs.turn.asked) return gs; const g = clone(gs); g.phase = 'ask'; g.ask = { seat: g.current, partner: PARTNER[g.current] }; g.log.push({ kind: 'ask', seat: g.current }); return g; } export function answerGoOut(gs, yes) { if (gs.phase !== 'ask') return gs; const g = clone(gs); g.turn.asked = yes ? 'yes' : 'no'; g.log.push({ kind: 'answer', seat: g.ask.partner, yes: !!yes }); g.ask = null; g.phase = 'play'; return g; } function goOut(g, seat) { const concealed = !g.turn.startMelded; g.stats[seat].outs++; if (concealed) g.stats[seat].concealed++; g.log.push({ kind: 'out', seat, concealed }); return endHand(g, seat, concealed); } // ── Scoring ────────────────────────────────────────────────────────────────── export function scoreTeam(gs, team, outSeat = null, concealed = false) { const t = gs.teams[team]; const d = { meldPoints: 0, natural: 0, mixed: 0, canastaBonus: 0, redThrees: t.redThrees.length, redThreeBonus: 0, goOut: 0, inHand: 0, total: 0, }; for (const m of t.melds) { d.meldPoints += valueOf(m.cards); if (isCanasta(m)) { if (wildsIn(m.cards) === 0) { d.natural++; d.canastaBonus += NATURAL_CANASTA; } else { d.mixed++; d.canastaBonus += MIXED_CANASTA; } } } const rt = t.redThrees.length; const rtv = rt === 4 ? ALL_RED_THREES : rt * RED_THREE; d.redThreeBonus = t.melded ? rtv : -rtv; if (outSeat != null && TEAM_OF_SEAT[outSeat] === team) d.goOut = concealed ? CONCEALED_GO_OUT : GO_OUT; for (const s of SEATS_OF_TEAM[team]) d.inHand += valueOf(gs.hands[s]); d.total = d.meldPoints + d.canastaBonus + d.redThreeBonus + d.goOut - d.inHand; return d; } function endHand(g, outSeat, concealed = false) { const detail = [0, 1].map((t) => scoreTeam(g, t, outSeat, concealed)); const before = g.scores.slice(); g.scores = g.scores.map((s, t) => s + detail[t].total); g.result = { outSeat, concealed, detail, before, reason: outSeat == null ? 'stock' : 'out' }; g.history.push({ hand: g.handNo, totals: detail.map((d) => d.total), scores: g.scores.slice(), outSeat, concealed }); g.ask = null; const target = g.rules.target ?? 5000; const [a, b] = g.scores; // A tie at or past the target plays another hand. if ((a >= target || b >= target) && a !== b) { g.winner = a > b ? 0 : 1; g.phase = 'gameOver'; } else { g.phase = 'handOver'; } g.log.push({ kind: 'handOver', totals: detail.map((d) => d.total), outSeat }); return g; } /** The whole state after any action, for the verifier: card conservation. */ export function cardCount(gs) { return gs.stock.length + gs.discard.length + gs.hands.reduce((s, h) => s + h.length, 0) + gs.teams.reduce((s, t) => s + t.redThrees.length + t.melds.reduce((x, m) => x + m.cards.length, 0), 0); }