새 게임 핫스트릭: 마스코트 넷의 카드 경주에 티켓으로 거는 파티 게임(2~10명, 놀이용 가상 돈)

- 엔진 packages/games/src/hot-streak/(cards·rules·race·index·sim·bot): 뱀 순서 티켓 뽑기(안전/위험 면) → 비밀 카드 넣기 → 경주 → 정산, 경주 3번
  - 경주는 서버 타이머가 flipSeconds마다 카드 한 장씩(timeoutPlayers 한 자리 + timeoutNotBefore, 끊겨도 빨라지지 않음), 모두 [빨리 보기]면 끝까지 바로
  - 카드 53장·충돌·기어가기·꺾기·초록 카드·허들·경주로 접기(13→10→7→3→0)·시상대 공동 실격·사이드 질문 12개 판정
  - 섞을 때마다 카드 id 접미사(#gen)를 새로 붙여 유출 검사가 헷갈리지 않음
  - §2 옵션 13개 모두: bettingMode(9~10명 상금 나누기 포함), races, finalBet, draftStart, reverseBets, cardsPerRace, burn, spicyDeck, hurdles, potScale, lifeStory, turnSeconds, flipSeconds
- 컴퓨터: 공개 정보로 덱을 추정해 몬테카를로 경주(레벨 1: 30번 ~ 60: 400번), 티켓·두 배·카드 넣기·상금 나누기 기대값, humanBest
- 화면 apps/web/src/games/hot-streak/: 직접 그린 SVG 마스코트(곰·핫도그·아귀·여왕)와 카드, PC 가로·휴대폰 세로 경주로, 경주 기록을 한 박자 늦게 다시 그리기(폴짝·쾅·실격·등수·접기), 티켓 더미·두 배·비밀 카드·상금 나누기·정산·최종 결과(인생 결과), 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·여럿이 파티 탭, docs/games/README.md, 설계 문서 §13 구현 메모(정한 세부 규칙)
- 테스트: 엔진 64개(§10 체크리스트·§5.8 예시·무작위 대국·시간 초과만으로 끝·유출 없음), 컴퓨터 15개, 도움말 2개, 방 통합 3개, e2e/games.e2e.ts hot-streak(PC + 휴대폰, 320px 넘침 확인)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 23:28:18 +09:00
parent 8620c82ca8
commit 8aad123222
26 changed files with 5227 additions and 2 deletions

View File

@@ -0,0 +1,150 @@
/** 핫스트릭 through a real Room: races flip on the server clock only, 빨리 보기 needs everyone, practice games finish (docs/games/hot-streak.md §10). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { HotStreakAction, HotStreakState, HotStreakView } from '@bg/games/hot-streak';
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
import { openDb } from '../db';
import { RoomManager } from './manager';
import { Room, type Conn } from './room';
import { RoomStore } from './store';
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness() {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
const conn = (userId: string) => {
const msgs: ServerMessage[] = [];
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
return { db, clock, manager, conn };
}
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as HotStreakView);
/** What the person presses, read only from their own screen. */
function personMove(v: HotStreakView, n: number): HotStreakAction | null {
const l = v.legal;
if (l.draft) {
const o = l.draft[n % l.draft.length]!;
return { type: 'DRAFT', stack: o.stack, side: n % 3 === 0 ? 'risky' : 'safe' };
}
if (l.double) return { type: 'DOUBLE', index: 0 };
if (l.submit) return { type: 'SUBMIT', cards: l.submit.cards.slice(0, l.submit.count) };
if (l.pot) return { type: 'POT_BET', mascot: 'D', last: false, side: 'NO', doubled: l.pot.doubleRequired ? 'mascot' : null };
if (l.ready) return { type: 'READY' };
return null;
}
function tick(h: ReturnType<typeof harness>, room: Room, ms = 250) {
h.clock.advance(ms);
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
const d = room.effectiveDeadline();
if (d !== null && d <= h.clock.now()) room.onTimer();
}
describe('핫스트릭 room flow', () => {
test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 남이 넣은 카드는 안 보여요', (nBots) => {
const h = harness();
let room: Room;
if (nBots === 1) room = h.manager.createPractice('A', 'hot-streak') as Room;
else {
const r = h.manager.create('A', 'hot-streak', 'private');
if (typeof r === 'string') throw new Error(r);
room = r;
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
}
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
const bots = room.game!.players.filter(isBotId);
expect(bots).toHaveLength(nBots);
let cs = 0;
let mine = 0;
let seen = 0;
for (let i = 0; i < 60_000 && !room.game!.finished; i++) {
tick(h, room);
const vs = views(a);
for (const v of vs.slice(seen)) {
expect(v.me).toBe('A');
const st = room.game!.state as HotStreakState;
for (const b of bots) for (const c of st.hands[b] ?? []) expect(JSON.stringify(v)).not.toContain(c);
}
seen = vs.length;
const v = vs.at(-1);
const m = v && personMove(v, mine);
if (m) {
room.act('A', ++cs, m);
mine++;
}
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
const s = room.game!.state as HotStreakState;
expect(s.results).toHaveLength(3);
expect(s.timeouts.A).toBe(0);
expect(mine).toBeGreaterThan(6);
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
});
test('경주는 서버 시계로만 넘어가요: 끊긴 사람이 있어도 2초마다 한 장, 모두 [빨리 보기]면 바로 끝', () => {
const h = harness();
const r = h.manager.create('A', 'hot-streak', 'private');
if (typeof r === 'string') throw new Error(r);
const room = r;
rooms.push(room);
const a = h.conn('A');
const b = h.conn('B');
const c = h.conn('C');
room.join(a, 'player');
room.join(b, 'player');
room.join(c, 'player');
expect(room.start('A')).toBeNull();
let cs = 0;
const st = () => room.game!.state as HotStreakState;
// Everyone plays the betting steps from their own view.
for (let i = 0; i < 400 && st().phase !== 'race'; i++) {
for (const [p, cn] of [['A', a], ['B', b], ['C', c]] as const) {
const v = views(cn).at(-1);
const m = v && personMove(v, i);
if (m) room.act(p, ++cs, m);
}
tick(h, room, 100);
}
expect(st().phase).toBe('race');
// C drops: nothing speeds up (the driver's grace is 0 but cards wait for their time).
room.disconnect(c);
const flipAt = st().race!.nextFlipAt;
expect(room.effectiveDeadline()).toBe(flipAt);
const before = st().race!.processed;
h.clock.advance(flipAt - h.clock.now() - 10);
room.onTimer();
expect(st().race!.processed).toBe(before);
h.clock.advance(10);
room.onTimer();
expect(st().race!.processed).toBe(before + 1);
// Next card two seconds later.
expect(room.effectiveDeadline()).toBe(h.clock.now() + 2000);
// 빨리 보기: A and B agree, C (offline) has not — still running.
room.act('A', ++cs, { type: 'HURRY' });
room.act('B', ++cs, { type: 'HURRY' });
if (st().phase === 'race') {
expect(st().race!.hurry.sort()).toEqual(['A', 'B']);
room.join(c, 'player');
room.act('C', ++cs, { type: 'HURRY' });
}
expect(st().phase).toBe('payout');
expect(st().race!.over).toBe(true);
});
});

View File

@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
const IDS = Object.keys(GAME_UI);
test('모든 게임에 도움말이 있어요', () => {
expect(IDS).toHaveLength(34);
expect(IDS).toHaveLength(35);
for (const id of IDS) {
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
expect(src, id).toMatch(/\bquickStart,/);

View File

@@ -0,0 +1,156 @@
/**
* 핫스트릭 그림: 우리가 새로 그린 탈 인형 마스코트 4명(곰·핫도그·아귀·여왕)과 경주 카드 (docs/games/hot-streak.md §9, §12).
* Simple inline SVG only — no original artwork.
*/
import { MASCOTS, cardInfo, type CardBase, type MascotId } from '@bg/games/hot-streak/cards';
/** A mascot face drawn in a 100×100 box (centre 50,50). */
export function MascotFace({ id }: { id: MascotId }) {
const m = MASCOTS[id];
const eyes = (y = 46, dx = 13) => (
<>
<circle cx={50 - dx} cy={y} r={6.5} fill="#fff" />
<circle cx={50 + dx} cy={y} r={6.5} fill="#fff" />
<circle cx={51 - dx} cy={y + 1} r={3.2} fill="#111827" />
<circle cx={51 + dx} cy={y + 1} r={3.2} fill="#111827" />
</>
);
switch (id) {
case 'G':
return (
<g>
<circle cx={24} cy={24} r={13} fill={m.color} stroke="#7c2d12" strokeWidth={3} />
<circle cx={76} cy={24} r={13} fill={m.color} stroke="#7c2d12" strokeWidth={3} />
<circle cx={24} cy={24} r={6} fill="#fed7aa" />
<circle cx={76} cy={24} r={6} fill="#fed7aa" />
<circle cx={50} cy={52} r={36} fill={m.color} stroke="#7c2d12" strokeWidth={3} />
<ellipse cx={50} cy={66} rx={17} ry={13} fill="#fed7aa" />
<ellipse cx={50} cy={60} rx={6} ry={4.5} fill="#3f1d0b" />
<path d="M44 70 Q50 75 56 70" stroke="#3f1d0b" strokeWidth={3} fill="none" strokeLinecap="round" />
{eyes(44)}
<rect x={22} y={82} width={56} height={12} rx={6} fill={m.color2} />
</g>
);
case 'H':
return (
<g>
<rect x={14} y={30} width={72} height={52} rx={26} fill="#f6c27a" stroke="#92400e" strokeWidth={3} />
<rect x={20} y={18} width={60} height={64} rx={30} fill={m.color} stroke="#7f1d1d" strokeWidth={3} />
<path d="M28 30 l8 6 l8 -6 l8 6 l8 -6 l8 6" stroke="#facc15" strokeWidth={4} fill="none" strokeLinejoin="round" strokeLinecap="round" />
{eyes(52, 12)}
<path d="M40 66 Q50 74 60 66" stroke="#7f1d1d" strokeWidth={3.5} fill="none" strokeLinecap="round" />
<rect x={10} y={76} width={80} height={14} rx={7} fill="#f6c27a" stroke="#92400e" strokeWidth={3} />
</g>
);
case 'D':
return (
<g>
<path d="M52 20 Q58 2 74 6" stroke="#1e3a8a" strokeWidth={3.5} fill="none" strokeLinecap="round" />
<circle cx={76} cy={7} r={6.5} fill="#fde047" stroke="#a16207" strokeWidth={2} />
<ellipse cx={50} cy={56} rx={38} ry={33} fill={m.color} stroke="#1e3a8a" strokeWidth={3} />
<path d="M12 56 L2 44 L4 68 Z" fill={m.color2} stroke="#1e3a8a" strokeWidth={2.5} strokeLinejoin="round" />
{eyes(42, 14)}
<path d="M24 66 Q50 86 76 66 Z" fill="#1e1b4b" />
<path d="M28 67 l5 7 l5 -6 l5 7 l5 -7 l5 7 l5 -7 l5 6 l5 -6" stroke="#fff" strokeWidth={2.5} fill="none" strokeLinejoin="round" />
</g>
);
case 'M':
return (
<g>
<path d="M22 34 L26 10 L38 24 L50 6 L62 24 L74 10 L78 34 Z" fill={m.color} stroke="#854d0e" strokeWidth={3} strokeLinejoin="round" />
<circle cx={50} cy={20} r={4} fill={m.color2} />
<circle cx={50} cy={58} r={30} fill="#fde68a" stroke="#854d0e" strokeWidth={3} />
<path d="M20 50 Q14 76 30 88 M80 50 Q86 76 70 88" stroke={m.color2} strokeWidth={7} fill="none" strokeLinecap="round" />
{eyes(54, 11)}
<circle cx={34} cy={68} r={5} fill="#fda4af" opacity={0.8} />
<circle cx={66} cy={68} r={5} fill="#fda4af" opacity={0.8} />
<path d="M43 72 Q50 77 57 72" stroke="#9f1239" strokeWidth={3} fill="none" strokeLinecap="round" />
</g>
);
}
}
/** Mascot icon as its own <svg> (lists, buttons). */
export function MascotIcon({ id, size = 28, title }: { id: MascotId; size?: number; title?: string }) {
return (
<svg viewBox="0 0 100 100" width={size} height={size} aria-hidden={title ? undefined : true} role={title ? 'img' : undefined} aria-label={title} style={{ flex: 'none', overflow: 'visible' }}>
<MascotFace id={id} />
</svg>
);
}
/** Small glyph of what a card does (arrow, star, fall …). */
function EffectGlyph({ base }: { base: CardBase }) {
const e = cardInfo(base).effect;
const stroke = { stroke: '#111827', strokeWidth: 5, fill: 'none', strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const };
switch (e.kind) {
case 'star':
return <path d="M50 18 L58 40 L82 40 L62 54 L70 78 L50 63 L30 78 L38 54 L18 40 L42 40 Z" fill="#facc15" stroke="#a16207" strokeWidth={3} />;
case 'fall':
return (
<g {...stroke}>
<path d="M22 70 L78 70" />
<path d="M40 44 L62 60" strokeWidth={9} />
<circle cx={34} cy={38} r={7} fill="#111827" />
</g>
);
case 'turn':
return <path d="M30 60 Q30 30 55 30 Q76 30 76 52 M68 44 L76 54 L84 44" {...stroke} />;
case 'weave':
return <path d="M20 66 L56 66 Q72 66 72 50 L72 30 M64 38 L72 28 L80 38" {...stroke} />;
case 'rise':
return (
<g {...stroke}>
<path d="M50 76 L50 30 M38 42 L50 28 L62 42" />
<path d="M30 80 L70 80" />
</g>
);
default:
return e.n < 0 ? <path d="M78 50 L24 50 M38 36 L22 50 L38 64" {...stroke} /> : <path d="M22 50 L76 50 M62 36 L78 50 L62 64" {...stroke} />;
}
}
const BIG: Record<string, string> = { move: '', rise: '↑', star: '★', fall: '', turn: '', weave: '' };
/** A race card face. `size` = width in px (height 1.4×). */
export function RaceCard({ base, size = 64, faceDown = false, className = '' }: { base?: CardBase | null; size?: number; faceDown?: boolean; className?: string }) {
const w = size;
const h = Math.round(size * 1.4);
if (faceDown || !base) {
return (
<svg viewBox="0 0 100 140" width={w} height={h} className={`hs-card ${className}`} aria-hidden>
<rect x={3} y={3} width={94} height={134} rx={12} fill="#1f2937" stroke="#f97316" strokeWidth={4} />
<path d="M20 40 L50 20 L80 40 M20 70 L50 50 L80 70 M20 100 L50 80 L80 100 M20 130 L50 110 L80 130" stroke="#f97316" strokeWidth={6} fill="none" opacity={0.6} />
</svg>
);
}
const c = cardInfo(base);
const m = c.who === 'all' ? null : MASCOTS[c.who];
const e = c.effect;
const num = e.kind === 'move' || e.kind === 'rise' || e.kind === 'weave' ? `${e.n < 0 ? '−' : ''}${Math.abs(e.n)}` : BIG[e.kind] ?? '';
return (
<svg viewBox="0 0 100 140" width={w} height={h} className={`hs-card ${className}`} role="img" aria-label={c.who === 'all' ? c.label : `${m!.name} ${c.label}`}>
<rect x={3} y={3} width={94} height={134} rx={12} fill={m ? '#fffdf7' : '#dcfce7'} stroke={c.starter ? '#111827' : m ? m.color : '#16a34a'} strokeWidth={c.starter ? 7 : 5} />
<rect x={3} y={3} width={94} height={30} rx={12} fill={m ? m.color : '#16a34a'} />
<rect x={3} y={22} width={94} height={11} fill={m ? m.color : '#16a34a'} />
{m ? (
<g transform="translate(6 4) scale(0.27)">
<MascotFace id={m.id} />
</g>
) : (
<text x={12} y={25} fontSize={18} fontWeight={900} fill="#fff">
모두
</text>
)}
<text x={90} y={26} fontSize={22} fontWeight={900} fill="#fff" textAnchor="end">
{num}
</text>
<g transform="translate(14 36) scale(0.72)">
<EffectGlyph base={base} />
</g>
<text x={50} y={124} fontSize={c.label.length > 6 ? 12 : 15} fontWeight={800} fill="#111827" textAnchor="middle">
{c.who === 'all' ? c.label.replace('모두 ', '') : c.label}
</text>
</svg>
);
}

View File

@@ -0,0 +1,30 @@
import { expect, test } from 'bun:test';
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
import { GAMES } from '@bg/games';
import { helpNow } from './help';
const ID = 'hot-streak';
const users = usersOf(['A', 'B', 'C', 'D']);
const view = (s: unknown, who: string | null) => GAMES[ID]!.view(s, who) as any;
const picker = (s: any): string => s.seats[s.draftOrder[s.draftAt]];
test('핫스트릭: 티켓 뽑기 차례 / 기다리기 / 관전', () => {
const { state } = setupGame(ID, 4);
const p = picker(state);
const other = state.seats.find((x: string) => x !== p)!;
expect(helpNow(view(state, p), p, users)).toContain('티켓을 가져올 차례');
expect(helpNow(view(state, other), other, users)).toContain(`${users[p]!.nickname}님이 티켓을 고르는 중`);
expect(helpNow(view(state, null), null, users)).toContain('1번째 경주');
});
test('핫스트릭: 카드 넣기와 경주', () => {
let { state } = setupGame(ID, 4);
while (state.phase === 'draft') {
const p = picker(state);
state = applyAction(ID, state, p, GAMES[ID]!.legalActions!(state, p)[0]);
}
expect(helpNow(view(state, 'A'), 'A', users)).toContain('[몰래 넣기]');
for (const p of ['A', 'B', 'C', 'D']) state = applyAction(ID, state, p, { type: 'SUBMIT', cards: [state.hands[p][0]] });
expect(state.phase).toBe('race');
expect(helpNow(view(state, 'A'), 'A', users)).toContain('[빨리 보기]');
});

View File

@@ -0,0 +1,59 @@
/** 핫스트릭 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
import type { HotStreakView } from '@bg/games/hot-streak';
import { MASCOTS, cardHelp, isMascot } from '@bg/games/hot-streak/cards';
import type { PublicUser } from '@bg/shared/lite';
export function helpNow(v: HotStreakView, me: string | null, players: Record<string, PublicUser>): string {
const name = (p: string) => `${players[p]?.nickname ?? '다른 사람'}님`;
const seated = !!me && v.seats.includes(me);
const money = seated ? `지금 내 돈은 $${v.money[me!]}이에요.` : '';
const goal = `경주를 ${v.races}번 하고 돈이 가장 많은 사람이 이겨요(놀이용 가상 돈).`;
if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
if (seated && v.left.includes(me!)) return '나는 그만해서 구경만 할 수 있어요. 내 차례는 자동으로 진행돼요.';
const head = `${v.raceNo}번째 경주예요. 이번 사이드 질문: ${v.side.text}`;
if (v.phase === 'draft' && v.mode === 'tickets') {
const d = v.draft!;
if (v.legal.draft) {
return [
head,
'지금 내가 티켓을 가져올 차례예요. 마스코트 더미나 YES·NO 더미를 눌러 맨 위 티켓을 안전 면이나 위험 면으로 가져와요.',
'안전 면은 2·3등이어도 꽤 받고, 위험 면은 1등일 때 크게 받아요. 사이드 위험 면은 틀리면 $5를 내요.',
v.faceUp.length ? '아래 "경주 덱 앞면"을 보고 카드가 많은 마스코트를 노려 보세요.' : '',
money,
]
.filter(Boolean)
.join('\n');
}
return `${head}\n지금은 ${name(d.picker)}이 티켓을 고르는 중이에요. 뱀 순서로 돌아가며 한 장씩 가져와요.\n${goal}\n${money}`.trim();
}
if (v.phase === 'double') {
if (v.legal.double) return `${head}\n마지막 경주예요! 내 티켓 중 하나를 골라 두 배로 해요. 틀리면 마이너스도 두 배예요.\n${money}`.trim();
return `${head}\n${name(v.doubleFor ?? '')}이 두 배로 할 티켓을 고르는 중이에요.\n${money}`.trim();
}
if (v.phase === 'draft') {
if (v.legal.pot) return `${head}\n마스코트 하나와 사이드 질문 YES/NO를 몰래 적어요. 18장 덱이 모두 앞면으로 보여요. 모두 적으면 함께 공개돼요.\n${goal}`;
return `${head}\n모두 몰래 적는 중이에요. 다 적으면 경주가 시작돼요.\n${goal}`;
}
if (v.phase === 'submit') {
if (v.legal.submit) {
const tip = v.hand?.[0] ? `예: ${cardHelp(v.hand[0].base)}` : '';
return `${head}\n손패에서 ${v.legal.submit.count}장을 눌러 고른 뒤 [몰래 넣기]를 눌러요. 내가 건 마스코트를 밀어 주거나 1등 후보를 넘어뜨리는 카드가 좋아요.\n${tip}\n${money}`.trim();
}
return `${head}\n다른 사람이 카드를 넣는 중이에요. 누가 무엇을 넣었는지는 끝까지 비밀이에요.\n${money}`.trim();
}
if (v.phase === 'race') {
const mine = seated ? v.tickets[me!] ?? [] : [];
const bet = mine.filter((t) => isMascot(t.stack)).map((t) => MASCOTS[t.stack as keyof typeof MASCOTS].name);
return [
`${head}\n경주 중이에요! 카드가 몇 초마다 한 장씩 넘어가요. 지금은 고를 것이 없어요. 구경하며 응원해요.`,
bet.length ? `내가 건 마스코트: ${[...new Set(bet)].join(', ')}.` : '',
seated ? '모두 [빨리 보기]를 누르면 끝까지 바로 처리해요.' : '',
money,
]
.filter(Boolean)
.join('\n');
}
return `${head}\n이번 경주 정산이에요. 티켓마다 받은 돈이 표에 나와요. [다음 경주로]를 누르거나 잠시 기다리면 넘어가요.\n${money}`.trim();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,112 @@
/** 핫스트릭 30초 규칙 요약 (docs/07 §5). */
import type { QuickCard } from '../types';
import { MascotFace, RaceCard } from './art';
function Ticket({ x, y, color, title, a, b, picked = false }: { x: number; y: number; color: string; title: string; a: string; b: string; picked?: boolean }) {
return (
<g transform={`translate(${x} ${y})`}>
<rect width={78} height={66} rx={8} fill={picked ? '#dbeafe' : '#fff'} stroke={picked ? '#2563eb' : '#6b7280'} strokeWidth={picked ? 3.5 : 2} />
<rect width={78} height={18} rx={8} fill={color} />
<text x={39} y={13} textAnchor="middle" fontSize={11} fontWeight={900} fill="#fff">
{title}
</text>
<text x={39} y={38} textAnchor="middle" fontSize={11} fontWeight={800} fill="#111827">
{a}
</text>
<text x={39} y={56} textAnchor="middle" fontSize={11} fontWeight={800} fill="#dc2626">
{b}
</text>
</g>
);
}
function BetPic() {
return (
<svg viewBox="0 0 260 150" width={250} height={144} aria-hidden>
<Ticket x={6} y={10} color="#2563eb" title="댕글 1단" a="안전 10/7/5" b="위험 15/5/2" picked />
<Ticket x={92} y={10} color="#f97316" title="고블러 1단" a="안전 10/7/5" b="위험 15/5/2" />
<Ticket x={178} y={10} color="#16a34a" title="YES 1단" a="맞히면 +10" b="+15 / −5" />
<text x={130} y={106} textAnchor="middle" fontSize={14} fontWeight={800} fill="#111827">
뱀 순서로 한 장씩, 안전 또는 위험
</text>
<text x={130} y={130} textAnchor="middle" fontSize={12} fill="#374151">
사이드 질문: "실격이 나올까요?"
</text>
</svg>
);
}
function SecretPic() {
return (
<svg viewBox="0 0 260 150" width={250} height={144} aria-hidden>
<g transform="translate(20 14)">
<RaceCard base="D-F3" size={50} />
</g>
<g transform="translate(80 14)">
<RaceCard base="G-FD" size={50} />
</g>
<path d="M140 50 Q170 30 196 54" stroke="#2563eb" strokeWidth={3} fill="none" strokeDasharray="5 4" />
<g transform="translate(196 18)">
<RaceCard faceDown size={50} />
</g>
<text x={130} y={118} textAnchor="middle" fontSize={14} fontWeight={800} fill="#111827">
🤫 손패 1장을 경주 덱에 몰래
</text>
<text x={130} y={140} textAnchor="middle" fontSize={12} fill="#374151">
누가 넣었는지는 끝까지 비밀
</text>
</svg>
);
}
function RacePic() {
const cells = Array.from({ length: 6 }, (_, i) => i);
return (
<svg viewBox="0 0 260 150" width={250} height={144} aria-hidden>
<rect x={4} y={22} width={252} height={84} rx={10} fill="#1f5132" />
{cells.map((i) => (
<rect key={i} x={10 + i * 36} y={30} width={32} height={32} rx={5} fill="#2d6a43" stroke="#4c8a5f" />
))}
{cells.map((i) => (
<rect key={`b${i}`} x={10 + i * 36} y={66} width={32} height={32} rx={5} fill="#2d6a43" stroke="#4c8a5f" />
))}
<rect x={226} y={30} width={4} height={68} fill="#fff" />
<g transform="translate(84 30) scale(0.32)">
<MascotFace id="H" />
</g>
<g transform="translate(120 66) rotate(80 16 16) scale(0.32)">
<MascotFace id="G" />
</g>
<text x={150} y={22} fontSize={16} fontWeight={900} fill="#dc2626">
쾅!
</text>
<text x={130} y={126} textAnchor="middle" fontSize={14} fontWeight={800} fill="#111827">
카드가 저절로 넘어가요. 구경하며 응원!
</text>
<text x={130} y={145} textAnchor="middle" fontSize={12} fill="#374151">
셋이 들어오거나 실격하면 정산
</text>
</svg>
);
}
export const quickStart: QuickCard[] = [
{
pic: <BetPic />,
alt: '댕글, 고블러 마스코트 티켓과 YES 티켓 중 댕글 티켓을 골라요',
title: '티켓을 뽑아 걸어요',
text: '뱀 순서로 티켓을 한 장씩 가져와요. 안전 면은 조금씩 확실하게, 위험 면은 1등이면 크게! 사이드 질문 YES·NO에도 걸 수 있어요.',
},
{
pic: <SecretPic />,
alt: '손패 카드 중 한 장을 뒷면 덱에 몰래 넣어요',
title: '카드 한 장 몰래 넣기',
text: '손패에서 카드 한 장을 경주 덱에 몰래 넣어요. 내가 건 마스코트를 밀어 주거나 다른 마스코트를 넘어뜨려요.',
},
{
pic: <RacePic />,
alt: '경주로에서 헐리가 달리고 고블러가 쾅 넘어졌어요',
title: '구경하며 소리 질러요',
text: '경주는 카드가 몇 초마다 넘어가며 저절로 진행돼요. 셋이 결승이나 실격이 되면 정산하고, 경주 세 번 뒤 돈이 많으면 이겨요.',
},
];

View File

@@ -0,0 +1,403 @@
/**
* 핫스트릭 경주로 (docs/games/hot-streak.md §9): PC는 가로(왼쪽 13번 칸 → 오른쪽 결승선·시상대), 휴대폰은 세로(위가 결승선).
* The view already has the result of every card; `useReplay` draws the race record a beat behind, card by card:
* the card turns over, the mascot hops space by space, then bumps / falls / 실격 / 결승 show up.
*/
import { useEffect, useRef, useState, type ReactElement } from 'react';
import type { HsRaceView, RaceLine, Racer } from '@bg/games/hot-streak';
import { MASCOTS, MASCOT_IDS, josa, type MascotId } from '@bg/games/hot-streak/cards';
import { noise, sfx, tone } from '../../lib/feedback';
import { fxMs } from '../../lib/motion';
import { MascotFace } from './art';
export const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
// ---------------------------------------------------------------- geometry
export interface Geo {
vertical: boolean;
w: number;
h: number;
/** Cell box of (lane, space). */
cell(lane: number, pos: number): { x: number; y: number; w: number; h: number };
/** Podium slot box in the finish zone (1~4). */
slot(place: number): { x: number; y: number; w: number; h: number };
tok: number;
/** Line between space p+1 and p (fold lines): from / to points. */
between(p: number): [number, number, number, number];
}
const H_LM = 30;
const H_CW = 62;
const H_LH = 58;
const H_TM = 24;
const H_FW = 118;
export const WIDE: Geo = {
vertical: false,
w: H_LM + 13 * H_CW + H_FW,
h: H_TM + 4 * H_LH + 6,
cell: (lane, pos) => ({ x: H_LM + (13 - pos) * H_CW, y: H_TM + lane * H_LH, w: H_CW, h: H_LH }),
slot: (place) => ({ x: H_LM + 13 * H_CW, y: H_TM + (place - 1) * H_LH, w: H_FW, h: H_LH }),
tok: 46,
between: (p) => {
const x = H_LM + (13 - p) * H_CW;
return [x, H_TM, x, H_TM + 4 * H_LH];
},
};
const V_LM = 4;
const V_LW = 76;
const V_CH = 34;
const V_FH = 66;
export const TALL: Geo = {
vertical: true,
w: V_LM * 2 + 4 * V_LW,
h: V_FH + 13 * V_CH + 6,
cell: (lane, pos) => ({ x: V_LM + lane * V_LW, y: V_FH + (pos - 1) * V_CH, w: V_LW, h: V_CH }),
slot: (place) => ({ x: V_LM + (place - 1) * V_LW, y: 0, w: V_LW, h: V_FH - 4 }),
tok: 30,
between: (p) => {
const y = V_FH + p * V_CH;
return [V_LM, y, V_LM + 4 * V_LW, y];
},
};
// ---------------------------------------------------------------- replay
export interface Shown {
racers: Racer[];
trackEnd: number;
/** Line on screen (card, text). */
line: RaceLine | null;
/** Index of the hop in the current walk (forces a re-render). */
hop: number;
}
interface Float {
k: number;
id: MascotId;
text: string;
cls: string;
lane: number;
pos: number;
}
const START: Racer[] = MASCOT_IDS.map((id) => ({ id, lane: MASCOTS[id].lane, pos: 11, facing: 'fwd', down: false, status: 'racing' }));
const raceSound = {
hop: (i: number) => tone(i % 2 ? 640 : 560, 35, 'triangle', 0.06),
bump: () => {
noise(110, 0.18, 0, 'lowpass', 600);
tone(140, 160, 'square', 0.05);
},
down: () => tone(320, 220, 'sawtooth', 0.05, 0, { slideTo: 120 }),
dq: () => [520, 390, 260].forEach((f, i) => tone(f, 120, 'square', 0.05, i * 90)),
finish: () => [784, 988, 1318].forEach((f, i) => tone(f, 130, 'triangle', 0.1, i * 80)),
fold: () => {
noise(380, 0.12, 0, 'lowpass', 500);
tone(110, 300, 'sine', 0.08);
},
};
/**
* Plays new race lines one after the other. A race already running when the board opens is shown as it is. When the
* screen falls behind (빨리 보기, a slow phone) the next lines play faster. `busy` is true while lines are still queued.
*/
export function useReplay(r: HsRaceView | null) {
const [shown, setShown] = useState<Shown>(() => ({ racers: r ? r.log.at(-1)?.racers ?? r.racers : START, trackEnd: r?.trackEnd ?? 13, line: r?.log.at(-1) ?? null, hop: 0 }));
const [floats, setFloats] = useState<Float[]>([]);
const [busy, setBusy] = useState(false);
const q = useRef<RaceLine[]>([]);
const st = useRef({ race: r?.no ?? 0, last: r?.log.at(-1)?.n ?? 0, playing: false, k: 0, dead: false });
const timers = useRef(new Set<ReturnType<typeof setTimeout>>());
const later = (fn: () => void, ms: number) => {
const t = setTimeout(() => {
timers.current.delete(t);
if (!st.current.dead) fn();
}, ms);
timers.current.add(t);
};
useEffect(() => {
const s = st.current;
s.dead = false;
return () => {
s.dead = true;
for (const t of timers.current) clearTimeout(t);
timers.current.clear();
};
}, []);
const pump = () => {
const s = st.current;
const line = q.current.shift();
if (!line) {
s.playing = false;
setBusy(false);
return;
}
s.playing = true;
setBusy(true);
const behind = q.current.length;
const speed = behind > 4 ? 0.25 : behind > 1 ? 0.5 : 1;
const T = (ms: number) => Math.max(10, Math.round(fxMs(ms) * speed));
const finishLine = () => {
setShown({ racers: line.racers, trackEnd: line.trackEnd, line, hop: 0 });
for (const f of line.fx ?? []) {
const x = line.racers.find((y) => y.id === f.id)!;
const text = { bump: '쾅!', down: '쿵!', dq: '실격!', finish: `${f.place ?? ''}등!`, turn: '↩', up: '벌떡!' }[f.t];
const k = ++s.k;
setFloats((fl) => [...fl.slice(-6), { k, id: f.id, text, cls: f.t, lane: x.lane, pos: x.pos }]);
later(() => setFloats((fl) => fl.filter((z) => z.k !== k)), fxMs(1300));
}
const t = new Set((line.fx ?? []).map((f) => f.t));
if (t.has('dq')) raceSound.dq();
else if (t.has('finish')) raceSound.finish();
else if (t.has('bump')) raceSound.bump();
else if (t.has('down')) raceSound.down();
if (line.kind === 'fold') raceSound.fold();
later(pump, T(line.kind === 'flip' ? 260 : 380));
};
if (reducedMotion()) {
setShown({ racers: line.racers, trackEnd: line.trackEnd, line, hop: 0 });
later(pump, behind ? 30 : 200);
return;
}
if (line.kind === 'flip') sfx.cardFlip();
else if (line.kind === 'shuffle' || line.kind === 'start') sfx.shuffle();
const moves = line.mv ?? [];
const steps = Math.max(0, ...moves.map((m) => m.path.length - 1));
// The card shows first, then the walk.
setShown((sh) => ({ ...sh, line }));
const hopMs = T(150);
const lead = T(line.kind === 'flip' ? 320 : 120);
for (let i = 1; i <= steps; i++) {
later(() => {
raceSound.hop(i);
setShown((sh) => ({
...sh,
hop: i,
racers: sh.racers.map((x) => {
const m = moves.find((mv) => mv.id === x.id);
if (!m) return x;
const [lane, pos] = m.path[Math.min(i, m.path.length - 1)]!;
return { ...x, lane, pos };
}),
}));
}, lead + (i - 1) * hopMs);
}
later(finishLine, lead + steps * hopMs + (steps ? T(60) : 0));
};
useEffect(() => {
const s = st.current;
if (!r) {
if (s.race !== 0) {
s.race = 0;
s.last = 0;
q.current = [];
setShown({ racers: START, trackEnd: 13, line: null, hop: 0 });
}
return;
}
if (r.no !== s.race) {
s.race = r.no;
s.last = 0;
q.current = [];
}
const fresh = r.log.filter((l) => l.n > s.last);
if (!fresh.length) return;
s.last = fresh.at(-1)!.n;
q.current.push(...fresh);
if (!s.playing) pump();
}, [r?.no, r?.log.at(-1)?.n]); // eslint-disable-line react-hooks/exhaustive-deps
return { shown, floats, busy };
}
// ---------------------------------------------------------------- drawing
const tokenLabel = (x: Racer) =>
`${MASCOTS[x.id].name}: ${x.status === 'finished' ? '결승' : x.status === 'dq' ? '실격' : `레인 ${x.lane + 1}, ${x.pos}번 칸${x.down ? ', 넘어짐' : ''}${x.facing === 'back' ? ', 뒤돌아 있음' : ''}`}`;
/** Where each mascot stands now (finished / DQ ones on their podium slot). */
function placeOf(g: Geo, x: Racer, all: Racer[], slots: Map<MascotId, number>, ended: boolean): { cx: number; cy: number; onPodium: boolean } {
const slot = slots.get(x.id);
if (slot && (x.status !== 'racing' || ended)) {
const b = g.slot(slot);
return { cx: b.x + (g.vertical ? b.w / 2 : 30), cy: b.y + b.h / 2 + (g.vertical ? 6 : 0), onPodium: true };
}
const lane = Math.max(-0.6, Math.min(3.6, x.lane));
const pos = Math.max(0.4, Math.min(13.6, x.pos));
const base = g.vertical
? { x: V_LM + lane * V_LW + V_LW / 2, y: V_FH + (pos - 1) * V_CH + V_CH / 2 }
: { x: H_LM + (13 - pos) * H_CW + H_CW / 2, y: H_TM + lane * H_LH + H_LH / 2 };
// Two or more on one space: spread them a little.
const mates = all.filter((y) => y.status === 'racing' && y.lane === x.lane && y.pos === x.pos);
const i = mates.indexOf(x);
const off = mates.length > 1 ? (i - (mates.length - 1) / 2) * (g.vertical ? 14 : 16) : 0;
return { cx: base.x + (g.vertical ? off : 0), cy: base.y + (g.vertical ? 0 : off), onPodium: false };
}
export function Track({
g,
shown,
floats,
final,
stars,
hurdles,
label,
}: {
g: Geo;
shown: Shown;
floats: Float[];
/** The race's places as the view has them (podium slots never change once taken). */
final: { top: MascotId[]; bottom: MascotId[][]; over: boolean } | null;
stars: number[];
hurdles: number[];
label: string;
}) {
const { racers, trackEnd } = shown;
const slots = new Map<MascotId, number>();
if (final) {
final.top.forEach((m, i) => slots.set(m, i + 1));
let low = 4;
for (const grp of final.bottom) {
for (let j = grp.length - 1; j >= 0; j--) slots.set(grp[j]!, low--);
}
}
const ended = shown.line?.kind === 'end';
const cells: ReactElement[] = [];
for (let lane = 0; lane < 4; lane++) {
for (let pos = 1; pos <= 13; pos++) {
const b = g.cell(lane, pos);
const stretch = pos <= 3;
cells.push(
<rect key={`c${lane}-${pos}`} x={b.x + 1} y={b.y + 1} width={b.w - 2} height={b.h - 2} rx={6} className={`hs-cell${stretch ? ' stretch' : ''}${pos === 11 ? ' start' : ''}`} />,
);
if (stars.includes(pos))
cells.push(
<text key={`s${lane}-${pos}`} x={b.x + b.w - (g.vertical ? 12 : 13)} y={b.y + (g.vertical ? 13 : 16)} className="hs-star" fontSize={g.vertical ? 12 : 15} textAnchor="middle">
★
</text>,
);
if (hurdles.includes(pos))
cells.push(
<path
key={`h${lane}-${pos}`}
d={g.vertical ? `M${b.x + 6} ${b.y + b.h - 5} v-9 h14 v9` : `M${b.x + 6} ${b.y + b.h - 5} v-12 h16 v12`}
className="hs-hurdle"
/>,
);
}
}
// Space numbers (once per row/column).
const nums: ReactElement[] = [];
for (let pos = 1; pos <= 13; pos++) {
const b = g.cell(0, pos);
if (g.vertical) continue;
nums.push(
<text key={`n${pos}`} x={b.x + b.w / 2} y={H_TM - 7} className="hs-num" textAnchor="middle" fontSize={13}>
{pos}
</text>,
);
}
const finish = g.slot(1);
const zone = g.vertical ? { x: V_LM, y: 0, w: 4 * V_LW, h: V_FH - 4 } : { x: finish.x, y: H_TM, w: H_FW, h: 4 * H_LH };
const folded = 13 - trackEnd;
const foldBox = folded <= 0 ? null : g.vertical ? { x: V_LM, y: V_FH + trackEnd * V_CH, w: 4 * V_LW, h: folded * V_CH } : { x: H_LM, y: H_TM, w: folded * H_CW, h: 4 * H_LH };
return (
<svg viewBox={`0 0 ${g.w} ${g.h}`} className="hs-svg" role="img" aria-label={label}>
<defs>
<pattern id="hs-fold" width="16" height="16" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
<rect width="16" height="16" fill="#facc15" />
<rect width="8" height="16" fill="#eab308" />
</pattern>
</defs>
<rect x={0} y={0} width={g.w} height={g.h} rx={14} className="hs-bg" />
{/* lane colour stripes */}
{MASCOT_IDS.map((m, lane) => {
const a = g.cell(lane, 13);
const b = g.cell(lane, 1);
return g.vertical ? (
<rect key={m} x={a.x + 2} y={b.y} width={4} height={a.y + a.h - b.y} fill={MASCOTS[m].color} opacity={0.7} rx={2} />
) : (
<rect key={m} x={a.x} y={a.y + 2} width={b.x + b.w - a.x} height={4} fill={MASCOTS[m].color} opacity={0.7} rx={2} />
);
})}
{cells}
{nums}
{!g.vertical &&
MASCOT_IDS.map((m, lane) => {
const b = g.cell(lane, 13);
return (
<text key={`l${m}`} x={H_LM / 2} y={b.y + b.h / 2 + 5} textAnchor="middle" fontSize={13} fontWeight={800} fill={MASCOTS[m].color}>
{lane + 1}
</text>
);
})}
{[3, 7, 10].map((p) => {
const [x1, y1, x2, y2] = g.between(p);
return <line key={`f${p}`} x1={x1} y1={y1} x2={x2} y2={y2} className="hs-foldline" />;
})}
<rect x={zone.x + 2} y={zone.y + 2} width={zone.w - 4} height={zone.h - 4} rx={10} className="hs-zone" />
{[1, 2, 3, 4].map((pl) => {
const b = g.slot(pl);
return (
<text key={`p${pl}`} x={g.vertical ? b.x + b.w / 2 : b.x + b.w - 26} y={g.vertical ? b.y + 14 : b.y + b.h / 2 + 6} textAnchor="middle" className="hs-place" fontSize={g.vertical ? 12 : 16}>
{pl}등
</text>
);
})}
{/* finish line */}
{g.vertical ? (
<rect x={V_LM} y={V_FH - 4} width={4 * V_LW} height={4} className="hs-finish" />
) : (
<rect x={finish.x - 2} y={H_TM} width={5} height={4 * H_LH} className="hs-finish" />
)}
{foldBox && <rect x={foldBox.x} y={foldBox.y} width={foldBox.w} height={foldBox.h} fill="url(#hs-fold)" opacity={0.92} className="hs-folded" rx={6} />}
{racers.map((x) => {
const { cx, cy, onPodium } = placeOf(g, x, racers, slots, ended);
const s = g.tok;
const dq = x.status === 'dq';
const turn = x.facing === 'back';
return (
<g key={x.id} className="hs-tok" style={{ transform: `translate(${cx}px, ${cy}px)` }} aria-label={tokenLabel(x)} role="img">
<g className={`hs-body${x.down && !onPodium ? ' down' : ''}${dq ? ' dq' : ''}`}>
<circle r={s / 2 + 3} className="hs-ring" style={{ stroke: MASCOTS[x.id].color }} />
<g transform={`translate(${-s / 2} ${-s / 2}) scale(${s / 100})${turn && !onPodium ? ` translate(100 0) scale(-1 1)` : ''}`}>
<MascotFace id={x.id} />
</g>
</g>
{turn && !onPodium && !dq && (
<text x={s / 2} y={-s / 2 + 6} className="hs-turn" fontSize={g.vertical ? 12 : 15} textAnchor="middle">
↩
</text>
)}
{dq && (
<text x={0} y={5} className="hs-stamp" fontSize={g.vertical ? 11 : 14} textAnchor="middle">
실격
</text>
)}
</g>
);
})}
{floats.map((f) => {
const x = racers.find((y) => y.id === f.id);
if (!x) return null;
const { cx, cy } = placeOf(g, { ...x, lane: f.lane, pos: f.pos }, racers, slots, ended);
return (
<text key={f.k} x={cx} y={cy - g.tok / 2 - 4} className={`hs-float ${f.cls}`} textAnchor="middle" fontSize={g.vertical ? 15 : 20}>
{f.text}
</text>
);
})}
</svg>
);
}
/** One sentence for screen readers about a race line. */
export function lineSpeech(l: RaceLine): string {
return [l.text, ...(l.notes ?? [])].join(' ');
}
export const nameGa = (id: MascotId) => josa(MASCOTS[id].name, '이', '가');

View File

@@ -36,6 +36,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
liar: () => import('./liar'),
'magical-athlete': () => import('./magical-athlete'),
blackjack: () => import('./blackjack'),
'hot-streak': () => import('./hot-streak'),
};
const cache = new Map<string, GameUI>();

View File

@@ -33,6 +33,7 @@ export const GAME_ICON: Record<string, string> = {
liar: '🤥',
'magical-athlete': '🏃',
blackjack: '🂡',
'hot-streak': '🏁',
};
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
@@ -42,5 +43,5 @@ export const UPCOMING: string[] = [];
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] },
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'hot-streak'] },
];

View File

@@ -47,6 +47,7 @@
| `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 |
| `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 |
| `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 |
| `hot-streak` | 핫스트릭 | 2~10 | 2026-10 새 게임 |
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).

View File

@@ -451,3 +451,15 @@ interface HotStreakState {
- 돈은 방 안에서만 쓰는 놀이용 가상 돈이다(docs/04 §6). 기록에는 승패만 남긴다.
- 원작과 다르게 정한 것: 9명 티켓 모드 무작위 5장, 네 번째 접기 전원 실격, 정산 합계 한 번에, 거꾸로 티켓 공동 등수, 허들 위치, 3단 위험·사이드 2단 값(※),
사이드 질문 세 개의 세부 판정. 실물·한국어판 규칙서로 확인되면 이 문서부터 고친다.
## 13. 구현 메모 (2026-10-15, 첫 구현)
- §2 옵션 13개를 모두 방 설정으로 구현했다(나중으로 미룬 옵션 없음). 코드: `packages/games/src/hot-streak/`(cards·rules·race·index·sim·bot), 화면 `apps/web/src/games/hot-streak/`(index·track·art·help·quick).
- 문서가 비어 있던 곳에서 정한 것:
- 넘어진 채 별 카드: 보는 쪽에 별이 있을 때만 그쪽으로 1칸(뒤쪽에 갈 별이 없으면 그대로).
- 경주 중 `activePlayers`는 빈 배열 대신 "아직 [빨리 보기]를 누르지 않은 사람"이다(공통 무작위 대국 도구가 진행 중인 게임에 기다리는 사람이 없으면 오류로 보기 때문). 카드 넘기기는 `timeoutPlayers`(남은 첫 자리) + `timeoutNotBefore = 다음 카드 시각`으로만 진행되어 연결이 끊겨도 빨라지거나 멈추지 않는다. 컴퓨터는 경주가 시작되면 [빨리 보기]에 동의하므로 사람들만 모두 누르면 바로 끝난다.
- 정산 화면은 8초(또는 모두 준비)인데, [빨리 보기]로 끝난 경주는 화면이 빠르게 다시 보여 주는 시간만큼 카드당 0.3초(최대 12초)를 더 기다린다. 화면은 다시 보기가 끝난 뒤 정산 표를 연다.
- 상금 나누기: 같은 정산 등수의 마스코트가 여럿이면(공동 실격) 그 등수의 상금 하나를 그 마스코트들에 건 사람 모두가 나눈다. 두 배·`bothBonus`도 상금 나누기 베팅 두 개에 같은 방식으로 적용한다.
- `draftStart=poorest` 동점: 지난 첫 사람의 시계 반대 방향 이웃부터 한 칸씩, 지난 첫 사람 자신은 맨 마지막.
- 결과 요약은 엔진이 닉네임을 몰라 "1위 $31 · 2위 $24"로 적는다(§6.4의 "OO님"은 화면 표에서 보여 준다).
- 사이드 질문 id(`out` 등)는 화면 정보의 키 이름과 겹쳐서, 유출 검사에는 "남은 사이드 카드 순서" 문자열 하나로 넣었다.
- 다음 경주 손패를 받기 전 지난 경주에 넘긴 카드 종류(`seenLast`)를 공개 정보로 둔다(모두 본 카드). 컴퓨터는 이것과 덱 앞면·자기 손패만으로 덱을 추정한다.

View File

@@ -3190,6 +3190,105 @@ const PLANS: Record<string, Plan> = {
console.log(` magical-athlete: ${st.picks} picks, ${st.selects} race picks, ${st.acts} turn choices (${st.second} second options), powers + wild track seen`);
},
},
'hot-streak': {
// PC host + phone guest, one race (so it is also the last one: 두 배 티켓), cards every 1.2 s. Real draft (one risky
// face), secret cards (2 each with 2 players), a few cards flipped by the server clock, then both press 빨리 보기,
// payout table, final result. The put-in cards stay private.
players: 2,
lobby: async (host) => {
await host.getByRole('group', { name: '경주 수' }).getByRole('button', { name: '1번(맛보기)' }).click();
await host.getByRole('group', { name: '카드 넘기는 간격' }).getByRole('button', { name: '1.2초' }).click();
await host.getByText('경주 1번').first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const st = { drafts: 0, risky: 0, doubles: 0, puts: 0, flips: 0, hurried: false, payout: false };
const shots = new Set<string>();
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
const shot = async (name: string) => {
if (shots.has(name)) return;
shots.add(name);
await host.screenshot({ path: join(SHOTS, `hot-streak-${name}-pc.png`) });
await guest.screenshot({ path: join(SHOTS, `hot-streak-${name}-phone.png`), fullPage: true });
await guest.setViewportSize({ width: 320, height: 720 });
await guest.waitForTimeout(300);
await guest.screenshot({ path: join(SHOTS, `hot-streak-${name}-phone320.png`), fullPage: true });
const wide = await guest.evaluate(() => document.documentElement.scrollWidth);
if (wide > 322) throw new Error(`hot-streak ${name}: page is ${wide}px wide at 320px`);
await guest.setViewportSize({ width: 390, height: 844 });
};
const tryClick = (l: Locator) => l.click({ timeout: 2000 }).then(() => true, () => false);
const until = Date.now() + 240_000;
while (Date.now() < until && !(await over())) {
let acted = false;
for (const p of pages) {
const stack = p.locator('section[aria-label="티켓 뽑기"] button.hs-stack:not([disabled])').first();
if (await stack.count()) {
if (st.drafts === 1) await shot('draft');
if (!(await stack.click({ timeout: 2000 }).then(() => true, () => false))) continue;
const risky = st.risky === 0;
if (!(await tryClick(p.getByRole('button', { name: risky ? /위험으로/ : /안전으로/ }).first()))) continue;
st.drafts++;
if (risky) st.risky++;
acted = true;
break;
}
const dbl = p.locator('section[aria-label="두 배 티켓 고르기"] button.btn:not([disabled])').first();
// The panel goes away once the server answers: a click that finds nothing is just retried next round.
if ((await dbl.count()) && (await dbl.click({ timeout: 2000 }).then(() => true, () => false))) {
st.doubles++;
acted = true;
break;
}
const cards = p.locator('section[aria-label="비밀 카드 넣기"] button.hs-hcard:not([disabled])');
if ((await cards.count()) && (await p.getByRole('button', { name: /몰래 넣기/ }).count())) {
await shot('submit');
if (!(await tryClick(cards.nth(0))) || !(await tryClick(cards.nth(1))) || !(await tryClick(p.getByRole('button', { name: /몰래 넣기/ })))) continue;
// The first one sees their own card while waiting; the last one starts the race at once.
if (st.puts === 0) await p.getByText('넣은 카드:').waitFor({ timeout: 5000 });
st.puts++;
acted = true;
break;
}
}
const flips = await host.locator('.hs-flipped .hs-card').count();
st.flips = Math.max(st.flips, flips);
if (flips >= 3 && !shots.has('race')) {
await shot('race');
await host.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(250);
await host.screenshot({ path: join(SHOTS, 'hot-streak-race-pc-dark.png') });
await host.emulateMedia({ colorScheme: 'light' });
// Secret cards: each sees only their own.
const mineH = await host.getByText('넣은 카드:').count();
const mineG = await guest.getByText('넣은 카드:').count();
if (mineH || mineG) throw new Error('put-in cards still shown during the race');
}
if (shots.has('race') && !st.hurried) {
for (const p of pages) await p.getByRole('button', { name: /빨리 보기/ }).click();
st.hurried = true;
}
const next = host.getByRole('button', { name: /최종 결과 보기|다음 경주로/ });
if (await next.count()) {
st.payout = true;
await host.waitForTimeout(300);
await shot('payout');
acted = await tryClick(next);
}
if (!acted) await host.waitForTimeout(150);
}
if (!(await over())) throw new Error(`game did not finish (${JSON.stringify(st)})`);
await guest.getByRole('dialog', { name: '게임 결과' }).waitFor();
await host.waitForTimeout(500);
await host.screenshot({ path: join(SHOTS, 'hot-streak-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'hot-streak-result-phone.png') });
await host.keyboard.press('Escape');
await host.locator('section[aria-label="최종 결과"]').waitFor();
await host.screenshot({ path: join(SHOTS, 'hot-streak-final-pc.png'), fullPage: true });
if (st.drafts !== 6 || st.doubles !== 2 || st.puts !== 2 || st.flips < 3 || !st.hurried || !st.payout) throw new Error(`too few real steps: ${JSON.stringify(st)}`);
console.log(` hot-streak: ${st.drafts} tickets (${st.risky} risky), ${st.doubles} doubles, ${st.puts} secret puts, ${st.flips}+ cards flipped on the clock, 빨리 보기, payout`);
},
},
};
const games = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(PLANS);

View File

@@ -12,6 +12,7 @@
"./liar/topics": "./src/liar/topics.ts",
"./magical-athlete/racers": "./src/magical-athlete/racers.ts",
"./seotda/money": "./src/seotda/money.ts",
"./hot-streak/cards": "./src/hot-streak/cards.ts",
"./*": "./src/*/index.ts"
},
"dependencies": {

View File

@@ -38,6 +38,7 @@ import { unoBot } from '../uno/bot';
import { liarBot } from '../liar/bot';
import { magicalAthleteBot } from '../magical-athlete/bot';
import { blackjackBot } from '../blackjack/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';
@@ -73,6 +74,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
uno: unoBot,
'magical-athlete': magicalAthleteBot,
blackjack: blackjackBot,
'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

@@ -33,6 +33,7 @@ import { uno } from './uno';
import { liar } from './liar';
import { magicalAthlete } from './magical-athlete';
import { blackjack } from './blackjack';
import { hotStreak } from './hot-streak';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -69,4 +70,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[liar.id]: liar,
[magicalAthlete.id]: magicalAthlete,
[blackjack.id]: blackjack,
[hotStreak.id]: hotStreak,
};

View File

@@ -59,6 +59,7 @@ export const BOT_GAMES: readonly string[] = [
'liar',
'magical-athlete',
'blackjack',
'hot-streak',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */

View File

@@ -45,6 +45,7 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true },
{ id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true },
{ id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true },
{ id: 'hot-streak', nameKo: '핫스트릭', minPlayers: 2, maxPlayers: 10, minutes: '15~25', level: '쉬움', blurb: '마스코트 넷의 엉망진창 달리기에 티켓으로 걸어요! 비밀 카드 한 장 몰래 넣고 소리 지르며 구경 · 놀이용 돈', available: true },
];
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);