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>
This commit is contained in:
agomizi1cmandClaude Opus 5.5 committed 2026-10-17 16:55:25 +09:00
1 parent 66907345ff
commit 0d3a054f0d
12 files changed
+550 -46

No files matched your search

+14 -7
View File
@@ -6,16 +6,22 @@
## ルール・仕様 ## ルール・仕様
基本はカードを実物で配り、このサイトはチップの代わりに使う(ベット・ポット・スタックの管理)。 テーブル作成時に種類を選ぶ(既定はキャッシュオンリー)。
実物のカードがないときは、テーブル作成時に「カードを配る」をオンにすると、サイトがカードを配って勝敗まで自動で判定する(既定はオフ)。
| 種類 | 内容 |
| --- | --- |
| キャッシュオンリー | カードは実物で配り、サイトはチップの代わりに使う(ベット・ポット・スタックの管理)。ショーダウンの勝者はホストが選ぶ |
| 友人戦 | 実物のカードがなくても遊べる。サイトがカードを配り、勝敗とポットの分配まで自動で判定する |
| CPU戦 | 友人戦に CPU プレイヤー(1〜8人)が加わる。空いている席には友達も参加できる |
- ノーリミット・テキサスホールデムのリングゲーム(最大9人)。ホストが START を押すと、以降は2人以上いる限り自動でハンドが続く。 - ノーリミット・テキサスホールデムのリングゲーム(最大9人)。ホストが START を押すと、以降は2人以上いる限り自動でハンドが続く。
- 画面にディーラーボタン(D)・SB・BB と、いまのストリート(PREFLOP / FLOP / TURN / RIVER)が出るので、それに合わせて実物のカードを配る。 - 画面にディーラーボタン(D)・SB・BB と、いまのストリート(PREFLOP / FLOP / TURN / RIVER)が出るので、それに合わせて実物のカードを配る。
- ブラインドは自動で支払われ、ハンド開始時のレベルで固定。ヘッズアップはボタンが SB。 - ブラインドは自動で支払われ、ハンド開始時のレベルで固定。ヘッズアップはボタンが SB。
- 各自が自分のスマホで Fold / Check / Call / Bet / Raise を行う。最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。 - 各自が自分のスマホで Fold / Check / Call / Bet / Raise を行う。最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。
- ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。 - ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。
- **ショーダウン(カード機能オフ)**: カードを見せ合い、ホストが勝った人を画面で選んで確定する(ポットの分配はテーブルのホストだけが行える)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。 - **ショーダウン(キャッシュオンリー)**: カードを見せ合い、ホストが勝った人を画面で選んで確定する(ポットの分配はテーブルのホストだけが行える)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。
- **カード機能オン**: 各自のスマホに自分の手札だけが表示され、場札はストリートごとに画面に配られる。ショーダウンでは残った人の手札を公開して役を判定し、ポット(サイドポット含む)を自動で分配する。引き分けは山分け(端数はボタンの左から)。全員オールインになったら手札を公開し、残りの場札を順にめくる。山札は暗号論的乱数でシャッフルし、サーバの外に出さない(他人の手札は公開されるまで送らない)。 - **カードを配るテーブル(友人戦・CPU戦)**: 各自のスマホに自分の手札だけが表示され、場札はストリートごとに画面に配られる。ショーダウンでは残った人の手札を公開して役を判定し、ポット(サイドポット含む)を自動で分配する。引き分けは山分け(端数はボタンの左から)。全員オールインになったら手札を公開し、残りの場札を順にめくる。山札は暗号論的乱数でシャッフルし、サーバの外に出さない(他人の手札は公開されるまで送らない)。
- **CPU**: 自前実装(`server/ai.js`、外部ライブラリなし)。自分の手札と場札から、残っている相手に勝つ確率をモンテカルロ法で見積もり、ポットオッズ・レイズの回数・相手の人数から行動を決める。CPU ごとに攻撃性・ブラフ頻度がランダムに違う。相手の手札は見ない。1手ごとに 0.7〜1.8 秒考える。チップがなくなると次のハンドで自動でリバイする。人間が1人も参加していないと次のハンドは始まらない。CPU はホストにならない。
- 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。 - 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。
- 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。 - 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。
- チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。 - チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。
@@ -73,9 +79,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ハンドの進行(ブラインド・ベッティング・サイドポット・勝者への分配、友人戦・CPU戦での配札とショーダウン) |
| `server/cards.js` | 山札のシャッフルと役の判定(カード機能オン時) | | `server/cards.js` | 山札のシャッフルと役の判定(カードを配るテーブル) |
| `test/` | チップ処理・役の判定のテスト(`npm test`) | | `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` | 各画面 |
+17 -9
View File
@@ -16,8 +16,8 @@
const timerInput = $('timer'); const timerInput = $('timer');
const intervalInput = $('interval'); const intervalInput = $('interval');
const scheduleEl = $('schedule'); const scheduleEl = $('schedule');
const cardsInput = $('cards'); const modeHint = $('mode-hint');
const cardsHint = $('cards-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');
@@ -68,16 +68,23 @@
.join(''); .join('');
} }
function updateCardsHint() { const MODE_HINTS = {
cardsHint.textContent = cardsInput.checked 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();
updateCardsHint(); updateMode();
} }
stackInput.addEventListener('input', () => { stackInput.addEventListener('input', () => {
@@ -100,7 +107,7 @@
}); });
timerInput.addEventListener('change', refresh); timerInput.addEventListener('change', refresh);
intervalInput.addEventListener('input', refresh); intervalInput.addEventListener('input', refresh);
cardsInput.addEventListener('change', refresh); form.querySelectorAll('input[type="radio"]').forEach((el) => el.addEventListener('change', refresh));
$('reroll').addEventListener('click', suggestName); $('reroll').addEventListener('click', suggestName);
function validate() { function validate() {
@@ -138,7 +145,8 @@
bigBlind: int(bbInput), bigBlind: int(bbInput),
blindTimerEnabled: timerInput.checked, blindTimerEnabled: timerInput.checked,
blindIntervalMin: int(intervalInput), blindIntervalMin: int(intervalInput),
cardsEnabled: cardsInput.checked, 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 -1
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,7 +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>
${t.cardsEnabled ? '<span>🃏 カードあり</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="満席(観戦のみ)"' : ''}>
+24
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;
+8 -2
View File
@@ -9,6 +9,8 @@
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 で絵文字として描画されないように // U+FE0E: iOS で絵文字として描画されないように
const SUIT_SYMBOL = { s: '♠︎', h: '♥︎', d: '♦︎', c: '♣︎' }; 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' };
@@ -234,6 +236,7 @@
.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');
@@ -273,7 +276,7 @@
return ` return `
<div class="${classes.join(' ')}"> <div class="${classes.join(' ')}">
<div class="avatar">${AVATAR_SVG}${markers}${cards}</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>
@@ -324,7 +327,10 @@
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 && 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 = '次のハンドを準備中…';
+22 -9
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">
@@ -49,15 +71,6 @@
</div> </div>
<div class="schedule" id="schedule" hidden></div> <div class="schedule" id="schedule" hidden></div>
<div class="switch-row">
<span>カードを配る</span>
<label class="switch">
<input id="cards" type="checkbox" aria-label="カードを配る">
<span></span>
</label>
</div>
<div class="hint" id="cards-hint">オフ: 実物のカードで遊び、ショーダウンの勝者はホストが選ぶ</div>
<div class="error-text" id="error"></div> <div class="error-text" id="error"></div>
<button class="btn btn-orange btn-block mt-8" id="submit" type="submit">テーブルを作成</button> <button class="btn btn-orange btn-block mt-8" id="submit" type="submit">テーブルを作成</button>
</form> </form>
+213
View File
@@ -0,0 +1,213 @@
'use strict';
// CPU プレイヤーの思考。
// モンテカルロで「残っている相手に勝つ確率(エクイティ)」を見積もり、
// ポットオッズ・ポジション・その CPU の性格(攻撃性・ブラフ頻度)から行動を決める。
// 相手の手札は見ない(自分の手札と場札、公開されているベット状況だけを使う)。
const RANKS = '23456789TJQKA';
const SUITS = 'shdc';
// "As" → 0〜51(rank * 4 + suit)
const toInt = (c) => RANKS.indexOf(c[0]) * 4 + SUITS.indexOf(c[1]);
// 13ビットのランクの集合から最も高いストレートの上端(0〜12)。無ければ -1
function straightHigh(mask) {
for (let h = 12; h >= 4; h--) {
const need = 0b11111 << (h - 4);
if ((mask & need) === need) return h;
}
// A-2-3-4-5
if ((mask & 0b1000000001111) === 0b1000000001111) return 3;
return -1;
}
// [役, 比較用の数字...] を1つの整数にする(大きいほど強い)
function encode(category, kickers) {
let v = category;
for (let i = 0; i < 5; i++) v = v * 16 + (kickers[i] === undefined ? 0 : kickers[i] + 1);
return v;
}
// 上位から n 個のランク(mask のビット)
function topRanks(mask, n, exclude = []) {
const out = [];
for (let r = 12; r >= 0 && out.length < n; r--) if (mask & (1 << r) && !exclude.includes(r)) out.push(r);
return out;
}
// 5〜7枚(整数)の最強の役の強さ。cards.js の bestHand と同じ順序になる(テストで確認)
function evaluate(cards) {
const counts = new Array(13).fill(0);
const suitCount = [0, 0, 0, 0];
const suitMask = [0, 0, 0, 0];
let mask = 0;
for (const c of cards) {
const r = c >> 2;
const s = c & 3;
counts[r]++;
suitCount[s]++;
suitMask[s] |= 1 << r;
mask |= 1 << r;
}
let flushMask = 0;
for (let s = 0; s < 4; s++) if (suitCount[s] >= 5) flushMask = suitMask[s];
if (flushMask) {
const sf = straightHigh(flushMask);
if (sf >= 0) return encode(8, [sf]);
}
let quad = -1;
const trips = [];
const pairs = [];
for (let r = 12; r >= 0; r--) {
if (counts[r] === 4) quad = r;
else if (counts[r] === 3) trips.push(r);
else if (counts[r] === 2) pairs.push(r);
}
if (quad >= 0) return encode(7, [quad, topRanks(mask, 1, [quad])[0]]);
if (trips.length && (trips.length > 1 || pairs.length)) {
const pair = Math.max(trips[1] === undefined ? -1 : trips[1], pairs[0] === undefined ? -1 : pairs[0]);
return encode(6, [trips[0], pair]);
}
if (flushMask) return encode(5, topRanks(flushMask, 5));
const st = straightHigh(mask);
if (st >= 0) return encode(4, [st]);
if (trips.length) return encode(3, [trips[0], ...topRanks(mask, 2, [trips[0]])]);
if (pairs.length >= 2) return encode(2, [pairs[0], pairs[1], topRanks(mask, 1, [pairs[0], pairs[1]])[0]]);
if (pairs.length) return encode(1, [pairs[0], ...topRanks(mask, 3, [pairs[0]])]);
return encode(0, topRanks(mask, 5));
}
// hole / board は "As" 形式。opponents 人のランダムな手札を相手にした勝率(引き分けは等分)
function equity(hole, board, opponents, iterations, rng = Math.random) {
const mine = hole.map(toInt);
const known = board.map(toInt);
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 best = 0;
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 (v > best) best = v;
}
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 = { evaluate, equity, decide, randomStyle, toInt, straightHigh };
+6
View File
@@ -67,6 +67,12 @@ module.exports = {
SHOWDOWN_MS: 4000, SHOWDOWN_MS: 4000,
CARD_SHOWDOWN_MS: 6000, 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,
+16 -1
View File
@@ -29,6 +29,10 @@ class Hand {
this.pot = 0; // 前のストリートまでに集めた額 this.pot = 0; // 前のストリートまでに集めた額
this.currentBet = 0; this.currentBet = 0;
this.minRaise = bb; 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;
@@ -75,6 +79,11 @@ class Hand {
return this.list.filter((p) => !p.folded); return this.list.filter((p) => !p.folded);
} }
// 前のストリートまでのポット + このストリートのベット
get potTotal() {
return this.pot + this.list.reduce((sum, p) => sum + p.bet, 0);
}
put(p, amount) { put(p, amount) {
const s = this.seats[p.seat]; const s = this.seats[p.seat];
s.stack -= amount; s.stack -= amount;
@@ -163,9 +172,11 @@ class Hand {
const raiseSize = amount - this.currentBet; const raiseSize = amount - this.currentBet;
this.put(p, amount - p.bet); this.put(p, amount - p.bet);
p.last = { type: o.isBet ? 'BET' : 'RAISE', amount }; p.last = { type: o.isBet ? 'BET' : 'RAISE', amount };
this.aggressor = seat;
if (raiseSize >= this.minRaise) { if (raiseSize >= this.minRaise) {
// 正規のレイズ: 他の人はもう一度アクションできる // 正規のレイズ: 他の人はもう一度アクションできる
this.minRaise = raiseSize; this.minRaise = raiseSize;
this.raises++;
for (const q of this.list) if (q !== p) q.acted = false; for (const q of this.list) if (q !== p) q.acted = false;
} }
// 足りないオールインのレイズはアクション済みの人に再レイズ権を与えない // 足りないオールインのレイズはアクション済みの人に再レイズ権を与えない
@@ -175,6 +186,7 @@ class Hand {
} }
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet }; if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet };
p.acted = true; p.acted = true;
this.actions++;
this.setNextActor(seat); this.setNextActor(seat);
return null; return null;
} }
@@ -225,6 +237,9 @@ class Hand {
if (this.live().length === 1) return this.finishFoldWin(); if (this.live().length === 1) return this.finishFoldWin();
this.currentBet = 0; this.currentBet = 0;
this.minRaise = this.bb; this.minRaise = this.bb;
this.raises = 0;
this.prevAggressor = this.aggressor;
this.aggressor = null;
const noMoreBetting = this.live().filter((p) => !p.allIn).length < 2; const noMoreBetting = this.live().filter((p) => !p.allIn).length < 2;
if (!this.cards) { if (!this.cards) {
@@ -365,7 +380,7 @@ class Hand {
runout: this.runout, 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,
+9 -3
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,7 +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 cardsEnabled = b.cardsEnabled === true; 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: 'テーブル数が上限に達しています' });
@@ -124,6 +125,10 @@ app.post('/api/tables', (req, res) => {
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, 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({
@@ -133,7 +138,8 @@ app.post('/api/tables', (req, res) => {
bigBlind, bigBlind,
blindTimerEnabled, blindTimerEnabled,
blindIntervalMin: blindTimerEnabled ? blindIntervalMin : 10, blindIntervalMin: blindTimerEnabled ? blindIntervalMin : 10,
cardsEnabled, mode,
cpuCount: mode === 'cpu' ? cpuCount : 0,
hostToken, hostToken,
}); });
broadcastLobby(); broadcastLobby();
+84 -8
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,14 +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 = opts.cardsEnabled === true; // カード機能: サーバがカードを配り、ショーダウンの勝敗も自動で判定する(キャッシュオンリーは実物のカード)
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;
@@ -38,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;
} }
@@ -74,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(観戦)
@@ -110,7 +146,7 @@ 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;
@@ -130,6 +166,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
@@ -143,6 +186,7 @@ class Table {
const { sb, bb } = this.blinds; const { sb, bb } = this.blinds;
this.nextHandAt = null; this.nextHandAt = null;
this.runoutAt = null; this.runoutAt = null;
this.botTurn = null;
this.hand = new Hand({ this.hand = new Hand({
number: this.handNumber, number: this.handNumber,
seats: this.seats, seats: this.seats,
@@ -217,6 +261,7 @@ class Table {
// 止めていた時間だけ次のハンドの開始・場札をめくる時刻を後ろにずらす // 止めていた時間だけ次のハンドの開始・場札をめくる時刻を後ろにずらす
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; 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;
@@ -231,7 +276,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;
@@ -242,6 +313,8 @@ class Table {
} }
if (this.paused) return changed; if (this.paused) return changed;
if (this.botStep(now)) changed = true;
const h = this.hand; const h = this.hand;
if (h && h.runout) { if (h && h.runout) {
if (this.runoutAt == null) this.runoutAt = now + config.RUNOUT_STEP_MS; if (this.runoutAt == null) this.runoutAt = now + config.RUNOUT_STEP_MS;
@@ -292,6 +365,7 @@ class Table {
timerEnabled: this.timerEnabled, timerEnabled: this.timerEnabled,
intervalMin: this.intervalMin, intervalMin: this.intervalMin,
cardsEnabled: this.cardsEnabled, cardsEnabled: this.cardsEnabled,
mode: this.mode,
createdAt: this.createdAt, createdAt: this.createdAt,
}; };
} }
@@ -313,6 +387,7 @@ class Table {
startingStack: this.startingStack, startingStack: this.startingStack,
maxSeats: this.maxSeats, maxSeats: this.maxSeats,
cardsEnabled: this.cardsEnabled, cardsEnabled: this.cardsEnabled,
mode: this.mode,
level: this.level, level: this.level,
smallBlind: sb, smallBlind: sb,
bigBlind: bb, bigBlind: bb,
@@ -336,7 +411,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 }),
} }
@@ -402,4 +478,4 @@ class TableManager {
} }
} }
module.exports = { TableManager, Table }; module.exports = { TableManager, Table, MODES };
+134 -6
View File
@@ -395,7 +395,7 @@ test('カードなしのテーブルでは手札も場札も扱わない', () =>
}); });
test('カードあり: 自分の手札だけが見え、ストリートごとに場札が配られ、勝者は自動で決まる', () => { test('カードあり: 自分の手札だけが見え、ストリートごとに場札が配られ、勝者は自動で決まる', () => {
const t = makeTable([1000, 1000, 1000], { cardsEnabled: true }); const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
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;
@@ -433,7 +433,7 @@ test('カードあり: 自分の手札だけが見え、ストリートごとに
}); });
test('カードあり: フォールドした人の手札は公開されない', () => { test('カードあり: フォールドした人の手札は公開されない', () => {
const t = makeTable([1000, 1000, 1000], { cardsEnabled: true }); const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
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;
@@ -449,7 +449,7 @@ test('カードあり: フォールドした人の手札は公開されない',
}); });
test('カードあり: 3人オールインで場札を順にめくり、サイドポットを自動で分配', () => { test('カードあり: 3人オールインで場札を順にめくり、サイドポットを自動で分配', () => {
const t = makeTable([100, 300, 500], { cardsEnabled: true }); const t = makeTable([100, 300, 500], { mode: 'friends' });
t.start(T(0), 0); t.start(T(0), 0);
const h = t.hand; const h = t.hand;
// 席0 が最強、席1 が2番目、席2 が最弱 // 席0 が最強、席1 が2番目、席2 が最弱
@@ -493,7 +493,7 @@ test('カードあり: 3人オールインで場札を順にめくり、サイ
}); });
test('カードあり: 引き分けは山分け', () => { test('カードあり: 引き分けは山分け', () => {
const t = makeTable([1000, 1000, 1000], { cardsEnabled: true }); const t = makeTable([1000, 1000, 1000], { mode: 'friends' });
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;
@@ -511,7 +511,7 @@ test('カードあり: 引き分けは山分け', () => {
}); });
test('カードあり: めくっている途中に1人を残して退席したら残った人が勝つ', () => { test('カードあり: めくっている途中に1人を残して退席したら残った人が勝つ', () => {
const t = makeTable([1000, 1000], { cardsEnabled: true }); const t = makeTable([1000, 1000], { mode: 'friends' });
t.start(T(0), 0); t.start(T(0), 0);
const h = t.hand; const h = t.hand;
t.act(tk(t, h.toAct), 'raise', h.options(h.toAct).maxRaiseTo); t.act(tk(t, h.toAct), 'raise', h.options(h.toAct).maxRaiseTo);
@@ -533,7 +533,7 @@ test('カードあり: ランダムに遊んでもチップの合計が変わら
for (let game = 0; game < 40; game++) { for (let game = 0; game < 40; game++) {
const n = 2 + (game % 8); const n = 2 + (game % 8);
const stacks = Array.from({ length: n }, () => 20 + rand(2000)); const stacks = Array.from({ length: n }, () => 20 + rand(2000));
const t = makeTable(stacks, { cardsEnabled: true }); const t = makeTable(stacks, { mode: 'friends' });
const sum = stacks.reduce((a, b) => a + b, 0); const sum = stacks.reduce((a, b) => a + b, 0);
t.start(T(0), 0); t.start(T(0), 0);
let now = 0; let now = 0;
@@ -570,3 +570,131 @@ test('カードあり: ランダムに遊んでもチップの合計が変わら
} }
assert.ok(showdowns > 100 && runouts > 20, `showdowns=${showdowns} runouts=${runouts}`); assert.ok(showdowns > 100 && runouts > 20, `showdowns=${showdowns} runouts=${runouts}`);
}); });
// ---------- CPU ----------
const ai = require('../server/ai');
const { newDeck } = require('../server/cards');
// 再現できる乱数
function seeded(seed) {
let x = seed;
return () => {
x = (x * 1103515245 + 12345) % 2147483648;
return x / 2147483648;
};
}
test('CPU: 高速な役判定は bestHand と同じ強さの順になる', () => {
for (let i = 0; i < 3000; i++) {
const d = newDeck();
const a = d.slice(0, 7);
const b = d.slice(7, 14);
const fast = Math.sign(ai.evaluate(a.map(ai.toInt)) - ai.evaluate(b.map(ai.toInt)));
const slow = Math.sign(compareScore(bestHand(a).score, bestHand(b).score));
assert.equal(fast, slow, `${a} / ${b}`);
}
});
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);
});