새 게임 핫스트릭: 마스코트 넷의 카드 경주에 티켓으로 거는 파티 게임(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

@@ -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'] },
];