Compare commits

...
4 Commits
Author SHA1 Message Date
agomizi1cmandClaude Opus 5.5 d92953a270 Use @pokertools/engine and evaluator for poker rules and hand ranking
Replace the hand-rolled betting rules, side pots, showdown and hand
evaluator with the published @pokertools/engine and @pokertools/evaluator
libraries (MIT, pinned to 2.1.0).

- server/hand.js now wraps a PokerEngine per hand: it maps seats,
  mirrors stacks, staggers the all-in runout, and pays host-chosen
  winners on cash-only tables.
- server/cards.js and server/ai.js use the library evaluator.
- Out-of-turn folds go through the engine's stand; all-in hands stay
  live when the player leaves; uncalled bets return to a leaver.
- The engine refuses some check-able folds that would leave a side pot
  without eligible players; those now return a message (or check for
  a leaving player) instead of crashing.
- BB must be greater than SB (engine requirement); Node >= 24.
- Tests rig cards via engine snapshots and cover the new edge cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 17:25:15 +09:00
agomizi1cmandClaude Opus 5.5 02c8e76237 Close CPU tables as soon as every human player leaves
- When the last human presses leave on a CPU table (even mid-hand), the table
  is deleted right away instead of lingering with CPUs only; friends / cash-only
  tables keep the existing 30-minute idle cleanup
- Spectators still watching get a "テーブルが終了しました" notice, and the lobby
  updates immediately
- Don't show the "接続が切れました" banner when the page disconnects on purpose
  (closed or missing table)
- Test for the close condition; README notes the behavior

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 17:03:58 +09:00
agomizi1cmandClaude Opus 5.5 0d3a054f0d Add CPU opponents and a table type selector (cash only / friends / CPU)
- Create screen: choose キャッシュオンリー (real cards, chips only), 友人戦
  (server deals and settles) or CPU戦 (友人戦 plus 1–8 CPU players); replaces
  the card toggle. The lobby shows each table's type
- Poker AI written from scratch (server/ai.js, no libraries): fast 7-card
  evaluator (checked against bestHand), Monte Carlo equity, and decisions from
  hand rank, pot odds, raise count, opponents and a per-CPU style (aggression,
  bluff rate); continuation bets via the last aggressor. It never sees other
  players' hole cards
- CPU seats: think time of 0.7–1.8s (faster when no human is left in the hand),
  automatic rebuy, never the host, no new hand unless a human is playing,
  re-think after pause
- Play UI: robot avatars and a "考えています…" status for CPU turns
- Tests for the evaluator, equity, legality of AI actions and CPU tables

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:55:25 +09:00
agomizi1cmandClaude Opus 5.5 66907345ff Add optional card mode: server deals cards and settles showdowns automatically
- New "カードを配る" switch on the create-table screen (default off); the lobby
  shows "カードあり" for tables that use it
- Card mode (server/cards.js restored): crypto-shuffled deck kept server-side,
  hole cards sent only to their owner until showdown/all-in reveal, board dealt
  per street with burns, all-in runout on a timer (frozen while paused)
- Showdown is evaluated and every pot (incl. side pots, split pots) is paid out
  automatically; host winner selection is only used when card mode is off
- Play UI: board, hole cards, own cards in the action bar, hand names, winning
  cards highlighted; layout tuned for 7+ seats and short screens
- Playing-card styles use .pcard so they don't clash with the existing .card panel
- Tests for hand evaluation, card privacy, runout, side pots, ties and random play

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:44:22 +09:00
16 changed files with 1390 additions and 190 deletions

No files matched your search

+20 -8
View File
@@ -2,23 +2,33 @@
友達専用のテキサスホールデム(リングゲーム)サイト。Node.js + Express + Socket.IO。 友達専用のテキサスホールデム(リングゲーム)サイト。Node.js + Express + Socket.IO。
「鍵入力 → ロビー → テーブル作成 → プレイ」まで動く。 「鍵入力 → ロビー → テーブル作成 → プレイ」まで動く。Node.js 24 以上が必要(@pokertools/engine の要件)。
## ルール・仕様 ## ルール・仕様
カードは実物で配り、このサイトはチップの代わりに使う(ベット・ポット・スタックの管理)。 テーブル作成時に種類を選ぶ(既定はキャッシュオンリー)。
| 種類 | 内容 |
| --- | --- |
| キャッシュオンリー | カードは実物で配り、サイトはチップの代わりに使う(ベット・ポット・スタックの管理)。ショーダウンの勝者はホストが選ぶ |
| 友人戦 | 実物のカードがなくても遊べる。サイトがカードを配り、勝敗とポットの分配まで自動で判定する |
| CPU戦 | 友人戦に CPU プレイヤー(1〜8人)が加わる。空いている席には友達も参加できる |
- ポーカーのルール(ブラインド・手番・最低レイズ額・再レイズ権・返金・サイドポット・ショーダウンの判定と分配)と役の判定は、公開ライブラリ [@pokertools/engine](https://www.npmjs.com/package/@pokertools/engine) / [@pokertools/evaluator](https://www.npmjs.com/package/@pokertools/evaluator)(MIT、バージョン固定)に任せている。
- ノーリミット・テキサスホールデムのリングゲーム(最大9人)。ホストが START を押すと、以降は2人以上いる限り自動でハンドが続く。 - ノーリミット・テキサスホールデムのリングゲーム(最大9人)。ホストが START を押すと、以降は2人以上いる限り自動でハンドが続く。
- 画面にディーラーボタン(D)・SB・BB と、いまのストリート(PREFLOP / FLOP / TURN / RIVER)が出るので、それに合わせて実物のカードを配る。 - 画面にディーラーボタン(D)・SB・BB と、いまのストリート(PREFLOP / FLOP / TURN / RIVER)が出るので、それに合わせて実物のカードを配る。
- ブラインドは自動で支払われ、ハンド開始時のレベルで固定。ヘッズアップはボタンが SB。 - ブラインドは自動で支払われ、ハンド開始時のレベルで固定。BB は SB より大きくする。ヘッズアップはボタンが SB。
- 各自が自分のスマホで Fold / Check / Call / Bet / Raise を行う。最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。 - 各自が自分のスマホで Fold / Check / Call / Bet / Raise を行う。最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。
- ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。 - ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。
- **ショーダウン**: カードを見せ合い、ホストが勝った人を画面で選んで確定する(ポットの分配はテーブルのホストだけが行える)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。 - **ショーダウン(キャッシュオンリー)**: カードを見せ合い、ホストが勝った人を画面で選んで確定する(ポットの分配はテーブルのホストだけが行える)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。
- **カードを配るテーブル(友人戦・CPU戦)**: 各自のスマホに自分の手札だけが表示され、場札はストリートごとに画面に配られる。ショーダウンでは残った人の手札を公開して役を判定し、ポット(サイドポット含む)を自動で分配する。引き分けは山分け(端数はボタンの左から)。全員オールインになったら手札を公開し、残りの場札を順にめくる。山札はエンジンが暗号論的乱数(Node.js の crypto)でシャッフルし、サーバの外に出さない(他人の手札は公開されるまで送らない)。
- **CPU**: 自前実装(`server/ai.js`。役の強さだけ @pokertools/evaluator を使う)。自分の手札と場札から、残っている相手に勝つ確率をモンテカルロ法で見積もり、ポットオッズ・レイズの回数・相手の人数から行動を決める。CPU ごとに攻撃性・ブラフ頻度がランダムに違う。相手の手札は見ない。1手ごとに 0.7〜1.8 秒考える。チップがなくなると次のハンドで自動でリバイする。人間が1人も参加していないと次のハンドは始まらない。CPU はホストにならない。人間が全員「退席」するとテーブルはすぐに削除される(ブラウザを閉じただけの場合は、ほかのテーブルと同じく誰も接続していない状態が30分続いたら削除)。
- 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。 - 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。
- 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。 - 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。
- チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。 - チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。
- ハンド中に退席するとフォールド扱い(出したチップはポットに残る)。 - ハンド中に退席するとフォールド扱い(出したチップはポットに残る。ただし誰もコールしていない分は返る)。オールインしている人の手は退席しても最後まで生きている。
- ホストの一時停止中は、アクション・勝者の確定・ブラインドタイマー・次のハンドの開始がすべて止まる。 - チェックできるのに降りるとサイドポットの対象者がいなくなる場合、エンジンが受け付けないので「チェックしてください」と出る(退席のときは自動でチェックになる)。
- ホストの一時停止中は、アクション・勝者の確定・オールイン後の場札・ブラインドタイマー・次のハンドの開始がすべて止まる。
## ローカルで動かす ## ローカルで動かす
@@ -71,8 +81,10 @@ 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/hand.js` | 1ハンドの進行。ルールは @pokertools/engine に任せ、テーブルとの橋渡し(席番号・スタック・退席・離席)、オールイン後に場札を順にめくる表示、キャッシュオンリーでホストが選んだ勝者への分配を行う |
| `test/` | チップ処理のテスト(`npm test`) | | `server/cards.js` | 役の名前と最強の5枚(@pokertools/evaluator) |
| `server/ai.js` | CPU の思考(勝率の見積もり・行動の決定) |
| `test/` | チップ処理・役の判定・CPU のテスト(`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` | 各画面 |
+52
View File
@@ -8,6 +8,8 @@
"name": "friends-holdem", "name": "friends-holdem",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@pokertools/engine": "2.1.0",
"@pokertools/evaluator": "2.1.0",
"express": "^4.22.3", "express": "^4.22.3",
"socket.io": "^4.8.4" "socket.io": "^4.8.4"
}, },
@@ -15,6 +17,47 @@
"node": ">=18" "node": ">=18"
} }
}, },
"node_modules/@pokertools/engine": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@pokertools/engine/-/engine-2.1.0.tgz",
"integrity": "sha512-/3kXKpFf6nHygWQuX1AMu8yQa6HW9RhLW7TkOZJnXSESJ/vs00YWs976F2zNzqnlBPK90LvRSw4ZyqwK+9Ajow==",
"license": "MIT",
"dependencies": {
"@pokertools/evaluator": "2.1.0",
"@pokertools/types": "2.1.0"
},
"engines": {
"node": "^24.15.0 || >=26.0.0",
"npm": ">=12.2.0"
},
"peerDependencies": {
"@pokertools/evaluator": "2.1.0",
"@pokertools/types": "2.1.0"
}
},
"node_modules/@pokertools/evaluator": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@pokertools/evaluator/-/evaluator-2.1.0.tgz",
"integrity": "sha512-9ZmmwrA9g2IvKST2y0HrdiwTGIM6uoMoom9fXq0ZfQHGcd24X5ydQJi3S5ciR/LFjSN4T2EakwXqVED6tuWD+w==",
"license": "MIT",
"engines": {
"node": "^24.15.0 || >=26.0.0",
"npm": ">=12.2.0"
}
},
"node_modules/@pokertools/types": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@pokertools/types/-/types-2.1.0.tgz",
"integrity": "sha512-FBKLd3cczFfHQAH4DY0n+VEcdccEW7C5wa4PaAA/jaBvmYo0OU7PBHduPEhcO3ZpWBAr3KjW1ESzaajhlvTzCw==",
"license": "MIT",
"dependencies": {
"zod": "^4.6.5"
},
"engines": {
"node": "^24.15.0 || >=26.0.0",
"npm": ">=12.2.0"
}
},
"node_modules/@socket.io/component-emitter": { "node_modules/@socket.io/component-emitter": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
@@ -1078,6 +1121,15 @@
"optional": true "optional": true
} }
} }
},
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
} }
} }
} }
+3 -1
View File
@@ -10,9 +10,11 @@
"test": "node --test" "test": "node --test"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=24"
}, },
"dependencies": { "dependencies": {
"@pokertools/engine": "2.1.0",
"@pokertools/evaluator": "2.1.0",
"express": "^4.22.3", "express": "^4.22.3",
"socket.io": "^4.8.4" "socket.io": "^4.8.4"
} }
+21 -2
View File
@@ -16,6 +16,8 @@
const timerInput = $('timer'); const timerInput = $('timer');
const intervalInput = $('interval'); const intervalInput = $('interval');
const scheduleEl = $('schedule'); const scheduleEl = $('schedule');
const modeHint = $('mode-hint');
const cpuOptions = $('cpu-options');
const blindHint = $('blind-hint'); const blindHint = $('blind-hint');
const errorEl = $('error'); const errorEl = $('error');
const submitBtn = $('submit'); const submitBtn = $('submit');
@@ -58,7 +60,7 @@
const bb = int(bbInput); const bb = int(bbInput);
const on = timerInput.checked; const on = timerInput.checked;
intervalInput.disabled = !on; intervalInput.disabled = !on;
scheduleEl.hidden = !on || !(sb > 0 && bb >= sb); scheduleEl.hidden = !on || !(sb > 0 && bb > sb);
if (scheduleEl.hidden) return; if (scheduleEl.hidden) return;
const mins = int(intervalInput) > 0 ? int(intervalInput) : 0; const mins = int(intervalInput) > 0 ? int(intervalInput) : 0;
scheduleEl.innerHTML = Blinds.schedule(sb, bb, 8) scheduleEl.innerHTML = Blinds.schedule(sb, bb, 8)
@@ -66,9 +68,23 @@
.join(''); .join('');
} }
const MODE_HINTS = {
chips: '実物のカードで遊び、サイトはチップだけを管理。ショーダウンの勝者はホストが選ぶ',
friends: '各自のスマホに手札が配られ、勝敗とポットの分配は自動',
cpu: 'CPU と対戦(友達も空いている席に参加できる)。カードの配布・勝敗の判定は自動',
};
const radioValue = (name) => (form.querySelector(`input[name="${name}"]:checked`) || {}).value;
function updateMode() {
const mode = radioValue('mode');
modeHint.textContent = MODE_HINTS[mode] || '';
cpuOptions.hidden = mode !== 'cpu';
}
function refresh() { function refresh() {
updateHint(); updateHint();
updateSchedule(); updateSchedule();
updateMode();
} }
stackInput.addEventListener('input', () => { stackInput.addEventListener('input', () => {
@@ -91,6 +107,7 @@
}); });
timerInput.addEventListener('change', refresh); timerInput.addEventListener('change', refresh);
intervalInput.addEventListener('input', refresh); intervalInput.addEventListener('input', refresh);
form.querySelectorAll('input[type="radio"]').forEach((el) => el.addEventListener('change', refresh));
$('reroll').addEventListener('click', suggestName); $('reroll').addEventListener('click', suggestName);
function validate() { function validate() {
@@ -102,7 +119,7 @@
if (!name) return [nameInput, 'テーブル名を入力してください']; if (!name) return [nameInput, 'テーブル名を入力してください'];
if (!(stack >= 10)) return [stackInput, '開始スタックは10以上の整数にしてください']; if (!(stack >= 10)) return [stackInput, '開始スタックは10以上の整数にしてください'];
if (!(sb >= 1)) return [sbInput, 'SBは1以上の整数にしてください']; if (!(sb >= 1)) return [sbInput, 'SBは1以上の整数にしてください'];
if (!(bb >= sb)) return [bbInput, 'BBはSB以上にしてください']; if (!(bb > sb)) return [bbInput, 'BBはSBより大きくしてください'];
if (bb > stack) return [bbInput, 'BBが開始スタックより大きいです']; if (bb > stack) return [bbInput, 'BBが開始スタックより大きいです'];
if (timerInput.checked && !(interval >= 1 && interval <= 240)) return [intervalInput, 'インターバルは1〜240分にしてください']; if (timerInput.checked && !(interval >= 1 && interval <= 240)) return [intervalInput, 'インターバルは1〜240分にしてください'];
return null; return null;
@@ -128,6 +145,8 @@
bigBlind: int(bbInput), bigBlind: int(bbInput),
blindTimerEnabled: timerInput.checked, blindTimerEnabled: timerInput.checked,
blindIntervalMin: int(intervalInput), blindIntervalMin: int(intervalInput),
mode: radioValue('mode'),
cpuCount: Number(radioValue('cpu-count')),
token: Store.token, token: Store.token,
}); });
location.href = '/table/' + encodeURIComponent(id); location.href = '/table/' + encodeURIComponent(id);
+3
View File
@@ -36,6 +36,8 @@
if (btn && requireName()) location.href = '/table/' + encodeURIComponent(btn.dataset.join); if (btn && requireName()) location.href = '/table/' + encodeURIComponent(btn.dataset.join);
}); });
const MODE_LABEL = { chips: '💰 キャッシュオンリー', friends: '🃏 友人戦', cpu: '🤖 CPU戦' };
function phaseBadge(t) { function phaseBadge(t) {
if (t.paused) return '<span class="badge paused">PAUSED</span>'; if (t.paused) return '<span class="badge paused">PAUSED</span>';
if (t.phase === 'WAITING') return '<span class="badge">WAITING</span>'; if (t.phase === 'WAITING') return '<span class="badge">WAITING</span>';
@@ -61,6 +63,7 @@
<span>開始 <b>${chips(t.startingStack)}</b></span> <span>開始 <b>${chips(t.startingStack)}</b></span>
<span class="gold">Lv.${t.level} <b class="gold">${chips(t.smallBlind)}/${chips(t.bigBlind)}</b></span> <span class="gold">Lv.${t.level} <b class="gold">${chips(t.smallBlind)}/${chips(t.bigBlind)}</b></span>
<span>${timer}</span> <span>${timer}</span>
<span>${MODE_LABEL[t.mode] || ''}</span>
</div> </div>
</div> </div>
<button class="btn btn-blue btn-sm" data-join="${esc(t.id)}" ${full ? 'title="満席(観戦のみ)"' : ''}> <button class="btn btn-blue btn-sm" data-join="${esc(t.id)}" ${full ? 'title="満席(観戦のみ)"' : ''}>
+112
View File
@@ -255,6 +255,29 @@ input.invalid { border-color: var(--red); }
.switch input:checked + span::before { transform: translateX(22px); background: #fff; } .switch input:checked + span::before { transform: translateX(22px); background: #fff; }
.switch input:focus-visible + span { outline: 2px solid var(--gold); } .switch input:focus-visible + span { outline: 2px solid var(--gold); }
/* 選択肢を横に並べたラジオボタン(テーブルの種類・CPU の人数) */
.segmented { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 6px; }
.segmented label { margin: 0; display: block; color: var(--text); }
.segmented input { position: absolute; opacity: 0; width: 0; height: 0; }
.segmented span {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
min-height: 52px;
padding: 6px 4px;
border-radius: 12px;
background: var(--input);
border: 2px solid transparent;
font-weight: 800;
font-size: 14px;
line-height: 1.2;
cursor: pointer;
}
.segmented input:checked + span { background: rgba(246, 199, 68, 0.15); border-color: var(--gold); color: var(--gold); }
.segmented input:focus-visible + span { outline: 2px solid var(--gold); outline-offset: 2px; }
.segmented.numbers span { min-height: 40px; font-size: 15px; }
.unit-input { position: relative; } .unit-input { position: relative; }
.unit-input input { padding-right: 56px; } .unit-input input { padding-right: 56px; }
.unit-input .unit { .unit-input .unit {
@@ -400,6 +423,7 @@ body.table-page {
} }
.avatar svg { width: 28px; height: 28px; fill: #fff; } .avatar svg { width: 28px; height: 28px; fill: #fff; }
.seat.me .avatar { background: #d35400; border-color: var(--gold); } .seat.me .avatar { background: #d35400; border-color: var(--gold); }
.seat.bot .avatar { background: #3d4a6b; border-color: #8fa2d6; }
.seat.offline .avatar { opacity: 0.45; } .seat.offline .avatar { opacity: 0.45; }
.nameplate { .nameplate {
margin-top: -10px; margin-top: -10px;
@@ -532,6 +556,71 @@ body.table-page {
z-index: 30; z-index: 30;
} }
/* ---------- カード(カード機能ありのテーブル) ---------- */
.pcard {
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;
}
.pcard b { font-size: 15px; letter-spacing: -0.05em; }
.pcard 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; }
.pcard.back {
background: repeating-linear-gradient(45deg, #c0392b 0 3px, #a93226 3px 6px);
border: 2px solid #fff;
}
.pcard.slot { background: rgba(0, 0, 0, 0.12); box-shadow: none; border: 1px dashed rgba(255, 255, 255, 0.3); }
.pcard.deal { animation: deal 0.35s ease-out both; }
@keyframes deal {
from { opacity: 0; transform: translateY(-10px) scale(0.8); }
}
.pcard.dim { filter: brightness(0.5); }
.pcard.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: 6px; min-height: 40px; }
.hole {
position: absolute;
top: -18px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 2px;
z-index: 1;
}
.hole .pcard { width: 25px; height: 35px; border-radius: 4px; }
.hole .pcard b { font-size: 13px; }
.hole .pcard i { font-size: 11px; }
.hole .pcard.back { border-width: 1.5px; }
/* 手札と重ならないよう D・SB/BB を横に出す */
.with-cards .chip-marker.dealer { top: 22px; right: -16px; }
.with-cards .blind-marker { top: 26px; left: -20px; }
.felt-area.with-cards { margin-top: 62px; }
.with-cards .bet.above { bottom: calc(100% + 20px); }
.crowded.with-cards .bet.above { bottom: calc(100% + 14px); }
.nameplate .phand {
font-size: 10px;
font-weight: 700;
color: var(--gold);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* ---------- 席の状態 ---------- */ /* ---------- 席の状態 ---------- */
.seat.folded .avatar, .seat.folded .nameplate { opacity: 0.45; } .seat.folded .avatar, .seat.folded .nameplate { opacity: 0.45; }
.seat.away .avatar { opacity: 0.4; } .seat.away .avatar { opacity: 0.4; }
@@ -615,10 +704,21 @@ body.table-page {
.crowded .nameplate { min-width: 72px; max-width: 80px; padding: 3px 6px; } .crowded .nameplate { min-width: 72px; max-width: 80px; padding: 3px 6px; }
.crowded .nameplate .pname { font-size: 11px; } .crowded .nameplate .pname { font-size: 11px; }
.crowded .nameplate .pstack { font-size: 12px; } .crowded .nameplate .pstack { font-size: 12px; }
.crowded .hole { top: -12px; }
.crowded .hole .pcard { width: 20px; height: 28px; }
.crowded .hole .pcard b { font-size: 11px; }
.crowded .hole .pcard i { font-size: 9px; }
.crowded.with-cards .chip-marker.dealer { top: 14px; }
.crowded.with-cards .blind-marker { top: 18px; }
/* ---------- 自分の操作エリア ---------- */ /* ---------- 自分の操作エリア ---------- */
.me-row { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; } .me-row { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; }
.me-info { flex: 1; min-width: 0; } .me-info { flex: 1; min-width: 0; }
.my-cards { display: flex; gap: 4px; flex: none; }
.my-cards .pcard { width: 42px; height: 58px; border-radius: 6px; }
.my-cards .pcard b { font-size: 22px; }
.my-cards .pcard i { font-size: 19px; }
.me-sub .my-hand { color: var(--gold); font-weight: 800; }
.me-sub { font-size: 12px; color: var(--muted); display: flex; gap: 8px; margin-top: 3px; white-space: nowrap; } .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 .my-bet { color: var(--gold); font-weight: 700; }
.me-sub .plus { color: var(--green); } .me-sub .plus { color: var(--green); }
@@ -664,6 +764,18 @@ body.table-page {
.crowded .nameplate .pname { font-size: 10px; } .crowded .nameplate .pname { font-size: 10px; }
.crowded .nameplate .pstack { font-size: 11px; } .crowded .nameplate .pstack { font-size: 11px; }
.crowded .chip-marker { width: 20px; height: 20px; font-size: 10px; } .crowded .chip-marker { width: 20px; height: 20px; font-size: 10px; }
.felt-area.with-cards { margin-top: 52px; }
.board .pcard { width: 24px; height: 34px; }
.board .pcard b { font-size: 13px; }
.board .pcard i { font-size: 11px; }
.board { min-height: 34px; margin-top: 4px; }
.my-cards .pcard { width: 34px; height: 48px; }
.my-cards .pcard b { font-size: 18px; }
.my-cards .pcard i { font-size: 15px; }
.crowded .hole { top: -10px; }
.crowded .hole .pcard { width: 17px; height: 24px; }
.crowded .hole .pcard b { font-size: 10px; }
.crowded .hole .pcard i { font-size: 8px; }
} }
[hidden] { display: none !important; } [hidden] { display: none !important; }
+96 -6
View File
@@ -1,5 +1,5 @@
// プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る // プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る
// カードは実物で配るので、ここで扱うのはチップのやり取りだけ // カード機能がオフのテーブルではカードは実物で配るので、ここで扱うのはチップのやり取りだけ
(function () { (function () {
'use strict'; 'use strict';
@@ -9,6 +9,10 @@
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 BOT_SVG =
'<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="11" y="1.5" width="2" height="3.5" rx="1"/><circle cx="12" cy="1.8" r="1.6"/><path d="M5 7.5A2.5 2.5 0 0 1 7.5 5h9A2.5 2.5 0 0 1 19 7.5v7a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 5 14.5zM9 9.2a1.6 1.6 0 1 0 0 3.2 1.6 1.6 0 0 0 0-3.2zm6 0a1.6 1.6 0 1 0 0 3.2 1.6 1.6 0 0 0 0-3.2zM2 9.5h2v4H2zm18 0h2v4h-2zM7 18.5h10a3 3 0 0 1 3 3V23H4v-1.5a3 3 0 0 1 3-3z"/></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' }; const ACTION_LABEL = { FOLD: 'Fold', CHECK: 'Check', CALL: 'Call', BET: 'Bet', RAISE: 'Raise', ALLIN: 'All-in' };
let socket = null; let socket = null;
@@ -18,6 +22,8 @@
let raising = false; let raising = false;
let raiseValue = 0; let raiseValue = 0;
let wasMyTurn = false; let wasMyTurn = false;
let seenBoard = ''; // 新しくめくられたカードだけアニメーションする
let seenHand = 0;
// ショーダウンの勝者選択(ポットごとの席番号の Set) // ショーダウンの勝者選択(ポットごとの席番号の Set)
let awardKey = ''; let awardKey = '';
let awardSel = []; let awardSel = [];
@@ -46,6 +52,7 @@
}); });
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:closed', () => showNotFound(true));
socket.on('table:state', (s) => { socket.on('table:state', (s) => {
state = s; state = s;
pending = false; pending = false;
@@ -84,15 +91,65 @@
render(); render();
} }
function showNotFound() { // closed: プレイヤーが全員退席してテーブルが閉じられた
function showNotFound(closed) {
if (closed) {
$('not-found-title').textContent = 'テーブルが終了しました';
$('not-found-text').textContent = 'プレイヤーが全員退席したため、テーブルを閉じました。';
}
$('main').hidden = true; $('main').hidden = true;
$('action-bar').hidden = true; $('action-bar').hidden = true;
$('not-found').hidden = false; $('not-found').hidden = false;
if (socket) socket.disconnect(); // 自分から切断するので「接続が切れました」は出さない
if (socket) {
socket.off('disconnect');
socket.off('connect_error');
socket.disconnect();
}
$('conn-lost').hidden = true;
} }
const nameOf = (seat) => (state.seats[seat] ? state.seats[seat].name : '退席者'); const nameOf = (seat) => (state.seats[seat] ? state.seats[seat].name : '退席者');
// ---------- カード(カード機能ありのテーブルのみ) ----------
function cardHtml(c, extra = '') {
if (typeof c !== 'string' || !/^[2-9TJQKA][shdc]$/.test(c)) return `<span class="pcard back ${extra}"></span>`;
const rank = c[0] === 'T' ? '10' : c[0];
return `<span class="pcard suit-${c[1]} ${extra}"><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] && h.results[0].bestCards
? new Set(h.results[0].bestCards)
: null;
}
function renderBoard(s) {
const el = $('board');
const h = s.hand;
el.hidden = !s.cardsEnabled;
if (!s.cardsEnabled) return;
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="pcard slot"></span>';
continue;
}
const cls = [i >= oldLen ? 'deal' : '', best ? (best.has(c) ? 'hl' : 'dim') : ''].join(' ');
html += cardHtml(c, cls);
}
el.innerHTML = html;
}
// ---------- 描画 ---------- // ---------- 描画 ----------
function render() { function render() {
const s = state; const s = state;
@@ -117,6 +174,7 @@
$('phase').parentElement.classList.toggle('paused', s.paused); $('phase').parentElement.classList.toggle('paused', s.paused);
$('phase').parentElement.classList.toggle('showdown', s.phase === 'SHOWDOWN' && !s.paused); $('phase').parentElement.classList.toggle('showdown', s.phase === 'SHOWDOWN' && !s.paused);
$('hand-no').textContent = s.handNumber ? `#${s.handNumber}` : ''; $('hand-no').textContent = s.handNumber ? `#${s.handNumber}` : '';
renderBoard(s);
renderResult(s); renderResult(s);
// ホスト操作 // ホスト操作
@@ -147,6 +205,10 @@
const tapped = !navigator.userActivation || navigator.userActivation.hasBeenActive; const tapped = !navigator.userActivation || navigator.userActivation.hasBeenActive;
if (myTurn && !wasMyTurn && navigator.vibrate && tapped) navigator.vibrate(80); if (myTurn && !wasMyTurn && navigator.vibrate && tapped) navigator.vibrate(80);
wasMyTurn = myTurn; wasMyTurn = myTurn;
if (h) {
seenBoard = `${h.number}:${h.board.length}`;
seenHand = h.number;
}
} }
function renderResult(s) { function renderResult(s) {
@@ -160,7 +222,8 @@
.map((r, i) => { .map((r, i) => {
const label = h.results.length > 1 ? `<span class="pot-tag">${i === 0 ? 'メイン' : 'サイド'}</span>` : ''; const label = h.results.length > 1 ? `<span class="pot-tag">${i === 0 ? 'メイン' : 'サイド'}</span>` : '';
const who = r.winners.map((w) => esc(nameOf(w))).join('・'); const who = r.winners.map((w) => esc(nameOf(w))).join('・');
return `<div>${label}<b>${who}</b> +${chips(r.amount)}</div>`; const hand = r.handName ? ` <span class="rhand">${esc(r.handName)}</span>` : '';
return `<div>${label}<b>${who}</b> +${chips(r.amount)}${hand}</div>`;
}) })
.join(''); .join('');
el.hidden = false; el.hidden = false;
@@ -176,13 +239,16 @@
const angles = ordered.map((_, i) => Math.PI / 2 + (i * 2 * Math.PI) / Math.max(n, 1)); const angles = ordered.map((_, i) => Math.PI / 2 + (i * 2 * Math.PI) / Math.max(n, 1));
const showdown = s.phase === 'SHOWDOWN'; const showdown = s.phase === 'SHOWDOWN';
const finished = Boolean(h && h.finished); const finished = Boolean(h && h.finished);
const best = winningCards(h);
const container = $('seats'); const container = $('seats');
$('felt-area').classList.toggle('crowded', n >= 7); // 7人以上は小さめに表示 $('felt-area').classList.toggle('crowded', n >= 7); // 7人以上は小さめに表示
$('felt-area').classList.toggle('with-cards', s.cardsEnabled);
container.innerHTML = ordered container.innerHTML = ordered
.map((p, idx) => { .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.bot) classes.push('bot');
if (!p.connected) classes.push('offline'); if (!p.connected) classes.push('offline');
if (p.inHand && p.folded) classes.push('folded'); if (p.inHand && p.folded) classes.push('folded');
if (s.toAct === p.seat) classes.push('turn'); if (s.toAct === p.seat) classes.push('turn');
@@ -198,6 +264,15 @@
].join('') ].join('')
: ''; : '';
// 手札(自分と公開された人は表、それ以外は裏)
let cards = '';
if (s.cardsEnabled && p.inHand && (!p.folded || p.cards)) {
const deal = h.number !== seenHand ? 'deal' : '';
const list = p.cards || [null, null];
const mark = (c) => (best && c ? (best.has(c) ? 'hl' : 'dim') : p.folded ? 'dim' : '');
cards = `<div class="hole">${list.map((c) => cardHtml(c, `${deal} ${mark(c)}`)).join('')}</div>`;
}
// ベット(中央寄り)・獲得額 // ベット(中央寄り)・獲得額
const below = Math.sin(angles[idx]) <= 0.35; const below = Math.sin(angles[idx]) <= 0.35;
let bet = ''; let bet = '';
@@ -213,11 +288,12 @@
return ` return `
<div class="${classes.join(' ')}"> <div class="${classes.join(' ')}">
<div class="avatar">${AVATAR_SVG}${markers}</div> <div class="avatar">${p.bot ? BOT_SVG : AVATAR_SVG}${markers}${cards}</div>
<div class="nameplate"> <div class="nameplate">
${tag} ${tag}
<div class="pname">${esc(p.name)}</div> <div class="pname">${esc(p.name)}</div>
<div class="pstack">${p.allIn && !finished ? 'ALL-IN' : chips(p.stack)}</div> <div class="pstack">${p.allIn && !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>'}
</div> </div>
${bet} ${bet}
@@ -242,6 +318,16 @@
$('my-net').textContent = `収支 ${net > 0 ? '+' : net < 0 ? '−' : '±'}${chips(Math.abs(net))}`; $('my-net').textContent = `収支 ${net > 0 ? '+' : net < 0 ? '−' : '±'}${chips(Math.abs(net))}`;
$('my-net').className = net > 0 ? 'plus' : net < 0 ? 'minus' : ''; $('my-net').className = net > 0 ? 'plus' : net < 0 ? 'minus' : '';
$('my-bet').textContent = seat.inHand && seat.bet > 0 ? `ベット中 ${chips(seat.bet)}` : ''; $('my-bet').textContent = seat.inHand && seat.bet > 0 ? `ベット中 ${chips(seat.bet)}` : '';
$('my-hand').textContent = (seat.inHand && seat.handName) || '';
$('my-cards').hidden = !s.cardsEnabled;
if (s.cardsEnabled) {
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="pcard slot"></span><span class="pcard slot"></span>';
}
$('sit-out').hidden = m.sittingOut; $('sit-out').hidden = m.sittingOut;
// 状況 // 状況
@@ -253,7 +339,11 @@
else if (m.canRebuy) status = 'チップがなくなりました'; else if (m.canRebuy) status = 'チップがなくなりました';
else if (o) status = o.canCheck ? 'あなたの番です' : `あなたの番です(コール ${chips(o.toCall)})`; else if (o) status = o.canCheck ? 'あなたの番です' : `あなたの番です(コール ${chips(o.toCall)})`;
else if (awaiting) status = m.canAward ? 'カードを見せ合って、勝った人を選んでください' : 'ホストが勝者を選んでいます'; else if (awaiting) status = m.canAward ? 'カードを見せ合って、勝った人を選んでください' : 'ホストが勝者を選んでいます';
else if (h && !h.finished && s.toAct != null) status = `${nameOf(s.toAct)} の番です`; else if (h && !h.finished && s.toAct != null) {
const actor = s.seats[s.toAct];
status = actor && actor.bot ? `${actor.name}(CPU)が考えています…` : `${nameOf(s.toAct)} の番です`;
}
else if (h && !h.finished && h.runout) status = 'オールイン — 残りのカードをめくります';
else if (h && !h.finished && !seat.inHand) status = '次のハンドから参加します'; else if (h && !h.finished && !seat.inHand) status = '次のハンドから参加します';
else if (h && h.finished) status = '次のハンドを準備中…'; else if (h && h.finished) status = '次のハンドを準備中…';
else if (!h) status = '参加者を待っています(2人以上で再開)'; else if (!h) status = '参加者を待っています(2人以上で再開)';
+22
View File
@@ -23,6 +23,28 @@
<button type="button" class="icon-btn" id="reroll" aria-label="別の名前にする">🎲</button> <button type="button" class="icon-btn" id="reroll" aria-label="別の名前にする">🎲</button>
</div> </div>
<div class="label" id="mode-label">テーブルの種類</div>
<div class="segmented" role="radiogroup" aria-labelledby="mode-label">
<label><input type="radio" name="mode" value="chips" checked><span>キャッシュ<br>オンリー</span></label>
<label><input type="radio" name="mode" value="friends"><span>友人戦</span></label>
<label><input type="radio" name="mode" value="cpu"><span>CPU戦</span></label>
</div>
<div class="hint" id="mode-hint"></div>
<div id="cpu-options" hidden>
<div class="label" id="cpu-label">CPU の人数</div>
<div class="segmented numbers" role="radiogroup" aria-labelledby="cpu-label">
<label><input type="radio" name="cpu-count" value="1"><span>1</span></label>
<label><input type="radio" name="cpu-count" value="2"><span>2</span></label>
<label><input type="radio" name="cpu-count" value="3"><span>3</span></label>
<label><input type="radio" name="cpu-count" value="4"><span>4</span></label>
<label><input type="radio" name="cpu-count" value="5" checked><span>5</span></label>
<label><input type="radio" name="cpu-count" value="6"><span>6</span></label>
<label><input type="radio" name="cpu-count" value="7"><span>7</span></label>
<label><input type="radio" name="cpu-count" value="8"><span>8</span></label>
</div>
</div>
<label for="stack">開始スタック</label> <label for="stack">開始スタック</label>
<input id="stack" type="number" inputmode="numeric" min="10" step="1" value="1000"> <input id="stack" type="number" inputmode="numeric" min="10" step="1" value="1000">
+5 -3
View File
@@ -38,6 +38,7 @@
<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="board" id="board" hidden></div>
<div class="phase"><span id="phase">WAITING</span><span class="hand-no" id="hand-no"></span></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 class="result" id="result" hidden></div>
</div> </div>
@@ -53,9 +54,10 @@
<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-row">
<div class="my-cards" id="my-cards" hidden></div>
<div class="me-info"> <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="me-sub"><span id="my-net"></span><span class="my-bet" id="my-bet"></span></div> <div class="me-sub"><span class="my-hand" id="my-hand"></span><span id="my-net"></span><span class="my-bet" id="my-bet"></span></div>
</div> </div>
<button class="btn btn-ghost btn-sm" id="sit-out" title="次のハンドから参加しません">離席</button> <button class="btn btn-ghost btn-sm" id="sit-out" title="次のハンドから参加しません">離席</button>
</div> </div>
@@ -98,8 +100,8 @@
</div> </div>
<div class="center-message" id="not-found" hidden> <div class="center-message" id="not-found" hidden>
<h2>テーブルが見つかりません</h2> <h2 id="not-found-title">テーブルが見つかりません</h2>
<p>終了したか、URLが間違っている可能性があります。</p> <p id="not-found-text">終了したか、URLが間違っている可能性があります。</p>
<a class="btn btn-blue" href="/">ロビーへ戻る</a> <a class="btn btn-blue" href="/">ロビーへ戻る</a>
</div> </div>
+139
View File
@@ -0,0 +1,139 @@
'use strict';
// CPU プレイヤーの思考。
// モンテカルロで「残っている相手に勝つ確率(エクイティ)」を見積もり、
// ポットオッズ・ポジション・その CPU の性格(攻撃性・ブラフ頻度)から行動を決める。
// 相手の手札は見ない(自分の手札と場札、公開されているベット状況だけを使う)。
const { evaluate, getCardCode } = require('@pokertools/evaluator');
// hole / board は "As" 形式。opponents 人のランダムな手札を相手にした勝率(引き分けは等分)
// 役の強さは @pokertools/evaluator で求める(スコアは小さいほど強い。カードは 0〜51 の整数)
function equity(hole, board, opponents, iterations, rng = Math.random) {
const mine = hole.map(getCardCode);
const known = board.map(getCardCode);
const used = new Set([...mine, ...known]);
const deck = [];
for (let c = 0; c < 52; c++) if (!used.has(c)) deck.push(c);
const needBoard = 5 - known.length;
const need = needBoard + opponents * 2;
let score = 0;
for (let it = 0; it < iterations; it++) {
// 必要な枚数だけ部分的にシャッフル
for (let i = 0; i < need; i++) {
const j = i + Math.floor(rng() * (deck.length - i));
const tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
const fullBoard = known.concat(deck.slice(0, needBoard));
const me = evaluate(mine.concat(fullBoard));
let ties = 0;
let lost = false;
for (let k = 0; k < opponents; k++) {
const o = needBoard + k * 2;
const v = evaluate([deck[o], deck[o + 1]].concat(fullBoard));
if (v < me) {
lost = true;
break;
}
if (v === me) ties++;
}
if (!lost) score += 1 / (ties + 1);
}
return score / iterations;
}
// CPU ごとの性格(作成時にランダムに決める)
function randomStyle(rng = Math.random) {
return {
aggression: 0.8 + rng() * 0.45, // 大きいほど積極的にベット・レイズする
bluff: 0.03 + rng() * 0.09, // 弱い手でベットする頻度
looseness: rng() * 0.08, // 大きいほど弱い手でもコールする
};
}
const DEFAULT_STYLE = { aggression: 1, bluff: 0.06, looseness: 0.04 };
// 手番の CPU の行動を決める。{ type, amount } を返す(hand.act にそのまま渡せる)
function decide(hand, seat, { style = DEFAULT_STYLE, rng = Math.random, iterations = 500 } = {}) {
const o = hand.options(seat);
if (!o) return null;
const p = hand.players.get(seat);
const stack = hand.seats[seat].stack;
const bb = hand.bb;
const preflop = hand.board.length === 0;
const opponents = hand.live().length - 1;
const pot = hand.potTotal;
const potOdds = o.toCall / (pot + o.toCall);
const raises = hand.raises || 0;
const aggr = style.aggression;
const raiseTo = (fraction) => {
// ポットの fraction 倍のレイズ。最低額〜オールインに収め、SB 単位に丸める
const unit = Math.max(1, hand.sb);
let to = hand.currentBet + Math.round(fraction * (pot + o.toCall));
to = Math.round(to / unit) * unit;
to = Math.min(o.maxRaiseTo, Math.max(o.minRaiseTo, to));
// 残りがわずかになるならオールイン
if (to - p.bet >= stack * 0.7) to = o.maxRaiseTo;
return { type: 'raise', amount: to };
};
const sizing = () => {
const r = rng();
return r < 0.4 ? 0.5 : r < 0.8 ? 0.75 : 1;
};
if (preflop) {
// プリフロップ: 1人のランダムな手に対する勝率で手の強さを順位付けする
// (0.6 ≒ 上位15%、0.65 ≒ 上位5%、0.7 ≒ 上位3%)
const hs = equity(p.cards, [], 1, iterations, rng);
const s1 = (hs - 0.5) / 0.5;
// スタックが少ないときはプッシュかフォールド
if (o.canRaise && stack + p.bet <= 10 * bb && s1 > 0.24 / aggr) return { type: 'raise', amount: o.maxRaiseTo };
// 誰もレイズしていなければオープン(残りの人数が少ないほど広く)、レイズされていたら 3bet・4bet
const raiseBar = (raises === 0 ? (opponents <= 3 ? 0.13 : 0.2) : raises === 1 ? 0.33 : 0.45) / aggr;
if (o.canRaise && (s1 > raiseBar || (raises === 1 && s1 > 0.1 && rng() < style.bluff * 0.5))) {
// オープンは 2.5〜3BB 程度、リレイズはポットの 0.75〜1倍
return raiseTo(raises === 0 ? 0.6 + rng() * 0.3 : 0.75 + rng() * 0.25);
}
if (o.canCheck) return { type: 'check' };
// コール: レイズしてきた相手は強い手を持っているので、その分だけ割り引いてポットオッズと比べる
const callScore = hs - 0.18 * raises - 0.04 * Math.max(0, opponents - 1);
if (callScore + style.looseness >= potOdds + 0.08) return { type: 'call' };
return { type: 'fold' };
}
// フロップ以降: 残っている相手全員のランダムな手に対する勝率
let e = equity(p.cards, hand.board, Math.max(1, opponents), iterations, rng);
// ベットしてきた相手は強い手を持っていることが多いので、ベットが大きいほど勝率を割り引く
if (o.toCall > 0) e *= 1 - 0.25 * Math.min(1, o.toCall / Math.max(pot - o.toCall, bb));
const fair = 1 / (Math.max(1, opponents) + 1);
const strength = (e - fair) / (1 - fair); // 0 で平均的、1 で必勝
// 強い手はベット・レイズ(何度もレイズされているほど慎重に)
const raiseBar = (0.35 + 0.17 * Math.min(raises, 3)) / aggr;
if (o.canRaise && strength > raiseBar) {
// 最強クラスはたまにスロープレイ
if (o.canCheck && strength > 0.85 && rng() < 0.2) return { type: 'check' };
return raiseTo(strength > 0.75 ? Math.max(0.75, sizing()) : sizing());
}
if (o.canCheck) {
// 前のストリートで最後にレイズした人は、相手が少なければ続けてベット(コンティニュエーションベット)
if (o.canRaise && hand.prevAggressor === seat && opponents <= 2 && rng() < 0.55 * aggr) return raiseTo(0.5);
// たまにブラフ
if (o.canRaise && opponents <= 2 && rng() < style.bluff * aggr) return raiseTo(0.5);
return { type: 'check' };
}
// コールするか: 勝率がポットオッズを上回るか
if (e + style.looseness >= potOdds + 0.02) return { type: 'call' };
if (o.canRaise && raises <= 1 && opponents === 1 && rng() < style.bluff * 0.4) return raiseTo(0.75);
return { type: 'fold' };
}
module.exports = { equity, decide, randomStyle };
+50
View File
@@ -0,0 +1,50 @@
'use strict';
// 役の判定は @pokertools/evaluator(@pokertools/engine のショーダウンと同じ判定器)を使う。
// ここでは表示用に、最強の5枚と日本語の役名を求める。
// カードは "As"(スペードのA), "Td"(ダイヤの10)のような2文字
const { evaluate, getCardCodes, rank, HandRank } = require('@pokertools/evaluator');
const HAND_NAMES = {
[HandRank.HighCard]: 'ハイカード',
[HandRank.OnePair]: 'ワンペア',
[HandRank.TwoPair]: 'ツーペア',
[HandRank.ThreeOfAKind]: 'スリーカード',
[HandRank.Straight]: 'ストレート',
[HandRank.Flush]: 'フラッシュ',
[HandRank.FullHouse]: 'フルハウス',
[HandRank.FourOfAKind]: 'フォーカード',
[HandRank.StraightFlush]: 'ストレートフラッシュ',
};
const ROYAL_FLUSH = 1; // 判定器のスコアは小さいほど強く、1 がロイヤルフラッシュ
// 5〜7枚の中で最も強い役。score は小さいほど強い
function bestHand(cards) {
const codes = getCardCodes(cards);
const score = evaluate(codes);
const name = score === ROYAL_FLUSH ? 'ロイヤルフラッシュ' : HAND_NAMES[rank(codes)];
// 役を作っている5枚(7枚から5枚を選ぶ21通りで、全体と同じ強さになる組)
let five = cards.slice(0, 5);
if (cards.length > 5) {
const n = cards.length;
const pick = (start, chosen) => {
if (chosen.length === 5) return evaluate(chosen.map((i) => codes[i])) === score ? chosen.slice() : null;
for (let i = start; i <= n - (5 - chosen.length); i++) {
chosen.push(i);
const found = pick(i + 1, chosen);
chosen.pop();
if (found) return found;
}
return null;
};
five = pick(0, []).map((i) => cards[i]);
}
return { score, cards: five, name };
}
// a が強ければ正、b が強ければ負、同じ強さなら 0
function compareScore(a, b) {
return b - a;
}
module.exports = { bestHand, compareScore };
+10 -1
View File
@@ -61,9 +61,18 @@ module.exports = {
// 誰も接続していないテーブルを削除するまでの時間 // 誰も接続していないテーブルを削除するまでの時間
EMPTY_TABLE_TTL_MS: 30 * 60 * 1000, EMPTY_TABLE_TTL_MS: 30 * 60 * 1000,
// ハンド終了後、次のハンドまで結果を表示する時間 // オールインで残りの場札をめくる間隔(カード機能あり)
RUNOUT_STEP_MS: 1500,
// ハンド終了後、次のハンドまで結果を表示する時間(カードありは手札を見比べられるよう長め)
SHOWDOWN_MS: 4000, SHOWDOWN_MS: 4000,
CARD_SHOWDOWN_MS: 6000,
FOLD_WIN_MS: 2500, FOLD_WIN_MS: 2500,
// CPU の考える時間(ランダム)。人間がハンドに残っていないときは BOT_FAST_MS
BOT_THINK_MIN_MS: 700,
BOT_THINK_MAX_MS: 1800,
BOT_FAST_MS: 400,
// CPU が勝率を見積もるときのシミュレーション回数
BOT_ITERATIONS: 800,
// 参加者が2人揃ってから次のハンドを始めるまで // 参加者が2人揃ってから次のハンドを始めるまで
NEXT_HAND_DELAY_MS: 2000, NEXT_HAND_DELAY_MS: 2000,
+263 -146
View File
@@ -1,125 +1,228 @@
'use strict'; 'use strict';
// 1ハンド分のチップの動き(ブラインド・ベッティング・ポット分配)。 const path = require('path');
// カードは実物で配るので扱わない。ショーダウンでは勝者をプレイヤーが選ぶ。 const { PokerEngine, ActionType, PlayerStatus } = require('@pokertools/engine');
// seats は Table.seats への参照で、スタックはここで直接増減する。 // サイドポットの計算はエンジン内部の関数を使う(パッケージの公開 API に無いので、ファイルを直接読む。
// package.json でバージョンを固定している)
const { calculateSidePots } = require(path.join(path.dirname(require.resolve('@pokertools/engine')), 'rules/side-pots'));
const { bestHand, compareScore } = require('./cards');
// 1ハンド分の進行。ルール(ブラインド・手番・最低レイズ額・再レイズ権・返金・サイドポット・
// ショーダウンの判定と分配)は @pokertools/engine に任せ、ここではテーブルとのやり取りと表示用の状態を持つ。
// cards = false: カードは実物で配るので扱わない。ショーダウンでは勝者をホストが選ぶ。
// cards = true : エンジンが配り、ショーダウンで役を判定して自動で分配する。
// seats は Table.seats への参照で、スタックはエンジンの状態に合わせて書き換える。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。 // 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
const STREETS = ['PREFLOP', 'FLOP', 'TURN', 'RIVER']; const RUNOUT_STREET = { 3: 'FLOP', 4: 'TURN', 5: 'RIVER' };
class Hand { class Hand {
constructor({ number, seats, order, button, sb, bb }) { constructor({ number, seats, order, button, sb, bb, cards = false }) {
this.number = number; this.number = number;
this.seats = seats; this.seats = seats;
this.order = order; // 参加者の席番号。ボタンの次から時計回り this.order = order; // 参加者の席番号。ボタンの次から時計回り
this.button = button; this.button = button;
this.sb = sb; this.sb = sb;
this.bb = bb; this.bb = bb;
this.cards = cards;
// エンジンには参加者だけを、ボタンを席0として時計回りに座らせる(空席の無い n 席のテーブル)
const n = order.length;
this.toEngine = new Map(order.map((s, k) => [s, (k + 1) % n]));
this.fromEngine = [];
for (const [s, e] of this.toEngine) this.fromEngine[e] = s;
this.engine = new PokerEngine({ smallBlind: sb, bigBlind: bb, maxPlayers: n });
for (const s of order) this.engine.sit(this.toEngine.get(s), String(s), String(s), seats[s].stack);
this.board = []; // 公開済みの場札(オールイン後はエンジンが配り終えていても順にめくる)
this.revealed = false; // ショーダウン・オールイン時に残った人の手札を公開
this.runout = false; // オールインでこれ以上ベットが無く、残りの場札を順にめくっている
this.street = 'PREFLOP'; // PREFLOP / FLOP / TURN / RIVER / SHOWDOWN this.street = 'PREFLOP'; // PREFLOP / FLOP / TURN / RIVER / SHOWDOWN
this.pot = 0; // 前のストリートまでに集めた額 this.pot = 0; // 前のストリートまでに集めた額
this.currentBet = 0; this.currentBet = 0;
this.minRaise = bb; this.raises = 0; // このストリートのベット・レイズの回数(CPU の判断用)
this.actions = 0; // アクションの通し番号(CPU の手番の管理用)
this.aggressor = null; // このストリートで最後にベット・レイズした席(CPU の判断用)
this.prevAggressor = null; // 前のストリートで最後にベット・レイズした席
this.toAct = null; this.toAct = null;
this.finished = false; this.finished = false;
this.showdown = false; this.showdown = false;
this.results = null; this.results = null;
this.settled = false; // エンジンの中ではハンドが決着した(結果の公開待ちを含む)
this.pots = null; // ショーダウンのポット(同じ参加者のポットはまとめる)
this.engineWon = null; // エンジンが分配した額(席番号 → 額)
this.taken = new Map(); // ハンド中に退席した人が持ち出したチップ(エンジンから外れた分)
this.players = new Map(); this.players = new Map();
for (const i of order) { for (const i of order) {
this.players.set(i, { this.players.set(i, {
seat: i, seat: i,
token: seats[i].token, token: seats[i].token,
cards: [],
best: null, // ショーダウンでの最強の5枚
bet: 0, // このストリートで出した額 bet: 0, // このストリートで出した額
committed: 0, // このハンドで出した合計 committed: 0, // このハンドで出した合計
folded: false, folded: false,
allIn: false, allIn: false,
acted: false,
last: null, // 直前のアクション(表示用) last: null, // 直前のアクション(表示用)
won: 0, won: 0,
}); });
} }
// ヘッズアップはボタンが SB // ヘッズアップはボタンが SB(エンジンも同じ配置にする)
const headsUp = order.length === 2; const headsUp = n === 2;
this.sbSeat = headsUp ? button : order[0]; this.sbSeat = headsUp ? button : order[0];
this.bbSeat = headsUp ? order[0] : order[1]; this.bbSeat = headsUp ? order[0] : order[1];
this.post(this.sbSeat, sb); this.engine.deal();
this.post(this.bbSeat, bb); this.sync();
this.currentBet = bb; // BB がショートでもコール額は BB }
this.setNextActor(this.bbSeat);
get state() {
return this.engine.state;
} }
get list() { get list() {
return this.order.map((i) => this.players.get(i)); return this.order.map((i) => this.players.get(i));
} }
// 勝者の選択待ち(カードありのときは自動で判定するので来ない)
get awaitingWinners() { get awaitingWinners() {
return this.street === 'SHOWDOWN' && !this.finished; return !this.cards && this.street === 'SHOWDOWN' && !this.finished;
} }
live() { live() {
return this.list.filter((p) => !p.folded); return this.list.filter((p) => !p.folded);
} }
put(p, amount) { // 前のストリートまでのポット + このストリートのベット
const s = this.seats[p.seat]; get potTotal() {
s.stack -= amount; return this.pot + this.list.reduce((sum, p) => sum + p.bet, 0);
p.bet += amount;
p.committed += amount;
if (s.stack === 0) p.allIn = true;
} }
post(seat, amount) { // エンジンの状態を写す。ハンドが決着していたら結果を作る
const p = this.players.get(seat); sync() {
this.put(p, Math.min(amount, this.seats[seat].stack)); if (this.settled) return;
const st = this.state;
for (const p of this.list) {
const e = this.toEngine.get(p.seat);
const ep = st.players[e];
p.bet = st.currentBets.get(e) || 0;
if (!ep) {
// 退席でエンジンから外れた(フォールド済み)
p.folded = true;
this.seats[p.seat].stack = this.taken.get(p.seat) || 0;
continue;
}
if (this.cards) p.cards = ep.hand || [];
p.committed = ep.totalInvestedThisHand;
p.folded = ep.status === PlayerStatus.FOLDED;
p.allIn = ep.status === PlayerStatus.ALL_IN;
this.seats[p.seat].stack = (this.taken.get(p.seat) || 0) + ep.stack;
} }
needsToAct(p) { const prevStreet = this.street;
return !p.folded && !p.allIn && (!p.acted || p.bet < this.currentBet); const ended = st.winners !== null;
if (ended || st.street !== prevStreet) {
// ストリートが終わったら直前のアクションの表示を消す(フォールドとオールインは残す)
for (const p of this.list) {
if (p.last && p.last.type !== 'FOLD' && p.last.type !== 'ALLIN') p.last = null;
} }
this.raises = 0;
bettingClosed() { this.prevAggressor = this.aggressor;
const live = this.live(); this.aggressor = null;
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));
} }
// 誰もコールしなかった分が返ってオールインでなくなった
for (const p of this.list) if (!p.allIn && p.last && p.last.type === 'ALLIN') p.last = null;
setNextActor(fromSeat) { if (ended) return this.settle();
this.toAct = null;
if (this.bettingClosed()) return this.endStreet(); this.street = st.street;
const n = this.order.length; if (this.cards) this.board = st.board.slice();
const start = this.order.indexOf(fromSeat); this.pot = st.pots.reduce((sum, pot) => sum + pot.amount, 0);
for (let k = 1; k <= n; k++) { // コール額(プリフロップは BB がショートでも BB)
const p = this.players.get(this.order[(start + k) % n]); this.currentBet = Math.max(0, ...st.currentBets.values(), st.street === 'PREFLOP' ? st.bigBlind : 0);
if (!this.needsToAct(p)) continue; this.toAct = st.actionTo == null ? null : this.fromEngine[st.actionTo];
this.toAct = p.seat;
// 離席中・退席済みの人は自動でチェック/フォールド // 離席中・退席済みの人は自動でチェック/フォールド
const s = this.seats[p.seat]; if (this.toAct != null) {
const s = this.seats[this.toAct];
if (s.sittingOut || s.left) this.autoAct(); if (s.sittingOut || s.left) this.autoAct();
}
}
// エンジンの中でハンドが決着した
settle() {
const st = this.state;
this.settled = true;
this.toAct = null;
this.engineWon = new Map();
for (const w of st.winners) this.engineWon.set(this.fromEngine[w.seat], (this.engineWon.get(this.fromEngine[w.seat]) || 0) + w.amount);
// 結果を公開するまでは分配前のスタックを見せる
for (const [s, amount] of this.engineWon) this.seats[s].stack -= amount;
if (this.live().length <= 1) {
const total = [...this.engineWon.values()].reduce((a, b) => a + b, 0);
this.pot = total;
this.applyEngineWon();
return this.end(false, [{ amount: total, winners: [...this.engineWon.keys()] }]);
}
this.pots = this.toPots(calculateSidePots(st));
this.pot = this.pots.reduce((sum, pot) => sum + pot.amount, 0);
if (!this.cards) {
this.street = 'SHOWDOWN';
return; return;
} }
this.endStreet(); // 手札を公開する。場札が残っていたら Table のタイマーで順にめくる(runoutStep)
this.revealed = true;
if (this.board.length < 5) this.runout = true;
else this.finishShowdown();
}
// エンジンのサイドポットを席番号に直す。同じ参加者のポットはまとめる
toPots(enginePots) {
const pots = [];
for (const ep of enginePots) {
const eligible = this.order.filter((s) => ep.eligibleSeats.includes(this.toEngine.get(s)));
const last = pots[pots.length - 1];
if (last && last.eligible.join() === eligible.join()) last.amount += ep.amount;
else pots.push({ amount: ep.amount, eligible });
}
return pots;
}
applyEngineWon() {
for (const [s, amount] of this.engineWon) {
this.seats[s].stack += amount;
this.players.get(s).won += amount;
}
}
engineAction(seat, type, amount) {
const playerId = String(seat);
if (type === 'fold') return { type: ActionType.FOLD, playerId };
if (type === 'check') return { type: ActionType.CHECK, playerId };
if (type === 'call') return { type: ActionType.CALL, playerId };
// amount はこのストリートでの合計額("raise to")
return { type: this.currentBet === 0 ? ActionType.BET : ActionType.RAISE, playerId, amount };
} }
// 手番の人の選択肢(手番でなければ null) // 手番の人の選択肢(手番でなければ null)
options(seat) { options(seat) {
if (this.finished || this.toAct !== seat) return null; if (this.finished || this.settled || this.toAct !== seat) return null;
const p = this.players.get(seat); const p = this.players.get(seat);
const stack = this.seats[seat].stack; const stack = this.seats[seat].stack;
const toCall = Math.min(this.currentBet - p.bet, stack); const toCall = Math.min(this.currentBet - p.bet, stack);
const maxTo = p.bet + stack; const maxTo = p.bet + stack;
// 他の全員がオールインならレイズしても意味がない // 他の全員がオールインならレイズしても意味がない
const opponentCanAct = this.live().some((q) => q !== p && !q.allIn); const opponentCanAct = this.live().some((q) => q !== p && !q.allIn);
// レイズできるか(足りないオールインのあとの再レイズ権など)はエンジンに聞く
const canRaise =
maxTo > this.currentBet && opponentCanAct && this.engine.validate(this.engineAction(seat, 'raise', maxTo)).valid;
return { return {
toCall, toCall,
canCheck: p.bet >= this.currentBet, canCheck: p.bet >= this.currentBet,
canRaise: !p.acted && stack > toCall && opponentCanAct, canRaise,
minRaiseTo: Math.min(this.currentBet + this.minRaise, maxTo), minRaiseTo: Math.min(this.state.minRaise, maxTo),
maxRaiseTo: maxTo, maxRaiseTo: maxTo,
isBet: this.currentBet === 0, isBet: this.currentBet === 0,
}; };
@@ -131,37 +234,39 @@ class Hand {
if (!o) return 'あなたの番ではありません'; if (!o) return 'あなたの番ではありません';
const p = this.players.get(seat); const p = this.players.get(seat);
let last;
if (type === 'fold') { if (type === 'fold') {
p.folded = true; last = { type: 'FOLD' };
p.last = { type: 'FOLD' };
} else if (type === 'check') { } else if (type === 'check') {
if (!o.canCheck) return 'チェックできません'; if (!o.canCheck) return 'チェックできません';
p.last = { type: 'CHECK' }; last = { type: 'CHECK' };
} else if (type === 'call') { } else if (type === 'call') {
if (o.canCheck || o.toCall <= 0) return 'コールする額がありません'; if (o.canCheck || o.toCall <= 0) return 'コールする額がありません';
this.put(p, o.toCall); last = { type: 'CALL', amount: p.bet + o.toCall };
p.last = { type: 'CALL', amount: p.bet };
} else if (type === 'raise') { } else if (type === 'raise') {
if (!o.canRaise) return 'レイズできません'; if (!o.canRaise) return 'レイズできません';
if (!Number.isInteger(amount) || amount < o.minRaiseTo || amount > o.maxRaiseTo) { if (!Number.isInteger(amount) || amount < o.minRaiseTo || amount > o.maxRaiseTo) {
return `${o.minRaiseTo}〜${o.maxRaiseTo} の額を指定してください`; return `${o.minRaiseTo}〜${o.maxRaiseTo} の額を指定してください`;
} }
const raiseSize = amount - this.currentBet; last = { type: o.isBet ? 'BET' : 'RAISE', amount };
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 { } else {
return '不正なアクションです'; return '不正なアクションです';
} }
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet }; const allIn = type !== 'fold' && type !== 'check' && last.amount === o.maxRaiseTo;
p.acted = true; const fullRaise = type === 'raise' && amount >= this.state.minRaise;
this.setNextActor(seat); try {
this.engine.act(this.engineAction(seat, type, amount));
} catch {
// エンジンが受け付けない(チェックできるのに降りてサイドポットの対象者がいなくなる場合など)
return type === 'fold' && o.canCheck ? 'いまはフォールドできません。チェックしてください' : 'そのアクションはできません';
}
p.last = allIn ? { type: 'ALLIN', amount: last.amount } : last;
this.actions++;
if (type === 'raise') {
this.aggressor = seat;
if (fullRaise) this.raises++;
}
this.sync();
return null; return null;
} }
@@ -170,76 +275,53 @@ class Hand {
if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0); if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0);
} }
// 退席などで手番に関係なくフォールドさせる // 退席などで手番に関係なくフォールドさせる。オールインの人の手は最後まで生きている
forceFold(seat) { forceFold(seat) {
const p = this.players.get(seat); const p = this.players.get(seat);
if (!p || p.folded || this.finished) return; if (!p || p.folded || this.finished) return;
if (this.toAct === seat) return this.act(seat, 'fold', 0); if (this.toAct === seat) {
p.folded = true; if (this.act(seat, 'fold', 0)) this.autoAct();
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; return;
} }
this.street = STREETS[STREETS.indexOf(this.street) + 1]; if (this.settled) {
this.setNextActor(this.button); // キャッシュオンリーの勝者選び待ち: 選べる人から外す
} if (!this.awaitingWinners) return;
p.folded = true;
// メインポット・サイドポット(同じ参加者のポットはまとめる) p.last = { type: 'FOLD' };
buildPots() { if (this.live().length === 1) return this.finishFoldWin();
const all = this.list; // 選べる人がいなくなったポットは前のポットにまとめる(メインポットには残った全員が入っている)
const levels = [...new Set(all.map((p) => p.committed).filter((c) => c > 0))].sort((a, b) => a - b);
const pots = []; const pots = [];
let prev = 0; for (const pot of this.pots) {
for (const level of levels) { const eligible = pot.eligible.filter((s) => s !== seat);
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]; const last = pots[pots.length - 1];
if (eligible.length === 0) eligible = last ? last.eligible : this.live().map((p) => p.seat); if (last && (eligible.length === 0 || last.eligible.join() === eligible.join())) last.amount += pot.amount;
if (last && last.eligible.join() === eligible.join()) last.amount += amount; else pots.push({ amount: pot.amount, eligible });
else pots.push({ amount, eligible });
} }
return pots; this.pots = pots;
return;
}
// エンジンは手番以外のフォールドを「席を立つ」として扱う。持ち出したチップは自分で覚えておく。
// オールインの人などエンジンが受け付けないときは、手番が来たら自動でチェック/フォールドする
const stand = { type: ActionType.STAND, playerId: String(seat) };
if (!this.engine.validate(stand).valid) return;
const before = this.state.initialChips;
this.engine.stand(String(seat));
this.taken.set(seat, (this.taken.get(seat) || 0) + before - this.state.initialChips);
p.last = { type: 'FOLD' };
this.sync();
} }
// オールイン後に場札を1ストリート分めくる。リバーまでめくり終えていたらショーダウン
runoutStep() {
if (!this.runout || this.finished) return;
const n = this.board.length;
if (n === 5) return this.finishShowdown();
const next = n === 0 ? 3 : n + 1;
this.board = this.state.board.slice(0, next);
this.street = RUNOUT_STREET[next];
}
// キャッシュオンリーのショーダウン中に1人を残して退席した: 残った人がすべて獲得
finishFoldWin() { finishFoldWin() {
const winner = this.live()[0]; const winner = this.live()[0];
winner.won = this.pot; winner.won = this.pot;
@@ -250,7 +332,7 @@ class Hand {
// ショーダウンの勝者を決める。winners[i] = i 番目のポットの勝者の席番号(引き分けは複数) // ショーダウンの勝者を決める。winners[i] = i 番目のポットの勝者の席番号(引き分けは複数)
award(winners) { award(winners) {
if (!this.awaitingWinners) return 'ショーダウンではありません'; if (!this.awaitingWinners) return 'ショーダウンではありません';
const pots = this.buildPots(); const pots = this.pots;
if (!Array.isArray(winners) || winners.length !== pots.length) return 'すべてのポットの勝者を選んでください'; if (!Array.isArray(winners) || winners.length !== pots.length) return 'すべてのポットの勝者を選んでください';
for (let i = 0; i < pots.length; i++) { for (let i = 0; i < pots.length; i++) {
const w = winners[i]; const w = winners[i];
@@ -258,41 +340,76 @@ class Hand {
if (new Set(w).size !== w.length || !w.every((s) => pots[i].eligible.includes(s))) return '勝者の指定が不正です'; if (new Set(w).size !== w.length || !w.every((s) => pots[i].eligible.includes(s))) return '勝者の指定が不正です';
} }
const results = []; const results = pots.map((pot, i) => ({ amount: pot.amount, winners: this.payout(pot.amount, winners[i]) }));
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); this.end(true, results);
return null; return null;
} }
// カードありのショーダウン: エンジンが分配した結果を公開する。表示用にポットごとの勝者と役を添える
finishShowdown() {
this.board = this.state.board.slice();
for (const p of this.live()) p.best = bestHand(p.cards.concat(this.board));
const results = this.pots.map((pot) => {
const contenders = pot.eligible.map((s) => this.players.get(s));
let top = null;
for (const c of contenders) if (top == null || compareScore(c.best.score, top) > 0) top = c.best.score;
const best = contenders.filter((c) => compareScore(c.best.score, top) === 0);
return {
amount: pot.amount,
winners: best.map((c) => c.seat),
handName: best[0].best.name,
bestCards: best[0].best.cards,
};
});
this.applyEngineWon();
this.end(true, results);
}
// amount を seats で山分けする。割り切れない端数はボタンの左から順に。分配した順の席番号を返す
// (キャッシュオンリーでホストが勝者を選んだときだけ使う)
payout(amount, seats) {
const ws = this.order.filter((s) => seats.includes(s));
const share = Math.floor(amount / ws.length);
let rest = amount - share * ws.length;
for (const s of ws) {
const a = share + (rest > 0 ? 1 : 0);
if (rest > 0) rest--;
this.players.get(s).won += a;
this.seats[s].stack += a;
}
return ws;
}
end(showdown, results) { end(showdown, results) {
this.finished = true; this.finished = true;
this.runout = false;
this.showdown = showdown; this.showdown = showdown;
this.toAct = null; this.toAct = null;
this.results = results; this.results = results;
} }
view() { // 閲覧者に見せてよい情報だけを返す(他人の手札は公開時のみ)
view(viewerSeat, viewerToken) {
const players = {}; const players = {};
for (const p of this.list) { for (const p of this.list) {
players[p.seat] = { bet: p.bet, folded: p.folded, allIn: p.allIn, last: p.last, won: p.won }; const v = { bet: p.bet, folded: p.folded, allIn: p.allIn, last: p.last, won: p.won };
if (this.cards) {
const mine = p.seat === viewerSeat && p.token === viewerToken;
const shown = mine || (this.revealed && !p.folded);
v.cards = shown ? p.cards : null;
v.handName =
shown && !p.folded && this.board.length >= 3 ? (p.best || bestHand(p.cards.concat(this.board))).name : null;
}
players[p.seat] = v;
} }
return { return {
number: this.number, number: this.number,
cards: this.cards,
board: this.board,
runout: this.runout,
street: this.street, street: this.street,
pot: this.pot, pot: this.pot,
potTotal: this.pot + this.list.reduce((sum, p) => sum + p.bet, 0), potTotal: this.potTotal,
currentBet: this.currentBet, currentBet: this.currentBet,
button: this.button, button: this.button,
sbSeat: this.sbSeat, sbSeat: this.sbSeat,
@@ -300,7 +417,7 @@ class Hand {
toAct: this.toAct, toAct: this.toAct,
finished: this.finished, finished: this.finished,
showdown: this.showdown, showdown: this.showdown,
pots: this.awaitingWinners ? this.buildPots() : null, pots: this.awaitingWinners ? this.pots : null,
results: this.results, results: this.results,
players, players,
}; };
+25 -4
View File
@@ -6,7 +6,7 @@ const express = require('express');
const { Server } = require('socket.io'); const { Server } = require('socket.io');
const config = require('./config'); const config = require('./config');
const auth = require('./auth'); const auth = require('./auth');
const { TableManager } = require('./tables'); const { TableManager, MODES } = require('./tables');
const PUBLIC = path.join(__dirname, '..', 'public'); const PUBLIC = path.join(__dirname, '..', 'public');
// 管理者専用のファイル(public の外に置き、管理者の Cookie があるときだけ返す) // 管理者専用のファイル(public の外に置き、管理者の Cookie があるときだけ返す)
@@ -114,6 +114,8 @@ app.post('/api/tables', (req, res) => {
const bigBlind = b.bigBlind; const bigBlind = b.bigBlind;
const blindTimerEnabled = b.blindTimerEnabled === true; const blindTimerEnabled = b.blindTimerEnabled === true;
const blindIntervalMin = b.blindIntervalMin; const blindIntervalMin = b.blindIntervalMin;
const mode = b.mode;
const cpuCount = b.cpuCount;
const hostToken = cleanToken(b.token); const hostToken = cleanToken(b.token);
if (tables.tables.size >= config.MAX_TABLES) return res.status(429).json({ error: 'テーブル数が上限に達しています' }); if (tables.tables.size >= config.MAX_TABLES) return res.status(429).json({ error: 'テーブル数が上限に達しています' });
@@ -121,8 +123,12 @@ app.post('/api/tables', (req, res) => {
if (tables.nameTaken(name)) return res.status(409).json({ error: '同じ名前のテーブルがすでにあります' }); if (tables.nameTaken(name)) return res.status(409).json({ error: '同じ名前のテーブルがすでにあります' });
if (!intIn(startingStack, 10, 100000000)) return res.status(400).json({ error: '開始スタックが不正です' }); if (!intIn(startingStack, 10, 100000000)) return res.status(400).json({ error: '開始スタックが不正です' });
if (!intIn(smallBlind, 1, startingStack)) return res.status(400).json({ error: 'SBが不正です' }); if (!intIn(smallBlind, 1, startingStack)) return res.status(400).json({ error: 'SBが不正です' });
if (!intIn(bigBlind, smallBlind, startingStack)) return res.status(400).json({ error: 'BBはSB以上・開始スタック以下にしてください' }); if (!intIn(bigBlind, smallBlind + 1, startingStack)) return res.status(400).json({ error: 'BBはSBより大きく・開始スタック以下にしてください' });
if (blindTimerEnabled && !intIn(blindIntervalMin, 1, 240)) return res.status(400).json({ error: 'インターバルは1〜240分で入力してください' }); if (blindTimerEnabled && !intIn(blindIntervalMin, 1, 240)) return res.status(400).json({ error: 'インターバルは1〜240分で入力してください' });
if (!MODES.includes(mode)) return res.status(400).json({ error: 'テーブルの種類が不正です' });
if (mode === 'cpu' && !intIn(cpuCount, 1, config.MAX_SEATS - 1)) {
return res.status(400).json({ error: `CPU の人数は1〜${config.MAX_SEATS - 1}人にしてください` });
}
if (!hostToken) return res.status(400).json({ error: 'プレイヤーIDがありません' }); if (!hostToken) return res.status(400).json({ error: 'プレイヤーIDがありません' });
const table = tables.create({ const table = tables.create({
@@ -132,6 +138,8 @@ app.post('/api/tables', (req, res) => {
bigBlind, bigBlind,
blindTimerEnabled, blindTimerEnabled,
blindIntervalMin: blindTimerEnabled ? blindIntervalMin : 10, blindIntervalMin: blindTimerEnabled ? blindIntervalMin : 10,
mode,
cpuCount: mode === 'cpu' ? cpuCount : 0,
hostToken, hostToken,
}); });
broadcastLobby(); broadcastLobby();
@@ -184,6 +192,17 @@ function changed(table) {
broadcastLobby(); broadcastLobby();
} }
// テーブルを削除し、残っている観戦者に知らせる(leaver: 退席した本人。すでにロビーへ戻るので知らせない)
function closeTable(table, leaver) {
tables.delete(table.id);
for (const s of roomSockets(table.id)) {
s.leave(roomOf(table.id));
if (s.data.tableId === table.id) s.data.tableId = null;
if (s !== leaver) s.emit('table:closed');
}
broadcastLobby();
}
// 二重チェック(allowRequest を通った後も念のため) // 二重チェック(allowRequest を通った後も念のため)
io.use((socket, next) => { io.use((socket, next) => {
if (auth.isAuthedCookieHeader(socket.handshake.headers.cookie)) next(); if (auth.isAuthedCookieHeader(socket.handshake.headers.cookie)) next();
@@ -266,7 +285,9 @@ io.on('connection', (socket) => {
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, p); 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) return;
if (event === 'table:leave' && table.shouldClose()) return closeTable(table, socket);
changed(table);
}); });
} }
@@ -276,7 +297,7 @@ 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()) {
+118 -11
View File
@@ -4,6 +4,14 @@ 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 } = require('./hand');
const ai = require('./ai');
// テーブルの種類
// chips : キャッシュオンリー。カードは実物で配り、サイトはチップだけを管理する
// friends: 友人戦。サーバがカードを配り、ショーダウンも自動で判定する
// cpu : CPU戦。友人戦に CPU プレイヤーが加わる
const MODES = ['chips', 'friends', 'cpu'];
const CPU_NAMES = ['ハル', 'ソラ', 'リク', 'ミオ', 'レン', 'ユイ', 'カイ', 'ナギ'];
class Table { class Table {
constructor(opts) { constructor(opts) {
@@ -14,12 +22,18 @@ class Table {
this.baseBigBlind = opts.bigBlind; this.baseBigBlind = opts.bigBlind;
this.timerEnabled = opts.blindTimerEnabled; this.timerEnabled = opts.blindTimerEnabled;
this.intervalMin = opts.blindIntervalMin; this.intervalMin = opts.blindIntervalMin;
this.mode = MODES.includes(opts.mode) ? opts.mode : 'chips';
// カード機能: サーバがカードを配り、ショーダウンの勝敗も自動で判定する(キャッシュオンリーは実物のカード)
this.cardsEnabled = this.mode !== 'chips';
this.hostToken = opts.hostToken || null; this.hostToken = opts.hostToken || null;
this.maxSeats = config.MAX_SEATS; this.maxSeats = config.MAX_SEATS;
// { token, name, stack, buyIns, sittingOut, left } // { token, name, stack, buyIns, sittingOut, left, bot, style }
// left: ハンド中に退席した人。ハンドが終わるまで席を予約しておく // left: ハンド中に退席した人。ハンドが終わるまで席を予約しておく
// bot : CPU プレイヤー(style は思考の性格)
this.seats = new Array(this.maxSeats).fill(null); this.seats = new Array(this.maxSeats).fill(null);
this.botTurn = null; // { key, at }: CPU が行動する時刻
if (this.mode === 'cpu') this.seatBots(opts.cpuCount);
this.hand = null; this.hand = null;
this.started = false; this.started = false;
this.paused = false; this.paused = false;
@@ -28,6 +42,7 @@ class Table {
this.handNumber = 0; this.handNumber = 0;
this.buttonSeat = null; this.buttonSeat = null;
this.nextHandAt = null; this.nextHandAt = null;
this.runoutAt = null; // オールイン後、次の場札をめくる時刻
this.levelEndsAt = null; this.levelEndsAt = null;
this.levelRemainingMs = this.intervalMs; this.levelRemainingMs = this.intervalMs;
@@ -35,6 +50,28 @@ class Table {
this.emptySince = null; this.emptySince = null;
} }
// CPU は席1から順に座らせる(席0は作成者)
seatBots(count) {
const n = Math.max(1, Math.min(this.maxSeats - 1, Number.isInteger(count) ? count : 1));
const names = CPU_NAMES.slice();
for (let i = names.length - 1; i > 0; i--) {
const j = crypto.randomInt(i + 1);
[names[i], names[j]] = [names[j], names[i]];
}
for (let k = 0; k < n; k++) {
this.seats[k + 1] = {
token: crypto.randomBytes(16).toString('hex'), // ブラウザには渡さない
name: names[k],
stack: this.startingStack,
buyIns: 1,
sittingOut: false,
left: false,
bot: true,
style: ai.randomStyle(),
};
}
}
get intervalMs() { get intervalMs() {
return this.intervalMin * 60 * 1000; return this.intervalMin * 60 * 1000;
} }
@@ -71,8 +108,10 @@ class Table {
.filter((i) => i >= 0); .filter((i) => i >= 0);
} }
// CPU だけでハンドを続けても意味がないので、人間が1人は参加している必要がある
canDeal() { canDeal() {
return this.started && !this.paused && this.eligibleSeats().length >= 2; const eligible = this.eligibleSeats();
return this.started && !this.paused && eligible.length >= 2 && eligible.some((i) => !this.seats[i].bot);
} }
// 着席した席番号を返す。満席なら -1(観戦) // 着席した席番号を返す。満席なら -1(観戦)
@@ -107,12 +146,17 @@ class Table {
this.seats[i] = null; this.seats[i] = null;
} }
if (this.hostToken === token) { if (this.hostToken === token) {
const next = this.seats.find((s) => s && !s.left); const next = this.seats.find((s) => s && !s.left && !s.bot);
this.hostToken = next ? next.token : null; this.hostToken = next ? next.token : null;
} }
return true; return true;
} }
// CPU戦で人間が全員退席したら、テーブルを残しておく意味がない
shouldClose() {
return this.mode === 'cpu' && !this.seats.some((s) => s && !s.left && !s.bot);
}
removeLeftSeats() { removeLeftSeats() {
this.seats = this.seats.map((s) => (s && s.left ? null : s)); this.seats = this.seats.map((s) => (s && s.left ? null : s));
} }
@@ -127,6 +171,13 @@ class Table {
startNewHand() { startNewHand() {
this.removeLeftSeats(); this.removeLeftSeats();
// チップがなくなった CPU は自動でリバイ
for (const s of this.seats) {
if (s && s.bot && s.stack === 0) {
s.stack = this.startingStack;
s.buyIns++;
}
}
const eligible = this.eligibleSeats(); const eligible = this.eligibleSeats();
this.buttonSeat = this.buttonSeat =
this.buttonSeat == null this.buttonSeat == null
@@ -139,7 +190,17 @@ class Table {
this.handNumber++; this.handNumber++;
const { sb, bb } = this.blinds; const { sb, bb } = this.blinds;
this.nextHandAt = null; this.nextHandAt = null;
this.hand = new Hand({ number: this.handNumber, seats: this.seats, order, button: this.buttonSeat, sb, bb }); this.runoutAt = null;
this.botTurn = null;
this.hand = new Hand({
number: this.handNumber,
seats: this.seats,
order,
button: this.buttonSeat,
sb,
bb,
cards: this.cardsEnabled,
});
} }
// ---- プレイヤー操作(エラー時はメッセージを返す) ---- // ---- プレイヤー操作(エラー時はメッセージを返す) ----
@@ -202,8 +263,10 @@ class Table {
if (!this.isHost(token)) return 'ホストのみ操作できます'; if (!this.isHost(token)) return 'ホストのみ操作できます';
if (!this.started) return 'まだ開始していません'; if (!this.started) return 'まだ開始していません';
if (this.paused) { if (this.paused) {
// 止めていた時間だけ次のハンドの開始を後ろにずらす // 止めていた時間だけ次のハンドの開始・場札をめくる時刻を後ろにずらす
if (this.nextHandAt != null) this.nextHandAt += now - this.pausedAt; if (this.nextHandAt != null) this.nextHandAt += now - this.pausedAt;
if (this.runoutAt != null) this.runoutAt += now - this.pausedAt;
this.botTurn = null; // CPU は再開してから考え直す
if (this.timerEnabled) this.levelEndsAt = now + this.levelRemainingMs; if (this.timerEnabled) this.levelEndsAt = now + this.levelRemainingMs;
this.paused = false; this.paused = false;
this.pausedAt = null; this.pausedAt = null;
@@ -218,7 +281,33 @@ class Table {
return null; return null;
} }
// 時間で進む処理(ブラインドタイマー・次のハンドの開始) // CPU の考える時間。人間がハンドに残っていなければ早めに進める
botDelay() {
const h = this.hand;
const humanLive = h.live().some((p) => !this.seats[p.seat].bot && !this.seats[p.seat].left);
if (!humanLive) return config.BOT_FAST_MS;
return config.BOT_THINK_MIN_MS + crypto.randomInt(config.BOT_THINK_MAX_MS - config.BOT_THINK_MIN_MS + 1);
}
// 手番の CPU が考える時間を過ぎていたら行動する。行動したら true
botStep(now) {
const h = this.hand;
if (!h || h.finished || h.toAct == null || !this.seats[h.toAct].bot) return false;
const key = `${h.number}:${h.actions}`;
if (!this.botTurn || this.botTurn.key !== key) {
this.botTurn = { key, at: now + this.botDelay() };
return false;
}
if (now < this.botTurn.at) return false;
this.botTurn = null;
const seat = h.toAct;
const d = ai.decide(h, seat, { style: this.seats[seat].style, iterations: config.BOT_ITERATIONS });
// 万一判断が不正でも止まらないよう、チェック/フォールドにする
if (!d || h.act(seat, d.type, d.amount)) h.autoAct();
return true;
}
// 時間で進む処理(ブラインドタイマー・CPU の行動・オールイン後の場札・次のハンドの開始)
// 状態が変わったら true // 状態が変わったら true
tick(now) { tick(now) {
let changed = false; let changed = false;
@@ -229,9 +318,22 @@ class Table {
} }
if (this.paused) return changed; if (this.paused) return changed;
if (this.botStep(now)) changed = true;
const h = this.hand;
if (h && h.runout) {
if (this.runoutAt == null) this.runoutAt = now + config.RUNOUT_STEP_MS;
else if (now >= this.runoutAt) {
h.runoutStep();
this.runoutAt = h.runout ? now + config.RUNOUT_STEP_MS : null;
changed = true;
}
}
if (this.hand && this.hand.finished) { if (this.hand && this.hand.finished) {
if (this.nextHandAt == null) { if (this.nextHandAt == null) {
this.nextHandAt = now + (this.hand.showdown ? config.SHOWDOWN_MS : config.FOLD_WIN_MS); const showdownMs = this.cardsEnabled ? config.CARD_SHOWDOWN_MS : config.SHOWDOWN_MS;
this.nextHandAt = now + (this.hand.showdown ? showdownMs : config.FOLD_WIN_MS);
} else if (now >= this.nextHandAt) { } else if (now >= this.nextHandAt) {
if (this.canDeal()) this.startNewHand(); if (this.canDeal()) this.startNewHand();
else { else {
@@ -267,18 +369,20 @@ class Table {
paused: this.paused, paused: this.paused,
timerEnabled: this.timerEnabled, timerEnabled: this.timerEnabled,
intervalMin: this.intervalMin, intervalMin: this.intervalMin,
cardsEnabled: this.cardsEnabled,
mode: this.mode,
createdAt: this.createdAt, createdAt: this.createdAt,
}; };
} }
// token = 閲覧者のトークン(他人のトークンは送らない) // token = 閲覧者のトークン(他人のトークンや手札は送らない)
publicState(token, connectedTokens) { publicState(token, connectedTokens) {
const now = Date.now(); 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 mySeat = this.seatOf(token); const mySeat = this.seatOf(token);
const h = this.hand; const h = this.hand;
const hv = h ? h.view() : null; const hv = h ? h.view(mySeat, token) : null;
const me = mySeat >= 0 ? this.seats[mySeat] : null; const me = mySeat >= 0 ? this.seats[mySeat] : null;
const inLiveHand = Boolean(this.handActive && h.players.has(mySeat) && !h.players.get(mySeat).folded); const inLiveHand = Boolean(this.handActive && h.players.has(mySeat) && !h.players.get(mySeat).folded);
@@ -287,6 +391,8 @@ class Table {
name: this.name, name: this.name,
startingStack: this.startingStack, startingStack: this.startingStack,
maxSeats: this.maxSeats, maxSeats: this.maxSeats,
cardsEnabled: this.cardsEnabled,
mode: this.mode,
level: this.level, level: this.level,
smallBlind: sb, smallBlind: sb,
bigBlind: bb, bigBlind: bb,
@@ -310,7 +416,8 @@ class Table {
seat: i, seat: i,
name: s.name, name: s.name,
stack: s.stack, stack: s.stack,
connected: connectedTokens.has(s.token), connected: Boolean(s.bot) || connectedTokens.has(s.token),
bot: Boolean(s.bot),
sittingOut: s.sittingOut, sittingOut: s.sittingOut,
...(hv && hv.players[i] ? { inHand: true, ...hv.players[i] } : { inHand: false }), ...(hv && hv.players[i] ? { inHand: true, ...hv.players[i] } : { inHand: false }),
} }
@@ -376,4 +483,4 @@ class TableManager {
} }
} }
module.exports = { TableManager, Table }; module.exports = { TableManager, Table, MODES };
+451 -8
View File
@@ -5,7 +5,12 @@ process.env.ACCESS_KEY = process.env.ACCESS_KEY || '000000';
const test = require('node:test'); const test = require('node:test');
const assert = require('node:assert/strict'); const assert = require('node:assert/strict');
const crypto = require('crypto');
const { PokerEngine } = require('@pokertools/engine');
const { getCardCodes, stringifyCardCode } = require('@pokertools/evaluator');
const { Table } = require('../server/tables'); const { Table } = require('../server/tables');
const { bestHand, compareScore } = require('../server/cards');
const config = require('../server/config');
const T = (n) => 't'.repeat(31) + n; // 32文字のトークン const T = (n) => 't'.repeat(31) + n; // 32文字のトークン
@@ -76,17 +81,20 @@ test('BBのオプションとチェックでストリートが進む', () => {
}); });
test('ミニマムレイズと、足りないオールインは再レイズ権を与えない', () => { test('ミニマムレイズと、足りないオールインは再レイズ権を与えない', () => {
const t = makeTable([1000, 1000, 1000]); // ボタンを席0にして、BB(席2)は 75 しか持っていない
const t = makeTable([1000, 1000, 75]);
t.buttonSeat = 2;
t.start(T(0), 0); t.start(T(0), 0);
const h = t.hand; const h = t.hand;
const [sb, bb, btn] = h.order; const [sb, bb, btn] = h.order;
assert.deepEqual([sb, bb, btn], [1, 2, 0]);
// 最低レイズ額は 40(20 + 20) // 最低レイズ額は 40(20 + 20)
assert.ok(t.act(tk(t, btn), 'raise', 39)); assert.ok(t.act(tk(t, btn), 'raise', 39));
assert.equal(t.act(tk(t, btn), 'raise', 60), null); // +40 のレイズ assert.equal(t.act(tk(t, btn), 'raise', 60), null); // +40 のレイズ
assert.equal(h.options(sb).minRaiseTo, 100); assert.equal(h.options(sb).minRaiseTo, 100);
assert.equal(t.act(tk(t, sb), 'call', 0), null); assert.equal(t.act(tk(t, sb), 'call', 0), null);
// BB は 75 しか持っていないとする → 75 オールインは 100 未満なので不完全なレイズ // BB の 75 オールインは 100 未満なので不完全なレイズ
t.seats[bb].stack = 75 - 20; assert.equal(h.options(bb).minRaiseTo, 75);
assert.equal(t.act(tk(t, bb), 'raise', 75), null); assert.equal(t.act(tk(t, bb), 'raise', 75), null);
assert.equal(h.currentBet, 75); assert.equal(h.currentBet, 75);
assert.equal(h.toAct, btn); assert.equal(h.toAct, btn);
@@ -266,15 +274,46 @@ test('ハンド中の退席: フォールド扱いで席はハンド終了まで
assert.equal(h.street, 'FLOP'); assert.equal(h.street, 'FLOP');
}); });
test('2人のうち片方が退席したら残った人が勝つ(BB は返らない)', () => { test('2人のうち片方が退席したら残った人が勝つ(コールされていない分は退席者に返る)', () => {
const t = makeTable([1000, 1000]); const t = makeTable([1000, 1000]);
t.start(T(0), 0); t.start(T(0), 0);
const h = t.hand; const h = t.hand;
const stay = h.toAct; // SB(ボタン) const stay = h.toAct; // SB(ボタン)
const other = h.order.find((s) => s !== stay); const other = h.order.find((s) => s !== stay);
t.leave(tk(t, other)); t.leave(tk(t, other));
assert.ok(h.finished); assert.ok(h.finished && !h.showdown);
assert.equal(t.seats[stay].stack, 1020); // BB の 20 のうち SB の 10 を超える分は返り、SB は 10 + 10 を獲得
assert.equal(t.seats[stay].stack, 1010);
assert.equal(t.seats[other].stack, 990);
});
test('チェックできるのに降りてサイドポットの対象者がいなくなるフォールドは断る', () => {
// 席0・席1 がオールイン、席2・席3 がサイドポットを作ったあと、席2 が降り、最後の席3 もチェックせずに降りようとする
// (@pokertools/engine はサイドポットの対象者がいなくなるとエラーになる)
const t = makeTable([100, 200, 1000, 1000]);
t.buttonSeat = 3;
t.start(T(0), 0);
const h = t.hand;
assert.deepEqual(h.order, [1, 2, 3, 0]);
assert.equal(t.act(tk(t, 3), 'raise', 500), null);
assert.equal(t.act(tk(t, 0), 'call', 0), null); // オールイン
assert.equal(t.act(tk(t, 1), 'call', 0), null); // オールイン
assert.equal(t.act(tk(t, 2), 'call', 0), null);
assert.equal(h.street, 'FLOP');
assert.equal(t.act(tk(t, 2), 'fold', 0), null);
assert.equal(t.act(tk(t, 3), 'fold', 0), 'いまはフォールドできません。チェックしてください');
assert.equal(h.toAct, 3);
// 退席なら代わりにチェックしたことになる(残りはオールインの人だけなのでショーダウンへ)
assert.ok(t.leave(tk(t, 3)));
assert.equal(h.street, 'SHOWDOWN');
assert.deepEqual(
h.view().pots.map((p) => [p.amount, p.eligible]),
[
[400, [1, 3, 0]],
[300, [1, 3]],
[600, [3]],
]
);
}); });
test('他人の手番では操作できない・不正な額は拒否', () => { test('他人の手番では操作できない・不正な額は拒否', () => {
@@ -321,8 +360,10 @@ test('ランダムに遊んでもチップの合計が変わらず、必ず終
const r = rand(10); const r = rand(10);
const me = tk(t, h.toAct); const me = tk(t, h.toAct);
let err; let err;
if (r < 2) err = t.act(me, 'fold', 0); if (r < 2) {
else if (r < 6 || !o.canRaise) err = t.act(me, o.canCheck ? 'check' : 'call', 0); err = t.act(me, 'fold', 0);
if (err && o.canCheck) err = t.act(me, 'check', 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)); else err = t.act(me, 'raise', o.minRaiseTo + rand(o.maxRaiseTo - o.minRaiseTo + 1));
assert.equal(err, null); assert.equal(err, null);
} else if (h.awaitingWinners) { } else if (h.awaitingWinners) {
@@ -345,3 +386,405 @@ test('ランダムに遊んでもチップの合計が変わらず、必ず終
} }
assert.ok(showdowns > 100 && sidePots > 20, `showdowns=${showdowns} sidePots=${sidePots}`); assert.ok(showdowns > 100 && sidePots > 20, `showdowns=${showdowns} sidePots=${sidePots}`);
}); });
// ---------- カード機能あり ----------
// エンジンの山札("As" 形式)
const deckOf = (hand) => hand.state.deck.map(stringifyCardCode);
// 手札と、これから配られる場札を差し替える(エンジンの状態をスナップショット経由で書き換える)。holes は h.order の順
function rig(hand, holes, board) {
const snap = hand.engine.snapshot;
const used = new Set([...holes.flat(), ...board]);
const rest = deckOf(hand)
.concat(...hand.order.map((s) => snap.players[hand.toEngine.get(s)].hand))
.filter((c) => !used.has(c));
hand.order.forEach((s, k) => {
const e = hand.toEngine.get(s);
snap.players[e] = { ...snap.players[e], hand: holes[k].slice() };
});
// 山札の先頭から バーン + フロップ3枚、バーン + ターン、バーン + リバー の順に配られる
const seq = ['X', ...board.slice(0, 3), 'X', board[3], 'X', board[4]].map((c) => (c === 'X' ? rest.pop() : c));
snap.deck = getCardCodes(seq.concat(rest));
hand.engine = PokerEngine.restore(snap);
hand.sync();
}
const SPECTATOR = 's'.repeat(32);
const viewOf = (t, token) => t.publicState(token, new Set()).hand;
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('カードなしのテーブルでは手札も場札も扱わない', () => {
const t = makeTable([1000, 1000]);
t.start(T(0), 0);
assert.equal(t.publicState(T(0), new Set()).cardsEnabled, false);
const v = viewOf(t, T(0));
assert.deepEqual(v.board, []);
assert.equal('cards' in v.players[0], false);
});
test('カードあり: 自分の手札だけが見え、ストリートごとに場札が配られ、勝者は自動で決まる', () => {
const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
assert.equal(t.publicState(tk(t, sb), new Set()).cardsEnabled, true);
let v = viewOf(t, tk(t, sb));
assert.equal(v.players[sb].cards.length, 2);
assert.equal(v.players[bb].cards, null);
assert.equal(v.players[btn].cards, null);
assert.equal(viewOf(t, SPECTATOR).players[sb].cards, null);
t.act(tk(t, btn), 'call', 0);
t.act(tk(t, sb), 'call', 0);
t.act(tk(t, bb), 'check', 0);
assert.equal(h.street, 'FLOP');
assert.equal(h.board.length, 3);
assert.ok(viewOf(t, tk(t, sb)).players[sb].handName);
t.act(tk(t, sb), 'check', 0);
t.act(tk(t, bb), 'check', 0);
t.act(tk(t, btn), 'check', 0);
assert.equal(h.board.length, 4);
checkDown(t);
assert.equal(h.board.length, 5);
assert.ok(h.finished && h.showdown);
assert.equal(h.awaitingWinners, false);
assert.equal(t.award(T(0), [[sb]]), 'ショーダウンではありません');
assert.ok(h.results[0].handName && h.results[0].bestCards.length === 5);
// ショーダウン後は残った人の手札が公開される
v = viewOf(t, SPECTATOR);
for (const s of [sb, bb, btn]) assert.equal(v.players[s].cards.length, 2);
// すべて別のカード(バーンの3枚は山札から消えている)
const all = [...deckOf(h), ...h.board, ...h.list.flatMap((p) => p.cards)];
assert.equal(new Set(all).size, all.length);
assert.equal(all.length, 52 - 3);
});
test('カードあり: フォールドした人の手札は公開されない', () => {
const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
t.act(tk(t, btn), 'fold', 0);
t.act(tk(t, sb), 'call', 0);
t.act(tk(t, bb), 'check', 0);
checkDown(t);
assert.ok(h.finished);
const v = viewOf(t, tk(t, sb));
assert.equal(v.players[btn].cards, null);
assert.equal(v.players[bb].cards.length, 2);
assert.equal(viewOf(t, tk(t, btn)).players[btn].cards.length, 2); // 本人には見える
});
test('カードあり: 3人オールインで場札を順にめくり、サイドポットを自動で分配', () => {
const t = makeTable([100, 300, 500], { mode: 'friends' });
t.start(T(0), 0);
const h = t.hand;
// 席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(t, h.toAct), o.canRaise ? 'raise' : 'call', o.canRaise ? o.maxRaiseTo : 0), null);
}
assert.ok(h.runout && h.revealed);
assert.equal(viewOf(t, SPECTATOR).players[2].cards.length, 2);
const step = config.RUNOUT_STEP_MS;
t.tick(0);
// 一時停止中はめくらない
t.togglePause(T(0), 0);
t.tick(10 * step);
assert.equal(h.board.length, 0);
t.togglePause(T(0), 10 * step);
t.tick(10 * step + step - 1);
assert.equal(h.board.length, 0);
t.tick(11 * step);
assert.equal(h.board.length, 3);
t.tick(12 * step);
assert.equal(h.board.length, 4);
t.tick(13 * step);
assert.equal(h.board.length, 5);
assert.ok(!h.finished);
t.tick(14 * step);
assert.ok(h.finished && h.showdown);
// メイン 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, r.handName]),
[
[300, [0], 'スリーカード'],
[400, [1], 'スリーカード'],
]
);
});
test('カードあり: 引き分けは山分け', () => {
const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
rig(h, [['2c', '3d'], ['2d', '3c'], ['4h', '5h']], ['As', 'Ks', 'Qs', 'Js', 'Ts']); // 全員ロイヤル
t.act(tk(t, btn), 'raise', 40);
t.act(tk(t, sb), 'call', 0);
t.act(tk(t, bb), 'call', 0);
checkDown(t);
assert.ok(h.finished);
assert.equal(t.seats[sb].stack, 1000);
assert.equal(t.seats[bb].stack, 1000);
assert.equal(t.seats[btn].stack, 1000);
assert.deepEqual(h.results[0].winners, [sb, bb, btn]);
assert.equal(h.results[0].handName, 'ロイヤルフラッシュ');
});
test('カードあり: オールインのあとに退席しても手は最後まで生きている', () => {
const t = makeTable([1000, 1000], { mode: 'friends' });
t.start(T(0), 0);
const h = t.hand;
const [a, b] = h.order;
rig(h, [['As', 'Ah'], ['7c', '2d']], ['Ad', 'Kd', '9c', '5s', '3h']);
t.act(tk(t, h.toAct), 'raise', h.options(h.toAct).maxRaiseTo);
t.act(tk(t, h.toAct), 'call', 0);
assert.ok(h.runout);
assert.ok(t.leave(tk(t, a)));
assert.ok(h.runout && !h.finished);
const step = config.RUNOUT_STEP_MS;
for (let k = 0; k <= 4; k++) t.tick(k * step);
assert.ok(h.finished && h.showdown);
assert.deepEqual(h.results[0].winners, [a]);
assert.equal(t.seats[a].stack, 2000);
assert.equal(t.seats[b].stack, 0);
});
test('カードあり: ランダムに遊んでもチップの合計が変わらず、必ず終わる', () => {
let rnd = 777;
const rand = (n) => {
rnd = (rnd * 1103515245 + 12345) % 2147483648;
return rnd % n;
};
let showdowns = 0;
let runouts = 0;
for (let game = 0; game < 40; game++) {
const n = 2 + (game % 8);
const stacks = Array.from({ length: n }, () => 20 + rand(2000));
const t = makeTable(stacks, { mode: 'friends' });
const sum = stacks.reduce((a, b) => a + b, 0);
t.start(T(0), 0);
let now = 0;
let prev = null;
for (let step = 0; step < 20000 && t.hand; step++) {
const h = t.hand;
if (h !== prev) {
if (prev && prev.showdown) {
showdowns++;
assert.equal(prev.board.length, 5);
}
prev = h;
assert.equal(new Set([...deckOf(h), ...h.list.flatMap((p) => p.cards)]).size, 52);
}
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);
if (err && o.canCheck) err = t.act(me, 'check', 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 {
assert.equal(h.awaitingWinners, false);
if (h.runout && t.runoutAt == null) runouts++;
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 && runouts > 20, `showdowns=${showdowns} runouts=${runouts}`);
});
// ---------- CPU ----------
const ai = require('../server/ai');
// 再現できる乱数
function seeded(seed) {
let x = seed;
return () => {
x = (x * 1103515245 + 12345) % 2147483648;
return x / 2147483648;
};
}
test('役の判定: 選んだ5枚は7枚全体と同じ強さ', () => {
const all = [];
for (const r of '23456789TJQKA') for (const su of 'shdc') all.push(r + su);
for (let i = 0; i < 3000; i++) {
for (let j = all.length - 1; j > 0; j--) {
const k = crypto.randomInt(j + 1);
[all[j], all[k]] = [all[k], all[j]];
}
const seven = all.slice(0, 7);
const best = bestHand(seven);
assert.equal(best.cards.length, 5);
assert.ok(best.cards.every((c) => seven.includes(c)));
assert.equal(compareScore(bestHand(best.cards).score, best.score), 0, `${seven}`);
}
});
test('CPU: 勝率の見積もり', () => {
const rng = seeded(42);
const near = (v, target) => assert.ok(Math.abs(v - target) < 0.03, `${v} ≉ ${target}`);
near(ai.equity(['As', 'Ah'], [], 1, 4000, rng), 0.85);
near(ai.equity(['7s', '2h'], [], 1, 4000, rng), 0.35);
// ナッツは負けない
assert.equal(ai.equity(['As', 'Ks'], ['Qs', 'Js', 'Ts'], 3, 500, rng), 1);
});
test('CPU: 強い手はレイズし、弱い手は大きなベットに降りる', () => {
const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
t.start(T(0), 0);
const h = t.hand;
const [sb, bb, btn] = h.order;
rig(h, [['7c', '2d'], ['8h', '3s'], ['As', 'Ah']], ['Kd', '9c', '4s', '5h', 'Jd']);
const rng = seeded(1);
const d = ai.decide(h, btn, { rng });
assert.equal(d.type, 'raise');
t.act(tk(t, btn), 'raise', 1000); // オールイン
assert.equal(ai.decide(h, sb, { rng }).type, 'fold');
});
test('CPU: どんな状況でも正しいアクションを返す', () => {
const rng = seeded(7);
let actions = 0;
for (let game = 0; game < 12; game++) {
const n = 2 + (game % 8);
const stacks = Array.from({ length: n }, () => 20 + Math.floor(rng() * 2000));
const t = makeTable(stacks, { mode: 'friends' });
const sum = stacks.reduce((a, b) => a + b, 0);
t.start(T(0), 0);
let now = 0;
for (let step = 0; step < 5000 && t.hand && t.hand.number <= 15; step++) {
const h = t.hand;
if (!h.finished && h.toAct != null) {
const style = ai.randomStyle(rng);
const d = ai.decide(h, h.toAct, { style, rng, iterations: 60 });
assert.equal(h.act(h.toAct, d.type, d.amount), null, JSON.stringify(d));
actions++;
} else {
t.tick((now += 10 ** 5));
}
const inPot = t.hand && !t.hand.finished ? t.hand.potTotal : 0;
assert.equal(t.seats.reduce((a, s) => a + (s ? s.stack : 0), 0) + inPot, sum);
}
}
assert.ok(actions > 300, `actions=${actions}`);
});
test('CPU戦: CPU が席に着き、ホストは人間のまま、CPU は自動で行動する', () => {
const t = new Table({
id: 'c',
name: 'cpu',
startingStack: 1000,
smallBlind: 10,
bigBlind: 20,
blindTimerEnabled: false,
blindIntervalMin: 10,
hostToken: T(0),
mode: 'cpu',
cpuCount: 3,
});
assert.equal(t.cardsEnabled, true);
assert.deepEqual(t.seats.map((s) => Boolean(s && s.bot)), [false, true, true, true, false, false, false, false, false]);
assert.equal(t.join(T(0), 'me'), 0);
assert.equal(t.isHost(T(0)), true);
const v = t.publicState(T(0), new Set([T(0)]));
assert.equal(v.mode, 'cpu');
assert.ok(v.seats[1].bot && v.seats[1].connected);
assert.equal(v.seats[0].bot, false);
assert.equal(t.start(T(0), 0), null);
// 人間の手番まで CPU が進める(人間の手番は代わりに動かない)
let now = 0;
for (let k = 0; k < 200 && t.hand.toAct !== 0 && !t.hand.finished; k++) t.tick((now += 5000));
if (!t.hand.finished) {
const before = t.hand.actions;
t.tick((now += 60000));
t.tick((now += 60000));
assert.equal(t.hand.toAct, 0);
assert.equal(t.hand.actions, before);
}
// 人間が離席すると CPU だけで次のハンドは始まらない
t.setSittingOut(T(0), true);
for (let k = 0; k < 400 && t.hand; k++) t.tick((now += 5000));
assert.equal(t.hand, null);
t.setSittingOut(T(0), false);
// チップがなくなった CPU は次のハンドでリバイ
t.seats[2].stack = 0;
for (let k = 0; k < 10 && !t.hand; k++) t.tick((now += 5000));
assert.ok(t.hand);
assert.equal(t.seats[2].buyIns, 2);
assert.ok(t.hand.players.has(2));
// ホストが退席しても CPU はホストにならない
t.leave(T(0));
assert.equal(t.hostToken, null);
t.join(T(5), 'friend');
assert.equal(t.isHost(T(5)), true);
});
test('CPU戦: 人間が全員退席したらテーブルを閉じる(ハンド中でも)', () => {
const opts = {
id: 'c',
name: 'cpu',
startingStack: 1000,
smallBlind: 10,
bigBlind: 20,
blindTimerEnabled: false,
blindIntervalMin: 10,
hostToken: T(0),
};
const t = new Table({ ...opts, mode: 'cpu', cpuCount: 2 });
t.join(T(0), 'me');
t.join(T(5), 'friend');
t.start(T(0), 0);
t.leave(T(0));
assert.equal(t.shouldClose(), false); // まだ友達がいる
t.leave(T(5));
assert.equal(t.shouldClose(), true);
// CPU戦以外は閉じない(これまでどおり、誰も接続していない状態が続いたら削除)
const f = new Table({ ...opts, mode: 'friends' });
f.join(T(0), 'me');
f.leave(T(0));
assert.equal(f.shouldClose(), false);
});