Files
Poker/server/hand.js
T
agomizi1cmandClaude Opus 5.5 66907345ff Add optional card mode: server deals cards and settles showdowns automatically
- New "カードを配る" switch on the create-table screen (default off); the lobby
  shows "カードあり" for tables that use it
- Card mode (server/cards.js restored): crypto-shuffled deck kept server-side,
  hole cards sent only to their owner until showdown/all-in reveal, board dealt
  per street with burns, all-in runout on a timer (frozen while paused)
- Showdown is evaluated and every pot (incl. side pots, split pots) is paid out
  automatically; host winner selection is only used when card mode is off
- Play UI: board, hole cards, own cards in the action bar, hand names, winning
  cards highlighted; layout tuned for 7+ seats and short screens
- Playing-card styles use .pcard so they don't clash with the existing .card panel
- Tests for hand evaluation, card privacy, runout, side pots, ties and random play

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:44:22 +09:00

384 lines
14 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.
'use strict';
const { newDeck, bestHand, compareScore } = require('./cards');
// 1ハンド分の進行(ブラインド・ベッティング・ポット分配)。
// cards = false: カードは実物で配るので扱わない。ショーダウンでは勝者をホストが選ぶ。
// cards = true : サーバが配り、ショーダウンで役を判定して自動で分配する。
// seats は Table.seats への参照で、スタックはここで直接増減する。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
const STREETS = ['PREFLOP', 'FLOP', 'TURN', 'RIVER'];
class Hand {
constructor({ number, seats, order, button, sb, bb, cards = false }) {
this.number = number;
this.seats = seats;
this.order = order; // 参加者の席番号。ボタンの次から時計回り
this.button = button;
this.sb = sb;
this.bb = bb;
this.cards = cards;
// 山札はサーバの外に出さない
this.deck = cards ? newDeck() : null;
this.board = [];
this.revealed = false; // ショーダウン・オールイン時に残った人の手札を公開
this.runout = false; // オールインでこれ以上ベットが無く、残りの場札を順にめくっている
this.street = 'PREFLOP'; // PREFLOP / FLOP / TURN / RIVER / SHOWDOWN
this.pot = 0; // 前のストリートまでに集めた額
this.currentBet = 0;
this.minRaise = bb;
this.toAct = null;
this.finished = false;
this.showdown = false;
this.results = null;
this.players = new Map();
for (const i of order) {
this.players.set(i, {
seat: i,
token: seats[i].token,
cards: [],
best: null, // ショーダウンでの最強の5枚
bet: 0, // このストリートで出した額
committed: 0, // このハンドで出した合計
folded: false,
allIn: false,
acted: false,
last: null, // 直前のアクション(表示用)
won: 0,
});
}
if (cards) for (let r = 0; r < 2; r++) for (const i of order) this.players.get(i).cards.push(this.deck.pop());
// ヘッズアップはボタンが SB
const headsUp = order.length === 2;
this.sbSeat = headsUp ? button : order[0];
this.bbSeat = headsUp ? order[0] : order[1];
this.post(this.sbSeat, sb);
this.post(this.bbSeat, bb);
this.currentBet = bb; // BB がショートでもコール額は BB
this.setNextActor(this.bbSeat);
}
get list() {
return this.order.map((i) => this.players.get(i));
}
// 勝者の選択待ち(カードありのときは自動で判定するので来ない)
get awaitingWinners() {
return !this.cards && this.street === 'SHOWDOWN' && !this.finished;
}
live() {
return this.list.filter((p) => !p.folded);
}
put(p, amount) {
const s = this.seats[p.seat];
s.stack -= amount;
p.bet += amount;
p.committed += amount;
if (s.stack === 0) p.allIn = true;
}
post(seat, amount) {
const p = this.players.get(seat);
this.put(p, Math.min(amount, this.seats[seat].stack));
}
needsToAct(p) {
return !p.folded && !p.allIn && (!p.acted || p.bet < this.currentBet);
}
bettingClosed() {
const live = this.live();
if (live.length <= 1) return true;
const actors = live.filter((p) => !p.allIn);
if (actors.length === 0) return true;
// 動ける人が1人だけで、誰かのベットに応じる必要もない
const maxBet = Math.max(...live.map((p) => p.bet));
if (actors.length === 1 && actors[0].bet >= maxBet) return true;
return actors.every((p) => !this.needsToAct(p));
}
setNextActor(fromSeat) {
this.toAct = null;
if (this.bettingClosed()) return this.endStreet();
const n = this.order.length;
const start = this.order.indexOf(fromSeat);
for (let k = 1; k <= n; k++) {
const p = this.players.get(this.order[(start + k) % n]);
if (!this.needsToAct(p)) continue;
this.toAct = p.seat;
// 離席中・退席済みの人は自動でチェック/フォールド
const s = this.seats[p.seat];
if (s.sittingOut || s.left) this.autoAct();
return;
}
this.endStreet();
}
// 手番の人の選択肢(手番でなければ null)
options(seat) {
if (this.finished || this.toAct !== seat) return null;
const p = this.players.get(seat);
const stack = this.seats[seat].stack;
const toCall = Math.min(this.currentBet - p.bet, stack);
const maxTo = p.bet + stack;
// 他の全員がオールインならレイズしても意味がない
const opponentCanAct = this.live().some((q) => q !== p && !q.allIn);
return {
toCall,
canCheck: p.bet >= this.currentBet,
canRaise: !p.acted && stack > toCall && opponentCanAct,
minRaiseTo: Math.min(this.currentBet + this.minRaise, maxTo),
maxRaiseTo: maxTo,
isBet: this.currentBet === 0,
};
}
// type: fold / check / call / raise(amount = このストリートでの合計額 "raise to")
act(seat, type, amount) {
const o = this.options(seat);
if (!o) return 'あなたの番ではありません';
const p = this.players.get(seat);
if (type === 'fold') {
p.folded = true;
p.last = { type: 'FOLD' };
} else if (type === 'check') {
if (!o.canCheck) return 'チェックできません';
p.last = { type: 'CHECK' };
} else if (type === 'call') {
if (o.canCheck || o.toCall <= 0) return 'コールする額がありません';
this.put(p, o.toCall);
p.last = { type: 'CALL', amount: p.bet };
} else if (type === 'raise') {
if (!o.canRaise) return 'レイズできません';
if (!Number.isInteger(amount) || amount < o.minRaiseTo || amount > o.maxRaiseTo) {
return `${o.minRaiseTo}〜${o.maxRaiseTo} の額を指定してください`;
}
const raiseSize = amount - this.currentBet;
this.put(p, amount - p.bet);
p.last = { type: o.isBet ? 'BET' : 'RAISE', amount };
if (raiseSize >= this.minRaise) {
// 正規のレイズ: 他の人はもう一度アクションできる
this.minRaise = raiseSize;
for (const q of this.list) if (q !== p) q.acted = false;
}
// 足りないオールインのレイズはアクション済みの人に再レイズ権を与えない
this.currentBet = amount;
} else {
return '不正なアクションです';
}
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet };
p.acted = true;
this.setNextActor(seat);
return null;
}
autoAct() {
const o = this.options(this.toAct);
if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0);
}
// 退席などで手番に関係なくフォールドさせる
forceFold(seat) {
const p = this.players.get(seat);
if (!p || p.folded || this.finished) return;
if (this.toAct === seat) return this.act(seat, 'fold', 0);
p.folded = true;
p.last = { type: 'FOLD' };
if (this.live().length === 1) {
if (this.awaitingWinners) this.finishFoldWin();
else this.endStreet();
} else if (this.toAct != null && this.bettingClosed()) {
this.endStreet();
}
}
// 誰もコールしなかった分を返す
returnUncalled() {
const bets = this.list.map((p) => p.bet).sort((a, b) => b - a);
const excess = bets[0] - (bets[1] || 0);
if (excess <= 0) return;
const p = this.list.find((q) => q.bet === bets[0]);
if (p.folded) return; // 退席でフォールドした人のベットはそのままポットに残る
p.bet -= excess;
p.committed -= excess;
this.seats[p.seat].stack += excess;
p.allIn = this.seats[p.seat].stack === 0;
if (!p.allIn && p.last && p.last.type === 'ALLIN') p.last = null;
}
endStreet() {
this.toAct = null;
this.returnUncalled();
for (const p of this.list) {
this.pot += p.bet;
p.bet = 0;
p.acted = false;
if (p.last && p.last.type !== 'FOLD' && p.last.type !== 'ALLIN') p.last = null;
}
if (this.live().length === 1) return this.finishFoldWin();
this.currentBet = 0;
this.minRaise = this.bb;
const noMoreBetting = this.live().filter((p) => !p.allIn).length < 2;
if (!this.cards) {
// リバーが終わった、または全員オールインでこれ以上ベットが無い → ショーダウン
if (this.street === 'RIVER' || noMoreBetting) {
this.street = 'SHOWDOWN';
return;
}
this.street = STREETS[STREETS.indexOf(this.street) + 1];
} else {
if (this.street === 'RIVER') return this.finishShowdown();
if (noMoreBetting) {
// 手札を公開して、残りの場札は Table のタイマーで順にめくる(runoutStep)
this.revealed = true;
this.runout = true;
return;
}
this.dealStreet();
}
this.setNextActor(this.button);
}
dealStreet() {
this.deck.pop(); // バーン
if (this.street === 'PREFLOP') this.board.push(this.deck.pop(), this.deck.pop(), this.deck.pop());
else this.board.push(this.deck.pop());
this.street = STREETS[STREETS.indexOf(this.street) + 1];
}
// オールイン後に場札を1ストリート分めくる。リバーまでめくり終えていたらショーダウン
runoutStep() {
if (!this.runout || this.finished) return;
if (this.street === 'RIVER') this.finishShowdown();
else this.dealStreet();
}
// メインポット・サイドポット(同じ参加者のポットはまとめる)
buildPots() {
const all = this.list;
const levels = [...new Set(all.map((p) => p.committed).filter((c) => c > 0))].sort((a, b) => a - b);
const pots = [];
let prev = 0;
for (const level of levels) {
let amount = 0;
for (const p of all) amount += Math.max(0, Math.min(p.committed, level) - prev);
prev = level;
let eligible = all.filter((p) => !p.folded && p.committed >= level).map((p) => p.seat);
const last = pots[pots.length - 1];
if (eligible.length === 0) eligible = last ? last.eligible : this.live().map((p) => p.seat);
if (last && last.eligible.join() === eligible.join()) last.amount += amount;
else pots.push({ amount, eligible });
}
return pots;
}
finishFoldWin() {
const winner = this.live()[0];
winner.won = this.pot;
this.seats[winner.seat].stack += this.pot;
this.end(false, [{ amount: this.pot, winners: [winner.seat] }]);
}
// ショーダウンの勝者を決める。winners[i] = i 番目のポットの勝者の席番号(引き分けは複数)
award(winners) {
if (!this.awaitingWinners) return 'ショーダウンではありません';
const pots = this.buildPots();
if (!Array.isArray(winners) || winners.length !== pots.length) return 'すべてのポットの勝者を選んでください';
for (let i = 0; i < pots.length; i++) {
const w = winners[i];
if (!Array.isArray(w) || w.length === 0) return 'すべてのポットの勝者を選んでください';
if (new Set(w).size !== w.length || !w.every((s) => pots[i].eligible.includes(s))) return '勝者の指定が不正です';
}
const results = pots.map((pot, i) => ({ amount: pot.amount, winners: this.payout(pot.amount, winners[i]) }));
this.end(true, results);
return null;
}
// カードありのショーダウン: ポットごとに役を比べて分配する
finishShowdown() {
this.revealed = true;
for (const p of this.live()) p.best = bestHand(p.cards.concat(this.board));
const results = this.buildPots().map((pot) => {
const contenders = pot.eligible.map((s) => this.players.get(s));
let top = null;
for (const c of contenders) if (!top || compareScore(c.best.score, top) > 0) top = c.best.score;
const best = contenders.filter((c) => compareScore(c.best.score, top) === 0);
return {
amount: pot.amount,
winners: this.payout(pot.amount, best.map((c) => c.seat)),
handName: best[0].best.name,
bestCards: best[0].best.cards,
};
});
this.end(true, results);
}
// amount を seats で山分けする。割り切れない端数はボタンの左から順に。分配した順の席番号を返す
payout(amount, seats) {
const ws = this.order.filter((s) => seats.includes(s));
const share = Math.floor(amount / ws.length);
let rest = amount - share * ws.length;
for (const s of ws) {
const a = share + (rest > 0 ? 1 : 0);
if (rest > 0) rest--;
this.players.get(s).won += a;
this.seats[s].stack += a;
}
return ws;
}
end(showdown, results) {
this.finished = true;
this.runout = false;
this.showdown = showdown;
this.toAct = null;
this.results = results;
}
// 閲覧者に見せてよい情報だけを返す(他人の手札は公開時のみ)
view(viewerSeat, viewerToken) {
const players = {};
for (const p of this.list) {
const v = { bet: p.bet, folded: p.folded, allIn: p.allIn, last: p.last, won: p.won };
if (this.cards) {
const mine = p.seat === viewerSeat && p.token === viewerToken;
const shown = mine || (this.revealed && !p.folded);
v.cards = shown ? p.cards : null;
v.handName =
shown && !p.folded && this.board.length >= 3 ? (p.best || bestHand(p.cards.concat(this.board))).name : null;
}
players[p.seat] = v;
}
return {
number: this.number,
cards: this.cards,
board: this.board,
runout: this.runout,
street: this.street,
pot: this.pot,
potTotal: this.pot + this.list.reduce((sum, p) => sum + p.bet, 0),
currentBet: this.currentBet,
button: this.button,
sbSeat: this.sbSeat,
bbSeat: this.bbSeat,
toAct: this.toAct,
finished: this.finished,
showdown: this.showdown,
pots: this.awaitingWinners ? this.buildPots() : null,
results: this.results,
players,
};
}
}
module.exports = { Hand };