섯다 엔진·컴퓨터 다시 만듦(한게임 섯다 기준): 원 단위(시작 100만원·기본금 1만원, v1 칩 방은 ×1000으로 옮김), 2장 한 번에 받기 기본, 20/40장, 베팅 규칙 111~444, 쿼터는 옵션, 땡잡이 3·7 아무 패·멍구사 9땡까지 기본, 시간 무제한, 베팅 기록·판별 손익을 view에

컴퓨터는 남은 패를 전부 따져 보고(맞대결·3명은 모든 경우, 큰 판은 3,000판 표본) 상대 베팅으로 패 범위를 좁혀 판돈 몫과 기댓값으로 결정.
1장만 받고 하프 한 번에 다이하던 버그(고정값 0.35 패 세기와 값 비율 비교) 고침, 회귀 테스트 추가.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:35:23 +09:00
parent f12cf12b84
commit 8cde4fa525
7 changed files with 1023 additions and 143 deletions

View File

@@ -11,6 +11,7 @@
"./bots/luck": "./src/bots/luck.ts",
"./liar/topics": "./src/liar/topics.ts",
"./magical-athlete/racers": "./src/magical-athlete/racers.ts",
"./seotda/money": "./src/seotda/money.ts",
"./*": "./src/*/index.ts"
},
"dependencies": {

View File

@@ -2,7 +2,10 @@ import { describe, expect, test } from 'bun:test';
import { SEOTDA_DECK, SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { rulesOfView, situation } from './bot';
import { evalSeotda, type HandRules } from './hands';
import { seotda, type SeotdaAction, type SeotdaOptions, type SeotdaState } from './index';
import { odds, shareOf } from './odds';
/** Special card of a month (1·3·8 광, others 열끗) and the plain card. */
const S = (m: number) => (m - 1) * 4;
@@ -25,25 +28,121 @@ function rig(s: SeotdaState, cards: Record<string, number[]>, next: number[] = [
return s;
}
const act = (s: SeotdaState, p: string, a: SeotdaAction) => seotda.apply(s, p, a, { rng: SeededRng.fromSeed([7, 7, 7, 7]), now: (clock += 1000) }).state;
const decide = (s: SeotdaState, p: string, r = 0.1) => decideBotAction(seotda, s, p, { now: clock, random: () => r }) as SeotdaAction;
const decide = (s: SeotdaState, p: string, r = 0.9) => decideBotAction(seotda, s, p, { now: clock, random: () => r }) as SeotdaAction;
const RULES: HandRules = { gwangTtaeng: 'all', ttaengjabi: 'loose', amhaeng: true, gusa: true, mungGusa: 'upTo9' };
describe('승률 계산 (odds): 남은 카드를 전부 따져 봄', () => {
test('맞대결은 정확히 전부 셈: 직접 센 값과 같음', () => {
for (const mine of [
[S(10), P(10)], // 장땡
[S(3), P(7)], // 땡잡이
[P(4), P(9)], // 구사
[S(4), S(7)], // 암행어사
[P(2), P(3)], // 5끗
]) {
const o = odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine, finalSize: 2, opponents: [() => 1] });
expect(o.exact).toBe(true);
// Brute force with the pure 족보 functions.
const rest = SEOTDA_DECK.filter((c) => !mine.includes(c));
let sum = 0;
let n = 0;
for (let i = 0; i < rest.length; i++)
for (let j = i + 1; j < rest.length; j++) {
sum += shareOf([evalSeotda(mine[0]!, mine[1]!, RULES), evalSeotda(rest[i]!, rest[j]!, RULES)], RULES);
n++;
}
expect(n).toBe(153);
expect(o.equity).toBeCloseTo(sum / n, 12);
}
});
test('38광땡은 언제나 이김, 망통은 거의 짐', () => {
expect(odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine: [S(3), S(8)], finalSize: 2, opponents: [() => 1, () => 1] }).equity).toBe(1);
expect(odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine: [P(2), P(8)], finalSize: 2, opponents: [() => 1] }).equity).toBeLessThan(0.05);
});
test('1장만 들고 있으면 둘째 장 19가지를 모두 따져 봄', () => {
const o = odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine: [S(1)], finalSize: 2, opponents: [() => 1] });
expect(o.exact).toBe(true);
expect(o.perDraw).toHaveLength(19);
expect(o.perDraw.find((d) => d.card === S(8))!.equity).toBeGreaterThan(0.95); // 18광땡
expect(o.perDraw.reduce((a, d) => a + d.weight, 0)).toBeCloseTo(1, 9);
});
test('사람이 많아 전부 셀 수 없으면 무작위로 많이 뽑아 셈: 정확한 값과 가까움', () => {
const base = { rules: RULES, tieRule: 'rematch' as const, deck: SEOTDA_DECK, mine: [P(2), P(7)], finalSize: 2 as const };
const exact = odds({ ...base, opponents: [() => 1, () => 1] });
expect(exact.exact).toBe(true);
const sampled = odds({ ...base, opponents: [() => 1, () => 1], samples: 3000 });
expect(sampled.exact).toBe(false);
expect(Math.abs(sampled.equity - exact.equity)).toBeLessThan(0.03);
});
});
describe('seotda bot', () => {
test('raises a 38광땡', () => {
const s = rig(make({ dealMode: 'oneRound' }), { A: [S(3), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] });
expect(['half', 'quarter', 'full']).toContain(decide(s, 'A').type);
const s = rig(make(), { A: [S(3), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] });
expect(['half', 'ping']).toContain(decide(s, 'A').type);
});
test('dies with 망통 facing a half bet, calls it with 장땡', () => {
let s = rig(make({ dealMode: 'oneRound' }), { A: [S(3), S(8)], B: [P(2), P(8)], C: [S(10), P(10)] });
test('dies with 망통 facing a half bet, calls or raises it with 장땡', () => {
let s = rig(make(), { A: [S(3), S(8)], B: [P(2), P(8)], C: [S(10), P(10)] });
s = act(s, 'A', { type: 'half' });
expect(decide(s, 'B', 0.9).type).toBe('die');
expect(decide(s, 'B').type).toBe('die');
s = act(s, 'B', { type: 'die' });
expect(['call', 'ddadang', 'quarter', 'half']).toContain(decide(s, 'C', 0.9).type);
expect(['call', 'ddadang', 'half']).toContain(decide(s, 'C').type);
});
test('checks a weak hand when betting is free (never dies for nothing)', () => {
const s = rig(make({ dealMode: 'oneRound' }), { A: [P(2), P(3)], B: [P(5), P(6)], C: [P(2), P(7)] });
expect(decide(s, 'A', 0.9).type).toBe('check');
const s = rig(make(), { A: [P(2), P(3)], B: [P(5), P(6)], C: [P(2), P(7)] });
for (const r of [0.05, 0.5, 0.95]) expect(decide(s, 'A', r).type).not.toBe('die');
});
test('2장 섯다 1장씩: 1장만 받은 상태에서 하프 한 번에 다이하지 않음 (예전 버그)', () => {
// 예전 봇은 1장 패를 고정값(0.35)으로 보고 "콜 값 비율 + 0.12"와 비교해, 하프만 나와도 절반쯤 다이했다.
const dies: string[] = [];
for (const players of [['A', 'B'], ['A', 'B', 'C'], ['A', 'B', 'C', 'D']])
for (const first of SEOTDA_DECK) {
let s = make({ dealMode: 'twoRounds' }, players);
const rest = SEOTDA_DECK.filter((c) => c !== first);
s.hand!.cards = Object.fromEntries(players.map((p, i) => [p, p === 'B' ? [first] : [rest[i]!]]));
s = act(s, 'A', { type: 'half' });
expect(seotda.view(s, 'B').seats.find((x) => x.id === 'B')!.cards).toHaveLength(1);
for (const r of [0.1, 0.5, 0.9]) if (decide(s, 'B', r).type === 'die') dies.push(`${players.length}명 ${first}번 ${r}`);
}
expect(dies).toEqual([]);
});
test('1장 단계라도 하프·따당이 이어져 값이 아주 비싸면 약한 카드는 다이할 수 있음', () => {
let s = make({ dealMode: 'twoRounds' }, ['A', 'B', 'C', 'D']);
s.hand!.cards = { A: [S(1)], B: [S(8)], C: [S(10)], D: [P(2)] };
s = act(s, 'A', { type: 'half' });
s = act(s, 'B', { type: 'ddadang' });
s = act(s, 'C', { type: 'ddadang' });
expect(decide(s, 'D').type).toBe('die');
});
test('상대 베팅으로 상대 패를 좁혀 봄: 하프를 맞은 8끗은 체크를 본 8끗보다 승률이 낮음', () => {
const base = rig(make(), { A: [P(5), P(6)], B: [P(3), P(5)], C: [P(2), P(7)] });
const checked = act(base, 'A', { type: 'check' });
const halved = act(base, 'A', { type: 'half' });
const eqCheck = situation(seotda.view(checked, 'B'), 'B', () => 0.5).equity;
const eqHalf = situation(seotda.view(halved, 'B'), 'B', () => 0.5).equity;
expect(eqHalf).toBeLessThan(eqCheck - 0.05);
});
test('땡잡이는 상대가 세게 걸수록(땡일 가능성이 클수록) 오히려 승률이 오름', () => {
const base = rig(make(), { A: [P(5), P(6)], B: [S(3), P(7)], C: [P(2), P(8)] });
const checked = act(base, 'A', { type: 'check' });
const halved = act(base, 'A', { type: 'half' });
const v = seotda.view(halved, 'B');
expect(rulesOfView(v.options).ttaengjabi).toBe('loose');
expect(situation(v, 'B', () => 0.5).equity).toBeGreaterThan(situation(seotda.view(checked, 'B'), 'B', () => 0.5).equity);
});
test('베팅 규칙 111: 하프·다이만 남으면 센 패는 하프', () => {
const s = rig(make({ betRule: '111' }), { A: [S(10), P(10)], B: [P(5), P(6)], C: [P(2), P(7)] });
expect(decide(s, 'A').type).toBe('half');
});
test('3장 섯다: keeps the best pair of its three cards', () => {
@@ -52,19 +151,21 @@ describe('seotda bot', () => {
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
expect(s.hand!.phase).toBe('choose');
const a = decide(s, 'A') as Extract<SeotdaAction, { type: 'choose' }>;
expect([...a.cardIds].sort((x, y) => x - y)).toEqual([P(4), P(6)]); // 세륙 over 구사·5끗
expect([...a.cardIds].sort((x, y) => x - y)).toEqual([P(4), P(6)]); // 세륙 over 구사·3끗
});
test.each([
['2장 섯다', {}],
['2장 섯다(한 번에)', {}],
['2장 섯다(1장씩)', { dealMode: 'twoRounds' }],
['3장 섯다', { cardMode: 'three' }],
] as const)('%s: 1 human + 3 bots finish without bot timeouts', (_, options) => {
['40장', { deck: 40 }],
] as const)('%s: 1 human + 3 bots finish without bot timeouts, fast', (_, options) => {
const opts = seotda.optionsSchema.parse(options);
for (let s = 1; s <= 2; s++) {
const r = botPlayout(seotda, { players: ['human', 'bot:1', 'bot:2', 'bot:3'], options: opts, seed: seedN(s), isBot: (p) => p.startsWith('bot:') });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
expect(r.maxBotMs).toBeLessThan(100);
expect(r.maxBotMs).toBeLessThan(150);
}
});
}, 30_000);
});

View File

@@ -1,16 +1,25 @@
/**
* 섯다 computer player: a cautious beginner that bets by the strength of its own cards.
* Strong 족보 raise, middling ones call cheap bets, weak ones check or die; an occasional small bluff.
* Uses only its own view (own cards, pot, legal bet amounts) and the pure 족보 helpers.
* 섯다 computer player (docs/games/seotda.md §8.7). It thinks like a careful player, using only its own screen:
*
* 1. Ranges: every bet it saw narrows what that opponent may hold — a 하프·따당 usually means a strong hand (but people
* bluff, so weak hands keep some weight), a call means "something", a check caps the very top a little. Forced bets of
* 베팅 규칙 111~444 say nothing.
* 2. Odds: `odds` enumerates every way the unseen cards can fall (the cards still to come included — with one card in
* hand it also counts all its own second cards) and adds up its share of the pot, special hands included.
* 3. Decision: each legal bet gets an expected value from that share, the pot, the price and how likely the others are to
* fold; the level (`humanBest`) adds the human-like slips. A small bluff now and then, a trap with a monster now and
* then. It never dies when checking is free, and with a card still to come it keeps cheap hands (the old bug: it died
* after one card because a fixed "one card = weak" guess was compared with the price).
*/
import type { BotStrategy } from '../bots/types';
import { pick, typeOf } from '../bots/policy';
import { evalSeotda, isGwang, monthOf, type HandRules } from './hands';
import type { SeotdaAction, SeotdaView } from './index';
import { humanBest, pick, typeOf } from '../bots/policy';
import type { HandRules } from './hands';
import { deckOf, type BetType, type SeotdaAction, type SeotdaView } from './index';
import { cardsKey, odds, strengthPercentile, type Odds, type RangeWeight } from './odds';
type Bet = SeotdaView['legal'][number];
const rulesOf = (o: SeotdaView['options']): HandRules => ({
export const rulesOfView = (o: SeotdaView['options']): HandRules => ({
gwangTtaeng: o.gwangTtaeng,
ttaengjabi: o.ttaengjabi,
amhaeng: o.amhaeng,
@@ -18,95 +27,233 @@ const rulesOf = (o: SeotdaView['options']): HandRules => ({
mungGusa: o.gusa ? o.mungGusa : 'off',
});
/** Rough winning chance (0..1) of a 2-card hand; specials count for what they can do. */
export function pairStrength(a: number, b: number, rules: HandRules): number {
const e = evalSeotda(a, b, rules);
let s: number;
if (e.value >= 980) s = 0.96 + (e.value - 980) / 500; // 광땡
else if (e.value >= 901) s = 0.8 + (e.value - 900) * 0.015; // 땡
else if (e.value >= 801) s = 0.6 + (e.value - 801) * 0.025; // 알리 … 세륙
else s = 0.12 + e.value * 0.045; // 망통 0.12 … 갑오 0.53
if (e.special === 'ttaengjabi' || e.special === 'gusa') s = Math.max(s, 0.4);
if (e.special === 'mungGusa') s = Math.max(s, 0.5);
if (e.special === 'amhaeng') s = Math.max(s, 0.3);
return s;
const RAISES: BetType[] = ['ping', 'quarter', 'half', 'ddadang', 'full'];
/** How strong a raise of this size usually is (percentile the range centres on). */
const RAISE_T: Partial<Record<BetType, number>> = { ping: 0.35, quarter: 0.45, half: 0.55, ddadang: 0.6, full: 0.68 };
const sigmoid = (x: number) => 1 / (1 + Math.exp(-x));
const myCardsOf = (v: SeotdaView, me: string): number[] =>
(v.seats.find((s) => s.id === me)?.cards ?? []).flatMap((c) => ('id' in c ? [c.id] : []));
const finalSizeOf = (v: SeotdaView): 2 | 3 => (v.options.cardMode === 'three' ? 3 : 2);
/** Opponents still in the hand, each with a range built from the public bets of this (re)match. */
export function rangesOf(v: SeotdaView, me: string): { id: string; weight: RangeWeight }[] {
const rules = rulesOfView(v.options);
const deck = deckOf(v.options);
const finalSize = finalSizeOf(v);
const forced = v.options.betRule === 'free' ? 0 : Number(v.options.betRule[0]);
const live = v.seats.filter((s) => s.id !== me && s.inHand && !s.folded);
// Which log entries were forced (the first `forced` actions of the first round).
let firstRound = 0;
const entries = v.betLog.map((e) => {
const isForced = e.street === 0 && firstRound++ < forced;
return { ...e, forced: isForced };
});
// Cards held when the bet was made: 2장 섯다 1장씩 → 1 card on street 0; 3장 섯다 → 2 of 3 on street 0.
const partialStreet0 = v.options.cardMode === 'three' || v.options.dealMode === 'twoRounds';
return live.map((s) => {
const mine = entries.filter((e) => e.p === s.id && !e.forced);
if (!mine.length) return { id: s.id, weight: () => 1 };
const memo = new Map<number, number>();
const weight: RangeWeight = (cards) => {
const key = cardsKey(cards);
const hit = memo.get(key);
if (hit !== undefined) return hit;
const p = strengthPercentile(cards, rules, deck, finalSize);
let w = 1;
let raises = 0;
for (const e of mine) {
// A bet made with fewer cards tells less about the final hand.
const blur = partialStreet0 && e.street === 0 ? 0.5 : 1;
if (RAISES.includes(e.t)) {
const t = (RAISE_T[e.t] ?? 0.5) + 0.05 * raises;
raises++;
const bluff = 0.22 + (1 - blur) * 0.4;
w *= bluff + (1 - bluff) * sigmoid((p - t) / 0.09);
} else if (e.t === 'call') {
const bluff = 0.45 + (1 - blur) * 0.3;
w *= bluff + (1 - bluff) * sigmoid((p - 0.25) / 0.1);
} else if (e.t === 'check') {
// Strong hands check now and then to trap: cap the top a little.
w *= 1 - 0.3 * blur * sigmoid((p - 0.85) / 0.05);
}
}
memo.set(key, w);
return w;
};
return { id: s.id, weight };
});
}
/** Strength from the cards I hold right now (1 card in 2장 섯다's first round, 2 of 3 before choosing). */
function strength(cards: number[], rules: HandRules, threeMode: boolean): number {
if (cards.length === 1) {
const c = cards[0]!;
const m = monthOf(c);
// 광 and 10월 lead to the big hands; 1·4 to 알리/독사/세륙 and friends.
return isGwang(c) || m === 10 ? 0.5 : m === 1 || m === 4 ? 0.45 : 0.35;
export interface Situation {
equity: number;
/** One card still to come: my equity for each card I may get. */
perDraw: Odds['perDraw'];
/** Cards still to come for me (or the 3장 섯다 third card). */
drawing: boolean;
exact: boolean;
}
export function situation(v: SeotdaView, me: string, random: () => number): Situation {
const finalSize = finalSizeOf(v);
const all = myCardsOf(v, me);
// 3장 섯다 after the secret choice: my hand is the chosen pair, the thrown card is out of play.
const chosen = v.myChosen;
const mine = chosen ? [...chosen] : all;
const ranges = rangesOf(v, me);
const o = odds({
rules: rulesOfView(v.options),
tieRule: v.options.tieRule,
deck: deckOf(v.options),
mine,
dead: chosen ? all.filter((c) => !chosen.includes(c)) : [],
finalSize: chosen ? 2 : finalSize,
oppSize: finalSize,
opponents: ranges.map((r) => r.weight),
random,
});
return { equity: o.equity, perDraw: o.perDraw, drawing: mine.length < (chosen ? 2 : finalSize), exact: o.exact };
}
/**
* What the rest of the hand is worth to me once the pot is `pot`, before I put in more: with a card still to come I look
* at every card I may get — a good one plays on (and may face a 하프 of about half the pot), a bad one dies there and
* loses nothing more. `scale` < 1 when only the stronger part of the others' range is still in.
*/
function continuation(sit: Situation, pot: number, scale = 1): number {
const play = (e: number) => {
const bet = 0.5 * pot;
// Half the time nobody bets on the last round; otherwise I call a 하프 only when it pays.
return 0.5 * e * pot + 0.5 * Math.max(0, e * (pot + 2 * bet) - bet);
};
if (!sit.drawing || !sit.perDraw.length) return Math.min(1, sit.equity * scale) * pot;
let v = 0;
for (const d of sit.perDraw) v += d.weight * play(Math.min(1, d.equity * scale));
return v;
}
/** Expected value (in 원) of each legal bet, from my share of the pot and the others' likely answers. */
export function betValues(v: SeotdaView, me: string, sit: Situation): Map<BetType, number> {
const pot = Math.max(1, v.pot);
const others = v.seats.filter((s) => s.id !== me && s.inHand && !s.folded);
const canAct = others.filter((s) => !s.allIn);
// Players who still have to answer this round's bet (no action yet on this street).
const yetToAct = canAct.filter((s) => !s.lastAction).length;
const out = new Map<BetType, number>();
for (const b of v.legal) {
switch (b.type) {
case 'die':
out.set('die', 0);
break;
case 'check':
// Free: whatever my share of the pot is (tiny edge so it always beats dying).
out.set('check', continuation(sit, pot) + 0.001 * pot);
break;
case 'call': {
const extra = yetToAct * 0.5 * b.amount; // later players calling too
out.set('call', continuation(sit, pot + b.amount + extra) - b.amount);
break;
}
default: {
// A raise of b.amount: each opponent who can act folds with some chance — more often to bigger bets, much less
// often when it has raised this hand itself (it showed strength) or already called.
const size = b.amount / (pot + b.amount);
const foldOf = (id: string) => {
const acts = v.betLog.filter((e) => e.p === id).map((e) => e.t);
const showed = acts.some((t) => RAISES.includes(t) && t !== 'ping') ? 0.35 : acts.includes('call') || acts.includes('ping') ? 0.7 : 1;
return Math.min(0.6, Math.max(0.03, (0.1 + 0.8 * size) * showed));
};
const folds = canAct.map((s) => foldOf(s.id));
const allFold = folds.length ? folds.reduce((a, f) => a * f, 1) : 0;
const meanFold = folds.length ? folds.reduce((a, f) => a + f, 0) / folds.length : 0;
// Those who call are the stronger part of their range: my share against them drops.
const scale = 0.85 - 0.05 * Math.min(3, Math.max(0, canAct.length - 1));
const callers = Math.max(1, canAct.length * (1 - meanFold));
const called = continuation(sit, pot + b.amount + callers * b.amount * 0.8, scale) - b.amount;
out.set(b.type, allFold * pot + (1 - allFold) * called);
break;
}
}
}
let s = 0;
for (let i = 0; i < cards.length; i++) for (let j = i + 1; j < cards.length; j++) s = Math.max(s, pairStrength(cards[i]!, cards[j]!, rules));
// 3장 섯다 first round: a third card is still coming.
return threeMode && cards.length === 2 ? Math.min(1, s + 0.06) : s;
return out;
}
export const seotdaBot: BotStrategy<SeotdaView, SeotdaAction> = ({ me, view, legal, random }) => {
const rules = rulesOf(view.options);
const mine = view.seats.find((x) => x.id === me);
const cards = (mine?.cards ?? []).flatMap((c) => ('id' in c ? [c.id] : []));
export const seotdaBot: BotStrategy<SeotdaView, SeotdaAction> = ({ me, view: v, legal, random, level }) => {
const rules = rulesOfView(v.options);
const mine = v.seats.find((x) => x.id === me);
const first = legal[0]!;
switch (typeOf(first)) {
case 'ready':
return first;
case 'rebuy':
// Keep playing: take the chips while rebuys remain.
return { type: 'rebuy', accept: true };
case 'rejoin': {
// Pay into a 구사 rematch only when it is cheap compared to the pot.
const cheap = !!view.rejoin && view.rejoin.cost <= Math.min(view.pot / 3, (mine?.stack ?? 0) / 5);
return legal.find((a) => a.type === 'rejoin' && a.accept === cheap) ?? first;
// 구사 재경기: pay in when my even share of the bigger pot is worth the price.
const r = v.rejoin;
if (!r || !r.canAfford) return legal.find((a) => a.type === 'rejoin' && !a.accept) ?? first;
const k = (v.seats.filter((s) => s.inHand && !s.folded).length || 2) + 1;
const join = (v.pot + r.cost) / k - r.cost > 0 && r.cost <= (mine?.stack ?? 0) / 3;
return legal.find((a) => a.type === 'rejoin' && a.accept === join) ?? first;
}
case 'choose': {
// 3장 섯다: keep the pair with the best chance (specials such as 땡잡이 included).
// 3장 섯다: keep the pair with the best share of the pot against what the others may hold (specials included).
const chooses = legal.filter((a): a is Extract<SeotdaAction, { type: 'choose' }> => a.type === 'choose');
let top = chooses[0]!;
for (const c of chooses) if (pairStrength(c.cardIds[0], c.cardIds[1], rules) > pairStrength(top.cardIds[0], top.cardIds[1], rules)) top = c;
return top;
const all = myCardsOf(v, me);
const pairScore = (c: Extract<SeotdaAction, { type: 'choose' }>) => pairEquity(v, me, c.cardIds, all, random);
return humanBest(chooses, pairScore, random, level, { small: 0.02, critical: 2 });
}
}
// Betting.
const s = strength(cards, rules, view.options.cardMode === 'three');
const bets = view.legal;
const by = (t: string) => bets.find((b) => b.type === t);
const act = (b: Bet | undefined) => (b ? (legal.find((a) => a.type === b.type) ?? null) : null);
const stack = mine?.stack ?? 0;
const call = by('call');
const toCall = call?.amount ?? 0;
const pot = Math.max(view.pot, 1);
// Raises that keep chips behind unless the hand is a monster.
const raises = bets.filter((b) => ['ping', 'ddadang', 'quarter', 'half', 'full'].includes(b.type) && (!b.allIn || s >= 0.85));
const raise = (big: boolean) => {
const order = big ? ['half', 'full', 'ddadang', 'quarter', 'ping'] : ['ping', 'quarter', 'ddadang', 'half'];
for (const t of order) {
const b = raises.find((r) => r.type === t);
if (b) return act(b);
}
return null;
};
if (!call) {
// Free to check (or open the betting).
if (s >= 0.75) return raise(true) ?? act(by('check'))!;
if ((s >= 0.5 && random() < 0.5) || random() < 0.08) return raise(false) ?? act(by('check'))!;
return act(by('check')) ?? act(by('die'))!;
const sit = situation(v, me, random);
const values = betValues(v, me, sit);
const has = (t: BetType) => values.has(t);
const potNow = Math.max(1, v.pot);
// With a card still to come nothing is settled yet: stay in unless the price is clearly wrong (the 1장 다이 bug: the old
// bot died to a single 하프 after one card). How much worse than break-even a call may be, as a share of its price:
// generous against one raise (it was made on one card too), much less when raise follows raise.
const call = v.legal.find((b) => b.type === 'call');
if (sit.drawing && call && has('call')) {
const raisesNow = v.betLog.filter((e) => e.street === v.street && e.p !== me && RAISES.includes(e.t)).length;
const single = myCardsOf(v, me).length === 1;
const tolerance = raisesNow <= 1 ? (single ? 0.8 : 0.4) : single ? 0.35 : 0.2;
if (values.get('call')! > -tolerance * call.amount) values.set('call', Math.max(values.get('call')!, 0.002 * potNow));
}
// Facing a bet: raise monsters, call when the hand is worth the price, otherwise die.
if (s >= 0.8 && random() < 0.7) {
const r = raise(true);
if (r) return r;
}
const price = toCall / (pot + toCall);
const allInCall = call.allIn || toCall >= stack;
const worth = allInCall ? s >= 0.6 : s >= Math.max(0.3, price + 0.12);
const cheapBluff = toCall <= view.baseUnit && random() < 0.3;
if (worth || cheapBluff) return act(call)!;
return act(by('die')) ?? pick(legal, random);
let pickType: BetType;
const choices = [...values.keys()];
pickType = humanBest(choices, (t) => values.get(t)!, random, level, { small: 0.04 * potNow, critical: Number.POSITIVE_INFINITY });
const raises = choices.filter((t) => RAISES.includes(t));
// A small bluff: rarely, a weak hand raises into players who showed no strength.
const quiet = v.betLog.every((e) => e.p === me || !['half', 'ddadang', 'full', 'quarter'].includes(e.t));
const opp = v.seats.filter((s) => s.id !== me && s.inHand && !s.folded).length;
if (raises.length && quiet && sit.equity < 0.35 && random() < 0.1 / opp) pickType = raises.includes('half') ? 'half' : raises[0]!;
// A trap: a monster sometimes just checks / calls to keep the others in.
if (sit.equity > 0.9 && random() < 0.2 && (has('check') || has('call'))) pickType = has('check') ? 'check' : 'call';
// Never die when checking is free (it can only lose the pot it already put in).
if (pickType === 'die' && has('check')) pickType = 'check';
const chosen: Bet | undefined = v.legal.find((b) => b.type === pickType);
const action = chosen ? legal.find((a) => a.type === chosen.type) : undefined;
return action ?? legal.find((a) => a.type === 'check') ?? pick(legal, random);
};
/** Share of the pot of one 2-card choice (3장 섯다) against the others' possible final hands. */
function pairEquity(v: SeotdaView, me: string, pair: [number, number], all: number[], random: () => number): number {
const rules = rulesOfView(v.options);
const thrown = all.filter((x) => !pair.includes(x));
const ranges = rangesOf(v, me);
// The others hold 3 cards each (best 2); my pair is fixed and my thrown card is out of their reach.
return odds({
rules,
tieRule: v.options.tieRule,
deck: deckOf(v.options),
mine: [...pair],
dead: thrown,
finalSize: 2,
oppSize: 3,
opponents: ranges.map((r) => r.weight),
random,
samples: 1200,
}).equity;
}

View File

@@ -1,4 +1,7 @@
/** 섯다 (docs/games/seotda.md). Chips are room-only play points (§12). */
/**
* 섯다 (docs/games/seotda.md), 한게임 섯다 방식. Amounts are 원 of room-only play money (놀이용 게임머니, §12):
* no real value, no exchange. Internal names (`stack`, `startingChips`, `baseUnit`) predate the 원 wording.
*/
import { z } from 'zod';
import {
HWATU,
@@ -26,29 +29,51 @@ import {
type Rng,
} from '@bg/engine';
import { bestChoice, combos, evalSeotda, hintText, resolve, strengthOf, type HandEval, type HandRules, type SpecialKind } from './hands';
import { formatWon, formatWonDelta } from './money';
export * from './hands';
export * from './money';
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>[]]);
/** Starting money (원). Before 2026-10-13 rooms stored chips (500 … 5000); those fall back to the default (`.catch`). */
export const STARTING_MONEY = [500_000, 1_000_000, 2_000_000, 5_000_000] as const;
/** 기본금 = 판마다 모두 내는 돈 = 삥 (원). */
export const BASE_MONEY = [2_000, 10_000, 20_000, 50_000] as const;
export const seotdaOptionsSchema = z
.object({
cardMode: z
.enum(['two', 'three'])
.default('two')
.meta({ title: '카드 수', labels: { two: '2장 섯다', three: '3장 섯다(3장 받아 2장 고르기)' } }),
.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: '풀까지' } }),
.enum(['oneRound', 'twoRounds'])
.default('oneRound')
.meta({ title: '2장 섯다 패 받기', labels: { oneRound: '2장 한 번에 받고 베팅 1번', twoRounds: '1장씩 두 번 받고 베팅 2번' } }),
deck: lit(20, 40)
.default(20)
.catch(20)
.meta({ title: '화투 장수', labels: { 20: '20장(1~10월 2장씩)', 40: '40장(1~10월 4장씩)' } }),
startingChips: lit(...STARTING_MONEY)
.default(1_000_000)
.catch(1_000_000)
.meta({ title: '시작 금액', labels: { 500000: '50만원', 1000000: '100만원', 2000000: '200만원', 5000000: '500만원' } }),
baseUnit: lit(...BASE_MONEY)
.default(10_000)
.catch(10_000)
.meta({ title: '기본금(판마다 내는 돈, 삥)', labels: { 2000: '2,000원', 10000: '1만원', 20000: '2만원', 50000: '5만원' } }),
betRule: z
.enum(['free', '111', '222', '333', '444'])
.default('free')
.catch('free')
.meta({
title: '베팅 규칙',
labels: { free: '일반 베팅', 111: '111(선은 하프·다이만)', 222: '222(앞 2명 하프·다이만)', 333: '333(앞 3명 하프·다이만)', 444: '444(앞 4명 하프·다이만)' },
}),
maxRaise: z.enum(['half', 'full']).default('half').meta({ title: '최대 베팅', labels: { half: '하프까지', full: '풀(판돈만큼)까지' } }),
quarter: z.boolean().default(false).catch(false).meta({ title: '쿼터 베팅 버튼' }),
endCondition: z
.enum(['hands', 'lastStanding'])
.default('hands')
@@ -58,15 +83,17 @@ export const seotdaOptionsSchema = z
.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판마다' } }),
.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: '무제한' } }),
.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)
turnSeconds: z
.union([z.literal(15), z.literal(20), z.literal(30), z.literal(60), z.literal(null)])
.default(20)
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
.catch(20)
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
dealerRule: z.enum(['winner', 'rotate']).default('winner').meta({ title: '다음 판의 선', labels: { winner: '이긴 사람', rotate: '돌아가며' } }),
gwangTtaeng: z
.enum(['all', 'only38'])
@@ -74,20 +101,20 @@ export const seotdaOptionsSchema = z
.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월 아무 패' } }),
.default('loose')
.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')
.default('upTo9')
.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: '내 족보 이름·족보표 강조' }),
.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번' } }),
@@ -97,7 +124,7 @@ export const seotdaOptionsSchema = z
})
.superRefine((o, ctx) => {
if (o.baseUnit * 20 > o.startingChips) {
ctx.addIssue({ code: 'custom', path: ['baseUnit'], message: '학교는 시작 칩의 20분의 1 이하여야 해요.' });
ctx.addIssue({ code: 'custom', path: ['baseUnit'], message: '기본금은 시작 금액의 20분의 1 이하여야 해요.' });
}
});
export type SeotdaOptions = z.infer<typeof seotdaOptionsSchema>;
@@ -192,6 +219,17 @@ export interface SeotdaHand {
next: 'rematch' | 'nextHand' | null;
ready: PlayerId[];
lastAction: Record<PlayerId, { type: BetType; amount: number }>;
/** 베팅 규칙 111~444: how many more first-round actions are limited to 하프·다이. */
forced: number;
/** Public bet log of this (re)match (everyone saw these bets). */
log: BetLogEntry[];
}
export interface BetLogEntry {
p: PlayerId;
t: BetType;
amount: number;
street: number;
}
export interface HandRecord {
@@ -266,6 +304,8 @@ export interface SeotdaSeatView {
lastAction: { type: BetType; amount: number } | null;
/** Shown after showdown only. */
handName: string | null;
/** Money won or lost in the finished hand (result screen only). */
handDelta: number | null;
}
export interface SeotdaView {
@@ -286,6 +326,10 @@ export interface SeotdaView {
pots: PotState[];
currentBet: number;
legal: { type: BetType; amount: number; allIn: boolean }[];
/** 베팅 규칙 111~444: the player to act may only 하프 or 다이. */
forcedHalf: boolean;
/** Public bets of this (re)match, oldest first. */
betLog: BetLogEntry[];
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;
@@ -305,7 +349,7 @@ export interface SeotdaView {
/** Placeholder better that carries earlier pots so 쿼터/하프/풀 see the whole 모인 칩 (§5.5-2). */
const CARRY = '#carried';
const HAND_END_MS = 4000;
const HAND_END_MS = 5000;
const AWAY_MS = 5000;
const STANDING_CAP = 300;
@@ -328,6 +372,28 @@ const contendersOf = (h: SeotdaHand): PlayerId[] =>
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);
/** 20장: 1~10월의 광·열끗과 띠(8월은 기러기) / 40장: 1~10월 4장 모두 (한게임 "카드 장수"). */
export const SEOTDA_DECK_40: number[] = Array.from({ length: 40 }, (_, i) => i);
export const deckOf = (o: Pick<SeotdaOptions, 'deck'>): number[] => (o.deck === 40 ? SEOTDA_DECK_40 : SEOTDA_DECK);
/** 베팅 규칙 111 → 1 … 444 → 4 limited first-round actions. */
const forcedCount = (o: SeotdaOptions): number => (o.betRule === 'free' ? 0 : Number(o.betRule[0]));
/**
* Legal bets of the shared Korean betting module, narrowed to this room: 쿼터 only when the room turns it on, and under
* 베팅 규칙 111~444 the first players of the first round may only 하프 (or the raise that is left) or 다이.
*/
function betsFor(s: SeotdaState, h: SeotdaHand, idx: number): { type: BetType; amount: number; allIn: boolean }[] {
if (!h.betting) return [];
let out = legalBets(h.betting, idx).map((l) => ({ type: toType(l.kind), amount: l.amount, allIn: l.allIn }));
if (!s.options.quarter) out = out.filter((l) => l.type !== 'quarter');
if (h.forced > 0 && h.street === 0 && out.length) {
const half = out.find((l) => l.type === 'half') ?? out.find((l) => l.type === 'full' || l.type === 'ddadang' || l.type === 'quarter');
const keep = half ?? out.find((l) => l.type === 'call' || l.type === 'check');
out = out.filter((l) => l === keep || l.type === 'die');
}
return out;
}
/** Total chips that must exist: Σ stacks + carried pots + live pot. */
export function chipsTotal(s: SeotdaState): number {
const h = s.hand;
@@ -420,7 +486,7 @@ function startHand(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
phase: 'betting',
dealer,
order,
deck: rng.shuffle(SEOTDA_DECK),
deck: rng.shuffle(deckOf(o)),
cards: Object.fromEntries(order.map((id) => [id, []])),
chosen: Object.fromEntries(order.map((id) => [id, null])),
betting: b,
@@ -437,6 +503,8 @@ function startHand(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
next: null,
ready: [],
lastAction: {},
forced: forcedCount(o),
log: [],
};
s.hand = h;
syncStacks(s);
@@ -456,7 +524,7 @@ function startRematch(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
h.order = order;
h.phase = 'betting';
h.street = 0;
h.deck = rng.shuffle(SEOTDA_DECK);
h.deck = rng.shuffle(deckOf(s.options));
h.cards = Object.fromEntries(order.map((id) => [id, []]));
h.chosen = Object.fromEntries(order.map((id) => [id, null]));
h.showdown = null;
@@ -466,6 +534,8 @@ function startRematch(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
h.rejoinPending = [];
h.rematchSet = [];
h.lastAction = {};
h.forced = forcedCount(s.options);
h.log = [];
let b = newBetting(
order.map((id) => ({ id, stack: seatOf(s, id)!.stack })),
{ style: 'korean', baseUnit: s.baseUnit, koreanMax: s.options.maxRaise },
@@ -738,11 +808,11 @@ function finishGame(s: SeotdaState, events: GameEvent[]): void {
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}`;
summary = `${s.handsPlayed}판 끝. 1위 ${formatWonDelta(sc)}${tie}${best}`;
} else {
summary = `${s.handsPlayed}판 만에 끝났어요. 1위 ${(seatOf(s, top[0]!)?.stack ?? 0).toLocaleString('ko-KR')}칩${best}`;
summary = `${s.handsPlayed}판 만에 끝났어요. 1위 ${formatWon(seatOf(s, top[0]!)?.stack ?? 0)}${best}`;
}
const scoreText = Object.fromEntries(s.seats.map((x) => [x.id, `${(byScore ? scores[x.id]! : x.stack).toLocaleString('ko-KR')}칩`]));
const scoreText = Object.fromEntries(s.seats.map((x) => [x.id, byScore ? formatWonDelta(scores[x.id]!) : formatWon(x.stack)]));
s.final = { ranking, scores, scoreText, summary };
events.push({ type: 'gameEnd', ranking });
}
@@ -756,6 +826,8 @@ function applyBetAction(s: SeotdaState, id: PlayerId, t: BetType, events: GameEv
h.betting = r.state;
h.betSeq += 1;
h.lastAction[id] = { type: t, amount: r.event.amount };
h.log.push({ p: id, t, amount: r.event.amount, street: h.street });
if (h.street === 0 && h.forced > 0) h.forced -= 1;
syncStacks(s);
events.push({ type: 'bet', player: id, kind: t, amount: r.event.amount, allIn: r.event.allIn });
}
@@ -802,6 +874,7 @@ function progress(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
settleFold(s, events);
continue;
}
// 3장 섯다: 2장 → 베팅 → 1장 더 → 3장 중 2장 몰래 고르기 → 마지막 베팅 → 공개.
if (h.street === 0 && s.options.cardMode === 'three') {
deal(h, h.order.filter((id) => contendersOf(h).includes(id)), 1, events);
h.phase = 'choose';
@@ -892,8 +965,9 @@ function refreshDeadline(s: SeotdaState, now: number): void {
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;
// 시간 무제한 방에서도 자리 비움(연속 시간 초과)은 없으니 기다린다.
ms = o.turnSeconds === null ? null : seatOf(s, id)!.away ? AWAY_MS : o.turnSeconds * 1000;
} else if (h.phase === 'choose') ms = o.turnSeconds === null ? null : (o.turnSeconds + 10) * 1000;
else if (h.phase === 'rejoin') ms = o.decisionSeconds * 1000;
else if (h.phase === 'handEnd') ms = HAND_END_MS;
}
@@ -925,10 +999,61 @@ function isBet(t: string): t is BetType {
return (BET_TYPES as string[]).includes(t);
}
/**
* v1 → v2 (2026-10-13, 한게임식 원 표기): amounts were chips (시작 1,000 / 학교 10); now they are 원 at ×1000
* (시작 100만원 / 기본 머니 1만원). Games in progress keep their own rules: 쿼터 stays on, no 베팅 규칙, 20장.
*/
const MONEY_V1 = 1000;
function migrateSeotda(old: unknown, from: number): SeotdaState {
const s = structuredClone(old) as SeotdaState;
if (from >= 2) return s;
const o = s.options as SeotdaOptions & Record<string, unknown>;
s.options = { ...o, deck: 20, betRule: 'free', quarter: true } as SeotdaOptions;
if (s.hand) {
s.hand.forced = 0;
s.hand.log = [];
}
return scaleMoney(s, MONEY_V1);
}
/** Multiplies every amount of a state by `k` (in place): options, stacks, pots, bets, history. Integers stay integers for k ≥ 1. */
export function scaleMoney(s: SeotdaState, k: number): SeotdaState {
const m = (n: number) => Math.round(n * k);
s.options = { ...s.options, startingChips: m(s.options.startingChips), baseUnit: m(s.options.baseUnit) } as SeotdaOptions;
s.baseUnit = m(s.baseUnit);
for (const x of s.seats) {
x.stack = m(x.stack);
x.stackAtHandStart = m(x.stackAtHandStart);
}
for (const r of s.history) r.amount = m(r.amount);
if (s.stats.biggestPot) s.stats.biggestPot.amount = m(s.stats.biggestPot.amount);
const h = s.hand;
if (h) {
for (const p of h.carried) p.amount = m(p.amount);
h.rejoinCost = m(h.rejoinCost);
if (h.foldWin) h.foldWin.amount = m(h.foldWin.amount);
if (h.showdown) for (const p of h.showdown.pots) p.amount = m(p.amount);
for (const a of Object.values(h.lastAction)) a.amount = m(a.amount);
for (const e of h.log ?? []) e.amount = m(e.amount);
const b = h.betting;
if (b) {
b.baseUnit = m(b.baseUnit);
b.currentBet = m(b.currentBet);
b.lastRaise = m(b.lastRaise);
for (const p of b.players) {
p.stack = m(p.stack);
p.round = m(p.round);
p.total = m(p.total);
}
}
}
return s;
}
// ---------------------------------------------------------------- definition
export function playerRange(o: Pick<SeotdaOptions, 'cardMode'>): { min: number; max: number } {
return { min: 2, max: o.cardMode === 'three' ? 6 : 10 };
export function playerRange(o: Pick<SeotdaOptions, 'cardMode' | 'deck'>): { min: number; max: number } {
return { min: 2, max: o.cardMode === 'three' && o.deck !== 40 ? 6 : 10 };
}
export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, SeotdaOptions> = {
@@ -936,7 +1061,8 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
nameKo: '섯다',
minPlayers: 2,
maxPlayers: 10,
stateVersion: 1,
stateVersion: 2,
migrate: migrateSeotda,
defaultOptions: seotdaOptionsSchema.parse({}),
optionsSchema: seotdaOptionsSchema as unknown as z.ZodType<SeotdaOptions>,
actionSchema: seotdaActionSchema as unknown as z.ZodType<SeotdaAction>,
@@ -986,7 +1112,7 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
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('지금은 칩을 다시 받을 수 없어요.');
if (s.phase !== 'rebuy' || !s.rebuyPending.includes(actor)) return fail('지금은 시작 금액을 다시 받을 수 없어요.');
return ok;
}
const h = s.hand;
@@ -996,7 +1122,9 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
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 (!err && betsFor(s, h, idx).some((l) => l.type === a.type)) return ok;
if (!err && a.type === 'quarter' && !s.options.quarter) return fail('이 방은 쿼터 베팅을 쓰지 않아요.');
if (!err) return fail(`베팅 규칙 ${s.options.betRule}: 지금은 하프 또는 다이만 할 수 있어요.`);
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('누가 이미 걸어서 삥을 할 수 없어요.');
@@ -1017,7 +1145,7 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
}
case 'rejoin': {
if (h.phase !== 'rejoin' || !h.rejoinPending.includes(actor)) return fail('재참가 대상이 아니에요.');
if (a.accept && st.stack < h.rejoinCost) return fail('칩이 모자라 재참가할 수 없어요.');
if (a.accept && st.stack < h.rejoinCost) return fail('보유 금액이 모자라 재참가할 수 없어요.');
return ok;
}
case 'ready': {
@@ -1070,7 +1198,9 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
events.push({ type: 'timeout', player: actor });
if (phase === 'betting') {
const b = h!.betting!;
applyBetAction(s, actor, toType(timeoutBet(b, betterIdx(h!, actor)).kind), events);
const idx = betterIdx(h!, actor);
const t = toType(timeoutBet(b, idx).kind);
applyBetAction(s, actor, betsFor(s, h!, idx).some((l) => l.type === t) ? t : 'die', 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);
@@ -1122,14 +1252,13 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
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,
handDelta: h?.phase === 'handEnd' && h.next === 'nextHand' && inHand ? x.stack - x.stackAtHandStart : 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 }))
: [];
h && b && myIdx >= 0 && h.phase === 'betting' && !seatOf(s, me!)!.left ? betsFor(s, h, myIdx) : [];
let myHand: SeotdaView['myHand'] = null;
let myCombos: SeotdaView['myCombos'] = null;
let myDiscard: SeotdaCardView | null = null;
@@ -1176,6 +1305,8 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
pots,
currentBet: b?.currentBet ?? 0,
legal,
forcedHalf: !!h && h.phase === 'betting' && h.street === 0 && h.forced > 0,
betLog: h?.log ?? [],
myHand,
myCombos,
myChosen,
@@ -1238,7 +1369,7 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
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);
return betsFor(s, h, idx).map((l) => ({ type: l.type }) as SeotdaAction);
}
case 'choose':
if (!contendersOf(h).includes(p) || h.chosen[p]) return [];

View File

@@ -0,0 +1,45 @@
/**
* 섯다 금액 표기 (docs/games/seotda.md §2, §9): 한게임 섯다처럼 "원"으로, 큰 수는 만·억 단위로 끊어 읽는다.
* 방 안에서만 쓰는 놀이용 게임머니라 실제 돈과는 상관없다(§12).
*/
/** 1234 → "1,234원", 15_000 → "1만 5,000원", 123_450_000 → "1억 2,345만원", 0 → "0원". */
export function formatWon(n: number, unit = '원'): string {
const neg = n < 0;
let v = Math.abs(Math.round(n));
if (v === 0) return `0${unit}`;
const parts: string[] = [];
const jo = Math.floor(v / 1e12);
v -= jo * 1e12;
const eok = Math.floor(v / 1e8);
v -= eok * 1e8;
const man = Math.floor(v / 1e4);
const rest = v - man * 1e4;
if (jo) parts.push(`${jo.toLocaleString('ko-KR')}조`);
if (eok) parts.push(`${eok.toLocaleString('ko-KR')}억`);
if (man) parts.push(`${man.toLocaleString('ko-KR')}만`);
if (rest) parts.push(rest.toLocaleString('ko-KR'));
return `${neg ? '-' : ''}${parts.join(' ')}${unit}`;
}
/** Signed change: "+1만 5,000원" / "-3,000원" / "0원". */
export function formatWonDelta(n: number): string {
return n > 0 ? `+${formatWon(n)}` : formatWon(n);
}
/** Short form for tight spots (seat boxes on phones): "1억 2,345만", "12만 3,000" → "12.3만", under 1만 as is. */
export function formatWonShort(n: number): string {
const v = Math.abs(Math.round(n));
const sign = n < 0 ? '-' : '';
if (v >= 1e8) {
const eok = Math.floor(v / 1e8);
const man = Math.floor((v % 1e8) / 1e4);
return `${sign}${eok.toLocaleString('ko-KR')}억${man ? ` ${man.toLocaleString('ko-KR')}만` : ''}`;
}
if (v >= 1e4) {
const man = v / 1e4;
const txt = Number.isInteger(man) ? man.toLocaleString('ko-KR') : (Math.floor(man * 10) / 10).toLocaleString('ko-KR');
return `${sign}${txt}만`;
}
return `${sign}${v.toLocaleString('ko-KR')}`;
}

View File

@@ -0,0 +1,308 @@
/**
* 섯다 승률 계산 (docs/games/seotda.md §8.7): from what one player can see (own cards, the room's deck, how many
* cards everyone holds, the public bets), enumerate every way the unseen cards can fall and add up the share of the pot
* this player gets at the showdown — 땡잡이·암행어사·구사 재경기·동점 included (the real `resolve`).
*
* The deck is tiny (20 or 40 cards), so heads-up and most 3-handed spots are enumerated exactly (≤ EXACT_LIMIT deals);
* bigger tables fall back to a fixed number of random deals. Pure CPU work, a few ms per decision.
*/
import { bestChoice, evalSeotda, gusaThreshold, type HandEval, type HandRules } from './hands';
/** Joint deals enumerated exactly up to this many; above it, `SAMPLES` random deals. */
export const EXACT_LIMIT = 30_000;
export const SAMPLES = 3_000;
/** Weight of an opponent's possible final hand (its cards, e.g. from the betting so far); 1 = no information. */
export type RangeWeight = (cards: number[]) => number;
export interface OddsInput {
rules: HandRules;
tieRule: 'rematch' | 'split';
/** The room's whole deck (20 or 40 ids). */
deck: number[];
/** Cards I hold now. */
mine: number[];
/** Cards each player holds at the showdown: 2 (2장 섯다) or 3 (3장 섯다, best 2 of 3). */
finalSize: 2 | 3;
/** Cards each opponent holds at the showdown when it differs from mine (3장 섯다 after I chose my pair). */
oppSize?: 2 | 3;
/** One entry per opponent still in the hand. */
opponents: RangeWeight[];
/** Cards I can see that nobody can hold any more (none in 섯다 today; kept for 3장 섯다 open cards). */
dead?: number[];
random?: () => number;
/** Random deals when the table is too big to enumerate (default `SAMPLES`). */
samples?: number;
}
export interface Odds {
/** Expected share of the pot at the showdown (win 1, split 1/k, rematch 1/k of the participants). */
equity: number;
/** Probability of winning the pot outright. */
win: number;
/** Probability of a rematch / split that includes me. */
tie: number;
/** Probability of losing the pot. */
lose: number;
/** Weighted number of deals looked at, and whether every deal was enumerated. */
deals: number;
exact: boolean;
/** When I still get one card: my equity for each card I may get (weights = how likely, given the others' ranges). */
perDraw: { card: number; equity: number; weight: number }[];
}
/** Order-independent numeric key of 2–3 card ids (< 64). */
export function cardsKey(cards: readonly number[]): number {
let a = cards[0]!;
let b = cards[1]!;
let c = cards.length > 2 ? cards[2]! : -1;
if (a > b) [a, b] = [b, a];
if (c >= 0) {
if (b > c) [b, c] = [c, b];
if (a > b) [a, b] = [b, a];
return 1 + a * 4096 + b * 64 + c + 300_000;
}
return a * 64 + b;
}
// ---------------------------------------------------------------- evaluation tables
const handCaches = new Map<string, Map<number, HandEval>>();
const rulesKey = (r: HandRules) => `${r.gwangTtaeng}|${r.ttaengjabi}|${r.amhaeng}|${r.gusa}|${r.mungGusa}`;
/** The showdown hand of a set of final cards (2 cards, or the best 2 of 3 as the automatic choice picks them). Cached. */
export function finalHand(cards: readonly number[], rules: HandRules): HandEval {
const rk = rulesKey(rules);
let t = handCaches.get(rk);
if (!t) {
t = new Map();
handCaches.set(rk, t);
}
const key = cardsKey(cards);
let h = t.get(key);
if (!h) {
const pair = cards.length === 2 ? cards : bestChoice([...cards], rules);
h = evalSeotda(pair[0]!, pair[1]!, rules);
t.set(key, h);
}
return h;
}
/**
* My share of the pot when these hands meet at the showdown (index 0 = me): 1 for a win, 1/k for a split or a rematch
* among k players, 0 for a loss. Same judgement as `resolve` (땡잡이, 암행어사, 구사 재경기), without allocations.
*/
export function shareOf(hands: readonly HandEval[], rules: HandRules, _tieRule: 'rematch' | 'split' = 'rematch'): number {
const n = hands.length;
let vmax = -1;
let tj = false;
let am = false;
for (const h of hands) {
if (h.value > vmax) vmax = h.value;
if (h.special === 'ttaengjabi') tj = true;
else if (h.special === 'amhaeng') am = true;
}
const mode = tj && vmax >= 901 && vmax <= 909 ? 1 : am && (vmax === 980 || vmax === 990) ? 2 : 0;
const inW = (h: HandEval) => (mode === 1 ? h.special === 'ttaengjabi' : mode === 2 ? h.special === 'amhaeng' : h.value === vmax);
let w = 0;
for (const h of hands) if (inW(h)) w++;
for (let i = 0; i < n; i++) {
const h = hands[i]!;
if ((h.special !== 'gusa' && h.special !== 'mungGusa') || inW(h)) continue;
const t = gusaThreshold(h.special, rules);
let best = -1;
for (let j = 0; j < n; j++) if (j !== i && hands[j]!.value > best) best = hands[j]!.value;
if (t !== null && best <= t) return 1 / n;
}
return inW(hands[0]!) ? 1 / w : 0;
}
// ---------------------------------------------------------------- enumeration
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function choose(n: number, k: number): number {
let r = 1;
for (let i = 0; i < k; i++) r = (r * (n - i)) / (i + 1);
return Math.round(r);
}
/** All k-subsets of `pool` (k ≤ 3). */
function subsets(pool: number[], k: number): number[][] {
const out: number[][] = [];
const n = pool.length;
if (k === 0) return [[]];
if (k === 1) return pool.map((x) => [x]);
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++) {
if (k === 2) out.push([pool[i]!, pool[j]!]);
else for (let l = j + 1; l < n; l++) out.push([pool[i]!, pool[j]!, pool[l]!]);
}
return out;
}
export function odds(input: OddsInput): Odds {
const { rules, tieRule, finalSize, opponents } = input;
const oppSize = input.oppSize ?? finalSize;
const seen = new Set([...input.mine, ...(input.dead ?? [])]);
const pool = input.deck.filter((c) => !seen.has(c));
const need = finalSize - input.mine.length;
const n = opponents.length;
const acc = { w: 0, eq: 0, win: 0, tie: 0, lose: 0 };
const draws = new Map<number, { w: number; eq: number }>();
const handOf = (cards: number[]) => finalHand(cards, rules);
const score = (myCards: number[], opp: number[][], weight: number) => {
if (weight <= 0) return;
const hands = [handOf(myCards), ...opp.map(handOf)];
const s = n === 0 ? 1 : shareOf(hands, rules, tieRule);
acc.w += weight;
acc.eq += weight * s;
if (need === 1) {
const c = myCards[myCards.length - 1]!;
const d = draws.get(c) ?? { w: 0, eq: 0 };
d.w += weight;
d.eq += weight * s;
draws.set(c, d);
}
if (s === 1) acc.win += weight;
else if (s > 0) acc.tie += weight;
else acc.lose += weight;
};
// How many joint deals there are: my missing cards, then each opponent's whole hand.
let total = choose(pool.length, Math.max(0, need));
let left = pool.length - Math.max(0, need);
for (let i = 0; i < n; i++) {
total *= choose(left, oppSize);
left -= oppSize;
}
const exact = left >= 0 && total <= (input.samples !== undefined ? Math.min(EXACT_LIMIT, input.samples * 4) : EXACT_LIMIT);
if (exact) {
const mineOpts = subsets(pool, Math.max(0, need));
for (const extra of mineOpts) {
const myCards = [...input.mine, ...extra];
const rest = pool.filter((c) => !extra.includes(c));
const rec = (i: number, avail: number[], opp: number[][], w: number) => {
if (i === n) return score(myCards, opp, w);
for (const h of subsets(avail, oppSize)) {
const wi = opponents[i]!(h);
if (wi <= 0) continue;
rec(
i + 1,
avail.filter((c) => !h.includes(c)),
[...opp, h],
w * wi,
);
}
};
rec(0, rest, [], 1);
}
} else {
// Own PRNG seeded once from the caller's: stays well spread even if `random` is a stub (tests).
const random = mulberry32(Math.floor((input.random ?? Math.random)() * 0x100000000) ^ 0x9e3779b9);
const deck = [...pool];
const take = Math.max(0, need) + n * oppSize;
for (let s = 0; s < (input.samples ?? SAMPLES); s++) {
// Partial Fisher–Yates: only the cards we need.
for (let i = 0; i < Math.min(take, deck.length - 1); i++) {
const j = i + Math.floor(random() * (deck.length - i));
const t = deck[i]!;
deck[i] = deck[j]!;
deck[j] = t;
}
const myCards = [...input.mine, ...deck.slice(0, Math.max(0, need))];
const opp: number[][] = [];
let w = 1;
let at = Math.max(0, need);
for (let i = 0; i < n; i++) {
const h = deck.slice(at, at + oppSize);
at += oppSize;
opp.push(h);
w *= opponents[i]!(h);
}
score(myCards, opp, w);
}
}
if (acc.w <= 0) return { equity: 1 / (n + 1), win: 0, tie: 0, lose: 0, deals: 0, exact, perDraw: [] };
const perDraw = [...draws.entries()].map(([card, d]) => ({ card, equity: d.w > 0 ? d.eq / d.w : 0, weight: d.w / acc.w }));
return { equity: acc.eq / acc.w, win: acc.win / acc.w, tie: acc.tie / acc.w, lose: acc.lose / acc.w, deals: acc.w, exact, perDraw };
}
// ---------------------------------------------------------------- hand strength percentiles (for ranges)
const pctCache = new Map<string, Map<string, number>>();
const pctFast = new Map<string, Map<number, number>>();
/**
* Where a final hand stands among all hands of the deck (0 = weakest, 1 = 38광땡), by its heads-up equity against a
* random hand. Used to turn bets into ranges ("a 하프 usually means a strong hand").
*/
export function strengthPercentile(cards: readonly number[], rules: HandRules, deck: readonly number[], finalSize: 2 | 3): number {
const key = `${rulesKey(rules)}|${deck.length}|${finalSize}`;
let fast = pctFast.get(key);
if (!fast) {
fast = new Map();
pctFast.set(key, fast);
}
const ck = cardsKey(cards);
const hit = fast.get(ck);
if (hit !== undefined) return hit;
let t = pctCache.get(key);
if (!t) {
t = buildPercentiles(rules, [...deck], finalSize);
pctCache.set(key, t);
}
const p = t.get(handKey(finalHand(cards, rules))) ?? 0.5;
fast.set(ck, p);
return p;
}
const handKey = (h: HandEval) => `${h.value}|${h.special ?? ''}`;
/**
* Hands are grouped by (value, special) — cards of the same month and kind behave the same. Each group's strength is its
* heads-up equity against every other pair of the deck; the percentile is the share of pairs with a lower equity.
*/
function buildPercentiles(rules: HandRules, deck: number[], _finalSize: 2 | 3): Map<string, number> {
const pairs = subsets(deck, 2);
const evals = pairs.map(([a, b]) => finalHand([a!, b!], rules));
const groups = new Map<string, { eq: number; n: number; count: number }>();
for (let i = 0; i < pairs.length; i++) {
const k = handKey(evals[i]!);
let g = groups.get(k);
if (!g) {
g = { eq: 0, n: 0, count: 0 };
groups.set(k, g);
// Equity of this representative against every disjoint pair.
const [a, b] = pairs[i]!;
for (let j = 0; j < pairs.length; j++) {
const [c, d] = pairs[j]!;
if (c === a || c === b || d === a || d === b) continue;
g.eq += shareOf([evals[i]!, evals[j]!], rules, 'rematch');
g.n += 1;
}
}
g.count += 1;
}
const list = [...groups.entries()].map(([k, g]) => ({ k, eq: g.eq / Math.max(1, g.n), count: g.count }));
list.sort((x, y) => x.eq - y.eq);
const total = list.reduce((s, x) => s + x.count, 0);
const out = new Map<string, number>();
let below = 0;
for (const x of list) {
// Middle of the group's band.
out.set(x.k, (below + x.count / 2) / total);
below += x.count;
}
return out;
}

View File

@@ -5,6 +5,7 @@ import {
chipsTotal,
evalSeotda,
resolve,
scaleMoney,
seotda,
type HandEval,
type HandRules,
@@ -25,12 +26,29 @@ const ev = (a: number, b: number, r: Partial<HandRules> = {}) => evalSeotda(a, b
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). */
function make(opts: Partial<SeotdaOptions> = {}, players = ['A', 'B', 'C'], dealer = 'A'): SeotdaState {
const options = seotda.optionsSchema.parse(opts);
/**
* 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 s;
if (s.hand!.dealer === dealer) return scaleMoney(s, 1 / 1000);
}
throw new Error('no seed with that dealer');
}
@@ -350,7 +368,7 @@ describe('재경기', () => {
expect(s.stats.rematches).toBe(1);
});
function gusaHand(opts: Partial<SeotdaOptions>) {
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' });
@@ -377,7 +395,7 @@ describe('재경기', () => {
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(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']);
@@ -547,7 +565,7 @@ describe('timeouts, away, leaving', () => {
describe('rebuy, elimination, scores', () => {
/** Ends the current hand by folds, then sets stacks before the hand-end processing. */
function toHandEnd(opts: Partial<SeotdaOptions>, players = ['A', 'B', 'C']): SeotdaState {
function toHandEnd(opts: OldOpts, players = ['A', 'B', 'C']): SeotdaState {
let s = make({ dealMode: 'oneRound', ...opts }, players);
while (s.hand!.phase !== 'handEnd') s = act(s, seotda.activePlayers(s)[0]!, { type: 'die' });
return s;
@@ -617,10 +635,132 @@ describe('rebuy, elimination, scores', () => {
});
});
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' });
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' });
const v = seotda.view(s, null);
expect(v.foldWin).toEqual({ winner: 'A', amount: 30_000 });
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(2);
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', () => {
expect(seotda.defaultOptions).toMatchObject({ cardMode: 'two', dealMode: 'twoRounds', startingChips: 1000, baseUnit: 10, rebuy: 'unlimited' });
expect(seotda.optionsSchema.safeParse({ startingChips: 500, baseUnit: 50 }).success).toBe(false);
// 한게임 섯다처럼: 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();
@@ -650,8 +790,10 @@ describe('random playouts', () => {
['기본', {}, 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, startingChips: 1000 }, 3, 4],
['10명·전액 재참가', { rejoinCost: 'full', mungGusa: 'upToJang', handLimit: 10, startingChips: 500, baseUnit: 2 }, 10, 2],
['최후 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) => {
@@ -673,7 +815,12 @@ describe('random playouts', () => {
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' });
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 });