fertig-classic-games/src/games/holdem/HoldemGame.js

1400 lines
62 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as Phaser from 'phaser';
import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { api } from '../../services/api.js';
import { auth } from '../../services/auth.js';
import {
createInitialState, startHand, applyAction,
getBlindLevel, LEVEL_INTERVAL_MS, BLIND_LEVELS, callAmount, canCheck,
evaluateHand, compareHands, potsFromTotals,
} from './HoldemLogic.js';
import { chooseAction } from './HoldemAI.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 / 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 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,
};
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.opponents = data.opponents ?? [];
this.playfield = data.playfield ?? null;
this.cardBack = data.cardBack ?? null;
this.n = Math.min(this.opponents.length, 7);
this.gs = null;
this.buyIn = 100;
this.globalChips = 0;
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 ───────────────────────────────────────────────────────────────
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.events.once('shutdown', () => {
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(time) {
if (!this.gs || !this.panelTxt || time - (this._panelAt ?? 0) < 250) return;
this._panelAt = time;
this.updatePanel();
}
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.playfield);
}
}
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(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;
}
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);
}
// ── 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.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);
}
// mode: 'idle' | 'act' | 'wait' | 'summary' | 'busted'
setDockMode(mode, status = '') {
this.dockMode = mode;
this.dock.setMode(mode, mode === 'idle' ? status : '');
if (mode === 'wait') this.refreshPreButtons();
}
// ── 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),
};
}
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.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 ─────────────────────────────────────────────────────────────────
async showBuyIn() {
try {
const { chips } = await api.get('/profile/chips');
this.globalChips = chips;
} catch {
this.globalChips = 0;
}
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) {
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;
}
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));
}
}
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();
}
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));
}
// ── 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);
}
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;
}
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() }));
}
this.lastBlindLevel = level;
this.updatePanel();
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();
}
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;
}
// Deal two cards to every live player, starting left of the dealer.
async dealHoleCards() {
const n = this.gs.players.length;
const order = [];
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);
});
}
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;
}
}
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 {
// 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');
}
}
// 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;
}
// ── 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));
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();
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();
// '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),
});
}
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();
}
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');
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));
// 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) : []);
// Board row
const BS = 1.25;
community.forEach((card, i) => {
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));
});
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();
};
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 });
}
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);
}
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() {
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);
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 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));
}
}