// Canasta — cards, rules and meld helpers. Pure (no Phaser, no state) so the // engine, the AI, the scene and tools/verifyCanasta.js all share it. // // Classic partnership Canasta (Hoyle / pagat.com): two decks plus four jokers // (108 cards), four players in fixed partnerships — seats 0 & 2 (you and Rosa) // against seats 1 & 3 — racing to 5,000. // // Cards are plain JSON so a whole game state can be autosaved: // { id: 'Ks1', rank: 'K', suit: 's' } (the trailing digit is the deck, 0/1) // { id: 'JK2', rank: 'JK', suit: 'x' } (jokers 0..3) export const ICON_FRAME = 65; export const PLAYER_COUNT = 4; export const HAND_SIZE = 11; export const CANASTA_SIZE = 7; export const MAX_WILDS = 3; // a meld may hold at most three wild cards export const MIN_NATURALS = 2; // …and at least two natural cards export const MIN_MELD = 3; export const TEAM_OF_SEAT = [0, 1, 0, 1]; export const SEATS_OF_TEAM = [[0, 2], [1, 3]]; export const PARTNER = [2, 3, 0, 1]; export const SUITS = ['s', 'h', 'd', 'c']; export const RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']; /** Ranks that can form ordinary melds, high to low (display order). */ export const MELD_RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4']; export const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣', x: '' }; const RANK_WORD = { A: 'ace', K: 'king', Q: 'queen', J: 'jack', T: 'ten', 9: 'nine', 8: 'eight', 7: 'seven', 6: 'six', 5: 'five', 4: 'four', 3: 'three', 2: 'two', JK: 'joker', }; // ── Scoring constants ──────────────────────────────────────────────────────── export const NATURAL_CANASTA = 500; export const MIXED_CANASTA = 300; export const RED_THREE = 100; export const ALL_RED_THREES = 800; export const GO_OUT = 100; export const CONCEALED_GO_OUT = 200; /** Standard rules. Every key is a Settings toggle. */ export const DEFAULT_RULES = { target: 5000, // 5000 · 3000 · 2500 goOutCanastas: 1, // canastas a side needs before it may go out (1 or 2) askPartner: false, // "Partner, may I go out?" — a 'no' binds for the turn alwaysFrozen: false, // the pile is always frozen: only a natural pair takes it }; // ── Cards ──────────────────────────────────────────────────────────────────── export function fullShoe() { const out = []; for (let d = 0; d < 2; d++) { for (const s of SUITS) for (const r of RANKS) out.push({ id: `${r}${s}${d}`, rank: r, suit: s }); } for (let j = 0; j < 4; j++) out.push({ id: `JK${j}`, rank: 'JK', suit: 'x' }); return out; } const SHOE = new Map(fullShoe().map((c) => [c.id, c])); export const cardFromId = (id) => SHOE.get(id) ?? null; /** Texture frame in the shared 'casino-cards' atlas. */ export const frameOf = (c) => (c.rank === 'JK' ? 'JK' : `${c.rank}${c.suit}`); export const isWild = (c) => c.rank === 'JK' || c.rank === '2'; export const isRedThree = (c) => c.rank === '3' && (c.suit === 'h' || c.suit === 'd'); export const isBlackThree = (c) => c.rank === '3' && (c.suit === 's' || c.suit === 'c'); /** A natural that may form an ordinary rank meld (4..A). */ export const isMeldable = (c) => !isWild(c) && c.rank !== '3'; export const isRed = (c) => c.suit === 'h' || c.suit === 'd'; export function cardScore(c) { if (c.rank === 'JK') return 50; if (c.rank === '2' || c.rank === 'A') return 20; if (c.rank === 'K' || c.rank === 'Q' || c.rank === 'J' || c.rank === 'T' || c.rank === '9' || c.rank === '8') return 10; if (isRedThree(c)) return 100; return 5; // 4..7 and black threes } export const valueOf = (cards) => cards.reduce((s, c) => s + cardScore(c), 0); export const rankLabel = (r) => (r === 'T' ? '10' : r === 'JK' ? 'Joker' : r); export const cardName = (c) => (!c ? '' : c.rank === 'JK' ? 'Joker' : `${rankLabel(c.rank)}${SUIT_SYM[c.suit]}`); export const rankWord = (r, n = 1) => { const w = RANK_WORD[r] ?? r; if (n === 1) return w; return w === 'six' ? 'sixes' : `${w}s`; }; /** Sort weight for a hand fanned left → right: naturals A high … 4, then black threes, then wilds. */ export function handOrder(c) { if (c.rank === 'JK') return 100; if (c.rank === '2') return 90; if (c.rank === '3') return 80; return MELD_RANKS.indexOf(c.rank); } const SUIT_ORDER = { s: 0, h: 1, c: 2, d: 3, x: 4 }; export const handSort = (a, b) => handOrder(a) - handOrder(b) || SUIT_ORDER[a.suit] - SUIT_ORDER[b.suit] || (a.id < b.id ? -1 : 1); // ── Minimum for a side's first meld ────────────────────────────────────────── /** Thresholds scale with a shorter match (2,500 / 3,000) so the ladder still bites. */ export function minimumMeld(score, rules = DEFAULT_RULES) { const k = (rules.target ?? 5000) / 5000; if (score < 0) return 15; if (score < 1500 * k) return 50; if (score < 3000 * k) return 90; return 120; } // ── Melds ──────────────────────────────────────────────────────────────────── // A meld on the table is { rank, cards: [card…] }. export const wildsIn = (cards) => cards.filter(isWild).length; export const naturalsIn = (cards) => cards.filter((c) => !isWild(c)).length; export const isCanasta = (m) => m.cards.length >= CANASTA_SIZE; export const isNaturalCanasta = (m) => isCanasta(m) && wildsIn(m.cards) === 0; /** * Why can't `adds` go onto `existing` (a team meld of `rank`, or null for a new * meld)? Returns null when legal, else a plain-English reason for the UI. * Black threes form a meld only when going out (the engine checks that). */ export function meldProblem(rank, existing, adds) { if (!adds.length) return 'No cards selected'; if (rank === '3') { if (existing) return 'Black threes are melded all at once'; if (adds.some((c) => !isBlackThree(c))) return 'A meld of threes may hold only black threes'; if (adds.length < 3) return 'Black threes meld three or four at a time'; return null; } for (const c of adds) { if (isWild(c)) continue; if (c.rank === '3') return isRedThree(c) ? 'Red threes are bonus cards' : 'Black threes only meld when going out'; if (c.rank !== rank) return `Those aren't all ${rankWord(rank, 2)}`; } const all = [...(existing?.cards ?? []), ...adds]; const nat = naturalsIn(all), wild = wildsIn(all); if (wild > MAX_WILDS) return 'A meld may hold at most three wild cards'; if (nat < MIN_NATURALS) return 'A meld needs at least two natural cards'; if (!existing && all.length < MIN_MELD) return 'A new meld needs at least three cards'; return null; } /** The rank a selection would meld as (its naturals' rank), or null when mixed / all wild. */ export function selectionRank(cards) { const nat = cards.filter((c) => !isWild(c)); if (!nat.length) return null; const r = nat[0].rank; return nat.every((c) => c.rank === r) ? r : null; } // ── Exact initial-meld solver ──────────────────────────────────────────────── /** * Find melds formed from `hand` (no team melds exist yet) whose card value * reaches `need`, using the fewest wild cards, then the fewest cards. * * forced: { card, rank, minNat } — a pile take: the top `card` must sit in a * meld of `rank` together with at least `minNat` naturals from hand * (the top card counts toward the minimum; the rest of the pile does not) * keep: cards that must stay in hand afterwards (excluding `extraIn`, the * pile cards that will arrive) * * Returns { groups: [{ rank, ids }], value } or null. `ids` never includes the * forced top card. Exhaustive over per-rank natural/wild counts (pruned by the * wild budget), so "can I make it?" never guesses. */ export function solveInitialMeld(hand, { need, forced = null, keep = 0, extraIn = 0 } = {}) { const wilds = hand.filter(isWild).sort((a, b) => cardScore(b) - cardScore(a)); const byRank = new Map(); for (const c of hand) if (isMeldable(c)) (byRank.get(c.rank) ?? byRank.set(c.rank, []).get(c.rank)).push(c); const ranks = [...byRank.keys()].filter((r) => byRank.get(r).length >= 2 || r === forced?.rank); if (forced && !byRank.has(forced.rank)) { if (forced.minNat > 0) return null; ranks.push(forced.rank); byRank.set(forced.rank, []); } // forced rank first so the search can't skip it ranks.sort((a, b) => (a === forced?.rank ? -1 : b === forced?.rank ? 1 : 0)); const W = wilds.length; const prefix = [0]; for (const w of wilds) prefix.push(prefix[prefix.length - 1] + cardScore(w)); const handLeftMin = keep - extraIn; let best = null; const choice = []; const visit = (i, wUsed, cards, natValue) => { if (best && (wUsed > best.w || (wUsed === best.w && cards > best.cards))) return; if (i === ranks.length) { const value = natValue + prefix[wUsed] + (forced ? cardScore(forced.card) : 0); if (value < need) return; if (hand.length - cards < handLeftMin) return; if (!choice.some((ch) => ch.m + ch.w > 0) && !forced) return; const better = !best || wUsed < best.w || (wUsed === best.w && (cards < best.cards || (cards === best.cards && value > best.value))); if (better) best = { w: wUsed, cards, value, plan: choice.map((ch) => ({ ...ch })) }; return; } const r = ranks[i]; const nats = byRank.get(r); const isForced = forced && r === forced.rank; const top = isForced ? 1 : 0; const per = cardScore({ rank: r, suit: 's' }); const options = []; if (!isForced) options.push([0, 0]); const mLo = isForced ? Math.max(forced.minNat, 0) : 2; for (let m = mLo; m <= nats.length; m++) { for (let w = 0; w <= MAX_WILDS && wUsed + w <= W; w++) { const natTotal = m + top; if (natTotal < MIN_NATURALS) continue; if (natTotal + w < MIN_MELD) continue; options.push([m, w]); } } for (const [m, w] of options) { choice.push({ rank: r, m, w }); visit(i + 1, wUsed + w, cards + m + w, natValue + m * per); choice.pop(); } }; visit(0, 0, 0, 0); if (!best) return null; // Materialise ids: wilds are handed out highest-value first (that is what `prefix` assumed). let wi = 0; const groups = []; for (const ch of best.plan) { if (ch.m + ch.w === 0 && !(forced && ch.rank === forced.rank)) continue; const ids = byRank.get(ch.rank).slice(0, ch.m).map((c) => c.id); for (let k = 0; k < ch.w; k++) ids.push(wilds[wi++].id); groups.push({ rank: ch.rank, ids }); } return { groups, value: best.value }; } /** Highest card value the hand could meld right now as a first meld (for the meter). */ export function maxInitialValue(hand) { let lo = 0, hi = valueOf(hand) + 1; // the solver answers "≥ need?" — binary-search the largest reachable need if (!solveInitialMeld(hand, { need: 1 })) return 0; while (hi - lo > 5) { const mid = Math.floor((lo + hi) / 2); if (solveInitialMeld(hand, { need: mid })) lo = mid; else hi = mid; } for (let v = hi; v >= lo; v--) if (solveInitialMeld(hand, { need: v })) return v; return lo; }