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>
This commit is contained in:
agomizi1cmandClaude Opus 5.5 committed 2026-10-17 16:44:22 +09:00
1 parent 6d33440048
commit 66907345ff
13 files changed
+653 -42

No files matched your search

+8 -5
View File
@@ -6,19 +6,21 @@
## ルール・仕様 ## ルール・仕様
カードは実物で配り、このサイトはチップの代わりに使う(ベット・ポット・スタックの管理)。 基本はカードを実物で配り、このサイトはチップの代わりに使う(ベット・ポット・スタックの管理)。
実物のカードがないときは、テーブル作成時に「カードを配る」をオンにすると、サイトがカードを配って勝敗まで自動で判定する(既定はオフ)。
- ノーリミット・テキサスホールデムのリングゲーム(最大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 を行う。最低レイズ額は直前のレイズ幅以上。足りないオールインのレイズは、すでにアクションした人に再レイズ権を与えない。
- ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。 - ベッティングが終わると次のストリートへ。全員オールインならその時点でショーダウンになる(残りのカードは実物でめくる)。
- **ショーダウン**: カードを見せ合い、ホストが勝った人を画面で選んで確定する(ポットの分配はテーブルのホストだけが行える)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。 - **ショーダウン(カード機能オフ)**: カードを見せ合い、ホストが勝った人を画面で選んで確定する(ポットの分配はテーブルのホストだけが行える)。サイドポットがあるときはポットごとに選ぶ。複数選ぶと山分け(端数はボタンの左から)。
- **カード機能オン**: 各自のスマホに自分の手札だけが表示され、場札はストリートごとに画面に配られる。ショーダウンでは残った人の手札を公開して役を判定し、ポット(サイドポット含む)を自動で分配する。引き分けは山分け(端数はボタンの左から)。全員オールインになったら手札を公開し、残りの場札を順にめくる。山札は暗号論的乱数でシャッフルし、サーバの外に出さない(他人の手札は公開されるまで送らない)。
- 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。 - 全員フォールドしたら残った人が自動でポットを獲得。誰もコールしなかった分は自動で返る。
- 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。 - 「離席」にすると次のハンドから配られない(手番が来たら自動でチェック/フォールド)。「復帰する」で戻る。
- チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。 - チップがなくなったら開始スタックでリバイできる。画面下に収支(現在のチップ − バイイン合計)を表示。
- ハンド中に退席するとフォールド扱い(出したチップはポットに残る)。 - ハンド中に退席するとフォールド扱い(出したチップはポットに残る)。
- ホストの一時停止中は、アクション・勝者の確定・ブラインドタイマー・次のハンドの開始がすべて止まる。 - ホストの一時停止中は、アクション・勝者の確定・オールイン後の場札・ブラインドタイマー・次のハンドの開始がすべて止まる。
## ローカルで動かす ## ローカルで動かす
@@ -71,8 +73,9 @@ 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ハンドの進行(ブラインド・ベッティング・サイドポット・勝者への分配、カード機能オン時の配札とショーダウン) |
| `test/` | チップ処理のテスト(`npm test`) | | `server/cards.js` | 山札のシャッフルと役の判定(カード機能オン時) |
| `test/` | チップ処理・役の判定のテスト(`npm test`) |
| `server/config.js` | `.env` の読み込みと各種上限値 | | `server/config.js` | `.env` の読み込みと各種上限値 |
| `public/assets/blinds.js` | ブラインド計算(サーバ・ブラウザ共用) | | `public/assets/blinds.js` | ブラインド計算(サーバ・ブラウザ共用) |
| `public/*.html`, `public/assets/*.js` | 各画面 | | `public/*.html`, `public/assets/*.js` | 各画面 |
+11
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 cardsInput = $('cards');
const cardsHint = $('cards-hint');
const blindHint = $('blind-hint'); const blindHint = $('blind-hint');
const errorEl = $('error'); const errorEl = $('error');
const submitBtn = $('submit'); const submitBtn = $('submit');
@@ -66,9 +68,16 @@
.join(''); .join('');
} }
function updateCardsHint() {
cardsHint.textContent = cardsInput.checked
? 'オン: 各自のスマホに手札が配られ、勝敗とポットの分配は自動'
: 'オフ: 実物のカードで遊び、ショーダウンの勝者はホストが選ぶ';
}
function refresh() { function refresh() {
updateHint(); updateHint();
updateSchedule(); updateSchedule();
updateCardsHint();
} }
stackInput.addEventListener('input', () => { stackInput.addEventListener('input', () => {
@@ -91,6 +100,7 @@
}); });
timerInput.addEventListener('change', refresh); timerInput.addEventListener('change', refresh);
intervalInput.addEventListener('input', refresh); intervalInput.addEventListener('input', refresh);
cardsInput.addEventListener('change', refresh);
$('reroll').addEventListener('click', suggestName); $('reroll').addEventListener('click', suggestName);
function validate() { function validate() {
@@ -128,6 +138,7 @@
bigBlind: int(bbInput), bigBlind: int(bbInput),
blindTimerEnabled: timerInput.checked, blindTimerEnabled: timerInput.checked,
blindIntervalMin: int(intervalInput), blindIntervalMin: int(intervalInput),
cardsEnabled: cardsInput.checked,
token: Store.token, token: Store.token,
}); });
location.href = '/table/' + encodeURIComponent(id); location.href = '/table/' + encodeURIComponent(id);
+1
View File
@@ -61,6 +61,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>' : ''}
</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="満席(観戦のみ)"' : ''}>
+88
View File
@@ -532,6 +532,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 +680,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 +740,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; }
+75 -3
View File
@@ -1,5 +1,5 @@
// プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る // プレイ画面: サーバから受け取ったテーブル状態を描画し、アクションを送る
// カードは実物で配るので、ここで扱うのはチップのやり取りだけ // カード機能がオフのテーブルではカードは実物で配るので、ここで扱うのはチップのやり取りだけ
(function () { (function () {
'use strict'; 'use strict';
@@ -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>';
// 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 +20,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 = [];
@@ -93,6 +97,45 @@
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 +160,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 +191,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 +208,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,9 +225,11 @@
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'];
@@ -198,6 +249,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 +273,12 @@
return ` return `
<div class="${classes.join(' ')}"> <div class="${classes.join(' ')}">
<div class="avatar">${AVATAR_SVG}${markers}</div> <div class="avatar">${AVATAR_SVG}${markers}${cards}</div>
<div class="nameplate"> <div class="nameplate">
${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 +303,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;
// 状況 // 状況
@@ -254,6 +325,7 @@
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) status = `${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人以上で再開)';
+9
View File
@@ -49,6 +49,15 @@
</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>
+3 -1
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>
+96
View File
@@ -0,0 +1,96 @@
'use strict';
const crypto = require('crypto');
// カードは "As"(スペードのA), "Td"(ダイヤの10)のような2文字
const RANKS = '23456789TJQKA';
const SUITS = 'shdc';
// 暗号論的乱数で Fisher-Yates シャッフル(山札はサーバの外に出さない)
function newDeck() {
const deck = [];
for (const r of RANKS) for (const s of SUITS) deck.push(r + s);
for (let i = deck.length - 1; i > 0; i--) {
const j = crypto.randomInt(i + 1);
[deck[i], deck[j]] = [deck[j], deck[i]];
}
return deck;
}
const rankValue = (card) => RANKS.indexOf(card[0]) + 2;
// 5枚の役の強さ。配列を先頭から比較して大きいほうが強い
// [役の種類(0〜8), 比較用の数字...]
function score5(cards) {
const vals = cards.map(rankValue).sort((a, b) => b - a);
const flush = cards.every((c) => c[1] === cards[0][1]);
let straightHigh = 0;
if (new Set(vals).size === 5) {
if (vals[0] - vals[4] === 4) straightHigh = vals[0];
else if (vals[0] === 14 && vals[1] === 5) straightHigh = 5; // A-2-3-4-5
}
if (straightHigh && flush) return [8, straightHigh];
// 枚数の多い順、同じ枚数なら数字の大きい順
const counts = new Map();
for (const v of vals) counts.set(v, (counts.get(v) || 0) + 1);
const groups = [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0]);
const byGroup = groups.map((g) => g[0]);
if (groups[0][1] === 4) return [7, ...byGroup];
if (groups[0][1] === 3 && groups[1][1] === 2) return [6, ...byGroup];
if (flush) return [5, ...vals];
if (straightHigh) return [4, straightHigh];
if (groups[0][1] === 3) return [3, ...byGroup];
if (groups[0][1] === 2 && groups[1][1] === 2) return [2, ...byGroup];
if (groups[0][1] === 2) return [1, ...byGroup];
return [0, ...vals];
}
function compareScore(a, b) {
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const d = (a[i] || 0) - (b[i] || 0);
if (d) return d;
}
return 0;
}
const HAND_NAMES = [
'ハイカード',
'ワンペア',
'ツーペア',
'スリーカード',
'ストレート',
'フラッシュ',
'フルハウス',
'フォーカード',
'ストレートフラッシュ',
];
function handName(score) {
if (score[0] === 8 && score[1] === 14) return 'ロイヤルフラッシュ';
return HAND_NAMES[score[0]];
}
// 5〜7枚から最も強い5枚を選ぶ
function bestHand(cards) {
let best = null;
const n = cards.length;
const pick = (start, chosen) => {
if (chosen.length === 5) {
const score = score5(chosen);
if (!best || compareScore(score, best.score) > 0) best = { score, cards: chosen.slice() };
return;
}
for (let i = start; i <= n - (5 - chosen.length); i++) {
chosen.push(cards[i]);
pick(i + 1, chosen);
chosen.pop();
}
};
pick(0, []);
return best && { score: best.score, cards: best.cards, name: handName(best.score) };
}
module.exports = { newDeck, score5, compareScore, bestHand, handName };
+4 -1
View File
@@ -61,8 +61,11 @@ 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,
// 参加者が2人揃ってから次のハンドを始めるまで // 参加者が2人揃ってから次のハンドを始めるまで
NEXT_HAND_DELAY_MS: 2000, NEXT_HAND_DELAY_MS: 2000,
+98 -25
View File
@@ -1,19 +1,29 @@
'use strict'; 'use strict';
// 1ハンド分のチップの動き(ブラインド・ベッティング・ポット分配)。 const { newDeck, bestHand, compareScore } = require('./cards');
// カードは実物で配るので扱わない。ショーダウンでは勝者をプレイヤーが選ぶ。
// 1ハンド分の進行(ブラインド・ベッティング・ポット分配)。
// cards = false: カードは実物で配るので扱わない。ショーダウンでは勝者をホストが選ぶ。
// cards = true : サーバが配り、ショーダウンで役を判定して自動で分配する。
// seats は Table.seats への参照で、スタックはここで直接増減する。 // seats は Table.seats への参照で、スタックはここで直接増減する。
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。 // 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
const STREETS = ['PREFLOP', 'FLOP', 'TURN', 'RIVER']; const STREETS = ['PREFLOP', 'FLOP', 'TURN', '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;
// 山札はサーバの外に出さない
this.deck = cards ? newDeck() : null;
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; // 前のストリートまでに集めた額
@@ -29,6 +39,8 @@ class Hand {
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,
@@ -38,6 +50,7 @@ class Hand {
won: 0, won: 0,
}); });
} }
if (cards) for (let r = 0; r < 2; r++) for (const i of order) this.players.get(i).cards.push(this.deck.pop());
// ヘッズアップはボタンが SB // ヘッズアップはボタンが SB
const headsUp = order.length === 2; const headsUp = order.length === 2;
@@ -53,8 +66,9 @@ class Hand {
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() {
@@ -212,15 +226,41 @@ class Hand {
this.currentBet = 0; this.currentBet = 0;
this.minRaise = this.bb; this.minRaise = this.bb;
// リバーが終わった、または全員オールインでこれ以上ベットが無い → ショーダウン const noMoreBetting = this.live().filter((p) => !p.allIn).length < 2;
if (this.street === 'RIVER' || this.live().filter((p) => !p.allIn).length < 2) { if (!this.cards) {
this.street = 'SHOWDOWN'; // リバーが終わった、または全員オールインでこれ以上ベットが無い → ショーダウン
return; if (this.street === 'RIVER' || noMoreBetting) {
this.street = 'SHOWDOWN';
return;
}
this.street = STREETS[STREETS.indexOf(this.street) + 1];
} else {
if (this.street === 'RIVER') return this.finishShowdown();
if (noMoreBetting) {
// 手札を公開して、残りの場札は Table のタイマーで順にめくる(runoutStep)
this.revealed = true;
this.runout = true;
return;
}
this.dealStreet();
} }
this.street = STREETS[STREETS.indexOf(this.street) + 1];
this.setNextActor(this.button); this.setNextActor(this.button);
} }
dealStreet() {
this.deck.pop(); // バーン
if (this.street === 'PREFLOP') this.board.push(this.deck.pop(), this.deck.pop(), this.deck.pop());
else this.board.push(this.deck.pop());
this.street = STREETS[STREETS.indexOf(this.street) + 1];
}
// オールイン後に場札を1ストリート分めくる。リバーまでめくり終えていたらショーダウン
runoutStep() {
if (!this.runout || this.finished) return;
if (this.street === 'RIVER') this.finishShowdown();
else this.dealStreet();
}
// メインポット・サイドポット(同じ参加者のポットはまとめる) // メインポット・サイドポット(同じ参加者のポットはまとめる)
buildPots() { buildPots() {
const all = this.list; const all = this.list;
@@ -258,38 +298,71 @@ 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.revealed = true;
for (const p of this.live()) p.best = bestHand(p.cards.concat(this.board));
const results = this.buildPots().map((pot) => {
const contenders = pot.eligible.map((s) => this.players.get(s));
let top = null;
for (const c of contenders) if (!top || compareScore(c.best.score, top) > 0) top = c.best.score;
const best = contenders.filter((c) => compareScore(c.best.score, top) === 0);
return {
amount: pot.amount,
winners: this.payout(pot.amount, best.map((c) => c.seat)),
handName: best[0].best.name,
bestCards: best[0].best.cards,
};
});
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.pot + this.list.reduce((sum, p) => sum + p.bet, 0),
+3 -1
View File
@@ -114,6 +114,7 @@ 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 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: 'テーブル数が上限に達しています' });
@@ -132,6 +133,7 @@ app.post('/api/tables', (req, res) => {
bigBlind, bigBlind,
blindTimerEnabled, blindTimerEnabled,
blindIntervalMin: blindTimerEnabled ? blindIntervalMin : 10, blindIntervalMin: blindTimerEnabled ? blindIntervalMin : 10,
cardsEnabled,
hostToken, hostToken,
}); });
broadcastLobby(); broadcastLobby();
@@ -276,7 +278,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()) {
+32 -6
View File
@@ -14,6 +14,8 @@ 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.cardsEnabled = opts.cardsEnabled === true;
this.hostToken = opts.hostToken || null; this.hostToken = opts.hostToken || null;
this.maxSeats = config.MAX_SEATS; this.maxSeats = config.MAX_SEATS;
@@ -28,6 +30,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;
@@ -139,7 +142,16 @@ 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.hand = new Hand({
number: this.handNumber,
seats: this.seats,
order,
button: this.buttonSeat,
sb,
bb,
cards: this.cardsEnabled,
});
} }
// ---- プレイヤー操作(エラー時はメッセージを返す) ---- // ---- プレイヤー操作(エラー時はメッセージを返す) ----
@@ -202,8 +214,9 @@ 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;
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 +231,7 @@ class Table {
return null; return null;
} }
// 時間で進む処理(ブラインドタイマー・次のハンドの開始) // 時間で進む処理(ブラインドタイマー・オールイン後の場札・次のハンドの開始)
// 状態が変わったら true // 状態が変わったら true
tick(now) { tick(now) {
let changed = false; let changed = false;
@@ -229,9 +242,20 @@ class Table {
} }
if (this.paused) return changed; if (this.paused) return changed;
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 +291,19 @@ class Table {
paused: this.paused, paused: this.paused,
timerEnabled: this.timerEnabled, timerEnabled: this.timerEnabled,
intervalMin: this.intervalMin, intervalMin: this.intervalMin,
cardsEnabled: this.cardsEnabled,
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 +312,7 @@ class Table {
name: this.name, name: this.name,
startingStack: this.startingStack, startingStack: this.startingStack,
maxSeats: this.maxSeats, maxSeats: this.maxSeats,
cardsEnabled: this.cardsEnabled,
level: this.level, level: this.level,
smallBlind: sb, smallBlind: sb,
bigBlind: bb, bigBlind: bb,
+225
View File
@@ -6,6 +6,8 @@ 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 { 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文字のトークン
@@ -345,3 +347,226 @@ test('ランダムに遊んでもチップの合計が変わらず、必ず終
} }
assert.ok(showdowns > 100 && sidePots > 20, `showdowns=${showdowns} sidePots=${sidePots}`); assert.ok(showdowns > 100 && sidePots > 20, `showdowns=${showdowns} sidePots=${sidePots}`);
}); });
// ---------- カード機能あり ----------
// 山札の上(pop される順)に指定のカードを積む。holes は h.order の順
function rig(hand, holes, board) {
const used = new Set([...holes.flat(), ...board]);
const rest = hand.deck.concat(...[...hand.players.values()].map((p) => p.cards)).filter((c) => !used.has(c));
hand.order.forEach((seat, k) => (hand.players.get(seat).cards = holes[k].slice()));
// dealStreet はバーン1枚 + 場札を pop する
const seq = ['X', board[0], board[1], board[2], 'X', board[3], 'X', board[4]];
hand.deck = rest.slice(0, rest.length - 3).concat(seq.map((c) => (c === 'X' ? rest.pop() : c)).reverse());
}
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], { cardsEnabled: true });
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 = [...h.deck, ...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], { cardsEnabled: true });
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], { cardsEnabled: true });
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], { cardsEnabled: true });
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('カードあり: めくっている途中に1人を残して退席したら残った人が勝つ', () => {
const t = makeTable([1000, 1000], { cardsEnabled: true });
t.start(T(0), 0);
const h = t.hand;
t.act(tk(t, h.toAct), 'raise', h.options(h.toAct).maxRaiseTo);
t.act(tk(t, h.toAct), 'call', 0);
assert.ok(h.runout);
t.leave(T(1));
assert.ok(h.finished && !h.showdown && !h.runout);
assert.equal(t.seats[0].stack, 2000);
});
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, { cardsEnabled: true });
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([...h.deck, ...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);
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}`);
});