Files
joke-app/apps/web/src/games/hot-streak/track.tsx
EJClaw 8aad123222 새 게임 핫스트릭: 마스코트 넷의 카드 경주에 티켓으로 거는 파티 게임(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>
2026-10-15 23:28:18 +09:00

404 lines
15 KiB
TypeScript

/**
* 핫스트릭 경주로 (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, '이', '가');