diff --git a/src/games/canasta/CanastaAI.js b/src/games/canasta/CanastaAI.js index 6a85641..c495bca 100644 --- a/src/games/canasta/CanastaAI.js +++ b/src/games/canasta/CanastaAI.js @@ -1,199 +1,387 @@ -// Canasta — heuristic partnership AI. No Phaser, no state mutation. Each chooser -// inspects the (already-cloned) engine state and returns a plain action -// descriptor that the scene / verify harness applies through CanastaLogic. +// Canasta — partnership AI and the Coach. No Phaser, no state mutation: every +// chooser inspects the engine state and returns a plain descriptor the scene / +// verify harness applies through CanastaLogic. // -// A full AI turn is three calls, in order: -// 1. chooseDraw → { type:'stock' } | { type:'take', plan } -// 2. chooseMelds → { actions:[{rank,cardIds}] } (applied in sequence) -// 3. chooseDiscard→ cardId -// The AI is partner-aware: melds belong to the team, so it freely extends a -// partner's melds and counts the partnership's canastas when deciding to go out. +// A turn is: +// chooseDraw(gs, seat, skill) → { type:'stock' } | { type:'take', plan } | { type:'pass' } +// chooseMelds(gs, seat, skill) → { groups } | { ask:true } | null (repeat until null) +// chooseDiscard(gs, seat, skill) → cardId +// chooseAnswer(gs, skill) → true/false (partner's reply to "may I go out?") +// +// What the AI knows: its own hand, the table, the pile, and what each player +// publicly picked up (pile cards that went into a hand and haven't been played +// since). Skill sets how much of that it uses and how noisy its choices are. import { - takePlan, takeDiscard, meld, meetsInitialMeld, teamMeld, isCanasta, - meldNaturals, meldWilds, -} from './CanastaLogic.js'; -import { - isWild, isMeldable, isBlackThree, cardScore, minimumMeld, - TEAM_OF_SEAT, CANASTA_SIZE, MAX_WILDS_IN_MELD, + CANASTA_SIZE, MAX_WILDS, TEAM_OF_SEAT, SEATS_OF_TEAM, PARTNER, MELD_RANKS, + isWild, isBlackThree, isMeldable, cardScore, valueOf, solveInitialMeld, isCanasta, + wildsIn, naturalsIn, rankWord, rankLabel, cardName, } from './CanastaData.js'; +import { + takeOption, mustTake, checkMelds, teamOf, topDiscard, frozenFor, minimumFor, + canastaCount, hasGoOutCanastas, +} from './CanastaLogic.js'; -// Skill 1–5 → reaction delay and decision noise (mirrors the other games). const PROFILE = { - 1: { delay: [820, 1300], aggression: 0.35, pushCanasta: false, noise: 2.4 }, - 2: { delay: [720, 1150], aggression: 0.5, pushCanasta: false, noise: 1.6 }, - 3: { delay: [620, 1000], aggression: 0.65, pushCanasta: true, noise: 1.0 }, - 4: { delay: [520, 880], aggression: 0.8, pushCanasta: true, noise: 0.5 }, - 5: { delay: [440, 760], aggression: 0.95, pushCanasta: true, noise: 0.0 }, + 1: { noise: 26, memory: false, danger: 0.2, freeze: false, block: 0.3, takeBar: 70, holdOut: false, miss: 0.25 }, + 2: { noise: 16, memory: false, danger: 0.5, freeze: false, block: 0.6, takeBar: 45, holdOut: false, miss: 0.12 }, + 3: { noise: 9, memory: true, danger: 0.85, freeze: true, block: 0.85, takeBar: 30, holdOut: true, miss: 0.04 }, + 4: { noise: 4, memory: true, danger: 1.1, freeze: true, block: 1, takeBar: 22, holdOut: true, miss: 0 }, + 5: { noise: 0, memory: true, danger: 1.3, freeze: true, block: 1, takeBar: 18, holdOut: true, miss: 0 }, }; -const prof = (skill) => PROFILE[Math.max(1, Math.min(5, skill | 0))] || PROFILE[3]; +export const prof = (skill) => PROFILE[Math.max(1, Math.min(5, skill | 0))] ?? PROFILE[3]; +const jitter = (p, rnd) => (rnd() - 0.5) * 2 * p.noise; -export function thinkDelay(skill) { - const [lo, hi] = prof(skill).delay; - return lo + Math.random() * (hi - lo); +const nextSeat = (s) => (s + 1) % 4; +const oppTeam = (seat) => 1 - TEAM_OF_SEAT[seat]; + +/** Ranks a seat is known to hold (public pickups still in hand). */ +export function knownRanks(gs, seat) { + const hand = new Set(gs.hands[seat].map((c) => c.id)); + const out = {}; + for (const id of gs.pickups[seat]) { + if (!hand.has(id)) continue; + const c = gs.hands[seat].find((x) => x.id === id); + if (c && isMeldable(c)) out[c.rank] = (out[c.rank] || 0) + 1; + } + return out; } -function team(state, seat) { return state.teams[TEAM_OF_SEAT[seat]]; } -function valueOfCards(cards) { return cards.reduce((s, c) => s + cardScore(c), 0); } - -function groupNaturalsByRank(cards) { - const g = {}; - for (const c of cards) { - if (isWild(c) || !isMeldable(c)) continue; - (g[c.rank] ||= []).push(c); - } - return g; +/** Is the other side close to going out? 0 (no) … 1 (any moment). */ +export function threatOf(gs, team) { + const need = gs.rules.goOutCanastas ?? 1; + const have = canastaCount(gs, team); + const minHand = Math.min(...SEATS_OF_TEAM[team].map((s) => gs.hands[s].length)); + let t = 0; + if (have >= need) t = minHand <= 2 ? 1 : minHand <= 4 ? 0.7 : minHand <= 7 ? 0.35 : 0.15; + else if (have === need - 1 && gs.teams[team].melds.some((m) => m.cards.length >= 5 && !isCanasta(m))) t = minHand <= 4 ? 0.4 : 0.15; + if (gs.stock.length < 8) t = Math.max(t, 0.5); + return t; } -// ── Core meld builder (no minimum gate) ────────────────────────────────────── -// Greedily proposes meld actions against a working copy of the seat's hand: -// extend the team's existing melds, then form fresh melds from triples, then -// 2-natural + wild starters. Returns { actions, hand, usedIds }. -function buildMeldActions(state, seat, p) { - const t = team(state, seat); - const hand = state.players[seat].hand.slice(); - const used = new Set(); - const actions = []; - const remaining = () => hand.filter((c) => !used.has(c.id)); - const wilds = () => remaining().filter((c) => isWild(c)); - const take = (cards) => cards.forEach((c) => used.add(c.id)); +// ── Draw ───────────────────────────────────────────────────────────────────── +/** How much would taking the pile be worth to this seat? */ +function pileWorth(gs, seat, plan) { + const hand = gs.hands[seat]; + const team = teamOf(gs, seat); + const top = topDiscard(gs); + const rest = gs.discard.slice(0, -1); + const rankCount = {}; + for (const c of hand) if (isMeldable(c)) rankCount[c.rank] = (rankCount[c.rank] || 0) + 1; + let w = 25; // the top card goes straight onto a meld + if (!team.melded) w += 60; // and it unlocks the side's first meld + const tm = team.melds.find((m) => m.rank === top.rank); + if (tm && tm.cards.length + 1 + plan.ids.length >= CANASTA_SIZE && tm.cards.length < CANASTA_SIZE) w += 120; + for (const c of rest) { + if (isWild(c)) { w += 30; continue; } + if (isBlackThree(c)) { w -= 4; continue; } + if (team.melds.some((m) => m.rank === c.rank)) w += 14; + else if (rankCount[c.rank]) w += 10; + else w += 4; + } + // a fat hand is a liability if the other side might go out soon + const threat = threatOf(gs, oppTeam(seat)); + w -= threat * valueOf(rest) * 0.4; + return w; +} - // 1. Extend existing team melds with matching naturals. - for (const m of t.melds) { - const adds = remaining().filter((c) => c.rank === m.rank && !isWild(c)); - if (adds.length) { actions.push({ rank: m.rank, cardIds: adds.map((c) => c.id) }); take(adds); } +export function chooseDraw(gs, seat, skill = 3, rnd = Math.random) { + const p = prof(skill); + const { plan } = takeOption(gs, seat); + if (!gs.stock.length) { + if (mustTake(gs, seat)) return { type: 'take', plan: takeOption(gs, seat).plan }; + if (plan && pileWorth(gs, seat, plan) > 0) return { type: 'take', plan }; + return { type: 'pass' }; } - // 2. Fresh melds from ranks with three or more naturals. - let groups = groupNaturalsByRank(remaining()); - for (const rank of Object.keys(groups)) { - if (teamMeld(state, seat, rank)) continue; - const nat = groups[rank]; - if (nat.length >= 3) { actions.push({ rank, cardIds: nat.map((c) => c.id) }); take(nat); } + if (!plan) return { type: 'stock' }; + if (rnd() < p.miss) return { type: 'stock' }; + const w = pileWorth(gs, seat, plan) + jitter(p, rnd); + return w >= p.takeBar ? { type: 'take', plan } : { type: 'stock' }; +} + +// ── Melding ────────────────────────────────────────────────────────────────── +/** + * Try to lay the whole hand (bar at most one card to discard). Returns + * { groups, discard } or null. Wilds go where they are legal, canasta-bound + * melds first. + */ +function goOutPlan(gs, seat) { + const hand = gs.hands[seat]; + const team = teamOf(gs, seat); + const groups = new Map(); + const add = (rank, c) => { if (!groups.has(rank)) groups.set(rank, []); groups.get(rank).push(c); }; + const left = []; + const byRank = {}; + for (const c of hand) { + if (isWild(c)) continue; + (byRank[c.rank] ||= []).push(c); } - // 3. Two naturals + a spare wild → a starter meld (2 naturals ≥ 1 wild is legal). - groups = groupNaturalsByRank(remaining()); - for (const rank of Object.keys(groups)) { - if (teamMeld(state, seat, rank)) continue; - const nat = groups[rank]; - const spareWild = wilds(); - if (nat.length === 2 && spareWild.length >= 1 && (t.hasMelded || p.aggression > 0.4)) { - const cards = [...nat, spareWild[0]]; - actions.push({ rank, cardIds: cards.map((c) => c.id) }); take(cards); + for (const [rank, cards] of Object.entries(byRank)) { + if (rank === '3') { + if (cards.length >= 3) cards.forEach((c) => add('3', c)); else left.push(...cards); + continue; } + const existing = team.melds.find((m) => m.rank === rank); + if (existing || cards.length >= 2) cards.forEach((c) => add(rank, c)); + else left.push(...cards); } - - return { actions, hand, used }; + // Wilds: complete 2-natural starters first, then any meld with wild room. + const wilds = hand.filter(isWild).sort((a, b) => cardScore(a) - cardScore(b)); + const room = (rank) => { + if (rank === '3') return 0; + const ex = team.melds.find((m) => m.rank === rank)?.cards ?? []; + const g = groups.get(rank) ?? []; + return MAX_WILDS - wildsIn([...ex, ...g]); + }; + const needs = (rank) => { + const ex = team.melds.find((m) => m.rank === rank)?.cards ?? []; + return ex.length + (groups.get(rank)?.length ?? 0) < 3; + }; + for (const rank of [...groups.keys()]) { + while (needs(rank) && wilds.length && room(rank) > 0) add(rank, wilds.shift()); + } + for (const rank of [...groups.keys()]) { + while (wilds.length && room(rank) > 0) add(rank, wilds.shift()); + } + left.push(...wilds); + // naturals that couldn't make a meld: if a single one is left over it is the discard + for (const rank of [...groups.keys()]) if (needs(rank)) { left.push(...groups.get(rank)); groups.delete(rank); } + if (left.length > 1) return null; + const out = [...groups.entries()].map(([rank, cards]) => ({ rank, ids: cards.map((c) => c.id) })); + if (!out.length) return null; + return { groups: out, discard: left[0]?.id ?? null }; } -const actionsValue = (actions, hand) => - actions.reduce((s, a) => s + a.cardIds.reduce((ss, id) => ss + cardScore(hand.find((c) => c.id === id)), 0), 0); - -// Simulate the exact turn that would follow a pile-take (take → real chooseMelds -// → meld) and confirm it ends in a legal discard. Using the real chooseMelds path -// guarantees the prediction matches what the turn will actually do, so the AI -// never takes a pile it cannot legally meld off or that would empty its hand with -// no card left to discard (this engine ends a hand only via the final discard). -export function takeYieldsLegalTurn(state, seat, skill, plan) { - let sim = takeDiscard(state, plan); - const { actions } = chooseMelds(sim, seat, skill); - for (const a of actions) sim = meld(sim, a.rank, a.cardIds); - if (!meetsInitialMeld(sim, seat)) return false; // under the initial minimum - return sim.players[seat].hand.length >= 1; // a card remains to discard +/** Should the seat go out now (when it can)? */ +function wantsOut(gs, seat, p) { + if (!p.holdOut) return true; + const team = TEAM_OF_SEAT[seat]; + const threat = threatOf(gs, 1 - team); + if (threat >= 0.6 || gs.stock.length < 15) return true; + const lead = gs.scores[team] - gs.scores[1 - team]; + // partner's cards count against us when we go out + const partnerLoad = valueOf(gs.hands[PARTNER[seat]]); + // a meld one or two short of a canasta is worth staying in for + const close = gs.teams[team].melds.some((m) => !isCanasta(m) && m.cards.length >= 5); + if (close && threat < 0.35 && partnerLoad < 150) return false; + if (lead > 1500 && threat < 0.35 && partnerLoad < 60) return false; + return true; } -// ── Draw decision ────────────────────────────────────────────────────────────── -export function chooseDraw(state, seat, skill) { +/** A first meld: the exact solver, cheapest in wilds and cards. */ +function firstMeld(gs, seat) { + const sol = solveInitialMeld(gs.hands[seat], { need: minimumFor(gs, seat), keep: 2 }); + return sol ? sol.groups : null; +} + +/** + * The next meld action for the AI, or null when done melding. Called again + * after each action is applied (the scene animates them one by one). + */ +export function chooseMelds(gs, seat, skill = 3) { + if (gs.phase !== 'play' || gs.current !== seat) return null; const p = prof(skill); - const plan = takePlan(state, seat); - if (plan && takeYieldsLegalTurn(state, seat, skill, plan)) { - const t = team(state, seat); - const pileSize = state.discard.length; - const chance = !t.hasMelded - ? 0.6 + p.aggression * 0.4 - : ((pileSize >= 3 || plan.useMeld || pileSize >= 2) ? 0.5 + p.aggression * 0.5 : 0); - if (Math.random() < chance) return { type: 'take', plan }; - } - return { type: 'stock' }; -} + const team = teamOf(gs, seat); + const hand = gs.hands[seat]; -// ── Meld planning ────────────────────────────────────────────────────────────── -export function chooseMelds(state, seat, skill) { - const p = prof(skill); - const t = team(state, seat); - const { actions, hand, used } = buildMeldActions(state, seat, p); - const preValue = valueOfCards(state.meldedThisTurn); // captured from a pile-take this turn - const minNeeded = minimumMeld(t.score); - - // Initial-meld gate: if the team hasn't melded and even everything on the table - // plus these actions can't clear the minimum, lay nothing extra this turn. - if (!t.hasMelded && preValue + actionsValue(actions, hand) < minNeeded) { - return { actions: [] }; - } - - const remaining = () => hand.filter((c) => !used.has(c.id)); - const wilds = () => remaining().filter((c) => isWild(c)); - - // Push a near-complete meld up to a canasta with a wild or two. - if (p.pushCanasta) { - for (const a of actions) { - const m = teamMeld(state, seat, a.rank); - let nat = (m ? meldNaturals(m) : 0) + a.cardIds.filter((id) => !isWild(hand.find((c) => c.id === id))).length; - let wild = (m ? meldWilds(m) : 0) + a.cardIds.filter((id) => isWild(hand.find((c) => c.id === id))).length; - let total = nat + wild; - const avail = wilds(); - let i = 0; - while (total < CANASTA_SIZE && total >= CANASTA_SIZE - 2 && wild < MAX_WILDS_IN_MELD - && nat > wild && i < avail.length) { - a.cardIds.push(avail[i].id); used.add(avail[i].id); i++; wild++; total++; + // Going out? + if (hasGoOutCanastas(gs, seat) || hand.length <= 9) { + const plan = goOutPlan(gs, seat); + if (plan) { + const legal = !checkMelds({ ...gs, turn: { ...gs.turn, asked: gs.rules.askPartner ? 'yes' : gs.turn.asked } }, plan.groups).problem; + if (legal && gs.turn.asked !== 'no' && wantsOut(gs, seat, p)) { + if (gs.rules.askPartner && gs.turn.asked !== 'yes') return { ask: true }; + if (!checkMelds(gs, plan.groups).problem) return { groups: plan.groups, out: true }; } } } - // Will the team hold a canasta once these actions land? - const willHaveCanasta = () => { - if (t.melds.some(isCanasta)) return true; - for (const a of actions) { - const m = teamMeld(state, seat, a.rank); - if ((m ? m.cards.length : 0) + a.cardIds.length >= CANASTA_SIZE) return true; - } - return false; - }; - - // Keep at least one card to discard; only deplete to a single card when the - // team will then hold a canasta (a legal go-out). - if (!(willHaveCanasta() && remaining().length === 1)) { - while (actions.length && remaining().length < 2) { - const a = actions.pop(); - a.cardIds.forEach((id) => used.delete(id)); - } - if (!t.hasMelded && preValue + actionsValue(actions, hand) < minNeeded) return { actions: [] }; + if (!team.melded) { + const g = firstMeld(gs, seat); + if (g && !checkMelds(gs, g).problem) return { groups: g }; + return null; } - return { actions }; + const keepFloor = 2; + const room = () => hand.length - keepFloor; + if (room() <= 0) return null; + + // 1. naturals onto our melds + for (const m of team.melds) { + if (m.rank === '3') continue; + const adds = hand.filter((c) => c.rank === m.rank && !isWild(c)).slice(0, room()); + if (adds.length) { + const g = [{ rank: m.rank, ids: adds.map((c) => c.id) }]; + if (!checkMelds(gs, g).problem) return { groups: g }; + } + } + // 2. fresh melds of three or more naturals + const byRank = {}; + for (const c of hand) if (isMeldable(c)) (byRank[c.rank] ||= []).push(c); + for (const rank of MELD_RANKS) { + const cards = byRank[rank]; + if (!cards || cards.length < 3 || team.melds.some((m) => m.rank === rank)) continue; + const take = cards.slice(0, Math.min(cards.length, room())); + if (take.length < 3) continue; + const g = [{ rank, ids: take.map((c) => c.id) }]; + if (!checkMelds(gs, g).problem) return { groups: g }; + } + // 3. wilds to finish a canasta (5 or 6 cards → 7) + const wilds = hand.filter(isWild).sort((a, b) => cardScore(a) - cardScore(b)); + for (const m of team.melds) { + if (m.rank === '3' || isCanasta(m)) continue; + const short = CANASTA_SIZE - m.cards.length; + const free = MAX_WILDS - wildsIn(m.cards); + if (short >= 1 && short <= 2 && short <= free && short <= wilds.length && short <= room()) { + const g = [{ rank: m.rank, ids: wilds.slice(0, short).map((c) => c.id) }]; + if (!checkMelds(gs, g).problem) return { groups: g }; + } + } + // 4. a natural pair + a spare wild, when wilds are plentiful or the hand is fat + if (wilds.length && (wilds.length >= 2 || hand.length >= 14)) { + for (const rank of MELD_RANKS) { + const cards = byRank[rank]; + if (!cards || cards.length !== 2 || team.melds.some((m) => m.rank === rank) || room() < 3) continue; + const g = [{ rank, ids: [...cards.map((c) => c.id), wilds[0].id] }]; + if (!checkMelds(gs, g).problem) return { groups: g }; + } + } + return null; } -// ── Discard decision ─────────────────────────────────────────────────────────── -export function chooseDiscard(state, seat, skill) { +// ── Discard ────────────────────────────────────────────────────────────────── +/** + * Lower = better to throw. Returns [{ id, score, why }] for every card in hand. + * `why` is the coach's reason, phrased for the human. + */ +export function rateDiscards(gs, seat, skill = 5, rnd = () => 0.5) { const p = prof(skill); - const hand = state.players[seat].hand; - if (hand.length === 0) return null; - if (hand.length === 1) return hand[0].id; // forced (going out / last card) - + const hand = gs.hands[seat]; + const team = teamOf(gs, seat); + const nxt = nextSeat(seat); + const nTeam = teamOf(gs, nxt); + const pile = gs.discard.length; + const threat = threatOf(gs, oppTeam(seat)); + const known = p.memory ? knownRanks(gs, nxt) : {}; + const nxtThrew = p.memory ? new Set(gs.discards[nxt].map((id) => (id.startsWith('JK') ? 'JK' : id.slice(0, -2)))) : new Set(); const counts = {}; - for (const c of hand) if (!isWild(c)) counts[c.rank] = (counts[c.rank] || 0) + 1; + for (const c of hand) if (isMeldable(c)) counts[c.rank] = (counts[c.rank] || 0) + 1; + const nextFrozen = gs.frozen || !nTeam.melded || gs.rules.alwaysFrozen; + const wildCount = hand.filter(isWild).length; - // Lower score = better discard candidate. Scored once per card. - const score = (c) => { - if (isWild(c)) return 1000; // never throw wilds - if (teamMeld(state, seat, c.rank)) return 800; // could be laid off — keep - let s = (counts[c.rank] || 1) * 30; // keep pairs/triples - s += cardScore(c); // shed cheap cards first - if (isBlackThree(c)) s -= 18; // black threes block the pile - s += (Math.random() - 0.5) * 2 * p.noise * 12; // skill noise - return s; - }; - - let best = hand[0], bestS = score(best); - for (const c of hand) { const s = score(c); if (s < bestS) { best = c; bestS = s; } } - return best.id; + return hand.map((c) => { + let s = 0, why = ''; + if (isWild(c)) { + s = 260; + why = 'wild cards build canastas'; + // freeze a fat pile the next player could take + if (p.freeze && !gs.frozen && pile >= 6 && wildCount >= 2 && c.rank === '2') { + const theyCanTake = !nextFrozen || Object.keys(known).length > 0; + if (theyCanTake) { s = 18; why = `freeze the pile — it's ${pile} cards and ${'they'} are hungry for it`; } + } + } else if (isBlackThree(c)) { + s = 30 - pile * 2.5 * p.block; + why = pile >= 3 ? `a black three blocks the next player from the ${pile}-card pile` : 'black threes are no use to keep'; + } else { + const n = counts[c.rank] || 0; + const onMeld = team.melds.some((m) => m.rank === c.rank); + s = 40 + cardScore(c) * (0.5 + threat); + if (onMeld) { s += 90; why = 'it fits one of your melds'; } + else if (n >= 2) { s += 45 * Math.min(n, 3); why = `you hold ${n} ${rankWord(c.rank, 2)}`; } + else why = n === 1 ? `a lone ${rankWord(c.rank)}` : ''; + // danger: would the next player take the pile with it? + let danger = 0; + if (!nextFrozen && nTeam.melds.some((m) => m.rank === c.rank)) danger = 60 + pile * 6; + else if (known[c.rank] >= 2) danger = 50 + pile * 6; + else if (known[c.rank] === 1 && !nextFrozen) danger = 25 + pile * 3; + if (nxtThrew.has(c.rank)) danger *= 0.4; + // the same rank as the top card: they had their chance — a little safer + const top = topDiscard(gs); + if (top && top.rank === c.rank) danger *= 0.6; + s += danger * p.danger; + if (danger > 30 && p.danger >= 0.8) why = `the next player could use ${rankWord(c.rank, 2)} to take the pile`; + else if (!why) why = 'nothing builds on it'; + } + s += (rnd() - 0.5) * 2 * p.noise; + return { id: c.id, score: s, why }; + }); } + +export function chooseDiscard(gs, seat, skill = 3, rnd = Math.random) { + const hand = gs.hands[seat]; + if (hand.length === 1) return hand[0].id; + const r = rateDiscards(gs, seat, skill, rnd); + r.sort((a, b) => a.score - b.score); + return r[0].id; +} + +// ── Partner's answer ───────────────────────────────────────────────────────── +/** gs.phase === 'ask': should the partner say yes? */ +export function chooseAnswer(gs, skill = 3) { + const partner = gs.ask?.partner; + if (partner == null) return true; + const team = TEAM_OF_SEAT[partner]; + const hand = gs.hands[partner]; + const load = valueOf(hand); + const threat = threatOf(gs, 1 - team); + if (threat >= 0.6 || gs.stock.length < 12) return true; + // cards partner could still lay on our melds next turn + const layable = hand.filter((c) => isWild(c) || gs.teams[team].melds.some((m) => m.rank === c.rank)); + const close = gs.teams[team].melds.some((m) => !isCanasta(m) && m.cards.length >= 5); + if (skill >= 3 && close && load >= 60 && layable.length >= 2) return false; + return load < 120; +} + +// ── Coach (for the human, in Rosa's voice) ─────────────────────────────────── +const fixedRnd = () => 0.5; + +export function coachDraw(gs, seat = 0) { + const { plan, problem } = takeOption(gs, seat); + const pick = chooseDraw(gs, seat, 5, fixedRnd); + const top = topDiscard(gs); + if (pick.type === 'take') { + const n = gs.discard.length; + const team = teamOf(gs, seat); + let text = `Take the pile, dear — ${n} card${n === 1 ? '' : 's'}`; + if (!team.melded) text += ` and it puts our first meld down`; + else if (mustTake(gs, seat)) text = `The stock's gone and that ${rankWord(top.rank)} fits our meld — we must take it`; + else if (n >= 5) text += '. A pile that size builds canastas'; + return { type: 'take', plan: pick.plan, text }; + } + if (pick.type === 'pass') return { type: 'pass', text: 'Nothing for us there — let the hand end' }; + if (plan) return { type: 'stock', text: `We could take it, but ${gs.discard.length} cards of little use would only weigh us down. Draw.` }; + return { type: 'stock', text: problem && top ? `Draw from the stock — ${problem.charAt(0).toLowerCase()}${problem.slice(1)}` : 'Draw from the stock' }; +} + +export function coachMelds(gs, seat = 0) { + const act = chooseMelds(gs, seat, 5); + if (!act) return null; + if (act.ask) return { ask: true, text: 'You can go out — ask me first, dear' }; + const g = act.groups; + const describe = (grp) => { + const cards = grp.ids.map((id) => gs.hands[seat].find((c) => c.id === id)); + const existing = teamOf(gs, seat).melds.some((m) => m.rank === grp.rank); + const nat = naturalsIn(cards), wild = cards.length - nat; + const what = nat && wild ? `${nat} ${rankWord(grp.rank, nat)} and ${wild} wild` : nat ? `${nat} ${rankWord(grp.rank, nat)}` : `${wild} wild card${wild === 1 ? '' : 's'}`; + return existing ? `add ${what} to our ${rankWord(grp.rank, 2)}` : `meld ${what}`; + }; + let text; + if (act.out) text = `Lay it all down and go out: ${g.map(describe).join(', ')}`; + else if (!teamOf(gs, seat).melded) { + const v = g.reduce((s, grp) => s + valueOf(grp.ids.map((id) => gs.hands[seat].find((c) => c.id === id))), 0); + text = `That's our first meld — ${g.map(describe).join(' and ')} makes ${v}`; + } else text = g.map(describe).join(', ').replace(/^./, (m) => m.toUpperCase()); + return { groups: g, text }; +} + +export function coachDiscard(gs, seat = 0) { + if (gs.phase !== 'play') return null; + const hand = gs.hands[seat]; + if (hand.length === 1) return { id: hand[0].id, text: 'Throw your last card and go out!' }; + const r = rateDiscards(gs, seat, 5, fixedRnd).sort((a, b) => a.score - b.score); + const c = hand.find((x) => x.id === r[0].id); + return { id: c.id, text: `Throw the ${cardName(c)} — ${r[0].why}` }; +} + +/** Short Rosa line for table chatter (seat 2's partner remarks). */ +export function describeRank(rank) { return rankLabel(rank); } diff --git a/src/games/canasta/CanastaArt.js b/src/games/canasta/CanastaArt.js new file mode 100644 index 0000000..a3fec79 --- /dev/null +++ b/src/games/canasta/CanastaArt.js @@ -0,0 +1,511 @@ +// Canasta art — "Rosa's Parlor", a 1950s living room on a Sunday evening. +// Baked once per page load into canvas textures (no image files). Card faces +// are the shared casino deck ('casino-cards', keyed 'As', 'Td', 'JK', …). +// +// can-room teal atomic-starburst wallpaper, a picture window at dusk with +// sheer curtains, a brass floor lamp (left), a blond-wood hi-fi +// console (right); a mahogany card table with a peacock-teal felt +// cover, a lace doily under the piles, a coffee cup on its saucer +// and a dish of ribbon candy +// can-back card back: a coral-and-mustard starburst on deep teal +// can-basket the canasta seal — a woven basket ("canasta" is Spanish for basket) +// can-record a spinning LP for the hi-fi +// can-clock the sunburst wall clock face (hands are drawn live) + +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, L } from './CanastaTable.js'; + +const CW = CARD_TEX.W, CH = CARD_TEX.H; +const SERIF = 'Georgia, "Times New Roman", serif'; +const MUSTARD = '#e3b448'; +const CORAL = '#f0806a'; +const TEAL = '#1d5a5c'; + +export const LAMP = { x: 118, y: 236 }; // the lamp shade (left wall) +export const HIFI = { x: 1822, y: 292 }; // the turntable on the console (right wall) +export const CLOCK = { x: 1826, y: 50, r: 40 }; +export const COFFEE = (() => { const p = T.P.project(-0.83, 0.74); return { x: p.x, y: p.y, s: p.s }; })(); +export const CANDY = (() => { const p = T.P.project(0.84, 0.74); return { x: p.x, y: p.y, s: p.s }; })(); + +function seeded(seed) { + let s = seed; + return () => { s = (s * 16807) % 2147483647; return s / 2147483647; }; +} + +/** An atomic starburst: n spikes of alternating length. */ +function starburst(ctx, x, y, r, n, color, width = 2) { + ctx.save(); + ctx.strokeStyle = color; + ctx.lineWidth = width; + ctx.lineCap = 'round'; + for (let i = 0; i < n; i++) { + const a = (i / n) * Math.PI * 2; + const rr2 = i % 2 ? r * 0.55 : r; + ctx.beginPath(); + ctx.moveTo(x + Math.cos(a) * r * 0.12, y + Math.sin(a) * r * 0.12); + ctx.lineTo(x + Math.cos(a) * rr2, y + Math.sin(a) * rr2); + ctx.stroke(); + ctx.beginPath(); + ctx.arc(x + Math.cos(a) * rr2, y + Math.sin(a) * rr2, width * 0.9, 0, Math.PI * 2); + ctx.fillStyle = color; + ctx.fill(); + } + ctx.restore(); +} + +/** A mid-century boomerang. */ +function boomerang(ctx, x, y, s, rot, color) { + ctx.save(); + ctx.translate(x, y); + ctx.rotate(rot); + ctx.scale(s, s); + ctx.beginPath(); + ctx.moveTo(-22, 6); + ctx.quadraticCurveTo(-4, -14, 0, -2); + ctx.quadraticCurveTo(6, -16, 24, 4); + ctx.quadraticCurveTo(6, -4, 0, 8); + ctx.quadraticCurveTo(-6, -2, -22, 6); + ctx.fillStyle = color; + ctx.fill(); + ctx.restore(); +} + +// ── The room ───────────────────────────────────────────────────────────────── +function wallpaper(ctx) { + const g = ctx.createLinearGradient(0, 0, 0, H); + g.addColorStop(0, '#1b3c3e'); + g.addColorStop(1, '#10262a'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + const rnd = seeded(29); + for (let y = 18; y < H; y += 92) { + for (let x = (Math.floor(y / 92) % 2) * 70; x < W + 70; x += 140) { + starburst(ctx, x + rnd() * 8, y + rnd() * 8, 15, 8, 'rgba(227,180,72,0.22)', 1.6); + boomerang(ctx, x + 70, y + 46, 0.8, rnd() * 6, 'rgba(240,128,106,0.13)'); + } + } + ctx.fillStyle = noisePattern(ctx, 128, 14); + ctx.fillRect(0, 0, W, H); +} + +function windowAtDusk(ctx) { + const x0 = 440, x1 = 740, y1 = 96; + // the sky: dusk — violet into tangerine at the horizon + const sky = ctx.createLinearGradient(0, 0, 0, y1); + sky.addColorStop(0, '#3a2a5a'); sky.addColorStop(0.6, '#a0506a'); sky.addColorStop(1, '#f0a060'); + ctx.fillStyle = sky; + ctx.fillRect(x0, 0, x1 - x0, y1); + // a rooftop and a TV aerial against it + ctx.fillStyle = '#2a1a2a'; + poly(ctx, [{ x: x0, y: y1 }, { x: x0 + 60, y: 70 }, { x: x0 + 150, y: 70 }, { x: x0 + 190, y: y1 }]); + ctx.fill(); + ctx.strokeStyle = '#2a1a2a'; + ctx.lineWidth = 2; + ctx.beginPath(); ctx.moveTo(x0 + 110, 70); ctx.lineTo(x0 + 110, 30); ctx.stroke(); + for (const [dy, w] of [[34, 30], [42, 22], [50, 14]]) { ctx.beginPath(); ctx.moveTo(x0 + 110 - w, dy); ctx.lineTo(x0 + 110 + w, dy); ctx.stroke(); } + // the evening star + ctx.fillStyle = 'rgba(255,250,220,0.9)'; + ctx.beginPath(); ctx.arc(x1 - 60, 22, 2.2, 0, Math.PI * 2); ctx.fill(); + // venetian blind half drawn, mullions, frame + ctx.fillStyle = 'rgba(240,230,200,0.85)'; + for (let y = 0; y < 26; y += 6) ctx.fillRect(x0, y, x1 - x0, 4); + ctx.fillStyle = '#e8dcc0'; + ctx.fillRect(x0 - 8, 0, 8, y1 + 8); ctx.fillRect(x1, 0, 8, y1 + 8); + ctx.fillRect((x0 + x1) / 2 - 3, 0, 6, y1); + // sheer curtains, gathered + for (const side of [-1, 1]) { + const cx = side < 0 ? x0 - 20 : x1 + 20; + for (let i = 0; i < 7; i++) { + const g = ctx.createLinearGradient(cx - 30, 0, cx + 30, 0); + g.addColorStop(0, 'rgba(250,240,220,0.05)'); g.addColorStop(0.5, 'rgba(250,240,220,0.32)'); g.addColorStop(1, 'rgba(250,240,220,0.05)'); + ctx.fillStyle = g; + ctx.fillRect(cx - 34 + i * 9 * side, 0, 22, y1 + 30); + } + } + // the glow it throws into the room + const glow = ctx.createRadialGradient((x0 + x1) / 2, 60, 10, (x0 + x1) / 2, 60, 360); + glow.addColorStop(0, 'rgba(255,170,120,0.18)'); glow.addColorStop(1, 'rgba(255,170,120,0)'); + ctx.fillStyle = glow; + ctx.fillRect(0, 0, 1200, 500); +} + +function floorLamp(ctx) { + const { x, y } = LAMP; + // brass pole down to the floor + const pole = ctx.createLinearGradient(x - 4, 0, x + 4, 0); + pole.addColorStop(0, '#7a5a20'); pole.addColorStop(0.5, '#f0d080'); pole.addColorStop(1, '#6a4a18'); + ctx.fillStyle = pole; + ctx.fillRect(x - 3, y + 30, 6, H - y); + // a tapered drum shade (cream linen, lit from within) + const sh = ctx.createLinearGradient(x - 70, 0, x + 70, 0); + sh.addColorStop(0, '#c8a870'); sh.addColorStop(0.5, '#fff0c8'); sh.addColorStop(1, '#c0a068'); + poly(ctx, [{ x: x - 46, y: y - 40 }, { x: x + 46, y: y - 40 }, { x: x + 72, y: y + 34 }, { x: x - 72, y: y + 34 }]); + ctx.fillStyle = sh; + ctx.fill(); + ctx.strokeStyle = '#8a6a30'; + ctx.lineWidth = 2; + ctx.stroke(); + ctx.fillStyle = 'rgba(255,240,200,0.55)'; + ctx.beginPath(); ctx.ellipse(x, y + 34, 72, 9, 0, 0, Math.PI * 2); ctx.fill(); + const g = ctx.createRadialGradient(x, y, 20, x, y, 330); + g.addColorStop(0, 'rgba(255,220,150,0.3)'); g.addColorStop(1, 'rgba(255,220,150,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, 500, 700); +} + +function hifi(ctx) { + const x0 = 1748, x1 = W + 10, y0 = HIFI.y - 26, y1 = HIFI.y + 110; + // blond wood cabinet on tapered legs + const wood = ctx.createLinearGradient(0, y0, 0, y1); + wood.addColorStop(0, '#d8a868'); wood.addColorStop(1, '#9a6a34'); + ctx.fillStyle = wood; + ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + ctx.fillStyle = 'rgba(0,0,0,0.25)'; + ctx.fillRect(x0, y0, x1 - x0, 5); + // speaker cloth with gold threads + ctx.fillStyle = '#5a4430'; + ctx.fillRect(x0 + 14, y0 + 52, x1 - x0 - 28, y1 - y0 - 66); + ctx.strokeStyle = 'rgba(227,180,72,0.35)'; + ctx.lineWidth = 1; + for (let x = x0 + 18; x < x1 - 14; x += 7) { ctx.beginPath(); ctx.moveTo(x, y0 + 54); ctx.lineTo(x, y1 - 16); ctx.stroke(); } + // turntable well (the record is a live sprite) + ctx.fillStyle = '#2a1c10'; + ctx.beginPath(); ctx.ellipse(HIFI.x, HIFI.y, 46, 18, 0, 0, Math.PI * 2); ctx.fill(); + // legs + ctx.strokeStyle = '#6a4420'; + ctx.lineWidth = 6; + for (const lx of [x0 + 20, x1 - 30]) { ctx.beginPath(); ctx.moveTo(lx, y1); ctx.lineTo(lx + (lx < 1820 ? -8 : 8), y1 + 46); ctx.stroke(); } +} + +function wall(ctx) { + wallpaper(ctx); + windowAtDusk(ctx); + floorLamp(ctx); + hifi(ctx); + // the clock's brass sunburst (its face is a live sprite) + starburst(ctx, CLOCK.x, CLOCK.y, CLOCK.r + 30, 24, 'rgba(227,190,100,0.9)', 2.6); + // evening: a soft dimming over the walls + ctx.fillStyle = 'rgba(8,10,14,0.22)'; + ctx.fillRect(0, 0, W, H); + // shag carpet below the table + const f = ctx.createLinearGradient(0, 990, 0, H); + f.addColorStop(0, '#6a3a1a'); f.addColorStop(1, '#3a1e0c'); + ctx.fillStyle = f; + ctx.fillRect(0, 990, W, H - 990); + ctx.fillStyle = noisePattern(ctx, 96, 40); + ctx.fillRect(0, 990, W, H - 990); +} + +function front(ctx, Tb) { + frontBands(ctx, Tb, ['#7a2e1e', '#682618', '#561e12', '#44160c', '#300e06'], { grooves: [0.4, 0.75] }); +} + +function rim(ctx, Tb) { + rimBand(ctx, Tb, { base: '#6e2a18', dark: '#2a0c04', light: '#d0805a', grain: ['#200802', '#e8a070'], gloss: 1.5 }); + ring(ctx, Tb, Tb.feltK + 0.012, 2.4, 'rgba(227,190,110,0.7)'); +} + +function felt(ctx, Tb) { + ctx.fillStyle = '#1c5458'; + ctx.fillRect(0, 0, W, H); + ctx.fillStyle = noisePattern(ctx, 200, 24); + ctx.fillRect(0, 0, W, H); + // a faint woven diamond in the felt + ctx.strokeStyle = 'rgba(255,255,255,0.025)'; + ctx.lineWidth = 1; + for (let u = -1.2; u < 1.2; u += 0.06) { + const a = Tb.P.project(u, 0), b = Tb.P.project(u + 0.6, 1); + ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke(); + const c = Tb.P.project(u, 1), d = Tb.P.project(u + 0.6, 0); + ctx.beginPath(); ctx.moveTo(c.x, c.y); ctx.lineTo(d.x, d.y); ctx.stroke(); + } + ring(ctx, Tb, Tb.feltK * 0.95, 2.2, 'rgba(227,180,72,0.45)'); + ring(ctx, Tb, Tb.feltK * 0.935, 1, 'rgba(227,180,72,0.3)'); + lampPool(ctx, Tb, { color: '255,214,160', alpha: 0.3, vignette: 0.55, at: { u: 0, v: 0.46 } }); + // the floor lamp warms the left of the table + const f = Tb.P.project(-1.1, 0.25); + const g = ctx.createRadialGradient(f.x, f.y, 20, f.x, f.y, 760); + g.addColorStop(0, 'rgba(255,200,120,0.16)'); g.addColorStop(1, 'rgba(255,200,120,0)'); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + rimShadow(ctx, Tb, 0.4); +} + +/** A crocheted lace doily lying flat under the piles. */ +function doily(ctx) { + const cu = 0, cv = 0.445; + const ru = 0.26, rv = 0.15; + const P = T.P; + const pt = (a, k) => P.project(cu + Math.cos(a) * ru * k, cv + Math.sin(a) * rv * k); + ctx.save(); + // scalloped edge + ctx.beginPath(); + const n = 72; + for (let i = 0; i <= n; i++) { + const a = (i / n) * Math.PI * 2; + const k = 1 + 0.045 * Math.cos(a * 24); + const p = pt(a, k); + if (i) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); + } + ctx.closePath(); + ctx.shadowColor = 'rgba(0,0,0,0.35)'; + ctx.shadowBlur = 10; + ctx.shadowOffsetY = 3; + ctx.fillStyle = 'rgba(246,238,218,0.2)'; + ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.lineWidth = 2; + ctx.strokeStyle = 'rgba(250,244,228,0.55)'; + ctx.stroke(); + // rings of lace holes + for (const [k, holes, r] of [[0.9, 60, 3.2], [0.76, 48, 2.6], [0.6, 36, 2.2], [0.42, 24, 2]]) { + for (let i = 0; i < holes; i++) { + const a = (i / holes) * Math.PI * 2; + const p = pt(a, k); + ctx.beginPath(); + ctx.ellipse(p.x, p.y, r * p.s * 1.4, r * p.s * 0.8, 0, 0, Math.PI * 2); + ctx.strokeStyle = 'rgba(250,244,228,0.45)'; + ctx.lineWidth = 1.2; + ctx.stroke(); + } + ctx.beginPath(); + for (let i = 0; i <= 90; i++) { + const p = pt((i / 90) * Math.PI * 2, k + 0.06); + if (i) ctx.lineTo(p.x, p.y); else ctx.moveTo(p.x, p.y); + } + ctx.strokeStyle = 'rgba(250,244,228,0.22)'; + ctx.lineWidth = 1; + ctx.stroke(); + } + // petal spokes + for (let i = 0; i < 12; i++) { + const a = (i / 12) * Math.PI * 2; + const p0 = pt(a, 0.3), p1 = pt(a, 0.9); + ctx.beginPath(); ctx.moveTo(p0.x, p0.y); ctx.lineTo(p1.x, p1.y); + ctx.strokeStyle = 'rgba(250,244,228,0.16)'; + ctx.lineWidth = 1; + ctx.stroke(); + } + ctx.restore(); +} + +function coffeeCup(ctx) { + const { x, y, s } = COFFEE; + ctx.save(); + ctx.translate(x, y); + ctx.scale(s, s); + // saucer + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 5; + ctx.beginPath(); ctx.ellipse(0, 8, 70, 28, 0, 0, Math.PI * 2); + ctx.fillStyle = '#f4ecdc'; ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.strokeStyle = MUSTARD; ctx.lineWidth = 2; + ctx.beginPath(); ctx.ellipse(0, 8, 62, 24, 0, 0, Math.PI * 2); ctx.stroke(); + // cup + const g = ctx.createLinearGradient(-38, 0, 38, 0); + g.addColorStop(0, '#d8cfbe'); g.addColorStop(0.45, '#ffffff'); g.addColorStop(1, '#c8bca8'); + ctx.beginPath(); + ctx.moveTo(-36, -30); ctx.lineTo(36, -30); ctx.quadraticCurveTo(32, 14, 0, 16); ctx.quadraticCurveTo(-32, 14, -36, -30); + ctx.fillStyle = g; ctx.fill(); + ctx.strokeStyle = '#b8a888'; ctx.lineWidth = 1.5; ctx.stroke(); + // coral band + ctx.strokeStyle = CORAL; ctx.lineWidth = 4; + ctx.beginPath(); ctx.moveTo(-34, -20); ctx.quadraticCurveTo(0, -14, 34, -20); ctx.stroke(); + // handle + ctx.strokeStyle = '#e8e0d0'; ctx.lineWidth = 6; + ctx.beginPath(); ctx.arc(42, -10, 12, -1.4, 1.4); ctx.stroke(); + // coffee + ctx.beginPath(); ctx.ellipse(0, -30, 35, 9, 0, 0, Math.PI * 2); + ctx.fillStyle = '#e8e0d0'; ctx.fill(); + ctx.beginPath(); ctx.ellipse(0, -29, 30, 7, 0, 0, Math.PI * 2); + ctx.fillStyle = '#3a200e'; ctx.fill(); + ctx.restore(); +} + +function candyDish(ctx) { + const { x, y, s } = CANDY; + ctx.save(); + ctx.translate(x, y); + ctx.scale(s, s); + ctx.shadowColor = 'rgba(0,0,0,0.45)'; ctx.shadowBlur = 12; ctx.shadowOffsetY = 5; + ctx.beginPath(); ctx.ellipse(0, 0, 78, 34, 0, 0, Math.PI * 2); + const g = ctx.createRadialGradient(-20, -10, 4, 0, 0, 80); + g.addColorStop(0, 'rgba(200,240,230,0.9)'); g.addColorStop(1, 'rgba(90,170,160,0.75)'); + ctx.fillStyle = g; ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.strokeStyle = 'rgba(255,255,255,0.6)'; ctx.lineWidth = 2; ctx.stroke(); + // ribbon candy: little coloured loops + const rnd = seeded(7); + const cols = ['#f04a5a', '#f0c040', '#5ac0f0', '#7ae07a', '#f08ad0']; + for (let i = 0; i < 16; i++) { + const a = rnd() * Math.PI * 2, r = rnd() * 50; + const cx = Math.cos(a) * r, cy = Math.sin(a) * r * 0.38 - 6; + ctx.save(); + ctx.translate(cx, cy); + ctx.rotate(rnd() * 3); + ctx.strokeStyle = cols[i % cols.length]; + ctx.lineWidth = 3.4; + ctx.beginPath(); + for (let k = 0; k < 3; k++) ctx.ellipse(-8 + k * 8, 0, 4, 7, 0, 0, Math.PI * 2); + ctx.stroke(); + ctx.restore(); + } + ctx.restore(); +} + +function onTop(ctx) { + doily(ctx); + pileSpot(ctx, L.stock, 'STOCK', { color: '240,226,190', alpha: 0.5 }); + pileSpot(ctx, L.discard, 'DISCARD', { color: '240,226,190', alpha: 0.5 }); + coffeeCup(ctx); + candyDish(ctx); +} + +// ── Card back: an atomic starburst ─────────────────────────────────────────── +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, '#236a6c'); g.addColorStop(1, '#0e3436'); + 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 = MUSTARD; ctx.stroke(); + ctx.save(); + rr(ctx, 14, 14, CW - 28, CH - 28, 10); + ctx.clip(); + const rnd = seeded(5); + for (let i = 0; i < 18; i++) boomerang(ctx, rnd() * CW, rnd() * CH, 0.7, rnd() * 6, 'rgba(240,128,106,0.18)'); + for (let i = 0; i < 14; i++) starburst(ctx, rnd() * CW, rnd() * CH, 7, 8, 'rgba(227,180,72,0.25)', 1.2); + ctx.restore(); + const cx = CW / 2, cy = CH / 2; + // the big starburst medallion + ctx.beginPath(); ctx.arc(cx, cy, 54, 0, Math.PI * 2); + ctx.fillStyle = '#0e3436'; ctx.fill(); + ctx.lineWidth = 3; ctx.strokeStyle = MUSTARD; ctx.stroke(); + starburst(ctx, cx, cy, 48, 16, CORAL, 3); + starburst(ctx, cx, cy, 30, 12, MUSTARD, 2.2); + ctx.beginPath(); ctx.arc(cx, cy, 9, 0, Math.PI * 2); + ctx.fillStyle = '#f4ecdc'; ctx.fill(); + ctx.fillStyle = MUSTARD; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.font = `italic bold 15px ${SERIF}`; + ctx.fillText("Rosa's", cx, 34); + ctx.font = `bold 12px ${SERIF}`; + ctx.fillText('PARLOR', cx, CH - 32); + scene.textures.addCanvas('can-back', c); +} + +// ── The canasta seal: a woven basket ───────────────────────────────────────── +function bakeBasket(scene) { + const S = 280; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + const cx = S / 2, cy = S / 2; + ctx.shadowColor = 'rgba(0,0,0,0.55)'; ctx.shadowBlur = 16; ctx.shadowOffsetY = 5; + ctx.beginPath(); ctx.arc(cx, cy, 120, 0, Math.PI * 2); + ctx.fillStyle = '#f2e6c8'; ctx.fill(); + ctx.shadowColor = 'transparent'; + ctx.lineWidth = 8; ctx.strokeStyle = MUSTARD; ctx.stroke(); + ctx.beginPath(); ctx.arc(cx, cy, 108, 0, Math.PI * 2); + ctx.lineWidth = 2; ctx.strokeStyle = TEAL; ctx.stroke(); + // basket body (woven) + ctx.save(); + ctx.beginPath(); + ctx.moveTo(cx - 70, cy - 8); ctx.lineTo(cx + 70, cy - 8); ctx.lineTo(cx + 52, cy + 62); ctx.lineTo(cx - 52, cy + 62); ctx.closePath(); + ctx.clip(); + ctx.fillStyle = '#b07a3a'; + ctx.fillRect(cx - 80, cy - 10, 160, 80); + for (let row = 0; row < 6; row++) { + for (let col = 0; col < 10; col++) { + const x = cx - 80 + col * 17 + (row % 2) * 8, y = cy - 8 + row * 12; + ctx.fillStyle = (row + col) % 2 ? '#d8a058' : '#8a5a24'; + rr(ctx, x, y, 15, 10, 4); + ctx.fill(); + } + } + ctx.restore(); + // rim and handle + ctx.lineWidth = 8; ctx.strokeStyle = '#7a4a1a'; + ctx.beginPath(); ctx.moveTo(cx - 74, cy - 8); ctx.lineTo(cx + 74, cy - 8); ctx.stroke(); + ctx.lineWidth = 7; + ctx.beginPath(); ctx.ellipse(cx, cy - 8, 52, 56, 0, Math.PI, 0); ctx.stroke(); + // three fanned cards peeking out + for (let i = 0; i < 3; i++) { + ctx.save(); + ctx.translate(cx - 22 + i * 22, cy - 20); + ctx.rotate((i - 1) * 0.32); + rr(ctx, -14, -26, 28, 38, 4); + ctx.fillStyle = '#fffaf0'; ctx.fill(); + ctx.strokeStyle = '#8a7a5a'; ctx.lineWidth = 1.2; ctx.stroke(); + ctx.fillStyle = i === 1 ? '#1a1208' : '#c0392b'; + ctx.font = 'bold 14px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + ctx.fillText(['♥', '♠', '♦'][i], 0, -10); + ctx.restore(); + } + ctx.fillStyle = TEAL; + ctx.font = `bold 18px ${SERIF}`; + ctx.textAlign = 'center'; + ctx.fillText('★ CANASTA ★', cx, cy + 92); + scene.textures.addCanvas('can-basket', c); +} + +function bakeRecord(scene) { + const S = 96; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + const cx = S / 2; + ctx.beginPath(); ctx.arc(cx, cx, 46, 0, Math.PI * 2); + ctx.fillStyle = '#111'; ctx.fill(); + for (let r = 18; r < 46; r += 3) { + ctx.beginPath(); ctx.arc(cx, cx, r, 0, Math.PI * 2); + ctx.strokeStyle = r % 2 ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.12)'; ctx.lineWidth = 1; ctx.stroke(); + } + // a highlight wedge so the spin reads + ctx.beginPath(); ctx.moveTo(cx, cx); ctx.arc(cx, cx, 45, -0.5, -0.1); ctx.closePath(); + ctx.fillStyle = 'rgba(255,255,255,0.12)'; ctx.fill(); + ctx.beginPath(); ctx.arc(cx, cx, 15, 0, Math.PI * 2); + ctx.fillStyle = CORAL; ctx.fill(); + ctx.beginPath(); ctx.arc(cx + 4, cx - 4, 4, 0, Math.PI * 2); + ctx.fillStyle = MUSTARD; ctx.fill(); + ctx.beginPath(); ctx.arc(cx, cx, 2, 0, Math.PI * 2); + ctx.fillStyle = '#111'; ctx.fill(); + scene.textures.addCanvas('can-record', c); +} + +function bakeClock(scene) { + const S = CLOCK.r * 2 + 8; + const c = canvas(S, S); + const ctx = c.getContext('2d'); + const cx = S / 2; + ctx.beginPath(); ctx.arc(cx, cx, CLOCK.r, 0, Math.PI * 2); + const g = ctx.createRadialGradient(cx - 10, cx - 10, 4, cx, cx, CLOCK.r); + g.addColorStop(0, '#fff8e6'); g.addColorStop(1, '#e0d0a8'); + ctx.fillStyle = g; ctx.fill(); + ctx.lineWidth = 4; ctx.strokeStyle = '#c8a050'; ctx.stroke(); + for (let i = 0; i < 12; i++) { + const a = (i / 12) * Math.PI * 2; + ctx.beginPath(); + ctx.arc(cx + Math.cos(a) * (CLOCK.r - 8), cx + Math.sin(a) * (CLOCK.r - 8), i % 3 ? 1.8 : 3, 0, Math.PI * 2); + ctx.fillStyle = TEAL; ctx.fill(); + } + scene.textures.addCanvas('can-clock', c); +} + +export async function prepareCanastaArt(scene) { + await prepareCasinoArt(scene); + if (!scene.textures.exists('can-back')) bakeBack(scene); + if (!scene.textures.exists('can-basket')) bakeBasket(scene); + if (!scene.textures.exists('can-record')) bakeRecord(scene); + if (!scene.textures.exists('can-clock')) bakeClock(scene); + return bakeRoom(scene, 'can-room', T, { wall, front, rim, top: felt, onTop }); +} + +export { W, H }; diff --git a/src/games/canasta/CanastaData.js b/src/games/canasta/CanastaData.js index dfca194..378c5ab 100644 --- a/src/games/canasta/CanastaData.js +++ b/src/games/canasta/CanastaData.js @@ -1,132 +1,243 @@ -// Canasta — static data, scoring helpers and table geometry. No Phaser, no -// state: imported by the logic engine, the AI, the Phaser scene and the headless -// verify harness alike. +// 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: two decks + four jokers (108 cards), four players -// in two fixed partnerships (seats 0 & 2 vs seats 1 & 3), race to 5000 points. - -import { SUITS, RANKS, Card } from '../cards/Deck.js'; - -export { Card }; +// 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; -// ── Rules ──────────────────────────────────────────────────────────────────── -export const DECKS = 2; // standard decks in the shoe -export const JOKERS = 4; // jokers added on top → 108 cards total export const PLAYER_COUNT = 4; -export const INITIAL_HAND = 11; // cards dealt to each player -export const WIN_SCORE = 5000; // cumulative team score that ends the match -export const CANASTA_SIZE = 7; // a meld of seven cards is a canasta -export const MAX_WILDS_IN_MELD = 3; // a meld may hold at most three wild cards -export const MIN_MELD_CARDS = 3; // a fresh meld is at least three cards +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; -// Bonus values (added to a team's hand score). -export const NATURAL_CANASTA = 500; // a canasta with no wild cards (pure) -export const MIXED_CANASTA = 300; // a canasta containing 1–3 wild cards -export const RED_THREE = 100; // each red three laid out -export const ALL_RED_THREES = 800; // a team holding all four (200 each) -export const GO_OUT = 100; // bonus for the player who goes out -export const CONCEALED_GO_OUT = 200; // going out in one turn having never melded +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]; -// ── Card classifiers ───────────────────────────────────────────────────────── -/** Wild card: a joker or any two. */ -export function isWild(card) { - return card.rank === 'JK' || card.rank === '2'; -} -/** Red three — a bonus card, laid out immediately, never melded or discarded. */ -export function isRedThree(card) { - return card.rank === '3' && (card.suit === 'h' || card.suit === 'd'); -} -/** Black three — only ever melded when going out (omitted here); blocks the pile. */ -export function isBlackThree(card) { - return card.rank === '3' && (card.suit === 's' || card.suit === 'c'); -} -/** A natural card that may form/extend a rank meld (4..A, not 3, not wild). */ -export function isMeldable(card) { - return !isWild(card) && card.rank !== '3'; +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; } -/** - * Point value of a single card, used for melds, the initial-meld minimum and - * the deduction for cards left in hand. Red threes score as a separate bonus. - */ -export function cardScore(card) { - if (card.rank === 'JK') return 50; // joker - if (card.rank === '2' || card.rank === 'A') return 20; - if (card.rank === '3') return 5; // (black threes; red threes bonus-only) - const v = card.value; // 4..K → 4..13 - if (v >= 8) return 10; // 8,9,10,J,Q,K - return 5; // 4,5,6,7 -} +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}`); -/** Minimum total card value required for a team's very first meld of the game. */ -export function minimumMeld(teamScore) { - if (teamScore < 0) return 15; - if (teamScore < 1500) return 50; - if (teamScore < 3000) return 90; +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; } -// ── Theme (luxe casino card room) ───────────────────────────────────────────── -export const THEME = { - feltTop: 0x1c6b3a, // emerald baize, lit centre - feltMid: 0x0f4a27, // mid green - feltEdge: 0x062c16, // deep green near the rail - rail: 0x4a1410, // burgundy leather rail - railHi: 0x6e201a, // lit burgundy - railDark: 0x2c0b09, // rail shadow - brass: 0xc9a227, // brass trim - brassHi: 0xf0d77a, // brass highlight - gold: 0xd4a017, - cardFace: 0xfbf6e7, - cardBack: 0x3a2a6b, // deep indigo card back - cardBackHi: 0x6c5bb0, - redThree: 0xe0b24a, // glow for red threes - team0: 0xf0d77a, // your team accent (gold) - team1: 0xe9e1cf, // their team accent (ivory) - text: 0xf2ead8, - suitRed: '#c0392b', - suitBlk: '#1a1208', - jokerHex: '#7b3fb0', -}; +// ── 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; -// ── Table geometry ──────────────────────────────────────────────────────────── -// Four seats around the felt. Seat 0 = South (human), 1 = West, 2 = North -// (human's partner), 3 = East. Returns the anchors the scene needs to lay out -// hands, the central stock/discard and the two team meld strips. -export function buildTableLayout(rect) { - const { x, y, w, h } = rect; - const cx = x + w / 2; - const cy = y + h / 2; - return { - cx, cy, - // hand anchors (centre of each player's fanned hand) - seats: { - 0: { x: cx, y: y + h - 96, dir: 'h', label: { x: x + 40, y: y + h - 150, align: 'left' } }, - 1: { x: x + 150, y: cy - 40, dir: 'v', label: { x: x + 40, y: cy - 220, align: 'left' } }, - 2: { x: cx, y: y + 96, dir: 'h', label: { x: x + 40, y: y + 40, align: 'left' } }, - 3: { x: x + w - 150, y: cy - 40, dir: 'v', label: { x: x + w - 40, y: cy - 220, align: 'right' } }, - }, - // central piles - stock: { x: cx - 70, y: cy }, - discard: { x: cx + 70, y: cy }, - // team meld strips (team 0 below centre near the human, team 1 above) - meldZones: { - 0: { x: cx, y: cy + 150, label: { x: x + 40, y: cy + 120 } }, - 1: { x: cx, y: cy - 230, label: { x: x + 40, y: cy - 260 } }, - }, - // team score panels - panels: { - 0: { x: x + w - 250, y: y + h - 120 }, - 1: { x: x + w - 250, y: y + 60 }, - }, - }; +/** + * 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; } -// Convenience: the four standard seats and which team each belongs to. -export const TEAM_OF_SEAT = [0, 1, 0, 1]; -export const SEATS_OF_TEAM = [[0, 2], [1, 3]]; +/** 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; +} -// Re-export for callers that build the deck. -export { SUITS, RANKS }; +// ── 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; +} diff --git a/src/games/canasta/CanastaDialogs.js b/src/games/canasta/CanastaDialogs.js new file mode 100644 index 0000000..90330c5 --- /dev/null +++ b/src/games/canasta/CanastaDialogs.js @@ -0,0 +1,115 @@ +// Canasta dialogs — How to play, Settings (house rules), and your lifetime +// record at Rosa's table. Each takes the scene (a CardTableScene). + +import { COLORS } from '../../config.js'; +import { DEPTH as D, CX, CY } from '../../ui/cardtable/CardTableScene.js'; +import { DEFAULT_RULES, TEAM_OF_SEAT, minimumMeld } from './CanastaData.js'; + +export const STATS_KEY = 'canasta-stats'; + +const emptyLifetime = () => ({ + games: 0, wins: 0, hands: 0, handsWon: 0, canastas: 0, naturals: 0, piles: 0, bigPile: 0, + outs: 0, concealed: 0, redThrees: 0, bestHand: null, bestMatch: null, bestDate: null, +}); + +export function loadLifetime() { + try { return { ...emptyLifetime(), ...JSON.parse(localStorage.getItem(STATS_KEY) || '{}') }; } catch (_) { return emptyLifetime(); } +} + +/** Fold a finished match (you are seat 0, on side 0) into the lifetime record. */ +export function recordLifetime(gs) { + const L = loadLifetime(); + const st = gs.stats[0]; + const won = gs.winner === 0; + L.games++; + if (won) L.wins++; + L.hands += gs.history.length; + L.handsWon += gs.history.filter(h => h.totals[0] > h.totals[1]).length; + L.canastas += st.canastas; + L.naturals += st.naturals; + L.piles += st.piles; + L.bigPile = Math.max(L.bigPile, st.bigPile); + L.outs += st.outs; + L.concealed += st.concealed; + L.redThrees += st.redThrees; + const best = Math.max(...gs.history.map(h => h.totals[0])); + const newBest = L.bestHand == null || best > L.bestHand; + if (newBest) { L.bestHand = best; L.bestDate = new Date().toISOString().slice(0, 10); } + if (won && (L.bestMatch == null || gs.scores[0] - gs.scores[1] > L.bestMatch)) L.bestMatch = gs.scores[0] - gs.scores[1]; + try { localStorage.setItem(STATS_KEY, JSON.stringify(L)); } catch (_) { /* private mode */ } + return { lifetime: L, newBest: newBest && best > 0, best }; +} + +export function openRules(scene) { + const h = 860; + scene.openModal({ w: 1120, h, onEscape: () => scene.closeModal() }); + const top = CY - h / 2; + scene.modalText(CX, top + 46, 'How to play Canasta', { fontFamily: 'Righteous', fontSize: '36px', color: COLORS.goldHex }); + const r = scene.gs?.rules ?? { ...DEFAULT_RULES, ...scene.settings.rules }; + const k = r.target / 5000; + const lines = [ + ['Partners', 'You and the player across from you are a team: your melds, canastas and score are shared.'], + ['Goal', `First side to ${r.target.toLocaleString()} wins. Score by melding — above all by building canastas.`], + ['Cards', '108: two decks and four jokers. Jokers 50 · 2s and aces 20 · K–8 10 · 7–4 and black 3s 5. Jokers and 2s are wild.'], + ['Your turn', 'Draw one card from the stock (or take the whole discard pile), meld if you like, then discard one card.'], + ['Melds', 'Three or more of a rank. At least two natural cards and no more than three wilds. Add to your side\'s melds any time.'], + ['First meld', `Your side's first meld must total ${minimumMeld(0, r)} (${minimumMeld(1500 * k, r)} from ${(1500 * k).toLocaleString()}, ${minimumMeld(3000 * k, r)} from ${(3000 * k).toLocaleString()}; 15 below zero).`], + ['Canasta', 'Seven cards of a rank. Natural (no wilds): +500, stacked with a red card on top. Mixed: +300, a black card on top.'], + ['The pile', 'Take it by melding its top card: two naturals of that rank, or (once you\'ve melded) one natural and a wild, or onto your meld.'], + ['Frozen', `A wild in the pile freezes it (it lies crosswise): only a natural pair takes it. It's frozen for a side that hasn't melded${r.alwaysFrozen ? ' — and in this game, always' : ''}.`], + ['Threes', 'Red threes are laid down at once for +100 each (all four 800) — but count against you if your side never melds. A black three on the pile blocks the next player.'], + ['Going out', `Meld all your cards (or all but one, then discard it). Your side needs ${r.goOutCanastas === 1 ? 'a canasta' : 'two canastas'} first${r.askPartner ? ', and you must ask your partner — "no" binds for that turn' : ''}. +100, or +200 "concealed" if you meld your whole hand in one turn.`], + ['Black 3s', 'Black threes can only be melded (three or four of them, no wilds) when you are going out.'], + ['Stock out', 'Once the stock is gone you must take the pile if its top card fits your meld; if no one can, the hand ends.'], + ['Scoring', 'Each side: meld cards + canasta bonuses + red threes + going out − the value of cards left in hand.'], + ]; + lines.forEach(([kk, v], i) => { + const y = top + 104 + i * 50; + scene.addToModal(scene.add.text(CX - 500, y, kk, { fontFamily: 'Righteous', fontSize: '18px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + scene.addToModal(scene.add.text(CX - 360, y, v, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.textHex, wordWrap: { width: 860 } }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + }); + scene.modalButton(CX, top + h - 42, 'Back to the table', () => scene.closeModal(), { width: 280, height: 46, fontSize: 18 }); +} + +export function openSettings(scene, onDone = null) { + const s = scene.settings; + const R = s.rules; + scene.openSettingsModal([ + { label: 'Opponent pace', options: [['relaxed', 'Relaxed'], ['normal', 'Normal'], ['fast', 'Fast']], get: () => s.pace, set: (v) => { s.pace = v; } }, + { label: 'Hints (★ coach · + fits a meld · pile glow)', options: [[false, 'Off'], [true, 'On']], get: () => s.hints, set: (v) => { s.hints = v; scene.layout?.(); scene.updateDock?.(); } }, + { label: 'Table talk from your partner', options: [[false, 'Off'], [true, 'On']], get: () => s.talk, set: (v) => { s.talk = v; } }, + { label: 'Peek through the pile (tooltip)', options: [[false, 'Off'], [true, 'On']], get: () => s.pilePeek, set: (v) => { s.pilePeek = v; } }, + { label: 'Play to', options: [[5000, '5,000'], [3000, '3,000'], [2500, '2,500']], get: () => R.target, set: (v) => { R.target = v; } }, + { label: 'Canastas needed to go out', options: [[1, 'One'], [2, 'Two']], get: () => R.goOutCanastas, set: (v) => { R.goOutCanastas = v; } }, + { label: '"Partner, may I go out?"', options: [[false, 'Off'], [true, 'Must ask']], get: () => R.askPartner, set: (v) => { R.askPartner = v; } }, + { label: 'Discard pile', options: [[false, 'Classic'], [true, 'Always frozen']], get: () => R.alwaysFrozen, set: (v) => { R.alwaysFrozen = v; } }, + ], { note: 'House rules start with the next game (Menu → New game). A shorter game scales the first-meld thresholds to match.', onDone }); +} + +export function openLifetime(scene, onBack = null) { + const L = loadLifetime(); + const h = 600; + const back = () => { scene.closeModal(); onBack?.(); }; + scene.openModal({ w: 920, h, onEscape: back }); + const top = CY - h / 2; + scene.modalText(CX, top + 48, 'Your record at Rosa\'s table', { fontFamily: 'Righteous', fontSize: '32px', color: COLORS.goldHex }); + const per = (n, d) => (d ? (n / d).toFixed(1) : '–'); + const rows = [ + ['Matches', L.games ? `${L.wins} won of ${L.games} (${Math.round((L.wins / L.games) * 100)}%)` : 'none yet'], + ['Hands', L.hands ? `${L.handsWon} of ${L.hands} won by your side` : '—'], + ['Your canastas', `${L.canastas} (${L.naturals} natural) · ${per(L.canastas, L.games)} a match`], + ['Piles taken', `${L.piles}${L.bigPile ? ` · biggest ${L.bigPile} cards` : ''}`], + ['Went out', `${L.outs} time${L.outs === 1 ? '' : 's'}${L.concealed ? ` · ${L.concealed} concealed!` : ''}`], + ['Red threes', `${L.redThrees}`], + ['Best hand', L.bestHand != null ? `${L.bestHand.toLocaleString()} for your side${L.bestDate ? ` (${L.bestDate})` : ''}` : '—'], + ['Biggest win', L.bestMatch != null ? `by ${L.bestMatch.toLocaleString()} points` : '—'], + ]; + rows.forEach(([k, v], i) => { + const y = top + 116 + i * 46; + scene.addToModal(scene.add.text(CX - 370, y, k, { fontFamily: 'Righteous', fontSize: '19px', color: COLORS.goldHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + scene.addToModal(scene.add.text(CX - 120, y, v, { fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.textHex }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + }); + scene.modalButton(CX, top + h - 44, 'Back', back, { width: 220, height: 46, fontSize: 18 }); +} + +export { TEAM_OF_SEAT }; diff --git a/src/games/canasta/CanastaEndScreen.js b/src/games/canasta/CanastaEndScreen.js new file mode 100644 index 0000000..6ed01f5 --- /dev/null +++ b/src/games/canasta/CanastaEndScreen.js @@ -0,0 +1,200 @@ +// Canasta — the hand tally (both sides counted up line by line, the way Rosa +// reads it off the score pad) and the end-of-match card (who won, the score +// race hand by hand, everyone's canastas and pickups, your record). + +import { COLORS } from '../../config.js'; +import { DEPTH as D, CX, CY, playSoundEx, SFX } from '../../ui/cardtable/CardTableScene.js'; +import { TEAM_OF_SEAT, NATURAL_CANASTA, MIXED_CANASTA, minimumMeld } from './CanastaData.js'; +import { TEAM_COLORS, TEAM_HEX, SEAT_HEX } from './CanastaTable.js'; + +const INK = '#f2ead8'; +const MUTED = '#b9a98a'; +const fmt = (n) => `${n < 0 ? '−' : ''}${Math.abs(n).toLocaleString()}`; +const signed = (n) => (n > 0 ? `+${n.toLocaleString()}` : n < 0 ? `−${Math.abs(n).toLocaleString()}` : '0'); + +/** + * opts: { gs, final?, instant?, onNext, onScores?, onLeave? } + */ +export function openHandTally(scene, { gs, final = false, instant = false, onNext, onScores = null, onLeave = null }) { + const w = 1120, h = 680; + scene.openModal({ w, h, onEscape: null, freeze: false }); + const top = CY - h / 2; + const r = gs.result; + const who = (s) => (s === 0 ? 'You' : scene.shortName(s, 12)); + const head = r.outSeat == null ? `Hand ${gs.handNo}: the stock ran out` + : `Hand ${gs.handNo}: ${who(r.outSeat)} went out${r.concealed ? ' concealed' : ''}`; + scene.modalText(CX, top + 46, head, { fontFamily: 'Righteous', fontSize: '34px', color: COLORS.goldHex }); + const objs = []; + const colX = [CX - 270, CX + 270]; + const names = [`You & ${scene.shortName(2, 10)}`, `${scene.shortName(1, 10)} & ${scene.shortName(3, 10)}`]; + [0, 1].forEach((t) => { + const [a, b] = t === 0 ? [0, 2] : [1, 3]; + scene.modalPortrait(a, colX[t] - 150, top + 112, 24, TEAM_COLORS[t]); + scene.modalPortrait(b, colX[t] - 112, top + 124, 24, TEAM_COLORS[t]); + scene.modalText(colX[t] + 20, top + 116, names[t], { fontFamily: '"Julius Sans One"', fontSize: '20px', color: TEAM_HEX[t] }); + }); + const rows = (d, t) => { + const out = [['Melds on the table', d.meldPoints]]; + if (d.natural || d.mixed) { + const parts = []; + if (d.natural) parts.push(`${d.natural} natural`); + if (d.mixed) parts.push(`${d.mixed} mixed`); + out.push([`Canastas (${parts.join(', ')})`, d.canastaBonus]); + } else out.push(['Canastas', 0]); + if (d.redThrees) out.push([`Red threes (${d.redThrees})${gs.teams[t].melded ? '' : ' — never melded!'}`, d.redThreeBonus]); + if (d.goOut) out.push([d.goOut === 200 ? 'Going out concealed' : 'Going out', d.goOut]); + out.push(['Cards left in hand', -d.inHand]); + return out; + }; + const lineH = 40; + const y0 = top + 176; + const steps = []; + [0, 1].forEach((t) => { + const d = r.detail[t]; + const list = rows(d, t); + list.forEach(([label, v], i) => { + const y = y0 + i * lineH; + const lt = scene.addToModal(scene.add.text(colX[t] - 200, y, label, { fontFamily: '"Julius Sans One"', fontSize: '17px', color: INK }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + const vt = scene.addToModal(scene.add.text(colX[t] + 200, y, signed(v), { fontFamily: 'Righteous', fontSize: '21px', color: v < 0 ? '#ff8a7a' : v > 0 ? '#8ce99a' : MUTED }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + steps.push({ objs: [lt, vt], i, t }); + }); + const ty = y0 + 6 * lineH; + const g = scene.addToModal(scene.add.graphics().setDepth(D.modal + 1)); + g.lineStyle(2, TEAM_COLORS[t], 0.7); + g.lineBetween(colX[t] - 200, ty - 24, colX[t] + 200, ty - 24); + const tl = scene.addToModal(scene.add.text(colX[t] - 200, ty, 'This hand', { fontFamily: 'Righteous', fontSize: '20px', color: TEAM_HEX[t] }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + const tv = scene.addToModal(scene.add.text(colX[t] + 200, ty, '0', { fontFamily: 'Righteous', fontSize: '30px', color: TEAM_HEX[t] }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + const ml = scene.addToModal(scene.add.text(colX[t] - 200, ty + 48, 'Match score', { fontFamily: '"Julius Sans One"', fontSize: '17px', color: MUTED }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + const mv = scene.addToModal(scene.add.text(colX[t] + 200, ty + 48, fmt(r.before[t]), { fontFamily: 'Righteous', fontSize: '26px', color: INK }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + objs.push({ t, tv, mv, tl, ml, total: d.total }); + // the side's first-meld bar for next hand + const need = minimumMeld(gs.scores[t], gs.rules); + const prevNeed = minimumMeld(r.before[t], gs.rules); + if (!final && need !== prevNeed) { + scene.addToModal(scene.add.text(colX[t], ty + 92, `First meld now needs ${need}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: '#ffc861' }).setOrigin(0.5).setDepth(D.modal + 1)); + } + }); + // reveal line by line, then tick the totals up + const maxRows = Math.max(...[0, 1].map(t => rows(r.detail[t], t).length)); + const per = instant ? 0 : 300; + for (const s of steps) { + if (per) { + s.objs.forEach(o => o.setAlpha(0)); + scene.time.delayedCall(250 + s.i * per + s.t * 90, () => { + if (!scene.modal || !s.objs.every(o => o.active)) return; + s.objs.forEach(o => scene.tweens.add({ targets: o, alpha: 1, duration: 180 })); + if (s.t === 0) playSoundEx(scene, SFX.PENCIL_WRITE, { volume: 0.35 }); + }); + } + } + const tickAt = 250 + maxRows * per + 200; + for (const o of objs) { + const counter = { v: 0, m: r.before[o.t] }; + // the modal may close (Next hand) mid-count: never touch destroyed texts + const alive = () => o.tv.active && o.mv.active; + const done = () => { if (!alive()) return; o.tv.setText(signed(o.total)); o.mv.setText(fmt(gs.scores[o.t])); }; + if (!per) { done(); continue; } + const tw = scene.tweens.add({ + targets: counter, v: o.total, m: gs.scores[o.t], delay: tickAt, duration: 900, ease: 'Cubic.easeOut', + onUpdate: () => { if (!alive()) { tw.stop(); return; } o.tv.setText(signed(Math.round(counter.v))); o.mv.setText(fmt(Math.round(counter.m))); }, + onComplete: done, + }); + } + if (per) scene.time.delayedCall(tickAt, () => scene.modal && playSoundEx(scene, SFX.KART_COIN ?? SFX.COINS, { volume: 0.4 })); + // footer + const fy = top + h - 52; + if (final) { + scene.modalText(CX, fy - 56, `${gs.winner === 0 ? 'That wins the match!' : 'And that\'s the match.'}`, { fontFamily: 'Righteous', fontSize: '24px', color: gs.winner === 0 ? '#ffd35a' : INK }); + scene.modalButton(CX, fy, 'See the result', onNext, { width: 260, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + } else { + scene.modalText(CX, fy - 56, `First to ${gs.rules.target.toLocaleString()} · next hand dealt by ${who((gs.dealer + 1) % 4)}`, { fontFamily: '"Julius Sans One"', fontSize: '15px', color: MUTED }); + scene.modalButton(CX - 250, fy, 'Next hand', onNext, { width: 220, bg: COLORS.accent, textColor: COLORS.textDarkHex }); + if (onScores) scene.modalButton(CX, fy, 'Score sheet', onScores, { width: 220, variant: 'ghost' }); + if (onLeave) scene.modalButton(CX + 250, fy, 'Leave', onLeave, { width: 220, variant: 'ghost' }); + } + scene.modal.onEnter = onNext; + // let the laid-down table show through a little + scene.modal.objs[0].setAlpha(0.4); +} + +/** + * buttons: [{ label, act, hot?, ghost? }] + * note: { newBest, best, lifetime } from recordLifetime() + */ +export function openEndScreen(scene, { gs, names, buttons, note = null }) { + const w = 1240, h = 840; + scene.openModal({ w, h, onEscape: null, freeze: false }); + const top = CY - h / 2, left = CX - w / 2; + const won = gs.winner === 0; + const sideName = (t) => (t === 0 ? `You & ${names[2]}` : `${names[1]} & ${names[3]}`); + scene.modalText(CX, top + 54, won ? 'You and your partner win!' : `${sideName(1)} win`, { fontFamily: 'Righteous', fontSize: '48px', color: won ? '#ffd35a' : INK }); + scene.modalText(CX, top + 108, `${fmt(gs.scores[0])} – ${fmt(gs.scores[1])} · ${gs.history.length} hands`, { fontFamily: 'Righteous', fontSize: '28px', color: INK }); + if (won) { + const seal = scene.addToModal(scene.add.image(left + 150, top + 100, 'can-basket').setDepth(D.modal + 2).setScale(1.6).setAlpha(0).setRotation(-0.2)); + scene.tweens.add({ targets: seal, scale: 0.62, alpha: 1, rotation: -0.08, duration: 420, delay: 300, ease: 'Back.easeOut' }); + scene.time.delayedCall(450, () => scene.burst({ x: left + 150, y: top + 100 }, 0xffd35a, { n: 16, r: 140 })); + } + + // ── the score race, hand by hand ── + const cx0 = left + 90, cx1 = left + 760, cy0 = top + 170, cy1 = top + 470; + const g = scene.addToModal(scene.add.graphics().setDepth(D.modal + 1)); + g.fillStyle(0x000000, 0.25); + g.fillRoundedRect(cx0 - 20, cy0 - 20, cx1 - cx0 + 40, cy1 - cy0 + 50, 12); + const series = [0, 1].map(t => [0, ...gs.history.map(hh => hh.scores[t])]); + const all = series.flat().concat([gs.rules.target]); + const lo = Math.min(0, ...all), hi = Math.max(...all); + const n = series[0].length; + const X = (i) => cx0 + (n > 1 ? (i / (n - 1)) * (cx1 - cx0) : 0); + const Y = (v) => cy1 - ((v - lo) / Math.max(1, hi - lo)) * (cy1 - cy0); + // target and zero lines + g.lineStyle(2, 0xffd35a, 0.6); + g.lineBetween(cx0, Y(gs.rules.target), cx1, Y(gs.rules.target)); + scene.modalText(cx1 - 4, Y(gs.rules.target) - 14, `${gs.rules.target.toLocaleString()}`, { fontFamily: '"Julius Sans One"', fontSize: '13px', color: '#ffd35a' }).setOrigin(1, 0.5); + if (lo < 0) { g.lineStyle(1, 0xffffff, 0.3); g.lineBetween(cx0, Y(0), cx1, Y(0)); } + for (let i = 1; i < n; i++) scene.modalText(X(i), cy1 + 18, `H${i}`, { fontFamily: '"Julius Sans One"', fontSize: '12px', color: MUTED }); + [1, 0].forEach((t) => { + const s = series[t]; + g.lineStyle(4, TEAM_COLORS[t], 1); + g.beginPath(); + s.forEach((v, i) => (i ? g.lineTo(X(i), Y(v)) : g.moveTo(X(i), Y(v)))); + g.strokePath(); + s.forEach((v, i) => { g.fillStyle(TEAM_COLORS[t], 1); g.fillCircle(X(i), Y(v), i === s.length - 1 ? 7 : 4); }); + scene.modalText(X(n - 1) + 12, Y(s[n - 1]) + (t ? 14 : -14), sideName(t), { fontFamily: '"Julius Sans One"', fontSize: '13px', color: TEAM_HEX[t] }).setOrigin(0, 0.5); + }); + + // ── who did what ── + const tx = left + 850; + scene.modalText(tx + 150, cy0 - 4, 'Around the table', { fontFamily: 'Righteous', fontSize: '22px', color: COLORS.goldHex }); + const cols = ['Canastas', 'Piles', 'Out']; + cols.forEach((c, i) => scene.modalText(tx + 150 + i * 80, cy0 + 34, c, { fontFamily: '"Julius Sans One"', fontSize: '12px', color: MUTED })); + [0, 2, 1, 3].forEach((seat, r) => { + const y = cy0 + 74 + r * 50; + const st = gs.stats[seat]; + scene.modalText(tx + 40, y, names[seat], { fontFamily: 'Righteous', fontSize: '19px', color: SEAT_HEX[seat] }).setOrigin(0, 0.5); + const vals = [`${st.canastas}${st.naturals ? ` (${st.naturals}★)` : ''}`, `${st.piles}${st.bigPile >= 8 ? ` (${st.bigPile})` : ''}`, `${st.outs}${st.concealed ? '★' : ''}`]; + vals.forEach((v, i) => scene.modalText(tx + 150 + i * 80, y, v, { fontFamily: 'Righteous', fontSize: '20px', color: TEAM_OF_SEAT[seat] === gs.winner ? INK : MUTED })); + }); + scene.modalText(tx + 150, cy0 + 290, `★ natural canastas (+${NATURAL_CANASTA}) · mixed +${MIXED_CANASTA}`, { fontFamily: '"Julius Sans One"', fontSize: '12px', color: MUTED }); + + // ── best hand & your record ── + const bestHand = Math.max(...gs.history.map(hh => hh.totals[0])); + const lines = [`Your side's best hand: ${fmt(bestHand)}`]; + if (note?.newBest) lines.push('A new personal best hand!'); + if (note?.lifetime) { + const L = note.lifetime; + lines.push(`Lifetime at Rosa's table: ${L.wins} won of ${L.games} · ${L.canastas} canastas`); + } + lines.forEach((l, i) => scene.modalText(CX, top + 560 + i * 34, l, { + fontFamily: i === 1 && note?.newBest ? 'Righteous' : '"Julius Sans One"', fontSize: i === 1 && note?.newBest ? '22px' : '17px', + color: i === 1 && note?.newBest ? '#ffd35a' : INK, + })); + + const by = top + h - 60; + buttons.forEach((b, i) => { + const x = CX + (i - (buttons.length - 1) / 2) * 260; + const opts = b.ghost ? { variant: 'ghost' } : b.hot ? { bg: COLORS.accent, textColor: COLORS.textDarkHex } : {}; + scene.modalButton(x, by, b.label, b.act, { width: 230, ...opts }); + }); + const hot = buttons.find(b => b.hot); + if (hot) scene.modal.onEnter = hot.act; +} diff --git a/src/games/canasta/CanastaGame.js b/src/games/canasta/CanastaGame.js index c2d2ddd..b3b091d 100644 --- a/src/games/canasta/CanastaGame.js +++ b/src/games/canasta/CanastaGame.js @@ -1,964 +1,1788 @@ 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 { api } from '../../services/api.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; -import { THEME, TEAM_OF_SEAT, isWild, isRedThree, minimumMeld, cardScore, NATURAL_CANASTA, MIXED_CANASTA } from './CanastaData.js'; import { - createInitialState, drawStock, takeDiscard, meld, discard, startNextHand, - takePlan, teamMeld, isCanasta, isNaturalCanasta, meetsInitialMeld, teamHasCanasta, -} from './CanastaLogic.js'; -import { chooseDraw, chooseMelds, chooseDiscard, thinkDelay, takeYieldsLegalTurn } from './CanastaAI.js'; + CardTableScene, DEPTH as D, CX, CY, COLORS, playSound, playSoundEx, SFX, +} from '../../ui/cardtable/CardTableScene.js'; +import { jitterFor } from '../../ui/casino/CasinoCards.js'; +import { ensurePad } from '../nerts/NertsArt.js'; +import { CARD_W, CARD_H, inPose, inRect, stackLift, fanZone, PLATE } from '../../ui/cardtable/TableGeometry.js'; +import { + DEFAULT_RULES, TEAM_OF_SEAT, PARTNER, CANASTA_SIZE, MAX_WILDS, + frameOf, cardFromId, cardName, rankLabel, rankWord, isWild, isRed, isRedThree, isBlackThree, isMeldable, + cardScore, valueOf, handSort, handOrder, wildsIn, isCanasta, isNaturalCanasta, meldProblem, maxInitialValue, + NATURAL_CANASTA, MIXED_CANASTA, RED_THREE, ALL_RED_THREES, +} from './CanastaData.js'; +import * as G from './CanastaLogic.js'; +import { + chooseDraw, chooseMelds, chooseDiscard, chooseAnswer, coachDraw, coachMelds, coachDiscard, threatOf, +} from './CanastaAI.js'; +import { + L, SQ, SEAT_COLORS, SEAT_HEX, TEAM_COLORS, TEAM_HEX, BAND, PAD, TICKER, READOUT, BUBBLE, + bandColumns, columnPoses, columnRect, columnLabelY, handPose, handHome, handBadge, spotFor, +} from './CanastaTable.js'; +import { prepareCanastaArt, LAMP, HIFI, CLOCK, COFFEE } from './CanastaArt.js'; +import { openRules, openSettings, openLifetime, recordLifetime, loadLifetime } from './CanastaDialogs.js'; +import { openHandTally, openEndScreen } from './CanastaEndScreen.js'; +import { partnerLine } from './CanastaTalk.js'; -// ── Geometry ────────────────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; -const CY = 470; +// ─── Canasta — "Rosa's Parlor" ──────────────────────────────────────────────── +// A 1950s living room on the shared card-table kit (src/ui/cardtable/). Rules +// live in CanastaLogic.js (pure JSON state), opponents + Coach in +// CanastaAI.js; this file is flow, animation and input. Every card is a +// persistent sprite keyed by its id ('Ks1', 'JK2', …). -const CARD_W = 74, CARD_H = 104, CARD_R = 8; -const HAND_GAP = 30; // overlap step for the human fan -const MINI = 0.6; // scale for meld / opponent cards - -const STOCK = { x: CX - 96, y: CY }; -const DISCARD = { x: CX + 96, y: CY }; - -const SEAT = { - 0: { hand: { x: CX, y: 930 }, port: { x: 650, y: 930 }, name: { x: 530, y: 858 } }, - 1: { hand: { x: 96, y: CY }, port: { x: 110, y: 290 }, name: { x: 110, y: 360 } }, - 2: { hand: { x: CX, y: 78 }, port: { x: 650, y: 96 }, name: { x: 530, y: 150 } }, - 3: { hand: { x: GAME_WIDTH - 96, y: CY }, port: { x: GAME_WIDTH - 110, y: 290 }, name: { x: GAME_WIDTH - 110, y: 360 } }, +const SETTINGS_KEY = 'canasta-settings'; +const SAVE_KEY = 'canasta-save-v1'; +const RULE_KEYS = ['target', 'goOutCanastas', 'askPartner', 'alwaysFrozen']; +export const DEFAULTS = { + pace: 'normal', hints: true, talk: true, pilePeek: false, sort: 'rank', + rules: Object.fromEntries(RULE_KEYS.map(k => [k, DEFAULT_RULES[k]])), }; -const MELD_ZONE = { 0: { y: 690 }, 1: { y: 282 } }; +const INK = '#f2ead8'; +const MUTED = '#b9a98a'; +const GREEN = '#8ce99a'; +const RED = '#ff8a7a'; +const AMBER = '#ffc861'; +const ICE = '#9fdcff'; +const PENCIL = '#2a2620'; -const D = { felt: -4, glow: -3, rail: -2, oval: -1, zone: 0, pile: 4, card: 10, cardText: 11, ui: 30, toast: 60, modal: 80, modalUI: 82 }; - -const HEX = (n) => '#' + n.toString(16).padStart(6, '0'); - -export default class CanastaGame extends Phaser.Scene { +export default class CanastaGame extends CardTableScene { constructor() { super('CanastaGame'); } init(data) { - this.gameDef = data.game ?? { slug: 'canasta', name: 'Canasta' }; - this.opponents = data.opponents ?? []; - // Seats 1, 2, 3 are the three AI players; seat 2 is the human's partner. - this.seatOpp = { 1: this.opponents[0], 2: this.opponents[1], 3: this.opponents[2] }; - this.seatSkill = { - 0: 5, - 1: this.clampSkill(this.opponents[0]?.skill), - 2: this.clampSkill(this.opponents[1]?.skill), - 3: this.clampSkill(this.opponents[2]?.skill), - }; - this.seatName = { - 0: 'You', - 1: this.opponents[0]?.name ?? 'West', - 2: this.opponents[1]?.name ?? 'Partner', - 3: this.opponents[2]?.name ?? 'East', - }; - - this.playfield = data.playfield ?? null; - - this.state = createInitialState(); + this.initTable(data, { settingsKey: SETTINGS_KEY, defaults: DEFAULTS, minPlayers: 4, maxPlayers: 4 }); + this.settings.rules = { ...DEFAULTS.rules, ...(this.settings.rules ?? {}) }; + this.initData = data; + this.backKey = 'can-back'; + this.gs = null; this.selected = new Set(); - this.busy = false; - this.recorded = false; - this.turnStartState = null; - this.meldDropZones = []; - this.handObjs = { 0: [], 1: [], 2: [], 3: [] }; - this.meldObjs = []; - this.pileObjs = []; - this.portraits = {}; + this.hoverId = null; + this.potentialDrag = null; + this.dragState = null; + this.dragPreview = null; + this.turnSnap = null; + this.pendingOut = null; + this.lastClick = { id: null, t: 0 }; + this.cache = { key: '', coach: null, best: null, take: null }; + this.labelPool = []; + this.ended = false; + this.flashIds = new Set(); } - clampSkill(s) { return Math.max(1, Math.min(5, s ?? 3)); } + faceFrame(card) { return { key: 'casino-cards', frame: frameOf(card) }; } - create() { - try { new MusicPlayer(this, this.cache.json.get('music')?.tracks ?? []); } catch { /* optional */ } - this.input.dragDistanceThreshold = 8; - - this.buildBackdrop(); - this.buildCenterLabels(); - this.buildPanels(); - this.buildPortraits(); - - this.statusText = this.add.text(CX, 600, '', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui).setShadow(0, 2, '#000', 6); - - this.buildButtons(); - - // Meld drop-zone highlight — drawn once in local space, repositioned during drag. - this.meldHighlight = this.add.graphics().setDepth(D.zone + 1).setVisible(false); - this.meldHighlight.fillStyle(THEME.brassHi, 0.13); - this.meldHighlight.lineStyle(2.5, THEME.brassHi, 0.9); - this.meldHighlight.fillRoundedRect(-72, -52, 144, 104, 14); - this.meldHighlight.strokeRoundedRect(-72, -52, 144, 104, 14); - - this.renderDynamic(); - this.advance(); + async create() { + this.createTableBase(); + const key = await prepareCanastaArt(this); + if (!this.alive()) return; + this.add.image(0, 0, key).setOrigin(0, 0).setDepth(D.table); + this.buildAmbience(); + this.buildSpot(); + this.slabG = this.add.graphics().setDepth(D.cards - 1); + this.pileG = this.add.graphics().setDepth(D.slots); + this.bandG = this.add.graphics().setDepth(D.slots + 0.5); + this.targetG = this.add.graphics().setDepth(D.glow); + const label = (size, color) => ({ fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, stroke: '#0a1a1c', strokeThickness: 4 }); + this.stockTxt = this.add.text(L.stock.x, L.stock.y + 76, '', label(15, '#e8dcc0')).setOrigin(0.5).setDepth(D.labels); + this.pileTxt = this.add.text(L.discard.x, L.discard.y + 76, '', label(15, '#e8dcc0')).setOrigin(0.5).setDepth(D.labels); + this.pileFlag = this.add.text(L.discard.x, L.discard.y - 86, '', { ...label(15, ICE), fontFamily: 'Righteous' }).setOrigin(0.5).setDepth(D.labels + 1); + this.buildPad(); + this.buildTicker(); + this.buildReadout(); + this.buildBubble(); + this.buildDropSlot(); + this.buildPlates(L.seats.map(s => s.plate), SEAT_COLORS, SEAT_HEX, { stampText: 'CANASTA!' }); + this.buildBadges(); + this.buildGhostHands(L.seats.map((_, s) => (s ? handHome(s) : null)), SEAT_COLORS); + this.buildTopButtons({ + Menu: () => this.openPause(), Scores: () => this.openScorePad({ readOnly: true }), Rules: () => openRules(this), + }, 'Click cards to select · double-click selects a whole rank · M meld · drag onto a meld · Enter discard one\nD draw · T take the pile · U undo your melds · H hint · S sort · Esc clear / menu'); + this.buildDock(); + this.buildSortRow([['rank', 'Rank'], ['count', 'Groups']], () => { this.sortHand(); this.layout(); }); + this.buildTooltips(); + this.setupInput(); + const save = this.readSave(); + if (save) this.offerResume(save); + else this.newMatch(); } - // ── Backdrop: luxe felt with a spotlight, burgundy rail and brass oval ──────── - buildBackdrop() { - const pf = this.playfield; - const hasPlayfield = pf?.key && this.textures.exists(pf.key); - - if (hasPlayfield) { - this.add.image(CX, GAME_HEIGHT / 2, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT) - .setDepth(D.felt - 1); - } - - const g = this.add.graphics().setDepth(D.felt); - g.fillGradientStyle(THEME.feltMid, THEME.feltMid, THEME.feltEdge, THEME.feltEdge, 1); - g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - - if (hasPlayfield) { - const maskShape = this.add.graphics().setVisible(false); - maskShape.fillStyle(0xffffff); - maskShape.fillEllipse(CX, CY + 30, 1640, 1180); - g.setMask(new Phaser.Display.Masks.GeometryMask(this, maskShape)); - } - - // Soft radial spotlight over the table centre (stacked translucent ellipses). - const glow = this.add.graphics().setDepth(D.glow); - for (let i = 8; i >= 1; i--) { - glow.fillStyle(THEME.feltTop, 0.05); - glow.fillEllipse(CX, CY, 1500 * (i / 8), 1020 * (i / 8)); - } - - // Burgundy leather rail around the playing oval. - const rail = this.add.graphics().setDepth(D.rail); - rail.lineStyle(40, THEME.rail, 1); - rail.strokeEllipse(CX, CY + 30, 1640, 1180); - rail.lineStyle(40, THEME.railHi, 0.25); - rail.strokeEllipse(CX, CY + 22, 1640, 1180); - - // Brass trim lines. - const oval = this.add.graphics().setDepth(D.oval); - oval.lineStyle(3, THEME.brass, 0.9); - oval.strokeEllipse(CX, CY + 30, 1560, 1100); - oval.lineStyle(1.5, THEME.brassHi, 0.5); - oval.strokeEllipse(CX, CY + 30, 1548, 1088); - - this.add.text(CX, 32, 'C A N A S T A', { - fontFamily: 'Righteous', fontSize: '30px', color: HEX(THEME.brassHi), - }).setOrigin(0.5, 0).setDepth(D.ui).setAlpha(0.55); - } - - buildCenterLabels() { - this.add.text(STOCK.x, CY - 92, 'STOCK', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.add.text(DISCARD.x, CY - 92, 'DISCARD', { - fontFamily: '"Julius Sans One"', fontSize: '16px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.ui); - this.stockCount = this.add.text(STOCK.x, CY + 92, '', { - fontFamily: 'Righteous', fontSize: '18px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.ui); - this.frozenBadge = this.add.text(DISCARD.x, CY + 92, '❄ FROZEN', { - fontFamily: 'Righteous', fontSize: '17px', color: '#8fd3ff', - }).setOrigin(0.5).setDepth(D.ui).setVisible(false); - } - - // ── Team score panels ──────────────────────────────────────────────────────── - buildPanels() { - this.panel = {}; - const make = (teamId, x, y, accent, title, backSeat, frontSeat) => { - const g = this.add.graphics().setDepth(D.ui); - g.fillStyle(0x000000, 0.42); g.fillRoundedRect(x, y, 360, 114, 12); - g.lineStyle(2, accent, 0.9); g.strokeRoundedRect(x, y, 360, 114, 12); - - // Two overlapping portrait pictures left of the text content. - const _p = []; - this.addMiniPortrait(_p, backSeat, x + 24, y + 48, 20, D.ui + 1); - this.addMiniPortrait(_p, frontSeat, x + 44, y + 64, 20, D.ui + 4); - - this.add.text(x + 74, y + 14, title, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: HEX(accent), - }).setDepth(D.ui + 7); - const score = this.add.text(x + 74, y + 38, '0', { - fontFamily: 'Righteous', fontSize: '40px', color: COLORS.textHex, - }).setDepth(D.ui + 7); - const sub = this.add.text(x + 338, y + 82, '', { - fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, - }).setOrigin(1, 0.5).setDepth(D.ui + 7); - this.panel[teamId] = { score, sub }; + // ── Ambience: lamp, hi-fi, wall clock, coffee steam ─────────────────────── + buildAmbience() { + // the floor lamp's warm pool, breathing a little + this.lampGlow = this.add.image(LAMP.x, LAMP.y + 40, 'ct-spot').setDisplaySize(640, 640).setTint(0xffc884) + .setBlendMode(Phaser.BlendModes.ADD).setAlpha(0.16).setDepth(D.spot); + const breathe = () => { + if (!this.alive()) return; + this.tweens.add({ targets: this.lampGlow, alpha: 0.13 + Math.random() * 0.06, duration: 900 + Math.random() * 1400, ease: 'Sine.easeInOut', onComplete: breathe }); }; - make(0, 1400, MELD_ZONE[0].y - 57 + 75, THEME.team0, 'YOUR TEAM', 2, 0); - make(1, 200, MELD_ZONE[1].y - 57 - 75, THEME.team1, 'OPPONENTS', 3, 1); + breathe(); + // a record turning on the hi-fi + // (the disc spins inside a squashed container, so it turns in perspective) + this.record = this.add.image(0, 0, 'can-record'); + this.add.container(HIFI.x, HIFI.y - 3, [this.record]).setScale(0.9, 0.36).setDepth(D.table + 0.1); + // the tone arm + const arm = this.add.graphics().setDepth(D.table + 0.3); + arm.lineStyle(3, 0xd8d0c0, 1); + arm.lineBetween(HIFI.x + 52, HIFI.y - 14, HIFI.x + 18, HIFI.y + 2); + arm.fillStyle(0xd8d0c0, 1); + arm.fillCircle(HIFI.x + 52, HIFI.y - 14, 4); + // the clock tells the real time + this.add.image(CLOCK.x, CLOCK.y, 'can-clock').setDepth(D.table + 0.1); + this.clockG = this.add.graphics().setDepth(D.table + 0.2); + this.drawClock(); + this.time.addEvent({ delay: 1000, loop: true, callback: () => this.drawClock() }); + // steam curling off the coffee + this.time.addEvent({ delay: 520, loop: true, callback: () => this.puff() }); } - buildPortraits() { - for (const seat of [0, 1, 2, 3]) { - const pos = SEAT[seat].port; - this.portraits[seat] = seat === 0 - ? createPlayerPortrait(this, pos.x, pos.y, 46, D.ui, 'CanastaGame') - : createOpponentPortrait(this, this.seatOpp[seat], pos.x, pos.y, 46, D.ui, { playIntro: seat === 2 }); - const n = SEAT[seat].name; - const partnerTag = TEAM_OF_SEAT[seat] === 0 && seat !== 0 ? ' ◆' : ''; - this.add.text(n.x, n.y, this.seatName[seat].toUpperCase() + partnerTag, { - fontFamily: 'Righteous', fontSize: '18px', - color: HEX(TEAM_OF_SEAT[seat] === 0 ? THEME.team0 : THEME.team1), - }).setOrigin(seat === 3 ? 1 : 0, 0.5).setDepth(D.ui); - // Glow ring used to mark whose turn it is. - const ring = this.add.graphics().setDepth(D.ui - 1).setVisible(false); - ring.lineStyle(5, THEME.brassHi, 0.95); ring.strokeCircle(pos.x, pos.y, 52); - this.portraits[seat].ring = ring; + update(_t, dt) { + if (!this.record || this.paused) return; + this.record.rotation += dt * 0.0035; // 33⅓ rpm, near enough + } + + drawClock() { + const g = this.clockG; + if (!g) return; + const now = new Date(); + const h = (now.getHours() % 12) + now.getMinutes() / 60, m = now.getMinutes() + now.getSeconds() / 60; + const hand = (a, len, w, col) => { + g.lineStyle(w, col, 1); + g.lineBetween(CLOCK.x, CLOCK.y, CLOCK.x + Math.sin(a) * len, CLOCK.y - Math.cos(a) * len); + }; + g.clear(); + hand((h / 12) * Math.PI * 2, 18, 4, 0x1d3a3c); + hand((m / 60) * Math.PI * 2, 28, 2.5, 0x1d3a3c); + hand((now.getSeconds() / 60) * Math.PI * 2, 30, 1, 0xd0604a); + g.fillStyle(0xc8a050, 1); + g.fillCircle(CLOCK.x, CLOCK.y, 3); + } + + puff() { + if (!this.alive() || this.paused) return; + const x = COFFEE.x + (Math.random() - 0.5) * 16 * COFFEE.s, y = COFFEE.y - 40 * COFFEE.s; + const p = this.add.circle(x, y, 7 * COFFEE.s, 0xffffff, 0.16).setDepth(D.labels - 1); + this.tweens.add({ + targets: p, y: y - 70, x: x + (Math.random() - 0.5) * 30, scale: 2.4, alpha: 0, duration: 2200, ease: 'Sine.easeOut', + onComplete: () => p.destroy(), + }); + } + + // ── Score pad (centre left) ──────────────────────────────────────────────── + buildPad() { + const key = ensurePad(this, 'can-pad', PAD.w, PAD.h); + this.add.image(PAD.x, PAD.y, key).setDepth(D.labels).setRotation(-0.025); + const hand = (size, color = PENCIL) => ({ fontFamily: '"YummyCupcakes", "Comic Sans MS", cursive', fontSize: `${size}px`, color }); + const x0 = PAD.x - PAD.w / 2, colX = [x0 + 96, x0 + 222]; + this.padTitle = this.add.text(PAD.x, PAD.y - 54, '', { ...hand(17, '#6a6050') }).setOrigin(0.5).setDepth(D.labels + 1).setRotation(-0.025); + this.padHead = [0, 1].map(t => this.add.text(colX[t], PAD.y - 28, t ? 'THEY' : 'WE', hand(22, t ? '#1f7a74' : '#b0442e')).setOrigin(0.5).setDepth(D.labels + 1).setRotation(-0.025)); + this.padScore = [0, 1].map(t => this.add.text(colX[t], PAD.y + 4, '0', hand(32)).setOrigin(0.5).setDepth(D.labels + 1).setRotation(-0.025)); + this.padSub = [0, 1].map(t => this.add.text(colX[t], PAD.y + 40, '', hand(16, '#5a5040')).setOrigin(0.5).setDepth(D.labels + 1).setRotation(-0.025)); + this.padG = this.add.graphics().setDepth(D.labels + 1); + this.padG.lineStyle(2, 0x8a8070, 0.7); + this.padG.lineBetween(PAD.x + 10, PAD.y - 40, PAD.x + 6, PAD.y + 58); + } + + updatePad() { + const gs = this.gs; + if (!gs) return; + this.padTitle.setText(`Hand ${gs.handNo} · first to ${gs.rules.target.toLocaleString()}`); + for (const t of [0, 1]) { + this.padScore[t].setText(gs.scores[t].toLocaleString()); + const team = gs.teams[t]; + const c = G.canastaCount(gs, t); + const need = G.minimumFor(gs, t); + this.padSub[t].setText(team.melded ? `${c ? `${'▲'.repeat(Math.min(c, 4))}${c > 4 ? `+${c - 4}` : ''}` : 'no canasta'}` : `needs ${need}`); } } - buildButtons() { - const y = 1042; - this.btn = {}; - this.btn.draw = new Button(this, CX - 360, y, 'Draw Stock', () => this.humanDraw('stock'), - { width: 220, height: 56, fontSize: 22 }).setDepth(D.ui); - this.btn.take = new Button(this, CX - 125, y, 'Take Pile', () => this.humanDraw('take'), - { width: 220, height: 56, fontSize: 22 }).setDepth(D.ui); - this.btn.meld = new Button(this, CX + 110, y, 'Meld', () => this.humanMeld(), - { width: 200, height: 56, fontSize: 22 }).setDepth(D.ui); - this.btn.reset = new Button(this, CX - 110, y, 'Reset Turn', () => this.humanResetTurn(), - { variant: 'ghost', width: 200, height: 56, fontSize: 20 }).setDepth(D.ui); - this.btn.discard = new Button(this, CX + 330, y, 'Discard', () => this.humanDiscard(), - { width: 200, height: 56, fontSize: 22 }).setDepth(D.ui); - this.btn.next = new Button(this, CX, y, 'Next Hand', () => this.onNextHand(), - { width: 280, height: 56, fontSize: 24 }).setDepth(D.ui).setVisible(false); - this.btn.leave = new Button(this, GAME_WIDTH - 110, 44, 'Leave', () => this.scene.start('GameMenu'), - { variant: 'ghost', width: 160, height: 48, fontSize: 20 }).setDepth(D.ui); - this.hideActionButtons(); + // ── Ticker (centre right): the last few plays ────────────────────────────── + buildTicker() { + this.add.text(TICKER.x, TICKER.y - 30, 'AT THE TABLE', { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#c9b08a', + }).setOrigin(0, 0.5).setDepth(D.labels); + this.tickerTxt = [0, 1, 2, 3].map(i => this.add.text(TICKER.x, TICKER.y + i * 23, '', { + fontFamily: '"Julius Sans One"', fontSize: i === 0 ? '16px' : '14px', color: INK, stroke: '#0a1a1c', strokeThickness: 4, + }).setOrigin(0, 0.5).setDepth(D.labels).setAlpha(1 - i * 0.2)); + this.tickerLines = []; } - hideActionButtons() { - ['draw', 'take', 'meld', 'reset', 'discard'].forEach((k) => this.btn[k].setVisible(false)); + pushTicker(text, color = INK) { + this.tickerLines.unshift({ text, color }); + this.tickerLines.length = Math.min(this.tickerLines.length, 4); + this.tickerTxt.forEach((t, i) => { + const l = this.tickerLines[i]; + t.setText(l ? l.text : '').setColor(l ? l.color : INK); + }); + const t0 = this.tickerTxt[0]; + t0.setAlpha(0); + this.tweens.add({ targets: t0, alpha: 1, duration: 260 }); } - // ── Card rendering ─────────────────────────────────────────────────────────── - drawFace(container, card, faceUp, scale = 1) { - const w = CARD_W * scale, h = CARD_H * scale, r = CARD_R * scale; - const x = -w / 2, y = -h / 2; + // ── Readout: meld preview & first-meld meter above your hand ─────────────── + buildReadout() { + this.readG = this.add.graphics().setDepth(D.labels + 1); + this.readTxt = this.add.text(READOUT.x, READOUT.y, '', { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: INK, stroke: '#0a1a1c', strokeThickness: 5, align: 'center', + }).setOrigin(0.5).setDepth(D.labels + 2); + this.meterTxt = this.add.text(READOUT.x - 200, READOUT.y + 30, '', { + fontFamily: 'Righteous', fontSize: '16px', color: AMBER, stroke: '#0a1a1c', strokeThickness: 4, + }).setOrigin(1, 0.5).setDepth(D.labels + 2); + } + + // ── Partner's speech bubble ──────────────────────────────────────────────── + buildBubble() { + const c = this.add.container(BUBBLE.x, BUBBLE.y).setDepth(D.stamp - 2).setVisible(false); const g = this.add.graphics(); - if (!faceUp) { - g.fillStyle(THEME.cardBack, 1); g.fillRoundedRect(x, y, w, h, r); - g.lineStyle(3 * scale, THEME.brass, 0.85); g.strokeRoundedRect(x + 4 * scale, y + 4 * scale, w - 8 * scale, h - 8 * scale, r); - for (let i = -1; i <= 1; i++) { - g.fillStyle(THEME.cardBackHi, 0.5); - g.fillRoundedRect(-5 * scale, y + h * (0.5 + i * 0.22) - 5 * scale, 10 * scale, 10 * scale, 2); - } - container.add(g); - return; - } - g.fillStyle(THEME.cardFace, 1); g.fillRoundedRect(x, y, w, h, r); - g.lineStyle(2, 0xcc9a3a, 0.5); g.strokeRoundedRect(x + 2, y + 2, w - 4, h - 4, r - 1); - container.add(g); + const t = this.add.text(0, 0, '', { + fontFamily: '"YummyCupcakes", "Comic Sans MS", cursive', fontSize: '21px', color: PENCIL, align: 'center', wordWrap: { width: 300 }, + }).setOrigin(0.5); + c.add([g, t]); + this.bubble = { c, g, t, timer: null }; + } - if (card.rank === 'JK') { - container.add(this.add.text(0, -h * 0.22, '★', { fontFamily: 'serif', fontSize: `${36 * scale}px`, color: THEME.jokerHex }).setOrigin(0.5)); - container.add(this.add.text(0, h * 0.18, 'JOKER', { fontFamily: 'Righteous', fontSize: `${13 * scale}px`, color: THEME.jokerHex }).setOrigin(0.5)); - return; - } - const col = card.isRed ? THEME.suitRed : THEME.suitBlk; - const sym = card.suitSymbol; - container.add(this.add.text(x + 7 * scale, y + 4 * scale, card.label, { fontFamily: 'Righteous', fontSize: `${20 * scale}px`, color: col })); - container.add(this.add.text(x + 8 * scale, y + 27 * scale, sym, { fontFamily: 'sans-serif', fontSize: `${17 * scale}px`, color: col })); - container.add(this.add.text(0, 3 * scale, sym, { fontFamily: 'sans-serif', fontSize: `${40 * scale}px`, color: col }).setOrigin(0.5)); - container.add(this.add.text(x + w - 7 * scale, y + h - 4 * scale, card.label, { fontFamily: 'Righteous', fontSize: `${20 * scale}px`, color: col }).setOrigin(1, 1)); - if (card.rank === '2') { - container.add(this.add.text(0, h * 0.32, 'WILD', { fontFamily: 'Righteous', fontSize: `${10 * scale}px`, color: HEX(THEME.brass) }).setOrigin(0.5)); + /** The partner says something (when table talk is on). */ + say(kind, ctx = {}) { + if (!this.settings.talk || !this.bubble) return; + const line = partnerLine(kind, { ...ctx, name: this.shortName(2, 12) }); + if (!line) return; + const b = this.bubble; + b.t.setText(line); + const w = Math.max(140, b.t.width + 34), h = b.t.height + 24; + b.g.clear(); + b.g.fillStyle(0x000000, 0.25); + b.g.fillRoundedRect(-w / 2 + 3, -h / 2 + 5, w, h, 16); + b.g.fillStyle(0xfffaf0, 0.97); + b.g.fillRoundedRect(-w / 2, -h / 2, w, h, 16); + b.g.fillTriangle(-14, -h / 2 + 1, 8, -h / 2 + 1, -4, -h / 2 - 16); + b.g.lineStyle(2, SEAT_COLORS[2], 1); + b.g.strokeRoundedRect(-w / 2, -h / 2, w, h, 16); + b.c.setPosition(BUBBLE.x, BUBBLE.y + h / 2 - 20).setVisible(true).setAlpha(0).setScale(0.8); + this.tweens.killTweensOf(b.c); + this.tweens.add({ targets: b.c, alpha: 1, scale: 1, duration: 200, ease: 'Back.easeOut' }); + this.tweens.add({ targets: b.c, alpha: 0, delay: 2600 + line.length * 25, duration: 380, onComplete: () => b.c.setVisible(false) }); + } + + buildBadges() { + this.badges = []; + for (let seat = 1; seat < 4; seat++) { + const p = handBadge(seat); + const c = this.add.container(p.x, p.y).setDepth(D.oppHand + 2); + const g = this.add.graphics(); + const t = this.add.text(0, 1, '11', { fontFamily: 'Righteous', fontSize: '16px', color: INK }).setOrigin(0.5); + c.add([g, t]); + this.badges[seat] = { c, g, t, warn: false }; } } - makeCard(card, x, y, { faceUp = true, scale = 1, depth = D.card } = {}) { - const c = this.add.container(x, y).setDepth(depth); - c.cardRef = card; - this.drawFace(c, card, faceUp, scale); - return c; - } - - // ── Dynamic layout (hands, melds, piles) ───────────────────────────────────── - renderDynamic() { - for (const seat of [0, 1, 2, 3]) { this.handObjs[seat].forEach((o) => o.destroy()); this.handObjs[seat] = []; } - this.meldObjs.forEach((o) => o.destroy()); this.meldObjs = []; - this.pileObjs.forEach((o) => o.destroy()); this.pileObjs = []; - - this.renderPiles(); - this.renderHands(); - this.renderMelds(); - this.renderPanels(); - this.updateTurnRing(); - } - - renderPiles() { - const s = this.state; - const humanDrawPhase = s.phase === 'draw' && s.currentPlayer === 0; - - // Stock as a neat stack of backs. - const n = Math.min(6, Math.ceil(s.stock.length / 12)); - let stockTop = null; - for (let i = 0; i < n; i++) { - const c = this.makeCard(null, STOCK.x - i * 2, STOCK.y - i * 2, { faceUp: false, depth: D.pile + i }); - this.pileObjs.push(c); - stockTop = c; - } - this.stockCount.setText(`${s.stock.length} left`); - - if (humanDrawPhase && stockTop) { - this.makeInteractive(stockTop, () => this.humanDraw('stock')); - } - - // Discard pile: a slightly fanned stack, top card face up. - const dn = Math.min(5, s.discard.length); - let discardTop = null; - for (let i = 0; i < dn; i++) { - const card = s.discard[s.discard.length - dn + i]; - const top = i === dn - 1; - const c = this.makeCard(card, DISCARD.x + (i - dn) * 3, DISCARD.y + (i - dn) * 2, { faceUp: top, depth: D.pile + i }); - this.pileObjs.push(c); - if (top) discardTop = c; - } - this.frozenBadge.setVisible(s.frozen); - - if (humanDrawPhase && discardTop) { - const plan = takePlan(s, 0); - const t = s.teams[0]; - const legal = !!plan && (t.hasMelded || takeYieldsLegalTurn(s, 0, 5, plan)); - if (legal) this.makeInteractive(discardTop, () => this.humanDraw('take')); + updateBadges() { + const gs = this.gs; + for (let s = 1; s < 4; s++) { + const b = this.badges[s]; + const n = gs.hands[s].length; + b.c.setVisible(!G.isOver(gs)); + b.t.setText(String(n)); + // danger: their side can go out and this player is nearly empty + const warn = TEAM_OF_SEAT[s] === 1 && G.hasGoOutCanastas(gs, s) && n <= 3; + b.g.clear(); + b.g.fillStyle(warn ? 0x5a1410 : 0x0a1a1c, 0.92); + b.g.fillCircle(0, 0, 17); + b.g.lineStyle(2.5, warn ? 0xff6a5a : SEAT_COLORS[s], 1); + b.g.strokeCircle(0, 0, 17); + if (warn && !b.warn) this.tweens.add({ targets: b.c, scale: 1.25, duration: 220, yoyo: true, repeat: 2 }); + b.warn = warn; } } - renderHands() { - const s = this.state; - const meldPhase = s.phase === 'meld' && s.currentPlayer === 0; - // Human hand — face up, fanned, sorted for readability. - const me = s.players[0].hand.slice().sort(this.handSort); - const total = (me.length - 1) * HAND_GAP + CARD_W; - me.forEach((card, i) => { - const x = SEAT[0].hand.x - total / 2 + CARD_W / 2 + i * HAND_GAP; - const sel = this.selected.has(card.id); - const c = this.makeCard(card, x, SEAT[0].hand.y - (sel ? 26 : 0), { depth: D.card + i }); - c.baseY = SEAT[0].hand.y; - if (isRedThree(card)) this.glowCard(c); - if (meldPhase) { - c.setSize(CARD_W, CARD_H); - c.setInteractive({ useHandCursor: true }); - this.input.setDraggable(c); - let dragged = false; - c.on('dragstart', () => { - dragged = true; - c._ox = c.x; c._oy = c.y; - c.setDepth(D.card + 50); - }); - c.on('drag', (pointer, dragX, dragY) => { - c.x = dragX; c.y = dragY; - const zone = this.meldDropZones.find(z => Math.abs(dragX - z.x) < 75 && Math.abs(dragY - z.y) < 65); - if (zone) { - this.meldHighlight.setVisible(true).setPosition(zone.x, zone.y); - } else { - this.meldHighlight.setVisible(false); - } - }); - c.on('dragend', () => { - this.meldHighlight.setVisible(false); - c.setDepth(D.card + i); - const dropX = c.x, dropY = c.y; - c.x = c._ox; c.y = c._oy; - // Check meld drop zones first. - const zone = this.meldDropZones.find(z => Math.abs(dropX - z.x) < 75 && Math.abs(dropY - z.y) < 65); - if (zone) { - const next = meld(this.state, zone.rank, [card.id]); - if (next !== this.state) { - this.state = next; - playSound(this, SFX.CARD_PLACE); - this.renderDynamic(); - this.updateMeldPhaseUi(); - } else { - this.toast('Cannot add that card to this meld', CX, 560, '#e06c75'); - } - return; - } - if (Math.abs(dropX - DISCARD.x) < 80 && Math.abs(dropY - DISCARD.y) < 100) { - this.selected = new Set([card.id]); - this.humanDiscard({ animate: false }); - } - }); - c.on('pointerup', () => { if (!dragged) this.toggleSelect(card.id); dragged = false; }); - } else { - this.makeInteractive(c, () => this.toggleSelect(card.id)); - } - this.handObjs[0].push(c); + // ── Tooltips ─────────────────────────────────────────────────────────────── + buildTooltips() { + for (let seat = 1; seat < 4; seat++) { + const pl = L.seats[seat].plate; + this.hoverZone(pl.x, pl.y, PLATE.w, PLATE.h, () => this.seatTip(seat)); + } + const d = L.discard, s = L.stock; + this.hoverZone(d.x, d.y, CARD_W * d.s + 24, CARD_H * d.s * SQ + 24, () => this.pileTip()); + this.hoverZone(s.x, s.y, CARD_W * s.s + 24, CARD_H * s.s * SQ + 24, () => this.stockTip()); + this.hoverZone(PAD.x, PAD.y, PAD.w, PAD.h, () => this.padTip()); + } + + seatTip(seat) { + const gs = this.gs; + if (!gs) return null; + const held = gs.pickups[seat].filter(id => gs.hands[seat].some(c => c.id === id)).map(cardFromId).filter(c => isMeldable(c)); + const byRank = {}; + for (const c of held) byRank[c.rank] = (byRank[c.rank] || 0) + 1; + const ranks = Object.entries(byRank).sort((a, b) => b[1] - a[1]).map(([r, n]) => `${n}×${rankLabel(r)}`); + const st = gs.stats[seat]; + const lines = [ + { text: `${gs.hands[seat].length} cards in hand${seat === gs.dealer ? ' · dealer' : ''}`, color: INK }, + { text: ranks.length ? `Known to hold (from the pile): ${ranks.join(' ')}` : 'Hasn\'t picked up the pile this hand', color: ranks.length ? AMBER : MUTED }, + { text: `This match: ${st.canastas} canasta${st.canastas === 1 ? '' : 's'} · ${st.piles} pile${st.piles === 1 ? '' : 's'} taken · out ${st.outs}×`, color: MUTED }, + { text: seat === 2 ? 'Your partner — your melds are shared' : `Opponent · skill ${this.skillFor(seat)} / 5`, color: COLORS.mutedHex }, + ]; + return { title: this.nameForSeat(seat), titleColor: SEAT_HEX[seat], lines }; + } + + stockTip() { + const gs = this.gs; + if (!gs) return null; + const n = gs.stock.length; + return { + title: `Stock — ${n} card${n === 1 ? '' : 's'}`, + lines: [ + { text: 'Draw one card. A red three is laid down at once and replaced.' }, + { text: n ? 'When the stock runs out, play goes on only while players take the discard.' : 'The stock is gone: take the pile if you can — or the hand ends.', color: n < 12 ? RED : MUTED }, + ], + }; + } + + pileTip() { + const gs = this.gs; + if (!gs) return null; + const top = G.topDiscard(gs); + if (!top) return { title: 'Discard pile — empty', lines: [] }; + const n = gs.discard.length; + const lines = []; + if (gs.frozen) lines.push({ text: '❄ Frozen (a wild card is in it): only a natural pair matching the top card takes it.', color: ICE }); + else if (!gs.teams[0].melded) lines.push({ text: 'Until our side melds, the pile is frozen for us: we need a natural pair.', color: ICE }); + if (isBlackThree(top)) lines.push({ text: 'A black three on top: nobody can take it this turn.', color: AMBER }); + if (this.isMyTurn() && gs.phase === 'draw') { + const t = this.takeInfo(); + lines.push(t.plan ? { text: `You can take it: ${this.describeTake(t.plan)}`, color: GREEN } : { text: t.problem ?? '', color: RED }); + } + if (this.settings.pilePeek) { + const shown = gs.discard.slice().reverse().slice(0, 24).map(cardName); + lines.push({ text: `In the pile: ${shown.join(' ')}${n > 24 ? ' …' : ''}`, color: MUTED }); + } else lines.push({ text: 'Whoever takes it gets every card in it.', color: MUTED }); + return { title: `Discard pile — ${n} card${n === 1 ? '' : 's'}, ${cardName(top)} on top`, lines }; + } + + padTip() { + const gs = this.gs; + if (!gs) return null; + const r = gs.rules; + const lines = [0, 1].map(t => { + const team = gs.teams[t]; + const need = G.minimumFor(gs, t); + return { text: `${t ? 'They' : 'We'}: ${gs.scores[t].toLocaleString()} · ${team.melded ? 'melded' : `first meld needs ${need}`} · ${G.canastaCount(gs, t)} canasta(s)`, color: TEAM_HEX[t] }; }); - - // Opponents / partner — face-down stacks (count only). - for (const seat of [1, 2, 3]) { - const hand = s.players[seat].hand; - const horiz = seat === 2; - const count = hand.length; - const step = horiz ? 22 : 0; - const vstep = horiz ? 0 : 16; - const span = horiz ? (count - 1) * step : (count - 1) * vstep; - for (let i = 0; i < count; i++) { - const x = SEAT[seat].hand.x + (horiz ? i * step - span / 2 : 0); - const y = SEAT[seat].hand.y + (horiz ? 0 : i * vstep - span / 2); - this.handObjs[seat].push(this.makeCard(null, x, y, { faceUp: false, scale: MINI, depth: D.card + i })); - } - this.handObjs[seat].push(this.add.text(SEAT[seat].hand.x, SEAT[seat].hand.y + (horiz ? 52 : 0), - horiz ? `${count}` : `${count}`, { fontFamily: 'Righteous', fontSize: '16px', color: COLORS.mutedHex }) - .setOrigin(0.5).setDepth(D.ui)); - } + lines.push({ text: `Going out needs ${r.goOutCanastas === 1 ? 'a canasta' : 'two canastas'}${r.askPartner ? ' — and your partner\'s say-so' : ''}.`, color: MUTED }); + lines.push({ text: 'First meld minimum: 50 · 90 from 1,500 · 120 from 3,000 (15 when below zero).', color: MUTED }); + return { title: `Score — first to ${r.target.toLocaleString()}`, lines }; } - renderMelds() { - this.meldDropZones = []; - const meldPhase = this.state.phase === 'meld' && this.state.currentPlayer === 0; - for (const teamId of [0, 1]) { - const melds = this.state.teams[teamId].melds; - const reds = this.state.teams[teamId].redThrees.length; - const y = MELD_ZONE[teamId].y; - const groupW = 150; - const totalW = Math.max(1, melds.length + (reds ? 1 : 0)) * groupW; - let gx = CX - totalW / 2 + groupW / 2; - for (const m of melds) { - this.renderMeldGroup(m, gx, y, teamId === 0 && meldPhase); - if (teamId === 0 && meldPhase) this.meldDropZones.push({ rank: m.rank, x: gx, y }); - gx += groupW; - } - if (reds) { - const badge = this.add.container(gx, y).setDepth(D.zone); - const g = this.add.graphics(); - g.fillStyle(0x000000, 0.3); g.fillRoundedRect(-58, -34, 116, 68, 10); - g.lineStyle(2, THEME.redThree, 0.9); g.strokeRoundedRect(-58, -34, 116, 68, 10); - badge.add(g); - badge.add(this.add.text(0, -8, `♥♦ ×${reds}`, { fontFamily: 'Righteous', fontSize: '22px', color: '#e0556a' }).setOrigin(0.5)); - badge.add(this.add.text(0, 18, 'red threes', { fontFamily: '"Julius Sans One"', fontSize: '12px', color: COLORS.mutedHex }).setOrigin(0.5)); - this.meldObjs.push(badge); - } - } + // ── Save / resume ────────────────────────────────────────────────────────── + signature() { return JSON.stringify({ 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() || s.gs?.version !== G.VERSION) return null; + if (!['draw', 'handOver'].includes(s.gs.phase) || G.cardCount(s.gs) !== 108) return null; + return s; + } catch (_) { return null; } } - renderMeldGroup(m, x, y, showScore = false) { - const cont = this.add.container(x, y).setDepth(D.zone); - const canasta = isCanasta(m); - if (canasta) { - const ring = this.add.graphics(); - const col = isNaturalCanasta(m) ? THEME.brassHi : 0xcfd6e0; - ring.fillStyle(col, 0.16); ring.fillRoundedRect(-66, -46, 132, 96, 14); - ring.lineStyle(3, col, 0.95); ring.strokeRoundedRect(-66, -46, 132, 96, 14); - cont.add(ring); + saveGame(gs = this.gs) { + if (!gs || !['draw', 'handOver'].includes(gs.phase)) return; + try { localStorage.setItem(SAVE_KEY, JSON.stringify({ v: 1, sig: this.signature(), gs, savedAt: Date.now() })); } catch (_) { /* private mode */ } + } + + clearSave() { try { localStorage.removeItem(SAVE_KEY); } catch (_) { /* */ } } + + offerResume(save) { + const when = new Date(save.savedAt).toLocaleDateString(); + const [a, b] = save.gs.scores; + this.confirm('Resume your game?', `A game from ${when} is still on the table — hand ${save.gs.handNo}, we have ${a.toLocaleString()}, they have ${b.toLocaleString()} (to ${save.gs.rules.target.toLocaleString()}).`, 'Resume', () => { + this.gs = save.gs; + if (this.gs.phase === 'handOver') this.gs = G.nextHand(this.gs); + this.startHand({ resumed: true }); + }, { no: 'New game', onNo: () => { this.clearSave(); this.newMatch(); } }); + } + + // ── Match / hand lifecycle ───────────────────────────────────────────────── + newMatch() { + const seed = (Math.random() * 2 ** 32) >>> 0; + this.gs = G.createGame({ rules: this.settings.rules, seed }); + this.startHand({ cut: true }); + } + + async startHand({ resumed = false, cut = false } = {}) { + this.clearSprites(); + this.closeModal(); + this.mode = 'deal'; + this.turnToken++; + const token = this.turnToken; + this.selected.clear(); + this.hoverId = null; + this.turnSnap = null; + this.pendingOut = null; + this.ended = false; + this.tickerLines = []; + this.tickerTxt.forEach(t => t.setText('')); + for (const pl of this.plates) { pl.tallyTxt.setVisible(false); pl.stamp.setVisible(false); } + const gs = this.gs; + const from = { ...L.stock, y: L.stock.y - 10 }; + const dealOrder = new Map(); + const first = (gs.dealer + 1) % 4; + for (let s = 0; s < 4; s++) { + gs.hands[s].forEach((c, i) => dealOrder.set(c.id, i * 4 + ((s - first + 4) % 4))); + for (const c of gs.hands[s]) this.lastLoc.set(c.id, { pose: from, faceUp: false, depth: D.fly }); } - const step = 17; - const span = (m.cards.length - 1) * step; - m.cards.forEach((card, i) => { - const mc = this.add.container(i * step - span / 2, -6).setDepth(D.zone); - this.drawFace(mc, card, true, MINI); - cont.add(mc); + for (const t of gs.teams) for (const c of [...t.redThrees, ...t.melds.flatMap(m => m.cards)]) 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.updatePad(); + this.updateDock(); + playSound(this, SFX.CARD_SHUFFLE); + if (cut && gs.cut) { + const w = gs.dealer; + this.floatText({ x: CX, y: L.stock.y - 120 }, `${w === 0 ? 'You cut' : `${this.shortName(w, 12)} cuts`} the high card${w === 0 ? ' and deal' : ' and deals'}`, '#e8dcc0', { size: 22, ms: 1900, rise: 14 }); + } + // the wall clock's cuckoo: a little chime each new hand + this.time.delayedCall(150, () => playSoundEx(this, SFX.UI_CHIME, { volume: 0.45 })); + const step = resumed ? 6 : 16; + const total = 44; + this.layout({ + duration: 300, + delayFor: (v) => (v.kind === 'hand' ? 300 + (dealOrder.get(v.card.id) ?? 0) * step : 320 + (total + 2) * step + (v.kind === 'red' ? 260 : 0)), }); - const label = canasta ? (isNaturalCanasta(m) ? '★ CANASTA' : 'CANASTA') : `${m.cards.length}`; - cont.add(this.add.text(0, 38, label, { - fontFamily: 'Righteous', fontSize: canasta ? '14px' : '15px', - color: canasta ? HEX(isNaturalCanasta(m) ? THEME.brassHi : 0xcfd6e0) : COLORS.mutedHex, - }).setOrigin(0.5)); - if (showScore) { - const cardVal = m.cards.reduce((s, c) => s + cardScore(c), 0); - const bonus = canasta ? (isNaturalCanasta(m) ? NATURAL_CANASTA : MIXED_CANASTA) : 0; - const scoreLabel = bonus > 0 ? `+${bonus}+${cardVal}` : `+${cardVal}`; - cont.add(this.add.text(0, 55, scoreLabel, { - fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#90c878', - }).setOrigin(0.5)); + for (let i = 0; i < total; i += 3) this.time.delayedCall(320 + i * step, () => playSoundEx(this, SFX.CARD_DEAL, { volume: 0.3 })); + await this.wait(300 + (total + 6) * step + 500); + if (!this.alive() || token !== this.turnToken) return; + if (!resumed) { + const reds = gs.log.filter(e => e.kind === 'redThree'); + for (const e of reds) this.pushTicker(`${this.who(e.seat)} ${e.seat === 0 ? 'lay' : 'lays'} down a red three`, SEAT_HEX[e.seat]); + if (reds.some(e => TEAM_OF_SEAT[e.seat] === 0)) this.say('redThree'); + if (gs.frozen) { + this.floatText({ x: L.discard.x, y: L.discard.y - 110 }, 'A wild upcard — the pile starts frozen', ICE, { size: 20, ms: 2000, rise: 14 }); + await this.wait(700); + } else if (gs.handNo === 1) this.say('deal'); } - this.meldObjs.push(cont); - } - - renderPanels() { - for (const teamId of [0, 1]) { - const t = this.state.teams[teamId]; - this.panel[teamId].score.setText(String(t.score)); - const canastas = t.melds.filter(isCanasta).length; - this.panel[teamId].sub.setText(t.hasMelded ? `${canastas} canasta${canastas === 1 ? '' : 's'}` : 'not melded'); - } - } - - updateTurnRing() { - for (const seat of [0, 1, 2, 3]) { - const active = this.state.currentPlayer === seat && !['handOver', 'gameOver'].includes(this.state.phase); - this.portraits[seat].ring.setVisible(active); - } - } - - glowCard(c) { try { c.postFX.addGlow(THEME.redThree, 4, 0, false, 0.1, 8); } catch { /* fx optional */ } } - - handSort(a, b) { - const w = (c) => (isWild(c) ? 100 : isRedThree(c) ? 99 : (c.value || 0)); - return w(a) - w(b) || a.suit.localeCompare(b.suit); - } - - makeInteractive(c, handler) { - // A Container's displayOrigin is width/2, which Phaser adds during hit-testing, - // so the auto-generated Rectangle(0,0,w,h) lands centered. Passing a manual - // (-w/2,-h/2,w,h) rect double-shifts the hitbox up-left — so don't. - c.setSize(CARD_W, CARD_H); - c.setInteractive({ useHandCursor: true }); - c.on('pointerdown', handler); - } - - // ── Draw animation ────────────────────────────────────────────────────────── - // Animates a single card flying from (fromX,fromY) to (toX,toY) over 1200 ms. - // faceUp: starting face state. flip: if true, scaleX collapses at 600 ms, - // the container is redrawn face-up, then scaleX expands back to 1. - animateDraw({ fromX, fromY, toX, toY, card, faceUp = true, flip = false, duration = 1200, startDelay = 0 }) { - return new Promise(resolve => { - const anim = this.makeCard(card, fromX, fromY, { faceUp, depth: D.card + 100 }); - const half = duration / 2; - - this.tweens.add({ - targets: anim, - x: toX, y: toY, - duration, - delay: startDelay, - ease: 'Power2.easeInOut', - onComplete: () => { anim.destroy(); resolve(); }, - }); - - if (flip) { - // Fold (scaleX → 0) during first half, swap to face-up, unfold during second half. - this.tweens.add({ - targets: anim, - scaleX: 0, - duration: half, - delay: startDelay, - ease: 'Sine.easeIn', - onComplete: () => { - anim.removeAll(true); - this.drawFace(anim, card, true); - this.tweens.add({ targets: anim, scaleX: 1, duration: half, ease: 'Sine.easeOut' }); - }, - }); - } - }); - } - - getMeldGroupPos(teamId, rank) { - const melds = this.state.teams[teamId].melds; - const reds = this.state.teams[teamId].redThrees.length; - const groupW = 150; - const totalW = Math.max(1, melds.length + (reds ? 1 : 0)) * groupW; - let gx = CX - totalW / 2 + groupW / 2; - for (const m of melds) { - if (m.rank === rank) return { x: gx, y: MELD_ZONE[teamId].y }; - gx += groupW; - } - return { x: CX, y: MELD_ZONE[teamId].y }; - } - - // ── Turn flow ──────────────────────────────────────────────────────────────── - advance() { - this.updateTurnRing(); - const s = this.state; - if (s.phase === 'gameOver') return this.showGameOver(); - if (s.phase === 'handOver') return this.showHandOver(); - - if (s.currentPlayer === 0) return this.enableHumanTurn(); - this.runAiTurn(); - } - - async runAiTurn() { - this.busy = true; - this.hideActionButtons(); - const seat = this.state.currentPlayer; - const skill = this.seatSkill[seat]; - this.statusText.setText(`${this.seatName[seat]} is thinking…`); - await this.delay(thinkDelay(skill)); - - // Draw. - const draw = chooseDraw(this.state, seat, skill); - let drawnCard, drawFromX, drawFromY, drawFaceUp; - if (draw.type === 'take') { - drawnCard = this.state.discard[this.state.discard.length - 1]; - drawFromX = DISCARD.x; drawFromY = DISCARD.y; drawFaceUp = true; - this.state = takeDiscard(this.state, draw.plan); - this.toast(`${this.seatName[seat]} takes the pile`, DISCARD.x, DISCARD.y - 80); - playSound(this, SFX.CARD_SHOW); - } else { - drawnCard = this.state.stock[0]; - drawFromX = STOCK.x; drawFromY = STOCK.y; drawFaceUp = false; - this.state = drawStock(this.state); - playSound(this, SFX.CARD_DEAL); - } - if (drawnCard && !['handOver', 'gameOver'].includes(this.state.phase)) { - await this.animateDraw({ - fromX: drawFromX, fromY: drawFromY, - toX: SEAT[seat].hand.x, toY: SEAT[seat].hand.y, - card: drawnCard, faceUp: drawFaceUp, flip: false, - }); - } - this.renderDynamic(); - if (['handOver', 'gameOver'].includes(this.state.phase)) { this.busy = false; return this.advance(); } - await this.delay(750); - - // Meld. - const { actions } = chooseMelds(this.state, seat, skill); - const teamId = TEAM_OF_SEAT[seat]; - for (const a of actions) { - const before = this.state.teams[teamId].melds.find((m) => m.rank === a.rank); - const wasCanasta = before ? isCanasta(before) : false; - const meldCards = a.cardIds.map(id => this.state.players[seat].hand.find(c => c.id === id)).filter(Boolean); - this.state = meld(this.state, a.rank, a.cardIds); - const after = this.state.teams[teamId].melds.find((m) => m.rank === a.rank); - const meldPos = this.getMeldGroupPos(teamId, a.rank); - const duration = before ? 750 : 500; - const stagger = before ? 80 : 60; - await Promise.all(meldCards.map((card, i) => - this.animateDraw({ - fromX: SEAT[seat].hand.x, fromY: SEAT[seat].hand.y, - toX: meldPos.x, toY: meldPos.y, - card, faceUp: false, flip: true, duration, startDelay: i * stagger, - }) - )); - this.renderDynamic(); - playSound(this, SFX.CARD_PLACE); - if (after && isCanasta(after) && !wasCanasta) this.toast('CANASTA!', CX, MELD_ZONE[teamId].y - 70, '#f0d77a'); - } - - // Discard (ends the turn, or the hand if it empties). - if (this.state.phase === 'meld') { - const cardId = chooseDiscard(this.state, seat, skill); - const discardCard = this.state.players[seat].hand.find((c) => c.id === cardId); - this.state = discard(this.state, cardId); - if (discardCard) { - await this.animateDraw({ - fromX: SEAT[seat].hand.x, fromY: SEAT[seat].hand.y, - toX: DISCARD.x, toY: DISCARD.y, - card: discardCard, faceUp: false, flip: true, duration: 1000, - }); - } - this.renderDynamic(); - playSound(this, SFX.CARD_PLACE); - } - - this.busy = false; + if (!this.alive() || token !== this.turnToken) return; this.advance(); } - // ── Human turn ─────────────────────────────────────────────────────────────── - enableHumanTurn() { - this.busy = false; - const s = this.state; - if (s.phase === 'meld') this.turnStartState = this.state; - if (s.phase === 'draw') { - this.statusText.setText('Draw from the stock, or take the discard pile'); - this.btn.draw.setVisible(true).setEnabled(true); - const plan = takePlan(s, 0); - const t = s.teams[0]; - const legal = !!plan && (t.hasMelded || takeYieldsLegalTurn(s, 0, 5, plan)); - this.btn.take.setVisible(true).setEnabled(legal); - this.btn.meld.setVisible(false); - this.btn.discard.setVisible(false); - } else if (s.phase === 'meld') { - this.updateMeldPhaseUi(); + advance() { + if (!this.alive() || !this.gs) return; + const gs = this.gs; + if (G.isOver(gs)) { this.onHandOver(); return; } + const seat = G.actor(gs); + if (gs.phase === 'draw') this.saveGame(); + this.setSpot(spotFor(gs.current)); + if (gs.phase === 'ask') { + if (seat === 0) this.humanAnswer(); + else this.aiAnswer(seat); + return; } - } - - updateMeldPhaseUi() { - const s = this.state; - const t = s.teams[0]; - const noCanasta = s.players[0].hand.length === 1 && !teamHasCanasta(s, 0); - let statusMsg; - if (noCanasta) { - statusMsg = 'No canasta yet — discarding will end the hand early'; - } else if (!t.hasMelded) { - statusMsg = `Select cards to meld (first meld must total ${this.minNeeded()} pts), then discard one`; + if (seat === 0) { + this.mode = 'human'; + if (gs.phase === 'play' && !this.turnSnap) this.turnSnap = gs; + this.layout(); + this.updateDock(); + this.updatePlates(); + if (gs.phase === 'draw' && !gs.stock.length) { + this.floatText({ x: CX, y: 770 }, G.mustTake(gs) ? 'The stock is gone — the top card fits our meld, so we must take the pile' : 'The stock is gone — take the pile if you can, or the hand ends', AMBER, { size: 21, ms: 2600, rise: 14 }); + } + if (this.pendingOut && gs.phase === 'play') this.resumePendingOut(); } else { - statusMsg = 'Meld more, or select one card and discard'; + this.mode = 'ai'; + this.selected.clear(); + this.layout(); + this.updateDock(); + this.updatePlates(); + this.runAITurn(seat); } - this.statusText.setText(statusMsg); - this.btn.draw.setVisible(false); - this.btn.take.setVisible(false); - this.btn.meld.setVisible(true).setEnabled(this.selected.size >= 1); - this.btn.reset.setVisible(s.meldedThisTurn.length > 0); - this.btn.discard.setVisible(true).setEnabled(this.selected.size === 1 && this.discardAllowed()); } - minNeeded() { - return minimumMeld(this.state.teams[0].score); + /** 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)); + for (const id of [...this.selected]) if (!next.hands[0].some(c => c.id === id)) this.selected.delete(id); + this.sortHand(); + this.layout({ durationFor: (v) => (carry != null && v.card.id === carry ? this.timing(carrySeat).carry : null) }); + const sameHand = prev.handNo === next.handNo; + for (const e of next.log.slice(sameHand ? prev.log.length : 0)) this.logEffect(e, next); + this.updatePlates(); + this.updatePad(); + this.updateDock(); + if (fresh.length && fresh.length <= 30) for (const c of fresh) this.flashGlow(c.id, 0x7cf0a0, { delay: 250, hold: 700 }); } - discardAllowed() { - // Mirror the engine: an under-minimum initial meld can't be closed with a discard. - const t = this.state.teams[0]; - if (!t.hasMelded && this.state.meldedThisTurn.length > 0 && !meetsInitialMeld(this.state, 0)) return false; + who(seat) { return seat === 0 ? 'You' : this.shortName(seat, 12); } + + logEffect(e, gs) { + const plateAt = (s) => { const pl = this.plates[s]; return { x: pl.x, y: pl.y + (s === 0 ? -76 : 70) }; }; + switch (e.kind) { + case 'redThree': { + const at = this.columnAnchor(TEAM_OF_SEAT[e.seat], 'red') ?? plateAt(e.seat); + this.floatText(at, `red three +${RED_THREE}`, '#ff7a8a', { size: 20, ms: 1500, rise: 26 }); + this.pushTicker(`${this.who(e.seat)} ${e.fromPile ? 'found' : 'drew'} a red three`, SEAT_HEX[e.seat]); + playSoundEx(this, SFX.UI_CHIME, { volume: 0.35, rate: 1.3 }); + if (TEAM_OF_SEAT[e.seat] === 0 && e.seat !== 2 && !e.dealt) this.say('redThree'); + break; + } + case 'take': { + const n = e.count; + this.pushTicker(`${this.who(e.seat)} took ${n} card${n === 1 ? '' : 's'} with ${rankWord(e.rank, 2)}`, SEAT_HEX[e.seat]); + playSound(this, SFX.CARD_SHUFFLE); + if (e.seat !== 0) this.floatText(plateAt(e.seat), `took the pile (${n})`, SEAT_HEX[e.seat], { size: 21, ms: 1800, rise: 18 }); + if (n >= 8) this.stamp(n >= 14 ? 'WHAT A PILE!' : 'BIG PILE!', { x: L.discard.x, y: L.discard.y - 40 }, SEAT_HEX[e.seat], { size: 52, hold: 900, sub: `${this.who(e.seat)} ${e.seat === 0 ? 'take' : 'takes'} ${n} cards` }); + if (TEAM_OF_SEAT[e.seat] === 0) { if (n >= 6) this.say('weTook', { n }); } else if (n >= 6) this.say('theyTook', { n }); + this.celebrateCanastas(e.seat, e.newCanastas, gs); + break; + } + case 'meld': { + const words = e.groups.map(g => `${g.ids.length} ${rankWord(g.rank === '3' ? '3' : g.rank, g.ids.length)}`); + this.pushTicker(`${this.who(e.seat)} melded ${words.join(', ')}`, SEAT_HEX[e.seat]); + this.celebrateCanastas(e.seat, e.newCanastas, gs); + break; + } + case 'discard': { + const c = cardFromId(e.id); + this.pushTicker(`${this.who(e.seat)} threw the ${cardName(c)}${e.freeze ? ' — frozen!' : ''}`, SEAT_HEX[e.seat]); + if (e.freeze) { + this.floatText({ x: L.discard.x, y: L.discard.y - 96 }, '❄ the pile is frozen', ICE, { size: 22, ms: 1700, rise: 18 }); + playSoundEx(this, SFX.UI_FLIP, { volume: 0.6, rate: 0.8 }); + if (e.seat === 2) this.say('freeze'); + else if (TEAM_OF_SEAT[e.seat] === 1 && Math.random() < 0.5) this.say('theyFroze'); + } else if (e.block && gs.discard.length >= 5) { + this.floatText({ x: L.discard.x, y: L.discard.y - 96 }, 'blocked with a black three', AMBER, { size: 20, ms: 1500, rise: 16 }); + } + break; + } + case 'ask': + this.floatText(plateAt(e.seat), '"Partner, may I go out?"', SEAT_HEX[e.seat], { size: 21, ms: 2000, rise: 14 }); + this.pushTicker(`${this.who(e.seat)} asked to go out`, SEAT_HEX[e.seat]); + break; + case 'answer': + this.plateStamp(e.seat, e.yes ? 'YES' : 'NO', e.yes ? '#8ce99a' : '#ff6b4a', 1600); + this.pushTicker(`${this.who(e.seat)} said ${e.yes ? 'yes' : 'no'}`, SEAT_HEX[e.seat]); + if (e.seat === 2) this.say(e.yes ? 'yes' : 'no'); + break; + case 'out': + this.pushTicker(`${this.who(e.seat)} went out${e.concealed ? ' concealed!' : ''}`, SEAT_HEX[e.seat]); + break; + case 'stockOut': + this.pushTicker('The stock is exhausted', AMBER); + break; + default: break; + } + } + + /** The basket seal pops over each canasta just completed. */ + celebrateCanastas(seat, ranks, gs) { + ranks.forEach((rank, i) => { + const team = TEAM_OF_SEAT[seat]; + const m = gs.teams[team].melds.find(x => x.rank === rank); + const natural = m && isNaturalCanasta(m); + this.time.delayedCall(420 + i * 900, () => { + const at = this.columnAnchor(team, rank) ?? { x: CX, y: BAND.top[team] }; + const img = this.add.image(at.x, at.y, 'can-basket').setDepth(D.stamp).setScale(1.4).setAlpha(0).setRotation(-0.1); + this.tweens.add({ targets: img, scale: 0.55, alpha: 1, rotation: 0, duration: 300, ease: 'Back.easeOut' }); + this.tweens.add({ targets: img, alpha: 0, scale: 0.45, delay: 1300, duration: 400, onComplete: () => img.destroy() }); + this.burst(at, natural ? 0xffd35a : 0xd8dce8, { n: 14, r: 120 }); + this.floatText({ x: at.x, y: at.y - 70 }, `${natural ? 'Natural' : 'Mixed'} canasta! +${natural ? NATURAL_CANASTA : MIXED_CANASTA}`, natural ? '#ffd35a' : '#e0e6f0', { size: 26, ms: 2000, rise: 24 }); + playSound(this, team === 0 ? SFX.CASINO_WIN : SFX.UI_CHIME); + this.portraits[seat]?.playEmotion?.('happy'); + if (team === 0) this.say(natural ? 'naturalCanasta' : 'ourCanasta', { rank }); + else this.say('theirCanasta', { rank }); + }); + }); + } + + columnAnchor(team, rank) { + const gs = this.gs; + const t = gs.teams[team]; + const cols = bandColumns(team, t.melds, t.redThrees.length, false); + const col = cols.find(c => (rank === 'red' ? c.kind === 'red' : c.rank === rank)); + return col ? { x: col.x, y: col.y + 20 } : null; + } + + // ── AI turns ─────────────────────────────────────────────────────────────── + async runAITurn(seat) { + const token = ++this.turnToken; + const T0 = this.timing(seat); + const 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 === 'draw') { + const d = chooseDraw(gs, seat, skill); + const take = d.type === 'take'; + const top = G.topDiscard(gs); + const at = take ? (this.poseOf(top?.id) ?? L.discard) : d.type === 'pass' ? null : this.deckTop(); + if (at) { this.moveHand(seat, at, T0.reach); await this.wait(T0.reach); } + if (!live()) return; + const next = take ? G.takePile(gs, d.plan) : d.type === 'pass' ? G.passStock(gs) : G.drawStock(gs); + if (next === gs) return; + const moved = take ? null : gs.stock[0]?.id; + this.moveHand(seat, handHome(seat), T0.carry, 'Cubic.easeOut'); + this.handRest(seat, T0.carry * 0.7, T0.carry); + playSoundEx(this, SFX.CARD_DEAL, { volume: 0.5 }); + this.commit(next, { carry: moved, carrySeat: seat }); + await this.wait(T0.carry + T0.between + (take ? 500 : 0)); + if (!live()) return; + if (next.phase !== 'play' || next.current !== seat) { this.advance(); return; } + await this.wait(T0.think * 0.7); + if (!live()) return; + } + // melds, one action at a time + for (let guard = 0; guard < 20; guard++) { + gs = this.gs; + if (gs.phase !== 'play' || gs.current !== seat) break; + const m = chooseMelds(gs, seat, skill); + if (!m) break; + if (m.ask) { + const next = G.askGoOut(gs); + if (next === gs) break; + this.commit(next); + await this.wait(700); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + return; + } + const target = this.columnAnchor(TEAM_OF_SEAT[seat], m.groups[0].rank) ?? { x: CX, y: BAND.top[TEAM_OF_SEAT[seat]] }; + this.moveHand(seat, target, T0.reach); + await this.wait(T0.reach * 0.8); + if (!live()) return; + const next = G.meldCards(gs, m.groups); + if (next === gs) break; + playSoundEx(this, SFX.CARD_PLACE, { volume: 0.55 }); + this.commit(next); + this.handRest(seat, T0.carry * 0.7, T0.carry); + await this.wait(Math.max(520, T0.between * 1.6)); + if (!live()) return; + } + gs = this.gs; + if (G.isOver(gs)) { this.advance(); return; } + if (gs.phase !== 'play' || gs.current !== seat) return; + await this.wait(T0.think * 0.5); + if (!live()) return; + const id = chooseDiscard(gs, seat, skill); + const pose = this.poseOf(id) ?? handHome(seat); + this.moveHand(seat, pose, T0.reach * 0.7); + await this.wait(T0.reach * 0.7); + if (!live()) return; + const next = G.discardCard(gs, id); + if (next === gs) return; + this.moveHand(seat, 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: id, carrySeat: seat }); + await this.wait(T0.carry + 140); + if (!this.alive() || token !== this.turnToken) return; + this.advance(); + } + + async aiAnswer(seat) { + const token = ++this.turnToken; + this.mode = 'ai'; + this.updateDock(); + await this.wait(900); + if (!this.alive() || token !== this.turnToken) return; + const next = G.answerGoOut(this.gs, chooseAnswer(this.gs, this.skillFor(seat))); + if (next === this.gs) return; + this.commit(next); + await this.wait(900); + if (!this.alive() || token !== this.turnToken) return; + if (this.gs.current === 0 && this.gs.turn.asked === 'no') { + this.pendingOut = null; + this.floatText({ x: CX, y: 770 }, 'Your partner says no — keep two cards this turn', RED, { size: 21, ms: 2200, rise: 14 }); + } + this.advance(); + } + + humanAnswer() { + const gs = this.gs; + const asker = gs.ask.seat; + this.mode = 'answer'; + this.updateDock(); + const load = valueOf(gs.hands[0]); + const threat = threatOf(gs, 1); + const body = `If ${this.shortName(asker, 12)} goes out now, the ${gs.hands[0].length} card${gs.hands[0].length === 1 ? '' : 's'} in your hand count −${load} against us.${threat >= 0.6 ? ' They look close to going out themselves.' : ''} A "no" stops them for this turn.`; + this.confirm(`${this.shortName(asker, 12)} asks: "Partner, may I go out?"`, body, 'Yes, go out', () => this.answer(true), { no: 'Not yet', onNo: () => this.answer(false) }); + } + + answer(yes) { + const next = G.answerGoOut(this.gs, yes); + if (next === this.gs) return; + playSoundEx(this, SFX.UI_PICK, { volume: 0.5 }); + this.mode = 'idle'; + this.commit(next); + this.time.delayedCall(500, () => this.advance()); + } + + // ── End of hand ──────────────────────────────────────────────────────────── + async onHandOver() { + if (this.mode === 'summary' || this.ended) return; + this.mode = 'summary'; + this.ended = true; + const token = ++this.turnToken; + this.cancelDrag(); + this.selected.clear(); + this.hoverId = null; + this.pendingOut = null; + this.input.setDefaultCursor('default'); + for (let s = 1; s < 4; s++) this.handRest(s, 300); + this.updateDock(); + this.layout({ duration: 520 }); // everyone's leftover cards turn face up + const gs = this.gs; + const r = gs.result; + await this.wait(600); + if (!this.alive() || token !== this.turnToken) return; + if (r.outSeat != null) { + const s = r.outSeat; + this.stamp(r.concealed ? 'CONCEALED!' : 'OUT!', { x: CX, y: CY - 30 }, SEAT_HEX[s], { size: 88, hold: 1300, sub: `${this.who(s)} ${s === 0 ? 'go' : 'goes'} out${r.concealed ? ' in one turn — +200' : ' — +100'}` }); + playSound(this, TEAM_OF_SEAT[s] === 0 ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + this.portraits[s]?.playEmotion?.('happy'); + } else { + this.stamp('Stock out', { x: CX, y: CY - 30 }, '#e8dcc0', { size: 70, hold: 1300, sub: 'Nobody went out — the hand is scored as it lies' }); + } + await this.wait(1700); + if (!this.alive() || token !== this.turnToken) return; + const won = r.detail[0].total > r.detail[1].total; + this.say(won ? 'handWon' : 'handLost'); + if (gs.phase === 'gameOver') { + this.clearSave(); + const note = recordLifetime(gs); + this.recordResult('canasta', { score: gs.scores[0], opponentScores: [gs.scores[1]], won: gs.winner === 0 }); + openHandTally(this, { + gs, final: true, + onNext: () => this.showEnd(note), + }); + return; + } + // save the next deal, so leaving from the tally resumes at the new hand + this.saveGame(gs); + openHandTally(this, { + gs, + onNext: () => this.nextHand(), + onScores: () => this.openScorePad({ back: () => this.reopenTally() }), + onLeave: () => this.confirm('Leave the table?', 'The match is saved — you can pick it up next time.', 'Leave', () => this.scene.start('GameMenu'), { no: 'Stay', onNo: () => this.reopenTally() }), + }); + } + + reopenTally() { + openHandTally(this, { + gs: this.gs, instant: true, + onNext: () => this.nextHand(), + onScores: () => this.openScorePad({ back: () => this.reopenTally() }), + onLeave: () => this.scene.start('GameMenu'), + }); + } + + showEnd(note) { + const gs = this.gs; + const won = gs.winner === 0; + playSound(this, won ? SFX.CASINO_WIN : SFX.CASINO_LOSE); + for (let s = 1; s < 4; s++) this.portraits[s]?.playEmotion?.(TEAM_OF_SEAT[s] === gs.winner ? 'win' : 'loss'); + openEndScreen(this, { + gs, names: [0, 1, 2, 3].map(s => this.shortName(s, 12)), note, + buttons: [ + { label: 'Play again', act: () => this.restart(), hot: true }, + { label: 'Your record', ghost: true, act: () => openLifetime(this, () => this.showEnd(note)) }, + { label: 'Leave', ghost: true, act: () => this.scene.start('GameMenu') }, + ], + }); + } + + async nextHand() { + this.closeModal(); + if (this.gs.phase !== 'handOver') return; + this.mode = 'deal'; + this.updateDock(); + this.bandG.clear(); + await this.sweepCards(L.stock); + if (!this.alive()) return; + this.gs = G.nextHand(this.gs); + this.startHand(); + } + + // ── Layout ───────────────────────────────────────────────────────────────── + deckTop() { + const n = this.gs.stock.length; + return { ...L.stock, y: L.stock.y - stackLift(n, L.stock.s, 0.08, 12) }; + } + + stateKey() { + const gs = this.gs; + return `${gs.handNo}|${gs.turnNo}|${gs.phase}|${gs.current}|${gs.hands[0].map(c => c.id).join('')}|${gs.discard.length}|${gs.teams[0].melds.length}|${gs.turn.asked}`; + } + + refreshCache() { + const key = this.stateKey(); + if (this.cache.key === key) return; + this.cache = { key, coach: null, best: null, take: null }; + } + + takeInfo() { + this.refreshCache(); + if (!this.cache.take) this.cache.take = G.takeOption(this.gs, 0); + return this.cache.take; + } + + /** Best first-meld value the hand could make (for the meter). */ + bestFirst() { + this.refreshCache(); + if (this.cache.best == null) this.cache.best = maxInitialValue(this.gs.hands[0]); + return this.cache.best; + } + + coach() { + this.refreshCache(); + const gs = this.gs; + if (this.cache.coach) return this.cache.coach; + if (gs.current !== 0) return null; + if (gs.phase === 'draw') this.cache.coach = coachDraw(gs, 0); + else if (gs.phase === 'play') this.cache.coach = coachMelds(gs, 0) ?? coachDiscard(gs, 0); + return this.cache.coach; + } + + isMyTurn() { return this.mode === 'human' && this.gs?.current === 0 && ['draw', 'play'].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 === 'count') { + const n = {}; + for (const c of hand) if (isMeldable(c)) n[c.rank] = (n[c.rank] || 0) + 1; + const melded = new Set(gs.teams[0].melds.map(m => m.rank)); + const w = (c) => (isWild(c) ? -1 : isBlackThree(c) ? -2 : (melded.has(c.rank) ? 100 : 0) + n[c.rank] * 10); + order = hand.slice().sort((a, b) => w(b) - w(a) || handOrder(a) - handOrder(b) || handSort(a, b)); + } else order = hand.slice().sort(handSort); + hand.splice(0, hand.length, ...order); + } + + humanLift(id) { + if (this.selected.has(id)) return 36; + if (id === this.hoverId) return 18; + return 0; + } + + humanPoses() { + const hand = this.gs.hands[0]; + const ids = this.dragPreview ?? hand.map(c => c.id); + return ids.map((id, i) => ({ id, idx: i, pose: handPose(0, i, ids.length, this.humanLift(id)) })); + } + + /** Selection → meld groups (naturals by rank; wilds go where they're needed). */ + selectionGroups(ids = [...this.selected]) { + const gs = this.gs; + const cards = ids.map(id => gs.hands[0].find(c => c.id === id)).filter(Boolean); + if (!cards.length) return { groups: [], problem: null }; + const team = gs.teams[0]; + const groups = new Map(); + const wilds = []; + for (const c of cards) { + if (isWild(c)) { wilds.push(c); continue; } + if (isRedThree(c)) return { groups: [], problem: 'Red threes are bonus cards' }; + const r = c.rank; + if (!groups.has(r)) groups.set(r, []); + groups.get(r).push(c); + } + if (!groups.size) { + // wilds alone: onto the meld that wants them most (nearest a canasta, with room) + const cands = team.melds.filter(m => m.rank !== '3' && !meldProblem(m.rank, m, wilds)); + if (!cands.length) return { groups: [], problem: team.melds.length ? 'No meld has room for that many wild cards' : 'Wild cards need a meld to join' }; + cands.sort((a, b) => (isCanasta(a) - isCanasta(b)) || b.cards.length - a.cards.length); + return { groups: [{ rank: cands[0].rank, ids: wilds.map(c => c.id) }], problem: null, autoTarget: cands[0].rank }; + } + const size = (r) => (team.melds.find(m => m.rank === r)?.cards.length ?? 0) + groups.get(r).length; + const wildRoom = (r) => MAX_WILDS - wildsIn([...(team.melds.find(m => m.rank === r)?.cards ?? []), ...groups.get(r)]); + const ranks = [...groups.keys()].filter(r => r !== '3'); + // first make every group a legal size, then push toward a canasta + for (const r of ranks) while (size(r) < 3 && wilds.length && wildRoom(r) > 0) groups.get(r).push(wilds.shift()); + for (const r of ranks.sort((a, b) => size(b) - size(a))) while (wilds.length && wildRoom(r) > 0) groups.get(r).push(wilds.shift()); + if (wilds.length) return { groups: [], problem: 'Too many wild cards for those melds (three at most each)' }; + return { groups: [...groups.entries()].map(([rank, cs]) => ({ rank, ids: cs.map(c => c.id) })), problem: null }; + } + + computeLayout() { + const 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 over = G.isOver(gs); + // stock + 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 askew; any wild in the pile lies crosswise (frozen) + const pn = gs.discard.length; + const dBase = L.discard; + gs.discard.forEach((card, i) => { + const j = jitterFor(`can-${card.id}`); + const lift = stackLift(Math.min(pn, 40), dBase.s, 0.08, 8) * ((i + 1) / pn); + const cross = isWild(card) || isRedThree(card); + const pose = cross + ? { ...dBase, x: dBase.x + j.x * 3, y: dBase.y - lift, rot: Math.PI / 2 + j.rot * 2 } + : { ...dBase, x: dBase.x + j.x * 5, y: dBase.y - lift + j.y * 4, rot: j.rot * 6 }; + const depth = D.cards + 1 + i * 0.001; + if (i >= pn - 4 || cross) put(card, { kind: 'discard', pose, faceUp: true, depth, top: i === pn - 1 }); + else loc.set(card.id, { pose, faceUp: true, depth: D.cards }); + }); + // meld bands + const ghost = this.ghostWanted(); + for (const team of [0, 1]) { + const t = gs.teams[team]; + const cols = bandColumns(team, t.melds, t.redThrees.length, team === 0 && ghost); + for (const col of cols) { + if (col.kind === 'red') { + const poses = columnPoses(col, t.redThrees.length, { reds: true }); + t.redThrees.forEach((card, i) => put(card, { kind: 'red', team, pose: poses[i], faceUp: true, depth: D.cards + 2 + i * 0.01 })); + } else if (col.kind === 'meld') { + const m = col.meld; + const canasta = isCanasta(m); + let cards = m.cards; + if (canasta) { + // the real convention: a red card on top of a natural canasta, black on a mixed one + const natural = isNaturalCanasta(m); + const topIdx = m.cards.findIndex(c => !isWild(c) && (natural ? isRed(c) : !isRed(c))); + if (topIdx >= 0) cards = [...m.cards.slice(0, topIdx), ...m.cards.slice(topIdx + 1), m.cards[topIdx]]; + } else { + // naturals first, wilds tucked at the bottom of the cascade + cards = [...m.cards.filter(c => !isWild(c)), ...m.cards.filter(isWild)]; + } + const poses = columnPoses(col, cards.length, { canasta }); + cards.forEach((card, i) => put(card, { + kind: 'meld', team, rank: m.rank, canasta, natural: canasta && isNaturalCanasta(m), topOfStack: i === cards.length - 1, size: cards.length, + pose: poses[i], faceUp: true, depth: D.cards + 2 + col.index * 0.05 + i * 0.002, + })); + } + } + } + // hands + for (let seat = 0; seat < 4; seat++) { + const hand = gs.hands[seat]; + if (seat === 0) { + const byId = new Map(hand.map(c => [c.id, c])); + for (const h of this.humanPoses()) { + const card = byId.get(h.id); + if (!card) 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) => put(card, { kind: 'hand', seat, idx: i, pose: handPose(seat, i, hand.length), faceUp: over, depth: D.oppHand + i * 0.01 })); + } + } + return { visible, loc }; + } + + /** Does the current selection open a new meld (show the ghost column)? */ + ghostWanted() { + const gs = this.gs; + if (!this.isMyTurn() || gs.phase !== 'play') return false; + const ids = this.dragState ? [...new Set([...this.selected, this.dragState.id])] : [...this.selected]; + if (!ids.length) return false; + const { groups } = this.selectionGroups(ids); + return groups.some(g => !gs.teams[0].melds.some(m => m.rank === g.rank && g.rank !== '3')); + } + + beforeLayout() { + this.suggested = new Set(); + if (this.settings.hints && this.isMyTurn() && this.gs.phase === 'play') { + const tip = this.coach(); + if (tip?.groups && !this.selected.size) tip.groups.forEach(g => g.ids.forEach(id => this.suggested.add(id))); + else if (tip?.id && !this.selected.size) this.suggested.add(tip.id); + } + this.fits = new Set(); + if (this.settings.hints && this.gs.current === 0 && this.gs.phase === 'play') { + const ranks = new Set(this.gs.teams[0].melds.filter(m => m.rank !== '3').map(m => m.rank)); + for (const c of this.gs.hands[0]) if (!isWild(c) && ranks.has(c.rank)) this.fits.add(c.id); + } + } + + decorate(c, v) { + let mark = '', markColor = '#ffd35a'; + let chip = ''; + let glow = false, tint = 0xffd35a, glowA = 1; + if (v.kind === 'hand' && v.seat === 0) { + if (this.fits?.has(v.card.id)) { mark = '+'; markColor = '#7cf0a0'; } + if (this.suggested?.has(v.card.id)) { mark = '★'; markColor = '#7cf0a0'; glow = true; tint = 0x7cf0a0; glowA = 0.55; } + if (this.selected.has(v.card.id)) { glow = true; tint = 0xffffff; glowA = 1; } + } else if (v.kind === 'meld' && v.canasta && v.topOfStack) { + chip = String(v.size); + glow = true; + tint = v.natural ? 0xffd35a : 0xd8dce8; + glowA = 0.85; + } else if (v.kind === 'discard' && v.top && this.isMyTurn() && this.gs.phase === 'draw' && this.takeInfo().plan) { + glow = true; tint = 0x7cf0a0; glowA = 0.8; + } + c.mark.setText(mark).setColor(markColor).setVisible(!!mark && v.faceUp); + c.chip.setText(chip).setFontSize(18).setVisible(!!chip && v.faceUp); + c.glow.setVisible(glow).setTint(tint).setAlpha(glowA); + } + + afterLayout() { + this.drawSlabs(); + this.drawPileHints(); + this.drawBands(); + this.drawReadout(); + this.updateBadges(); + const gs = this.gs; + const n = gs.stock.length; + this.stockTxt.setText(n ? `${n} left` : 'stock gone').setColor(n < 12 ? '#ff9a7a' : '#e8dcc0'); + const top = G.topDiscard(gs); + this.pileTxt.setText(gs.discard.length ? `${gs.discard.length} card${gs.discard.length === 1 ? '' : 's'}` : 'empty'); + this.pileFlag.setText(gs.frozen ? '❄ FROZEN' : gs.rules.alwaysFrozen ? '❄ always frozen' : top && isBlackThree(top) ? 'BLOCKED' : '') + .setColor(gs.frozen || gs.rules.alwaysFrozen ? ICE : AMBER); + } + + drawSlabs() { + const g = this.slabG; + g.clear(); + const n = this.gs.stock.length; + if (n <= 1) return; + const base = L.stock; + const lift = stackLift(n, base.s, 0.08, 12); + const layers = Math.max(1, Math.min(9, Math.ceil(lift / 1.5))); + 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 ? 0x1d5a5c : 0x123a3c, 1); + g.fillRoundedRect(base.x - hw, y - hh, hw * 2, hh * 2, 8 * base.s); + } + } + + drawPileHints() { + const g = this.pileG; + g.clear(); + if (!this.isMyTurn() || this.gs.phase !== 'draw') return; + const ring = (p, color, a, w = 4) => { + const hw = (CARD_W / 2) * p.s + 12, hh = (CARD_H / 2) * p.s * SQ + 12; + g.lineStyle(w, color, a); + g.strokeRoundedRect(p.x - hw, p.y - hh, hw * 2, hh * 2, 14); + }; + if (this.gs.stock.length) ring(this.deckTop(), 0xe8dcc0, 0.55); + const take = this.takeInfo(); + if (take.plan) ring(L.discard, 0x7cf0a0, 0.75); + if (!this.settings.hints) return; + const tip = this.coach(); + if (!tip) return; + if (tip.type === 'take') ring(L.discard, 0x7cf0a0, 1, 6); + else if (tip.type === 'stock') ring(this.deckTop(), 0x7cf0a0, 1, 6); + } + + label(i) { + if (!this.labelPool[i]) { + this.labelPool[i] = this.add.text(0, 0, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: INK, align: 'center', stroke: '#0a1a1c', strokeThickness: 4, + }).setOrigin(0.5).setDepth(D.labels + 1); + } + return this.labelPool[i]; + } + + /** Column captions, the ghost slot and drop-target glows. */ + drawBands() { + const g = this.bandG; + g.clear(); + this.targetG.clear(); + const gs = this.gs; + let li = 0; + const ghost = this.ghostWanted(); + const staged = this.isMyTurn() && gs.phase === 'play' ? this.selectionGroups(this.dragState ? [...new Set([...this.selected, this.dragState.id])] : undefined) : { groups: [] }; + const stagedRanks = new Set(staged.groups.map(x => x.rank)); + for (const team of [0, 1]) { + const t = gs.teams[team]; + const cols = bandColumns(team, t.melds, t.redThrees.length, team === 0 && ghost); + // the side's name at the far left of its band + const side = this.label(li++); + const sx = Math.max(150, (cols[0]?.x ?? BAND.cx) - 110); + const emptyX = cols.length ? sx : BAND.cx; + side.setText(team === 0 ? 'OUR MELDS' : 'THEIR MELDS').setPosition(cols.length ? sx : emptyX, BAND.top[team] + 24).setColor(TEAM_HEX[team]).setFontSize(cols.length ? 13 : 16).setVisible(true) + .setAlpha(cols.length ? 0.8 : 0.5); + if (!cols.length) side.setText(team === 0 ? 'OUR MELDS GO HERE' : 'THEIR MELDS'); + for (const col of cols) { + const lab = this.label(li++); + const ly = columnLabelY(col, team); + if (col.kind === 'red') { + const n = t.redThrees.length; + const v = n === 4 ? ALL_RED_THREES : n * RED_THREE; + lab.setText(`RED 3s ${t.melded ? '+' : '−'}${v}`).setPosition(col.x, ly).setColor(t.melded ? '#ff8a9a' : RED).setFontSize(13).setVisible(true).setAlpha(1); + } else if (col.kind === 'meld') { + const m = col.meld; + const n = m.cards.length; + if (isCanasta(m)) { + const nat = isNaturalCanasta(m); + lab.setText(`${nat ? 'NATURAL' : 'MIXED'}\n+${nat ? NATURAL_CANASTA : MIXED_CANASTA}`).setColor(nat ? '#ffd35a' : '#dfe4ee'); + } else { + const wild = wildsIn(m.cards); + lab.setText(`${rankLabel(m.rank)}${m.rank === '3' ? ' (black)' : ''} · ${n}/7${wild ? `\n${wild} wild` : ''}`).setColor(n >= 5 ? AMBER : INK); + } + lab.setPosition(col.x, ly + (isCanasta(m) && team === 0 ? -BAND.step * 3 : 0)).setFontSize(13).setVisible(true).setAlpha(1); + // staging glow on our melds that the selection would extend + if (team === 0 && stagedRanks.has(m.rank)) { + const r = columnRect(col, isCanasta(m) ? n : n, { canasta: isCanasta(m) }); + const ok = !staged.problem && !G.checkMelds(gs, staged.groups).problem; + g.lineStyle(3, ok ? 0x7cf0a0 : 0xff7a6a, 0.9); + g.strokeRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 10); + } + const hot = this.dragState?.target?.type === 'meld' && this.dragState.target.rank === m.rank && team === 0; + if (hot) { + const r = columnRect(col, n, { canasta: isCanasta(m) }); + this.targetG.lineStyle(5, this.dragState.target.ok ? 0x7cf0a0 : 0xff7a6a, 1); + this.targetG.strokeRoundedRect(r.x0 - 4, r.y0 - 4, r.x1 - r.x0 + 8, r.y1 - r.y0 + 8, 12); + } + } else if (col.kind === 'ghost') { + const r = columnRect(col, 3); + const ok = !staged.problem && !G.checkMelds(gs, staged.groups).problem; + const hot = this.dragState?.target?.type === 'ghost'; + g.fillStyle(ok ? 0x7cf0a0 : 0xffc861, hot ? 0.2 : 0.08); + g.fillRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 10); + g.lineStyle(hot ? 4 : 2, ok ? 0x7cf0a0 : 0xffc861, 0.9); + g.strokeRoundedRect(r.x0, r.y0, r.x1 - r.x0, r.y1 - r.y0, 10); + const newRanks = staged.groups.filter(x => !t.melds.some(m => m.rank === x.rank)).map(x => rankLabel(x.rank)); + lab.setText(`NEW\n${newRanks.join(' · ')}`).setPosition(col.x, col.y + 10).setColor(ok ? GREEN : AMBER).setFontSize(14).setVisible(true).setAlpha(1); + } + } + } + for (let i = li; i < this.labelPool.length; i++) this.labelPool[i].setVisible(false); + } + + /** The line above your hand: what a selection would meld, the first-meld meter, the take preview. */ + drawReadout() { + const g = this.readG; + g.clear(); + this.meterTxt.setText(''); + const gs = this.gs; + const show = (text, color = INK) => this.readTxt.setText(text).setColor(color); + if (!this.isMyTurn()) { show(''); return; } + const team = gs.teams[0]; + const need = G.minimumFor(gs, 0); + if (gs.phase === 'draw') { + const t = this.takeInfo(); + if (t.plan) show(`Take the pile (${gs.discard.length}): ${this.describeTake(t.plan)}`, GREEN); + else show(gs.stock.length ? `Draw from the stock${t.problem && G.topDiscard(gs) ? ` — pile: ${t.problem.charAt(0).toLowerCase()}${t.problem.slice(1)}` : ''}` : (t.problem ?? 'Nothing to take — the hand ends'), gs.stock.length ? MUTED : AMBER); + return; + } + const sel = this.dragState ? [...new Set([...this.selected, this.dragState.id])] : [...this.selected]; + let staged = 0; + if (sel.length) { + const sg = this.selectionGroups(sel); + if (sel.length === 1 && !sg.groups.length) show(`Discard the ${cardName(gs.hands[0].find(c => c.id === sel[0]))}? (Enter)`, INK); + else if (sg.problem) show(sg.problem, RED); + else { + const chk = G.checkMelds(gs, sg.groups); + const desc = sg.groups.map(x => this.describeGroup(x)).join(' + '); + staged = chk.value; + if (chk.problem) { + if (sel.length === 1) show(`${cardName(gs.hands[0].find(c => c.id === sel[0]))}: discard it (Enter), or select more to meld`, INK); + else show(`${desc} — ${chk.problem}`, RED); + } else { + const tail = chk.newCanastas.length ? ` — CANASTA!` : chk.goingOut ? ' — and out!' : ''; + show(`Meld ${desc} → ${chk.value} pts${tail} (M)`, GREEN); + } + } + } else if (!team.melded) { + const best = this.bestFirst(); + show(best >= need ? `First meld needs ${need}: your hand can make ${best} — select the cards (H shows them)` : `First meld needs ${need} — your hand makes ${best || 'no meld'} so far`, best >= need ? AMBER : MUTED); + } else { + show(this.gs.hands[0].length === 1 ? 'Discard your last card to go out' : 'Select cards to meld (+ = fits a meld), or one card to discard', MUTED); + } + // the first-meld meter + if (!team.melded) { + const w = 340, h = 12, x0 = READOUT.x - w / 2, y = READOUT.y + 30; + const max = Math.max(need * 1.6, 80); + g.fillStyle(0x0a1a1c, 0.8); + g.fillRoundedRect(x0 - 5, y - h / 2 - 5, w + 10, h + 10, 8); + g.fillStyle(0x2a3a3a, 1); + g.fillRoundedRect(x0, y - h / 2, w, h, 6); + if (staged > 0) { + g.fillStyle(staged >= need ? 0x5ee0a0 : 0xffc861, 1); + g.fillRoundedRect(x0, y - h / 2, Math.max(10, Math.min(1, staged / max) * w), h, 6); + } + const nx = x0 + (need / max) * w; + g.lineStyle(3, 0xffffff, 0.9); + g.lineBetween(nx, y - h, nx, y + h); + this.meterTxt.setText(`${staged} / ${need}`).setColor(staged >= need ? GREEN : AMBER); + } + } + + describeGroup(grp) { + const gs = this.gs; + const cards = grp.ids.map(id => gs.hands[0].find(c => c.id === id) ?? cardFromId(id)); + const nat = cards.filter(c => !isWild(c)).length, wild = cards.length - nat; + const onto = gs.teams[0].melds.some(m => m.rank === grp.rank && grp.rank !== '3'); + const base = nat ? `${nat} ${rankWord(grp.rank, nat)}` : ''; + const w = wild ? `${wild} wild` : ''; + return `${[base, w].filter(Boolean).join(' + ')}${onto ? ` onto our ${rankWord(grp.rank, 2)}` : ''}`; + } + + describeTake(plan) { + const gs = this.gs; + const top = G.topDiscard(gs); + const mine = plan.ids.map(id => cardName(gs.hands[0].find(c => c.id === id))); + let s = mine.length ? `${mine.join(' ')} with the ${cardName(top)}` : `the ${cardName(top)} onto our ${rankWord(top.rank, 2)}`; + if (plan.extra?.length) { + const v = valueOf([top, ...plan.ids.map(id => gs.hands[0].find(c => c.id === id))]) + plan.extra.reduce((a, g) => a + valueOf(g.ids.map(id => gs.hands[0].find(c => c.id === id))), 0); + s += `, plus ${plan.extra.map(g => this.describeGroup(g)).join(', ')} (${v} for the first meld)`; + } + return s; + } + + // ── Plates ───────────────────────────────────────────────────────────────── + updatePlates() { + if (!this.gs) return; + const gs = this.gs; + for (let s = 0; s < 4; s++) { + const pl = this.plates[s]; + if (!pl) continue; + const t = TEAM_OF_SEAT[s]; + pl.scoreTxt.setText(gs.scores[t].toLocaleString()).setColor(TEAM_HEX[t]); + const n = gs.hands[s].length; + let info = s === 0 ? `${n} cards` : `${n} card${n === 1 ? '' : 's'}`; + if (s === 2) info += ' · partner'; + if (gs.stats[s].piles && s) info += ` · ${gs.stats[s].piles} pile${gs.stats[s].piles === 1 ? '' : 's'}`; + pl.infoTxt.setText(info).setColor(t === 0 ? '#f2c8b8' : '#a8e8e0'); + const status = s === gs.dealer ? 'dealer' : ''; + pl.statusTxt.setText(status).setColor(MUTED); + const active = !G.isOver(gs) && G.actor(gs) === s && ['human', 'ai', 'answer'].includes(this.mode); + this.setPlateActive(s, active); + } + } + + // ── Dock ─────────────────────────────────────────────────────────────────── + updateDock() { + if (!this.gs || !this.prompt) return; + const gs = this.gs; + const hint = { label: 'Hint (H)', act: () => this.flashHint() }; + if (this.mode === 'deal') { this.setDock('Shuffling and dealing…'); return; } + if (this.mode === 'summary') { this.setDock('Hand over — counting it up.'); return; } + if (this.mode === 'answer') { this.setDock('Your partner wants to go out…'); return; } + if (this.mode === 'human' && gs.current === 0) { + if (gs.phase === 'draw') { + const t = this.takeInfo(); + if (!gs.stock.length) { + const must = G.mustTake(gs); + this.setDock(must ? 'The stock is gone and the top card fits our meld — take the pile.' : 'The stock is gone. Take the pile, or pass and the hand ends.', [ + { label: `Take pile (T)`, act: () => this.humanTake(), enabled: !!t.plan, hot: !!t.plan }, + { label: 'Pass (P)', act: () => this.humanPass(), enabled: !must }, + hint, + ]); + return; + } + this.setDock(t.plan ? `Your turn: draw, or take the ${gs.discard.length}-card pile.` : 'Your turn: draw from the stock.', [ + { label: 'Draw (D)', act: () => this.humanDraw(), hot: !t.plan }, + { label: `Take pile (T)`, act: () => this.humanTake(), enabled: !!t.plan, hot: !!t.plan }, + hint, + ]); + return; + } + if (gs.phase === 'play') { + const sg = this.selectionGroups(); + const chk = sg.groups.length && !sg.problem ? G.checkMelds(gs, sg.groups) : null; + const canMeld = !!chk && !chk.problem; + const needAsk = chk && chk.problem && gs.rules.askPartner && !gs.turn.asked && /Ask your partner/.test(chk.problem); + const one = this.selected.size === 1 ? gs.hands[0].find(c => c.id === [...this.selected][0]) : null; + const undo = this.turnSnap && this.turnSnap !== gs && this.turnSnap.teams[0].melds.length !== undefined; + const prompt = !gs.teams[0].melded ? `Meld at least ${G.minimumFor(gs, 0)} points first, or just discard.` : gs.hands[0].length === 1 ? 'Discard your last card to go out.' : 'Meld what you like, then discard one card.'; + this.setDock(prompt, [ + { label: 'Meld (M)', act: () => this.humanMeld(), enabled: canMeld || !!needAsk, hot: canMeld }, + { label: one ? `Discard ${cardName(one)}` : 'Discard (Enter)', act: () => this.humanDiscard(), enabled: !!one, hot: !!one && !canMeld }, + { label: 'Undo (U)', act: () => this.humanUndo(), enabled: !!undo && this.turnHasMelds() }, + hint, + ]); + return; + } + } + if (this.mode === 'ai') { + const s = G.actor(gs); + const verb = gs.phase === 'ask' ? 'is deciding' : gs.phase === 'draw' ? 'is drawing' : 'is playing'; + this.setDock(`${this.nameForSeat(s)} ${verb}…`); + return; + } + this.setDock(''); + } + + turnHasMelds() { + const a = this.turnSnap, b = this.gs; + if (!a) return false; + return a.hands[0].length !== b.hands[0].length; + } + + // ── Human actions ────────────────────────────────────────────────────────── + notYet() { + if (this.mode === 'ai') this.floatText({ x: CX, y: 770 }, 'Hang on — not your turn yet', '#f2d6a0', { size: 20 }); + } + + humanDraw() { + if (!this.canAct()) { this.notYet(); return; } + const gs = this.gs; + if (gs.phase !== 'draw') { this.floatText({ x: CX, y: 770 }, 'You\'ve drawn — meld, then discard', AMBER, { size: 20 }); return; } + const next = G.drawStock(gs); + if (next === gs) return; + playSound(this, SFX.CARD_DEAL); + this.selected.clear(); + this.turnSnap = null; + this.commit(next); + if (G.isOver(next)) { this.advance(); return; } + this.turnSnap = next; + this.updateDock(); + } + + humanTake() { + if (!this.canAct()) { this.notYet(); return; } + const gs = this.gs; + if (gs.phase !== 'draw') return; + const t = this.takeInfo(); + if (!t.plan) { this.nudgePile(t.problem); return; } + const next = G.takePile(gs, t.plan); + if (next === gs) return; + this.selected.clear(); + this.commit(next); + if (G.isOver(next)) { this.advance(); return; } + this.turnSnap = next; + this.updateDock(); + } + + humanPass() { + if (!this.canAct() || this.gs.phase !== 'draw' || this.gs.stock.length) return; + const next = G.passStock(this.gs); + if (next === this.gs) { this.floatText({ x: CX, y: 770 }, 'The top card fits our meld — we must take the pile', AMBER, { size: 20 }); return; } + this.commit(next); + this.advance(); + } + + nudgePile(problem) { + const top = G.topDiscard(this.gs); + if (top) this.nudge(top.id); + this.floatText({ x: L.discard.x, y: L.discard.y - 110 }, problem ?? 'You can\'t take the pile', RED, { size: 20, ms: 2200, rise: 14 }); + } + + toggleCard(id, { rank = false } = {}) { + if (!this.canAct()) { this.notYet(); return; } + const gs = this.gs; + if (gs.phase !== 'play') { + this.floatText({ x: CX, y: 770 }, 'Draw first — the stock, or take the pile', AMBER, { size: 20 }); + return; + } + const card = gs.hands[0].find(c => c.id === id); + if (!card) return; + if (rank && !isWild(card)) { + const same = gs.hands[0].filter(c => c.rank === card.rank && (card.rank !== '3' || isBlackThree(c))); + const all = same.every(c => this.selected.has(c.id)); + for (const c of same) if (all) this.selected.delete(c.id); else this.selected.add(c.id); + } else if (this.selected.has(id)) this.selected.delete(id); + else this.selected.add(id); + playSoundEx(this, SFX.UI_PICK, { volume: 0.35 }); + this.layout({ duration: 140 }); + this.updateDock(); + } + + humanMeld(groups = null) { + if (!this.canAct() || this.gs.phase !== 'play') return false; + const gs = this.gs; + let gr = groups; + if (!gr) { + const sg = this.selectionGroups(); + if (sg.problem || !sg.groups.length) { this.floatText({ x: CX, y: 770 }, sg.problem ?? 'Select cards to meld', RED, { size: 20 }); return false; } + gr = sg.groups; + } + const chk = G.checkMelds(gs, gr); + if (chk.problem) { + if (gs.rules.askPartner && !gs.turn.asked && /Ask your partner/.test(chk.problem)) { this.askToGoOut({ groups: gr }); return false; } + this.floatText({ x: CX, y: 770 }, chk.problem, RED, { size: 20, ms: 2200 }); + for (const id of gr.flatMap(x => x.ids)) this.nudge(id); + return false; + } + const next = G.meldCards(gs, gr); + if (next === gs) return false; + playSound(this, SFX.CARD_PLACE); + this.selected.clear(); + this.commit(next); + if (G.isOver(next)) { this.mode = 'idle'; this.advance(); } return true; } - toggleSelect(id) { - if (this.busy || this.state.currentPlayer !== 0 || this.state.phase !== 'meld') { - // Selection only matters in the meld phase. - if (this.state.phase !== 'meld') return; + humanDiscard(id = null) { + if (!this.canAct() || this.gs.phase !== 'play') return false; + const gs = this.gs; + const pick = id ?? (this.selected.size === 1 ? [...this.selected][0] : null); + if (!pick) { this.floatText({ x: CX, y: 770 }, 'Select one card to discard', AMBER, { size: 20 }); return false; } + const p = G.discardProblem(gs, pick); + if (p) { + if (gs.hands[0].length === 1 && gs.rules.askPartner && !gs.turn.asked && G.hasGoOutCanastas(gs, 0)) { this.askToGoOut({ discard: pick }); return false; } + this.nudge(pick); + this.floatText({ x: CX, y: 770 }, p, RED, { size: 20 }); + return false; } - if (this.selected.has(id)) this.selected.delete(id); else this.selected.add(id); - playSound(this, SFX.PIECE_CLICK); - this.renderDynamic(); - this.updateMeldPhaseUi(); - } - - async humanDraw(kind) { - if (this.busy) return; - this.busy = true; - this.hideActionButtons(); - - let drawnCard, fromX, fromY, faceUp, flip; - if (kind === 'stock') { - drawnCard = this.state.stock[0]; - fromX = STOCK.x; fromY = STOCK.y; faceUp = false; flip = true; - this.state = drawStock(this.state); - playSound(this, SFX.CARD_DEAL); - } else { - drawnCard = this.state.discard[this.state.discard.length - 1]; - fromX = DISCARD.x; fromY = DISCARD.y; faceUp = true; flip = false; - const plan = takePlan(this.state, 0); - if (!plan) { this.busy = false; return; } - this.state = takeDiscard(this.state, plan); - playSound(this, SFX.CARD_SHOW); - } - - // Compute where the card will land in the human hand after the state update. - // For discard take, the top card goes to a meld (not hand), so idx = -1 → fallback centre. - const me = this.state.players[0].hand.slice().sort(this.handSort); - const total = (me.length - 1) * HAND_GAP + CARD_W; - const idx = drawnCard ? me.findIndex(c => c.id === drawnCard.id) : -1; - const toX = idx >= 0 - ? SEAT[0].hand.x - total / 2 + CARD_W / 2 + idx * HAND_GAP - : SEAT[0].hand.x; - const toY = SEAT[0].hand.y; - - this.selected.clear(); - if (drawnCard) { - await this.animateDraw({ fromX, fromY, toX, toY, card: drawnCard, faceUp, flip }); - } - this.renderDynamic(); - this.busy = false; - this.advance(); - } - - humanMeld() { - if (this.busy || this.selected.size === 0) return; - const ids = [...this.selected]; - const cards = ids.map((id) => this.state.players[0].hand.find((c) => c.id === id)).filter(Boolean); - const naturals = cards.filter((c) => !isWild(c)); - let rank = naturals[0]?.rank; - if (rank && !naturals.every((c) => c.rank === rank)) return this.toast('Pick one rank to meld', CX, 560, '#e06c75'); - if (!rank) { - // All wilds — only valid as an addition to an existing single team meld. - const melds = this.state.teams[0].melds; - if (melds.length !== 1) return this.toast('Drag wild cards onto a specific meld', CX, 560, '#e06c75'); - rank = melds[0].rank; - } - const next = meld(this.state, rank, ids); - if (next === this.state) return this.toast('Not a legal meld', CX, 560, '#e06c75'); - this.state = next; - this.selected.clear(); + const card = gs.hands[0].find(c => c.id === pick); + // a friendly warning before feeding the next player the pile + const next = G.discardCard(gs, pick); + if (next === gs) return false; playSound(this, SFX.CARD_PLACE); - this.renderDynamic(); - this.updateMeldPhaseUi(); - } - - humanResetTurn() { - if (this.busy || !this.turnStartState) return; - this.state = this.turnStartState; this.selected.clear(); - playSound(this, SFX.CARD_PLACE); - this.renderDynamic(); - this.updateMeldPhaseUi(); + this.turnSnap = null; + this.mode = 'idle'; + this.commit(next); + if (isWild(card) && !G.isOver(next)) this.say('youFroze'); + this.time.delayedCall(320, () => this.advance()); + return true; } - async humanDiscard({ animate = true } = {}) { - if (this.busy || this.selected.size !== 1) return; - if (!this.discardAllowed()) { - return this.toast(`Initial meld needs ${this.minNeeded()} points`, CX, 560, '#e06c75'); - } - this.busy = true; - this.hideActionButtons(); - - const id = [...this.selected][0]; - const card = this.state.players[0].hand.find((c) => c.id === id); - - // Compute card's current hand position before state changes. - const me = this.state.players[0].hand.slice().sort(this.handSort); - const total = (me.length - 1) * HAND_GAP + CARD_W; - const idx = me.findIndex((c) => c.id === id); - const fromX = SEAT[0].hand.x - total / 2 + CARD_W / 2 + idx * HAND_GAP; - const fromY = SEAT[0].hand.y; - - const goingOut = this.state.players[0].hand.length === 1; - this.state = discard(this.state, id); - this.turnStartState = null; - this.selected.clear(); - - if (animate && card) { - await this.animateDraw({ - fromX, fromY, toX: DISCARD.x, toY: DISCARD.y, - card, faceUp: true, flip: false, duration: 1000, - }); - } - - playSound(this, SFX.CARD_PLACE); - if (goingOut && teamHasCanasta(this.state, 0)) this.toast('You go out!', CX, 560, '#f0d77a'); - this.renderDynamic(); - this.busy = false; - this.advance(); + askToGoOut(pending) { + const gs = this.gs; + const next = G.askGoOut(gs); + if (next === gs) return; + this.pendingOut = pending; + this.mode = 'idle'; + this.commit(next); + this.time.delayedCall(400, () => this.advance()); } - // ── Hand-over & game-over ──────────────────────────────────────────────────── - addMiniPortrait(layer, seat, cx, cy, radius, depth) { - const size = radius * 2; - const backing = this.add.graphics().setDepth(depth); - backing.fillStyle(0x1a1208, 1); - backing.fillCircle(cx, cy, radius); - layer.push(backing); - - if (seat === 0) { - const avatarKey = Object.keys(this.textures.list).find(k => k.startsWith('player-avatar-')); - if (avatarKey) { - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); maskG.fillCircle(cx, cy, radius); - layer.push(this.add.image(cx, cy, avatarKey).setDisplaySize(size, size) - .setMask(maskG.createGeometryMask()).setDepth(depth + 1)); - } else { - // Show initial while avatar loads; swap it in when the texture arrives. - const placeholder = this.add.text(cx, cy, 'Y', { - fontFamily: '"Julius Sans One"', fontSize: `${Math.round(radius * 0.85)}px`, - color: HEX(THEME.brassHi), - }).setOrigin(0.5).setDepth(depth + 1); - layer.push(placeholder); - const onTex = (key) => { - if (!key.startsWith('player-avatar-')) return; - this.textures.off('addtexture', onTex); - if (!placeholder.active) return; - placeholder.destroy(); - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); maskG.fillCircle(cx, cy, radius); - this.add.image(cx, cy, key).setDisplaySize(size, size) - .setMask(maskG.createGeometryMask()).setDepth(depth + 1); - }; - this.textures.on('addtexture', onTex); - } - } else { - const opp = this.seatOpp[seat]; - if (this.textures.exists('opponents')) { - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); maskG.fillCircle(cx, cy, radius); - layer.push(this.add.image(cx, cy, 'opponents', opp?.spriteIndex ?? 0) - .setDisplaySize(size, size) - .setMask(maskG.createGeometryMask()) - .setDepth(depth + 1)); - } - } - - const ring = this.add.graphics().setDepth(depth + 2); - ring.lineStyle(2.5, THEME.rail, 1); ring.strokeCircle(cx, cy, radius); - layer.push(ring); - } - - showHandOver() { - this.hideActionButtons(); - this.updateTurnRing(); - const scores = this.state.handScores; - const w = 840, h = 540, x = CX - w / 2, y = CY - h / 2 + 20; - const halfW = w / 2; // 420 - const layer = []; - const g = this.add.graphics().setDepth(D.modal); - g.fillStyle(0x000000, 0.6); g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - g.fillStyle(THEME.feltEdge, 1); g.fillRoundedRect(x, y, w, h, 20); - g.lineStyle(3, THEME.brass, 1); g.strokeRoundedRect(x, y, w, h, 20); - layer.push(g); - layer.push(this.add.text(CX, y + 36, 'Hand Over', { fontFamily: 'Righteous', fontSize: '40px', color: HEX(THEME.brassHi) }).setOrigin(0.5).setDepth(D.modalUI)); - - // Portrait radius and diagonal offset for the overlapping pair - const PR = 22; - const names = ['YOUR TEAM', 'OPPONENTS']; - [0, 1].forEach((teamId, idx) => { - const d = scores[idx]; - const col = idx === 0 ? THEME.team0 : THEME.team1; - const colX = x + idx * halfW; - const px = colX + 95; - const portMidY = y + 215; - - // Two portraits overlapping diagonally — back (up-left) then front (down-right) - const [backSeat, frontSeat] = teamId === 0 ? [2, 0] : [3, 1]; - this.addMiniPortrait(layer, backSeat, colX + 36, portMidY - 12, PR, D.modalUI); - this.addMiniPortrait(layer, frontSeat, colX + 58, portMidY + 10, PR, D.modalUI + 2); - - layer.push(this.add.text(px, y + 92, names[idx], { fontFamily: '"Julius Sans One"', fontSize: '22px', color: HEX(col) }).setDepth(D.modalUI)); - const lines = [ - `Melds ${d.meldPoints}`, - `Canasta bonus ${d.canastaBonus}`, - `Red threes ${d.redThreeBonus}`, - d.goOut ? `Go out ${d.goOut}` : null, - `In hand -${d.handPenalty}`, - `———`, - `Hand total ${d.total}`, - `Match ${this.state.teams[teamId].score}`, - ].filter(Boolean); - layer.push(this.add.text(px, y + 128, lines.join('\n'), { - fontFamily: 'Righteous', fontSize: '20px', color: COLORS.textHex, lineSpacing: 8, - }).setDepth(D.modalUI)); + resumePendingOut() { + const p = this.pendingOut; + this.pendingOut = null; + if (!p || this.gs.turn.asked !== 'yes') return; + this.time.delayedCall(300, () => { + if (p.groups) this.humanMeld(p.groups); + else if (p.discard) this.humanDiscard(p.discard); }); - layer.push(new Button(this, CX, y + h - 52, 'Next Round', () => this.onNextHand(), - { width: 280, height: 56, fontSize: 24 }).setDepth(D.modalUI)); - this.handOverLayer = layer; } - onNextHand() { - this.btn.next.setVisible(false); - (this.handOverLayer || []).forEach((o) => o.destroy()); - this.handOverLayer = null; - this.state = startNextHand(this.state); + humanUndo() { + if (!this.canAct() || this.gs.phase !== 'play' || !this.turnSnap || !this.turnHasMelds()) return; + const asked = this.gs.turn.asked; + const back = JSON.parse(JSON.stringify(this.turnSnap)); + back.turn.asked = asked; + back.log = this.gs.log.slice(0, this.turnSnap.log.length); + this.gs = back; + this.turnSnap = back; + this.cache.key = ''; this.selected.clear(); - playSound(this, SFX.CARD_SHUFFLE); - this.renderDynamic(); - this.advance(); + playSoundEx(this, SFX.REWIND ?? SFX.UI_PICK, { volume: 0.4 }); + this.sortHand(); + this.layout(); + this.updatePlates(); + this.updatePad(); + this.updateDock(); } - showGameOver() { - this.hideActionButtons(); - this.btn.next.setVisible(false); - this.updateTurnRing(); - (this.handOverLayer || []).forEach((o) => o.destroy()); - const won = this.state.winnerTeam === 0; - playSound(this, won ? SFX.CASINO_WIN : SFX.CASINO_LOSE); - this.postHistory(won ? 'win' : 'loss'); - - const g = this.add.graphics().setDepth(D.modal); - g.fillStyle(0x000000, 0.72); g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); - g.fillStyle(THEME.feltMid, 1); g.fillRoundedRect(CX - 380, CY - 170, 760, 340, 24); - g.lineStyle(4, THEME.brass, 1); g.strokeRoundedRect(CX - 380, CY - 170, 760, 340, 24); - this.add.text(CX, CY - 96, won ? 'Your Team Wins!' : 'Opponents Win', { - fontFamily: 'Righteous', fontSize: '56px', color: won ? HEX(THEME.brassHi) : HEX(THEME.team1), - }).setOrigin(0.5).setDepth(D.modalUI); - this.add.text(CX, CY - 16, `${this.state.teams[0].score} – ${this.state.teams[1].score}`, { - fontFamily: 'Righteous', fontSize: '44px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modalUI); - new Button(this, CX, CY + 92, 'Back to Menu', () => this.scene.start('GameMenu'), - { width: 300, fontSize: 26 }).setDepth(D.modalUI); + flashHint() { + if (!this.gs || !this.isMyTurn()) return; + const tip = this.coach(); + if (!tip) return; + this.floatText({ x: CX, y: 770 }, tip.text, '#7cf0a0', { size: 22, ms: 3000, rise: 14 }); + if (this.gs.phase === 'play') { + if (tip.groups) { this.selected = new Set(tip.groups.flatMap(g => g.ids)); } + else if (tip.id) { this.selected = new Set([tip.id]); } + this.layout({ duration: 140 }); + this.updateDock(); + } } - // ── Helpers ────────────────────────────────────────────────────────────────── - toast(text, x, y, color = '#f2ead8') { - const t = this.add.text(x, y, text, { - fontFamily: 'Righteous', fontSize: '30px', color, - }).setOrigin(0.5).setDepth(D.toast).setShadow(0, 0, 'rgba(255,207,74,0.7)', 12); - this.tweens.add({ targets: t, y: y - 50, alpha: 0, duration: 1200, ease: 'Cubic.easeOut', onComplete: () => t.destroy() }); + // ── 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)); } - async postHistory(result) { - if (this.recorded) return; - this.recorded = true; - try { - await api.post('/history/single-player', { - slug: 'canasta', - score: this.state.teams[0].score, - opponentScores: [this.state.teams[1].score], - result, - }); - } catch { /* non-fatal */ } + handIdAt(pt) { + if (!this.gs) 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; } - delay(ms) { return new Promise((resolve) => this.time.delayedCall(ms, resolve)); } + busyMode() { return ['deal', '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 (inPose(pointer, this.deckTop(), 10)) { this.isMyTurn() ? this.humanDraw() : this.notYet(); return; } + if (inPose(pointer, L.discard, 14)) { + if (!this.isMyTurn()) { this.notYet(); return; } + if (this.gs.phase === 'play') { + if (this.selected.size === 1) this.humanDiscard(); + else this.floatText({ x: CX, y: 770 }, 'Select one card to discard (or drag it here)', AMBER, { size: 20 }); + } else this.humanTake(); + return; + } + // clicking one of our melds with cards selected adds them to it + if (this.isMyTurn() && this.gs.phase === 'play' && this.selected.size) { + const t = this.meldTargetAt(pointer, [...this.selected]); + if (t) this.dropOnTarget(t, [...this.selected]); + } + } + + 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() && (inPose(pointer, this.deckTop(), 10) || inPose(pointer, L.discard, 14))) 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; + const now = this.time.now; + const dbl = this.lastClick.id === pd.id && now - this.lastClick.t < 380; + this.lastClick = { id: pd.id, t: now }; + if (dbl) { + // second click of a double-click: undo the single toggle, then select the whole rank + this.toggleCard(pd.id); + this.toggleCard(pd.id, { rank: true }); + this.lastClick = { id: null, t: 0 }; + return; + } + this.toggleCard(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); + } + + /** Cards being dragged: the grabbed card plus the selection (if it's part of it). */ + dragIds() { + const ds = this.dragState; + if (!ds) return []; + return this.selected.has(ds.id) ? [...this.selected] : [ds.id]; + } + + meldTargetAt(pt, ids) { + const gs = this.gs; + const t = gs.teams[0]; + const cols = bandColumns(0, t.melds, t.redThrees.length, this.ghostWanted()); + for (const col of cols) { + if (col.kind === 'red') continue; + const n = col.kind === 'meld' ? col.meld.cards.length : 3; + const r = columnRect(col, n, { canasta: col.kind === 'meld' && isCanasta(col.meld) }); + if (!inRect(pt, { x0: r.x0 - 8, x1: r.x1 + 8, y0: r.y0 - 30, y1: r.y1 + 30 })) continue; + const groups = this.groupsForTarget(col, ids); + const ok = !!groups && !G.checkMelds(gs, groups).problem; + return col.kind === 'ghost' ? { type: 'ghost', groups, ok } : { type: 'meld', rank: col.rank, groups, ok }; + } + return null; + } + + /** What dropping `ids` on a column would meld. */ + groupsForTarget(col, ids) { + const gs = this.gs; + const cards = ids.map(id => gs.hands[0].find(c => c.id === id)).filter(Boolean); + if (col.kind === 'meld') { + if (cards.every(c => isWild(c) || c.rank === col.rank)) return [{ rank: col.rank, ids: cards.map(c => c.id) }]; + return null; + } + const sg = this.selectionGroups(ids); + return sg.problem ? null : sg.groups; + } + + dropTargetAt(pt) { + const gs = this.gs; + if (this.isMyTurn() && gs.phase === 'play') { + const t = this.meldTargetAt(pt, this.dragIds()); + if (t) return t; + if (inPose(pt, L.discard, 50)) return { type: 'discard' }; + } + const n = gs.hands[0].length; + if (inRect(pt, fanZone(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; + 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 x = pointer.x + ds.offX, y = pointer.y + ds.offY; + const t = Math.max(0, Math.min(1, (y - 560) / 380)); + const s = 0.62 + 0.38 * t; + this.applyPose(ds.sprite, { x, y, rot: 0, s, q: SQ + (1 - SQ) * t }, 1); + const prevT = JSON.stringify(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 (prevT !== JSON.stringify(ds.target)) { this.drawBands(); this.drawReadout(); } + if (order) { + const idx = order.indexOf(ds.id); + this.drawDropSlot(handPose(0, idx, order.length), D.hand + idx * 0.01 - 0.004); + } else this.drawDropSlot(null); + if (this.isMyTurn() && this.gs.phase === 'play') { + const g = this.pileG; + g.clear(); + const d = L.discard; + const hot = ds.target?.type === 'discard'; + const hw = (CARD_W / 2) * d.s + 16, hh = (CARD_H / 2) * d.s * SQ + 16; + g.fillStyle(0x7cf0a0, hot ? 0.22 : 0.06); + g.fillRoundedRect(d.x - hw, d.y - hh, hw * 2, hh * 2, 14); + g.lineStyle(hot ? 4 : 2, 0x7cf0a0, hot ? 1 : 0.6); + g.strokeRoundedRect(d.x - hw, d.y - hh, hw * 2, hh * 2, 14); + } + } + + cancelDrag() { + if (!this.dragState) return; + this.dragState = null; + this.dragPreview = null; + this.drawDropSlot(null); + this.targetG?.clear(); + this.input.setDefaultCursor('default'); + this.layout(); + } + + dropOnTarget(t, ids) { + if (!t.groups) { + this.floatText({ x: CX, y: 770 }, t.type === 'meld' ? `Only ${rankWord(t.rank, 2)} and wild cards go there` : 'Those cards don\'t make a meld', RED, { size: 20 }); + return false; + } + const prevSel = this.selected; + this.selected = new Set(ids); + const ok = this.humanMeld(t.groups); + if (!ok) this.selected = prevSel; + return ok; + } + + endDrag(pointer) { + const ds = this.dragState; + const ids = this.dragIds(); + 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' && this.canAct() && this.humanDiscard(ds.id)) return; + if ((t?.type === 'meld' || t?.type === 'ghost') && this.canAct() && this.dropOnTarget(t, ids)) return; + this.layout(); + this.updateDock(); + } + + onKey(e) { + if (e.code === 'Escape') { + if (this.modal?.onEscape) this.modal.onEscape(); + else if (this.selected.size) { this.selected.clear(); this.layout({ duration: 140 }); 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 (!this.canAct()) return; + const ph = this.gs.phase; + if (k === 'd' && ph === 'draw') this.humanDraw(); + else if (k === 't' && ph === 'draw') this.humanTake(); + else if (k === 'p' && ph === 'draw') this.humanPass(); + else if (k === 'm' && ph === 'play') this.humanMeld(); + else if (k === 'u' && ph === 'play') this.humanUndo(); + else if ((e.code === 'Enter' || e.code === 'Space') && ph === 'play') this.humanDiscard(); + } + + cycleSort() { + const order = ['rank', 'count']; + const i = order.indexOf(this.settings.sort); + this.settings.sort = order[(i + 1) % order.length]; + this.saveSettings(); + this.refreshSortButtons(); + this.sortHand(); + this.layout(); + } + + // ── Menus & panels ───────────────────────────────────────────────────────── + openPause() { + this.openPauseMenu([ + { label: 'Settings', act: () => { this.closeModal(); openSettings(this); } }, + { label: 'Score sheet', act: () => { this.closeModal(); this.openScorePad({ readOnly: true }); } }, + { label: 'How to play', act: () => { this.closeModal(); openRules(this); } }, + { label: 'Your record', act: () => { this.closeModal(); openLifetime(this); } }, + { 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() }, + ]); + } + + 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 }); + } + + /** The paper score sheet, hand by hand. */ + openScorePad({ readOnly = true, back = null } = {}) { + const gs = this.gs; + if (!gs) return; + const names = ['We', 'They']; + const rows = [0, 1].map(t => ({ + seat: t, color: TEAM_COLORS[t], name: `${names[t]} (${t ? `${this.shortName(1, 8)} & ${this.shortName(3, 8)}` : `you & ${this.shortName(2, 8)}`})`, + cells: gs.history.map(h => ({ + text: `${h.totals[t] >= 0 ? '+' : ''}${h.totals[t]}`, color: h.totals[t] >= 0 ? '#1e7a3b' : '#b8231f', + mark: h.outSeat != null && TEAM_OF_SEAT[h.outSeat] === t ? (h.concealed ? 'conc.' : 'out') : '', markColor: '#5a3a8a', + })), + total: gs.scores[t].toLocaleString(), + totalColor: gs.scores[t] >= gs.scores[1 - t] ? '#1e7a3b' : '#22201a', + circled: gs.phase === 'gameOver' && gs.winner === t, + })); + const close = () => { this.closeModal(); back?.(); }; + this.openScorePadModal({ + title: `Score sheet — first to ${gs.rules.target.toLocaleString()}`, + sub: 'Each hand: melds + canastas + red threes + going out − cards left in hand', + columns: gs.history.map(h => `H${h.hand}`), + rows, buttons: [{ label: back ? 'Back' : 'Back to the table', act: close }], readOnly, + }); + if (this.modal) this.modal.onEscape = close; + } } diff --git a/src/games/canasta/CanastaLogic.js b/src/games/canasta/CanastaLogic.js index 676c747..42f5bdd 100644 --- a/src/games/canasta/CanastaLogic.js +++ b/src/games/canasta/CanastaLogic.js @@ -1,497 +1,581 @@ -// Canasta — pure state engine. No Phaser imports. +// Canasta — pure rules engine. No Phaser, no timers. // -// Classic partnership rules (with a few documented simplifications so the engine -// stays tractable and always terminates): +// 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. // -// - Four players, two fixed partnerships: seats 0 & 2 vs seats 1 & 3. -// - 108-card shoe (two decks + four jokers). 11 cards dealt each. -// - A turn is: DRAW (stock, or take the discard pile) → MELD (optional) → -// DISCARD (mandatory, unless you empty your hand to go out). -// - Wild cards: jokers (50) and twos (20). Naturals are 4..A. -// - Red threes are bonus cards: laid out immediately and replaced from stock. -// - A meld is 3+ cards of one rank, at most 3 wild, at least 2 natural. -// Seven cards = a canasta (natural 500 / mixed 300). -// - Taking the pile: the top card must be a natural (not a 3, not wild). You -// take it by holding two matching naturals (always legal), or — only when the -// pile is NOT frozen and your team has already melded — one natural + one wild, -// or by adding it to an existing team meld of that rank. A team that has not -// yet made its initial meld must use two naturals. A wild discard freezes the -// pile; a black three on top blocks it for the next player. -// - To go out a team must own at least one canasta; the going-out player then -// sheds the rest of their hand. The hand also ends if the stock runs out. +// 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 // -// All mutating helpers return a NEW state (immutable style, mirrors HeartsLogic). +// 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 { - SUITS, RANKS, Card, PLAYER_COUNT, INITIAL_HAND, WIN_SCORE, CANASTA_SIZE, - MAX_WILDS_IN_MELD, MIN_MELD_CARDS, NATURAL_CANASTA, MIXED_CANASTA, RED_THREE, - ALL_RED_THREES, GO_OUT, CONCEALED_GO_OUT, TEAM_OF_SEAT, SEATS_OF_TEAM, - isWild, isRedThree, isBlackThree, isMeldable, cardScore, minimumMeld, + 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 { - isWild, isRedThree, isBlackThree, cardScore, minimumMeld, TEAM_OF_SEAT, - SEATS_OF_TEAM, WIN_SCORE, -}; +export const VERSION = 1; -// ── Seedable PRNG (mirrors the other games) ─────────────────────────────────── -function rng(seed) { - let a = (seed >>> 0) || 1; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; +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(arr, rand) { +function shuffle(gs, arr) { for (let i = arr.length - 1; i > 0; i--) { - const j = Math.floor(rand() * (i + 1)); + const j = Math.floor(rand(gs) * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } + return arr; } -// ── Card construction (jokers are Cards with a synthetic rank) ───────────────── -function makeCard(rank, suit, id) { - const c = new Card(rank, suit); - c.id = id; - return c; +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); } -function buildShoe() { - const cards = []; - let id = 0; - for (let d = 0; d < 2; d++) { - for (const suit of SUITS) { - for (const rank of RANKS) cards.push(makeCard(rank, suit, id++)); +/** 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); } } - for (let j = 0; j < 4; j++) cards.push(makeCard('JK', j < 2 ? 'r' : 'b', id++)); - return cards; + + // 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; } -function cloneCard(c) { - const out = new Card(c.rank, c.suit); - out.id = c.id; +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; } -// ── Meld helpers ────────────────────────────────────────────────────────────── -function meldNaturals(meld) { return meld.cards.filter((c) => !isWild(c)).length; } -function meldWilds(meld) { return meld.cards.filter((c) => isWild(c)).length; } -function isCanasta(meld) { return meld.cards.length >= CANASTA_SIZE; } -function isNaturalCanasta(meld) { return isCanasta(meld) && meldWilds(meld) === 0; } - -/** Total card-value of a meld (cards only, no bonuses). */ -function meldValue(meld) { return meld.cards.reduce((s, c) => s + cardScore(c), 0); } - -// ── State ───────────────────────────────────────────────────────────────────── -export function cloneState(state) { - return { - players: state.players.map((p) => ({ - seat: p.seat, - team: p.team, - hand: p.hand.map(cloneCard), - })), - teams: state.teams.map((t) => ({ - melds: t.melds.map((m) => ({ rank: m.rank, cards: m.cards.map(cloneCard) })), - redThrees: t.redThrees.map(cloneCard), - hasMelded: t.hasMelded, - score: t.score, - })), - stock: state.stock.map(cloneCard), - discard: state.discard.map(cloneCard), - frozen: state.frozen, - currentPlayer: state.currentPlayer, - phase: state.phase, - hasDrawn: state.hasDrawn, - meldedThisTurn: state.meldedThisTurn.map((c) => cloneCard(c)), - turnTeamMeldedAtStart: state.turnTeamMeldedAtStart, - dealer: state.dealer, - handNumber: state.handNumber, - handScores: state.handScores ? state.handScores.map((h) => ({ ...h })) : null, - outPlayer: state.outPlayer, - winnerTeam: state.winnerTeam, - seed: state.seed, - log: state.log.map((e) => ({ ...e })), - _rand: state._rand, - }; -} - -function team(state, seat) { return state.teams[TEAM_OF_SEAT[seat]]; } - -/** Pull any red threes out of a hand into the team's row; returns how many. */ -function harvestRedThrees(state, seat) { - const p = state.players[seat]; - const t = team(state, seat); - let moved = 0; - p.hand = p.hand.filter((c) => { - if (isRedThree(c)) { t.redThrees.push(c); moved++; return false; } - return true; - }); - return moved; -} - -function dealHand(state, rand) { - const deck = buildShoe(); - shuffle(deck, rand); - for (let seat = 0; seat < PLAYER_COUNT; seat++) { - state.players[seat].hand = deck.splice(0, INITIAL_HAND); +/** 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); } - state.stock = deck; - // Flip the first non-special card to start the discard pile. Red threes go to - // the bottom of the stock; a wild up-card freezes the pile from the start. - state.discard = []; - state.frozen = false; - let up = state.stock.shift(); - while (isRedThree(up)) { state.stock.push(up); up = state.stock.shift(); } - if (isWild(up) || isBlackThree(up)) state.frozen = true; - state.discard.push(up); - - // Players harvest red threes dealt to them, drawing replacements. - for (let seat = 0; seat < PLAYER_COUNT; seat++) { - let guard = 0; - while (harvestRedThrees(state, seat) > 0 && state.stock.length > 0) { - if (++guard > 20) break; - state.players[seat].hand.push(state.stock.shift()); - } - } - - state.phase = 'draw'; - state.hasDrawn = false; - state.meldedThisTurn = []; - state.currentPlayer = (state.dealer + 1) % PLAYER_COUNT; - state.turnTeamMeldedAtStart = team(state, state.currentPlayer).hasMelded; - state.handScores = null; - state.outPlayer = null; -} - -export function createInitialState({ seed } = {}) { - const rand = seed === undefined ? Math.random : rng(seed); - const players = []; - for (let i = 0; i < PLAYER_COUNT; i++) { - players.push({ seat: i, team: TEAM_OF_SEAT[i], hand: [] }); - } - const teams = [0, 1].map(() => ({ melds: [], redThrees: [], hasMelded: false, score: 0 })); - const state = { - players, teams, - stock: [], discard: [], frozen: false, - currentPlayer: 0, phase: 'draw', hasDrawn: false, - meldedThisTurn: [], turnTeamMeldedAtStart: false, - dealer: seed === undefined ? Math.floor(Math.random() * PLAYER_COUNT) : (seed % PLAYER_COUNT), - handNumber: 0, - handScores: null, outPlayer: null, winnerTeam: null, - seed: seed ?? null, log: [], _rand: rand, - }; - dealHand(state, rand); - return state; -} - -// ── Queries ─────────────────────────────────────────────────────────────────── -export function topDiscard(state) { - return state.discard.length ? state.discard[state.discard.length - 1] : null; -} - -/** Find a team's existing meld of a rank, or null. */ -export function teamMeld(state, seat, rank) { - return team(state, seat).melds.find((m) => m.rank === rank) || null; + return [...byRank.entries()].map(([rank, cards]) => ({ rank, cards })); } /** - * Can the seat legally take the whole discard pile right now? Returns a plan - * { rank, naturalIds, wildIds, useMeld } describing the cheapest legal capture, - * or null. The top card itself is always part of the new/extended meld. + * Check a meld action for the current player. Returns + * { problem, value, left, goingOut, canastasAfter, newCanastas: [rank…] } + * where problem is null when legal. */ -export function takePlan(state, seat) { - if (state.phase !== 'draw' || state.hasDrawn) return null; - if (state.currentPlayer !== seat) return null; - const top = topDiscard(state); - if (!top || !isMeldable(top)) return null; // 3s and wilds can't be captured - const hand = state.players[seat].hand; - const t = team(state, seat); - const rank = top.rank; - const naturals = hand.filter((c) => c.rank === rank && !isWild(c)); - const wilds = hand.filter((c) => isWild(c)); - const existing = teamMeld(state, seat, rank); - // A team that hasn't melded, or a frozen pile, requires two natural matches. - const mustUseNaturals = state.frozen || !t.hasMelded; +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; +} - if (naturals.length >= 2) { - return { rank, naturalIds: [naturals[0].id, naturals[1].id], wildIds: [], useMeld: !!existing }; +/** + * 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}`; } - if (mustUseNaturals) return null; - if (existing) { - // Add the top card to an existing meld (no extra cards needed). - return { rank, naturalIds: [], wildIds: [], useMeld: true }; + 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 (naturals.length === 1 && wilds.length >= 1) { - return { rank, naturalIds: [naturals[0].id], wildIds: [wilds[0].id], useMeld: false }; + 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; } -// ── Drawing ─────────────────────────────────────────────────────────────────── -function drawReplacingRedThrees(state, seat) { - // Draw one card; if it's a red three, harvest it and keep drawing. - let drew = null; - let guard = 0; - do { - if (state.stock.length === 0) return drew; // ran dry mid-replacement - drew = state.stock.shift(); - if (isRedThree(drew)) { - team(state, seat).redThrees.push(drew); - drew = null; - } - if (++guard > 30) break; - } while (drew === null); - if (drew) state.players[seat].hand.push(drew); - return drew; -} - -export function drawStock(state) { - if (state.phase !== 'draw' || state.hasDrawn) return state; - const next = cloneState(state); - const seat = next.currentPlayer; - if (next.stock.length === 0) { endHand(next, null); return next; } - drawReplacingRedThrees(next, seat); - next.hasDrawn = true; - next.phase = 'meld'; - if (next.stock.length === 0 && next.players[seat].hand.length === 0) { - // Drew the last card replacing red threes and somehow emptied — guard. - endHand(next, null); - } - next.log.push({ kind: 'draw', seat }); - return next; -} - -export function takeDiscard(state, plan) { - if (state.phase !== 'draw' || state.hasDrawn) return state; - const seat = state.currentPlayer; - const p = plan || takePlan(state, seat); - if (!p) return state; - const next = cloneState(state); - const player = next.players[seat]; - const t = team(next, seat); - const top = next.discard.pop(); - - // Build / extend the rank meld with the top card + supplied cards. - let meld = t.melds.find((m) => m.rank === p.rank) || null; - const used = [top]; - for (const id of [...p.naturalIds, ...p.wildIds]) { - const idx = player.hand.findIndex((c) => c.id === id); - if (idx >= 0) used.push(player.hand.splice(idx, 1)[0]); - } - if (!meld) { - meld = { rank: p.rank, cards: [] }; - t.melds.push(meld); - } - meld.cards.push(...used); - next.meldedThisTurn.push(...used.filter((c) => c.id !== top.id), top); - - // The rest of the pile goes into the taker's hand. - player.hand.push(...next.discard.splice(0)); - next.discard = []; - next.frozen = false; - next.hasDrawn = true; - next.phase = 'meld'; - next.log.push({ kind: 'takePile', seat, rank: p.rank }); - // Harvest any red threes that arrived inside the pile. - harvestRedThrees(next, seat); - return next; -} - -// ── Melding ─────────────────────────────────────────────────────────────────── /** - * Validate a proposed meld of card ids for the current player (creating a new - * meld of `rank` or extending the team's existing one). Returns null if illegal, - * else { meld, cards } refs into a clone-ready shape. Does NOT mutate. + * 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. */ -function validateMeld(state, seat, rank, cardIds) { - const player = state.players[seat]; - const cards = cardIds.map((id) => player.hand.find((c) => c.id === id)).filter(Boolean); - if (cards.length !== cardIds.length || cards.length === 0) return null; - // Every card is either a wild or a natural of the target rank. - for (const c of cards) { - if (isWild(c)) continue; - if (c.rank !== rank || !isMeldable(c)) return null; - } - const existing = teamMeld(state, seat, rank); - const naturalsAdded = cards.filter((c) => !isWild(c)).length; - const wildsAdded = cards.filter((c) => isWild(c)).length; - const totalNatural = (existing ? meldNaturals(existing) : 0) + naturalsAdded; - const totalWild = (existing ? meldWilds(existing) : 0) + wildsAdded; - const totalCards = (existing ? existing.cards.length : 0) + cards.length; - if (totalWild > MAX_WILDS_IN_MELD) return null; - if (totalNatural < 2) return null; // never more wilds than naturals base - if (totalWild > totalNatural) return null; - if (!existing && totalCards < MIN_MELD_CARDS) return null; - return { existing, cards }; -} - -export function meld(state, rank, cardIds) { - if (state.phase !== 'meld') return state; - const seat = state.currentPlayer; - const v = validateMeld(state, seat, rank, cardIds); - if (!v) return state; - const next = cloneState(state); - const player = next.players[seat]; - const t = team(next, seat); - let m = t.melds.find((x) => x.rank === rank); - if (!m) { m = { rank, cards: [] }; t.melds.push(m); } - for (const id of cardIds) { - const idx = player.hand.findIndex((c) => c.id === id); - if (idx >= 0) { - const card = player.hand.splice(idx, 1)[0]; - m.cards.push(card); - next.meldedThisTurn.push(card); +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) }); } - } - next.log.push({ kind: 'meld', seat, rank, count: cardIds.length }); - return next; -} - -/** - * After melds are laid, has the player met the team's initial-meld minimum? - * Only relevant on the team's first meld of the game. - */ -export function meetsInitialMeld(state, seat) { - const t = team(state, seat); - if (t.hasMelded) return true; - const value = state.meldedThisTurn.reduce((s, c) => s + cardScore(c), 0); - return value >= minimumMeld(t.score); -} - -// ── Discard & turn end ───────────────────────────────────────────────────────── -/** Could the seat legally go out if they emptied their hand now? */ -export function teamHasCanasta(state, seat) { - return team(state, seat).melds.some(isCanasta); -} - -export function discard(state, cardId) { - if (state.phase !== 'meld') return state; - const seat = state.currentPlayer; - const player = state.players[seat]; - const idx = player.hand.findIndex((c) => c.id === cardId); - if (idx < 0) return state; - const card = player.hand[idx]; - if (isRedThree(card)) return state; // red threes are never discarded - - // If the team laid its first melds this turn, the minimum must be satisfied. - const t = team(state, seat); - if (!t.hasMelded && state.meldedThisTurn.length > 0 && !meetsInitialMeld(state, seat)) { - return state; // illegal — would leave an under-value initial meld - } - - const goingOut = player.hand.length === 1; // this discard would empty the hand - if (goingOut && !teamHasCanasta(state, seat)) { - // You may not go out without a canasta, but with a single card there is no - // other legal discard. Rather than deadlock, end the hand as a stock-out. - // (The AI never melds itself into this corner.) - const next = cloneState(state); - finalizeMelds(next); - endHand(next, null); - return next; - } - - const next = cloneState(state); - const np = next.players[seat]; - const ni = np.hand.findIndex((c) => c.id === cardId); - const [dc] = np.hand.splice(ni, 1); - // Mark the team as having melded if it laid anything this turn. - if (next.meldedThisTurn.length > 0) next.teams[next.players[seat].team].hasMelded = true; - next.discard.push(dc); - if (isWild(dc) || isBlackThree(dc)) next.frozen = true; - next.log.push({ kind: 'discard', seat, card: { rank: dc.rank, suit: dc.suit } }); - - if (np.hand.length === 0) { - finalizeMelds(next); - endHand(next, seat); - return next; - } - - // Advance to the next player. - next.currentPlayer = (seat + 1) % PLAYER_COUNT; - next.phase = 'draw'; - next.hasDrawn = false; - next.meldedThisTurn = []; - next.turnTeamMeldedAtStart = team(next, next.currentPlayer).hasMelded; - return next; -} - -function finalizeMelds(state) { - // Commit hasMelded for any team that laid cards (covers the go-out path). - for (const seat of [0, 1, 2, 3]) { - const t = state.teams[TEAM_OF_SEAT[seat]]; - if (t.melds.length > 0) t.hasMelded = true; - } -} - -// ── Scoring ───────────────────────────────────────────────────────────────── -export function scoreTeamHand(state, teamId, { outPlayer } = {}) { - const t = state.teams[teamId]; - const detail = { meldPoints: 0, naturalCanastas: 0, mixedCanastas: 0, canastaBonus: 0, - redThrees: t.redThrees.length, redThreeBonus: 0, goOut: 0, handPenalty: 0, total: 0 }; - - for (const m of t.melds) { - detail.meldPoints += meldValue(m); - if (isCanasta(m)) { - if (isNaturalCanasta(m)) { detail.naturalCanastas++; detail.canastaBonus += NATURAL_CANASTA; } - else { detail.mixedCanastas++; detail.canastaBonus += MIXED_CANASTA; } + // 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)}` }; } - } - - // Red threes: positive only if the team melded; all four → 800. - const rt = t.redThrees.length; - let rtBonus = (rt === 4 ? ALL_RED_THREES : rt * RED_THREE); - if (!t.hasMelded) rtBonus = -rtBonus; - detail.redThreeBonus = rtBonus; - - // Going-out bonus (concealed if the team had not melded before this turn). - if (outPlayer !== null && TEAM_OF_SEAT[outPlayer] === teamId) { - detail.goOut = state.turnTeamMeldedAtStart ? GO_OUT : CONCEALED_GO_OUT; - } - - // Deduct the value of every card still held by the team's players. - for (const seat of SEATS_OF_TEAM[teamId]) { - for (const c of state.players[seat].hand) detail.handPenalty += cardScore(c); - } - - detail.total = detail.meldPoints + detail.canastaBonus + detail.redThreeBonus - + detail.goOut - detail.handPenalty; - return detail; -} - -function endHand(state, outPlayer) { - state.outPlayer = outPlayer; - const scores = [0, 1].map((teamId) => scoreTeamHand(state, teamId, { outPlayer })); - for (let teamId = 0; teamId < 2; teamId++) state.teams[teamId].score += scores[teamId].total; - state.handScores = scores; - - const reached = state.teams.some((t) => t.score >= WIN_SCORE); - if (reached) { - state.phase = 'gameOver'; - const a = state.teams[0].score, b = state.teams[1].score; - state.winnerTeam = a === b ? null : (a > b ? 0 : 1); } else { - state.phase = 'handOver'; + 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] }); } - state.log.push({ kind: 'handOver', scores: scores.map((s) => s.total), outPlayer }); + 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 }; } -export function startNextHand(state) { - if (state.phase !== 'handOver') return state; - const next = cloneState(state); - next.handNumber += 1; - next.dealer = (next.dealer + 1) % PLAYER_COUNT; - // Per-hand reset of melds / red threes (cumulative score persists). - for (const t of next.teams) { t.melds = []; t.redThrees = []; t.hasMelded = false; } - dealHand(next, next._rand); - return next; +/** 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: [] }); } -export function isGameOver(state) { return state.phase === 'gameOver'; } +// ── 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; +} -// Re-export a couple of internals used by the AI / verify harness. -export { meldValue, isCanasta, isNaturalCanasta, meldNaturals, meldWilds }; +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); +} diff --git a/src/games/canasta/CanastaTable.js b/src/games/canasta/CanastaTable.js new file mode 100644 index 0000000..24aba17 --- /dev/null +++ b/src/games/canasta/CanastaTable.js @@ -0,0 +1,192 @@ +// Canasta table layout — Phaser-free so tools/verifyCanasta.js can test it. +// +// "Rosa's Parlor": a 1950s living room, the mahogany card table dressed in a +// teal baize cover with a lace doily under the piles. You sit at the bottom, +// your partner across (top), the opponents left and right. +// +// Across the table, top to bottom: +// the opponents' meld band · the score pad · stock & discard · the ticker · +// your side's meld band · your hand. +// A meld is a short cascade; a canasta squares up into one stack (a red card +// on top for a natural canasta, a black one for a mixed — the real +// convention). Red threes sit face up at the left end of each band. + +import { + makeTable, CARD_W, CARD_H, fanPose, fanPoint, fanBounds, cardBounds, rectsOverlap, onScreen, + HUMAN_PLATE, PLATE, plateRect, hudFurniture, centreRect, unionRect, +} from '../../ui/cardtable/TableGeometry.js'; +import { MELD_RANKS } from './CanastaData.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; + +// you · west · partner · east — your side warm rose, theirs atomic teal +export const SEAT_COLORS = [0xf09a8a, 0x58c8c0, 0xf0b0c8, 0x7ad0e8]; +export const SEAT_HEX = ['#f09a8a', '#58c8c0', '#f0b0c8', '#7ad0e8']; +export const TEAM_COLORS = [0xf2a28e, 0x5ccac2]; +export const TEAM_HEX = ['#f2a28e', '#5ccac2']; + +const HUMAN_FAN = { x: 960, y: 994, rot: 0, k: 1, spread: 64, curve: 1.0, tilt: 0.028, q: 1, maxSpan: 960, maxDrop: 26, maxTilt: 0.2 }; +const opp = (x, y, rot, k, maxSpan) => ({ x, y, rot, k, spread: 30, curve: 0.45, tilt: 0.03, q: 1, maxSpan, maxDrop: 12, maxTilt: 0.16 }); + +export const L = { + seats: [ + { fan: HUMAN_FAN, plate: HUMAN_PLATE }, + { fan: opp(84, 560, Math.PI / 2, 0.5, 360), plate: { x: 190, y: 150 } }, + { fan: opp(960, 78, Math.PI, 0.5, 520), plate: { x: 1420, y: 86 } }, + { fan: opp(1836, 560, -Math.PI / 2, 0.5, 360), plate: { x: 1730, y: 150 } }, + ], + stock: T.flat(-0.085, 0.445, 0.92), + discard: T.flat(0.085, 0.445, 0.92), +}; + +// ── Meld bands ─────────────────────────────────────────────────────────────── +// Screen space. Columns centre on BAND.cx; a column is a cascade of cards. +export const BAND = { + cx: 960, colW: 94, xMin: 330, xMax: 1590, + k: 0.6, // card scale relative to the table's perspective scale + step: 17, // cascade step (px) between cards in an open meld + redStep: 18, // red threes fan sideways + top: [606, 214], // y of the first card's centre: [your side, theirs] +}; +export const PAD = { x: 590, y: 466, w: 300, h: 150 }; // the score pad, left of the piles +export const TICKER = { x: 1196, y: 430, w: 400 }; // the recent-play ticker, right of the piles +export const READOUT = { x: 960, y: 812 }; // meld preview / first-meld meter +export const BUBBLE = { x: 1420, y: 196 }; // partner's speech bubble (under their plate) + +const bandScale = (y) => BAND.k * T.P.unproject(BAND.cx, y).s; + +/** + * Column plan for one side's band. + * melds: [{ rank, cards }] in table order · reds: number of red threes · + * ghost: true → a trailing empty column for a new meld (staging) + * Returns [{ kind: 'red'|'meld'|'ghost', rank, x, y, s, index }]. + */ +export function bandColumns(team, melds, reds = 0, ghost = false) { + const order = sortedMelds(melds); + const cols = []; + if (reds) cols.push({ kind: 'red', rank: '3r' }); + order.forEach((m) => cols.push({ kind: 'meld', rank: m.rank, meld: m })); + if (ghost) cols.push({ kind: 'ghost', rank: null }); + const y = BAND.top[team]; + const s = bandScale(y); + const n = cols.length; + // red threes take a slightly wider column (they fan sideways) + const widths = cols.map((c) => (c.kind === 'red' ? BAND.colW + Math.max(0, reds - 1) * BAND.redStep * 0.6 : BAND.colW)); + const total = widths.reduce((a, b) => a + b, 0); + let x = Math.max(BAND.xMin, BAND.cx - total / 2); + return cols.map((c, i) => { + const cx = x + widths[i] / 2; + x += widths[i]; + return { ...c, x: cx, y, s, index: i, n }; + }); +} + +/** Melds in display order: A K Q … 4, black threes last. */ +export function sortedMelds(melds) { + const w = (r) => (r === '3' ? 99 : MELD_RANKS.indexOf(r)); + return melds.slice().sort((a, b) => w(a.rank) - w(b.rank)); +} + +/** Card poses within a column (cards in meld order). */ +export function columnPoses(col, n, { canasta = false, reds = false } = {}) { + const out = []; + for (let i = 0; i < n; i++) { + if (reds) out.push({ x: col.x - ((n - 1) * BAND.redStep) / 2 + i * BAND.redStep, y: col.y + (i % 2) * 3, rot: (i - (n - 1) / 2) * 0.05, s: col.s, q: SQ }); + else if (canasta) out.push({ x: col.x + (i % 2 ? 0.6 : -0.6), y: col.y + 22 - i * 1.3, rot: (i % 3 - 1) * 0.012, s: col.s, q: SQ }); + else out.push({ x: col.x, y: col.y + i * BAND.step, rot: 0, s: col.s, q: SQ }); + } + return out; +} + +/** Rect around a column (hit tests, drop targets, glows). n = cards shown. */ +export function columnRect(col, n, { canasta = false } = {}) { + const hw = (CARD_W / 2) * col.s, hh = (CARD_H / 2) * col.s * SQ; + const span = canasta ? 0 : Math.max(0, n - 1) * BAND.step; + const y0 = (canasta ? col.y + 22 - n * 1.3 : col.y) - hh; + return { x0: col.x - hw - 6, x1: col.x + hw + 6, y0: y0 - 6, y1: (canasta ? col.y + 22 : col.y + span) + hh + 6 }; +} + +/** Where a column's caption sits (under the deepest a meld can grow: 6 open cards). */ +export function columnLabelY(col, team = 0) { + const hh = (CARD_H / 2) * col.s * SQ; + // their band sits just above the piles, so its captions go over the columns + if (team === 1) return col.y - hh - 16; + return col.y + 5 * BAND.step + hh + 14; +} + +// ── Seats ──────────────────────────────────────────────────────────────────── +export function handPose(seat, i, n, lift = 0) { + return fanPose(L.seats[seat].fan, i, n, lift); +} +export function handHome(seat) { + const f = L.seats[seat].fan; + const p = fanPoint(f, 0, -CARD_H * 0.95); + return { ...p, rot: f.rot, k: f.k }; +} +export function handBadge(seat) { + const f = L.seats[seat].fan; + return fanPoint(f, -(f.maxSpan / 2 + CARD_W / 2 + 40), 0); +} +export function spotFor(seat) { + const f = L.seats[seat].fan; + if (seat === 0) return { x: f.x, y: 840, w: 1400, h: 440 }; + 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: 360, h: 600 } : { x: c.x, y: c.y + 20, w: 700, h: 260 }; +} + +export { CARD_W, CARD_H, PLATE }; + +// ── Layout self-check (tools/verifyCanasta.js) ─────────────────────────────── +/** Worst case: 12 columns per band (red threes + 11 melds); hands at their largest. */ +export function verifyLayout() { + const problems = []; + const fake = (rank, n) => ({ rank, cards: Array.from({ length: n }, (_, i) => ({ id: `${rank}${i}` })) }); + const ranks = [...MELD_RANKS]; + const bandRect = [0, 1].map((team) => { + const melds = ranks.map((r) => fake(r, 6)); + const cols = bandColumns(team, melds, 4, false); + let r = null; + for (const c of cols) { + const poses = columnPoses(c, c.kind === 'red' ? 4 : 6, { reds: c.kind === 'red' }); + for (const p of poses) r = unionRect(r, cardBounds(p)); + } + const last = cols[cols.length - 1]; + if (last.x + (CARD_W / 2) * last.s > BAND.xMax + 4) problems.push(`band ${team}: ${cols.length} columns overflow to x=${Math.round(last.x)}`); + if (cols[0].x - (CARD_W / 2) * cols[0].s < BAND.xMin - 4) problems.push(`band ${team}: underflows the left edge`); + return r; + }); + // with one extra ghost column for staging, typical bands (≤ 9 melds) still fit + { + const cols = bandColumns(0, ranks.slice(0, 9).map((r) => fake(r, 6)), 4, true); + const last = cols[cols.length - 1]; + if (last.x + (CARD_W / 2) * last.s > BAND.xMax + 4) problems.push('band 0: ghost column overflows with 9 melds'); + } + const handR = fanBounds(L.seats[0].fan, 22, 40); + const pileR = unionRect(cardBounds(L.stock), cardBounds({ ...L.discard, rot: Math.PI / 2 })); + const padR = centreRect(PAD); + const named = [ + ['your hand (22 cards, lifted)', handR], + ['West hand', fanBounds(L.seats[1].fan, 20)], + ['partner hand', fanBounds(L.seats[2].fan, 20)], + ['East hand', fanBounds(L.seats[3].fan, 20)], + ['piles', pileR], + ['score pad', padR], + ['West plate', plateRect(L.seats[1].plate)], + ['partner plate', plateRect(L.seats[2].plate)], + ['East plate', plateRect(L.seats[3].plate)], + ]; + for (const [name, r] of named) { + if (!onScreen(r, 2)) problems.push(`${name} off screen`); + if (rectsOverlap(r, bandRect[0])) problems.push(`your band overlaps ${name}`); + if (rectsOverlap(r, bandRect[1])) problems.push(`their band overlaps ${name}`); + } + if (rectsOverlap(pileR, padR)) problems.push('score pad overlaps piles'); + for (const f of hudFurniture()) { + for (let t = 0; t < 2; t++) if (rectsOverlap(f.r, bandRect[t])) problems.push(`band ${t} overlaps ${f.name}`); + for (const [name, r] of named.slice(1)) if (rectsOverlap(f.r, r) && !(name === 'partner plate')) problems.push(`${name} overlaps ${f.name}`); + } + return problems; +} diff --git a/src/games/canasta/CanastaTalk.js b/src/games/canasta/CanastaTalk.js new file mode 100644 index 0000000..c21a0b1 --- /dev/null +++ b/src/games/canasta/CanastaTalk.js @@ -0,0 +1,81 @@ +// Canasta — your partner's table talk. A Sunday-parlor voice: warm, a little +// competitive, never mean. partnerLine(kind, ctx) returns a line or null +// (some moments only get a remark now and then, so it never nags). + +import { rankWord } from './CanastaData.js'; + +const LINES = { + deal: [ + 'Cards up, coffee hot. Let\'s show them how it\'s done.', + 'Sit up straight, partner — they\'re watching us.', + 'I have a good feeling about this one.', + ], + redThree: [ + 'A red three! Now let\'s get a meld down so it counts.', + 'Ooh, a red one. That\'s a hundred, dear.', + ], + weTook: [ + '{n} cards! Now THAT\'S a pickup.', + 'Look at that pile come home to us.', + 'Well, that\'ll keep us busy.', + ], + theyTook: [ + 'Oh, they would take that one.', + 'Hmph. Mind what you feed them, partner.', + 'That pile was supposed to be ours.', + ], + ourCanasta: [ + 'A canasta! Three hundred in the basket.', + 'There she is — our canasta!', + 'Now we can go out whenever we like.', + ], + naturalCanasta: [ + 'A NATURAL canasta! Five hundred, dear. Five hundred!', + 'Not a wild card in it. Beautiful.', + ], + theirCanasta: [ + 'They\'ve made a canasta. Watch for them going out.', + 'Well, good for them. Now let\'s make two.', + 'Don\'t let it rattle you — we\'ll catch up.', + ], + freeze: [ + 'There — I froze it. Let them try to take it now.', + 'Frozen solid. Natural pairs only, darlings.', + ], + theyFroze: [ + 'They froze it on us. We\'ll need a natural pair.', + ], + youFroze: [ + 'Froze it! Clever partner.', + 'A wild on the pile — that\'ll slow them down.', + ], + yes: [ + 'Go on, take us out!', + 'Yes — out you go, dear.', + ], + no: [ + 'Not yet — I\'ve still got cards to lay down.', + 'Hold on, partner, I\'m sitting on points.', + ], + handWon: [ + 'That\'s how we do it on Sundays.', + 'A lovely hand, partner.', + 'Write that down before they argue.', + ], + handLost: [ + 'Well. Fresh deck, fresh start.', + 'We\'ll get them back this hand.', + 'Don\'t you worry — the night is young.', + ], +}; + +// remarks that only come now and then +const CHANCE = { weTook: 0.8, theyTook: 0.6, theirCanasta: 0.7, handWon: 0.9, handLost: 0.9, deal: 1, redThree: 0.6, youFroze: 0.7 }; + +export function partnerLine(kind, ctx = {}) { + const pool = LINES[kind]; + if (!pool) return null; + if (Math.random() > (CHANCE[kind] ?? 1)) return null; + const line = pool[Math.floor(Math.random() * pool.length)]; + return line.replace('{n}', ctx.n ?? '').replace('{rank}', ctx.rank ? rankWord(ctx.rank, 2) : ''); +} diff --git a/src/games/canasta/tutorial.md b/src/games/canasta/tutorial.md index d93124a..281085a 100644 --- a/src/games/canasta/tutorial.md +++ b/src/games/canasta/tutorial.md @@ -4,59 +4,101 @@ --- -Come in, come in — wipe your feet and sit *across* from me. No, not beside — *across*. In Canasta we play in partnerships, and you and I are a team. The two across the table from us? Lovely people. The enemy. We'll be polite and we'll beat them. +Come in, come in — wipe your feet, there's coffee on, and the hi-fi's playing something nice. Sit *across* from your partner. No, not beside — *across*. In Canasta we play in partnerships: you and the one across the table are a team. The two at either side? Lovely people. The enemy. We'll be polite and we'll beat them. ## The Goal -First **team** to **5,000 points** wins the match — not in one hand, but over several. You score by laying down *melds* and, above all, by building **canastas**. Help me build ours and we'll be drinking the good coffee by evening. +First **side** to **5,000 points** wins the match — not in one hand, but over several. (Short on time? In Settings you can play to 3,000 or 2,500.) You score by laying down *melds* and, above all, by building **canastas**. The word means *basket* — and that's what you're filling. ## The Cards -We play with **two whole decks plus four jokers** — 108 cards. You start with **eleven** in your hand. Some cards are special: +**Two whole decks plus four jokers** — 108 cards. Eleven each to start. What they're worth: -- **Wild cards** — the **jokers** (worth 50) and every **two** (worth 20). A wild can stand in for almost any card in a meld. -- **Red threes** — pure bonus. The moment one lands in your hand it pops onto the table by itself and you draw a replacement. Each is worth **100** (all four together, a glorious **800**) — *but only if our team has melded.* Sit there doing nothing and they count *against* us. -- **Black threes** — stubborn little things. You can't meld them, and tossing one onto the discard pile slams the door so the next player can't grab it. +| Card | Points | +|---|---| +| Joker | 50 | +| 2s and aces | 20 | +| K, Q, J, 10, 9, 8 | 10 | +| 7, 6, 5, 4 and black 3s | 5 | -## Your Turn, Step by Step +- **Wild cards** — jokers and every **two**. A wild can stand in for any rank in a meld. +- **Red threes** — pure bonus. The moment one lands in your hand it goes face up beside your side's melds and you draw a replacement. **100** each (all four: **800**) — *but only if our side has melded.* Sit there doing nothing and they count *against* us. +- **Black threes** — stubborn little things. Throw one on the pile and the next player can't take it. You can only meld them (three or four, no wilds) on the turn you go out. + +## Your Turn ### 1. Draw -Either take the top card of the **stock**, or scoop up the *entire* **discard pile** — pile-taking is how fortunes are made. But you may only take the pile if you can use its **top card** right away: +Click the **stock** (or press **D**) to draw one card — or take the *whole* **discard pile** (click it, or **T**). Pile-taking is how fortunes are made, but you must meld its top card right away: -- Hold **two natural cards** matching it and you may always take it. -- If the pile isn't **frozen** and we've already melded, one natural plus a wild will do, or you can add the top card to a meld we already have. +- **Two natural cards** of the top card's rank always do it. +- Once our side has melded — and the pile isn't frozen — **one natural and a wild** will do, or simply drop the top card **onto a meld we already have**. -A **frozen** pile (someone discarded a wild onto it — you'll see the ❄ badge) demands two natural matches, no shortcuts. And remember: before our team's *first* meld, you must use two naturals regardless. +Hover the pile and I'll tell you exactly how you'd take it, or why you can't. + +**Frozen piles.** A wild card thrown on the pile *freezes* it — you'll see it lying crosswise, and a ❄. A frozen pile takes a **natural pair**, nothing less. And until our side has made its first meld, the pile is frozen *for us* no matter what. ### 2. Meld -A **meld** is three or more cards of the same rank laid on the table — and melds belong to the *team*, so I can build on yours and you on mine. A meld may carry up to **three** wild cards, but never more wilds than naturals. +A **meld** is three or more cards of one rank — at least **two naturals**, and no more than **three wilds**. Melds belong to the *side*, so I build on yours and you on mine. -Our **first** meld of the game must reach a minimum point total that climbs as our score grows — **50** to start, then 90, then 120. The game will tell you the number; just select cards and press **Meld**. +- **Click** cards to select them; **double-click** grabs every card of that rank. +- Press **M** (or the Meld button), drag them onto one of our melds, or drop them on the **NEW** slot. The line above your hand tells you what you're about to meld and what it's worth. +- Wild cards on their own go wherever there's room — or drag them onto the meld you mean. +- Changed your mind? **U** undoes this turn's melds. + +**The first meld.** Our side's *first* meld of each hand must reach a minimum, and the bar is set by our score: + +| Our score | First meld needs | +|---|---| +| below zero | 15 | +| 0 – 1,495 | 50 | +| 1,500 – 2,995 | 90 | +| 3,000 or more | 120 | + +The little meter over your hand fills as you pick cards. If you take the pile to make that first meld, only the top card and cards from your own hand count — the rest of the pile doesn't. ### 3. Discard -End your turn by tossing one card onto the discard pile. Select a single card and press **Discard**. (Throw a wild and you *freeze* the pile — sometimes exactly what you want.) +End your turn by throwing one card: select it and press **Enter**, click the pile, or drag it there. Mind what you throw — the player on your left may be waiting for exactly that rank. ## Canastas — the Whole Point -A **canasta** is a meld of **seven** cards. +A **canasta** is a meld of **seven** cards. When it's done it squares up into one neat stack: -- **Natural canasta** — seven cards, no wilds. A beauty. **500** points. -- **Mixed canasta** — seven cards with a wild or two. Still grand. **300** points. - -You'll see ours glow gold (natural) or silver (mixed) in the meld area. +- **Natural canasta** — no wilds at all. A **red** card on top. **500** points. +- **Mixed canasta** — one to three wilds. A **black** card on top. **300** points. ## Going Out -To end the hand, a player empties their hand — but **only if our team owns at least one canasta**. Going out earns a **100** bonus (200 if you do it all in one breathtaking turn having never melded before). When the hand ends we tally melds, canastas, red threes and the go-out bonus, then *subtract* the value of every card still stuck in our hands. So don't get caught holding a fistful at the end. +You go out by melding every card in your hand — or all but one, and discarding that last one. But only when **our side has a canasta** on the table. Until then you must always keep two cards in hand. + +Going out earns **100**, or **200** if you do it *concealed* — your whole hand laid down in a single turn when we'd melded nothing before. + +When the **stock runs dry**, the hand goes on only while players take the pile — you *must* take it if its top card fits one of our melds. When nobody can, the hand ends. + +## Counting Up + +At the end of each hand, each side scores: + +**melds on the table + canasta bonuses + red threes + going out − every card still in our hands** + +So don't get caught holding a fistful at the end. + +## House Rules (Settings) + +- **Two canastas to go out** — longer, richer hands. +- **"Partner, may I go out?"** — you must ask first, and a *no* holds for that turn. I'll ask you too, so keep an eye on what you're holding. +- **Always frozen** — the pile only ever takes a natural pair. A careful player's game. +- **Play to 3,000 or 2,500** — a quicker evening; the first-meld bars come sooner. ## Rosa's Rules of the Heart -- **Hoard for a canasta.** A meld of four is nice; a canasta is a fortune. Don't break up a near-canasta to start something new. -- **Watch what they want.** If the pile is fat, the player after you may be drooling for it — drop a black three and shut them out. -- **Mind the freeze.** Frozen piles are heavy and hard to take; freeze it when *we're* sitting pretty and they aren't. -- **Red threes love a melded team.** Get a meld down early so our bonus cards count *for* us. +- **Hoard for a canasta.** A meld of four is nice; a canasta is a fortune. +- **Watch what they pick up.** Hover their nameplates — I keep track of what they took from the pile. Don't feed them those ranks. +- **Freeze it when it's fat.** A big pile and a hungry opponent? A two on top shuts the door. +- **Block with black threes.** A black three on a juicy pile buys us a turn. +- **Meld early.** Red threes only count once we have a meld down, and the pile stays frozen for us until then. +- **Stuck? Press H.** I'll whisper what I'd do. -That's the whole song, dear. Watch the table, trust your partner, and build, build, build. Now — your draw. And do try to look like you know what you're doing; they're watching. +That's the whole song, dear. Watch the table, trust your partner, and build, build, build. diff --git a/tools/verifyCanasta.js b/tools/verifyCanasta.js index 77a924b..e1a6ce7 100644 --- a/tools/verifyCanasta.js +++ b/tools/verifyCanasta.js @@ -1,22 +1,30 @@ -// Headless verification for Canasta. -// node server/scripts/verifyCanasta.js [--games=N] +// Headless verification for Canasta ("Rosa's Parlor"). +// node tools/verifyCanasta.js [--games=N] [--ladder=N] [--quick] // Exits non-zero on any failure. // -// 1. Fixture tests: card values, canasta/red-three/go-out scoring, the initial -// meld minimum, freeze behaviour and discard-pile take legality. -// 2. Self-play: full partnership games driven by the heuristic AI in all four -// seats, asserting invariants (no exceptions, hands have legal sizes, melds -// are well-formed, the match terminates with a winner) over many seeded games. +// 1. Data: card values, the first-meld minimum, meld legality, and the exact +// first-meld solver against a brute-force search. +// 2. Engine fixtures: one per rules fix (black-three blocks without freezing, +// the upcard, atomic first-meld pile takes, no going out without a +// canasta, the exhausted stock, concealed going out, black-three melds, +// ties past the target) plus every house rule and scoring. +// 3. AI: legality over full self-play matches (card conservation, well-formed +// melds, terminating matches), save/load round trips, and the skill ladder. +// 4. Layout (when CanastaTable.js exists): no overlaps at maximum counts. import { - Card, cardScore, minimumMeld, NATURAL_CANASTA, MIXED_CANASTA, ALL_RED_THREES, - GO_OUT, CONCEALED_GO_OUT, TEAM_OF_SEAT, PLAYER_COUNT, isWild, isRedThree, + DEFAULT_RULES, cardFromId, cardScore, minimumMeld, meldProblem, solveInitialMeld, valueOf, + isWild, isMeldable, isCanasta, wildsIn, naturalsIn, TEAM_OF_SEAT, CANASTA_SIZE, MAX_WILDS, } from '../src/games/canasta/CanastaData.js'; +import * as L from '../src/games/canasta/CanastaLogic.js'; import { - createInitialState, drawStock, takeDiscard, meld, discard, startNextHand, - takePlan, scoreTeamHand, teamMeld, isCanasta, meldNaturals, meldWilds, -} from '../src/games/canasta/CanastaLogic.js'; -import { chooseDraw, chooseMelds, chooseDiscard } from '../src/games/canasta/CanastaAI.js'; + chooseDraw, chooseMelds, chooseDiscard, chooseAnswer, coachDraw, coachMelds, coachDiscard, +} from '../src/games/canasta/CanastaAI.js'; + +const args = Object.fromEntries(process.argv.slice(2).map((a) => a.replace(/^--/, '').split('=')).map(([k, v]) => [k, v ?? true])); +const QUICK = !!args.quick; +const GAMES = Number(args.games ?? (QUICK ? 30 : 200)); +const LADDER = Number(args.ladder ?? (QUICK ? 10 : 40)); let failures = 0; function check(name, cond, detail = '') { @@ -24,213 +32,442 @@ function check(name, cond, detail = '') { failures++; console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`); } +const section = (t) => console.log(`\n${t}`); +const C = (id) => { const c = cardFromId(id); if (!c) throw new Error(`bad card ${id}`); return { ...c }; }; +const Cs = (s) => s.split(/\s+/).filter(Boolean).map(C); +const ids = (cards) => cards.map((c) => c.id); +const clone = (o) => JSON.parse(JSON.stringify(o)); -// Base ids well above the 0..107 the engine deck uses, so fixture cards injected -// into a real state never collide with dealt cards. -let _id = 100000; -const C = (rank, suit) => { const c = new Card(rank, suit); c.id = _id++; return c; }; -const JK = () => C('JK', 'r'); +/** A blank state in the draw phase for seat 0 with the given hands / pile. */ +function fixture({ hands = {}, discard = 'Kd0', stock = null, teams = null, rules = {}, frozen = false, scores = [0, 0], current = 0, phase = 'draw' } = {}) { + const gs = L.createGame({ seed: 7, rules, dealer: 3 }); + gs.hands = [0, 1, 2, 3].map((s) => (hands[s] != null ? Cs(hands[s]) : Cs('4s0 5s0 6s0'))); + gs.discard = Cs(discard); + gs.stock = stock != null ? Cs(stock) : Cs('9c1 9d1 8c1 8d1 7c1 7d1 6c1 6d1'); + gs.teams = teams ?? [0, 1].map(() => ({ melds: [], redThrees: [], melded: false })); + for (const t of gs.teams) t.melds = t.melds.map((m) => (typeof m.cards === 'string' ? { rank: m.rank, cards: Cs(m.cards) } : m)); + gs.frozen = frozen; + gs.scores = scores; + gs.current = current; + gs.phase = phase; + gs.turn = { startMelded: gs.teams[TEAM_OF_SEAT[current]].melded, tookPile: false, asked: null, drew: null }; + gs.pickups = [[], [], [], []]; + gs.discards = [[], [], [], []]; + return gs; +} +const melded = (melds = []) => ({ melds, redThrees: [], melded: true }); +const unmelded = () => ({ melds: [], redThrees: [], melded: false }); -// Minimal state for scoring fixtures. -function mkState() { - const players = []; - for (let i = 0; i < PLAYER_COUNT; i++) players.push({ seat: i, team: TEAM_OF_SEAT[i], hand: [] }); - const teams = [0, 1].map(() => ({ melds: [], redThrees: [], hasMelded: false, score: 0 })); - return { players, teams, turnTeamMeldedAtStart: false }; -} +// ── 1. Data ────────────────────────────────────────────────────────────────── +section('Card values & minimum'); +check('joker 50, two 20, ace 20', cardScore(C('JK0')) === 50 && cardScore(C('2s0')) === 20 && cardScore(C('Ah0')) === 20); +check('K..8 are 10, 7..4 are 5, black three 5', cardScore(C('Ks0')) === 10 && cardScore(C('8d0')) === 10 && cardScore(C('7c0')) === 5 && cardScore(C('4h0')) === 5 && cardScore(C('3s0')) === 5); +check('minimum: -10→15, 0→50, 1500→90, 3000→120', minimumMeld(-10) === 15 && minimumMeld(0) === 50 && minimumMeld(1500) === 90 && minimumMeld(3000) === 120); +check('minimum scales with a 2,500 target', minimumMeld(800, { target: 2500 }) === 90 && minimumMeld(1600, { target: 2500 }) === 120); -// ── 1. Card values ───────────────────────────────────────────────────────────── -console.log('Card values:'); -check('joker = 50', cardScore(C('JK', 'r')) === 50); -check('two = 20', cardScore(C('2', 's')) === 20); -check('ace = 20', cardScore(C('A', 'h')) === 20); -check('king = 10', cardScore(C('K', 'c')) === 10); -check('eight = 10', cardScore(C('8', 'd')) === 10); -check('seven = 5', cardScore(C('7', 's')) === 5); -check('four = 5', cardScore(C('4', 'c')) === 5); +section('Meld legality'); +check('three naturals', meldProblem('K', null, Cs('Ks0 Kh0 Kd0')) === null); +check('two naturals + wild', meldProblem('K', null, Cs('Ks0 Kh0 2c0')) === null); +check('one natural + two wilds is illegal', meldProblem('K', null, Cs('Ks0 2h0 JK0')) !== null); +check('two naturals + three wilds legal, four wilds illegal', + meldProblem('K', null, Cs('Ks0 Kh0 2c0 2d0 JK0')) === null && meldProblem('K', null, Cs('Ks0 Kh0 2c0 2d0 JK0 JK1')) !== null); +check('wilds onto an existing meld respect the cap', + meldProblem('K', { rank: 'K', cards: Cs('Ks0 Kh0 2c0 2d0') }, Cs('JK0')) === null + && meldProblem('K', { rank: 'K', cards: Cs('Ks0 Kh0 2c0 2d0 JK0') }, Cs('JK1')) !== null); +check('red three never melds', meldProblem('3', null, Cs('3h0 3d0 3h1')) !== null); +check('black threes: 3+ only, no wilds', meldProblem('3', null, Cs('3s0 3c0 3s1')) === null && meldProblem('3', null, Cs('3s0 3c0 2s1')) !== null); -// ── 2. Canasta + red-three + go-out scoring ───────────────────────────────────── -console.log('Scoring fixtures:'); +section('First-meld solver vs brute force'); { - const s = mkState(); - s.teams[0].hasMelded = true; - // Natural canasta of seven kings: 70 cards + 500 bonus = 570. - s.teams[0].melds = [{ rank: 'K', cards: ['K','K','K','K','K','K','K'].map((r) => C(r, 's')) }]; - const d = scoreTeamHand(s, 0, { outPlayer: null }); - check('natural canasta cards = 70', d.meldPoints === 70, `got ${d.meldPoints}`); - check('natural canasta bonus = 500', d.canastaBonus === NATURAL_CANASTA, `got ${d.canastaBonus}`); - check('one natural canasta counted', d.naturalCanastas === 1); -} -{ - const s = mkState(); - s.teams[0].hasMelded = true; - // Mixed canasta: five sixes + two wilds. - s.teams[0].melds = [{ rank: '6', cards: [C('6','s'),C('6','d'),C('6','c'),C('6','h'),C('6','s'), JK(), C('2','c')] }]; - const d = scoreTeamHand(s, 0, { outPlayer: null }); - check('mixed canasta bonus = 300', d.canastaBonus === MIXED_CANASTA, `got ${d.canastaBonus}`); - check('mixed canasta counted', d.mixedCanastas === 1 && d.naturalCanastas === 0); -} -{ - const s = mkState(); - s.teams[1].hasMelded = true; - s.teams[1].redThrees = [C('3','h'), C('3','d'), C('3','h'), C('3','d')]; - const d = scoreTeamHand(s, 1, { outPlayer: null }); - check('all four red threes = 800', d.redThreeBonus === ALL_RED_THREES, `got ${d.redThreeBonus}`); -} -{ - const s = mkState(); // team did NOT meld → red threes go negative - s.teams[0].hasMelded = false; - s.teams[0].redThrees = [C('3','h'), C('3','d')]; - const d = scoreTeamHand(s, 0, { outPlayer: null }); - check('unmelded red threes are negative', d.redThreeBonus === -200, `got ${d.redThreeBonus}`); -} -{ - const s = mkState(); - s.teams[0].hasMelded = true; - s.turnTeamMeldedAtStart = true; - const normal = scoreTeamHand(s, 0, { outPlayer: 0 }); - check('go-out bonus = 100', normal.goOut === GO_OUT, `got ${normal.goOut}`); - s.turnTeamMeldedAtStart = false; - const concealed = scoreTeamHand(s, 0, { outPlayer: 2 }); - check('concealed go-out = 200', concealed.goOut === CONCEALED_GO_OUT, `got ${concealed.goOut}`); -} -{ - const s = mkState(); - s.teams[0].hasMelded = true; - s.teams[0].melds = [{ rank: '5', cards: [C('5','s'),C('5','d'),C('5','c')] }]; // 15 pts - s.players[0].hand = [C('K','s'), C('A','h')]; // 30 pts left in hand - const d = scoreTeamHand(s, 0, { outPlayer: null }); - check('hand cards deducted', d.handPenalty === 30 && d.total === 15 - 30, `got total ${d.total}`); -} - -// ── 3. Minimum meld thresholds ────────────────────────────────────────────────── -console.log('Minimum meld:'); -check('negative score → 15', minimumMeld(-50) === 15); -check('0 → 50', minimumMeld(0) === 50); -check('1495 → 50', minimumMeld(1495) === 50); -check('1500 → 90', minimumMeld(1500) === 90); -check('3000 → 120', minimumMeld(3000) === 120); - -// ── 4. Take-pile legality ─────────────────────────────────────────────────────── -console.log('Take-pile legality:'); -{ - const s = createInitialState({ seed: 7 }); - const seat = s.currentPlayer; - // Force a known top card and a matching natural pair in hand. - s.discard = [C('9','s')]; - s.frozen = false; - s.players[seat].hand = [C('9','d'), C('9','c'), C('K','h'), C('4','s')]; - const plan = takePlan(s, seat); - check('two naturals can take an unfrozen pile', !!plan && plan.naturalIds.length === 2); -} -{ - const s = createInitialState({ seed: 8 }); - const seat = s.currentPlayer; - s.discard = [C('9','s')]; - s.frozen = true; - s.players[seat].hand = [C('9','d'), JK(), C('K','h')]; // one natural + wild, but frozen - check('frozen pile needs two naturals (one+wild fails)', takePlan(s, seat) === null); -} -{ - const s = createInitialState({ seed: 9 }); - const seat = s.currentPlayer; - s.discard = [JK()]; // wild on top can never be captured - s.frozen = true; - s.players[seat].hand = [JK(), C('2','c'), C('K','h')]; - check('cannot take a pile topped by a wild', takePlan(s, seat) === null); -} -{ - const s = createInitialState({ seed: 10 }); - const seat = s.currentPlayer; - const t = s.teams[TEAM_OF_SEAT[seat]]; - t.hasMelded = true; - t.melds = [{ rank: '9', cards: [C('9','s'),C('9','d'),C('9','c')] }]; - s.discard = [C('9','h')]; - s.frozen = false; - s.players[seat].hand = [C('9','c'), C('K','h')]; // one natural + existing meld - const plan = takePlan(s, seat); - check('one natural takes via existing meld when unfrozen', !!plan); -} - -// ── 5. Freeze on wild discard (full turn through the engine) ───────────────────── -console.log('Freeze behaviour:'); -{ - let s = createInitialState({ seed: 3 }); - const seat = s.currentPlayer; - s = drawStock(s); - // Give the player a wild to discard. - s.players[seat].hand.push(C('2', 's')); - const wild = s.players[seat].hand[s.players[seat].hand.length - 1]; - s = discard(s, wild.id); - check('discarding a wild freezes the pile', s.frozen === true); -} - -// ── 6. Self-play ──────────────────────────────────────────────────────────────── -const games = Number((process.argv.find((a) => a.startsWith('--games=')) || '').split('=')[1]) || 300; -console.log(`Self-play (${games} games):`); - -function meldWellFormed(m) { - const n = meldNaturals(m), w = meldWilds(m); - return n >= 2 && w <= 3 && w <= n; -} - -function aiTurn(s) { - const seat = s.currentPlayer; - const skill = 3 + (seat % 2); // alternate 3 / 4 - const draw = chooseDraw(s, seat, skill); - s = draw.type === 'take' ? takeDiscard(s, draw.plan) : drawStock(s); - if (s.phase === 'handOver' || s.phase === 'gameOver') return s; // stock-out during draw - if (s.phase === 'draw') s = drawStock(s); // take was rejected → fall back to stock - if (s.phase === 'handOver' || s.phase === 'gameOver') return s; - const { actions } = chooseMelds(s, seat, skill); - for (const a of actions) s = meld(s, a.rank, a.cardIds); - if (s.phase === 'meld') { - const cardId = chooseDiscard(s, seat, skill); - s = discard(s, cardId); - } - return s; -} - -let wins = [0, 0], exceptions = 0, maxHands = 0, malformed = 0, badHandSize = 0; -let meldedGames = 0, draws = 0; -for (let g = 1; g <= games; g++) { - try { - let s = createInitialState({ seed: g * 2654435761 }); - let turns = 0, hands = 0, sawMeld = false; - while (s.phase !== 'gameOver') { - if (s.phase === 'handOver') { - if (++hands > 400) throw new Error('match did not terminate'); - s = startNextHand(s); - continue; - } - if (++turns > 100000) throw new Error('turn loop did not terminate'); - const before = s.currentPlayer; - s = aiTurn(s); - // Validate any melds present. - for (const t of s.teams) for (const m of t.melds) { - if (m.cards.length >= 3 && !meldWellFormed(m)) malformed++; - if (t.melds.length) sawMeld = true; - } - // Hand sizes never negative / absurd. - for (const p of s.players) if (p.hand.length < 0 || p.hand.length > 40) badHandSize++; - if (s.currentPlayer === before && s.phase === 'draw') throw new Error('turn failed to advance'); + // brute force: every subset → partition by rank into legal melds; maximise value + const brute = (hand, need, keep) => { + let best = null; + const n = hand.length; + for (let mask = 1; mask < (1 << n); mask++) { + const used = hand.filter((_, i) => mask & (1 << i)); + if (n - used.length < keep) continue; + const wild = used.filter(isWild); + const nat = used.filter((c) => !isWild(c)); + if (nat.some((c) => !isMeldable(c))) continue; + const ranks = [...new Set(nat.map((c) => c.rank))]; + if (!ranks.length) continue; + // distribute wilds: each rank gets 0..3, total = wild.length + const per = ranks.map((r) => nat.filter((c) => c.rank === r).length); + if (per.some((k) => k < 2)) continue; + let ok = false; + const dist = (i, rem) => { + if (ok) return; + if (i === ranks.length) { if (rem === 0) ok = true; return; } + for (let w = 0; w <= Math.min(MAX_WILDS, rem); w++) { + if (per[i] + w < 3) continue; + dist(i + 1, rem - w); + } + }; + dist(0, wild.length); + if (!ok) continue; + const v = valueOf(used); + if (v < need) continue; + const key = [wild.length, used.length]; + if (!best || key[0] < best[0] || (key[0] === best[0] && key[1] < best[1])) best = key; } - if (sawMeld) meldedGames++; - maxHands = Math.max(maxHands, hands); - if (s.winnerTeam === null) draws++; - else wins[s.winnerTeam]++; - } catch (e) { - exceptions++; - if (exceptions <= 5) console.error(` game ${g}: ${e.message}`); + return best; + }; + let rngS = 12345; + const rnd = () => { rngS = (rngS * 1103515245 + 12345) & 0x7fffffff; return rngS / 0x7fffffff; }; + const shoe = []; for (const r of 'A K Q J T 9 8 7 6 5 4 2'.split(' ')) for (const s of 'shdc') shoe.push(`${r}${s}0`, `${r}${s}1`); + shoe.push('JK0', 'JK1', 'JK2', 'JK3'); + let agree = 0, total = QUICK ? 120 : 400, bad = null; + for (let t = 0; t < total; t++) { + const pool = shoe.slice(); + const hand = []; + // bias toward pairs so melds exist + const size = 7 + Math.floor(rnd() * 6); + while (hand.length < size) { + const id = pool.splice(Math.floor(rnd() * pool.length), 1)[0]; + hand.push(C(id)); + if (rnd() < 0.45 && hand.length < size) { + const twin = pool.findIndex((x) => x.slice(0, -2) === id.slice(0, -2)); + if (twin >= 0) hand.push(C(pool.splice(twin, 1)[0])); + } + } + const need = [15, 50, 90, 120][Math.floor(rnd() * 4)]; + const keep = rnd() < 0.5 ? 2 : 0; + const b = brute(hand, need, keep); + const s = solveInitialMeld(hand, { need, keep }); + let same = (!b && !s) || (b && s); + if (b && s) { + const used = s.groups.flatMap((g) => g.ids).map((id) => hand.find((c) => c.id === id)); + const legal = s.groups.every((g) => meldProblem(g.rank, null, g.ids.map((id) => hand.find((c) => c.id === id))) === null); + same = legal && wildsIn(used) === b[0] && used.length === b[1] && valueOf(used) >= need && hand.length - used.length >= keep; + } + if (same) agree++; else if (!bad) bad = { hand: ids(hand).join(' '), need, keep, b, s }; } + check(`solver matches brute force on ${total} random hands`, agree === total, bad ? JSON.stringify(bad) : ''); + const forced = solveInitialMeld(Cs('Qs0 Qh0 9s0 9h0 9d0 4c0 5d0'), { need: 50, forced: { card: C('Qd1'), rank: 'Q', minNat: 2 }, keep: 2 }); + check('forced (pile) solve: Q-pair + top + nines = 60', forced && forced.value === 60 && forced.groups.some((g) => g.rank === 'Q' && g.ids.length === 2)); + check('forced solve fails without the pair', solveInitialMeld(Cs('Qs0 9s0 9h0 9d0 2c0'), { need: 50, forced: { card: C('Qd1'), rank: 'Q', minNat: 2 } }) === null); } -check('no exceptions during self-play', exceptions === 0, `${exceptions} games threw`); -check('all melds well-formed', malformed === 0, `${malformed} malformed`); -check('hand sizes stay sane', badHandSize === 0, `${badHandSize} bad`); -check('teams meld in most games', meldedGames >= games * 0.9, `${meldedGames}/${games}`); -check('both teams win some games', wins[0] > 0 && wins[1] > 0, `wins ${wins[0]}/${wins[1]}, draws ${draws}`); -console.log(` results: team0 ${wins[0]} / team1 ${wins[1]} / draws ${draws}, longest match ${maxHands} hands`); +// ── 2. Engine fixtures ─────────────────────────────────────────────────────── +section('Deal & upcard'); +{ + let redUp = 0, wildUp = 0, okConserve = true, okHands = true, okFrozenUp = true; + for (let seed = 1; seed <= 400; seed++) { + const gs = L.createGame({ seed }); + if (L.cardCount(gs) !== 108) okConserve = false; + if (gs.hands.some((h) => h.length !== 11 || h.some((c) => c.rank === '3' && (c.suit === 'h' || c.suit === 'd')))) okHands = false; + const top = L.topDiscard(gs); + if (isWild(top) || (top.rank === '3' && 'hd'.includes(top.suit))) okFrozenUp = false; + const covered = gs.discard.length > 1; + if (covered !== gs.frozen) okFrozenUp = false; + if (gs.discard.some((c) => c.rank === '3' && 'hd'.includes(c.suit))) redUp++; + if (gs.discard.slice(0, -1).some(isWild)) wildUp++; + } + check('108 cards accounted for after every deal', okConserve); + check('11 cards each, dealt red threes laid out and replaced', okHands); + check('a wild / red-three upcard is covered and freezes the pile (only then)', okFrozenUp, `${redUp} red, ${wildUp} wild`); + check('red-three and wild upcards actually occur in 400 deals', redUp > 0 && wildUp > 0); + const g = L.createGame({ seed: 99 }); + check('cut for deal recorded', Array.isArray(g.cut) && g.cut.length === 4 && g.dealer >= 0 && g.dealer < 4); +} + +section('Bug fix 1: black three blocks but does not freeze'); +{ + let gs = fixture({ hands: { 0: '3s0 Kh0 Qh0 Qs0', 1: 'Kc0 Ks1 5d0 6d0' }, discard: 'Kd0', phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), melded([{ rank: 'J', cards: 'Js0 Jh0 Jd0' }])] }); + gs = L.discardCard(gs, '3s0'); + check('black three discard leaves the pile unfrozen', gs.frozen === false && gs.current === 1); + check('the next player cannot take a pile topped by a black three', L.takeProblem(gs, 1, { ids: [] }) !== null && L.takeOption(gs, 1).plan === null); + gs = L.drawStock(gs); + gs = L.discardCard(gs, '5d0'); + check('once covered, the pile is takeable with one natural + wild rules intact', L.frozenFor(gs, 2) === false); +} + +section('Bug fix 3: first meld via the pile is atomic and must reach the minimum'); +{ + // Unmelded: Q pair + Q top = 30 — not enough alone; with 9-9-9 (30) = 60 ≥ 50. + let gs = fixture({ hands: { 0: 'Qs0 Qh0 9s0 9h0 9d0 4c0 5d0' }, discard: '7c1 Qd1' }); + const opt = L.takeOption(gs, 0); + check('take plan includes the nines to reach 50', opt.plan && opt.plan.extra.length === 1 && opt.plan.extra[0].rank === '9'); + check('taking with the pair alone is refused (30 < 50)', L.takeProblem(gs, 0, { ids: ['Qs0', 'Qh0'] }) !== null); + const next = L.takePile(gs, opt.plan); + check('take applied: side melded, pile rest in hand', next !== gs && next.teams[0].melded && next.hands[0].some((c) => c.id === '7c1') && next.discard.length === 0); + check('player can discard straight away (no stuck turn)', next.phase === 'play' && L.discardProblem(next, next.hands[0][0].id) === null); + // pile cards can't count toward the minimum + gs = fixture({ hands: { 0: 'Qs0 Qh0 4c0 5d0' }, discard: 'Ks0 Kh0 Kc0 Qd1' }); + check('pile cards never count toward the minimum', L.takeOption(gs, 0).plan === null); +} + +section('Bug fix 4: no going out without a canasta'); +{ + const gs = fixture({ hands: { 0: 'Ks0 Kh0 Kd0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), unmelded()] }); + check('melding down to 0 cards without a canasta is refused', L.checkMelds(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); + const g2 = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), unmelded()] }); + check('melding down to 1 card without a canasta is refused', L.checkMelds(g2, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); + const g3 = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0 6c0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), unmelded()] }); + check('keeping two cards is fine', L.checkMelds(g3, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem === null); + const g4 = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), unmelded()] }); + let out = L.meldCards(g4, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]); + check('with a canasta you may meld down to one card…', out !== g4 && out.hands[0].length === 1); + out = L.discardCard(out, '5c0'); + check('…and go out on the discard (+100)', out.phase === 'handOver' && out.result.outSeat === 0 && out.result.detail[0].goOut === 100); +} + +section('Bug fix 5: exhausted stock'); +{ + let gs = fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: '9d0', stock: '', teams: [melded([{ rank: '9', cards: '9s0 9h0 9c0' }]), unmelded()] }); + check('drawing from an empty stock is impossible', L.drawStock(gs) === gs); + check('top card fits our meld → must take (pass refused)', L.mustTake(gs) && L.passStock(gs) === gs); + const t = L.takePile(gs); + check('forced take works', t !== gs && t.phase === 'play'); + gs = fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: '8d0', stock: '', teams: [melded([{ rank: '9', cards: '9s0 9h0 9c0' }]), unmelded()] }); + const p = L.passStock(gs); + check('nothing to take → the hand ends with no go-out bonus', p.phase === 'handOver' && p.result.reason === 'stock' && p.result.detail.every((d) => d.goOut === 0)); + gs = fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: '8d0', stock: '3h1', teams: [melded([{ rank: '9', cards: '9s0 9h0 9c0' }]), unmelded()] }); + const r = L.drawStock(gs); + check('a red three as the last stock card ends the hand at once', r.phase === 'handOver' && r.teams[0].redThrees.length === 1); +} + +section('Bug fix 6: concealed going out'); +{ + const gs = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 Kc0 Ks1 Kh1 Kd1 4c0 4d0 4h0 5c0' }, phase: 'play', teams: [unmelded(), unmelded()] }); + const chk = L.checkMelds(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0', 'Kc0', 'Ks1', 'Kh1', 'Kd1'] }, { rank: '4', ids: ['4c0', '4d0', '4h0'] }]); + check('whole hand bar one: legal concealed meld', chk.problem === null && chk.goingOut); + let out = L.meldCards(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0', 'Kc0', 'Ks1', 'Kh1', 'Kd1'] }, { rank: '4', ids: ['4c0', '4d0', '4h0'] }]); + out = L.discardCard(out, '5c0'); + check('concealed go-out scores 200', out.result?.concealed === true && out.result.detail[0].goOut === 200); + // concealed waives the minimum + const lowMin = fixture({ hands: { 0: '4s0 4h0 4d0 4c0 4s1 4h1 4d1 5c0' }, phase: 'play', scores: [3500, 0], teams: [unmelded(), unmelded()] }); + check('concealed go-out ignores the 120 minimum', L.checkMelds(lowMin, [{ rank: '4', ids: ['4s0', '4h0', '4d0', '4c0', '4s1', '4h1', '4d1'] }]).problem === null); + check('…but the same cards without going out would need 120', L.checkMelds(lowMin, [{ rank: '4', ids: ['4s0', '4h0', '4d0'] }]).problem !== null); +} + +section('Bug fix 7: black threes meld only when going out'); +{ + const base = { teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), unmelded()], phase: 'play' }; + const gs = fixture({ ...base, hands: { 0: '3s0 3c0 3s1 Kh0 Kd0' } }); + check('black threes mid-hand are refused', L.checkMelds(gs, [{ rank: '3', ids: ['3s0', '3c0', '3s1'] }]).problem !== null); + const g2 = fixture({ ...base, hands: { 0: '3s0 3c0 3s1 Kh0' } }); + check('black threes when going out are fine', L.checkMelds(g2, [{ rank: '3', ids: ['3s0', '3c0', '3s1'] }]).problem === null); +} + +section('Bug fix 8: a tie past the target plays on'); +{ + let gs = fixture({ hands: { 0: '5c0', 1: '6c0', 2: '6d0', 3: '6h0' }, phase: 'play', scores: [4900, 5000 - 70], + teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), melded([{ rank: 'K', cards: 'Ks0 Kh0 Kd0' }])] }); + // team0: 140 + 300 + 100 out - 6 (partner) = 534 → 5434 ; set team1 so the totals tie + const d0 = L.scoreTeam({ ...gs, hands: [[], ...gs.hands.slice(1)] }, 0, 0); + const d1 = L.scoreTeam(gs, 1, 0); + gs.scores = [5000, 5000 + d0.total - d1.total]; + const out = L.discardCard(gs, '5c0'); + check('tied scores past the target → another hand', out.phase === 'handOver' && out.scores[0] === out.scores[1], `${out.scores}`); +} + +section('Pile taking rules'); +{ + const t = () => [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), melded([{ rank: 'J', cards: 'Js0 Jh0 Jd0' }])]; + check('two naturals take an unfrozen pile', L.takeOption(fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: 'Kd0', teams: t() }), 0).plan !== null); + check('one natural + wild takes an unfrozen pile', L.takeOption(fixture({ hands: { 0: 'Ks0 2h0 5c0 6c0' }, discard: 'Kd0', teams: t() }), 0).plan !== null); + check('frozen pile refuses natural + wild', L.takeOption(fixture({ hands: { 0: 'Ks0 2h0 5c0' }, discard: '2d0 Kd0', teams: t(), frozen: true }), 0).plan === null); + check('frozen pile accepts a natural pair', L.takeOption(fixture({ hands: { 0: 'Ks0 Kh0 5c0' }, discard: '2d0 Kd0', teams: t(), frozen: true }), 0).plan !== null); + check('a take leaving a single card (no canasta) is refused', L.takeOption(fixture({ hands: { 0: 'Ks0 Kh0 5c0' }, discard: 'Kd0', teams: t() }), 0).plan === null); + check('top card onto our meld (unfrozen)', L.takeOption(fixture({ hands: { 0: '5c0 6c0' }, discard: 'Ac1', teams: t() }), 0).plan?.ids.length === 0); + check('wild on top cannot be taken', L.takeOption(fixture({ hands: { 0: '5c0 6c0' }, discard: 'Ac1 2c0', teams: t(), frozen: true }), 0).plan === null); + check('discarding a wild freezes', L.discardCard(fixture({ hands: { 0: '2c0 5c0 6c0' }, teams: t(), phase: 'play' }), '2c0').frozen === true); + check('alwaysFrozen rule needs a pair even with a meld', L.takeOption(fixture({ hands: { 0: '5c0 6c0' }, discard: 'Ac1', teams: t(), rules: { alwaysFrozen: true } }), 0).plan === null); + const big = fixture({ hands: { 0: 'Ks0 Kh0 5c0' }, discard: '4c0 4d0 3h0 9c0 Kd0', teams: t() }); + const tk = L.takePile(big); + check('a red three in the pile is laid out, not held', tk.teams[0].redThrees.some((c) => c.id === '3h0') && !tk.hands[0].some((c) => c.id === '3h0')); +} + +section('House rules'); +{ + const one = [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), unmelded()]; + const gs = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: clone(one), rules: { goOutCanastas: 2 } }); + check('two-canasta rule: one canasta is not enough to go out', L.checkMelds(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); + let a = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: clone(one), rules: { askPartner: true } }); + check('askPartner: going out without asking is refused', L.checkMelds(a, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); + a = L.askGoOut(a); + check('askGoOut → partner (seat 2) to answer', a.phase === 'ask' && L.actor(a) === 2); + const no = L.answerGoOut(a, false); + check('a "no" binds for the turn', no.phase === 'play' && L.checkMelds(no, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null && L.askGoOut(no) === no); + const yes = L.answerGoOut(a, true); + check('a "yes" lets you go out', L.checkMelds(yes, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem === null); + const g = L.createGame({ seed: 4, rules: { target: 2500 } }); + check('target is stored with the rules', g.rules.target === 2500 && L.minimumFor({ ...g, scores: [1300, 0] }, 0) === 90); +} + +section('Scoring'); +{ + const gs = fixture({ hands: { 0: '', 1: 'Ks1 JK3', 2: '5c0', 3: '' } }); + gs.teams = [ + { melds: [{ rank: 'A', cards: Cs('As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1') }, { rank: 'K', cards: Cs('Ks0 Kh0 2c0 Kd0 Kc0 Kh1 Kd1') }], redThrees: Cs('3h0 3d0 3h1 3d1'), melded: true }, + { melds: [], redThrees: Cs(''), melded: false }, + ]; + const d = L.scoreTeam(gs, 0, 0, false); + check('natural 500 + mixed 300', d.natural === 1 && d.mixed === 1 && d.canastaBonus === 800); + check('all four red threes = 800', d.redThreeBonus === 800); + check('meld points and in-hand penalty', d.meldPoints === 140 + 80 && d.inHand === 5 && d.total === 220 + 800 + 800 + 100 - 5); + gs.teams[1].redThrees = Cs('3h0'); + const d1 = L.scoreTeam(gs, 1, 0, false); + check('an unmelded side loses its red threes and its hand', d1.redThreeBonus === -100 && d1.inHand === 60 && d1.total === -160); +} + +// ── 3. AI self-play ────────────────────────────────────────────────────────── +function seeded(seed) { + let a = seed >>> 0; + return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; +} + +/** Play one full turn (or answer) for whoever is to act. Throws on any illegal move. */ +function step(gs, skills, rnd) { + const seat = L.actor(gs); + const sk = skills[seat]; + if (gs.phase === 'ask') { + const n = L.answerGoOut(gs, chooseAnswer(gs, sk)); + if (n === gs) throw new Error('answer refused'); + return n; + } + if (gs.phase === 'draw') { + const d = chooseDraw(gs, seat, sk, rnd); + const n = d.type === 'take' ? L.takePile(gs, d.plan) : d.type === 'pass' ? L.passStock(gs) : L.drawStock(gs); + if (n === gs) throw new Error(`draw refused: ${JSON.stringify(d)} ${L.takeProblem(gs, seat, d.plan ?? { ids: [] })}`); + return n; + } + if (gs.phase === 'play') { + let g = gs; + for (let guard = 0; guard < 30 && g.phase === 'play'; guard++) { + const m = chooseMelds(g, seat, sk); + if (!m) break; + if (m.ask) { const a = L.askGoOut(g); if (a === g) throw new Error('ask refused'); return a; } + const n = L.meldCards(g, m.groups); + if (n === g) throw new Error(`meld refused: ${JSON.stringify(m.groups)} — ${L.checkMelds(g, m.groups).problem}`); + g = n; + } + if (g.phase !== 'play') return g; + const id = chooseDiscard(g, seat, sk, rnd); + const n = L.discardCard(g, id); + if (n === g) throw new Error(`discard refused: ${id} — ${L.discardProblem(g, id)}`); + return n; + } + throw new Error(`unexpected phase ${gs.phase}`); +} + +function playMatch(seed, skills, rules = {}, { onState = null } = {}) { + const rnd = seeded(seed * 7 + 1); + let gs = L.createGame({ seed, rules }); + let steps = 0; + while (gs.phase !== 'gameOver') { + if (gs.phase === 'handOver') { gs = L.nextHand(gs); continue; } + gs = step(gs, skills, rnd); + onState?.(gs); + if (++steps > 40000) throw new Error('match did not terminate'); + } + return gs; +} + +section(`AI self-play (${GAMES} matches, house rules mixed in)`); +{ + let errors = 0, firstErr = '', badCards = 0, badMeld = 0, wins = [0, 0], hands = 0, outs = 0, concealed = 0, stockEnds = 0; + let maxHands = 0, canastas = 0, saves = 0, saveBad = 0, asks = 0; + const ruleSets = [{}, { goOutCanastas: 2 }, { askPartner: true }, { alwaysFrozen: true }, { target: 2500 }]; + for (let i = 0; i < GAMES; i++) { + const rules = ruleSets[i % ruleSets.length]; + const skills = [1 + (i % 5), 1 + ((i + 2) % 5), 1 + ((i + 1) % 5), 1 + ((i + 3) % 5)]; + try { + const end = playMatch(1000 + i, skills, rules, { + onState: (gs) => { + if (L.cardCount(gs) !== 108) badCards++; + for (const t of gs.teams) for (const m of t.melds) { + if (m.rank === '3') { if (m.cards.length < 3 || m.cards.some((c) => c.rank !== '3')) badMeld++; continue; } + if (naturalsIn(m.cards) < 2 || wildsIn(m.cards) > MAX_WILDS || m.cards.length < 3 || m.cards.some((c) => !isWild(c) && c.rank !== m.rank)) badMeld++; + } + if (gs.phase === 'ask') asks++; + if (gs.phase === 'draw' && Math.random() < 0.02) { + saves++; + const back = JSON.parse(JSON.stringify(gs)); + if (JSON.stringify(back) !== JSON.stringify(gs)) saveBad++; + } + if (gs.phase === 'handOver' || gs.phase === 'gameOver') { + hands++; + if (gs.result.reason === 'stock') stockEnds++; else outs++; + if (gs.result.concealed) concealed++; + } + }, + }); + wins[end.winner]++; + maxHands = Math.max(maxHands, end.handNo); + canastas += end.stats.reduce((s, x) => s + x.canastas, 0); + } catch (e) { + errors++; + if (!firstErr) firstErr = `match ${i}: ${e.message}`; + } + } + check('no illegal AI moves or exceptions', errors === 0, firstErr); + check('108 cards conserved at every step', badCards === 0, `${badCards}`); + check('every meld on the table is well-formed', badMeld === 0, `${badMeld}`); + check('both sides win matches', wins[0] > 0 && wins[1] > 0, `${wins}`); + check('hands mostly end by going out', outs > stockEnds * 3, `out ${outs} / stock ${stockEnds}`); + check('askPartner rule exercised', asks > 0, `${asks}`); + check('state survives a JSON round trip', saveBad === 0 && saves > 0, `${saves} sampled`); + console.log(` ${hands} hands, ${canastas} canastas, ${concealed} concealed go-outs, longest match ${maxHands} hands, wins ${wins}`); +} + +section('Coach'); +{ + let ok = true, why = ''; + for (let seed = 1; seed <= 40 && ok; seed++) { + let gs = L.createGame({ seed }); + const rnd = seeded(seed); + for (let k = 0; k < 120 && gs.phase !== 'gameOver'; k++) { + if (gs.phase === 'handOver') { gs = L.nextHand(gs); continue; } + if (gs.current === 0 && gs.phase === 'draw') { + const c = coachDraw(gs, 0); + if (!c?.text) { ok = false; why = 'coachDraw no text'; } + if (c.type === 'take' && L.takeProblem(gs, 0, c.plan)) { ok = false; why = 'coach suggested illegal take'; } + } + if (gs.current === 0 && gs.phase === 'play') { + const m = coachMelds(gs, 0); + if (m?.groups && L.checkMelds(gs, m.groups).problem) { ok = false; why = `coach meld illegal: ${L.checkMelds(gs, m.groups).problem}`; } + const d = coachDiscard(gs, 0); + if (!d?.text || L.discardProblem(gs, d.id)) { ok = false; why = 'coach discard illegal'; } + } + gs = step(gs, [5, 3, 3, 3], rnd); + } + } + check('coach suggestions are always legal and explained', ok, why); +} + +section(`Skill ladder (${LADDER} paired matches, skill 5 vs skill 1)`); +{ + let strong = 0, total = 0, pts = 0; + for (let i = 0; i < LADDER; i++) { + for (const flip of [false, true]) { + const skills = flip ? [1, 5, 1, 5] : [5, 1, 5, 1]; + const strongTeam = flip ? 1 : 0; + try { + const end = playMatch(5000 + i, skills, { target: 2500 }); + total++; + if (end.winner === strongTeam) strong++; + pts += end.scores[strongTeam] - end.scores[1 - strongTeam]; + } catch (e) { check('ladder match runs', false, e.message); } + } + } + check('skill 5 beats skill 1 most of the time', strong / total >= 0.65, `${strong}/${total}, avg margin ${Math.round(pts / Math.max(1, total))}`); + console.log(` skill 5 won ${strong}/${total} (avg margin ${Math.round(pts / Math.max(1, total))})`); +} + +// ── 4. Layout ──────────────────────────────────────────────────────────────── +section('Layout'); +try { + const T = await import('../src/games/canasta/CanastaTable.js'); + if (typeof T.verifyLayout === 'function') { + const problems = T.verifyLayout(); + check('no overlaps at maximum counts', problems.length === 0, problems.slice(0, 5).join('; ')); + } else console.log(' (no verifyLayout export yet)'); +} catch (e) { + if (e.code === 'ERR_MODULE_NOT_FOUND') console.log(' (CanastaTable.js not present yet)'); + else check('layout module loads', false, e.message); +} console.log(failures ? `\n${failures} check(s) FAILED` : '\nAll checks passed.'); process.exit(failures ? 1 : 0);