From d33ab09ae031473a840ab0149f9d4cccf6f444ec Mon Sep 17 00:00:00 2001 From: Brian Fertig Date: Mon, 23 Nov 2026 22:46:40 -0700 Subject: [PATCH] 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 --- src/games/holdem/HoldemAI.js | 4 +- src/games/holdem/HoldemArt.js | 253 +++ src/games/holdem/HoldemGame.js | 2678 +++++++++++++--------------- src/games/holdem/HoldemLogic.js | 79 +- src/games/holdem/HoldemShowdown.js | 134 ++ src/games/holdem/HoldemTable.js | 346 ++++ src/ui/casino/CasinoGeometry.js | 48 +- tools/verifyHoldem.js | 319 ++++ 8 files changed, 2412 insertions(+), 1449 deletions(-) create mode 100644 src/games/holdem/HoldemArt.js create mode 100644 src/games/holdem/HoldemShowdown.js create mode 100644 src/games/holdem/HoldemTable.js create mode 100644 tools/verifyHoldem.js diff --git a/src/games/holdem/HoldemAI.js b/src/games/holdem/HoldemAI.js index 925fe71..8a8c8bf 100644 --- a/src/games/holdem/HoldemAI.js +++ b/src/games/holdem/HoldemAI.js @@ -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) { diff --git a/src/games/holdem/HoldemArt.js b/src/games/holdem/HoldemArt.js new file mode 100644 index 0000000..dcb26f1 --- /dev/null +++ b/src/games/holdem/HoldemArt.js @@ -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); +} diff --git a/src/games/holdem/HoldemGame.js b/src/games/holdem/HoldemGame.js index abd0d1b..b692334 100644 --- a/src/games/holdem/HoldemGame.js +++ b/src/games/holdem/HoldemGame.js @@ -5,1537 +5,1395 @@ import { api } from '../../services/api.js'; import { auth } from '../../services/auth.js'; import { createInitialState, startHand, applyAction, - getBlindLevel, callAmount, canCheck, minRaise, - getActivePlayers, evaluateHand, resolveShowdown, + getBlindLevel, LEVEL_INTERVAL_MS, BLIND_LEVELS, callAmount, canCheck, + evaluateHand, compareHands, potsFromTotals, } from './HoldemLogic.js'; import { chooseAction } from './HoldemAI.js'; -import { createOpponentPortrait, createPlayerPortrait } from '../../ui/Portrait.js'; +import { bestFive, equity, handLabel, describe, raiseSizes, assignPlaces, ordinal } from './HoldemShowdown.js'; +import { createOpponentPortrait } from '../../ui/Portrait.js'; import { playSound, playChipBet, SFX } from '../../ui/Sounds.js'; import { MusicPlayer } from '../../ui/MusicPlayer.js'; +import { makeChipStack, breakdown, throwStack } from '../../ui/CasinoChips.js'; +import { CasinoDock } from '../../ui/casino/CasinoDock.js'; +import { CardSkin } from '../../ui/casino/CasinoCards.js'; +import { ensureLeatherPanel } from '../../ui/casino/CasinoArt.js'; +import { + VIEW, seatLayout, communityPose, potPose, deckSpot, muckSpot, DOCK, PANEL, CARD_W, CARD_H, CHIP, +} from './HoldemTable.js'; +import { prepareHoldemArt } from './HoldemArt.js'; -// ── Layout constants ────────────────────────────────────────────────────────── -const CX = GAME_WIDTH / 2; // 960 -const CY = GAME_HEIGHT / 2; // 540 +// ─── Layout / tuning ────────────────────────────────────────────────────────── +// Table positions come from HoldemTable.js (casino poker-room oval, shared +// perspective kit); the art is baked by HoldemArt.js. This file is flow + UI. +const CX = GAME_WIDTH / 2; +const CY = GAME_HEIGHT / 2; +const SQ = VIEW.squash; +const DOCK_Y = DOCK.y + DOCK.h / 2; +const BUY_INS = [100, 250, 500]; -const CARD_W = 100; -const CARD_H = 140; -const CARD_R = 8; // corner radius +const D = { + bg: -2, playfield: -1, table: 0, cards: 10, stacks: 12, pucks: 14, glow: 16, flying: 22, + badges: 24, dock: 26, ui: 30, dockUi: 32, prompt: 38, modal: 50, +}; -// Opponents are spaced evenly around a seating ellipse so the table stays -// balanced for any count (3–7 opponents). The human owns the bottom of the ring -// (fixed bottom-centre). Per-game positions are computed in computeSeatLayout(). -const SEAT_ELLIPSE = { cx: CX, cy: 540, rx: 760, ry: 330 }; -// Diagonal corner seats (top/bottom on either side) are pulled this far toward -// the table centre so they don't hug the screen edges. -const CORNER_NUDGE = 60; - -// Depth layers -const D = { bg: -1, table: 0, cards: 10, chips: 20, ui: 30, modal: 50 }; - -// Suit colors -const SUIT_COLOR = { s: '#1a1a2e', h: '#c0392b', d: '#c0392b', c: '#1a1a2e' }; -const SUIT_SYMBOL = { s: '♠', h: '♥', d: '♦', c: '♣' }; - -const AI_ACTION_DELAY_MS = 900; +const ACTION_LABEL = (a, st) => ({ + fold: 'FOLD', check: 'CHECK', call: `CALL $${st}`, raise: `RAISE TO $${st}`, allin: 'ALL IN', +}); +const ACTION_COLOR = { fold: '#e06c75', check: '#c9c2b0', call: '#7fd1c7', raise: '#ffd700', allin: '#ff6b35', bet: '#ffd700' }; export default class HoldemGame extends Phaser.Scene { constructor() { super('HoldemGame'); } init(data) { - this.gameDef = data.game; + this.gameDef = data.game; this.opponents = data.opponents ?? []; this.playfield = data.playfield ?? null; - this.cardBack = data.cardBack ?? null; + this.cardBack = data.cardBack ?? null; + this.n = Math.min(this.opponents.length, 7); - this.gs = null; - this.buyIn = 100; + this.gs = null; + this.buyIn = 100; this.globalChips = 0; - this.animating = false; - - // Elimination tracking - this.eliminatedSeats = new Set(); - this.eliminatedBg = null; - this.eliminatedTitleTxt = null; - this.eliminatedPicList = []; // { backing, portraitObj, maskG } - - // UI references - this.portraits = []; // portrait handles per seat (for cleanup) - this.foldedCardDisplays = {}; // seat → [container] kept on table after fold - this.summaryObjects = []; // all Phaser/DOM objects created for the summary overlay - this.betChipDisplays = {}; // seat → Phaser Container showing chip stack at bet zone - this.potChipDisplay = null; // persistent chip stack near the Pot label - this.seatContainers = []; // graphics/containers per seat - this.communitySlots = []; // card containers for community row - this.potText = null; - this.blindText = null; - this.timerText = null; - this.actionButtons = []; - this.raiseSlider = null; - this.raiseAmtText = null; - this.raisePanel = null; - this.raiseValue = 0; - this.statusBanner = null; + this.cashedOut = false; + this.busy = false; + this.portraits = []; + this.nameTxts = {}; + this.chipTxts = {}; + this.cards = new Map(); // 'seat:i' hole cards, 'b:i' board + this.muckPile = []; + this.stackObjs = {}; // seat → chip columns in front of the player + this.betObjs = {}; // seat → bet stack over the line + this.potObjs = []; + this.decor = []; // badges, glows, equity pills — cleared each hand + this.summaryObjects = []; + this.preAction = null; + this.preActionBet = 0; + this.raiseValue = 0; + this.eliminatedSeats = new Set(); + this.places = new Map(); // seat → finishing place + this.elimPics = []; + this.lastBlindLevel = 0; + this.humanWatching = false; + this.handStartChips = {}; } // ── Lifecycle ─────────────────────────────────────────────────────────────── - - create() { + async create() { new MusicPlayer(this, this.cache.json.get('music').tracks); + this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, COLORS.bg).setDepth(D.bg); this.buildPlayfield(); - this.buildTable(); - this.buildCommunitySlots(); - this.buildPotDisplay(); - this.buildBlindDisplay(); - this.buildSeatContainers(); - this.buildActionButtons(); - this.buildLeaveButton(); - this.buildEliminatedPanel(); - this.showBuyInModal(); this.events.once('shutdown', () => { - for (const p of this.portraits) p.destroy(); - for (const e of this.eliminatedPicList) e.maskG?.destroy(); + for (const p of this.portraits) p?.destroy?.(); + for (const e of this.elimPics) e.maskG?.destroy(); }); + + await prepareHoldemArt(this); + if (!this.sys.isActive()) return; + this.skin = new CardSkin(this, this.cardBack, { depth: D.cards }); + this.add.image(0, 0, 'he-table').setOrigin(0, 0).setDepth(D.table); + + this.buildDeck(); + this.buildSeats(); + this.buildDock(); + this.buildPanel(); + new Button(this, 84, 44, 'Leave', () => this.onLeave(), { + variant: 'ghost', width: 140, height: 48, fontSize: 20, + }).setDepth(D.ui); + this.input.keyboard?.on('keydown', (e) => this.onKey(e)); + this.setDockMode('idle'); + this.showBuyIn(); } - update() { - if (!this.gs) return; - const elapsed = Date.now() - this.gs.gameStartMs; - const level = getBlindLevel(elapsed); - const next = (level.level) * 10 * 60 * 1000; - const remaining = Math.max(0, next - elapsed); - const m = Math.floor(remaining / 60000); - const s = Math.floor((remaining % 60000) / 1000); - if (this.timerText) { - this.timerText.setText(`Level ${level.level} — next in ${m}:${String(s).padStart(2, '0')}`); - } - if (this.blindText) { - this.blindText.setText(`Blinds $${level.small}/$${level.big}`); - } + update(time) { + if (!this.gs || !this.panelTxt || time - (this._panelAt ?? 0) < 250) return; + this._panelAt = time; + this.updatePanel(); } - // ── Background / Table ────────────────────────────────────────────────────── + wait(ms) { return new Promise(res => this.time.delayedCall(ms, res)); } + tweenP(cfg) { + return new Promise(res => this.tweens.add({ ...cfg, onComplete: (...a) => { cfg.onComplete?.(...a); res(); } })); + } + + alive() { return this.sys.isActive(); } + + L(seat) { return seatLayout(seat, this.n); } + + // ── Static scenery ───────────────────────────────────────────────────────── buildPlayfield() { const pf = this.playfield; if (pf?.key && this.textures.exists(pf.key)) { - this.add.image(CX, CY, pf.key) - .setDisplaySize(GAME_WIDTH, GAME_HEIGHT) - .setDepth(D.bg); + this.add.image(CX, CY, pf.key).setDisplaySize(GAME_WIDTH, GAME_HEIGHT).setDepth(D.playfield); } } - buildTable() { - const g = this.add.graphics().setDepth(D.table); - // Outer shadow + buildDeck() { + const d = deckSpot(); + this.deckPos = d; + this.muckPos = muckSpot(); + for (let i = 0; i < 4; i++) { + this.skin.make(null, false, d.x + i * 0.8, d.y - i * 1.5, d.s, 0.04).setDepth(D.cards); + } + // dealer button + blind pucks + this.dealerPuck = this.makePuck('DEALER', 0xf4efe4, '#1a1208', 19).setVisible(false); + this.sbPuck = this.makePuck('SB', 0x2b5fb4, '#ffffff', 14).setVisible(false); + this.bbPuck = this.makePuck('BB', 0xd4a017, '#1a1208', 14).setVisible(false); + } + + makePuck(text, color, textColor, r) { + const c = this.add.container(0, 0).setDepth(D.pucks); + const g = this.add.graphics(); g.fillStyle(0x000000, 0.35); - g.fillEllipse(CX + 6, CY + 8, 1540, 640); - // Rail (wood-tone border) - g.fillStyle(0x3d1f08, 1); - g.fillEllipse(CX, CY, 1540, 640); - // Felt surface - g.fillStyle(0x0a3d1e, 1); - g.fillEllipse(CX, CY, 1460, 560); - // Subtle felt highlight - g.fillStyle(0x0d4a23, 0.4); - g.fillEllipse(CX, CY - 60, 1200, 320); - } - - // ── Community cards ───────────────────────────────────────────────────────── - - buildCommunitySlots() { - const totalW = 5 * CARD_W + 4 * 14; - const startX = CX - totalW / 2 + CARD_W / 2; - for (let i = 0; i < 5; i++) { - const x = startX + i * (CARD_W + 14); - const slot = this.add.container(x, CY - 10).setDepth(D.cards); - const outline = this.add.graphics(); - outline.lineStyle(2, 0xffffff, 0.15); - outline.strokeRoundedRect(-CARD_W / 2, -CARD_H / 2, CARD_W, CARD_H, CARD_R); - slot.add(outline); - this.communitySlots.push({ container: slot, cardObj: null }); - } - } - - // ── Pot / Blind display ───────────────────────────────────────────────────── - - buildPotDisplay() { - this.potText = this.add.text(CX, CY - CARD_H / 2 - 36, 'Pot: $0', { - fontFamily: '"Julius Sans One"', - fontSize: '26px', - color: '#f0e8d0', - }).setOrigin(0.5).setDepth(D.ui); - } - - buildBlindDisplay() { - this.blindText = this.add.text(24, 24, 'Blinds $5/$10', { - fontFamily: '"Julius Sans One"', - fontSize: '20px', - color: COLORS.mutedHex, - }).setOrigin(0, 0).setDepth(D.ui); - - this.timerText = this.add.text(24, 50, '', { - fontFamily: '"Julius Sans One"', - fontSize: '16px', - color: COLORS.mutedHex, - }).setOrigin(0, 0).setDepth(D.ui); - } - - // ── Seat containers ───────────────────────────────────────────────────────── - - // Build per-game seat positions: human bottom-centre, opponents fanned evenly - // across the top arc of the seating ellipse (matches the legacy left/top/right - // look at 3 opponents, fans out to 7). - computeSeatLayout() { - const numOpp = Math.min(this.opponents.length, 7); - const portraitR = numOpp >= 5 ? 58 : 72; - const { cx, cy, rx, ry } = SEAT_ELLIPSE; - const seats = [ - { x: CX, y: 900, portraitR: 85, portraitX: CX - 210, portraitY: 900 }, // human - ]; - // Spread opponents evenly around the whole ellipse. The human owns the - // bottom slot (270°); opponents fill the remaining ring symmetrically. - const cardHalfSpan = (CARD_W * 0.7 + 8) / 2 + CARD_W / 2; // half-width of an opponent's card pair - const n = numOpp + 1; - for (let i = 1; i <= numOpp; i++) { - const deg = 270 - (i * 360) / n; - const rad = (deg * Math.PI) / 180; - const ex = cx + rx * Math.cos(rad); // outer (on-ellipse) anchor - const ey = cy - ry * Math.sin(rad); - - // Seats near the horizontal axis are "side" seats: cards pulled toward the - // table interior, portrait beside them on the outer edge (vertically - // centred), name/chips stacked below the portrait. - if (Math.abs(ey - CY) <= 90) { - const interiorSign = ex < CX ? 1 : -1; - const cardX = ex + interiorSign * (portraitR + 14 + cardHalfSpan); - seats.push({ - x: cardX, y: ey, portraitR, - portraitX: ex, portraitY: ey, - side: ex < CX ? 'left' : 'right', interiorSign, - }); - continue; - } - - // Pull diagonal corner seats inward (seats on the vertical centre axis stay put). - const ax = ex + (Math.abs(ex - cx) > 1 ? (ex < cx ? CORNER_NUDGE : -CORNER_NUDGE) : 0); - - const flipped = ey > CY; // bottom-of-table seats: portrait below, cards toward centre - let portraitX, portraitY; - if (flipped) { - portraitX = ax; - portraitY = ey + CARD_H / 2 + portraitR + 8; - } else { - // Portrait sits above the cards; if that clips the top edge, place it - // beside the cards (toward the nearest screen edge) at card height. - const aboveY = ey - CARD_H / 2 - portraitR - 8; - if (aboveY >= portraitR + 4) { - portraitX = ax; - portraitY = aboveY; - } else { - const spacing = CARD_W * 0.7 + 8; - const sideSign = ax <= CX ? -1 : 1; - portraitX = ax + sideSign * (spacing / 2 + portraitR + 12); - portraitY = ey; - } - } - seats.push({ x: ax, y: ey, portraitR, portraitX, portraitY, flipped }); - } - this.seatPos = seats; - } - - buildSeatContainers() { - this.computeSeatLayout(); - for (let seat = 0; seat < this.seatPos.length; seat++) { - const sp = this.seatPos[seat]; - const { x, y, flipped, side } = sp; - const isHuman = seat === 0; - const container = this.add.container(x, y).setDepth(D.cards); - - // Label positions (local to the seat container). Side seats stack their - // name/chips directly below the portrait, which sits beside the cards; - // other seats keep them on the table-centre side of the cards. - let nameX = 0, chipX = 0, betX = 0, nameY, chipY, betY; - if (isHuman) { - nameY = -CARD_H / 2 - 48; chipY = -CARD_H / 2 - 24; betY = -CARD_H / 2 - 80; - } else if (side) { - nameX = chipX = sp.portraitX - x; - nameY = sp.portraitR + 26; chipY = sp.portraitR + 52; - betX = sp.interiorSign * 140; betY = 0; - } else if (flipped) { - nameY = -CARD_H / 2 - 28; chipY = -CARD_H / 2 - 52; betY = -CARD_H / 2 - 80; - } else { - nameY = CARD_H / 2 + 28; chipY = CARD_H / 2 + 52; betY = CARD_H / 2 + 80; - } - - // Name label - const name = this.add.text(nameX, nameY, '—', { - fontFamily: '"Julius Sans One"', - fontSize: '18px', - color: COLORS.textHex, - }).setOrigin(0.5); - - // Chip count - const chipTxt = this.add.text(chipX, chipY, '$0', { - fontFamily: '"Julius Sans One"', - fontSize: '20px', - color: '#f0e8d0', - }).setOrigin(0.5); - - // Bet display (shown between the seat and the table centre) - const betTxt = this.add.text(betX, betY, '', { - fontFamily: '"Julius Sans One"', - fontSize: '18px', - color: '#ffd700', - }).setOrigin(0.5); - - // Dealer chip - const dealerChip = this.add.circle(CARD_W / 2 + 16, -CARD_H / 2 + 16, 14, 0xf0e8d0).setVisible(false); - const dealerTxt = this.add.text(CARD_W / 2 + 16, -CARD_H / 2 + 16, 'D', { - fontFamily: '"Julius Sans One"', fontSize: '14px', color: '#1a1a1a', - }).setOrigin(0.5).setVisible(false); - - // Card containers — each holds graphics + text children - const cardObjs = []; - const spacing = isHuman ? CARD_W + 12 : CARD_W * 0.7 + 8; - const offsets = [-spacing / 2, spacing / 2]; - for (const ox of offsets) { - const cardCont = this.add.container(ox, 0).setVisible(false); - container.add(cardCont); - cardObjs.push(cardCont); - } - - container.add([name, chipTxt, betTxt, dealerChip, dealerTxt]); - this.seatContainers.push({ container, name, chipTxt, betTxt, cardObjs, dealerChip, dealerTxt }); - - // Portrait (world-space — outside the container) - const { x: px, y: py, portraitR, portraitX, portraitY: portraitYOverride } = this.seatPos[seat]; - const portraitWorldX = portraitX ?? px; - const portraitY = portraitYOverride ?? (isHuman - ? py - CARD_H / 2 - 48 - portraitR - 8 // above name label - : py - CARD_H / 2 - portraitR - 8); // above card area - - if (isHuman) { - this.portraits.push(createPlayerPortrait(this, portraitWorldX, portraitY, portraitR, D.ui, 'HoldemGame')); - } else { - const opp = this.opponents[seat - 1] ?? null; - this.portraits.push(createOpponentPortrait(this, opp, portraitWorldX, portraitY, portraitR, D.ui)); - } - } - } - - // ── Action buttons ────────────────────────────────────────────────────────── - - buildActionButtons() { - const btnY = 1020; - const foldBtn = new Button(this, CX - 240, btnY, 'Fold', () => this.playerAction({ type: 'fold' }), { variant: 'ghost', width: 160 }); - const callBtn = new Button(this, CX, btnY, 'Call', () => this.playerAction({ type: 'call' }), { width: 160 }); - const raiseBtn = new Button(this, CX + 240, btnY, 'Raise', () => this.toggleRaisePanel(), { width: 160 }); - foldBtn.setDepth(D.ui); - callBtn.setDepth(D.ui); - raiseBtn.setDepth(D.ui); - this.actionButtons = [foldBtn, callBtn, raiseBtn]; - this.callBtn = callBtn; - this.foldBtn = foldBtn; - this.raiseBtn = raiseBtn; - - this.buildRaisePanel(); - this.setActionButtonsVisible(false); - } - - buildLeaveButton() { - new Button(this, 90, GAME_HEIGHT - 36, 'Leave', () => this.scene.start('GameMenu'), { - variant: 'ghost', - width: 140, - height: 44, - }).setDepth(D.ui); - } - - buildRaisePanel() { - const panelY = 950; - this.raisePanel = this.add.container(CX, panelY).setDepth(D.ui).setVisible(false); - - const bg = this.add.rectangle(0, 0, 560, 68, 0x111923, 0.95) - .setStrokeStyle(1, COLORS.accent); - this.raiseAmtText = this.add.text(0, -10, '$0', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: '#f0e8d0', + g.fillEllipse(2, 4, r * 2.2, r * 2.2 * SQ); + g.fillStyle(color, 1); + g.fillCircle(0, 0, r); + g.lineStyle(2, 0x000000, 0.35); + g.strokeCircle(0, 0, r - 1); + g.lineStyle(1.5, 0xffffff, 0.5); + g.strokeCircle(0, 0, r - 4); + const t = this.add.text(0, 0, text, { + fontFamily: '"Julius Sans One"', fontSize: `${text.length > 2 ? 9 : 12}px`, color: textColor, fontStyle: 'bold', }).setOrigin(0.5); + c.add([g, t]); + c.setScale(1, SQ); + return c; + } - const minus = new Button(this, -200, 0, '−', () => this.adjustRaise(-this.raiseStep()), { width: 50, height: 40, fontSize: 22 }); - const plus = new Button(this, -130, 0, '+', () => this.adjustRaise(+this.raiseStep()), { width: 50, height: 40, fontSize: 22 }); - const allIn = new Button(this, 160, 0, 'All-In', () => this.playerAction({ type: 'allin' }), { width: 110, height: 40, fontSize: 18 }); - const go = new Button(this, 280, 0, 'Bet ✓', () => this.confirmRaise(), { width: 110, height: 40, fontSize: 18 }); + buildSeats() { + for (let seat = 1; seat <= this.n; seat++) { + const opp = this.opponents[seat - 1]; + const pt = this.L(seat).portrait; + const nameY = pt.y + pt.r + 18, chipY = nameY + 23; + this.nameTxts[seat] = this.add.text(pt.x, nameY, opp?.name ?? `Seat ${seat}`, { + fontFamily: '"Julius Sans One"', fontSize: '19px', color: COLORS.textHex, + }).setOrigin(0.5).setDepth(D.ui); + this.chipTxts[seat] = this.add.text(pt.x, chipY, '', { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(D.ui); + const rectW = Math.max(this.nameTxts[seat].width, 120) + 20; + const bg = this.add.graphics().setDepth(D.ui - 1); + bg.fillStyle(0x000000, 0.6); + bg.fillRoundedRect(pt.x - rectW / 2, nameY - 16, rectW, chipY - nameY + 32, 6); + this.portraits[seat] = createOpponentPortrait(this, opp, pt.x, pt.y, pt.r, D.ui); + } + this.turnRing = this.add.graphics().setDepth(D.ui + 3); + } - this.raisePanel.add([bg, this.raiseAmtText]); - // Buttons are already scene-level, just position them relative to panel - [minus, plus, allIn, go].forEach((btn) => { - btn.setDepth(D.modal); - btn.x += CX; - btn.y += panelY; + // ── Dock ─────────────────────────────────────────────────────────────────── + buildDock() { + this.dock = new CasinoDock(this, { + sceneName: 'HoldemGame', + portrait: this.L(0).portrait, + depth: { dock: D.dock, ui: D.ui, dockUi: D.dockUi, prompt: D.prompt }, + chipAmounts: [], + keys: { + act: 'F fold · C check / call · R or Enter bet · ← → size · A all-in', + wait: 'Pre-select your next move — it plays automatically when the action reaches you', + summary: 'Space continue', + }, }); - this.raisePanelButtons = [minus, plus, allIn, go]; - this.raisePanelButtons.forEach((b) => b.setVisible(false)); + this.portraits[0] = this.dock.portrait; + this.nameTxts[0] = this.dock.nameTxt; + this.chipTxts[0] = this.dock.balanceTxt; + this.dock.betPill.setVisible(false); + + this.handCaption = this.add.text(400, DOCK_Y - 20, '', { + fontFamily: '"Julius Sans One"', fontSize: '13px', color: COLORS.mutedHex, + }).setOrigin(0, 0.5).setDepth(D.dockUi); + this.handTxt = this.add.text(400, DOCK_Y + 10, '', { + fontFamily: '"Julius Sans One"', fontSize: '21px', color: COLORS.goldHex, fontStyle: 'bold', + }).setOrigin(0, 0.5).setDepth(D.dockUi); + + // act: Fold · Check/Call · slider + presets · Raise + this.foldBtn = new Button(this, 770, DOCK_Y, 'Fold', () => this.humanAct({ type: 'fold' }), { width: 120, height: 56, fontSize: 22, variant: 'ghost' }); + this.callBtn = new Button(this, 916, DOCK_Y, 'Check', () => this.onCallBtn(), { width: 160, height: 56, fontSize: 20 }); + this.raiseBtn = new Button(this, 1455, DOCK_Y, 'Raise', () => this.onRaiseBtn(), { width: 210, height: 56, fontSize: 19 }); + for (const b of [this.foldBtn, this.callBtn, this.raiseBtn]) b.setDepth(D.dockUi); + + const tx0 = 1030, tx1 = 1310, ty = DOCK_Y + 8; + this.slider = { x0: tx0, x1: tx1, y: ty, min: 0, max: 0, step: 5 }; + const track = this.add.graphics().setDepth(D.dockUi); + this.sliderTrack = track; + track.fillStyle(0x000000, 0.6); + track.fillRoundedRect(tx0 - 8, ty - 6, tx1 - tx0 + 16, 12, 6); + track.lineStyle(1.5, COLORS.accent, 0.7); + track.strokeRoundedRect(tx0 - 8, ty - 6, tx1 - tx0 + 16, 12, 6); + this.sliderFill = this.add.graphics().setDepth(D.dockUi + 1); + const trackZone = this.add.zone((tx0 + tx1) / 2, ty, tx1 - tx0 + 30, 34).setDepth(D.dockUi + 1) + .setInteractive({ useHandCursor: true }); + trackZone.on('pointerdown', (p) => this.setSliderFromX(p.worldX)); + this.trackZone = trackZone; + this.sliderHandle = this.add.circle(tx0, ty, 13, 0xf5d020).setStrokeStyle(3, 0x1a1208).setDepth(D.dockUi + 2) + .setInteractive({ useHandCursor: true, draggable: true }); + this.sliderHandle.on('drag', (_p, x) => this.setSliderFromX(x)); + this.sliderValue = this.add.text((tx0 + tx1) / 2, DOCK_Y - 26, '', { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: '#f7ecd0', fontStyle: 'bold', + }).setOrigin(0.5).setDepth(D.dockUi); + this.presetBtns = [['Min', 'min'], ['½ Pot', 'half'], ['¾ Pot', 'threeQuarter'], ['Pot', 'pot'], ['All-In', 'max']] + .map(([label, key], i) => { + const b = new Button(this, 1012 + i * 76, DOCK.y - 26, label, () => this.applyPreset(key), { + width: 70, height: 32, fontSize: 13, variant: 'ghost', + }).setDepth(D.dockUi); + b.presetKey = key; + return b; + }); + this.dock.addToGroup('act', this.foldBtn, this.callBtn, this.raiseBtn, track, this.sliderFill, trackZone, + this.sliderHandle, this.sliderValue, ...this.presetBtns); + for (const o of [trackZone, this.sliderHandle, this.foldBtn, this.callBtn, this.raiseBtn, ...this.presetBtns]) o._dockReenable = true; + + // wait: pre-action toggles + this.preBtns = [['Check / Fold', 'checkfold'], ['Check', 'check'], ['Call Any', 'callany']].map(([label, key], i) => { + const b = new Button(this, 780 + i * 168, DOCK_Y, label, () => this.togglePreAction(key), { + width: 156, height: 48, fontSize: 16, variant: 'ghost', + }).setDepth(D.dockUi); + b.preKey = key; + return b; + }); + this.waitTxt = this.add.text(1560, DOCK_Y, '', { + fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(D.dockUi); + for (const b of this.preBtns) b._dockReenable = true; + this.dock.addToGroup('wait', ...this.preBtns, this.waitTxt); } - raiseStep() { - if (!this.gs) return 5; - return this.gs.blind?.big ?? 10; + // mode: 'idle' | 'act' | 'wait' | 'summary' | 'busted' + setDockMode(mode, status = '') { + this.dockMode = mode; + this.dock.setMode(mode, mode === 'idle' ? status : ''); + if (mode === 'wait') this.refreshPreButtons(); } - adjustRaise(delta) { - if (!this.gs) return; - const p = this.gs.players[0]; - const min = minRaise(this.gs); - const max = p.chips + p.bet; - this.raiseValue = Math.max(min, Math.min(max, this.raiseValue + delta)); - this.raiseAmtText?.setText(`$${this.raiseValue}`); + // ── Tournament panel ─────────────────────────────────────────────────────── + buildPanel() { + const h = PANEL.h + 34; + ensureLeatherPanel(this, 'he-panel', PANEL.w, h, { radius: 14 }); + this.add.image(PANEL.x, PANEL.y, 'he-panel').setOrigin(0, 0).setDepth(D.ui); + const style = (size, color, bold) => ({ fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, ...(bold ? { fontStyle: 'bold' } : {}) }); + const x = PANEL.x + 20; + this.panelTxt = { + level: this.add.text(x, PANEL.y + 24, '', style(18, '#e8c15a', true)).setOrigin(0, 0.5).setDepth(D.ui + 1), + next: this.add.text(x, PANEL.y + 52, '', style(15, '#f2ead8')).setOrigin(0, 0.5).setDepth(D.ui + 1), + field: this.add.text(x, PANEL.y + 80, '', style(15, '#f2ead8')).setOrigin(0, 0.5).setDepth(D.ui + 1), + out: this.add.text(x, PANEL.y + 116, '', style(13, '#9e9080')).setOrigin(0, 0.5).setDepth(D.ui + 1), + }; } - toggleRaisePanel() { - const visible = !this.raisePanel.visible; - this.raisePanel.setVisible(visible); - this.raisePanelButtons.forEach((b) => b.setVisible(visible)); - if (visible && this.gs) { - this.raiseValue = minRaise(this.gs); - this.raiseAmtText?.setText(`$${this.raiseValue}`); - } - } - - confirmRaise() { - this.raisePanel.setVisible(false); - this.raisePanelButtons.forEach((b) => b.setVisible(false)); - this.playerAction({ type: 'raise', amount: this.raiseValue }); - } - - setActionButtonsVisible(visible) { - this.actionButtons.forEach((b) => b.setVisible(visible)); - if (!visible) { - this.raisePanel.setVisible(false); - this.raisePanelButtons.forEach((b) => b.setVisible(false)); - } - } - - updateActionButtons() { - if (!this.gs || this.gs.players[0].folded || this.gs.players[0].allIn) { - this.setActionButtonsVisible(false); - return; - } - const isMyTurn = this.gs.actionSeat === 0; - this.setActionButtonsVisible(isMyTurn); - if (!isMyTurn) return; - - const toCall = callAmount(this.gs, 0); - const check = canCheck(this.gs, 0); - - if (check) { - this.callBtn.setLabel('Check'); - this.raiseBtn.setLabel('Bet'); + updatePanel() { + const gs = this.gs; + if (!gs) return; + const elapsed = Date.now() - gs.gameStartMs; + const level = getBlindLevel(elapsed); + const idx = BLIND_LEVELS.indexOf(level); + const nextLevel = BLIND_LEVELS[idx + 1]; + this.panelTxt.level.setText(`LEVEL ${level.level} · BLINDS $${level.small} / $${level.big}`); + if (nextLevel) { + const remaining = Math.max(0, level.level * LEVEL_INTERVAL_MS - elapsed); + const m = Math.floor(remaining / 60000), s = Math.floor((remaining % 60000) / 1000); + this.panelTxt.next.setText(`Next $${nextLevel.small} / $${nextLevel.big} in ${m}:${String(s).padStart(2, '0')}`); } else { - this.callBtn.setLabel(`Call $${toCall}`); - this.raiseBtn.setLabel('Raise'); + this.panelTxt.next.setText('Final blind level'); + } + const live = gs.players.filter(p => !p.eliminated); + const avg = Math.round(gs.players.reduce((a, p) => a + p.chips + p.bet, 0) / Math.max(1, live.length)); + const human = gs.players[0]; + let rank = '—'; + if (!human.eliminated) { + rank = ordinal(1 + live.filter(p => p.seat !== 0 && p.chips + p.bet > human.chips + human.bet).length); + } else if (this.places.has(0)) rank = `out ${ordinal(this.places.get(0))}`; + this.panelTxt.field.setText(`Players ${live.length} / ${gs.players.length} · Avg $${avg} · You: ${rank}`); + this.panelTxt.out.setText(this.elimPics.length ? 'Eliminated' : ''); + } + + // ── Keyboard ─────────────────────────────────────────────────────────────── + onKey(e) { + const k = (e.key ?? '').toLowerCase(); + if (this.dockMode === 'act') { + const bb = this.gs?.blind?.big ?? 10; + if (k === 'f') this.humanAct({ type: 'fold' }); + else if (k === 'c') this.onCallBtn(); + else if (k === 'r' || k === 'enter') this.onRaiseBtn(); + else if (k === 'a') this.applyPreset('max'); + else if (k === 'arrowleft') this.setRaise(this.raiseValue - (e.shiftKey ? bb * 5 : bb)); + else if (k === 'arrowright') this.setRaise(this.raiseValue + (e.shiftKey ? bb * 5 : bb)); + } else if (this.dockMode === 'summary') { + if (k === ' ' || k === 'enter') this.continueFromSummary?.(); } } - // ── Buy-in modal ──────────────────────────────────────────────────────────── - - async showBuyInModal() { - // Fetch global balance + // ── Buy-in ───────────────────────────────────────────────────────────────── + async showBuyIn() { try { const { chips } = await api.get('/profile/chips'); this.globalChips = chips; } catch { this.globalChips = 0; } - - this.buyIn = Math.min(100, this.globalChips); - - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.75).setDepth(D.modal); - const panel = this.add.rectangle(CX, CY, 540, 340, COLORS.panel) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - - const title = this.add.text(CX, CY - 120, "Texas Hold 'Em", { - fontFamily: 'Righteous', fontSize: '36px', color: COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal); - - const balanceTxt = this.add.text(CX, CY - 60, `Your balance: $${this.globalChips.toLocaleString()}`, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modal); - - const buyInTxt = this.add.text(CX, CY - 20, `Buy-in: $${this.buyIn}`, { - fontFamily: '"Julius Sans One"', fontSize: '28px', color: '#ffd700', - }).setOrigin(0.5).setDepth(D.modal); - - const modalItems = [overlay, panel, title, balanceTxt, buyInTxt]; + if (!this.alive()) return; + const objs = []; + const add = (o) => { objs.push(o); return o; }; + add(this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6).setDepth(D.modal).setInteractive()); + ensureLeatherPanel(this, 'he-buyin', 640, 400, { radius: 22, felt: '#0f5a33' }); + add(this.add.image(CX, CY, 'he-buyin').setDepth(D.modal)); + const txt = (y, s, size, color, font = '"Julius Sans One"') => add(this.add.text(CX, y, s, { + fontFamily: font, fontSize: `${size}px`, color, + }).setOrigin(0.5).setDepth(D.modal + 1)); + txt(CY - 140, "Texas Hold 'Em", 40, COLORS.textHex, 'Righteous'); + txt(CY - 92, `${this.n + 1}-player tournament · blinds rise every 5 minutes`, 17, '#c9c2b0'); + txt(CY - 50, `Your balance: $${this.globalChips.toLocaleString()}`, 22, COLORS.mutedHex); if (this.globalChips <= 0) { - this.add.text(CX, CY + 40, 'You have no chips! Return to the menu.', { - fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.modal); + txt(CY + 20, 'You have no chips! Return to the menu.', 20, COLORS.dangerHex); + add(new Button(this, CX, CY + 110, 'Leave', () => this.scene.start('GameMenu'), { width: 200, variant: 'ghost' }).setDepth(D.modal + 1)); return; } - - const startBtn = new Button(this, CX, CY + 80, `Buy In — $${this.buyIn}`, async () => { - startBtn.setEnabled(false); - try { - const { chips } = await api.post('/profile/chips/adjust', { delta: -this.buyIn }); - this.globalChips = chips; - for (const item of modalItems) item.destroy(); - startBtn.destroy(); - this.beginGame(); - } catch { - startBtn.setEnabled(true); - } - }, { width: 260 }).setDepth(D.modal); - + txt(CY + 2, 'Choose your buy-in', 18, '#e8c15a'); + BUY_INS.forEach((amt, i) => { + const affordable = amt <= this.globalChips; + const b = add(new Button(this, CX - 190 + i * 190, CY + 70, `$${amt}`, async () => { + for (const o of objs) if (o.disableInteractive) o.disableInteractive(); + try { + const { chips } = await api.post('/profile/chips/adjust', { delta: -amt }); + this.globalChips = chips; + this.buyIn = amt; + for (const o of objs) o.destroy(); + this.beginGame(); + } catch { + for (const o of objs) if (o.setInteractive && o !== objs[0]) o.setInteractive?.(); + } + }, { width: 170, height: 60, fontSize: 26 }).setDepth(D.modal + 1)); + if (!affordable) b.setEnabled(false); + }); + if (this.globalChips < BUY_INS[0]) { + // Short-stacked: offer whatever is left. + const amt = this.globalChips; + add(new Button(this, CX, CY + 150, `Buy in for $${amt}`, async () => { + try { + const { chips } = await api.post('/profile/chips/adjust', { delta: -amt }); + this.globalChips = chips; + this.buyIn = amt; + for (const o of objs) o.destroy(); + this.beginGame(); + } catch { /* try again */ } + }, { width: 260, height: 50, fontSize: 20, variant: 'ghost' }).setDepth(D.modal + 1)); + } } - // ── Game flow ──────────────────────────────────────────────────────────────── - beginGame() { this.gs = createInitialState(this.opponents.slice(0, 7), this.buyIn); + this.renderSeatInfo(); + for (let s = 0; s <= this.n; s++) this.renderStack(s); + this.updatePanel(); this.dealNextHand(); } - dealNextHand() { - if (this.animating) return; - this.cleanupSummary(); - if (this.potChipDisplay) { this.potChipDisplay.destroy(); this.potChipDisplay = null; } - for (const cards of Object.values(this.foldedCardDisplays)) { - for (const c of cards) c.destroy(); - } - this.foldedCardDisplays = {}; - this.gs = startHand(this.gs); - - const newlyEliminated = this.gs.players.filter( - p => p.eliminated && !this.eliminatedSeats.has(p.seat) - ); - - if (newlyEliminated.length > 0) { - this.animating = true; - this._animateEliminations(newlyEliminated, () => { - this.animating = false; - this._proceedWithHand(); - }); - } else { - this._proceedWithHand(); + onLeave() { + const human = this.gs?.players[0]; + if (!human || human.eliminated || this.cashedOut || this.gs.phase === 'game_over') { + this.scene.start('GameMenu'); + return; } + const objs = []; + const add = (o) => { objs.push(o); return o; }; + add(this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.6).setDepth(D.modal + 10).setInteractive()); + ensureLeatherPanel(this, 'he-confirm', 560, 260, { radius: 20, felt: '#0f5a33' }); + add(this.add.image(CX, CY, 'he-confirm').setDepth(D.modal + 10)); + add(this.add.text(CX, CY - 60, `Cash out $${human.chips.toLocaleString()} and leave?`, { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: COLORS.textHex, + }).setOrigin(0.5).setDepth(D.modal + 11)); + add(this.add.text(CX, CY - 22, 'Chips already in this hand\'s pot are forfeited.', { + fontFamily: '"Julius Sans One"', fontSize: '15px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(D.modal + 11)); + add(new Button(this, CX - 110, CY + 60, 'Cash Out', async () => { + if (this.cashedOut) return; + this.cashedOut = true; + try { await api.post('/profile/chips/adjust', { delta: human.chips }); } catch { /* resyncs later */ } + this.scene.start('GameMenu'); + }, { width: 190, height: 54, fontSize: 20 }).setDepth(D.modal + 11)); + add(new Button(this, CX + 110, CY + 60, 'Keep Playing', () => objs.forEach(o => o.destroy()), { + width: 190, height: 54, fontSize: 20, variant: 'ghost', + }).setDepth(D.modal + 11)); } - _proceedWithHand() { - playSound(this, SFX.CARD_SHUFFLE); + // ── Hand lifecycle ───────────────────────────────────────────────────────── + async clearTable() { + for (const o of this.decor) { this.tweens.killTweensOf(o); o.destroy(); } + this.decor = []; + for (const p of this.potObjs) p.destroy(); + this.potObjs = []; + for (const b of Object.values(this.betObjs)) b.destroy(); + this.betObjs = {}; + const all = [...this.cards.values(), ...this.muckPile]; + this.cards.clear(); + this.muckPile = []; + if (!all.length) return; + playSound(this, SFX.CARD_PLACE); + const m = this.muckPos; + all.forEach((c, i) => { + c.setDepth(D.flying); + this.tweens.add({ + targets: c, x: m.x, y: m.y, rotation: (Math.random() - 0.5) * 0.3, scaleX: m.s, scaleY: m.s * SQ, + alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 380, delay: i * 12, ease: 'Cubic.easeInOut', + onComplete: () => c.destroy(), + }); + }); + await this.wait(400 + all.length * 12); + } - if (this.gs.phase === 'game_over') { + async dealNextHand() { + this.setDockMode('idle', ''); + this.clearTurnRing(); + await this.clearTable(); + if (!this.alive()) return; + for (const p of this.gs.players) this.handStartChips[p.seat] = p.chips; + this.preAction = null; + playSound(this, SFX.CARD_SHUFFLE); + this.gs = startHand(this.gs); + if (this.gs.phase === 'game_over' || !this.gs.blind || this.gs.players.filter(p => !p.eliminated).length < 2) { this.showGameOver(); return; } - // Render names/chips/pot but keep cards invisible until deal animation. - // renderBetChips() creates displays for SB/BB — hide them immediately so - // animateBlinds can reveal them with animation. - this.renderAll(); - for (const sc of this.seatContainers) { - for (const c of sc.cardObjs) c.setVisible(false); + const level = this.gs.blind.level; + if (this.lastBlindLevel && level > this.lastBlindLevel) { + const b = this.banner(`Blinds up — $${this.gs.blind.small} / $${this.gs.blind.big}`, 360, '#ffd700'); + this.time.delayedCall(1800, () => this.tweens.add({ targets: b, alpha: 0, duration: 300, onComplete: () => b.destroy() })); } - const { sbSeat, bbSeat } = this.gs; - if (this.betChipDisplays[sbSeat]) this.betChipDisplays[sbSeat].setVisible(false); - if (this.betChipDisplays[bbSeat]) this.betChipDisplays[bbSeat].setVisible(false); + this.lastBlindLevel = level; + this.updatePanel(); - this.animating = true; - this.animateBlinds(() => { - this.animateDeal(() => { - this.animating = false; - this.renderSeats(); - this.scheduleNextAction(); - }); - }); + await this.moveButtons(); + // blinds: chips slide from the stacks onto the line + const blinds = [this.gs.sbSeat, this.gs.bbSeat].filter(s => this.gs.players[s].bet > 0); + await Promise.all(blinds.map((seat, i) => this.pushChips(seat, this.gs.players[seat].bet, i * 160))); + this.renderBets(); + for (const s of blinds) this.renderStack(s); + this.renderSeatInfo(); + + await this.dealHoleCards(); + if (!this.alive()) return; + this.updateHandLabel(); + if (this.gs.phase === 'between_hands' || this.gs.phase === 'game_over') { + await this.endOfHand(0); + return; + } + this.nextTurn(); } - // ── Eliminated panel ───────────────────────────────────────────────────────── - - // Panel constants (game coordinates). PANEL_W is wide enough for all 8 seats. - // Pics are placed right-to-left (rightmost = first eliminated). - // Anchored to the lower-right corner regardless of size. - static get ELIM() { - return { - RIGHT: GAME_WIDTH - 18, // 1902 — right anchor - BOTTOM: GAME_HEIGHT - 18, // 1062 — bottom anchor - PANEL_H: 120, - PANEL_W: 380, // fits title + up to 8 × 36 px pics + gaps - PAD_X: 16, - PAD_Y: 14, - PIC_R: 18, // portrait radius (36 px diameter ≈ title font height) - PIC_GAP: 8, - DEPTH: 31, // D.ui + 1 — above gameplay, below modals + async moveButtons() { + const { dealerSeat, sbSeat, bbSeat } = this.gs; + const L = this.L(dealerSeat); + const puck = this.dealerPuck; + if (!puck.visible) puck.setPosition(L.button.x, L.button.y).setVisible(true); + const tween = this.tweenP({ targets: puck, x: L.button.x, y: L.button.y, duration: 420, ease: 'Cubic.easeInOut' }); + const placeBlind = (p, seat) => { + const spot = this.L(seat).blind; // just inboard of the bet, clear of its amount pill + p.setPosition(spot.x, spot.y).setVisible(true).setAlpha(0); + this.tweens.add({ targets: p, alpha: 1, duration: 200 }); }; + placeBlind(this.sbPuck, sbSeat); + placeBlind(this.bbPuck, bbSeat); + await tween; } - buildEliminatedPanel() { - const { RIGHT, BOTTOM, PANEL_H, PANEL_W, PAD_X, PAD_Y, DEPTH } = HoldemGame.ELIM; - const panelCY = BOTTOM - PANEL_H / 2; - const panelCX = RIGHT - PANEL_W / 2; - - this.eliminatedBg = this.add.rectangle(panelCX, panelCY, PANEL_W, PANEL_H, 0x0a0a16, 0.85) - .setStrokeStyle(1, 0x8a7050) - .setDepth(DEPTH) - .setAlpha(0); - - this.eliminatedTitleTxt = this.add.text(RIGHT - PAD_X, BOTTOM - PANEL_H + PAD_Y, 'Eliminated', { - fontFamily: 'Righteous', - fontSize: '34px', - color: COLORS.mutedHex, - }).setOrigin(1, 0).setDepth(DEPTH + 1).setAlpha(0); - - this.eliminatedPicList = []; // { backing, portraitObj, maskG } - } - - addToEliminatedPanel(player) { - const { RIGHT, BOTTOM, PAD_X, PAD_Y, PIC_R, PIC_GAP, DEPTH } = HoldemGame.ELIM; - - const n = this.eliminatedPicList.length; // pics already in panel - const picX = RIGHT - PAD_X - PIC_R - n * (PIC_R * 2 + PIC_GAP); - const picY = BOTTOM - PAD_Y - PIC_R; - - // Fade in panel on first elimination - if (n === 0) { - this.tweens.add({ targets: [this.eliminatedBg, this.eliminatedTitleTxt], alpha: 1, duration: 300 }); - } - - // Backing circle - const backing = this.add.circle(picX, picY, PIC_R, 0x1a1a2e).setDepth(DEPTH + 1).setAlpha(0); - - let portraitObj = null; - let maskG = null; - - if (!player.isHuman) { - const opp = this.opponents[player.seat - 1]; - if (opp && this.textures.exists('opponents')) { - maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); - maskG.fillCircle(picX, picY, PIC_R); - portraitObj = this.add.image(picX, picY, 'opponents', opp.spriteIndex ?? 0) - .setDisplaySize(PIC_R * 2, PIC_R * 2) - .setMask(maskG.createGeometryMask()) - .setDepth(DEPTH + 2) - .setAlpha(0); - } - } else { - // Try a loaded avatar texture - const avatarKey = Object.keys(this.textures.list).find(k => k.startsWith('player-avatar-')); - if (avatarKey) { - maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); - maskG.fillCircle(picX, picY, PIC_R); - portraitObj = this.add.image(picX, picY, avatarKey) - .setDisplaySize(PIC_R * 2, PIC_R * 2) - .setMask(maskG.createGeometryMask()) - .setDepth(DEPTH + 2) - .setAlpha(0); - } else { - const initial = (auth.user?.username ?? 'You').charAt(0).toUpperCase(); - portraitObj = this.add.text(picX, picY, initial, { - fontFamily: '"Julius Sans One"', - fontSize: `${PIC_R + 2}px`, - color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(DEPTH + 2).setAlpha(0); - } - } - - const fadeIn = [backing]; - if (portraitObj) fadeIn.push(portraitObj); - this.tweens.add({ targets: fadeIn, alpha: 1, duration: 300 }); - - this.eliminatedPicList.push({ backing, portraitObj, maskG }); - } - - _animateEliminations(newlyEliminated, callback) { - const { RIGHT, BOTTOM, PAD_X, PAD_Y, PIC_R } = HoldemGame.ELIM; - const targetX = RIGHT - PAD_X - PIC_R; // world x of first panel pic - const targetY = BOTTOM - PAD_Y - PIC_R; // world y of pic row - - let pending = newlyEliminated.length; - const done = () => { if (--pending === 0) callback(); }; - - for (const player of newlyEliminated) { - const seat = player.seat; - const sp = this.seatPos[seat]; - const px = sp.portraitX ?? sp.x; - const py = sp.portraitY ?? sp.y; - const pr = sp.portraitR; - - this.portraits[seat]?.stopVideo(); - this.portraits[seat]?.fadeToEliminated(700); - - // Build an animation clone: backing circle + face - const animContainer = this.add.container(px, py).setDepth(D.modal); - const bg = this.add.circle(0, 0, pr, 0x1a1a2e); - animContainer.add(bg); - - if (!player.isHuman) { - const opp = this.opponents[seat - 1]; - if (opp && this.textures.exists('opponents')) { - const face = this.add.image(0, 0, 'opponents', opp.spriteIndex ?? 0) - .setDisplaySize(pr * 2, pr * 2); - animContainer.add(face); - } - } else { - const initial = (auth.user?.username ?? 'You').charAt(0).toUpperCase(); - const lbl = this.add.text(0, 0, initial, { - fontFamily: '"Julius Sans One"', - fontSize: `${Math.round(pr * 0.9)}px`, - color: COLORS.accentHex, - }).setOrigin(0.5); - animContainer.add(lbl); - } - - this.tweens.add({ - targets: animContainer, - x: targetX, y: targetY, - scaleX: PIC_R / pr, scaleY: PIC_R / pr, - alpha: 0, - duration: 750, - ease: 'Power2.easeIn', - onComplete: () => { - this.addToEliminatedPanel(player); - this.eliminatedSeats.add(seat); - animContainer.destroy(); - done(); - }, - }); - } - } - - scheduleNextAction() { - if (!this.gs || this.gs.phase === 'game_over' || this.gs.phase === 'between_hands') return; - - const seat = this.gs.actionSeat; - if (seat === 0) { - // Human's turn - this.updateActionButtons(); - } else { - // AI's turn — delay then act - this.setActionButtonsVisible(false); - this.time.delayedCall(AI_ACTION_DELAY_MS, () => this.runAIAction(seat)); - } - } - - runAIAction(seat) { - if (!this.gs || this.gs.actionSeat !== seat) return; - const action = chooseAction(this.gs, seat); - this.applyAndAdvance(seat, action); - } - - playerAction(action) { - if (!this.gs || this.gs.actionSeat !== 0 || this.animating) return; - this.setActionButtonsVisible(false); - this.applyAndAdvance(0, action); - } - - applyAndAdvance(seat, action) { - const prevPhase = this.gs.phase; - const prevCommunityCount = this.gs.community.length; - // Snapshot bets before applyAction collects them into the pot - const prevBets = this.gs.players - .filter(p => p && p.bet > 0) - .map(p => ({ seat: p.seat, bet: p.bet })); - - this.gs = applyAction(this.gs, seat, action); - - this.showActionBadge(seat, action); - this.animating = true; - - this.playActionAnimation(seat, action, () => { - this.animating = false; - this.renderAll(); - // Suppress any new community cards immediately so they don't flash - // visible before the deal animation reveals them one by one. - for (let i = prevCommunityCount; i < this.gs.community.length; i++) { - const slot = this.communitySlots[i]; - if (slot.cardObj) slot.cardObj.setVisible(false); - } - - if (this.gs.phase === 'game_over') { - this.time.delayedCall(800, () => this.showGameOver()); - return; - } - - if (this.gs.phase !== prevPhase) { - // Betting round ended — animate bets to pot, then continue - this.time.delayedCall(150, () => { - this.animateChipsToPot(prevBets, () => { - this.rebuildPotChipDisplay(); - if (this.gs.phase === 'between_hands') { - this.time.delayedCall(350, () => this.showHandSummary()); - } else { - this.time.delayedCall(150, () => { - this.animateCommunityReveal(prevCommunityCount, () => { - this.time.delayedCall(200, () => this.scheduleNextAction()); - }); - }); - } - }); - }); - } else { - this.time.delayedCall(200, () => this.scheduleNextAction()); - } - }); - } - - // ── Action animations ───────────────────────────────────────────────────────── - - // Returns world coords of the "bet zone" in front of a seat (between seat and table centre). - betZone(seat) { - const { x, y } = this.seatPos[seat]; - const dx = CX - x; - const dy = CY - y; - const len = Math.sqrt(dx * dx + dy * dy); - // Seats on the vertical centre axis shift their bet zone right so chip - // stacks don't overlap the name/chip-count text centred at CX. - const xOffset = Math.abs(x - CX) < 120 ? 160 : 0; - return { x: x + (dx / len) * 140 + xOffset, y: y + (dy / len) * 100 }; - } - - playActionAnimation(seat, action, onComplete) { - switch (action.type) { - case 'fold': return this.animateFold(seat, onComplete); - case 'call': - case 'raise': - case 'allin': return this.animateChips(seat, onComplete); - default: return onComplete(); // check — no animation - } - } - - animateFold(seat, onComplete) { - playSound(this, SFX.CARD_PLACE); - const sc = this.seatContainers[seat]; - const { x: sx, y: sy } = this.seatPos[seat]; - const { x: tx, y: ty } = this.betZone(seat); - - const tempCards = sc.cardObjs - .filter(c => c.visible) - .map(cardCont => { - const wx = sx + cardCont.x; - const wy = sy + cardCont.y; - const temp = this.add.container(wx, wy).setDepth(D.cards + 5); - if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - temp.add( - this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H).setOrigin(0.5) - ); - } else { - const g = this.add.graphics(); - this.drawCardBack(g, -CARD_W / 2, -CARD_H / 2); - temp.add(g); - } - cardCont.setVisible(false); - return temp; - }); - - if (tempCards.length === 0) { onComplete(); return; } - - // Slight rotation: tilt toward the table edge based on which side the seat is on - const angle = seat === 0 ? 10 : (sx < CX ? -14 : sx > CX ? 14 : -10); - - this.tweens.add({ - targets: tempCards, - x: tx, - y: ty, - alpha: 0.28, - angle, - duration: 400, - ease: 'Power2.easeOut', - onComplete: () => { - this.time.delayedCall(150, () => { - this.foldedCardDisplays[seat] = tempCards; - onComplete(); - }); - }, - }); - } - - animateChips(seat, onComplete) { - const { x: sx, y: sy } = this.seatPos[seat]; - const { x: tx, y: ty } = this.betZone(seat); - - playChipBet(this); - const CHIP_COLORS = [0xf0e8d0, 0x4a90d9, 0xe05c5c, 0x5cb85c, 0xf0a830]; - const allObjs = []; - let done = 0; - - for (let i = 0; i < CHIP_COLORS.length; i++) { - const startX = sx + (Math.random() - 0.5) * 20; - const startY = sy + (Math.random() - 0.5) * 20; - const endX = tx + (Math.random() - 0.5) * 28; - const endY = ty + (Math.random() - 0.5) * 20; - - const chip = this.add.circle(startX, startY, 11, CHIP_COLORS[i]).setDepth(D.chips + 5 + i); - const ring = this.add.circle(startX, startY, 7, 0x000000, 0.2).setDepth(D.chips + 6 + i); - allObjs.push(chip, ring); - - this.tweens.add({ - targets: [chip, ring], - x: endX, - y: endY, - duration: 330, - delay: i * 45, - ease: 'Power2.easeOut', - onComplete: () => { - done++; - if (done === CHIP_COLORS.length) { - this.time.delayedCall(160, () => { - allObjs.forEach(c => c.destroy()); - onComplete(); - }); - } - }, - }); - } - } - - // ── Chips-to-pot animation ──────────────────────────────────────────────────── - - // Fly temporary chip stacks from each seat's bet zone to the pot area. - // prevBets is [{ seat, bet }] captured before applyAction ran. - animateChipsToPot(prevBets, onComplete) { - if (prevBets.length === 0) { onComplete(); return; } - - const POT_X = CX - 110; - const POT_Y = CY - CARD_H / 2 - 36; - const CHIP_COLORS = [0xf0e8d0, 0x4a90d9, 0xe05c5c, 0x5cb85c, 0xf0a830]; - const big = this.gs.blind?.big ?? 10; - let done = 0; - - prevBets.forEach(({ seat, bet }, idx) => { - const { x: bx, y: by } = this.betZone(seat); - const numChips = Math.min(5, Math.max(1, Math.ceil(bet / big))); - - const cont = this.add.container(bx, by).setDepth(D.chips + 8); - for (let i = 0; i < numChips; i++) { - const g = this.add.graphics(); - g.fillStyle(CHIP_COLORS[i % CHIP_COLORS.length], 1); - g.fillCircle(0, -i * 5, 12); - g.lineStyle(1.5, 0xffffff, 0.25); - g.strokeCircle(0, -i * 5, 12); - cont.add(g); - } - - this.tweens.add({ - targets: cont, - x: POT_X, - y: POT_Y, - duration: 320, - delay: idx * 70, - ease: 'Power2.easeIn', - onComplete: () => { - cont.destroy(); - done++; - if (done === prevBets.length) onComplete(); - }, - }); - }); - } - - // Build (or rebuild) the persistent chip stack display beside the Pot label. - rebuildPotChipDisplay() { - if (this.potChipDisplay) { this.potChipDisplay.destroy(); this.potChipDisplay = null; } - const pot = this.gs?.pot ?? 0; - if (pot <= 0) return; - - const POT_X = CX - 110; - const POT_Y = CY - CARD_H / 2 - 36; - const CHIP_COLORS = [0xf0e8d0, 0x4a90d9, 0xe05c5c, 0x5cb85c, 0xf0a830]; - const big = this.gs.blind?.big ?? 10; - - const cont = this.add.container(POT_X, POT_Y).setDepth(D.chips + 2).setAlpha(0); - - // Arrange chips in a 3-column cluster so a large pot looks dense, not just tall - const total = Math.min(12, Math.max(1, Math.ceil(pot / (big * 2)))); - const COLS = 3; - const COL_GAP = 16; - const ROW_GAP = 6; - const startX = -((Math.min(COLS, total) - 1) * COL_GAP) / 2; - - for (let i = 0; i < total; i++) { - const col = i % COLS; - const row = Math.floor(i / COLS); - const g = this.add.graphics(); - g.fillStyle(CHIP_COLORS[i % CHIP_COLORS.length], 1); - g.fillCircle(startX + col * COL_GAP, -row * ROW_GAP, 13); - g.lineStyle(1.5, 0xffffff, 0.25); - g.strokeCircle(startX + col * COL_GAP, -row * ROW_GAP, 13); - cont.add(g); - } - - this.tweens.add({ targets: cont, alpha: 1, duration: 180, ease: 'Power2.easeOut' }); - this.potChipDisplay = cont; - } - - // ── Blind animations ────────────────────────────────────────────────────────── - - // Animate SB then BB posting chips, then reveal their persistent stacks. - animateBlinds(onComplete) { - const { sbSeat, bbSeat } = this.gs; - this.animateChips(sbSeat, () => { - if (this.betChipDisplays[sbSeat]) this.betChipDisplays[sbSeat].setVisible(true); - this.time.delayedCall(120, () => { - this.animateChips(bbSeat, () => { - if (this.betChipDisplays[bbSeat]) this.betChipDisplays[bbSeat].setVisible(true); - this.time.delayedCall(120, onComplete); - }); - }); - }); - } - - // ── Bet zone chip stack display ──────────────────────────────────────────────── - - renderBetChips() { - for (const d of Object.values(this.betChipDisplays)) d?.destroy(); - this.betChipDisplays = {}; - if (!this.gs) return; - - const CHIP_COLORS = [0xf0e8d0, 0x4a90d9, 0xe05c5c, 0x5cb85c, 0xf0a830]; - const big = this.gs.blind?.big ?? 10; - - for (const p of this.gs.players) { - if (!p || p.bet <= 0) continue; - const { x, y } = this.betZone(p.seat); - const cont = this.add.container(x, y).setDepth(D.chips + 2); - - const numChips = Math.min(6, Math.max(1, Math.ceil(p.bet / big))); - for (let i = 0; i < numChips; i++) { - const g = this.add.graphics(); - g.fillStyle(CHIP_COLORS[i % CHIP_COLORS.length], 1); - g.fillCircle(0, -i * 5, 12); - g.lineStyle(1.5, 0xffffff, 0.25); - g.strokeCircle(0, -i * 5, 12); - cont.add(g); - } - - const label = this.add.text(0, 22, `$${p.bet}`, { - fontFamily: '"Julius Sans One"', - fontSize: '15px', - color: '#f0e8d0', - stroke: '#000000', - strokeThickness: 3, - }).setOrigin(0.5); - cont.add(label); - - this.betChipDisplays[p.seat] = cont; - } - } - - // ── Deal animations ─────────────────────────────────────────────────────────── - - // Animate hole cards flying from the deck (centre) to each seat, one at a time. - animateDeal(onComplete) { - // Deal order: opponents around the table (seats 1..n-1) then the human (0), - // one pass, then a second pass (standard poker) + // Deal two cards to every live player, starting left of the dealer. + async dealHoleCards() { const n = this.gs.players.length; const order = []; - for (let s = 1; s < n; s++) order.push(s); - order.push(0); - const seatOrder = order.filter((s) => !this.gs.players[s]?.eliminated); - const sequence = [...seatOrder, ...seatOrder]; // card 0 then card 1 - - let done = 0; - const CARD_DELAY = 120; // ms between each card leaving the deck - const CARD_DURATION = 220; - - sequence.forEach((seat, idx) => { - const cardIdx = idx < seatOrder.length ? 0 : 1; - const { x: sx, y: sy } = this.seatPos[seat]; - const isHuman = seat === 0; - const spacing = isHuman ? CARD_W + 12 : CARD_W * 0.7 + 8; - const targetX = sx + (cardIdx === 0 ? -spacing / 2 : spacing / 2); - const targetY = sy; - - this.time.delayedCall(idx * CARD_DELAY, () => { - const cardCont = this.add.container(CX, CY).setDepth(D.cards + 10); - const g = this.add.graphics(); - this.drawCardBack(g, -CARD_W / 2, -CARD_H / 2); - cardCont.add(g); - - this.tweens.add({ - targets: cardCont, - x: targetX, - y: targetY, - duration: CARD_DURATION, - ease: 'Power2.easeOut', - onComplete: () => { - cardCont.destroy(); - playSound(this, SFX.CARD_DEAL); - const sc = this.seatContainers[seat]; - if (sc?.cardObjs[cardIdx]) sc.cardObjs[cardIdx].setVisible(true); - done++; - if (done === sequence.length) onComplete(); - }, + for (let i = 1; i <= n; i++) { + const s = (this.gs.dealerSeat + i) % n; + if (!this.gs.players[s].eliminated) order.push(s); + } + let last = null; + for (let i = 0; i < 2; i++) { + for (const seat of order) { + const pose = this.L(seat).cards[i]; + const card = this.gs.players[seat].hand[i]; + const { c, promise } = this.skin.deal(card, false, this.deckPos, pose, { + duration: 260, flyingDepth: D.flying, sound: () => playSound(this, SFX.CARD_DEAL), }); - }); + this.cards.set(`${seat}:${i}`, c); + last = promise; + await this.wait(85); + } + } + await last; + // you peek at your cards + await Promise.all([0, 1].map(i => { + const c = this.cards.get(`0:${i}`); + return c ? this.wait(i * 90).then(() => this.skin.flip(c, true, 280)) : null; + })); + } + + updateHandLabel() { + const human = this.gs.players[0]; + if (human.eliminated || !human.hand?.length) { this.handCaption.setText(''); this.handTxt.setText(''); return; } + this.handCaption.setText(human.folded ? 'FOLDED' : 'YOUR HAND'); + this.handTxt.setText(handLabel(human.hand, this.gs.community)).setColor(human.folded ? COLORS.mutedHex : COLORS.goldHex); + } + + // ── Turns ────────────────────────────────────────────────────────────────── + nextTurn() { + if (!this.alive() || !this.gs) return; + const gs = this.gs; + if (gs.phase === 'between_hands' || gs.phase === 'game_over') return; + const seat = gs.actionSeat; + const human = gs.players[0]; + if (seat === 0) { + const auto = this.resolvePreAction(); + if (auto) { this.clearTurnRing(); this.act(0, auto); return; } + this.showTurnRing(0, 0); + this.showActDock(); + return; + } + const inHand = !human.folded && !human.eliminated && !human.allIn; + this.setDockMode(inHand ? 'wait' : 'idle', inHand ? '' : (human.eliminated ? 'Watching the table' : '')); + this.waitTxt?.setText(`${gs.players[seat].name} is thinking…`); + const action = chooseAction(gs, seat); + const ms = this.thinkTime(action, seat); + this.showTurnRing(seat, ms); + this.time.delayedCall(ms, () => { + if (!this.alive() || this.gs.actionSeat !== seat) return; + this.act(seat, action); }); } - // Animate newly added community cards flying face-up from deck to their slot. - animateCommunityReveal(prevCount, onComplete) { - const newCount = this.gs.community.length; - if (newCount <= prevCount) { onComplete(); return; } - - // Hide pre-rendered slot cards — the flying animation reveals each on arrival - for (let i = prevCount; i < newCount; i++) { - const slot = this.communitySlots[i]; - if (slot.cardObj) slot.cardObj.setVisible(false); - } - - let done = 0; - const toReveal = newCount - prevCount; - const CARD_DELAY = 1200; - const FLY_DURATION = 260; - - for (let i = prevCount; i < newCount; i++) { - const slot = this.communitySlots[i]; - const card = this.gs.community[i]; - const delay = (i - prevCount) * CARD_DELAY; - - this.time.delayedCall(delay, () => { - // Fly a face-up card from the deck position to the slot - const temp = this.add.container(CX, CY).setDepth(D.cards + 10); - this.renderCard(temp, card, true); - - this.tweens.add({ - targets: temp, - x: slot.container.x, - y: slot.container.y, - duration: FLY_DURATION, - ease: 'Power2.easeOut', - onComplete: () => { - temp.destroy(); - if (!slot.cardObj) { - slot.cardObj = this.add.container(0, 0); - slot.container.add(slot.cardObj); - this.renderCard(slot.cardObj, card, true); - } - slot.cardObj.setVisible(true); - playSound(this, SFX.CARD_SHOW); - done++; - if (done === toReveal) onComplete(); - }, - }); - }); + thinkTime(action, seat) { + const p = this.gs.players[seat]; + const toCall = callAmount(this.gs, seat); + const r = (a, b) => a + Math.random() * (b - a); + const big = toCall > (p.chips + p.bet) * 0.3; + switch (action.type) { + case 'fold': return r(420, 760) + (big ? 500 : 0); + case 'check': return r(480, 880); + case 'call': return r(780, 1350) + (big ? 900 : 0); + case 'raise': return r(1050, 1850); + case 'allin': return r(1500, 2500); + default: return 800; } } - // ── Rendering ──────────────────────────────────────────────────────────────── - - renderAll() { - if (!this.gs) return; - this.renderSeats(); - this.renderCommunity(); - this.renderBetChips(); - this.updatePotDisplay(); - } - - renderSeats() { - for (let seat = 0; seat < this.seatContainers.length; seat++) { - const sc = this.seatContainers[seat]; - const p = this.gs.players[seat]; - if (!p) continue; - - sc.name.setText(p.name ?? '—'); - sc.chipTxt.setText(p.eliminated ? 'ELIMINATED' : `$${p.chips}`); - sc.betTxt.setText(''); - - // Dealer chip - const isDealer = p.seat === this.gs.dealerSeat; - sc.dealerChip.setVisible(isDealer); - sc.dealerTxt.setVisible(isDealer); - - // Card visibility - const showCards = !p.eliminated && !p.folded && this.gs.phase !== 'waiting'; - const faceUp = p.isHuman || this.gs.phase === 'showdown'; - for (let c = 0; c < sc.cardObjs.length; c++) { - const cardCont = sc.cardObjs[c]; - const hasCard = showCards && p.hand[c] !== undefined; - cardCont.setVisible(hasCard); - if (hasCard) this.renderCard(cardCont, p.hand[c], faceUp); - } - - // Dim folded/eliminated players - sc.container.setAlpha(p.eliminated ? 0.3 : p.folded ? 0.5 : 1); - - // Highlight active seat - if (seat === this.gs.actionSeat) { - this.tweens.add({ - targets: sc.container, - alpha: { from: 1, to: 0.7 }, - duration: 400, yoyo: true, repeat: 2, - }); - } - } - } - - renderCommunity() { - for (let i = 0; i < 5; i++) { - const slot = this.communitySlots[i]; - const card = this.gs?.community[i]; - if (card) { - if (!slot.cardObj) { - slot.cardObj = this.add.container(0, 0); - slot.container.add(slot.cardObj); - } - this.renderCard(slot.cardObj, card, true); - } else if (slot.cardObj) { - slot.cardObj.removeAll(true); - } - } - } - - updatePotDisplay() { - const total = (this.gs?.pot ?? 0) - + (this.gs?.players ?? []).reduce((s, p) => s + p.bet, 0); - this.potText?.setText(`Pot: $${total}`); - } - - // ── Card rendering ──────────────────────────────────────────────────────────── - // Each card is a Phaser Container. Children (Graphics + Text) are local to - // the container so their x/y are relative coordinates — no absolute-scene - // coordinate bugs. - - renderCard(container, card, faceUp) { - container.removeAll(true); // destroy previous children - - const x = -CARD_W / 2; - const y = -CARD_H / 2; - - if (faceUp && card) { - const g = this.add.graphics(); - g.fillStyle(0xffffff, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(1, 0xcccccc, 1); - g.strokeRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - container.add(g); - - const color = card.isRed ? '#c0392b' : '#1a1a2e'; - const sym = card.suitSymbol; - const style = (size, bold = false) => ({ - fontFamily: '"Julius Sans One"', - fontSize: `${size}px`, - color, - ...(bold ? { fontStyle: 'bold' } : {}), - }); - - // All text is added to the container → coordinates are local to card - container.add(this.add.text(x + 7, y + 5, card.label, style(18, true))); - container.add(this.add.text(x + 7, y + 24, sym, style(14))); - container.add(this.add.text(0, 0, sym, style(44)).setOrigin(0.5)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 8, card.label, style(18, true)).setOrigin(1, 1)); - container.add(this.add.text(x + CARD_W - 7, y + CARD_H - 24, sym, style(14)).setOrigin(1, 1)); - } else if (this.cardBack?.spriteIndex !== undefined && this.textures.exists('cardbacks')) { - container.add( - this.add.image(0, 0, 'cardbacks', this.cardBack.spriteIndex) - .setDisplaySize(CARD_W, CARD_H) - .setOrigin(0.5) - ); + showTurnRing(seat, ms) { + this.clearTurnRing(); + const pt = this.L(seat).portrait; + const g = this.turnRing; + const draw = (t) => { + g.clear(); + g.lineStyle(6, 0x000000, 0.45); + g.strokeCircle(pt.x, pt.y, pt.r + 9); + g.lineStyle(5, t < 0.75 ? 0xf5d020 : 0xff6b35, 1); + g.beginPath(); + g.arc(pt.x, pt.y, pt.r + 9, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * (1 - t), false); + g.strokePath(); + }; + if (ms > 0) { + const prox = { t: 0 }; + this.ringTween = this.tweens.add({ targets: prox, t: 1, duration: ms, onUpdate: () => draw(prox.t) }); } else { - const g = this.add.graphics(); - this.drawCardBack(g, x, y); - container.add(g); + // the human: a calm pulsing gold ring, no clock + draw(0); + g.setAlpha(1); + this.ringTween = this.tweens.add({ targets: g, alpha: 0.45, duration: 650, yoyo: true, repeat: -1 }); + } + this.nameTxts[seat]?.setColor(COLORS.accentHex); + this.ringSeat = seat; + } + + clearTurnRing() { + this.ringTween?.remove(); + this.ringTween = null; + this.turnRing?.clear().setAlpha(1); + if (this.ringSeat !== undefined) this.nameTxts[this.ringSeat]?.setColor(COLORS.textHex); + this.ringSeat = undefined; + } + + // ── Human controls ───────────────────────────────────────────────────────── + showActDock() { + const gs = this.gs; + const p = gs.players[0]; + const toCall = callAmount(gs, 0); + const check = canCheck(gs, 0); + this.setDockMode('act'); + this.callBtn.setLabel(check ? 'Check' : toCall >= p.chips ? `Call $${toCall} (All-In)` : `Call $${toCall}`); + const sizes = raiseSizes(gs, 0); + this.sizes = sizes; + const canRaise = p.chips > toCall && sizes.max > gs.roundBet; + this.slider.min = sizes.min; + this.slider.max = sizes.max; + this.slider.step = gs.blind?.big >= 50 ? 25 : 5; + this.foldBtn.setEnabled(true); + this.callBtn.setEnabled(true); + const raiseUi = [this.raiseBtn, this.sliderHandle, this.sliderValue, this.sliderFill, this.sliderTrack, this.trackZone, ...this.presetBtns]; + for (const o of raiseUi) o.setVisible(canRaise); + if (!canRaise) { + for (const o of raiseUi) o.disableInteractive?.(); + } else { + this.raiseBtn.setEnabled(true); + this.presetBtns.forEach(b => b.setEnabled(sizes[b.presetKey] >= sizes.min && sizes[b.presetKey] <= sizes.max)); + } + this.setRaise(sizes.min); + } + + setRaise(v) { + if (!this.sizes) return; + const { min, max } = this.slider; + const step = this.slider.step; + let val = Math.round(v / step) * step; + if (v >= max) val = max; + val = Math.max(min, Math.min(max, val)); + this.raiseValue = val; + const t = max > min ? (val - min) / (max - min) : 1; + const x = this.slider.x0 + t * (this.slider.x1 - this.slider.x0); + this.sliderHandle.x = x; + this.sliderFill.clear(); + this.sliderFill.fillStyle(0xd4a017, 0.9); + this.sliderFill.fillRoundedRect(this.slider.x0 - 6, this.slider.y - 4, x - this.slider.x0 + 6, 8, 4); + const allIn = val >= max; + const check = canCheck(this.gs, 0); + this.sliderValue.setText(allIn ? `ALL IN $${val}` : `$${val}`); + this.raiseBtn.setLabel(allIn ? `All-In $${val}` : check ? `Bet $${val}` : `Raise to $${val}`); + } + + setSliderFromX(x) { + const { x0, x1, min, max } = this.slider; + const t = Math.max(0, Math.min(1, (x - x0) / (x1 - x0))); + this.setRaise(min + t * (max - min)); + } + + applyPreset(key) { + if (this.dockMode !== 'act' || !this.sizes) return; + if (key === 'max' && !this.raiseBtn.visible) { this.onCallBtn(); return; } + this.setRaise(this.sizes[key]); + } + + onCallBtn() { + if (this.dockMode !== 'act') return; + this.humanAct(canCheck(this.gs, 0) ? { type: 'check' } : { type: 'call' }); + } + + onRaiseBtn() { + if (this.dockMode !== 'act' || !this.raiseBtn.visible) return; + const p = this.gs.players[0]; + if (this.raiseValue >= p.chips + p.bet) this.humanAct({ type: 'allin' }); + else this.humanAct({ type: 'raise', amount: this.raiseValue }); + } + + humanAct(action) { + if (this.dockMode !== 'act' || this.busy || this.gs?.actionSeat !== 0) return; + this.clearTurnRing(); + this.act(0, action); + } + + togglePreAction(key) { + this.preAction = this.preAction === key ? null : key; + this.preActionBet = this.gs?.roundBet ?? 0; + this.refreshPreButtons(); + } + + refreshPreButtons() { + const toCall = this.gs ? callAmount(this.gs, 0) : 0; + for (const b of this.preBtns ?? []) { + b.setActive(this.preAction === b.preKey); + if (b.preKey === 'callany') b.setLabel(toCall > 0 ? `Call $${toCall}+` : 'Call Any'); } } - drawCardBack(g, x, y) { - const color = this.cardBack?.fallbackColor - ? parseInt(this.cardBack.fallbackColor.replace('#', ''), 16) - : 0x1a3a6b; - g.fillStyle(color, 1); - g.fillRoundedRect(x, y, CARD_W, CARD_H, CARD_R); - g.lineStyle(2, 0xffffff, 0.25); - g.strokeRoundedRect(x + 6, y + 6, CARD_W - 12, CARD_H - 12, CARD_R - 2); - g.lineStyle(1, 0xffffff, 0.1); - g.strokeRoundedRect(x + 10, y + 10, CARD_W - 20, CARD_H - 20, CARD_R - 4); + // Pre-selected moves fire when the action reaches the human. + resolvePreAction() { + const pa = this.preAction; + if (!pa) return null; + const check = canCheck(this.gs, 0); + if (pa === 'checkfold') { this.preAction = null; return check ? { type: 'check' } : { type: 'fold' }; } + if (pa === 'check') { + this.preAction = null; + return check ? { type: 'check' } : null; // someone bet — cancelled, decide yourself + } + if (pa === 'callany') return check ? { type: 'check' } : { type: 'call' }; + return null; } - // ── Action badge ───────────────────────────────────────────────────────────── + // ── Applying actions ─────────────────────────────────────────────────────── + async act(seat, action) { + if (this.busy) return; + this.busy = true; + if (seat === 0 || this.dockMode === 'act') this.setDockMode('idle', ''); + const before = this.gs; + const prevPhase = before.phase; + const prevCommunity = before.community.length; + const beforeP = before.players[seat]; + this.gs = applyAction(before, seat, action); + if (this.gs === before) { + // Illegal move: the human picks again; an AI falls back to check / fold. + this.busy = false; + if (seat === 0) { this.nextTurn(); return; } + this.act(seat, canCheck(before, seat) ? { type: 'check' } : { type: 'fold' }); + return; + } + const afterP = this.gs.players[seat]; + const put = afterP.totalBet - beforeP.totalBet; + // what each seat had on the line at the end of this action (before any sweep) + const lineBets = before.players.map(p => p.bet + (p.seat === seat ? put : 0)); - showActionBadge(seat, action) { - const pos = this.seatPos[seat]; - const isHuman = seat === 0; - const badgeY = isHuman - ? pos.y - CARD_H / 2 - 110 - : pos.flipped ? pos.y - CARD_H / 2 - 70 : pos.y + CARD_H / 2 + 70; - const labels = { fold: 'FOLD', check: 'CHECK', call: 'CALL', raise: `RAISE $${action.amount ?? ''}`, allin: 'ALL IN' }; - const colors = { fold: '#e06c75', check: '#9e9080', call: COLORS.accentHex, raise: '#ffd700', allin: '#ff6b35' }; + const type = action.type === 'raise' && before.roundBet === 0 ? 'bet' : action.type; + const shownAmount = type === 'call' ? put : afterP.totalBet - (beforeP.totalBet - beforeP.bet); + this.actionBadge(seat, type, shownAmount, afterP.allIn && action.type !== 'fold'); + if (seat > 0 && (action.type === 'raise' || action.type === 'allin') && Math.random() < 0.25) { + this.portraits[seat]?.playEmotion?.('happy'); + } + this.clearTurnRing(); - const badge = this.add.text(pos.x, badgeY, labels[action.type] ?? action.type.toUpperCase(), { - fontFamily: '"Julius Sans One"', - fontSize: '22px', - color: colors[action.type] ?? COLORS.textHex, - backgroundColor: '#111923cc', - padding: { x: 14, y: 6 }, - }).setOrigin(0.5).setDepth(D.modal); + if (action.type === 'fold') { + await this.foldCards(seat); + } else if (put > 0) { + await this.pushChips(seat, put); + this.renderStack(seat); + } else { + playSound(this, SFX.CARD_PLACE); // knuckle tap + await this.wait(180); + } + this.renderSeatInfo(); - this.tweens.add({ - targets: badge, - alpha: { from: 1, to: 0 }, - y: badgeY - 30, - duration: 1200, - delay: 400, - onComplete: () => badge.destroy(), + // 'Check' pre-action cancels if someone bets into you. + if (this.preAction === 'check' && this.gs.roundBet > this.preActionBet) this.preAction = null; + + if (this.gs.phase === prevPhase) { + this.renderBets(); + this.busy = false; + if (seat === 0) this.updateHandLabel(); + this.nextTurn(); + return; + } + + // Street over: show the final bets, sweep them into the pot. + this.renderBets(lineBets); + await this.wait(260); + await this.sweepBets(); + this.busy = false; + if (this.gs.phase === 'between_hands' || this.gs.phase === 'game_over') { + await this.endOfHand(prevCommunity); + return; + } + this.preAction = null; + await this.revealBoard(prevCommunity, this.gs.community.length); + this.updateHandLabel(); + this.nextTurn(); + } + + // Chips slide from a seat's stack onto its bet spot. + async pushChips(seat, amount, delay = 0) { + const L = this.L(seat); + await throwStack(this, L.stack, L.bet, amount, { + delay, size: CHIP, depth: D.flying, sound: () => playChipBet(this), }); } - // ── Hand summary ───────────────────────────────────────────────────────────── - - cleanupSummary() { - for (const obj of this.summaryObjects) { - if (obj?.destroy) obj.destroy(); - } - this.summaryObjects = []; - for (const p of this.portraits) p.show?.(); + async foldCards(seat) { + playSound(this, SFX.CARD_PLACE); + const m = this.muckPos; + const moves = [0, 1].map(i => { + const key = `${seat}:${i}`; + const c = this.cards.get(key); + if (!c) return null; + this.cards.delete(key); + this.muckPile.push(c); + if (c.faceUp) this.skin.setFace(c, false); + c.setDepth(D.flying); + return this.tweenP({ + targets: c, x: m.x + (Math.random() - 0.5) * 16, y: m.y + (Math.random() - 0.5) * 6, + rotation: (Math.random() - 0.5) * 0.6, scaleX: m.s, scaleY: m.s * SQ, + duration: 360, delay: i * 50, ease: 'Cubic.easeOut', + onComplete: () => c.setDepth(D.cards - 1), + }); + }); + await Promise.all(moves); + if (seat === 0) this.updateHandLabel(); } - showHandSummary() { + async sweepBets() { + const objs = Object.values(this.betObjs); + this.betObjs = {}; + if (objs.length) { + playChipBet(this); + const to = potPose(0); + await Promise.all(objs.map((o, i) => this.tweenP({ + targets: o, x: to.x, y: to.y, scale: 0.8, alpha: { value: 0.2, ease: 'Expo.easeIn' }, + duration: 360, delay: i * 40, ease: 'Cubic.easeIn', + }))); + objs.forEach(o => o.destroy()); + } + this.renderPots(); + } + + // Burn one, then turn the next street's cards. + async revealBoard(from, to) { + if (to <= from) return; + await this.burnCard(); + for (let i = from; i < to; i++) { + const { c, promise } = this.skin.deal(this.gs.community[i], true, this.deckPos, communityPose(i), { + duration: 320, flyingDepth: D.flying, sound: () => playSound(this, SFX.CARD_SHOW), + }); + this.cards.set(`b:${i}`, c); + if (i < to - 1) await this.wait(170); else await promise; + } + await this.wait(250); + } + + async burnCard() { + const { c, promise } = this.skin.deal(null, false, this.deckPos, { + x: this.muckPos.x + (Math.random() - 0.5) * 12, y: this.muckPos.y, rot: (Math.random() - 0.5) * 0.5, s: this.muckPos.s, + }, { duration: 240, flyingDepth: D.flying }); + this.muckPile.push(c); + await promise; + c.setDepth(D.cards - 1); + } + + // ── Rendering ────────────────────────────────────────────────────────────── + renderSeatInfo() { + for (const p of this.gs.players) { + const t = this.chipTxts[p.seat]; + if (!t) continue; + t.setText(p.eliminated ? (this.places.has(p.seat) ? `Out · ${ordinal(this.places.get(p.seat))}` : 'Out') : `$${p.chips.toLocaleString()}`); + if (p.seat > 0) this.nameTxts[p.seat]?.setAlpha(p.eliminated ? 0.5 : p.folded ? 0.65 : 1); + } + } + + // Columns of chips (max 10 per column, 2 columns — the footprint HoldemTable + // reserves outside the betting line) with an amount pill underneath. + makeChipColumns(x, y, amount, size, depth) { + const c = this.add.container(x, y).setDepth(depth); + if (amount <= 0) return c; + const chips = breakdown(amount); + const cols = []; + for (let i = 0; i < chips.length && cols.length < 2; i += 10) cols.push(chips.slice(i, i + 10)); + cols.forEach((col, i) => { + const amt = col.reduce((a, b) => a + b, 0); + c.add(makeChipStack(this, (i - (cols.length - 1) / 2) * size * 1.04, 0, amt, { size, label: false, seed: i + amount })); + }); + const t = this.add.text(0, size * 0.55, `$${amount.toLocaleString()}`, { + fontFamily: '"Julius Sans One"', fontSize: `${Math.round(14 * Math.max(0.85, size / CHIP))}px`, color: '#f7ecd0', fontStyle: 'bold', + }).setOrigin(0.5, 0); + const pill = this.add.graphics(); + pill.fillStyle(0x0b0806, 0.8); + pill.fillRoundedRect(-t.width / 2 - 6, t.y - 2, t.width + 12, t.height + 4, 6); + c.add([pill, t]); + return c; + } + + renderStack(seat) { + this.stackObjs[seat]?.destroy(); + delete this.stackObjs[seat]; + const p = this.gs.players[seat]; + if (!p || p.eliminated || p.chips <= 0) return; + const L = this.L(seat); + this.stackObjs[seat] = this.makeChipColumns(L.stack.x, L.stack.y, p.chips, CHIP * L.stack.s, D.stacks); + } + + renderBets(override = null) { + for (const b of Object.values(this.betObjs)) b.destroy(); + this.betObjs = {}; + this.gs.players.forEach((p, seat) => { + const amt = override ? override[seat] : p.bet; + if (!amt) return; + const L = this.L(seat); + const st = makeChipStack(this, L.bet.x, L.bet.y, amt, { size: CHIP * L.bet.s, depth: D.stacks, seed: seat + amt }); + this.betObjs[seat] = st; + }); + if (!override) { + this.sbPuck.setVisible(this.gs.players[this.gs.sbSeat]?.bet > 0 && this.gs.phase === 'preflop'); + this.bbPuck.setVisible(this.gs.players[this.gs.bbSeat]?.bet > 0 && this.gs.phase === 'preflop'); + } + } + + // Main pot + side pots from what has been swept into the middle. + currentPots() { + const players = this.gs.players.map(p => ({ ...p, totalBet: p.totalBet - p.bet })); + return potsFromTotals(players); + } + + renderPots(pots = this.currentPots()) { + for (const p of this.potObjs) p.destroy(); + this.potObjs = []; + // pots[0] is the main pot (every live player is eligible); later slices are side pots. + pots.forEach((pot, i) => { + const pose = potPose(i); + const c = this.makeChipColumns(pose.x, pose.y, pot.amount, CHIP * pose.s, D.stacks); + const tag = this.add.text(0, -CHIP * pose.s * 1.25, i === 0 ? 'MAIN POT' : `SIDE POT ${i}`, { + fontFamily: '"Julius Sans One"', fontSize: '12px', color: '#e8c15a', fontStyle: 'bold', + }).setOrigin(0.5); + if (pots.length > 1) c.add(tag); else tag.destroy(); + c.pot = pot; + this.potObjs.push(c); + }); + } + + actionBadge(seat, type, amount, allIn) { + const L = this.L(seat); + const label = allIn ? `ALL IN $${amount}` : type === 'bet' ? `BET $${amount}` : (ACTION_LABEL(type, amount)[type] ?? type.toUpperCase()); + const color = allIn ? ACTION_COLOR.allin : ACTION_COLOR[type] ?? COLORS.textHex; + const b = this.pill(L.badge.x, L.badge.y, label, color, 18); + b.setDepth(D.badges + 2).setAlpha(0).setScale(1.25); + this.tweens.add({ targets: b, alpha: 1, scale: 1, duration: 160, ease: 'Back.Out' }); + this.time.delayedCall(1100, () => this.tweens.add({ + targets: b, alpha: 0, y: b.y - 24, duration: 420, onComplete: () => b.destroy(), + })); + } + + pill(x, y, text, color, size = 17, fill = 0x0b0906) { + const c = this.add.container(x, y).setDepth(D.badges); + const t = this.add.text(0, 0, text, { + fontFamily: '"Julius Sans One"', fontSize: `${size}px`, color, fontStyle: 'bold', + }).setOrigin(0.5); + const g = this.add.graphics(); + const w = t.width + 24, h = t.height + 10; + g.fillStyle(fill, 0.88); + g.fillRoundedRect(-w / 2, -h / 2, w, h, h / 2); + g.lineStyle(1.5, 0xc8a84b, 0.8); + g.strokeRoundedRect(-w / 2, -h / 2, w, h, h / 2); + c.add([g, t]); + c.t = t; + return c; + } + + banner(text, y, color = '#f7ecd0') { + const c = this.pill(CX, y, text, color, 26); + c.setDepth(D.prompt).setAlpha(0); + this.tweens.add({ targets: c, alpha: 1, duration: 220 }); + return c; + } + + // ── End of hand: runout, showdown, eliminations, summary ─────────────────── + contenders() { + return this.gs.players.filter(p => !p.folded && p.hand?.length === 2 && p.totalBet > 0); + } + + async endOfHand(prevCommunity) { + this.clearTurnRing(); + this.setDockMode('idle', ''); + const live = this.contenders(); + if (this.gs.runout && live.length > 1) await this.runout(prevCommunity, live); + else if (this.gs.community.length > prevCommunity) await this.revealBoard(prevCommunity, this.gs.community.length); + await this.showdown(live); + await this.handleEliminations(); + this.renderSeatInfo(); + this.updatePanel(); + this.showSummary(); + } + + // TV-style: all hands face-up, the board runs out street by street with live equity. + async runout(from, live) { + const banner = this.banner('ALL IN — RUNNING IT OUT', 128, '#ff6b35'); + this.decor.push(banner); + await this.flipHands(live); + const pills = new Map(); + const showEquity = (count) => { + const board = this.gs.community.slice(0, count); + const eq = equity(live.map(p => p.hand), board, 600); + live.forEach((p, i) => { + const L = this.L(p.seat); + let pill = pills.get(p.seat); + if (!pill) { + pill = this.pill(L.badge.x, L.badge.y, '', '#ffffff', 20, 0x1b1b20); + pills.set(p.seat, pill); + this.decor.push(pill); + } + const pct = Math.round(eq[i].equity * 100); + pill.t.setText(`${pct}%`).setColor(pct >= 50 ? '#7ee081' : pct >= 20 ? '#f5d020' : '#ff8a80'); + this.tweens.add({ targets: pill, scale: { from: 1.25, to: 1 }, duration: 220, ease: 'Back.Out' }); + }); + }; + showEquity(from); + await this.wait(1200); + const streets = [3, 4, 5].filter(n => n > from); + let prev = from; + for (const n of streets) { + await this.revealBoard(prev, n); + prev = n; + showEquity(n); + await this.wait(n === 5 ? 900 : 1300); + } + for (const p of pills.values()) this.tweens.add({ targets: p, alpha: 0, duration: 300 }); + } + + async flipHands(players) { + await Promise.all(players.flatMap(p => [0, 1].map(i => { + const c = this.cards.get(`${p.seat}:${i}`); + if (!c || c.faceUp) return null; + return this.wait(i * 70).then(() => this.skin.flip(c, true, 260)); + }))); + } + + // Lift + glow the cards that make a winning hand. + glowCards(cardList) { + const keys = new Set(cardList.map(c => c.key)); + for (const c of this.cards.values()) { + if (!keys.has(c.card?.key)) continue; + const g = this.add.graphics().setDepth(D.glow); + g.lineStyle(4 / c.scaleX, 0xf5d020, 1); + g.strokeRoundedRect(-CARD_W / 2 - 4, -CARD_H / 2 - 4, CARD_W + 8, CARD_H + 8, 12); + g.setPosition(c.x, c.y - 10).setRotation(c.rotation).setScale(c.scaleX, c.scaleY).setAlpha(0); + this.tweens.add({ targets: c, y: c.y - 10, duration: 220, ease: 'Back.Out' }); + this.tweens.add({ targets: g, alpha: 1, duration: 220 }); + this.decor.push(g); + c.setDepth(D.glow + 1); + } + } + + async showdown(live) { + const gs = this.gs; + const pots = potsFromTotals(gs.players); + const handOf = (seat) => gs.players[seat].hand; + if (live.length > 1) { + if (!gs.runout) await this.flipHands(live); + for (const p of live) { + const L = this.L(p.seat); + const pill = this.pill(L.badge.x, L.badge.y + 30 * L.s, describe(evaluateHand([...p.hand, ...gs.community])), '#f7ecd0', 16); + this.decor.push(pill); + } + await this.wait(500); + } + // Award pots: side pots first (they were built last-in-first), main pot last. + this.renderPots(pots); + const ordered = pots.map((pot, i) => ({ pot, sprite: this.potObjs[i] })).reverse(); + for (const { pot, sprite } of ordered) { + const eligible = pot.eligibleSeats.filter(s => !gs.players[s].folded); + let winners; + if (eligible.length <= 1 || live.length <= 1) winners = eligible.length ? eligible : [live[0]?.seat ?? 0]; + else { + const evs = eligible.map(s => ({ s, ev: evaluateHand([...handOf(s), ...gs.community]) })); + let best = evs[0].ev; + for (const e of evs) if (compareHands(e.ev, best) > 0) best = e.ev; + winners = evs.filter(e => compareHands(e.ev, best) === 0).map(e => e.s); + for (const s of winners) this.glowCards(bestFive([...handOf(s), ...gs.community]).cards); + this.showdownBanner?.destroy(); + const potName = pots.length > 1 ? (pot === pots[0] ? 'Main pot: ' : 'Side pot: ') : ''; + this.showdownBanner = winners.length > 1 + ? this.banner(`${potName}split — ${describe(best)}`, 128, '#e8c15a') + : this.banner(`${potName}${gs.players[winners[0]].name} ${winners[0] === 0 ? 'win' : 'wins'} with ${describe(best)}`, 128, '#ffd700'); + this.decor.push(this.showdownBanner); + await this.wait(700); + } + await this.awardPot(sprite, winners, pot.amount); + } + // Emotions + sounds + const won = new Map(); + for (const p of gs.players) won.set(p.seat, p.chips - (this.handStartChips[p.seat] ?? p.chips)); + if ((won.get(0) ?? 0) > 0) playSound(this, SFX.CASINO_WIN); + for (const p of gs.players) { + if (p.seat === 0 || p.eliminated && !this.handStartChips[p.seat]) continue; + const delta = won.get(p.seat); + if (delta > 0) this.portraits[p.seat]?.playEmotion?.('happy'); + else if (delta < -(this.handStartChips[p.seat] ?? 0) * 0.3) this.portraits[p.seat]?.playEmotion?.('upset'); + } + for (let s = 0; s <= this.n; s++) this.renderStack(s); + this.renderSeatInfo(); + await this.wait(900); + } + + async awardPot(sprite, winners, amount) { + if (!sprite) return; + const share = Math.floor(amount / winners.length); + playChipBet(this); + if (winners.length === 1) { + const to = this.L(winners[0]).stack; + await this.tweenP({ targets: sprite, x: to.x, y: to.y, scale: 0.9, alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 620, ease: 'Cubic.easeInOut' }); + sprite.destroy(); + } else { + const from = { x: sprite.x, y: sprite.y }; + sprite.destroy(); + await Promise.all(winners.map((s, i) => { + const part = this.makeChipColumns(from.x, from.y, share, CHIP * 0.85, D.flying); + const to = this.L(s).stack; + return this.tweenP({ targets: part, x: to.x, y: to.y, alpha: { value: 0, ease: 'Expo.easeIn' }, duration: 640, delay: i * 80, ease: 'Cubic.easeInOut' }) + .then(() => part.destroy()); + })); + } + this.potObjs = this.potObjs.filter(p => p !== sprite); + } + + async handleEliminations() { + const newlyOut = this.gs.players.filter(p => p.eliminated && !this.eliminatedSeats.has(p.seat)).map(p => p.seat); + if (!newlyOut.length) return; + const stillIn = this.gs.players.filter(p => !p.eliminated).length; + const places = assignPlaces(newlyOut, this.handStartChips, stillIn); + for (const [seat, place] of places) this.places.set(seat, place); + if (this.gs.phase === 'game_over' && this.gs.winner != null) this.places.set(this.gs.winner, 1); + await Promise.all(newlyOut.map(seat => this.animateElimination(seat))); + } + + elimPicPos(i) { + return { x: PANEL.x + PANEL.w - 30 - i * 40, y: PANEL.y + PANEL.h + 0 }; + } + + async animateElimination(seat) { + this.eliminatedSeats.add(seat); + this.stackObjs[seat]?.destroy(); + delete this.stackObjs[seat]; + const pt = this.L(seat).portrait; + this.portraits[seat]?.stopVideo?.(); + this.portraits[seat]?.fadeToEliminated?.(700); + const target = this.elimPicPos(this.elimPics.length); + const R = 16; + const anim = this.add.container(pt.x, pt.y).setDepth(D.modal); + anim.add(this.add.circle(0, 0, pt.r, 0x1a1a2e)); + const opp = seat > 0 ? this.opponents[seat - 1] : null; + if (opp && this.textures.exists('opponents')) { + anim.add(this.add.image(0, 0, 'opponents', opp.spriteIndex ?? 0).setDisplaySize(pt.r * 2, pt.r * 2)); + } else { + anim.add(this.add.text(0, 0, (auth.user?.username ?? 'You').charAt(0).toUpperCase(), { + fontFamily: '"Julius Sans One"', fontSize: `${Math.round(pt.r * 0.9)}px`, color: COLORS.accentHex, + }).setOrigin(0.5)); + } + const placeTxt = this.pill(pt.x, pt.y + pt.r + 4, `${ordinal(this.places.get(seat))} place`, '#ff8a80', 16); + placeTxt.setDepth(D.modal + 1); + await this.wait(700); + placeTxt.destroy(); + await this.tweenP({ + targets: anim, x: target.x, y: target.y, scale: R / pt.r, duration: 750, ease: 'Power2.easeIn', + }); + anim.destroy(); + // the little face in the panel strip + const backing = this.add.circle(target.x, target.y, R, 0x1a1a2e).setDepth(D.ui + 1); + let face = null, maskG = null; + if (opp && this.textures.exists('opponents')) { + maskG = this.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff); + maskG.fillCircle(target.x, target.y, R); + face = this.add.image(target.x, target.y, 'opponents', opp.spriteIndex ?? 0) + .setDisplaySize(R * 2, R * 2).setMask(maskG.createGeometryMask()).setDepth(D.ui + 2).setAlpha(0.75); + } + this.elimPics.push({ backing, face, maskG }); + this.updatePanel(); + } + + // ── Summary (restyled) ───────────────────────────────────────────────────── + cleanupSummary() { + for (const o of this.summaryObjects) o?.destroy?.(); + this.summaryObjects = []; + for (const p of this.portraits) p?.show?.(); + this.continueFromSummary = null; + } + + showSummary() { const { community, players } = this.gs; const S = this.summaryObjects; + const add = (o) => { S.push(o); return o; }; + for (const p of this.portraits) p?.hide?.(); + this.setDockMode('summary'); - // Compute winnings (resolveShowdown handles the fold-win case correctly) - const winnings = resolveShowdown(players, community); - if ((winnings.get(0) ?? 0) > 0) playSound(this, SFX.CASINO_WIN); + add(this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.55).setDepth(D.modal).setInteractive()); + const PW = 1800, PH = 1020; + ensureLeatherPanel(this, 'he-summary', PW, PH, { radius: 26, felt: '#0f5a33' }); + const panel = add(this.add.image(CX, CY - 4, 'he-summary').setDepth(D.modal).setAlpha(0)); + this.tweens.add({ targets: panel, alpha: 1, duration: 260 }); + add(this.add.text(CX, 52, `Hand #${this.gs.handNumber} · Summary`, { + fontFamily: 'Righteous', fontSize: '28px', color: '#e8c15a', + }).setOrigin(0.5).setDepth(D.modal + 1)); - // Hide game-world portraits so their DOM videos don't bleed through the overlay - for (const p of this.portraits) p.hide?.(); + // Who won what, and the main winner's best five (for highlights). + const net = new Map(players.map(p => [p.seat, p.chips - (this.handStartChips[p.seat] ?? 0)])); + const live = this.contenders(); + const bestBySeat = new Map(live.filter(() => community.length === 5).map(p => [p.seat, bestFive([...p.hand, ...community])])); + let topSeat = null; + for (const [seat, b] of bestBySeat) if (!topSeat || compareHands(b.eval, bestBySeat.get(topSeat).eval) > 0) topSeat = seat; + const winKeys = new Set(topSeat != null && live.length > 1 ? bestBySeat.get(topSeat).cards.map(c => c.key) : []); - // Dark overlay - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.88) - .setDepth(D.modal).setAlpha(0); - S.push(overlay); - this.tweens.add({ targets: overlay, alpha: 1, duration: 400 }); - - // Title - const title = this.add.text(CX, 38, 'Hand Summary', { - fontFamily: '"Julius Sans One"', fontSize: '26px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modal + 1).setAlpha(0); - S.push(title); - this.tweens.add({ targets: title, alpha: 1, duration: 300, delay: 200 }); - - // Community cards — animate from original slot positions to enlarged top row - const origStartX = CX - (5 * CARD_W + 4 * 14) / 2 + CARD_W / 2; // 732 - const SCALE = 1.5; - const LW = CARD_W * SCALE; - const totalTargetW = 5 * LW + 4 * 20; - const targetStartX = CX - totalTargetW / 2 + LW / 2; // 620 + // Board row + const BS = 1.25; community.forEach((card, i) => { - const fromX = origStartX + i * (CARD_W + 14); - const toX = targetStartX + i * (LW + 20); - const cont = this.add.container(fromX, CY - 10).setDepth(D.modal + 1).setScale(1); - this.renderCard(cont, card, true); - S.push(cont); - this.tweens.add({ - targets: cont, x: toX, y: 165, scaleX: SCALE, scaleY: SCALE, - duration: 550, delay: 150 + i * 90, ease: 'Power2.easeOut', - }); + const x = CX + (i - 2) * 132; + const c = add(this.skin.make(card, true, x, 160, BS, 0).setDepth(D.modal + 1).setScale(BS)); + if (winKeys.has(card.key)) this.summaryGlow(c, S); + }); + if (!community.length) { + add(this.add.text(CX, 160, 'Won before the flop', { fontFamily: '"Julius Sans One"', fontSize: '20px', color: '#c9c2b0' }) + .setOrigin(0.5).setDepth(D.modal + 1)); + } + + const rowStart = 290; + const rowH = Math.min(150, 680 / players.length); + const scale = Math.min(1, rowH / 150); + players.forEach((p, i) => { + const y = rowStart + i * rowH; + const delta = net.get(p.seat); + const isWinner = delta > 0; + const rowBg = add(this.add.graphics().setDepth(D.modal + 1)); + rowBg.fillStyle(0x0b0806, isWinner ? 0.62 : 0.45); + rowBg.fillRoundedRect(CX - 820, y - rowH / 2 + 6, 1640, rowH - 12, 12); + rowBg.lineStyle(2, isWinner ? 0xf5d020 : 0x2a2a3a, isWinner ? 1 : 0.7); + rowBg.strokeRoundedRect(CX - 820, y - rowH / 2 + 6, 1640, rowH - 12, 12); + this.summaryPortrait(p, CX - 740, y, Math.round(50 * scale), isWinner, S); + + add(this.add.text(CX - 660, y - 22 * scale, p.name ?? '—', { + fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + let status = '', statusColor = COLORS.accentHex; + if (p.eliminated && !this.handStartChips[p.seat]) { status = 'ELIMINATED'; statusColor = COLORS.mutedHex; } + else if (p.folded) { status = 'FOLDED'; statusColor = COLORS.dangerHex; } + else if (p.hand?.length && community.length === 5 && live.length > 1) status = describe(evaluateHand([...p.hand, ...community])); + else if (!p.folded && live.length === 1) status = 'Won uncontested'; + if (p.eliminated && this.places.has(p.seat) && this.handStartChips[p.seat]) { status = `${status ? `${status} · ` : ''}OUT — ${ordinal(this.places.get(p.seat))}`; } + if (status) { + add(this.add.text(CX - 660, y + 12 * scale, status, { + fontFamily: '"Julius Sans One"', fontSize: '17px', color: statusColor, + }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + } + if (p.hand?.length === 2) { + const showFace = p.seat === 0 || (!p.folded && live.length > 1); + p.hand.forEach((card, ci) => { + const c = add(this.skin.make(card, showFace, CX - 300 + (ci - 0.5) * 92 * scale, y, 0.8 * scale, 0) + .setDepth(D.modal + 2).setScale(0.8 * scale)); + if (!showFace) c.setAlpha(0.35); + if (showFace && isWinner && bestBySeat.get(p.seat)?.cards.some(k => k.key === card.key)) this.summaryGlow(c, S); + }); + } + if (delta !== 0 && !(p.eliminated && !this.handStartChips[p.seat])) { + add(this.add.text(CX - 120, y, `${delta > 0 ? '+' : '−'}$${Math.abs(delta).toLocaleString()}`, { + fontFamily: '"Julius Sans One"', fontSize: '28px', color: delta > 0 ? '#ffd700' : '#ff8a80', fontStyle: 'bold', + }).setOrigin(0, 0.5).setDepth(D.modal + 2)); + } + add(this.add.text(CX + 160, y, p.eliminated ? 'Eliminated' : `$${p.chips.toLocaleString()} chips`, { + fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, + }).setOrigin(0, 0.5).setDepth(D.modal + 2)); }); - // Divider - const divider = this.add.rectangle(CX, 262, 1600, 1, COLORS.muted, 0.4).setDepth(D.modal + 1); - S.push(divider); - - // Player rows — one per seat, staggered. Pitch shrinks to fit up to 8 rows - // between the divider and the Continue button. - const rowStartY = 305; - const rowH = Math.min(155, 700 / players.length); - const scale = Math.min(1, rowH / 155); - players.forEach((player, seat) => { - const rowY = rowStartY + seat * rowH; - this.buildSummaryRow(player, rowY, winnings, 500 + seat * 190, community, S, rowH, scale); - }); - - // Continue button — fades in after rows have appeared - const continueBtn = new Button(this, CX, 1042, 'Continue to Next Hand', () => { + const gameOver = this.gs.phase === 'game_over'; + const humanOut = players[0].eliminated; + const go = () => { + if (!this.continueFromSummary) return; this.cleanupSummary(); + if (gameOver) { this.showGameOver(); return; } + if (humanOut && !this.humanWatching) { this.showBustedChoice(); return; } this.dealNextHand(); - }, { width: 420, fontSize: 24 }).setDepth(D.modal + 2).setAlpha(0); - S.push(continueBtn); - this.tweens.add({ targets: continueBtn, alpha: 1, duration: 300, delay: 1100 }); + }; + this.continueFromSummary = go; + const label = gameOver ? 'See Final Standings' : 'Continue to Next Hand'; + const btn = add(new Button(this, CX, 1018, label, go, { width: 420, height: 60, fontSize: 24 }).setDepth(D.modal + 3).setAlpha(0)); + this.tweens.add({ targets: btn, alpha: 1, duration: 300, delay: 500 }); } - buildSummaryRow(player, rowY, winnings, delay, community, S, rowH = 155, scale = 1) { - const isWinner = (winnings.get(player.seat) ?? 0) > 0; - - // Row panel - const panelH = Math.max(70, rowH - 14); - const panel = this.add.rectangle(CX, rowY, 1720, panelH, COLORS.panel) - .setStrokeStyle(2, isWinner ? 0xffd700 : 0x2a2a3a) - .setDepth(D.modal + 1).setAlpha(0); - S.push(panel); - this.tweens.add({ targets: panel, alpha: 0.9, duration: 350, delay }); - - // Portrait backing - const portX = 145; - const portR = Math.round(52 * scale); - const backing = this.add.circle(portX, rowY, portR + 3, 0x1a1a2e) - .setDepth(D.modal + 1).setAlpha(0); - S.push(backing); - this.tweens.add({ targets: backing, alpha: 1, duration: 350, delay }); - - if (isWinner) { - const ring = this.add.circle(portX, rowY, portR + 3) - .setStrokeStyle(3, 0xffd700).setDepth(D.modal + 2).setAlpha(0); - S.push(ring); - this.tweens.add({ targets: ring, alpha: 1, duration: 350, delay }); - } - - if (!player.isHuman) { - const opp = this.opponents[player.seat - 1] ?? null; - if (opp && this.textures.exists('opponents')) { - const maskG = this.make.graphics({ x: 0, y: 0, add: false }); - maskG.fillStyle(0xffffff); - maskG.fillCircle(portX, rowY, portR); - const sprite = this.add.image(portX, rowY, 'opponents', opp.spriteIndex ?? 0) - .setDisplaySize(portR * 2, portR * 2) - .setMask(maskG.createGeometryMask()) - .setDepth(D.modal + 2).setAlpha(0); - S.push(sprite); - this.tweens.add({ targets: sprite, alpha: 1, duration: 350, delay }); - } - // Inline emotion video for summary (DOM renders above canvas overlay) - if (opp) { - const emotion = isWinner ? 'happy' : 'upset'; - const videoEl = document.createElement('video'); - videoEl.src = `assets/videos/${opp.id}-${emotion}.mp4`; - videoEl.style.cssText = `width:${portR * 2}px;height:${portR * 2}px;border-radius:50%;object-fit:cover;display:block;`; - videoEl.muted = true; - videoEl.loop = true; - videoEl.autoplay = true; - videoEl.playsInline = true; - videoEl.addEventListener('error', () => { videoEl.style.display = 'none'; }, { once: true }); - videoEl.play().catch(() => {}); - const domEl = this.add.dom(portX, rowY, videoEl).setDepth(D.modal + 3); - S.push(domEl); - } - } else { - const initial = (auth.user?.username ?? 'You').charAt(0).toUpperCase(); - const initTxt = this.add.text(portX, rowY, initial, { - fontFamily: 'Righteous', fontSize: `${Math.round(46 * scale)}px`, color: COLORS.accentHex, - }).setOrigin(0.5).setDepth(D.modal + 2).setAlpha(0); - S.push(initTxt); - this.tweens.add({ targets: initTxt, alpha: 1, duration: 350, delay }); - } - - // Player name - const nameX = 250; - const nameTxt = this.add.text(nameX, rowY - 28, player.name ?? '—', { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.textHex, - }).setOrigin(0, 0.5).setDepth(D.modal + 2).setAlpha(0); - S.push(nameTxt); - this.tweens.add({ targets: nameTxt, alpha: 1, duration: 350, delay }); - - // Status text (hand rank or FOLDED/ELIMINATED) - let statusStr = ''; - let statusColor = COLORS.accentHex; - if (player.folded) { - statusStr = 'FOLDED'; - statusColor = COLORS.dangerHex; - } else if (player.eliminated) { - statusStr = 'ELIMINATED'; - statusColor = COLORS.mutedHex; - } else if (player.hand?.length && player.hand.length + community.length >= 5) { - const result = evaluateHand([...player.hand, ...community]); - statusStr = result.name; - } - if (statusStr) { - const statusTxt = this.add.text(nameX, rowY + 4, statusStr, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: statusColor, - }).setOrigin(0, 0.5).setDepth(D.modal + 2).setAlpha(0); - S.push(statusTxt); - this.tweens.add({ targets: statusTxt, alpha: 1, duration: 350, delay }); - } - - // Hole cards (0.82× scale → 82×115, shrinks further when rows are compact) - const cardScale = 0.82 * scale; - const cardBaseX = 490; - const cardOffsets = [-48 * scale, 48 * scale]; - if (player.hand?.length === 2) { - player.hand.forEach((card, ci) => { - const cx = cardBaseX + cardOffsets[ci]; - const cont = this.add.container(cx, rowY).setDepth(D.modal + 2).setScale(cardScale).setAlpha(0); - if (player.folded) { - this.renderCard(cont, card, false); - this.tweens.add({ targets: cont, alpha: 0.28, duration: 350, delay }); - } else { - this.renderCard(cont, card, true); - this.tweens.add({ targets: cont, alpha: 1, duration: 350, delay }); - } - S.push(cont); - }); - } - - // Result badge - const won = winnings.get(player.seat) ?? 0; - if (won > 0) { - const wonTxt = this.add.text(790, rowY, `+$${won}`, { - fontFamily: '"Julius Sans One"', fontSize: '28px', - color: '#ffd700', fontStyle: 'bold', - }).setOrigin(0, 0.5).setDepth(D.modal + 2).setAlpha(0); - S.push(wonTxt); - this.tweens.add({ targets: wonTxt, alpha: 1, duration: 350, delay }); - } - - // Chip count - const chipStr = player.eliminated ? 'Eliminated' : `$${player.chips} chips`; - const chipTxt = this.add.text(1050, rowY, chipStr, { - fontFamily: '"Julius Sans One"', fontSize: '18px', color: COLORS.mutedHex, - }).setOrigin(0, 0.5).setDepth(D.modal + 2).setAlpha(0); - S.push(chipTxt); - this.tweens.add({ targets: chipTxt, alpha: 1, duration: 350, delay }); + summaryGlow(c, S) { + const g = this.add.graphics().setDepth(c.depth - 0.5); + g.lineStyle(4 / c.scaleX, 0xf5d020, 1); + g.strokeRoundedRect(-CARD_W / 2 - 5, -CARD_H / 2 - 5, CARD_W + 10, CARD_H + 10, 12); + g.setPosition(c.x, c.y).setScale(c.scaleX, c.scaleY); + S.push(g); } - // ── Game over ──────────────────────────────────────────────────────────────── + summaryPortrait(player, x, y, r, isWinner, S) { + S.push(this.add.circle(x, y, r + 3, 0x1a1a2e).setDepth(D.modal + 2)); + if (isWinner) S.push(this.add.circle(x, y, r + 3).setStrokeStyle(3, 0xffd700).setDepth(D.modal + 3)); + if (player.isHuman) { + S.push(this.add.text(x, y, (auth.user?.username ?? 'You').charAt(0).toUpperCase(), { + fontFamily: 'Righteous', fontSize: `${Math.round(r * 0.9)}px`, color: COLORS.accentHex, + }).setOrigin(0.5).setDepth(D.modal + 3)); + return; + } + const opp = this.opponents[player.seat - 1] ?? null; + if (opp && this.textures.exists('opponents')) { + const maskG = this.make.graphics({ x: 0, y: 0, add: false }); + maskG.fillStyle(0xffffff); + maskG.fillCircle(x, y, r); + S.push(this.add.image(x, y, 'opponents', opp.spriteIndex ?? 0) + .setDisplaySize(r * 2, r * 2).setMask(maskG.createGeometryMask()).setDepth(D.modal + 3)); + S.push(maskG); + } + if (opp && !player.eliminated) { + const videoEl = document.createElement('video'); + videoEl.src = `assets/videos/${opp.id}-${isWinner ? 'happy' : 'upset'}.mp4`; + videoEl.style.cssText = `width:${r * 2}px;height:${r * 2}px;border-radius:50%;object-fit:cover;display:block;`; + videoEl.muted = true; videoEl.loop = true; videoEl.autoplay = true; videoEl.playsInline = true; + videoEl.addEventListener('error', () => { videoEl.style.display = 'none'; }, { once: true }); + videoEl.play().catch(() => {}); + S.push(this.add.dom(x, y, videoEl).setDepth(D.modal + 4)); + } + } + // ── Busted: watch or skip ────────────────────────────────────────────────── + showBustedChoice() { + this.setDockMode('busted'); + const place = this.places.get(0); + const t = this.add.text(560, DOCK_Y, `You finished ${ordinal(place)} of ${this.gs.players.length}`, { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: '#ff8a80', + }).setOrigin(0, 0.5).setDepth(D.dockUi); + const watch = new Button(this, 1150, DOCK_Y, 'Watch', () => { + this.humanWatching = true; + this.dealNextHand(); + }, { width: 170, height: 56, fontSize: 20, variant: 'ghost' }).setDepth(D.dockUi); + const skip = new Button(this, 1350, DOCK_Y, 'Skip to Result', () => this.skipToResult(), { + width: 210, height: 56, fontSize: 20, + }).setDepth(D.dockUi); + this.dock.addTransient(t, watch, skip); + } + + // Play the rest of the tournament headlessly with the same rules and AI. + skipToResult() { + this.setDockMode('idle', 'Playing out the tournament…'); + let gs = this.gs; + for (let hand = 0; hand < 3000 && gs.phase !== 'game_over'; hand++) { + const start = Object.fromEntries(gs.players.map(p => [p.seat, p.chips])); + gs = startHand(gs); + let steps = 0; + while (!['between_hands', 'game_over'].includes(gs.phase) && steps++ < 400) { + gs = applyAction(gs, gs.actionSeat, chooseAction(gs, gs.actionSeat)); + } + const out = gs.players.filter(p => p.eliminated && !this.places.has(p.seat)).map(p => p.seat); + if (out.length) { + const places = assignPlaces(out, start, gs.players.filter(p => !p.eliminated).length); + for (const [s, pl] of places) this.places.set(s, pl); + } + if (gs.players.filter(p => !p.eliminated).length <= 1) break; + } + if (gs.winner != null) this.places.set(gs.winner, 1); + this.gs = { ...gs, phase: 'game_over' }; + this.showGameOver(); + } + + // ── Game over ────────────────────────────────────────────────────────────── async showGameOver() { - const humanPlayer = this.gs?.players[0]; - const finalChips = humanPlayer?.chips ?? 0; - const net = finalChips - this.buyIn; - const won = net >= 0; + this.setDockMode('idle', ''); + this.clearTurnRing(); + const human = this.gs.players[0]; + const finalChips = human.eliminated ? 0 : human.chips; + const netAmt = finalChips - this.buyIn; + if (!this.cashedOut) { + this.cashedOut = true; + try { + const { chips } = await api.post('/profile/chips/adjust', { delta: finalChips }); + this.globalChips = chips; + } catch { /* balance update failed — continue anyway */ } + } + if (!this.alive()) return; + for (const p of this.portraits) p?.hide?.(); + if (this.gs.winner != null) this.places.set(this.gs.winner, 1); - // Cash out: return final chips to global balance - try { - const { chips } = await api.post('/profile/chips/adjust', { delta: finalChips }); - this.globalChips = chips; - } catch { /* balance update failed — continue anyway */ } + const objs = []; + const add = (o) => { objs.push(o); return o; }; + add(this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.65).setDepth(D.modal).setInteractive()); + const PW = 760, PH = 300 + this.gs.players.length * 40; + ensureLeatherPanel(this, `he-over-${this.gs.players.length}`, PW, PH, { radius: 24, felt: '#0f5a33' }); + add(this.add.image(CX, CY, `he-over-${this.gs.players.length}`).setDepth(D.modal)); + const top = CY - PH / 2; + const youWon = this.places.get(0) === 1; + add(this.add.text(CX, top + 52, youWon ? 'You win the tournament!' : `You finished ${ordinal(this.places.get(0) ?? 2)}`, { + fontFamily: 'Righteous', fontSize: '38px', color: youWon ? '#ffd700' : COLORS.textHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); + add(this.add.text(CX, top + 98, netAmt >= 0 ? `+$${netAmt} profit` : `−$${Math.abs(netAmt)}`, { + fontFamily: '"Julius Sans One"', fontSize: '24px', color: netAmt >= 0 ? COLORS.accentHex : COLORS.dangerHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); - const overlay = this.add.rectangle(CX, CY, GAME_WIDTH, GAME_HEIGHT, 0x000000, 0.78).setDepth(D.modal); - const panel = this.add.rectangle(CX, CY, 580, 380, COLORS.panel) - .setStrokeStyle(2, COLORS.accent).setDepth(D.modal); - - const winnerSeat = this.gs?.winner; - const winnerName = winnerSeat != null ? this.gs.players[winnerSeat]?.name : null; - - const headline = winnerName && winnerSeat !== 0 - ? `${winnerName} wins!` - : humanPlayer?.eliminated - ? 'You were eliminated!' - : '🎉 You win!'; - - this.add.text(CX, CY - 140, headline, { - fontFamily: 'Righteous', fontSize: '40px', - color: won ? '#ffd700' : COLORS.textHex, - }).setOrigin(0.5).setDepth(D.modal); - - this.add.text(CX, CY - 70, won - ? `+$${net} profit` - : net === 0 ? 'Broke even' : `-$${Math.abs(net)} loss`, { - fontFamily: '"Julius Sans One"', fontSize: '28px', - color: won ? COLORS.accentHex : COLORS.dangerHex, - }).setOrigin(0.5).setDepth(D.modal); - - this.add.text(CX, CY - 20, `Your balance: $${this.globalChips.toLocaleString()}`, { - fontFamily: '"Julius Sans One"', fontSize: '22px', color: COLORS.mutedHex, - }).setOrigin(0.5).setDepth(D.modal); - - new Button(this, CX - 110, CY + 100, 'Play Again', () => { - overlay.destroy(); panel.destroy(); - this.scene.restart(); - }, { width: 200 }).setDepth(D.modal); - - new Button(this, CX + 110, CY + 100, 'Leave', () => { - this.scene.start('GameMenu'); - }, { variant: 'ghost', width: 200 }).setDepth(D.modal); + const standings = [...this.gs.players].sort((a, b) => (this.places.get(a.seat) ?? 99) - (this.places.get(b.seat) ?? 99)); + standings.forEach((p, i) => { + const y = top + 150 + i * 40; + const place = this.places.get(p.seat); + const color = p.seat === 0 ? '#ffd700' : COLORS.textHex; + add(this.add.text(CX - 250, y, place ? ordinal(place) : '—', { fontFamily: '"Julius Sans One"', fontSize: '20px', color }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + add(this.add.text(CX - 160, y, p.name, { fontFamily: '"Julius Sans One"', fontSize: '20px', color }).setOrigin(0, 0.5).setDepth(D.modal + 1)); + add(this.add.text(CX + 250, y, place === 1 ? `$${(p.chips).toLocaleString()}` : '', { fontFamily: '"Julius Sans One"', fontSize: '20px', color: '#e8c15a' }).setOrigin(1, 0.5).setDepth(D.modal + 1)); + }); + add(this.add.text(CX, top + PH - 100, `Your balance: $${this.globalChips.toLocaleString()}`, { + fontFamily: '"Julius Sans One"', fontSize: '20px', color: COLORS.mutedHex, + }).setOrigin(0.5).setDepth(D.modal + 1)); + add(new Button(this, CX - 120, top + PH - 48, 'Play Again', () => this.scene.restart(), { width: 210, height: 56 }).setDepth(D.modal + 1)); + add(new Button(this, CX + 120, top + PH - 48, 'Leave', () => this.scene.start('GameMenu'), { width: 210, height: 56, variant: 'ghost' }).setDepth(D.modal + 1)); } } diff --git a/src/games/holdem/HoldemLogic.js b/src/games/holdem/HoldemLogic.js index f9e5547..b400bb9 100644 --- a/src/games/holdem/HoldemLogic.js +++ b/src/games/holdem/HoldemLogic.js @@ -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); } diff --git a/src/games/holdem/HoldemShowdown.js b/src/games/holdem/HoldemShowdown.js new file mode 100644 index 0000000..1f94869 --- /dev/null +++ b/src/games/holdem/HoldemShowdown.js @@ -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. +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]}`; +} diff --git a/src/games/holdem/HoldemTable.js b/src/games/holdem/HoldemTable.js new file mode 100644 index 0000000..2975c72 --- /dev/null +++ b/src/games/holdem/HoldemTable.js @@ -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) diff --git a/src/ui/casino/CasinoGeometry.js b/src/ui/casino/CasinoGeometry.js index 1de5f41..6879c90 100644 --- a/src/ui/casino/CasinoGeometry.js +++ b/src/ui/casino/CasinoGeometry.js @@ -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) { diff --git a/tools/verifyHoldem.js b/tools/verifyHoldem.js new file mode 100644 index 0000000..a01189d --- /dev/null +++ b/tools/verifyHoldem.js @@ -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);