599 lines
34 KiB
JavaScript
599 lines
34 KiB
JavaScript
#!/usr/bin/env node
|
||
// verifyCraps.js — headless checks for Craps: every bet against all 36 dice
|
||
// combos, exact house edges (Markov solve over resolveRoll itself), odds caps,
|
||
// take-down / working rules, a seeded AI soak for chip conservation, and the
|
||
// table geometry (zones, per-seat bet spots, rail stacks).
|
||
|
||
import { readFileSync } from 'node:fs';
|
||
import {
|
||
BET, POINT_NUMBERS, HARD_NUMBERS, NUMBERED, ONE_ROLL,
|
||
createInitialState, placeBet, addOdds, reduceBet, removeBet, setWorking, refundBets,
|
||
setDice, rollDice, resolveRoll, clearLastDeltas, totalAtRisk, maxOddsFor, oddsRoom,
|
||
isContract, isWorking, houseEdge, paysLabel, stickCall, explainPayout, explainMove, betLabel,
|
||
} from '../src/games/craps/CrapsLogic.js';
|
||
import { chooseBets, chooseOdds } from '../src/games/craps/CrapsAI.js';
|
||
import {
|
||
P, VIEW, TUB, ZONES, LANES, SEATS, SLOT_ORDER, FILL_ORDER, seatNames, laneSpot, laneForBet, hitZoneUV, inTub,
|
||
NEAR_VISIBLE_V, railUV, railPose, seatPortrait, throwOrigin, LANDING, BOARD, DOCK, offerSpot, OFFER, PROP, CALL,
|
||
puckOnUV, puckOffUV, BOX_NUMS, zoneKeyFor, lift, RESULT,
|
||
} from '../src/games/craps/CrapsTable.js';
|
||
import { simulateThrow, topFace, restingQ, DIE } from '../src/games/craps/CrapsDice.js';
|
||
|
||
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 near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;
|
||
|
||
function mulberry32(seed) {
|
||
return function () {
|
||
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
|
||
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
}
|
||
|
||
const ALL_DICE = [];
|
||
for (let a = 1; a <= 6; a++) for (let b = 1; b <= 6; b++) ALL_DICE.push([a, b]);
|
||
|
||
// A one-player table with the bankroll large enough for anything.
|
||
function table(point = null, chips = 100000) {
|
||
const s = createInitialState([], chips, 'T');
|
||
s.point = point;
|
||
s.phase = point === null ? 'comeout' : 'point';
|
||
return s;
|
||
}
|
||
|
||
function withBet(point, spec, { comePoint = null, odds = 0, onComeOut = false } = {}) {
|
||
const line = spec.type === BET.PASS || spec.type === BET.DONT_PASS;
|
||
const come = spec.type === BET.COME || spec.type === BET.DONT_COME;
|
||
let s = table(line ? null : come ? 6 : (point === 'cp' ? 6 : point));
|
||
s = placeBet(s, 0, spec);
|
||
const b = s.players[0].bets[0];
|
||
if (!b) throw new Error(`withBet: rejected ${JSON.stringify(spec)}`);
|
||
if (comePoint != null) b.comePoint = comePoint;
|
||
b.oddsAmount = odds;
|
||
s.players[0].chips -= odds;
|
||
b.onComeOut = onComeOut;
|
||
if (point !== 'cp') s.point = point;
|
||
s.phase = s.point === null ? 'comeout' : 'point';
|
||
return s;
|
||
}
|
||
|
||
// One roll with a single bet: returns { delta, result, kept, open, next }.
|
||
function oneRoll(state, dice) {
|
||
const r = resolveRoll(setDice(state, dice));
|
||
const pay = r.payouts.find((p) => p.playerIndex === 0);
|
||
return { r, pay, next: r.state };
|
||
}
|
||
|
||
// Exact expected value (per decision) of the player's single bet, by value
|
||
// iteration over the Markov chain that resolveRoll itself defines.
|
||
function exactEV(start) {
|
||
const key = (s) => JSON.stringify([s.point, s.players[0].bets.map((b) => [b.comePoint, b.amount, b.oddsAmount, b.onComeOut])]);
|
||
const states = new Map();
|
||
const queue = [start];
|
||
states.set(key(start), { s: start, edges: null, v: 0 });
|
||
while (queue.length) {
|
||
const s = queue.shift();
|
||
const node = states.get(key(s));
|
||
node.edges = [];
|
||
for (const d of ALL_DICE) {
|
||
const { pay, next } = oneRoll(s, d);
|
||
if (pay) { node.edges.push({ p: 1 / 36, delta: pay.delta }); continue; }
|
||
next.players[0].lastDelta = 0;
|
||
const k = key(next);
|
||
if (!states.has(k)) { states.set(k, { s: next, edges: null, v: 0 }); queue.push(next); }
|
||
node.edges.push({ p: 1 / 36, to: k });
|
||
}
|
||
}
|
||
for (let it = 0; it < 4000; it++) {
|
||
let change = 0;
|
||
for (const node of states.values()) {
|
||
let v = 0;
|
||
for (const e of node.edges) v += e.p * (e.to ? states.get(e.to).v : e.delta);
|
||
change = Math.max(change, Math.abs(v - node.v));
|
||
node.v = v;
|
||
}
|
||
if (change < 1e-13) break;
|
||
}
|
||
return states.get(key(start)).v;
|
||
}
|
||
|
||
const edgeOf = (s) => -exactEV(s) / (s.players[0].bets[0].amount + s.players[0].bets[0].oddsAmount) * 100;
|
||
|
||
// ── 1. Every bet × all 36 rolls against a hand-written table ─────────────────
|
||
section('Single-roll resolution (36 combos per bet)');
|
||
{
|
||
// expected(total, hard, isComeOut) → ['win', winnings] | ['lose'] | ['push'] | ['open']
|
||
const W = (w) => ['win', w];
|
||
const L = ['lose'], O = ['open'], Pu = ['push'];
|
||
const cases = [
|
||
{ name: 'Field $10', spec: { type: BET.FIELD, amount: 10 }, point: null,
|
||
exp: (t) => (t === 2 ? W(20) : t === 12 ? W(30) : [3, 4, 9, 10, 11].includes(t) ? W(10) : L) },
|
||
{ name: 'Pass $10 come-out', spec: { type: BET.PASS, amount: 10 }, point: null,
|
||
exp: (t) => (t === 7 || t === 11 ? W(10) : [2, 3, 12].includes(t) ? L : O) },
|
||
{ name: "Don't Pass $10 come-out", spec: { type: BET.DONT_PASS, amount: 10 }, point: null,
|
||
exp: (t) => (t === 2 || t === 3 ? W(10) : t === 7 || t === 11 ? L : O) }, // 12 barred: stands
|
||
{ name: 'Any 7 $5', spec: { type: BET.ANY7, amount: 5 }, point: 6, exp: (t) => (t === 7 ? W(20) : L) },
|
||
{ name: 'Any Craps $5', spec: { type: BET.ANY_CRAPS, amount: 5 }, point: 6, exp: (t) => ([2, 3, 12].includes(t) ? W(35) : L) },
|
||
{ name: 'Yo $5', spec: { type: BET.YO, amount: 5 }, point: null, exp: (t) => (t === 11 ? W(75) : L) },
|
||
{ name: 'Aces $5', spec: { type: BET.ACES, amount: 5 }, point: null, exp: (t) => (t === 2 ? W(150) : L) },
|
||
{ name: 'Ace-Deuce $5', spec: { type: BET.ACE_DEUCE, amount: 5 }, point: null, exp: (t) => (t === 3 ? W(75) : L) },
|
||
{ name: 'Boxcars $5', spec: { type: BET.BOXCARS, amount: 5 }, point: null, exp: (t) => (t === 12 ? W(150) : L) },
|
||
{ name: 'C&E $2', spec: { type: BET.CE, amount: 2 }, point: null, exp: (t) => ([2, 3, 12].includes(t) ? W(6) : t === 11 ? W(14) : L) },
|
||
{ name: 'Horn $4', spec: { type: BET.HORN, amount: 4 }, point: null, exp: (t) => (t === 2 || t === 12 ? W(27) : t === 3 || t === 11 ? W(12) : L) },
|
||
{ name: 'Big 6 $10', spec: { type: BET.BIG, number: 6, amount: 10 }, point: 5, exp: (t) => (t === 6 ? W(10) : t === 7 ? L : O) },
|
||
{ name: 'Hard 8 $5 (point)', spec: { type: BET.HARD, number: 8, amount: 5 }, point: 5,
|
||
exp: (t, h) => (t === 8 && h ? W(45) : t === 8 || t === 7 ? L : O) },
|
||
{ name: 'Hard 4 $5 (point)', spec: { type: BET.HARD, number: 4, amount: 5 }, point: 5,
|
||
exp: (t, h) => (t === 4 && h ? W(35) : t === 4 || t === 7 ? L : O) },
|
||
{ name: 'Hard 6 $5 (come-out, off)', spec: { type: BET.HARD, number: 6, amount: 5 }, point: null, exp: () => O },
|
||
{ name: 'Place 6 $12 (point)', spec: { type: BET.PLACE, number: 6, amount: 12 }, point: 5, exp: (t) => (t === 6 ? W(14) : t === 7 ? L : O) },
|
||
{ name: 'Place 4 $10 (point)', spec: { type: BET.PLACE, number: 4, amount: 10 }, point: 5, exp: (t) => (t === 4 ? W(18) : t === 7 ? L : O) },
|
||
{ name: 'Place 9 $10 (point)', spec: { type: BET.PLACE, number: 9, amount: 10 }, point: 5, exp: (t) => (t === 9 ? W(14) : t === 7 ? L : O) },
|
||
{ name: 'Place 8 $6 (come-out, off)', spec: { type: BET.PLACE, number: 8, amount: 6 }, point: null, exp: () => O },
|
||
{ name: 'Buy 10 $20', spec: { type: BET.BUY, number: 10, amount: 20 }, point: 5, exp: (t) => (t === 10 ? W(40) : t === 7 ? L : O) },
|
||
{ name: 'Lay 4 $40', spec: { type: BET.LAY, number: 4, amount: 40 }, point: null, exp: (t) => (t === 7 ? W(20) : t === 4 ? L : O) },
|
||
];
|
||
for (const c of cases) {
|
||
const s0 = placeBet(table(c.point), 0, c.spec);
|
||
ok(`${c.name}: placed`, s0.players[0].bets.length === 1);
|
||
let bad = 0;
|
||
for (const d of ALL_DICE) {
|
||
const t = d[0] + d[1], h = d[0] === d[1];
|
||
const [res, w] = c.exp(t, h);
|
||
const { pay } = oneRoll(s0, d);
|
||
const got = pay ? pay.result : 'open';
|
||
if (got !== res || (res === 'win' && pay.winnings !== w)) {
|
||
bad++;
|
||
if (bad < 3) ok(`${c.name} on ${d.join('-')}`, false, `expected ${res}${w ? ' ' + w : ''}, got ${got}${pay ? ' ' + pay.winnings : ''}`);
|
||
}
|
||
}
|
||
ok(`${c.name}: all 36 combos`, bad === 0);
|
||
}
|
||
|
||
// Commissions
|
||
{
|
||
const s0 = placeBet(table(5), 0, { type: BET.BUY, number: 4, amount: 20 });
|
||
const { pay } = oneRoll(s0, [2, 2]);
|
||
ok('Buy 4 $20: pays 40 less $1 vig', pay.winnings === 40 && pay.commission === 1 && pay.delta === 39 && pay.kept);
|
||
const s1 = placeBet(table(5), 0, { type: BET.LAY, number: 10, amount: 40 });
|
||
const r1 = oneRoll(s1, [3, 4]).pay;
|
||
ok('Lay 10 $40: wins 20 less $1 vig', r1.winnings === 20 && r1.commission === 1 && r1.delta === 19 && r1.kept);
|
||
}
|
||
// Pass / Don't on the point, with odds
|
||
for (const n of POINT_NUMBERS) {
|
||
const mult = n === 4 || n === 10 ? 3 : n === 5 || n === 9 ? 4 : 5;
|
||
let s = placeBet(table(null), 0, { type: BET.PASS, amount: 10 });
|
||
s.point = n; s.phase = 'point';
|
||
const b = s.players[0].bets[0];
|
||
ok(`Pass on ${n}: odds cap is ${mult}×`, maxOddsFor(b, s) === 10 * mult);
|
||
s = addOdds(s, 0, b.id, 10000);
|
||
ok(`Pass on ${n}: addOdds clamps to the cap`, s.players[0].bets[0].oddsAmount === 10 * mult);
|
||
const odds = 10 * mult;
|
||
const trueW = n === 4 || n === 10 ? odds * 2 : n === 5 || n === 9 ? odds * 3 / 2 : odds * 6 / 5;
|
||
const hit = oneRoll(s, n === 4 ? [2, 2] : n === 10 ? [5, 5] : [1, n - 1]).pay;
|
||
ok(`Pass on ${n} + max odds: point made pays flat + true odds`, hit.result === 'win' && hit.winnings === 10 + trueW, `${hit.winnings}`);
|
||
const seven = oneRoll(s, [3, 4]).pay;
|
||
ok(`Pass on ${n} + odds: seven-out loses everything`, seven.result === 'lose' && seven.delta === -(10 + odds));
|
||
|
||
let d = placeBet(table(null), 0, { type: BET.DONT_PASS, amount: 10 });
|
||
d.point = n; d.phase = 'point';
|
||
const db = d.players[0].bets[0];
|
||
ok(`Don't on ${n}: lay cap is 6× flat`, maxOddsFor(db, d) === 60);
|
||
d = addOdds(d, 0, db.id, 60);
|
||
const layW = n === 4 || n === 10 ? 30 : n === 5 || n === 9 ? 40 : 50;
|
||
const dw = oneRoll(d, [3, 4]).pay;
|
||
ok(`Don't on ${n} + 6× lay: seven pays flat + ${layW} (max win = 6× flat)`, dw.result === 'win' && dw.winnings === 10 + layW);
|
||
}
|
||
// A barred 12 is no action: the Don't bet stays exactly where it is.
|
||
{
|
||
const dp = placeBet(table(null), 0, { type: BET.DONT_PASS, amount: 10 });
|
||
const r = resolveRoll(setDice(dp, [6, 6]));
|
||
ok("Don't Pass on a come-out 12 stays up, untouched", r.payouts.length === 0 && r.state.players[0].bets.length === 1
|
||
&& r.state.players[0].bets[0].amount === 10 && r.state.players[0].chips === dp.players[0].chips);
|
||
const dc = placeBet(table(8), 0, { type: BET.DONT_COME, amount: 10 });
|
||
const r2 = resolveRoll(setDice(dc, [6, 6]));
|
||
ok("Don't Come on a 12 stays in the Don't Come box", r2.payouts.length === 0 && r2.state.players[0].bets[0].comePoint == null);
|
||
}
|
||
// Come bets travel, then win / lose; come odds off on the come-out.
|
||
{
|
||
let s = placeBet(table(5), 0, { type: BET.COME, amount: 10 });
|
||
const r = resolveRoll(setDice(s, [4, 4]));
|
||
ok('Come on 8: travels', r.moves.length === 1 && r.moves[0].to === 8 && r.state.players[0].bets[0].comePoint === 8);
|
||
s = r.state;
|
||
const cb = s.players[0].bets[0];
|
||
ok('Come on 8: is a contract bet', isContract(cb, s));
|
||
ok('Come on 8: cannot be taken down', removeBet(s, 0, cb.id) === s);
|
||
s = addOdds(s, 0, cb.id, 50);
|
||
ok('Come on 8: takes 5× odds', s.players[0].bets[0].oddsAmount === 50);
|
||
const win = oneRoll(s, [5, 3]).pay;
|
||
ok('Come 8 hits: flat + 6:5 odds', win.result === 'win' && win.winnings === 10 + 60);
|
||
// come-out: odds off
|
||
const co = { ...s, point: null, phase: 'comeout' };
|
||
const lose7 = oneRoll(co, [3, 4]).pay;
|
||
ok('Come 8 on a come-out 7: flat loses, odds returned', lose7.result === 'lose' && lose7.refund === 50 && lose7.delta === -10);
|
||
const hit8 = oneRoll(co, [4, 4]).pay;
|
||
ok('Come 8 hits on the come-out: flat paid, odds returned unpaid', hit8.result === 'win' && hit8.winnings === 10 && hit8.delta === 10);
|
||
// Don't Come
|
||
let dc = placeBet(table(5), 0, { type: BET.DONT_COME, amount: 10 });
|
||
dc = resolveRoll(setDice(dc, [2, 2])).state;
|
||
const dcb = dc.players[0].bets[0];
|
||
ok("Don't Come travels to 4", dcb.comePoint === 4 && !isContract(dcb, dc));
|
||
ok("Don't Come lay cap 6×", maxOddsFor(dcb, dc) === 60);
|
||
ok("Don't Come can be taken down", removeBet(dc, 0, dcb.id).players[0].bets.length === 0);
|
||
}
|
||
}
|
||
|
||
// ── 2. Exact house edges ─────────────────────────────────────────────────────
|
||
section('Exact house edges (Markov solve)');
|
||
{
|
||
const E = [
|
||
['Pass', withBet(null, { type: BET.PASS, amount: 10 }), 7 / 495 * 100],
|
||
// per decision: a barred 12 is no action, so the bet simply stands
|
||
["Don't Pass", withBet(null, { type: BET.DONT_PASS, amount: 10 }), 108 / 7700 * 100],
|
||
['Come', withBet('cp', { type: BET.COME, amount: 10 }), 7 / 495 * 100],
|
||
["Don't Come", withBet('cp', { type: BET.DONT_COME, amount: 10 }), 108 / 7700 * 100],
|
||
['Field', withBet(null, { type: BET.FIELD, amount: 10 }), 100 / 36],
|
||
['Place 6 $6', withBet(5, { type: BET.PLACE, number: 6, amount: 6 }), 100 / 66],
|
||
['Place 5 $5', withBet(6, { type: BET.PLACE, number: 5, amount: 5 }), 4],
|
||
['Place 4 $5', withBet(6, { type: BET.PLACE, number: 4, amount: 5 }), 100 / 15],
|
||
['Place 8 $6 from the come-out', withBet(null, { type: BET.PLACE, number: 8, amount: 6 }), 100 / 66],
|
||
['Buy 4 $20', withBet(6, { type: BET.BUY, number: 4, amount: 20 }), 5 / 3],
|
||
['Buy 5 $20', withBet(6, { type: BET.BUY, number: 5, amount: 20 }), 2],
|
||
['Buy 6 $20', withBet(5, { type: BET.BUY, number: 6, amount: 20 }), 25 / 11],
|
||
['Lay 4 $40', withBet(6, { type: BET.LAY, number: 4, amount: 40 }), 5 / 3],
|
||
['Lay 5 $30', withBet(6, { type: BET.LAY, number: 5, amount: 30 }), 2],
|
||
['Lay 6 $30', withBet(5, { type: BET.LAY, number: 6, amount: 30 }), 20 / 11],
|
||
['Big 6', withBet(5, { type: BET.BIG, number: 6, amount: 10 }), 100 / 11],
|
||
['Hard 6', withBet(5, { type: BET.HARD, number: 6, amount: 5 }), 100 / 11],
|
||
['Hard 4', withBet(5, { type: BET.HARD, number: 4, amount: 5 }), 100 / 9],
|
||
['Hard 10 from the come-out', withBet(null, { type: BET.HARD, number: 10, amount: 5 }), 100 / 9],
|
||
['Any 7', withBet(null, { type: BET.ANY7, amount: 5 }), 100 / 6],
|
||
['Any Craps', withBet(null, { type: BET.ANY_CRAPS, amount: 5 }), 100 / 9],
|
||
['Yo', withBet(null, { type: BET.YO, amount: 5 }), 100 / 9],
|
||
['Aces', withBet(null, { type: BET.ACES, amount: 5 }), 500 / 36],
|
||
['Ace-Deuce', withBet(null, { type: BET.ACE_DEUCE, amount: 5 }), 100 / 9],
|
||
['Boxcars', withBet(null, { type: BET.BOXCARS, amount: 5 }), 500 / 36],
|
||
['C&E $2', withBet(null, { type: BET.CE, amount: 2 }), 100 / 9],
|
||
['Horn $4', withBet(null, { type: BET.HORN, amount: 4 }), 12.5],
|
||
];
|
||
for (const [name, s, want] of E) {
|
||
const got = edgeOf(s);
|
||
ok(`${name}: edge ${want.toFixed(3)}%`, near(got, want, 1e-6), `got ${got.toFixed(6)}%`);
|
||
const b = s.players[0].bets[0];
|
||
const shown = houseEdge(b.type, b.number);
|
||
ok(`${name}: tooltip edge ${shown}% matches to 2dp`, shown != null && Math.abs(shown - want) < 0.006, `exact ${want.toFixed(4)}`);
|
||
}
|
||
// Odds are free: adding max odds to a Pass/Come on any point leaves EV unchanged.
|
||
for (const n of POINT_NUMBERS) {
|
||
const mult = n === 4 || n === 10 ? 3 : n === 5 || n === 9 ? 4 : 5;
|
||
const flat = withBet(n, { type: BET.PASS, amount: 10 });
|
||
const odds = withBet(n, { type: BET.PASS, amount: 10 }, { odds: 10 * mult });
|
||
ok(`Pass odds on ${n} are zero-edge`, near(exactEV(flat), exactEV(odds), 1e-9));
|
||
const dflat = withBet(n, { type: BET.DONT_PASS, amount: 10 });
|
||
const dodds = withBet(n, { type: BET.DONT_PASS, amount: 10 }, { odds: 60 });
|
||
ok(`Lay odds on ${n} are zero-edge`, near(exactEV(dflat), exactEV(dodds), 1e-9));
|
||
}
|
||
}
|
||
|
||
// ── 3. Placement, take-downs, working ────────────────────────────────────────
|
||
section('Placement / take-down / working rules');
|
||
{
|
||
let s = table(null, 100);
|
||
ok('Come is illegal on the come-out', placeBet(s, 0, { type: BET.COME, amount: 5 }) === s);
|
||
ok('Place needs a point number', placeBet(s, 0, { type: BET.PLACE, number: 7, amount: 5 }) === s);
|
||
ok('Hard needs 4/6/8/10', placeBet(s, 0, { type: BET.HARD, number: 5, amount: 5 }) === s);
|
||
ok('Big only 6/8', placeBet(s, 0, { type: BET.BIG, number: 4, amount: 5 }) === s);
|
||
ok('Cannot bet more than the bankroll', placeBet(s, 0, { type: BET.FIELD, amount: 101 }) === s);
|
||
s = placeBet(s, 0, { type: BET.PASS, amount: 10 });
|
||
s = placeBet(s, 0, { type: BET.PASS, amount: 5 });
|
||
ok('Repeat chips stack onto the same bet', s.players[0].bets.length === 1 && s.players[0].bets[0].amount === 15);
|
||
ok('Bankroll debited', s.players[0].chips === 85);
|
||
const pb = s.players[0].bets[0];
|
||
ok('Pass is not contract before the point', !isContract(pb, s));
|
||
const part = reduceBet(s, 0, pb.id, { amount: 5 });
|
||
ok('Undo a chip: reduceBet partial', part.players[0].bets[0].amount === 10 && part.players[0].chips === 90);
|
||
const off = removeBet(s, 0, pb.id);
|
||
ok('Pass can come down on the come-out', off.players[0].bets.length === 0 && off.players[0].chips === 100);
|
||
|
||
// Place bets: off on come-out, can be called on.
|
||
let p = placeBet(table(null, 100), 0, { type: BET.PLACE, number: 6, amount: 12 });
|
||
const plb = p.players[0].bets[0];
|
||
ok('Place is off on the come-out', !isWorking(plb, p));
|
||
p = setWorking(p, 0, plb.id, true);
|
||
ok('Place called on for the come-out', isWorking(p.players[0].bets[0], p));
|
||
const hit = oneRoll(p, [3, 3]).pay;
|
||
ok('Called-on Place 6 wins on a come-out 6', hit && hit.result === 'win' && hit.winnings === 14);
|
||
const after = oneRoll(p, [3, 3]).next;
|
||
ok('A point resets the called-on flag', after.point === 6 && after.players[0].bets[0].onComeOut === false);
|
||
ok('Winning place stays up, stake not returned', after.players[0].chips === 100 - 12 + 14 && after.players[0].bets[0].amount === 12);
|
||
const pt = table(5, 100);
|
||
const pp = placeBet(pt, 0, { type: BET.PLACE, number: 6, amount: 12 });
|
||
ok('setWorking only during the come-out', setWorking(pp, 0, pp.players[0].bets[0].id, false) === pp);
|
||
|
||
// Contract Pass after the point.
|
||
let c = placeBet(table(null, 100), 0, { type: BET.PASS, amount: 10 });
|
||
c = resolveRoll(setDice(c, [2, 2])).state;
|
||
const cb = c.players[0].bets[0];
|
||
ok('Pass is contract once the point is set', isContract(cb, c) && removeBet(c, 0, cb.id) === c);
|
||
c = addOdds(c, 0, cb.id, 30);
|
||
ok('oddsRoom is 0 at the cap', oddsRoom(c, 0, cb.id) === 0);
|
||
const oddsOff = reduceBet(c, 0, cb.id, { part: 'odds' });
|
||
ok('Odds can always come down', oddsOff.players[0].bets[0].oddsAmount === 0 && oddsOff.players[0].chips === c.players[0].chips + 30);
|
||
const cleared = refundBets(c, 0);
|
||
ok('Clear leaves contract bets', cleared.players[0].bets.length === 1);
|
||
const left = refundBets(c, 0, { force: true });
|
||
ok('Leaving refunds everything', left.players[0].bets.length === 0 && left.players[0].chips === 100);
|
||
// Shrinking a Don't flat trims laid odds above the new cap.
|
||
let dd = placeBet(table(null, 500), 0, { type: BET.DONT_PASS, amount: 20 });
|
||
dd = resolveRoll(setDice(dd, [2, 2])).state;
|
||
const ddb = dd.players[0].bets[0];
|
||
dd = addOdds(dd, 0, ddb.id, 120);
|
||
const dd2 = reduceBet(dd, 0, ddb.id, { amount: 10 });
|
||
ok("Shrinking a Don't flat returns excess odds", dd2.players[0].bets[0].oddsAmount === 60 && dd2.players[0].chips === dd.players[0].chips + 10 + 60);
|
||
|
||
// Stickman always has something to say.
|
||
let calls = 0;
|
||
for (const point of [null, 4, 6, 9]) {
|
||
for (const d of ALL_DICE) {
|
||
const r = resolveRoll(setDice(table(point), d));
|
||
if (typeof stickCall(r, point) === 'string' && stickCall(r, point).length > 0) calls++;
|
||
}
|
||
}
|
||
ok('stickCall covers every roll', calls === 4 * 36);
|
||
|
||
// Every decision on every bet gets a plain-English reason and a name.
|
||
let explained = 0, blank = 0;
|
||
for (const point of [null, 4, 5, 6, 8, 9, 10]) {
|
||
for (const z of Object.values(ZONES)) {
|
||
if (z.type === 'odds') continue;
|
||
const s0 = table(point);
|
||
s0.players[0].bets.push({ id: 1, type: z.type, number: z.number ?? null, comePoint: null, amount: 20, oddsAmount: 0, onComeOut: true });
|
||
const moved = table(point);
|
||
if (z.type === BET.COME || z.type === BET.DONT_COME) moved.players[0].bets.push({ id: 2, type: z.type, number: null, comePoint: 6, amount: 20, oddsAmount: 20, onComeOut: false });
|
||
for (const d of ALL_DICE) {
|
||
for (const [st, unmoved] of [[s0, true], [moved, false]]) {
|
||
const r = resolveRoll(setDice(st, d));
|
||
for (const p of r.payouts) {
|
||
const why = explainPayout(p, { dice: d, prevPoint: point, unmoved: unmoved && p.betId === 1 });
|
||
const name = betLabel(p.betType, p.number);
|
||
if (!why || !name || /undefined|null|NaN/.test(why + name)) { blank++; if (blank < 4) ok(`explain ${p.betType} ${d}`, false, `${name}: ${why}`); }
|
||
else explained++;
|
||
}
|
||
for (const m of r.moves) if (!explainMove(m).includes(String(m.to))) blank++;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
ok(`every decision explained (${explained})`, blank === 0 && explained > 3000, `${blank} blank`);
|
||
const ex = (type, number, result, dice, prevPoint, extra = {}) => explainPayout({ betType: type, number, result, commission: 0, refund: 0, kept: false, ...extra }, { dice, prevPoint, ...extra });
|
||
ok('Field loss says why', ex(BET.FIELD, null, 'lose', [5, 3], 6) === "8 isn't a Field number");
|
||
ok('Hard way lost to the easy way', ex(BET.HARD, 8, 'lose', [5, 3], 6) === '8 came easy (5-3)');
|
||
ok('Seven-out named', ex(BET.PLACE, 6, 'lose', [3, 4], 9) === 'Seven-out before the 6');
|
||
ok('Point made named', ex(BET.PASS, null, 'win', [4, 2], 6) === 'Point 6 made');
|
||
ok('Come natural on its own come-out', ex(BET.COME, null, 'win', [5, 6], 8, { unmoved: true }) === 'Natural 11 on the Come');
|
||
ok('Buy vig noted', ex(BET.BUY, 4, 'win', [2, 2], 8, { commission: 1, kept: true }) === 'The 4 rolled · stays up · $1 vig');
|
||
ok('Come odds returned noted', ex(BET.COME, 8, 'lose', [3, 4], null, { refund: 40 }).includes('odds returned'));
|
||
for (const type of Object.values(BET)) {
|
||
const nums = NUMBERED[type] ?? [null];
|
||
for (const n of nums) ok(`${type}${n ?? ''} has a pays label`, paysLabel(type, n).length > 0);
|
||
}
|
||
}
|
||
|
||
// ── 4. Seeded AI soak: chip conservation ─────────────────────────────────────
|
||
section('AI soak (chip conservation, 6 bots × 20k rolls)');
|
||
{
|
||
const rng = mulberry32(20261124);
|
||
// names chosen so all four AI personalities play
|
||
const opps = ['ava', 'ben', 'cara', 'eli', 'ivy', 'kai'].map((id) => ({ id, name: id }));
|
||
let s = createInitialState(opps, 2000, 'Human');
|
||
s.players[0].isAI = true;
|
||
let violations = 0, rolls = 0, sevenOuts = 0, points = 0, propHits = 0;
|
||
const seen = new Set();
|
||
for (let i = 0; i < 20000; i++) {
|
||
for (let pi = 0; pi < s.players.length; pi++) {
|
||
if (s.players[pi].chips + totalAtRisk(s.players[pi]) < 50) s.players[pi].chips += 2000; // rebuy
|
||
for (const spec of chooseBets(s.players[pi], s, rng)) s = placeBet(s, pi, spec);
|
||
for (const o of chooseOdds(s.players[pi], s)) s = addOdds(s, pi, o.betId, o.amount);
|
||
}
|
||
for (const p of s.players) for (const b of p.bets) {
|
||
seen.add(b.type);
|
||
if (b.amount <= 0 || b.oddsAmount < 0 || b.oddsAmount > Math.max(0, maxOddsFor(b, s))) violations++;
|
||
}
|
||
const before = s.players.map((p) => p.chips + totalAtRisk(p));
|
||
s = clearLastDeltas(rollDice(s, rng));
|
||
const r = resolveRoll(s);
|
||
s = r.state;
|
||
rolls++;
|
||
if (r.sevenOut) sevenOuts++;
|
||
if (r.pointEstablished) points++;
|
||
propHits += r.payouts.filter((p) => ONE_ROLL.has(p.betType) && p.result === 'win').length;
|
||
s.players.forEach((p, pi) => {
|
||
const after = p.chips + totalAtRisk(p);
|
||
if (after - before[pi] !== p.lastDelta) violations++;
|
||
if (p.chips < 0) violations++;
|
||
});
|
||
}
|
||
ok('no conservation / cap violations', violations === 0, `${violations}`);
|
||
ok('shooter rotated', sevenOuts > 1000, `${sevenOuts}`);
|
||
ok('points were set', points > 2000, `${points}`);
|
||
ok('props got hit', propHits > 50, `${propHits}`);
|
||
for (const t of [BET.PASS, BET.DONT_PASS, BET.COME, BET.DONT_COME, BET.FIELD, BET.PLACE, BET.HARD, BET.LAY, BET.CE, BET.YO, BET.ANY_CRAPS]) {
|
||
ok(`AI uses ${t}`, seen.has(t));
|
||
}
|
||
}
|
||
|
||
// ── 5. Source lint ───────────────────────────────────────────────────────────
|
||
section('Source lint');
|
||
{
|
||
const logic = readFileSync(new URL('../src/games/craps/CrapsLogic.js', import.meta.url), 'utf8');
|
||
ok('logic is Phaser-free', !/from 'phaser'/.test(logic));
|
||
for (const f of ['CrapsTable.js', 'CrapsDice.js', 'CrapsAI.js']) {
|
||
const src = readFileSync(new URL(`../src/games/craps/${f}`, import.meta.url), 'utf8');
|
||
ok(`${f} is Phaser-free`, !/from 'phaser'/.test(src));
|
||
}
|
||
const game = readFileSync(new URL('../src/games/craps/CrapsGame.js', import.meta.url), 'utf8');
|
||
ok('no hand-built Rectangle hit areas', !/new Phaser\.Geom\.Rectangle\(/.test(game));
|
||
ok('no setInteractive on containers', !/add\.container\([^)]*\)[^;]*setInteractive/.test(game));
|
||
ok('felt clicks go through table-space hit-testing', /hitZone\(x, y\)/.test(game));
|
||
ok('uses the shared dock + chip stacks', /new CasinoDock\(/.test(game) && /makeChipStack\(/.test(game));
|
||
}
|
||
|
||
|
||
// ── 6. Table geometry ────────────────────────────────────────────────────────
|
||
section('Table geometry');
|
||
{
|
||
const inRect = (pt, r, eps = 1e-9) => pt.u >= r.u0 - eps && pt.u <= r.u1 + eps && pt.v >= r.v0 - eps && pt.v <= r.v1 + eps;
|
||
const all = Object.values(ZONES).flatMap((z) => z.rects.map((r) => ({ key: z.key, r })));
|
||
for (const { key, r } of all) {
|
||
const corners = [[r.u0, r.v0], [r.u1, r.v0], [r.u0, r.v1], [r.u1, r.v1]];
|
||
ok(`${key}: on the felt`, corners.every(([u, v]) => inTub(u, v)));
|
||
ok(`${key}: not hidden under the near rail`, r.v1 <= NEAR_VISIBLE_V);
|
||
const c = { u: (r.u0 + r.u1) / 2, v: (r.v0 + r.v1) / 2 };
|
||
ok(`${key}: centre hit-tests to itself`, hitZoneUV(c.u, c.v) === key, hitZoneUV(c.u, c.v));
|
||
const a = P.project(r.u0, r.v0), b = P.project(r.u1, r.v1);
|
||
ok(`${key}: big enough to click (≥ 24px)`, Math.abs(b.x - a.x) >= 24 && Math.abs(b.y - a.y) >= 20, `${(b.x - a.x).toFixed(0)}×${(b.y - a.y).toFixed(0)}`);
|
||
}
|
||
let overlaps = 0;
|
||
for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {
|
||
const A = all[i].r, B = all[j].r;
|
||
const ou = Math.min(A.u1, B.u1) - Math.max(A.u0, B.u0), ov = Math.min(A.v1, B.v1) - Math.max(A.v0, B.v0);
|
||
if (ou > 1e-6 && ov > 1e-6 && all[i].key !== all[j].key) { overlaps++; ok(`${all[i].key} ∩ ${all[j].key}`, false); }
|
||
}
|
||
ok('no two zones overlap', overlaps === 0);
|
||
// Every bet type maps to a zone the player can click.
|
||
for (const type of Object.values(BET)) {
|
||
for (const n of NUMBERED[type] ?? [null]) ok(`${type}${n ?? ''} has a zone`, !!zoneKeyFor(type, n));
|
||
}
|
||
|
||
// Lane spots sit inside their zone, for every seat / crowding.
|
||
const laneZone = (k) => {
|
||
if (k.startsWith('comept')) return ZONES[`place${k.slice(6)}`];
|
||
return ZONES[k];
|
||
};
|
||
for (const [k, L] of Object.entries(LANES)) {
|
||
const z = laneZone(k);
|
||
ok(`lane ${k} has a zone`, !!z);
|
||
if (!z) continue;
|
||
const pts = [];
|
||
if (L.kind === 'flow') for (let n = 1; n <= 7; n++) for (let i = 0; i < n; i++) pts.push(laneSpot(k, { index: i, count: n }));
|
||
else for (const seat of SLOT_ORDER) pts.push(laneSpot(k, { seat }));
|
||
ok(`lane ${k}: every spot inside ${z.key}`, pts.every((p) => z.rects.some((r) => inRect(p, r))));
|
||
}
|
||
// Seat-fixed lanes give each seat its own spot.
|
||
for (const k of ['pass', 'field', 'come', 'dontpass', 'odds', 'ce']) {
|
||
const keys = new Set(SLOT_ORDER.map((seat) => JSON.stringify(laneSpot(k, { seat }))));
|
||
ok(`lane ${k}: 7 distinct seat spots`, keys.size === 7);
|
||
}
|
||
// Bets → lanes
|
||
const sample = [
|
||
{ type: 'pass' }, { type: 'dontpass' }, { type: 'come' }, { type: 'come', comePoint: 9 }, { type: 'dontcome' },
|
||
{ type: 'dontcome', comePoint: 4 }, { type: 'field' }, { type: 'place', number: 6 }, { type: 'buy', number: 10 },
|
||
{ type: 'lay', number: 5 }, { type: 'big', number: 8 }, { type: 'hard', number: 4 }, { type: 'any7' }, { type: 'horn' },
|
||
{ type: 'ce' }, { type: 'yo' }, { type: 'aces' }, { type: 'acedeuce' }, { type: 'boxcars' }, { type: 'anycraps' },
|
||
];
|
||
for (const b of sample) ok(`${b.type}${b.number ?? b.comePoint ?? ''} has a lane`, !!LANES[laneForBet(b)]);
|
||
|
||
// Seats
|
||
ok('seat names: human first, fill order after', seatNames(6).join() === ['H', ...FILL_ORDER].join());
|
||
const portraits = seatNames(6).slice(1).map((n) => ({ n, ...seatPortrait(n) }));
|
||
for (const p of portraits) {
|
||
ok(`${p.n}: portrait on screen`, p.x - p.r >= 0 && p.x + p.r <= 1920 && p.y - p.r >= 0);
|
||
ok(`${p.n}: portrait clear of the dock`, p.y + p.r + 22 <= DOCK.y, `${p.y + p.r}`);
|
||
ok(`${p.n}: portrait clear of the history board`, p.x + p.r < BOARD.x || p.y - p.r > BOARD.y + BOARD.h);
|
||
ok(`${p.n}: portrait clear of the Leave button`, !(p.x - p.r < 160 && p.y - p.r < 72));
|
||
}
|
||
for (let i = 0; i < portraits.length; i++) for (let j = i + 1; j < portraits.length; j++) {
|
||
const a = portraits[i], b = portraits[j];
|
||
ok(`${a.n}/${b.n}: portraits don't overlap`, Math.hypot(a.x - b.x, a.y - b.y) > a.r + b.r + 60);
|
||
}
|
||
for (const n of Object.keys(SEATS)) {
|
||
const { u, v } = railUV(n);
|
||
ok(`${n}: chips sit on the rail, not the felt`, !inTub(u, v) && inTub(u, v, TUB.RW));
|
||
const r = railPose(n);
|
||
ok(`${n}: rail stack on screen`, r.x > 20 && r.x < 1900 && r.y > 60 && r.y < DOCK.y);
|
||
const o = throwOrigin(n);
|
||
ok(`${n}: throw starts over the felt`, inTub(o.u, o.v));
|
||
}
|
||
// Furniture
|
||
for (let i = 0; i < 5; i++) {
|
||
const o = offerSpot(i);
|
||
ok(`offer die ${i} on visible felt, below the prop box`, inTub(o.u, o.v) && o.v <= NEAR_VISIBLE_V && o.v > PROP.v1 && !hitZoneUV(o.u, o.v));
|
||
}
|
||
for (const n of BOX_NUMS) ok(`puck ON spot inside place${n}`, ZONES[`place${n}`].rects.some((r) => inRect(puckOnUV(n), r)));
|
||
ok('puck OFF spot inside the Don\'t Come box', ZONES.dontcome.rects.some((r) => inRect(puckOffUV(), r)));
|
||
ok('board on screen', BOARD.x + BOARD.w <= 1920 && BOARD.y >= 0);
|
||
{
|
||
const inCard = (p, pad = 0) => p.x > RESULT.x - pad && p.x < RESULT.x + RESULT.w + pad && p.y > RESULT.y - pad && p.y < RESULT.y + RESULT.h + pad;
|
||
ok('results card on screen, above the dock', RESULT.x + RESULT.w <= 1920 && RESULT.y + RESULT.h <= DOCK.y - 4);
|
||
ok('results card clear of the history board', RESULT.y > BOARD.y + BOARD.h);
|
||
const L = LANDING;
|
||
ok('landing area clear of the results card', [[L.u0, L.v0], [L.u1, L.v0], [L.u1, L.v1], [L.u0, L.v1]].every(([u, v]) => !inCard(P.project(u, v))));
|
||
for (const z of Object.values(ZONES)) for (const r of z.rects) {
|
||
ok(`${z.key} clear of the results card`, [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]].every(([u, v]) => !inCard(P.project(u, v))));
|
||
}
|
||
for (let i = 0; i < 5; i++) ok(`offer die ${i} clear of the results card`, !inCard(P.project(offerSpot(i).u, offerSpot(i).v), 24));
|
||
for (const n of seatNames(6).slice(1)) { const p = seatPortrait(n); ok(`${n} portrait clear of the results card`, !inCard(p, p.r)); }
|
||
}
|
||
ok('board below the music player (top ~76px on the right)', BOARD.y >= 80);
|
||
{
|
||
// right rail's outer edge where the board's bottom-left corner sits
|
||
let near = null;
|
||
for (let v = -0.1; v <= 1.1; v += 0.001) {
|
||
const p = lift(1 + TUB.RW, v, TUB.H);
|
||
if (!near || Math.abs(p.y - (BOARD.y + BOARD.h)) < Math.abs(near.y - (BOARD.y + BOARD.h))) near = p;
|
||
}
|
||
ok('board clear of the right rail', BOARD.x - near.x >= 8, `${(BOARD.x - near.x).toFixed(0)}px`);
|
||
}
|
||
{
|
||
const c0 = CALL.x - CALL.maxW / 2, c1 = CALL.x + CALL.maxW / 2;
|
||
ok('stickman banner clear of the history board', c1 < BOARD.x);
|
||
for (const n of ['F1', 'F2', 'F3']) {
|
||
const p = seatPortrait(n);
|
||
const plateEnd = p.x + p.r + 12 + 120; // name / bankroll plate to the right
|
||
ok(`stickman banner clear of ${n}'s plate`, plateEnd < c0 || p.x - p.r > c1, `${plateEnd.toFixed(0)} vs ${c0}`);
|
||
}
|
||
}
|
||
ok('landing area on the felt', inTub(LANDING.u0, LANDING.v0) && inTub(LANDING.u1, LANDING.v1));
|
||
}
|
||
|
||
// ── 7. Dice throws ───────────────────────────────────────────────────────────
|
||
section('Dice throws (300 seeded throws)');
|
||
{
|
||
const rng = mulberry32(777);
|
||
let wrongFace = 0, outside = 0, close = 0, noWall = 0, maxDur = 0, maxTries = 0, underCard = 0;
|
||
for (let i = 0; i < 300; i++) {
|
||
const seat = seatNames(6)[i % 7];
|
||
const faces = [1 + (i % 6), 1 + ((i * 5 + 2) % 6)];
|
||
const plan = simulateThrow(throwOrigin(seat), faces, rng);
|
||
maxDur = Math.max(maxDur, plan.duration);
|
||
maxTries = Math.max(maxTries, plan.tries);
|
||
plan.dice.forEach((d, k) => {
|
||
const last = d.frames[d.frames.length - 1];
|
||
if (topFace(last.q) !== faces[k]) wrongFace++;
|
||
if (!(last.u >= LANDING.u0 - 0.04 && last.u <= LANDING.u1 && last.v >= LANDING.v0 && last.v <= LANDING.v1)) outside++;
|
||
const sp = P.project(last.u, last.v);
|
||
if (sp.x > RESULT.x - 24 && sp.y > RESULT.y - 12) underCard++;
|
||
if (!d.hitWall) noWall++;
|
||
if (!d.frames.every((f) => inTub(f.u, f.v) && f.h >= 0 && Number.isFinite(f.u))) outside++;
|
||
});
|
||
const [a, b] = plan.dice.map((d) => d.frames[d.frames.length - 1]);
|
||
if (Math.hypot((a.u - b.u) * VIEW.halfW, (a.v - b.v) * VIEW.halfW * 4 / 3) < DIE.size * 1.2) close++;
|
||
}
|
||
ok('every die lands showing the rolled number', wrongFace === 0, `${wrongFace}`);
|
||
ok('dice stay in the tub and land in the landing area', outside === 0, `${outside}`);
|
||
ok('every die hits the back wall', noWall === 0, `${noWall}`);
|
||
ok('no die comes to rest under the results card', underCard === 0, `${underCard}`);
|
||
ok('dice never come to rest on top of each other', close === 0, `${close}`);
|
||
ok('throws last under 3.6 s', maxDur < 3.6, maxDur.toFixed(2));
|
||
for (let f = 1; f <= 6; f++) ok(`restingQ shows ${f}`, topFace(restingQ(f, f * 0.7)) === f);
|
||
}
|
||
|
||
console.log(`\n${pass} passed, ${fail} failed`);
|
||
process.exit(fail ? 1 : 0);
|