Implement Texas Hold'em play: dealing, betting, side pots, showdown

- Hand engine (server/hand.js): crypto-shuffled deck kept server-side,
  blinds (heads-up button = SB), min-raise rules incl. incomplete all-in,
  uncalled bet refunds, side pots, split pots, all-in runout
- Hand evaluator (server/cards.js) and node:test suite (npm test)
- Table flow: hands auto-continue after host START, 30s action clock
  (timeout = check/fold + sit out), sit out / sit in, rebuy, mid-hand leave
  folds and keeps the seat reserved until the hand ends, pause freezes all clocks
- Only each player's own hole cards are sent until a showdown/runout reveal;
  all actions validated server-side
- Play UI: board, hole cards, bets, action tags, turn timer, raise panel with
  presets, showdown results with winning cards highlighted, compact 7+ layout
- Remove the host crown and the temporary "next phase" control

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
agomizi1cmandClaude Opus 5.5 committed 2026-10-15 17:34:25 +09:00
1 parent b2c91062f1
commit 8de55f7ca5
12 files changed
+1648 -167

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
'use strict';
const crypto = require('crypto');
// カードは "As"(スペードのA), "Td"(ダイヤの10)のような2文字
const RANKS = '23456789TJQKA';
const SUITS = 'shdc';
// 暗号論的乱数で Fisher-Yates シャッフル(山札はサーバの外に出さない)
function newDeck() {
const deck = [];
for (const r of RANKS) for (const s of SUITS) deck.push(r + s);
for (let i = deck.length - 1; i > 0; i--) {
const j = crypto.randomInt(i + 1);
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
}
const rankValue = (card) => RANKS.indexOf(card[0]) + 2;
// 5枚の役の強さ。配列を先頭から比較して大きいほうが強い
// [役の種類(0〜8), 比較用の数字...]
function score5(cards) {
const vals = cards.map(rankValue).sort((a, b) => b - a);
const flush = cards.every((c) => c[1] === cards[0][1]);
let straightHigh = 0;
if (new Set(vals).size === 5) {
if (vals[0] - vals[4] === 4) straightHigh = vals[0];
else if (vals[0] === 14 && vals[1] === 5) straightHigh = 5; // A-2-3-4-5
}
if (straightHigh && flush) return [8, straightHigh];
// 枚数の多い順、同じ枚数なら数字の大きい順
const counts = new Map();
for (const v of vals) counts.set(v, (counts.get(v) || 0) + 1);
const groups = [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0]);
const byGroup = groups.map((g) => g[0]);
if (groups[0][1] === 4) return [7, ...byGroup];
if (groups[0][1] === 3 && groups[1][1] === 2) return [6, ...byGroup];
if (flush) return [5, ...vals];
if (straightHigh) return [4, straightHigh];
if (groups[0][1] === 3) return [3, ...byGroup];
if (groups[0][1] === 2 && groups[1][1] === 2) return [2, ...byGroup];
if (groups[0][1] === 2) return [1, ...byGroup];
return [0, ...vals];
}
function compareScore(a, b) {
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const d = (a[i] || 0) - (b[i] || 0);
if (d) return d;
}
return 0;
}
const HAND_NAMES = [
'ハイカード',
'ワンペア',
'ツーペア',
'スリーカード',
'ストレート',
'フラッシュ',
'フルハウス',
'フォーカード',
'ストレートフラッシュ',
];
function handName(score) {
if (score[0] === 8 && score[1] === 14) return 'ロイヤルフラッシュ';
return HAND_NAMES[score[0]];
}
// 5〜7枚から最も強い5枚を選ぶ
function bestHand(cards) {
let best = null;
const n = cards.length;
const pick = (start, chosen) => {
if (chosen.length === 5) {
const score = score5(chosen);
if (!best || compareScore(score, best.score) > 0) best = { score, cards: chosen.slice() };
return;
}
for (let i = start; i <= n - (5 - chosen.length); i++) {
chosen.push(cards[i]);
pick(i + 1, chosen);
chosen.pop();
}
};
pick(0, []);
return best && { score: best.score, cards: best.cards, name: handName(best.score) };
}
module.exports = { newDeck, score5, compareScore, bestHand, handName };
+10
View File
@@ -53,6 +53,16 @@ module.exports = {
// 誰も接続していないテーブルを削除するまでの時間
EMPTY_TABLE_TTL_MS: 30 * 60 * 1000,
// 1手の持ち時間。過ぎると自動でチェック/フォールドして離席扱い
ACTION_TIME_MS: 30 * 1000,
// オールインで残りのカードをめくる間隔
RUNOUT_STEP_MS: 1500,
// ハンド終了後、次のハンドまで結果を表示する時間
SHOWDOWN_MS: 5000,
FOLD_WIN_MS: 2500,
// 参加者が2人揃ってから次のハンドを始めるまで
NEXT_HAND_DELAY_MS: 2000,
// 鍵入力のブルートフォース対策
// IP(IPv6 は /64 単位)ごと: WINDOW 内で MAX_FAILURES 回まで
AUTH_MAX_FAILURES: 5,
+360
View File
@@ -0,0 +1,360 @@
'use strict';
const config = require('./config');
const { newDeck, bestHand, compareScore } = require('./cards');
// 1ハンド分の進行(配札・ベッティング・ショーダウン・ポット分配)
// seats は Table.seats への参照で、スタックはここで直接増減する。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
class Hand {
constructor({ number, seats, order, button, sb, bb, now }) {
this.number = number;
this.seats = seats;
this.order = order; // 参加者の席番号。ボタンの次から時計回り
this.button = button;
this.sb = sb;
this.bb = bb;
this.deck = newDeck();
this.board = [];
this.street = 'PREFLOP';
this.pot = 0; // 前のストリートまでに集めた額
this.currentBet = 0;
this.minRaise = bb;
this.toAct = null;
this.deadline = null;
this.runoutAt = null;
this.revealed = false; // オールインで以降のアクションが無いとき、ショーダウン時に公開
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: [],
bet: 0, // このストリートで出した額
committed: 0, // このハンドで出した合計
folded: false,
allIn: false,
acted: false,
last: null, // 直前のアクション(表示用)
won: 0,
best: null,
});
}
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, now);
}
get list() {
return this.order.map((i) => this.players.get(i));
}
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, now) {
this.toAct = null;
this.deadline = null;
if (this.bettingClosed()) return this.endStreet(now);
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;
this.deadline = now + config.ACTION_TIME_MS;
// 離席中・退席済みの人は自動でチェック/フォールド
const s = this.seats[p.seat];
if (s.sittingOut || s.left) this.autoAct(now);
return;
}
this.endStreet(now);
}
// 手番の人の選択肢(手番でなければ 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, now) {
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, now);
return null;
}
autoAct(now) {
const o = this.options(this.toAct);
if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0, now);
}
// 退席などで手番に関係なくフォールドさせる
forceFold(seat, now) {
const p = this.players.get(seat);
if (!p || p.folded || this.finished) return;
if (this.toAct === seat) return this.act(seat, 'fold', 0, now);
p.folded = true;
p.last = { type: 'FOLD' };
if (this.live().length === 1) {
this.runoutAt = null;
this.endStreet(now);
} else if (this.toAct != null && this.bettingClosed()) {
this.endStreet(now);
}
}
// 誰もコールしなかった分を返す
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(now) {
this.toAct = null;
this.deadline = 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.finish(false);
if (this.street === 'RIVER') return this.finish(true);
this.currentBet = 0;
this.minRaise = this.bb;
if (this.live().filter((p) => !p.allIn).length >= 2) {
this.dealStreet();
this.setNextActor(this.button, now);
} else {
// これ以上ベットが無いので手札を公開して残りのカードを順にめくる
this.revealed = true;
this.runoutAt = now + config.RUNOUT_STEP_MS;
}
}
dealStreet() {
this.deck.pop(); // バーン
if (this.street === 'PREFLOP') {
this.board.push(this.deck.pop(), this.deck.pop(), this.deck.pop());
this.street = 'FLOP';
} else if (this.street === 'TURN' || this.street === 'FLOP') {
this.board.push(this.deck.pop());
this.street = this.street === 'FLOP' ? 'TURN' : 'RIVER';
}
}
runoutStep(now) {
if (this.street === 'RIVER') {
this.runoutAt = null;
return this.finish(true);
}
this.dealStreet();
this.runoutAt = now + config.RUNOUT_STEP_MS;
}
// 手番の時間切れ。true なら時間切れ処理をした
timeout(now) {
if (this.finished || this.toAct == null || now < this.deadline) return false;
this.autoAct(now);
return true;
}
// メインポット・サイドポット(同じ参加者のポットはまとめる)
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;
}
finish(showdown) {
this.finished = true;
this.showdown = showdown;
this.toAct = null;
this.deadline = null;
this.runoutAt = null;
const results = [];
if (!showdown) {
const winner = this.live()[0];
winner.won = this.pot;
this.seats[winner.seat].stack += this.pot;
results.push({ amount: this.pot, winners: [winner.seat], handName: null, bestCards: [] });
} else {
this.revealed = true;
for (const p of this.live()) p.best = bestHand(p.cards.concat(this.board));
for (const pot of this.buildPots()) {
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 winners = contenders.filter((c) => compareScore(c.best.score, top) === 0);
// 割り切れない端数はボタンの左から順に
const share = Math.floor(pot.amount / winners.length);
let rest = pot.amount - share * winners.length;
for (const w of winners) {
const amount = share + (rest > 0 ? 1 : 0);
if (rest > 0) rest--;
w.won += amount;
this.seats[w.seat].stack += amount;
}
results.push({
amount: pot.amount,
winners: winners.map((w) => w.seat),
handName: winners[0].best.name,
bestCards: winners[0].best.cards,
});
}
}
this.pot = results.reduce((sum, r) => sum + r.amount, 0);
this.results = results;
}
// 閲覧者 viewerSeat に見せてよい情報だけを返す(他人の手札は公開時のみ)
view(viewerSeat, viewerToken) {
const players = {};
for (const p of this.list) {
const mine = p.seat === viewerSeat && p.token === viewerToken;
const shown = mine || (this.revealed && !p.folded);
let handName = null;
if (shown && !p.folded && this.board.length >= 3) {
handName = (p.best || bestHand(p.cards.concat(this.board))).name;
}
players[p.seat] = {
bet: p.bet,
folded: p.folded,
allIn: p.allIn,
last: p.last,
cards: shown ? p.cards : null,
handName,
won: p.won,
};
}
return {
number: this.number,
street: this.street,
board: this.board,
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,
results: this.results,
players,
};
}
}
module.exports = { Hand };
+15 -6
View File
@@ -216,18 +216,27 @@ io.on('connection', (socket) => {
changed(table);
});
// ホスト操作・退席は同じ形で処理する
// プレイヤー操作・ホスト操作は同じ形で処理する(操作者は join 時のトークンで決まる)
const ACTION_TYPES = new Set(['fold', 'check', 'call', 'raise']);
const actions = {
'table:leave': (t, token) => (t.leave(token) ? null : '着席していません'),
'table:start': (t, token) => t.start(token),
'table:nextPhase': (t, token) => t.nextPhase(token),
'table:pause': (t, token) => t.togglePause(token),
'table:action': (t, token, p) => {
if (!p || typeof p !== 'object' || !ACTION_TYPES.has(p.type)) return '不正なアクションです';
const amount = p.type === 'raise' ? p.amount : 0;
if (!Number.isSafeInteger(amount)) return '額が不正です';
return t.act(token, p.type, amount);
},
'table:sitOut': (t, token) => t.setSittingOut(token, true),
'table:sitIn': (t, token) => t.setSittingOut(token, false),
'table:rebuy': (t, token) => t.rebuy(token),
};
for (const [event, fn] of Object.entries(actions)) {
socket.on(event, (_p, ack) => {
socket.on(event, (p, ack) => {
const table = socket.data.tableId && tables.get(socket.data.tableId);
if (!table) return reply(ack, { ok: false, error: 'NOT_FOUND' });
const error = fn(table, socket.data.token);
const error = fn(table, socket.data.token, p);
reply(ack, error ? { ok: false, error } : { ok: true });
if (!error) changed(table);
});
@@ -239,13 +248,13 @@ io.on('connection', (socket) => {
});
});
// ブラインドタイマー
// ブラインドタイマー・持ち時間・次のハンドなど時間で進む処理
setInterval(() => {
const now = Date.now();
for (const table of tables.tables.values()) {
if (table.tick(now)) changed(table);
}
}, 1000);
}, 250);
// 誰も見ていないテーブルを片付ける
setInterval(() => {
+200 -77
View File
@@ -3,9 +3,7 @@
const crypto = require('crypto');
const config = require('./config');
const Blinds = require('../public/assets/blinds');
// 進行フェーズ。プレイ処理は未実装なので、ホストが手動で進めるスタブ。
const HAND_PHASES = ['PREFLOP', 'FLOP', 'TURN', 'RIVER', 'SHOWDOWN'];
const { Hand } = require('./hand');
class Table {
constructor(opts) {
@@ -19,14 +17,17 @@ class Table {
this.hostToken = opts.hostToken || null;
this.maxSeats = config.MAX_SEATS;
this.seats = new Array(this.maxSeats).fill(null); // { token, name, stack }
this.phase = 'WAITING';
// { token, name, stack, buyIns, sittingOut, left }
// left: ハンド中に退席した人。ハンドが終わるまで席を予約しておく
this.seats = new Array(this.maxSeats).fill(null);
this.hand = null;
this.started = false;
this.paused = false;
this.pausedAt = null;
this.level = 1;
this.handNumber = 0;
this.pot = 0;
this.buttonSeat = null;
this.nextHandAt = null;
this.levelEndsAt = null;
this.levelRemainingMs = this.intervalMs;
@@ -42,114 +43,165 @@ class Table {
return Blinds.blindsAt(this.baseSmallBlind, this.baseBigBlind, this.level);
}
get phase() {
if (!this.hand) return 'WAITING';
return this.hand.finished ? 'FINISHING' : this.hand.street;
}
get handActive() {
return Boolean(this.hand && !this.hand.finished);
}
get playerCount() {
return this.seats.filter(Boolean).length;
return this.seats.filter((s) => s && !s.left).length;
}
seatOf(token) {
return this.seats.findIndex((s) => s && s.token === token);
return token ? this.seats.findIndex((s) => s && s.token === token) : -1;
}
isHost(token) {
return Boolean(token) && token === this.hostToken;
}
// 次のハンドに参加できる席
eligibleSeats() {
return this.seats
.map((s, i) => (s && !s.left && !s.sittingOut && s.stack > 0 ? i : -1))
.filter((i) => i >= 0);
}
canDeal() {
return this.started && !this.paused && this.eligibleSeats().length >= 2;
}
// 着席した席番号を返す。満席なら -1(観戦)
join(token, name) {
const existing = this.seatOf(token);
if (existing >= 0) {
this.seats[existing].name = name;
const s = this.seats[existing];
s.name = name;
if (s.left) {
s.left = false; // ハンド中に退席して戻ってきた
if (this.seatOf(this.hostToken) < 0 || this.seats[this.seatOf(this.hostToken)].left) this.hostToken = token;
}
return existing;
}
const free = this.seats.findIndex((s) => !s);
if (free < 0) return -1;
this.seats[free] = { token, name, stack: this.startingStack };
this.seats[free] = { token, name, stack: this.startingStack, buyIns: 1, sittingOut: false, left: false };
// ホスト(通常は作成者)が着席していなければ、この人がホストになる
if (this.seatOf(this.hostToken) < 0) this.hostToken = token;
const host = this.seatOf(this.hostToken);
if (host < 0 || this.seats[host].left) this.hostToken = token;
return free;
}
leave(token) {
leave(token, now = Date.now()) {
const i = this.seatOf(token);
if (i < 0) return false;
this.seats[i] = null;
if (this.hostToken === token) {
const next = this.seats.find(Boolean);
this.hostToken = next ? next.token : null;
if (i < 0 || this.seats[i].left) return false;
if (this.hand && this.hand.players.has(i)) {
// 結果表示やポット計算のため、ハンドが終わるまで席は残す
this.seats[i].left = true;
this.hand.forceFold(i, now);
} else {
this.seats[i] = null;
}
if (this.playerCount < 2 && this.phase !== 'WAITING') {
this.phase = 'WAITING';
if (this.hostToken === token) {
const next = this.seats.find((s) => s && !s.left);
this.hostToken = next ? next.token : null;
}
return true;
}
// 次に埋まっている席(時計回り = 席番号の昇順)
nextOccupied(from) {
removeLeftSeats() {
this.seats = this.seats.map((s) => (s && s.left ? null : s));
}
nextOf(list, from) {
for (let k = 1; k <= this.maxSeats; k++) {
const i = (from + k) % this.maxSeats;
if (this.seats[i]) return i;
if (list.includes(i)) return i;
}
return null;
}
blindSeats() {
if (this.buttonSeat == null || this.phase === 'WAITING' || this.playerCount < 2) {
return { sbSeat: null, bbSeat: null };
}
let sbSeat;
if (this.playerCount === 2 && this.seats[this.buttonSeat]) {
sbSeat = this.buttonSeat; // ヘッズアップはボタンがSB
} else {
sbSeat = this.nextOccupied(this.buttonSeat);
}
return { sbSeat, bbSeat: this.nextOccupied(sbSeat) };
}
startNewHand() {
const occupied = this.seats.map((s, i) => (s ? i : -1)).filter((i) => i >= 0);
startNewHand(now) {
this.removeLeftSeats();
const eligible = this.eligibleSeats();
this.buttonSeat =
this.buttonSeat == null
? occupied[Math.floor(Math.random() * occupied.length)]
: this.nextOccupied(this.buttonSeat);
this.handNumber++;
this.pot = 0;
this.phase = 'PREFLOP';
}
// ---- ホスト操作(エラー時はメッセージを返す) ----
start(token) {
if (!this.isHost(token)) return 'ホストのみ開始できます';
if (this.phase !== 'WAITING') return 'すでに進行中です';
if (this.playerCount < 2) return '2人以上必要です';
if (!this.started) {
this.started = true;
if (this.timerEnabled) this.levelEndsAt = Date.now() + this.intervalMs;
? eligible[crypto.randomInt(eligible.length)]
: this.nextOf(eligible, this.buttonSeat);
const order = [];
for (let i = this.nextOf(eligible, this.buttonSeat); order.length < eligible.length; i = this.nextOf(eligible, i)) {
order.push(i);
}
this.startNewHand();
this.handNumber++;
const { sb, bb } = this.blinds;
this.nextHandAt = null;
this.hand = new Hand({ number: this.handNumber, seats: this.seats, order, button: this.buttonSeat, sb, bb, now });
}
// ---- プレイヤー操作(エラー時はメッセージを返す) ----
act(token, type, amount, now = Date.now()) {
const i = this.seatOf(token);
if (i < 0) return '着席していません';
if (!this.handActive) return 'ハンドが進行していません';
if (this.paused) return '一時停止中です';
return this.hand.act(i, type, amount, now);
}
setSittingOut(token, value, now = Date.now()) {
const i = this.seatOf(token);
if (i < 0) return '着席していません';
const s = this.seats[i];
s.sittingOut = value;
// 手番中に離席したら、その場でチェック/フォールド
if (value && this.handActive && this.hand.toAct === i && !this.paused) this.hand.autoAct(now);
return null;
}
// スタブ: フェーズを1つ進める(SHOWDOWN の次は新しいハンド)
nextPhase(token) {
if (!this.isHost(token)) return 'ホストのみ操作できます';
if (this.phase === 'WAITING') return 'まだ開始していません';
if (this.playerCount < 2) return '2人以上必要です';
const i = HAND_PHASES.indexOf(this.phase);
if (i === HAND_PHASES.length - 1) this.startNewHand();
else this.phase = HAND_PHASES[i + 1];
rebuy(token) {
const i = this.seatOf(token);
if (i < 0) return '着席していません';
const s = this.seats[i];
if (s.stack > 0) return 'チップが残っています';
if (this.handActive && this.hand.players.has(i) && !this.hand.players.get(i).folded) return 'ハンドの終了後にリバイできます';
s.stack = this.startingStack;
s.buyIns++;
s.sittingOut = false;
return null;
}
togglePause(token) {
// ---- ホスト操作 ----
start(token, now = Date.now()) {
if (!this.isHost(token)) return 'ホストのみ開始できます';
if (this.started) return 'すでに開始しています';
if (this.eligibleSeats().length < 2) return '2人以上必要です';
this.started = true;
if (this.timerEnabled) this.levelEndsAt = now + this.intervalMs;
this.startNewHand(now);
return null;
}
togglePause(token, now = Date.now()) {
if (!this.isHost(token)) return 'ホストのみ操作できます';
if (!this.started) return 'まだ開始していません';
const now = Date.now();
if (this.paused) {
this.paused = false;
// 止めていた時間だけ各期限を後ろにずらす
const shift = now - this.pausedAt;
const h = this.hand;
if (h && h.deadline != null) h.deadline += shift;
if (h && h.runoutAt != null) h.runoutAt += shift;
if (this.nextHandAt != null) this.nextHandAt += shift;
if (this.timerEnabled) this.levelEndsAt = now + this.levelRemainingMs;
this.paused = false;
this.pausedAt = null;
} else {
this.paused = true;
this.pausedAt = now;
if (this.timerEnabled) {
this.levelRemainingMs = Math.max(0, this.levelEndsAt - now);
this.levelEndsAt = null;
@@ -158,7 +210,8 @@ class Table {
return null;
}
// ブラインドタイマー。レベルが上がったら true
// 時間で進む処理(ブラインドタイマー・手番の時間切れ・オールイン時のめくり・次のハンド)
// 状態が変わったら true
tick(now) {
let changed = false;
while (this.levelEndsAt != null && now >= this.levelEndsAt) {
@@ -166,6 +219,41 @@ class Table {
this.levelEndsAt += this.intervalMs;
changed = true;
}
if (this.paused) return changed;
const h = this.hand;
if (h && !h.finished) {
if (h.toAct != null && now >= h.deadline) {
this.seats[h.toAct].sittingOut = true; // 時間切れの人は離席扱い(戻るボタンで復帰)
h.timeout(now);
changed = true;
}
if (h.runoutAt != null && now >= h.runoutAt) {
h.runoutStep(now);
changed = true;
}
}
if (this.hand && this.hand.finished) {
if (this.nextHandAt == null) {
this.nextHandAt = now + (this.hand.showdown ? config.SHOWDOWN_MS : config.FOLD_WIN_MS);
} else if (now >= this.nextHandAt) {
if (this.canDeal()) this.startNewHand(now);
else {
this.hand = null;
this.nextHandAt = null;
this.removeLeftSeats();
}
changed = true;
}
} else if (!this.hand) {
if (!this.canDeal()) this.nextHandAt = null;
else if (this.nextHandAt == null) this.nextHandAt = now + config.NEXT_HAND_DELAY_MS;
else if (now >= this.nextHandAt) {
this.startNewHand(now);
changed = true;
}
}
return changed;
}
@@ -188,11 +276,28 @@ class Table {
};
}
// token = 閲覧者のトークン(他人のトークンは送らない)
// token = 閲覧者のトークン(他人のトークンや手札は送らない)
publicState(token, connectedTokens) {
const now = Date.now();
const { sb, bb } = this.blinds;
const next = Blinds.blindsAt(this.baseSmallBlind, this.baseBigBlind, this.level + 1);
const host = this.seatOf(this.hostToken);
const mySeat = this.seatOf(token);
const h = this.hand;
const hv = h ? h.view(mySeat, token) : null;
const me = mySeat >= 0 ? this.seats[mySeat] : null;
const inLiveHand = Boolean(this.handActive && h.players.has(mySeat) && !h.players.get(mySeat).folded);
let turn = null;
if (this.handActive && h.toAct != null) {
const remainingMs = Math.max(0, h.deadline - (this.paused ? this.pausedAt : now));
turn = {
seat: h.toAct,
endsAt: this.paused ? null : h.deadline,
remainingMs,
totalMs: config.ACTION_TIME_MS,
};
}
return {
id: this.id,
name: this.name,
@@ -206,23 +311,41 @@ class Table {
enabled: this.timerEnabled,
intervalMin: this.intervalMin,
endsAt: this.levelEndsAt,
remainingMs: this.levelEndsAt != null ? this.levelEndsAt - Date.now() : this.levelRemainingMs,
remainingMs: this.levelEndsAt != null ? this.levelEndsAt - now : this.levelRemainingMs,
running: this.levelEndsAt != null,
},
phase: this.phase,
started: this.started,
paused: this.paused,
pot: this.pot,
handNumber: this.handNumber,
buttonSeat: this.phase === 'WAITING' ? null : this.buttonSeat,
...this.blindSeats(),
hostSeat: host >= 0 ? host : null,
hand: hv,
turn,
seats: this.seats.map((s, i) =>
s ? { seat: i, name: s.name, stack: s.stack, connected: connectedTokens.has(s.token) } : null
s && !s.left
? {
seat: i,
name: s.name,
stack: s.stack,
connected: connectedTokens.has(s.token),
sittingOut: s.sittingOut,
...(hv && hv.players[i] ? { inHand: true, ...hv.players[i] } : { inHand: false }),
}
: null
),
mySeat: this.seatOf(token),
mySeat: me && !me.left ? mySeat : -1,
me:
me && !me.left
? {
stack: me.stack,
net: me.stack + (inLiveHand ? h.players.get(mySeat).committed : 0) - me.buyIns * this.startingStack,
buyIns: me.buyIns,
sittingOut: me.sittingOut,
canRebuy: me.stack === 0 && !inLiveHand,
options: this.handActive && !this.paused ? h.options(mySeat) : null,
}
: null,
isHost: this.isHost(token),
serverNow: Date.now(),
serverNow: now,
};
}
}
@@ -268,4 +391,4 @@ class TableManager {
}
}
module.exports = { TableManager };
module.exports = { TableManager, Table };