diff --git a/apps/server/src/rooms/magical-athlete.room.test.ts b/apps/server/src/rooms/magical-athlete.room.test.ts new file mode 100644 index 0000000..d14a582 --- /dev/null +++ b/apps/server/src/rooms/magical-athlete.room.test.ts @@ -0,0 +1,103 @@ +/** 야단법석 달리기 through a real Room: practice games against computers played to the end from the person's own screen (docs/games/magical-athlete.md §10). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import type { MagicalAthleteAction, MagicalAthleteState, MagicalAthleteView } from '@bg/games/magical-athlete'; +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; +const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as MagicalAthleteView); + +/** What the person presses, read only from their own screen (uses a power whenever one is offered). */ +function personMove(v: MagicalAthleteView, me: string, n: number): MagicalAthleteAction | null { + if (v.phase === 'draft') return v.draft!.picker === me ? { type: 'DRAFT', racer: v.draft!.line[n % v.draft!.line.length]! } : null; + if (v.phase === 'select') { + if (v.picked[me]) return null; + const left = v.teams[me]!.filter((id) => !v.used[me]!.includes(id)); + return { type: 'SELECT', racers: left.slice(0, v.perRace) }; + } + const pr = v.prompt; + if (v.phase !== 'race' || !pr || pr.owner !== me) return null; + if (pr.step === 'go') return { type: 'GO', racer: pr.options[0]!.key as never }; + if (pr.step === 'roll') return n % 4 === 3 && pr.options.some((o) => o.key === 'use') ? { type: 'CHOOSE', key: 'use' } : { type: 'ROLL' }; + return { type: 'CHOOSE', key: n % 2 === 0 ? pr.options[0]!.key : 'skip' }; +} + +describe('야단법석 달리기 room flow', () => { + test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 출전 선수는 경주 전까지 안 보여요', (nBots) => { + const h = harness(); + let room: Room; + if (nBots === 1) room = h.manager.createPractice('A', 'magical-athlete') as Room; + else { + const r = h.manager.create('A', 'magical-athlete', '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 seen = 0; + let mine = 0; + for (let i = 0; i < 40_000 && !room.game!.finished; i++) { + h.clock.advance(250); + 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(); + const vs = views(a); + // A computer's secret pick never reaches my screen before the race starts. + for (const v of vs.slice(seen)) { + if (v.phase === 'select') for (const b of bots) expect(JSON.stringify(v)).not.toContain(`-${b}-`); + expect(v.me).toBe('A'); + } + seen = vs.length; + const v = vs.at(-1); + const m = v && personMove(v, 'A', 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 MagicalAthleteState; + expect(s.results).toHaveLength(4); + expect(s.timeouts.A).toBe(0); // every step of the person was a real press + expect(s.perRace).toBe(nBots === 1 ? 2 : 1); + for (const p of s.seats) expect(s.used[p]).toHaveLength(4 * s.perRace); + const last = views(a).at(-1)!; + expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort()); + const total = (p: string) => last.scores[p]!.total; + expect(last.result!.ranking[0]!.total).toBe(Math.max(...s.seats.map(total))); + expect(mine).toBeGreaterThan(20); + const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!; + expect(JSON.parse(row.result_json).practice).toBe(true); + }); +}); diff --git a/apps/web/src/games/help.test.ts b/apps/web/src/games/help.test.ts index 0918811..05d3f6a 100644 --- a/apps/web/src/games/help.test.ts +++ b/apps/web/src/games/help.test.ts @@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti const IDS = Object.keys(GAME_UI); test('모든 게임에 도움말이 있어요', () => { - expect(IDS).toHaveLength(32); + expect(IDS).toHaveLength(33); for (const id of IDS) { const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); expect(src, id).toMatch(/\bquickStart,/); diff --git a/apps/web/src/games/magical-athlete/help.test.ts b/apps/web/src/games/magical-athlete/help.test.ts new file mode 100644 index 0000000..3de1e34 --- /dev/null +++ b/apps/web/src/games/magical-athlete/help.test.ts @@ -0,0 +1,38 @@ +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 = 'magical-athlete'; +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.draft.order[s.draft.at]]; + +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/2바퀴'); +}); + +test('야단법석 달리기: 출전 선수 고르기와 경주', () => { + let { state } = setupGame(ID, 4); + while (state.phase === 'draft') { + const p = picker(state); + state = applyAction(ID, state, p, { type: 'DRAFT', racer: state.draft.line[0] }); + } + expect(helpNow(view(state, 'A'), 'A', users)).toContain('[내보내기]'); + state = applyAction(ID, state, 'A', { type: 'SELECT', racers: [state.teams.A[0]] }); + expect(helpNow(view(state, 'A'), 'A', users)).toContain('다른 사람이 고를 때까지 기다려요'); + for (const p of ['B', 'C', 'D']) state = applyAction(ID, state, p, { type: 'SELECT', racers: [state.teams[p][0]] }); + expect(state.phase).toBe('race'); + const v = view(state, null); + const owner = v.prompt.owner; + const mine = helpNow(view(state, owner), owner, users); + expect(mine).toContain('1번째 경주예요'); + expect(mine).toMatch(/차례예요|골라요/); + const other = state.seats.find((x: string) => x !== owner)!; + expect(helpNow(view(state, other), other, users)).toContain('기다려 주세요'); +}); diff --git a/apps/web/src/games/magical-athlete/help.ts b/apps/web/src/games/magical-athlete/help.ts new file mode 100644 index 0000000..8205564 --- /dev/null +++ b/apps/web/src/games/magical-athlete/help.ts @@ -0,0 +1,64 @@ +/** 야단법석 달리기 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { MagicalAthleteView } from '@bg/games/magical-athlete'; +import { RACERS } from '@bg/games/magical-athlete/racers'; +import type { PublicUser } from '@bg/shared/lite'; + +export function helpNow(v: MagicalAthleteView, me: string | null, players: Record): string { + const name = (p: string) => `${players[p]?.nickname ?? '다른 사람'}님`; + const seated = !!me && v.seats.includes(me); + const score = seated ? `지금까지 내 점수는 ${v.scores[me!]!.total}점이에요.` : ''; + const goal = '경주마다 1등과 2등만 점수를 받아요. 네 경주가 끝나면 점수가 가장 많은 사람이 이겨요.'; + + if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.'; + if (seated && v.left.includes(me!)) return '나는 그만해서 구경만 할 수 있어요. 내 선수는 자동으로 달려요.'; + + if (v.phase === 'draft') { + const d = v.draft!; + const head = `선수 뽑기 ${d.round}/${d.rounds}바퀴예요. 펼쳐진 선수 중에서 한 명씩 차례로 뽑아요.`; + if (seated && d.picker === me) { + const best = [...d.line].sort((a, b) => RACERS[b].rating - RACERS[a].rating)[0]; + return [ + `${head}\n지금 내가 고를 차례예요. 카드를 누르면 바로 내 선수가 돼요.`, + best ? `처음이라면 능력이 쉬운 ${RACERS[best].name}(${RACERS[best].text}) 같은 선수가 무난해요.` : '', + `각자 ${v.perRace * 4}명을 모아 경주마다 ${v.perRace}명씩 내보내요.`, + ] + .filter(Boolean) + .join('\n'); + } + return `${head}\n지금은 ${name(d.picker)}이 고르는 중이에요. ${seated ? '내 차례가 오면 카드를 눌러 뽑아요.' : ''}\n${goal}`.trim(); + } + + if (v.phase === 'select') { + const m = v.medals[v.raceNo - 1]!; + const head = `${v.raceNo}번째 경주(1등 ${m.gold}점, 2등 ${m.silver}점)에 내보낼 선수를 모두 몰래 고르는 중이에요.`; + if (!seated) return `${head}\n${goal}`; + if (v.mySelection) return `${head}\n나는 ${v.mySelection.racers.map((id) => RACERS[id].name).join(', ')}을(를) 골랐어요. 다른 사람이 고를 때까지 기다려요.\n${score}`; + return `${head}\n아직 안 달린 내 선수 ${v.perRace}명을 누른 뒤 [내보내기]를 눌러요. 한 번 달린 선수는 다시 못 나가요.\n${score}`; + } + + const r = v.race!; + const pr = v.prompt; + const lines = [`${r.no}번째 경주예요(${r.side === 'wild' ? '거친 판: 화살표·돌·별 칸이 있어요' : '순한 판'}). 30칸을 먼저 달려 결승선을 넘으면 돼요.`]; + if (!pr) return lines.join('\n'); + const racer = pr.racer ? `${RACERS[pr.racer].name}` : ''; + if (pr.owner !== me) { + lines.push(`지금은 ${name(pr.owner)}의 ${racer ? `${racer} ` : ''}차례예요. 기다려 주세요.`); + if (seated) { + const mine = r.racers.filter((x) => x.owner === me); + if (mine.length) lines.push(`내 선수: ${mine.map((x) => `${RACERS[x.id].name} ${x.status === 'done' ? `${x.place}등 도착` : x.status === 'out' ? '탈락' : `${x.pos}칸`}`).join(', ')}.`); + } + } else if (pr.step === 'go') { + lines.push('내 선수 둘 중 어느 선수가 먼저 움직일지 골라요. 둘 다 이번 차례에 움직여요.'); + } else if (pr.step === 'roll') { + lines.push(`내 ${racer} 차례예요. [🎲 주사위 굴리기]를 누르면 나온 만큼 앞으로 가요.`); + if (pr.racer === 'legs') lines.push('롱다리는 굴리지 않고 5칸을 갈 수도 있어요.'); + } else if (pr.step === 'start') { + lines.push(`내 ${racer} 차례예요. ${RACERS[pr.racer!].text} 쓰고 싶지 않으면 [능력 안 쓰고 주사위 굴리기]를 눌러요.`); + } else if (pr.step === 'reroll') { + lines.push(`주사위 ${r.roll?.value}이(가) 나왔어요. 마술사는 마음에 안 들면 다시 굴릴 수 있어요(두 번까지).`); + } else { + lines.push(`주사위 ${r.roll?.value}이(가) 나왔어요. ${RACERS[pr.racer!].text}`); + } + if (score) lines.push(score); + return lines.join('\n'); +} diff --git a/apps/web/src/games/magical-athlete/index.tsx b/apps/web/src/games/magical-athlete/index.tsx new file mode 100644 index 0000000..81ddccb --- /dev/null +++ b/apps/web/src/games/magical-athlete/index.tsx @@ -0,0 +1,825 @@ +/** 야단법석 달리기 화면 (docs/games/magical-athlete.md §9). Points are play points of this room only. */ +import { useEffect, useLayoutEffect, useRef, useState } from 'react'; +import type { LogLine, MaPrompt, MaRacerView, MagicalAthleteOptions, MagicalAthleteView, RaceResult, SpaceEffect } from '@bg/games/magical-athlete'; +import { RACERS, type RacerId } from '@bg/games/magical-athlete/racers'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar, ConfirmSheet } from '../../components/ui'; +import { TurnTimer } from '../../components/TurnTimer'; +import { haptic, sounds } from '../../lib/feedback'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +const ROLL_MS = 600; +const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4']; + +const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; +const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; +const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches; +const seatColor = (v: MagicalAthleteView, p: string) => COLORS[v.seats.indexOf(p)] ?? '#888'; +const rname = (id: RacerId) => `${RACERS[id].emoji} ${RACERS[id].name}`; +const who = (players: Record, me: string | null, p: string) => (p === me ? '나' : nick(players, p)); + +const CSS = ` +.ma-wrap { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; } +/* Taller than the play area on PC: start at the top (centring would cut the top off where nobody can scroll to). */ +.game-main:has(> .ma-wrap) { justify-content: flex-start; } +.ma-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; flex-wrap: wrap; padding: 10px 14px; } +.ma-side-tag { border-radius: 999px; padding: 2px 10px; font-weight: 800; font-size: .85rem; } +.ma-side-tag.mild { background: var(--success-soft); color: var(--success); } +.ma-side-tag.wild { background: var(--warning-soft); color: var(--warning); } +.ma-track { padding: 8px; overflow: hidden; } +.ma-track svg { display: block; width: 100%; height: auto; } +.ma-cell { fill: var(--surface-2); stroke: var(--border); stroke-width: 1.5; } +.ma-cell.start { fill: var(--primary-soft); } +.ma-cell.finish { fill: #fde68a; stroke: #b45309; } +.ma-cell.cur { stroke: var(--focus); stroke-width: 3; } +.ma-num { fill: var(--text-sub); font-size: 11px; font-weight: 700; } +.ma-num.fin { fill: #92400e; } +.ma-fx { font-size: 15px; } +.ma-fxt { font-size: 11px; font-weight: 900; } +.ma-tok { transition: transform .45s ease; } +.ma-tok circle { stroke: #1f2937; stroke-width: 2; } +.ma-tok.cur circle { stroke: var(--focus); stroke-width: 4; } +.ma-tok.trip { opacity: .55; } +.ma-emoji { font-size: 16px; } +.ma-lower { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; align-items: start; } +.ma-panel { padding: 12px; display: flex; flex-direction: column; gap: 10px; } +.ma-panel h3 { margin: 0; font-size: 1rem; } +.ma-opts { display: flex; flex-direction: column; gap: 8px; } +.ma-opts .btn { min-height: 52px; font-size: 1.02rem; } +.ma-die { width: 54px; height: 54px; border-radius: 12px; background: #fffdf8; border: 3px solid #1f2937; display: inline-block; flex: none; } +.ma-die svg { width: 100%; height: 100%; display: block; } +@keyframes ma-tumble { 0% { transform: translateY(-14px) rotate(-50deg); } 60% { transform: translateY(3px) rotate(200deg); } 100% { transform: none; } } +.ma-die.rolling { animation: ma-tumble ${ROLL_MS}ms ease-out both; } +.ma-rollrow { display: flex; align-items: center; gap: 12px; } +.ma-news { display: flex; flex-direction: column; gap: 4px; } +.ma-news div { border-radius: 8px; padding: 6px 10px; font-size: .92rem; background: var(--surface-2); } +.ma-news .power { background: var(--primary-soft); font-weight: 700; } +.ma-news .space { background: var(--warning-soft); } +.ma-news .finish { background: var(--success-soft); font-weight: 800; } +@keyframes ma-pop { 0% { transform: scale(.94); opacity: 0; } 100% { transform: none; opacity: 1; } } +.ma-news .fresh { animation: ma-pop .35s ease-out both; } +.ma-log { max-height: 220px; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; font-size: .85rem; margin: 0; padding: 0; list-style: none; } +.ma-log li { padding: 2px 4px; border-bottom: 1px solid var(--border); } +.ma-log li.power { font-weight: 700; } +.ma-legend { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 6px; margin: 0; padding: 0; list-style: none; } +.ma-legend li { display: flex; gap: 8px; align-items: flex-start; padding: 6px 8px; border-radius: 10px; border: 2px solid var(--border); background: var(--surface); } +.ma-legend li.cur { border-color: var(--focus); } +.ma-legend li.gone { opacity: .6; } +.ma-dot { width: 14px; height: 14px; border-radius: 50%; border: 2px solid rgba(0,0,0,.45); flex: none; margin-top: 3px; display: inline-block; } +.ma-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 8px; } +.ma-card { display: flex; flex-direction: column; gap: 4px; padding: 10px; border-radius: var(--radius); border: 3px solid var(--border); background: var(--surface); color: var(--text); font: inherit; text-align: left; min-height: 104px; } +button.ma-card { cursor: pointer; } +button.ma-card:hover:not(:disabled) { border-color: var(--primary); } +.ma-card:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.ma-card[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); } +.ma-card:disabled { cursor: default; } +.ma-card.used { opacity: .45; } +.ma-card b { font-size: 1.05rem; } +.ma-card .em { font-size: 1.6rem; line-height: 1; } +.ma-card small { color: var(--text-sub); line-height: 1.35; } +.ma-chips { display: flex; flex-wrap: wrap; gap: 4px; } +.ma-chip { display: inline-flex; align-items: center; gap: 2px; border-radius: 999px; padding: 1px 8px; font-size: .8rem; background: var(--surface-2); border: 1px solid var(--border); white-space: nowrap; } +.ma-chip.used { opacity: .45; text-decoration: line-through; } +.ma-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; font-size: .9rem; } +.ma-table th, .ma-table td { padding: 4px 6px; border-bottom: 1px solid var(--border); text-align: center; } +.ma-table td.l { text-align: left; } +@media (max-width: 899px) { + .ma-lower { grid-template-columns: minmax(0, 1fr); } +} +@media (max-width: 599px) { + .ma-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; } + .ma-card { padding: 8px; min-height: 96px; } + .ma-card small { font-size: .78rem; } + .ma-legend { grid-template-columns: minmax(0, 1fr); } + .ma-panel.act { position: sticky; bottom: 0; z-index: 4; box-shadow: 0 -4px 14px rgba(0,0,0,.12); } +} +@media (prefers-reduced-motion: reduce) { + .ma-tok { transition: none; } + .ma-die.rolling, .ma-news .fresh { animation: none; } +} +`; + +// prettier-ignore +const PIPS: Record = { + 1: [[50, 50]], 2: [[28, 28], [72, 72]], 3: [[26, 26], [50, 50], [74, 74]], + 4: [[28, 28], [72, 28], [28, 72], [72, 72]], 5: [[26, 26], [74, 26], [50, 50], [26, 74], [74, 74]], + 6: [[28, 24], [72, 24], [28, 50], [72, 50], [28, 76], [72, 76]], +}; + +function Die({ value, rolling }: { value: number; rolling: boolean }) { + return ( + + + {PIPS[value]!.map(([x, y], i) => ( + + ))} + + + ); +} + +function useNarrow(): boolean { + const q = '(max-width: 599px)'; + const [narrow, setNarrow] = useState(() => typeof matchMedia !== 'undefined' && matchMedia(q).matches); + useEffect(() => { + if (typeof matchMedia === 'undefined') return; + const m = matchMedia(q); + const on = () => setNarrow(m.matches); + m.addEventListener('change', on); + return () => m.removeEventListener('change', on); + }, []); + return narrow; +} + +// ---------------------------------------------------------------- track + +const CELL = 60; + +function fxText(e: SpaceEffect): string { + if (e.kind === 'arrow') return e.by > 0 ? `앞으로 ${e.by}칸 화살표` : `뒤로 ${-e.by}칸 화살표`; + return e.kind === 'rock' ? '돌(넘어짐)' : '별(1점)'; +} + +function Track({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { + const r = v.race!; + const narrow = useNarrow(); + const cols = narrow ? 8 : 11; + const cells = v.finish + 1; // 0..29 + finish + const rows = Math.ceil(cells / cols); + const at = (i: number) => { + const row = Math.floor(i / cols); + const k = i % cols; + const col = row % 2 === 0 ? k : cols - 1 - k; + return { x: col * CELL, y: row * CELL }; + }; + const fx = new Map(v.spaces[r.side].map((s) => [s.pos, s.effect])); + const onTrack = r.racers.filter((x) => x.status !== 'out'); + const groups = new Map(); + for (const x of onTrack) groups.set(x.pos, [...(groups.get(x.pos) ?? []), x]); + const curPos = r.cur ? r.racers.find((x) => x.id === r.cur)?.pos : undefined; + const label = `${r.no}번째 경주 ${r.side === 'wild' ? '거친 판' : '순한 판'}. ${r.racers + .map((x) => `${RACERS[x.id].name}(${who(players, me, x.owner)}) ${x.status === 'done' ? `${x.place}등 도착` : x.status === 'out' ? '탈락' : `${x.pos}칸${x.tripped ? ' 넘어짐' : ''}`}`) + .join(', ')}`; + return ( +
+ + {Array.from({ length: cells }, (_, i) => { + const { x, y } = at(i); + const e = fx.get(i); + const cls = `ma-cell${i === 0 ? ' start' : ''}${i === v.finish ? ' finish' : ''}${curPos === i && i !== v.finish ? ' cur' : ''}`; + return ( + + + + {i === 0 ? '출발' : i === v.finish ? '결승' : i} + + {i === v.finish && ( + + 🏁 + + )} + {e && ( + + {e.kind === 'arrow' ? ( + 0 ? 'var(--success)' : 'var(--danger)'}> + {e.by > 0 ? `▶+${e.by}` : `◀${e.by}`} + + ) : ( + + {e.kind === 'rock' ? '🪨' : '⭐'} + + )} + + )} + + ); + })} + {onTrack.map((x) => { + const group = groups.get(x.pos)!; + const k = group.indexOf(x); + const n = group.length; + const per = n <= 4 ? 2 : 3; + const size = n === 2 ? 12 : n <= 4 ? 11 : 9; + const { x: cx, y: cy } = at(Math.min(x.pos, v.finish)); + const ox = cx + (n === 1 ? CELL / 2 : 14 + (k % per) * ((CELL - 28) / Math.max(1, per - 1))); + // Below the space number (top-left), so a crowded space never hides it. + const oy = cy + (n === 1 ? CELL / 2 + 4 : n === 2 ? 34 : 30 + Math.floor(k / per) * (size * 2 - 6)); + const isCur = r.cur === x.id; + return ( + + + + {RACERS[x.id].emoji} + + {x.place && ( + + {x.place === 1 ? '🥇' : '🥈'} + + )} + + ); + })} + +
+ ); +} + +function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { + const r = v.race!; + return ( +
+

이번 경주 선수

+
    + {r.racers.map((x) => ( +
  • + +
    +
    + {rname(x.id)} · {who(players, me, x.owner)} +
    +
    + {x.status === 'done' ? `🏁 ${x.place}등 도착` : x.status === 'out' ? '탈락' : `${x.pos === 0 ? '출발점' : `${x.pos}칸`}${x.tripped ? ' · 넘어짐(다음 차례 쉼)' : ''}`} +
    +
    {RACERS[x.id].text}
    +
    +
  • + ))} +
+
+ ); +} + +// ---------------------------------------------------------------- panels + +function actionFor(pr: MaPrompt, key: string): unknown { + if (pr.step === 'go') return { type: 'GO', racer: key }; + if (pr.step === 'roll' && key === 'roll') return { type: 'ROLL' }; + return { type: 'CHOOSE', key }; +} + +const STEP_TITLE: Record = { + go: '어느 선수가 먼저 갈까요?', + start: '차례 시작: 능력을 쓸까요?', + roll: '주사위를 굴려요', + reroll: '다시 굴릴까요?', + boost: '능력을 쓸까요?', +}; + +function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; rolling: boolean }) { + const r = v.race!; + const pr = v.prompt; + const mine = !!pr && pr.owner === me; + const curName = r.cur ? rname(r.cur) : ''; + return ( +
+ {pr ? ( + <> +
+ {r.roll?.value ? : } +
+ {pr.owner === me ? '내 차례' : `${nick(players, pr.owner)}님 차례`} +
{curName ? `${curName}${r.roll?.value ? ` · 주사위 ${r.roll.value}` : ''}` : '먼저 갈 선수 고르기'}
+
+
+ {mine ? ( + <> +

{STEP_TITLE[pr.step]}

+
+ {pr.options.map((o, i) => ( + + ))} +
+

+ 시간이 지나면 {pr.timeoutText}. +

+ + ) : ( +

+ {nick(players, pr.owner)}님이 {pr.step === 'roll' ? '주사위를 굴릴 차례예요' : pr.step === 'go' ? '먼저 갈 선수를 고르는 중이에요' : '능력을 쓸지 고르는 중이에요'}. +

+ )} + + ) : ( +

+ 경주가 끝났어요. +

+ )} +
+ ); +} + +function Draft({ v, me, players, act, pending }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean }) { + const d = v.draft!; + const mine = d.picker === me; + return ( +
+

+ 선수 뽑기 {d.round}/{d.rounds}바퀴 · {mine ? '내가 고를 차례예요' : `${nick(players, d.picker)}님이 고르는 중`} +

+

+ 순서: {[d.picker, ...d.next].map((p) => who(players, me, p)).join(' → ')} (남은 선수 더미 {v.deckCount}명) +

+
+ {d.line.map((id) => ( + + ))} +
+
+ ); +} + +function Select({ v, me, players, act, pending }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean }) { + const [sel, setSel] = useState([]); + useEffect(() => setSel([]), [v.raceNo]); + const seated = !!me && v.seats.includes(me) && !v.left.includes(me); + const team = seated ? v.teams[me!]! : []; + const used = seated ? v.used[me!]! : []; + const done = v.mySelection; + const toggle = (id: RacerId) => + setSel((cur) => (cur.includes(id) ? cur.filter((x) => x !== id) : v.perRace === 1 ? [id] : [...cur, id].slice(-v.perRace))); + const side = v.options.track === 'mild' ? '순한 판' : v.options.track === 'wild' ? '거친 판' : v.raceNo % 2 ? '순한 판' : '거친 판'; + const m = v.medals[v.raceNo - 1]!; + return ( +
+

+ {v.raceNo}번째 경주({side}, 1등 {m.gold}점 · 2등 {m.silver}점)에 내보낼 선수 {v.perRace}명 +

+

+ 다른 사람에게는 고른 선수가 경주가 시작될 때까지 보이지 않아요. 고른 사람: {v.seats.filter((p) => v.picked[p]).map((p) => who(players, me, p)).join(', ') || '아직 없음'} +

+ {seated && !done && ( + <> +
+ {team.map((id) => { + const u = used.includes(id); + return ( + + ); + })} +
+ + + )} + {done &&

내가 고른 선수: {done.racers.map(rname).join(', ')}. 다른 사람을 기다려요.

} +
+ ); +} + +function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { + if (!v.results.length) return null; + const cell = (id: RacerId | null, rr: RaceResult) => { + if (!id) return '—'; + const o = rr.field.find((x) => x.id === id)!.owner; + return ( + <> + + {rname(id)} ({who(players, me, o)}) + + ); + }; + return ( +
+

경주 결과

+ + + + + + + + + + {v.results.map((rr) => ( + + + + + + ))} + +
경주🥇 1등🥈 2등
+ {rr.no} + {rr.capped &&
시간 다 됨
} +
{cell(rr.gold, rr)}{cell(rr.silver, rr)}
+
+ ); +} + +function FinalTable({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { + const r = v.result!; + return ( +
+

최종 결과

+ + + + + + + + + + + + + {r.ranking.map((row) => ( + + + + + + + + + ))} + +
순위이름🥇🥈⭐ 보너스합계
{row.rank}등 + + {who(players, me, row.player)} + {row.left && (나감)} + {row.gold}{row.silver}{row.bonus} + {row.total}점 +
+
+ ); +} + +const ICON: Record = { turn: '▶', roll: '🎲', move: '👟', power: '✨', space: '🧭', finish: '🏁', info: 'ℹ️' }; + +function News({ lines, fresh }: { lines: LogLine[]; fresh: number }) { + if (!lines.length) return null; + return ( +
+ {lines.map((l) => ( +
fresh ? ' fresh' : ''}`}> + {ICON[l.kind]} {l.text} +
+ ))} +
+ ); +} + +// ---------------------------------------------------------------- board + +function Board({ view: v, me, players, act, pending }: BoardProps) { + const [rolling, setRolling] = useState(false); + const [announce, setAnnounce] = useState(''); + const prevRoll = useRef(v.rollSeq); + const prevLog = useRef(v.race?.log.at(-1)?.n ?? 0); + const prevRace = useRef(v.race?.no ?? 0); + const [fresh, setFresh] = useState(prevLog.current); + const prevTurn = useRef(v.turnSeq); + + useLayoutEffect(() => { + if (v.rollSeq <= prevRoll.current) { + prevRoll.current = v.rollSeq; + return; + } + prevRoll.current = v.rollSeq; + if (reducedMotion()) return sounds.stone(); + setRolling(true); + const t = setTimeout(() => { + setRolling(false); + sounds.stone(); + }, ROLL_MS); + return () => clearTimeout(t); + }, [v.rollSeq]); + + // New log lines → screen-reader announcement and the "방금 일어난 일" highlight. + useEffect(() => { + const r = v.race; + if (!r) return; + if (r.no !== prevRace.current) { + prevRace.current = r.no; + prevLog.current = 0; + } + const last = r.log.at(-1)?.n ?? 0; + if (last <= prevLog.current) return; + const added = r.log.filter((l) => l.n > prevLog.current && l.kind !== 'turn'); + setFresh(prevLog.current); + prevLog.current = last; + if (added.length) setAnnounce(added.slice(-4).map((l) => l.text).join(' ')); + if (added.some((l) => l.kind === 'power')) haptic(30); + if (added.some((l) => l.kind === 'finish')) sounds.ding(); + }, [v.race?.log.at(-1)?.n, v.race?.no]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (v.turnSeq === prevTurn.current) return; + prevTurn.current = v.turnSeq; + if (isMyTurn(v, me)) { + haptic(40); + if (document.visibilityState === 'hidden') sounds.myTurn(); + } + }, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps + + const r = v.race; + // Lines of the latest step (since the last turn line), newest last. + const recent = (() => { + if (!r) return []; + const lastTurn = [...r.log].reverse().find((l) => l.kind === 'turn'); + const from = lastTurn ? r.log.indexOf(lastTurn) : 0; + const prevTurnIdx = lastTurn ? [...r.log.slice(0, from)].reverse().find((l) => l.kind === 'turn') : undefined; + // Show the previous racer's turn too while the current one hasn't done anything yet. + const start = from === r.log.length - 1 && prevTurnIdx ? r.log.indexOf(prevTurnIdx) : from; + return r.log.slice(start).filter((l) => l.kind !== 'turn').slice(-6); + })(); + + return ( +
+ +
+ {v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? '선수 뽑기' : `${v.raceNo} / ${v.races} 경주`} + {r && v.phase === 'race' && {r.side === 'wild' ? '거친 판' : '순한 판'}} + + {v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.gold}점 · 2등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.silver}점 + +
+ {v.result && } + {v.phase === 'draft' && v.draft && } + {v.phase === 'select' &&