Rework Canasta into Rosa's Parlor with full partnership rules

- New 1950s living-room art (baked canvas textures), shared CardTableScene
  base, and table layout with meld bands, score pad, and ticker
- Rewritten rules engine on plain JSON state: atomic first-meld pile takes,
  go-out validation (canasta requirement + optional partner ask), exhausted
  stock, concealed go-out, black-three melding, tie past target, and four
  house-rule toggles (target, two canastas, ask partner, always frozen)
- Exact initial-meld solver (exhaustive per-rank natural/wild enumeration)
  with brute-force cross-check in the verify harness
- Partnership AI rebuilt around skill profiles (noise, memory, danger,
  freeze, block, hold-out) plus a Coach layer that explains draws, melds,
  and discards in Rosa's voice
- Partner table talk, how-to-play and settings dialogs, hand tally with
  animated score reveal, end-of-match screen with score-race chart, and
  lifetime stats persisted to localStorage
- Save/resume mid-match via versioned JSON in localStorage
- Expanded verify suite: per-bug-fix fixtures, solver vs brute-force,
  AI self-play with invariants, save/load round-trips, and layout check
This commit is contained in:
Brian Fertig 2026-12-01 11:06:08 -07:00
parent 5424a7e379
commit ad9c58528b
11 changed files with 4441 additions and 1856 deletions

View File

@ -1,199 +1,387 @@
// Canasta — heuristic partnership AI. No Phaser, no state mutation. Each chooser // Canasta — partnership AI and the Coach. No Phaser, no state mutation: every
// inspects the (already-cloned) engine state and returns a plain action // chooser inspects the engine state and returns a plain descriptor the scene /
// descriptor that the scene / verify harness applies through CanastaLogic. // verify harness applies through CanastaLogic.
// //
// A full AI turn is three calls, in order: // A turn is:
// 1. chooseDraw → { type:'stock' } | { type:'take', plan } // chooseDraw(gs, seat, skill) → { type:'stock' } | { type:'take', plan } | { type:'pass' }
// 2. chooseMelds → { actions:[{rank,cardIds}] } (applied in sequence) // chooseMelds(gs, seat, skill) → { groups } | { ask:true } | null (repeat until null)
// 3. chooseDiscard→ cardId // chooseDiscard(gs, seat, skill) → cardId
// The AI is partner-aware: melds belong to the team, so it freely extends a // chooseAnswer(gs, skill) → true/false (partner's reply to "may I go out?")
// partner's melds and counts the partnership's canastas when deciding to 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 { import {
takePlan, takeDiscard, meld, meetsInitialMeld, teamMeld, isCanasta, CANASTA_SIZE, MAX_WILDS, TEAM_OF_SEAT, SEATS_OF_TEAM, PARTNER, MELD_RANKS,
meldNaturals, meldWilds, isWild, isBlackThree, isMeldable, cardScore, valueOf, solveInitialMeld, isCanasta,
} from './CanastaLogic.js'; wildsIn, naturalsIn, rankWord, rankLabel, cardName,
import {
isWild, isMeldable, isBlackThree, cardScore, minimumMeld,
TEAM_OF_SEAT, CANASTA_SIZE, MAX_WILDS_IN_MELD,
} from './CanastaData.js'; } 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 = { const PROFILE = {
1: { delay: [820, 1300], aggression: 0.35, pushCanasta: false, noise: 2.4 }, 1: { noise: 26, memory: false, danger: 0.2, freeze: false, block: 0.3, takeBar: 70, holdOut: false, miss: 0.25 },
2: { delay: [720, 1150], aggression: 0.5, pushCanasta: false, noise: 1.6 }, 2: { noise: 16, memory: false, danger: 0.5, freeze: false, block: 0.6, takeBar: 45, holdOut: false, miss: 0.12 },
3: { delay: [620, 1000], aggression: 0.65, pushCanasta: true, noise: 1.0 }, 3: { noise: 9, memory: true, danger: 0.85, freeze: true, block: 0.85, takeBar: 30, holdOut: true, miss: 0.04 },
4: { delay: [520, 880], aggression: 0.8, pushCanasta: true, noise: 0.5 }, 4: { noise: 4, memory: true, danger: 1.1, freeze: true, block: 1, takeBar: 22, holdOut: true, miss: 0 },
5: { delay: [440, 760], aggression: 0.95, pushCanasta: true, noise: 0.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 nextSeat = (s) => (s + 1) % 4;
const [lo, hi] = prof(skill).delay; const oppTeam = (seat) => 1 - TEAM_OF_SEAT[seat];
return lo + Math.random() * (hi - lo);
/** 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]]; } /** Is the other side close to going out? 0 (no) … 1 (any moment). */
function valueOfCards(cards) { return cards.reduce((s, c) => s + cardScore(c), 0); } export function threatOf(gs, team) {
const need = gs.rules.goOutCanastas ?? 1;
function groupNaturalsByRank(cards) { const have = canastaCount(gs, team);
const g = {}; const minHand = Math.min(...SEATS_OF_TEAM[team].map((s) => gs.hands[s].length));
for (const c of cards) { let t = 0;
if (isWild(c) || !isMeldable(c)) continue; if (have >= need) t = minHand <= 2 ? 1 : minHand <= 4 ? 0.7 : minHand <= 7 ? 0.35 : 0.15;
(g[c.rank] ||= []).push(c); 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 g; return t;
} }
// ── Core meld builder (no minimum gate) ────────────────────────────────────── // ── Draw ─────────────────────────────────────────────────────────────────────
// Greedily proposes meld actions against a working copy of the seat's hand: /** How much would taking the pile be worth to this seat? */
// extend the team's existing melds, then form fresh melds from triples, then function pileWorth(gs, seat, plan) {
// 2-natural + wild starters. Returns { actions, hand, usedIds }. const hand = gs.hands[seat];
function buildMeldActions(state, seat, p) { const team = teamOf(gs, seat);
const t = team(state, seat); const top = topDiscard(gs);
const hand = state.players[seat].hand.slice(); const rest = gs.discard.slice(0, -1);
const used = new Set(); const rankCount = {};
const actions = []; for (const c of hand) if (isMeldable(c)) rankCount[c.rank] = (rankCount[c.rank] || 0) + 1;
const remaining = () => hand.filter((c) => !used.has(c.id)); let w = 25; // the top card goes straight onto a meld
const wilds = () => remaining().filter((c) => isWild(c)); if (!team.melded) w += 60; // and it unlocks the side's first meld
const take = (cards) => cards.forEach((c) => used.add(c.id)); 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;
// 1. Extend existing team melds with matching naturals. for (const c of rest) {
for (const m of t.melds) { if (isWild(c)) { w += 30; continue; }
const adds = remaining().filter((c) => c.rank === m.rank && !isWild(c)); if (isBlackThree(c)) { w -= 4; continue; }
if (adds.length) { actions.push({ rank: m.rank, cardIds: adds.map((c) => c.id) }); take(adds); } if (team.melds.some((m) => m.rank === c.rank)) w += 14;
else if (rankCount[c.rank]) w += 10;
else w += 4;
} }
// 2. Fresh melds from ranks with three or more naturals. // a fat hand is a liability if the other side might go out soon
let groups = groupNaturalsByRank(remaining()); const threat = threatOf(gs, oppTeam(seat));
for (const rank of Object.keys(groups)) { w -= threat * valueOf(rest) * 0.4;
if (teamMeld(state, seat, rank)) continue; return w;
const nat = groups[rank];
if (nat.length >= 3) { actions.push({ rank, cardIds: nat.map((c) => c.id) }); take(nat); }
}
// 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);
}
}
return { actions, hand, used };
} }
const actionsValue = (actions, hand) => export function chooseDraw(gs, seat, skill = 3, rnd = Math.random) {
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
}
// ── Draw decision ──────────────────────────────────────────────────────────────
export function chooseDraw(state, seat, skill) {
const p = prof(skill); const p = prof(skill);
const plan = takePlan(state, seat); const { plan } = takeOption(gs, seat);
if (plan && takeYieldsLegalTurn(state, seat, skill, plan)) { if (!gs.stock.length) {
const t = team(state, seat); if (mustTake(gs, seat)) return { type: 'take', plan: takeOption(gs, seat).plan };
const pileSize = state.discard.length; if (plan && pileWorth(gs, seat, plan) > 0) return { type: 'take', plan };
const chance = !t.hasMelded return { type: 'pass' };
? 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' }; 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' };
} }
// ── Meld planning ────────────────────────────────────────────────────────────── // ── Melding ──────────────────────────────────────────────────────────────────
export function chooseMelds(state, seat, skill) { /**
const p = prof(skill); * Try to lay the whole hand (bar at most one card to discard). Returns
const t = team(state, seat); * { groups, discard } or null. Wilds go where they are legal, canasta-bound
const { actions, hand, used } = buildMeldActions(state, seat, p); * melds first.
const preValue = valueOfCards(state.meldedThisTurn); // captured from a pile-take this turn */
const minNeeded = minimumMeld(t.score); function goOutPlan(gs, seat) {
const hand = gs.hands[seat];
// Initial-meld gate: if the team hasn't melded and even everything on the table const team = teamOf(gs, seat);
// plus these actions can't clear the minimum, lay nothing extra this turn. const groups = new Map();
if (!t.hasMelded && preValue + actionsValue(actions, hand) < minNeeded) { const add = (rank, c) => { if (!groups.has(rank)) groups.set(rank, []); groups.get(rank).push(c); };
return { actions: [] }; const left = [];
const byRank = {};
for (const c of hand) {
if (isWild(c)) continue;
(byRank[c.rank] ||= []).push(c);
} }
for (const [rank, cards] of Object.entries(byRank)) {
const remaining = () => hand.filter((c) => !used.has(c.id)); if (rank === '3') {
const wilds = () => remaining().filter((c) => isWild(c)); if (cards.length >= 3) cards.forEach((c) => add('3', c)); else left.push(...cards);
continue;
// 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++;
} }
const existing = team.melds.find((m) => m.rank === rank);
if (existing || cards.length >= 2) cards.forEach((c) => add(rank, c));
else left.push(...cards);
} }
} // Wilds: complete 2-natural starters first, then any meld with wild room.
const wilds = hand.filter(isWild).sort((a, b) => cardScore(a) - cardScore(b));
// Will the team hold a canasta once these actions land? const room = (rank) => {
const willHaveCanasta = () => { if (rank === '3') return 0;
if (t.melds.some(isCanasta)) return true; const ex = team.melds.find((m) => m.rank === rank)?.cards ?? [];
for (const a of actions) { const g = groups.get(rank) ?? [];
const m = teamMeld(state, seat, a.rank); return MAX_WILDS - wildsIn([...ex, ...g]);
if ((m ? m.cards.length : 0) + a.cardIds.length >= CANASTA_SIZE) return true;
}
return false;
}; };
const needs = (rank) => {
// Keep at least one card to discard; only deplete to a single card when the const ex = team.melds.find((m) => m.rank === rank)?.cards ?? [];
// team will then hold a canasta (a legal go-out). return ex.length + (groups.get(rank)?.length ?? 0) < 3;
if (!(willHaveCanasta() && remaining().length === 1)) { };
while (actions.length && remaining().length < 2) { for (const rank of [...groups.keys()]) {
const a = actions.pop(); while (needs(rank) && wilds.length && room(rank) > 0) add(rank, wilds.shift());
a.cardIds.forEach((id) => used.delete(id));
} }
if (!t.hasMelded && preValue + actionsValue(actions, hand) < minNeeded) return { actions: [] }; for (const rank of [...groups.keys()]) {
while (wilds.length && room(rank) > 0) add(rank, wilds.shift());
} }
left.push(...wilds);
return { actions }; // 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 };
} }
// ── Discard decision ─────────────────────────────────────────────────────────── /** Should the seat go out now (when it can)? */
export function chooseDiscard(state, seat, skill) { function wantsOut(gs, seat, p) {
const p = prof(skill); if (!p.holdOut) return true;
const hand = state.players[seat].hand; const team = TEAM_OF_SEAT[seat];
if (hand.length === 0) return null; const threat = threatOf(gs, 1 - team);
if (hand.length === 1) return hand[0].id; // forced (going out / last card) 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;
}
/** 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 team = teamOf(gs, seat);
const hand = gs.hands[seat];
// 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 };
}
}
}
if (!team.melded) {
const g = firstMeld(gs, seat);
if (g && !checkMelds(gs, g).problem) return { groups: g };
return null;
}
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 ──────────────────────────────────────────────────────────────────
/**
* 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 = 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 = {}; 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. return hand.map((c) => {
const score = (c) => { let s = 0, why = '';
if (isWild(c)) return 1000; // never throw wilds if (isWild(c)) {
if (teamMeld(state, seat, c.rank)) return 800; // could be laid off — keep s = 260;
let s = (counts[c.rank] || 1) * 30; // keep pairs/triples why = 'wild cards build canastas';
s += cardScore(c); // shed cheap cards first // freeze a fat pile the next player could take
if (isBlackThree(c)) s -= 18; // black threes block the pile if (p.freeze && !gs.frozen && pile >= 6 && wildCount >= 2 && c.rank === '2') {
s += (Math.random() - 0.5) * 2 * p.noise * 12; // skill noise const theyCanTake = !nextFrozen || Object.keys(known).length > 0;
return s; if (theyCanTake) { s = 18; why = `freeze the pile — it's ${pile} cards and ${'they'} are hungry for it`; }
}; }
} else if (isBlackThree(c)) {
let best = hand[0], bestS = score(best); s = 30 - pile * 2.5 * p.block;
for (const c of hand) { const s = score(c); if (s < bestS) { best = c; bestS = s; } } why = pile >= 3 ? `a black three blocks the next player from the ${pile}-card pile` : 'black threes are no use to keep';
return best.id; } 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); }

View File

@ -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 };

View File

@ -1,132 +1,243 @@
// Canasta — static data, scoring helpers and table geometry. No Phaser, no // Canasta — cards, rules and meld helpers. Pure (no Phaser, no state) so the
// state: imported by the logic engine, the AI, the Phaser scene and the headless // engine, the AI, the scene and tools/verifyCanasta.js all share it.
// verify harness alike.
// //
// Classic partnership Canasta: two decks + four jokers (108 cards), four players // Classic partnership Canasta (Hoyle / pagat.com): two decks plus four jokers
// in two fixed partnerships (seats 0 & 2 vs seats 1 & 3), race to 5000 points. // (108 cards), four players in fixed partnerships — seats 0 & 2 (you and Rosa)
// against seats 1 & 3 — racing to 5,000.
import { SUITS, RANKS, Card } from '../cards/Deck.js'; //
// Cards are plain JSON so a whole game state can be autosaved:
export { Card }; // { id: 'Ks1', rank: 'K', suit: 's' } (the trailing digit is the deck, 0/1)
// { id: 'JK2', rank: 'JK', suit: 'x' } (jokers 0..3)
export const ICON_FRAME = 65; export const 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 PLAYER_COUNT = 4;
export const INITIAL_HAND = 11; // cards dealt to each player export const HAND_SIZE = 11;
export const WIN_SCORE = 5000; // cumulative team score that ends the match export const CANASTA_SIZE = 7;
export const CANASTA_SIZE = 7; // a meld of seven cards is a canasta export const MAX_WILDS = 3; // a meld may hold at most three wild cards
export const MAX_WILDS_IN_MELD = 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_CARDS = 3; // a fresh meld is at least three cards export const MIN_MELD = 3;
// Bonus values (added to a team's hand score). export const TEAM_OF_SEAT = [0, 1, 0, 1];
export const NATURAL_CANASTA = 500; // a canasta with no wild cards (pure) export const SEATS_OF_TEAM = [[0, 2], [1, 3]];
export const MIXED_CANASTA = 300; // a canasta containing 1–3 wild cards export const PARTNER = [2, 3, 0, 1];
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
// ── Card classifiers ───────────────────────────────────────────────────────── export const SUITS = ['s', 'h', 'd', 'c'];
/** Wild card: a joker or any two. */ export const RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'];
export function isWild(card) { /** Ranks that can form ordinary melds, high to low (display order). */
return card.rank === 'JK' || card.rank === '2'; export const MELD_RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4'];
} export const SUIT_SYM = { s: '♠', h: '♥', d: '♦', c: '♣', x: '' };
/** Red three — a bonus card, laid out immediately, never melded or discarded. */ const RANK_WORD = {
export function isRedThree(card) { A: 'ace', K: 'king', Q: 'queen', J: 'jack', T: 'ten', 9: 'nine', 8: 'eight', 7: 'seven',
return card.rank === '3' && (card.suit === 'h' || card.suit === 'd'); 6: 'six', 5: 'five', 4: 'four', 3: 'three', 2: 'two', JK: 'joker',
} };
/** Black three — only ever melded when going out (omitted here); blocks the pile. */
export function isBlackThree(card) { // ── Scoring constants ────────────────────────────────────────────────────────
return card.rank === '3' && (card.suit === 's' || card.suit === 'c'); export const NATURAL_CANASTA = 500;
} export const MIXED_CANASTA = 300;
/** A natural card that may form/extend a rank meld (4..A, not 3, not wild). */ export const RED_THREE = 100;
export function isMeldable(card) { export const ALL_RED_THREES = 800;
return !isWild(card) && card.rank !== '3'; export const GO_OUT = 100;
export const CONCEALED_GO_OUT = 200;
/** Standard rules. Every key is a Settings toggle. */
export const DEFAULT_RULES = {
target: 5000, // 5000 · 3000 · 2500
goOutCanastas: 1, // canastas a side needs before it may go out (1 or 2)
askPartner: false, // "Partner, may I go out?" — a 'no' binds for the turn
alwaysFrozen: false, // the pile is always frozen: only a natural pair takes it
};
// ── Cards ────────────────────────────────────────────────────────────────────
export function fullShoe() {
const out = [];
for (let d = 0; d < 2; d++) {
for (const s of SUITS) for (const r of RANKS) out.push({ id: `${r}${s}${d}`, rank: r, suit: s });
}
for (let j = 0; j < 4; j++) out.push({ id: `JK${j}`, rank: 'JK', suit: 'x' });
return out;
} }
/** const SHOE = new Map(fullShoe().map((c) => [c.id, c]));
* Point value of a single card, used for melds, the initial-meld minimum and export const cardFromId = (id) => SHOE.get(id) ?? null;
* the deduction for cards left in hand. Red threes score as a separate bonus. /** Texture frame in the shared 'casino-cards' atlas. */
*/ export const frameOf = (c) => (c.rank === 'JK' ? 'JK' : `${c.rank}${c.suit}`);
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
}
/** Minimum total card value required for a team's very first meld of the game. */ export const isWild = (c) => c.rank === 'JK' || c.rank === '2';
export function minimumMeld(teamScore) { export const isRedThree = (c) => c.rank === '3' && (c.suit === 'h' || c.suit === 'd');
if (teamScore < 0) return 15; export const isBlackThree = (c) => c.rank === '3' && (c.suit === 's' || c.suit === 'c');
if (teamScore < 1500) return 50; /** A natural that may form an ordinary rank meld (4..A). */
if (teamScore < 3000) return 90; 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; return 120;
} }
// ── Theme (luxe casino card room) ───────────────────────────────────────────── // ── Melds ────────────────────────────────────────────────────────────────────
export const THEME = { // A meld on the table is { rank, cards: [card…] }.
feltTop: 0x1c6b3a, // emerald baize, lit centre export const wildsIn = (cards) => cards.filter(isWild).length;
feltMid: 0x0f4a27, // mid green export const naturalsIn = (cards) => cards.filter((c) => !isWild(c)).length;
feltEdge: 0x062c16, // deep green near the rail export const isCanasta = (m) => m.cards.length >= CANASTA_SIZE;
rail: 0x4a1410, // burgundy leather rail export const isNaturalCanasta = (m) => isCanasta(m) && wildsIn(m.cards) === 0;
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',
};
// ── Table geometry ──────────────────────────────────────────────────────────── /**
// Four seats around the felt. Seat 0 = South (human), 1 = West, 2 = North * Why can't `adds` go onto `existing` (a team meld of `rank`, or null for a new
// (human's partner), 3 = East. Returns the anchors the scene needs to lay out * meld)? Returns null when legal, else a plain-English reason for the UI.
// hands, the central stock/discard and the two team meld strips. * Black threes form a meld only when going out (the engine checks that).
export function buildTableLayout(rect) { */
const { x, y, w, h } = rect; export function meldProblem(rank, existing, adds) {
const cx = x + w / 2; if (!adds.length) return 'No cards selected';
const cy = y + h / 2; if (rank === '3') {
return { if (existing) return 'Black threes are melded all at once';
cx, cy, if (adds.some((c) => !isBlackThree(c))) return 'A meld of threes may hold only black threes';
// hand anchors (centre of each player's fanned hand) if (adds.length < 3) return 'Black threes meld three or four at a time';
seats: { return null;
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' } }, for (const c of adds) {
2: { x: cx, y: y + 96, dir: 'h', label: { x: x + 40, y: y + 40, align: 'left' } }, if (isWild(c)) continue;
3: { x: x + w - 150, y: cy - 40, dir: 'v', label: { x: x + w - 40, y: cy - 220, align: 'right' } }, 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)}`;
// central piles }
stock: { x: cx - 70, y: cy }, const all = [...(existing?.cards ?? []), ...adds];
discard: { x: cx + 70, y: cy }, const nat = naturalsIn(all), wild = wildsIn(all);
// team meld strips (team 0 below centre near the human, team 1 above) if (wild > MAX_WILDS) return 'A meld may hold at most three wild cards';
meldZones: { if (nat < MIN_NATURALS) return 'A meld needs at least two natural cards';
0: { x: cx, y: cy + 150, label: { x: x + 40, y: cy + 120 } }, if (!existing && all.length < MIN_MELD) return 'A new meld needs at least three cards';
1: { x: cx, y: cy - 230, label: { x: x + 40, y: cy - 260 } }, return null;
},
// team score panels
panels: {
0: { x: x + w - 250, y: y + h - 120 },
1: { x: x + w - 250, y: y + 60 },
},
};
} }
// Convenience: the four standard seats and which team each belongs to. /** The rank a selection would meld as (its naturals' rank), or null when mixed / all wild. */
export const TEAM_OF_SEAT = [0, 1, 0, 1]; export function selectionRank(cards) {
export const SEATS_OF_TEAM = [[0, 2], [1, 3]]; 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. // ── Exact initial-meld solver ────────────────────────────────────────────────
export { SUITS, RANKS }; /**
* 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;
}

View File

@ -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 };

View File

@ -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;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -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;
}

View File

@ -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) : '');
}

View File

@ -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 ## 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 ## 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. | Card | Points |
- **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. | 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 ### 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. - **Two natural cards** of the top card's rank always do 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. - 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 ### 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 ### 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 ## 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. - **Natural canasta** — no wilds at all. A **red** card on top. **500** points.
- **Mixed canasta** — seven cards with a wild or two. Still grand. **300** points. - **Mixed canasta** — one to three wilds. A **black** card on top. **300** points.
You'll see ours glow gold (natural) or silver (mixed) in the meld area.
## Going Out ## 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 ## 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. - **Hoard for a canasta.** A meld of four is nice; a canasta is a fortune.
- **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. - **Watch what they pick up.** Hover their nameplates — I keep track of what they took from the pile. Don't feed them those ranks.
- **Mind the freeze.** Frozen piles are heavy and hard to take; freeze it when *we're* sitting pretty and they aren't. - **Freeze it when it's fat.** A big pile and a hungry opponent? A two on top shuts the door.
- **Red threes love a melded team.** Get a meld down early so our bonus cards count *for* us. - **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.

View File

@ -1,22 +1,30 @@
// Headless verification for Canasta. // Headless verification for Canasta ("Rosa's Parlor").
// node server/scripts/verifyCanasta.js [--games=N] // node tools/verifyCanasta.js [--games=N] [--ladder=N] [--quick]
// Exits non-zero on any failure. // Exits non-zero on any failure.
// //
// 1. Fixture tests: card values, canasta/red-three/go-out scoring, the initial // 1. Data: card values, the first-meld minimum, meld legality, and the exact
// meld minimum, freeze behaviour and discard-pile take legality. // first-meld solver against a brute-force search.
// 2. Self-play: full partnership games driven by the heuristic AI in all four // 2. Engine fixtures: one per rules fix (black-three blocks without freezing,
// seats, asserting invariants (no exceptions, hands have legal sizes, melds // the upcard, atomic first-meld pile takes, no going out without a
// are well-formed, the match terminates with a winner) over many seeded games. // 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 { import {
Card, cardScore, minimumMeld, NATURAL_CANASTA, MIXED_CANASTA, ALL_RED_THREES, DEFAULT_RULES, cardFromId, cardScore, minimumMeld, meldProblem, solveInitialMeld, valueOf,
GO_OUT, CONCEALED_GO_OUT, TEAM_OF_SEAT, PLAYER_COUNT, isWild, isRedThree, isWild, isMeldable, isCanasta, wildsIn, naturalsIn, TEAM_OF_SEAT, CANASTA_SIZE, MAX_WILDS,
} from '../src/games/canasta/CanastaData.js'; } from '../src/games/canasta/CanastaData.js';
import * as L from '../src/games/canasta/CanastaLogic.js';
import { import {
createInitialState, drawStock, takeDiscard, meld, discard, startNextHand, chooseDraw, chooseMelds, chooseDiscard, chooseAnswer, coachDraw, coachMelds, coachDiscard,
takePlan, scoreTeamHand, teamMeld, isCanasta, meldNaturals, meldWilds, } from '../src/games/canasta/CanastaAI.js';
} from '../src/games/canasta/CanastaLogic.js';
import { chooseDraw, chooseMelds, chooseDiscard } 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; let failures = 0;
function check(name, cond, detail = '') { function check(name, cond, detail = '') {
@ -24,213 +32,442 @@ function check(name, cond, detail = '') {
failures++; failures++;
console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`); 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 /** A blank state in the draw phase for seat 0 with the given hands / pile. */
// into a real state never collide with dealt cards. function fixture({ hands = {}, discard = 'Kd0', stock = null, teams = null, rules = {}, frozen = false, scores = [0, 0], current = 0, phase = 'draw' } = {}) {
let _id = 100000; const gs = L.createGame({ seed: 7, rules, dealer: 3 });
const C = (rank, suit) => { const c = new Card(rank, suit); c.id = _id++; return c; }; gs.hands = [0, 1, 2, 3].map((s) => (hands[s] != null ? Cs(hands[s]) : Cs('4s0 5s0 6s0')));
const JK = () => C('JK', 'r'); 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. // ── 1. Data ──────────────────────────────────────────────────────────────────
function mkState() { section('Card values & minimum');
const players = []; check('joker 50, two 20, ace 20', cardScore(C('JK0')) === 50 && cardScore(C('2s0')) === 20 && cardScore(C('Ah0')) === 20);
for (let i = 0; i < PLAYER_COUNT; i++) players.push({ seat: i, team: TEAM_OF_SEAT[i], hand: [] }); 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);
const teams = [0, 1].map(() => ({ melds: [], redThrees: [], hasMelded: false, score: 0 })); check('minimum: -10→15, 0→50, 1500→90, 3000→120', minimumMeld(-10) === 15 && minimumMeld(0) === 50 && minimumMeld(1500) === 90 && minimumMeld(3000) === 120);
return { players, teams, turnTeamMeldedAtStart: false }; check('minimum scales with a 2,500 target', minimumMeld(800, { target: 2500 }) === 90 && minimumMeld(1600, { target: 2500 }) === 120);
}
// ── 1. Card values ───────────────────────────────────────────────────────────── section('Meld legality');
console.log('Card values:'); check('three naturals', meldProblem('K', null, Cs('Ks0 Kh0 Kd0')) === null);
check('joker = 50', cardScore(C('JK', 'r')) === 50); check('two naturals + wild', meldProblem('K', null, Cs('Ks0 Kh0 2c0')) === null);
check('two = 20', cardScore(C('2', 's')) === 20); check('one natural + two wilds is illegal', meldProblem('K', null, Cs('Ks0 2h0 JK0')) !== null);
check('ace = 20', cardScore(C('A', 'h')) === 20); check('two naturals + three wilds legal, four wilds illegal',
check('king = 10', cardScore(C('K', 'c')) === 10); meldProblem('K', null, Cs('Ks0 Kh0 2c0 2d0 JK0')) === null && meldProblem('K', null, Cs('Ks0 Kh0 2c0 2d0 JK0 JK1')) !== null);
check('eight = 10', cardScore(C('8', 'd')) === 10); check('wilds onto an existing meld respect the cap',
check('seven = 5', cardScore(C('7', 's')) === 5); meldProblem('K', { rank: 'K', cards: Cs('Ks0 Kh0 2c0 2d0') }, Cs('JK0')) === null
check('four = 5', cardScore(C('4', 'c')) === 5); && 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 ───────────────────────────────────── section('First-meld solver vs brute force');
console.log('Scoring fixtures:');
{ {
const s = mkState(); // brute force: every subset → partition by rank into legal melds; maximise value
s.teams[0].hasMelded = true; const brute = (hand, need, keep) => {
// Natural canasta of seven kings: 70 cards + 500 bonus = 570. let best = null;
s.teams[0].melds = [{ rank: 'K', cards: ['K','K','K','K','K','K','K'].map((r) => C(r, 's')) }]; const n = hand.length;
const d = scoreTeamHand(s, 0, { outPlayer: null }); for (let mask = 1; mask < (1 << n); mask++) {
check('natural canasta cards = 70', d.meldPoints === 70, `got ${d.meldPoints}`); const used = hand.filter((_, i) => mask & (1 << i));
check('natural canasta bonus = 500', d.canastaBonus === NATURAL_CANASTA, `got ${d.canastaBonus}`); if (n - used.length < keep) continue;
check('one natural canasta counted', d.naturalCanastas === 1); const wild = used.filter(isWild);
} const nat = used.filter((c) => !isWild(c));
{ if (nat.some((c) => !isMeldable(c))) continue;
const s = mkState(); const ranks = [...new Set(nat.map((c) => c.rank))];
s.teams[0].hasMelded = true; if (!ranks.length) continue;
// Mixed canasta: five sixes + two wilds. // distribute wilds: each rank gets 0..3, total = wild.length
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 per = ranks.map((r) => nat.filter((c) => c.rank === r).length);
const d = scoreTeamHand(s, 0, { outPlayer: null }); if (per.some((k) => k < 2)) continue;
check('mixed canasta bonus = 300', d.canastaBonus === MIXED_CANASTA, `got ${d.canastaBonus}`); let ok = false;
check('mixed canasta counted', d.mixedCanastas === 1 && d.naturalCanastas === 0); const dist = (i, rem) => {
} if (ok) return;
{ if (i === ranks.length) { if (rem === 0) ok = true; return; }
const s = mkState(); for (let w = 0; w <= Math.min(MAX_WILDS, rem); w++) {
s.teams[1].hasMelded = true; if (per[i] + w < 3) continue;
s.teams[1].redThrees = [C('3','h'), C('3','d'), C('3','h'), C('3','d')]; dist(i + 1, rem - w);
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; };
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;
}
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);
} }
let wins = [0, 0], exceptions = 0, maxHands = 0, malformed = 0, badHandSize = 0; // ── 2. Engine fixtures ───────────────────────────────────────────────────────
let meldedGames = 0, draws = 0; section('Deal & upcard');
for (let g = 1; g <= games; g++) { {
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 { try {
let s = createInitialState({ seed: g * 2654435761 }); const end = playMatch(1000 + i, skills, rules, {
let turns = 0, hands = 0, sawMeld = false; onState: (gs) => {
while (s.phase !== 'gameOver') { if (L.cardCount(gs) !== 108) badCards++;
if (s.phase === 'handOver') { for (const t of gs.teams) for (const m of t.melds) {
if (++hands > 400) throw new Error('match did not terminate'); if (m.rank === '3') { if (m.cards.length < 3 || m.cards.some((c) => c.rank !== '3')) badMeld++; continue; }
s = startNextHand(s); 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++;
continue;
} }
if (++turns > 100000) throw new Error('turn loop did not terminate'); if (gs.phase === 'ask') asks++;
const before = s.currentPlayer; if (gs.phase === 'draw' && Math.random() < 0.02) {
s = aiTurn(s); saves++;
// Validate any melds present. const back = JSON.parse(JSON.stringify(gs));
for (const t of s.teams) for (const m of t.melds) { if (JSON.stringify(back) !== JSON.stringify(gs)) saveBad++;
if (m.cards.length >= 3 && !meldWellFormed(m)) malformed++;
if (t.melds.length) sawMeld = true;
} }
// Hand sizes never negative / absurd. if (gs.phase === 'handOver' || gs.phase === 'gameOver') {
for (const p of s.players) if (p.hand.length < 0 || p.hand.length > 40) badHandSize++; hands++;
if (s.currentPlayer === before && s.phase === 'draw') throw new Error('turn failed to advance'); if (gs.result.reason === 'stock') stockEnds++; else outs++;
if (gs.result.concealed) concealed++;
} }
if (sawMeld) meldedGames++; },
maxHands = Math.max(maxHands, hands); });
if (s.winnerTeam === null) draws++; wins[end.winner]++;
else wins[s.winnerTeam]++; maxHands = Math.max(maxHands, end.handNo);
canastas += end.stats.reduce((s, x) => s + x.canastas, 0);
} catch (e) { } catch (e) {
exceptions++; errors++;
if (exceptions <= 5) console.error(` game ${g}: ${e.message}`); 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}`);
} }
check('no exceptions during self-play', exceptions === 0, `${exceptions} games threw`); section('Coach');
check('all melds well-formed', malformed === 0, `${malformed} malformed`); {
check('hand sizes stay sane', badHandSize === 0, `${badHandSize} bad`); let ok = true, why = '';
check('teams meld in most games', meldedGames >= games * 0.9, `${meldedGames}/${games}`); for (let seed = 1; seed <= 40 && ok; seed++) {
check('both teams win some games', wins[0] > 0 && wins[1] > 0, `wins ${wins[0]}/${wins[1]}, draws ${draws}`); let gs = L.createGame({ seed });
console.log(` results: team0 ${wins[0]} / team1 ${wins[1]} / draws ${draws}, longest match ${maxHands} hands`); 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.'); console.log(failures ? `\n${failures} check(s) FAILED` : '\nAll checks passed.');
process.exit(failures ? 1 : 0); process.exit(failures ? 1 : 0);