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>
This commit is contained in:
1 parent
02c8e76237
commit
d92953a270
9 files changed
+410
-382
No files matched your search
+6
-80
@@ -5,85 +5,13 @@
|
||||
// ポットオッズ・ポジション・その 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));
|
||||
}
|
||||
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(toInt);
|
||||
const known = board.map(toInt);
|
||||
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);
|
||||
@@ -101,18 +29,16 @@ function equity(hole, board, opponents, iterations, rng = Math.random) {
|
||||
}
|
||||
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) {
|
||||
if (v < me) {
|
||||
lost = true;
|
||||
break;
|
||||
}
|
||||
if (v === me) ties++;
|
||||
if (v > best) best = v;
|
||||
}
|
||||
if (!lost) score += 1 / (ties + 1);
|
||||
}
|
||||
@@ -210,4 +136,4 @@ function decide(hand, seat, { style = DEFAULT_STYLE, rng = Math.random, iteratio
|
||||
return { type: 'fold' };
|
||||
}
|
||||
|
||||
module.exports = { evaluate, equity, decide, randomStyle, toInt, straightHigh };
|
||||
module.exports = { equity, decide, randomStyle };
|
||||
+42
-88
@@ -1,96 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
// 役の判定は @pokertools/evaluator(@pokertools/engine のショーダウンと同じ判定器)を使う。
|
||||
// ここでは表示用に、最強の5枚と日本語の役名を求める。
|
||||
// カードは "As"(スペードのA), "Td"(ダイヤの10)のような2文字
|
||||
const RANKS = '23456789TJQKA';
|
||||
const SUITS = 'shdc';
|
||||
const { evaluate, getCardCodes, rank, HandRank } = require('@pokertools/evaluator');
|
||||
|
||||
// 暗号論的乱数で 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 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 がロイヤルフラッシュ
|
||||
|
||||
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枚を選ぶ
|
||||
// 5〜7枚の中で最も強い役。score は小さいほど強い
|
||||
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) };
|
||||
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 };
|
||||
}
|
||||
|
||||
module.exports = { newDeck, score5, compareScore, bestHand, handName };
|
||||
// a が強ければ正、b が強ければ負、同じ強さなら 0
|
||||
function compareScore(a, b) {
|
||||
return b - a;
|
||||
}
|
||||
|
||||
module.exports = { bestHand, compareScore };
|
||||
+201
-172
@@ -1,13 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
const { newDeck, bestHand, compareScore } = require('./cards');
|
||||
const path = require('path');
|
||||
const { PokerEngine, ActionType, PlayerStatus } = require('@pokertools/engine');
|
||||
// サイドポットの計算はエンジン内部の関数を使う(パッケージの公開 API に無いので、ファイルを直接読む。
|
||||
// package.json でバージョンを固定している)
|
||||
const { calculateSidePots } = require(path.join(path.dirname(require.resolve('@pokertools/engine')), 'rules/side-pots'));
|
||||
const { bestHand, compareScore } = require('./cards');
|
||||
|
||||
// 1ハンド分の進行(ブラインド・ベッティング・ポット分配)。
|
||||
// 1ハンド分の進行。ルール(ブラインド・手番・最低レイズ額・再レイズ権・返金・サイドポット・
|
||||
// ショーダウンの判定と分配)は @pokertools/engine に任せ、ここではテーブルとのやり取りと表示用の状態を持つ。
|
||||
// cards = false: カードは実物で配るので扱わない。ショーダウンでは勝者をホストが選ぶ。
|
||||
// cards = true : サーバが配り、ショーダウンで役を判定して自動で分配する。
|
||||
// seats は Table.seats への参照で、スタックはここで直接増減する。
|
||||
// cards = true : エンジンが配り、ショーダウンで役を判定して自動で分配する。
|
||||
// seats は Table.seats への参照で、スタックはエンジンの状態に合わせて書き換える。
|
||||
// 参加者の席はハンド終了まで空席にならない(退席者は Table 側で予約したまま)。
|
||||
const STREETS = ['PREFLOP', 'FLOP', 'TURN', 'RIVER'];
|
||||
const RUNOUT_STREET = { 3: 'FLOP', 4: 'TURN', 5: 'RIVER' };
|
||||
|
||||
class Hand {
|
||||
constructor({ number, seats, order, button, sb, bb, cards = false }) {
|
||||
@@ -19,16 +25,21 @@ class Hand {
|
||||
this.bb = bb;
|
||||
this.cards = cards;
|
||||
|
||||
// 山札はサーバの外に出さない
|
||||
this.deck = cards ? newDeck() : null;
|
||||
this.board = [];
|
||||
// エンジンには参加者だけを、ボタンを席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.pot = 0; // 前のストリートまでに集めた額
|
||||
this.currentBet = 0;
|
||||
this.minRaise = bb;
|
||||
this.raises = 0; // このストリートのベット・レイズの回数(CPU の判断用)
|
||||
this.actions = 0; // アクションの通し番号(CPU の手番の管理用)
|
||||
this.aggressor = null; // このストリートで最後にベット・レイズした席(CPU の判断用)
|
||||
@@ -37,6 +48,10 @@ class Hand {
|
||||
this.finished = false;
|
||||
this.showdown = false;
|
||||
this.results = null;
|
||||
this.settled = false; // エンジンの中ではハンドが決着した(結果の公開待ちを含む)
|
||||
this.pots = null; // ショーダウンのポット(同じ参加者のポットはまとめる)
|
||||
this.engineWon = null; // エンジンが分配した額(席番号 → 額)
|
||||
this.taken = new Map(); // ハンド中に退席した人が持ち出したチップ(エンジンから外れた分)
|
||||
|
||||
this.players = new Map();
|
||||
for (const i of order) {
|
||||
@@ -49,21 +64,21 @@ class Hand {
|
||||
committed: 0, // このハンドで出した合計
|
||||
folded: false,
|
||||
allIn: false,
|
||||
acted: false,
|
||||
last: null, // 直前のアクション(表示用)
|
||||
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
|
||||
const headsUp = order.length === 2;
|
||||
// ヘッズアップはボタンが SB(エンジンも同じ配置にする)
|
||||
const headsUp = n === 2;
|
||||
this.sbSeat = headsUp ? button : order[0];
|
||||
this.bbSeat = headsUp ? order[0] : order[1];
|
||||
this.post(this.sbSeat, sb);
|
||||
this.post(this.bbSeat, bb);
|
||||
this.currentBet = bb; // BB がショートでもコール額は BB
|
||||
this.setNextActor(this.bbSeat);
|
||||
this.engine.deal();
|
||||
this.sync();
|
||||
}
|
||||
|
||||
get state() {
|
||||
return this.engine.state;
|
||||
}
|
||||
|
||||
get list() {
|
||||
@@ -84,65 +99,130 @@ class Hand {
|
||||
return this.pot + this.list.reduce((sum, p) => sum + p.bet, 0);
|
||||
}
|
||||
|
||||
put(p, amount) {
|
||||
const s = this.seats[p.seat];
|
||||
s.stack -= amount;
|
||||
p.bet += amount;
|
||||
p.committed += amount;
|
||||
if (s.stack === 0) p.allIn = true;
|
||||
}
|
||||
// エンジンの状態を写す。ハンドが決着していたら結果を作る
|
||||
sync() {
|
||||
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;
|
||||
}
|
||||
|
||||
post(seat, amount) {
|
||||
const p = this.players.get(seat);
|
||||
this.put(p, Math.min(amount, this.seats[seat].stack));
|
||||
}
|
||||
const prevStreet = this.street;
|
||||
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;
|
||||
this.prevAggressor = this.aggressor;
|
||||
this.aggressor = null;
|
||||
}
|
||||
// 誰もコールしなかった分が返ってオールインでなくなった
|
||||
for (const p of this.list) if (!p.allIn && p.last && p.last.type === 'ALLIN') p.last = null;
|
||||
|
||||
needsToAct(p) {
|
||||
return !p.folded && !p.allIn && (!p.acted || p.bet < this.currentBet);
|
||||
}
|
||||
if (ended) return this.settle();
|
||||
|
||||
bettingClosed() {
|
||||
const live = this.live();
|
||||
if (live.length <= 1) return true;
|
||||
const actors = live.filter((p) => !p.allIn);
|
||||
if (actors.length === 0) return true;
|
||||
// 動ける人が1人だけで、誰かのベットに応じる必要もない
|
||||
const maxBet = Math.max(...live.map((p) => p.bet));
|
||||
if (actors.length === 1 && actors[0].bet >= maxBet) return true;
|
||||
return actors.every((p) => !this.needsToAct(p));
|
||||
}
|
||||
|
||||
setNextActor(fromSeat) {
|
||||
this.toAct = null;
|
||||
if (this.bettingClosed()) return this.endStreet();
|
||||
const n = this.order.length;
|
||||
const start = this.order.indexOf(fromSeat);
|
||||
for (let k = 1; k <= n; k++) {
|
||||
const p = this.players.get(this.order[(start + k) % n]);
|
||||
if (!this.needsToAct(p)) continue;
|
||||
this.toAct = p.seat;
|
||||
// 離席中・退席済みの人は自動でチェック/フォールド
|
||||
const s = this.seats[p.seat];
|
||||
this.street = st.street;
|
||||
if (this.cards) this.board = st.board.slice();
|
||||
this.pot = st.pots.reduce((sum, pot) => sum + pot.amount, 0);
|
||||
// コール額(プリフロップは BB がショートでも BB)
|
||||
this.currentBet = Math.max(0, ...st.currentBets.values(), st.street === 'PREFLOP' ? st.bigBlind : 0);
|
||||
this.toAct = st.actionTo == null ? null : this.fromEngine[st.actionTo];
|
||||
// 離席中・退席済みの人は自動でチェック/フォールド
|
||||
if (this.toAct != null) {
|
||||
const s = this.seats[this.toAct];
|
||||
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;
|
||||
}
|
||||
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)
|
||||
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 stack = this.seats[seat].stack;
|
||||
const toCall = Math.min(this.currentBet - p.bet, stack);
|
||||
const maxTo = p.bet + stack;
|
||||
// 他の全員がオールインならレイズしても意味がない
|
||||
const opponentCanAct = this.live().some((q) => q !== p && !q.allIn);
|
||||
// レイズできるか(足りないオールインのあとの再レイズ権など)はエンジンに聞く
|
||||
const canRaise =
|
||||
maxTo > this.currentBet && opponentCanAct && this.engine.validate(this.engineAction(seat, 'raise', maxTo)).valid;
|
||||
return {
|
||||
toCall,
|
||||
canCheck: p.bet >= this.currentBet,
|
||||
canRaise: !p.acted && stack > toCall && opponentCanAct,
|
||||
minRaiseTo: Math.min(this.currentBet + this.minRaise, maxTo),
|
||||
canRaise,
|
||||
minRaiseTo: Math.min(this.state.minRaise, maxTo),
|
||||
maxRaiseTo: maxTo,
|
||||
isBet: this.currentBet === 0,
|
||||
};
|
||||
@@ -154,40 +234,39 @@ class Hand {
|
||||
if (!o) return 'あなたの番ではありません';
|
||||
const p = this.players.get(seat);
|
||||
|
||||
let last;
|
||||
if (type === 'fold') {
|
||||
p.folded = true;
|
||||
p.last = { type: 'FOLD' };
|
||||
last = { type: 'FOLD' };
|
||||
} else if (type === 'check') {
|
||||
if (!o.canCheck) return 'チェックできません';
|
||||
p.last = { type: 'CHECK' };
|
||||
last = { type: 'CHECK' };
|
||||
} else if (type === 'call') {
|
||||
if (o.canCheck || o.toCall <= 0) return 'コールする額がありません';
|
||||
this.put(p, o.toCall);
|
||||
p.last = { type: 'CALL', amount: p.bet };
|
||||
last = { type: 'CALL', amount: p.bet + o.toCall };
|
||||
} else if (type === 'raise') {
|
||||
if (!o.canRaise) return 'レイズできません';
|
||||
if (!Number.isInteger(amount) || amount < o.minRaiseTo || amount > o.maxRaiseTo) {
|
||||
return `${o.minRaiseTo}〜${o.maxRaiseTo} の額を指定してください`;
|
||||
}
|
||||
const raiseSize = amount - this.currentBet;
|
||||
this.put(p, amount - p.bet);
|
||||
p.last = { type: o.isBet ? 'BET' : 'RAISE', amount };
|
||||
this.aggressor = seat;
|
||||
if (raiseSize >= this.minRaise) {
|
||||
// 正規のレイズ: 他の人はもう一度アクションできる
|
||||
this.minRaise = raiseSize;
|
||||
this.raises++;
|
||||
for (const q of this.list) if (q !== p) q.acted = false;
|
||||
}
|
||||
// 足りないオールインのレイズはアクション済みの人に再レイズ権を与えない
|
||||
this.currentBet = amount;
|
||||
last = { type: o.isBet ? 'BET' : 'RAISE', amount };
|
||||
} else {
|
||||
return '不正なアクションです';
|
||||
}
|
||||
if (p.allIn) p.last = { type: 'ALLIN', amount: p.bet };
|
||||
p.acted = true;
|
||||
const allIn = type !== 'fold' && type !== 'check' && last.amount === o.maxRaiseTo;
|
||||
const fullRaise = type === 'raise' && amount >= this.state.minRaise;
|
||||
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++;
|
||||
this.setNextActor(seat);
|
||||
if (type === 'raise') {
|
||||
this.aggressor = seat;
|
||||
if (fullRaise) this.raises++;
|
||||
}
|
||||
this.sync();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -196,105 +275,53 @@ class Hand {
|
||||
if (o) this.act(this.toAct, o.canCheck ? 'check' : 'fold', 0);
|
||||
}
|
||||
|
||||
// 退席などで手番に関係なくフォールドさせる
|
||||
// 退席などで手番に関係なくフォールドさせる。オールインの人の手は最後まで生きている
|
||||
forceFold(seat) {
|
||||
const p = this.players.get(seat);
|
||||
if (!p || p.folded || this.finished) return;
|
||||
if (this.toAct === seat) return this.act(seat, 'fold', 0);
|
||||
p.folded = true;
|
||||
if (this.toAct === seat) {
|
||||
if (this.act(seat, 'fold', 0)) this.autoAct();
|
||||
return;
|
||||
}
|
||||
if (this.settled) {
|
||||
// キャッシュオンリーの勝者選び待ち: 選べる人から外す
|
||||
if (!this.awaitingWinners) return;
|
||||
p.folded = true;
|
||||
p.last = { type: 'FOLD' };
|
||||
if (this.live().length === 1) return this.finishFoldWin();
|
||||
// 選べる人がいなくなったポットは前のポットにまとめる(メインポットには残った全員が入っている)
|
||||
const pots = [];
|
||||
for (const pot of this.pots) {
|
||||
const eligible = pot.eligible.filter((s) => s !== seat);
|
||||
const last = pots[pots.length - 1];
|
||||
if (last && (eligible.length === 0 || last.eligible.join() === eligible.join())) last.amount += pot.amount;
|
||||
else pots.push({ amount: pot.amount, eligible });
|
||||
}
|
||||
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' };
|
||||
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;
|
||||
this.raises = 0;
|
||||
this.prevAggressor = this.aggressor;
|
||||
this.aggressor = null;
|
||||
|
||||
const noMoreBetting = this.live().filter((p) => !p.allIn).length < 2;
|
||||
if (!this.cards) {
|
||||
// リバーが終わった、または全員オールインでこれ以上ベットが無い → ショーダウン
|
||||
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.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];
|
||||
this.sync();
|
||||
}
|
||||
|
||||
// オールイン後に場札を1ストリート分めくる。リバーまでめくり終えていたらショーダウン
|
||||
runoutStep() {
|
||||
if (!this.runout || this.finished) return;
|
||||
if (this.street === 'RIVER') this.finishShowdown();
|
||||
else this.dealStreet();
|
||||
}
|
||||
|
||||
// メインポット・サイドポット(同じ参加者のポットはまとめる)
|
||||
buildPots() {
|
||||
const all = this.list;
|
||||
const levels = [...new Set(all.map((p) => p.committed).filter((c) => c > 0))].sort((a, b) => a - b);
|
||||
const pots = [];
|
||||
let prev = 0;
|
||||
for (const level of levels) {
|
||||
let amount = 0;
|
||||
for (const p of all) amount += Math.max(0, Math.min(p.committed, level) - prev);
|
||||
prev = level;
|
||||
let eligible = all.filter((p) => !p.folded && p.committed >= level).map((p) => p.seat);
|
||||
const last = pots[pots.length - 1];
|
||||
if (eligible.length === 0) eligible = last ? last.eligible : this.live().map((p) => p.seat);
|
||||
if (last && last.eligible.join() === eligible.join()) last.amount += amount;
|
||||
else pots.push({ amount, eligible });
|
||||
}
|
||||
return pots;
|
||||
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() {
|
||||
const winner = this.live()[0];
|
||||
winner.won = this.pot;
|
||||
@@ -305,7 +332,7 @@ class Hand {
|
||||
// ショーダウンの勝者を決める。winners[i] = i 番目のポットの勝者の席番号(引き分けは複数)
|
||||
award(winners) {
|
||||
if (!this.awaitingWinners) return 'ショーダウンではありません';
|
||||
const pots = this.buildPots();
|
||||
const pots = this.pots;
|
||||
if (!Array.isArray(winners) || winners.length !== pots.length) return 'すべてのポットの勝者を選んでください';
|
||||
for (let i = 0; i < pots.length; i++) {
|
||||
const w = winners[i];
|
||||
@@ -318,26 +345,28 @@ class Hand {
|
||||
return null;
|
||||
}
|
||||
|
||||
// カードありのショーダウン: ポットごとに役を比べて分配する
|
||||
// カードありのショーダウン: エンジンが分配した結果を公開する。表示用にポットごとの勝者と役を添える
|
||||
finishShowdown() {
|
||||
this.revealed = true;
|
||||
this.board = this.state.board.slice();
|
||||
for (const p of this.live()) p.best = bestHand(p.cards.concat(this.board));
|
||||
const results = this.buildPots().map((pot) => {
|
||||
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 || compareScore(c.best.score, top) > 0) top = c.best.score;
|
||||
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: this.payout(pot.amount, best.map((c) => c.seat)),
|
||||
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);
|
||||
@@ -388,7 +417,7 @@ class Hand {
|
||||
toAct: this.toAct,
|
||||
finished: this.finished,
|
||||
showdown: this.showdown,
|
||||
pots: this.awaitingWinners ? this.buildPots() : null,
|
||||
pots: this.awaitingWinners ? this.pots : null,
|
||||
results: this.results,
|
||||
players,
|
||||
};
|
||||
|
||||
+1
-1
@@ -123,7 +123,7 @@ app.post('/api/tables', (req, res) => {
|
||||
if (tables.nameTaken(name)) return res.status(409).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(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 (!MODES.includes(mode)) return res.status(400).json({ error: 'テーブルの種類が不正です' });
|
||||
if (mode === 'cpu' && !intIn(cpuCount, 1, config.MAX_SEATS - 1)) {
|
||||
|
||||
Reference in new issue
Block a user