#!/usr/bin/env node // verifyGinRummy.js — headless checks for Gin Rummy ("The Juniper Still"): // cards + meld solver (exact, vs brute force), lay-off search, the rules // engine (upcard offer, no throw-back, wash at 2 cards / one reshuffle at // 3–4p, knock/gin/Big Gin, undercut, Oklahoma, bonuses, save validity), // regressions from the old build (AI missed gins on 11 cards, knocked on 0), // the AI (always legal, optimal lay-offs, skill ladder), the table layout // and an all-AI soak (every match ends, 52 cards conserved). // Usage: node tools/verifyGinRummy.js [--quick] import { makeCard, cardFromId, fullDeck, bestMelds, meldSolver, deadwoodValue, discardOptions, bestDiscard, canLayoff, bestDefense, isMeld, meldOrder, pairScore, DEFAULT_RULES, } from '../src/games/ginrummy/GinRummyData.js'; import * as G from '../src/games/ginrummy/GinRummyLogic.js'; import { chooseDraw, chooseAction, chooseLayoffs, coachDraw, coachAction, rankDiscards } from '../src/games/ginrummy/GinRummyAI.js'; import { mulberry32 } from '../src/ui/cardtable/AITiming.js'; import { W, H as SCREEN_H, CARD_W, CARD_H, cardBounds, inPose, fanBounds, rectsOverlap, onScreen, hudFurniture, plateRect, } from '../src/ui/cardtable/TableGeometry.js'; import { T, layoutFor, handPose, blockSlots, handBadge, handHome, rowPoses, blockRect, METER, ROW, } from '../src/games/ginrummy/GinRummyTable.js'; const QUICK = process.argv.includes('--quick'); let pass = 0, fail = 0; function ok(label, cond, detail = '') { if (cond) pass++; else { console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); fail++; } } const section = (n) => console.log(`\n${n}`); const H = (s) => s.split(' ').filter(Boolean).map(cardFromId); const ids = (cards) => cards.map(c => c.id).sort().join(' '); // ── Cards ──────────────────────────────────────────────────────────────────── section('Cards'); ok('52 unique cards', new Set(fullDeck().map(c => c.id)).size === 52); ok('A = 1 point', makeCard('A', 's').pts === 1); ok('9 = 9 points', makeCard('9', 'h').pts === 9); ok('T J Q K = 10 points', ['T', 'J', 'Q', 'K'].every(r => makeCard(r, 'c').pts === 10)); ok('ace is low in runs', isMeld(H('As 2s 3s')) && !isMeld(H('Qs Ks As'))); ok('set needs different suits', isMeld(H('7s 7h 7d')) && !isMeld(H('7s 7s 7d'))); // ── Meld solver ────────────────────────────────────────────────────────────── section('Meld solver'); // Independent brute force: try every way to split the hand into disjoint melds. function brute(hand) { const n = hand.length; let best = Infinity; const rec = (used, meldedPts) => { let i = 0; while (i < n && (used & (1 << i))) i++; if (i >= n) { best = Math.min(best, hand.reduce((s, c) => s + c.pts, 0) - meldedPts); return; } rec(used | (1 << i), meldedPts); // card i stays loose const free = []; for (let k = i + 1; k < n; k++) if (!(used & (1 << k))) free.push(k); for (let mask = 0; mask < (1 << free.length); mask++) { const pick = [i]; for (let b = 0; b < free.length; b++) if (mask & (1 << b)) pick.push(free[b]); if (pick.length < 3 || !isMeld(pick.map(k => hand[k]))) continue; let u = used, pts = 0; for (const k of pick) { u |= 1 << k; pts += hand[k].pts; } rec(u, meldedPts + pts); } }; rec(0, 0); return best; } { const rng = mulberry32(42); let agree = true, bad = ''; for (let t = 0; t < (QUICK ? 150 : 600); t++) { const deck = fullDeck(); for (let i = deck.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [deck[i], deck[j]] = [deck[j], deck[i]]; } // bias toward meld-rich hands: half the time draw from two suits only const pool = t % 2 ? deck : deck.filter(c => c.suit === 's' || c.suit === 'h' || c.rank === '7'); const hand = pool.slice(0, 10 + (t % 2)); const a = deadwoodValue(hand), b = brute(hand); if (a !== b) { agree = false; bad = `${ids(hand)}: solver ${a}, brute ${b}`; break; } const bm = bestMelds(hand); if (!bm.melds.every(isMeld) || bm.deadwood !== a) { agree = false; bad = `melds wrong for ${ids(hand)}`; break; } } ok('solver matches brute force on random hands', agree, bad); } ok('gin hand: 0 deadwood', deadwoodValue(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd')) === 0); ok('overlap: 7♠ used once', deadwoodValue(H('5s 6s 7s 7h 7d')) === 5 + 6 || deadwoodValue(H('5s 6s 7s 7h 7d')) === 14); ok('overlap chooses the cheaper loose cards', deadwoodValue(H('5s 6s 7s 7h 7d')) === 11); ok('4-run + set sharing a card → split it', deadwoodValue(H('4h 5h 6h 7h 7s 7d')) === 0); { const opts = discardOptions(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd 9c')); ok('discard options: dropping the 9♣ leaves gin', opts.find(o => o.card.id === '9c').deadwood === 0); ok('best discard is the 9♣', bestDiscard(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd 9c')).card.id === '9c'); ok('best discard respects the banned card', bestDiscard(H('As 2s 3s 4s 7h 7d 7c Jd Qd Kd 9c'), '9c').card.id !== '9c'); } { const mo = meldOrder(H('Kd 2s 7h Jd 3s 7c As 9c Qd 7d')); ok('meld order: melds first, loose last', mo.loose.map(c => c.id).join() === '9c' && mo.order.length === 10 && mo.melds.length === 3); } // ── Lay-offs ───────────────────────────────────────────────────────────────── section('Lay-offs'); ok('extend a run low and high', canLayoff(cardFromId('4h'), H('5h 6h 7h')) && canLayoff(cardFromId('8h'), H('5h 6h 7h'))); ok('no gap in a run', !canLayoff(cardFromId('9h'), H('5h 6h 7h'))); ok('fourth card of a set', canLayoff(cardFromId('7c'), H('7s 7h 7d')) && !canLayoff(cardFromId('7c'), H('7s 7h 7d 7c'))); ok('no ace above king', !canLayoff(cardFromId('As'), H('Js Qs Ks'))); { const d = bestDefense(H('8h 9h Ks Qd 2c 3c 4c Jh 5d 6d'), [H('5h 6h 7h'), H('Js Jd Jc')]); ok('chain: 8♥ then 9♥ both laid off', ['8h', '9h'].every(id => d.layoffs.some(l => l.card.id === id)), JSON.stringify(d.layoffs.map(l => l.card.id))); ok('J♥ laid on the jacks', d.layoffs.some(l => l.card.id === 'Jh' && l.meldIdx === 1)); ok('own run 2-3-4♣ kept', d.melds.some(m => ids(m) === ids(H('2c 3c 4c')))); ok('defense deadwood', d.deadwood === 10 + 10 + 5 + 6, String(d.deadwood)); // laying the 7♣ off would break 7♣ 8♣ 9♣ — the search keeps the run const d2 = bestDefense(H('7c 8c 9c Kd'), [H('7s 7h 7d')]); ok('never lays off out of a better own meld', d2.deadwood === 10 && !d2.layoffs.length); } // ── Engine ─────────────────────────────────────────────────────────────────── section('Engine'); // A rigged 2p round: set hands / stock / discard directly. function rig({ hands, upcard = 'Kc', stock = null, n = 2, rules = {}, phase = 'draw', current = 0, takenFrom = null }) { let gs = G.createGame({ players: n, rules, seed: 7, dealer: n - 1 }); gs = structuredClone(gs); hands = hands.map(h => (typeof h === 'string' ? h.split(' ') : h)); const used = new Set([...hands.flat(), upcard]); gs.hands = hands.map(h => h.map(cardFromId)); gs.discard = [cardFromId(upcard)]; gs.stock = stock ? stock.map(cardFromId) : fullDeck().filter(c => !used.has(c.id)); gs.phase = phase; gs.current = current; gs.takenFrom = takenFrom; return gs; } { const gs = G.createGame({ players: 2, seed: 1 }); ok('deal: 10 cards each, 1 up, 31 in stock', gs.hands.every(h => h.length === 10) && gs.discard.length === 1 && gs.stock.length === 31); ok('deal: starts with the upcard offer to the non-dealer', gs.phase === 'upcard' && gs.current === (gs.dealer + 1) % 2); ok('52 cards in play', G.cardsInPlay(gs) === 52); const p1 = G.passUpcard(gs, gs.current); ok('pass moves the offer to the dealer', p1.phase === 'upcard' && p1.current === gs.dealer); const p2 = G.passUpcard(p1, p1.current); ok('both pass: first player must draw from the stock', p2.phase === 'draw' && p2.current === gs.first && p2.stockOnly); ok('…and may not take the upcard', G.drawDiscard(p2, p2.current) === p2); const t = G.takeUpcard(gs, gs.current); ok('take the upcard → discard phase', t.phase === 'discard' && t.hands[gs.current].length === 11 && t.takenFrom === gs.discard[0].id); ok('can\'t throw the upcard straight back', G.discard(t, gs.current, gs.discard[0].id) === t); ok('wrong seat can\'t act', G.takeUpcard(gs, gs.dealer) === gs); const s3 = G.createGame({ players: 3, seed: 2 }); ok('3p: 21 in stock', s3.stock.length === 21); const s4 = G.createGame({ players: 4, seed: 3 }); ok('4p: 11 in stock', s4.stock.length === 11); const nu = G.createGame({ players: 2, seed: 4, rules: { upcard: false } }); ok('upcard rule off: straight to draw', nu.phase === 'draw' && !nu.stockOnly); } { const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd 5c', '2h 3h 9s 9d Ts Th 5h 6d 8c Kh'], upcard: 'Kd' }); const d = G.drawDiscard(gs, 0); ok('take the discard', d.hands[0].length === 11 && d.takenFrom === 'Kd' && d.pickups[0].includes('Kd')); ok('no throw-back of the taken card', G.discard(d, 0, 'Kd') === d); ok('no knocking with the taken card either', G.knock(d, 0, 'Kd') === d); const g = G.knock(d, 0, '5c'); ok('knock on 0 is gin automatically', g.phase === 'roundOver' && g.result.kind === 'gin'); const opp = bestMelds(g.hands[1]).deadwood; ok('gin scores deadwood + 25', g.result.deltas[0] === opp + 25, `${g.result.deltas[0]} vs ${opp}+25`); ok('gin: no lay-offs happened', g.result.lines[0].laid.length === 0); ok('box counted', g.boxes[0] === 1 && g.stats[0].gins === 1); } { // knock with 5 (5♣ loose), defender lays off const gs = rig({ hands: ['2s 3s 4s 7h 7d 7c Jd Qd Kd 5c', '5s 8h 9s 9d Ts Td As 6d 8c Kh'], upcard: 'Qh', stock: ['Kc', '4h', '3d', '6h', '4d', '6c'] }); const d = G.drawStock(gs, 0); ok('draw stock', d.hands[0].length === 11 && d.takenFrom === null && d.stock.length === 5); ok('knock over the limit refused', G.knock(d, 0, '2s') === d); const k = G.knock(d, 0, 'Kc'); ok('knock with 5 → lay-off phase for the defender', k.phase === 'layoff' && k.showdown.layoffSeat === 1 && k.showdown.knockerDW === 5, k.phase); const mi = k.showdown.melds.findIndex(m => m.some(c => c.id === '4s')); const l = G.layoff(k, 1, '5s', mi); ok('lay 5♠ on 2-4♠', l !== k && l.showdown.melds[mi].length === 4 && !l.hands[1].some(c => c.id === '5s')); const l1 = G.layoff(l, 1, 'As', mi); ok('…and the A♠ below it', l1 !== l && l1.showdown.melds[mi][0].id === 'As'); ok('illegal lay-off refused', G.layoff(l1, 1, 'Kh', mi) === l1); ok('no card lost or doubled during lay-offs', G.cardsInPlay(l1) === G.cardsInPlay(k)); const kdIdx = l1.showdown.melds.findIndex(m => m.some(c => c.id === 'Jd')); const l2 = G.layoff(l1, 1, 'Td', kdIdx); ok('T♦ onto J-Q-K♦', l2 !== l1); const e = G.endLayoff(l2, 1); const dDW = bestMelds(e.hands[1]).deadwood; ok('scored after the last defender', e.phase === 'roundOver' && e.result.lines[0].deadwood === dDW); ok('knock win = difference', e.result.deltas[0] === dDW - 5, `${e.result.deltas[0]} vs ${dDW}-5`); ok('lay-offs recorded', e.result.lines[0].laid.length === 3); } { // undercut: knocker 1 (A♥), defender 1 (A♣) → tie is an undercut const gs = rig({ hands: ['2s 3s 4s 7h 7d 7c Jd Qd Kd 9c', '4c 5c 6c 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Ah', '5h', '9h', 'Qc', 'Jc', 'Th'] }); const k = G.knock(G.drawStock(gs, 0), 0, '9c'); ok('knocking with 1', k.showdown?.knockerDW === 1); const e = G.endLayoff(k, 1); ok('undercut: defender gets 0 + 25', e.result.deltas[1] === 25 && e.result.deltas[0] === 0 && e.result.undercut, JSON.stringify(e.result.deltas)); ok('undercut stats', e.stats[1].undercuts === 1 && e.stats[0].undercutBy === 1); ok('pairScore undercut on a tie', pairScore('knock', 6, 6, DEFAULT_RULES).to === 'defender' && pairScore('knock', 6, 6, DEFAULT_RULES).pts === 25); ok('undercut bonus setting', pairScore('knock', 8, 3, { ...DEFAULT_RULES, undercutBonus: 10 }).pts === 15); } { // Big Gin const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['5s', '4h', '3c', '6c'] }); const d = G.drawStock(gs, 0); ok('Big Gin available', G.canBigGin(d, 0)); const b = G.bigGin(d, 0); ok('Big Gin scores deadwood + 31', b.result.kind === 'biggin' && b.result.deltas[0] === bestMelds(b.hands[1]).deadwood + 31); const off = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['5s', '4h'], rules: { bigGin: false } }); ok('Big Gin off by rule', !G.canBigGin(G.drawStock(off, 0), 0)); } { // wash: 2p, a discard leaving 2 in the stock voids the hand const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Kc', 'Qc', 'Jc'] }); const d = G.drawStock(gs, 0); const w = G.discard(d, 0, 'Kc'); ok('2p: wash when 2 cards remain', w.phase === 'roundOver' && w.result.kind === 'wash' && w.scores.every(s => s === 0)); const nr = G.nextRound(w); ok('wash: same dealer redeals', nr.dealer === w.dealer && nr.round === w.round + 1); const k = G.knock(d, 0, 'Kc'); ok('a knock on the last turn still counts', k === d || k.phase === 'layoff' || k.phase === 'roundOver'); // 3p: one reshuffle first const g3 = rig({ n: 3, hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac', '2c 3c 4c 5c 6c 7c 9h Th Jh Qh'], upcard: 'Kh', stock: ['Kc', 'Qc', 'Jc'] }); g3.discard = ['Kh', '8h', '5d'].map(cardFromId); // stock 3 + discard 3 + hands 30 = 36, fine for this test (not 52) const d3 = G.drawStock(g3, 0); const r3 = G.discard(d3, 0, 'Kc'); ok('3p: first time → reshuffle, play goes on', r3.phase === 'draw' && r3.reshuffles === 1 && r3.discard.length === 1 && r3.stock.length === 2 + 3); ok('3p: the top discard stays up', r3.discard[0].id === 'Kc'); } { // Oklahoma: knock limit from the upcard; spade doubles const gs = G.createGame({ players: 2, seed: 99, rules: { oklahoma: true } }); const up = gs.discard[0]; ok('Oklahoma knock limit = upcard value', gs.knockLimit === up.pts); ok('Oklahoma spade doubles', gs.doubled === (up.suit === 's')); const s = rig({ hands: ['2s 3s 4s 7h 7d 7c Jd Qd Kd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: '3h', stock: ['5c', '4h', '3c', '6c', '4c', '6d'], rules: { oklahoma: true } }); s.knockLimit = 3; const d = G.drawStock(s, 0); ok('Oklahoma: can\'t knock with 5 when the limit is 3', G.knock(d, 0, '9c') === d); } { // match end, bonuses const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd 5c', '2h 3h 9s 9d Ts Th 5h 6d 8c Kh'], upcard: 'Kd' }); gs.scores = [90, 0]; const g = G.knock(G.drawDiscard(gs, 0), 0, '5c'); ok('reaching 100 ends the match', g.phase === 'gameOver' && g.winner === 0); const f = g.final[0]; ok('final: game bonus + box bonus', f.game === 100 && f.box === 25 * g.boxes[0]); ok('shutout doubles the winner', f.shutout && f.total === (f.points + f.game + f.box) * 2); const nb = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd 5c', '2h 3h 9s 9d Ts Th 5h 6d 8c Kh'], upcard: 'Kd', rules: { bonuses: false } }); nb.scores = [90, 0]; const g2 = G.knock(G.drawDiscard(nb, 0), 0, '5c'); ok('bonuses off: total = points', g2.final[0].total === g2.scores[0]); ok('target setting', G.createGame({ players: 2, rules: { target: 250 } }).rules.target === 250); } { const gs = G.createGame({ players: 3, seed: 5 }); ok('save is valid', G.isValidSave(JSON.parse(JSON.stringify(gs)), 3)); ok('save checks seat count', !G.isValidSave(gs, 2)); } // ── Regressions from the old build ─────────────────────────────────────────── section('Regressions'); { // old AI judged knock/gin on all 11 cards: this gin-after-discard hand read as 10 deadwood const gs = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Kc', '4h', '3c', '6c', '4c', '6d'] }); const d = G.drawStock(gs, 0); for (let sk = 1; sk <= 5; sk++) { const a = chooseAction(d, 0, { skill: sk, rng: mulberry32(sk) }); ok(`skill ${sk} goes gin when the discard leaves 0`, a.kind === 'gin' && a.id === 'Kc', JSON.stringify(a)); } const bg = rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['5s', '4h', '3c', '6c'] }); ok('AI calls Big Gin', chooseAction(G.drawStock(bg, 0), 0, { skill: 3 }).kind === 'biggin'); // old AI laid off out of its own melds const k = rig({ hands: ['2s 3s 4s 7h 7d 7s Jd Qd Kd 9c', '7c 8c 9h Kc 5c 6c 5d 5h Th Jh'], upcard: 'Ks', stock: ['Ac', '4h', '3c', '2c', '4c', '6d'] }); const kk = G.knock(G.drawStock(k, 0), 0, '9c'); if (kk.phase === 'layoff') { const ls = chooseLayoffs(kk, 1, { skill: 4 }); ok('AI keeps its own clubs run instead of laying the 7♣ off', !ls.some(l => l.id === '7c'), JSON.stringify(ls)); } else ok('knock fixture', false, kk.phase); } // ── AI + Coach ─────────────────────────────────────────────────────────────── section('AI'); { let legal = true, why = ''; for (let t = 0; t < 120 && legal; t++) { let gs = G.createGame({ players: 2 + (t % 3), seed: 1000 + t }); for (let step = 0; step < 6 && legal; step++) { const seat = G.actor(gs); const sk = 1 + (t % 5); const r = mulberry32(t * 31 + step); if (gs.phase === 'upcard') { const src = chooseDraw(gs, seat, { skill: sk, rng: r }); gs = src === 'discard' ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat); continue; } if (gs.phase === 'draw') { const src = chooseDraw(gs, seat, { skill: sk, rng: r }); const nx = src === 'discard' ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat); if (nx === gs) { legal = false; why = `draw ${src}`; } gs = nx; continue; } if (gs.phase === 'discard') { const a = chooseAction(gs, seat, { skill: sk, rng: r }); const nx = a.kind === 'biggin' ? G.bigGin(gs, seat) : a.kind === 'discard' ? G.discard(gs, seat, a.id) : G.knock(gs, seat, a.id); if (nx === gs) { legal = false; why = `${a.kind} ${a.id}`; } gs = nx; } if (G.isOver(gs) || gs.phase === 'layoff') break; } } ok('AI moves are always legal', legal, why); const gs = G.drawDiscard(rig({ hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: '7c' }), 0); ok('AI never ranks the taken card as a discard', !rankDiscards(gs, 0, { skill: 5 }).some(r => r.card.id === '7c')); const cd = coachDraw(rig({ hands: ['As 2s 3s 4s 7h 7d 8c Jd Qd 9c', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: '7c' }), 0); ok('coach takes the card that makes a set', cd.source === 'discard' && /7♣/.test(cd.reason), cd.reason); const ca = coachAction(G.drawStock(rig({ hands: ['As 2s 3s 4s 7h 7d 7c Jd Qd Kd', '5h 6h 7s 8s 9s Ts 2d 3d 4d Ac'], upcard: 'Kh', stock: ['Kc', '4h', '3c', '6c', '4c'] }), 0), 0); ok('coach says gin', ca.kind === 'gin' && /GIN/.test(ca.reason), JSON.stringify(ca)); } // ── Layout ─────────────────────────────────────────────────────────────────── section('Layout'); for (const n of [2, 3, 4]) { const L = layoutFor(n); const furn = hudFurniture(); for (let s = 1; s < n; s++) furn.push({ name: `plate ${s}`, r: plateRect(L.seats[s].plate) }); for (let i = 0; i < furn.length; i++) for (let j = i + 1; j < furn.length; j++) { ok(`${n}p: ${furn[i].name} clear of ${furn[j].name}`, !rectsOverlap(furn[i].r, furn[j].r)); } const stockB = cardBounds({ ...L.stock, y: L.stock.y - 10 }), discB = cardBounds(L.discard); const sdS = cardBounds(L.sdStock), sdD = cardBounds(L.sdDiscard); ok(`${n}p: piles apart`, !rectsOverlap(stockB, discB) && !rectsOverlap(sdS, sdD)); ok(`${n}p: piles on the baize`, [stockB, discB, sdS, sdD].every(b => T.onFelt({ x: b.x0, y: b.y0 }) && T.onFelt({ x: b.x1, y: b.y1 }))); const meter = { x0: METER.x - METER.w / 2 - 70, x1: METER.x + METER.w / 2 + 12, y0: METER.y - 36, y1: METER.y + 34 }; for (const f of furn) ok(`${n}p: meter clear of ${f.name}`, !rectsOverlap(meter, f.r)); ok(`${n}p: meter clear of the piles`, !rectsOverlap(meter, stockB) && !rectsOverlap(meter, discB)); for (let s = 0; s < n; s++) { for (const cards of [10, 11]) { const fb = fanBounds(L.seats[s].fan, cards, s === 0 ? 40 : 0); ok(`${n}p seat ${s} (${cards}): hand on screen`, onScreen(fb, s === 0 ? 50 : 10), JSON.stringify(fb)); for (const f of furn) ok(`${n}p seat ${s} (${cards}): hand clear of ${f.name}`, !rectsOverlap(fb, f.r), `${JSON.stringify(fb)} vs ${JSON.stringify(f.r)}`); ok(`${n}p seat ${s} (${cards}): hand clear of piles`, !rectsOverlap(fb, stockB) && !rectsOverlap(fb, discB)); if (s === 0) ok(`${n}p (${cards}): hand clear of the meter`, !rectsOverlap(fb, meter)); } if (s > 0) { const b = handBadge(L, s), br = { x0: b.x - 17, x1: b.x + 17, y0: b.y - 17, y1: b.y + 17 }; ok(`${n}p seat ${s}: badge on screen`, onScreen(br)); for (const f of furn) ok(`${n}p seat ${s}: badge clear of ${f.name}`, !rectsOverlap(br, f.r)); const hh = handHome(L, s); ok(`${n}p seat ${s}: ghost hand rests on screen`, hh.x > 0 && hh.x < W && hh.y > 0 && hh.y < SCREEN_H); } } // showdown rows: knocker + up to 3 opponents, a long row (16 cards in 5 blocks) const human = fanBounds(L.seats[0].fan, 10, 40); const blocks = [[1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1, 2]]; for (let rows = 1; rows <= n; rows++) { for (let r = 0; r < rows; r++) { const row = rowPoses(r, rows, blocks); let rb = null; row.poses.flat().forEach(p => { const b = cardBounds(p); rb = rb ? { x0: Math.min(rb.x0, b.x0), x1: Math.max(rb.x1, b.x1), y0: Math.min(rb.y0, b.y0), y1: Math.max(rb.y1, b.y1) } : b; }); rb = { ...rb, y1: rb.y1 + 10 }; // brackets const label = { x0: ROW.labelX - 170, x1: ROW.labelX, y0: row.y - 22, y1: row.y + 22 }; const tag = `${n}p rows ${rows}/${r}`; ok(`${tag}: on the baize`, T.onFelt({ x: rb.x0, y: rb.y0 }) && T.onFelt({ x: rb.x1, y: rb.y1 }), JSON.stringify(rb)); for (const f of furn) ok(`${tag}: clear of ${f.name}`, !rectsOverlap(rb, f.r) && !rectsOverlap(label, f.r)); ok(`${tag}: clear of your hand`, !rectsOverlap(rb, human)); ok(`${tag}: clear of the retired piles`, !rectsOverlap(rb, sdS) && !rectsOverlap(rb, sdD) && !rectsOverlap(label, sdS) && !rectsOverlap(label, sdD)); ok(`${tag}: label clear of the cards`, label.x1 < rb.x0); if (r > 0) { const prev = rowPoses(r - 1, rows, blocks); ok(`${tag}: rows don't overlap`, blockRect(prev, 0).y1 + 12 < blockRect(row, 0).y0); } } } // hand hit-tests with meld gaps (the Melds sort) for (const sizes of [[3, 3, 4], [4, 3, 3, 1], [3, 0, 8]]) { const { slots, total } = blockSlots(sizes); const cards = slots.length; let rt = true; for (let i = 0; i < cards; i++) { const p = handPose(L, 0, i, cards, 0, slots, total); // the topmost card under a point on card i's left strip is i const pt = { x: p.x - CARD_W / 2 + 8, y: p.y }; let hit = -1; for (let j = cards - 1; j >= 0; j--) if (inPose(pt, handPose(L, 0, j, cards, 0, slots, total))) { hit = j; break; } if (hit !== i) rt = false; } ok(`${n}p: gapped hand hit-tests (${sizes})`, rt); const fb = (() => { let b = null; for (let i = 0; i < cards; i++) { const c = cardBounds(handPose(L, 0, i, cards, 40, slots, total)); b = b ? { x0: Math.min(b.x0, c.x0), x1: Math.max(b.x1, c.x1), y0: Math.min(b.y0, c.y0), y1: Math.max(b.y1, c.y1) } : c; } return b; })(); for (const f of furn) ok(`${n}p: gapped hand clear of ${f.name}`, !rectsOverlap(fb, f.r)); } } // ── Soak + skill ladder ────────────────────────────────────────────────────── section('Soak'); export function playMatch(n, skills, seed, rules = {}) { const r = mulberry32(seed * 7 + 1); let gs = G.createGame({ players: n, seed, rules }); let rounds = 0, conserve = true, illegal = 0; for (let guard = 0; guard < 6000; guard++) { if (gs.phase === 'gameOver') return { gs, rounds, conserve, illegal }; if (gs.phase === 'roundOver') { rounds++; gs = G.nextRound(gs); continue; } const seat = G.actor(gs); const opt = { skill: skills[seat], rng: r }; let nx = gs; if (gs.phase === 'upcard') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat); else if (gs.phase === 'draw') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat); else if (gs.phase === 'discard') { const a = chooseAction(gs, seat, opt); nx = a.kind === 'biggin' ? G.bigGin(gs, seat) : a.kind === 'discard' ? G.discard(gs, seat, a.id) : G.knock(gs, seat, a.id); } else if (gs.phase === 'layoff') { let g = gs; for (const l of chooseLayoffs(gs, seat, opt)) { const y = G.layoff(g, seat, l.id, l.meldIdx); if (y === g) illegal++; g = y; } nx = G.endLayoff(g, seat); } if (nx === gs) { illegal++; break; } gs = nx; if (G.cardsInPlay(gs) !== 52) conserve = false; } return { gs, rounds, conserve, illegal, stuck: gs.phase !== 'gameOver' }; } { const M = QUICK ? 6 : 24; for (const rules of [{}, { upcard: false, bonuses: false }, { oklahoma: true, undercutBonus: 10, bigGin: false }]) { for (const n of [2, 3, 4]) { let ended = 0, illegal = 0, conserve = true, rounds = 0, scoreOk = true; for (let i = 0; i < M; i++) { const skills = Array.from({ length: n }, (_, s) => 1 + ((i + s * 2) % 5)); const res = playMatch(n, skills, 400 + i * 13 + n, rules); if (!res.stuck) ended++; illegal += res.illegal; if (!res.conserve) conserve = false; rounds += res.rounds; if (res.gs.phase === 'gameOver') { const w = res.gs.winner; if (res.gs.scores[w] < res.gs.rules.target || res.gs.scores[w] < Math.max(...res.gs.scores)) scoreOk = false; } } const tag = `${n}p ${JSON.stringify(rules)}`; ok(`${tag}: every match ends`, ended === M, `${ended}/${M}`); ok(`${tag}: no illegal AI moves`, illegal === 0, String(illegal)); ok(`${tag}: 52 cards conserved`, conserve); ok(`${tag}: the winner has the top score ≥ target`, scoreOk); if (!Object.keys(rules).length) console.log(` ${n}p: ${M} matches, avg ${(rounds / M).toFixed(1)} hands`); } } } section('Skill ladder (2p, points per hand)'); { // play single hands both ways round; measure average net points per hand for A function duel(a, b, hands) { let net = 0; for (let i = 0; i < hands; i++) { const seatA = i % 2; const skills = seatA === 0 ? [a, b] : [b, a]; const r = mulberry32(77 + i * 5); let gs = G.createGame({ players: 2, seed: 5000 + Math.floor(i / 2), dealer: 1 }); for (let guard = 0; guard < 400 && !G.isOver(gs); guard++) { const seat = G.actor(gs); const opt = { skill: skills[seat], rng: r }; let nx = gs; if (gs.phase === 'upcard') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.takeUpcard(gs, seat) : G.passUpcard(gs, seat); else if (gs.phase === 'draw') nx = chooseDraw(gs, seat, opt) === 'discard' ? G.drawDiscard(gs, seat) : G.drawStock(gs, seat); else if (gs.phase === 'discard') { const ac = chooseAction(gs, seat, opt); nx = ac.kind === 'biggin' ? G.bigGin(gs, seat) : ac.kind === 'discard' ? G.discard(gs, seat, ac.id) : G.knock(gs, seat, ac.id); } else if (gs.phase === 'layoff') { let g = gs; for (const l of chooseLayoffs(gs, seat, opt)) g = G.layoff(g, seat, l.id, l.meldIdx); nx = G.endLayoff(g, seat); } gs = nx; } if (gs.result) net += gs.result.deltas[seatA] - gs.result.deltas[1 - seatA]; } return net / hands; } const N = QUICK ? 300 : 2000; const t0 = Date.now(); const pairs = [[2, 1], [3, 2], [4, 3], [5, 4], [5, 3], [5, 1]]; const res = {}; for (const [a, b] of pairs) res[`${a}v${b}`] = duel(a, b, N); console.log(` ${Object.entries(res).map(([k, v]) => `${k} ${v >= 0 ? '+' : ''}${v.toFixed(1)}`).join(' · ')} (${N} hands each, ${((Date.now() - t0) / 1000).toFixed(1)}s)`); ok('skill 2 beats 1', res['2v1'] > 0, res['2v1'].toFixed(2)); ok('skill 3 beats 2', res['3v2'] > 0, res['3v2'].toFixed(2)); // measured over 5000 paired hands: 4v3 ≈ +1.0, 5v4 ≈ +2.1, 5v3 ≈ +3.0 (± 0.33) ok('skill 4 beats 3', res['4v3'] > (QUICK ? -2 : 0), res['4v3'].toFixed(2)); ok('skill 5 beats 4', res['5v4'] > (QUICK ? -2 : 0), res['5v4'].toFixed(2)); ok('skill 5 beats 3', res['5v3'] > (QUICK ? 0 : 1), res['5v3'].toFixed(2)); ok('skill 5 clearly beats 1', res['5v1'] > 4, res['5v1'].toFixed(2)); } console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0);