diff --git a/server/cards.js b/server/cards.js
deleted file mode 100644
index 09c1d35..0000000
--- a/server/cards.js
+++ /dev/null
@@ -1,96 +0,0 @@
-'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 };
diff --git a/server/config.js b/server/config.js
index 3b5a80b..f0eef7e 100644
--- a/server/config.js
+++ b/server/config.js
@@ -53,12 +53,8 @@ module.exports = {
// 誰も接続していないテーブルを削除するまでの時間
EMPTY_TABLE_TTL_MS: 30 * 60 * 1000,
- // 1手の持ち時間。過ぎると自動でチェック/フォールドして離席扱い
- ACTION_TIME_MS: 30 * 1000,
- // オールインで残りのカードをめくる間隔
- RUNOUT_STEP_MS: 1500,
// ハンド終了後、次のハンドまで結果を表示する時間
- SHOWDOWN_MS: 5000,
+ SHOWDOWN_MS: 4000,
FOLD_WIN_MS: 2500,
// 参加者が2人揃ってから次のハンドを始めるまで
NEXT_HAND_DELAY_MS: 2000,
diff --git a/server/hand.js b/server/hand.js
index 0f7ffb4..be8ba6d 100644
--- a/server/hand.js
+++ b/server/hand.js
@@ -1,13 +1,13 @@
'use strict';
-const config = require('./config');
-const { newDeck, bestHand, compareScore } = require('./cards');
-
-// 1ハンド分の進行(配札・ベッティング・ショーダウン・ポット分配)
+// 1ハンド分のチップの動き(ブラインド・ベッティング・ポット分配)。
+// カードは実物で配るので扱わない。ショーダウンでは勝者をプレイヤーが選ぶ。
// seats は Table.seats への参照で、スタックはここで直接増減する。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
+const STREETS = ['PREFLOP', 'FLOP', 'TURN', 'RIVER'];
+
class Hand {
- constructor({ number, seats, order, button, sb, bb, now }) {
+ constructor({ number, seats, order, button, sb, bb }) {
this.number = number;
this.seats = seats;
this.order = order; // 参加者の席番号。ボタンの次から時計回り
@@ -15,16 +15,11 @@ class Hand {
this.sb = sb;
this.bb = bb;
- this.deck = newDeck();
- this.board = [];
- this.street = 'PREFLOP';
+ this.street = 'PREFLOP'; // PREFLOP / FLOP / TURN / RIVER / SHOWDOWN
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;
@@ -34,7 +29,6 @@ class Hand {
this.players.set(i, {
seat: i,
token: seats[i].token,
- cards: [],
bet: 0, // このストリートで出した額
committed: 0, // このハンドで出した合計
folded: false,
@@ -42,10 +36,8 @@ class Hand {
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;
@@ -54,13 +46,17 @@ class Hand {
this.post(this.sbSeat, sb);
this.post(this.bbSeat, bb);
this.currentBet = bb; // BB がショートでもコール額は BB
- this.setNextActor(this.bbSeat, now);
+ this.setNextActor(this.bbSeat);
}
get list() {
return this.order.map((i) => this.players.get(i));
}
+ get awaitingWinners() {
+ return this.street === 'SHOWDOWN' && !this.finished;
+ }
+
live() {
return this.list.filter((p) => !p.folded);
}
@@ -93,23 +89,21 @@ class Hand {
return actors.every((p) => !this.needsToAct(p));
}
- setNextActor(fromSeat, now) {
+ setNextActor(fromSeat) {
this.toAct = null;
- this.deadline = null;
- if (this.bettingClosed()) return this.endStreet(now);
+ 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;
- this.deadline = now + config.ACTION_TIME_MS;
// 離席中・退席済みの人は自動でチェック/フォールド
const s = this.seats[p.seat];
- if (s.sittingOut || s.left) this.autoAct(now);
+ if (s.sittingOut || s.left) this.autoAct();
return;
}
- this.endStreet(now);
+ this.endStreet();
}
// 手番の人の選択肢(手番でなければ null)
@@ -132,7 +126,7 @@ class Hand {
}
// type: fold / check / call / raise(amount = このストリートでの合計額 "raise to")
- act(seat, type, amount, now) {
+ act(seat, type, amount) {
const o = this.options(seat);
if (!o) return 'あなたの番ではありません';
const p = this.players.get(seat);
@@ -167,27 +161,27 @@ class Hand {
}
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet };
p.acted = true;
- this.setNextActor(seat, now);
+ this.setNextActor(seat);
return null;
}
- autoAct(now) {
+ autoAct() {
const o = this.options(this.toAct);
- if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0, now);
+ if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0);
}
// 退席などで手番に関係なくフォールドさせる
- forceFold(seat, now) {
+ 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, now);
+ if (this.toAct === seat) return this.act(seat, 'fold', 0);
p.folded = true;
p.last = { type: 'FOLD' };
if (this.live().length === 1) {
- this.runoutAt = null;
- this.endStreet(now);
+ if (this.awaitingWinners) this.finishFoldWin();
+ else this.endStreet();
} else if (this.toAct != null && this.bettingClosed()) {
- this.endStreet(now);
+ this.endStreet();
}
}
@@ -205,9 +199,8 @@ class Hand {
if (!p.allIn && p.last && p.last.type === 'ALLIN') p.last = null;
}
- endStreet(now) {
+ endStreet() {
this.toAct = null;
- this.deadline = null;
this.returnUncalled();
for (const p of this.list) {
this.pot += p.bet;
@@ -215,46 +208,17 @@ class Hand {
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);
+ if (this.live().length === 1) return this.finishFoldWin();
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;
+ // リバーが終わった、または全員オールインでこれ以上ベットが無い → ショーダウン
+ if (this.street === 'RIVER' || this.live().filter((p) => !p.allIn).length < 2) {
+ this.street = 'SHOWDOWN';
+ return;
}
- }
-
- 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;
+ this.street = STREETS[STREETS.indexOf(this.street) + 1];
+ this.setNextActor(this.button);
}
// メインポット・サイドポット(同じ参加者のポットはまとめる)
@@ -276,72 +240,57 @@ class Hand {
return pots;
}
- finish(showdown) {
+ 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.forEach((pot, i) => {
+ // 割り切れない端数はボタンの左から順に
+ const ws = this.order.filter((s) => winners[i].includes(s));
+ const share = Math.floor(pot.amount / ws.length);
+ let rest = pot.amount - share * ws.length;
+ for (const s of ws) {
+ const amount = share + (rest > 0 ? 1 : 0);
+ if (rest > 0) rest--;
+ this.players.get(s).won += amount;
+ this.seats[s].stack += amount;
+ }
+ results.push({ amount: pot.amount, winners: ws });
+ });
+ this.end(true, results);
+ return null;
+ }
+
+ end(showdown, results) {
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) {
+ view() {
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,
- };
+ players[p.seat] = { bet: p.bet, folded: p.folded, allIn: p.allIn, last: p.last, 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,
@@ -351,6 +300,7 @@ class Hand {
toAct: this.toAct,
finished: this.finished,
showdown: this.showdown,
+ pots: this.awaitingWinners ? this.buildPots() : null,
results: this.results,
players,
};
diff --git a/server/index.js b/server/index.js
index 97cf85d..90048ad 100644
--- a/server/index.js
+++ b/server/index.js
@@ -228,6 +228,15 @@ io.on('connection', (socket) => {
if (!Number.isSafeInteger(amount)) return '額が不正です';
return t.act(token, p.type, amount);
},
+ 'table:award': (t, token, p) => {
+ // winners: ポットごとの勝者の席番号の配列
+ const w = p && typeof p === 'object' ? p.winners : null;
+ const ok =
+ Array.isArray(w) &&
+ w.length <= config.MAX_SEATS &&
+ w.every((a) => Array.isArray(a) && a.length <= config.MAX_SEATS && a.every((s) => Number.isInteger(s)));
+ return ok ? t.award(token, w) : '勝者の指定が不正です';
+ },
'table:sitOut': (t, token) => t.setSittingOut(token, true),
'table:sitIn': (t, token) => t.setSittingOut(token, false),
'table:rebuy': (t, token) => t.rebuy(token),
diff --git a/server/tables.js b/server/tables.js
index b0845ce..9d4198a 100644
--- a/server/tables.js
+++ b/server/tables.js
@@ -96,13 +96,13 @@ class Table {
return free;
}
- leave(token, now = Date.now()) {
+ leave(token) {
const i = this.seatOf(token);
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);
+ this.hand.forceFold(i);
} else {
this.seats[i] = null;
}
@@ -125,7 +125,7 @@ class Table {
return null;
}
- startNewHand(now) {
+ startNewHand() {
this.removeLeftSeats();
const eligible = this.eligibleSeats();
this.buttonSeat =
@@ -139,26 +139,41 @@ class Table {
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 });
+ this.hand = new Hand({ number: this.handNumber, seats: this.seats, order, button: this.buttonSeat, sb, bb });
}
// ---- プレイヤー操作(エラー時はメッセージを返す) ----
- act(token, type, amount, now = Date.now()) {
+ act(token, type, amount) {
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);
+ return this.hand.act(i, type, amount);
}
- setSittingOut(token, value, now = Date.now()) {
+ // ショーダウンの勝者を選べるのは、ショーダウンに残った人とホスト
+ canAward(token) {
+ if (!this.handActive || !this.hand.awaitingWinners) return false;
+ const i = this.seatOf(token);
+ const p = i >= 0 ? this.hand.players.get(i) : null;
+ return this.isHost(token) || Boolean(p && !p.folded && !this.seats[i].left);
+ }
+
+ award(token, winners) {
+ if (!this.handActive || !this.hand.awaitingWinners) return 'ショーダウンではありません';
+ if (!this.canAward(token)) return 'ショーダウンに残った人かホストが選んでください';
+ if (this.paused) return '一時停止中です';
+ return this.hand.award(winners);
+ }
+
+ setSittingOut(token, value) {
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);
+ if (value && this.handActive && this.hand.toAct === i && !this.paused) this.hand.autoAct();
return null;
}
@@ -182,7 +197,7 @@ class Table {
if (this.eligibleSeats().length < 2) return '2人以上必要です';
this.started = true;
if (this.timerEnabled) this.levelEndsAt = now + this.intervalMs;
- this.startNewHand(now);
+ this.startNewHand();
return null;
}
@@ -190,12 +205,8 @@ class Table {
if (!this.isHost(token)) return 'ホストのみ操作できます';
if (!this.started) return 'まだ開始していません';
if (this.paused) {
- // 止めていた時間だけ各期限を後ろにずらす
- 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.nextHandAt != null) this.nextHandAt += now - this.pausedAt;
if (this.timerEnabled) this.levelEndsAt = now + this.levelRemainingMs;
this.paused = false;
this.pausedAt = null;
@@ -210,7 +221,7 @@ class Table {
return null;
}
- // 時間で進む処理(ブラインドタイマー・手番の時間切れ・オールイン時のめくり・次のハンド)
+ // 時間で進む処理(ブラインドタイマー・次のハンドの開始)
// 状態が変わったら true
tick(now) {
let changed = false;
@@ -221,24 +232,11 @@ class Table {
}
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);
+ if (this.canDeal()) this.startNewHand();
else {
this.hand = null;
this.nextHandAt = null;
@@ -250,7 +248,7 @@ class Table {
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);
+ this.startNewHand();
changed = true;
}
}
@@ -276,28 +274,17 @@ 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 mySeat = this.seatOf(token);
const h = this.hand;
- const hv = h ? h.view(mySeat, token) : null;
+ const hv = h ? h.view() : 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,
@@ -319,7 +306,7 @@ class Table {
paused: this.paused,
handNumber: this.handNumber,
hand: hv,
- turn,
+ toAct: this.handActive ? h.toAct : null,
seats: this.seats.map((s, i) =>
s && !s.left
? {
@@ -342,6 +329,7 @@ class Table {
sittingOut: me.sittingOut,
canRebuy: me.stack === 0 && !inLiveHand,
options: this.handActive && !this.paused ? h.options(mySeat) : null,
+ canAward: this.canAward(token),
}
: null,
isHost: this.isHost(token),
diff --git a/test/engine.test.js b/test/engine.test.js
index 0475bdb..bf41b8a 100644
--- a/test/engine.test.js
+++ b/test/engine.test.js
@@ -5,9 +5,7 @@ process.env.ACCESS_KEY = process.env.ACCESS_KEY || '000000';
const test = require('node:test');
const assert = require('node:assert/strict');
-const { bestHand, compareScore } = require('../server/cards');
const { Table } = require('../server/tables');
-const config = require('../server/config');
const T = (n) => 't'.repeat(31) + n; // 32文字のトークン
@@ -30,41 +28,17 @@ function makeTable(stacks, opts = {}) {
return table;
}
-// 山札の上(pop される順)に指定のカードを積む
-function rig(hand, holes, board) {
- const used = new Set([...holes.flat(), ...board]);
- const rest = hand.deck.concat(...[...hand.players.values()].map((p) => p.cards)).filter((c) => !used.has(c));
- hand.order.forEach((seat, k) => (hand.players.get(seat).cards = holes[k].slice()));
- // dealStreet はバーン1枚 + 場札を pop する
- const seq = [];
- seq.push('X', board[0], board[1], board[2], 'X', board[3], 'X', board[4]);
- const filler = rest.slice();
- hand.deck = filler.slice(0, filler.length - 8).concat(seq.map((c) => (c === 'X' ? filler.pop() : c)).reverse());
+const tk = (t, seat) => t.seats[seat].token;
+
+// ショーダウンまでチェック/コールで進める
+function checkDown(t) {
+ const h = t.hand;
+ for (let guard = 0; guard < 100 && h.toAct != null; guard++) {
+ const o = h.options(h.toAct);
+ assert.equal(t.act(tk(t, h.toAct), o.canCheck ? 'check' : 'call', 0), null);
+ }
}
-test('役の判定と比較', () => {
- const h = (s) => bestHand(s.split(' '));
- assert.equal(h('As Ks Qs Js Ts 2d 3c').name, 'ロイヤルフラッシュ');
- assert.equal(h('5s 4s 3s 2s As Kd Kc').name, 'ストレートフラッシュ');
- assert.equal(h('9h 9d 9s 9c 2d 3c 4h').name, 'フォーカード');
- assert.equal(h('9h 9d 9s 2c 2d 3c 4h').name, 'フルハウス');
- assert.equal(h('Ah 9h 7h 4h 2h Kd Kc').name, 'フラッシュ');
- assert.equal(h('Ah 2d 3c 4s 5h Kd Kc').name, 'ストレート');
- assert.equal(h('Qh Qd Qs 7c 2d 3c 4h').name, 'スリーカード');
- assert.equal(h('Qh Qd 7s 7c 2d 3c 4h').name, 'ツーペア');
- assert.equal(h('Qh Qd 8s 7c 2d 3c 5h').name, 'ワンペア');
- assert.equal(h('Ah Qd 8s 7c 2d 3c 5h').name, 'ハイカード');
-
- // A-5 は最弱のストレート
- assert.ok(compareScore(h('Ah 2d 3c 4s 5h').score, h('2h 3d 4c 5s 6h').score) < 0);
- // キッカー
- assert.ok(compareScore(h('Ah Ad Ks 7c 2d').score, h('As Ac Qs 7d 2h').score) > 0);
- // 同点
- assert.equal(compareScore(h('Ah Kd Qs Jc 9d').score, h('As Kc Qd Jh 9s').score), 0);
- // ツーペアは上のペア → 下のペア → キッカー
- assert.ok(compareScore(h('Kh Kd 3s 3c Ad').score, h('Qh Qd Js Jc Ad').score) > 0);
-});
-
test('ヘッズアップ: ボタンがSBで先に動き、フォールドでBBが勝つ', () => {
const t = makeTable([1000, 1000]);
assert.equal(t.start(T(0), 0), null);
@@ -75,12 +49,10 @@ test('ヘッズアップ: ボタンがSBで先に動き、フォールドでBB
const bb = h.bbSeat;
assert.equal(t.seats[sb].stack, 990);
assert.equal(t.seats[bb].stack, 980);
- assert.equal(t.act(t.seats[sb].token, 'fold', 0, 1), null);
- assert.ok(h.finished);
+ assert.equal(t.act(tk(t, sb), 'fold', 0), null);
+ assert.ok(h.finished && !h.showdown);
assert.equal(t.seats[sb].stack, 990);
assert.equal(t.seats[bb].stack, 1010);
- // 手札は公開されない
- assert.equal(h.view(sb, t.seats[sb].token).players[bb].cards, null);
});
test('BBのオプションとチェックでストリートが進む', () => {
@@ -89,16 +61,18 @@ test('BBのオプションとチェックでストリートが進む', () => {
const h = t.hand;
const [sb, bb, btn] = h.order;
assert.equal(h.toAct, btn); // UTG = ボタン(3人)
- assert.equal(t.act(t.seats[btn].token, 'call', 0, 1), null);
- assert.equal(t.act(t.seats[sb].token, 'call', 0, 1), null);
+ assert.equal(t.act(tk(t, btn), 'call', 0), null);
+ assert.equal(t.act(tk(t, sb), 'call', 0), null);
assert.equal(h.street, 'PREFLOP');
assert.equal(h.toAct, bb); // BB はまだ動ける
assert.ok(h.options(bb).canRaise);
- assert.equal(t.act(t.seats[bb].token, 'check', 0, 1), null);
+ assert.equal(t.act(tk(t, bb), 'check', 0), null);
assert.equal(h.street, 'FLOP');
- assert.equal(h.board.length, 3);
assert.equal(h.pot, 60);
assert.equal(h.toAct, sb); // ポストフロップは SB から
+ checkDown(t);
+ assert.equal(t.phase, 'SHOWDOWN');
+ assert.deepEqual(h.view().pots, [{ amount: 60, eligible: [sb, bb, btn] }]);
});
test('ミニマムレイズと、足りないオールインは再レイズ権を与えない', () => {
@@ -106,106 +80,156 @@ test('ミニマムレイズと、足りないオールインは再レイズ権
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
- const tk = (s) => t.seats[s].token;
// 最低レイズ額は 40(20 + 20)
- assert.ok(t.act(tk(btn), 'raise', 39, 1));
- assert.equal(t.act(tk(btn), 'raise', 60, 1), null); // +40 のレイズ
+ assert.ok(t.act(tk(t, btn), 'raise', 39));
+ assert.equal(t.act(tk(t, btn), 'raise', 60), null); // +40 のレイズ
assert.equal(h.options(sb).minRaiseTo, 100);
- assert.equal(t.act(tk(sb), 'call', 0, 1), null);
+ assert.equal(t.act(tk(t, sb), 'call', 0), null);
// BB は 75 しか持っていないとする → 75 オールインは 100 未満なので不完全なレイズ
t.seats[bb].stack = 75 - 20;
- assert.equal(t.act(tk(bb), 'raise', 75, 1), null);
+ assert.equal(t.act(tk(t, bb), 'raise', 75), null);
assert.equal(h.currentBet, 75);
assert.equal(h.toAct, btn);
assert.equal(h.options(btn).canRaise, false); // コールかフォールドのみ
- assert.equal(t.act(tk(btn), 'raise', 200, 1), 'レイズできません');
- assert.equal(t.act(tk(btn), 'call', 0, 1), null);
- assert.equal(t.act(tk(sb), 'call', 0, 1), null);
+ assert.equal(t.act(tk(t, btn), 'raise', 200), 'レイズできません');
+ assert.equal(t.act(tk(t, btn), 'call', 0), null);
+ assert.equal(t.act(tk(t, sb), 'call', 0), null);
assert.equal(h.street, 'FLOP');
});
-test('3人オールイン: サイドポットと返金', () => {
+test('3人オールイン: すぐショーダウンになり、サイドポットと返金', () => {
const t = makeTable([100, 300, 500]);
t.start(T(0), 0);
const h = t.hand;
- const tk = (s) => t.seats[s].token;
- // 席0 が最強、席1 が2番目、席2 が最弱になるように配る
- const holes = { 0: ['As', 'Ah'], 1: ['Ks', 'Kh'], 2: ['7c', '2d'] };
- rig(h, h.order.map((s) => holes[s]), ['Ad', 'Kd', '9c', '5s', '3h']);
-
for (let guard = 0; guard < 10 && h.toAct != null; guard++) {
const o = h.options(h.toAct);
- assert.equal(t.act(tk(h.toAct), o.canRaise ? 'raise' : 'call', o.canRaise ? o.maxRaiseTo : 0, 1), null);
+ assert.equal(t.act(tk(t, h.toAct), o.canRaise ? 'raise' : 'call', o.canRaise ? o.maxRaiseTo : 0), null);
}
- assert.ok(h.revealed);
- // 残りのカードを順にめくる
- for (let now = 2; !h.finished && now < 100; now++) t.tick(now * config.RUNOUT_STEP_MS);
+ assert.equal(h.street, 'SHOWDOWN');
+ // 席2 の超過 200 は返金済み。メイン 300(全員)、サイド 400(席1・席2)
+ assert.equal(t.seats[2].stack, 200);
+ assert.deepEqual(
+ h.view().pots.map((p) => [p.amount, p.eligible.slice().sort()]),
+ [[300, [0, 1, 2]], [400, [1, 2]]]
+ );
+ // 席0 がメイン、席1 がサイドを獲得
+ assert.equal(t.award(T(0), [[0], [1]]), null);
assert.ok(h.finished && h.showdown);
- assert.equal(h.board.length, 5);
- // メイン 300 → 席0、サイド 400 → 席1、席2 の超過 200 は返金
assert.equal(t.seats[0].stack, 300);
assert.equal(t.seats[1].stack, 400);
assert.equal(t.seats[2].stack, 200);
- assert.deepEqual(h.results.map((r) => [r.amount, r.winners]), [[300, [0]], [400, [1]]]);
});
-test('引き分けは山分け、端数はボタンの左から', () => {
+test('勝者の指定: 山分け(端数はボタンの左から)と不正な指定の拒否', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
- const tk = (s) => t.seats[s].token;
const [sb, bb, btn] = h.order;
- rig(h, [['2c', '3d'], ['2d', '3c'], ['4h', '5h']], ['As', 'Ks', 'Qs', 'Js', 'Ts']); // 全員ロイヤル
- t.seats[sb].stack = 0; // SB は 10 だけ入れてオールイン扱いにする
- h.players.get(sb).allIn = true;
- t.act(tk(btn), 'call', 0, 1);
- t.act(tk(bb), 'check', 0, 1);
- for (let now = 2; !h.finished && now < 100; now++) {
- if (h.toAct != null) t.act(tk(h.toAct), 'check', 0, now);
- }
- assert.ok(h.finished);
- // メイン 30 を3人で 10 ずつ、サイド 20 を2人で 10 ずつ
- assert.equal(t.seats[sb].stack, 10);
- assert.equal(t.seats[bb].stack, 1000);
- assert.equal(t.seats[btn].stack, 1000);
+ // SB をフォールドさせて、BB とボタンで 50 のポットを争う(SB の 10 + 20 + 20)
+ assert.equal(t.act(tk(t, btn), 'call', 0), null);
+ assert.equal(t.act(tk(t, sb), 'fold', 0), null);
+ assert.equal(t.act(tk(t, bb), 'check', 0), null);
+ checkDown(t);
+ assert.equal(h.street, 'SHOWDOWN');
+ t.hostToken = T(7); // ホストの特例を除いて確認する
+
+ assert.equal(t.award(tk(t, sb), [[bb]]), 'ショーダウンに残った人かホストが選んでください');
+ assert.ok(t.award(tk(t, bb), []));
+ assert.ok(t.award(tk(t, bb), [[]]));
+ assert.ok(t.award(tk(t, bb), [[sb]])); // フォールドした人は勝てない
+ assert.ok(t.award(tk(t, bb), [[bb, bb]]));
+ assert.ok(t.award(tk(t, bb), [[bb], [btn]])); // ポットは1つ
+ assert.ok(t.award(T(8), [[bb]])); // 着席していない
+ assert.ok(!h.finished);
+
+ assert.equal(t.award(tk(t, bb), [[bb, btn]]), null);
+ // 50 を2人で → 25 ずつ
+ assert.equal(t.seats[bb].stack, 1005);
+ assert.equal(t.seats[btn].stack, 1005);
+ assert.equal(t.award(tk(t, bb), [[bb]]), 'ショーダウンではありません');
});
-test('持ち時間切れで自動フォールドし離席扱い、次のハンドから外れる', () => {
+test('端数はボタンの左から配る', () => {
+ const t = makeTable([1000, 1000, 1000], { smallBlind: 5, bigBlind: 10 });
+ t.start(T(0), 0);
+ const h = t.hand;
+ const [sb, bb, btn] = h.order;
+ t.act(tk(t, btn), 'call', 0);
+ t.act(tk(t, sb), 'fold', 0);
+ t.act(tk(t, bb), 'check', 0);
+ checkDown(t);
+ // 25 を2人で → ボタンの左に近い BB が 13、ボタンが 12
+ assert.equal(t.award(T(0), [[btn, bb]]), null);
+ assert.equal(t.seats[bb].stack, 990 + 13);
+ assert.equal(t.seats[btn].stack, 990 + 12);
+});
+
+test('ホストはショーダウンに参加していなくても勝者を選べる', () => {
+ const t = makeTable([1000, 1000, 1000]);
+ t.start(T(0), 0);
+ const h = t.hand;
+ // ホスト(席0)だけフォールドさせる
+ for (let guard = 0; guard < 50 && h.toAct != null; guard++) {
+ const o = h.options(h.toAct);
+ t.act(tk(t, h.toAct), h.toAct === 0 ? 'fold' : o.canCheck ? 'check' : 'call', 0);
+ }
+ assert.equal(h.street, 'SHOWDOWN');
+ const other = h.live().map((p) => p.seat);
+ assert.equal(t.canAward(T(0)), true);
+ assert.equal(t.award(T(0), [[other[0]]]), null);
+ assert.ok(h.finished);
+});
+
+test('ショーダウン中に1人を残して退席したら残った人が勝つ', () => {
+ const t = makeTable([1000, 1000]);
+ t.start(T(0), 0);
+ const h = t.hand;
+ checkDown(t);
+ assert.equal(h.street, 'SHOWDOWN');
+ const [a, b] = h.order;
+ t.leave(tk(t, a));
+ assert.ok(h.finished && !h.showdown);
+ assert.equal(t.seats[b].stack, 1020);
+});
+
+test('離席中の人の手番は自動でチェック/フォールド、次のハンドから外れる', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const first = h.toAct;
- t.tick(config.ACTION_TIME_MS + 1);
+ assert.equal(t.setSittingOut(tk(t, first), true), null);
assert.ok(h.players.get(first).folded);
- assert.ok(t.seats[first].sittingOut);
assert.notEqual(h.toAct, first);
- // 残りの2人で終わらせる
- while (!h.finished) {
- const o = h.options(h.toAct);
- t.act(t.seats[h.toAct].token, o.canCheck ? 'check' : 'call', 0, 2);
- }
+ t.act(tk(t, h.toAct), 'fold', 0); // 残り1人で終了
+ assert.ok(h.finished);
t.tick(10 ** 6);
t.tick(10 ** 7);
assert.equal(t.hand.number, 2);
assert.ok(!t.hand.players.has(first));
- // 復帰すると次から参加
- assert.equal(t.setSittingOut(t.seats[first].token, false), null);
+ assert.equal(t.setSittingOut(tk(t, first), false), null);
assert.ok(t.eligibleSeats().includes(first));
});
-test('一時停止中は持ち時間が進まず、アクションもできない', () => {
+test('一時停止中はアクションも勝者の決定も次のハンドもできない', () => {
const t = makeTable([1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
t.togglePause(T(0), 1000);
- assert.equal(t.act(t.seats[h.toAct].token, 'fold', 0, 1500), '一時停止中です');
- t.tick(10 ** 6);
- assert.ok(!h.finished);
- t.togglePause(T(0), 10 ** 6);
- t.tick(10 ** 6 + config.ACTION_TIME_MS - 2000);
- assert.ok(!h.finished);
- t.tick(10 ** 6 + config.ACTION_TIME_MS);
- assert.ok(h.finished);
+ assert.equal(t.act(tk(t, h.toAct), 'fold', 0), '一時停止中です');
+ t.togglePause(T(0), 2000);
+ checkDown(t);
+ t.togglePause(T(0), 3000);
+ assert.equal(t.award(T(0), [[h.order[0]]]), '一時停止中です');
+ t.togglePause(T(0), 4000);
+ assert.equal(t.award(T(0), [[h.order[0]]]), null);
+ t.togglePause(T(0), 5000);
+ t.tick(10 ** 7);
+ t.tick(10 ** 8);
+ assert.equal(t.hand.number, 1); // 止まっている
+ t.togglePause(T(0), 10 ** 8);
+ t.tick(10 ** 8 + 10 ** 5);
+ t.tick(10 ** 8 + 10 ** 6);
+ assert.equal(t.hand.number, 2);
});
test('ハンド中の退席: フォールド扱いで席はハンド終了まで予約', () => {
@@ -213,30 +237,25 @@ test('ハンド中の退席: フォールド扱いで席はハンド終了まで
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
- const leaver = t.seats[sb].token;
- t.act(t.seats[btn].token, 'call', 0, 1);
- assert.ok(t.leave(leaver, 1)); // 手番の SB が退席
+ t.act(tk(t, btn), 'call', 0);
+ assert.ok(t.leave(tk(t, sb))); // 手番の SB が退席
assert.ok(h.players.get(sb).folded);
assert.ok(t.seats[sb].left);
assert.equal(t.playerCount, 2);
// 新しく来た人は予約席には座らない
- const seat = t.join(T(9), 'new');
- assert.notEqual(seat, sb);
- assert.equal(t.act(t.seats[bb].token, 'check', 0, 1), null);
+ assert.notEqual(t.join(T(9), 'new'), sb);
+ assert.equal(t.act(tk(t, bb), 'check', 0), null);
assert.equal(h.street, 'FLOP');
- // ホストが抜けたら次の人へ
- if (leaver === T(0)) assert.notEqual(t.hostToken, T(0));
});
-test('2人のうち片方が退席したら残った人が勝つ', () => {
+test('2人のうち片方が退席したら残った人が勝つ(BB は返らない)', () => {
const t = makeTable([1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const stay = h.toAct; // SB(ボタン)
const other = h.order.find((s) => s !== stay);
- t.leave(t.seats[other].token, 1);
+ t.leave(tk(t, other));
assert.ok(h.finished);
- // BB の 20 は返らずそのまま勝者へ
assert.equal(t.seats[stay].stack, 1020);
});
@@ -245,19 +264,19 @@ test('他人の手番では操作できない・不正な額は拒否', () => {
t.start(T(0), 0);
const h = t.hand;
const notTurn = h.order.find((s) => s !== h.toAct);
- assert.equal(t.act(t.seats[notTurn].token, 'fold', 0, 1), 'あなたの番ではありません');
- const tk = t.seats[h.toAct].token;
- assert.ok(t.act(tk, 'raise', 10 ** 9, 1));
- assert.ok(t.act(tk, 'raise', 40.5, 1));
- assert.ok(t.act(tk, 'check', 0, 1)); // BB に対してチェックはできない
- assert.ok(t.act(T(8), 'fold', 0, 1)); // 着席していない
+ assert.equal(t.act(tk(t, notTurn), 'fold', 0), 'あなたの番ではありません');
+ const me = tk(t, h.toAct);
+ assert.ok(t.act(me, 'raise', 10 ** 9));
+ assert.ok(t.act(me, 'raise', 40.5));
+ assert.ok(t.act(me, 'check', 0)); // BB に対してチェックはできない
+ assert.ok(t.act(T(8), 'fold', 0)); // 着席していない
});
test('リバイ', () => {
const t = makeTable([1000, 1000]);
t.seats[1].stack = 0;
- assert.equal(t.rebuy(t.seats[0].token), 'チップが残っています');
- assert.equal(t.rebuy(t.seats[1].token), null);
+ assert.equal(t.rebuy(tk(t, 0)), 'チップが残っています');
+ assert.equal(t.rebuy(tk(t, 1)), null);
assert.equal(t.seats[1].stack, 1000);
assert.equal(t.seats[1].buyIns, 2);
});
@@ -268,7 +287,9 @@ test('ランダムに遊んでもチップの合計が変わらず、必ず終
rnd = (rnd * 1103515245 + 12345) % 2147483648;
return rnd % n;
};
- for (let game = 0; game < 30; game++) {
+ let showdowns = 0;
+ let sidePots = 0;
+ for (let game = 0; game < 60; game++) {
const n = 2 + (game % 8);
const stacks = Array.from({ length: n }, () => 20 + rand(2000));
const t = makeTable(stacks);
@@ -276,28 +297,33 @@ test('ランダムに遊んでもチップの合計が変わらず、必ず終
t.start(T(0), 0);
let now = 0;
for (let step = 0; step < 20000 && t.hand; step++) {
- now += 100;
const h = t.hand;
- if (h && !h.finished && h.toAct != null) {
+ if (!h.finished && h.toAct != null) {
const o = h.options(h.toAct);
const r = rand(10);
- const tk = t.seats[h.toAct].token;
+ const me = tk(t, h.toAct);
let err;
- if (r < 2) err = t.act(tk, 'fold', 0, now);
- else if (r < 6) err = t.act(tk, o.canCheck ? 'check' : 'call', 0, now);
- else if (o.canRaise) {
- const amt = o.minRaiseTo + rand(o.maxRaiseTo - o.minRaiseTo + 1);
- err = t.act(tk, 'raise', amt, now);
- } else err = t.act(tk, o.canCheck ? 'check' : 'call', 0, now);
+ if (r < 2) err = t.act(me, 'fold', 0);
+ else if (r < 6 || !o.canRaise) err = t.act(me, o.canCheck ? 'check' : 'call', 0);
+ else err = t.act(me, 'raise', o.minRaiseTo + rand(o.maxRaiseTo - o.minRaiseTo + 1));
assert.equal(err, null);
+ } else if (h.awaitingWinners) {
+ const pots = h.view().pots;
+ showdowns++;
+ if (pots.length > 1) sidePots++;
+ const winners = pots.map((p) => {
+ const w = p.eligible.filter(() => rand(3) === 0);
+ return w.length ? w : [p.eligible[rand(p.eligible.length)]];
+ });
+ assert.equal(t.award(T(0), winners), null);
} else {
- t.tick(now + 10 ** 5);
- now += 10 ** 5;
+ t.tick((now += 10 ** 5));
}
for (const s of t.seats) if (s) assert.ok(s.stack >= 0);
- const inPot = t.hand && !t.hand.finished ? t.hand.view(-1).potTotal : 0;
+ const inPot = t.hand && !t.hand.finished ? t.hand.view().potTotal : 0;
assert.equal(t.seats.reduce((a, s) => a + (s ? s.stack : 0), 0) + inPot, sum);
if (t.hand && t.hand.number > 40) break;
}
}
+ assert.ok(showdowns > 100 && sidePots > 20, `showdowns=${showdowns} sidePots=${sidePots}`);
});