1037 lines
53 KiB
TypeScript
1037 lines
53 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
||
import { HWATU, SEOTDA_DECK, SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent } from '@bg/engine';
|
||
import {
|
||
bestChoice,
|
||
chipsTotal,
|
||
evalSeotda,
|
||
resolve,
|
||
scaleMoney,
|
||
seotda,
|
||
type HandEval,
|
||
type HandRules,
|
||
type SeotdaAction,
|
||
type SeotdaOptions,
|
||
type SeotdaState,
|
||
type SpecialKind,
|
||
} from './index';
|
||
|
||
// ---------------------------------------------------------------- helpers
|
||
|
||
/** Special card of a month (1·3·8 광, others 열끗) and the plain card. */
|
||
const S = (m: number) => (m - 1) * 4;
|
||
const P = (m: number) => (m - 1) * 4 + 1;
|
||
const DEFAULT_RULES: HandRules = { gwangTtaeng: 'all', ttaengjabi: 'strict', amhaeng: true, gusa: true, mungGusa: 'upTo8' };
|
||
const ev = (a: number, b: number, r: Partial<HandRules> = {}) => evalSeotda(a, b, { ...DEFAULT_RULES, ...r });
|
||
|
||
let clock = 1000;
|
||
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
|
||
|
||
/**
|
||
* Most flow tests were written for 1장씩 두 번 + 쿼터 + strict 땡잡이 + 멍구사 8땡까지 (the defaults before the 한게임
|
||
* rebuild); they keep those rules explicitly. The 한게임 defaults have their own tests below.
|
||
*/
|
||
const CLASSIC: Partial<SeotdaOptions> = { dealMode: 'twoRounds', quarter: true, ttaengjabi: 'strict', mungGusa: 'upTo8' };
|
||
|
||
/** Fresh game whose first dealer is `dealer` (seat order = players). */
|
||
/**
|
||
* The flow tests count in the old small units (시작 1,000 / 기본금 10, i.e. 원 ÷ 1000): `startingChips`/`baseUnit` given
|
||
* in those units are scaled up for the schema, and the new game is scaled back down (`scaleMoney`, the inverse of the
|
||
* v1 → v2 migration). The engine itself is unit-free.
|
||
*/
|
||
/** Options in the old small units (startingChips 500…5000, baseUnit 2…50). */
|
||
type OldOpts = Partial<Omit<SeotdaOptions, 'startingChips' | 'baseUnit'>> & { startingChips?: number; baseUnit?: number };
|
||
|
||
function make(opts: OldOpts = {}, players = ['A', 'B', 'C'], dealer = 'A'): SeotdaState {
|
||
const up = { ...opts };
|
||
if (up.startingChips !== undefined) up.startingChips *= 1000;
|
||
if (up.baseUnit !== undefined) up.baseUnit *= 1000;
|
||
const options = seotda.optionsSchema.parse({ ...CLASSIC, ...up });
|
||
for (let seed = 1; seed < 500; seed++) {
|
||
const s = seotda.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||
if (s.hand!.dealer === dealer) return scaleMoney(s, 1 / 1000);
|
||
}
|
||
throw new Error('no seed with that dealer');
|
||
}
|
||
|
||
/** Replaces the dealt cards; `next` are the next cards off the deck (in dealing order). */
|
||
function rig(s: SeotdaState, cards: Record<string, number[]>, next: number[] = []): SeotdaState {
|
||
const h = s.hand!;
|
||
for (const [id, cs] of Object.entries(cards)) h.cards[id] = [...cs];
|
||
const used = new Set([...Object.values(h.cards).flat(), ...next]);
|
||
h.deck = [...next, ...SEOTDA_DECK.filter((c) => !used.has(c))];
|
||
return s;
|
||
}
|
||
|
||
function act(s: SeotdaState, p: string, a: SeotdaAction, now = (clock += 1000)): SeotdaState {
|
||
const v = seotda.validate(s, p, a);
|
||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||
return seotda.apply(s, p, a, { rng: rng(), now }).state;
|
||
}
|
||
function actE(s: SeotdaState, p: string, a: SeotdaAction): { state: SeotdaState; events: GameEvent[] } {
|
||
const v = seotda.validate(s, p, a);
|
||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||
return seotda.apply(s, p, a, { rng: rng(), now: (clock += 1000) });
|
||
}
|
||
const reject = (s: SeotdaState, p: string, a: SeotdaAction) => {
|
||
const v = seotda.validate(s, p, a);
|
||
return v.ok ? null : v.reason;
|
||
};
|
||
/** Everyone dies until the hand ends; the last player keeps the cards hidden. */
|
||
function foldOut(s: SeotdaState): SeotdaState {
|
||
while (s.hand!.phase !== 'handEnd') s = act(s, seotda.activePlayers(s)[0]!, s.hand!.phase === 'reveal' ? { type: 'reveal', show: false } : { type: 'die' });
|
||
return s;
|
||
}
|
||
function readyAll(s: SeotdaState): SeotdaState {
|
||
for (const p of seotda.activePlayers(s)) s = act(s, p, { type: 'ready' });
|
||
return s;
|
||
}
|
||
const stack = (s: SeotdaState, id: string) => s.seats.find((x) => x.id === id)!.stack;
|
||
const total = (s: SeotdaState) => s.seats.length * s.options.startingChips + s.seats.reduce((a, x) => a + x.rebuys, 0) * s.options.startingChips;
|
||
|
||
// ---------------------------------------------------------------- 족보
|
||
|
||
/** Independent reference straight from the §6.1/§6.2 tables, using the shared HWATU kinds. */
|
||
function reference(a: number, b: number, r: HandRules): { value: number; special: SpecialKind | null } {
|
||
const ca = HWATU[a]!;
|
||
const cb = HWATU[b]!;
|
||
const ms = [ca.month, cb.month].sort((x, y) => x - y) as [number, number];
|
||
const both = (x: number, y: number) => ms[0] === x && ms[1] === y;
|
||
const gw = ca.kind === 'gwang' && cb.kind === 'gwang';
|
||
const yeol = (m: number) => [ca, cb].some((c) => c.month === m && c.kind === 'yeol');
|
||
const gwangOf = (m: number) => [ca, cb].some((c) => c.month === m && c.kind === 'gwang');
|
||
let value: number;
|
||
if (gw && both(3, 8)) value = 1000;
|
||
else if (gw && both(1, 8) && r.gwangTtaeng === 'all') value = 990;
|
||
else if (gw && both(1, 3) && r.gwangTtaeng === 'all') value = 980;
|
||
else if (ms[0] === ms[1]) value = 900 + ms[0];
|
||
else if (both(1, 2)) value = 806;
|
||
else if (both(1, 4)) value = 805;
|
||
else if (both(1, 9)) value = 804;
|
||
else if (both(1, 10)) value = 803;
|
||
else if (both(4, 10)) value = 802;
|
||
else if (both(4, 6)) value = 801;
|
||
else value = (ms[0] + ms[1]) % 10;
|
||
let special: SpecialKind | null = null;
|
||
if (both(3, 7) && (r.ttaengjabi === 'loose' || (r.ttaengjabi === 'strict' && gwangOf(3) && yeol(7)))) special = 'ttaengjabi';
|
||
else if (both(4, 7) && r.amhaeng && yeol(4) && yeol(7)) special = 'amhaeng';
|
||
else if (both(4, 9) && r.gusa) special = r.mungGusa !== 'off' && yeol(4) && yeol(9) ? 'mungGusa' : 'gusa';
|
||
return { value, special };
|
||
}
|
||
|
||
describe('족보 (§6.1, §6.2)', () => {
|
||
const pairs: [number, number][] = [];
|
||
for (let i = 0; i < SEOTDA_DECK.length; i++) for (let j = i + 1; j < SEOTDA_DECK.length; j++) pairs.push([SEOTDA_DECK[i]!, SEOTDA_DECK[j]!]);
|
||
|
||
test('190 two-card combinations', () => expect(pairs).toHaveLength(190));
|
||
|
||
const variants: [string, HandRules][] = [
|
||
['기본', DEFAULT_RULES],
|
||
['38광땡만·땡잡이 느슨', { ...DEFAULT_RULES, gwangTtaeng: 'only38', ttaengjabi: 'loose' }],
|
||
['특수패 모두 끔', { gwangTtaeng: 'all', ttaengjabi: 'off', amhaeng: false, gusa: false, mungGusa: 'upTo8' }],
|
||
['멍구사 끔', { ...DEFAULT_RULES, mungGusa: 'off' }],
|
||
['멍구사 장땡까지', { ...DEFAULT_RULES, mungGusa: 'upToJang' }],
|
||
];
|
||
test.each(variants)('every combination matches the table (%s)', (_n, rules) => {
|
||
for (const [a, b] of pairs) {
|
||
const e = evalSeotda(a, b, rules);
|
||
expect({ value: e.value, special: e.special }).toEqual(reference(a, b, rules));
|
||
expect(evalSeotda(b, a, rules)).toEqual(e);
|
||
}
|
||
});
|
||
|
||
test('counts per name with default options', () => {
|
||
const count: Record<string, number> = {};
|
||
for (const [a, b] of pairs) {
|
||
const n = ev(a, b).name;
|
||
count[n] = (count[n] ?? 0) + 1;
|
||
}
|
||
expect([count['38광땡'], count['18광땡'], count['13광땡'], count['장땡'], count['삥땡'], count['5땡']]).toEqual([1, 1, 1, 1, 1, 1]);
|
||
expect([count['알리'], count['독사'], count['구삥'], count['장삥'], count['장사'], count['세륙']]).toEqual([4, 4, 4, 4, 4, 4]);
|
||
expect([count['땡잡이'], count['암행어사'], count['구사'], count['멍텅구리구사']]).toEqual([1, 1, 3, 1]);
|
||
});
|
||
|
||
test('1월 광 + 3월 광: 13광땡 or 4끗; 1월 띠 + 8월 광 = 갑오; 3월 띠 + 8월 광 = 1끗', () => {
|
||
expect(ev(S(1), S(3)).name).toBe('13광땡');
|
||
expect(ev(S(1), S(3), { gwangTtaeng: 'only38' })).toMatchObject({ name: '4끗', value: 4 });
|
||
expect(ev(S(1), S(8), { gwangTtaeng: 'only38' })).toMatchObject({ name: '갑오', value: 9 });
|
||
expect(ev(P(1), S(8))).toMatchObject({ name: '갑오', value: 9 });
|
||
expect(ev(P(3), S(8))).toMatchObject({ name: '1끗', value: 1 });
|
||
expect(ev(P(2), S(8))).toMatchObject({ name: '망통', value: 0 });
|
||
expect(ev(S(10), P(10))).toMatchObject({ name: '장땡', value: 910 });
|
||
});
|
||
|
||
test('special hands keep their normal value', () => {
|
||
expect(ev(S(3), S(7))).toMatchObject({ special: 'ttaengjabi', value: 0, baseName: '망통' });
|
||
expect(ev(S(4), S(7))).toMatchObject({ special: 'amhaeng', value: 1 });
|
||
expect(ev(P(4), S(9))).toMatchObject({ special: 'gusa', value: 3 });
|
||
expect(ev(S(4), S(9))).toMatchObject({ special: 'mungGusa', value: 3 });
|
||
expect(ev(S(4), S(9), { mungGusa: 'off' }).special).toBe('gusa');
|
||
expect(ev(S(4), S(9), { gusa: false })).toMatchObject({ special: null, name: '3끗' });
|
||
});
|
||
});
|
||
|
||
describe('쇼다운 판정 (§6.3, §6.4)', () => {
|
||
const run = (hands: [string, HandEval][], tie: 'rematch' | 'split' = 'rematch', r: Partial<HandRules> = {}) =>
|
||
resolve(hands.map(([id, hand]) => ({ id, hand })), tie, { ...DEFAULT_RULES, ...r });
|
||
const gusa = ev(P(4), S(9));
|
||
const mung = ev(S(4), S(9));
|
||
const tj = ev(S(3), S(7));
|
||
const amh = ev(S(4), S(7));
|
||
|
||
test('1. 38광땡 vs 암행어사 → 38광땡', () => expect(run([['A', ev(S(3), S(8))], ['B', amh]])).toEqual({ type: 'win', winners: ['A'], reason: 'normal' }));
|
||
test('2. 13광땡, 암행어사, 장땡 → 암행어사', () =>
|
||
expect(run([['A', ev(S(1), S(3))], ['B', amh], ['C', ev(S(10), P(10))]])).toEqual({ type: 'win', winners: ['B'], reason: 'amhaeng' }));
|
||
test('3. 9땡, 땡잡이, 알리 → 땡잡이', () =>
|
||
expect(run([['A', ev(S(9), P(9))], ['B', tj], ['C', ev(S(1), P(2))]])).toEqual({ type: 'win', winners: ['B'], reason: 'ttaengjabi' }));
|
||
test('4. 장땡 vs 땡잡이 → 장땡', () => expect(run([['A', ev(S(10), P(10))], ['B', tj]])).toMatchObject({ winners: ['A'] }));
|
||
test('5. 땡잡이 vs 알리 → 알리', () => expect(run([['A', tj], ['B', ev(S(1), P(2))]])).toMatchObject({ winners: ['B'] }));
|
||
test('6. 구사 vs 알리 → 구사 재경기', () =>
|
||
expect(run([['A', gusa], ['B', ev(S(1), P(2))]])).toEqual({ type: 'rematch', reason: 'gusa', participants: ['A', 'B'] }));
|
||
test('7. 구사 vs 삥땡 → 삥땡', () => expect(run([['A', gusa], ['B', ev(S(1), P(1))]])).toMatchObject({ type: 'win', winners: ['B'] }));
|
||
test('8. 구사, 2끗, 망통 → 구사 승(재경기 없음)', () =>
|
||
expect(run([['A', gusa], ['B', ev(P(5), P(7))], ['C', ev(P(2), P(8))]])).toMatchObject({ type: 'win', winners: ['A'] }));
|
||
test('9. 멍텅구리구사 vs 8땡 → 재경기(upTo8); 9땡 → 승; upToJang이면 장땡까지 재경기; 광땡은 이김', () => {
|
||
expect(run([['A', mung], ['B', ev(S(8), P(8))]])).toMatchObject({ type: 'rematch', reason: 'mungGusa' });
|
||
expect(run([['A', mung], ['B', ev(S(9), P(9))]])).toMatchObject({ type: 'win', winners: ['B'] });
|
||
expect(run([['A', mung], ['B', ev(S(9), P(9))]], 'rematch', { mungGusa: 'upTo9' })).toMatchObject({ type: 'rematch' });
|
||
expect(run([['A', mung], ['B', ev(S(10), P(10))]], 'rematch', { mungGusa: 'upToJang' })).toMatchObject({ type: 'rematch' });
|
||
expect(run([['A', mung], ['B', ev(S(1), S(3))]], 'rematch', { mungGusa: 'upToJang' })).toMatchObject({ type: 'win', winners: ['B'] });
|
||
});
|
||
test('10. 5끗 동점 → 재경기 또는 나눔', () => {
|
||
const a = ev(P(2), P(3));
|
||
const b = ev(P(6), P(9));
|
||
expect(run([['A', a], ['B', b]])).toEqual({ type: 'rematch', reason: 'tie', participants: ['A', 'B'] });
|
||
expect(run([['A', a], ['B', b]], 'split')).toEqual({ type: 'split', winners: ['A', 'B'] });
|
||
});
|
||
test('11. 구사, 5땡, 땡잡이 → 땡잡이; 멍구사였다면 재경기', () => {
|
||
expect(run([['A', gusa], ['B', ev(S(5), P(5))], ['C', tj]])).toEqual({ type: 'win', winners: ['C'], reason: 'ttaengjabi' });
|
||
expect(run([['A', mung], ['B', ev(S(5), P(5))], ['C', ev(P(3), P(7))]], 'rematch', { ttaengjabi: 'loose' })).toMatchObject({ type: 'rematch', reason: 'mungGusa' });
|
||
});
|
||
test('12. 3장 섯다: 1광·8광·4열끗 → 18광땡 조합', () => {
|
||
expect(bestChoice([S(1), S(8), S(4)], DEFAULT_RULES)).toEqual([S(1), S(8)]);
|
||
});
|
||
|
||
test('strict 땡잡이: 3월 띠 + 7월 열끗은 망통이라 9땡을 못 잡고, loose면 잡음', () => {
|
||
const weak = ev(P(3), S(7));
|
||
expect(weak).toMatchObject({ special: null, name: '망통' });
|
||
expect(run([['A', weak], ['B', ev(S(9), P(9))]])).toMatchObject({ winners: ['B'] });
|
||
const loose = ev(P(3), S(7), { ttaengjabi: 'loose' });
|
||
expect(run([['A', loose], ['B', ev(S(9), P(9))]], 'rematch', { ttaengjabi: 'loose' })).toMatchObject({ winners: ['A'], reason: 'ttaengjabi' });
|
||
});
|
||
|
||
test('loose 땡잡이 두 명 + 5땡 → 땡잡이끼리 동점 처리', () => {
|
||
const r: Partial<HandRules> = { ttaengjabi: 'loose' };
|
||
const hands: [string, HandEval][] = [
|
||
['A', ev(S(3), P(7), r)],
|
||
['B', ev(S(5), P(5), r)],
|
||
['C', ev(P(3), S(7), r)],
|
||
];
|
||
expect(run(hands, 'rematch', r)).toEqual({ type: 'rematch', reason: 'tie', participants: ['A', 'C'] });
|
||
expect(run(hands, 'split', r)).toEqual({ type: 'split', winners: ['A', 'C'] });
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- betting & flow
|
||
|
||
describe('betting flow', () => {
|
||
test('§5.4 example: 학교 30 → 삥 → 하프 35 → 따당 70 → 콜 → 콜 = 240', () => {
|
||
let s = make();
|
||
const v0 = seotda.view(s, 'A');
|
||
expect(v0.pot).toBe(30);
|
||
expect(v0.legal.map((l) => l.type)).toEqual(['check', 'ping', 'quarter', 'half', 'die']);
|
||
s = act(s, 'A', { type: 'ping' });
|
||
expect(seotda.view(s, 'B').legal.find((l) => l.type === 'half')!.amount).toBe(35);
|
||
s = act(s, 'B', { type: 'half' });
|
||
expect(seotda.view(s, 'C').legal.find((l) => l.type === 'ddadang')!.amount).toBe(70);
|
||
s = act(s, 'C', { type: 'ddadang' });
|
||
expect(seotda.view(s, 'A').legal.map((l) => l.type)).toEqual(['call', 'die']);
|
||
s = act(s, 'A', { type: 'call' });
|
||
expect(seotda.view(s, null).pot).toBe(205);
|
||
s = act(s, 'B', { type: 'call' });
|
||
expect(seotda.view(s, null).pot).toBe(240);
|
||
// twoRounds: second card dealt, second betting round starts with the dealer.
|
||
expect(s.hand!.street).toBe(1);
|
||
expect(s.hand!.cards.A).toHaveLength(2);
|
||
expect(seotda.view(s, null).toAct).toBe('A');
|
||
expect(chipsTotal(s)).toBe(3000);
|
||
});
|
||
|
||
test('check or call, then no raise in the same round; half-only room rejects 풀', () => {
|
||
let s = make();
|
||
expect(reject(s, 'A', { type: 'full' })).toBe('이 방은 하프까지만 올릴 수 있어요.');
|
||
expect(reject(s, 'B', { type: 'check' })).toBe('지금은 내 차례가 아니에요.');
|
||
s = act(s, 'A', { type: 'check' });
|
||
s = act(s, 'B', { type: 'ping' });
|
||
expect(reject(s, 'C', { type: 'check' })).toBe('누가 이미 걸어서 체크할 수 없어요.');
|
||
expect(reject(s, 'C', { type: 'ping' })).toBe('누가 이미 걸어서 삥을 할 수 없어요.');
|
||
s = act(s, 'C', { type: 'call' });
|
||
expect(reject(s, 'A', { type: 'half' })).toBe('이번 라운드에는 더 올릴 수 없어요(콜 또는 다이).');
|
||
expect(reject(s, 'A', { type: 'ddadang' })).toBe('이번 라운드에는 더 올릴 수 없어요(콜 또는 다이).');
|
||
s = act(s, 'A', { type: 'call' });
|
||
expect(s.hand!.street).toBe(1);
|
||
const full = make({ maxRaise: 'full' });
|
||
expect(seotda.view(full, 'A').legal.map((l) => l.type)).toContain('full');
|
||
});
|
||
|
||
test('everyone checks → next street; second round starts after a dead dealer', () => {
|
||
let s = make();
|
||
s = act(s, 'A', { type: 'die' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
s = act(s, 'C', { type: 'check' });
|
||
expect(s.hand!.street).toBe(1);
|
||
expect(seotda.view(s, null).toAct).toBe('B');
|
||
expect(seotda.view(s, null).pot).toBe(30);
|
||
});
|
||
|
||
test('dealMode=oneRound: one betting round then showdown', () => {
|
||
let s = make({ dealMode: 'oneRound' });
|
||
expect(s.hand!.cards.A).toHaveLength(2);
|
||
s = rig(s, { A: [S(10), P(10)], B: [S(1), P(2)], C: [P(3), P(5)] });
|
||
s = act(s, 'A', { type: 'check' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
s = act(s, 'C', { type: 'check' });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(s.hand!.showdown!.pots).toEqual([{ amount: 30, eligible: ['A', 'B', 'C'], type: 'win', winners: ['A'], reason: 'normal' }]);
|
||
expect(stack(s, 'A')).toBe(1020);
|
||
expect(seotda.view(s, 'B').seats.find((x) => x.id === 'A')!.handName).toBe('장땡');
|
||
});
|
||
|
||
test('fold to one: winner keeps the cards hidden and takes the pot (uncalled bet back)', () => {
|
||
let s = make({ dealMode: 'oneRound' });
|
||
s = act(s, 'A', { type: 'half' }); // 15
|
||
s = act(s, 'B', { type: 'die' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
expect(s.hand!.phase).toBe('reveal');
|
||
s = act(s, 'A', { type: 'reveal', show: false });
|
||
expect(s.hand!.foldWin).toEqual({ winner: 'A', amount: 30, shown: false }); // A's uncalled 15 came back first
|
||
expect(stack(s, 'A')).toBe(1020);
|
||
expect(s.hand!.showdown).toBeNull();
|
||
const bView = seotda.view(s, 'B');
|
||
expect(bView.seats.find((x) => x.id === 'A')!.cards).toEqual([{ hidden: true }, { hidden: true }]);
|
||
expect(seotda.view(s, null).seats.every((x) => x.cards.every((c) => 'hidden' in c))).toBe(true);
|
||
s = readyAll(s);
|
||
expect(s.handsPlayed).toBe(1);
|
||
expect(s.hand!.dealer).toBe('A'); // dealerRule=winner
|
||
});
|
||
|
||
test('dealerRule=rotate moves the dealer clockwise', () => {
|
||
let s = make({ dealMode: 'oneRound', dealerRule: 'rotate' });
|
||
s = act(s, 'A', { type: 'die' });
|
||
s = act(s, 'B', { type: 'die' });
|
||
s = act(s, 'C', { type: 'reveal', show: false });
|
||
s = readyAll(s);
|
||
expect(s.hand!.dealer).toBe('B');
|
||
});
|
||
|
||
test('all-in run-out with a side pot at showdown', () => {
|
||
let s = make({ dealMode: 'oneRound' });
|
||
// A has only 20 chips left after the 학교.
|
||
s.seats[0]!.stack = 20;
|
||
s.hand!.betting!.players[0]!.stack = 20;
|
||
s = rig(s, { A: [S(10), P(10)], B: [S(1), P(2)], C: [P(3), P(5)] });
|
||
const before = chipsTotal(s);
|
||
s = act(s, 'A', { type: 'ping' }); // 10
|
||
s = act(s, 'B', { type: 'half' }); // 10 + 25 = 35
|
||
s = act(s, 'C', { type: 'call' }); // 35
|
||
s = act(s, 'A', { type: 'call' }); // only 10 left → all-in
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
const pots = s.hand!.showdown!.pots;
|
||
expect(pots).toEqual([
|
||
{ amount: 30, eligible: ['B', 'C'], type: 'win', winners: ['B'], reason: 'normal' },
|
||
{ amount: 90, eligible: ['A', 'B', 'C'], type: 'win', winners: ['A'], reason: 'normal' },
|
||
]);
|
||
expect(stack(s, 'A')).toBe(90);
|
||
expect(chipsTotal(s)).toBe(before);
|
||
});
|
||
});
|
||
|
||
describe('모두 다이하고 혼자 남으면 카드 공개를 골라요', () => {
|
||
/** A 38광땡 bets 하프, B and C die: A decides. */
|
||
function lone(opts: OldOpts = {}): SeotdaState {
|
||
let s = make({ dealMode: 'oneRound', ...opts });
|
||
s = rig(s, { A: [S(3), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] });
|
||
s = act(s, 'A', { type: 'half' });
|
||
s = act(s, 'B', { type: 'die' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
return s;
|
||
}
|
||
const cardsOf = (s: SeotdaState, viewer: string | null, id = 'A') => seotda.view(s, viewer).seats.find((x) => x.id === id)!.cards;
|
||
|
||
test('only the last player decides; the pot waits until then', () => {
|
||
const s = lone();
|
||
expect(s.hand!.phase).toBe('reveal');
|
||
expect(seotda.activePlayers(s)).toEqual(['A']);
|
||
expect(seotda.legalActions!(s, 'A')).toEqual([{ type: 'reveal', show: true }, { type: 'reveal', show: false }]);
|
||
expect(seotda.legalActions!(s, 'B')).toEqual([]);
|
||
expect(reject(s, 'B', { type: 'reveal', show: true })).toBe('지금은 카드 공개를 고를 때가 아니에요.');
|
||
expect(reject(s, 'A', { type: 'ready' })).toBe('아직 판이 끝나지 않았어요.');
|
||
expect(reject(make(), 'A', { type: 'reveal', show: true })).toBe('지금은 카드 공개를 고를 때가 아니에요.');
|
||
expect(s.hand!.foldWin).toBeNull();
|
||
expect(stack(s, 'A')).toBe(990); // uncalled 하프 back, pot not paid yet
|
||
expect(chipsTotal(s)).toBe(total(s));
|
||
const v = seotda.view(s, 'B');
|
||
expect(v.reveal).toEqual({ by: 'A', mine: false });
|
||
expect(seotda.view(s, 'A').reveal).toEqual({ by: 'A', mine: true });
|
||
expect(v.pot).toBe(30);
|
||
expect(cardsOf(s, 'B')).toEqual([{ hidden: true }, { hidden: true }]);
|
||
});
|
||
|
||
test('show: everyone (spectators too) sees the cards and the 족보, and the record says so', () => {
|
||
const r = actE(lone(), 'A', { type: 'reveal', show: true });
|
||
const s = r.state;
|
||
expect(r.events).toContainEqual({ type: 'foldWin', winner: 'A', amount: 30, shown: true });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(stack(s, 'A')).toBe(1020);
|
||
for (const viewer of ['B', 'C', null]) {
|
||
expect(cardsOf(s, viewer).map((c) => ('id' in c ? c.id : null))).toEqual([S(3), S(8)]);
|
||
expect(seotda.view(s, viewer).seats.find((x) => x.id === 'A')!.handName).toBe('38광땡');
|
||
}
|
||
expect(cardsOf(s, 'C', 'B')).toEqual([{ hidden: true }, { hidden: true }]);
|
||
expect(seotda.view(s, null).foldWin).toEqual({ winner: 'A', amount: 30, shown: true });
|
||
expect(s.history.at(-1)).toMatchObject({ how: 'fold', shown: true, name: '38광땡' });
|
||
expect(seotda.secretsOf!(s, 'A')).not.toContain(`h1r0c${S(3)}`);
|
||
});
|
||
|
||
test('hide: nobody else sees the cards, as before', () => {
|
||
const s = act(lone(), 'A', { type: 'reveal', show: false });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(s.hand!.foldWin).toEqual({ winner: 'A', amount: 30, shown: false });
|
||
for (const viewer of ['B', 'C', null]) {
|
||
expect(cardsOf(s, viewer)).toEqual([{ hidden: true }, { hidden: true }]);
|
||
expect(seotda.view(s, viewer).seats.find((x) => x.id === 'A')!.handName).toBeNull();
|
||
expect(JSON.stringify(seotda.view(s, viewer))).not.toContain(`h1r0c${S(3)}`);
|
||
}
|
||
expect(seotda.secretsOf!(s, 'A')).toContain(`h1r0c${S(3)}`);
|
||
expect(s.history.at(-1)).toMatchObject({ how: 'fold', shown: false, name: null });
|
||
});
|
||
|
||
test('time runs out (재참가·리바이·카드 공개 답 시간) or the player leaves: cards stay hidden', () => {
|
||
let s = lone();
|
||
expect(s.deadlineAt).toBe(clock + 15_000);
|
||
expect(seotda.timeoutPlayers!(s)).toEqual(['A']);
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
expect(s.hand!.foldWin!.shown).toBe(false);
|
||
expect(s.seats[0]!.timeoutsInRow).toBe(0); // not a missed turn
|
||
expect(cardsOf(s, 'B')).toEqual([{ hidden: true }, { hidden: true }]);
|
||
const t = act(lone(), 'A', seotda.onLeave!(lone(), 'A')!);
|
||
expect(t.hand!.phase).toBe('handEnd');
|
||
expect(t.hand!.foldWin!.shown).toBe(false);
|
||
});
|
||
|
||
test('3장 섯다 after choosing: the chosen pair is shown, the thrown card stays secret', () => {
|
||
let s = make({ cardMode: 'three', threeOpen: false, threePick: 'beforeBet' });
|
||
s = rig(s, { A: [S(1), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] }, [P(3), P(9), P(10)]);
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'timeout' }); // best pairs
|
||
expect(s.hand!.chosen.A).toEqual([S(1), S(8)]);
|
||
s = act(s, 'A', { type: 'half' });
|
||
s = act(s, 'B', { type: 'die' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
s = act(s, 'A', { type: 'reveal', show: true });
|
||
expect(cardsOf(s, 'B').map((c) => ('id' in c ? c.id : null))).toEqual([S(1), S(8)]);
|
||
expect(seotda.view(s, 'B').seats.find((x) => x.id === 'A')!.handName).toBe('18광땡');
|
||
expect(JSON.stringify(seotda.view(s, 'B'))).not.toContain(`"id":${P(3)},`);
|
||
expect(seotda.secretsOf!(s, 'A')).toContain(`h1r0c${P(3)}`);
|
||
});
|
||
|
||
test('a saved fold win from before this choice (no `shown`) stays hidden', () => {
|
||
const s = act(lone(), 'A', { type: 'reveal', show: true });
|
||
delete s.hand!.foldWin!.shown;
|
||
expect(cardsOf(s, 'B')).toEqual([{ hidden: true }, { hidden: true }]);
|
||
expect(seotda.view(s, 'B').seats.find((x) => x.id === 'A')!.handName).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe('재경기', () => {
|
||
test('구사 재경기: 모인 칩 유지, 학교 재징수 없음, 쇼다운 생존자만', () => {
|
||
let s = make({ dealMode: 'oneRound' });
|
||
s = rig(s, { A: [P(4), S(9)], B: [S(1), P(2)], C: [P(5), P(6)] });
|
||
s = act(s, 'A', { type: 'check' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
expect(s.hand!.showdown!.pots[0]).toMatchObject({ type: 'rematch', reason: 'gusa', winners: ['A', 'B'] });
|
||
expect(s.hand!.next).toBe('rematch');
|
||
s = readyAll(s);
|
||
const h = s.hand!;
|
||
expect([h.handNo, h.rematchNo, s.handsPlayed]).toEqual([1, 1, 0]);
|
||
expect(h.order).toEqual(['A', 'B']);
|
||
expect(h.dealer).toBe('A');
|
||
expect([stack(s, 'A'), stack(s, 'B'), stack(s, 'C')]).toEqual([990, 990, 990]);
|
||
const v = seotda.view(s, 'A');
|
||
expect([v.pot, v.rematchNo, v.rematchReason]).toEqual([30, 1, 'gusa']);
|
||
// 하프 in a rematch sees the carried pot: 10 + floor(30/2) → 15.
|
||
expect(v.legal.find((l) => l.type === 'half')!.amount).toBe(15);
|
||
expect(reject(s, 'C', { type: 'check' })).toBe('이번 판에 참가하지 않았어요.');
|
||
// Rematch resolves the carried pot; winner takes it all.
|
||
s = rig(s, { A: [S(10), P(10)], B: [P(2), P(3)] });
|
||
s = act(s, 'A', { type: 'ping' });
|
||
s = act(s, 'B', { type: 'call' });
|
||
expect(s.hand!.showdown!.pots).toEqual([{ amount: 50, eligible: ['A', 'B'], type: 'win', winners: ['A'], reason: 'normal' }]);
|
||
expect(stack(s, 'A')).toBe(1030);
|
||
s = readyAll(s);
|
||
expect(s.handsPlayed).toBe(1);
|
||
expect(s.stats.rematches).toBe(1);
|
||
});
|
||
|
||
function gusaHand(opts: OldOpts) {
|
||
let s = make({ dealMode: 'oneRound', ...opts });
|
||
s = rig(s, { A: [P(4), S(9)], B: [S(1), P(2)], C: [P(5), P(6)] });
|
||
s = act(s, 'A', { type: 'check' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
return readyAll(s);
|
||
}
|
||
|
||
test('rejoinCost=half: the folded player pays half (rounded down) and joins', () => {
|
||
let s = gusaHand({ rejoinCost: 'half', baseUnit: 2, startingChips: 500 });
|
||
expect(s.hand!.phase).toBe('rejoin');
|
||
expect(seotda.activePlayers(s)).toEqual(['C']);
|
||
expect(seotda.view(s, 'C').rejoin).toEqual({ pending: ['C'], cost: 3, mine: true, canAfford: true });
|
||
const before = chipsTotal(s);
|
||
s = act(s, 'C', { type: 'rejoin', accept: true });
|
||
expect(s.hand!.rematchNo).toBe(1);
|
||
expect(s.hand!.order).toEqual(['A', 'B', 'C']);
|
||
expect(stack(s, 'C')).toBe(498 - 3);
|
||
expect(seotda.view(s, null).pot).toBe(9);
|
||
expect(chipsTotal(s)).toBe(before);
|
||
});
|
||
|
||
test('rejoin: not enough chips → refused; timeout → not joining', () => {
|
||
let s = gusaHand({ rejoinCost: 'full' });
|
||
expect(s.hand!.rejoinCost).toBe(30);
|
||
s.seats[2]!.stack = 20;
|
||
expect(reject(s, 'C', { type: 'rejoin', accept: true })).toBe('보유 금액이 모자라 재참가할 수 없어요.');
|
||
expect(seotda.legalActions!(s, 'C')).toEqual([{ type: 'rejoin', accept: false }]);
|
||
s = act(s, 'C', { type: 'timeout' });
|
||
expect(s.hand!.order).toEqual(['A', 'B']);
|
||
expect(stack(s, 'C')).toBe(20);
|
||
});
|
||
|
||
test('tie rematch 3 times in a row, then the 4th tie splits (odd chip to the dealer side)', () => {
|
||
let s = make({ dealMode: 'oneRound' });
|
||
const fives = { A: [P(2), P(3)], B: [P(6), S(9)] };
|
||
s = rig(s, { ...fives, C: [P(5), P(6)] });
|
||
s = act(s, 'A', { type: 'half' }); // 15 → pot 45
|
||
s = act(s, 'B', { type: 'call' });
|
||
s = act(s, 'C', { type: 'call' }); // pot 75, C loses with 1끗
|
||
expect(s.hand!.showdown!.pots[0]).toMatchObject({ amount: 75, type: 'rematch', reason: 'tie', winners: ['A', 'B'] });
|
||
for (let k = 1; k <= 3; k++) {
|
||
s = readyAll(s);
|
||
expect(s.hand!.rematchNo).toBe(k);
|
||
expect(s.hand!.order).toEqual(['A', 'B']);
|
||
s = rig(s, fives);
|
||
s = act(s, 'A', { type: 'check' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
}
|
||
expect(s.hand!.showdown!.pots).toEqual([{ amount: 75, eligible: ['A', 'B'], type: 'split', winners: ['A', 'B'], reason: 'limit' }]);
|
||
expect([stack(s, 'A'), stack(s, 'B'), stack(s, 'C')]).toEqual([975 + 38, 975 + 37, 975]);
|
||
expect(chipsTotal(s)).toBe(3000);
|
||
});
|
||
|
||
test('side pot + rematch: side pot paid at once, only the main pot is replayed', () => {
|
||
let s = make({ dealMode: 'oneRound' });
|
||
s.seats[0]!.stack = 20;
|
||
s.hand!.betting!.players[0]!.stack = 20;
|
||
s = rig(s, { A: [P(2), P(3)], B: [P(6), S(9)], C: [P(5), P(8)] });
|
||
s = act(s, 'A', { type: 'ping' });
|
||
s = act(s, 'B', { type: 'half' });
|
||
s = act(s, 'C', { type: 'call' });
|
||
s = act(s, 'A', { type: 'call' }); // all-in for the main pot only
|
||
expect(s.hand!.showdown!.pots).toEqual([
|
||
{ amount: 30, eligible: ['B', 'C'], type: 'win', winners: ['B'], reason: 'normal' },
|
||
{ amount: 90, eligible: ['A', 'B', 'C'], type: 'rematch', winners: ['A', 'B'], reason: 'tie' },
|
||
]);
|
||
expect(stack(s, 'B')).toBe(1000 - 45 + 30); // 학교 10 + 하프 35, side pot back
|
||
expect(s.hand!.carried).toEqual([{ amount: 90, eligible: ['A', 'B'] }]);
|
||
const sum = chipsTotal(s);
|
||
// A is all-in: the rematch has no betting decisions and goes straight to showdown.
|
||
s = readyAll(s);
|
||
expect(s.hand!.rematchNo).toBe(1);
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
const pot = s.hand!.showdown!.pots[0]!;
|
||
expect([pot.amount, pot.eligible]).toEqual([90, ['A', 'B']]);
|
||
expect(chipsTotal(s)).toBe(sum);
|
||
});
|
||
});
|
||
|
||
describe('3장 섯다 (옵션: 공개패 없이, 마지막 베팅 전에 고르기)', () => {
|
||
function three() {
|
||
let s = make({ cardMode: 'three', threeOpen: false, threePick: 'beforeBet' });
|
||
s = rig(s, { A: [S(1), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] }, [S(4), P(9), P(10)]);
|
||
s = act(s, 'A', { type: 'check' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
s = act(s, 'C', { type: 'check' });
|
||
return s;
|
||
}
|
||
|
||
test('simultaneous secret choice before the last betting round', () => {
|
||
let s = three();
|
||
expect(s.hand!.phase).toBe('choose');
|
||
expect(s.hand!.cards.A).toEqual([S(1), S(8), S(4)]);
|
||
expect(seotda.activePlayers(s).sort()).toEqual(['A', 'B', 'C']);
|
||
const mine = seotda.view(s, 'A');
|
||
expect(mine.myCombos!.find((c) => c.best)!.name).toBe('18광땡');
|
||
expect(mine.myHand!.name).toBe('최고 조합 18광땡');
|
||
expect(reject(s, 'A', { type: 'choose', cardIds: [S(1), S(1)] })).toBe('카드 두 장을 골라 주세요.');
|
||
expect(reject(s, 'A', { type: 'choose', cardIds: [S(1), P(9)] })).toBe('카드 두 장을 골라 주세요.');
|
||
s = act(s, 'A', { type: 'choose', cardIds: [S(1), S(4)] }); // 독사 on purpose
|
||
expect(reject(s, 'A', { type: 'choose', cardIds: [S(1), S(8)] })).toBe('이미 골랐어요.');
|
||
const other = seotda.view(s, 'B');
|
||
expect(other.seats.find((x) => x.id === 'A')!.chosen).toBe(true);
|
||
expect(other.seats.find((x) => x.id === 'A')!.cards).toEqual([{ hidden: true }, { hidden: true }]);
|
||
expect(JSON.stringify(other)).not.toContain('"id":0,');
|
||
expect(other.myChosen).toBeNull();
|
||
expect(seotda.view(s, 'A').myDiscard!.id).toBe(S(8));
|
||
});
|
||
|
||
test('timeout picks the best combination; the discard never appears in any view or event', () => {
|
||
let s = three();
|
||
let events: GameEvent[] = [];
|
||
for (const p of ['A', 'B', 'C']) {
|
||
const r = actE(s, p, { type: 'timeout' });
|
||
s = r.state;
|
||
events = events.concat(r.events);
|
||
}
|
||
expect(s.hand!.chosen.A).toEqual([S(1), S(8)]);
|
||
expect(s.hand!.phase).toBe('betting');
|
||
expect(s.hand!.street).toBe(1);
|
||
for (const p of ['A', 'B', 'C']) {
|
||
const r = actE(s, p, { type: 'check' });
|
||
s = r.state;
|
||
events = events.concat(r.events);
|
||
}
|
||
expect(s.hand!.showdown!.hands.find((x) => x.id === 'A')!.name).toBe('18광땡');
|
||
for (const p of ['A', 'B', 'C']) {
|
||
const discard = s.hand!.cards[p]!.find((c) => !s.hand!.chosen[p]!.includes(c))!;
|
||
const key = `"key":"h1r0c${discard}"`;
|
||
for (const viewer of ['A', 'B', 'C', null]) {
|
||
if (viewer === p) continue;
|
||
expect(JSON.stringify(seotda.view(s, viewer))).not.toContain(key);
|
||
}
|
||
const shown = events.filter((e) => e.type === 'showdown').flatMap((e) => (e.hands as { cards: number[] }[]).flatMap((x) => x.cards));
|
||
expect(shown).not.toContain(discard);
|
||
}
|
||
expect(events.filter((e) => e.type !== 'showdown').every((e) => !('cards' in e) && !('card' in e))).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe('3장 섯다 (한게임 기본: 2장 → 공개패 1장 → 1구 베팅 → 1장 더 → 2구 베팅 → 2장 고르기)', () => {
|
||
function opened() {
|
||
let s = make({ cardMode: 'three' });
|
||
s = rig(s, { A: [S(1), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] }, [S(4), P(9), P(10)]);
|
||
return s;
|
||
}
|
||
|
||
test('2장을 받으면 먼저 모두 공개할 패 1장을 고르고, 고른 패는 모두에게 앞면으로 보여요', () => {
|
||
let s = opened();
|
||
expect(s.hand!.phase).toBe('open');
|
||
expect(s.hand!.cards.A).toHaveLength(2);
|
||
expect(seotda.activePlayers(s).sort()).toEqual(['A', 'B', 'C']);
|
||
expect(reject(s, 'A', { type: 'check' })).toBe('지금은 베팅 시간이 아니에요.');
|
||
expect(reject(s, 'A', { type: 'open', cardId: P(9) })).toBe('내 패 중에서 골라 주세요.');
|
||
s = act(s, 'A', { type: 'open', cardId: S(8) });
|
||
expect(reject(s, 'A', { type: 'open', cardId: S(1) })).toBe('이미 공개패를 골랐어요.');
|
||
const b = seotda.view(s, 'B');
|
||
expect(b.seats.find((x) => x.id === 'A')!.cards).toEqual([{ hidden: true }, expect.objectContaining({ id: S(8) })]);
|
||
expect(b.seats.find((x) => x.id === 'A')!.opening).toBe(true);
|
||
expect(b.seats.find((x) => x.id === 'C')!.opening).toBe(false);
|
||
expect(JSON.stringify(b)).not.toContain(`"id":${S(1)},`);
|
||
expect(seotda.secretsOf!(s, 'A')).not.toContain(`h1r0c${S(8)}`);
|
||
s = act(s, 'B', { type: 'open', cardId: P(6) });
|
||
s = act(s, 'C', { type: 'timeout' }); // 낮은 월(2월)을 보여 줘요
|
||
expect(s.hand!.opened.C).toBe(P(2));
|
||
expect(s.hand!.phase).toBe('betting');
|
||
expect(s.hand!.street).toBe(0);
|
||
expect(seotda.activePlayers(s)).toEqual(['A']);
|
||
});
|
||
|
||
test('1구 베팅 뒤 1장 더 받고 2구 베팅, 그다음 3장 중 2장을 골라 공개해요', () => {
|
||
let s = opened();
|
||
for (const [p, c] of [['A', S(8)], ['B', P(6)], ['C', P(7)]] as const) s = act(s, p, { type: 'open', cardId: c });
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||
expect(s.hand!.phase).toBe('betting');
|
||
expect(s.hand!.street).toBe(1);
|
||
expect(s.hand!.cards.A).toEqual([S(1), S(8), S(4)]);
|
||
// The third card is hidden from the others; the 공개패 stays face up.
|
||
expect(seotda.view(s, 'C').seats.find((x) => x.id === 'A')!.cards).toEqual([{ hidden: true }, expect.objectContaining({ id: S(8) }), { hidden: true }]);
|
||
s = act(s, 'A', { type: 'half' });
|
||
s = act(s, 'B', { type: 'call' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
expect(s.hand!.phase).toBe('choose');
|
||
expect(seotda.activePlayers(s).sort()).toEqual(['A', 'B']);
|
||
expect(seotda.view(s, 'A').myCombos!.find((c) => c.best)!.name).toBe('18광땡');
|
||
s = act(s, 'A', { type: 'choose', cardIds: [S(1), S(4)] }); // 공개패(8광)를 버리고 독사
|
||
expect(seotda.view(s, 'B').seats.find((x) => x.id === 'A')!.cards).toEqual([{ hidden: true }, { hidden: true }]);
|
||
s = act(s, 'B', { type: 'timeout' });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(s.hand!.showdown!.hands.find((x) => x.id === 'A')!.name).toBe('독사');
|
||
});
|
||
|
||
test('2구 베팅에서 한 사람만 남으면 고르기 없이 끝나요', () => {
|
||
let s = opened();
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'timeout' });
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||
s = act(s, 'A', { type: 'half' });
|
||
s = act(s, 'B', { type: 'die' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
expect(s.hand!.phase).toBe('reveal');
|
||
expect(s.hand!.chosen.A).toBeNull();
|
||
s = act(s, 'A', { type: 'reveal', show: true });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(s.hand!.foldWin!.winner).toBe('A');
|
||
// Not chosen yet: the three cards are shown, named by their best pair (1·8 광 → 18광땡).
|
||
const c = seotda.view(s, 'C').seats.find((x) => x.id === 'A')!;
|
||
expect(c.cards.map((x) => ('id' in x ? x.id : null))).toEqual([S(1), S(8), S(4)]);
|
||
expect(c.handName).toBe('18광땡');
|
||
});
|
||
|
||
test('시간 무제한이면 공개패 고르기에도 마감이 없어요', () => {
|
||
const s = make({ turnSeconds: null, cardMode: 'three' });
|
||
expect(s.hand!.phase).toBe('open');
|
||
expect(s.deadlineAt).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe('timeouts, away, leaving', () => {
|
||
test('timeout: check when nobody bet, otherwise die; two in a row → away with a 5 s limit', () => {
|
||
let s = make();
|
||
const t0 = s.deadlineAt!;
|
||
expect(t0).toBe(20_000);
|
||
s = act(s, 'A', { type: 'timeout' }, 21_000);
|
||
expect(s.hand!.lastAction.A).toEqual({ type: 'check', amount: 0 });
|
||
s = act(s, 'B', { type: 'ping' }, 22_000);
|
||
s = act(s, 'C', { type: 'timeout' }, 43_000);
|
||
expect(s.hand!.lastAction.C!.type).toBe('die');
|
||
s = act(s, 'A', { type: 'timeout' }, 64_000);
|
||
expect(s.hand!.lastAction.A!.type).toBe('die');
|
||
expect(s.seats[0]!.away).toBe(true);
|
||
s = act(s, 'B', { type: 'reveal', show: false }, 65_000);
|
||
// Next hand (result screen times out): A is away → 5 s limit on A's turn; a real action clears it.
|
||
for (const p of seotda.activePlayers(s)) s = act(s, p, { type: 'timeout' }, 70_000);
|
||
const h = s.hand!;
|
||
const first = seotda.activePlayers(s)[0]!;
|
||
expect(first).toBe(h.order[0]!);
|
||
// Walk to A's turn.
|
||
while (seotda.activePlayers(s)[0] !== 'A') s = act(s, seotda.activePlayers(s)[0]!, { type: 'check' }, 100_000);
|
||
expect(s.deadlineAt).toBe(100_000 + 5000);
|
||
s = act(s, 'A', { type: 'check' }, 101_000);
|
||
expect(s.seats[0]!.away).toBe(false);
|
||
});
|
||
|
||
test('disconnected dealer: timeout acts after the deadline, then normal play resumes', () => {
|
||
let s = make();
|
||
expect(seotda.timeoutPlayers!(s)).toEqual(['A']);
|
||
expect(seotda.onTimeout(s, 'A')).toEqual({ type: 'timeout' });
|
||
expect(reject(s, 'B', { type: 'timeout' })).toBe('시간 초과 대상이 아니에요.');
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
s = act(s, 'B', { type: 'check' });
|
||
s = act(s, 'C', { type: 'check' });
|
||
s = act(s, 'A', { type: 'ping' }); // reconnected
|
||
expect(s.seats[0]!.timeoutsInRow).toBe(0);
|
||
});
|
||
|
||
test('a player who leaves auto-dies; with one connected player left the game ends after the hand', () => {
|
||
let s = make({}, ['A', 'B', 'C']);
|
||
s = act(s, 'A', { type: 'ping' });
|
||
s = act(s, 'B', seotda.onLeave!(s, 'B')!);
|
||
expect(s.hand!.betting!.players.find((p) => p.id === 'B')!.status).toBe('folded');
|
||
expect(seotda.activePlayers(s)).toEqual(['C']);
|
||
s = act(s, 'C', { type: 'leave' });
|
||
expect(s.hand!.foldWin).toEqual({ winner: 'A', amount: 30, shown: false }); // nobody left to show the cards to
|
||
s = readyAll(s);
|
||
expect(s.phase).toBe('finished');
|
||
const r = seotda.result(s)!;
|
||
expect(r.ranking[0]).toEqual(['A']);
|
||
expect(seotda.onLeave!(s, 'A')).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe('rebuy, elimination, scores', () => {
|
||
/** Ends the current hand by folds, then sets stacks before the hand-end processing. */
|
||
function toHandEnd(opts: OldOpts, players = ['A', 'B', 'C']): SeotdaState {
|
||
let s = make({ dealMode: 'oneRound', ...opts }, players);
|
||
s = foldOut(s);
|
||
return s;
|
||
}
|
||
|
||
test('rebuy: busted player may take chips again; hands score = chips - start × rebuys', () => {
|
||
let s = toHandEnd({ rebuy: 'limited', rebuyLimit: 1, handLimit: 10 });
|
||
s.seats[0]!.stack += s.seats[1]!.stack;
|
||
s.seats[1]!.stack = 0;
|
||
s = readyAll(s);
|
||
expect(s.phase).toBe('rebuy');
|
||
expect(seotda.activePlayers(s)).toEqual(['B']);
|
||
expect(seotda.view(s, 'B').rebuy).toEqual({ pending: ['B'], mine: true, left: 1 });
|
||
s = act(s, 'B', { type: 'rebuy', accept: true });
|
||
expect([s.phase, stack(s, 'B'), s.seats[1]!.rebuys]).toEqual(['playing', 990, 1]); // refilled, then paid the next 학교
|
||
expect(chipsTotal(s)).toBe(total(s));
|
||
// Last hand: no rebuy question, the game ends.
|
||
s = foldOut(s);
|
||
s.handsPlayed = 9;
|
||
s = readyAll(s);
|
||
expect(s.phase).toBe('finished');
|
||
const r = seotda.result(s)!;
|
||
for (const x of s.seats) expect(r.scores![x.id]).toBe(x.stack - 1000 * x.rebuys);
|
||
expect(r.ranking.flat().sort()).toEqual(['A', 'B', 'C']);
|
||
expect(r.summary).toMatch(/^10판 끝\. 1위/);
|
||
});
|
||
|
||
test('limited rebuys used up → eliminated; declining also eliminates', () => {
|
||
let s = toHandEnd({ rebuy: 'limited', rebuyLimit: 1 });
|
||
s.seats[1]!.rebuys = 1;
|
||
s.seats[0]!.stack += s.seats[1]!.stack;
|
||
s.seats[1]!.stack = 0;
|
||
s = readyAll(s);
|
||
expect(s.phase).toBe('playing');
|
||
expect(s.seats[1]!.status).toBe('eliminated');
|
||
expect(s.hand!.order).not.toContain('B');
|
||
let t = toHandEnd({});
|
||
t.seats[0]!.stack += t.seats[1]!.stack;
|
||
t.seats[1]!.stack = 0;
|
||
t = readyAll(t);
|
||
t = act(t, 'B', { type: 'timeout' });
|
||
expect(t.seats[1]!.status).toBe('eliminated');
|
||
});
|
||
|
||
test('lastStanding: same-hand eliminations ranked by chips at hand start', () => {
|
||
let s = toHandEnd({ endCondition: 'lastStanding', rebuy: 'off' });
|
||
s.seats[1]!.stackAtHandStart = 300;
|
||
s.seats[2]!.stackAtHandStart = 100;
|
||
s.seats[0]!.stack += s.seats[1]!.stack + s.seats[2]!.stack;
|
||
s.seats[1]!.stack = 0;
|
||
s.seats[2]!.stack = 0;
|
||
s = readyAll(s);
|
||
expect(s.phase).toBe('finished');
|
||
const r = seotda.result(s)!;
|
||
expect(r.ranking).toEqual([['A'], ['B'], ['C']]);
|
||
expect(r.scores).toEqual({ A: 3, B: 2, C: 1 });
|
||
});
|
||
|
||
test('학교 doubles every N hands (capped at startingChips / 5)', () => {
|
||
let s = make({ dealMode: 'oneRound', schoolUpEvery: 5, startingChips: 500, baseUnit: 20 });
|
||
for (let i = 0; i < 10; i++) {
|
||
s = foldOut(s);
|
||
s = readyAll(s);
|
||
}
|
||
expect(s.baseUnit).toBe(80);
|
||
expect(seotda.view(s, null).baseUnit).toBe(80);
|
||
});
|
||
});
|
||
|
||
describe('한게임 방식 (원 단위, 기본 설정)', () => {
|
||
/** A game with the real options (no CLASSIC rules, no unit scaling). */
|
||
function hg(opts: Partial<SeotdaOptions> = {}, players = ['A', 'B', 'C'], dealer = 'A'): SeotdaState {
|
||
const options = seotda.optionsSchema.parse(opts);
|
||
for (let seed = 1; seed < 500; seed++) {
|
||
const s = seotda.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||
if (s.hand!.dealer === dealer) return s;
|
||
}
|
||
throw new Error('no seed with that dealer');
|
||
}
|
||
|
||
test('2장을 한 번에 받고 한 번 베팅한 뒤 공개, 금액은 원 (기본금 1만원 × 3명 = 판돈 3만원)', () => {
|
||
let s = hg();
|
||
expect(Object.values(s.hand!.cards).map((c) => c.length)).toEqual([2, 2, 2]);
|
||
const v = seotda.view(s, 'A');
|
||
expect([v.pot, v.baseUnit, v.seats[0]!.stack]).toEqual([30_000, 10_000, 990_000]);
|
||
expect(v.legal.map((l) => l.type)).toEqual(['check', 'ping', 'half', 'die']); // 쿼터는 한게임에 없어 기본으로 꺼 둠
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(s.hand!.showdown).not.toBeNull();
|
||
});
|
||
|
||
test('베팅 규칙 222: 선과 다음 사람은 첫 베팅에서 하프·다이만, 그 뒤는 자유', () => {
|
||
let s = hg({ betRule: '222' });
|
||
const v = seotda.view(s, 'A');
|
||
expect(v.forcedHalf).toBe(true);
|
||
expect(v.legal.map((l) => l.type)).toEqual(['half', 'die']);
|
||
expect(reject(s, 'A', { type: 'check' })).toBe('베팅 규칙 222: 지금은 하프 또는 다이만 할 수 있어요.');
|
||
s = act(s, 'A', { type: 'half' });
|
||
expect(seotda.view(s, 'B').legal.map((l) => l.type)).toEqual(['half', 'die']);
|
||
s = act(s, 'B', { type: 'half' });
|
||
const c = seotda.view(s, 'C');
|
||
expect(c.forcedHalf).toBe(false);
|
||
expect(c.legal.map((l) => l.type)).toEqual(['call', 'ddadang', 'half', 'die']);
|
||
expect(c.betLog.map((e) => [e.p, e.t])).toEqual([
|
||
['A', 'half'],
|
||
['B', 'half'],
|
||
]);
|
||
});
|
||
|
||
test('베팅 규칙 111: 선이 시간을 넘기면 체크가 아니라 다이', () => {
|
||
let s = hg({ betRule: '111' });
|
||
s = act(s, 'A', { type: 'timeout' }, 21_000);
|
||
expect(s.hand!.lastAction.A!.type).toBe('die');
|
||
});
|
||
|
||
test('쿼터를 켠 방만 쿼터를 받음', () => {
|
||
const off = hg();
|
||
expect(reject(off, 'A', { type: 'quarter' })).toBe('이 방은 쿼터 베팅을 쓰지 않아요.');
|
||
const on = hg({ quarter: true });
|
||
expect(seotda.view(on, 'A').legal.map((l) => l.type)).toContain('quarter');
|
||
});
|
||
|
||
test('40장: 1~10월 4장 모두 쓰고, 3장 섯다도 10명까지', () => {
|
||
const s = hg({ deck: 40 });
|
||
const all = [...s.hand!.deck, ...Object.values(s.hand!.cards).flat()].sort((a, b) => a - b);
|
||
expect(all).toEqual(Array.from({ length: 40 }, (_, i) => i));
|
||
expect(seotda.playersFor!({ ...seotda.defaultOptions, deck: 40, cardMode: 'three' })).toEqual({ min: 2, max: 10 });
|
||
});
|
||
|
||
test('행동 제한 시간 무제한: 베팅·고르기에 마감이 없고, 판 결과 화면만 시간이 흐름', () => {
|
||
let s = hg({ turnSeconds: null });
|
||
expect(s.deadlineAt).toBeNull();
|
||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||
expect(s.hand!.phase).toBe('handEnd');
|
||
expect(s.deadlineAt).not.toBeNull();
|
||
const three = hg({ turnSeconds: null, cardMode: 'three', threeOpen: false, threePick: 'beforeBet' });
|
||
let t = three;
|
||
for (const p of ['A', 'B', 'C']) t = act(t, p, { type: 'check' });
|
||
expect(t.hand!.phase).toBe('choose');
|
||
expect(t.deadlineAt).toBeNull();
|
||
});
|
||
|
||
test('판이 끝나면 각자 얼마를 따고 잃었는지(handDelta)', () => {
|
||
let s = hg();
|
||
s = act(s, 'A', { type: 'half' }); // 1만 5천원
|
||
s = act(s, 'B', { type: 'die' });
|
||
s = act(s, 'C', { type: 'die' });
|
||
s = act(s, 'A', { type: 'reveal', show: false });
|
||
const v = seotda.view(s, null);
|
||
expect(v.foldWin).toEqual({ winner: 'A', amount: 30_000, shown: false });
|
||
expect(v.seats.map((x) => x.handDelta)).toEqual([20_000, -10_000, -10_000]);
|
||
});
|
||
|
||
test('v1(칩) 방 상태를 v2(원)로 옮김: 금액 × 1000, 진행 중 규칙은 그대로(쿼터 켬, 20장, 일반 베팅)', () => {
|
||
let s = make({ dealMode: 'twoRounds' }); // old units: 시작 1,000 / 학교 10
|
||
s = act(s, 'A', { type: 'half' });
|
||
const v1 = structuredClone(s) as unknown as Record<string, unknown>;
|
||
const o = { ...(v1.options as Record<string, unknown>) };
|
||
delete o.deck;
|
||
delete o.betRule;
|
||
delete o.quarter;
|
||
v1.options = o;
|
||
const h = v1.hand as Record<string, unknown>;
|
||
delete h.forced;
|
||
delete h.log;
|
||
const m = seotda.migrate!(v1, 1);
|
||
expect(seotda.stateVersion).toBe(3);
|
||
expect(m.options).toMatchObject({ threeOpen: false, threePick: 'beforeBet' });
|
||
expect([m.options.startingChips, m.options.baseUnit, m.baseUnit]).toEqual([1_000_000, 10_000, 10_000]);
|
||
expect(m.options).toMatchObject({ deck: 20, betRule: 'free', quarter: true });
|
||
expect(m.seats.map((x) => x.stack)).toEqual(s.seats.map((x) => x.stack * 1000));
|
||
expect(chipsTotal(m)).toBe(chipsTotal(s) * 1000);
|
||
expect(seotda.view(m, 'B').legal.find((l) => l.type === 'call')!.amount).toBe(15_000);
|
||
expect(m.hand!.log).toEqual([]);
|
||
});
|
||
});
|
||
|
||
describe('options', () => {
|
||
test('schema defaults and validation', () => {
|
||
// 한게임 섯다처럼: 2장을 한 번에 받고 한 번 베팅, 20장, 일반 베팅, 쿼터 없음, 땡잡이 3·7 아무 패, 멍구사 9땡까지, 원 단위.
|
||
expect(seotda.defaultOptions).toMatchObject({
|
||
cardMode: 'two',
|
||
dealMode: 'oneRound',
|
||
deck: 20,
|
||
betRule: 'free',
|
||
quarter: false,
|
||
ttaengjabi: 'loose',
|
||
mungGusa: 'upTo9',
|
||
startingChips: 1_000_000,
|
||
baseUnit: 10_000,
|
||
rebuy: 'unlimited',
|
||
turnSeconds: 20,
|
||
});
|
||
expect(seotda.optionsSchema.safeParse({ startingChips: 500_000, baseUnit: 50_000 }).success).toBe(false);
|
||
expect(seotda.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||
// Rooms saved with the old chip options fall back to the defaults instead of failing.
|
||
expect(seotda.optionsSchema.parse({ startingChips: 1000, baseUnit: 10 })).toMatchObject({ startingChips: 1_000_000, baseUnit: 10_000 });
|
||
expect(seotda.playersFor!({ ...seotda.defaultOptions, cardMode: 'three' })).toEqual({ min: 2, max: 6 });
|
||
expect(seotda.playersFor!(seotda.defaultOptions)).toEqual({ min: 2, max: 10 });
|
||
expect(() => seotda.setup({ players: 'ABCDEFG'.split(''), options: { ...seotda.defaultOptions, cardMode: 'three' }, rng: rng(), now: 0 })).toThrow();
|
||
});
|
||
|
||
test('every option has Korean metadata', () => {
|
||
const shape = (seotda.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
|
||
for (const [k, v] of Object.entries(shape)) expect(v.meta()?.title, k).toBeTruthy();
|
||
});
|
||
|
||
test('client actions only (system actions are not in the schema)', () => {
|
||
expect(seotda.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false);
|
||
expect(seotda.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
|
||
expect(seotda.actionSchema.safeParse({ type: 'ddadang' }).success).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- properties
|
||
|
||
describe('random playouts', () => {
|
||
const conserve = (st: unknown) => {
|
||
const s = st as SeotdaState;
|
||
if (chipsTotal(s) !== total(s)) throw new Error(`chips not conserved: ${chipsTotal(s)} vs ${total(s)}`);
|
||
if (s.seats.some((x) => x.stack < 0)) throw new Error('negative stack');
|
||
};
|
||
const configs: [string, Partial<SeotdaOptions>, number, number][] = [
|
||
['기본', {}, 4, 4],
|
||
['2장 한 번에·나눔·풀', { dealMode: 'oneRound', tieRule: 'split', maxRaise: 'full' }, 5, 3],
|
||
['3장 섯다·재참가 절반', { cardMode: 'three', rejoinCost: 'half', ttaengjabi: 'loose' }, 6, 3],
|
||
['최후 1인·리바이 없음·회전', { endCondition: 'lastStanding', rebuy: 'off', dealerRule: 'rotate', baseUnit: 50_000, startingChips: 1_000_000 }, 3, 4],
|
||
['10명·전액 재참가', { rejoinCost: 'full', mungGusa: 'upToJang', handLimit: 10, startingChips: 500_000, baseUnit: 2_000 }, 10, 2],
|
||
['1장씩·쿼터·베팅 규칙 333', { dealMode: 'twoRounds', quarter: true, betRule: '333' }, 5, 3],
|
||
['40장·3장 섯다·8명', { deck: 40, cardMode: 'three', betRule: '111' }, 8, 2],
|
||
['2명·학교 상승·제한 리바이', { schoolUpEvery: 5, rebuy: 'limited', rebuyLimit: 2, handLimit: 30 }, 2, 4],
|
||
];
|
||
test.each(configs)('%s: finishes, chips conserved, no leaks, deterministic', (_n, opts, n, runs) => {
|
||
const options = seotda.optionsSchema.parse(opts);
|
||
const players = Array.from({ length: n }, (_, i) => `P${i}`);
|
||
for (let i = 1; i <= playoutSeeds(runs); i++) {
|
||
const a = randomPlayout(seotda, { players, options, seed: seedN(i), maxSteps: 20_000, invariant: conserve, maxApplyMs: 30 });
|
||
expect(a.finished).toBe(true);
|
||
expect(seotda.result(a.finalState as SeotdaState)!.ranking.flat().sort()).toEqual([...players].sort());
|
||
if (i === 1) {
|
||
const b = randomPlayout(seotda, { players, options, seed: seedN(i), maxSteps: 20_000, maxApplyMs: 30 });
|
||
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
|
||
}
|
||
}
|
||
}, 15_000);
|
||
|
||
const LEAK_SEEDS = playoutSeeds(1000);
|
||
test(`leak property: ${LEAK_SEEDS} seeds × first hand, every viewer and every event`, () => {
|
||
for (let seed = 1; seed <= LEAK_SEEDS; seed++) {
|
||
const n = 2 + (seed % 5);
|
||
const players = Array.from({ length: n }, (_, i) => `P${i}`);
|
||
const options = seotda.optionsSchema.parse({
|
||
cardMode: seed % 3 === 0 ? 'three' : 'two',
|
||
dealMode: seed % 4 === 1 ? 'oneRound' : 'twoRounds',
|
||
deck: seed % 7 === 0 ? 40 : 20,
|
||
betRule: seed % 5 === 2 ? '222' : 'free',
|
||
});
|
||
const r = SeededRng.fromSeed(seedN(seed));
|
||
const chooser = SeededRng.fromSeed(seedN(seed + 77));
|
||
let s = seotda.setup({ players, options, rng: r, now: 0 });
|
||
for (let step = 0; step < 200 && s.handsPlayed === 0 && s.phase !== 'finished'; step++) {
|
||
// Same check as checkNoLeak, computing each view once.
|
||
const views = new Map([...players, null].map((v) => [v, JSON.stringify(seotda.view(s, v))]));
|
||
for (const owner of players)
|
||
for (const secret of seotda.secretsOf!(s, owner))
|
||
for (const [viewer, json] of views) if (viewer !== owner && json.includes(JSON.stringify(secret))) throw new Error(`leak ${secret} of ${owner} to ${viewer}`);
|
||
const actives = seotda.activePlayers(s);
|
||
const actor = actives[chooser.int(actives.length)]!;
|
||
const legal = seotda.legalActions!(s, actor);
|
||
const a = chooser.int(5) === 0 ? seotda.onTimeout(s, actor) : legal[chooser.int(legal.length)]!;
|
||
const out = seotda.apply(s, actor, a, { rng: r, now: step * 1000 });
|
||
const revealed = new Set(out.state.hand?.showdown?.hands.flatMap((x) => x.cards) ?? []);
|
||
for (const e of out.events) {
|
||
if (e.type === 'showdown') {
|
||
for (const c of (e.hands as { cards: number[] }[]).flatMap((x) => x.cards)) if (!revealed.has(c)) throw new Error('showdown event leaks');
|
||
} else if ('cards' in e || 'card' in e || 'hand' in e) throw new Error(`event leaks cards: ${e.type}`);
|
||
}
|
||
s = out.state;
|
||
}
|
||
// Deck order is never part of any view.
|
||
const deck = JSON.stringify(s.hand?.deck ?? []);
|
||
if (s.hand && s.hand.deck.length > 3) for (const p of [...players, null]) expect(JSON.stringify(seotda.view(s, p))).not.toContain(deck.slice(1, -1));
|
||
}
|
||
}, 20_000);
|
||
});
|