Files
joke-app/packages/engine/src/betting.test.ts
EJClaw 9519b09be8 M3 기반: 공용 베팅 엔진, 카드 정의, 카드·칩 화면 컴포넌트, 돈 표현 금지 검사
- packages/engine/betting: 한국식(체크·삥·콜·따당·쿼터·하프·풀·다이, 라운드당 1회·첫 행동에서만 레이즈),
  노리밋·팟리밋(최소 레이즈, 불완전 올인 레이즈는 재오픈 안 함, BB 옵션), 앤티·블라인드, 올인,
  받지 않은 베팅 반환, 사이드 팟 분할, 동점 분배(홀수 칩 순서), 시간 초과 자동 행동
- 테스트 24개: 포커·섯다 계획서 계산 예시, 행동별 상태 전이, 사이드 팟 예시, 무작위 베팅 1,500판
  (칩 총량 보존·라운드 종료·라운드 끝 금액 일치·팟 합계=판 전체)
- packages/engine/cards: 트럼프 52+조커, 화투 48(+보너스)·섯다 20장 정의와 테스트
- 웹: 직접 그린 SVG 트럼프·화투 카드, 칩 표시("1,250 칩"), 놀이용 칩 안내문
- apps/web/src/no-money-wording.test.ts: 베팅 게임 화면에 통화 기호·"원"·판돈·충전·환전 등 금지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 05:45:13 +09:00

377 lines
15 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import {
applyBet,
awardPots,
bettingClosed,
buildPots,
chipsInPlay,
formatChips,
handDecided,
legalBets,
newBetting,
postAnte,
postBlind,
potTotal,
returnUncalled,
roundComplete,
setFirstToAct,
splitAmount,
startRound,
timeoutBet,
validateBet,
type BetAction,
type BettingState,
} from './betting';
import { SeededRng } from './rng';
const ids = (n: number, stack = 1000) => Array.from({ length: n }, (_, i) => ({ id: 'ABCDEFGHIJ'[i]!, stack }));
const kinds = (s: BettingState, i: number) => legalBets(s, i).map((l) => l.kind);
function act(s: BettingState, i: number, a: BetAction): BettingState {
return applyBet(s, i, a).state;
}
const idx = (s: BettingState, id: string) => s.players.findIndex((p) => p.id === id);
describe('korean betting — documented examples', () => {
test('poker.md §5.2: 4 players, ante 10, ping → half → double → die → call → call = 280', () => {
let s = newBetting(ids(4), { style: 'korean', baseUnit: 10 });
s = postAnte(s, 10);
s = startRound(s, 0);
expect(potTotal(s)).toBe(40);
s = act(s, 0, { kind: 'ping' });
expect([potTotal(s), s.currentBet]).toEqual([50, 10]);
expect(legalBets(s, 1).find((l) => l.kind === 'half')!.amount).toBe(40);
s = act(s, 1, { kind: 'half' });
expect([potTotal(s), s.currentBet]).toEqual([90, 40]);
s = act(s, 2, { kind: 'double' });
expect([potTotal(s), s.currentBet]).toEqual([170, 80]);
s = act(s, 3, { kind: 'die' });
expect(s.turn).toBe(0);
expect(kinds(s, 0)).toEqual(['call', 'die']); // already pinged → no re-raise
s = act(s, 0, { kind: 'call' });
expect(potTotal(s)).toBe(240);
expect(kinds(s, 1)).toEqual(['call', 'die']);
s = act(s, 1, { kind: 'call' });
expect(potTotal(s)).toBe(280);
expect(s.turn).toBeNull();
expect(roundComplete(s)).toBe(true);
expect(chipsInPlay(s)).toBe(4000);
});
test('seotda.md §5.4: 3 players, 학교 10, ping → half 35 → double 70 → call → call = 240', () => {
let s = newBetting(ids(3), { style: 'korean', baseUnit: 10 });
s = startRound(postAnte(s, 10), 0);
s = act(s, 0, { kind: 'ping' });
expect(legalBets(s, 1).find((l) => l.kind === 'half')!.amount).toBe(35);
s = act(s, 1, { kind: 'half' });
s = act(s, 2, { kind: 'double' });
expect(s.currentBet).toBe(70);
s = act(s, 0, { kind: 'call' });
s = act(s, 1, { kind: 'call' });
expect(potTotal(s)).toBe(240);
expect(s.turn).toBeNull();
});
});
describe('korean betting — state transitions', () => {
const fresh = (n = 3) => startRound(postAnte(newBetting(ids(n), { style: 'korean', baseUnit: 10 }), 10), 0);
test('unopened round offers check/ping/quarter/half/die; full only when allowed', () => {
const s = fresh();
expect(kinds(s, 0)).toEqual(['check', 'ping', 'quarter', 'half', 'die']);
const full = startRound(postAnte(newBetting(ids(3), { style: 'korean', baseUnit: 10, koreanMax: 'full' }), 10), 0);
expect(kinds(full, 0)).toEqual(['check', 'ping', 'quarter', 'half', 'full', 'die']);
// quarter of 30 = 7 → bumped to the base unit 10
expect(legalBets(s, 0).find((l) => l.kind === 'quarter')!.amount).toBe(10);
expect(legalBets(s, 0).find((l) => l.kind === 'half')!.amount).toBe(15);
});
test('everyone checks → round complete, nothing added', () => {
let s = fresh();
s = act(s, 0, { kind: 'check' });
expect(kinds(s, 1)).toContain('ping');
s = act(s, 1, { kind: 'check' });
s = act(s, 2, { kind: 'check' });
expect(s.turn).toBeNull();
expect(potTotal(s)).toBe(30);
});
test('check then someone bets: the checker may only call or die (no check-raise)', () => {
let s = fresh();
s = act(s, 0, { kind: 'check' });
s = act(s, 1, { kind: 'ping' });
s = act(s, 2, { kind: 'call' });
expect(s.turn).toBe(0);
expect(kinds(s, 0)).toEqual(['call', 'die']);
s = act(s, 0, { kind: 'call' });
expect(s.turn).toBeNull();
});
test('caller cannot raise later in the same round (no call-raise)', () => {
let s = fresh();
s = act(s, 0, { kind: 'ping' });
s = act(s, 1, { kind: 'call' });
s = act(s, 2, { kind: 'half' });
expect(kinds(s, 1)).toEqual([]); // not their turn yet: A acts first
expect(s.turn).toBe(0);
expect(kinds(s, 0)).toEqual(['call', 'die']); // pinged already
s = act(s, 0, { kind: 'call' });
expect(kinds(s, 1)).toEqual(['call', 'die']); // called already → no raise
s = act(s, 1, { kind: 'call' });
expect(s.turn).toBeNull();
});
test('a new round resets raise rights', () => {
let s = fresh();
s = act(s, 0, { kind: 'ping' });
s = act(s, 1, { kind: 'call' });
s = act(s, 2, { kind: 'call' });
s = startRound(s, 0);
expect(kinds(s, 0)).toContain('ping');
expect(s.players.every((p) => p.round === 0 && !p.acted && !p.raised)).toBe(true);
});
test('die until one player remains → hand decided, round over', () => {
let s = fresh();
s = act(s, 0, { kind: 'ping' });
s = act(s, 1, { kind: 'die' });
s = act(s, 2, { kind: 'die' });
expect(handDecided(s)).toBe(true);
expect(s.turn).toBeNull();
const back = returnUncalled(s);
expect(back.refunded).toEqual({ id: 'A', amount: 10 }); // the ping nobody called comes back
expect(potTotal(back.state)).toBe(30);
});
test('raise that exceeds the stack becomes an all-in; short all-in call creates a side pot', () => {
let s = newBetting([{ id: 'A', stack: 1000 }, { id: 'B', stack: 60 }, { id: 'C', stack: 1000 }], { style: 'korean', baseUnit: 10 });
s = startRound(postAnte(s, 10), 0);
s = act(s, 0, { kind: 'half' }); // 15
const bHalf = legalBets(s, 1).find((l) => l.kind === 'half')!;
expect(bHalf.allIn).toBe(false);
s = act(s, 1, { kind: 'double' }); // 30 of 50 left
s = act(s, 2, { kind: 'half' });
expect(s.currentBet).toBeGreaterThan(50);
s = act(s, 0, { kind: 'call' });
// B has 20 left and owes more → call is a partial all-in
const call = legalBets(s, 1).find((l) => l.kind === 'call')!;
expect(call).toMatchObject({ amount: 20, allIn: true });
s = act(s, 1, { kind: 'call' });
expect(s.players[1]!.status).toBe('allIn');
expect(s.turn).toBeNull();
const pots = buildPots(s.players);
expect(pots[0]).toEqual({ amount: 180, eligible: ['A', 'B', 'C'] }); // 60 each
expect(pots.reduce((a, p) => a + p.amount, 0)).toBe(potTotal(s));
expect(pots[1]!.eligible).toEqual(['A', 'C']);
});
test('all-in players are skipped; betting closes when ≤1 player can still act', () => {
let s = newBetting([{ id: 'A', stack: 20 }, { id: 'B', stack: 500 }], { style: 'korean', baseUnit: 10 });
s = startRound(postAnte(s, 10), 0);
s = act(s, 0, { kind: 'ping' }); // A all-in with the ping
expect(s.players[0]!.status).toBe('allIn');
s = act(s, 1, { kind: 'call' });
expect(s.turn).toBeNull();
expect(bettingClosed(s)).toBe(true);
s = startRound(s, 0);
expect(s.turn).toBeNull(); // next round has no decisions
});
test('timeouts: check when possible, otherwise die', () => {
let s = fresh();
expect(timeoutBet(s, 0)).toEqual({ kind: 'check' });
s = act(s, 0, { kind: 'ping' });
expect(timeoutBet(s, 1)).toEqual({ kind: 'die' });
});
test('validation messages', () => {
const s = fresh();
expect(validateBet(s, 1, { kind: 'check' })).toBe('지금은 내 차례가 아니에요.');
expect(validateBet(s, 0, { kind: 'call' })).toBe('지금은 콜을(를) 할 수 없어요.');
expect(validateBet(s, 0, { kind: 'raise', to: 50 })).toBe('지금은 올릴 수 없어요.');
expect(() => applyBet(s, 0, { kind: 'double' })).toThrow();
});
});
describe('no-limit / pot-limit', () => {
/** Heads-up or ring hold'em preflop: SB/BB posted, first actor given. */
function preflop(n: number, style: 'noLimit' | 'potLimit' = 'noLimit', stacks?: number[]) {
let s = newBetting(
ids(n).map((p, i) => ({ ...p, stack: stacks?.[i] ?? p.stack })),
{ style, baseUnit: 10 },
);
s = startRound(s, 0);
const sb = n === 2 ? 0 : 1;
const bb = n === 2 ? 1 : 2;
s = postBlind(s, sb, 5);
s = postBlind(s, bb, 10);
s = setFirstToAct(s, n === 2 ? 0 : 3 % n);
return s;
}
test('min raise = current bet + last raise; raise 30 makes next min 50', () => {
let s = preflop(4);
expect(s.turn).toBe(3);
const r = legalBets(s, 3).find((l) => l.kind === 'raise')!;
expect([r.minTo, r.maxTo]).toEqual([20, 1000]);
s = act(s, 3, { kind: 'raise', to: 30 });
expect(legalBets(s, 0).find((l) => l.kind === 'raise')!.minTo).toBe(50);
expect(validateBet(s, 0, { kind: 'raise', to: 40 })).toBe('50~1000 칩 사이로 올려 주세요.');
});
test('big blind option: limpers → BB may check or raise', () => {
let s = preflop(3);
s = act(s, 0, { kind: 'call' }); // dealer/UTG at seat 0 in 3-handed
s = act(s, 1, { kind: 'call' }); // SB completes
expect(s.turn).toBe(2);
expect(kinds(s, 2)).toEqual(['fold', 'check', 'raise', 'allIn']);
s = act(s, 2, { kind: 'check' });
expect(s.turn).toBeNull();
expect(potTotal(s)).toBe(30);
});
test('heads-up: dealer (SB) acts first preflop', () => {
const s = preflop(2);
expect(s.turn).toBe(0);
expect(kinds(s, 0)).toContain('call');
});
test('incomplete all-in raise does not reopen betting for players who already acted', () => {
// A raises to 100 (raise size 90), B goes all-in for 150 (only +50, incomplete), A may only call/fold.
let s = preflop(3, 'noLimit', [1000, 150, 1000]);
s = act(s, 0, { kind: 'raise', to: 100 });
s = act(s, 1, { kind: 'allIn' });
expect(s.currentBet).toBe(150);
expect(s.lastRaise).toBe(90);
// C has not acted yet → may still raise (min 150 + 90)
expect(legalBets(s, 2).find((l) => l.kind === 'raise')!.minTo).toBe(240);
s = act(s, 2, { kind: 'call' });
expect(kinds(s, 0)).toEqual(['fold', 'call']);
s = act(s, 0, { kind: 'call' });
expect(s.turn).toBeNull();
});
test('full raise re-opens betting for everyone', () => {
let s = preflop(3);
s = act(s, 0, { kind: 'raise', to: 40 });
s = act(s, 1, { kind: 'call' });
s = act(s, 2, { kind: 'raise', to: 100 });
expect(kinds(s, 0)).toContain('raise');
});
test('pot-limit maximum (poker.md §5.3): pot 100, opponent bets 20 → max raise to 160', () => {
let s = newBetting(ids(2), { style: 'potLimit', baseUnit: 10 });
s = postAnte(s, 50); // pot 100 from earlier rounds
s = startRound(s, 0);
s = act(s, 0, { kind: 'raise', to: 20 }); // pot 120
const r = legalBets(s, 1).find((l) => l.kind === 'raise')!;
expect(potTotal(s)).toBe(120);
expect(r.maxTo).toBe(160);
expect(validateBet(s, 1, { kind: 'raise', to: 161 })).not.toBeNull();
});
test('uncalled bet is returned when everyone folds', () => {
let s = preflop(3);
s = act(s, 0, { kind: 'raise', to: 300 });
s = act(s, 1, { kind: 'fold' });
s = act(s, 2, { kind: 'fold' });
expect(handDecided(s)).toBe(true);
const r = returnUncalled(s);
expect(r.refunded).toEqual({ id: 'A', amount: 290 });
expect(potTotal(r.state)).toBe(25);
expect(chipsInPlay(r.state)).toBe(3000);
});
});
describe('pots and awards', () => {
test('poker.md §5.5 example: A 100 / B 300 all-in / C 300 → main 300, side 400', () => {
const pots = buildPots([
{ id: 'A', total: 100, status: 'allIn' },
{ id: 'B', total: 300, status: 'allIn' },
{ id: 'C', total: 300, status: 'active' },
]);
expect(pots).toEqual([
{ amount: 300, eligible: ['A', 'B', 'C'] },
{ amount: 400, eligible: ['B', 'C'] },
]);
});
test('folded chips stay in the pots they reached', () => {
const pots = buildPots([
{ id: 'A', total: 50, status: 'allIn' },
{ id: 'B', total: 80, status: 'folded' },
{ id: 'C', total: 200, status: 'active' },
{ id: 'D', total: 200, status: 'active' },
]);
expect(pots).toEqual([
{ amount: 200, eligible: ['A', 'C', 'D'] },
{ amount: 330, eligible: ['C', 'D'] },
]);
});
test('award: side pot to the best eligible, ties split with odd chip by seat order', () => {
const rank: Record<string, number> = { A: 9, B: 5, C: 5 };
const pots = [
{ amount: 301, eligible: ['A', 'B', 'C'] },
{ amount: 401, eligible: ['B', 'C'] },
];
const won = awardPots(pots, (x, y) => rank[x]! - rank[y]!, ['C', 'A', 'B']);
expect(won).toEqual({ A: 301, C: 201, B: 200 });
expect(splitAmount(10, ['X', 'Y', 'Z'])).toEqual({ X: 4, Y: 3, Z: 3 });
});
test('chips are shown as play chips, never money', () => {
expect(formatChips(12500)).toBe('12,500 칩');
expect(formatChips(5)).not.toMatch(/원|₩|\$/);
});
});
describe('property: random betting sequences', () => {
test('chips conserved, rounds always terminate, pots partition the total, complete rounds are matched', () => {
for (let seed = 1; seed <= 1500; seed++) {
const rng = SeededRng.fromSeed([seed, seed * 7, seed * 13, 99]);
const style = (['korean', 'noLimit', 'potLimit'] as const)[seed % 3]!;
const n = 2 + rng.int(7);
const players = Array.from({ length: n }, (_, i) => ({ id: `P${i}`, stack: 1 + rng.int(400) }));
const total = players.reduce((a, p) => a + p.stack, 0);
let s = newBetting(players, { style, baseUnit: 10, koreanMax: rng.int(2) ? 'full' : 'half' });
if (style === 'korean') s = postAnte(s, 5);
for (let round = 0; round < 4 && !bettingClosed(s); round++) {
s = startRound(s, rng.int(n));
if (style !== 'korean' && round === 0) {
s = postBlind(s, 0, 5);
s = postBlind(s, 1 % n, 10);
s = setFirstToAct(s, 2 % n);
}
let steps = 0;
while (s.turn !== null) {
const legal = legalBets(s, s.turn);
expect(legal.length).toBeGreaterThan(0);
const pick = legal[rng.int(legal.length)]!;
const a: BetAction =
pick.kind === 'raise' ? { kind: 'raise', to: pick.minTo! + rng.int(pick.maxTo! - pick.minTo! + 1) } : ({ kind: pick.kind } as BetAction);
expect(validateBet(s, s.turn, a)).toBeNull();
s = applyBet(s, s.turn, a).state;
expect(chipsInPlay(s)).toBe(total);
expect(s.players.every((p) => p.stack >= 0 && p.round >= 0)).toBe(true);
if (++steps > 4 * n + 4) throw new Error(`round did not terminate (seed ${seed})`);
}
expect(roundComplete(s)).toBe(true);
for (const p of s.players) if (p.status === 'active' && !handDecided(s)) expect(p.round).toBe(s.currentBet);
s = returnUncalled(s).state;
expect(chipsInPlay(s)).toBe(total);
}
const pots = buildPots(s.players);
expect(pots.reduce((a, p) => a + p.amount, 0)).toBe(potTotal(s));
for (const pot of pots) {
expect(pot.eligible.length).toBeGreaterThan(0);
for (const id of pot.eligible) expect(['active', 'allIn']).toContain(s.players[idx(s, id)]!.status);
}
// Award everything with random hand strengths: chips stay conserved.
const strength = Object.fromEntries(s.players.map((p) => [p.id, rng.int(5)]));
const won = awardPots(pots, (a, b) => strength[a]! - strength[b]!, s.players.map((p) => p.id));
const after = s.players.reduce((a, p) => a + p.stack, 0) + Object.values(won).reduce((a, b) => a + b, 0);
expect(after).toBe(total);
}
});
});