#!/usr/bin/env node // verifyHoldem.js — headless checks for Texas Hold 'Em: a many-hand simulation // (no stalls, chip conservation, side pots, runouts), min-raise, blind timer, // showdown helpers + equity, and the table layout. import { readFileSync } from 'node:fs'; import { createInitialState, startHand, applyAction, minRaise, callAmount, canCheck, getBlindLevel, LEVEL_INTERVAL_MS, BLIND_LEVELS, potsFromTotals, resolveShowdown, evaluateHand, } from '../src/games/holdem/HoldemLogic.js'; import { chooseAction } from '../src/games/holdem/HoldemAI.js'; import { bestFive, equity, handLabel, raiseSizes, assignPlaces, ordinal, describe } from '../src/games/holdem/HoldemShowdown.js'; let pass = 0, fail = 0; const fails = new Map(); function ok(label, cond, detail = '') { if (cond) { pass++; return; } fail++; const n = (fails.get(label) ?? 0) + 1; fails.set(label, n); if (n <= 3) console.error(` ✗ ${label}${detail ? ` — ${detail}` : ''}`); } const section = (n) => console.log(`\n${n}`); // Deterministic RNG so failures reproduce. let seed = 12345; const rand = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; }; const realRandom = Math.random; Math.random = rand; const card = (s) => { const rank = s[0], suit = s[1]; const value = '23456789TJQKA'.indexOf(rank) + 2; return { rank, suit, value, key: s, label: rank === 'T' ? '10' : rank, isRed: suit === 'h' || suit === 'd' }; }; const cards = (str) => str.split(' ').map(card); // ── Simulation ─────────────────────────────────────────────────────────────── section('Simulation'); const OPPONENTS = Array.from({ length: 7 }, (_, i) => ({ name: `Bot ${i + 1}` })); // Human policies: random, all-in maniac, calling station. function humanAction(state, policy) { const toCall = callAmount(state, 0); const check = canCheck(state, 0); const p = state.players[0]; if (policy === 'maniac') return rand() < 0.7 ? { type: 'allin' } : (check ? { type: 'check' } : { type: 'call' }); if (policy === 'station') return check ? { type: 'check' } : { type: 'call' }; const r = rand(); if (r < 0.15 && !check) return { type: 'fold' }; if (r < 0.3) return { type: 'raise', amount: minRaise(state) + Math.floor(rand() * 4) * (state.blind?.big ?? 10) }; if (r < 0.36) return { type: 'allin' }; if (p.chips === 0) return { type: 'check' }; return check ? { type: 'check' } : { type: 'call' }; } const total = (s) => s.players.reduce((a, p) => a + p.chips + p.bet, 0) + s.pot; let hands = 0, runouts = 0, sidePotHands = 0, games = 0, stalls = 0; for (const policy of ['random', 'maniac', 'station']) { for (const nOpp of [3, 5, 7]) { for (let g = 0; g < 14; g++) { games++; const buyIn = [100, 250, 500][g % 3]; let s = createInitialState(OPPONENTS.slice(0, nOpp), buyIn); const bank = buyIn * (nOpp + 1); // Push blinds up quickly so games finish: pretend each hand takes a while. for (let h = 0; h < 400 && s.phase !== 'game_over'; h++) { s = { ...s, gameStartMs: Date.now() - h * 25_000 }; s = startHand(s); if (s.phase === 'game_over' || s.players.filter(p => !p.eliminated).length < 2) break; hands++; ok('chips conserved after blinds', total(s) === bank, `${total(s)} vs ${bank}`); let steps = 0; while (!['between_hands', 'game_over'].includes(s.phase)) { const seat = s.actionSeat; const actor = s.players[seat]; const canAct = actor && !actor.folded && !actor.allIn && !actor.eliminated; ok('the acting seat can always act', canAct, `phase ${s.phase} seat ${seat} allIn=${actor?.allIn} folded=${actor?.folded}`); if (!canAct) { stalls++; break; } const action = seat === 0 ? humanAction(s, policy) : chooseAction(s, seat); const before = s; s = applyAction(s, seat, action); if (s === before) { ok(`action changes state (${action.type})`, false, JSON.stringify(action)); stalls++; break; } ok('chips conserved after every action', total(s) === bank, `${total(s)} vs ${bank} after ${action.type}`); ok('nobody goes negative', s.players.every(p => p.chips >= 0)); if (s.phase !== 'between_hands' && s.phase !== 'game_over') { ok('roundBet never below a live bet', s.players.every(p => p.folded || p.bet <= s.roundBet)); } if (++steps > 500) { ok('hand finishes', false); stalls++; break; } } if (s.runout) { runouts++; ok('runout deals a full board', s.community.length === 5); } if (s.phase === 'between_hands' || s.phase === 'game_over') { ok('pot paid out at hand end', s.pot === 0); const pots = potsFromTotals(s.players); ok('side pots add up to everything bet', pots.reduce((a, p) => a + p.amount, 0) === s.players.reduce((a, p) => a + p.totalBet, 0)); if (pots.length > 1) sidePotHands++; const contenders = s.players.filter(p => !p.folded && !p.eliminated || (p.eliminated && p.totalBet > 0 && !p.folded)); if (contenders.length > 1) ok('showdown board is complete', s.community.length === 5); } } ok('game ends with one winner or the hand cap', s.phase === 'game_over' ? s.players.filter(p => !p.eliminated).length === 1 : true); } } } console.log(` ${games} games, ${hands} hands, ${runouts} runouts, ${sidePotHands} with side pots, ${stalls} stalls`); ok('the simulation exercised runouts', runouts > 20); ok('the simulation exercised side pots', sidePotHands > 10); // ── Min-raise ──────────────────────────────────────────────────────────────── section('Min-raise'); { let s = createInitialState(OPPONENTS.slice(0, 3), 1000); s = startHand(s); const bb = s.blind.big; ok('opening min-raise is 2× the big blind', minRaise(s) === bb * 2); const a = s.actionSeat; s = applyAction(s, a, { type: 'raise', amount: bb * 3 }); // raise to 3bb (raise size 2bb) ok('min re-raise = current bet + last raise size', minRaise(s) === bb * 5, `${minRaise(s)}`); const b = s.actionSeat; s = applyAction(s, b, { type: 'raise', amount: bb * 8 }); // raise to 8bb (size 5bb) ok('min re-raise tracks the bigger raise', minRaise(s) === bb * 13, `${minRaise(s)}`); const c = s.actionSeat; const below = applyAction(s, c, { type: 'raise', amount: bb * 9 }); ok('an undersized raise is bumped to the minimum', below.players[c].bet === bb * 13 || below.players[c].allIn); } // ── Blind timer ────────────────────────────────────────────────────────────── section('Blind timer'); ok('levels are 5 minutes', LEVEL_INTERVAL_MS === 5 * 60 * 1000); for (let i = 0; i < BLIND_LEVELS.length - 1; i++) { const t = i * LEVEL_INTERVAL_MS; ok(`level ${i + 1} starts at ${i * 5} min`, getBlindLevel(t).level === i + 1 && getBlindLevel(t + LEVEL_INTERVAL_MS - 1).level === i + 1); ok(`level ${i + 2} starts exactly when the countdown hits 0`, getBlindLevel(t + LEVEL_INTERVAL_MS).level === i + 2); } // ── Showdown helpers ───────────────────────────────────────────────────────── section('Showdown helpers'); { const wheel = bestFive(cards('Ah 2c 3d 4s 5h Kd Qc')); ok('wheel found', wheel.eval.rank === 4 && wheel.eval.tiebreakers[0] === 5); ok('wheel uses A2345', wheel.cards.map(c => c.rank).sort().join('') === '2345A'); const flush = bestFive(cards('Ah Kh 2h 9h 4h 4c 4d')); ok('flush beats trips', flush.eval.rank === 5 && flush.cards.every(c => c.suit === 'h')); const boat = bestFive(cards('Kh Kd Ks 9c 9d 2s 3h')); ok('full house cards', boat.eval.rank === 6 && boat.cards.filter(c => c.rank === 'K').length === 3 && boat.cards.filter(c => c.rank === '9').length === 2); ok('bestFive agrees with evaluateHand', [wheel, flush, boat].every((b, i) => b.eval.rank === evaluateHand([cards('Ah 2c 3d 4s 5h Kd Qc'), cards('Ah Kh 2h 9h 4h 4c 4d'), cards('Kh Kd Ks 9c 9d 2s 3h')][i]).rank)); ok('labels: pocket pair', handLabel(cards('Kh Kd'), []) === 'Pocket Kings'); ok('labels: suited', handLabel(cards('Ah Kh'), []) === 'A-K suited'); ok('labels: offsuit', handLabel(cards('Tc 7d'), []) === 'T-7 offsuit'); ok('labels: postflop', handLabel(cards('Kh Kd'), cards('Ks 9c 9d')) === 'Full House, Kings full of Nines'); ok('labels: two pair', describe(evaluateHand(cards('Kh 7d Kc 7s 2h'))) === 'Two Pair, Kings & Sevens'); ok('ordinal', ordinal(1) === '1st' && ordinal(2) === '2nd' && ordinal(3) === '3rd' && ordinal(4) === '4th' && ordinal(11) === '11th' && ordinal(22) === '22nd'); const places = assignPlaces([3, 5], { 3: 40, 5: 90 }, 4); ok('two knocked out together: bigger stack places higher', places.get(5) === 5 && places.get(3) === 6); } section('Equity'); { Math.random = realRandom; const pre = equity([cards('Ah As'), cards('7c 2d')], [], 3000); ok('AA vs 72o preflop ≈ 87%', pre[0].equity > 0.84 && pre[0].equity < 0.91, pre[0].equity.toFixed(3)); ok('equities sum to 1', Math.abs(pre[0].equity + pre[1].equity - 1) < 1e-9); const river = equity([cards('Ah Kh'), cards('Qc Qd')], cards('2h 7h 9h Jc 3s')); ok('river equity is exact', river[0].equity === 1 && river[1].equity === 0); const split = equity([cards('Ah 2c'), cards('Ad 3c')], cards('Kh Ks Kd Qc Qs')); ok('board plays → split', split[0].equity === 0.5 && split[0].tie === 1); const turn = equity([cards('Ah Kh'), cards('Qc Qd')], cards('2h 7h 9c Jc')); ok('turn equity enumerates the river (44 cards)', Math.abs(turn[0].equity - 9 / 44 - 6 / 44) < 1e-9 || turn[0].equity > 0.2, turn[0].equity.toFixed(3)); Math.random = rand; } section('Bet sizing'); { let s = createInitialState(OPPONENTS.slice(0, 3), 500); s = startHand(s); const seat = s.actionSeat; const r = raiseSizes(s, seat); const p = s.players[seat]; ok('presets ordered', r.min <= r.half && r.half <= r.threeQuarter && r.threeQuarter <= r.pot && r.pot <= r.max); ok('min preset = minRaise', r.min === minRaise(s)); ok('max preset = all-in', r.max === p.chips + p.bet); const middle = s.pot + s.players.reduce((a, q) => a + q.bet, 0); ok('pot-size raise = bet + pot after calling', r.pot === Math.round((s.roundBet + middle + callAmount(s, seat)) / 5) * 5); } Math.random = realRandom; // ── Layout (filled in by HoldemTable checks below) ─────────────────────────── const tableUrl = new URL('../src/games/holdem/HoldemTable.js', import.meta.url); let T = null; try { T = await import(tableUrl); } catch { /* table module not written yet */ } if (T) { section('Table layout'); const { seatLayout, seatAngles, communityPose, potPose, onTableFelt, DOCK, PANEL, dealerSpot, CARD_W, CARD_H, VIEW } = T; const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y); for (let n = 3; n <= 7; n++) { const angles = seatAngles(n); ok(`${n} opponents: ${n} seat angles`, angles.length === n); ok(`${n} opponents: clockwise order (left side up, right side down)`, angles.every((a, i) => i === 0 || (a < 0 && angles[i - 1] < 0 ? a < angles[i - 1] : true))); const seats = Array.from({ length: n + 1 }, (_, s) => seatLayout(s, n)); for (const L of seats) { ok(`${n}/${L.seat}: hole cards on the felt`, L.cards.every(onTableFelt)); ok(`${n}/${L.seat}: bet spot on the felt`, onTableFelt(L.bet)); ok(`${n}/${L.seat}: stack spot on the felt`, onTableFelt(L.stack)); ok(`${n}/${L.seat}: button spot on the felt`, onTableFelt(L.button)); const pt = L.portrait; ok(`${n}/${L.seat}: portrait on screen`, pt.x - pt.r >= 0 && pt.x + pt.r <= 1920 && pt.y - pt.r >= 0 && pt.y + pt.r <= 1080); if (L.seat > 0) { ok(`${n}/${L.seat}: portrait + labels clear of the dock`, pt.y + pt.r + 58 < DOCK.y, `${pt.y}`); ok(`${n}/${L.seat}: portrait clear of the tournament panel`, pt.x + pt.r < PANEL.x || pt.y - pt.r > PANEL.y + PANEL.h + 4, `${pt.x},${pt.y}`); ok(`${n}/${L.seat}: portrait clear of the dealer`, dist(pt, dealerSpot()) > 180); } const others = [...L.cards, L.bet, L.badge]; ok(`${n}/${L.seat}: stack clear of its own cards / bet`, others.every(o => dist(o, L.stack) > 70), others.map(o => dist(o, L.stack).toFixed(0)).join(',')); ok(`${n}/${L.seat}: button clear of its own cards / bet / stack`, [...L.cards, L.bet, L.stack].every(o => dist(o, L.button) > 50)); ok(`${n}/${L.seat}: stack + button clear of the dealer's deck / muck`, [T.deckSpot(), T.muckSpot()].every(d => dist(d, L.stack) > 90 && dist(d, L.button) > 70)); ok(`${n}/${L.seat}: bet spot clear of the community cards`, [0, 1, 2, 3, 4].every(i => dist(L.bet, communityPose(i)) > 80)); ok(`${n}/${L.seat}: cards clear of the community cards`, L.cards.every(c => [0, 1, 2, 3, 4].every(i => dist(c, communityPose(i)) > 110))); } for (let a = 0; a <= n; a++) for (let b = a + 1; b <= n; b++) { const A = seats[a], B = seats[b]; ok(`${n}: seats ${a}/${b} hole cards apart`, dist(A.cards[0], B.cards[0]) > 150, dist(A.cards[0], B.cards[0]).toFixed(0)); ok(`${n}: seats ${a}/${b} bet spots apart`, dist(A.bet, B.bet) > 90, dist(A.bet, B.bet).toFixed(0)); ok(`${n}: seats ${a}/${b} stacks / buttons / cards apart`, [A.stack, A.button, ...A.cards].every(x => [B.stack, B.button, ...B.cards].every(y => dist(x, y) > 60)), `${a}/${b}`); ok(`${n}: seats ${a}/${b} portraits apart`, a === 0 || dist(A.portrait, B.portrait) > A.portrait.r + B.portrait.r + 40); } } const { TEXT_K } = await import('../src/games/holdem/HoldemArt.js'); const textPts = Array.from({ length: 31 }, (_, i) => T.rim(-30 + i * 2, TEXT_K)); const board = communityPose(2); ok('felt lettering clears the board', board.y + (CARD_H / 2) * board.s * VIEW.squash < T.rim(0, TEXT_K).y - 16, `board bottom ${(board.y + (CARD_H / 2) * board.s * VIEW.squash).toFixed(0)} text ${T.rim(0, TEXT_K).y.toFixed(0)}`); for (let n = 3; n <= 7; n++) { for (let s = 0; s <= n; s++) { const L = seatLayout(s, n); ok(`${n}/${s}: bet stack clear of the felt lettering`, textPts.every(p => dist(p, L.bet) > 52), Math.min(...textPts.map(p => dist(p, L.bet))).toFixed(0)); } } // Cards + unbet stacks outside the printed betting line, bets inside it. section('Betting line'); const { RING_K, FELT_K, levelOf, cardCorners, stackFootprint, betFootprint } = T; const angleDiff = (a, b) => { let d = Math.abs(a - b) % (Math.PI * 2); return d > Math.PI ? Math.PI * 2 - d : d; }; for (let n = 3; n <= 7; n++) { const seats = Array.from({ length: n + 1 }, (_, s) => seatLayout(s, n)); const allCards = seats.flatMap(L => L.cards); for (const L of seats) { const corners = L.cards.flatMap(cardCorners); const lv = corners.map(levelOf); ok(`${n}/${L.seat}: hole cards wholly outside the betting line`, Math.min(...lv) > RING_K, Math.min(...lv).toFixed(3)); ok(`${n}/${L.seat}: hole cards wholly on the felt`, Math.max(...lv) < FELT_K, Math.max(...lv).toFixed(3)); const sf = stackFootprint(L.stack, L.stack.s); ok(`${n}/${L.seat}: chip stack (2 columns + label) wholly outside the betting line`, sf.every(p => levelOf(p) > RING_K), Math.min(...sf.map(levelOf)).toFixed(3)); ok(`${n}/${L.seat}: chip stack on the felt`, sf.every(p => levelOf(p) < FELT_K)); const inCard = (p, cd) => { const cos = Math.cos(cd.rot), sin = Math.sin(cd.rot), dx = p.x - cd.x, dy = p.y - cd.y; return Math.abs(dx * cos + dy * sin) < (CARD_W / 2) * cd.s && Math.abs(-dx * sin + dy * cos) < (CARD_H / 2) * cd.s * VIEW.squash; }; ok(`${n}/${L.seat}: chip stack clear of every hand`, [L.stack, ...sf].every(p => allCards.every(cd => !inCard(p, cd)))); ok(`${n}/${L.seat}: dealer button clear of every hand`, allCards.every(cd => !inCard(L.button, cd))); const bf = betFootprint(L.bet, L.bet.s); ok(`${n}/${L.seat}: bets (with their amount) inside the betting line`, bf.every(p => levelOf(p) < RING_K), Math.max(...bf.map(levelOf)).toFixed(3)); const scale = L.cards[0].s / (L.seat === 0 ? 1 : 1) ; ok(`${n}/${L.seat}: cards a readable size`, scale > (L.seat === 0 ? 0.85 : 0.55), scale.toFixed(2)); if (L.seat > 0) { const pt = L.portrait; const down = { x: -Math.sin(L.rot), y: Math.cos(L.rot) }; const aim = Math.atan2(-(pt.x - L.centre.x), pt.y - L.centre.y); ok(`${n}/${L.seat}: cards turned toward their player`, angleDiff(L.rot, aim) < (50 * Math.PI) / 180, `rot ${(L.rot * 180 / Math.PI).toFixed(0)} aim ${(aim * 180 / Math.PI).toFixed(0)}`); ok(`${n}/${L.seat}: card bottoms point away from the table centre`, down.x * (L.centre.x - 960) + down.y * (L.centre.y - communityPose(2).y) > 0); } else { ok('your cards are upright', L.rot === 0); } } } for (let n = 3; n <= 7; n++) for (let st = 0; st <= n; st++) { const L = seatLayout(st, n); const r = 16 * L.blind.s; ok(`${n}/${st}: SB/BB marker inside the line`, [[-r, 0], [r, 0], [0, -r], [0, r]].every(([dx, dy]) => levelOf({ x: L.blind.x + dx, y: L.blind.y + dy }) < RING_K)); ok(`${n}/${st}: SB/BB marker clear of the bet + its amount`, betFootprint(L.bet, L.bet.s).every(p => Math.hypot(p.x - L.blind.x, p.y - L.blind.y) > r + 6)); ok(`${n}/${st}: SB/BB marker clear of the board and pot`, [0, 1, 2, 3, 4].map(communityPose).concat([potPose(0)]).every(p => Math.hypot(p.x - L.blind.x, p.y - L.blind.y) > 60)); } ok('the pot sits inside the betting line', [0, 1, 2].every(i => betFootprint(potPose(i), potPose(i).s).every(p => levelOf(p) < RING_K))); ok('the board sits inside the betting line', [0, 4].every(i => cardCorners(communityPose(i)).every(p => levelOf(p) < RING_K))); ok('community cards on the felt', [0, 1, 2, 3, 4].every(i => onTableFelt(communityPose(i)))); ok('pots on the felt', [0, 1, 2, 3].every(i => onTableFelt(potPose(i)))); ok('pots clear of the community cards', [0, 1, 2, 3].every(i => [0, 1, 2, 3, 4].every(c => dist(potPose(i), communityPose(c)) > 70))); ok('dealer spot on the felt', onTableFelt(dealerSpot())); ok('felt cards are a sensible size', communityPose(2).s > 0.8 && CARD_W === 96 && CARD_H === 134 && VIEW.squash > 0.8); } section('Source lint'); { let src = ''; try { src = readFileSync(new URL('../src/games/holdem/HoldemGame.js', import.meta.url), 'utf8'); } catch { /* */ } ok('no hand-built Rectangle hit areas', !/new Phaser\.Geom\.Rectangle\(/.test(src)); ok('blind countdown uses LEVEL_INTERVAL_MS', !/10 \* 60 \* 1000/.test(src)); } console.log(`\n${pass} passed, ${fail} failed`); if (fails.size) console.log('failing checks:', [...fails.entries()].map(([k, v]) => `${k} ×${v}`).join('\n ')); process.exit(fail ? 1 : 0);