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

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

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

No files matched your search

+30 -3
View File
@@ -2,7 +2,19 @@
友達専用のテキサスホールデム(リングゲーム)サイト。Node.js + Express + Socket.IO。 友達専用のテキサスホールデム(リングゲーム)サイト。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(インラインスクリプト・インラインスタイル禁止)、表示時のエスケープ、名前から制御文字・不可視文字を除去。 - **XSS**: 厳格な CSP(インラインスクリプト・インラインスタイル禁止)、表示時のエスケープ、名前から制御文字・不可視文字を除去。
- **その他**: クリックジャッキング防止(`frame-ancestors 'none'`)、`nosniff`、`no-referrer`、HTML/API は `no-store`、検索エンジン除外、エラー時に内部情報を返さない、リクエストサイズ・イベント連打・テーブル数の上限。 - **その他**: クリックジャッキング防止(`frame-ancestors 'none'`)、`nosniff`、`no-referrer`、HTML/API は `no-store`、検索エンジン除外、エラー時に内部情報を返さない、リクエストサイズ・イベント連打・テーブル数の上限。
- 他人の席を操作できないよう、席の持ち主を示すプレイヤーIDはブラウザ内だけに保存し、他のプレイヤーには送らない。 - 他人の席を操作できないよう、席の持ち主を示すプレイヤーIDはブラウザ内だけに保存し、他のプレイヤーには送らない。
- **カード**: 山札は暗号論的乱数(`crypto.randomInt`)でシャッフルしてサーバ内だけに保持。各プレイヤーには自分の手札だけを送り、他人の手札は公開時(オールイン・ショーダウン)まで送らない。アクションはサーバ側で手番・額をすべて検証する。
6桁のキーはそれ自体が強い秘密ではないので、上記の回数制限が守りの要になっている。キーは友達にだけ直接伝えること。 6桁のキーはそれ自体が強い秘密ではないので、上記の回数制限が守りの要になっている。キーは友達にだけ直接伝えること。
@@ -44,14 +57,17 @@ http://localhost:4671 を開く。
| --- | --- | | --- | --- |
| `server/index.js` | HTTP ルーティング・セキュリティヘッダ・REST API・Socket.IO | | `server/index.js` | HTTP ルーティング・セキュリティヘッダ・REST API・Socket.IO |
| `server/auth.js` | 参加キー認証(Cookie)・回数制限・Origin チェック | | `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` の読み込みと各種上限値 | | `server/config.js` | `.env` の読み込みと各種上限値 |
| `public/assets/blinds.js` | ブラインド計算(サーバ・ブラウザ共用) | | `public/assets/blinds.js` | ブラインド計算(サーバ・ブラウザ共用) |
| `public/*.html`, `public/assets/*.js` | 各画面 | | `public/*.html`, `public/assets/*.js` | 各画面 |
- テーブルはメモリ上にのみ保持(サーバ再起動で消える)。誰も接続していない状態が30分続くと自動削除。 - テーブルはメモリ上にのみ保持(サーバ再起動で消える)。誰も接続していない状態が30分続くと自動削除。
- 名前とプレイヤーID はブラウザの localStorage に保存。リロードしても同じ席に戻れる。 - 名前とプレイヤーID はブラウザの localStorage に保存。リロードしても同じ席に戻れる。
- 作成者がホスト(👑)。ホストが退席すると次の着席者に移る。 - 作成者がホスト(START・一時停止ができる)。ホストが退席すると次の着席者に移る。
## VPS へのデプロイ例(Ubuntu + nginx + systemd + HTTPS) ## VPS へのデプロイ例(Ubuntu + nginx + systemd + HTTPS)
@@ -138,3 +154,14 @@ sudo systemctl daemon-reload && sudo systemctl enable --now holdem
# ファイアウォール: 4671 は開けない(nginx だけが 127.0.0.1 経由で使う) # ファイアウォール: 4671 は開けない(nginx だけが 127.0.0.1 経由で使う)
sudo ufw allow OpenSSH && sudo ufw allow 'Nginx Full' && sudo ufw enable 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
```
+2 -1
View File
@@ -6,7 +6,8 @@
"main": "server/index.js", "main": "server/index.js",
"scripts": { "scripts": {
"start": "node server/index.js", "start": "node server/index.js",
"dev": "node --watch server/index.js" "dev": "node --watch server/index.js",
"test": "node --test"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=18"
+1 -1
View File
@@ -92,7 +92,7 @@
FLOP: 'FLOP', FLOP: 'FLOP',
TURN: 'TURN', TURN: 'TURN',
RIVER: 'RIVER', RIVER: 'RIVER',
SHOWDOWN: 'SHOWDOWN', FINISHING: 'FINISHING',
}; };
window.App = { Store, esc, chips, toast, api, connectSocket, safeNext, PHASE_LABELS }; window.App = { Store, esc, chips, toast, api, connectSocket, safeNext, PHASE_LABELS };
+201 -18
View File
@@ -320,7 +320,7 @@ input.invalid { border-color: var(--red); }
position: relative; position: relative;
flex: 1; flex: 1;
min-height: 400px; min-height: 400px;
margin: 8px 0; margin: 30px 0 26px;
} }
.felt { .felt {
position: absolute; position: absolute;
@@ -356,7 +356,7 @@ input.invalid { border-color: var(--red); }
padding: 5px 14px; padding: 5px 14px;
border-radius: 999px; 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 { .seat {
position: absolute; position: absolute;
@@ -386,8 +386,8 @@ input.invalid { border-color: var(--red); }
background: rgba(10, 30, 20, 0.88); background: rgba(10, 30, 20, 0.88);
border-radius: 10px; border-radius: 10px;
padding: 4px 8px; padding: 4px 8px;
min-width: 84px; min-width: 80px;
max-width: 92px; max-width: 88px;
text-align: center; text-align: center;
position: relative; position: relative;
} }
@@ -411,11 +411,12 @@ input.invalid { border-color: var(--red); }
justify-content: center; justify-content: center;
border: 2px solid #222; 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 { .blind-marker {
position: absolute; position: absolute;
top: -4px; top: 26px;
left: -10px; left: -20px;
z-index: 2;
font-size: 10px; font-size: 10px;
font-weight: 900; font-weight: 900;
padding: 2px 5px; padding: 2px 5px;
@@ -424,34 +425,43 @@ input.invalid { border-color: var(--red); }
} }
.blind-marker.sb { background: #7fd3ff; } .blind-marker.sb { background: #7fd3ff; }
.blind-marker.bb { background: var(--gold); } .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); } .offline-tag { font-size: 10px; color: var(--muted); }
.spectator-note { .spectator-note {
text-align: center; display: flex;
align-items: center;
justify-content: center;
gap: 12px;
font-size: 13px; font-size: 13px;
color: var(--muted); color: var(--muted);
margin-bottom: 8px; margin-bottom: 12px;
} }
.action-bar { .action-bar {
position: sticky;
bottom: 0;
z-index: 5;
background: #161c19; background: #161c19;
padding: 12px 16px calc(14px + env(safe-area-inset-bottom)); padding: 12px 16px calc(14px + env(safe-area-inset-bottom));
} }
.action-bar .inner { max-width: 480px; margin: 0 auto; } .action-bar .inner { max-width: 480px; margin: 0 auto; }
.my-stack { .my-stack {
text-align: center; font-size: 24px;
font-size: 28px;
font-weight: 900; font-weight: 900;
margin-bottom: 10px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; gap: 8px;
gap: 10px; 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 { 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 { .modal-backdrop {
position: fixed; position: fixed;
@@ -469,7 +479,7 @@ input.invalid { border-color: var(--red); }
.toast { .toast {
position: fixed; position: fixed;
left: 50%; left: 50%;
bottom: 160px; bottom: 210px;
transform: translateX(-50%); transform: translateX(-50%);
background: rgba(0, 0, 0, 0.85); background: rgba(0, 0, 0, 0.85);
color: #fff; color: #fff;
@@ -499,6 +509,179 @@ input.invalid { border-color: var(--red); }
z-index: 30; 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; } [hidden] { display: none !important; }
/* ---------- ユーティリティ(CSP で style 属性を使わないため) ---------- */ /* ---------- ユーティリティ(CSP で style 属性を使わないため) ---------- */
+385 -52
View File
@@ -1,4 +1,4 @@
// プレイ画面(スタブ): サーバから受け取ったテーブル状態を表示するだけ // プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る
(function () { (function () {
'use strict'; 'use strict';
@@ -8,10 +8,19 @@
const AVATAR_SVG = const AVATAR_SVG =
'<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="4.5"/><path d="M3 21c0-4.4 4-7.5 9-7.5s9 3.1 9 7.5z"/></svg>'; '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="4.5"/><path d="M3 21c0-4.4 4-7.5 9-7.5s9 3.1 9 7.5z"/></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 socket = null;
let state = null; let state = null;
let clockOffset = 0; // serverNow - clientNow let clockOffset = 0; // serverNow - clientNow
let pending = false; // アクション送信中(連打防止)
let raising = false;
let raiseValue = 0;
let seenBoard = ''; // 新しくめくられたカードだけアニメーションする
let seenHand = 0;
let wasMyTurn = false;
// ---------- 名前 ---------- // ---------- 名前 ----------
function ensureName() { function ensureName() {
@@ -33,28 +42,49 @@
socket = App.connectSocket(); socket = App.connectSocket();
socket.on('connect', () => { socket.on('connect', () => {
$('conn-lost').hidden = true; $('conn-lost').hidden = true;
socket.emit('table:join', { tableId, token: Store.token, name: Store.name }, (res) => { join();
if (res && res.ok) return;
if (res && res.error === 'NOT_FOUND') return showNotFound();
toast('参加できませんでした: ' + ((res && res.error) || '不明なエラー'));
});
}); });
socket.on('disconnect', () => { $('conn-lost').hidden = false; }); socket.on('disconnect', () => { $('conn-lost').hidden = false; });
socket.on('connect_error', () => { $('conn-lost').hidden = false; }); socket.on('connect_error', () => { $('conn-lost').hidden = false; });
socket.on('table:state', (s) => { socket.on('table:state', (s) => {
state = s; state = s;
pending = false;
clockOffset = s.serverNow - Date.now(); clockOffset = s.serverNow - Date.now();
render(); render();
}); });
} }
function emit(event) { function join(manual) {
if (!socket) return; socket.emit('table:join', { tableId, token: Store.token, name: Store.name }, (res) => {
socket.emit(event, null, (res) => { if (res && res.ok) {
if (res && !res.ok) toast(res.error === 'NOT_FOUND' ? 'テーブルが見つかりません' : res.error); 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() { function showNotFound() {
$('main').hidden = true; $('main').hidden = true;
$('action-bar').hidden = true; $('action-bar').hidden = true;
@@ -62,11 +92,27 @@
if (socket) socket.disconnect(); if (socket) socket.disconnect();
} }
// ---------- カード ----------
function cardHtml(c, extra = '') {
if (typeof c !== 'string' || !/^[2-9TJQKA][shdc]$/.test(c)) return `<span class="card back ${extra}"></span>`;
const rank = c[0] === 'T' ? '10' : c[0];
return `<span class="card suit-${c[1]} ${extra}" data-card="${c}"><b>${rank}</b><i>${SUIT_SYMBOL[c[1]]}</i></span>`;
}
// ショーダウンで勝った5枚
function winningCards(h) {
return h && h.finished && h.showdown && h.results && h.results[0] ? new Set(h.results[0].bestCards) : null;
}
// ---------- 描画 ---------- // ---------- 描画 ----------
function render() { function render() {
const s = state; 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; $('main').hidden = false;
document.title = `${s.name} - Hold'em Night`; document.title = `${myTurn ? '▶ ' : ''}${s.name} - Hold'em Night`;
$('table-name').textContent = s.name; $('table-name').textContent = s.name;
$('level').textContent = `Lv.${s.level}`; $('level').textContent = `Lv.${s.level}`;
@@ -76,95 +122,382 @@
: 'ブラインドタイマーなし'; : 'ブラインドタイマーなし';
$('stack-info').textContent = `開始スタック ${chips(s.startingStack)}`; $('stack-info').textContent = `開始スタック ${chips(s.startingStack)}`;
$('pot').textContent = chips(s.pot); // 中央
$('phase').textContent = App.PHASE_LABELS[s.phase] || s.phase; $('pot').textContent = chips(h ? h.potTotal : 0);
$('hand-no').textContent = s.handNumber ? `Hand #${s.handNumber}` : ''; $('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-controls').hidden = !s.isHost;
$('host-spacer').hidden = s.isHost; $('host-spacer').hidden = s.isHost;
$('start').disabled = s.phase !== 'WAITING' || players < 2; const eligible = s.seats.filter((p) => p && !p.sittingOut && p.stack > 0).length;
$('start').title = players < 2 ? '2人以上で開始できます' : ''; $('start').hidden = s.started;
$('next-phase').disabled = s.phase === 'WAITING'; $('start').disabled = eligible < 2;
$('pause').disabled = !s.started; $('start').title = eligible < 2 ? '2人以上で開始できます' : '';
$('pause').hidden = !s.started;
$('pause').textContent = s.paused ? '再開' : '一時停止'; $('pause').textContent = s.paused ? '再開' : '一時停止';
// 自分 // 自分
const me = s.mySeat >= 0 ? s.seats[s.mySeat] : null;
$('action-bar').hidden = !me; $('action-bar').hidden = !me;
$('spectator-note').hidden = Boolean(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 ? '退席する' : 'ロビーへ戻る'; $('leave').title = me ? '退席する' : 'ロビーへ戻る';
if (me) $('my-stack').textContent = chips(me.stack);
renderSeats(s); renderSeats(s);
if (me) renderActionBar(s, me);
renderTimer(); 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 += '<span class="card slot"></span>';
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 ? `<span class="pot-tag">${i === 0 ? 'メイン' : 'サイド'}</span>` : '';
const who = r.winners.map((w) => esc(nameOf(w))).join('・');
const hand = r.handName ? `<span class="rhand">${esc(r.handName)}</span>` : '';
return `<div>${label}<b>${who}</b> +${chips(r.amount)} ${hand}</div>`;
})
.join('');
el.hidden = false;
} }
// 着席者を楕円上に配置。自分が一番下、そこから時計回り。 // 着席者を楕円上に配置。自分が一番下、そこから時計回り。
function renderSeats(s) { function renderSeats(s) {
const h = s.hand;
const occupied = s.seats.filter(Boolean); const occupied = s.seats.filter(Boolean);
const startIdx = Math.max(0, occupied.findIndex((p) => p.seat === s.mySeat)); const startIdx = Math.max(0, occupied.findIndex((p) => p.seat === s.mySeat));
const ordered = occupied.slice(startIdx).concat(occupied.slice(0, startIdx)); const ordered = occupied.slice(startIdx).concat(occupied.slice(0, startIdx));
const n = ordered.length; const n = ordered.length;
const best = winningCards(h);
const angles = ordered.map((_, i) => Math.PI / 2 + (i * 2 * Math.PI) / Math.max(n, 1));
const container = $('seats'); const container = $('seats');
$('felt-area').classList.toggle('crowded', n >= 7); // 7人以上は小さめに表示
container.innerHTML = ordered container.innerHTML = ordered
.map((p) => { .map((p, idx) => {
const classes = ['seat']; const classes = ['seat'];
const isTurn = s.turn && s.turn.seat === p.seat;
if (p.seat === s.mySeat) classes.push('me'); if (p.seat === s.mySeat) classes.push('me');
if (!p.connected) classes.push('offline'); if (!p.connected) classes.push('offline');
const markers = [ if (p.inHand && p.folded) classes.push('folded');
p.seat === s.buttonSeat ? '<span class="chip-marker dealer" title="ディーラーボタン">D</span>' : '', if (isTurn) classes.push('turn');
p.seat === s.sbSeat ? '<span class="blind-marker sb">SB</span>' : '', if (h && h.finished && p.won > 0) classes.push('winner');
p.seat === s.bbSeat ? '<span class="blind-marker bb">BB</span>' : '', if (p.sittingOut && !p.inHand) classes.push('away');
].join('');
const markers = h
? [
p.seat === h.button ? '<span class="chip-marker dealer" title="ディーラーボタン">D</span>' : '',
p.seat === h.sbSeat ? '<span class="blind-marker sb">SB</span>' : '',
p.seat === h.bbSeat ? '<span class="blind-marker bb">BB</span>' : '',
].join('')
: '';
// 手札(自分と公開された人は表、それ以外は裏)
let cards = '';
if (p.inHand && (!p.folded || p.cards)) {
const deal = h.number !== seenHand ? 'deal' : '';
const list = p.cards || [null, null];
cards = `<div class="hole">${list
.map((c) => cardHtml(c, [deal, best && c ? (best.has(c) ? 'hl' : 'dim') : ''].join(' ')))
.join('')}</div>`;
}
// ベット(中央寄り)・獲得額
const below = Math.sin(angles[idx]) <= 0.35;
let bet = '';
if (h && h.finished && p.won > 0) bet = `<div class="bet win ${below ? 'below' : 'above'}">+${chips(p.won)}</div>`;
else if (p.bet > 0) bet = `<div class="bet ${below ? 'below' : 'above'}">${chips(p.bet)}</div>`;
let tag = '';
if (p.last && !(h && h.finished && p.won > 0)) {
tag = `<div class="act-tag tag-${p.last.type.toLowerCase()}">${ACTION_LABEL[p.last.type] || ''}</div>`;
} else if (p.sittingOut && !p.inHand) {
tag = '<div class="act-tag tag-away">離席中</div>';
}
return ` return `
<div class="${classes.join(' ')}"> <div class="${classes.join(' ')}">
<div class="avatar">${AVATAR_SVG}${markers}</div> <div class="avatar">${AVATAR_SVG}${markers}${cards}</div>
<div class="nameplate"> <div class="nameplate">
<div class="pname">${p.seat === s.hostSeat ? '<span title="ホスト">👑</span>' : ''}${esc(p.name)}</div> ${tag}
<div class="pstack">${chips(p.stack)}</div> <div class="pname">${esc(p.name)}</div>
<div class="pstack">${p.allIn && !(h && h.finished) ? 'ALL-IN' : chips(p.stack)}</div>
${p.handName && p.seat !== s.mySeat ? `<div class="phand">${esc(p.handName)}</div>` : ''}
${p.connected ? '' : '<div class="offline-tag">オフライン</div>'} ${p.connected ? '' : '<div class="offline-tag">オフライン</div>'}
${isTurn ? '<div class="seat-timer"><i></i></div>' : ''}
</div> </div>
${bet}
</div>`; </div>`;
}) })
.join(''); .join('');
// 位置は CSSOM で設定(CSP で style 属性を禁止しているため) // 位置は CSSOM で設定(CSP で style 属性を禁止しているため)
[...container.children].forEach((el, i) => { [...container.children].forEach((el, i) => {
const angle = Math.PI / 2 + (i * 2 * Math.PI) / Math.max(n, 1); el.style.left = `${(50 + 38 * Math.cos(angles[i])).toFixed(2)}%`;
el.style.left = `${(50 + 38 * Math.cos(angle)).toFixed(2)}%`; el.style.top = `${(50 + 41 * Math.sin(angles[i])).toFixed(2)}%`;
el.style.top = `${(50 + 41 * Math.sin(angle)).toFixed(2)}%`;
}); });
} }
function renderTimer() { function renderActionBar(s, seat) {
const el = $('timer'); const m = s.me;
if (!state) return; const h = s.hand;
const t = state.timer; const o = m.options;
el.classList.toggle('paused', state.paused);
if (!t.enabled) { $('my-stack').textContent = chips(m.stack);
el.textContent = state.paused ? '⏸ PAUSED' : ''; const net = m.net;
$('my-net').textContent = `収支 ${net > 0 ? '+' : net < 0 ? '−' : '±'}${chips(Math.abs(net))}`;
$('my-net').className = net > 0 ? 'plus' : net < 0 ? 'minus' : '';
$('my-hand').textContent = seat.handName || '';
const myCards = seat.inHand && seat.cards ? seat.cards : null;
const best = winningCards(h);
$('my-cards').innerHTML = myCards
? myCards.map((c) => cardHtml(c, [seat.folded ? 'dim' : '', best && best.has(c) ? 'hl' : ''].join(' '))).join('')
: '<span class="card slot"></span><span class="card slot"></span>';
$('sit-out').hidden = m.sittingOut;
// 状況
let status = '';
if (!s.started) status = s.isHost ? '2人以上揃ったら START を押してください' : 'ホストの開始を待っています';
else if (s.paused) status = '一時停止中';
else if (m.sittingOut) status = '離席中です。復帰すると次のハンドから参加します';
else if (m.canRebuy) status = 'チップがなくなりました';
else if (o) status = o.canCheck ? 'あなたの番です' : `あなたの番です(コール ${chips(o.toCall)})`;
else if (h && !h.finished && s.turn) status = `${(s.seats[s.turn.seat] || {}).name || ''} の番です`;
else if (h && !h.finished && !seat.inHand) status = '次のハンドから参加します';
else if (h && !h.finished && !s.turn) status = 'オールイン — 残りのカードをめくります';
else if (h && h.finished) status = '次のハンドを準備中…';
else if (!h) status = '参加者を待っています(2人以上で再開)';
$('status-line').textContent = status;
$('status-line').classList.toggle('my-turn', Boolean(o));
// ボタン
const alt = m.sittingOut || m.canRebuy;
$('alt-actions').hidden = !alt;
$('sit-in').hidden = !m.sittingOut;
$('rebuy').hidden = !m.canRebuy;
$('rebuy').textContent = `リバイ(${chips(s.startingStack)})`;
if (!o) raising = false;
$('actions').hidden = alt || raising;
$('raise-actions').hidden = alt || !raising;
$('raise-panel').hidden = alt || !raising;
$('status-line').hidden = raising;
const fold = $('act-fold');
const call = $('act-call');
const raise = $('act-raise');
fold.disabled = call.disabled = raise.disabled = !o || pending;
if (!o) {
call.textContent = 'Check';
raise.textContent = 'Raise';
return; return;
} }
const remaining = t.running ? t.endsAt - (Date.now() + clockOffset) : t.remainingMs; call.textContent = o.canCheck ? 'Check' : o.toCall >= m.stack ? `All-in ${chips(o.toCall)}` : `Call ${chips(o.toCall)}`;
const sec = Math.max(0, Math.ceil(remaining / 1000)); raise.disabled = pending || !o.canRaise;
const time = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`; raise.textContent = !o.canRaise
el.textContent = state.paused ? `⏸ ${time}` : time; ? o.isBet ? 'Bet' : 'Raise'
el.classList.toggle('warn', t.running && sec <= 60); : o.minRaiseTo >= o.maxRaiseTo
} ? `All-in ${chips(o.maxRaiseTo)}`
setInterval(renderTimer, 250); : o.isBet ? 'Bet' : 'Raise';
// ---------- 操作 ---------- if (raising) renderRaisePanel(o);
}
// ---------- レイズ ----------
function presetValue(o, kind) {
const h = state.hand;
const potAfterCall = h.potTotal + o.toCall;
const base = h.currentBet;
const v = {
min: o.minRaiseTo,
half: base + Math.round(potAfterCall / 2),
threeq: base + Math.round((potAfterCall * 3) / 4),
pot: base + potAfterCall,
max: o.maxRaiseTo,
}[kind];
return clampRaise(o, v);
}
function clampRaise(o, v) {
if (!Number.isFinite(v)) return o.minRaiseTo;
return Math.min(o.maxRaiseTo, Math.max(o.minRaiseTo, Math.round(v)));
}
function renderRaisePanel(o) {
raiseValue = clampRaise(o, raiseValue);
const range = $('raise-range');
range.min = o.minRaiseTo;
range.max = o.maxRaiseTo;
range.step = 1;
range.value = raiseValue;
const amount = $('raise-amount');
if (document.activeElement !== amount) amount.value = raiseValue;
amount.min = o.minRaiseTo;
amount.max = o.maxRaiseTo;
for (const b of $('presets').children) {
b.classList.toggle('active', presetValue(o, b.dataset.preset) === raiseValue);
}
const allIn = raiseValue >= o.maxRaiseTo;
$('raise-confirm').textContent = allIn
? `All-in ${chips(raiseValue)}`
: `${o.isBet ? 'Bet' : 'Raise to'} ${chips(raiseValue)}`;
$('raise-confirm').disabled = pending;
}
const options = () => (state && state.me && state.me.options) || null;
$('act-fold').addEventListener('click', () => {
const o = options();
if (!o) return;
if (o.canCheck && !confirm('チェックできます。フォールドしますか?')) return;
sendAction('fold');
});
$('act-call').addEventListener('click', () => {
const o = options();
if (o) sendAction(o.canCheck ? 'check' : 'call');
});
$('act-raise').addEventListener('click', () => {
const o = options();
if (!o || !o.canRaise) return;
if (o.minRaiseTo >= o.maxRaiseTo) return sendAction('raise', o.maxRaiseTo); // オールインしかない
raising = true;
raiseValue = o.minRaiseTo;
render();
});
$('raise-cancel').addEventListener('click', () => {
raising = false;
render();
});
$('raise-confirm').addEventListener('click', () => {
const o = options();
if (o) sendAction('raise', clampRaise(o, raiseValue));
});
$('presets').addEventListener('click', (e) => {
const b = e.target.closest('[data-preset]');
const o = options();
if (!b || !o) return;
raiseValue = presetValue(o, b.dataset.preset);
$('raise-amount').value = raiseValue;
renderRaisePanel(o);
});
$('raise-range').addEventListener('input', (e) => {
const o = options();
if (!o) return;
// BB 単位に丸める(最大はオールイン額そのまま)
const unit = Math.max(1, state.smallBlind);
let v = Number(e.target.value);
if (v < o.maxRaiseTo) v = o.minRaiseTo + Math.round((v - o.minRaiseTo) / unit) * unit;
raiseValue = clampRaise(o, v);
$('raise-amount').value = raiseValue;
renderRaisePanel(o);
});
$('raise-amount').addEventListener('input', (e) => {
const o = options();
const v = Number(e.target.value);
if (!o || !Number.isFinite(v) || v <= 0) return;
raiseValue = clampRaise(o, v);
renderRaisePanel(o);
});
$('raise-amount').addEventListener('blur', () => {
const o = options();
if (o) $('raise-amount').value = clampRaise(o, raiseValue);
});
// ---------- タイマー ----------
function renderTimer() {
if (!state) return;
const el = $('timer');
const t = state.timer;
const now = Date.now() + clockOffset;
el.classList.toggle('paused', state.paused);
if (!t.enabled) {
el.textContent = state.paused ? '⏸' : '';
} else {
const remaining = t.running ? t.endsAt - now : t.remainingMs;
const sec = Math.max(0, Math.ceil(remaining / 1000));
const time = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
el.textContent = state.paused ? `⏸ ${time}` : time;
el.classList.toggle('warn', t.running && sec <= 60);
}
// 手番の残り時間
const turn = state.turn;
const ratio = turn ? Math.max(0, Math.min(1, (turn.endsAt != null ? turn.endsAt - now : turn.remainingMs) / turn.totalMs)) : 0;
const width = `${(ratio * 100).toFixed(1)}%`;
const bar = document.querySelector('.seat.turn .seat-timer i');
if (bar) {
bar.style.width = width;
bar.classList.toggle('low', ratio < 0.3);
}
const mine = Boolean(turn && turn.seat === state.mySeat);
$('turn-progress').hidden = !mine;
if (mine) {
$('turn-bar').style.width = width;
$('turn-bar').classList.toggle('low', ratio < 0.3);
}
}
setInterval(renderTimer, 200);
// ---------- その他の操作 ----------
$('start').addEventListener('click', () => emit('table:start')); $('start').addEventListener('click', () => emit('table:start'));
$('next-phase').addEventListener('click', () => emit('table:nextPhase'));
$('pause').addEventListener('click', () => emit('table:pause')); $('pause').addEventListener('click', () => emit('table:pause'));
$('sit-out').addEventListener('click', () => emit('table:sitOut'));
$('take-seat').addEventListener('click', () => join(true));
$('sit-in').addEventListener('click', () => emit('table:sitIn'));
$('rebuy').addEventListener('click', () => emit('table:rebuy'));
$('leave').addEventListener('click', () => { $('leave').addEventListener('click', () => {
const seated = state && state.mySeat >= 0; const me = state && state.mySeat >= 0 ? state.seats[state.mySeat] : null;
if (!seated) return (location.href = '/'); if (!me) return (location.href = '/');
if (!confirm('テーブルから退席しますか?(チップは失われます)')) return; const inHand = state.hand && !state.hand.finished && me.inHand && !me.folded;
const msg = inHand
? 'ハンドの途中です。退席するとフォールドになり、チップは失われます。退席しますか?'
: 'テーブルから退席しますか?(チップは失われます)';
if (!confirm(msg)) return;
socket.emit('table:leave', null, () => { location.href = '/'; }); socket.emit('table:leave', null, () => { location.href = '/'; });
}); });
+45 -9
View File
@@ -20,7 +20,6 @@
<div class="host-controls" id="host-controls" hidden> <div class="host-controls" id="host-controls" hidden>
<button class="btn btn-green" id="start">START ▶</button> <button class="btn btn-green" id="start">START ▶</button>
<button class="btn btn-dark" id="next-phase" title="プレイ未実装のため手動でフェーズを進めます">次へ(仮)</button>
<button class="btn btn-dark" id="pause">一時停止</button> <button class="btn btn-dark" id="pause">一時停止</button>
</div> </div>
<div class="host-spacer" id="host-spacer"></div> <div class="host-spacer" id="host-spacer"></div>
@@ -39,22 +38,59 @@
<div class="felt"> <div class="felt">
<div class="pot-label">POT</div> <div class="pot-label">POT</div>
<div class="pot" id="pot">$0</div> <div class="pot" id="pot">$0</div>
<div class="phase" id="phase">WAITING</div> <div class="board" id="board"></div>
<div class="hand-no" id="hand-no"></div> <div class="phase"><span id="phase">WAITING</span><span class="hand-no" id="hand-no"></span></div>
<div class="result" id="result" hidden></div>
</div> </div>
<div id="seats"></div> <div id="seats"></div>
</div> </div>
<div class="spectator-note" id="spectator-note" hidden>満席のため観戦中です</div> <div class="spectator-note" id="spectator-note" hidden>
<span id="spectator-text">満席のため観戦中です</span>
<button class="btn btn-orange btn-sm" id="take-seat" hidden>空席に座る</button>
</div>
</main> </main>
<div class="action-bar" id="action-bar" hidden> <div class="action-bar" id="action-bar" hidden>
<div class="turn-progress" id="turn-progress" hidden><i id="turn-bar"></i></div>
<div class="inner"> <div class="inner">
<div class="my-stack"><span class="wallet">👛</span><span id="my-stack">$0</span></div> <div class="me-row">
<div class="actions"> <div class="my-cards" id="my-cards"></div>
<button class="btn" disabled>Fold</button> <div class="me-info">
<button class="btn" disabled>Check</button> <div class="my-stack"><span class="wallet">👛</span><span id="my-stack">$0</span></div>
<button class="btn" disabled>Raise</button> <div class="me-sub"><span class="my-hand" id="my-hand"></span><span id="my-net"></span></div>
</div>
<button class="btn btn-ghost btn-sm" id="sit-out" title="次のハンドから参加しません">離席</button>
</div>
<div class="status-line" id="status-line"></div>
<div class="raise-panel" id="raise-panel" hidden>
<div class="presets" id="presets">
<button class="btn btn-dark btn-sm" data-preset="min">Min</button>
<button class="btn btn-dark btn-sm" data-preset="half">½</button>
<button class="btn btn-dark btn-sm" data-preset="threeq">¾</button>
<button class="btn btn-dark btn-sm" data-preset="pot">Pot</button>
<button class="btn btn-dark btn-sm" data-preset="max">All-in</button>
</div>
<div class="raise-row">
<input type="range" id="raise-range" aria-label="レイズ額">
<input type="number" id="raise-amount" inputmode="numeric" aria-label="レイズ額">
</div>
</div>
<div class="actions" id="actions">
<button class="btn act-fold" id="act-fold" disabled>Fold</button>
<button class="btn act-call" id="act-call" disabled>Check</button>
<button class="btn act-raise" id="act-raise" disabled>Raise</button>
</div>
<div class="actions raising" id="raise-actions" hidden>
<button class="btn btn-dark" id="raise-cancel">戻る</button>
<button class="btn act-raise" id="raise-confirm">Raise</button>
</div>
<div class="actions single" id="alt-actions" hidden>
<button class="btn btn-orange" id="sit-in">復帰する</button>
<button class="btn btn-blue" id="rebuy">リバイ</button>
</div> </div>
</div> </div>
</div> </div>
+96
View File
@@ -0,0 +1,96 @@
'use strict';
const crypto = require('crypto');
// カードは "As"(スペードのA), "Td"(ダイヤの10)のような2文字
const RANKS = '23456789TJQKA';
const SUITS = 'shdc';
// 暗号論的乱数で Fisher-Yates シャッフル(山札はサーバの外に出さない)
function newDeck() {
const deck = [];
for (const r of RANKS) for (const s of SUITS) deck.push(r + s);
for (let i = deck.length - 1; i > 0; i--) {
const j = crypto.randomInt(i + 1);
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
}
const rankValue = (card) => RANKS.indexOf(card[0]) + 2;
// 5枚の役の強さ。配列を先頭から比較して大きいほうが強い
// [役の種類(0〜8), 比較用の数字...]
function score5(cards) {
const vals = cards.map(rankValue).sort((a, b) => b - a);
const flush = cards.every((c) => c[1] === cards[0][1]);
let straightHigh = 0;
if (new Set(vals).size === 5) {
if (vals[0] - vals[4] === 4) straightHigh = vals[0];
else if (vals[0] === 14 && vals[1] === 5) straightHigh = 5; // A-2-3-4-5
}
if (straightHigh && flush) return [8, straightHigh];
// 枚数の多い順、同じ枚数なら数字の大きい順
const counts = new Map();
for (const v of vals) counts.set(v, (counts.get(v) || 0) + 1);
const groups = [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0]);
const byGroup = groups.map((g) => g[0]);
if (groups[0][1] === 4) return [7, ...byGroup];
if (groups[0][1] === 3 && groups[1][1] === 2) return [6, ...byGroup];
if (flush) return [5, ...vals];
if (straightHigh) return [4, straightHigh];
if (groups[0][1] === 3) return [3, ...byGroup];
if (groups[0][1] === 2 && groups[1][1] === 2) return [2, ...byGroup];
if (groups[0][1] === 2) return [1, ...byGroup];
return [0, ...vals];
}
function compareScore(a, b) {
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const d = (a[i] || 0) - (b[i] || 0);
if (d) return d;
}
return 0;
}
const HAND_NAMES = [
'ハイカード',
'ワンペア',
'ツーペア',
'スリーカード',
'ストレート',
'フラッシュ',
'フルハウス',
'フォーカード',
'ストレートフラッシュ',
];
function handName(score) {
if (score[0] === 8 && score[1] === 14) return 'ロイヤルフラッシュ';
return HAND_NAMES[score[0]];
}
// 5〜7枚から最も強い5枚を選ぶ
function bestHand(cards) {
let best = null;
const n = cards.length;
const pick = (start, chosen) => {
if (chosen.length === 5) {
const score = score5(chosen);
if (!best || compareScore(score, best.score) > 0) best = { score, cards: chosen.slice() };
return;
}
for (let i = start; i <= n - (5 - chosen.length); i++) {
chosen.push(cards[i]);
pick(i + 1, chosen);
chosen.pop();
}
};
pick(0, []);
return best && { score: best.score, cards: best.cards, name: handName(best.score) };
}
module.exports = { newDeck, score5, compareScore, bestHand, handName };
+10
View File
@@ -53,6 +53,16 @@ module.exports = {
// 誰も接続していないテーブルを削除するまでの時間 // 誰も接続していないテーブルを削除するまでの時間
EMPTY_TABLE_TTL_MS: 30 * 60 * 1000, 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 回まで // IP(IPv6 は /64 単位)ごと: WINDOW 内で MAX_FAILURES 回まで
AUTH_MAX_FAILURES: 5, AUTH_MAX_FAILURES: 5,
+360
View File
@@ -0,0 +1,360 @@
'use strict';
const config = require('./config');
const { newDeck, bestHand, compareScore } = require('./cards');
// 1ハンド分の進行(配札・ベッティング・ショーダウン・ポット分配)
// seats は Table.seats への参照で、スタックはここで直接増減する。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
class Hand {
constructor({ number, seats, order, button, sb, bb, now }) {
this.number = number;
this.seats = seats;
this.order = order; // 参加者の席番号。ボタンの次から時計回り
this.button = button;
this.sb = sb;
this.bb = bb;
this.deck = newDeck();
this.board = [];
this.street = 'PREFLOP';
this.pot = 0; // 前のストリートまでに集めた額
this.currentBet = 0;
this.minRaise = bb;
this.toAct = null;
this.deadline = null;
this.runoutAt = null;
this.revealed = false; // オールインで以降のアクションが無いとき、ショーダウン時に公開
this.finished = false;
this.showdown = false;
this.results = null;
this.players = new Map();
for (const i of order) {
this.players.set(i, {
seat: i,
token: seats[i].token,
cards: [],
bet: 0, // このストリートで出した額
committed: 0, // このハンドで出した合計
folded: false,
allIn: false,
acted: false,
last: null, // 直前のアクション(表示用)
won: 0,
best: null,
});
}
for (let r = 0; r < 2; r++) for (const i of order) this.players.get(i).cards.push(this.deck.pop());
// ヘッズアップはボタンが SB
const headsUp = order.length === 2;
this.sbSeat = headsUp ? button : order[0];
this.bbSeat = headsUp ? order[0] : order[1];
this.post(this.sbSeat, sb);
this.post(this.bbSeat, bb);
this.currentBet = bb; // BB がショートでもコール額は BB
this.setNextActor(this.bbSeat, now);
}
get list() {
return this.order.map((i) => this.players.get(i));
}
live() {
return this.list.filter((p) => !p.folded);
}
put(p, amount) {
const s = this.seats[p.seat];
s.stack -= amount;
p.bet += amount;
p.committed += amount;
if (s.stack === 0) p.allIn = true;
}
post(seat, amount) {
const p = this.players.get(seat);
this.put(p, Math.min(amount, this.seats[seat].stack));
}
needsToAct(p) {
return !p.folded && !p.allIn && (!p.acted || p.bet < this.currentBet);
}
bettingClosed() {
const live = this.live();
if (live.length <= 1) return true;
const actors = live.filter((p) => !p.allIn);
if (actors.length === 0) return true;
// 動ける人が1人だけで、誰かのベットに応じる必要もない
const maxBet = Math.max(...live.map((p) => p.bet));
if (actors.length === 1 && actors[0].bet >= maxBet) return true;
return actors.every((p) => !this.needsToAct(p));
}
setNextActor(fromSeat, now) {
this.toAct = null;
this.deadline = null;
if (this.bettingClosed()) return this.endStreet(now);
const n = this.order.length;
const start = this.order.indexOf(fromSeat);
for (let k = 1; k <= n; k++) {
const p = this.players.get(this.order[(start + k) % n]);
if (!this.needsToAct(p)) continue;
this.toAct = p.seat;
this.deadline = now + config.ACTION_TIME_MS;
// 離席中・退席済みの人は自動でチェック/フォールド
const s = this.seats[p.seat];
if (s.sittingOut || s.left) this.autoAct(now);
return;
}
this.endStreet(now);
}
// 手番の人の選択肢(手番でなければ null)
options(seat) {
if (this.finished || this.toAct !== seat) return null;
const p = this.players.get(seat);
const stack = this.seats[seat].stack;
const toCall = Math.min(this.currentBet - p.bet, stack);
const maxTo = p.bet + stack;
// 他の全員がオールインならレイズしても意味がない
const opponentCanAct = this.live().some((q) => q !== p && !q.allIn);
return {
toCall,
canCheck: p.bet >= this.currentBet,
canRaise: !p.acted && stack > toCall && opponentCanAct,
minRaiseTo: Math.min(this.currentBet + this.minRaise, maxTo),
maxRaiseTo: maxTo,
isBet: this.currentBet === 0,
};
}
// type: fold / check / call / raise(amount = このストリートでの合計額 "raise to")
act(seat, type, amount, now) {
const o = this.options(seat);
if (!o) return 'あなたの番ではありません';
const p = this.players.get(seat);
if (type === 'fold') {
p.folded = true;
p.last = { type: 'FOLD' };
} else if (type === 'check') {
if (!o.canCheck) return 'チェックできません';
p.last = { type: 'CHECK' };
} else if (type === 'call') {
if (o.canCheck || o.toCall <= 0) return 'コールする額がありません';
this.put(p, o.toCall);
p.last = { type: 'CALL', amount: p.bet };
} else if (type === 'raise') {
if (!o.canRaise) return 'レイズできません';
if (!Number.isInteger(amount) || amount < o.minRaiseTo || amount > o.maxRaiseTo) {
return `${o.minRaiseTo}〜${o.maxRaiseTo} の額を指定してください`;
}
const raiseSize = amount - this.currentBet;
this.put(p, amount - p.bet);
p.last = { type: o.isBet ? 'BET' : 'RAISE', amount };
if (raiseSize >= this.minRaise) {
// 正規のレイズ: 他の人はもう一度アクションできる
this.minRaise = raiseSize;
for (const q of this.list) if (q !== p) q.acted = false;
}
// 足りないオールインのレイズはアクション済みの人に再レイズ権を与えない
this.currentBet = amount;
} else {
return '不正なアクションです';
}
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet };
p.acted = true;
this.setNextActor(seat, now);
return null;
}
autoAct(now) {
const o = this.options(this.toAct);
if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0, now);
}
// 退席などで手番に関係なくフォールドさせる
forceFold(seat, now) {
const p = this.players.get(seat);
if (!p || p.folded || this.finished) return;
if (this.toAct === seat) return this.act(seat, 'fold', 0, now);
p.folded = true;
p.last = { type: 'FOLD' };
if (this.live().length === 1) {
this.runoutAt = null;
this.endStreet(now);
} else if (this.toAct != null && this.bettingClosed()) {
this.endStreet(now);
}
}
// 誰もコールしなかった分を返す
returnUncalled() {
const bets = this.list.map((p) => p.bet).sort((a, b) => b - a);
const excess = bets[0] - (bets[1] || 0);
if (excess <= 0) return;
const p = this.list.find((q) => q.bet === bets[0]);
if (p.folded) return; // 退席でフォールドした人のベットはそのままポットに残る
p.bet -= excess;
p.committed -= excess;
this.seats[p.seat].stack += excess;
p.allIn = this.seats[p.seat].stack === 0;
if (!p.allIn && p.last && p.last.type === 'ALLIN') p.last = null;
}
endStreet(now) {
this.toAct = null;
this.deadline = null;
this.returnUncalled();
for (const p of this.list) {
this.pot += p.bet;
p.bet = 0;
p.acted = false;
if (p.last && p.last.type !== 'FOLD' && p.last.type !== 'ALLIN') p.last = null;
}
if (this.live().length === 1) return this.finish(false);
if (this.street === 'RIVER') return this.finish(true);
this.currentBet = 0;
this.minRaise = this.bb;
if (this.live().filter((p) => !p.allIn).length >= 2) {
this.dealStreet();
this.setNextActor(this.button, now);
} else {
// これ以上ベットが無いので手札を公開して残りのカードを順にめくる
this.revealed = true;
this.runoutAt = now + config.RUNOUT_STEP_MS;
}
}
dealStreet() {
this.deck.pop(); // バーン
if (this.street === 'PREFLOP') {
this.board.push(this.deck.pop(), this.deck.pop(), this.deck.pop());
this.street = 'FLOP';
} else if (this.street === 'TURN' || this.street === 'FLOP') {
this.board.push(this.deck.pop());
this.street = this.street === 'FLOP' ? 'TURN' : 'RIVER';
}
}
runoutStep(now) {
if (this.street === 'RIVER') {
this.runoutAt = null;
return this.finish(true);
}
this.dealStreet();
this.runoutAt = now + config.RUNOUT_STEP_MS;
}
// 手番の時間切れ。true なら時間切れ処理をした
timeout(now) {
if (this.finished || this.toAct == null || now < this.deadline) return false;
this.autoAct(now);
return true;
}
// メインポット・サイドポット(同じ参加者のポットはまとめる)
buildPots() {
const all = this.list;
const levels = [...new Set(all.map((p) => p.committed).filter((c) => c > 0))].sort((a, b) => a - b);
const pots = [];
let prev = 0;
for (const level of levels) {
let amount = 0;
for (const p of all) amount += Math.max(0, Math.min(p.committed, level) - prev);
prev = level;
let eligible = all.filter((p) => !p.folded && p.committed >= level).map((p) => p.seat);
const last = pots[pots.length - 1];
if (eligible.length === 0) eligible = last ? last.eligible : this.live().map((p) => p.seat);
if (last && last.eligible.join() === eligible.join()) last.amount += amount;
else pots.push({ amount, eligible });
}
return pots;
}
finish(showdown) {
this.finished = true;
this.showdown = showdown;
this.toAct = null;
this.deadline = null;
this.runoutAt = null;
const results = [];
if (!showdown) {
const winner = this.live()[0];
winner.won = this.pot;
this.seats[winner.seat].stack += this.pot;
results.push({ amount: this.pot, winners: [winner.seat], handName: null, bestCards: [] });
} else {
this.revealed = true;
for (const p of this.live()) p.best = bestHand(p.cards.concat(this.board));
for (const pot of this.buildPots()) {
const contenders = pot.eligible.map((s) => this.players.get(s));
let top = null;
for (const c of contenders) if (!top || compareScore(c.best.score, top) > 0) top = c.best.score;
const winners = contenders.filter((c) => compareScore(c.best.score, top) === 0);
// 割り切れない端数はボタンの左から順に
const share = Math.floor(pot.amount / winners.length);
let rest = pot.amount - share * winners.length;
for (const w of winners) {
const amount = share + (rest > 0 ? 1 : 0);
if (rest > 0) rest--;
w.won += amount;
this.seats[w.seat].stack += amount;
}
results.push({
amount: pot.amount,
winners: winners.map((w) => w.seat),
handName: winners[0].best.name,
bestCards: winners[0].best.cards,
});
}
}
this.pot = results.reduce((sum, r) => sum + r.amount, 0);
this.results = results;
}
// 閲覧者 viewerSeat に見せてよい情報だけを返す(他人の手札は公開時のみ)
view(viewerSeat, viewerToken) {
const players = {};
for (const p of this.list) {
const mine = p.seat === viewerSeat && p.token === viewerToken;
const shown = mine || (this.revealed && !p.folded);
let handName = null;
if (shown && !p.folded && this.board.length >= 3) {
handName = (p.best || bestHand(p.cards.concat(this.board))).name;
}
players[p.seat] = {
bet: p.bet,
folded: p.folded,
allIn: p.allIn,
last: p.last,
cards: shown ? p.cards : null,
handName,
won: p.won,
};
}
return {
number: this.number,
street: this.street,
board: this.board,
pot: this.pot,
potTotal: this.pot + this.list.reduce((sum, p) => sum + p.bet, 0),
currentBet: this.currentBet,
button: this.button,
sbSeat: this.sbSeat,
bbSeat: this.bbSeat,
toAct: this.toAct,
finished: this.finished,
showdown: this.showdown,
results: this.results,
players,
};
}
}
module.exports = { Hand };
+15 -6
View File
@@ -216,18 +216,27 @@ io.on('connection', (socket) => {
changed(table); changed(table);
}); });
// ホスト操作・退席は同じ形で処理する // プレイヤー操作・ホスト操作は同じ形で処理する(操作者は join 時のトークンで決まる)
const ACTION_TYPES = new Set(['fold', 'check', 'call', 'raise']);
const actions = { const actions = {
'table:leave': (t, token) => (t.leave(token) ? null : '着席していません'), 'table:leave': (t, token) => (t.leave(token) ? null : '着席していません'),
'table:start': (t, token) => t.start(token), 'table:start': (t, token) => t.start(token),
'table:nextPhase': (t, token) => t.nextPhase(token),
'table:pause': (t, token) => t.togglePause(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)) { 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); const table = socket.data.tableId && tables.get(socket.data.tableId);
if (!table) return reply(ack, { ok: false, error: 'NOT_FOUND' }); 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 }); reply(ack, error ? { ok: false, error } : { ok: true });
if (!error) changed(table); if (!error) changed(table);
}); });
@@ -239,13 +248,13 @@ io.on('connection', (socket) => {
}); });
}); });
// ブラインドタイマー // ブラインドタイマー・持ち時間・次のハンドなど時間で進む処理
setInterval(() => { setInterval(() => {
const now = Date.now(); const now = Date.now();
for (const table of tables.tables.values()) { for (const table of tables.tables.values()) {
if (table.tick(now)) changed(table); if (table.tick(now)) changed(table);
} }
}, 1000); }, 250);
// 誰も見ていないテーブルを片付ける // 誰も見ていないテーブルを片付ける
setInterval(() => { setInterval(() => {
+200 -77
View File
@@ -3,9 +3,7 @@
const crypto = require('crypto'); const crypto = require('crypto');
const config = require('./config'); const config = require('./config');
const Blinds = require('../public/assets/blinds'); const Blinds = require('../public/assets/blinds');
const { Hand } = require('./hand');
// 進行フェーズ。プレイ処理は未実装なので、ホストが手動で進めるスタブ。
const HAND_PHASES = ['PREFLOP', 'FLOP', 'TURN', 'RIVER', 'SHOWDOWN'];
class Table { class Table {
constructor(opts) { constructor(opts) {
@@ -19,14 +17,17 @@ class Table {
this.hostToken = opts.hostToken || null; this.hostToken = opts.hostToken || null;
this.maxSeats = config.MAX_SEATS; this.maxSeats = config.MAX_SEATS;
this.seats = new Array(this.maxSeats).fill(null); // { token, name, stack } // { token, name, stack, buyIns, sittingOut, left }
this.phase = 'WAITING'; // left: ハンド中に退席した人。ハンドが終わるまで席を予約しておく
this.seats = new Array(this.maxSeats).fill(null);
this.hand = null;
this.started = false; this.started = false;
this.paused = false; this.paused = false;
this.pausedAt = null;
this.level = 1; this.level = 1;
this.handNumber = 0; this.handNumber = 0;
this.pot = 0;
this.buttonSeat = null; this.buttonSeat = null;
this.nextHandAt = null;
this.levelEndsAt = null; this.levelEndsAt = null;
this.levelRemainingMs = this.intervalMs; this.levelRemainingMs = this.intervalMs;
@@ -42,114 +43,165 @@ class Table {
return Blinds.blindsAt(this.baseSmallBlind, this.baseBigBlind, this.level); 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() { get playerCount() {
return this.seats.filter(Boolean).length; return this.seats.filter((s) => s && !s.left).length;
} }
seatOf(token) { seatOf(token) {
return this.seats.findIndex((s) => s && s.token === token); return token ? this.seats.findIndex((s) => s && s.token === token) : -1;
} }
isHost(token) { isHost(token) {
return Boolean(token) && token === this.hostToken; 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(観戦) // 着席した席番号を返す。満席なら -1(観戦)
join(token, name) { join(token, name) {
const existing = this.seatOf(token); const existing = this.seatOf(token);
if (existing >= 0) { 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; return existing;
} }
const free = this.seats.findIndex((s) => !s); const free = this.seats.findIndex((s) => !s);
if (free < 0) return -1; 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; return free;
} }
leave(token) { leave(token, now = Date.now()) {
const i = this.seatOf(token); const i = this.seatOf(token);
if (i < 0) return false; if (i < 0 || this.seats[i].left) return false;
this.seats[i] = null; if (this.hand && this.hand.players.has(i)) {
if (this.hostToken === token) { // 結果表示やポット計算のため、ハンドが終わるまで席は残す
const next = this.seats.find(Boolean); this.seats[i].left = true;
this.hostToken = next ? next.token : null; this.hand.forceFold(i, now);
} else {
this.seats[i] = null;
} }
if (this.playerCount < 2 && this.phase !== 'WAITING') { if (this.hostToken === token) {
this.phase = 'WAITING'; const next = this.seats.find((s) => s && !s.left);
this.hostToken = next ? next.token : null;
} }
return true; return true;
} }
// 次に埋まっている席(時計回り = 席番号の昇順) removeLeftSeats() {
nextOccupied(from) { this.seats = this.seats.map((s) => (s && s.left ? null : s));
}
nextOf(list, from) {
for (let k = 1; k <= this.maxSeats; k++) { for (let k = 1; k <= this.maxSeats; k++) {
const i = (from + k) % this.maxSeats; const i = (from + k) % this.maxSeats;
if (this.seats[i]) return i; if (list.includes(i)) return i;
} }
return null; return null;
} }
blindSeats() { startNewHand(now) {
if (this.buttonSeat == null || this.phase === 'WAITING' || this.playerCount < 2) { this.removeLeftSeats();
return { sbSeat: null, bbSeat: null }; const eligible = this.eligibleSeats();
}
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);
this.buttonSeat = this.buttonSeat =
this.buttonSeat == null this.buttonSeat == null
? occupied[Math.floor(Math.random() * occupied.length)] ? eligible[crypto.randomInt(eligible.length)]
: this.nextOccupied(this.buttonSeat); : this.nextOf(eligible, this.buttonSeat);
this.handNumber++; const order = [];
this.pot = 0; for (let i = this.nextOf(eligible, this.buttonSeat); order.length < eligible.length; i = this.nextOf(eligible, i)) {
this.phase = 'PREFLOP'; order.push(i);
}
// ---- ホスト操作(エラー時はメッセージを返す) ----
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;
} }
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; return null;
} }
// スタブ: フェーズを1つ進める(SHOWDOWN の次は新しいハンド) rebuy(token) {
nextPhase(token) { const i = this.seatOf(token);
if (!this.isHost(token)) return 'ホストのみ操作できます'; if (i < 0) return '着席していません';
if (this.phase === 'WAITING') return 'まだ開始していません'; const s = this.seats[i];
if (this.playerCount < 2) return '2人以上必要です'; if (s.stack > 0) return 'チップが残っています';
const i = HAND_PHASES.indexOf(this.phase); if (this.handActive && this.hand.players.has(i) && !this.hand.players.get(i).folded) return 'ハンドの終了後にリバイできます';
if (i === HAND_PHASES.length - 1) this.startNewHand(); s.stack = this.startingStack;
else this.phase = HAND_PHASES[i + 1]; s.buyIns++;
s.sittingOut = false;
return null; 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.isHost(token)) return 'ホストのみ操作できます';
if (!this.started) return 'まだ開始していません'; if (!this.started) return 'まだ開始していません';
const now = Date.now();
if (this.paused) { 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; if (this.timerEnabled) this.levelEndsAt = now + this.levelRemainingMs;
this.paused = false;
this.pausedAt = null;
} else { } else {
this.paused = true; this.paused = true;
this.pausedAt = now;
if (this.timerEnabled) { if (this.timerEnabled) {
this.levelRemainingMs = Math.max(0, this.levelEndsAt - now); this.levelRemainingMs = Math.max(0, this.levelEndsAt - now);
this.levelEndsAt = null; this.levelEndsAt = null;
@@ -158,7 +210,8 @@ class Table {
return null; return null;
} }
// ブラインドタイマー。レベルが上がったら true // 時間で進む処理(ブラインドタイマー・手番の時間切れ・オールイン時のめくり・次のハンド)
// 状態が変わったら true
tick(now) { tick(now) {
let changed = false; let changed = false;
while (this.levelEndsAt != null && now >= this.levelEndsAt) { while (this.levelEndsAt != null && now >= this.levelEndsAt) {
@@ -166,6 +219,41 @@ class Table {
this.levelEndsAt += this.intervalMs; this.levelEndsAt += this.intervalMs;
changed = true; 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; return changed;
} }
@@ -188,11 +276,28 @@ class Table {
}; };
} }
// token = 閲覧者のトークン(他人のトークンは送らない) // token = 閲覧者のトークン(他人のトークンや手札は送らない)
publicState(token, connectedTokens) { publicState(token, connectedTokens) {
const now = Date.now();
const { sb, bb } = this.blinds; const { sb, bb } = this.blinds;
const next = Blinds.blindsAt(this.baseSmallBlind, this.baseBigBlind, this.level + 1); 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 { return {
id: this.id, id: this.id,
name: this.name, name: this.name,
@@ -206,23 +311,41 @@ class Table {
enabled: this.timerEnabled, enabled: this.timerEnabled,
intervalMin: this.intervalMin, intervalMin: this.intervalMin,
endsAt: this.levelEndsAt, 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, running: this.levelEndsAt != null,
}, },
phase: this.phase, phase: this.phase,
started: this.started, started: this.started,
paused: this.paused, paused: this.paused,
pot: this.pot,
handNumber: this.handNumber, handNumber: this.handNumber,
buttonSeat: this.phase === 'WAITING' ? null : this.buttonSeat, hand: hv,
...this.blindSeats(), turn,
hostSeat: host >= 0 ? host : null,
seats: this.seats.map((s, i) => 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), isHost: this.isHost(token),
serverNow: Date.now(), serverNow: now,
}; };
} }
} }
@@ -268,4 +391,4 @@ class TableManager {
} }
} }
module.exports = { TableManager }; module.exports = { TableManager, Table };
+303
View File
@@ -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;
}
}
});