- GameResult/GameResultView에 scoreText(게임별 표시 문구) 추가 - 점수가 있는 18개 게임이 결과에 최종 점수 문구를 넣음 (n점, n칩, 총자산 nP, 난 말 n개, 카드 n장 등) - 점수가 없는 게임(오목·체스·쿼리도·다빈치 코드·99·뱅·마피아·바퀴벌레 포커)은 등수만 - 결과 창 각 줄 오른쪽에 최종 점수(진하게), 그 아래 이 방 전적 - 전 게임 무작위 진행 테스트, 요트 기권 E2E, docs/06·09 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1264 lines
49 KiB
TypeScript
1264 lines
49 KiB
TypeScript
/** 섯다 (docs/games/seotda.md). Chips are room-only play points (§12). */
|
|
import { z } from 'zod';
|
|
import {
|
|
HWATU,
|
|
SEOTDA_DECK,
|
|
applyBet,
|
|
buildPots,
|
|
fail,
|
|
handDecided,
|
|
legalBets,
|
|
newBetting,
|
|
ok,
|
|
postAnte,
|
|
returnUncalled,
|
|
splitAmount,
|
|
startRound,
|
|
timeoutBet,
|
|
validateBet,
|
|
type BetAction,
|
|
type BettingState,
|
|
type GameDefinition,
|
|
type GameEvent,
|
|
type GameResult,
|
|
type KoreanKind,
|
|
type PlayerId,
|
|
type Rng,
|
|
} from '@bg/engine';
|
|
import { bestChoice, combos, evalSeotda, hintText, resolve, strengthOf, type HandEval, type HandRules, type SpecialKind } from './hands';
|
|
|
|
export * from './hands';
|
|
|
|
const lit = <T extends number>(...vals: T[]) =>
|
|
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
|
|
|
export const seotdaOptionsSchema = z
|
|
.object({
|
|
cardMode: z
|
|
.enum(['two', 'three'])
|
|
.default('two')
|
|
.meta({ title: '카드 수', labels: { two: '2장 섯다', three: '3장 섯다(3장 받아 2장 고르기)' } }),
|
|
dealMode: z
|
|
.enum(['twoRounds', 'oneRound'])
|
|
.default('twoRounds')
|
|
.meta({ title: '2장 섯다 나눠 주기', labels: { twoRounds: '1장씩 두 번(베팅 2번)', oneRound: '2장 한 번에(베팅 1번)' } }),
|
|
startingChips: lit(500, 1000, 2000, 5000)
|
|
.default(1000)
|
|
.meta({ title: '시작 칩', labels: { 500: '500칩', 1000: '1,000칩', 2000: '2,000칩', 5000: '5,000칩' } }),
|
|
baseUnit: lit(2, 10, 20, 50)
|
|
.default(10)
|
|
.meta({ title: '학교(기본 칩) = 삥', labels: { 2: '2칩', 10: '10칩', 20: '20칩', 50: '50칩' } }),
|
|
maxRaise: z.enum(['half', 'full']).default('half').meta({ title: '최대 레이즈', labels: { half: '하프까지', full: '풀까지' } }),
|
|
endCondition: z
|
|
.enum(['hands', 'lastStanding'])
|
|
.default('hands')
|
|
.meta({ title: '게임 끝내는 방식', labels: { hands: '정해진 판 수', lastStanding: '최후의 1인' } }),
|
|
handLimit: lit(10, 20, 30, 50)
|
|
.default(20)
|
|
.meta({ title: '총 판 수(재경기 제외)', labels: { 10: '10판', 20: '20판', 30: '30판', 50: '50판' } }),
|
|
schoolUpEvery: lit(0, 5, 10, 15)
|
|
.default(0)
|
|
.meta({ title: '학교 2배로 올리기', labels: { 0: '안 올림', 5: '5판마다', 10: '10판마다', 15: '15판마다' } }),
|
|
rebuy: z
|
|
.enum(['off', 'limited', 'unlimited'])
|
|
.default('unlimited')
|
|
.meta({ title: '칩 다시 받기(리바이)', labels: { off: '안 함(탈락)', limited: '횟수 제한', unlimited: '무제한' } }),
|
|
rebuyLimit: lit(1, 2, 3).default(1).meta({ title: '리바이 횟수(1인당)', labels: { 1: '1번', 2: '2번', 3: '3번' } }),
|
|
turnSeconds: lit(15, 20, 30, 60)
|
|
.default(20)
|
|
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
|
dealerRule: z.enum(['winner', 'rotate']).default('winner').meta({ title: '다음 판의 선', labels: { winner: '이긴 사람', rotate: '돌아가며' } }),
|
|
gwangTtaeng: z
|
|
.enum(['all', 'only38'])
|
|
.default('all')
|
|
.meta({ title: '광땡 종류', labels: { all: '38·18·13광땡', only38: '38광땡만' } }),
|
|
ttaengjabi: z
|
|
.enum(['off', 'strict', 'loose'])
|
|
.default('strict')
|
|
.meta({ title: '땡잡이(3·7)', labels: { off: '없음', strict: '3월 광 + 7월 열끗', loose: '3월 + 7월 아무 패' } }),
|
|
amhaeng: z.boolean().default(true).meta({ title: '암행어사(4·7 열끗)' }),
|
|
gusa: z.boolean().default(true).meta({ title: '구사 재경기(4·9)' }),
|
|
mungGusa: z
|
|
.enum(['off', 'upTo8', 'upTo9', 'upToJang'])
|
|
.default('upTo8')
|
|
.meta({ title: '멍텅구리구사 재경기 범위', labels: { off: '일반 구사로', upTo8: '8땡까지', upTo9: '9땡까지', upToJang: '장땡까지' } }),
|
|
tieRule: z.enum(['rematch', 'split']).default('rematch').meta({ title: '같은 족보일 때', labels: { rematch: '재경기', split: '나눠 가짐' } }),
|
|
rejoinCost: z
|
|
.enum(['none', 'half', 'full'])
|
|
.default('none')
|
|
.meta({ title: '구사 재경기 때 다이한 사람', labels: { none: '참가 불가', half: '모인 칩 절반 내고 참가', full: '모인 칩만큼 내고 참가' } }),
|
|
hints: z.boolean().default(true).meta({ title: '내 족보 이름·족보표 강조' }),
|
|
maxRematches: lit(1, 2, 3, 5)
|
|
.default(3)
|
|
.meta({ title: '한 판의 재경기 최대 횟수(넘으면 나눠 가짐)', labels: { 1: '1번', 2: '2번', 3: '3번', 5: '5번' } }),
|
|
decisionSeconds: lit(10, 15, 30)
|
|
.default(15)
|
|
.meta({ title: '재참가·리바이 답 시간', labels: { 10: '10초', 15: '15초', 30: '30초' } }),
|
|
})
|
|
.superRefine((o, ctx) => {
|
|
if (o.baseUnit * 20 > o.startingChips) {
|
|
ctx.addIssue({ code: 'custom', path: ['baseUnit'], message: '학교는 시작 칩의 20분의 1 이하여야 해요.' });
|
|
}
|
|
});
|
|
export type SeotdaOptions = z.infer<typeof seotdaOptionsSchema>;
|
|
|
|
export const seotdaActionSchema = z.discriminatedUnion('type', [
|
|
z.object({ type: z.literal('check') }),
|
|
z.object({ type: z.literal('ping') }),
|
|
z.object({ type: z.literal('call') }),
|
|
z.object({ type: z.literal('ddadang') }),
|
|
z.object({ type: z.literal('quarter') }),
|
|
z.object({ type: z.literal('half') }),
|
|
z.object({ type: z.literal('full') }),
|
|
z.object({ type: z.literal('die') }),
|
|
z.object({ type: z.literal('choose'), cardIds: z.tuple([z.number().int(), z.number().int()]) }),
|
|
z.object({ type: z.literal('rejoin'), accept: z.boolean() }),
|
|
z.object({ type: z.literal('ready') }),
|
|
z.object({ type: z.literal('rebuy'), accept: z.boolean() }),
|
|
]);
|
|
/** Client actions plus system-only ones (timer, leaving) that are not in the schema. */
|
|
export type SeotdaAction = z.infer<typeof seotdaActionSchema> | { type: 'timeout' } | { type: 'leave' };
|
|
|
|
export type BetType = 'check' | 'ping' | 'call' | 'ddadang' | 'quarter' | 'half' | 'full' | 'die';
|
|
const BET_TYPES: BetType[] = ['check', 'ping', 'call', 'ddadang', 'quarter', 'half', 'full', 'die'];
|
|
const toKind = (t: BetType): KoreanKind => (t === 'ddadang' ? 'double' : t);
|
|
const toType = (k: string): BetType => (k === 'double' ? 'ddadang' : (k as BetType));
|
|
export const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
|
|
|
|
// ---------------------------------------------------------------- state
|
|
|
|
export interface SeatState {
|
|
id: PlayerId;
|
|
stack: number;
|
|
rebuys: number;
|
|
/** busted = 0 chips, waiting for the rebuy answer. */
|
|
status: 'playing' | 'busted' | 'eliminated';
|
|
left: boolean;
|
|
away: boolean;
|
|
timeoutsInRow: number;
|
|
eliminatedAtHand: number | null;
|
|
stackAtHandStart: number;
|
|
}
|
|
|
|
export interface PotState {
|
|
amount: number;
|
|
eligible: PlayerId[];
|
|
}
|
|
|
|
export interface ShowdownHand {
|
|
id: PlayerId;
|
|
cards: [number, number];
|
|
name: string;
|
|
baseName: string;
|
|
value: number;
|
|
special: SpecialKind | null;
|
|
}
|
|
|
|
export interface PotOutcome {
|
|
amount: number;
|
|
eligible: PlayerId[];
|
|
type: 'win' | 'split' | 'rematch' | 'fold';
|
|
winners: PlayerId[];
|
|
reason: 'normal' | 'ttaengjabi' | 'amhaeng' | 'gusa' | 'mungGusa' | 'tie' | 'limit' | 'fold';
|
|
}
|
|
|
|
export interface SeotdaHand {
|
|
handNo: number;
|
|
/** 0 = 본 판, 1.. = 재경기 차수. */
|
|
rematchNo: number;
|
|
phase: 'betting' | 'choose' | 'rejoin' | 'handEnd';
|
|
dealer: PlayerId;
|
|
/** Participants of this (re)match, from the dealer clockwise. */
|
|
order: PlayerId[];
|
|
/** Remaining deck (secret). */
|
|
deck: number[];
|
|
cards: Record<PlayerId, number[]>;
|
|
/** 3장 섯다: chosen pair (secret until showdown). */
|
|
chosen: Record<PlayerId, [number, number] | null>;
|
|
betting: BettingState | null;
|
|
street: 0 | 1;
|
|
/** Bet counter (deadline key). */
|
|
betSeq: number;
|
|
/** Pots carried from earlier matches of the same hand (eligibility fixed). */
|
|
carried: PotState[];
|
|
rematchReason: 'gusa' | 'mungGusa' | 'tie' | null;
|
|
/** Upcoming rematch participants (handEnd → rejoin → rematch). */
|
|
rematchSet: PlayerId[];
|
|
rejoinPending: PlayerId[];
|
|
rejoinCost: number;
|
|
rejoined: PlayerId[];
|
|
showdown: { hands: ShowdownHand[]; pots: PotOutcome[] } | null;
|
|
foldWin: { winner: PlayerId; amount: number } | null;
|
|
next: 'rematch' | 'nextHand' | null;
|
|
ready: PlayerId[];
|
|
lastAction: Record<PlayerId, { type: BetType; amount: number }>;
|
|
}
|
|
|
|
export interface HandRecord {
|
|
handNo: number;
|
|
rematchNo: number;
|
|
winners: PlayerId[];
|
|
amount: number;
|
|
name: string | null;
|
|
how: PotOutcome['reason'] | 'rematch';
|
|
}
|
|
|
|
export interface SeotdaFinal {
|
|
ranking: PlayerId[][];
|
|
scores: Record<PlayerId, number>;
|
|
/** Result-screen score: chips at the end (re-buys taken back when the game ends by hand count). */
|
|
scoreText?: Record<PlayerId, string>;
|
|
summary: string;
|
|
}
|
|
|
|
export interface SeotdaState {
|
|
options: SeotdaOptions;
|
|
seats: SeatState[];
|
|
baseUnit: number;
|
|
hand: SeotdaHand | null;
|
|
handsPlayed: number;
|
|
lastWinner: PlayerId | null;
|
|
lastDealer: PlayerId | null;
|
|
phase: 'playing' | 'rebuy' | 'finished';
|
|
rebuyPending: PlayerId[];
|
|
deadlineAt: number | null;
|
|
waitKey: string;
|
|
history: HandRecord[];
|
|
stats: {
|
|
rematches: number;
|
|
bestHand: { playerId: PlayerId; name: string; value: number; handNo: number } | null;
|
|
biggestPot: { handNo: number; amount: number; winners: PlayerId[] } | null;
|
|
};
|
|
final: SeotdaFinal | null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- view
|
|
|
|
export interface SeotdaCardView {
|
|
/** Unique per (hand, match, card) so leak tests can spot it. */
|
|
key: string;
|
|
id: number;
|
|
month: number;
|
|
kind: 'gwang' | 'yeol' | 'tti' | 'pi' | 'ssangpi' | 'bonus';
|
|
tti?: 'hong' | 'cheong' | 'cho' | 'plain';
|
|
name: string;
|
|
}
|
|
export type CardSlot = SeotdaCardView | { hidden: true };
|
|
|
|
export interface SeotdaSeatView {
|
|
id: PlayerId;
|
|
stack: number;
|
|
rebuys: number;
|
|
status: SeatState['status'];
|
|
left: boolean;
|
|
away: boolean;
|
|
inHand: boolean;
|
|
folded: boolean;
|
|
allIn: boolean;
|
|
roundBet: number;
|
|
matchBet: number;
|
|
cards: CardSlot[];
|
|
/** 3장 섯다 choose phase: has chosen (null outside that phase). */
|
|
chosen: boolean | null;
|
|
isDealer: boolean;
|
|
isTurn: boolean;
|
|
ready: boolean;
|
|
lastAction: { type: BetType; amount: number } | null;
|
|
/** Shown after showdown only. */
|
|
handName: string | null;
|
|
}
|
|
|
|
export interface SeotdaView {
|
|
options: SeotdaOptions;
|
|
me: PlayerId | null;
|
|
phase: SeotdaState['phase'];
|
|
handPhase: SeotdaHand['phase'] | null;
|
|
handNo: number;
|
|
handsPlayed: number;
|
|
rematchNo: number;
|
|
rematchReason: SeotdaHand['rematchReason'];
|
|
baseUnit: number;
|
|
seats: SeotdaSeatView[];
|
|
dealer: PlayerId | null;
|
|
toAct: PlayerId | null;
|
|
street: number;
|
|
pot: number;
|
|
pots: PotState[];
|
|
currentBet: number;
|
|
legal: { type: BetType; amount: number; allIn: boolean }[];
|
|
myHand: { name: string; value: number | null; special: SpecialKind | null; hint: string; strength: 'high' | 'mid' | 'low' | null } | null;
|
|
myCombos: { cardIds: [number, number]; name: string; value: number; best: boolean }[] | null;
|
|
myChosen: [number, number] | null;
|
|
myDiscard: SeotdaCardView | null;
|
|
rejoin: { pending: PlayerId[]; cost: number; mine: boolean; canAfford: boolean } | null;
|
|
rebuy: { pending: PlayerId[]; mine: boolean; left: number | null } | null;
|
|
showdown: { hands: (Omit<ShowdownHand, 'cards'> & { cards: SeotdaCardView[] })[]; pots: PotOutcome[] } | null;
|
|
foldWin: SeotdaHand['foldWin'];
|
|
next: SeotdaHand['next'];
|
|
deadlineAt: number | null;
|
|
history: HandRecord[];
|
|
stats: SeotdaState['stats'];
|
|
result: SeotdaFinal | null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- helpers
|
|
|
|
/** Placeholder better that carries earlier pots so 쿼터/하프/풀 see the whole 모인 칩 (§5.5-2). */
|
|
const CARRY = '#carried';
|
|
const HAND_END_MS = 4000;
|
|
const AWAY_MS = 5000;
|
|
const STANDING_CAP = 300;
|
|
|
|
const rulesOf = (o: SeotdaOptions): HandRules => ({
|
|
gwangTtaeng: o.gwangTtaeng,
|
|
ttaengjabi: o.ttaengjabi,
|
|
amhaeng: o.amhaeng,
|
|
gusa: o.gusa,
|
|
mungGusa: o.gusa ? o.mungGusa : 'off',
|
|
});
|
|
const seatOf = (s: SeotdaState, id: PlayerId): SeatState | undefined => s.seats.find((x) => x.id === id);
|
|
const seatIdx = (s: SeotdaState, id: PlayerId): number => s.seats.findIndex((x) => x.id === id);
|
|
const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0);
|
|
const carriedTotal = (h: SeotdaHand): number => sum(h.carried.map((p) => p.amount));
|
|
const realPlayers = (b: BettingState) => b.players.filter((p) => p.id !== CARRY);
|
|
/** Chips bet in the current match (carried pots excluded). */
|
|
const livePot = (h: SeotdaHand): number => (h.betting ? sum(realPlayers(h.betting).map((p) => p.total)) : 0);
|
|
const contendersOf = (h: SeotdaHand): PlayerId[] =>
|
|
h.betting ? realPlayers(h.betting).filter((p) => p.status === 'active' || p.status === 'allIn').map((p) => p.id) : [];
|
|
const betterIdx = (h: SeotdaHand, id: PlayerId): number => (h.betting ? h.betting.players.findIndex((p) => p.id === id) : -1);
|
|
const maxRebuys = (o: SeotdaOptions): number => (o.rebuy === 'off' ? 0 : o.rebuy === 'limited' ? o.rebuyLimit : Infinity);
|
|
|
|
/** Total chips that must exist: Σ stacks + carried pots + live pot. */
|
|
export function chipsTotal(s: SeotdaState): number {
|
|
const h = s.hand;
|
|
return sum(s.seats.map((x) => x.stack)) + (h ? carriedTotal(h) + livePot(h) : 0);
|
|
}
|
|
|
|
function syncStacks(s: SeotdaState): void {
|
|
const b = s.hand?.betting;
|
|
if (!b) return;
|
|
for (const p of realPlayers(b)) seatOf(s, p.id)!.stack = p.stack;
|
|
}
|
|
|
|
/** Runs `fn` on the betting state without the carried-pot placeholder. */
|
|
function withoutCarry(b: BettingState, fn: (core: BettingState) => BettingState): BettingState {
|
|
const ph = b.players.find((p) => p.id === CARRY);
|
|
const out = fn({ ...b, players: b.players.filter((p) => p.id !== CARRY) });
|
|
if (ph) out.players.push(structuredClone(ph));
|
|
return out;
|
|
}
|
|
|
|
function cardView(h: SeotdaHand, id: number): SeotdaCardView {
|
|
const c = HWATU[id]!;
|
|
const key = `h${h.handNo}r${h.rematchNo}c${id}`;
|
|
// 8월 둘째 장은 섯다에서 일반 패(기러기)일 뿐이라 열끗 표시를 하지 않는다 (§3).
|
|
if (c.month === 8 && c.kind !== 'gwang') return { key, id, month: 8, kind: 'pi', name: '8월 기러기(공산)' };
|
|
return { key, id, month: c.month, kind: c.kind, ...(c.tti ? { tti: c.tti } : {}), name: c.name };
|
|
}
|
|
|
|
function orderFrom(ids: PlayerId[], s: SeotdaState, start: PlayerId): PlayerId[] {
|
|
const n = s.seats.length;
|
|
const st = seatIdx(s, start);
|
|
const out: PlayerId[] = [];
|
|
for (let k = 0; k < n; k++) {
|
|
const id = s.seats[(st + k) % n]!.id;
|
|
if (ids.includes(id)) out.push(id);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** First seat at or after `from` (clockwise, optionally exclusive) that is in `ids`. */
|
|
function firstFrom(s: SeotdaState, from: PlayerId, ids: PlayerId[], inclusive: boolean): PlayerId | null {
|
|
const n = s.seats.length;
|
|
const st = seatIdx(s, from);
|
|
for (let k = inclusive ? 0 : 1; k <= n; k++) {
|
|
const id = s.seats[(st + k) % n]!.id;
|
|
if (ids.includes(id)) return id;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function pushHistory(s: SeotdaState, r: HandRecord): void {
|
|
s.history.push(r);
|
|
if (s.history.length > 30) s.history.splice(0, s.history.length - 30);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- hand flow
|
|
|
|
function deal(h: SeotdaHand, ids: PlayerId[], count: number, events: GameEvent[]): void {
|
|
for (let r = 0; r < count; r++)
|
|
for (const id of ids) {
|
|
const c = h.deck.shift();
|
|
if (c === undefined) throw new Error('deck exhausted');
|
|
h.cards[id]!.push(c);
|
|
}
|
|
for (const id of ids) events.push({ type: 'dealt', to: id, count });
|
|
}
|
|
|
|
function firstDealCount(o: SeotdaOptions): number {
|
|
return o.cardMode === 'three' || o.dealMode === 'oneRound' ? 2 : 1;
|
|
}
|
|
|
|
function startHand(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
|
const o = s.options;
|
|
const eligible = s.seats.filter((x) => x.status === 'playing' && x.stack > 0).map((x) => x.id);
|
|
let dealer: PlayerId;
|
|
if (!s.lastDealer) dealer = eligible[rng.int(eligible.length)]!;
|
|
else if (o.dealerRule === 'winner' && s.lastWinner) dealer = firstFrom(s, s.lastWinner, eligible, true)!;
|
|
else dealer = firstFrom(s, s.lastDealer, eligible, false)!;
|
|
s.lastDealer = dealer;
|
|
const order = orderFrom(eligible, s, dealer);
|
|
for (const id of order) seatOf(s, id)!.stackAtHandStart = seatOf(s, id)!.stack;
|
|
let b = newBetting(
|
|
order.map((id) => ({ id, stack: seatOf(s, id)!.stack })),
|
|
{ style: 'korean', baseUnit: s.baseUnit, koreanMax: o.maxRaise },
|
|
);
|
|
b = postAnte(b, s.baseUnit);
|
|
const h: SeotdaHand = {
|
|
handNo: s.handsPlayed + 1,
|
|
rematchNo: 0,
|
|
phase: 'betting',
|
|
dealer,
|
|
order,
|
|
deck: rng.shuffle(SEOTDA_DECK),
|
|
cards: Object.fromEntries(order.map((id) => [id, []])),
|
|
chosen: Object.fromEntries(order.map((id) => [id, null])),
|
|
betting: b,
|
|
street: 0,
|
|
betSeq: 0,
|
|
carried: [],
|
|
rematchReason: null,
|
|
rematchSet: [],
|
|
rejoinPending: [],
|
|
rejoinCost: 0,
|
|
rejoined: [],
|
|
showdown: null,
|
|
foldWin: null,
|
|
next: null,
|
|
ready: [],
|
|
lastAction: {},
|
|
};
|
|
s.hand = h;
|
|
syncStacks(s);
|
|
events.push({ type: 'handStart', handNo: h.handNo, rematchNo: 0, dealer, ante: s.baseUnit });
|
|
deal(h, order, firstDealCount(o), events);
|
|
h.betting = startRound(b, 0);
|
|
}
|
|
|
|
function startRematch(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
const parts = h.rematchSet;
|
|
const dealer = parts.includes(h.dealer) ? h.dealer : firstFrom(s, h.dealer, parts, false)!;
|
|
const order = orderFrom(parts, s, dealer);
|
|
h.rematchNo += 1;
|
|
s.stats.rematches += 1;
|
|
h.dealer = dealer;
|
|
h.order = order;
|
|
h.phase = 'betting';
|
|
h.street = 0;
|
|
h.deck = rng.shuffle(SEOTDA_DECK);
|
|
h.cards = Object.fromEntries(order.map((id) => [id, []]));
|
|
h.chosen = Object.fromEntries(order.map((id) => [id, null]));
|
|
h.showdown = null;
|
|
h.foldWin = null;
|
|
h.next = null;
|
|
h.ready = [];
|
|
h.rejoinPending = [];
|
|
h.rematchSet = [];
|
|
h.lastAction = {};
|
|
let b = newBetting(
|
|
order.map((id) => ({ id, stack: seatOf(s, id)!.stack })),
|
|
{ style: 'korean', baseUnit: s.baseUnit, koreanMax: s.options.maxRaise },
|
|
);
|
|
// Players already all-in keep playing for the pots they reached (§5.5-3).
|
|
for (const p of b.players) if (p.stack === 0) p.status = 'allIn';
|
|
b.players.push({ id: CARRY, stack: 0, round: 0, total: carriedTotal(h), status: 'out', acted: true, raised: true, mayRaise: false });
|
|
events.push({ type: 'handStart', handNo: h.handNo, rematchNo: h.rematchNo, dealer, ante: 0, reason: h.rematchReason });
|
|
deal(h, order, firstDealCount(s.options), events);
|
|
h.betting = startRound(b, 0);
|
|
}
|
|
|
|
/** Pots of the current match: carried (re-filtered by who is still in) + this match's bets. */
|
|
function currentPots(h: SeotdaHand): PotState[] {
|
|
const live = contendersOf(h);
|
|
const b = h.betting!;
|
|
const fresh = buildPots(realPlayers(b));
|
|
const all: PotState[] = [
|
|
...h.carried.map((p) => {
|
|
const el = p.eligible.filter((id) => live.includes(id));
|
|
return { amount: p.amount, eligible: el.length ? el : [...live] };
|
|
}),
|
|
...fresh.map((p) => ({ amount: p.amount, eligible: p.eligible.filter((id) => live.includes(id)) })),
|
|
];
|
|
// Merge pots with the same eligible set; order by eligibility size (side pots first, §6.5).
|
|
const merged: PotState[] = [];
|
|
for (const p of all) {
|
|
if (p.amount <= 0) continue;
|
|
const key = [...p.eligible].sort().join();
|
|
const m = merged.find((x) => [...x.eligible].sort().join() === key);
|
|
if (m) m.amount += p.amount;
|
|
else merged.push({ amount: p.amount, eligible: h.order.filter((id) => p.eligible.includes(id)) });
|
|
}
|
|
return merged.sort((a, b2) => a.eligible.length - b2.eligible.length);
|
|
}
|
|
|
|
/** Clears the match's chips from the betting state after they were moved into pots / payouts. */
|
|
function clearBetting(s: SeotdaState): void {
|
|
const b = s.hand!.betting!;
|
|
for (const p of b.players) {
|
|
p.total = 0;
|
|
p.round = 0;
|
|
if (p.id !== CARRY) p.stack = seatOf(s, p.id)!.stack;
|
|
}
|
|
b.turn = null;
|
|
}
|
|
|
|
function pay(s: SeotdaState, won: Record<PlayerId, number>): void {
|
|
for (const [id, amt] of Object.entries(won)) seatOf(s, id)!.stack += amt;
|
|
}
|
|
|
|
function noteBiggest(s: SeotdaState, handNo: number, amount: number, winners: PlayerId[]): void {
|
|
if (!s.stats.biggestPot || amount > s.stats.biggestPot.amount) s.stats.biggestPot = { handNo, amount, winners: [...winners] };
|
|
}
|
|
|
|
function enterHandEnd(s: SeotdaState): void {
|
|
const h = s.hand!;
|
|
h.phase = 'handEnd';
|
|
h.ready = [];
|
|
}
|
|
|
|
function settleFold(s: SeotdaState, events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
const winner = contendersOf(h)[0] ?? h.order[0]!;
|
|
const amount = carriedTotal(h) + livePot(h);
|
|
h.carried = [];
|
|
clearBetting(s);
|
|
pay(s, { [winner]: amount });
|
|
syncBackStacks(s);
|
|
h.foldWin = { winner, amount };
|
|
h.next = 'nextHand';
|
|
s.lastWinner = winner;
|
|
noteBiggest(s, h.handNo, amount, [winner]);
|
|
pushHistory(s, { handNo: h.handNo, rematchNo: h.rematchNo, winners: [winner], amount, name: null, how: 'fold' });
|
|
events.push({ type: 'foldWin', winner, amount });
|
|
enterHandEnd(s);
|
|
}
|
|
|
|
function settleShowdown(s: SeotdaState, events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
const o = s.options;
|
|
const rules = rulesOf(o);
|
|
const live = h.order.filter((id) => contendersOf(h).includes(id));
|
|
const evals: Record<PlayerId, HandEval> = {};
|
|
const hands: ShowdownHand[] = [];
|
|
for (const id of live) {
|
|
const pair = (o.cardMode === 'three' ? h.chosen[id] : h.cards[id]) as [number, number];
|
|
const e = evalSeotda(pair[0], pair[1], rules);
|
|
evals[id] = e;
|
|
hands.push({ id, cards: pair, name: e.name, baseName: e.baseName, value: e.value, special: e.special });
|
|
if (!s.stats.bestHand || e.value > s.stats.bestHand.value) s.stats.bestHand = { playerId: id, name: e.baseName, value: e.value, handNo: h.handNo };
|
|
}
|
|
const pots = currentPots(h);
|
|
clearBetting(s);
|
|
const outcomes: PotOutcome[] = [];
|
|
const rematchPots: PotState[] = [];
|
|
let reason: SeotdaHand['rematchReason'] = null;
|
|
for (const pot of pots) {
|
|
const S = pot.eligible;
|
|
if (S.length === 1) {
|
|
pay(s, { [S[0]!]: pot.amount });
|
|
outcomes.push({ ...pot, type: 'win', winners: [...S], reason: 'normal' });
|
|
continue;
|
|
}
|
|
const r = resolve(S.map((id) => ({ id, hand: evals[id]! })), o.tieRule, rules);
|
|
if (r.type === 'win') {
|
|
pay(s, { [r.winners[0]!]: pot.amount });
|
|
outcomes.push({ ...pot, type: 'win', winners: r.winners, reason: r.reason });
|
|
} else if (r.type === 'split') {
|
|
pay(s, splitAmount(pot.amount, r.winners));
|
|
outcomes.push({ ...pot, type: 'split', winners: r.winners, reason: 'tie' });
|
|
} else if (h.rematchNo >= o.maxRematches) {
|
|
pay(s, splitAmount(pot.amount, r.participants));
|
|
outcomes.push({ ...pot, type: 'split', winners: r.participants, reason: 'limit' });
|
|
} else {
|
|
rematchPots.push({ amount: pot.amount, eligible: [...r.participants] });
|
|
outcomes.push({ ...pot, type: 'rematch', winners: r.participants, reason: r.reason });
|
|
if (r.reason !== 'tie') reason = r.reason;
|
|
else reason ??= 'tie';
|
|
}
|
|
}
|
|
syncBackStacks(s);
|
|
h.showdown = { hands, pots: outcomes };
|
|
events.push({ type: 'showdown', hands: hands.map((x) => ({ id: x.id, cards: x.cards, name: x.name })), pots: outcomes });
|
|
for (const out of outcomes) {
|
|
if (out.type === 'rematch') continue;
|
|
noteBiggest(s, h.handNo, out.amount, out.winners);
|
|
const name = out.winners.length ? evals[out.winners[0]!]!.name : null;
|
|
pushHistory(s, { handNo: h.handNo, rematchNo: h.rematchNo, winners: out.winners, amount: out.amount, name, how: out.reason });
|
|
}
|
|
// Main pot = the one with the most eligible players (last after sorting).
|
|
const main = outcomes[outcomes.length - 1];
|
|
if (rematchPots.length) {
|
|
h.carried = rematchPots;
|
|
h.rematchReason = reason;
|
|
h.rematchSet = h.order.filter((id) => rematchPots.some((p) => p.eligible.includes(id)));
|
|
h.next = 'rematch';
|
|
pushHistory(s, { handNo: h.handNo, rematchNo: h.rematchNo, winners: [], amount: carriedTotal(h), name: null, how: 'rematch' });
|
|
events.push({ type: 'rematch', reason, participants: h.rematchSet });
|
|
} else {
|
|
h.carried = [];
|
|
h.next = 'nextHand';
|
|
}
|
|
if (main && main.type !== 'rematch') s.lastWinner = main.winners[0]!;
|
|
enterHandEnd(s);
|
|
}
|
|
|
|
/** After payouts, keep the betting copy of stacks equal to the seats. */
|
|
function syncBackStacks(s: SeotdaState): void {
|
|
const b = s.hand?.betting;
|
|
if (!b) return;
|
|
for (const p of realPlayers(b)) p.stack = seatOf(s, p.id)!.stack;
|
|
}
|
|
|
|
function afterHandEnd(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
if (h.next === 'rematch') {
|
|
const gusaRematch = h.rematchReason === 'gusa' || h.rematchReason === 'mungGusa';
|
|
const folded = h.betting ? realPlayers(h.betting).filter((p) => p.status === 'folded').map((p) => p.id) : [];
|
|
const pending = folded.filter((id) => {
|
|
const st = seatOf(s, id)!;
|
|
return st.status === 'playing' && !st.left;
|
|
});
|
|
if (gusaRematch && s.options.rejoinCost !== 'none' && pending.length) {
|
|
const pot = carriedTotal(h);
|
|
h.rejoinCost = s.options.rejoinCost === 'half' ? Math.floor(pot / 2) : pot;
|
|
h.rejoinPending = pending;
|
|
h.rejoined = [];
|
|
h.phase = 'rejoin';
|
|
events.push({ type: 'rejoinAsk', players: pending, cost: h.rejoinCost });
|
|
return;
|
|
}
|
|
startRematch(s, rng, events);
|
|
return;
|
|
}
|
|
finishHand(s, rng, events);
|
|
}
|
|
|
|
function finishHand(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
|
const o = s.options;
|
|
const h = s.hand!;
|
|
s.handsPlayed += 1;
|
|
s.hand = null;
|
|
events.push({ type: 'handEnd', handNo: h.handNo });
|
|
if (o.schoolUpEvery > 0 && s.handsPlayed % o.schoolUpEvery === 0) {
|
|
const next = Math.min(s.baseUnit * 2, Math.floor(o.startingChips / 5));
|
|
if (next > s.baseUnit) {
|
|
s.baseUnit = next;
|
|
events.push({ type: 'schoolUp', baseUnit: next });
|
|
}
|
|
}
|
|
const lastHand = o.endCondition === 'hands' && s.handsPlayed >= o.handLimit;
|
|
s.rebuyPending = [];
|
|
for (const st of s.seats) {
|
|
if (st.status !== 'playing' || st.stack > 0) continue;
|
|
if (!st.left && !lastHand && st.rebuys < maxRebuys(o)) {
|
|
st.status = 'busted';
|
|
s.rebuyPending.push(st.id);
|
|
} else {
|
|
eliminate(s, st, h.handNo, events);
|
|
}
|
|
}
|
|
if (s.rebuyPending.length) {
|
|
s.phase = 'rebuy';
|
|
events.push({ type: 'rebuyAsk', players: s.rebuyPending });
|
|
return;
|
|
}
|
|
nextOrFinish(s, rng, events);
|
|
}
|
|
|
|
function eliminate(s: SeotdaState, st: SeatState, handNo: number, events: GameEvent[]): void {
|
|
st.status = 'eliminated';
|
|
st.eliminatedAtHand = handNo;
|
|
events.push({ type: 'eliminated', player: st.id, handNo });
|
|
}
|
|
|
|
function nextOrFinish(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
|
s.phase = 'playing';
|
|
const o = s.options;
|
|
const connected = s.seats.filter((x) => !x.left && x.status !== 'eliminated');
|
|
const withChips = s.seats.filter((x) => x.status === 'playing' && x.stack > 0);
|
|
const done =
|
|
connected.length <= 1 ||
|
|
withChips.length < 2 ||
|
|
(o.endCondition === 'hands' && s.handsPlayed >= o.handLimit) ||
|
|
(o.endCondition === 'lastStanding' && s.handsPlayed >= STANDING_CAP);
|
|
if (done) finishGame(s, events);
|
|
else startHand(s, rng, events);
|
|
}
|
|
|
|
function finishGame(s: SeotdaState, events: GameEvent[]): void {
|
|
const o = s.options;
|
|
s.phase = 'finished';
|
|
s.hand = null;
|
|
s.rebuyPending = [];
|
|
const byScore = o.endCondition === 'hands' || s.handsPlayed >= STANDING_CAP;
|
|
const scores: Record<PlayerId, number> = {};
|
|
let ranking: PlayerId[][] = [];
|
|
const group = (ids: PlayerId[], keyOf: (id: PlayerId) => string) => {
|
|
const out: PlayerId[][] = [];
|
|
for (const id of ids) {
|
|
const last = out[out.length - 1];
|
|
if (last && keyOf(last[0]!) === keyOf(id)) last.push(id);
|
|
else out.push([id]);
|
|
}
|
|
return out;
|
|
};
|
|
if (byScore) {
|
|
for (const x of s.seats) scores[x.id] = x.stack - o.startingChips * x.rebuys;
|
|
const ids = s.seats.map((x) => x.id).sort((a, b) => scores[b]! - scores[a]!);
|
|
ranking = group(ids, (id) => String(scores[id]));
|
|
} else {
|
|
const alive = s.seats.filter((x) => x.status !== 'eliminated').sort((a, b) => b.stack - a.stack);
|
|
const dead = s.seats
|
|
.filter((x) => x.status === 'eliminated')
|
|
.sort((a, b) => (b.eliminatedAtHand ?? 0) - (a.eliminatedAtHand ?? 0) || b.stackAtHandStart - a.stackAtHandStart);
|
|
const aliveKey = (id: PlayerId) => `a${seatOf(s, id)!.stack}`;
|
|
const deadKey = (id: PlayerId) => `d${seatOf(s, id)!.eliminatedAtHand}:${seatOf(s, id)!.stackAtHandStart}`;
|
|
ranking = [...group(alive.map((x) => x.id), aliveKey), ...group(dead.map((x) => x.id), deadKey)];
|
|
const n = s.seats.length;
|
|
let rank = 1;
|
|
for (const g of ranking) {
|
|
for (const id of g) scores[id] = n + 1 - rank;
|
|
rank += g.length;
|
|
}
|
|
}
|
|
const top = ranking[0] ?? [];
|
|
const best = s.stats.bestHand ? `, 최고 족보 ${s.stats.bestHand.name}` : '';
|
|
let summary: string;
|
|
if (byScore) {
|
|
const sc = scores[top[0]!] ?? 0;
|
|
const tie = top.length > 1 ? ` (공동 ${top.length}명)` : '';
|
|
summary = `${s.handsPlayed}판 끝. 1위 ${sc >= 0 ? '+' : ''}${sc.toLocaleString('ko-KR')}칩${tie}${best}`;
|
|
} else {
|
|
summary = `${s.handsPlayed}판 만에 끝났어요. 1위 ${(seatOf(s, top[0]!)?.stack ?? 0).toLocaleString('ko-KR')}칩${best}`;
|
|
}
|
|
const scoreText = Object.fromEntries(s.seats.map((x) => [x.id, `${(byScore ? scores[x.id]! : x.stack).toLocaleString('ko-KR')}칩`]));
|
|
s.final = { ranking, scores, scoreText, summary };
|
|
events.push({ type: 'gameEnd', ranking });
|
|
}
|
|
|
|
// ---------------------------------------------------------------- progression
|
|
|
|
function applyBetAction(s: SeotdaState, id: PlayerId, t: BetType, events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
const idx = betterIdx(h, id);
|
|
const r = applyBet(h.betting!, idx, { kind: toKind(t) } as BetAction);
|
|
h.betting = r.state;
|
|
h.betSeq += 1;
|
|
h.lastAction[id] = { type: t, amount: r.event.amount };
|
|
syncStacks(s);
|
|
events.push({ type: 'bet', player: id, kind: t, amount: r.event.amount, allIn: r.event.allIn });
|
|
}
|
|
|
|
function chooseFor(s: SeotdaState, id: PlayerId, pair: [number, number], events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
h.chosen[id] = [Math.min(...pair), Math.max(...pair)] as [number, number];
|
|
events.push({ type: 'chose', player: id });
|
|
}
|
|
|
|
function requiredReady(s: SeotdaState): PlayerId[] {
|
|
return s.seats.filter((x) => x.status === 'playing' && !x.left).map((x) => x.id);
|
|
}
|
|
|
|
/** Advances automatic steps (round ends, dealing, left players) until someone must decide. */
|
|
function progress(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
|
for (let guard = 0; guard < 10_000; guard++) {
|
|
if (s.phase === 'finished') return;
|
|
if (s.phase === 'rebuy') {
|
|
const gone = s.rebuyPending.filter((id) => seatOf(s, id)!.left);
|
|
for (const id of gone) decideRebuy(s, id, false, events);
|
|
if (s.rebuyPending.length === 0) {
|
|
nextOrFinish(s, rng, events);
|
|
continue;
|
|
}
|
|
return;
|
|
}
|
|
const h = s.hand;
|
|
if (!h) return;
|
|
switch (h.phase) {
|
|
case 'betting': {
|
|
const b = h.betting!;
|
|
if (b.turn !== null) {
|
|
const id = b.players[b.turn]!.id;
|
|
if (seatOf(s, id)!.left) {
|
|
applyBetAction(s, id, 'die', events);
|
|
continue;
|
|
}
|
|
return;
|
|
}
|
|
h.betting = withoutCarry(b, (core) => returnUncalled(core).state);
|
|
syncStacks(s);
|
|
if (handDecided(h.betting)) {
|
|
settleFold(s, events);
|
|
continue;
|
|
}
|
|
if (h.street === 0 && s.options.cardMode === 'three') {
|
|
deal(h, h.order.filter((id) => contendersOf(h).includes(id)), 1, events);
|
|
h.phase = 'choose';
|
|
continue;
|
|
}
|
|
if (h.street === 0 && s.options.dealMode === 'twoRounds') {
|
|
deal(h, h.order.filter((id) => contendersOf(h).includes(id)), 1, events);
|
|
h.street = 1;
|
|
h.lastAction = {};
|
|
h.betting = startRound(h.betting, 0);
|
|
continue;
|
|
}
|
|
settleShowdown(s, events);
|
|
continue;
|
|
}
|
|
case 'choose': {
|
|
const waiting = contendersOf(h).filter((id) => !h.chosen[id]);
|
|
for (const id of waiting) if (seatOf(s, id)!.left) chooseFor(s, id, bestChoice(h.cards[id]!, rulesOf(s.options)), events);
|
|
if (contendersOf(h).every((id) => h.chosen[id])) {
|
|
h.phase = 'betting';
|
|
h.street = 1;
|
|
h.lastAction = {};
|
|
h.betting = startRound(h.betting!, 0);
|
|
continue;
|
|
}
|
|
return;
|
|
}
|
|
case 'rejoin': {
|
|
for (const id of [...h.rejoinPending]) if (seatOf(s, id)!.left) decideRejoin(s, id, false, events);
|
|
if (h.rejoinPending.length === 0) {
|
|
startRematch(s, rng, events);
|
|
continue;
|
|
}
|
|
return;
|
|
}
|
|
case 'handEnd': {
|
|
if (requiredReady(s).every((id) => h.ready.includes(id))) {
|
|
afterHandEnd(s, rng, events);
|
|
continue;
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
throw new Error('seotda: progress did not settle');
|
|
}
|
|
|
|
function decideRejoin(s: SeotdaState, id: PlayerId, accept: boolean, events: GameEvent[]): void {
|
|
const h = s.hand!;
|
|
h.rejoinPending = h.rejoinPending.filter((x) => x !== id);
|
|
if (accept) {
|
|
const st = seatOf(s, id)!;
|
|
st.stack -= h.rejoinCost;
|
|
// Paid into the main (largest) rematch pot; the rejoiner can win every carried pot.
|
|
h.carried[h.carried.length - 1]!.amount += h.rejoinCost;
|
|
for (const p of h.carried) if (!p.eligible.includes(id)) p.eligible.push(id);
|
|
h.rejoined.push(id);
|
|
h.rematchSet = orderFrom([...h.rematchSet, id], s, h.dealer);
|
|
}
|
|
events.push({ type: 'rejoin', player: id, accept, cost: accept ? h.rejoinCost : 0 });
|
|
}
|
|
|
|
function decideRebuy(s: SeotdaState, id: PlayerId, accept: boolean, events: GameEvent[]): void {
|
|
const st = seatOf(s, id)!;
|
|
s.rebuyPending = s.rebuyPending.filter((x) => x !== id);
|
|
if (accept) {
|
|
st.stack = s.options.startingChips;
|
|
st.rebuys += 1;
|
|
st.status = 'playing';
|
|
} else {
|
|
eliminate(s, st, s.handsPlayed, events);
|
|
}
|
|
events.push({ type: 'rebuy', player: id, accept });
|
|
}
|
|
|
|
/** Deadline bookkeeping: a new wait (different phase / turn) restarts the clock. */
|
|
function refreshDeadline(s: SeotdaState, now: number): void {
|
|
const o = s.options;
|
|
const h = s.hand;
|
|
let key: string = s.phase;
|
|
let ms: number | null = null;
|
|
if (s.phase === 'rebuy') {
|
|
key += `|${s.handsPlayed}`;
|
|
ms = o.decisionSeconds * 1000;
|
|
}
|
|
else if (s.phase === 'playing' && h) {
|
|
key += `|${h.handNo}|${h.rematchNo}|${h.phase}|${h.street}`;
|
|
if (h.phase === 'betting' && h.betting?.turn != null) {
|
|
const id = h.betting.players[h.betting.turn]!.id;
|
|
key += `|${id}|${h.betSeq}`;
|
|
ms = seatOf(s, id)!.away ? AWAY_MS : o.turnSeconds * 1000;
|
|
} else if (h.phase === 'choose') ms = (o.turnSeconds + 10) * 1000;
|
|
else if (h.phase === 'rejoin') ms = o.decisionSeconds * 1000;
|
|
else if (h.phase === 'handEnd') ms = HAND_END_MS;
|
|
}
|
|
if (key !== s.waitKey) {
|
|
s.waitKey = key;
|
|
s.deadlineAt = ms === null ? null : now + ms;
|
|
}
|
|
if (ms === null) s.deadlineAt = null;
|
|
}
|
|
|
|
function waiting(s: SeotdaState): PlayerId[] {
|
|
if (s.phase === 'finished') return [];
|
|
if (s.phase === 'rebuy') return [...s.rebuyPending];
|
|
const h = s.hand;
|
|
if (!h) return [];
|
|
switch (h.phase) {
|
|
case 'betting':
|
|
return h.betting?.turn != null ? [h.betting.players[h.betting.turn]!.id] : [];
|
|
case 'choose':
|
|
return contendersOf(h).filter((id) => !h.chosen[id]);
|
|
case 'rejoin':
|
|
return [...h.rejoinPending];
|
|
case 'handEnd':
|
|
return requiredReady(s).filter((id) => !h.ready.includes(id));
|
|
}
|
|
}
|
|
|
|
function isBet(t: string): t is BetType {
|
|
return (BET_TYPES as string[]).includes(t);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- definition
|
|
|
|
export function playerRange(o: Pick<SeotdaOptions, 'cardMode'>): { min: number; max: number } {
|
|
return { min: 2, max: o.cardMode === 'three' ? 6 : 10 };
|
|
}
|
|
|
|
export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, SeotdaOptions> = {
|
|
id: 'seotda',
|
|
nameKo: '섯다',
|
|
minPlayers: 2,
|
|
maxPlayers: 10,
|
|
stateVersion: 1,
|
|
defaultOptions: seotdaOptionsSchema.parse({}),
|
|
optionsSchema: seotdaOptionsSchema as unknown as z.ZodType<SeotdaOptions>,
|
|
actionSchema: seotdaActionSchema as unknown as z.ZodType<SeotdaAction>,
|
|
playersFor: playerRange,
|
|
|
|
setup({ players, options, rng, now }) {
|
|
const range = playerRange(options);
|
|
if (players.length < range.min || players.length > range.max) throw new Error(`seotda: ${players.length} players not allowed`);
|
|
const s: SeotdaState = {
|
|
options,
|
|
seats: players.map((id) => ({
|
|
id,
|
|
stack: options.startingChips,
|
|
rebuys: 0,
|
|
status: 'playing',
|
|
left: false,
|
|
away: false,
|
|
timeoutsInRow: 0,
|
|
eliminatedAtHand: null,
|
|
stackAtHandStart: options.startingChips,
|
|
})),
|
|
baseUnit: options.baseUnit,
|
|
hand: null,
|
|
handsPlayed: 0,
|
|
lastWinner: null,
|
|
lastDealer: null,
|
|
phase: 'playing',
|
|
rebuyPending: [],
|
|
deadlineAt: null,
|
|
waitKey: '',
|
|
history: [],
|
|
stats: { rematches: 0, bestHand: null, biggestPot: null },
|
|
final: null,
|
|
};
|
|
const events: GameEvent[] = [];
|
|
startHand(s, rng, events);
|
|
progress(s, rng, events);
|
|
refreshDeadline(s, now);
|
|
return s;
|
|
},
|
|
|
|
validate(s, actor, a) {
|
|
const st = seatOf(s, actor);
|
|
if (!st) return fail('이 게임의 플레이어가 아니에요.');
|
|
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
|
|
if (a.type === 'leave') return st.left ? fail('이미 나간 플레이어예요.') : ok;
|
|
if (a.type === 'timeout') return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
|
|
if (st.left) return 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('지금은 할 수 없어요.');
|
|
if (isBet(a.type)) {
|
|
if (h.phase !== 'betting' || !h.betting) return fail('지금은 베팅 시간이 아니에요.');
|
|
const idx = betterIdx(h, actor);
|
|
if (idx < 0) return fail('이번 판에 참가하지 않았어요.');
|
|
const err = validateBet(h.betting, idx, { kind: toKind(a.type) } as BetAction);
|
|
if (!err) return ok;
|
|
if (h.betting.turn === idx && ['ping', 'ddadang', 'quarter', 'half', 'full'].includes(a.type)) {
|
|
if (a.type === 'full' && s.options.maxRaise === 'half') return fail('이 방은 하프까지만 올릴 수 있어요.');
|
|
if (a.type === 'ping' && h.betting.opened) return fail('누가 이미 걸어서 삥을 할 수 없어요.');
|
|
return fail('이번 라운드에는 더 올릴 수 없어요(콜 또는 다이).');
|
|
}
|
|
if (a.type === 'check' && h.betting.turn === idx) return fail('누가 이미 걸어서 체크할 수 없어요.');
|
|
return fail(err);
|
|
}
|
|
switch (a.type) {
|
|
case 'choose': {
|
|
if (h.phase !== 'choose') return fail('지금은 카드를 고를 때가 아니에요.');
|
|
if (!contendersOf(h).includes(actor)) return fail('이번 판에 남아 있지 않아요.');
|
|
if (h.chosen[actor]) return fail('이미 골랐어요.');
|
|
const [x, y] = a.cardIds;
|
|
const mine = h.cards[actor] ?? [];
|
|
if (x === y || !mine.includes(x) || !mine.includes(y)) return fail('카드 두 장을 골라 주세요.');
|
|
return ok;
|
|
}
|
|
case 'rejoin': {
|
|
if (h.phase !== 'rejoin' || !h.rejoinPending.includes(actor)) return fail('재참가 대상이 아니에요.');
|
|
if (a.accept && st.stack < h.rejoinCost) return fail('칩이 모자라 재참가할 수 없어요.');
|
|
return ok;
|
|
}
|
|
case 'ready': {
|
|
if (h.phase !== 'handEnd') return fail('아직 판이 끝나지 않았어요.');
|
|
if (!requiredReady(s).includes(actor) || h.ready.includes(actor)) return fail('이미 준비했어요.');
|
|
return ok;
|
|
}
|
|
}
|
|
return fail('알 수 없는 행동이에요.');
|
|
},
|
|
|
|
apply(prev, actor, a, { rng, now }) {
|
|
const s = structuredClone(prev);
|
|
const events: GameEvent[] = [];
|
|
const st = seatOf(s, actor)!;
|
|
const h = s.hand;
|
|
if (a.type !== 'timeout' && a.type !== 'leave') {
|
|
st.timeoutsInRow = 0;
|
|
st.away = false;
|
|
}
|
|
if (isBet(a.type)) applyBetAction(s, actor, a.type, events);
|
|
else
|
|
switch (a.type) {
|
|
case 'choose':
|
|
chooseFor(s, actor, a.cardIds, events);
|
|
break;
|
|
case 'rejoin':
|
|
decideRejoin(s, actor, a.accept, events);
|
|
break;
|
|
case 'ready':
|
|
h!.ready.push(actor);
|
|
break;
|
|
case 'rebuy':
|
|
decideRebuy(s, actor, a.accept, events);
|
|
break;
|
|
case 'leave':
|
|
st.left = true;
|
|
events.push({ type: 'left', player: actor });
|
|
if (h?.phase === 'handEnd') h.ready = h.ready.filter((x) => x !== actor);
|
|
break;
|
|
case 'timeout': {
|
|
const phase = s.phase === 'rebuy' ? 'rebuy' : h!.phase;
|
|
if (phase === 'betting' || phase === 'choose') {
|
|
st.timeoutsInRow += 1;
|
|
if (st.timeoutsInRow >= 2 && !st.away) {
|
|
st.away = true;
|
|
events.push({ type: 'away', player: actor });
|
|
}
|
|
}
|
|
events.push({ type: 'timeout', player: actor });
|
|
if (phase === 'betting') {
|
|
const b = h!.betting!;
|
|
applyBetAction(s, actor, toType(timeoutBet(b, betterIdx(h!, actor)).kind), events);
|
|
} else if (phase === 'choose') chooseFor(s, actor, bestChoice(h!.cards[actor]!, rulesOf(s.options)), events);
|
|
else if (phase === 'rejoin') decideRejoin(s, actor, false, events);
|
|
else if (phase === 'handEnd') h!.ready.push(actor);
|
|
else decideRebuy(s, actor, false, events);
|
|
break;
|
|
}
|
|
}
|
|
progress(s, rng, events);
|
|
refreshDeadline(s, now);
|
|
return { state: s, events };
|
|
},
|
|
|
|
view(s, viewer) {
|
|
const o = s.options;
|
|
const h = s.hand;
|
|
const rules = rulesOf(o);
|
|
const b = h?.betting ?? null;
|
|
const showdownIds = new Set(h?.showdown?.hands.map((x) => x.id) ?? []);
|
|
const seats: SeotdaSeatView[] = s.seats.map((x) => {
|
|
const better = b?.players.find((p) => p.id === x.id) ?? null;
|
|
const inHand = !!h && h.order.includes(x.id);
|
|
const cards = h && inHand ? (h.cards[x.id] ?? []) : [];
|
|
let slots: CardSlot[];
|
|
if (h && showdownIds.has(x.id)) {
|
|
const pair = h.showdown!.hands.find((y) => y.id === x.id)!.cards;
|
|
slots = pair.map((c) => cardView(h, c));
|
|
} else if (h && x.id === viewer) slots = cards.map((c) => cardView(h, c));
|
|
else {
|
|
// 3장 섯다 after choosing: others see two face-down cards (the discard stays secret).
|
|
const n = o.cardMode === 'three' && h?.chosen[x.id] ? 2 : cards.length;
|
|
slots = Array.from({ length: n }, () => ({ hidden: true as const }));
|
|
}
|
|
return {
|
|
id: x.id,
|
|
stack: x.stack,
|
|
rebuys: x.rebuys,
|
|
status: x.status,
|
|
left: x.left,
|
|
away: x.away,
|
|
inHand,
|
|
folded: better?.status === 'folded',
|
|
allIn: better?.status === 'allIn',
|
|
roundBet: better?.round ?? 0,
|
|
matchBet: better?.total ?? 0,
|
|
cards: slots,
|
|
chosen: h?.phase === 'choose' && contendersOf(h).includes(x.id) ? !!h.chosen[x.id] : null,
|
|
isDealer: h?.dealer === x.id,
|
|
isTurn: !!b && b.turn !== null && h?.phase === 'betting' && b.players[b.turn]!.id === x.id,
|
|
ready: !!h && h.phase === 'handEnd' && h.ready.includes(x.id),
|
|
lastAction: h?.lastAction[x.id] ?? null,
|
|
handName: h?.showdown?.hands.find((y) => y.id === x.id)?.name ?? null,
|
|
};
|
|
});
|
|
const me = viewer && seatOf(s, viewer) ? viewer : null;
|
|
const myIdx = h && me ? betterIdx(h, me) : -1;
|
|
const legal =
|
|
h && b && myIdx >= 0 && h.phase === 'betting' && !seatOf(s, me!)!.left
|
|
? legalBets(b, myIdx).map((l) => ({ type: toType(l.kind), amount: l.amount, allIn: l.allIn }))
|
|
: [];
|
|
let myHand: SeotdaView['myHand'] = null;
|
|
let myCombos: SeotdaView['myCombos'] = null;
|
|
let myDiscard: SeotdaCardView | null = null;
|
|
const myCards = h && me ? (h.cards[me] ?? []) : [];
|
|
const myChosen = h && me ? (h.chosen[me] ?? null) : null;
|
|
if (h && me && myCards.length) {
|
|
if (o.cardMode === 'three' && myCards.length === 3) {
|
|
const best = bestChoice(myCards, rules);
|
|
myCombos = combos(myCards).map((c) => {
|
|
const e = evalSeotda(c[0], c[1], rules);
|
|
const ids = [Math.min(...c), Math.max(...c)] as [number, number];
|
|
return { cardIds: ids, name: e.name, value: e.value, best: ids[0] === best[0] && ids[1] === best[1] };
|
|
});
|
|
if (myChosen) myDiscard = cardView(h, myCards.find((c) => !myChosen.includes(c))!);
|
|
}
|
|
if (o.hints) {
|
|
const pair = myChosen ?? (myCards.length === 2 ? (myCards as [number, number]) : myCards.length === 3 ? bestChoice(myCards, rules) : null);
|
|
if (pair) {
|
|
const e = evalSeotda(pair[0], pair[1], rules);
|
|
const prefix = !myChosen && myCards.length === 3 ? '최고 조합 ' : '';
|
|
myHand = { name: prefix + e.name, value: e.value, special: e.special, hint: hintText(e, rules), strength: strengthOf(e) };
|
|
} else {
|
|
const c = HWATU[myCards[0]!]!;
|
|
myHand = { name: `${c.month}월 한 장`, value: null, special: null, hint: '한 장 더 받으면 족보가 정해져요.', strength: null };
|
|
}
|
|
}
|
|
}
|
|
const pots: PotState[] = h ? (b && (h.phase === 'betting' || h.phase === 'choose') ? currentPots(h) : h.carried) : [];
|
|
return {
|
|
options: o,
|
|
me,
|
|
phase: s.phase,
|
|
handPhase: h?.phase ?? null,
|
|
handNo: h?.handNo ?? s.handsPlayed,
|
|
handsPlayed: s.handsPlayed,
|
|
rematchNo: h?.rematchNo ?? 0,
|
|
rematchReason: h && h.rematchNo > 0 ? h.rematchReason : null,
|
|
baseUnit: s.baseUnit,
|
|
seats,
|
|
dealer: h?.dealer ?? null,
|
|
toAct: b && b.turn !== null && h?.phase === 'betting' ? b.players[b.turn]!.id : null,
|
|
street: h?.street ?? 0,
|
|
pot: h ? carriedTotal(h) + livePot(h) : 0,
|
|
pots,
|
|
currentBet: b?.currentBet ?? 0,
|
|
legal,
|
|
myHand,
|
|
myCombos,
|
|
myChosen,
|
|
myDiscard,
|
|
rejoin:
|
|
h?.phase === 'rejoin'
|
|
? { pending: h.rejoinPending, cost: h.rejoinCost, mine: !!me && h.rejoinPending.includes(me), canAfford: !!me && seatOf(s, me)!.stack >= h.rejoinCost }
|
|
: null,
|
|
rebuy:
|
|
s.phase === 'rebuy'
|
|
? {
|
|
pending: s.rebuyPending,
|
|
mine: !!me && s.rebuyPending.includes(me),
|
|
left: me ? (Number.isFinite(maxRebuys(o)) ? maxRebuys(o) - seatOf(s, me)!.rebuys : null) : null,
|
|
}
|
|
: null,
|
|
showdown: h?.showdown
|
|
? { hands: h.showdown.hands.map((x) => ({ ...x, cards: x.cards.map((c) => cardView(h, c)) })), pots: h.showdown.pots }
|
|
: null,
|
|
foldWin: h?.foldWin ?? null,
|
|
next: h?.next ?? null,
|
|
deadlineAt: s.deadlineAt,
|
|
history: s.history,
|
|
stats: s.stats,
|
|
result: s.final,
|
|
};
|
|
},
|
|
|
|
activePlayers: waiting,
|
|
|
|
deadline(s) {
|
|
return s.phase === 'finished' ? null : s.deadlineAt;
|
|
},
|
|
|
|
timeoutPlayers: waiting,
|
|
|
|
onTimeout() {
|
|
return { type: 'timeout' };
|
|
},
|
|
|
|
onLeave(s, player) {
|
|
const st = seatOf(s, player);
|
|
if (!st || st.left || s.phase === 'finished') return null;
|
|
return { type: 'leave' };
|
|
},
|
|
|
|
result(s): GameResult | null {
|
|
if (!s.final) return null;
|
|
const { ranking, scores, scoreText, summary } = s.final;
|
|
return { ranking, scores, ...(scoreText ? { scoreText } : {}), summary, reason: 'normal' };
|
|
},
|
|
|
|
legalActions(s, p) {
|
|
const st = seatOf(s, p);
|
|
if (!st || st.left || s.phase === 'finished') return [];
|
|
if (s.phase === 'rebuy') return s.rebuyPending.includes(p) ? [{ type: 'rebuy', accept: true }, { type: 'rebuy', accept: false }] : [];
|
|
const h = s.hand;
|
|
if (!h) return [];
|
|
switch (h.phase) {
|
|
case 'betting': {
|
|
const idx = betterIdx(h, p);
|
|
if (idx < 0 || !h.betting) return [];
|
|
return legalBets(h.betting, idx).map((l) => ({ type: toType(l.kind) }) as SeotdaAction);
|
|
}
|
|
case 'choose':
|
|
if (!contendersOf(h).includes(p) || h.chosen[p]) return [];
|
|
return combos(h.cards[p]!).map((c) => ({ type: 'choose', cardIds: c }) as SeotdaAction);
|
|
case 'rejoin':
|
|
if (!h.rejoinPending.includes(p)) return [];
|
|
return st.stack >= h.rejoinCost ? [{ type: 'rejoin', accept: true }, { type: 'rejoin', accept: false }] : [{ type: 'rejoin', accept: false }];
|
|
case 'handEnd':
|
|
return requiredReady(s).includes(p) && !h.ready.includes(p) ? [{ type: 'ready' }] : [];
|
|
}
|
|
},
|
|
|
|
/** Hidden cards of `player` (unrevealed hand, 3장 discard) plus the deck — keys as used in views. */
|
|
secretsOf(s, player) {
|
|
const h = s.hand;
|
|
if (!h) return [];
|
|
const revealed = new Set(h.showdown?.hands.find((x) => x.id === player)?.cards ?? []);
|
|
const key = (c: number) => `h${h.handNo}r${h.rematchNo}c${c}`;
|
|
const own = (h.cards[player] ?? []).filter((c) => !revealed.has(c)).map(key);
|
|
return [...own, ...h.deck.map(key)];
|
|
},
|
|
};
|