Compare commits

...
2 Commits
Author SHA1 Message Date
agomizi1cmandClaude Opus 5.5 b5d84e5f65 Switch to chips-only play: real cards at the table, winners picked on screen
- Remove the deck, hole cards, board, hand evaluator and reveal logic
  (cards are dealt physically; the site only tracks bets, pots and stacks)
- Showdown now waits for a winner per pot (main/side), chosen by a player
  still in the hand or the host; multiple winners split the pot
- All-in with no further betting goes straight to showdown
- Remove the 30s action clock / auto sit-out (everyone is at the same table)
- UI: winner picker panel (main winner auto-fills side pots), compact table

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 17:46:10 +09:00
agomizi1cmandClaude Opus 5.5 8de55f7ca5 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>
2026-10-15 17:34:25 +09:00
11 changed files with 1428 additions and 144 deletions

No files matched your search

+33 -3
View File
@@ -2,7 +2,23 @@
友達専用のテキサスホールデム(リングゲーム)サイト。Node.js + Express + Socket.IO。 友達専用のテキサスホールデム(リングゲーム)サイト。Node.js + Express + Socket.IO。
現状は「鍵入力 → ロビー → テーブル作成 → プレイ画面(スタブ)」まで。カード配布・ベッティングなどのゲーム処理は未実装で、プレイ画面ではホストが「次へ(仮)」でフェーズを手動で進められる。 「鍵入力 → ロビー → テーブル作成 → プレイ」まで動く。
## ルール・仕様
カードは実物で配り、このサイトはチップの代わりに使う(ベット・ポット・スタックの管理)。
- ノーリミット・テキサスホールデムのリングゲーム(最大9人)。ホストが START を押すと、以降は2人以上いる限り自動でハンドが続く。
- 画面にディーラーボタン(D)・SB・BB と、いまのストリート(PREFLOP / FLOP / TURN / RIVER)が出るので、それに合わせて実物のカードを配る。
- ブラインドは自動で支払われ、ハンド開始時のレベルで固定。ヘッズアップはボタンが SB。
- 各自が自分のスマホで Fold / Check / Call / Bet / Raise を行う。最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。
- ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。
- **ショーダウン**: カードを見せ合い、勝った人を画面で選んで確定する(選べるのはショーダウンに残った人とホスト)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。
- 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。
- 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。
- チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。
- ハンド中に退席するとフォールド扱い(出したチップはポットに残る)。
- ホストの一時停止中は、アクション・勝者の確定・ブラインドタイマー・次のハンドの開始がすべて止まる。
## ローカルで動かす ## ローカルで動かす
@@ -35,6 +51,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はブラウザ内だけに保存し、他のプレイヤーには送らない。
- **チップ操作**: アクションはサーバ側で手番・額をすべて検証する。ショーダウンの勝者を確定できるのは残った人とホストだけで、ポットの対象外の人は選べない。
6桁のキーはそれ自体が強い秘密ではないので、上記の回数制限が守りの要になっている。キーは友達にだけ直接伝えること。 6桁のキーはそれ自体が強い秘密ではないので、上記の回数制限が守りの要になっている。キーは友達にだけ直接伝えること。
@@ -44,14 +61,16 @@ 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ハンドのチップの動き(ブラインド・ベッティング・サイドポット・勝者への分配) |
| `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 +157,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
View File
@@ -93,6 +93,7 @@
TURN: 'TURN', TURN: 'TURN',
RIVER: 'RIVER', RIVER: 'RIVER',
SHOWDOWN: 'SHOWDOWN', 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 };
+136 -17
View File
@@ -319,8 +319,8 @@ input.invalid { border-color: var(--red); }
.felt-area { .felt-area {
position: relative; position: relative;
flex: 1; flex: 1;
min-height: 400px; min-height: 340px;
margin: 8px 0; margin: 20px 0 24px;
} }
.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: -4px; right: -8px; z-index: 2; }
.blind-marker { .blind-marker {
position: absolute; position: absolute;
top: -4px; top: -4px;
left: -10px; left: -10px;
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,115 @@ input.invalid { border-color: var(--red); }
z-index: 30; z-index: 30;
} }
/* ---------- 席の状態 ---------- */
.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); }
.seat.contender .avatar { border-color: var(--orange); }
.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% + 4px); }
.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); }
.phase.showdown { background: var(--orange); color: #111; }
.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: 420px; }
.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; }
/* ---------- 自分の操作エリア ---------- */
.me-row { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; }
.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-bet { color: var(--gold); font-weight: 700; }
.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; }
.award-panel { margin-bottom: 4px; }
.award-pot { background: var(--panel-2); border-radius: 10px; padding: 8px 10px; margin-bottom: 8px; }
.award-title { font-size: 12px; color: var(--muted); margin-bottom: 6px; }
.award-title b { color: var(--gold); font-size: 14px; }
.picks { display: flex; flex-wrap: wrap; gap: 6px; }
.picks .pick { background: var(--input); color: var(--text); border: 2px solid transparent; }
.picks .pick.on { background: rgba(246, 199, 68, 0.18); border-color: var(--gold); color: var(--gold); }
.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 属性を使わないため) ---------- */
+360 -39
View File
@@ -1,4 +1,5 @@
// プレイ画面(スタブ): サーバから受け取ったテーブル状態を表示するだけ // プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る
// カードは実物で配るので、ここで扱うのはチップのやり取りだけ
(function () { (function () {
'use strict'; 'use strict';
@@ -8,10 +9,18 @@
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>';
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 wasMyTurn = false;
// ショーダウンの勝者選択(ポットごとの席番号の Set)
let awardKey = '';
let awardSel = [];
// ---------- 名前 ---------- // ---------- 名前 ----------
function ensureName() { function ensureName() {
@@ -33,28 +42,48 @@
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) {
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();
}
});
}
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 +91,17 @@
if (socket) socket.disconnect(); if (socket) socket.disconnect();
} }
const nameOf = (seat) => (state.seats[seat] ? state.seats[seat].name : '退席者');
// ---------- 描画 ---------- // ---------- 描画 ----------
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 || (s.me.canAward && !s.paused)));
$('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,76 +111,355 @@
: 'ブラインドタイマーなし'; : 'ブラインドタイマーなし';
$('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);
$('phase').parentElement.classList.toggle('showdown', s.phase === 'SHOWDOWN' && !s.paused);
$('hand-no').textContent = s.handNumber ? `#${s.handNumber}` : '';
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;
}
function renderResult(s) {
const el = $('result');
const h = s.hand;
if (!h || !h.finished || !h.results) {
el.hidden = true;
return;
}
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('・');
return `<div>${label}<b>${who}</b> +${chips(r.amount)}</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 angles = ordered.map((_, i) => Math.PI / 2 + (i * 2 * Math.PI) / Math.max(n, 1));
const showdown = s.phase === 'SHOWDOWN';
const finished = Boolean(h && h.finished);
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'];
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 (s.toAct === p.seat) classes.push('turn');
p.seat === s.sbSeat ? '<span class="blind-marker sb">SB</span>' : '', if (showdown && p.inHand && !p.folded) classes.push('contender');
p.seat === s.bbSeat ? '<span class="blind-marker bb">BB</span>' : '', if (finished && p.won > 0) classes.push('winner');
].join(''); if (p.sittingOut && !p.inHand) classes.push('away');
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('')
: '';
// ベット(中央寄り)・獲得額
const below = Math.sin(angles[idx]) <= 0.35;
let bet = '';
if (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 && !(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}</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 && !finished ? 'ALL-IN' : chips(p.stack)}</div>
${p.connected ? '' : '<div class="offline-tag">オフライン</div>'} ${p.connected ? '' : '<div class="offline-tag">オフライン</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 renderActionBar(s, seat) {
const m = s.me;
const h = s.hand;
const o = m.options;
$('my-stack').textContent = chips(m.stack);
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-bet').textContent = seat.inHand && seat.bet > 0 ? `ベット中 ${chips(seat.bet)}` : '';
$('sit-out').hidden = m.sittingOut;
// 状況
const awaiting = Boolean(h && h.pots && !h.finished);
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 (awaiting) status = m.canAward ? 'カードを見せ合って、勝った人を選んでください' : '勝者の選択を待っています';
else if (h && !h.finished && s.toAct != null) status = `${nameOf(s.toAct)} の番です`;
else if (h && !h.finished && !seat.inHand) status = '次のハンドから参加します';
else if (h && h.finished) status = '次のハンドを準備中…';
else if (!h) status = '参加者を待っています(2人以上で再開)';
$('status-line').textContent = status;
$('status-line').classList.toggle('my-turn', Boolean(o) || (awaiting && m.canAward));
// ショーダウンの勝者選択
const awarding = awaiting && m.canAward && !s.paused;
$('award-panel').hidden = !awarding;
if (awarding) renderAwardPanel(h.pots);
// ボタン
const alt = (m.sittingOut || m.canRebuy) && !awarding;
if (!o) raising = false;
$('alt-actions').hidden = !alt;
$('sit-in').hidden = !m.sittingOut;
$('rebuy').hidden = !m.canRebuy;
$('rebuy').textContent = `リバイ(${chips(s.startingStack)})`;
$('actions').hidden = alt || raising || awarding;
$('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;
}
call.textContent = o.canCheck ? 'Check' : o.toCall >= m.stack ? `All-in ${chips(o.toCall)}` : `Call ${chips(o.toCall)}`;
raise.disabled = pending || !o.canRaise;
raise.textContent = !o.canRaise
? o.isBet ? 'Bet' : 'Raise'
: o.minRaiseTo >= o.maxRaiseTo
? `All-in ${chips(o.maxRaiseTo)}`
: o.isBet ? 'Bet' : 'Raise';
if (raising) renderRaisePanel(o);
}
// ---------- 勝者選択 ----------
function renderAwardPanel(pots) {
const key = `${state.handNumber}:${JSON.stringify(pots)}`;
if (key !== awardKey) {
awardKey = key;
// 参加者が1人だけのポットは最初から選んでおく
awardSel = pots.map((p) => new Set(p.eligible.length === 1 ? p.eligible : []));
}
$('award-pots').innerHTML = pots
.map((p, i) => {
const title = pots.length === 1 ? 'ポット' : i === 0 ? 'メインポット' : `サイドポット${pots.length > 2 ? i : ''}`;
const names = p.eligible
.map(
(seat) =>
`<button type="button" class="btn btn-sm pick${awardSel[i].has(seat) ? ' on' : ''}" data-pot="${i}" data-seat="${seat}">${esc(nameOf(seat))}</button>`
)
.join('');
return `<div class="award-pot"><div class="award-title">${title} <b>${chips(p.amount)}</b></div><div class="picks">${names}</div></div>`;
})
.join('');
const ready = awardSel.every((set) => set.size > 0);
const split = awardSel.some((set) => set.size > 1);
$('award-confirm').disabled = !ready || pending;
$('award-confirm').textContent = split ? '山分けで確定' : '確定';
}
$('award-pots').addEventListener('click', (e) => {
const b = e.target.closest('[data-pot]');
if (!b || !state || !state.hand || !state.hand.pots) return;
const i = Number(b.dataset.pot);
const seat = Number(b.dataset.seat);
const set = awardSel[i];
if (set.has(seat)) set.delete(seat);
else {
set.add(seat);
// メインで勝った人は、まだ決めていないサイドポットでも勝っているはず
state.hand.pots.forEach((p, j) => {
if (j > i && awardSel[j].size === 0 && p.eligible.includes(seat)) awardSel[j].add(seat);
});
}
renderAwardPanel(state.hand.pots);
});
$('award-confirm').addEventListener('click', () => {
if (pending || !awardSel.every((set) => set.size > 0)) return;
const winners = awardSel.map((set) => [...set]);
const names = winners.map((w) => w.map(nameOf).join('・'));
const msg =
names.length === 1
? `${names[0]} の勝ちで確定しますか?`
: names.map((n, i) => `${i === 0 ? 'メイン' : 'サイド'}: ${n}`).join('\n') + '\nで確定しますか?';
if (!confirm(msg)) return;
pending = true;
emit('table:award', { winners });
render();
});
// ---------- レイズ ----------
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;
// SB 単位に丸める(最大はオールイン額そのまま)
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() { function renderTimer() {
const el = $('timer');
if (!state) return; if (!state) return;
const el = $('timer');
const t = state.timer; const t = state.timer;
el.classList.toggle('paused', state.paused); el.classList.toggle('paused', state.paused);
if (!t.enabled) { if (!t.enabled) {
el.textContent = state.paused ? '⏸ PAUSED' : ''; el.textContent = state.paused ? '⏸' : '';
return; return;
} }
const remaining = t.running ? t.endsAt - (Date.now() + clockOffset) : t.remainingMs; const remaining = t.running ? t.endsAt - (Date.now() + clockOffset) : t.remainingMs;
@@ -156,15 +470,22 @@
} }
setInterval(renderTimer, 250); setInterval(renderTimer, 250);
// ---------- 操作 ---------- // ---------- その他の操作 ----------
$('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'));
$('sit-in').addEventListener('click', () => emit('table:sitIn'));
$('rebuy').addEventListener('click', () => emit('table:rebuy'));
$('take-seat').addEventListener('click', () => join(true));
$('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 = '/'; });
}); });
+46 -8
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,61 @@
<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="phase"><span id="phase">WAITING</span><span class="hand-no" id="hand-no"></span></div>
<div class="hand-no" id="hand-no"></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="inner"> <div class="inner">
<div class="me-row">
<div class="me-info">
<div class="my-stack"><span class="wallet">👛</span><span id="my-stack">$0</span></div> <div class="my-stack"><span class="wallet">👛</span><span id="my-stack">$0</span></div>
<div class="actions"> <div class="me-sub"><span id="my-net"></span><span class="my-bet" id="my-bet"></span></div>
<button class="btn" disabled>Fold</button> </div>
<button class="btn" disabled>Check</button> <button class="btn btn-ghost btn-sm" id="sit-out" title="次のハンドから参加しません">離席</button>
<button class="btn" disabled>Raise</button> </div>
<div class="status-line" id="status-line"></div>
<div class="award-panel" id="award-panel" hidden>
<div id="award-pots"></div>
<button class="btn btn-orange btn-block" id="award-confirm" disabled>確定</button>
</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>
+6
View File
@@ -53,6 +53,12 @@ module.exports = {
// 誰も接続していないテーブルを削除するまでの時間 // 誰も接続していないテーブルを削除するまでの時間
EMPTY_TABLE_TTL_MS: 30 * 60 * 1000, EMPTY_TABLE_TTL_MS: 30 * 60 * 1000,
// ハンド終了後、次のハンドまで結果を表示する時間
SHOWDOWN_MS: 4000,
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,
+310
View File
@@ -0,0 +1,310 @@
'use strict';
// 1ハンド分のチップの動き(ブラインド・ベッティング・ポット分配)。
// カードは実物で配るので扱わない。ショーダウンでは勝者をプレイヤーが選ぶ。
// seats は Table.seats への参照で、スタックはここで直接増減する。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
const STREETS = ['PREFLOP', 'FLOP', 'TURN', 'RIVER'];
class Hand {
constructor({ number, seats, order, button, sb, bb }) {
this.number = number;
this.seats = seats;
this.order = order; // 参加者の席番号。ボタンの次から時計回り
this.button = button;
this.sb = sb;
this.bb = bb;
this.street = 'PREFLOP'; // PREFLOP / FLOP / TURN / RIVER / SHOWDOWN
this.pot = 0; // 前のストリートまでに集めた額
this.currentBet = 0;
this.minRaise = bb;
this.toAct = null;
this.finished = false;
this.showdown = false;
this.results = null;
this.players = new Map();
for (const i of order) {
this.players.set(i, {
seat: i,
token: seats[i].token,
bet: 0, // このストリートで出した額
committed: 0, // このハンドで出した合計
folded: false,
allIn: false,
acted: false,
last: null, // 直前のアクション(表示用)
won: 0,
});
}
// ヘッズアップはボタンが SB
const headsUp = order.length === 2;
this.sbSeat = headsUp ? button : order[0];
this.bbSeat = headsUp ? order[0] : order[1];
this.post(this.sbSeat, sb);
this.post(this.bbSeat, bb);
this.currentBet = bb; // BB がショートでもコール額は BB
this.setNextActor(this.bbSeat);
}
get list() {
return this.order.map((i) => this.players.get(i));
}
get awaitingWinners() {
return this.street === 'SHOWDOWN' && !this.finished;
}
live() {
return this.list.filter((p) => !p.folded);
}
put(p, amount) {
const s = this.seats[p.seat];
s.stack -= amount;
p.bet += amount;
p.committed += amount;
if (s.stack === 0) p.allIn = true;
}
post(seat, amount) {
const p = this.players.get(seat);
this.put(p, Math.min(amount, this.seats[seat].stack));
}
needsToAct(p) {
return !p.folded && !p.allIn && (!p.acted || p.bet < this.currentBet);
}
bettingClosed() {
const live = this.live();
if (live.length <= 1) return true;
const actors = live.filter((p) => !p.allIn);
if (actors.length === 0) return true;
// 動ける人が1人だけで、誰かのベットに応じる必要もない
const maxBet = Math.max(...live.map((p) => p.bet));
if (actors.length === 1 && actors[0].bet >= maxBet) return true;
return actors.every((p) => !this.needsToAct(p));
}
setNextActor(fromSeat) {
this.toAct = null;
if (this.bettingClosed()) return this.endStreet();
const n = this.order.length;
const start = this.order.indexOf(fromSeat);
for (let k = 1; k <= n; k++) {
const p = this.players.get(this.order[(start + k) % n]);
if (!this.needsToAct(p)) continue;
this.toAct = p.seat;
// 離席中・退席済みの人は自動でチェック/フォールド
const s = this.seats[p.seat];
if (s.sittingOut || s.left) this.autoAct();
return;
}
this.endStreet();
}
// 手番の人の選択肢(手番でなければ null)
options(seat) {
if (this.finished || this.toAct !== seat) return null;
const p = this.players.get(seat);
const stack = this.seats[seat].stack;
const toCall = Math.min(this.currentBet - p.bet, stack);
const maxTo = p.bet + stack;
// 他の全員がオールインならレイズしても意味がない
const opponentCanAct = this.live().some((q) => q !== p && !q.allIn);
return {
toCall,
canCheck: p.bet >= this.currentBet,
canRaise: !p.acted && stack > toCall && opponentCanAct,
minRaiseTo: Math.min(this.currentBet + this.minRaise, maxTo),
maxRaiseTo: maxTo,
isBet: this.currentBet === 0,
};
}
// type: fold / check / call / raise(amount = このストリートでの合計額 "raise to")
act(seat, type, amount) {
const o = this.options(seat);
if (!o) return 'あなたの番ではありません';
const p = this.players.get(seat);
if (type === 'fold') {
p.folded = true;
p.last = { type: 'FOLD' };
} else if (type === 'check') {
if (!o.canCheck) return 'チェックできません';
p.last = { type: 'CHECK' };
} else if (type === 'call') {
if (o.canCheck || o.toCall <= 0) return 'コールする額がありません';
this.put(p, o.toCall);
p.last = { type: 'CALL', amount: p.bet };
} else if (type === 'raise') {
if (!o.canRaise) return 'レイズできません';
if (!Number.isInteger(amount) || amount < o.minRaiseTo || amount > o.maxRaiseTo) {
return `${o.minRaiseTo}〜${o.maxRaiseTo} の額を指定してください`;
}
const raiseSize = amount - this.currentBet;
this.put(p, amount - p.bet);
p.last = { type: o.isBet ? 'BET' : 'RAISE', amount };
if (raiseSize >= this.minRaise) {
// 正規のレイズ: 他の人はもう一度アクションできる
this.minRaise = raiseSize;
for (const q of this.list) if (q !== p) q.acted = false;
}
// 足りないオールインのレイズはアクション済みの人に再レイズ権を与えない
this.currentBet = amount;
} else {
return '不正なアクションです';
}
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet };
p.acted = true;
this.setNextActor(seat);
return null;
}
autoAct() {
const o = this.options(this.toAct);
if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0);
}
// 退席などで手番に関係なくフォールドさせる
forceFold(seat) {
const p = this.players.get(seat);
if (!p || p.folded || this.finished) return;
if (this.toAct === seat) return this.act(seat, 'fold', 0);
p.folded = true;
p.last = { type: 'FOLD' };
if (this.live().length === 1) {
if (this.awaitingWinners) this.finishFoldWin();
else this.endStreet();
} else if (this.toAct != null && this.bettingClosed()) {
this.endStreet();
}
}
// 誰もコールしなかった分を返す
returnUncalled() {
const bets = this.list.map((p) => p.bet).sort((a, b) => b - a);
const excess = bets[0] - (bets[1] || 0);
if (excess <= 0) return;
const p = this.list.find((q) => q.bet === bets[0]);
if (p.folded) return; // 退席でフォールドした人のベットはそのままポットに残る
p.bet -= excess;
p.committed -= excess;
this.seats[p.seat].stack += excess;
p.allIn = this.seats[p.seat].stack === 0;
if (!p.allIn && p.last && p.last.type === 'ALLIN') p.last = null;
}
endStreet() {
this.toAct = null;
this.returnUncalled();
for (const p of this.list) {
this.pot += p.bet;
p.bet = 0;
p.acted = false;
if (p.last && p.last.type !== 'FOLD' && p.last.type !== 'ALLIN') p.last = null;
}
if (this.live().length === 1) return this.finishFoldWin();
this.currentBet = 0;
this.minRaise = this.bb;
// リバーが終わった、または全員オールインでこれ以上ベットが無い → ショーダウン
if (this.street === 'RIVER' || this.live().filter((p) => !p.allIn).length < 2) {
this.street = 'SHOWDOWN';
return;
}
this.street = STREETS[STREETS.indexOf(this.street) + 1];
this.setNextActor(this.button);
}
// メインポット・サイドポット(同じ参加者のポットはまとめる)
buildPots() {
const all = this.list;
const levels = [...new Set(all.map((p) => p.committed).filter((c) => c > 0))].sort((a, b) => a - b);
const pots = [];
let prev = 0;
for (const level of levels) {
let amount = 0;
for (const p of all) amount += Math.max(0, Math.min(p.committed, level) - prev);
prev = level;
let eligible = all.filter((p) => !p.folded && p.committed >= level).map((p) => p.seat);
const last = pots[pots.length - 1];
if (eligible.length === 0) eligible = last ? last.eligible : this.live().map((p) => p.seat);
if (last && last.eligible.join() === eligible.join()) last.amount += amount;
else pots.push({ amount, eligible });
}
return pots;
}
finishFoldWin() {
const winner = this.live()[0];
winner.won = this.pot;
this.seats[winner.seat].stack += this.pot;
this.end(false, [{ amount: this.pot, winners: [winner.seat] }]);
}
// ショーダウンの勝者を決める。winners[i] = i 番目のポットの勝者の席番号(引き分けは複数)
award(winners) {
if (!this.awaitingWinners) return 'ショーダウンではありません';
const pots = this.buildPots();
if (!Array.isArray(winners) || winners.length !== pots.length) return 'すべてのポットの勝者を選んでください';
for (let i = 0; i < pots.length; i++) {
const w = winners[i];
if (!Array.isArray(w) || w.length === 0) return 'すべてのポットの勝者を選んでください';
if (new Set(w).size !== w.length || !w.every((s) => pots[i].eligible.includes(s))) return '勝者の指定が不正です';
}
const results = [];
pots.forEach((pot, i) => {
// 割り切れない端数はボタンの左から順に
const ws = this.order.filter((s) => winners[i].includes(s));
const share = Math.floor(pot.amount / ws.length);
let rest = pot.amount - share * ws.length;
for (const s of ws) {
const amount = share + (rest > 0 ? 1 : 0);
if (rest > 0) rest--;
this.players.get(s).won += amount;
this.seats[s].stack += amount;
}
results.push({ amount: pot.amount, winners: ws });
});
this.end(true, results);
return null;
}
end(showdown, results) {
this.finished = true;
this.showdown = showdown;
this.toAct = null;
this.results = results;
}
view() {
const players = {};
for (const p of this.list) {
players[p.seat] = { bet: p.bet, folded: p.folded, allIn: p.allIn, last: p.last, won: p.won };
}
return {
number: this.number,
street: this.street,
pot: this.pot,
potTotal: this.pot + this.list.reduce((sum, p) => sum + p.bet, 0),
currentBet: this.currentBet,
button: this.button,
sbSeat: this.sbSeat,
bbSeat: this.bbSeat,
toAct: this.toAct,
finished: this.finished,
showdown: this.showdown,
pots: this.awaitingWinners ? this.buildPots() : null,
results: this.results,
players,
};
}
}
module.exports = { Hand };
+24 -6
View File
@@ -216,18 +216,36 @@ 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:award': (t, token, p) => {
// winners: ポットごとの勝者の席番号の配列
const w = p && typeof p === 'object' ? p.winners : null;
const ok =
Array.isArray(w) &&
w.length <= config.MAX_SEATS &&
w.every((a) => Array.isArray(a) && a.length <= config.MAX_SEATS && a.every((s) => Number.isInteger(s)));
return ok ? t.award(token, w) : '勝者の指定が不正です';
},
'table:sitOut': (t, token) => t.setSittingOut(token, true),
'table:sitIn': (t, token) => t.setSittingOut(token, false),
'table:rebuy': (t, token) => t.rebuy(token),
}; };
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 +257,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(() => {
+181 -70
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,176 @@ 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) {
const i = this.seatOf(token); const i = this.seatOf(token);
if (i < 0) return false; 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);
} else {
this.seats[i] = null; this.seats[i] = null;
if (this.hostToken === token) {
const next = this.seats.find(Boolean);
this.hostToken = next ? next.token : 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() {
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() { startNewHand() {
const occupied = this.seats.map((s, i) => (s ? i : -1)).filter((i) => i >= 0); this.removeLeftSeats();
const eligible = this.eligibleSeats();
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);
const order = [];
for (let i = this.nextOf(eligible, this.buttonSeat); order.length < eligible.length; i = this.nextOf(eligible, i)) {
order.push(i);
}
this.handNumber++; this.handNumber++;
this.pot = 0; const { sb, bb } = this.blinds;
this.phase = 'PREFLOP'; this.nextHandAt = null;
this.hand = new Hand({ number: this.handNumber, seats: this.seats, order, button: this.buttonSeat, sb, bb });
} }
// ---- ホスト操作(エラー時はメッセージを返す) ---- // ---- プレイヤー操作(エラー時はメッセージを返す) ----
start(token) { act(token, type, amount) {
const i = this.seatOf(token);
if (i < 0) return '着席していません';
if (!this.handActive) return 'ハンドが進行していません';
if (this.paused) return '一時停止中です';
return this.hand.act(i, type, amount);
}
// ショーダウンの勝者を選べるのは、ショーダウンに残った人とホスト
canAward(token) {
if (!this.handActive || !this.hand.awaitingWinners) return false;
const i = this.seatOf(token);
const p = i >= 0 ? this.hand.players.get(i) : null;
return this.isHost(token) || Boolean(p && !p.folded && !this.seats[i].left);
}
award(token, winners) {
if (!this.handActive || !this.hand.awaitingWinners) return 'ショーダウンではありません';
if (!this.canAward(token)) return 'ショーダウンに残った人かホストが選んでください';
if (this.paused) return '一時停止中です';
return this.hand.award(winners);
}
setSittingOut(token, value) {
const i = this.seatOf(token);
if (i < 0) return '着席していません';
const s = this.seats[i];
s.sittingOut = value;
// 手番中に離席したら、その場でチェック/フォールド
if (value && this.handActive && this.hand.toAct === i && !this.paused) this.hand.autoAct();
return null;
}
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;
}
// ---- ホスト操作 ----
start(token, now = Date.now()) {
if (!this.isHost(token)) return 'ホストのみ開始できます'; if (!this.isHost(token)) return 'ホストのみ開始できます';
if (this.phase !== 'WAITING') return 'すでに進行中です'; if (this.started) return 'すでに開始しています';
if (this.playerCount < 2) return '2人以上必要です'; if (this.eligibleSeats().length < 2) return '2人以上必要です';
if (!this.started) {
this.started = true; this.started = true;
if (this.timerEnabled) this.levelEndsAt = Date.now() + this.intervalMs; if (this.timerEnabled) this.levelEndsAt = now + this.intervalMs;
}
this.startNewHand(); this.startNewHand();
return null; return null;
} }
// スタブ: フェーズを1つ進める(SHOWDOWN の次は新しいハンド) togglePause(token, now = Date.now()) {
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];
return null;
}
togglePause(token) {
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; // 止めていた時間だけ次のハンドの開始を後ろにずらす
if (this.nextHandAt != null) this.nextHandAt += now - this.pausedAt;
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 +221,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 +230,28 @@ class Table {
this.levelEndsAt += this.intervalMs; this.levelEndsAt += this.intervalMs;
changed = true; changed = true;
} }
if (this.paused) return changed;
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();
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();
changed = true;
}
}
return changed; return changed;
} }
@@ -190,9 +276,15 @@ 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() : null;
const me = mySeat >= 0 ? this.seats[mySeat] : null;
const inLiveHand = Boolean(this.handActive && h.players.has(mySeat) && !h.players.get(mySeat).folded);
return { return {
id: this.id, id: this.id,
name: this.name, name: this.name,
@@ -206,23 +298,42 @@ 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(), toAct: this.handActive ? h.toAct : null,
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,
canAward: this.canAward(token),
}
: null,
isHost: this.isHost(token), isHost: this.isHost(token),
serverNow: Date.now(), serverNow: now,
}; };
} }
} }
@@ -268,4 +379,4 @@ class TableManager {
} }
} }
module.exports = { TableManager }; module.exports = { TableManager, Table };
+329
View File
@@ -0,0 +1,329 @@
'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 { Table } = require('../server/tables');
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;
}
const tk = (t, seat) => t.seats[seat].token;
// ショーダウンまでチェック/コールで進める
function checkDown(t) {
const h = t.hand;
for (let guard = 0; guard < 100 && h.toAct != null; guard++) {
const o = h.options(h.toAct);
assert.equal(t.act(tk(t, h.toAct), o.canCheck ? 'check' : 'call', 0), null);
}
}
test('ヘッズアップ: ボタンが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(tk(t, sb), 'fold', 0), null);
assert.ok(h.finished && !h.showdown);
assert.equal(t.seats[sb].stack, 990);
assert.equal(t.seats[bb].stack, 1010);
});
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(tk(t, btn), 'call', 0), null);
assert.equal(t.act(tk(t, sb), 'call', 0), null);
assert.equal(h.street, 'PREFLOP');
assert.equal(h.toAct, bb); // BB はまだ動ける
assert.ok(h.options(bb).canRaise);
assert.equal(t.act(tk(t, bb), 'check', 0), null);
assert.equal(h.street, 'FLOP');
assert.equal(h.pot, 60);
assert.equal(h.toAct, sb); // ポストフロップは SB から
checkDown(t);
assert.equal(t.phase, 'SHOWDOWN');
assert.deepEqual(h.view().pots, [{ amount: 60, eligible: [sb, bb, btn] }]);
});
test('ミニマムレイズと、足りないオールインは再レイズ権を与えない', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
// 最低レイズ額は 40(20 + 20)
assert.ok(t.act(tk(t, btn), 'raise', 39));
assert.equal(t.act(tk(t, btn), 'raise', 60), null); // +40 のレイズ
assert.equal(h.options(sb).minRaiseTo, 100);
assert.equal(t.act(tk(t, sb), 'call', 0), null);
// BB は 75 しか持っていないとする → 75 オールインは 100 未満なので不完全なレイズ
t.seats[bb].stack = 75 - 20;
assert.equal(t.act(tk(t, bb), 'raise', 75), null);
assert.equal(h.currentBet, 75);
assert.equal(h.toAct, btn);
assert.equal(h.options(btn).canRaise, false); // コールかフォールドのみ
assert.equal(t.act(tk(t, btn), 'raise', 200), 'レイズできません');
assert.equal(t.act(tk(t, btn), 'call', 0), null);
assert.equal(t.act(tk(t, sb), 'call', 0), null);
assert.equal(h.street, 'FLOP');
});
test('3人オールイン: すぐショーダウンになり、サイドポットと返金', () => {
const t = makeTable([100, 300, 500]);
t.start(T(0), 0);
const h = t.hand;
for (let guard = 0; guard < 10 && h.toAct != null; guard++) {
const o = h.options(h.toAct);
assert.equal(t.act(tk(t, h.toAct), o.canRaise ? 'raise' : 'call', o.canRaise ? o.maxRaiseTo : 0), null);
}
assert.equal(h.street, 'SHOWDOWN');
// 席2 の超過 200 は返金済み。メイン 300(全員)、サイド 400(席1・席2)
assert.equal(t.seats[2].stack, 200);
assert.deepEqual(
h.view().pots.map((p) => [p.amount, p.eligible.slice().sort()]),
[[300, [0, 1, 2]], [400, [1, 2]]]
);
// 席0 がメイン、席1 がサイドを獲得
assert.equal(t.award(T(0), [[0], [1]]), null);
assert.ok(h.finished && h.showdown);
assert.equal(t.seats[0].stack, 300);
assert.equal(t.seats[1].stack, 400);
assert.equal(t.seats[2].stack, 200);
});
test('勝者の指定: 山分け(端数はボタンの左から)と不正な指定の拒否', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
// SB をフォールドさせて、BB とボタンで 50 のポットを争う(SB の 10 + 20 + 20)
assert.equal(t.act(tk(t, btn), 'call', 0), null);
assert.equal(t.act(tk(t, sb), 'fold', 0), null);
assert.equal(t.act(tk(t, bb), 'check', 0), null);
checkDown(t);
assert.equal(h.street, 'SHOWDOWN');
t.hostToken = T(7); // ホストの特例を除いて確認する
assert.equal(t.award(tk(t, sb), [[bb]]), 'ショーダウンに残った人かホストが選んでください');
assert.ok(t.award(tk(t, bb), []));
assert.ok(t.award(tk(t, bb), [[]]));
assert.ok(t.award(tk(t, bb), [[sb]])); // フォールドした人は勝てない
assert.ok(t.award(tk(t, bb), [[bb, bb]]));
assert.ok(t.award(tk(t, bb), [[bb], [btn]])); // ポットは1つ
assert.ok(t.award(T(8), [[bb]])); // 着席していない
assert.ok(!h.finished);
assert.equal(t.award(tk(t, bb), [[bb, btn]]), null);
// 50 を2人で → 25 ずつ
assert.equal(t.seats[bb].stack, 1005);
assert.equal(t.seats[btn].stack, 1005);
assert.equal(t.award(tk(t, bb), [[bb]]), 'ショーダウンではありません');
});
test('端数はボタンの左から配る', () => {
const t = makeTable([1000, 1000, 1000], { smallBlind: 5, bigBlind: 10 });
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
t.act(tk(t, btn), 'call', 0);
t.act(tk(t, sb), 'fold', 0);
t.act(tk(t, bb), 'check', 0);
checkDown(t);
// 25 を2人で → ボタンの左に近い BB が 13、ボタンが 12
assert.equal(t.award(T(0), [[btn, bb]]), null);
assert.equal(t.seats[bb].stack, 990 + 13);
assert.equal(t.seats[btn].stack, 990 + 12);
});
test('ホストはショーダウンに参加していなくても勝者を選べる', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
// ホスト(席0)だけフォールドさせる
for (let guard = 0; guard < 50 && h.toAct != null; guard++) {
const o = h.options(h.toAct);
t.act(tk(t, h.toAct), h.toAct === 0 ? 'fold' : o.canCheck ? 'check' : 'call', 0);
}
assert.equal(h.street, 'SHOWDOWN');
const other = h.live().map((p) => p.seat);
assert.equal(t.canAward(T(0)), true);
assert.equal(t.award(T(0), [[other[0]]]), null);
assert.ok(h.finished);
});
test('ショーダウン中に1人を残して退席したら残った人が勝つ', () => {
const t = makeTable([1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
checkDown(t);
assert.equal(h.street, 'SHOWDOWN');
const [a, b] = h.order;
t.leave(tk(t, a));
assert.ok(h.finished && !h.showdown);
assert.equal(t.seats[b].stack, 1020);
});
test('離席中の人の手番は自動でチェック/フォールド、次のハンドから外れる', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const first = h.toAct;
assert.equal(t.setSittingOut(tk(t, first), true), null);
assert.ok(h.players.get(first).folded);
assert.notEqual(h.toAct, first);
t.act(tk(t, h.toAct), 'fold', 0); // 残り1人で終了
assert.ok(h.finished);
t.tick(10 ** 6);
t.tick(10 ** 7);
assert.equal(t.hand.number, 2);
assert.ok(!t.hand.players.has(first));
assert.equal(t.setSittingOut(tk(t, first), 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(tk(t, h.toAct), 'fold', 0), '一時停止中です');
t.togglePause(T(0), 2000);
checkDown(t);
t.togglePause(T(0), 3000);
assert.equal(t.award(T(0), [[h.order[0]]]), '一時停止中です');
t.togglePause(T(0), 4000);
assert.equal(t.award(T(0), [[h.order[0]]]), null);
t.togglePause(T(0), 5000);
t.tick(10 ** 7);
t.tick(10 ** 8);
assert.equal(t.hand.number, 1); // 止まっている
t.togglePause(T(0), 10 ** 8);
t.tick(10 ** 8 + 10 ** 5);
t.tick(10 ** 8 + 10 ** 6);
assert.equal(t.hand.number, 2);
});
test('ハンド中の退席: フォールド扱いで席はハンド終了まで予約', () => {
const t = makeTable([1000, 1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
t.act(tk(t, btn), 'call', 0);
assert.ok(t.leave(tk(t, sb))); // 手番の SB が退席
assert.ok(h.players.get(sb).folded);
assert.ok(t.seats[sb].left);
assert.equal(t.playerCount, 2);
// 新しく来た人は予約席には座らない
assert.notEqual(t.join(T(9), 'new'), sb);
assert.equal(t.act(tk(t, bb), 'check', 0), null);
assert.equal(h.street, 'FLOP');
});
test('2人のうち片方が退席したら残った人が勝つ(BB は返らない)', () => {
const t = makeTable([1000, 1000]);
t.start(T(0), 0);
const h = t.hand;
const stay = h.toAct; // SB(ボタン)
const other = h.order.find((s) => s !== stay);
t.leave(tk(t, other));
assert.ok(h.finished);
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(tk(t, notTurn), 'fold', 0), 'あなたの番ではありません');
const me = tk(t, h.toAct);
assert.ok(t.act(me, 'raise', 10 ** 9));
assert.ok(t.act(me, 'raise', 40.5));
assert.ok(t.act(me, 'check', 0)); // BB に対してチェックはできない
assert.ok(t.act(T(8), 'fold', 0)); // 着席していない
});
test('リバイ', () => {
const t = makeTable([1000, 1000]);
t.seats[1].stack = 0;
assert.equal(t.rebuy(tk(t, 0)), 'チップが残っています');
assert.equal(t.rebuy(tk(t, 1)), null);
assert.equal(t.seats[1].stack, 1000);
assert.equal(t.seats[1].buyIns, 2);
});
test('ランダムに遊んでもチップの合計が変わらず、必ず終わる', () => {
let rnd = 12345;
const rand = (n) => {
rnd = (rnd * 1103515245 + 12345) % 2147483648;
return rnd % n;
};
let showdowns = 0;
let sidePots = 0;
for (let game = 0; game < 60; game++) {
const n = 2 + (game % 8);
const stacks = Array.from({ length: n }, () => 20 + rand(2000));
const t = makeTable(stacks);
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++) {
const h = t.hand;
if (!h.finished && h.toAct != null) {
const o = h.options(h.toAct);
const r = rand(10);
const me = tk(t, h.toAct);
let err;
if (r < 2) err = t.act(me, 'fold', 0);
else if (r < 6 || !o.canRaise) err = t.act(me, o.canCheck ? 'check' : 'call', 0);
else err = t.act(me, 'raise', o.minRaiseTo + rand(o.maxRaiseTo - o.minRaiseTo + 1));
assert.equal(err, null);
} else if (h.awaitingWinners) {
const pots = h.view().pots;
showdowns++;
if (pots.length > 1) sidePots++;
const winners = pots.map((p) => {
const w = p.eligible.filter(() => rand(3) === 0);
return w.length ? w : [p.eligible[rand(p.eligible.length)]];
});
assert.equal(t.award(T(0), winners), null);
} else {
t.tick((now += 10 ** 5));
}
for (const s of t.seats) if (s) assert.ok(s.stack >= 0);
const inPot = t.hand && !t.hand.finished ? t.hand.view().potTotal : 0;
assert.equal(t.seats.reduce((a, s) => a + (s ? s.stack : 0), 0) + inPot, sum);
if (t.hand && t.hand.number > 40) break;
}
}
assert.ok(showdowns > 100 && sidePots > 20, `showdowns=${showdowns} sidePots=${sidePots}`);
});