// Headless verification for Canasta ("Rosa's Parlor"). // node tools/verifyCanasta.js [--games=N] [--ladder=N] [--quick] // Exits non-zero on any failure. // // 1. Data: card values, the first-meld minimum, meld legality, and the exact // first-meld solver against a brute-force search. // 2. Engine fixtures: one per rules fix (black-three blocks without freezing, // the upcard, atomic first-meld pile takes, no going out without a // canasta, the exhausted stock, concealed going out, black-three melds, // ties past the target) plus every house rule and scoring. // 3. AI: legality over full self-play matches (card conservation, well-formed // melds, terminating matches), save/load round trips, and the skill ladder. // 4. Layout (when CanastaTable.js exists): no overlaps at maximum counts. import { DEFAULT_RULES, cardFromId, cardScore, minimumMeld, meldProblem, solveInitialMeld, valueOf, isWild, isMeldable, isCanasta, wildsIn, naturalsIn, TEAM_OF_SEAT, CANASTA_SIZE, MAX_WILDS, } from '../src/games/canasta/CanastaData.js'; import * as L from '../src/games/canasta/CanastaLogic.js'; import { chooseDraw, chooseMelds, chooseDiscard, chooseAnswer, coachDraw, coachMelds, coachDiscard, } from '../src/games/canasta/CanastaAI.js'; const args = Object.fromEntries(process.argv.slice(2).map((a) => a.replace(/^--/, '').split('=')).map(([k, v]) => [k, v ?? true])); const QUICK = !!args.quick; const GAMES = Number(args.games ?? (QUICK ? 30 : 200)); const LADDER = Number(args.ladder ?? (QUICK ? 10 : 40)); let failures = 0; function check(name, cond, detail = '') { if (cond) { console.log(` ok ${name}`); return; } failures++; console.error(` FAIL ${name}${detail ? ` — ${detail}` : ''}`); } const section = (t) => console.log(`\n${t}`); const C = (id) => { const c = cardFromId(id); if (!c) throw new Error(`bad card ${id}`); return { ...c }; }; const Cs = (s) => s.split(/\s+/).filter(Boolean).map(C); const ids = (cards) => cards.map((c) => c.id); const clone = (o) => JSON.parse(JSON.stringify(o)); /** A blank state in the draw phase for seat 0 with the given hands / pile. */ function fixture({ hands = {}, discard = 'Kd0', stock = null, teams = null, rules = {}, frozen = false, scores = [0, 0], current = 0, phase = 'draw' } = {}) { const gs = L.createGame({ seed: 7, rules, dealer: 3 }); gs.hands = [0, 1, 2, 3].map((s) => (hands[s] != null ? Cs(hands[s]) : Cs('4s0 5s0 6s0'))); gs.discard = Cs(discard); gs.stock = stock != null ? Cs(stock) : Cs('9c1 9d1 8c1 8d1 7c1 7d1 6c1 6d1'); gs.teams = teams ?? [0, 1].map(() => ({ melds: [], redThrees: [], melded: false })); for (const t of gs.teams) t.melds = t.melds.map((m) => (typeof m.cards === 'string' ? { rank: m.rank, cards: Cs(m.cards) } : m)); gs.frozen = frozen; gs.scores = scores; gs.current = current; gs.phase = phase; gs.turn = { startMelded: gs.teams[TEAM_OF_SEAT[current]].melded, tookPile: false, asked: null, drew: null }; gs.pickups = [[], [], [], []]; gs.discards = [[], [], [], []]; return gs; } const melded = (melds = []) => ({ melds, redThrees: [], melded: true }); const unmelded = () => ({ melds: [], redThrees: [], melded: false }); // ── 1. Data ────────────────────────────────────────────────────────────────── section('Card values & minimum'); check('joker 50, two 20, ace 20', cardScore(C('JK0')) === 50 && cardScore(C('2s0')) === 20 && cardScore(C('Ah0')) === 20); check('K..8 are 10, 7..4 are 5, black three 5', cardScore(C('Ks0')) === 10 && cardScore(C('8d0')) === 10 && cardScore(C('7c0')) === 5 && cardScore(C('4h0')) === 5 && cardScore(C('3s0')) === 5); check('minimum: -10→15, 0→50, 1500→90, 3000→120', minimumMeld(-10) === 15 && minimumMeld(0) === 50 && minimumMeld(1500) === 90 && minimumMeld(3000) === 120); check('minimum scales with a 2,500 target', minimumMeld(800, { target: 2500 }) === 90 && minimumMeld(1600, { target: 2500 }) === 120); section('Meld legality'); check('three naturals', meldProblem('K', null, Cs('Ks0 Kh0 Kd0')) === null); check('two naturals + wild', meldProblem('K', null, Cs('Ks0 Kh0 2c0')) === null); check('one natural + two wilds is illegal', meldProblem('K', null, Cs('Ks0 2h0 JK0')) !== null); check('two naturals + three wilds legal, four wilds illegal', meldProblem('K', null, Cs('Ks0 Kh0 2c0 2d0 JK0')) === null && meldProblem('K', null, Cs('Ks0 Kh0 2c0 2d0 JK0 JK1')) !== null); check('wilds onto an existing meld respect the cap', meldProblem('K', { rank: 'K', cards: Cs('Ks0 Kh0 2c0 2d0') }, Cs('JK0')) === null && meldProblem('K', { rank: 'K', cards: Cs('Ks0 Kh0 2c0 2d0 JK0') }, Cs('JK1')) !== null); check('red three never melds', meldProblem('3', null, Cs('3h0 3d0 3h1')) !== null); check('black threes: 3+ only, no wilds', meldProblem('3', null, Cs('3s0 3c0 3s1')) === null && meldProblem('3', null, Cs('3s0 3c0 2s1')) !== null); section('First-meld solver vs brute force'); { // brute force: every subset → partition by rank into legal melds; maximise value const brute = (hand, need, keep) => { let best = null; const n = hand.length; for (let mask = 1; mask < (1 << n); mask++) { const used = hand.filter((_, i) => mask & (1 << i)); if (n - used.length < keep) continue; const wild = used.filter(isWild); const nat = used.filter((c) => !isWild(c)); if (nat.some((c) => !isMeldable(c))) continue; const ranks = [...new Set(nat.map((c) => c.rank))]; if (!ranks.length) continue; // distribute wilds: each rank gets 0..3, total = wild.length const per = ranks.map((r) => nat.filter((c) => c.rank === r).length); if (per.some((k) => k < 2)) continue; let ok = false; const dist = (i, rem) => { if (ok) return; if (i === ranks.length) { if (rem === 0) ok = true; return; } for (let w = 0; w <= Math.min(MAX_WILDS, rem); w++) { if (per[i] + w < 3) continue; dist(i + 1, rem - w); } }; dist(0, wild.length); if (!ok) continue; const v = valueOf(used); if (v < need) continue; const key = [wild.length, used.length]; if (!best || key[0] < best[0] || (key[0] === best[0] && key[1] < best[1])) best = key; } 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); } // ── 2. Engine fixtures ─────────────────────────────────────────────────────── section('Deal & upcard'); { let redUp = 0, wildUp = 0, okConserve = true, okHands = true, okFrozenUp = true; for (let seed = 1; seed <= 400; seed++) { const gs = L.createGame({ seed }); if (L.cardCount(gs) !== 108) okConserve = false; if (gs.hands.some((h) => h.length !== 11 || h.some((c) => c.rank === '3' && (c.suit === 'h' || c.suit === 'd')))) okHands = false; const top = L.topDiscard(gs); if (isWild(top) || (top.rank === '3' && 'hd'.includes(top.suit))) okFrozenUp = false; const covered = gs.discard.length > 1; if (covered !== gs.frozen) okFrozenUp = false; if (gs.discard.some((c) => c.rank === '3' && 'hd'.includes(c.suit))) redUp++; if (gs.discard.slice(0, -1).some(isWild)) wildUp++; } check('108 cards accounted for after every deal', okConserve); check('11 cards each, dealt red threes laid out and replaced', okHands); check('a wild / red-three upcard is covered and freezes the pile (only then)', okFrozenUp, `${redUp} red, ${wildUp} wild`); check('red-three and wild upcards actually occur in 400 deals', redUp > 0 && wildUp > 0); const g = L.createGame({ seed: 99 }); check('cut for deal recorded', Array.isArray(g.cut) && g.cut.length === 4 && g.dealer >= 0 && g.dealer < 4); } section('Bug fix 1: black three blocks but does not freeze'); { let gs = fixture({ hands: { 0: '3s0 Kh0 Qh0 Qs0', 1: 'Kc0 Ks1 5d0 6d0' }, discard: 'Kd0', phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), melded([{ rank: 'J', cards: 'Js0 Jh0 Jd0' }])] }); gs = L.discardCard(gs, '3s0'); check('black three discard leaves the pile unfrozen', gs.frozen === false && gs.current === 1); check('the next player cannot take a pile topped by a black three', L.takeProblem(gs, 1, { ids: [] }) !== null && L.takeOption(gs, 1).plan === null); gs = L.drawStock(gs); gs = L.discardCard(gs, '5d0'); check('once covered, the pile is takeable with one natural + wild rules intact', L.frozenFor(gs, 2) === false); } section('Bug fix 3: first meld via the pile is atomic and must reach the minimum'); { // Unmelded: Q pair + Q top = 30 — not enough alone; with 9-9-9 (30) = 60 ≥ 50. let gs = fixture({ hands: { 0: 'Qs0 Qh0 9s0 9h0 9d0 4c0 5d0' }, discard: '7c1 Qd1' }); const opt = L.takeOption(gs, 0); check('take plan includes the nines to reach 50', opt.plan && opt.plan.extra.length === 1 && opt.plan.extra[0].rank === '9'); check('taking with the pair alone is refused (30 < 50)', L.takeProblem(gs, 0, { ids: ['Qs0', 'Qh0'] }) !== null); const next = L.takePile(gs, opt.plan); check('take applied: side melded, pile rest in hand', next !== gs && next.teams[0].melded && next.hands[0].some((c) => c.id === '7c1') && next.discard.length === 0); check('player can discard straight away (no stuck turn)', next.phase === 'play' && L.discardProblem(next, next.hands[0][0].id) === null); // pile cards can't count toward the minimum gs = fixture({ hands: { 0: 'Qs0 Qh0 4c0 5d0' }, discard: 'Ks0 Kh0 Kc0 Qd1' }); check('pile cards never count toward the minimum', L.takeOption(gs, 0).plan === null); } section('Bug fix 4: no going out without a canasta'); { const gs = fixture({ hands: { 0: 'Ks0 Kh0 Kd0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), unmelded()] }); check('melding down to 0 cards without a canasta is refused', L.checkMelds(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); const g2 = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), unmelded()] }); check('melding down to 1 card without a canasta is refused', L.checkMelds(g2, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); const g3 = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0 6c0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), unmelded()] }); check('keeping two cards is fine', L.checkMelds(g3, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem === null); const g4 = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), unmelded()] }); let out = L.meldCards(g4, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]); check('with a canasta you may meld down to one card…', out !== g4 && out.hands[0].length === 1); out = L.discardCard(out, '5c0'); check('…and go out on the discard (+100)', out.phase === 'handOver' && out.result.outSeat === 0 && out.result.detail[0].goOut === 100); } section('Bug fix 5: exhausted stock'); { let gs = fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: '9d0', stock: '', teams: [melded([{ rank: '9', cards: '9s0 9h0 9c0' }]), unmelded()] }); check('drawing from an empty stock is impossible', L.drawStock(gs) === gs); check('top card fits our meld → must take (pass refused)', L.mustTake(gs) && L.passStock(gs) === gs); const t = L.takePile(gs); check('forced take works', t !== gs && t.phase === 'play'); gs = fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: '8d0', stock: '', teams: [melded([{ rank: '9', cards: '9s0 9h0 9c0' }]), unmelded()] }); const p = L.passStock(gs); check('nothing to take → the hand ends with no go-out bonus', p.phase === 'handOver' && p.result.reason === 'stock' && p.result.detail.every((d) => d.goOut === 0)); gs = fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: '8d0', stock: '3h1', teams: [melded([{ rank: '9', cards: '9s0 9h0 9c0' }]), unmelded()] }); const r = L.drawStock(gs); check('a red three as the last stock card ends the hand at once', r.phase === 'handOver' && r.teams[0].redThrees.length === 1); } section('Bug fix 6: concealed going out'); { const gs = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 Kc0 Ks1 Kh1 Kd1 4c0 4d0 4h0 5c0' }, phase: 'play', teams: [unmelded(), unmelded()] }); const chk = L.checkMelds(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0', 'Kc0', 'Ks1', 'Kh1', 'Kd1'] }, { rank: '4', ids: ['4c0', '4d0', '4h0'] }]); check('whole hand bar one: legal concealed meld', chk.problem === null && chk.goingOut); let out = L.meldCards(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0', 'Kc0', 'Ks1', 'Kh1', 'Kd1'] }, { rank: '4', ids: ['4c0', '4d0', '4h0'] }]); out = L.discardCard(out, '5c0'); check('concealed go-out scores 200', out.result?.concealed === true && out.result.detail[0].goOut === 200); // concealed waives the minimum const lowMin = fixture({ hands: { 0: '4s0 4h0 4d0 4c0 4s1 4h1 4d1 5c0' }, phase: 'play', scores: [3500, 0], teams: [unmelded(), unmelded()] }); check('concealed go-out ignores the 120 minimum', L.checkMelds(lowMin, [{ rank: '4', ids: ['4s0', '4h0', '4d0', '4c0', '4s1', '4h1', '4d1'] }]).problem === null); check('…but the same cards without going out would need 120', L.checkMelds(lowMin, [{ rank: '4', ids: ['4s0', '4h0', '4d0'] }]).problem !== null); } section('Bug fix 7: black threes meld only when going out'); { const base = { teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), unmelded()], phase: 'play' }; const gs = fixture({ ...base, hands: { 0: '3s0 3c0 3s1 Kh0 Kd0' } }); check('black threes mid-hand are refused', L.checkMelds(gs, [{ rank: '3', ids: ['3s0', '3c0', '3s1'] }]).problem !== null); const g2 = fixture({ ...base, hands: { 0: '3s0 3c0 3s1 Kh0' } }); check('black threes when going out are fine', L.checkMelds(g2, [{ rank: '3', ids: ['3s0', '3c0', '3s1'] }]).problem === null); } section('Bug fix 8: a tie past the target plays on'); { let gs = fixture({ hands: { 0: '5c0', 1: '6c0', 2: '6d0', 3: '6h0' }, phase: 'play', scores: [4900, 5000 - 70], teams: [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), melded([{ rank: 'K', cards: 'Ks0 Kh0 Kd0' }])] }); // team0: 140 + 300 + 100 out - 6 (partner) = 534 → 5434 ; set team1 so the totals tie const d0 = L.scoreTeam({ ...gs, hands: [[], ...gs.hands.slice(1)] }, 0, 0); const d1 = L.scoreTeam(gs, 1, 0); gs.scores = [5000, 5000 + d0.total - d1.total]; const out = L.discardCard(gs, '5c0'); check('tied scores past the target → another hand', out.phase === 'handOver' && out.scores[0] === out.scores[1], `${out.scores}`); } section('Pile taking rules'); { const t = () => [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0' }]), melded([{ rank: 'J', cards: 'Js0 Jh0 Jd0' }])]; check('two naturals take an unfrozen pile', L.takeOption(fixture({ hands: { 0: 'Ks0 Kh0 5c0 6c0' }, discard: 'Kd0', teams: t() }), 0).plan !== null); check('one natural + wild takes an unfrozen pile', L.takeOption(fixture({ hands: { 0: 'Ks0 2h0 5c0 6c0' }, discard: 'Kd0', teams: t() }), 0).plan !== null); check('frozen pile refuses natural + wild', L.takeOption(fixture({ hands: { 0: 'Ks0 2h0 5c0' }, discard: '2d0 Kd0', teams: t(), frozen: true }), 0).plan === null); check('frozen pile accepts a natural pair', L.takeOption(fixture({ hands: { 0: 'Ks0 Kh0 5c0' }, discard: '2d0 Kd0', teams: t(), frozen: true }), 0).plan !== null); check('a take leaving a single card (no canasta) is refused', L.takeOption(fixture({ hands: { 0: 'Ks0 Kh0 5c0' }, discard: 'Kd0', teams: t() }), 0).plan === null); check('top card onto our meld (unfrozen)', L.takeOption(fixture({ hands: { 0: '5c0 6c0' }, discard: 'Ac1', teams: t() }), 0).plan?.ids.length === 0); check('wild on top cannot be taken', L.takeOption(fixture({ hands: { 0: '5c0 6c0' }, discard: 'Ac1 2c0', teams: t(), frozen: true }), 0).plan === null); check('discarding a wild freezes', L.discardCard(fixture({ hands: { 0: '2c0 5c0 6c0' }, teams: t(), phase: 'play' }), '2c0').frozen === true); check('alwaysFrozen rule needs a pair even with a meld', L.takeOption(fixture({ hands: { 0: '5c0 6c0' }, discard: 'Ac1', teams: t(), rules: { alwaysFrozen: true } }), 0).plan === null); const big = fixture({ hands: { 0: 'Ks0 Kh0 5c0' }, discard: '4c0 4d0 3h0 9c0 Kd0', teams: t() }); const tk = L.takePile(big); check('a red three in the pile is laid out, not held', tk.teams[0].redThrees.some((c) => c.id === '3h0') && !tk.hands[0].some((c) => c.id === '3h0')); } section('House rules'); { const one = [melded([{ rank: 'A', cards: 'As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1' }]), unmelded()]; const gs = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: clone(one), rules: { goOutCanastas: 2 } }); check('two-canasta rule: one canasta is not enough to go out', L.checkMelds(gs, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); let a = fixture({ hands: { 0: 'Ks0 Kh0 Kd0 5c0' }, phase: 'play', teams: clone(one), rules: { askPartner: true } }); check('askPartner: going out without asking is refused', L.checkMelds(a, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null); a = L.askGoOut(a); check('askGoOut → partner (seat 2) to answer', a.phase === 'ask' && L.actor(a) === 2); const no = L.answerGoOut(a, false); check('a "no" binds for the turn', no.phase === 'play' && L.checkMelds(no, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem !== null && L.askGoOut(no) === no); const yes = L.answerGoOut(a, true); check('a "yes" lets you go out', L.checkMelds(yes, [{ rank: 'K', ids: ['Ks0', 'Kh0', 'Kd0'] }]).problem === null); const g = L.createGame({ seed: 4, rules: { target: 2500 } }); check('target is stored with the rules', g.rules.target === 2500 && L.minimumFor({ ...g, scores: [1300, 0] }, 0) === 90); } section('Scoring'); { const gs = fixture({ hands: { 0: '', 1: 'Ks1 JK3', 2: '5c0', 3: '' } }); gs.teams = [ { melds: [{ rank: 'A', cards: Cs('As0 Ah0 Ad0 Ac0 As1 Ah1 Ad1') }, { rank: 'K', cards: Cs('Ks0 Kh0 2c0 Kd0 Kc0 Kh1 Kd1') }], redThrees: Cs('3h0 3d0 3h1 3d1'), melded: true }, { melds: [], redThrees: Cs(''), melded: false }, ]; const d = L.scoreTeam(gs, 0, 0, false); check('natural 500 + mixed 300', d.natural === 1 && d.mixed === 1 && d.canastaBonus === 800); check('all four red threes = 800', d.redThreeBonus === 800); check('meld points and in-hand penalty', d.meldPoints === 140 + 80 && d.inHand === 5 && d.total === 220 + 800 + 800 + 100 - 5); gs.teams[1].redThrees = Cs('3h0'); const d1 = L.scoreTeam(gs, 1, 0, false); check('an unmelded side loses its red threes and its hand', d1.redThreeBonus === -100 && d1.inHand === 60 && d1.total === -160); } // ── 3. AI self-play ────────────────────────────────────────────────────────── function seeded(seed) { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** Play one full turn (or answer) for whoever is to act. Throws on any illegal move. */ function step(gs, skills, rnd) { const seat = L.actor(gs); const sk = skills[seat]; if (gs.phase === 'ask') { const n = L.answerGoOut(gs, chooseAnswer(gs, sk)); if (n === gs) throw new Error('answer refused'); return n; } if (gs.phase === 'draw') { const d = chooseDraw(gs, seat, sk, rnd); const n = d.type === 'take' ? L.takePile(gs, d.plan) : d.type === 'pass' ? L.passStock(gs) : L.drawStock(gs); if (n === gs) throw new Error(`draw refused: ${JSON.stringify(d)} ${L.takeProblem(gs, seat, d.plan ?? { ids: [] })}`); return n; } if (gs.phase === 'play') { let g = gs; for (let guard = 0; guard < 30 && g.phase === 'play'; guard++) { const m = chooseMelds(g, seat, sk); if (!m) break; if (m.ask) { const a = L.askGoOut(g); if (a === g) throw new Error('ask refused'); return a; } const n = L.meldCards(g, m.groups); if (n === g) throw new Error(`meld refused: ${JSON.stringify(m.groups)} — ${L.checkMelds(g, m.groups).problem}`); g = n; } if (g.phase !== 'play') return g; const id = chooseDiscard(g, seat, sk, rnd); const n = L.discardCard(g, id); if (n === g) throw new Error(`discard refused: ${id} — ${L.discardProblem(g, id)}`); return n; } throw new Error(`unexpected phase ${gs.phase}`); } function playMatch(seed, skills, rules = {}, { onState = null } = {}) { const rnd = seeded(seed * 7 + 1); let gs = L.createGame({ seed, rules }); let steps = 0; while (gs.phase !== 'gameOver') { if (gs.phase === 'handOver') { gs = L.nextHand(gs); continue; } gs = step(gs, skills, rnd); onState?.(gs); if (++steps > 40000) throw new Error('match did not terminate'); } return gs; } section(`AI self-play (${GAMES} matches, house rules mixed in)`); { let errors = 0, firstErr = '', badCards = 0, badMeld = 0, wins = [0, 0], hands = 0, outs = 0, concealed = 0, stockEnds = 0; let maxHands = 0, canastas = 0, saves = 0, saveBad = 0, asks = 0; const ruleSets = [{}, { goOutCanastas: 2 }, { askPartner: true }, { alwaysFrozen: true }, { target: 2500 }]; for (let i = 0; i < GAMES; i++) { const rules = ruleSets[i % ruleSets.length]; const skills = [1 + (i % 5), 1 + ((i + 2) % 5), 1 + ((i + 1) % 5), 1 + ((i + 3) % 5)]; try { const end = playMatch(1000 + i, skills, rules, { onState: (gs) => { if (L.cardCount(gs) !== 108) badCards++; for (const t of gs.teams) for (const m of t.melds) { if (m.rank === '3') { if (m.cards.length < 3 || m.cards.some((c) => c.rank !== '3')) badMeld++; continue; } if (naturalsIn(m.cards) < 2 || wildsIn(m.cards) > MAX_WILDS || m.cards.length < 3 || m.cards.some((c) => !isWild(c) && c.rank !== m.rank)) badMeld++; } if (gs.phase === 'ask') asks++; if (gs.phase === 'draw' && Math.random() < 0.02) { saves++; const back = JSON.parse(JSON.stringify(gs)); if (JSON.stringify(back) !== JSON.stringify(gs)) saveBad++; } if (gs.phase === 'handOver' || gs.phase === 'gameOver') { hands++; if (gs.result.reason === 'stock') stockEnds++; else outs++; if (gs.result.concealed) concealed++; } }, }); wins[end.winner]++; maxHands = Math.max(maxHands, end.handNo); canastas += end.stats.reduce((s, x) => s + x.canastas, 0); } catch (e) { errors++; if (!firstErr) firstErr = `match ${i}: ${e.message}`; } } check('no illegal AI moves or exceptions', errors === 0, firstErr); check('108 cards conserved at every step', badCards === 0, `${badCards}`); check('every meld on the table is well-formed', badMeld === 0, `${badMeld}`); check('both sides win matches', wins[0] > 0 && wins[1] > 0, `${wins}`); check('hands mostly end by going out', outs > stockEnds * 3, `out ${outs} / stock ${stockEnds}`); check('askPartner rule exercised', asks > 0, `${asks}`); check('state survives a JSON round trip', saveBad === 0 && saves > 0, `${saves} sampled`); console.log(` ${hands} hands, ${canastas} canastas, ${concealed} concealed go-outs, longest match ${maxHands} hands, wins ${wins}`); } section('Coach'); { let ok = true, why = ''; for (let seed = 1; seed <= 40 && ok; seed++) { let gs = L.createGame({ seed }); const rnd = seeded(seed); for (let k = 0; k < 120 && gs.phase !== 'gameOver'; k++) { if (gs.phase === 'handOver') { gs = L.nextHand(gs); continue; } if (gs.current === 0 && gs.phase === 'draw') { const c = coachDraw(gs, 0); if (!c?.text) { ok = false; why = 'coachDraw no text'; } if (c.type === 'take' && L.takeProblem(gs, 0, c.plan)) { ok = false; why = 'coach suggested illegal take'; } } if (gs.current === 0 && gs.phase === 'play') { const m = coachMelds(gs, 0); if (m?.groups && L.checkMelds(gs, m.groups).problem) { ok = false; why = `coach meld illegal: ${L.checkMelds(gs, m.groups).problem}`; } const d = coachDiscard(gs, 0); if (!d?.text || L.discardProblem(gs, d.id)) { ok = false; why = 'coach discard illegal'; } } gs = step(gs, [5, 3, 3, 3], rnd); } } check('coach suggestions are always legal and explained', ok, why); } section(`Skill ladder (${LADDER} paired matches, skill 5 vs skill 1)`); { let strong = 0, total = 0, pts = 0; for (let i = 0; i < LADDER; i++) { for (const flip of [false, true]) { const skills = flip ? [1, 5, 1, 5] : [5, 1, 5, 1]; const strongTeam = flip ? 1 : 0; try { const end = playMatch(5000 + i, skills, { target: 2500 }); total++; if (end.winner === strongTeam) strong++; pts += end.scores[strongTeam] - end.scores[1 - strongTeam]; } catch (e) { check('ladder match runs', false, e.message); } } } check('skill 5 beats skill 1 most of the time', strong / total >= 0.65, `${strong}/${total}, avg margin ${Math.round(pts / Math.max(1, total))}`); console.log(` skill 5 won ${strong}/${total} (avg margin ${Math.round(pts / Math.max(1, total))})`); } // ── 4. Layout ──────────────────────────────────────────────────────────────── section('Layout'); try { const T = await import('../src/games/canasta/CanastaTable.js'); if (typeof T.verifyLayout === 'function') { const problems = T.verifyLayout(); check('no overlaps at maximum counts', problems.length === 0, problems.slice(0, 5).join('; ')); } else console.log(' (no verifyLayout export yet)'); } catch (e) { if (e.code === 'ERR_MODULE_NOT_FOUND') console.log(' (CanastaTable.js not present yet)'); else check('layout module loads', false, e.message); } console.log(failures ? `\n${failures} check(s) FAILED` : '\nAll checks passed.'); process.exit(failures ? 1 : 0);