- GameResult/GameResultView에 scoreText(게임별 표시 문구) 추가 - 점수가 있는 18개 게임이 결과에 최종 점수 문구를 넣음 (n점, n칩, 총자산 nP, 난 말 n개, 카드 n장 등) - 점수가 없는 게임(오목·체스·쿼리도·다빈치 코드·99·뱅·마피아·바퀴벌레 포커)은 등수만 - 결과 창 각 줄 오른쪽에 최종 점수(진하게), 그 아래 이 방 전적 - 전 게임 무작위 진행 테스트, 요트 기권 E2E, docs/06·09 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
396 lines
15 KiB
TypeScript
396 lines
15 KiB
TypeScript
/** 포커 (docs/games/poker.md): 7 modes on one engine, betting via @bg/engine betting.ts. */
|
|
import { z } from 'zod';
|
|
import {
|
|
fail,
|
|
legalBets,
|
|
ok,
|
|
timeoutBet,
|
|
toCallOf,
|
|
validateBet,
|
|
type BetAction,
|
|
type GameDefinition,
|
|
type GameResult,
|
|
type PlayerId,
|
|
type Rng,
|
|
type Validation,
|
|
} from '@bg/engine';
|
|
import { hi, type CardId } from './cards';
|
|
import {
|
|
advance,
|
|
autoChoice,
|
|
chipsOnTable,
|
|
closeHand,
|
|
decideRebuy,
|
|
deadlineSig,
|
|
doBet,
|
|
finishGame,
|
|
forceFold,
|
|
idxOf,
|
|
inPlay,
|
|
log,
|
|
seatOf,
|
|
startHand,
|
|
syncDeadline,
|
|
waitingFor,
|
|
type Ctx,
|
|
} from './hand';
|
|
import { playerRange, pokerOptionsSchema, resolveBetStyle, type PokerOptions } from './options';
|
|
import { pokerActionSchema, type BetActionType, type PokerAction, type PokerClientAction, type PokerState, type PokerView, type Side } from './types';
|
|
import { betTypeOf, buildView, drawLimitFor } from './view';
|
|
|
|
export { pokerOptionsSchema, playerRange, resolveBetStyle, MODE_KO, MODES, type PokerMode, type PokerOptions } from './options';
|
|
export { pokerActionSchema } from './types';
|
|
export type * from './types';
|
|
export { chipsOnTable, LAST_STANDING_CAP } from './hand';
|
|
|
|
const BET_KIND: Record<BetActionType, BetAction['kind']> = {
|
|
'k.check': 'check',
|
|
'k.ping': 'ping',
|
|
'k.call': 'call',
|
|
'k.ddadang': 'double',
|
|
'k.quarter': 'quarter',
|
|
'k.half': 'half',
|
|
'k.full': 'full',
|
|
'k.die': 'die',
|
|
'nl.fold': 'fold',
|
|
'nl.check': 'check',
|
|
'nl.call': 'call',
|
|
'nl.raise': 'raise',
|
|
'nl.allIn': 'allIn',
|
|
};
|
|
|
|
const isBetType = (t: string): t is BetActionType => t in BET_KIND;
|
|
export function toBetAction(a: PokerClientAction): BetAction {
|
|
if (a.type === 'nl.raise') return { kind: 'raise', to: a.to };
|
|
return { kind: BET_KIND[a.type as BetActionType] } as BetAction;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- setup
|
|
|
|
export interface FixedHand {
|
|
dealerSeat?: number;
|
|
deck?: CardId[];
|
|
}
|
|
|
|
/** Builds the initial state and deals the first hand. `fixed` is for tests (dealer seat, deck order). */
|
|
export function setupPoker(ctx: { players: PlayerId[]; options: PokerOptions; rng: Rng; now: number }, fixed?: FixedHand): PokerState {
|
|
const o = ctx.options;
|
|
const range = playerRange(o);
|
|
if (ctx.players.length < range.min || ctx.players.length > range.max) throw new Error(`이 모드는 ${range.min}~${range.max}명이 할 수 있어요.`);
|
|
const s: PokerState = {
|
|
options: o,
|
|
betStyle: resolveBetStyle(o),
|
|
seats: ctx.players.map((id) => ({
|
|
id,
|
|
stack: o.startingChips,
|
|
rebuys: 0,
|
|
status: 'playing',
|
|
timeoutsInRow: 0,
|
|
eliminatedAtHand: null,
|
|
stackAtHandStart: o.startingChips,
|
|
})),
|
|
baseUnit: o.baseUnit,
|
|
level: 1,
|
|
hand: null,
|
|
handsPlayed: 0,
|
|
carryOver: 0,
|
|
carryFrom: [],
|
|
indianDeck: null,
|
|
indianUsed: [],
|
|
phase: 'playing',
|
|
rebuyPending: [],
|
|
deadlineAt: null,
|
|
deadlineMs: 0,
|
|
deadlineSig: '',
|
|
lastWinner: null,
|
|
eliminationSeq: [],
|
|
log: [],
|
|
stats: { biggestPot: null, bestHand: null },
|
|
chipsIssued: o.startingChips * ctx.players.length,
|
|
result: null,
|
|
};
|
|
startHand(s, { rng: ctx.rng, now: ctx.now, events: [] }, fixed);
|
|
syncDeadline(s, ctx.now, '');
|
|
return s;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- validation
|
|
|
|
const KOREAN_RAISES: BetActionType[] = ['k.ping', 'k.ddadang', 'k.quarter', 'k.half', 'k.full'];
|
|
|
|
function validateBetAction(s: PokerState, actor: PlayerId, a: PokerClientAction & { type: BetActionType }): Validation {
|
|
const h = s.hand!;
|
|
if (h.phase !== 'betting' || !h.waiting) return fail('지금은 베팅할 때가 아니에요.');
|
|
if (!inPlay(h, actor)) return fail('이번 판에서 이미 다이했어요.');
|
|
const i = idxOf(h, actor);
|
|
if (h.bet.turn !== i) return fail('지금은 내 차례가 아니에요.');
|
|
const korean = s.betStyle === 'korean';
|
|
if (a.type.startsWith('k.') !== korean) return fail(korean ? '이 방은 한국식 베팅이에요.' : '이 방은 노리밋·팟리밋 베팅이에요.');
|
|
const p = h.bet.players[i]!;
|
|
const toCall = toCallOf(h.bet, p);
|
|
if ((a.type === 'k.check' || a.type === 'nl.check') && toCall > 0) return fail('콜 금액이 있어서 체크할 수 없어요.');
|
|
if ((a.type === 'k.call' || a.type === 'nl.call') && toCall === 0) return fail('낼 콜 금액이 없어요. 체크해 주세요.');
|
|
if (korean) {
|
|
if (KOREAN_RAISES.includes(a.type) && (p.acted || p.raised)) return fail('이번 라운드에서는 더 올릴 수 없어요(콜 또는 다이만 가능).');
|
|
if (a.type === 'k.full' && s.options.koreanMaxRaise !== 'full') return fail('이 방은 하프까지만 올릴 수 있어요.');
|
|
if (a.type === 'k.ping' && h.bet.opened) return fail('이미 누가 걸어서 삥은 할 수 없어요.');
|
|
if (a.type === 'k.ddadang' && toCall === 0) return fail('따당은 앞사람이 건 칩이 있을 때만 할 수 있어요.');
|
|
} else if (a.type === 'nl.raise' || a.type === 'nl.allIn') {
|
|
if (!p.mayRaise) return fail('이번 라운드에서는 더 올릴 수 없어요(콜 또는 폴드만 가능).');
|
|
const r = legalBets(h.bet, i).find((l) => l.kind === 'raise');
|
|
const stackTo = p.round + p.stack;
|
|
if (a.type === 'nl.raise' && r) {
|
|
if (a.to < r.minTo! && a.to !== stackTo) return fail(`최소 레이즈는 ${r.minTo} 칩이에요.`);
|
|
if (a.to > r.maxTo!) return fail(s.betStyle === 'potLimit' ? `팟리밋 최대는 ${r.maxTo} 칩이에요.` : '가진 칩보다 많이 걸 수 없어요.');
|
|
}
|
|
if (a.type === 'nl.allIn' && r && s.betStyle === 'potLimit' && stackTo > r.maxTo!) return fail(`팟리밋에서는 ${r.maxTo} 칩까지만 올릴 수 있어요.`);
|
|
}
|
|
const err = validateBet(h.bet, i, toBetAction(a));
|
|
return err ? fail(err) : ok;
|
|
}
|
|
|
|
export function validateDraw(s: PokerState, hole: CardId[], ids: CardId[]): Validation {
|
|
if (new Set(ids).size !== ids.length) return fail('같은 카드를 두 번 고를 수 없어요.');
|
|
if (!ids.every((c) => hole.includes(c))) return fail('내 손에 있는 카드만 바꿀 수 있어요.');
|
|
const { max, aceBonus } = drawLimitFor(s);
|
|
if (ids.length <= max) return ok;
|
|
const kept = hole.filter((c) => !ids.includes(c));
|
|
if (aceBonus && ids.length === max + 1 && kept.some((c) => hi(c) === 14)) return ok;
|
|
return fail(aceBonus ? '3장까지 바꿀 수 있어요(A를 남기면 4장).' : `${max}장까지 바꿀 수 있어요.`);
|
|
}
|
|
|
|
function validate(s: PokerState, actor: PlayerId, a: PokerAction): Validation {
|
|
const seat = seatOf(s, actor);
|
|
if (!seat) return fail('이 게임의 플레이어가 아니에요.');
|
|
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
|
|
if (a.type === 'leave') return seat.status === 'left' ? fail('이미 나갔어요.') : ok;
|
|
if (a.type === 'timeout') return waitingFor(s).includes(actor) ? ok : fail('지금은 시간 초과를 적용할 수 없어요.');
|
|
if (a.type === 'rebuy') {
|
|
if (s.phase !== 'rebuy' || !s.rebuyPending.includes(actor)) return fail('지금은 칩을 다시 받을 수 없어요.');
|
|
return ok;
|
|
}
|
|
const h = s.hand;
|
|
if (s.phase !== 'playing' || !h) return fail('지금은 할 수 없어요.');
|
|
const hp = h.players[actor];
|
|
if (!hp) return fail('이번 판에 참가하지 않았어요.');
|
|
if (seat.status === 'left') return fail('이미 나간 자리예요.');
|
|
switch (a.type) {
|
|
case 'ready':
|
|
if (h.phase !== 'handEnd') return fail('아직 판이 끝나지 않았어요.');
|
|
return hp.ready ? fail('이미 준비했어요.') : ok;
|
|
case 'choose':
|
|
if (h.phase !== 'choice' || !h.waiting || !hp.choice) return fail('지금은 카드를 고를 때가 아니에요.');
|
|
if (!inPlay(h, actor)) return fail('이번 판에서 이미 다이했어요.');
|
|
if (hp.choiceSel) return fail('이미 골랐어요.');
|
|
if (a.discardId === a.openId) return fail('버릴 카드와 보여 줄 카드는 달라야 해요.');
|
|
if (!hp.choice.includes(a.discardId) || !hp.choice.includes(a.openId)) return fail('내 카드 중에서 골라 주세요.');
|
|
return ok;
|
|
case 'draw':
|
|
if (h.phase !== 'draw' || !h.waiting) return fail('지금은 카드를 바꿀 때가 아니에요.');
|
|
if (!inPlay(h, actor)) return fail('이번 판에서 이미 다이했어요.');
|
|
if (hp.drawPending) return fail('이미 바꿀 카드를 냈어요.');
|
|
return validateDraw(s, hp.hole, a.cardIds);
|
|
case 'declare':
|
|
if (h.phase !== 'declare' || !h.waiting) return fail('지금은 선언할 때가 아니에요.');
|
|
if (!inPlay(h, actor)) return fail('이번 판에서 이미 다이했어요.');
|
|
return hp.declare ? fail('이미 선언했어요.') : ok;
|
|
default:
|
|
if (!isBetType(a.type)) return fail('알 수 없는 행동이에요.');
|
|
return validateBetAction(s, actor, a as PokerClientAction & { type: BetActionType });
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- apply
|
|
|
|
function applyTimeout(s: PokerState, ctx: Ctx, actor: PlayerId): void {
|
|
if (s.phase === 'rebuy') return decideRebuy(s, ctx, actor, false);
|
|
const h = s.hand!;
|
|
const seat = seatOf(s, actor)!;
|
|
if (h.phase === 'handEnd') {
|
|
for (const id of h.order) h.players[id]!.ready = true;
|
|
return closeHand(s, ctx);
|
|
}
|
|
seat.timeoutsInRow++;
|
|
if (seat.timeoutsInRow === 2) log(s, actor, '시간 초과가 이어져 자리 비움으로 표시했어요');
|
|
const hp = h.players[actor]!;
|
|
switch (h.phase) {
|
|
case 'betting':
|
|
return doBet(s, ctx, actor, timeoutBet(h.bet, idxOf(h, actor)));
|
|
case 'choice':
|
|
hp.choiceSel = autoChoice(hp.choice!);
|
|
break;
|
|
case 'draw':
|
|
hp.drawPending = [];
|
|
break;
|
|
case 'declare':
|
|
hp.declare = 'high';
|
|
break;
|
|
}
|
|
advance(s, ctx);
|
|
}
|
|
|
|
function applyLeave(s: PokerState, ctx: Ctx, actor: PlayerId): void {
|
|
const seat = seatOf(s, actor)!;
|
|
if (seat.status !== 'eliminated') seat.status = 'left';
|
|
log(s, actor, '방을 나갔어요');
|
|
if (s.phase === 'rebuy' && s.rebuyPending.includes(actor)) decideRebuy(s, ctx, actor, false);
|
|
else if (s.phase === 'playing' && s.hand) {
|
|
const h = s.hand;
|
|
if (!h.settled) forceFold(s, ctx, actor);
|
|
else if (h.players[actor] && !h.players[actor]!.ready) {
|
|
h.players[actor]!.ready = true;
|
|
if (h.order.every((id) => h.players[id]!.ready)) closeHand(s, ctx);
|
|
}
|
|
}
|
|
// §6.7 공통: one or no connected player with chips left → end right away.
|
|
const connected = s.seats.filter((x) => x.status === 'playing' && x.stack > 0).length;
|
|
if (s.phase === 'playing' && s.hand?.settled && connected <= 1 && s.rebuyPending.length === 0) finishGame(s, ctx);
|
|
}
|
|
|
|
function apply(prev: PokerState, actor: PlayerId, a: PokerAction, { rng, now }: { rng: Rng; now: number }) {
|
|
const s = structuredClone(prev);
|
|
const ctx: Ctx = { rng, now, events: [] };
|
|
const sig = deadlineSig(prev);
|
|
const seat = seatOf(s, actor)!;
|
|
if (a.type !== 'timeout' && a.type !== 'leave') seat.timeoutsInRow = 0;
|
|
const hp = s.hand?.players[actor];
|
|
switch (a.type) {
|
|
case 'timeout':
|
|
applyTimeout(s, ctx, actor);
|
|
break;
|
|
case 'leave':
|
|
applyLeave(s, ctx, actor);
|
|
break;
|
|
case 'rebuy':
|
|
decideRebuy(s, ctx, actor, a.accept);
|
|
break;
|
|
case 'ready': {
|
|
const h = s.hand!;
|
|
hp!.ready = true;
|
|
if (h.order.every((id) => h.players[id]!.ready)) closeHand(s, ctx);
|
|
break;
|
|
}
|
|
case 'choose':
|
|
hp!.choiceSel = { discard: a.discardId, open: a.openId };
|
|
advance(s, ctx);
|
|
break;
|
|
case 'draw':
|
|
hp!.drawPending = [...a.cardIds];
|
|
log(s, actor, '바꿀 카드를 냈어요');
|
|
advance(s, ctx);
|
|
break;
|
|
case 'declare':
|
|
hp!.declare = a.side;
|
|
advance(s, ctx);
|
|
break;
|
|
default:
|
|
doBet(s, ctx, actor, toBetAction(a));
|
|
}
|
|
syncDeadline(s, now, sig);
|
|
return { state: s, events: ctx.events };
|
|
}
|
|
|
|
// ---------------------------------------------------------------- test helpers
|
|
|
|
function legalActions(s: PokerState, p: PlayerId): PokerAction[] {
|
|
if (!waitingFor(s).includes(p)) return [];
|
|
if (s.phase === 'rebuy') return [{ type: 'rebuy', accept: true }, { type: 'rebuy', accept: false }];
|
|
const h = s.hand!;
|
|
const hp = h.players[p]!;
|
|
switch (h.phase) {
|
|
case 'handEnd':
|
|
return [{ type: 'ready' }];
|
|
case 'choice': {
|
|
const out: PokerAction[] = [];
|
|
for (const d of hp.choice!) for (const o of hp.choice!) if (d !== o) out.push({ type: 'choose', discardId: d, openId: o });
|
|
return out;
|
|
}
|
|
case 'draw': {
|
|
const out: PokerAction[] = [];
|
|
for (let mask = 0; mask < 1 << hp.hole.length; mask++) {
|
|
const ids = hp.hole.filter((_, i) => mask & (1 << i));
|
|
if (validateDraw(s, hp.hole, ids).ok) out.push({ type: 'draw', cardIds: ids });
|
|
}
|
|
return out;
|
|
}
|
|
case 'declare':
|
|
return (['high', 'low', 'swing'] as Side[]).map((side) => ({ type: 'declare', side }));
|
|
case 'betting': {
|
|
const korean = s.betStyle === 'korean';
|
|
const out: PokerAction[] = [];
|
|
for (const l of legalBets(h.bet, idxOf(h, p))) {
|
|
const type = betTypeOf(korean, l.kind);
|
|
if (type === 'nl.raise') {
|
|
const tos = new Set([l.minTo!, l.maxTo!, Math.floor((l.minTo! + l.maxTo!) / 2)]);
|
|
for (const to of tos) out.push({ type, to });
|
|
} else out.push({ type } as PokerAction);
|
|
}
|
|
return out;
|
|
}
|
|
default:
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/** Card ids only `player` (or nobody) may see: hidden cards, 초이스 cards, deck, burns and discards. */
|
|
function secretsOf(s: PokerState, player: PlayerId): string[] {
|
|
const out: string[] = [];
|
|
const h = s.hand;
|
|
if (h) {
|
|
const hp = h.players[player];
|
|
const revealed = !!h.showdown?.some((e) => e.id === player) || (s.options.mode === 'indian' && h.settled);
|
|
if (hp) {
|
|
if (!revealed) out.push(...hp.hole);
|
|
if (hp.choice) out.push(...hp.choice);
|
|
if (hp.discarded) out.push(hp.discarded);
|
|
}
|
|
out.push(...h.deck, ...h.muck);
|
|
}
|
|
if (s.indianDeck) out.push(...s.indianDeck);
|
|
return out;
|
|
}
|
|
|
|
function result(s: PokerState): (GameResult & { stats: PokerState['stats']; handsPlayed: number }) | null {
|
|
if (!s.result) return null;
|
|
return {
|
|
ranking: s.result.ranking,
|
|
scores: s.result.scores,
|
|
...(s.result.scoreText ? { scoreText: s.result.scoreText } : {}),
|
|
summary: s.result.summary,
|
|
reason: s.result.abandoned ? 'abandoned' : 'normal',
|
|
stats: s.stats,
|
|
handsPlayed: s.handsPlayed,
|
|
};
|
|
}
|
|
|
|
export const poker: GameDefinition<PokerState, PokerAction, PokerView, PokerOptions> = {
|
|
id: 'poker',
|
|
nameKo: '포커',
|
|
minPlayers: 2,
|
|
maxPlayers: 10,
|
|
stateVersion: 1,
|
|
defaultOptions: pokerOptionsSchema.parse({}),
|
|
optionsSchema: pokerOptionsSchema,
|
|
actionSchema: pokerActionSchema as z.ZodType<PokerAction>,
|
|
playersFor: (o) => playerRange(o),
|
|
setup: ({ players, options, rng, now }) => setupPoker({ players, options, rng, now }),
|
|
validate,
|
|
apply,
|
|
view: buildView,
|
|
activePlayers: waitingFor,
|
|
deadline: (s) => s.deadlineAt,
|
|
timeoutPlayers: waitingFor,
|
|
onTimeout: () => ({ type: 'timeout' }),
|
|
onLeave: (s, p) => {
|
|
const seat = seatOf(s, p);
|
|
if (!seat || s.phase === 'finished' || seat.status === 'left' || seat.status === 'eliminated') return null;
|
|
return { type: 'leave' };
|
|
},
|
|
result,
|
|
legalActions,
|
|
secretsOf,
|
|
};
|
|
|
|
/** Conservation helper for tests: chips on the table must equal chips ever issued. */
|
|
export const chipsBalanced = (s: PokerState): boolean => chipsOnTable(s) === s.chipsIssued;
|