diff --git a/README.md b/README.md
index fd029cf..d8bd0e9 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,19 @@
友達専用のテキサスホールデム(リングゲーム)サイト。Node.js + Express + Socket.IO。
-現状は「鍵入力 → ロビー → テーブル作成 → プレイ画面(スタブ)」まで。カード配布・ベッティングなどのゲーム処理は未実装で、プレイ画面ではホストが「次へ(仮)」でフェーズを手動で進められる。
+「鍵入力 → ロビー → テーブル作成 → プレイ」まで動く。
+
+## ルール・仕様
+
+- ノーリミット・テキサスホールデムのリングゲーム(最大9人)。ホストが START を押すと、以降は2人以上いる限り自動でハンドが続く。
+- ブラインドはハンド開始時のレベルで固定。ヘッズアップはボタンが SB。
+- 最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。
+- サイドポット・山分け(端数はボタンの左から)・誰もコールしなかった分の返金に対応。
+- 全員オールインになったら手札を公開して残りのカードを順にめくる。ショーダウンでは残った全員の手札を公開。
+- 持ち時間は1手30秒(`server/config.js` の `ACTION_TIME_MS`)。過ぎるとチェック(できなければフォールド)して「離席中」になり、「復帰する」を押すまで配られない。
+- チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。
+- ハンド中に退席するとフォールド扱い(出したチップはポットに残る)。
+- ホストの一時停止中は、持ち時間・ブラインドタイマー・次のハンドの開始がすべて止まる。
## ローカルで動かす
@@ -35,6 +47,7 @@ http://localhost:4671 を開く。
- **XSS**: 厳格な CSP(インラインスクリプト・インラインスタイル禁止)、表示時のエスケープ、名前から制御文字・不可視文字を除去。
- **その他**: クリックジャッキング防止(`frame-ancestors 'none'`)、`nosniff`、`no-referrer`、HTML/API は `no-store`、検索エンジン除外、エラー時に内部情報を返さない、リクエストサイズ・イベント連打・テーブル数の上限。
- 他人の席を操作できないよう、席の持ち主を示すプレイヤーIDはブラウザ内だけに保存し、他のプレイヤーには送らない。
+- **カード**: 山札は暗号論的乱数(`crypto.randomInt`)でシャッフルしてサーバ内だけに保持。各プレイヤーには自分の手札だけを送り、他人の手札は公開時(オールイン・ショーダウン)まで送らない。アクションはサーバ側で手番・額をすべて検証する。
6桁のキーはそれ自体が強い秘密ではないので、上記の回数制限が守りの要になっている。キーは友達にだけ直接伝えること。
@@ -44,14 +57,17 @@ http://localhost:4671 を開く。
| --- | --- |
| `server/index.js` | HTTP ルーティング・セキュリティヘッダ・REST API・Socket.IO |
| `server/auth.js` | 参加キー認証(Cookie)・回数制限・Origin チェック |
-| `server/tables.js` | テーブル状態(席・ボタン・ブラインド・フェーズ・タイマー) |
+| `server/tables.js` | テーブル状態(席・ボタン・ブラインド・タイマー・ハンドの開始/進行) |
+| `server/hand.js` | 1ハンドの進行(配札・ベッティング・サイドポット・ショーダウン) |
+| `server/cards.js` | 山札と役判定 |
+| `test/` | ゲーム処理のテスト(`npm test`) |
| `server/config.js` | `.env` の読み込みと各種上限値 |
| `public/assets/blinds.js` | ブラインド計算(サーバ・ブラウザ共用) |
| `public/*.html`, `public/assets/*.js` | 各画面 |
- テーブルはメモリ上にのみ保持(サーバ再起動で消える)。誰も接続していない状態が30分続くと自動削除。
- 名前とプレイヤーID はブラウザの localStorage に保存。リロードしても同じ席に戻れる。
-- 作成者がホスト(👑)。ホストが退席すると次の着席者に移る。
+- 作成者がホスト(START・一時停止ができる)。ホストが退席すると次の着席者に移る。
## VPS へのデプロイ例(Ubuntu + nginx + systemd + HTTPS)
@@ -138,3 +154,14 @@ sudo systemctl daemon-reload && sudo systemctl enable --now holdem
# ファイアウォール: 4671 は開けない(nginx だけが 127.0.0.1 経由で使う)
sudo ufw allow OpenSSH && sudo ufw allow 'Nginx Full' && sudo ufw enable
```
+
+## 更新(デプロイ済みのサーバに反映)
+
+テーブルはメモリ上にしかないので、再起動すると進行中のテーブルは消える。誰も遊んでいないときに行う。
+
+```bash
+cd /opt/holdem
+sudo git pull
+sudo npm ci --omit=dev
+sudo systemctl restart holdem
+```
diff --git a/package.json b/package.json
index 1a6ecc4..ceafadf 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,8 @@
"main": "server/index.js",
"scripts": {
"start": "node server/index.js",
- "dev": "node --watch server/index.js"
+ "dev": "node --watch server/index.js",
+ "test": "node --test"
},
"engines": {
"node": ">=18"
diff --git a/public/assets/common.js b/public/assets/common.js
index 03b498c..d36abae 100644
--- a/public/assets/common.js
+++ b/public/assets/common.js
@@ -92,7 +92,7 @@
FLOP: 'FLOP',
TURN: 'TURN',
RIVER: 'RIVER',
- SHOWDOWN: 'SHOWDOWN',
+ FINISHING: 'FINISHING',
};
window.App = { Store, esc, chips, toast, api, connectSocket, safeNext, PHASE_LABELS };
diff --git a/public/assets/style.css b/public/assets/style.css
index 138fbbb..e440eb9 100644
--- a/public/assets/style.css
+++ b/public/assets/style.css
@@ -320,7 +320,7 @@ input.invalid { border-color: var(--red); }
position: relative;
flex: 1;
min-height: 400px;
- margin: 8px 0;
+ margin: 30px 0 26px;
}
.felt {
position: absolute;
@@ -356,7 +356,7 @@ input.invalid { border-color: var(--red); }
padding: 5px 14px;
border-radius: 999px;
}
-.hand-no { font-size: 11px; color: rgba(0, 0, 0, 0.45); font-weight: 700; margin-top: 2px; }
+.phase .hand-no { margin-left: 8px; font-size: 11px; opacity: 0.6; letter-spacing: 0; }
.seat {
position: absolute;
@@ -386,8 +386,8 @@ input.invalid { border-color: var(--red); }
background: rgba(10, 30, 20, 0.88);
border-radius: 10px;
padding: 4px 8px;
- min-width: 84px;
- max-width: 92px;
+ min-width: 80px;
+ max-width: 88px;
text-align: center;
position: relative;
}
@@ -411,11 +411,12 @@ input.invalid { border-color: var(--red); }
justify-content: center;
border: 2px solid #222;
}
-.chip-marker.dealer { background: #fff; color: #111; top: -4px; right: -8px; }
+.chip-marker.dealer { background: #fff; color: #111; top: 22px; right: -16px; z-index: 2; }
.blind-marker {
position: absolute;
- top: -4px;
- left: -10px;
+ top: 26px;
+ left: -20px;
+ z-index: 2;
font-size: 10px;
font-weight: 900;
padding: 2px 5px;
@@ -424,34 +425,43 @@ input.invalid { border-color: var(--red); }
}
.blind-marker.sb { background: #7fd3ff; }
.blind-marker.bb { background: var(--gold); }
-.host-mark { position: absolute; bottom: -2px; right: -6px; font-size: 14px; }
.offline-tag { font-size: 10px; color: var(--muted); }
.spectator-note {
- text-align: center;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
font-size: 13px;
color: var(--muted);
- margin-bottom: 8px;
+ margin-bottom: 12px;
}
.action-bar {
+ position: sticky;
+ bottom: 0;
+ z-index: 5;
background: #161c19;
padding: 12px 16px calc(14px + env(safe-area-inset-bottom));
}
.action-bar .inner { max-width: 480px; margin: 0 auto; }
.my-stack {
- text-align: center;
- font-size: 28px;
+ font-size: 24px;
font-weight: 900;
- margin-bottom: 10px;
display: flex;
align-items: center;
- justify-content: center;
- gap: 10px;
+ gap: 8px;
+ line-height: 1.1;
}
-.my-stack .wallet { color: var(--gold); font-size: 22px; }
+.my-stack .wallet { color: var(--gold); font-size: 18px; }
.actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
-.actions .btn { background: #555; color: #bbb; font-size: 18px; }
+.actions.raising { grid-template-columns: 1fr 2fr; }
+.actions.single { grid-template-columns: 1fr; }
+.actions .btn { font-size: 16px; padding: 14px 4px; white-space: normal; line-height: 1.15; min-height: 52px; }
+.act-fold, .act-call, .act-raise { background: #555; color: #bbb; }
+.act-fold:not(:disabled) { background: #5d646b; color: #fff; }
+.act-call:not(:disabled) { background: var(--blue); color: #fff; }
+.act-raise:not(:disabled) { background: var(--orange); color: #fff; }
.modal-backdrop {
position: fixed;
@@ -469,7 +479,7 @@ input.invalid { border-color: var(--red); }
.toast {
position: fixed;
left: 50%;
- bottom: 160px;
+ bottom: 210px;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.85);
color: #fff;
@@ -499,6 +509,179 @@ input.invalid { border-color: var(--red); }
z-index: 30;
}
+/* ---------- カード ---------- */
+.card {
+ display: inline-flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ flex: none;
+ width: 28px;
+ height: 40px;
+ background: #fff;
+ border-radius: 5px;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
+ font-weight: 900;
+ line-height: 1;
+ user-select: none;
+ transition: filter 0.2s;
+}
+.card b { font-size: 15px; letter-spacing: -0.05em; }
+.card i { font-style: normal; font-size: 13px; margin-top: 1px; }
+.suit-s { color: #1a1a1a; }
+.suit-h { color: #d62839; }
+.suit-d { color: #1f6fd1; }
+.suit-c { color: #16884a; }
+.card.back {
+ background: repeating-linear-gradient(45deg, #c0392b 0 3px, #a93226 3px 6px);
+ border: 2px solid #fff;
+}
+.card.slot { background: rgba(0, 0, 0, 0.12); box-shadow: none; border: 1px dashed rgba(255, 255, 255, 0.3); }
+.card.deal { animation: deal 0.35s ease-out both; }
+@keyframes deal {
+ from { opacity: 0; transform: translateY(-10px) scale(0.8); }
+}
+.card.dim { filter: brightness(0.5); }
+.card.hl { box-shadow: 0 0 0 2px var(--gold), 0 0 10px rgba(246, 199, 68, 0.8); }
+
+.board { display: flex; gap: 3px; margin-top: 8px; min-height: 40px; }
+
+.hole {
+ position: absolute;
+ top: -18px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ gap: 2px;
+ z-index: 1;
+}
+.hole .card { width: 25px; height: 35px; border-radius: 4px; }
+.hole .card b { font-size: 13px; }
+.hole .card i { font-size: 11px; }
+.hole .card.back { border-width: 1.5px; }
+
+/* ---------- 席の状態 ---------- */
+.seat.folded .avatar, .seat.folded .nameplate { opacity: 0.45; }
+.seat.away .avatar { opacity: 0.4; }
+.seat.turn .avatar {
+ border-color: var(--gold);
+ box-shadow: 0 0 0 3px rgba(246, 199, 68, 0.35), 0 0 18px rgba(246, 199, 68, 0.7);
+}
+.seat.winner .nameplate { box-shadow: 0 0 0 2px var(--gold), 0 0 12px rgba(246, 199, 68, 0.6); }
+.nameplate .phand {
+ font-size: 10px;
+ font-weight: 700;
+ color: var(--gold);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.seat-timer { height: 3px; background: rgba(255, 255, 255, 0.15); border-radius: 2px; margin-top: 3px; overflow: hidden; }
+.seat-timer i, .turn-progress i { display: block; height: 100%; width: 100%; background: var(--green); transition: width 0.2s linear; }
+.seat-timer i.low, .turn-progress i.low { background: var(--red); }
+
+.act-tag {
+ position: absolute;
+ top: -10px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 10px;
+ font-weight: 900;
+ padding: 1px 7px;
+ border-radius: 6px;
+ color: #fff;
+ white-space: nowrap;
+ z-index: 2;
+}
+.tag-fold { background: #555; color: #ccc; }
+.tag-check { background: #3b7dd8; }
+.tag-call { background: #2e9e5b; }
+.tag-bet, .tag-raise { background: #e67e22; }
+.tag-allin { background: var(--red); }
+.tag-away { background: #444; color: #bbb; }
+
+.bet {
+ position: absolute;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ background: rgba(0, 0, 0, 0.55);
+ color: var(--gold);
+ font-weight: 800;
+ font-size: 12px;
+ padding: 2px 8px 2px 4px;
+ border-radius: 999px;
+ white-space: nowrap;
+ z-index: 3;
+}
+.bet::before {
+ content: "";
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ background: var(--gold);
+ border: 2px dashed #fff;
+ box-sizing: border-box;
+}
+.bet.above { bottom: calc(100% + 20px); }
+.bet.below { top: calc(100% + 4px); }
+.bet.win { background: var(--gold); color: #111; padding: 2px 8px; }
+.bet.win::before { display: none; }
+
+.phase.paused { background: var(--red); }
+.result {
+ margin-top: 6px;
+ background: rgba(0, 0, 0, 0.4);
+ border-radius: 8px;
+ padding: 4px 8px;
+ font-size: 11px;
+ line-height: 1.45;
+ text-align: center;
+ max-width: 94%;
+}
+.result b { color: var(--gold); }
+.result .rhand { color: #fff; opacity: 0.85; }
+.pot-tag { font-size: 9px; background: rgba(255, 255, 255, 0.2); padding: 0 4px; border-radius: 4px; margin-right: 4px; }
+
+/* 7人以上 */
+.felt-area.crowded { min-height: 470px; }
+.crowded .seat { width: 80px; }
+.crowded .avatar { width: 46px; height: 46px; }
+.crowded .avatar svg { width: 22px; height: 22px; }
+.crowded .nameplate { min-width: 72px; max-width: 80px; padding: 3px 6px; }
+.crowded .nameplate .pname { font-size: 11px; }
+.crowded .nameplate .pstack { font-size: 12px; }
+.crowded .hole { top: -12px; }
+.crowded .hole .card { width: 20px; height: 28px; }
+.crowded .hole .card b { font-size: 11px; }
+.crowded .hole .card i { font-size: 9px; }
+.crowded .chip-marker.dealer { top: 14px; }
+.crowded .blind-marker { top: 18px; }
+
+/* ---------- 自分の操作エリア ---------- */
+.turn-progress { position: absolute; top: 0; left: 0; right: 0; height: 4px; background: rgba(255, 255, 255, 0.08); }
+.me-row { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; }
+.my-cards { display: flex; gap: 4px; flex: none; }
+.my-cards .card { width: 42px; height: 58px; border-radius: 6px; }
+.my-cards .card b { font-size: 22px; }
+.my-cards .card i { font-size: 19px; }
+.me-info { flex: 1; min-width: 0; }
+.me-sub { font-size: 12px; color: var(--muted); display: flex; gap: 8px; margin-top: 3px; white-space: nowrap; }
+.me-sub .my-hand { color: var(--gold); font-weight: 800; }
+.me-sub .plus { color: var(--green); }
+.me-sub .minus { color: var(--red); }
+.status-line { text-align: center; font-size: 12px; color: var(--muted); margin-bottom: 8px; min-height: 16px; }
+.status-line.my-turn { color: var(--gold); font-weight: 800; }
+.raise-panel { margin-bottom: 8px; }
+.presets { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; }
+.presets .btn { padding: 8px 0; font-size: 13px; }
+.presets .btn.active { background: var(--orange); color: #111; }
+.raise-row { display: flex; gap: 10px; align-items: center; margin-top: 8px; }
+.raise-row input[type="range"] { flex: 1; min-width: 0; accent-color: var(--orange); height: 28px; }
+.raise-row input[type="number"] { width: 100px; flex: none; font-size: 16px; padding: 8px 10px; }
+
[hidden] { display: none !important; }
/* ---------- ユーティリティ(CSP で style 属性を使わないため) ---------- */
diff --git a/public/assets/table.js b/public/assets/table.js
index d967930..9610311 100644
--- a/public/assets/table.js
+++ b/public/assets/table.js
@@ -1,4 +1,4 @@
-// プレイ画面(スタブ): サーバから受け取ったテーブル状態を表示するだけ
+// プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る
(function () {
'use strict';
@@ -8,10 +8,19 @@
const AVATAR_SVG =
'';
+ // U+FE0E: iOS で絵文字として描画されないように
+ const SUIT_SYMBOL = { s: '♠︎', h: '♥︎', d: '♦︎', c: '♣︎' };
+ const ACTION_LABEL = { FOLD: 'Fold', CHECK: 'Check', CALL: 'Call', BET: 'Bet', RAISE: 'Raise', ALLIN: 'All-in' };
let socket = null;
let state = null;
let clockOffset = 0; // serverNow - clientNow
+ let pending = false; // アクション送信中(連打防止)
+ let raising = false;
+ let raiseValue = 0;
+ let seenBoard = ''; // 新しくめくられたカードだけアニメーションする
+ let seenHand = 0;
+ let wasMyTurn = false;
// ---------- 名前 ----------
function ensureName() {
@@ -33,28 +42,49 @@
socket = App.connectSocket();
socket.on('connect', () => {
$('conn-lost').hidden = true;
- socket.emit('table:join', { tableId, token: Store.token, name: Store.name }, (res) => {
- if (res && res.ok) return;
- if (res && res.error === 'NOT_FOUND') return showNotFound();
- toast('参加できませんでした: ' + ((res && res.error) || '不明なエラー'));
- });
+ join();
});
socket.on('disconnect', () => { $('conn-lost').hidden = false; });
socket.on('connect_error', () => { $('conn-lost').hidden = false; });
socket.on('table:state', (s) => {
state = s;
+ pending = false;
clockOffset = s.serverNow - Date.now();
render();
});
}
- function emit(event) {
- if (!socket) return;
- socket.emit(event, null, (res) => {
- if (res && !res.ok) toast(res.error === 'NOT_FOUND' ? 'テーブルが見つかりません' : res.error);
+ function join(manual) {
+ socket.emit('table:join', { tableId, token: Store.token, name: Store.name }, (res) => {
+ if (res && res.ok) {
+ if (res.seat < 0 && manual) toast('空いている席がありません');
+ return;
+ }
+ if (res && res.error === 'NOT_FOUND') return showNotFound();
+ toast('参加できませんでした: ' + ((res && res.error) || '不明なエラー'));
});
}
+ function emit(event, payload, onDone) {
+ if (!socket) return;
+ socket.emit(event, payload || null, (res) => {
+ if (res && !res.ok) {
+ pending = false;
+ toast(res.error === 'NOT_FOUND' ? 'テーブルが見つかりません' : res.error);
+ if (state) render();
+ }
+ if (onDone) onDone(res);
+ });
+ }
+
+ function sendAction(type, amount) {
+ if (pending) return;
+ pending = true;
+ raising = false;
+ emit('table:action', { type, amount });
+ render();
+ }
+
function showNotFound() {
$('main').hidden = true;
$('action-bar').hidden = true;
@@ -62,11 +92,27 @@
if (socket) socket.disconnect();
}
+ // ---------- カード ----------
+ function cardHtml(c, extra = '') {
+ if (typeof c !== 'string' || !/^[2-9TJQKA][shdc]$/.test(c)) return ``;
+ const rank = c[0] === 'T' ? '10' : c[0];
+ return ``;
+ }
+
+ // ショーダウンで勝った5枚
+ function winningCards(h) {
+ return h && h.finished && h.showdown && h.results && h.results[0] ? new Set(h.results[0].bestCards) : null;
+ }
+
// ---------- 描画 ----------
function render() {
const s = state;
+ const h = s.hand;
+ const me = s.mySeat >= 0 ? s.seats[s.mySeat] : null;
+ const myTurn = Boolean(s.me && s.me.options);
+
$('main').hidden = false;
- document.title = `${s.name} - Hold'em Night`;
+ document.title = `${myTurn ? '▶ ' : ''}${s.name} - Hold'em Night`;
$('table-name').textContent = s.name;
$('level').textContent = `Lv.${s.level}`;
@@ -76,95 +122,382 @@
: 'ブラインドタイマーなし';
$('stack-info').textContent = `開始スタック ${chips(s.startingStack)}`;
- $('pot').textContent = chips(s.pot);
- $('phase').textContent = App.PHASE_LABELS[s.phase] || s.phase;
- $('hand-no').textContent = s.handNumber ? `Hand #${s.handNumber}` : '';
+ // 中央
+ $('pot').textContent = chips(h ? h.potTotal : 0);
+ $('phase').textContent = s.paused ? 'PAUSED' : App.PHASE_LABELS[s.phase] || s.phase;
+ $('phase').parentElement.classList.toggle('paused', s.paused);
+ $('hand-no').textContent = s.handNumber ? `#${s.handNumber}` : '';
+ renderBoard(h);
+ renderResult(s);
// ホスト操作
- const players = s.seats.filter(Boolean).length;
$('host-controls').hidden = !s.isHost;
$('host-spacer').hidden = s.isHost;
- $('start').disabled = s.phase !== 'WAITING' || players < 2;
- $('start').title = players < 2 ? '2人以上で開始できます' : '';
- $('next-phase').disabled = s.phase === 'WAITING';
- $('pause').disabled = !s.started;
+ const eligible = s.seats.filter((p) => p && !p.sittingOut && p.stack > 0).length;
+ $('start').hidden = s.started;
+ $('start').disabled = eligible < 2;
+ $('start').title = eligible < 2 ? '2人以上で開始できます' : '';
+ $('pause').hidden = !s.started;
$('pause').textContent = s.paused ? '再開' : '一時停止';
// 自分
- const me = s.mySeat >= 0 ? s.seats[s.mySeat] : null;
$('action-bar').hidden = !me;
$('spectator-note').hidden = Boolean(me);
+ const hasFreeSeat = s.seats.some((p) => !p);
+ $('take-seat').hidden = Boolean(me) || !hasFreeSeat;
+ $('spectator-text').textContent = hasFreeSeat ? '観戦中です' : '満席のため観戦中です';
$('leave').title = me ? '退席する' : 'ロビーへ戻る';
- if (me) $('my-stack').textContent = chips(me.stack);
renderSeats(s);
+ if (me) renderActionBar(s, me);
renderTimer();
+
+ // 自分の番になったら知らせる
+ const tapped = !navigator.userActivation || navigator.userActivation.hasBeenActive;
+ if (myTurn && !wasMyTurn && navigator.vibrate && tapped) navigator.vibrate(80);
+ wasMyTurn = myTurn;
+ if (h) {
+ seenBoard = `${h.number}:${h.board.length}`;
+ seenHand = h.number;
+ }
+ }
+
+ function renderBoard(h) {
+ const el = $('board');
+ if (!h) {
+ el.innerHTML = '';
+ return;
+ }
+ const [seenNo, seenLen] = seenBoard.split(':').map(Number);
+ const oldLen = seenNo === h.number ? seenLen : 0;
+ const best = winningCards(h);
+ let html = '';
+ for (let i = 0; i < 5; i++) {
+ const c = h.board[i];
+ if (!c) {
+ html += '';
+ continue;
+ }
+ const cls = [i >= oldLen ? 'deal' : '', best ? (best.has(c) ? 'hl' : 'dim') : ''].join(' ');
+ html += cardHtml(c, cls);
+ }
+ el.innerHTML = html;
+ }
+
+ function renderResult(s) {
+ const el = $('result');
+ const h = s.hand;
+ if (!h || !h.finished || !h.results) {
+ el.hidden = true;
+ return;
+ }
+ const nameOf = (seat) => (s.seats[seat] ? s.seats[seat].name : '退席者');
+ el.innerHTML = h.results
+ .map((r, i) => {
+ const label = h.results.length > 1 ? `${i === 0 ? 'メイン' : 'サイド'}` : '';
+ const who = r.winners.map((w) => esc(nameOf(w))).join('・');
+ const hand = r.handName ? `${esc(r.handName)}` : '';
+ return `
${list
+ .map((c) => cardHtml(c, [deal, best && c ? (best.has(c) ? 'hl' : 'dim') : ''].join(' ')))
+ .join('')}
`;
+ }
+
+ // ベット(中央寄り)・獲得額
+ const below = Math.sin(angles[idx]) <= 0.35;
+ let bet = '';
+ if (h && h.finished && p.won > 0) bet = `
+
-
👛$0
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/server/cards.js b/server/cards.js
new file mode 100644
index 0000000..09c1d35
--- /dev/null
+++ b/server/cards.js
@@ -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 };
diff --git a/server/config.js b/server/config.js
index c3fe7cd..3b5a80b 100644
--- a/server/config.js
+++ b/server/config.js
@@ -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,
diff --git a/server/hand.js b/server/hand.js
new file mode 100644
index 0000000..0f7ffb4
--- /dev/null
+++ b/server/hand.js
@@ -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 };
diff --git a/server/index.js b/server/index.js
index b4f7f06..97cf85d 100644
--- a/server/index.js
+++ b/server/index.js
@@ -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(() => {
diff --git a/server/tables.js b/server/tables.js
index c4c9822..b0845ce 100644
--- a/server/tables.js
+++ b/server/tables.js
@@ -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 };
diff --git a/test/engine.test.js b/test/engine.test.js
new file mode 100644
index 0000000..0475bdb
--- /dev/null
+++ b/test/engine.test.js
@@ -0,0 +1,303 @@
+'use strict';
+
+// node --test で実行(ACCESS_KEY はテスト用のダミー)
+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文字のトークン
+
+function makeTable(stacks, opts = {}) {
+ const table = new Table({
+ id: 'x',
+ name: 'test',
+ startingStack: 1000,
+ smallBlind: 10,
+ bigBlind: 20,
+ blindTimerEnabled: false,
+ blindIntervalMin: 10,
+ hostToken: T(0),
+ ...opts,
+ });
+ stacks.forEach((st, i) => {
+ table.join(T(i), 'p' + i);
+ table.seats[i].stack = st;
+ });
+ 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());
+}
+
+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);
+ const h = t.hand;
+ assert.equal(h.sbSeat, h.button);
+ assert.equal(h.toAct, h.sbSeat);
+ const sb = h.sbSeat;
+ 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.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のオプションとチェックでストリートが進む', () => {
+ const t = makeTable([1000, 1000, 1000]);
+ t.start(T(0), 0);
+ 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(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(h.street, 'FLOP');
+ assert.equal(h.board.length, 3);
+ assert.equal(h.pot, 60);
+ assert.equal(h.toAct, sb); // ポストフロップは SB から
+});
+
+test('ミニマムレイズと、足りないオールインは再レイズ権を与えない', () => {
+ const t = makeTable([1000, 1000, 1000]);
+ 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.equal(h.options(sb).minRaiseTo, 100);
+ assert.equal(t.act(tk(sb), 'call', 0, 1), null);
+ // BB は 75 しか持っていないとする → 75 オールインは 100 未満なので不完全なレイズ
+ t.seats[bb].stack = 75 - 20;
+ assert.equal(t.act(tk(bb), 'raise', 75, 1), 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(h.street, 'FLOP');
+});
+
+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.ok(h.revealed);
+ // 残りのカードを順にめくる
+ for (let now = 2; !h.finished && now < 100; now++) t.tick(now * config.RUNOUT_STEP_MS);
+ 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('引き分けは山分け、端数はボタンの左から', () => {
+ 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);
+});
+
+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.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.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.ok(t.eligibleSeats().includes(first));
+});
+
+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);
+});
+
+test('ハンド中の退席: フォールド扱いで席はハンド終了まで予約', () => {
+ const t = makeTable([1000, 1000, 1000]);
+ 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 が退席
+ 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.equal(h.street, 'FLOP');
+ // ホストが抜けたら次の人へ
+ if (leaver === T(0)) assert.notEqual(t.hostToken, T(0));
+});
+
+test('2人のうち片方が退席したら残った人が勝つ', () => {
+ 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);
+ assert.ok(h.finished);
+ // BB の 20 は返らずそのまま勝者へ
+ assert.equal(t.seats[stay].stack, 1020);
+});
+
+test('他人の手番では操作できない・不正な額は拒否', () => {
+ const t = makeTable([1000, 1000, 1000]);
+ 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)); // 着席していない
+});
+
+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.seats[1].stack, 1000);
+ assert.equal(t.seats[1].buyIns, 2);
+});
+
+test('ランダムに遊んでもチップの合計が変わらず、必ず終わる', () => {
+ let rnd = 12345;
+ const rand = (n) => {
+ rnd = (rnd * 1103515245 + 12345) % 2147483648;
+ return rnd % n;
+ };
+ for (let game = 0; game < 30; game++) {
+ const n = 2 + (game % 8);
+ const stacks = Array.from({ length: n }, () => 20 + rand(2000));
+ const t = makeTable(stacks);
+ const sum = stacks.reduce((a, b) => a + b, 0);
+ 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) {
+ const o = h.options(h.toAct);
+ const r = rand(10);
+ const tk = t.seats[h.toAct].token;
+ 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);
+ assert.equal(err, null);
+ } else {
+ t.tick(now + 10 ** 5);
+ 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;
+ assert.equal(t.seats.reduce((a, s) => a + (s ? s.stack : 0), 0) + inPot, sum);
+ if (t.hand && t.hand.number > 40) break;
+ }
+ }
+});