Merge branch 'wip/game-hot-streak' into codex/owner/grp_discord_joke-app

# Conflicts:
#	apps/web/src/games/help.test.ts
#	apps/web/src/games/registry.ts
#	apps/web/src/lib/catalog-ui.ts
#	docs/games/README.md
#	e2e/games.e2e.ts
#	packages/games/package.json
#	packages/games/src/bots/index.ts
#	packages/games/src/index.ts
#	packages/shared/src/bots.ts
#	packages/shared/src/catalog.ts
This commit is contained in:
EJClaw
2026-10-15 23:29:17 +09:00
26 changed files with 5216 additions and 2 deletions

View File

@@ -40,6 +40,7 @@ import { magicalAthleteBot } from '../magical-athlete/bot';
import { blackjackBot } from '../blackjack/bot';
import { sixNimmtBot } from '../six-nimmt/bot';
import { gembloBot } from '../gemblo/bot';
import { hotStreakBot } from '../hot-streak/bot';
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -77,6 +78,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
blackjack: blackjackBot,
'six-nimmt': sixNimmtBot,
gemblo: gembloBot,
'hot-streak': hotStreakBot,
};
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */

View File

@@ -0,0 +1,99 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots';
import { botPlayout } from '../bots/playout';
import { hotStreakBot, runsFor, ticketEv } from './bot';
import { hotStreak as def, type HotStreakAction, type HotStreakOptions, type HotStreakState } from './index';
import { seededRng, simulate } from './sim';
const isBot = (p: string) => p.startsWith('bot:');
const seats = (n: number, humans: number) => Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i}:x`));
const opts = (o: Partial<HotStreakOptions> = {}) => def.optionsSchema.parse({ ...def.defaultOptions, ...o });
describe('핫스트릭 컴퓨터', () => {
test('시뮬레이션 횟수: 레벨 1은 30번, 60은 400번', () => {
expect(runsFor(1)).toBe(30);
expect(runsFor(60)).toBe(400);
expect(runsFor(30)).toBeGreaterThan(30);
});
test('몬테카를로: 시작 카드만 많은 덱이면 마스코트 넷이 고르게, 등수 분포 합은 시행 수', () => {
const st = simulate(() => ['G-S2', 'H-S2', 'D-S2', 'M-S2', 'A1a', 'A1b', 'A2a', 'A2b', 'A3a', 'A3b', 'G-F3', 'H-F3', 'D-F3', 'M-F3', 'G-F2', 'H-F2', 'D-F2', 'M-F2'], 200, { burn: 3, hurdles: false, side: 'any-dq' }, seededRng(5));
for (const m of ['G', 'H', 'D', 'M'] as const) expect(st.low[m].reduce((a, b) => a + b, 0)).toBe(200);
// Lots of 3s for 고블러 only → 고블러 wins more often.
const g = simulate(() => ['G-S2', 'H-S2', 'D-S2', 'M-S2', 'G-F3', 'G-F2', 'G-W1', 'G-ST', 'A1a', 'A1b', 'H-TA', 'D-TA', 'M-TA', 'H-B2', 'D-B2', 'M-B2', 'A2a', 'A2b'], 300, { burn: 3, hurdles: false, side: 'any-dq' }, seededRng(6));
expect(g.low.G[0]! / 300).toBeGreaterThan(0.5);
expect(ticketEv({ stack: 'G', tier: 1, side: 'risky', reverse: false }, g)).toBeGreaterThan(ticketEv({ stack: 'M', tier: 1, side: 'risky', reverse: false }, g));
});
for (const level of [1, 60]) {
for (const n of [2, 3, 6, 9, 10]) {
test(`레벨 ${level}, ${n}명: 컴퓨터끼리 끝까지, 모든 수 합법, 한 수가 빠름`, () => {
const r = botPlayout(def, { players: seats(n, 0), seed: seedN(n + level), isBot, level, maxSteps: 20_000 });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
expect(r.maxBotMs).toBeLessThan(level === 60 ? 120 : 60);
});
}
}
test('하우스 룰 조합(거꾸로·2장·상금 나누기 두 배)에서도 합법한 수만', () => {
for (const o of [{ reverseBets: true, cardsPerRace: 2 as const, races: 1 as const }, { bettingMode: 'pots' as const, reverseBets: true, races: 1 as const }, { finalBet: 'bothBonus' as const, hurdles: true }]) {
const r = botPlayout(def, { players: seats(4, 1), options: opts(o), seed: seedN(77), isBot, level: 30, maxSteps: 20_000 });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
}
});
test('레벨 60은 아무렇게나 고르는 사람보다 돈을 더 많이 벌어요', () => {
let bot = 0;
let rnd = 0;
for (let g = 1; g <= 12; g++) {
const players = ['bot:0:x', 'rand1', 'bot:2:x', 'rand3'];
const rng = SeededRng.fromSeed(seedN(300 + g));
const pick = SeededRng.fromSeed(seedN(400 + g));
let s: HotStreakState = def.setup({ players, options: def.defaultOptions, rng, now: 0 });
let now = 0;
for (let step = 0; step < 5000 && !def.result(s); step++) {
now += 500;
const p = def.activePlayers(s)[0] ?? def.timeoutPlayers!(s)[0]!;
let a: HotStreakAction;
if (s.phase === 'race' || s.phase === 'payout') a = { type: 'TIMEOUT' };
else if (isBot(p)) a = decideBotAction(def, s, p, { now, random: () => pick.next(), level: 60 }) as HotStreakAction;
else {
const legal = def.legalActions!(s, p);
a = legal[pick.int(legal.length)]!;
}
now = Math.max(now, s.phase === 'race' ? s.race!.nextFlipAt : now);
s = def.apply(s, p, a, { rng, now }).state;
}
expect(def.result(s)).not.toBeNull();
bot += s.money['bot:0:x']! + s.money['bot:2:x']!;
rnd += s.money.rand1! + s.money.rand3!;
}
expect(bot).toBeGreaterThan(rnd);
}, 60_000);
test('카드 넣기: 내가 건 마스코트를 미는 카드를 골라요', () => {
const s = def.setup({ players: ['bot:0:x', 'b'], options: opts({ races: 1, finalBet: 'none' }), rng: SeededRng.fromSeed(seedN(3)), now: 0 });
s.phase = 'submit';
s.tickets['bot:0:x'] = [
{ stack: 'D', tier: 1, side: 'risky', reverse: false, doubled: false },
{ stack: 'D', tier: 2, side: 'risky', reverse: false, doubled: false },
];
s.hands['bot:0:x'] = ['D-F3#1', 'D-FD#1', 'D-B2#1', 'D-TA#1'];
s.hands.b = s.hands.b!.filter((c) => !c.startsWith('D-'));
s.pool = s.pool.filter((c) => !c.startsWith('D-') || c.startsWith('D-S2'));
while (s.pool.length < 14) s.pool.push(`A1a#9${s.pool.length}`);
const legal = def.legalActions!(s, 'bot:0:x');
let fd = 0;
for (let i = 0; i < 6; i++) {
const r = SeededRng.fromSeed(seedN(i));
const a = hotStreakBot({ me: 'bot:0:x', view: def.view(s, 'bot:0:x'), legal, random: () => r.next(), level: 60 }) as Extract<HotStreakAction, { type: 'SUBMIT' }>;
expect(a.type).toBe('SUBMIT');
expect(a.cards).toHaveLength(2);
if (a.cards.includes('D-FD#1') && a.cards.includes('D-TA#1')) fd++;
}
expect(fd).toBe(0);
});
});

View File

@@ -0,0 +1,118 @@
/**
* 핫스트릭 컴퓨터 (docs/games/hot-streak.md §8.7). Only its own view: it guesses the race deck from the face-up list,
* the cards seen last race and its own hand, runs the race many times (레벨 1: 30번 … 60: 400번) and
* - 티켓: 안전·위험(·거꾸로) 면의 기대 달러가 가장 큰 것, 마지막 경주 두 배는 기대값이 가장 큰 티켓,
* - 카드 넣기: 넣었을 때 내 티켓 기대 수익이 가장 큰 카드(같은 셔플로 비교),
* - 상금 나누기: 상금 기대값이 큰 마스코트 + 확률이 높은 쪽 YES/NO.
* Lower levels slip to a slightly worse choice now and then (`humanBest`, small = $1, no critical moves).
*/
import type { Rng } from '@bg/engine';
import type { BotStrategy } from '../bots/types';
import { humanBest, playable } from '../bots/policy';
import { ALL_CARDS, SIDE_PAY, isMascot, mascotPay, type CardBase, type MascotId } from './cards';
import { LAST_POT, POT_PRIZES, SIDE_POT, type HotStreakAction, type Ticket } from './rules';
import { sampleDeck, seededRng, simulate, type DeckModel, type SimStats } from './sim';
import type { HotStreakView } from './index';
type Act = HotStreakAction;
const SCALE = { small: 1, critical: Infinity };
/** Simulated races for a decision at this level (1 → 30, 60 → 400). */
export const runsFor = (level: number | undefined): number => {
const l = Math.min(60, Math.max(1, level ?? 30));
return Math.round(30 + ((l - 1) / 59) * 370);
};
/** What the bot can tell about the coming race deck (public info + its own hand). */
export function deckModel(v: HotStreakView, me: string): { model: DeckModel; mine: CardBase[]; put: CardBase[] | null; k: number } {
const mine = v.hand?.map((c) => c.base) ?? [];
const put = v.myPut;
const k = v.perRace;
const n = v.seats.length;
if (v.mode === 'pots' || v.faceUp.length) {
const fixed = [...v.faceUp];
const shown = new Set([...fixed, ...mine, ...(put ?? [])]);
return { model: { fixed, likely: [], likelyN: 0, unknown: ALL_CARDS.filter((c) => !shown.has(c)) }, mine, put, k };
}
// Later races: the deck is last race's cards minus the dealt ones, plus everyone's put-in cards.
const shown = new Set([...mine, ...(put ?? [])]);
const likely = v.seenLast.filter((c) => !shown.has(c));
return {
model: { fixed: [], likely, likelyN: 18 - n * k, unknown: ALL_CARDS.filter((c) => !shown.has(c) && !likely.includes(c)) },
mine,
put,
k,
};
}
const pickK = (cards: CardBase[], k: number, rng: Rng) => rng.shuffle(cards).slice(0, k);
/** Expected dollars of one ticket from the place / side odds. */
export function ticketEv(t: Pick<Ticket, 'stack' | 'tier' | 'side' | 'reverse'>, st: SimStats): number {
if (isMascot(t.stack)) {
const dist = t.reverse ? st.high[t.stack] : st.low[t.stack];
let ev = 0;
for (let r = 1; r <= 4; r++) ev += (dist[r - 1]! / st.runs) * mascotPay(t.tier, t.side, r, t.reverse);
return ev;
}
const p = st.yes / st.runs;
const right = t.stack === 'YES' ? p : 1 - p;
const pay = SIDE_PAY[t.tier][t.side];
return right * pay.win + (1 - right) * pay.lose;
}
const potEv = (v: HotStreakView, m: MascotId, last: boolean, st: SimStats): number => {
const scale = v.options.potScale;
const share = 1 + (v.seats.length - 1) / 4;
if (last) return ((st.low[m][3]! / st.runs) * LAST_POT * scale) / share;
let ev = 0;
for (let r = 1; r <= 3; r++) ev += (st.low[m][r - 1]! / st.runs) * POT_PRIZES[r - 1]! * scale;
return ev / share;
};
export const hotStreakBot: BotStrategy<HotStreakView, Act> = ({ me, view: v, legal, random, level }) => {
const acts = playable(legal) as Act[];
const choose = (score: (a: Act) => number) => humanBest(acts, (a) => score(a) + random() * 1e-3, random, level, SCALE);
const only = acts.find((a) => a.type === 'HURRY' || a.type === 'READY');
if (only) return only;
const runs = runsFor(level);
const opts = { burn: v.options.burn, hurdles: v.options.hurdles, side: v.side.id };
const { model, mine, put, k } = deckModel(v, me);
const seed = Math.floor(random() * 2 ** 32);
if (acts[0]?.type === 'SUBMIT') {
const cands = acts.filter((a): a is Extract<Act, { type: 'SUBMIT' }> => a.type === 'SUBMIT');
const per = Math.max(20, Math.round((runs * 1.5) / cands.length));
const ids = new Map(v.hand!.map((c) => [c.id, c.base]));
const mineT = v.tickets[me] ?? [];
const ev = new Map<Act, number>();
for (const a of cands) {
const bases = a.cards.map((c) => ids.get(c)!);
const st = simulate((rng) => sampleDeck(model, bases, rng), per, opts, seededRng(seed));
ev.set(a, mineT.reduce((t, x) => t + ticketEv(x, st) * (x.doubled ? 2 : 1), 0));
}
return choose((a) => ev.get(a) ?? -99);
}
const st = simulate((rng) => sampleDeck(model, put ?? pickK(mine, k, rng), rng), runs, opts, seededRng(seed));
if (acts[0]?.type === 'DRAFT') {
return choose((a) => (a.type === 'DRAFT' ? ticketEv({ stack: a.stack, tier: v.stacks[a.stack][0]!, side: a.side, reverse: !!a.reverse }, st) : -99));
}
if (acts[0]?.type === 'DOUBLE') {
const ts = v.tickets[me] ?? [];
return choose((a) => (a.type === 'DOUBLE' ? ticketEv(ts[a.index]!, st) : -99));
}
if (acts[0]?.type === 'POT_BET') {
const p = st.yes / st.runs;
const sideEv = (side: 'YES' | 'NO') => ((side === 'YES' ? p : 1 - p) * SIDE_POT * v.options.potScale) / (1 + (v.seats.length - 1) / 2);
return choose((a) => {
if (a.type !== 'POT_BET') return -99;
const m = potEv(v, a.mascot, a.last, st);
const s = sideEv(a.side);
return m + s + (a.doubled === 'mascot' ? m : a.doubled === 'side' ? s : 0);
});
}
return acts[0]!;
};

View File

@@ -0,0 +1,241 @@
/**
* 핫스트릭 구성물 (docs/games/hot-streak.md §3): 마스코트 4명, 경주 카드 53장, 베팅 티켓 18장, 사이드 질문 12장, 인생 결과 문장.
* Pure data + small helpers; shared by the engine, the computer and the web screen.
*/
export const MASCOT_IDS = ['G', 'H', 'D', 'M'] as const;
export type MascotId = (typeof MASCOT_IDS)[number];
export interface MascotInfo {
id: MascotId;
name: string;
/** What the mask looks like (our own drawing). */
look: string;
/** Main / second colour of the costume. */
color: string;
color2: string;
/** Starting lane (0 = left end facing the finish). */
lane: 0 | 1 | 2 | 3;
/** Side a weave card turns to, relative to where the mascot faces. */
turn: 'right' | 'left';
}
export const MASCOTS: Record<MascotId, MascotInfo> = {
G: { id: 'G', name: '고블러', look: '곰', color: '#f97316', color2: '#7c3aed', lane: 0, turn: 'right' },
H: { id: 'H', name: '헐리', look: '핫도그', color: '#dc2626', color2: '#fdba74', lane: 1, turn: 'right' },
D: { id: 'D', name: '댕글', look: '아귀', color: '#2563eb', color2: '#93c5fd', lane: 2, turn: 'left' },
M: { id: 'M', name: '맘', look: '여왕', color: '#eab308', color2: '#a21caf', lane: 3, turn: 'left' },
};
/** Korean particle after a name: 받침 → first form, else second (이/가, 은/는, 을/를, 와/과). */
export function josa(word: string, withBatchim: string, without: string): string {
const c = word.charCodeAt(word.length - 1);
if (c < 0xac00 || c > 0xd7a3) return `${word}${without}`;
return `${word}${(c - 0xac00) % 28 ? withBatchim : without}`;
}
// ---------------------------------------------------------------- race cards
export const MASCOT_KINDS = ['S2', 'R1', 'F3', 'F2', 'B2', 'ST', 'W1', 'W2', 'W3', 'FD', 'TA'] as const;
export type MascotKind = (typeof MASCOT_KINDS)[number];
export const GREEN_CARDS = ['A1a', 'A1b', 'A2a', 'A2b', 'A3a', 'A3b', 'AB2', 'AR2', 'AR3'] as const;
export type GreenCard = (typeof GREEN_CARDS)[number];
/** Card kind: `G-W2`, `A1a` …; in the state a card id adds `#gen` (new every shuffle, §8.3). */
export type CardBase = string;
export type CardId = string;
export const STARTERS: CardBase[] = MASCOT_IDS.map((m) => `${m}-S2`);
export const ALL_CARDS: CardBase[] = [...MASCOT_IDS.flatMap((m) => MASCOT_KINDS.map((k) => `${m}-${k}`)), ...GREEN_CARDS];
export const baseOf = (id: CardId): CardBase => {
const i = id.indexOf('#');
return i < 0 ? id : id.slice(0, i);
};
export const withGen = (base: CardBase, gen: number): CardId => `${base}#${gen}`;
export type Effect =
| { kind: 'move'; n: number }
| { kind: 'rise'; n: number }
| { kind: 'star' }
| { kind: 'fall' }
| { kind: 'turn' }
| { kind: 'weave'; n: number };
export interface CardInfo {
base: CardBase;
/** Mascot the card moves, or 'all' (green card). */
who: MascotId | 'all';
effect: Effect;
/** Short face text ("2칸 가고 꺾기"). */
label: string;
starter: boolean;
}
const KIND_INFO: Record<MascotKind, { effect: Effect; label: string }> = {
S2: { effect: { kind: 'rise', n: 2 }, label: '일어나서 2칸' },
R1: { effect: { kind: 'rise', n: 1 }, label: '일어나서 1칸' },
F3: { effect: { kind: 'move', n: 3 }, label: '3칸' },
F2: { effect: { kind: 'move', n: 2 }, label: '2칸' },
B2: { effect: { kind: 'move', n: -2 }, label: '거꾸로 2칸' },
ST: { effect: { kind: 'star' }, label: '다음 별까지' },
W1: { effect: { kind: 'weave', n: 1 }, label: '1칸 가고 꺾기' },
W2: { effect: { kind: 'weave', n: 2 }, label: '2칸 가고 꺾기' },
W3: { effect: { kind: 'weave', n: 3 }, label: '3칸 가고 꺾기' },
FD: { effect: { kind: 'fall' }, label: '넘어지기' },
TA: { effect: { kind: 'turn' }, label: '뒤돌기' },
};
const GREEN_INFO: Record<string, { effect: Effect; label: string }> = {
A1: { effect: { kind: 'move', n: 1 }, label: '모두 1칸' },
A2: { effect: { kind: 'move', n: 2 }, label: '모두 2칸' },
A3: { effect: { kind: 'move', n: 3 }, label: '모두 3칸' },
AB2: { effect: { kind: 'move', n: -2 }, label: '모두 거꾸로 2칸' },
AR2: { effect: { kind: 'rise', n: 2 }, label: '모두 일어나서 2칸' },
AR3: { effect: { kind: 'rise', n: 3 }, label: '모두 일어나서 3칸' },
};
const INFO = new Map<CardBase, CardInfo>();
for (const base of ALL_CARDS) {
if (base.includes('-')) {
const [m, k] = base.split('-') as [MascotId, MascotKind];
const ki = KIND_INFO[k];
INFO.set(base, { base, who: m, effect: ki.effect, label: ki.label, starter: k === 'S2' });
} else {
const key = base.startsWith('AB') || base.startsWith('AR') ? base : base.slice(0, 2);
const gi = GREEN_INFO[key]!;
INFO.set(base, { base, who: 'all', effect: gi.effect, label: gi.label, starter: false });
}
}
export function cardInfo(idOrBase: string): CardInfo {
const info = INFO.get(baseOf(idOrBase));
if (!info) throw new Error(`hot-streak: unknown card ${idOrBase}`);
return info;
}
/** "헐리: 2칸 가고 꺾기" / "모두 2칸". */
export function cardText(idOrBase: string): string {
const c = cardInfo(idOrBase);
return c.who === 'all' ? c.label : `${MASCOTS[c.who].name}: ${c.label}`;
}
/** What a card does, in a sentence (hand preview, rules). */
export function cardHelp(idOrBase: string): string {
const c = cardInfo(idOrBase);
const e = c.effect;
if (c.who === 'all') {
const what = e.kind === 'rise' ? `모두 일어나서 결승선 쪽으로 ${e.n}칸` : e.kind === 'move' && e.n < 0 ? '모두 거꾸로 2칸' : `모두 보는 쪽으로 ${e.kind === 'move' ? e.n : 0}칸`;
return `${what} 가요. 서로 부딪치지 않고, 결승선 앞 1번 칸에서 멈춰요.`;
}
const m = MASCOTS[c.who];
const who = josa(m.name, '이', '가');
switch (e.kind) {
case 'move':
return e.n > 0 ? `${who} 보는 쪽으로 ${e.n}칸 가요.` : `${who} 거꾸로 ${-e.n}칸 가요(뒤돌아 있으면 결승선 쪽으로).`;
case 'rise':
return `${who} 일어나 결승선 쪽을 보고 ${e.n}칸 가요.`;
case 'star':
return `${who} 보는 쪽 다음 별 칸까지 가요.`;
case 'fall':
return `${who} 넘어져요. 이미 넘어져 있으면 실격이에요.`;
case 'turn':
return `${who} 뒤돌아요.`;
case 'weave':
return `${who} ${e.n}칸 가고 ${m.turn === 'right' ? '오른쪽' : '왼쪽'}으로 꺾어요.`;
}
}
/** Rough forward value of a card for a mascot (timeout default, quick bot hints): spaces toward the finish. */
export function forwardValue(idOrBase: string, m: MascotId): number {
const c = cardInfo(idOrBase);
if (c.who !== 'all' && c.who !== m) return 0;
switch (c.effect.kind) {
case 'move':
case 'rise':
case 'weave':
return c.effect.n;
case 'star':
return 4;
case 'fall':
return -2;
default:
return 0;
}
}
// ---------------------------------------------------------------- tickets
export type StackId = MascotId | 'YES' | 'NO';
export const STACK_IDS: StackId[] = [...MASCOT_IDS, 'YES', 'NO'];
export type Tier = 1 | 2 | 3;
export type Face = 'safe' | 'risky';
/** Mascot tickets: [1등, 2등, 3등] (4등 $0). §3.3 (※ 3단 위험은 우리가 맞춘 값). */
export const MASCOT_PAY: Record<Tier, Record<Face, [number, number, number]>> = {
1: { safe: [10, 7, 5], risky: [15, 5, 2] },
2: { safe: [7, 5, 3], risky: [11, 3, 1] },
3: { safe: [5, 3, 2], risky: [7, 2, 1] },
};
/** Side tickets (YES / NO): right / wrong. §3.3 (※ 2단은 우리가 맞춘 값). */
export const SIDE_PAY: Record<Tier, Record<Face, { win: number; lose: number }>> = {
1: { safe: { win: 10, lose: 0 }, risky: { win: 15, lose: -5 } },
2: { safe: { win: 7, lose: 0 }, risky: { win: 12, lose: -5 } },
3: { safe: { win: 5, lose: 0 }, risky: { win: 10, lose: -5 } },
};
export const isMascot = (s: StackId): s is MascotId => s !== 'YES' && s !== 'NO';
/** Value of a mascot ticket for a settled place (1~4); reverse tickets pay 4등 → 1등 값 … 1등 → $0. */
export function mascotPay(tier: Tier, face: Face, place: number, reverse: boolean): number {
const row = MASCOT_PAY[tier][face];
const p = reverse ? 5 - place : place;
return p >= 1 && p <= 3 ? row[p - 1]! : 0;
}
// ---------------------------------------------------------------- side bets
export const SIDE_IDS = ['bottom-G', 'bottom-H', 'bottom-D', 'bottom-M', 'two-down', 'two-at-line', 'any-dq', 'crawl-stretch', 'empty-stretch', 'out', 'same-space', 'knockout'] as const;
export type SideId = (typeof SIDE_IDS)[number];
export function sideQuestion(id: SideId): string {
if (id.startsWith('bottom-')) {
const m = MASCOTS[id.slice(7) as MascotId];
return `${josa(m.name, '이', '가')} 아래 두 자리(3·4등)로 들어올까요?`;
}
switch (id) {
case 'two-down':
return '마스코트 둘 이상이 동시에 넘어져 있을까요?';
case 'two-at-line':
return '마스코트 둘 이상이 동시에 결승선 바로 앞(1번 칸)에 있을까요?';
case 'any-dq':
return '실격이 한 명이라도 나올까요?';
case 'crawl-stretch':
return '마지막 스퍼트 구역(1~3번 칸)에서 누가 기어갈까요?';
case 'empty-stretch':
return '1등이 들어올 때 마지막 스퍼트 구역(1~3번 칸)이 비어 있을까요?';
case 'out':
return '누가 경주로 밖으로 나갈까요?';
case 'same-space':
return '두 마스코트가 같은 칸에 함께 멈출까요?';
case 'knockout':
return '누가 녹아웃될까요(넘어진 채 또 넘어짐)?';
}
return id;
}
// ---------------------------------------------------------------- life story (our own lines, §6.4)
export function lifeStory(money: number): string {
if (money <= 0) return '빈털터리. 야생으로 돌아갑니다';
if (money <= 5) return '핫도그 하나 사 먹고 끝';
if (money <= 9) return '본전도 못 찾았지만 웃었으니 됐다';
if (money === 10) return '딱 본전. 오늘을 다시 사는 기분';
if (money <= 19) return '마스코트 인형 열쇠고리 득템';
if (money <= 29) return '경기장 매점에서 한턱 쏨';
if (money <= 39) return '곰 마스코트 장학금에 기부';
if (money <= 59) return '응원가를 직접 녹음함';
if (money <= 99) return '구단 주식을 조금 삼';
return '너무 많이 땄다. 야생으로 돌아갑니다';
}

View File

@@ -0,0 +1,910 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, checkRoundTrip, playoutSeeds, randomPlayout, seedN, type Rng } from '@bg/engine';
import {
ALL_CARDS,
GREEN_CARDS,
MASCOTS,
MASCOT_IDS,
MASCOT_PAY,
SIDE_IDS,
SIDE_PAY,
STARTERS,
baseOf,
cardInfo,
hotStreak as def,
lifeStory,
nextStart,
placesOf,
podiumOf,
settle,
sideAnswer,
type HotStreakAction,
type HotStreakOptions,
type HotStreakState,
type MascotId,
type RaceState,
type Racer,
type SideId,
} from './index';
import { flipOne, freshFlags, startRace, startRacers, type RaceOpts } from './race';
// ---------------------------------------------------------------- helpers
const opts = (o: Partial<HotStreakOptions> = {}): HotStreakOptions => def.optionsSchema.parse({ ...def.defaultOptions, ...o });
const players = (n: number) => Array.from({ length: n }, (_, i) => `p${i}`);
const setup = (n: number, o: Partial<HotStreakOptions> = {}, seed = 1) => def.setup({ players: players(n), options: opts(o), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
const keep: Rng = { next: () => 0, int: () => 0, shuffle: (a) => [...a] };
const RO: RaceOpts = { burn: 3, hurdles: false, log: true };
function act(s: HotStreakState, p: string, a: HotStreakAction, rng: Rng = SeededRng.fromSeed(seedN(9)), now = 1000): HotStreakState {
const v = def.validate(s, p, a);
if (!v.ok) throw new Error(`rejected ${JSON.stringify(a)}: ${v.reason}`);
return def.apply(s, p, a, { rng, now }).state;
}
/** A race in progress with the mascots placed as given (others at the start). */
function race(spec: Partial<Record<MascotId, Partial<Racer>>> = {}, trackEnd = 13): RaceState {
const racers = startRacers();
for (const m of MASCOT_IDS) Object.assign(racers[m], spec[m] ?? {});
return {
no: 1,
racers,
trackEnd,
deck: [],
burned: [],
flipped: [],
passes: 0,
top: [],
bottom: [],
flags: freshFlags(),
processed: 0,
over: false,
log: [],
logSeq: 0,
nextFlipAt: 0,
hurry: [],
};
}
/** Plays one card (a filler stays under it so the deck doesn't run out). */
function play(r: RaceState, card: string, o: Partial<RaceOpts> = {}): RaceState {
r.deck = [card, 'A1a', 'A1b'];
flipOne(r, { rng: keep, regen: (c) => c }, { ...RO, ...o });
return r;
}
const at = (r: RaceState, m: MascotId) => {
const x = r.racers[m];
return `${x.lane}:${x.pos}${x.facing === 'back' ? '<' : ''}${x.down ? '_' : ''}${x.status === 'dq' ? 'X' : x.status === 'finished' ? 'F' : ''}`;
};
// ---------------------------------------------------------------- components
describe('구성물 (§3)', () => {
test('카드 53장: 마스코트마다 11장 + 초록 9장, 시작 카드 4장', () => {
expect(ALL_CARDS).toHaveLength(53);
expect(new Set(ALL_CARDS).size).toBe(53);
for (const m of MASCOT_IDS) expect(ALL_CARDS.filter((c) => c.startsWith(`${m}-`))).toHaveLength(11);
expect(GREEN_CARDS).toHaveLength(9);
expect(STARTERS).toEqual(['G-S2', 'H-S2', 'D-S2', 'M-S2']);
for (const c of STARTERS) expect(cardInfo(c).starter).toBe(true);
expect(cardInfo('A2b').who).toBe('all');
expect(cardInfo('H-W2#7').effect).toEqual({ kind: 'weave', n: 2 });
});
test('꺾는 방향: 고블러·헐리 오른쪽, 댕글·맘 왼쪽 / 레인 0~3', () => {
expect([MASCOTS.G.turn, MASCOTS.H.turn, MASCOTS.D.turn, MASCOTS.M.turn]).toEqual(['right', 'right', 'left', 'left']);
expect(MASCOT_IDS.map((m) => MASCOTS[m].lane)).toEqual([0, 1, 2, 3]);
});
test('티켓 18장 값 (§3.3)', () => {
expect(MASCOT_PAY[1]).toEqual({ safe: [10, 7, 5], risky: [15, 5, 2] });
expect(MASCOT_PAY[2]).toEqual({ safe: [7, 5, 3], risky: [11, 3, 1] });
expect(MASCOT_PAY[3]).toEqual({ safe: [5, 3, 2], risky: [7, 2, 1] });
expect(SIDE_PAY[1].risky).toEqual({ win: 15, lose: -5 });
expect(SIDE_PAY[3].safe).toEqual({ win: 5, lose: 0 });
const s = setup(4);
expect(Object.values(s.stacks).flat()).toHaveLength(18);
});
test('사이드 질문 12장, 인생 결과 구간', () => {
expect(SIDE_IDS).toHaveLength(12);
expect(lifeStory(0)).toContain('빈털터리');
expect(lifeStory(10)).toContain('본전');
expect(lifeStory(150)).toContain('너무 많이');
});
});
// ---------------------------------------------------------------- setup
describe('셋업 (§4)', () => {
const allCards = (s: HotStreakState): string[] => {
const ids = [...s.pool, ...s.seats.flatMap((p) => [...s.hands[p]!, ...(s.phase === 'race' || s.phase === 'payout' ? [] : (s.submitted[p] ?? []))])];
if (s.race && (s.phase === 'race' || s.phase === 'payout')) ids.push(...s.race.deck, ...s.race.burned, ...s.race.flipped);
return [...ids.map(baseOf), ...s.box];
};
test.each([
[2, 10, 4, 2],
[3, 11, 3, 1],
[4, 10, 3, 1],
[5, 9, 3, 1],
[6, 8, 3, 1],
[7, 7, 3, 1],
[8, 6, 3, 1],
])('%i명 티켓 모드: 무작위 %i장, 손패 %i장, 넣기 %i장 → 경주 덱 18장', (n, random, hand, k) => {
const s = setup(n);
expect(s.mode).toBe('tickets');
expect(s.pool).toHaveLength(4 + random);
for (const p of s.seats) expect(s.hands[p]).toHaveLength(hand);
expect(s.perRace as number).toBe(k);
expect(s.pool.length + n * k).toBe(18);
expect(allCards(s).sort()).toEqual([...ALL_CARDS].sort());
expect(s.faceUp).toHaveLength(4 + random);
for (const c of STARTERS) expect(s.faceUp).toContain(c);
});
test('9명 티켓 모드는 무작위 5장(우리 추정), 9~10명 자동은 상금 나누기(무작위 14장, 손패 없음)', () => {
expect(setup(9, { bettingMode: 'tickets' }).pool).toHaveLength(9);
for (const n of [9, 10]) {
const s = setup(n);
expect(s.mode).toBe('pots');
expect(s.pool).toHaveLength(18);
expect(s.faceUp).toHaveLength(18);
expect(s.handSize).toBe(0);
for (const p of s.seats) expect(s.money[p]).toBe(0);
}
expect(setup(4, { bettingMode: 'pots' }).pool).toHaveLength(18);
expect(() => setup(10, { bettingMode: 'tickets' })).toThrow();
expect(def.playersFor!(opts({ bettingMode: 'tickets' }))).toEqual({ min: 2, max: 9 });
expect(def.playersFor!(opts())).toEqual({ min: 2, max: 10 });
});
test('cardsPerRace=2: 3~6명만 손패 4장·2장 넣기, 7명 이상은 1장', () => {
for (const [n, random] of [
[3, 8],
[4, 6],
[5, 4],
[6, 2],
] as const) {
const s = setup(n, { cardsPerRace: 2 });
expect(s.perRace).toBe(2);
expect(s.pool).toHaveLength(4 + random);
for (const p of s.seats) expect(s.hands[p]).toHaveLength(4);
}
expect(setup(7, { cardsPerRace: 2 }).perRace).toBe(1);
});
test('spicyDeck: 넘어지기 4장은 언제나 덱이나 손패에', () => {
for (let seed = 1; seed <= 30; seed++) {
for (const n of [3, 8]) {
const s = setup(n, { spicyDeck: true }, seed);
const used = [...s.pool, ...s.seats.flatMap((p) => s.hands[p]!)].map(baseOf);
for (const m of MASCOT_IDS) expect(used).toContain(`${m}-FD`);
}
}
});
test('모두 $10에서 시작, 처음 사이드 질문 공개, 마스코트는 11번 칸', () => {
const s = setup(4);
for (const p of s.seats) expect(s.money[p]).toBe(10);
const v = def.view(s, 'p0');
expect(v.side.text.length).toBeGreaterThan(5);
expect(v.hand).toHaveLength(3);
expect(def.view(s, 'p1').hand!.map((c) => c.id)).not.toEqual(v.hand!.map((c) => c.id));
expect(startRacers().G).toMatchObject({ lane: 0, pos: 11, facing: 'fwd', down: false });
});
});
// ---------------------------------------------------------------- draft
describe('베팅 (§5.1·§5.2)', () => {
test('뱀 순서: 4명 P1~P4→P4~P1, 2명 1-2-2-1-1-2', () => {
const four = def.setup({ players: players(4), options: opts(), rng: { ...keep, int: () => 0 }, now: 0 });
expect(four.draftOrder).toEqual([0, 1, 2, 3, 3, 2, 1, 0]);
const two = def.setup({ players: players(2), options: opts(), rng: { ...keep, int: () => 0 }, now: 0 });
expect(two.draftOrder).toEqual([0, 1, 1, 0, 0, 1]);
});
test('같은 더미 두 번, 빈 더미 거부, 남이 가져간 티켓은 공개', () => {
let s = def.setup({ players: players(3), options: opts(), rng: { ...keep, int: () => 0 }, now: 0 });
s = act(s, 'p0', { type: 'DRAFT', stack: 'H', side: 'risky' });
s = act(s, 'p1', { type: 'DRAFT', stack: 'H', side: 'safe' });
s = act(s, 'p2', { type: 'DRAFT', stack: 'H', side: 'safe' });
expect(s.stacks.H).toEqual([]);
expect(def.validate(s, 'p2', { type: 'DRAFT', stack: 'H', side: 'safe' }).ok).toBe(false);
expect(def.validate(s, 'p1', { type: 'DRAFT', stack: 'G', side: 'safe' }).ok).toBe(false); // not their turn
s = act(s, 'p2', { type: 'DRAFT', stack: 'NO', side: 'risky' });
expect(s.tickets.p2!.map((t) => `${t.stack}${t.tier}${t.side}`)).toEqual(['H3safe', 'NO1risky']);
expect(def.view(s, 'p0').tickets.p1).toEqual([{ stack: 'H', tier: 2, side: 'safe', reverse: false, doubled: false }]);
expect(def.validate(s, 'p1', { type: 'DRAFT', stack: 'G', side: 'safe', reverse: true }).ok).toBe(false);
});
test('거꾸로 티켓은 옵션이 켜졌을 때 마스코트 더미에만', () => {
const s = def.setup({ players: players(3), options: opts({ reverseBets: true }), rng: { ...keep, int: () => 0 }, now: 0 });
expect(def.validate(s, 'p0', { type: 'DRAFT', stack: 'G', side: 'safe', reverse: true }).ok).toBe(true);
expect(def.validate(s, 'p0', { type: 'DRAFT', stack: 'YES', side: 'safe', reverse: true }).ok).toBe(false);
});
test('마지막 경주 두 배: 자기 마지막 티켓을 뽑은 직후, 다음 사람 차례 전에', () => {
let s = def.setup({ players: players(2), options: opts({ races: 1 }), rng: { ...keep, int: () => 0 }, now: 0 });
// 2명: p0 p1 p1 p0 p0 p1
s = act(s, 'p0', { type: 'DRAFT', stack: 'G', side: 'safe' });
s = act(s, 'p1', { type: 'DRAFT', stack: 'H', side: 'safe' });
s = act(s, 'p1', { type: 'DRAFT', stack: 'D', side: 'safe' });
s = act(s, 'p0', { type: 'DRAFT', stack: 'M', side: 'safe' });
s = act(s, 'p0', { type: 'DRAFT', stack: 'YES', side: 'risky' });
expect(s.phase).toBe('double');
expect(def.activePlayers(s)).toEqual(['p0']);
expect(def.validate(s, 'p1', { type: 'DRAFT', stack: 'NO', side: 'safe' }).ok).toBe(false);
s = act(s, 'p0', { type: 'DOUBLE', index: 2 });
expect(s.tickets.p0![2]!.doubled).toBe(true);
s = act(s, 'p1', { type: 'DRAFT', stack: 'NO', side: 'safe' });
expect(s.phase).toBe('double');
s = act(s, 'p1', { type: 'DOUBLE', index: 0 });
expect(s.phase).toBe('submit');
});
test('finalBet=none / 마지막 경주가 아니면 두 배 단계 없음', () => {
let s = def.setup({ players: players(2), options: opts({ races: 1, finalBet: 'none' }), rng: { ...keep, int: () => 0 }, now: 0 });
for (const p of ['p0', 'p1', 'p1', 'p0', 'p0', 'p1']) s = act(s, p, def.legalActions!(s, p)[0]!);
expect(s.phase).toBe('submit');
});
test('상금 나누기: 모두 동시에 몰래 적고, 다 적으면 공개되며 경주 시작', () => {
let s = setup(4, { bettingMode: 'pots', races: 1 });
expect(def.activePlayers(s).sort()).toEqual(players(4));
expect(def.validate(s, 'p0', { type: 'POT_BET', mascot: 'G', last: false, side: 'YES', doubled: null }).ok).toBe(false); // final race: double required
s = act(s, 'p0', { type: 'POT_BET', mascot: 'G', last: false, side: 'YES', doubled: 'mascot' });
const v1 = def.view(s, 'p1');
expect(v1.potBets.p0).toBeNull();
expect(v1.potDone.p0).toBe(true);
expect(def.view(s, 'p0').potBets.p0).toMatchObject({ mascot: 'G' });
expect(def.validate(s, 'p1', { type: 'POT_BET', mascot: 'G', last: true, side: 'YES', doubled: 'side' }).ok).toBe(false); // last off
for (const p of ['p1', 'p2', 'p3']) s = act(s, p, { type: 'POT_BET', mascot: 'D', last: false, side: 'NO', doubled: 'side' });
expect(s.phase).toBe('race');
expect(def.view(s, 'p1').potBets.p0).toMatchObject({ mascot: 'G', side: 'YES' });
});
});
// ---------------------------------------------------------------- submit
describe('카드 넣기 (§5.3)', () => {
test('정확히 1장(2명·2장 옵션은 2장), 내 손패만, 누가 넣었는지만 공개', () => {
let s = def.setup({ players: players(3), options: opts(), rng: SeededRng.fromSeed(seedN(4)), now: 0 });
while (s.phase === 'draft') s = act(s, def.activePlayers(s)[0]!, def.legalActions!(s, def.activePlayers(s)[0]!)[0]!);
expect(s.phase).toBe('submit');
const h = s.hands.p0!;
expect(def.validate(s, 'p0', { type: 'SUBMIT', cards: [h[0]!, h[1]!] }).ok).toBe(false);
expect(def.validate(s, 'p0', { type: 'SUBMIT', cards: [s.hands.p1![0]!] }).ok).toBe(false);
s = act(s, 'p0', { type: 'SUBMIT', cards: [h[1]!] });
expect(s.hands.p0).toHaveLength(2);
const v1 = def.view(s, 'p1');
expect(v1.put.p0).toBe(true);
expect(JSON.stringify(v1)).not.toContain(h[1]!);
expect(def.view(s, 'p0').myPut).toEqual([baseOf(h[1]!)]);
s = act(s, 'p1', { type: 'SUBMIT', cards: [s.hands.p1![0]!] });
s = act(s, 'p2', { type: 'SUBMIT', cards: [s.hands.p2![2]!] });
expect(s.phase).toBe('race');
const r = s.race!;
expect(r.deck.length + r.burned.length).toBe(18);
expect(r.burned).toHaveLength(3);
// New ids at every shuffle.
expect(r.deck.every((c) => !s.pool.includes(c) && c.endsWith(`#${s.gen}`))).toBe(true);
});
});
// ---------------------------------------------------------------- cards
describe('카드 처리 (§5.5)', () => {
test('숫자: 보는 방향으로, 음수는 반대로, 뒤돈 마스코트의 −2는 결승선 쪽', () => {
expect(at(play(race(), 'G-F3'), 'G')).toBe('0:8');
expect(at(play(race(), 'G-B2'), 'G')).toBe('0:13');
expect(at(play(race({ D: { pos: 6, facing: 'back' } }), 'D-F2'), 'D')).toBe('2:8<');
expect(at(play(race({ D: { pos: 6, facing: 'back' } }), 'D-B2'), 'D')).toBe('2:4<');
});
test('뒤로 경주로 끝을 넘으면 뒤로 나감 → 실격', () => {
const r = play(race({ M: { pos: 12 } }), 'M-B2');
expect(at(r, 'M')).toBe('3:13X');
expect(r.flags.out).toBe(true);
expect(r.bottom).toEqual([['M']]);
});
test('별: 앞 → 다음 별, 뒤돎 → 뒤 별, 별 칸에서도 다음 별, 갈 별 없으면 그대로, 1번 칸에서 결승', () => {
expect(at(play(race(), 'G-ST'), 'G')).toBe('0:6');
expect(at(play(race({ G: { facing: 'back' } }), 'G-ST'), 'G')).toBe('0:13<');
expect(at(play(race({ G: { pos: 6 } }), 'G-ST'), 'G')).toBe('0:1');
expect(at(play(race({ G: { pos: 13, facing: 'back' } }), 'G-ST'), 'G')).toBe('0:13<');
expect(at(play(race({ G: { pos: 12, facing: 'back' } }, 10), 'G-ST'), 'G')).toBe('0:12<');
const r = play(race({ G: { pos: 1 } }), 'G-ST');
expect(at(r, 'G')).toBe('0:0F');
expect(r.top).toEqual(['G']);
});
test('넘어짐 두 번 = 녹아웃 실격, 뒤돌기 두 번은 원래대로(넘어져 있어도 돎)', () => {
const r = play(race(), 'H-FD');
expect(at(r, 'H')).toBe('1:11_');
play(r, 'H-FD');
expect(at(r, 'H')).toBe('1:11_X');
expect(r.flags.knockout).toBe(true);
const t = play(race({ D: { down: true } }), 'D-TA');
expect(at(t, 'D')).toBe('2:11<_');
expect(at(play(t, 'D-TA'), 'D')).toBe('2:11_');
});
test('일어나서 n: 넘어짐·뒤돎 모두 회복한 뒤 n칸 다 감', () => {
expect(at(play(race({ M: { pos: 9, down: true, facing: 'back' } }), 'M-R1'), 'M')).toBe('3:8');
expect(at(play(race({ M: { pos: 9, down: true } }), 'M-S2'), 'M')).toBe('3:7');
});
test('넘어진 마스코트는 앞·뒤·별 1칸만', () => {
expect(at(play(race({ G: { pos: 9, down: true } }), 'G-F3'), 'G')).toBe('0:8_');
expect(at(play(race({ G: { pos: 9, down: true } }), 'G-B2'), 'G')).toBe('0:10_');
expect(at(play(race({ M: { pos: 6, down: true } }), 'M-ST'), 'M')).toBe('3:5_');
});
test('꺾기: n칸 뒤 옆 레인(보는 방향 기준), 레인 밖은 실격, 결승선을 넘으면 꺾지 않음', () => {
expect(at(play(race(), 'G-W2'), 'G')).toBe('1:9');
expect(at(play(race(), 'M-W1'), 'M')).toBe('2:10');
// Facing back: right of the mascot is the other way.
expect(at(play(race({ H: { facing: 'back', pos: 5 } }), 'H-W1'), 'H')).toBe('0:6<');
const out = play(race({ G: { facing: 'back', pos: 5 } }), 'G-W1');
expect(at(out, 'G')).toBe('0:6<X');
expect(out.flags.out).toBe(true);
const fin = play(race({ D: { pos: 2 } }), 'D-W3');
expect(at(fin, 'D')).toBe('2:0F');
expect(fin.bottom).toEqual([]);
});
test('넘어진 채 꺾기: 앞 1칸 + 옆 1칸, 충돌 두 번', () => {
const r = play(race({ H: { pos: 9, down: true }, G: { lane: 1, pos: 8 }, D: { lane: 2, pos: 8 } }), 'H-W3');
expect(at(r, 'H')).toBe('2:8_');
expect(at(r, 'G')).toBe('1:8_');
expect(at(r, 'D')).toBe('2:8_');
expect(r.flags.twoDown).toBe(true);
});
});
describe('충돌 (§5.5)', () => {
test('지나가기만 해도 충돌, 움직이는 쪽은 안전, 한 칸 여럿 모두 충돌', () => {
const r = play(race({ D: { lane: 0, pos: 10 }, M: { lane: 0, pos: 10 } }), 'G-F3');
expect(at(r, 'G')).toBe('0:8');
expect(at(r, 'D')).toBe('0:10_');
expect(at(r, 'M')).toBe('0:10_');
});
test('같은 칸 녹아웃 둘 = 동시 실격, 다른 칸 녹아웃은 지나간 순서', () => {
const same = play(race({ D: { lane: 0, pos: 10, down: true }, M: { lane: 0, pos: 10, down: true } }), 'G-F2');
expect(same.bottom).toEqual([['D', 'M']]);
const order = play(race({ D: { lane: 0, pos: 10, down: true }, M: { lane: 0, pos: 9, down: true } }), 'G-F2');
expect(order.bottom).toEqual([['D'], ['M']]);
expect(podiumOf({ top: [], bottom: order.bottom })).toEqual([['M'], ['D']]);
expect(order.flags.knockout).toBe(true);
});
test('넘어진 채 기어가는 마스코트도 남을 넘어뜨림', () => {
const r = play(race({ H: { pos: 9, down: true }, G: { lane: 1, pos: 8 } }), 'H-F3');
expect(at(r, 'G')).toBe('1:8_');
});
});
describe('초록 카드 (§5.5)', () => {
test('충돌 없음, 1번 칸에서 멈춤, 넘어짐 1칸, 뒤돎 반대, 뒤로 밖은 동시 실격', () => {
const r = play(race({ G: { pos: 12, facing: 'back' }, H: { pos: 5, down: true }, D: { pos: 2 }, M: { pos: 13, facing: 'back' } }), 'A2a');
expect(at(r, 'D')).toBe('2:1');
expect(at(r, 'H')).toBe('1:4_');
expect(r.bottom).toEqual([['G', 'M']]);
expect(r.top).toEqual([]);
const same = play(race({ G: { lane: 1, pos: 12 }, H: { down: true } }), 'A2a');
expect(at(same, 'G')).toBe('1:10');
expect(at(same, 'H')).toBe('1:10_');
expect(same.flags.sameSpace).toBe(true);
});
test('모두 일어나서 2·3칸, 모두 거꾸로 2칸', () => {
const r = play(race({ G: { down: true, facing: 'back' } }), 'AR3');
for (const m of MASCOT_IDS) expect(r.racers[m].pos).toBe(8);
expect(r.racers.G.down).toBe(false);
const b = play(race({ H: { facing: 'back', pos: 4 } }), 'AB2');
expect(at(b, 'G')).toBe('0:13');
expect(at(b, 'H')).toBe('1:2<');
});
});
describe('§5.8 예시', () => {
test('충돌: 헐리 3칸 꺾기 → 레인 2의 8번 칸 댕글이 넘어지고, 댕글 넘어지기 → 실격, 4등', () => {
const r = play(race({ D: { lane: 2, pos: 8 } }), 'H-W3');
expect(at(r, 'H')).toBe('2:8');
expect(at(r, 'D')).toBe('2:8_');
play(r, 'D-FD');
expect(at(r, 'D')).toBe('2:8_X');
expect(placesOf(podiumOf({ top: ['G', 'H', 'M'], bottom: r.bottom })).D).toEqual({ high: 4, low: 4 });
});
test('별: 11 → 6, 뒤돎 → 13, 13에서 또 별 → 그대로', () => {
const r = play(race(), 'G-ST');
expect(r.racers.G.pos).toBe(6);
const b = play(race({ G: { facing: 'back' } }), 'G-ST');
expect(b.racers.G.pos).toBe(13);
expect(play(b, 'G-ST').racers.G.pos).toBe(13);
});
test('넘어져서 별: 넘어진 맘 6번 칸 → 5번 칸', () => {
expect(play(race({ M: { pos: 6, down: true } }), 'M-ST').racers.M.pos).toBe(5);
});
test('초록 "모두 2칸": 맘 1번 칸에서 멈춤, 넘어진 헐리 4번 칸, 뒤돈 고블러 밖 → 실격', () => {
const r = play(race({ M: { pos: 2 }, H: { pos: 5, down: true }, G: { pos: 12, facing: 'back' }, D: { pos: 7 } }), 'A2b');
expect(r.racers.M.pos).toBe(1);
expect(r.racers.H.pos).toBe(4);
expect(r.racers.G.status).toBe('dq');
});
test('뒤돈 댕글 2번 칸 −2 → 결승', () => {
const r = play(race({ D: { pos: 2, facing: 'back' } }), 'D-B2');
expect(r.racers.D.status).toBe('finished');
expect(r.top).toEqual(['D']);
});
test('접기: 고블러 11·맘 12번 칸에서 덱이 바닥 → 10까지 접혀 둘 동시 실격, 비어 있는 3·4등이면 둘 다 4등', () => {
const r = race({ M: { pos: 12 }, D: { pos: 0, status: 'finished' }, H: { pos: 3 } });
r.top = ['D'];
r.racers.H.pos = 3;
r.deck = ['H-F2'];
r.burned = ['A1a', 'A1b', 'A2a'];
flipOne(r, { rng: keep, regen: (c) => c }, RO);
expect(r.trackEnd).toBe(10);
expect(r.bottom).toEqual([['G', 'M']]);
expect(r.over).toBe(true);
const pl = placesOf(podiumOf(r));
expect(pl.G).toEqual({ high: 3, low: 4 });
expect(pl.M).toEqual({ high: 3, low: 4 });
expect(pl.H.low).toBe(2);
});
});
describe('시상대·경주 끝 (§5.4·§6.3)', () => {
test('결승은 위에서, 실격은 아래에서, 3명 확정 순간 끝·남은 1명 자동', () => {
const r = race({ G: { pos: 1 }, H: { pos: 1, lane: 1 }, D: { down: true } });
play(r, 'G-F2');
play(r, 'D-FD');
expect(r.over).toBe(false);
play(r, 'H-F2');
expect(r.over).toBe(true);
expect(podiumOf(r)).toEqual([['G'], ['H'], ['M'], ['D']]);
});
test('넷이 한꺼번에 실격하면 모두 4등, 거꾸로 티켓은 묶음의 높은 등수', () => {
const pl = placesOf([['G', 'H', 'D', 'M']]);
for (const m of MASCOT_IDS) expect(pl[m]).toEqual({ high: 1, low: 4 });
const p2 = placesOf([['D'], ['G', 'H', 'M']]);
expect(p2.G).toEqual({ high: 2, low: 4 });
});
test('이미 들어왔거나 실격한 마스코트 카드는 넘어감', () => {
const r = race({ G: { pos: 0, status: 'finished' } });
r.top = ['G'];
play(r, 'G-F3');
expect(r.log.at(-1)!.text).toContain('넘어가요');
});
});
describe('접기 (§5.6)', () => {
test('13 → 10 → 7 → 3 → 0, 버린 카드까지 다시 섞고 다시 버림, 네 번째 접기는 전원 실격', () => {
const r = race({ G: { pos: 2 }, H: { pos: 2 }, D: { pos: 2 }, M: { pos: 2 } });
r.deck = ['G-TA'];
r.burned = ['A1b', 'A2a', 'A2b'];
const shuffles: number[] = [];
const ctx = { rng: keep, regen: (c: string[]) => (shuffles.push(c.length), c) };
flipOne(r, ctx, RO);
expect(r.trackEnd).toBe(10);
expect(shuffles).toEqual([4]);
expect(r.burned).toHaveLength(3);
expect(r.deck).toHaveLength(1);
expect(r.passes).toBe(1);
const ends: number[] = [];
for (let i = 0; i < 3 && !r.over; i++) {
// Keep everyone standing still with turn-arounds.
r.deck = ['G-TA'];
flipOne(r, ctx, RO);
ends.push(r.trackEnd);
}
expect(ends).toEqual([7, 3, 0]);
expect(r.over).toBe(true);
expect(r.bottom.flat().sort()).toEqual([...MASCOT_IDS].sort());
});
test('카드 처리 200번 상한에서 끝', () => {
const r = race();
r.processed = 199;
play(r, 'G-TA');
expect(r.over).toBe(true);
expect(r.bottom).toEqual([['G', 'H', 'D', 'M']]);
});
});
describe('사이드 질문 판정 (§3.4)', () => {
const ans = (r: RaceState, id: SideId) => sideAnswer(id, r.flags, podiumOf(r));
test('two-at-line: 밟혀 실격하면 동시에 있던 것이 아님', () => {
const r = play(race({ G: { pos: 2 }, H: { lane: 0, pos: 1, down: true } }), 'G-W1');
// G walks onto H (down) → H knocked out, then turns into lane 1 at space 1.
expect(r.racers.H.status).toBe('dq');
expect(r.flags.twoAtLine).toBe(false);
const yes = play(race({ G: { pos: 2 }, H: { pos: 1 } }), 'A1a');
expect(yes.flags.twoAtLine).toBe(true);
});
test('empty-stretch / crawl-stretch / out(옆·뒤·접힘)', () => {
const e = play(race({ G: { pos: 1 } }), 'G-F2');
expect(e.flags.emptyStretchAtWin).toBe(true);
const ne = play(race({ G: { pos: 1 }, H: { pos: 3 } }), 'G-F2');
expect(ne.flags.emptyStretchAtWin).toBe(false);
expect(play(race({ M: { pos: 4, down: true } }), 'M-F3').flags.crawlStretch).toBe(true);
expect(play(race({ M: { pos: 5, down: true } }), 'M-F3').flags.crawlStretch).toBe(false);
expect(play(race({ M: { pos: 4, down: true } }), 'A1a').flags.crawlStretch).toBe(true);
expect(play(race({ M: { facing: 'back' } }), 'M-W1').flags.out).toBe(true);
expect(play(race({ M: { pos: 13 } }), 'M-B2').flags.out).toBe(true);
const f = race({ G: { pos: 12 } });
f.deck = ['H-TA'];
flipOne(f, { rng: keep, regen: (c) => c }, RO);
expect(f.flags.out).toBe(true);
expect(play(race(), 'G-F2').flags.out).toBe(false);
});
test('bottom-X, two-down, any-dq, same-space, knockout: YES와 NO', () => {
const r = race({ G: { pos: 1 }, H: { pos: 1 }, D: { pos: 1 } });
play(r, 'G-F2');
play(r, 'H-F2');
play(r, 'M-FD');
play(r, 'D-F2');
expect(r.over).toBe(true);
expect(ans(r, 'bottom-M')).toBe(true);
expect(ans(r, 'bottom-H')).toBe(false);
expect(ans(r, 'bottom-D')).toBe(true);
expect(ans(r, 'two-down')).toBe(false);
expect(ans(r, 'any-dq')).toBe(false);
expect(ans(r, 'knockout')).toBe(false);
expect(ans(r, 'same-space')).toBe(false);
const k = play(play(race({ G: { down: true } }), 'H-FD'), 'G-FD');
expect(ans(k, 'two-down')).toBe(true);
expect(ans(k, 'any-dq')).toBe(true);
expect(ans(k, 'knockout')).toBe(true);
expect(ans(play(race({ G: { lane: 1, pos: 12 }, H: { down: true } }), 'A2a'), 'same-space')).toBe(true);
expect(ans(play(race(), 'G-F2'), 'same-space')).toBe(false);
});
test('허들: 서 있는 채 허들 칸에서 멈추면 넘어짐, 지나가기·기어가기는 그대로', () => {
const h = { hurdles: true };
expect(at(play(race(), 'G-F3', h), 'G')).toBe('0:8_');
expect(at(play(race(), 'G-F2', h), 'G')).toBe('0:9');
expect(at(play(race({ G: { pos: 9, down: true } }), 'G-F3', h), 'G')).toBe('0:8_');
expect(at(play(race({ G: { pos: 9 } }), 'G-W1', h), 'G')).toBe('1:8_');
expect(at(play(race(), 'A3a', h), 'G')).toBe('0:8_');
expect(at(play(race(), 'G-F3'), 'G')).toBe('0:8');
});
});
// ---------------------------------------------------------------- payout
describe('정산 (§6)', () => {
/** A state in the payout step of race `no` with the given podium and tickets. */
function payoutState(n: number, podium: MascotId[][], tickets: Record<string, HotStreakState['tickets'][string]>, side: SideId, o: Partial<HotStreakOptions> = {}): HotStreakState {
const s = setup(n, o);
s.tickets = { ...Object.fromEntries(s.seats.map((p) => [p, []])), ...tickets };
const r = race();
r.top = podium.filter((g) => g.length === 1).slice(0, 1).flat();
// Rebuild top/bottom from the podium: singletons first as finishers, the rest as DQ groups.
r.top = [];
r.bottom = [];
let tail = false;
for (const g of podium) {
if (g.length > 1) tail = true;
if (!tail) r.top.push(g[0]!);
else r.bottom.unshift(g);
}
r.over = true;
s.race = r;
s.sideDeck = [side, ...SIDE_IDS.filter((x) => x !== side)];
return s;
}
test('§6.1 예시: 댕글 1, 고블러 2, 헐리 3, 맘 4 / 녹아웃 YES', () => {
const s = payoutState(
2,
[['D'], ['G'], ['H'], ['M']],
{
p0: [
{ stack: 'D', tier: 2, side: 'risky', reverse: false, doubled: false },
{ stack: 'M', tier: 1, side: 'safe', reverse: false, doubled: false },
],
p1: [
{ stack: 'NO', tier: 1, side: 'risky', reverse: false, doubled: true },
{ stack: 'G', tier: 1, side: 'safe', reverse: false, doubled: false },
],
},
'knockout',
);
s.race!.flags.knockout = true;
const res = settle(s);
expect(res.side.yes).toBe(true);
expect(res.rows.p0!.total).toBe(11);
// Not the final race (3 races): no doubling.
expect(res.rows.p1!.total).toBe(2);
s.raceNo = 3;
expect(settle(s).rows.p1!.total).toBe(-3);
s.money.p1 = 2;
expect(settle(s).rows.p1!.after).toBe(0);
});
test('거꾸로 티켓: 4등 → 1등 값, 공동 묶음은 높은 등수', () => {
const t = (stack: MascotId) => [{ stack, tier: 1 as const, side: 'safe' as const, reverse: true, doubled: false }];
const s = payoutState(4, [['D'], ['G'], ['H', 'M']], { p0: t('M'), p1: t('D'), p2: t('G') }, 'any-dq', { reverseBets: true });
const res = settle(s);
expect(res.rows.p0!.total).toBe(7); // group 3·4 → counts as 3rd → 2등 값
expect(res.rows.p1!.total).toBe(0);
expect(res.rows.p2!.total).toBe(5);
});
test('bothBonus: 마지막 경주에 두 티켓 모두 플러스면 평균(내림)만큼 더', () => {
const s = payoutState(
3,
[['D'], ['G'], ['H'], ['M']],
{
p0: [
{ stack: 'D', tier: 1, side: 'safe', reverse: false, doubled: false },
{ stack: 'G', tier: 1, side: 'risky', reverse: false, doubled: false },
],
},
'any-dq',
{ finalBet: 'bothBonus', races: 1 },
);
const res = settle(s);
expect(res.rows.p0!.lines.map((l) => l.amount)).toEqual([10, 5, 7]);
});
test('상금 나누기: 5명이 1등에 → $3씩(내림), 아무도 없으면 사라짐, 두 배 몫, 꼴찌 상금', () => {
const s = payoutState(6, [['D'], ['G'], ['H'], ['M']], {}, 'any-dq', { bettingMode: 'pots', reverseBets: true, races: 1 });
for (const p of ['p0', 'p1', 'p2', 'p3', 'p4']) s.potBets[p] = { mascot: 'D', last: false, side: 'NO', doubled: 'mascot' };
s.potBets.p5 = { mascot: 'M', last: true, side: 'YES', doubled: 'side' };
const res = settle(s);
expect(res.rows.p0!.lines[0]!.amount).toBe(6); // 18 / 5 = 3, doubled
expect(res.rows.p0!.lines[1]!.amount).toBe(3); // side NO right: 18 / 5
expect(res.rows.p5!.lines[0]!.amount).toBe(18);
expect(res.rows.p5!.lines[1]!.amount).toBe(0);
const big = payoutState(3, [['D'], ['G'], ['H'], ['M']], {}, 'any-dq', { bettingMode: 'pots', potScale: 3 });
big.potBets = { p0: { mascot: 'G', last: false, side: 'YES', doubled: null }, p1: { mascot: 'G', last: false, side: 'YES', doubled: null }, p2: { mascot: 'M', last: false, side: 'NO', doubled: null } };
const b = settle(big);
expect(b.rows.p0!.lines.map((l) => l.amount)).toEqual([18, 0]);
expect(b.rows.p2!.lines.map((l) => l.amount)).toEqual([0, 54]);
});
});
// ---------------------------------------------------------------- between races
describe('경주 사이 (§5.7)', () => {
function toPayout(s: HotStreakState, rng: Rng): HotStreakState {
let t = s;
for (let i = 0; i < 400 && t.phase !== 'payout' && t.phase !== 'finished'; i++) {
const p = def.activePlayers(t)[0]!;
const a = t.phase === 'race' ? ({ type: 'TIMEOUT' } as const) : def.legalActions!(t, p)[0]!;
t = act(t, p, a, rng, 1000 + i);
}
return t;
}
test('티켓 복귀, 다음 사이드 카드, 덱에서 1장 받기, 카드 총수 보존', () => {
const rng = SeededRng.fromSeed(seedN(11));
let s = setup(4);
const firstSide = s.sideDeck[0];
s = toPayout(s, rng);
expect(s.phase).toBe('payout');
for (const p of s.seats) s = act(s, p, { type: 'READY' }, rng);
expect(s.phase).toBe('draft');
expect(s.raceNo).toBe(2);
expect(s.sideDeck.at(-1)).toBe(firstSide!);
expect(Object.values(s.stacks).flat()).toHaveLength(18);
for (const p of s.seats) expect(s.hands[p]).toHaveLength(3);
expect(s.pool).toHaveLength(14);
expect(s.faceUp).toEqual([]);
expect(s.seenLast.length).toBeGreaterThan(0);
const all = [...s.pool, ...s.seats.flatMap((p) => s.hands[p]!)].map(baseOf);
expect([...all, ...s.box].sort()).toEqual([...ALL_CARDS].sort());
});
test('draftStart: 한 자리씩 / 건너뛰기 / 돈이 가장 적은 사람(같으면 시계 반대 방향 가장 가까운 사람)', () => {
const s = setup(7);
s.startSeat = 2;
expect(nextStart(s)).toBe(3);
s.options = opts({ draftStart: 'spread' });
expect(nextStart(s)).toBe(5);
const five = setup(5, { draftStart: 'spread' });
five.startSeat = 4;
expect(nextStart(five)).toBe(1);
s.options = opts({ draftStart: 'poorest' });
for (const p of s.seats) s.money[p] = 20;
s.money.p5 = 3;
expect(nextStart(s)).toBe(5);
s.money.p0 = 3;
// Tie p0 / p5: counter-clockwise from seat 2 → 1, 0 first.
expect(nextStart(s)).toBe(0);
});
test('상금 나누기: 3장 빼고 3장 새로 넣어 18장 모두 앞면', () => {
const rng = SeededRng.fromSeed(seedN(12));
let s = setup(9);
const before = [...s.faceUp];
s = toPayout(s, rng);
s = act(s, s.seats[0]!, { type: 'TIMEOUT' }, rng);
expect(s.raceNo).toBe(2);
expect(s.faceUp).toHaveLength(18);
expect(s.faceUp.filter((c) => !before.includes(c)).length).toBeLessThanOrEqual(3);
expect([...s.pool.map(baseOf), ...s.box].sort()).toEqual([...ALL_CARDS].sort());
});
});
// ---------------------------------------------------------------- engine common
function invariant(state: unknown): void {
const s = state as HotStreakState;
const live = s.phase === 'race' || s.phase === 'payout';
const ids = [...s.pool, ...s.seats.flatMap((p) => [...s.hands[p]!, ...(live ? [] : (s.submitted[p] ?? []))])];
if (live && s.race) ids.push(...s.race.deck, ...s.race.burned, ...s.race.flipped);
if (!live && s.race && s.phase !== 'finished') throw new Error('race left over');
if (s.phase !== 'finished') {
const all = [...ids.map(baseOf), ...s.box];
if (all.length !== 53 || new Set(all).size !== 53) throw new Error(`card count ${all.length}`);
}
for (const p of s.seats) if (s.money[p]! < 0) throw new Error('negative money');
if (s.phase === 'race' && s.race!.deck.length + s.race!.burned.length + s.race!.flipped.length !== 18) throw new Error('race deck != 18');
}
describe('무작위 대국', () => {
const COMBOS: Partial<HotStreakOptions>[] = [
{},
{ reverseBets: true, hurdles: true },
{ cardsPerRace: 2, burn: 5, spicyDeck: true },
{ finalBet: 'bothBonus', draftStart: 'poorest', races: 5 },
{ bettingMode: 'pots', potScale: 2, reverseBets: true },
{ finalBet: 'none', draftStart: 'spread', races: 1 },
{ bettingMode: 'tickets' },
];
const COUNTS = [2, 3, 5, 8, 9, 10];
const playable = (o: Partial<HotStreakOptions>, n: number) => !(o.bettingMode === 'tickets' && n > 9);
const ENGINE = playoutSeeds(200);
test(`엔진 공통 무작위 대국 ${ENGINE}판(2·3·5·8·9·10명, 옵션 조합): 끝나고, JSON 왕복, 비공개 정보가 새지 않아요`, () => {
let done = 0;
for (let i = 1; done < ENGINE; i++) {
const n = COUNTS[i % COUNTS.length]!;
const o = COMBOS[i % COMBOS.length]!;
if (!playable(o, n)) continue;
const r = randomPlayout(def, { players: players(n), options: opts(o), seed: seedN(i), maxSteps: 6000, invariant, maxApplyMs: 30 });
expect(r.finished).toBe(true);
expect((r.finalState as HotStreakState).results).toHaveLength(opts(o).races);
done++;
}
}, 120_000);
const FAST = playoutSeeds(1000);
test(`빠른 무작위 대국 ${FAST}판: 카드 총수 보존(18 + 손패 + 상자 = 53), 돈은 0 이상, 경주 수만큼 정산`, () => {
for (let i = 1; i <= FAST; i++) {
const n = COUNTS[i % COUNTS.length]!;
const o = COMBOS[(i * 3) % COMBOS.length]!;
if (!playable(o, n)) continue;
const rng = SeededRng.fromSeed(seedN(5000 + i));
const chooser = SeededRng.fromSeed(seedN(9000 + i));
let s = def.setup({ players: players(n), options: opts(o), rng, now: 0 });
let steps = 0;
while (!def.result(s)) {
if (++steps > 4000) throw new Error(`seed ${i}: game did not finish`);
const actives = def.activePlayers(s);
const p = actives[chooser.int(actives.length)]!;
const legal = def.legalActions!(s, p);
// Now and then the clock instead of a choice (races flip card by card).
const a = !legal.length || chooser.next() < 0.3 ? def.onTimeout(s, p) : legal[chooser.int(legal.length)]!;
expect(def.validate(s, p, a).ok).toBe(true);
s = def.apply(s, p, a, { rng, now: steps * 1000 }).state;
invariant(s);
}
expect(s.results).toHaveLength(opts(o).races);
}
}, 120_000);
test('같은 시드면 같은 결과(결정성)', () => {
for (let i = 1; i <= 5; i++) {
const a = randomPlayout(def, { players: players(4), seed: seedN(100 + i), maxApplyMs: 30 });
const b = randomPlayout(def, { players: players(4), seed: seedN(100 + i), maxApplyMs: 30 });
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
}
});
test('시간 초과만으로 끝나요: 경주는 마감 타이머로 카드를 한 장씩 넘겨요(유출 없음, 보존)', () => {
let flips = 0;
for (let i = 1; i <= 14; i++) {
const n = COUNTS[i % COUNTS.length]!;
const o = COMBOS[i % COMBOS.length]!;
if (!playable(o, n)) continue;
const rng = SeededRng.fromSeed(seedN(i));
let s = def.setup({ players: players(n), options: opts(o), rng, now: 0 });
let now = 0;
let steps = 0;
while (!def.result(s)) {
if (++steps > 5000) throw new Error(`seed ${i}: did not finish`);
const p = def.timeoutPlayers!(s)[0]!;
const d = def.deadline!(s);
now = Math.max(now + 1, d ?? now + 1);
const nb = def.timeoutNotBefore!(s);
if (nb !== null) expect(now).toBeGreaterThanOrEqual(nb);
const a = def.onTimeout(s, p);
expect(def.validate(s, p, a).ok).toBe(true);
if (s.phase === 'race') flips++;
s = def.apply(s, p, a, { rng, now }).state;
checkRoundTrip(s);
invariant(s);
if (steps % 3 === 0) for (const q of s.seats) checkNoLeak(def, s, q, s.seats);
}
expect(s.results).toHaveLength(opts(o).races);
}
expect(flips).toBeGreaterThan(200);
}, 60_000);
test('경주 중: 화면은 하나씩, [빨리 보기] 모두 동의하면 끝까지 바로 / 한 명만이면 그대로', () => {
const rng = SeededRng.fromSeed(seedN(21));
let s = setup(3);
while (s.phase !== 'race') {
const p = def.activePlayers(s)[0]!;
s = act(s, p, def.legalActions!(s, p)[0]!, rng);
}
expect(def.timeoutPlayers!(s)).toEqual(['p0']);
expect(def.disconnectGraceMs!(s)).toBe(0);
expect(def.deadline!(s)).toBe(s.race!.nextFlipAt);
s = act(s, 'p1', { type: 'HURRY' }, rng);
s = act(s, 'p1', { type: 'HURRY' }, rng);
expect(s.race!.hurry).toEqual([]);
s = act(s, 'p0', { type: 'HURRY' }, rng);
s = act(s, 'p1', { type: 'HURRY' }, rng);
expect(s.phase).toBe('race');
s = act(s, 'p2', { type: 'HURRY' }, rng, 5000);
expect(s.phase).toBe('payout');
expect(s.race!.over).toBe(true);
expect(s.payoutAt!).toBeGreaterThan(5000 + 8000);
// Everyone ready → next race at once.
for (const p of s.seats) s = act(s, p, { type: 'READY' }, rng);
expect(s.raceNo).toBe(2);
});
test('나가기: 차례는 자동, 혼자 남으면 바로 끝(resign), 나간 사람은 맨 아래', () => {
const rng = SeededRng.fromSeed(seedN(31));
let s = setup(3);
const first = def.activePlayers(s)[0]!;
s = act(s, first, { type: 'LEAVE' }, rng);
expect(def.activePlayers(s)).toEqual([first]);
expect(s.deadlineAt).toBe(2000);
expect(def.validate(s, first, { type: 'TIMEOUT' }).ok).toBe(true);
s = def.apply(s, first, { type: 'TIMEOUT' }, { rng, now: 2000 }).state;
expect(s.tickets[first]).toHaveLength(1);
const rest = s.seats.filter((p) => p !== first);
s = act(s, rest[0]!, { type: 'LEAVE' }, rng);
expect(s.phase).toBe('finished');
const res = def.result(s)!;
expect(res.reason).toBe('resign');
expect(res.ranking[0]).toEqual([rest[1]!]);
expect(res.scoreText![rest[1]!]).toMatch(/^\$\d+$/);
});
test('자리 비움: 연속 3번 시간 초과면 마감 5초, 직접 하면 다시 보통', () => {
const rng = SeededRng.fromSeed(seedN(41));
// 2명, p0부터: p0 p1 p1 p0 p0 p1
let s = def.setup({ players: players(2), options: opts(), rng: { ...keep, int: () => 0 }, now: 0 });
s.timeouts.p0 = 2;
s = def.apply(s, 'p0', { type: 'TIMEOUT' }, { rng, now: 30_000 }).state;
expect(def.view(s, 'p1').away).toEqual(['p0']);
expect(s.deadlineAt).toBe(60_000);
s = act(s, 'p1', def.legalActions!(s, 'p1')[0]!, rng, 31_000);
s = act(s, 'p1', def.legalActions!(s, 'p1')[0]!, rng, 32_000);
expect(s.deadlineAt).toBe(32_000 + 5000);
s = act(s, 'p0', def.legalActions!(s, 'p0')[0]!, rng, 33_000);
expect(s.timeouts.p0).toBe(0);
expect(s.deadlineAt).toBe(33_000 + 30_000);
});
});

View File

@@ -0,0 +1,950 @@
/**
* 핫스트릭 (docs/games/hot-streak.md). 경주마다 ① 베팅(뱀 순서 티켓 뽑기, 또는 상금 나누기 동시 베팅) → ② 비밀 카드 넣기 →
* ③ 경주(서버 타이머가 `flipSeconds`마다 카드를 넘김, 모두 [빨리 보기]면 바로 끝까지) → ④ 정산. 돈이 가장 많은 사람이 이겨요.
* Hidden: deck order, burned cards, the others' hands and put-in cards, the next side questions, 상금 나누기 bets until all are in.
*/
import type { ZodType } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
import {
ALL_CARDS,
MASCOTS,
MASCOT_IDS,
MASCOT_PAY,
SIDE_IDS,
SIDE_PAY,
STACK_IDS,
STARTERS,
baseOf,
forwardValue,
isMascot,
lifeStory,
mascotPay,
sideQuestion,
withGen,
type CardBase,
type CardId,
type MascotId,
type SideId,
type StackId,
type Tier,
} from './cards';
import { flipOne, placesOf, podiumOf, runToEnd, sideAnswer, startRace, type RaceCtx, type RaceOpts } from './race';
import {
AWAY_AFTER,
AWAY_MS,
DECK_SIZE,
HURDLES,
HURRY_REPLAY_CAP,
HURRY_REPLAY_MS,
LAST_POT,
LEFT_MS,
PAYOUT_MS,
POT_PRIZES,
POT_RANDOM,
RACE_LEAD_MS,
SIDE_POT,
STARS,
START_MONEY,
cardsPerRaceFor,
handSizeFor,
hotStreakActionSchema,
hotStreakOptionsSchema,
modeFor,
ticketsPerPlayer,
type BetMode,
type HotStreakAction,
type HotStreakOptions,
type HotStreakState,
type PayLine,
type PotBet,
type RaceFlags,
type RaceLine,
type RaceResult,
type Racer,
type Ticket,
} from './rules';
export * from './cards';
export * from './rules';
export { placesOf, podiumOf, sideAnswer, starTarget } from './race';
// ---------------------------------------------------------------- view types
export interface HsDraftOption {
stack: StackId;
tier: Tier;
/** 거꾸로 is allowed on this stack (house rule on + mascot stack). */
reverse: boolean;
}
export interface HsRaceView {
no: number;
racers: Racer[];
trackEnd: number;
/** Cards flipped since the last shuffle (kinds). */
flipped: CardBase[];
deckLeft: number;
burned: number;
passes: number;
top: MascotId[];
bottom: MascotId[][];
over: boolean;
flags: RaceFlags;
log: RaceLine[];
nextFlipAt: number;
hurry: PlayerId[];
}
export interface HsRankRow {
rank: number;
player: PlayerId;
money: number;
left: boolean;
story: string | null;
}
export interface HotStreakView {
options: HotStreakOptions;
me: PlayerId | null;
seats: PlayerId[];
mode: BetMode;
perRace: 0 | 1 | 2;
handSize: number;
phase: HotStreakState['phase'];
raceNo: number;
races: number;
final: boolean;
firstPlayer: PlayerId;
money: Record<PlayerId, number>;
stacks: Record<StackId, Tier[]>;
tickets: Record<PlayerId, Ticket[]>;
side: { id: SideId; text: string };
/** Race deck shown face up (1경주 전·상금 나누기), kinds sorted by mascot. Empty when it's hidden. */
faceUp: CardBase[];
known: CardBase[];
seenLast: CardBase[];
/** My hand (ids for SUBMIT). Null for spectators and in 상금 나누기. */
hand: { id: CardId; base: CardBase }[] | null;
/** What I put in this race (kinds). */
myPut: CardBase[] | null;
/** Who put their card(s) in (not which). */
put: Record<PlayerId, boolean>;
/** 상금 나누기 bets: mine always, everybody's once all are in. */
potBets: Record<PlayerId, PotBet | null>;
potDone: Record<PlayerId, boolean>;
myPotKey: string | null;
draft: { order: PlayerId[]; at: number; picker: PlayerId } | null;
doubleFor: PlayerId | null;
race: HsRaceView | null;
results: RaceResult[];
ready: PlayerId[];
left: PlayerId[];
away: PlayerId[];
/** What I may do right now. */
legal: {
draft: HsDraftOption[] | null;
double: number[] | null;
submit: { cards: CardId[]; count: number } | null;
pot: { last: boolean; doubleRequired: boolean } | null;
hurry: boolean;
ready: boolean;
};
stars: number[];
hurdles: number[];
deadlineAt: number | null;
payoutAt: number | null;
turnSeq: number;
result: { ranking: HsRankRow[]; summary: string; reason: GameResult['reason'] } | null;
}
// ---------------------------------------------------------------- helpers
type S = HotStreakState;
type A = HotStreakAction;
type ClientA = Exclude<A, { type: 'TIMEOUT' }>;
const isIn = (s: S, p: PlayerId) => !s.left.includes(p);
const inGame = (s: S) => s.seats.filter((p) => isIn(s, p));
const isFinal = (s: S) => s.raceNo >= s.options.races;
const flipMs = (s: S) => Math.round(s.options.flipSeconds * 1000);
const raceOpts = (s: S, log = true): RaceOpts => ({ burn: s.options.burn, hurdles: s.options.hurdles, log });
const potKey = (s: S, p: PlayerId, b: PotBet) => `hs-bet-r${s.raceNo}-${p}-${b.mascot}${b.last ? 'L' : ''}-${b.side}-${b.doubled ?? 'x'}`;
const MASCOT_ORDER = (b: CardBase) => {
const i = MASCOT_IDS.indexOf(b.split('-')[0] as MascotId);
return i < 0 ? 9 : i;
};
const sortCards = (cards: CardBase[]) => [...cards].sort((a, b) => MASCOT_ORDER(a) - MASCOT_ORDER(b) || ALL_CARDS.indexOf(a) - ALL_CARDS.indexOf(b));
function ctxOf(s: S, rng: Rng): RaceCtx {
return {
rng,
regen: (cards) => {
s.gen++;
return cards.map((c) => withGen(baseOf(c), s.gen));
},
};
}
function remember(s: S, bases: CardBase[]): void {
for (const b of bases) if (!s.known.includes(b)) s.known.push(b);
}
/** Players the game waits on (see docs/09 §2: display + timer; validation is separate). */
function activeOf(s: S): PlayerId[] {
switch (s.phase) {
case 'draft':
if (s.mode === 'pots') return inGame(s).filter((p) => s.potBets[p] === null);
return [s.seats[s.draftOrder[s.draftAt]!]!];
case 'double':
return s.doubleFor ? [s.doubleFor] : [];
case 'submit':
return inGame(s).filter((p) => s.submitted[p] === null);
case 'race':
return inGame(s).filter((p) => !s.race!.hurry.includes(p));
case 'payout':
return inGame(s).filter((p) => !s.ready.includes(p));
default:
return [];
}
}
function refreshDeadline(s: S, now: number): void {
if (s.phase === 'race' || s.phase === 'payout' || s.phase === 'finished') {
s.deadlineAt = null;
return;
}
const act = activeOf(s);
if (!act.length) {
s.deadlineAt = null;
return;
}
const allAway = act.every((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER);
if (s.phase === 'submit' || (s.phase === 'draft' && s.mode === 'pots')) {
s.deadlineAt = allAway ? Math.min(s.phaseDeadline ?? Infinity, now + AWAY_MS) : s.phaseDeadline;
return;
}
if (act.some((p) => !isIn(s, p))) s.deadlineAt = now + LEFT_MS;
else if (allAway) s.deadlineAt = now + AWAY_MS;
else s.deadlineAt = s.options.turnSeconds === null ? null : now + s.options.turnSeconds * 1000;
}
function snake(start: number, n: number, rounds: number): number[] {
const fwd = Array.from({ length: n }, (_, k) => (start + k) % n);
const out: number[] = [];
for (let r = 0; r < rounds; r++) out.push(...(r % 2 === 0 ? fwd : [...fwd].reverse()));
return out;
}
const freshStacks = (): Record<StackId, Tier[]> => Object.fromEntries(STACK_IDS.map((k) => [k, [1, 2, 3] as Tier[]])) as Record<StackId, Tier[]>;
/** Mascot whose face-up cards push it furthest (timeout default); ties in G-H-D-M order. */
function favourite(s: S, among: MascotId[]): MascotId {
let best = among[0]!;
let bestV = -Infinity;
for (const m of among) {
const v = s.faceUp.reduce((t, c) => t + forwardValue(c, m), 0);
if (v > bestV) {
bestV = v;
best = m;
}
}
return best;
}
// ---------------------------------------------------------------- phases
function startBetting(s: S, rng: Rng, ev: GameEvent[], now: number): void {
s.phase = 'draft';
s.stacks = freshStacks();
s.tickets = Object.fromEntries(s.seats.map((p) => [p, []]));
s.potBets = Object.fromEntries(s.seats.map((p) => [p, null]));
s.submitted = Object.fromEntries(s.seats.map((p) => [p, null]));
s.ready = [];
s.doubleFor = null;
s.turnSeq++;
if (s.mode === 'tickets') {
s.draftOrder = snake(s.startSeat, s.seats.length, ticketsPerPlayer(s.seats.length));
s.draftAt = 0;
s.phaseDeadline = null;
} else {
s.draftOrder = [];
s.draftAt = 0;
s.phaseDeadline = s.options.turnSeconds === null ? null : now + s.options.turnSeconds * 1000;
for (const p of s.seats) if (!isIn(s, p)) s.potBets[p] = defaultPotBet(s);
if (inGame(s).every((p) => s.potBets[p] !== null)) beginRace(s, rng, ev, now);
}
}
function startSubmit(s: S, rng: Rng, ev: GameEvent[], now: number): void {
s.phase = 'submit';
s.turnSeq++;
s.phaseDeadline = s.options.turnSeconds === null ? null : now + s.options.turnSeconds * 1000;
for (const p of s.seats) if (!isIn(s, p)) putIn(s, p, s.hands[p]!.slice(0, s.perRace), ev);
if (s.seats.every((p) => s.submitted[p] !== null)) beginRace(s, rng, ev, now);
}
function putIn(s: S, p: PlayerId, cards: CardId[], ev: GameEvent[]): void {
s.submitted[p] = [...cards];
s.hands[p] = s.hands[p]!.filter((c) => !cards.includes(c));
ev.push({ type: 'submitted', player: p });
}
function beginRace(s: S, rng: Rng, ev: GameEvent[], now: number): void {
const cards = [...s.pool, ...s.seats.flatMap((p) => s.submitted[p] ?? [])];
if (cards.length !== DECK_SIZE) throw new Error(`hot-streak: race deck has ${cards.length} cards`);
s.pool = [];
s.race = startRace(s.raceNo, cards, ctxOf(s, rng), raceOpts(s), now + RACE_LEAD_MS + flipMs(s));
s.phase = 'race';
s.phaseDeadline = null;
s.turnSeq++;
ev.push({ type: 'raceStart', race: s.raceNo });
ev.push({ type: 'burn', count: s.race.burned.length });
}
function flip(s: S, rng: Rng, ev: GameEvent[], now: number): void {
const r = s.race!;
const before = r.logSeq;
const top = r.deck[0];
if (top) remember(s, [baseOf(top)]);
flipOne(r, ctxOf(s, rng), raceOpts(s));
r.nextFlipAt = now + flipMs(s);
for (const l of r.log.filter((x) => x.n > before)) {
if (l.kind === 'flip') ev.push({ type: 'flip', card: l.card, n: l.n });
else if (l.kind === 'fold') ev.push({ type: 'fold', trackEnd: l.trackEnd });
}
if (r.over) toPayout(s, ev, now, 0);
}
/** Everyone agreed to 빨리 보기: the race runs to the end right now (the screen replays it fast). */
function hurryUp(s: S, rng: Rng, ev: GameEvent[], now: number): void {
const r = s.race!;
const before = r.processed;
const ctx = ctxOf(s, rng);
for (let guard = 0; !r.over && guard < 400; guard++) {
const top = r.deck[0];
if (top) remember(s, [baseOf(top)]);
flipOne(r, ctx, raceOpts(s));
}
if (!r.over) runToEnd(r, ctx, raceOpts(s));
ev.push({ type: 'hurried', cards: r.processed - before });
toPayout(s, ev, now, r.processed - before);
}
function ticketLabel(t: Ticket): string {
const who = isMascot(t.stack) ? MASCOTS[t.stack].name : t.stack;
return `${who} ${t.tier}단 ${t.side === 'safe' ? '안전' : '위험'}${t.reverse ? ' 거꾸로' : ''}`;
}
/** Settles this race (§6): every player's lines, money after (never below 0). Exported for tests. */
export function settle(s: S): RaceResult {
const r = s.race!;
const podium = podiumOf(r);
const places = placesOf(podium);
const sideId = s.sideDeck[0]!;
const yes = sideAnswer(sideId, r.flags, podium);
const final = isFinal(s);
const rows: RaceResult['rows'] = {};
const scale = s.options.potScale;
// 상금 나누기: shares per prize.
const shares = { rank: [0, 0, 0, 0], last: 0, side: 0 };
if (s.mode === 'pots') {
for (let rank = 1; rank <= 3; rank++) {
const n = s.seats.filter((p) => {
const b = s.potBets[p];
return b && !b.last && places[b.mascot].low === rank;
}).length;
shares.rank[rank - 1] = n ? Math.floor((POT_PRIZES[rank - 1]! * scale) / n) : 0;
}
const lastN = s.seats.filter((p) => s.potBets[p]?.last && places[s.potBets[p]!.mascot].low === 4).length;
shares.last = lastN ? Math.floor((LAST_POT * scale) / lastN) : 0;
const sideN = s.seats.filter((p) => s.potBets[p] && (s.potBets[p]!.side === 'YES') === yes).length;
shares.side = sideN ? Math.floor((SIDE_POT * scale) / sideN) : 0;
}
for (const p of s.seats) {
const lines: PayLine[] = [];
if (s.mode === 'tickets') {
for (const t of s.tickets[p]!) {
let amount: number;
let label = ticketLabel(t);
if (isMascot(t.stack)) {
const place = t.reverse ? places[t.stack].high : places[t.stack].low;
amount = mascotPay(t.tier, t.side, place, t.reverse);
label += ` · ${place}등`;
} else {
const right = (t.stack === 'YES') === yes;
const pay = SIDE_PAY[t.tier][t.side];
amount = right ? pay.win : pay.lose;
label += right ? ' · 맞힘' : ' · 틀림';
}
const doubled = final && s.options.finalBet === 'double' && t.doubled;
lines.push({ label, amount: doubled ? amount * 2 : amount, ...(doubled ? { doubled: true } : {}) });
}
} else {
const b = s.potBets[p];
if (b) {
const pl = places[b.mascot];
const won = b.last ? (pl.low === 4 ? shares.last : 0) : pl.low <= 3 ? shares.rank[pl.low - 1]! : 0;
const dm = final && s.options.finalBet === 'double' && b.doubled === 'mascot';
lines.push({ label: `${b.last ? '꼴찌 ' : ''}${MASCOTS[b.mascot].name} · ${pl.low}등`, amount: dm ? won * 2 : won, ...(dm ? { doubled: true } : {}) });
const right = (b.side === 'YES') === yes;
const ds = final && s.options.finalBet === 'double' && b.doubled === 'side';
const sw = right ? shares.side : 0;
lines.push({ label: `사이드 ${b.side} · ${right ? '맞힘' : '틀림'}`, amount: ds ? sw * 2 : sw, ...(ds ? { doubled: true } : {}) });
}
}
if (final && s.options.finalBet === 'bothBonus' && lines.length && lines.every((l) => l.amount > 0)) {
lines.push({ label: '모두 맞힘 보너스', amount: Math.floor(lines.reduce((t, l) => t + l.amount, 0) / lines.length) });
}
const total = lines.reduce((t, l) => t + l.amount, 0);
const before = s.money[p]!;
rows[p] = { lines, total, before, after: Math.max(0, before + total) };
}
return { no: s.raceNo, podium, side: { id: sideId, yes }, rows };
}
function toPayout(s: S, ev: GameEvent[], now: number, hurried: number): void {
const res = settle(s);
for (const p of s.seats) s.money[p] = res.rows[p]!.after;
s.results.push(res);
s.phase = 'payout';
s.ready = s.seats.filter((p) => !isIn(s, p));
s.payoutAt = now + PAYOUT_MS + (hurried ? Math.min(HURRY_REPLAY_CAP, hurried * HURRY_REPLAY_MS) : 0);
s.turnSeq++;
ev.push({ type: 'raceEnd', race: s.raceNo, podium: res.podium, side: res.side.yes });
}
/** First drafter of the next race (`draftStart`). Exported for tests. */
export function nextStart(s: S): number {
const n = s.seats.length;
switch (s.options.draftStart) {
case 'spread':
return (s.startSeat + (n <= 4 ? 1 : n <= 6 ? 2 : 3)) % n;
case 'poorest': {
const low = Math.min(...s.seats.map((p) => s.money[p]!));
// Ties: nearest counter-clockwise from the last first player (the last first player itself comes last).
for (let d = 1; d <= n; d++) {
const i = (s.startSeat - d + n * 2) % n;
if (s.money[s.seats[i]!] === low) return i;
}
return s.startSeat;
}
default:
return (s.startSeat + 1) % n;
}
}
function nextRace(s: S, rng: Rng, ev: GameEvent[], now: number): void {
if (s.raceNo >= s.options.races) return finishGame(s, ev);
const r = s.race!;
let cards = [...r.deck, ...r.burned, ...r.flipped];
s.seenLast = sortCards([...new Set(r.log.filter((l) => l.kind === 'flip').map((l) => l.card!))]);
s.raceNo++;
s.sideDeck.push(s.sideDeck.shift()!);
s.startSeat = nextStart(s);
const ctx = ctxOf(s, rng);
if (s.mode === 'tickets') {
cards = rng.shuffle(ctx.regen(cards));
for (const p of s.seats) s.hands[p]!.push(...cards.splice(0, s.perRace));
s.pool = cards;
s.faceUp = [];
} else {
// 상금 나누기: 3 random cards out, 3 unused ones in, all shown face up (§5.7-4).
const sh = rng.shuffle(cards);
const out = sh.splice(0, 3).map(baseOf);
const box = rng.shuffle(s.box);
const inc = box.splice(0, 3);
s.box = [...box, ...out];
s.pool = ctx.regen([...sh, ...inc]);
s.faceUp = sortCards(s.pool.map(baseOf));
remember(s, s.faceUp);
}
s.race = null;
s.payoutAt = null;
ev.push({ type: 'nextRace', race: s.raceNo });
startBetting(s, rng, ev, now);
}
function finishGame(s: S, ev: GameEvent[]): void {
s.phase = 'finished';
s.deadlineAt = null;
s.payoutAt = null;
s.phaseDeadline = null;
ev.push({ type: 'gameOver' });
}
function afterDraftPick(s: S, rng: Rng, ev: GameEvent[], now: number): void {
if (s.draftAt >= s.draftOrder.length) startSubmit(s, rng, ev, now);
}
// ---------------------------------------------------------------- defaults (timeouts, left players)
function defaultDraft(s: S): Extract<ClientA, { type: 'DRAFT' }> {
const mascots = MASCOT_IDS.filter((m) => s.stacks[m].length);
if (mascots.length) return { type: 'DRAFT', stack: favourite(s, mascots), side: 'safe' };
return { type: 'DRAFT', stack: s.stacks.NO.length ? 'NO' : 'YES', side: 'safe' };
}
function defaultDouble(s: S, p: PlayerId): number {
const ts = s.tickets[p]!;
let best = 0;
let bestV = -Infinity;
ts.forEach((t, i) => {
const v = isMascot(t.stack) ? MASCOT_PAY[t.tier][t.side][0] : SIDE_PAY[t.tier][t.side].win;
if (v > bestV) {
bestV = v;
best = i;
}
});
return best;
}
function defaultPotBet(s: S): PotBet {
return { mascot: favourite(s, [...MASCOT_IDS]), last: false, side: 'NO', doubled: isFinal(s) && s.options.finalBet === 'double' ? 'mascot' : null };
}
/** What the server plays for `p` when their time runs out. */
export function defaultAction(s: S, p: PlayerId): ClientA | null {
switch (s.phase) {
case 'draft':
if (s.mode === 'pots') return s.potBets[p] === null ? { type: 'POT_BET', ...defaultPotBet(s) } : null;
return defaultDraft(s);
case 'double':
return { type: 'DOUBLE', index: defaultDouble(s, p) };
case 'submit':
return s.submitted[p] === null ? { type: 'SUBMIT', cards: s.hands[p]!.slice(0, s.perRace) } : null;
default:
return null;
}
}
function perform(s: S, p: PlayerId, a: ClientA, rng: Rng, ev: GameEvent[], now: number): void {
switch (a.type) {
case 'DRAFT': {
const tier = s.stacks[a.stack].shift()!;
const t: Ticket = { stack: a.stack, tier, side: a.side, reverse: !!a.reverse && isMascot(a.stack), doubled: false };
s.tickets[p]!.push(t);
s.draftAt++;
s.turnSeq++;
ev.push({ type: 'drafted', player: p, stack: a.stack, tier, side: a.side, reverse: t.reverse });
if (isFinal(s) && s.options.finalBet === 'double' && s.tickets[p]!.length === ticketsPerPlayer(s.seats.length)) {
s.phase = 'double';
s.doubleFor = p;
return;
}
return afterDraftPick(s, rng, ev, now);
}
case 'DOUBLE':
s.tickets[p]![a.index]!.doubled = true;
s.doubleFor = null;
s.phase = 'draft';
s.turnSeq++;
ev.push({ type: 'doubled', player: p, index: a.index });
return afterDraftPick(s, rng, ev, now);
case 'POT_BET':
s.potBets[p] = { mascot: a.mascot, last: a.last, side: a.side, doubled: a.doubled };
ev.push({ type: 'betPlaced', player: p });
if (inGame(s).every((q) => s.potBets[q] !== null)) beginRace(s, rng, ev, now);
return;
case 'SUBMIT':
putIn(s, p, a.cards, ev);
if (s.seats.every((q) => s.submitted[q] !== null)) beginRace(s, rng, ev, now);
return;
case 'HURRY': {
const r = s.race!;
r.hurry = r.hurry.includes(p) ? r.hurry.filter((q) => q !== p) : [...r.hurry, p];
ev.push({ type: 'hurry', player: p, on: r.hurry.includes(p) });
if (inGame(s).every((q) => r.hurry.includes(q))) hurryUp(s, rng, ev, now);
return;
}
case 'READY':
s.ready.push(p);
if (inGame(s).every((q) => s.ready.includes(q))) nextRace(s, rng, ev, now);
return;
case 'LEAVE':
s.left.push(p);
ev.push({ type: 'left', player: p });
if (inGame(s).length < 2) return finishGame(s, ev);
s.turnSeq++;
if (s.phase === 'submit' && s.submitted[p] === null) {
putIn(s, p, s.hands[p]!.slice(0, s.perRace), ev);
if (s.seats.every((q) => s.submitted[q] !== null)) beginRace(s, rng, ev, now);
} else if (s.phase === 'draft' && s.mode === 'pots') {
if (s.potBets[p] === null) s.potBets[p] = defaultPotBet(s);
if (inGame(s).every((q) => s.potBets[q] !== null)) beginRace(s, rng, ev, now);
} else if (s.phase === 'race') {
if (inGame(s).every((q) => s.race!.hurry.includes(q))) hurryUp(s, rng, ev, now);
} else if (s.phase === 'payout') {
if (!s.ready.includes(p)) s.ready.push(p);
if (inGame(s).every((q) => s.ready.includes(q))) nextRace(s, rng, ev, now);
}
return;
}
}
// ---------------------------------------------------------------- result
function rankRows(s: S): HsRankRow[] {
const rows = s.seats.map((p) => ({ player: p, money: s.money[p]!, left: !isIn(s, p) }));
rows.sort((a, b) => Number(a.left) - Number(b.left) || b.money - a.money);
const out: HsRankRow[] = [];
rows.forEach((r, i) => {
const prev = out[i - 1];
const tied = prev && prev.left === r.left && prev.money === r.money;
out.push({ ...r, rank: tied ? prev.rank : i + 1, story: s.options.lifeStory ? lifeStory(r.money) : null });
});
return out;
}
function buildResult(s: S): NonNullable<HotStreakView['result']> {
const ranking = rankRows(s);
const winners = ranking.filter((r) => r.rank === 1);
const early = s.left.length > 0 && inGame(s).length < 2;
const second = ranking.find((r) => r.rank > 1);
let summary = winners.length > 1 ? `공동 1위 ${winners.length}명 $${winners[0]!.money}` : `1위 $${winners[0]!.money}${second ? ` · ${second.rank}위 $${second.money}` : ''}`;
if (early) summary = `다른 사람이 모두 나갔어요. ${summary}`;
return { ranking, summary, reason: early ? 'resign' : 'normal' };
}
// ---------------------------------------------------------------- legal moves
function draftOptions(s: S): HsDraftOption[] {
return STACK_IDS.filter((k) => s.stacks[k].length).map((k) => ({ stack: k, tier: s.stacks[k][0]!, reverse: s.options.reverseBets && isMascot(k) }));
}
function legalFor(s: S, p: PlayerId): ClientA[] {
if (!isIn(s, p) || !s.seats.includes(p)) return [];
switch (s.phase) {
case 'draft': {
if (s.mode === 'pots') {
if (s.potBets[p] !== null) return [];
const out: ClientA[] = [];
const dbl: (PotBet['doubled'])[] = isFinal(s) && s.options.finalBet === 'double' ? ['mascot', 'side'] : [null];
for (const m of MASCOT_IDS)
for (const last of s.options.reverseBets ? [false, true] : [false])
for (const side of ['YES', 'NO'] as const) for (const doubled of dbl) out.push({ type: 'POT_BET', mascot: m, last, side, doubled });
return out;
}
if (activeOf(s)[0] !== p) return [];
const out: ClientA[] = [];
for (const o of draftOptions(s))
for (const side of ['safe', 'risky'] as const) {
out.push({ type: 'DRAFT', stack: o.stack, side });
if (o.reverse) out.push({ type: 'DRAFT', stack: o.stack, side, reverse: true });
}
return out;
}
case 'double':
return s.doubleFor === p ? s.tickets[p]!.map((_, index) => ({ type: 'DOUBLE' as const, index })) : [];
case 'submit': {
if (s.submitted[p] !== null) return [];
const h = s.hands[p]!;
if (s.perRace === 1) return h.map((c) => ({ type: 'SUBMIT' as const, cards: [c] }));
const out: ClientA[] = [];
for (let i = 0; i < h.length; i++) for (let j = i + 1; j < h.length; j++) out.push({ type: 'SUBMIT', cards: [h[i]!, h[j]!] });
return out;
}
case 'race':
return s.race!.hurry.includes(p) ? [] : [{ type: 'HURRY' }];
case 'payout':
return s.ready.includes(p) ? [] : [{ type: 'READY' }];
default:
return [];
}
}
// ---------------------------------------------------------------- definition
export const hotStreak: GameDefinition<HotStreakState, HotStreakAction, HotStreakView, HotStreakOptions> = {
id: 'hot-streak',
nameKo: '핫스트릭',
minPlayers: 2,
maxPlayers: 10,
stateVersion: 1,
defaultOptions: hotStreakOptionsSchema.parse({}),
optionsSchema: hotStreakOptionsSchema as unknown as ZodType<HotStreakOptions>,
actionSchema: hotStreakActionSchema as unknown as ZodType<HotStreakAction>,
playersFor(o) {
return o.bettingMode === 'tickets' ? { min: 2, max: 9 } : { min: 2, max: 10 };
},
setup({ players, options, rng, now }) {
const n = players.length;
const mode = modeFor(options.bettingMode, n);
if (n < 2 || n > (mode === 'tickets' ? 9 : 10)) throw new Error(`hot-streak: ${mode === 'tickets' ? '티켓 뽑기는 2~9명' : '2~10명'}이 할 수 있어요.`);
const perRace = cardsPerRaceFor(options, n, mode);
const handSize = handSizeFor(perRace, n);
const randomN = mode === 'pots' ? POT_RANDOM : DECK_SIZE - 4 - n * perRace;
const bundleN = randomN + n * handSize;
const rest = ALL_CARDS.filter((c) => !STARTERS.includes(c));
let bundle: CardBase[];
let box: CardBase[];
if (options.spicyDeck) {
// 넘어지기 4장은 꼭 덱이나 누군가의 손에 (§4-2).
const others = rng.shuffle(rest.filter((c) => !c.endsWith('-FD')));
bundle = rng.shuffle([...rest.filter((c) => c.endsWith('-FD')), ...others.slice(0, bundleN - 4)]);
box = others.slice(bundleN - 4);
} else {
const sh = rng.shuffle(rest);
bundle = sh.slice(0, bundleN);
box = sh.slice(bundleN);
}
const gen = 1;
const poolBases = [...STARTERS, ...bundle.slice(0, randomN)];
const dealt = bundle.slice(randomN);
const s: S = {
options,
seats: [...players],
mode,
perRace,
handSize,
phase: 'draft',
raceNo: 1,
startSeat: rng.int(n),
money: Object.fromEntries(players.map((p) => [p, mode === 'pots' ? 0 : START_MONEY])),
pool: poolBases.map((b) => withGen(b, gen)),
faceUp: sortCards(poolBases),
known: sortCards(poolBases),
seenLast: [],
box,
hands: Object.fromEntries(players.map((p, i) => [p, dealt.slice(i * handSize, (i + 1) * handSize).map((b) => withGen(b, gen))])),
submitted: Object.fromEntries(players.map((p) => [p, null])),
stacks: freshStacks(),
tickets: Object.fromEntries(players.map((p) => [p, []])),
potBets: Object.fromEntries(players.map((p) => [p, null])),
draftOrder: [],
draftAt: 0,
doubleFor: null,
sideDeck: rng.shuffle(SIDE_IDS),
race: null,
results: [],
ready: [],
left: [],
timeouts: Object.fromEntries(players.map((p) => [p, 0])),
gen,
turnSeq: 0,
deadlineAt: null,
phaseDeadline: null,
payoutAt: null,
};
startBetting(s, rng, [], now);
refreshDeadline(s, now);
return s;
},
validate(s, actor, a) {
if (!s.seats.includes(actor)) return fail('이 게임의 참가자가 아니에요.');
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
if (a.type === 'TIMEOUT') {
if (s.phase === 'race' || s.phase === 'payout') return ok;
return activeOf(s).includes(actor) ? ok : fail('지금은 시간 초과를 처리할 수 없어요.');
}
if (!isIn(s, actor)) return fail('이미 나간 자리예요.');
switch (a.type) {
case 'LEAVE':
return ok;
case 'DRAFT': {
if (s.phase !== 'draft' || s.mode !== 'tickets') return fail('지금은 티켓을 뽑을 때가 아니에요.');
if (activeOf(s)[0] !== actor) return fail('지금은 내 차례가 아니에요.');
if (!s.stacks[a.stack].length) return fail('그 더미는 비었어요.');
if (a.reverse && (!s.options.reverseBets || !isMascot(a.stack))) return fail('거꾸로 티켓은 이 방에서 쓸 수 없어요.');
return ok;
}
case 'DOUBLE':
if (s.phase !== 'double' || s.doubleFor !== actor) return fail('지금은 두 배 티켓을 고를 때가 아니에요.');
return a.index < s.tickets[actor]!.length ? ok : fail('내 티켓 중에서 골라 주세요.');
case 'POT_BET': {
if (s.phase !== 'draft' || s.mode !== 'pots') return fail('지금은 상금 나누기 베팅을 할 때가 아니에요.');
if (s.potBets[actor] !== null) return fail('이미 적었어요.');
if (a.last && !s.options.reverseBets) return fail('꼴찌 걸기는 이 방에서 쓸 수 없어요.');
const need = isFinal(s) && s.options.finalBet === 'double';
if (need && a.doubled === null) return fail('마지막 경주에는 두 배로 할 베팅을 골라 주세요.');
if (!need && a.doubled !== null) return fail('두 배는 마지막 경주에만 할 수 있어요.');
return ok;
}
case 'SUBMIT': {
if (s.phase !== 'submit') return fail('지금은 카드를 넣을 때가 아니에요.');
if (s.submitted[actor] !== null) return fail('이미 카드를 넣었어요.');
if (a.cards.length !== s.perRace) return fail(`카드 ${s.perRace}장을 골라 주세요.`);
if (new Set(a.cards).size !== a.cards.length) return fail('같은 카드를 두 번 고를 수 없어요.');
return a.cards.every((c) => s.hands[actor]!.includes(c)) ? ok : fail('내 손에 있는 카드만 넣을 수 있어요.');
}
case 'HURRY':
return s.phase === 'race' ? ok : fail('지금은 경주 중이 아니에요.');
case 'READY':
if (s.phase !== 'payout') return fail('지금은 정산 중이 아니에요.');
return s.ready.includes(actor) ? fail('이미 눌렀어요.') : ok;
}
return fail('알 수 없는 행동이에요.');
},
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const ev: GameEvent[] = [];
const seq = s.turnSeq;
if (a.type === 'TIMEOUT') {
if (s.phase === 'race') flip(s, rng, ev, now);
else if (s.phase === 'payout') nextRace(s, rng, ev, now);
else {
s.timeouts[actor] = (s.timeouts[actor] ?? 0) + 1;
ev.push({ type: 'timeout', player: actor });
if (s.timeouts[actor] === AWAY_AFTER) ev.push({ type: 'away', player: actor });
const d = defaultAction(s, actor);
if (d) perform(s, actor, d, rng, ev, now);
}
} else {
if (a.type !== 'LEAVE') s.timeouts[actor] = 0;
perform(s, actor, a, rng, ev, now);
}
if (s.phase === 'finished') s.deadlineAt = null;
else if (s.turnSeq !== seq || a.type === 'TIMEOUT' || a.type === 'LEAVE') refreshDeadline(s, now);
return { state: s, events: ev };
},
view(s, viewer) {
const me = viewer !== null && s.seats.includes(viewer) ? viewer : null;
const r = s.race;
const allBet = s.mode === 'pots' && s.phase !== 'draft';
const potBets: HotStreakView['potBets'] = {};
for (const p of s.seats) potBets[p] = s.potBets[p] && (allBet || p === me) ? { ...s.potBets[p]! } : null;
const my = me && isIn(s, me) ? me : null;
const legal: HotStreakView['legal'] = { draft: null, double: null, submit: null, pot: null, hurry: false, ready: false };
if (my) {
if (s.phase === 'draft' && s.mode === 'tickets' && activeOf(s)[0] === my) legal.draft = draftOptions(s);
if (s.phase === 'double' && s.doubleFor === my) legal.double = s.tickets[my]!.map((_, i) => i);
if (s.phase === 'submit' && s.submitted[my] === null) legal.submit = { cards: [...s.hands[my]!], count: s.perRace };
if (s.phase === 'draft' && s.mode === 'pots' && s.potBets[my] === null)
legal.pot = { last: s.options.reverseBets, doubleRequired: isFinal(s) && s.options.finalBet === 'double' };
legal.hurry = s.phase === 'race';
legal.ready = s.phase === 'payout' && !s.ready.includes(my);
}
const mine = me ? s.potBets[me] : null;
return {
options: s.options,
me,
seats: [...s.seats],
mode: s.mode,
perRace: s.perRace,
handSize: s.handSize,
phase: s.phase,
raceNo: s.raceNo,
races: s.options.races,
final: isFinal(s),
firstPlayer: s.seats[s.startSeat]!,
money: { ...s.money },
stacks: structuredClone(s.stacks),
tickets: structuredClone(s.tickets),
side: { id: s.sideDeck[0]!, text: sideQuestion(s.sideDeck[0]!) },
faceUp: [...s.faceUp],
known: [...s.known],
seenLast: [...s.seenLast],
hand: me && s.mode === 'tickets' ? s.hands[me]!.map((id) => ({ id, base: baseOf(id) })) : null,
myPut: me && s.submitted[me] ? s.submitted[me]!.map(baseOf) : null,
put: Object.fromEntries(s.seats.map((p) => [p, s.submitted[p] !== null])),
potBets,
potDone: Object.fromEntries(s.seats.map((p) => [p, s.potBets[p] !== null])),
myPotKey: me && mine && s.phase === 'draft' ? potKey(s, me, mine) : null,
draft:
s.mode === 'tickets' && (s.phase === 'draft' || s.phase === 'double')
? { order: s.draftOrder.map((i) => s.seats[i]!), at: s.draftAt, picker: s.seats[s.draftOrder[Math.min(s.draftAt, s.draftOrder.length - 1)]!]! }
: null,
doubleFor: s.doubleFor,
race: r
? {
no: r.no,
racers: MASCOT_IDS.map((id) => ({ ...r.racers[id] })),
trackEnd: r.trackEnd,
flipped: r.flipped.map(baseOf),
deckLeft: r.deck.length,
burned: r.burned.length,
passes: r.passes,
top: [...r.top],
bottom: r.bottom.map((g) => [...g]),
over: r.over,
flags: { ...r.flags },
log: structuredClone(r.log.slice(-80)),
nextFlipAt: r.nextFlipAt,
hurry: [...r.hurry],
}
: null,
results: structuredClone(s.results),
ready: [...s.ready],
left: [...s.left],
away: s.seats.filter((p) => isIn(s, p) && (s.timeouts[p] ?? 0) >= AWAY_AFTER),
legal,
stars: [...STARS],
hurdles: s.options.hurdles ? [...HURDLES] : [],
deadlineAt: s.phase === 'race' ? r!.nextFlipAt : s.phase === 'payout' ? s.payoutAt : s.deadlineAt,
payoutAt: s.payoutAt,
turnSeq: s.turnSeq,
result: s.phase === 'finished' ? buildResult(s) : null,
};
},
activePlayers: activeOf,
deadline(s) {
if (s.phase === 'finished') return null;
if (s.phase === 'race') return s.race!.nextFlipAt;
if (s.phase === 'payout') return s.payoutAt;
return s.deadlineAt;
},
/** The race and the payout pause run on the server clock: one seat drives it (§8.2). */
timeoutPlayers(s) {
if (s.phase === 'race' || s.phase === 'payout') return inGame(s).slice(0, 1);
return activeOf(s);
},
/** A disconnected driver never speeds the race up: cards flip on the clock only. */
timeoutNotBefore(s) {
if (s.phase === 'race') return s.race!.nextFlipAt;
if (s.phase === 'payout') return s.payoutAt;
return null;
},
disconnectGraceMs(s) {
return s.phase === 'race' || s.phase === 'payout' ? 0 : null;
},
onTimeout() {
return { type: 'TIMEOUT' };
},
onLeave(s, player) {
if (s.phase === 'finished' || !s.seats.includes(player) || !isIn(s, player)) return null;
return { type: 'LEAVE' };
},
result(s): GameResult | null {
if (s.phase !== 'finished') return null;
const r = buildResult(s);
const groups = new Map<number, PlayerId[]>();
for (const row of r.ranking) groups.set(row.rank, [...(groups.get(row.rank) ?? []), row.player]);
const scores: Record<PlayerId, number> = {};
for (const row of r.ranking) scores[row.player] = row.money;
return {
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ps]) => ps),
scores,
scoreText: Object.fromEntries(Object.entries(scores).map(([p, n]) => [p, `$${n}`])),
summary: r.summary,
reason: r.reason,
};
},
/** Test / computer helper: every choice the player has now (LEAVE left out). */
legalActions: legalFor,
/** Test helper: hidden card ids, the next side questions and secret 상금 나누기 bets. */
secretsOf(s, player) {
const out = [...(s.hands[player] ?? []), ...(s.submitted[player] ?? [])];
// Deck order, burned cards and the cards waiting for the race: nobody's (listed under every player).
out.push(...s.pool);
if (s.race) out.push(...s.race.deck, ...s.race.burned);
// The coming side questions (their order; plain ids like "out" also appear as view keys).
out.push(`hs-sides:${s.sideDeck.slice(1, s.sideDeck.length - (s.raceNo - 1)).join(',')}`);
const b = s.potBets[player];
if (b && s.phase === 'draft') out.push(potKey(s, player, b));
return out;
},
};

View File

@@ -0,0 +1,440 @@
/**
* 핫스트릭 경주 처리 (docs/games/hot-streak.md §5.4–§5.6). Pure functions over `RaceState`; the engine runs one card
* per server tick (`flipOne`), the computer's Monte Carlo runs whole races with `log: false` (sim.ts).
*
* Space numbers count the distance to the finish line (1 = right in front, 13 = the back end); 0 = across the line.
* Moving toward the finish is −1 per space. Lanes are 0 (left end, facing the finish) … 3 (right end).
*/
import type { Rng } from '@bg/engine';
import { MASCOTS, MASCOT_IDS, baseOf, cardInfo, cardText, josa, type CardBase, type CardId, type MascotId, type SideId } from './cards';
import {
CARD_CAP,
FOLDS,
HURDLES,
START_POS,
STARS,
STRETCH,
type RaceFlags,
type RaceLine,
type RaceLineKind,
type RaceMove,
type RaceState,
type Racer,
} from './rules';
export interface RaceOpts {
burn: number;
hurdles: boolean;
/** Keep the public record (off in simulations). */
log: boolean;
}
export interface RaceCtx {
rng: Rng;
/** New ids for a fresh shuffle (the engine bumps `gen`; simulations keep the kinds). */
regen: (cards: CardId[]) => CardId[];
}
const nm = (id: MascotId) => MASCOTS[id].name;
const ga = (id: MascotId) => josa(nm(id), '이', '가');
const eul = (id: MascotId) => josa(nm(id), '을', '를');
export const freshFlags = (): RaceFlags => ({
twoDown: false,
twoAtLine: false,
anyDq: false,
crawlStretch: false,
emptyStretchAtWin: null,
out: false,
sameSpace: false,
knockout: false,
});
export function startRacers(): Record<MascotId, Racer> {
const out = {} as Record<MascotId, Racer>;
for (const id of MASCOT_IDS) out[id] = { id, lane: MASCOTS[id].lane, pos: START_POS, facing: 'fwd', down: false, status: 'racing' };
return out;
}
const snap = (r: RaceState): Racer[] => MASCOT_IDS.map((id) => ({ ...r.racers[id] }));
function pushLine(r: RaceState, o: RaceOpts, kind: RaceLineKind, text: string, extra: Partial<RaceLine> = {}): void {
if (!o.log) return;
r.log.push({ n: ++r.logSeq, kind, text, ...extra, racers: snap(r), trackEnd: r.trackEnd });
}
/** Shuffles the race cards, burns `burn` face down and sets the mascots at the start. */
export function startRace(no: number, cards: CardId[], ctx: RaceCtx, o: RaceOpts, nextFlipAt: number): RaceState {
const deck = ctx.rng.shuffle(ctx.regen(cards));
const burned = deck.splice(0, o.burn);
const r: RaceState = {
no,
racers: startRacers(),
trackEnd: 13,
deck,
burned,
flipped: [],
passes: 0,
top: [],
bottom: [],
flags: freshFlags(),
processed: 0,
over: false,
log: [],
logSeq: 0,
nextFlipAt,
hurry: [],
};
pushLine(r, o, 'start', `${no}번째 경주! 덱 ${cards.length}장을 섞었어요.`);
pushLine(r, o, 'burn', `3, 2, 1… 카드 ${burned.length}장을 보지 않고 버렸어요. 출발!`);
return r;
}
const racingOf = (r: RaceState): Racer[] => MASCOT_IDS.map((id) => r.racers[id]).filter((x) => x.status === 'racing');
export const placedCount = (r: RaceState): number => r.top.length + r.bottom.reduce((n, g) => n + g.length, 0);
/** One card being worked out: collects the line's notes, effects and walked cells. */
class Work {
notes: string[] = [];
fx: NonNullable<RaceLine['fx']> = [];
mv = new Map<MascotId, [number, number][]>();
constructor(
readonly r: RaceState,
readonly o: RaceOpts,
) {}
private cell(x: Racer, lane = x.lane, pos = x.pos): void {
if (!this.o.log) return;
let p = this.mv.get(x.id);
if (!p) this.mv.set(x.id, (p = [[x.lane, x.pos]]));
p.push([lane, pos]);
}
private note(s: string): void {
if (this.o.log) this.notes.push(s);
}
checkTwoDown(): void {
if (racingOf(this.r).filter((x) => x.down).length >= 2) this.r.flags.twoDown = true;
}
dq(group: Racer[], why: 'knockout' | 'side' | 'back' | 'fold' | 'cap'): void {
if (!group.length) return;
const r = this.r;
for (const x of group) x.status = 'dq';
r.bottom.push(group.map((x) => x.id));
r.flags.anyDq = true;
if (why === 'knockout') r.flags.knockout = true;
if (why === 'side' || why === 'back' || why === 'fold') r.flags.out = true;
const names = group.map((x) => nm(x.id)).join('·');
const reason = { knockout: '녹아웃', side: '옆으로 나감', back: '뒤로 나감', fold: '접힌 경주로에 깔림', cap: '경주가 너무 길어 끝냄' }[why];
this.note(`${names} 실격! (${reason}${group.length > 1 ? ', 동시 실격' : ''})`);
for (const x of group) this.fx.push({ id: x.id, t: 'dq' });
}
private finish(x: Racer): void {
const r = this.r;
x.status = 'finished';
x.pos = 0;
x.down = false;
r.top.push(x.id);
if (r.top.length === 1 && r.flags.emptyStretchAtWin === null) {
r.flags.emptyStretchAtWin = !racingOf(r).some((y) => y.pos >= 1 && y.pos <= STRETCH);
}
this.note(`${ga(x.id)} 결승선을 넘었어요! ${r.top.length}등!`);
this.fx.push({ id: x.id, t: 'finish', place: r.top.length });
}
/** Everyone standing still on the mover's cell is hit: up → down, already down → knocked out (together). */
private collide(x: Racer): void {
const hit = racingOf(this.r).filter((y) => y !== x && y.lane === x.lane && y.pos === x.pos);
if (!hit.length) return;
const ups = hit.filter((y) => !y.down);
const downs = hit.filter((y) => y.down);
for (const y of ups) {
y.down = true;
this.note(`쾅! ${ga(x.id)} ${eul(y.id)} 넘어뜨렸어요.`);
this.fx.push({ id: y.id, t: 'down' });
}
if (downs.length) {
this.note(`쾅! ${ga(x.id)} 넘어져 있던 ${downs.map((y) => nm(y.id)).join('·')}에 부딪혔어요.`);
this.dq(downs, 'knockout');
}
this.fx.push({ id: x.id, t: 'bump' });
this.checkTwoDown();
}
private crawlCheck(x: Racer, from: number, to: number): void {
if (x.down && ((from >= 1 && from <= STRETCH) || (to >= 1 && to <= STRETCH))) this.r.flags.crawlStretch = true;
}
/** One space along the lane (−1 = toward the finish). False when the move is over (finished / out). */
step(x: Racer, dir: -1 | 1): boolean {
const from = x.pos;
const np = from + dir;
this.crawlCheck(x, from, np);
if (np <= 0) {
this.cell(x, x.lane, 0);
this.finish(x);
return false;
}
if (np > this.r.trackEnd) {
this.cell(x, x.lane, np);
this.dq([x], 'back');
return false;
}
x.pos = np;
this.cell(x);
this.collide(x);
return true;
}
/** Sideways into the next lane (weave). */
lateral(x: Racer, d: -1 | 1): boolean {
const nl = x.lane + d;
this.crawlCheck(x, x.pos, x.pos);
if (nl < 0 || nl > 3) {
this.cell(x, nl, x.pos);
this.dq([x], 'side');
return false;
}
x.lane = nl;
this.cell(x);
this.collide(x);
return true;
}
/** Standing still on a hurdle after moving: falls (§5.5 허들). */
hurdle(x: Racer, moved: boolean): void {
if (!this.o.hurdles || !moved || x.status !== 'racing' || x.down) return;
if (!(HURDLES as readonly number[]).includes(x.pos) || x.pos > this.r.trackEnd) return;
x.down = true;
this.note(`${ga(x.id)} 허들에 걸려 넘어졌어요.`);
this.fx.push({ id: x.id, t: 'down' });
this.checkTwoDown();
}
moves(): RaceMove[] {
return [...this.mv.entries()].map(([id, path]) => ({ id, path }));
}
}
const fdir = (x: Racer): -1 | 1 => (x.facing === 'fwd' ? -1 : 1);
/** Nearest star beyond the current space the way the mascot faces (finish zone counts toward the line); null = none. */
export function starTarget(x: Racer, trackEnd: number): number | null {
if (x.facing === 'fwd') {
const s = STARS.filter((p) => p < x.pos && p <= trackEnd);
return s.length ? Math.max(...s) : 0;
}
const s = STARS.filter((p) => p > x.pos && p <= trackEnd);
return s.length ? Math.min(...s) : null;
}
/** A mascot card for a mascot still on the track. */
function mascotCard(w: Work, x: Racer, base: CardBase): void {
const eff = cardInfo(base).effect;
const start = `${x.lane}:${x.pos}`;
const movedFrom = () => `${x.lane}:${x.pos}` !== start;
switch (eff.kind) {
case 'move': {
const dir = (eff.n > 0 ? fdir(x) : -fdir(x)) as -1 | 1;
const steps = x.down ? 1 : Math.abs(eff.n);
for (let i = 0; i < steps; i++) if (!w.step(x, dir)) return;
return w.hurdle(x, movedFrom());
}
case 'rise': {
if (x.down || x.facing === 'back') w.fx.push({ id: x.id, t: 'up' });
x.down = false;
x.facing = 'fwd';
for (let i = 0; i < eff.n; i++) if (!w.step(x, -1)) return;
return w.hurdle(x, movedFrom());
}
case 'star': {
const target = starTarget(x, w.r.trackEnd);
if (target === null) {
if (w.o.log) w.notes.push(`${ga(x.id)} 갈 별이 없어서 그대로예요.`);
return;
}
const dir = fdir(x);
const steps = x.down ? 1 : Math.abs(target - x.pos);
for (let i = 0; i < steps; i++) if (!w.step(x, dir)) return;
return w.hurdle(x, movedFrom());
}
case 'fall':
if (x.down) {
if (w.o.log) w.notes.push(`${ga(x.id)} 넘어진 채 또 넘어졌어요.`);
w.dq([x], 'knockout');
} else {
x.down = true;
w.fx.push({ id: x.id, t: 'down' });
w.checkTwoDown();
}
return;
case 'turn':
x.facing = x.facing === 'fwd' ? 'back' : 'fwd';
w.fx.push({ id: x.id, t: 'turn' });
return;
case 'weave': {
const dir = fdir(x);
const steps = x.down ? 1 : eff.n;
for (let i = 0; i < steps; i++) if (!w.step(x, dir)) return;
const right = MASCOTS[x.id].turn === 'right';
const d = (right === (x.facing === 'fwd') ? 1 : -1) as -1 | 1;
if (!w.lateral(x, d)) return;
return w.hurdle(x, true);
}
}
}
/** A green card: everyone on the track moves at once, no bumps and no finishing (stops at space 1). */
function greenCard(w: Work, base: CardBase): void {
const r = w.r;
const eff = cardInfo(base).effect;
const field = racingOf(r);
if (eff.kind === 'rise') {
for (const x of field) {
if (x.down || x.facing === 'back') w.fx.push({ id: x.id, t: 'up' });
x.down = false;
x.facing = 'fwd';
}
}
const n = eff.kind === 'move' || eff.kind === 'rise' ? eff.n : 0;
const outs: Racer[] = [];
const moved: Racer[] = [];
for (const x of field) {
const dir = n > 0 ? fdir(x) : -fdir(x);
const steps = x.down ? 1 : Math.abs(n);
const from = x.pos;
let to = from + dir * steps;
if (dir < 0) to = Math.max(1, to);
const path: [number, number][] = [[x.lane, from]];
for (let p = from; p !== to; ) path.push([x.lane, (p += dir)]);
if (x.down && path.some(([, p]) => p >= 1 && p <= STRETCH) && to !== from) r.flags.crawlStretch = true;
if (w.o.log && to !== from) w.mv.set(x.id, path);
if (to > r.trackEnd) {
outs.push(x);
continue;
}
if (to !== from) moved.push(x);
x.pos = to;
}
if (outs.length) w.dq(outs, 'back');
for (const x of moved) w.hurdle(x, true);
w.checkTwoDown();
}
function afterCard(r: RaceState): void {
const field = racingOf(r);
if (field.filter((x) => x.pos === 1).length >= 2) r.flags.twoAtLine = true;
const cells = new Set<string>();
for (const x of field) {
const k = `${x.lane}:${x.pos}`;
if (cells.has(k)) r.flags.sameSpace = true;
cells.add(k);
}
}
/** 3 or more placed: the race ends, the mascot still running takes the slot left. */
function checkEnd(r: RaceState, o: RaceOpts): boolean {
if (r.over) return true;
if (placedCount(r) < 3) return false;
for (const x of racingOf(r)) r.top.push(x.id);
r.over = true;
pushLine(r, o, 'end', `경주 끝! ${podiumOf(r).map((g, i) => `${i + 1}. ${g.map(nm).join('·')}`).join(' / ')}`);
return true;
}
/** Deck ran out: fold the track to the next line (everyone behind it is out together), then reshuffle and burn. */
function fold(r: RaceState, ctx: RaceCtx, o: RaceOpts): void {
const next = FOLDS.find((f) => f < r.trackEnd) ?? 0;
r.trackEnd = next;
const w = new Work(r, o);
const victims = racingOf(r).filter((x) => x.pos > next);
w.dq(victims, 'fold');
pushLine(r, o, 'fold', next > 0 ? `덱이 바닥났어요. 경주로가 ${next}번 칸까지 접혔어요.` : '덱이 또 바닥났어요. 경주로가 모두 접혔어요.', { notes: w.notes, fx: w.fx });
if (checkEnd(r, o)) return;
const cards = [...r.flipped, ...r.burned];
r.deck = ctx.rng.shuffle(ctx.regen(cards));
r.burned = r.deck.splice(0, o.burn);
r.flipped = [];
r.passes++;
pushLine(r, o, 'shuffle', `버린 카드까지 ${cards.length}장을 다시 섞고 ${r.burned.length}장을 버렸어요.`);
}
/** Turns over the top card and works it out (one server tick). */
export function flipOne(r: RaceState, ctx: RaceCtx, o: RaceOpts): void {
if (r.over) return;
const id = r.deck.shift();
if (id === undefined) throw new Error('hot-streak: empty race deck');
r.flipped.push(id);
r.processed++;
const base = baseOf(id);
const info = cardInfo(base);
const w = new Work(r, o);
let text = cardText(base);
if (info.who === 'all') greenCard(w, base);
else {
const x = r.racers[info.who];
if (x.status === 'racing') mascotCard(w, x, base);
else text += x.status === 'finished' ? ' (이미 들어와서 넘어가요)' : ' (실격이라 넘어가요)';
}
afterCard(r);
pushLine(r, o, 'flip', text, { card: base, notes: w.notes, mv: w.moves(), fx: w.fx });
if (checkEnd(r, o)) return;
if (r.processed >= CARD_CAP) {
const cap = new Work(r, o);
cap.dq(racingOf(r), 'cap');
pushLine(r, o, 'fold', '경주가 너무 길어져서 남은 마스코트를 모두 실격으로 끝냈어요.', { notes: cap.notes, fx: cap.fx });
checkEnd(r, o);
return;
}
if (!r.deck.length) fold(r, ctx, o);
}
/** Flips until the race is over (빨리 보기 / simulations). */
export function runToEnd(r: RaceState, ctx: RaceCtx, o: RaceOpts): void {
for (let guard = 0; !r.over && guard < CARD_CAP + 10; guard++) flipOne(r, ctx, o);
if (!r.over) throw new Error('hot-streak: race did not end');
}
// ---------------------------------------------------------------- places & side bets
/** Place groups, best first (finishers one by one, then DQ groups from the higher slots down). */
export function podiumOf(r: Pick<RaceState, 'top' | 'bottom'>): MascotId[][] {
return [...r.top.map((m) => [m]), ...[...r.bottom].reverse().map((g) => [...g])];
}
/** Slots each mascot's group covers: `low` (정산 등수, the lower place) and `high` (거꾸로 티켓). */
export function placesOf(podium: MascotId[][]): Record<MascotId, { high: number; low: number }> {
const out = {} as Record<MascotId, { high: number; low: number }>;
let at = 0;
for (const g of podium) {
for (const m of g) out[m] = { high: at + 1, low: at + g.length };
at += g.length;
}
return out;
}
export function sideAnswer(id: SideId, flags: RaceFlags, podium: MascotId[][]): boolean {
if (id.startsWith('bottom-')) return (placesOf(podium)[id.slice(7) as MascotId]?.low ?? 4) >= 3;
switch (id) {
case 'two-down':
return flags.twoDown;
case 'two-at-line':
return flags.twoAtLine;
case 'any-dq':
return flags.anyDq;
case 'crawl-stretch':
return flags.crawlStretch;
case 'empty-stretch':
return flags.emptyStretchAtWin === true;
case 'out':
return flags.out;
case 'same-space':
return flags.sameSpace;
case 'knockout':
return flags.knockout;
}
return false;
}

View File

@@ -0,0 +1,282 @@
/**
* 핫스트릭 옵션·상수·상태 타입 (docs/games/hot-streak.md §2, §4, §8).
*/
import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
import { MASCOT_IDS, STACK_IDS, type CardBase, type CardId, type Face, type MascotId, type SideId, type StackId, type Tier } from './cards';
// ---------------------------------------------------------------- options
const lit = <T extends number | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const hotStreakOptionsSchema = z.object({
bettingMode: z
.enum(['auto', 'tickets', 'pots'])
.default('auto')
.meta({
title: '베팅 방식',
labels: { auto: '자동(2~8명 티켓, 9~10명 상금 나누기 — 원작)', tickets: '티켓 뽑기(2~9명)', pots: '상금 나누기(2~10명, 모두 동시에 적기)' },
}),
races: lit(1, 3, 5)
.default(3)
.meta({ title: '경주 수', labels: { 1: '1번(맛보기)', 3: '3번(원작)', 5: '5번(긴 판)' } }),
finalBet: z
.enum(['double', 'bothBonus', 'none'])
.default('double')
.meta({
title: '마지막 경주 보너스',
labels: { double: '티켓 하나 두 배(원작)', bothBonus: '두 티켓 모두 맞히면 평균만큼 보너스', none: '없음' },
}),
draftStart: z
.enum(['rotate', 'spread', 'poorest'])
.default('rotate')
.meta({
title: '다음 경주 첫 순서',
labels: { rotate: '한 자리씩 옮겨요(원작)', spread: '사람이 많으면 두세 자리씩 건너뛰어요', poorest: '돈이 가장 적은 사람부터' },
}),
reverseBets: z.boolean().default(false).meta({ title: '(하우스 룰) 꼴찌 걸기(거꾸로 티켓)', labels: { true: '켜기', false: '끄기' } }),
cardsPerRace: lit(1, 2)
.default(1)
.meta({ title: '경주마다 넣는 비밀 카드(3~6명)', labels: { 1: '1장(원작)', 2: '2장(손패 4장, 더 시끌벅적)' } }),
burn: lit(3, 5)
.default(3)
.meta({ title: '경주 시작 때 버리는 카드', labels: { 3: '3장(원작)', 5: '5장(하우스 룰)' } }),
spicyDeck: z.boolean().default(false).meta({ title: '(하우스 룰) 넘어지기 카드 4장은 꼭 쓰기', labels: { true: '켜기', false: '끄기' } }),
hurdles: z.boolean().default(false).meta({ title: '(하우스 룰) 허들 칸(멈추면 넘어짐)', labels: { true: '켜기', false: '끄기' } }),
potScale: lit(1, 2, 3)
.default(1)
.meta({ title: '상금 크기(상금 나누기 모드)', labels: { 1: '×1(원작)', 2: '×2', 3: '×3' } }),
lifeStory: z.boolean().default(true).meta({ title: '끝나고 "인생 결과" 한 줄', labels: { true: '보여 줘요', false: '안 보여 줘요' } }),
turnSeconds: lit(20, 30, 60, null)
.default(30)
.meta({ title: '티켓 뽑기·카드 넣기 제한 시간', labels: { 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
flipSeconds: lit(1.2, 2, 3)
.default(2)
.meta({ title: '경주 카드 넘기는 간격', labels: { 1.2: '1.2초(빠르게)', 2: '2초', 3: '3초(천천히)' } }),
});
export type HotStreakOptions = z.infer<typeof hotStreakOptionsSchema>;
const mascot = z.enum(MASCOT_IDS);
const stack = z.enum(STACK_IDS as [StackId, ...StackId[]]);
export const hotStreakActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('DRAFT'), stack, side: z.enum(['safe', 'risky']), reverse: z.boolean().optional() }),
z.object({ type: z.literal('DOUBLE'), index: z.number().int().min(0).max(2) }),
z.object({
type: z.literal('POT_BET'),
mascot,
last: z.boolean(),
side: z.enum(['YES', 'NO']),
doubled: z.enum(['mascot', 'side']).nullable(),
}),
z.object({ type: z.literal('SUBMIT'), cards: z.array(z.string().max(16)).min(1).max(2) }),
z.object({ type: z.literal('HURRY') }),
z.object({ type: z.literal('READY') }),
z.object({ type: z.literal('LEAVE') }),
]);
export type HotStreakClientAction = z.infer<typeof hotStreakActionSchema>;
/** Client actions plus the system-only timer action (경주 카드 넘기기, 시간 초과 — docs/09 §2). */
export type HotStreakAction = HotStreakClientAction | { type: 'TIMEOUT' };
// ---------------------------------------------------------------- constants
/** Random cards added to the 4 starters (티켓 모드, 경주마다 1장 넣기): 18 − 4 − 인원 (§4 표, 9명은 우리 추정). */
export const POT_RANDOM = 14;
export const DECK_SIZE = 18;
/** Track length; folds shorten it 13 → 10 → 7 → 3 → 0 (§5.6). */
export const TRACK = 13;
export const FOLDS = [10, 7, 3, 0] as const;
export const START_POS = 11;
export const STARS = [1, 6, 13] as const;
export const HURDLES = [8, 5, 2] as const;
/** Last stretch (사이드 질문): spaces 1~3. */
export const STRETCH = 3;
/** Safety net: a race ends after this many cards (§8.6). */
export const CARD_CAP = 200;
export const START_MONEY = 10;
/** 상금 나누기 상금 (×potScale). §6.2 */
export const POT_PRIZES = [18, 12, 6] as const;
export const SIDE_POT = 18;
export const LAST_POT = 18;
export const AWAY_AFTER = 3;
export const AWAY_MS = 5000;
/** A player who left plays automatically after this long. */
export const LEFT_MS = 1000;
/** Pause before the first card of a race ("3, 2, 1… 출발!"). */
export const RACE_LEAD_MS = 2500;
/** Settlement screen (§8.5): this long, or until everybody presses READY. */
export const PAYOUT_MS = 8000;
/** After 빨리 보기 the screen still replays the race quickly: the payout waits this much per card (capped). */
export const HURRY_REPLAY_MS = 300;
export const HURRY_REPLAY_CAP = 12_000;
export type BetMode = 'tickets' | 'pots';
export const modeFor = (opt: HotStreakOptions['bettingMode'], n: number): BetMode => (opt === 'auto' ? (n >= 9 ? 'pots' : 'tickets') : opt);
/** Cards each player adds per race (2명 원작 2장, `cardsPerRace=2`는 3~6명만). */
export const cardsPerRaceFor = (o: HotStreakOptions, n: number, mode: BetMode): 0 | 1 | 2 => {
if (mode === 'pots') return 0;
if (n === 2) return 2;
return o.cardsPerRace === 2 && n >= 3 && n <= 6 ? 2 : 1;
};
export const handSizeFor = (k: number, n: number): number => (k === 0 ? 0 : n === 2 || k === 2 ? 4 : 3);
/** Tickets each player draws (2명이면 3장). */
export const ticketsPerPlayer = (n: number): number => (n === 2 ? 3 : 2);
// ---------------------------------------------------------------- race state
export type Facing = 'fwd' | 'back';
export type RacerStatus = 'racing' | 'finished' | 'dq';
export interface Racer {
id: MascotId;
lane: number;
/** Spaces left to the finish line (1..trackEnd); 0 once finished. */
pos: number;
facing: Facing;
down: boolean;
status: RacerStatus;
}
export interface RaceFlags {
twoDown: boolean;
twoAtLine: boolean;
anyDq: boolean;
crawlStretch: boolean;
/** Set when the first mascot finishes: was the stretch empty of the others? */
emptyStretchAtWin: boolean | null;
out: boolean;
sameSpace: boolean;
knockout: boolean;
}
/** One mascot's way through a card for the screen: cells walked ([lane, pos], pos 0 = finished). */
export interface RaceMove {
id: MascotId;
path: [number, number][];
}
export type RaceLineKind = 'start' | 'burn' | 'flip' | 'fold' | 'shuffle' | 'end';
/** Public race record (screen replay, `aria-live`). Each line carries the board right after it. */
export interface RaceLine {
n: number;
kind: RaceLineKind;
text: string;
/** Flipped card (kind only, never the id). */
card?: CardBase;
/** What happened besides the move (충돌·실격·결승). */
notes?: string[];
mv?: RaceMove[];
racers: Racer[];
trackEnd: number;
/** Bumps on screen ("쾅!", "실격!", "1등!"). */
fx?: { id: MascotId; t: 'bump' | 'down' | 'dq' | 'finish' | 'turn' | 'up'; place?: number }[];
}
export interface RaceState {
no: number;
racers: Record<MascotId, Racer>;
trackEnd: number;
deck: CardId[];
burned: CardId[];
flipped: CardId[];
passes: number;
/** Finishers in order (slots 1, 2, …). */
top: MascotId[];
/** DQ groups from the bottom (slot 4 first); a group is a simultaneous DQ. */
bottom: MascotId[][];
flags: RaceFlags;
processed: number;
over: boolean;
log: RaceLine[];
logSeq: number;
nextFlipAt: number;
hurry: PlayerId[];
}
// ---------------------------------------------------------------- game state
export interface Ticket {
stack: StackId;
tier: Tier;
side: Face;
reverse: boolean;
doubled: boolean;
}
export interface PotBet {
mascot: MascotId;
last: boolean;
side: 'YES' | 'NO';
doubled: 'mascot' | 'side' | null;
}
export interface PayLine {
/** "댕글 2단 위험", "YES 1단 안전", "꼴찌 고블러", "보너스". */
label: string;
amount: number;
doubled?: boolean;
}
export interface RaceResult {
no: number;
/** Place groups, best first: [[D], [G], [H, M]]. */
podium: MascotId[][];
side: { id: SideId; yes: boolean };
rows: Record<PlayerId, { lines: PayLine[]; total: number; before: number; after: number }>;
}
export interface HotStreakState {
options: HotStreakOptions;
seats: PlayerId[];
mode: BetMode;
/** Cards each player puts in per race (0 = 상금 나누기). */
perRace: 0 | 1 | 2;
handSize: number;
phase: 'draft' | 'double' | 'submit' | 'race' | 'payout' | 'finished';
raceNo: number;
/** Seat index that drafts first this race. */
startSeat: number;
money: Record<PlayerId, number>;
/** The race deck before a race (hidden order). */
pool: CardId[];
/** Deck list shown face up (1경주 전 티켓 모드·상금 나누기 모드), kinds only. */
faceUp: CardBase[];
/** Kinds seen face up at some point this game (deck guessing). */
known: CardBase[];
/** Kinds flipped in the last race (most of them are in the next race deck). */
seenLast: CardBase[];
/** Cards not used this game (hidden). */
box: CardBase[];
hands: Record<PlayerId, CardId[]>;
submitted: Record<PlayerId, CardId[] | null>;
/** Tickets left per stack (top first). */
stacks: Record<StackId, Tier[]>;
tickets: Record<PlayerId, Ticket[]>;
potBets: Record<PlayerId, PotBet | null>;
/** Snake order (seat indexes) and how far it got. */
draftOrder: number[];
draftAt: number;
/** Player who must pick a ticket to double now (phase 'double'). */
doubleFor: PlayerId | null;
/** Side questions; [0] is this race's (the rest hidden). */
sideDeck: SideId[];
race: RaceState | null;
results: RaceResult[];
ready: PlayerId[];
left: PlayerId[];
timeouts: Record<PlayerId, number>;
/** Shuffle counter: card ids get a new `#gen` suffix every shuffle. */
gen: number;
turnSeq: number;
deadlineAt: number | null;
/** Shared deadline of the simultaneous steps (카드 넣기, 상금 나누기 베팅). */
phaseDeadline: number | null;
payoutAt: number | null;
}
export type { CardBase, CardId, Face, MascotId, SideId, StackId, Tier };

View File

@@ -0,0 +1,98 @@
/**
* 핫스트릭 컴퓨터용 몬테카를로 경주 (docs/games/hot-streak.md §8.7). Only public information goes in: the face-up deck,
* the kinds seen last race, the bot's own hand; the unknown cards are filled at random from what nobody has shown.
*/
import type { Rng } from '@bg/engine';
import { ALL_CARDS, MASCOT_IDS, type CardBase, type MascotId, type SideId } from './cards';
import { placesOf, podiumOf, runToEnd, sideAnswer, startRace } from './race';
import { DECK_SIZE } from './rules';
/** Small fast PRNG (mulberry32) so several candidates can share the same shuffles (common random numbers). */
export function seededRng(seed: number): Rng {
let a = seed >>> 0;
const next = () => {
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;
};
const int = (n: number) => Math.min(n - 1, Math.floor(next() * n));
return {
next,
int,
shuffle<T>(arr: readonly T[]): T[] {
const out = [...arr];
for (let i = out.length - 1; i > 0; i--) {
const j = int(i + 1);
[out[i], out[j]] = [out[j]!, out[i]!];
}
return out;
},
};
}
export interface DeckModel {
/** Cards surely in the race deck. */
fixed: CardBase[];
/** Cards probably in it (seen last race, not in my hand), used before `unknown`. */
likely: CardBase[];
/** How many of the deck come from `likely` at most. */
likelyN: number;
/** Everything nobody has shown (fills the rest). */
unknown: CardBase[];
}
export interface SimStats {
runs: number;
/** low[m][r-1]: how often mascot m settled at place r (정산 등수). */
low: Record<MascotId, number[]>;
/** high[m][r-1]: the group's higher place (거꾸로 티켓). */
high: Record<MascotId, number[]>;
/** How often the side question came true. */
yes: number;
}
/** One deck for one run: fixed + my put-in cards + likely + unknown, 18 cards. */
export function sampleDeck(model: DeckModel, mine: CardBase[], rng: Rng): CardBase[] {
const deck = [...model.fixed, ...mine];
const taken = new Set(deck);
if (deck.length < DECK_SIZE && model.likely.length) {
const l = rng.shuffle(model.likely.filter((c) => !taken.has(c)));
for (const c of l.slice(0, Math.min(model.likelyN, DECK_SIZE - deck.length))) {
deck.push(c);
taken.add(c);
}
}
if (deck.length < DECK_SIZE) {
const u = rng.shuffle(model.unknown.filter((c) => !taken.has(c)));
deck.push(...u.slice(0, DECK_SIZE - deck.length));
}
return deck;
}
export function simulate(
makeDeck: (rng: Rng) => CardBase[],
runs: number,
opts: { burn: number; hurdles: boolean; side: SideId },
rng: Rng,
): SimStats {
const zero = () => Object.fromEntries(MASCOT_IDS.map((m) => [m, [0, 0, 0, 0]])) as Record<MascotId, number[]>;
const st: SimStats = { runs, low: zero(), high: zero(), yes: 0 };
const ro = { burn: opts.burn, hurdles: opts.hurdles, log: false };
const ctx = { rng, regen: (c: string[]) => c };
for (let i = 0; i < runs; i++) {
const r = startRace(1, makeDeck(rng), ctx, ro, 0);
runToEnd(r, ctx, ro);
const podium = podiumOf(r);
const pl = placesOf(podium);
for (const m of MASCOT_IDS) {
st.low[m][pl[m].low - 1]!++;
st.high[m][pl[m].high - 1]!++;
}
if (sideAnswer(opts.side, r.flags, podium)) st.yes++;
}
return st;
}
export const ALL = ALL_CARDS;

View File

@@ -35,6 +35,7 @@ import { magicalAthlete } from './magical-athlete';
import { blackjack } from './blackjack';
import { sixNimmt } from './six-nimmt';
import { gemblo } from './gemblo';
import { hotStreak } from './hot-streak';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -73,4 +74,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[blackjack.id]: blackjack,
[sixNimmt.id]: sixNimmt,
[gemblo.id]: gemblo,
[hotStreak.id]: hotStreak,
};