Redesign Hold'em table with casino oval art and proper betting rules
- New baked table art (HoldemArt.js) on a shared perspective kit (CasinoGeometry.makeProjection), plus layout solver in HoldemTable.js that fits cards, stacks, bets and buttons around the felt without overlap - Correct min-raise tracking via lastRaiseSize; pot odds now include current street's bets - All-in runouts: when nobody can act, deal the board out with live equity pills instead of stalling on a single actor - Side-pot logic fixed so players who bust in the hand still claim their share; action skips all-in seats - New HoldemShowdown.js helpers (bestFive, equity, hand labels, raise presets, finishing places) and headless test suite tools/verifyHoldem.js - Rebuilt UI: casino dock with pre-action toggles, bet slider + pot-size presets, tournament panel, TV-style showdown with card glow, busted watch/skip flow, and cash-out confirmation on leave
This commit is contained in:
parent
a103c9ed74
commit
d33ab09ae0
|
|
@ -46,7 +46,9 @@ function handStrength(player, community) {
|
|||
function potOdds(state, seat) {
|
||||
const toCall = callAmount(state, seat);
|
||||
if (toCall === 0) return 1; // free to check
|
||||
return toCall / (state.pot + toCall);
|
||||
// Everything already in the middle this hand: the pot plus this street's bets.
|
||||
const inMiddle = state.pot + state.players.reduce((sum, p) => sum + (p.bet ?? 0), 0);
|
||||
return toCall / (inMiddle + toCall);
|
||||
}
|
||||
|
||||
export function chooseAction(state, seat) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,253 @@
|
|||
// Texas Hold 'Em table art — a casino poker-room oval baked once into 'he-table':
|
||||
// floor shadow, padded rail with a visible front face, wooden racetrack, lit
|
||||
// poker-green felt with a printed betting line, board outlines and lettering,
|
||||
// and the dealer's chip rack + nameplate at the far side.
|
||||
|
||||
import { prepareCasinoArt, canvas, rr, poly, mix, lerp, noisePattern } from '../../ui/casino/CasinoArt.js';
|
||||
import { CHIP_DEFS } from '../../ui/CasinoChips.js';
|
||||
import {
|
||||
P, VIEW, rim, rimPoints, communityPose, dealerSpot, DEALER_PLATE,
|
||||
FELT_K, WOOD_K, RAIL_K, RAIL_FACE_PX, RING_K, CARD_W, CARD_H,
|
||||
} from './HoldemTable.js';
|
||||
|
||||
const W = 1920, H = 1080;
|
||||
const FELT = '#0f5a33';
|
||||
export const TEXT_K = 0.345; // felt lettering sits on this rim fraction (bottom arc)
|
||||
const LEATHER_DARK = '#0f0806', LEATHER_MID = '#2c1a12', LEATHER_HI = '#5e3e2b';
|
||||
|
||||
function bandPath(ctx, k0, k1) {
|
||||
const outer = rimPoints(k1, 200), inner = rimPoints(k0, 200);
|
||||
ctx.beginPath();
|
||||
outer.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
|
||||
ctx.closePath();
|
||||
inner.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
function ring(ctx, k, width, color) {
|
||||
poly(ctx, rimPoints(k, 200));
|
||||
ctx.lineWidth = width;
|
||||
ctx.strokeStyle = color;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Text along the rim curve at scale k, centred on the bottom (φ = 0).
|
||||
function rimText(ctx, text, k, size, color, { bold = false, alpha = 1, spacing = 1 } = {}) {
|
||||
ctx.font = `${bold ? 'bold ' : ''}${size}px "Julius Sans One", sans-serif`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
const pxPerDeg = Math.hypot(rim(0.5, k).x - rim(-0.5, k).x, rim(0.5, k).y - rim(-0.5, k).y);
|
||||
const widths = [...text].map(ch => ctx.measureText(ch).width * spacing);
|
||||
const totalDeg = widths.reduce((a, b) => a + b, 0) / pxPerDeg;
|
||||
let deg = -totalDeg / 2;
|
||||
const s0 = rim(0, k).s;
|
||||
ctx.save();
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.fillStyle = color;
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.35)';
|
||||
ctx.shadowBlur = 2;
|
||||
ctx.shadowOffsetY = 1;
|
||||
[...text].forEach((ch, i) => {
|
||||
const mid = deg + widths[i] / 2 / pxPerDeg;
|
||||
deg += widths[i] / pxPerDeg;
|
||||
if (ch === ' ') return;
|
||||
const p = rim(mid, k), a = rim(mid - 0.4, k), b = rim(mid + 0.4, k);
|
||||
ctx.save();
|
||||
ctx.translate(p.x, p.y);
|
||||
ctx.rotate(Math.atan2(b.y - a.y, b.x - a.x));
|
||||
const sc = p.s / s0;
|
||||
ctx.scale(sc, sc * VIEW.squash);
|
||||
ctx.fillText(ch, 0, 0);
|
||||
ctx.restore();
|
||||
});
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawShadow(ctx) {
|
||||
const OFF = 6000;
|
||||
const pts = rimPoints(RAIL_K, 160).map(p => ({ x: p.x - OFF, y: p.y + RAIL_FACE_PX * p.s }));
|
||||
ctx.save();
|
||||
ctx.shadowColor = 'rgba(0,0,0,0.7)';
|
||||
ctx.shadowBlur = 60;
|
||||
ctx.shadowOffsetX = OFF;
|
||||
ctx.shadowOffsetY = 26;
|
||||
poly(ctx, pts);
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawRailFace(ctx) {
|
||||
const top = rimPoints(RAIL_K, 200);
|
||||
const shifted = top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s }));
|
||||
// union of the outline and its shifted copy = the visible side of the rail
|
||||
ctx.save();
|
||||
poly(ctx, shifted);
|
||||
ctx.fillStyle = LEATHER_DARK;
|
||||
ctx.fill();
|
||||
for (let i = 0; i <= 12; i++) {
|
||||
const f = i / 12;
|
||||
poly(ctx, top.map(p => ({ x: p.x, y: p.y + RAIL_FACE_PX * p.s * f })));
|
||||
ctx.lineWidth = 4;
|
||||
ctx.strokeStyle = mix(LEATHER_MID, LEATHER_DARK, Math.min(1, f * 1.25));
|
||||
ctx.stroke();
|
||||
}
|
||||
poly(ctx, shifted);
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.8)';
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function railColor(f) {
|
||||
const ridge = Math.max(0, Math.cos((f - 0.42) * Math.PI * 1.05));
|
||||
return ridge > 0.72 ? mix(LEATHER_MID, LEATHER_HI, (ridge - 0.72) / 0.28) : mix(LEATHER_DARK, LEATHER_MID, Math.min(1, ridge * 1.4));
|
||||
}
|
||||
|
||||
function drawRail(ctx) {
|
||||
ctx.save();
|
||||
bandPath(ctx, WOOD_K, RAIL_K);
|
||||
ctx.fillStyle = LEATHER_MID;
|
||||
ctx.fill('evenodd');
|
||||
ctx.clip('evenodd');
|
||||
for (let i = 0; i <= 26; i++) ring(ctx, lerp(WOOD_K, RAIL_K, i / 26), 6, railColor(i / 26));
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 26);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ring(ctx, lerp(WOOD_K, RAIL_K, 0.4), 3, 'rgba(255,230,200,0.13)');
|
||||
ctx.setLineDash([7, 5]);
|
||||
ring(ctx, lerp(WOOD_K, RAIL_K, 0.1), 1.5, 'rgba(214,174,120,0.42)');
|
||||
ring(ctx, lerp(WOOD_K, RAIL_K, 0.9), 1.5, 'rgba(214,174,120,0.42)');
|
||||
ctx.setLineDash([]);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawWood(ctx) {
|
||||
ctx.save();
|
||||
bandPath(ctx, FELT_K, WOOD_K);
|
||||
ctx.fillStyle = '#7a4520';
|
||||
ctx.fill('evenodd');
|
||||
ctx.clip('evenodd');
|
||||
for (let i = 0; i <= 10; i++) {
|
||||
const f = i / 10;
|
||||
ring(ctx, lerp(FELT_K, WOOD_K, f), 4, mix('#5a3216', '#a8692f', Math.sin(f * Math.PI)));
|
||||
}
|
||||
ctx.fillStyle = noisePattern(ctx, 128, 16);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.restore();
|
||||
ring(ctx, WOOD_K, 1.5, 'rgba(0,0,0,0.5)');
|
||||
ring(ctx, FELT_K, 1.5, 'rgba(0,0,0,0.6)');
|
||||
}
|
||||
|
||||
function drawFelt(ctx) {
|
||||
ctx.save();
|
||||
poly(ctx, rimPoints(FELT_K, 200));
|
||||
ctx.clip();
|
||||
ctx.fillStyle = FELT;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
ctx.fillStyle = noisePattern(ctx, 256, 22);
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
|
||||
// printed betting line
|
||||
ring(ctx, RING_K, 3, 'rgba(217,180,90,0.7)');
|
||||
ring(ctx, RING_K - 0.017, 1, 'rgba(217,180,90,0.35)');
|
||||
|
||||
// board outlines
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const c = communityPose(i);
|
||||
ctx.save();
|
||||
ctx.translate(c.x, c.y);
|
||||
ctx.scale(c.s, c.s * VIEW.squash);
|
||||
rr(ctx, -CARD_W / 2 - 5, -CARD_H / 2 - 5, CARD_W + 10, CARD_H + 10, 10);
|
||||
ctx.lineWidth = 2 / c.s;
|
||||
ctx.strokeStyle = 'rgba(242,234,216,0.28)';
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
rimText(ctx, "NO LIMIT TEXAS HOLD 'EM", TEXT_K, 28, '#e8c15a', { bold: true, alpha: 0.92, spacing: 1.06 });
|
||||
|
||||
const c = P.project(0, 0.5);
|
||||
const lamp = ctx.createRadialGradient(c.x, c.y, 40, c.x, c.y, 900);
|
||||
lamp.addColorStop(0, 'rgba(255,248,210,0.20)');
|
||||
lamp.addColorStop(0.45, 'rgba(255,248,210,0.07)');
|
||||
lamp.addColorStop(1, 'rgba(255,248,210,0)');
|
||||
ctx.fillStyle = lamp;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
const vig = ctx.createRadialGradient(c.x, c.y, 360, c.x, c.y, 1000);
|
||||
vig.addColorStop(0, 'rgba(0,0,0,0)');
|
||||
vig.addColorStop(1, 'rgba(0,0,0,0.5)');
|
||||
ctx.fillStyle = vig;
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
for (let i = 0; i < 10; i++) ring(ctx, FELT_K - i * 0.005, 4, `rgba(0,0,0,${0.32 * (1 - i / 10)})`);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// Dealer side: a chip rack set into the rail and a brass nameplate.
|
||||
function drawDealer(ctx) {
|
||||
const top = rim(180, (WOOD_K + RAIL_K) / 2);
|
||||
const w = 300, h = 30, x0 = top.x - w / 2, y0 = top.y - h / 2;
|
||||
rr(ctx, x0 - 6, y0 - 5, w + 12, h + 10, 8);
|
||||
ctx.fillStyle = '#17110c';
|
||||
ctx.fill();
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'rgba(214,174,120,0.55)';
|
||||
ctx.stroke();
|
||||
const cols = [1, 5, 5, 25, 25, 50, 100, 100, 50, 25, 25, 5, 5, 1];
|
||||
const cw = w / cols.length;
|
||||
cols.forEach((d, i) => {
|
||||
const def = CHIP_DEFS[d];
|
||||
for (let k = 0; k < 6; k++) {
|
||||
ctx.fillStyle = k % 2 ? def.base : mix(def.base, '#000000', 0.18);
|
||||
ctx.fillRect(x0 + i * cw + 1, y0 + k * (h / 6), cw - 2, h / 6 - 0.6);
|
||||
}
|
||||
const g = ctx.createLinearGradient(x0 + i * cw, 0, x0 + (i + 1) * cw, 0);
|
||||
g.addColorStop(0, 'rgba(0,0,0,0.5)');
|
||||
g.addColorStop(0.4, 'rgba(255,255,255,0.18)');
|
||||
g.addColorStop(1, 'rgba(0,0,0,0.5)');
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(x0 + i * cw + 1, y0, cw - 2, h);
|
||||
});
|
||||
|
||||
const { x, y } = DEALER_PLATE;
|
||||
rr(ctx, x - 92, y - 18, 184, 36, 8);
|
||||
const pg = ctx.createLinearGradient(0, y - 18, 0, y + 18);
|
||||
pg.addColorStop(0, '#e9c46a');
|
||||
pg.addColorStop(1, '#9a7420');
|
||||
ctx.fillStyle = pg;
|
||||
ctx.fill();
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = '#5c4210';
|
||||
ctx.stroke();
|
||||
ctx.font = 'bold 18px "Julius Sans One", sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillStyle = '#2a1c06';
|
||||
ctx.fillText('DEALER', x, y + 1);
|
||||
|
||||
// a faint dealer's work area on the felt (deck + muck)
|
||||
const d = dealerSpot();
|
||||
ctx.save();
|
||||
ctx.translate(d.x, d.y);
|
||||
ctx.scale(d.s, d.s * VIEW.squash);
|
||||
rr(ctx, -120, -50, 240, 100, 16);
|
||||
ctx.setLineDash([8, 6]);
|
||||
ctx.lineWidth = 2 / d.s;
|
||||
ctx.strokeStyle = 'rgba(242,234,216,0.18)';
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
export async function prepareHoldemArt(scene) {
|
||||
await prepareCasinoArt(scene);
|
||||
if (scene.textures.exists('he-table')) return;
|
||||
const c = canvas(W, H);
|
||||
const ctx = c.getContext('2d');
|
||||
drawShadow(ctx);
|
||||
drawRailFace(ctx);
|
||||
drawRail(ctx);
|
||||
drawWood(ctx);
|
||||
drawFelt(ctx);
|
||||
drawDealer(ctx);
|
||||
scene.textures.addCanvas('he-table', c);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -14,7 +14,7 @@ export const BLIND_LEVELS = [
|
|||
{ level: 10, small: 400, big: 800 },
|
||||
];
|
||||
|
||||
const LEVEL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
export const LEVEL_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
export function getBlindLevel(elapsedMs) {
|
||||
const idx = Math.min(
|
||||
|
|
@ -129,7 +129,9 @@ export function compareHands(a, b) {
|
|||
// after bets have been swept into state.pot by collectBets.
|
||||
// Returns array of { amount, eligibleSeats[] } ordered smallest to largest.
|
||||
function buildPotsFromTotals(allPlayers) {
|
||||
const live = allPlayers.filter((p) => !p.eliminated && p.totalBet > 0);
|
||||
// Anyone who put chips in this hand counts — including a player who busted
|
||||
// in it (earlier busts have totalBet 0 and are folded, so they drop out).
|
||||
const live = allPlayers.filter((p) => p.totalBet > 0);
|
||||
if (live.length === 0) return [];
|
||||
|
||||
const allInLevels = [...new Set(
|
||||
|
|
@ -168,6 +170,9 @@ function buildPotsFromTotals(allPlayers) {
|
|||
return pots;
|
||||
}
|
||||
|
||||
// Public alias for UI: pots (main + side) from cumulative hand contributions.
|
||||
export const potsFromTotals = buildPotsFromTotals;
|
||||
|
||||
// Legacy helper used for UI side-pot display during active betting rounds.
|
||||
// Uses current-round p.bet values (only valid before collectBets is called).
|
||||
export function buildPots(players) {
|
||||
|
|
@ -343,10 +348,12 @@ export function startHand(state) {
|
|||
}
|
||||
}
|
||||
|
||||
// First to act pre-flop is after big blind
|
||||
let actionSeat = seatOrder[2] ?? seatOrder[0];
|
||||
// First to act pre-flop is the first player after the big blind who can
|
||||
// still act (players all-in from posting a blind are skipped).
|
||||
const rotation = [...seatOrder.slice(2), ...seatOrder.slice(0, 2)];
|
||||
const actionSeat = rotation.find((s) => !players[s].allIn) ?? -1;
|
||||
|
||||
return {
|
||||
const next = {
|
||||
...state,
|
||||
phase: 'preflop',
|
||||
deck,
|
||||
|
|
@ -357,12 +364,33 @@ export function startHand(state) {
|
|||
dealerSeat,
|
||||
actionSeat,
|
||||
roundBet: bb,
|
||||
lastRaiseSize: bb,
|
||||
lastRaiser: bbSeat,
|
||||
handNumber: state.handNumber + 1,
|
||||
sbSeat,
|
||||
bbSeat,
|
||||
blind,
|
||||
runout: false,
|
||||
};
|
||||
|
||||
// Nobody left who could still bet (e.g. short stacks all-in from the blinds)?
|
||||
const actors = players.filter((p) => !p.eliminated && !p.folded && !p.allIn);
|
||||
if (actors.length === 0 || (actors.length === 1 && actors[0].bet >= bb)) {
|
||||
return runoutToShowdown(next);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
// No more betting is possible: sweep bets, deal the rest of the board, showdown.
|
||||
function runoutToShowdown(state) {
|
||||
const { players: clearedPlayers, pot } = collectBets(state.players, state.pot);
|
||||
const runoutFrom = state.community.length;
|
||||
const community = [...state.community];
|
||||
while (community.length < 5) community.push(...state.deck.deal(1));
|
||||
return endHand({
|
||||
...state, players: clearedPlayers, pot, community, phase: 'showdown',
|
||||
runout: true, runoutFrom,
|
||||
});
|
||||
}
|
||||
|
||||
// Returns active (not eliminated, not folded) seat numbers starting after dealer
|
||||
|
|
@ -384,6 +412,7 @@ export function applyAction(state, seat, action) {
|
|||
const players = state.players.map((p) => ({ ...p }));
|
||||
const player = players[seat];
|
||||
let { pot, roundBet, lastRaiser } = state;
|
||||
let lastRaiseSize = state.lastRaiseSize ?? state.blind?.big ?? 10;
|
||||
|
||||
switch (action.type) {
|
||||
case 'fold':
|
||||
|
|
@ -407,18 +436,22 @@ export function applyAction(state, seat, action) {
|
|||
}
|
||||
|
||||
case 'raise': {
|
||||
const minR = roundBet === 0 ? (state.blind?.big ?? 10) : roundBet * 2;
|
||||
const minR = minRaise(state);
|
||||
const raiseTotal = Math.max(minR, action.amount ?? minR);
|
||||
const toAdd = Math.min(raiseTotal - player.bet, player.chips);
|
||||
player.chips -= toAdd;
|
||||
player.bet += toAdd;
|
||||
player.totalBet += toAdd;
|
||||
if (player.chips === 0) player.allIn = true;
|
||||
roundBet = player.bet;
|
||||
lastRaiser = seat;
|
||||
for (const p of players) {
|
||||
if (p.seat !== seat && !p.eliminated && !p.folded && !p.allIn) {
|
||||
p.hasActedThisRound = false;
|
||||
if (player.bet > roundBet) {
|
||||
const raiseSize = player.bet - roundBet;
|
||||
if (raiseSize >= lastRaiseSize) lastRaiseSize = raiseSize;
|
||||
roundBet = player.bet;
|
||||
lastRaiser = seat;
|
||||
for (const p of players) {
|
||||
if (p.seat !== seat && !p.eliminated && !p.folded && !p.allIn) {
|
||||
p.hasActedThisRound = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
player.hasActedThisRound = true;
|
||||
|
|
@ -432,6 +465,8 @@ export function applyAction(state, seat, action) {
|
|||
player.totalBet += toAdd;
|
||||
player.allIn = true;
|
||||
if (player.bet > roundBet) {
|
||||
const raiseSize = player.bet - roundBet;
|
||||
if (raiseSize >= lastRaiseSize) lastRaiseSize = raiseSize;
|
||||
roundBet = player.bet;
|
||||
lastRaiser = seat;
|
||||
for (const p of players) {
|
||||
|
|
@ -452,10 +487,10 @@ export function applyAction(state, seat, action) {
|
|||
|
||||
if (nextSeat === null) {
|
||||
// Betting round over — collect bets into pot and advance phase
|
||||
return advancePhase({ ...state, players, pot, roundBet, lastRaiser });
|
||||
return advancePhase({ ...state, players, pot, roundBet, lastRaiser, lastRaiseSize });
|
||||
}
|
||||
|
||||
return { ...state, players, pot, roundBet, lastRaiser, actionSeat: nextSeat };
|
||||
return { ...state, players, pot, roundBet, lastRaiser, lastRaiseSize, actionSeat: nextSeat };
|
||||
}
|
||||
|
||||
function nextToAct(players, currentSeat, roundBet) {
|
||||
|
|
@ -492,6 +527,12 @@ function advancePhase(state) {
|
|||
return endHand({ ...state, players: clearedPlayers, pot: 0, phase: 'showdown', community });
|
||||
}
|
||||
|
||||
// At most one player can still bet → no more decisions: run the board out.
|
||||
const actors = remaining.filter((p) => !p.allIn);
|
||||
if (actors.length <= 1 && state.phase !== 'river') {
|
||||
return runoutToShowdown(state);
|
||||
}
|
||||
|
||||
const nextPhase = { preflop: 'flop', flop: 'turn', turn: 'river', river: 'showdown' }[state.phase];
|
||||
|
||||
let newCommunity = [...community];
|
||||
|
|
@ -503,9 +544,10 @@ function advancePhase(state) {
|
|||
return endHand({ ...state, players: clearedPlayers, pot, community: newCommunity, phase: 'showdown' });
|
||||
}
|
||||
|
||||
// Reset bets for new round; first to act is first active after dealer
|
||||
// Reset bets for new round; first to act is the first player after the
|
||||
// dealer who can still act (all-in players never get the action).
|
||||
const seatOrder = getSeatOrder(clearedPlayers, state.dealerSeat);
|
||||
const actionSeat = seatOrder[0];
|
||||
const actionSeat = seatOrder.find((s) => !clearedPlayers[s].allIn) ?? seatOrder[0];
|
||||
|
||||
return {
|
||||
...state,
|
||||
|
|
@ -514,9 +556,10 @@ function advancePhase(state) {
|
|||
pot,
|
||||
community: newCommunity,
|
||||
roundBet: 0,
|
||||
lastRaiseSize: state.blind?.big ?? 10,
|
||||
lastRaiser: null,
|
||||
actionSeat,
|
||||
sidePots: buildPots(clearedPlayers),
|
||||
sidePots: buildPotsFromTotals(clearedPlayers),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -572,6 +615,8 @@ export function callAmount(state, seat) {
|
|||
return Math.min(state.roundBet - p.bet, p.chips);
|
||||
}
|
||||
|
||||
// Minimum legal raise-TO amount: the current bet plus the last full raise.
|
||||
export function minRaise(state) {
|
||||
return state.roundBet === 0 ? (state.blind?.big ?? 10) : state.roundBet * 2;
|
||||
const bb = state.blind?.big ?? 10;
|
||||
return state.roundBet === 0 ? bb : state.roundBet + (state.lastRaiseSize ?? bb);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,134 @@
|
|||
// Hold'em presentation helpers — pure, so tools/verifyHoldem.js can test them.
|
||||
// best five cards, all-in equity, hand labels, bet-sizing presets, finishing places.
|
||||
|
||||
import { evaluateHand, compareHands, callAmount, minRaise } from './HoldemLogic.js';
|
||||
import { SUITS, RANKS } from '../cards/Deck.js';
|
||||
|
||||
const RANK_VAL = Object.fromEntries(RANKS.map((r, i) => [r, i + 2]));
|
||||
const RANK_NAME = { 14: 'Ace', 13: 'King', 12: 'Queen', 11: 'Jack', 10: 'Ten', 9: 'Nine', 8: 'Eight', 7: 'Seven', 6: 'Six', 5: 'Five', 4: 'Four', 3: 'Three', 2: 'Two' };
|
||||
const RANK_PLURAL = { 6: 'Sixes' };
|
||||
const SHORT = { 14: 'A', 13: 'K', 12: 'Q', 11: 'J', 10: 'T' };
|
||||
|
||||
const plural = (v) => RANK_PLURAL[v] ?? `${RANK_NAME[v]}s`;
|
||||
const short = (v) => SHORT[v] ?? String(v);
|
||||
|
||||
// The best 5-card hand out of 5–7 cards, with the actual cards that make it.
|
||||
export function bestFive(cards) {
|
||||
if (cards.length < 5) return null;
|
||||
let best = null;
|
||||
const n = cards.length;
|
||||
for (let a = 0; a < n - 4; a++)
|
||||
for (let b = a + 1; b < n - 3; b++)
|
||||
for (let c = b + 1; c < n - 2; c++)
|
||||
for (let d = c + 1; d < n - 1; d++)
|
||||
for (let e = d + 1; e < n; e++) {
|
||||
const five = [cards[a], cards[b], cards[c], cards[d], cards[e]];
|
||||
const ev = evaluateHand(five);
|
||||
if (!best || compareHands(ev, best.eval) > 0) best = { eval: ev, cards: five };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// A readable description: "Pocket Kings", "A-K suited", "Two Pair, Kings & Sevens"…
|
||||
export function handLabel(hole, community = []) {
|
||||
if (!hole || hole.length < 2) return '';
|
||||
if (community.length === 0) {
|
||||
const [a, b] = [...hole].sort((x, y) => y.value - x.value);
|
||||
if (a.value === b.value) return `Pocket ${plural(a.value)}`;
|
||||
return `${short(a.value)}-${short(b.value)} ${a.suit === b.suit ? 'suited' : 'offsuit'}`;
|
||||
}
|
||||
const all = [...hole, ...community];
|
||||
if (all.length < 5) return '';
|
||||
return describe(evaluateHand(all));
|
||||
}
|
||||
|
||||
export function describe(ev) {
|
||||
const t = ev.tiebreakers;
|
||||
switch (ev.rank) {
|
||||
case 8: return ev.name === 'Royal Flush' ? 'Royal Flush' : `Straight Flush, ${RANK_NAME[t[0]]} high`;
|
||||
case 7: return `Four ${plural(t[0])}`;
|
||||
case 6: return `Full House, ${plural(t[0])} full of ${plural(t[1])}`;
|
||||
case 5: return `Flush, ${RANK_NAME[t[0]]} high`;
|
||||
case 4: return `Straight, ${RANK_NAME[t[0]]} high`;
|
||||
case 3: return `Three ${plural(t[0])}`;
|
||||
case 2: return `Two Pair, ${plural(t[0])} & ${plural(t[1])}`;
|
||||
case 1: return `Pair of ${plural(t[0])}`;
|
||||
default: return `${RANK_NAME[t[0]]} High`;
|
||||
}
|
||||
}
|
||||
|
||||
function fullDeck() {
|
||||
const cards = [];
|
||||
for (const suit of SUITS) for (const rank of RANKS) {
|
||||
cards.push({ rank, suit, value: RANK_VAL[rank], key: `${rank}${suit}` });
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
// Win/tie share for each hand given a (partial) board. Monte Carlo on early
|
||||
// streets, exact enumeration once one or zero cards are left to come.
|
||||
// Returns [{ win, tie, equity }] in the order of `hands` (fractions 0…1).
|
||||
export function equity(hands, community, iterations = 500, rng = Math.random) {
|
||||
const used = new Set([...hands.flat(), ...community].map(c => c.key));
|
||||
const deck = fullDeck().filter(c => !used.has(c.key));
|
||||
const need = 5 - community.length;
|
||||
const tallies = hands.map(() => ({ win: 0, tie: 0, equity: 0 }));
|
||||
let trials = 0;
|
||||
|
||||
const score = (board) => {
|
||||
const evs = hands.map(h => evaluateHand([...h, ...board]));
|
||||
let best = evs[0];
|
||||
for (const e of evs) if (compareHands(e, best) > 0) best = e;
|
||||
const winners = evs.map((e, i) => (compareHands(e, best) === 0 ? i : -1)).filter(i => i >= 0);
|
||||
for (const i of winners) {
|
||||
if (winners.length === 1) tallies[i].win++;
|
||||
else tallies[i].tie++;
|
||||
tallies[i].equity += 1 / winners.length;
|
||||
}
|
||||
trials++;
|
||||
};
|
||||
|
||||
if (need === 0) score(community);
|
||||
else if (need === 1) for (const c of deck) score([...community, c]);
|
||||
else if (need === 2 && deck.length * (deck.length - 1) / 2 <= 1200) {
|
||||
for (let i = 0; i < deck.length; i++) for (let j = i + 1; j < deck.length; j++) score([...community, deck[i], deck[j]]);
|
||||
} else {
|
||||
const d = [...deck];
|
||||
for (let it = 0; it < iterations; it++) {
|
||||
for (let k = 0; k < need; k++) {
|
||||
const j = k + Math.floor(rng() * (d.length - k));
|
||||
[d[k], d[j]] = [d[j], d[k]];
|
||||
}
|
||||
score([...community, ...d.slice(0, need)]);
|
||||
}
|
||||
}
|
||||
return tallies.map(t => ({ win: t.win / trials, tie: t.tie / trials, equity: t.equity / trials }));
|
||||
}
|
||||
|
||||
// Bet-sizing presets as raise-TO amounts for `seat`, clamped to [min, all-in].
|
||||
export function raiseSizes(state, seat, round = 5) {
|
||||
const p = state.players[seat];
|
||||
const max = p.chips + p.bet;
|
||||
const min = Math.min(minRaise(state), max);
|
||||
const toCall = callAmount(state, seat);
|
||||
const middle = state.pot + state.players.reduce((s, q) => s + q.bet, 0);
|
||||
const potAfterCall = middle + toCall;
|
||||
const clamp = (v) => Math.max(min, Math.min(max, Math.round(v / round) * round));
|
||||
const potRaise = (frac) => clamp(state.roundBet + potAfterCall * frac);
|
||||
return { min, half: potRaise(0.5), threeQuarter: potRaise(0.75), pot: potRaise(1), max };
|
||||
}
|
||||
|
||||
// Finishing places for players knocked out in one hand: bigger starting stack
|
||||
// = better place. `stillIn` is how many players remain after the hand.
|
||||
// Returns Map<seat, place>.
|
||||
export function assignPlaces(newlyOut, startChips, stillIn) {
|
||||
const order = [...newlyOut].sort((a, b) => (startChips[b] ?? 0) - (startChips[a] ?? 0));
|
||||
const places = new Map();
|
||||
order.forEach((seat, i) => places.set(seat, stillIn + 1 + i));
|
||||
return places;
|
||||
}
|
||||
|
||||
export function ordinal(n) {
|
||||
const s = ['th', 'st', 'nd', 'rd'], v = n % 100;
|
||||
return `${n}${s[(v - 20) % 10] ?? s[v] ?? s[0]}`;
|
||||
}
|
||||
|
|
@ -0,0 +1,346 @@
|
|||
// Texas Hold 'Em table layout — Phaser-free so tools/verifyHoldem.js can test it.
|
||||
//
|
||||
// A casino poker-room oval: the dealer sits at the far (top) centre, players
|
||||
// wrap the other sides, the human at the near (bottom) centre. Uses the shared
|
||||
// casino perspective (makeProjection) with a milder tilt than the half-moons.
|
||||
//
|
||||
// Table space: the oval is a racetrack superellipse centred at (0, 0.5) with
|
||||
// half-width 1 (u) and half-depth 0.5 (v). rim(φ, k) is the point at angle φ
|
||||
// (0 = toward the human, +φ toward screen-right) scaled by k of the rim radius.
|
||||
|
||||
import { makeProjection, DOCK } from '../../ui/casino/CasinoGeometry.js';
|
||||
|
||||
export { DOCK };
|
||||
export const VIEW = { cx: 960, yFar: 250, yNear: 780, sFar: 0.78, halfW: 760, squash: 0.9 };
|
||||
export const P = makeProjection(VIEW);
|
||||
export const CARD_W = 96;
|
||||
export const CARD_H = 134;
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
const EXP = 2.4; // superellipse exponent — 2 = ellipse, higher = racetrack
|
||||
const HALF_U = 1, HALF_V = 0.5, CENTER_V = 0.5;
|
||||
|
||||
export const FELT_K = 0.985;
|
||||
export const WOOD_K = 1.045; // wooden racetrack (drink rail) outer edge
|
||||
export const RAIL_K = 1.16; // padded rail outer edge
|
||||
export const RAIL_FACE_PX = 30;
|
||||
export const RING_K = 0.6; // the printed gold betting line: bets inside, cards + stacks outside
|
||||
export const CHIP = 44; // chip diameter at perspective scale 1 (stacks + bets)
|
||||
const RING_MARGIN = 0.02, FELT_MARGIN = 0.022;
|
||||
|
||||
export function rimRadius(phiDeg) {
|
||||
const t = phiDeg * RAD;
|
||||
const a = Math.abs(Math.sin(t)) / HALF_U, b = Math.abs(Math.cos(t)) / HALF_V;
|
||||
return 1 / Math.pow(a ** EXP + b ** EXP, 1 / EXP);
|
||||
}
|
||||
|
||||
// Table-space point on the rim at angle φ, scaled by k.
|
||||
export function rimUV(phiDeg, k = 1) {
|
||||
const t = phiDeg * RAD, r = rimRadius(phiDeg) * k;
|
||||
return { u: r * Math.sin(t), v: CENTER_V + r * Math.cos(t) };
|
||||
}
|
||||
|
||||
export function rim(phiDeg, k = 1) {
|
||||
const { u, v } = rimUV(phiDeg, k);
|
||||
return P.project(u, v);
|
||||
}
|
||||
|
||||
export function rimPoints(k, steps = 180) {
|
||||
const pts = [];
|
||||
for (let i = 0; i < steps; i++) pts.push(rim((360 * i) / steps, k));
|
||||
return pts;
|
||||
}
|
||||
|
||||
// Is a screen point on the felt (inside the rim)?
|
||||
export function onTableFelt(pt) {
|
||||
const { u, v } = P.unproject(pt.x, pt.y);
|
||||
const du = Math.abs(u) / HALF_U, dv = Math.abs(v - CENTER_V) / HALF_V;
|
||||
return du ** EXP + dv ** EXP <= FELT_K ** EXP;
|
||||
}
|
||||
|
||||
// Superellipse level of a screen point: 1 = the felt edge, RING_K = the betting line.
|
||||
export function levelOf(pt) {
|
||||
const { u, v } = P.unproject(pt.x, pt.y);
|
||||
return Math.pow((Math.abs(u) / HALF_U) ** EXP + (Math.abs(v - CENTER_V) / HALF_V) ** EXP, 1 / EXP);
|
||||
}
|
||||
|
||||
const inBand = (pt) => { const l = levelOf(pt); return l >= RING_K + RING_MARGIN && l <= FELT_K - FELT_MARGIN; };
|
||||
const insideRing = (pt) => levelOf(pt) <= RING_K - RING_MARGIN;
|
||||
|
||||
// Screen corners of a card pose (container scale (s, s·squash), then rotation).
|
||||
export function cardCorners(pose) {
|
||||
const cos = Math.cos(pose.rot), sin = Math.sin(pose.rot);
|
||||
return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => {
|
||||
const lx = a * (CARD_W / 2) * pose.s, ly = b * (CARD_H / 2) * pose.s * VIEW.squash;
|
||||
return { x: pose.x + lx * cos - ly * sin, y: pose.y + lx * sin + ly * cos };
|
||||
});
|
||||
}
|
||||
|
||||
// What a chip stack covers on the felt (up to two columns + the amount pill).
|
||||
export function stackFootprint(pt, s) {
|
||||
const size = CHIP * s;
|
||||
return [
|
||||
{ x: pt.x - size * 1.1, y: pt.y }, { x: pt.x + size * 1.1, y: pt.y },
|
||||
{ x: pt.x, y: pt.y - size * 0.3 }, { x: pt.x, y: pt.y + size * 0.95 },
|
||||
{ x: pt.x - size * 0.9, y: pt.y + size * 0.8 }, { x: pt.x + size * 0.9, y: pt.y + size * 0.8 },
|
||||
];
|
||||
}
|
||||
|
||||
// What a single bet stack covers (one column + an amount pill up to "$1,250" on its right).
|
||||
export function betFootprint(pt, s) {
|
||||
const size = CHIP * s;
|
||||
return [
|
||||
{ x: pt.x - size * 0.6, y: pt.y }, { x: pt.x + size * 0.6, y: pt.y },
|
||||
{ x: pt.x, y: pt.y - size * 0.3 }, { x: pt.x, y: pt.y + size * 0.3 },
|
||||
{ x: pt.x + size * 2.6, y: pt.y }, { x: pt.x + size * 2.6, y: pt.y + size * 0.25 },
|
||||
];
|
||||
}
|
||||
|
||||
// Offset a table-space point along the rim tangent at φ (+ = clockwise on screen).
|
||||
function alongTangent(uv, phiDeg, d) {
|
||||
const t = phiDeg * RAD;
|
||||
return { u: uv.u + Math.cos(t) * d, v: uv.v - Math.sin(t) * d };
|
||||
}
|
||||
|
||||
// Rotation whose card "down" points from `from` toward `to` (screen points).
|
||||
const aimAt = (from, to) => Math.atan2(-(to.x - from.x), to.y - from.y);
|
||||
|
||||
// Rotation that lines a card up with the rail: its "down" follows the rail's
|
||||
// outward normal (so the hand sits squarely in the band outside the betting line).
|
||||
export function railRotation(phiDeg, k = 0.8) {
|
||||
const a = rim(phiDeg - 0.5, k), b = rim(phiDeg + 0.5, k);
|
||||
let nx = -(b.y - a.y), ny = b.x - a.x;
|
||||
const c = rim(phiDeg, k), o = rim(phiDeg, k + 0.1);
|
||||
if (nx * (o.x - c.x) + ny * (o.y - c.y) < 0) { nx = -nx; ny = -ny; }
|
||||
return Math.atan2(-nx, ny);
|
||||
}
|
||||
|
||||
const lerpAngle = (a, b, t) => {
|
||||
let d = b - a;
|
||||
while (d > Math.PI) d -= Math.PI * 2;
|
||||
while (d < -Math.PI) d += Math.PI * 2;
|
||||
return a + d * t;
|
||||
};
|
||||
|
||||
// ── Seats ────────────────────────────────────────────────────────────────────
|
||||
// Opponents fill clockwise in logic seat order (seat 1 = just left of the
|
||||
// human): left side bottom → top, then right side top → bottom.
|
||||
const SIDE_NEAR = 50, SIDE_FAR = 140;
|
||||
|
||||
export function seatAngles(nOpp) {
|
||||
const L = Math.ceil(nOpp / 2), R = nOpp - L;
|
||||
const side = (count) => (count === 1 ? [90] : Array.from({ length: count }, (_, i) => SIDE_NEAR + (i * (SIDE_FAR - SIDE_NEAR)) / (count - 1)));
|
||||
const left = side(L).map(a => -a); // -50 … -140
|
||||
const right = R ? side(R).reverse() : []; // 140 … 50
|
||||
return [...left, ...right];
|
||||
}
|
||||
|
||||
export const HUMAN = { maxScale: 1.0, gap: 104, minScale: 0.9 };
|
||||
export const OPP = { maxScale: 0.9, gap: 72, minScale: 0.78 };
|
||||
|
||||
// Fit a hand: both hole cards wholly between the betting line and the rail,
|
||||
// turned toward the player (`seatPt`, where their portrait sits). The cards
|
||||
// face the player fully when they fit at a decent size; otherwise they ease
|
||||
// toward the rail's own direction (which always fits best) and shrink as needed.
|
||||
function fitAt(phi, cfg, aim) {
|
||||
for (let scale = cfg.maxScale; scale >= 0.5; scale -= 0.02) {
|
||||
const fits = [];
|
||||
for (let k = FELT_K; k >= RING_K; k -= 0.004) {
|
||||
const c = rim(phi, k);
|
||||
const rot = aim(c, k);
|
||||
const s = c.s * scale;
|
||||
const cos = Math.cos(rot), sin = Math.sin(rot);
|
||||
const cards = [-1, 1].map(side => {
|
||||
const lx = side * (cfg.gap / 2) * s;
|
||||
return { x: c.x + lx * cos, y: c.y + lx * sin, rot, s };
|
||||
});
|
||||
if (cards.every(cd => cardCorners(cd).every(inBand))) fits.push({ k, c, cards, scale });
|
||||
}
|
||||
if (fits.length) return fits[Math.floor(fits.length / 2)];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function fitCards(phi, cfg, seatPt) {
|
||||
if (phi === 0) return fitAt(phi, cfg, () => 0);
|
||||
let best = null;
|
||||
for (let t = 1; t >= -0.001; t -= 0.1) {
|
||||
const fit = fitAt(phi, cfg, (c, k) => lerpAngle(railRotation(phi, k), aimAt(c, seatPt), t));
|
||||
if (fit && fit.scale >= cfg.minScale) return { ...fit, toward: t };
|
||||
if (fit && (!best || fit.scale > best.scale)) best = { ...fit, toward: t };
|
||||
}
|
||||
if (best) return best;
|
||||
const k = (RING_K + FELT_K) / 2, c = rim(phi, k), rot = railRotation(phi, k);
|
||||
return { k, c, scale: 0.5, toward: 0, cards: [-1, 1].map(side => ({ x: c.x + side * 20, y: c.y, rot, s: c.s * 0.5 })) };
|
||||
}
|
||||
|
||||
// SB / BB marker: beside the bet (left of it first — the amount pill is on the
|
||||
// right), inside the betting line, clear of the bet, the board and the pot.
|
||||
function blindSpot(bet) {
|
||||
const r = 16 * bet.s, dist = CHIP * bet.s * 1.05;
|
||||
const keepOut = [...[0, 1, 2, 3, 4].map(communityPose), potPose(0)];
|
||||
for (const deg of [180, 160, 200, 140, 220, 120, 240, 100, 260, 90, 270]) {
|
||||
const a = (deg * Math.PI) / 180;
|
||||
const p = { x: bet.x + Math.cos(a) * dist, y: bet.y + Math.sin(a) * dist * VIEW.squash, s: bet.s };
|
||||
const edge = [[-r, 0], [r, 0], [0, -r], [0, r]].map(([dx, dy]) => ({ x: p.x + dx, y: p.y + dy }));
|
||||
if (!edge.every(insideRing)) continue;
|
||||
if (!betFootprint(bet, bet.s).every(q => Math.hypot(q.x - p.x, q.y - p.y) > r + 6)) continue;
|
||||
if (!keepOut.every(q => Math.hypot(q.x - p.x, q.y - p.y) > 62)) continue;
|
||||
return p;
|
||||
}
|
||||
return { x: bet.x - dist, y: bet.y, s: bet.s };
|
||||
}
|
||||
|
||||
// Deepest spot on the seat line where a bet (and its amount pill) stays inside the line.
|
||||
function fitBet(phi) {
|
||||
for (let k = RING_K - 0.05; k >= 0.3; k -= 0.005) {
|
||||
const p = rim(phi, k);
|
||||
if (betFootprint(p, p.s).every(insideRing)) return p;
|
||||
}
|
||||
return rim(phi, 0.4);
|
||||
}
|
||||
|
||||
// Cards, bet spot, badge and portrait for one seat (stack/button are placed
|
||||
// table-wide by tableLayout so neighbours never collide).
|
||||
function baseSeat(seat, nOpp) {
|
||||
const phi = seat === 0 ? 0 : seatAngles(nOpp)[seat - 1];
|
||||
const cfg = seat === 0 ? HUMAN : OPP;
|
||||
let portrait;
|
||||
if (seat === 0) portrait = { x: 160, y: 1013, r: 50 };
|
||||
else {
|
||||
const p = rim(phi, 1.32);
|
||||
portrait = { x: Math.max(64, Math.min(1856, p.x)), y: Math.min(812, p.y), r: 52 };
|
||||
}
|
||||
const fit = fitCards(phi, cfg, portrait);
|
||||
const centre = fit.c;
|
||||
const cards = fit.cards;
|
||||
const rot = cards[0].rot;
|
||||
const s = cards[0].s;
|
||||
const bet = fitBet(phi);
|
||||
const blind = blindSpot(bet);
|
||||
const badge = rim(phi, RING_K);
|
||||
return {
|
||||
seat, phi, cfg, centre, cards, rot, s, portrait, cardK: fit.k, cardScale: fit.scale, toward: fit.toward ?? 1, bet, blind, badge,
|
||||
};
|
||||
}
|
||||
|
||||
// Does a footprint (polygon-ish point set) stay clear of a card's rectangle?
|
||||
function clearOfCards(points, cards, pad) {
|
||||
return cards.every(cd => {
|
||||
const cos = Math.cos(cd.rot), sin = Math.sin(cd.rot);
|
||||
const hw = (CARD_W / 2) * cd.s + pad, hh = (CARD_H / 2) * cd.s * VIEW.squash + pad;
|
||||
return points.every(p => {
|
||||
const dx = p.x - cd.x, dy = p.y - cd.y;
|
||||
const lx = dx * cos + dy * sin, ly = -dx * sin + dy * cos;
|
||||
return Math.abs(lx) > hw || Math.abs(ly) > hh;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Candidate spots beside a seat's cards, wholly outside the betting line
|
||||
// (or, for the dealer button only, `inner` also allows a strip just inside it).
|
||||
function candidates(b, footprint, pad, inner = false) {
|
||||
const out = [];
|
||||
const kMin = inner ? RING_K - 0.14 : RING_K + 0.03;
|
||||
for (let k = FELT_K - 0.03; k >= kMin; k -= 0.02) {
|
||||
for (let d = 0.06; d <= 0.3; d += 0.02) {
|
||||
for (const sign of [-1, 1]) {
|
||||
const uv = alongTangent(rimUV(b.phi, k), b.phi, sign * d);
|
||||
const pt = P.project(uv.u, uv.v);
|
||||
const fp = footprint(pt, pt.s);
|
||||
const placeOk = inner
|
||||
? fp.every(p => levelOf(p) <= FELT_K - FELT_MARGIN) && !fp.some(p => Math.abs(levelOf(p) - RING_K) < 0.012)
|
||||
&& betFootprint(b.bet, b.bet.s).every(q => Math.hypot(q.x - pt.x, q.y - pt.y) > 34 * pt.s)
|
||||
: fp.every(inBand);
|
||||
if (placeOk && clearOfCards([pt, ...fp], b.cards, pad)) out.push(pt);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const buttonFootprint = (pt, s) => {
|
||||
const r = 22 * s;
|
||||
return [{ x: pt.x - r, y: pt.y }, { x: pt.x + r, y: pt.y }, { x: pt.x, y: pt.y - r * 0.9 }, { x: pt.x, y: pt.y + r * 0.9 }];
|
||||
};
|
||||
|
||||
// Pick the candidate that is clear of everything (up to `enough` px counts as
|
||||
// fully clear), and among those the one nearest the player's own cards.
|
||||
function bestSpot(cands, avoid, home, enough = 70) {
|
||||
let best = null, bestScore = -Infinity;
|
||||
for (const c of cands) {
|
||||
const clear = Math.min(enough, ...avoid.map(a => Math.hypot(a.x - c.x, a.y - c.y)));
|
||||
const score = clear * 1000 - Math.hypot(home.x - c.x, home.y - c.y);
|
||||
if (score > bestScore) { bestScore = score; best = c; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
const layoutCache = new Map();
|
||||
export function tableLayout(nOpp) {
|
||||
if (layoutCache.has(nOpp)) return layoutCache.get(nOpp);
|
||||
const seats = Array.from({ length: nOpp + 1 }, (_, seat) => baseSeat(seat, nOpp));
|
||||
const allCards = seats.flatMap(b => b.cards);
|
||||
const fixed = [
|
||||
...seats.flatMap(b => [...b.cards, ...b.cards.flatMap(cardCorners), b.bet, b.badge]),
|
||||
deckSpot(), muckSpot(), dealerSpot(), potPose(0), potPose(1), potPose(2),
|
||||
// the dealer's deck and muck pile are card-sized (the muck spreads a little)
|
||||
...[deckSpot(), muckSpot()].flatMap(d => cardCorners({ ...d, rot: 0, s: d.s * 1.25 })),
|
||||
...[0, 1, 2, 3, 4].map(communityPose),
|
||||
];
|
||||
const placed = [];
|
||||
const fallback = (b, k, d) => {
|
||||
const uv = alongTangent(rimUV(b.phi, k), b.phi, d);
|
||||
return P.project(uv.u, uv.v);
|
||||
};
|
||||
// Place the most cramped seats first: the human, then the far corners
|
||||
// (squeezed between the dealer and their neighbour), working toward the sides.
|
||||
const order = [...seats].sort((a, b) => (a.seat === 0 ? -1 : b.seat === 0 ? 1 : Math.abs(b.phi) - Math.abs(a.phi)));
|
||||
for (const b of order) {
|
||||
const avoid = () => [...fixed, ...placed.flatMap(p => [p, ...stackFootprint(p, p.s)])];
|
||||
let stackC = candidates({ ...b, cards: allCards }, stackFootprint, 6);
|
||||
if (b.seat === 0) stackC = stackC.filter(p => p.x < b.centre.x); // the human's chips sit on the left
|
||||
b.stack = bestSpot(stackC, avoid(), b.centre) ?? fallback(b, (RING_K + FELT_K) / 2, -0.25);
|
||||
placed.push(b.stack);
|
||||
let buttonC = candidates({ ...b, cards: allCards }, buttonFootprint, 4, true)
|
||||
.filter(p => !stackFootprint(b.stack, b.stack.s).some(q => Math.hypot(q.x - p.x, q.y - p.y) < 30 * p.s));
|
||||
if (b.seat === 0) buttonC = buttonC.filter(p => p.x > b.centre.x);
|
||||
b.button = bestSpot(buttonC, avoid(), b.centre, 66) ?? fallback(b, RING_K + 0.06, 0.15);
|
||||
placed.push(b.button);
|
||||
}
|
||||
layoutCache.set(nOpp, seats);
|
||||
return seats;
|
||||
}
|
||||
|
||||
export function seatLayout(seat, nOpp) {
|
||||
const b = tableLayout(nOpp)[seat];
|
||||
return { seat: b.seat, phi: b.phi, centre: b.centre, cards: b.cards, stack: b.stack, button: b.button,
|
||||
bet: b.bet, blind: b.blind, badge: b.badge, portrait: { ...b.portrait }, rot: b.rot, s: b.s };
|
||||
}
|
||||
|
||||
// ── Centre: community cards and pots ─────────────────────────────────────────
|
||||
export const COMMUNITY_V = 0.5;
|
||||
export const COMMUNITY_GAP = 106;
|
||||
|
||||
export function communityPose(i) {
|
||||
const c = P.project(0, COMMUNITY_V);
|
||||
return { x: c.x + (i - 2) * COMMUNITY_GAP * c.s, y: c.y, rot: 0, s: c.s };
|
||||
}
|
||||
|
||||
// Main pot (0) sits between the board and the dealer; side pots fan out beside it.
|
||||
export const POT_V = 0.335;
|
||||
const POT_OFFSETS = [0, -1, 1, -2, 2];
|
||||
export function potPose(i) {
|
||||
const c = P.project(0, POT_V);
|
||||
return { x: c.x + POT_OFFSETS[Math.min(i, POT_OFFSETS.length - 1)] * 112 * c.s, y: c.y, s: c.s };
|
||||
}
|
||||
|
||||
// ── Dealer ───────────────────────────────────────────────────────────────────
|
||||
export const DEALER_V = 0.07;
|
||||
export function dealerSpot() { return P.project(0, DEALER_V); }
|
||||
export function deckSpot() { const p = P.project(-0.085, DEALER_V); return { ...p, s: p.s * 0.85 }; }
|
||||
export function muckSpot() { const p = P.project(0.085, DEALER_V); return { ...p, s: p.s * 0.85 }; }
|
||||
export const DEALER_PLATE = { x: 960, y: 168 };
|
||||
|
||||
// ── HUD ──────────────────────────────────────────────────────────────────────
|
||||
export const PANEL = { x: 1452, y: 12, w: 456, h: 118 }; // tournament panel (top-right)
|
||||
|
|
@ -21,32 +21,38 @@ export const VIEW = {
|
|||
squash: 0.9, // extra vertical squash for things lying flat on the felt
|
||||
};
|
||||
|
||||
const A = 1 / VIEW.sFar - 1;
|
||||
const K = (VIEW.yNear - VIEW.yFar) / (1 - VIEW.sFar);
|
||||
const Y_HORIZON = VIEW.yFar - VIEW.sFar * K;
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
export function depthScale(v) {
|
||||
return 1 / (1 + A * (1 - v));
|
||||
}
|
||||
|
||||
export function project(u, v) {
|
||||
const s = depthScale(v);
|
||||
return { x: VIEW.cx + u * VIEW.halfW * s, y: Y_HORIZON + K * s, s };
|
||||
}
|
||||
|
||||
export function polar(r, thetaDeg) {
|
||||
const t = thetaDeg * RAD;
|
||||
return project(r * Math.sin(t), r * Math.cos(t));
|
||||
// A perspective camera for any table. Half-moon tables use the default VIEW;
|
||||
// other shapes (the Hold'em oval) build their own with makeProjection(view).
|
||||
export function makeProjection(view) {
|
||||
const A = 1 / view.sFar - 1;
|
||||
const K = (view.yNear - view.yFar) / (1 - view.sFar);
|
||||
const yh = view.yFar - view.sFar * K;
|
||||
const depthScale = (v) => 1 / (1 + A * (1 - v));
|
||||
const project = (u, v) => {
|
||||
const s = depthScale(v);
|
||||
return { x: view.cx + u * view.halfW * s, y: yh + K * s, s };
|
||||
};
|
||||
const unproject = (x, y) => {
|
||||
const s = (y - yh) / K;
|
||||
const v = 1 - (1 / s - 1) / A;
|
||||
const u = (x - view.cx) / (view.halfW * s);
|
||||
return { u, v, s };
|
||||
};
|
||||
const polar = (r, thetaDeg) => {
|
||||
const t = thetaDeg * RAD;
|
||||
return project(r * Math.sin(t), r * Math.cos(t));
|
||||
};
|
||||
return { view, depthScale, project, unproject, polar };
|
||||
}
|
||||
|
||||
const DEFAULT = makeProjection(VIEW);
|
||||
export const depthScale = DEFAULT.depthScale;
|
||||
export const project = DEFAULT.project;
|
||||
export const polar = DEFAULT.polar;
|
||||
// Inverse of project() for a screen point.
|
||||
export function unproject(x, y) {
|
||||
const s = (y - Y_HORIZON) / K;
|
||||
const v = 1 - (1 / s - 1) / A;
|
||||
const u = (x - VIEW.cx) / (VIEW.halfW * s);
|
||||
return { u, v, s };
|
||||
}
|
||||
export const unproject = DEFAULT.unproject;
|
||||
|
||||
// Screen point → table-space polar (r, θ in degrees). Used for felt hit-testing.
|
||||
export function toPolar(x, y) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,319 @@
|
|||
#!/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);
|
||||
Loading…
Reference in New Issue