/** 야단법석 달리기 화면 (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, noise, sfx, sounds, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { itemsOf, type Item } from './replay'; import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; 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)); /** Game sounds on top of the shared palette (site volume applies). */ const maSound = { /** One footstep onto the next space. */ step: (i: number) => { tone(i % 2 ? 620 : 540, 40, 'triangle', 0.08); noise(26, 0.05, 0, 'lowpass', 1500); }, /** The token lands on its space. */ land: () => { tone(300, 90, 'triangle', 0.13); noise(60, 0.08, 0, 'lowpass', 700); }, /** The die stops on the table. */ dieLand: () => { noise(50, 0.12, 0, 'lowpass', 900); tone(180, 60, 'triangle', 0.1); }, /** A racer's power: a quick sparkle up. */ power: () => [880, 1175, 1568].forEach((f, i) => tone(f, 90, 'triangle', 0.08, i * 60)), /** Star space (+1 point). */ star: () => { tone(1318, 70, 'square', 0.05); tone(1976, 160, 'square', 0.05, 70); }, /** Rock space / slipped: tripped. */ trip: () => { noise(90, 0.12, 0, 'lowpass', 500); tone(300, 220, 'sawtooth', 0.05, 40, { slideTo: 140 }); }, /** Arrow space: slide forward / back. */ arrow: (up: boolean) => tone(up ? 500 : 900, 260, 'sine', 0.09, 0, { slideTo: up ? 1000 : 450 }), /** Flown to another space (최면술사·끼어들기·자리바꿈이·시시포스). */ fly: () => tone(400, 300, 'sine', 0.07, 0, { slideTo: 1100 }), /** Crossing the finish line. */ finish: () => [784, 988, 1318, 1568].forEach((f, i) => tone(f, 140, 'triangle', 0.1, i * 90)), }; // ---------------------------------------------------------------- board geometry (viewBox 0..1000 × 0..g.bh) /** * A ring board like 부루마불: space 0 (출발) at the bottom-right corner, then clockwise — the bottom row leftwards, up the * left side, the top row rightwards and down the right side. 30 spaces go round once, so the finish line (30) is the * start corner again: one lap. PC: 9 across × 8 down (corners included); phone: 7 × 10, taller for a portrait screen. */ interface Geo { across: number; down: number; /** Corner size; side spaces are `sw` wide and `corner` deep. */ corner: number; sw: number; bh: number; corners: number[]; /** Text / token scale (phone spaces are drawn smaller on screen). */ k: number; } const BW = 1000; const RING = 30; function geoOf(across: number, down: number, corner: number, k: number): Geo { const sw = (BW - 2 * corner) / (across - 2); return { across, down, corner, sw, bh: Math.round(2 * corner + (down - 2) * sw), corners: [0, across - 1, across + down - 2, 2 * across + down - 3], k }; } const WIDE = geoOf(9, 8, 132, 1); const TALL = geoOf(7, 10, 150, 1.35); /** Band colour of each side (inner edge), bottom → left → top → right. */ const BANDS = ['#f97316', '#3b82f6', '#22c55e', '#a855f7']; /** Band on the inner edge of a side space. */ const BAND_W = 16; type Side = 0 | 1 | 2 | 3; interface Cell { x: number; y: number; w: number; h: number; side: Side; corner: boolean; } function cellOf(g: Geo, pos: number): Cell { const i = ((pos % RING) + RING) % RING; const { corner: C, sw: SW, bh: BH } = g; const [, bl, tl, tr] = g.corners as [number, number, number, number]; if (i === 0) return { x: BW - C, y: BH - C, w: C, h: C, side: 0, corner: true }; if (i < bl) return { x: BW - C - i * SW, y: BH - C, w: SW, h: C, side: 0, corner: false }; if (i === bl) return { x: 0, y: BH - C, w: C, h: C, side: 1, corner: true }; if (i < tl) return { x: 0, y: BH - C - (i - bl) * SW, w: C, h: SW, side: 1, corner: false }; if (i === tl) return { x: 0, y: 0, w: C, h: C, side: 2, corner: true }; if (i < tr) return { x: C + (i - tl - 1) * SW, y: 0, w: SW, h: C, side: 2, corner: false }; if (i === tr) return { x: BW - C, y: 0, w: C, h: C, side: 3, corner: true }; return { x: BW - C, y: C + (i - tr - 1) * SW, w: C, h: SW, side: 3, corner: false }; } /** A point inside a space: `u` along the row (0..width), `d` inwards from the outer edge (0..depth). */ function local(c: Cell, u: number, d: number): [number, number] { if (c.corner) { // Corners: measured from the outer corner. const ox = c.x === 0 ? c.x : c.x + c.w; const oy = c.y === 0 ? c.y : c.y + c.h; return [ox + (c.x === 0 ? u : -u), oy + (c.y === 0 ? d : -d)]; } switch (c.side) { case 0: return [c.x + u, c.y + c.h - d]; case 1: return [c.x + d, c.y + u]; case 2: return [c.x + u, c.y + d]; default: return [c.x + c.w - d, c.y + u]; } } const span = (g: Geo, c: Cell) => (c.corner ? g.corner : g.sw); /** Outer part of a space with its number and effect; tokens stand between it and the band. */ const infoOf = (g: Geo) => 54 * g.k; /** Token radius when `n` tokens share a space. */ const tokR = (g: Geo, n: number) => (n <= 1 ? 32 : n === 2 ? 25 : n <= 4 ? 19 : 16) * g.k; /** Where token `i` of `n` on a space stands. */ function spot(g: Geo, pos: number, i: number, n: number): [number, number] { const c = cellOf(g, pos); const w = span(g, c); const info = infoOf(g); const mid = c.corner ? g.corner / 2 + 10 * g.k : info + (g.corner - info - BAND_W) / 2; if (n <= 1) return local(c, w / 2, mid); if (n === 2) return local(c, w / 2 + (i ? 26 : -26) * g.k, mid); const cols = n <= 4 ? 2 : 3; const gap = (cols === 2 ? 42 : 33) * g.k; const row = Math.floor(i / cols); const col = i % cols; return local(c, w / 2 + (col - (cols - 1) / 2) * gap, mid + (row ? 17 : -17) * g.k); } const cellCenter = (g: Geo, pos: number) => spot(g, pos, 0, 1); // ---------------------------------------------------------------- styles const ROLL_MS = 900; const CSS = ` .ma-wrap { width: 100%; max-width: 1100px; display: flex; flex-direction: column; align-items: center; gap: 10px; } .ma-wrap > * { width: 100%; } /* 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); } /* The board (부루마불-style ring) */ .ma-track { padding: 0; background: none; border: 0; box-shadow: none; display: flex; flex-direction: column; align-items: center; gap: 6px; } .ma-box { position: relative; width: 100%; aspect-ratio: ${BW} / ${WIDE.bh}; max-width: min(100%, calc((100vh - var(--site-h) - 52px - 88px) * ${(BW / WIDE.bh).toFixed(3)})); } .ma-box.tall { aspect-ratio: ${BW} / ${TALL.bh}; max-width: 100%; } @media (max-width: 1099px) { .ma-box { max-width: min(100%, 780px); } } .ma-svg { position: absolute; inset: 0; width: 100%; height: 100%; display: block; border-radius: 18px; box-shadow: var(--shadow); user-select: none; } .ma-cell { stroke: var(--border); stroke-width: 2; } .ma-num { fill: var(--text-sub); font-weight: 800; } .ma-trail { animation: ma-trail .55s ease-out both; pointer-events: none; } @keyframes ma-trail { from { opacity: .7; } to { opacity: 0; } } .ma-tok { transition-property: transform; transition-timing-function: linear; } .ma-body { transform-box: fill-box; transform-origin: center bottom; } .ma-hop { animation: ma-hop var(--ma-dur, 150ms) ease-out; } @keyframes ma-hop { 0% { transform: translateY(0); } 45% { transform: translateY(-22px) scale(1.06); } 100% { transform: translateY(0); } } .ma-fly { animation: ma-fly var(--ma-dur, 420ms) ease-in-out; } @keyframes ma-fly { 0% { transform: none; } 50% { transform: translateY(-46px) scale(1.45); } 100% { transform: none; } } .ma-trip-anim { animation: anim-shake .45s ease both; } .ma-ring { animation: ma-pulse 1.1s ease-in-out infinite; pointer-events: none; } @keyframes ma-pulse { 0%, 100% { opacity: .35; } 50% { opacity: 1; } } .ma-float { font-weight: 900; font-size: 30px; paint-order: stroke; stroke: var(--surface); stroke-width: 6px; stroke-linejoin: round; pointer-events: none; animation: ma-float 1.3s ease-out both; } .ma-float.power { fill: #8e5cf0; } .ma-float.star { fill: #d97706; } .ma-float.trip, .ma-float.back { fill: var(--danger); } .ma-float.up { fill: var(--success); } .ma-float.info { fill: var(--text-sub); font-size: 24px; } @keyframes ma-float { 0% { transform: translateY(10px) scale(.6); opacity: 0; } 18% { transform: translateY(0) scale(1.1); opacity: 1; } 75% { opacity: 1; } 100% { transform: translateY(-34px); opacity: 0; } } .ma-float, .ma-conf { transform-box: fill-box; transform-origin: center; } .ma-conf { animation: ma-conf 1.1s cubic-bezier(.2,.7,.4,1) both; pointer-events: none; } @keyframes ma-conf { 0% { transform: translate(0, 0) rotate(0); opacity: 1; } 100% { transform: translate(var(--dx), var(--dy)) rotate(var(--rot)); opacity: 0; } } /* Centre of the ring: dice, whose turn, podium, what to do, what just happened. */ .ma-center { position: absolute; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; padding: 10px; overflow: auto; text-align: center; } .ma-title { font-weight: 900; font-size: 1.35rem; letter-spacing: -.02em; opacity: .85; } .ma-meta { display: flex; gap: 6px; flex-wrap: wrap; justify-content: center; } .ma-pill { display: inline-flex; align-items: center; gap: 4px; padding: 2px 10px; border-radius: 999px; background: var(--surface); border: 1px solid var(--border); font-weight: 700; font-size: .85rem; white-space: nowrap; } .ma-dice-row { display: flex; align-items: center; gap: 14px; justify-content: center; min-height: 76px; } .ma-now { text-align: left; min-width: 0; } .ma-now strong { display: block; font-size: 1.05rem; } .ma-podium { display: flex; gap: 6px; flex-wrap: wrap; justify-content: center; } .ma-podium span { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 3px 10px 3px 4px; background: var(--surface); border: 2px solid; font-weight: 800; font-size: .9rem; } .ma-podium i { font-style: normal; width: 24px; height: 24px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; color: #fff; font-size: .85rem; } .ma-ticker { width: 100%; max-width: 440px; display: flex; flex-direction: column; gap: 3px; } .ma-ticker div { border-radius: 8px; padding: 4px 10px; font-size: .86rem; background: var(--surface); border: 1px solid var(--border); text-align: left; animation: ma-in .3s ease-out both; } .ma-ticker .power { background: var(--primary-soft); font-weight: 700; } .ma-ticker .space { background: var(--warning-soft); } .ma-ticker .finish { background: var(--success-soft); font-weight: 800; } .ma-ticker div:not(:last-child) { opacity: .7; } @keyframes ma-in { from { transform: translateY(6px); opacity: 0; } } .ma-center .ma-panel.act { width: 100%; max-width: 440px; background: var(--surface); border-radius: 14px; border: 2px solid var(--border); box-shadow: var(--shadow); padding: 10px; gap: 8px; } .ma-center .ma-panel.act.mine { border-color: var(--primary); } .ma-banner-wrap { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; z-index: 3; } .ma-banner { padding: 10px 24px; border-radius: 18px; font-weight: 900; font-size: 2rem; letter-spacing: -.02em; white-space: nowrap; background: var(--surface); color: var(--primary); border: 3px solid currentColor; box-shadow: 0 12px 34px rgba(0,0,0,.32); } .ma-banner.gold { color: #b45309; } .ma-banner.silver { color: #64748b; } .ma-key { display: flex; flex-wrap: wrap; gap: 4px 14px; justify-content: center; font-size: .85rem; color: var(--text-sub); } /* 3D die */ .ma-die3d { --ds: 64px; width: var(--ds); height: var(--ds); perspective: 420px; position: relative; flex: none; } .ma-cube { position: absolute; inset: 0; transform-style: preserve-3d; transform: translate3d(0,0,0) rotateX(var(--rx)) rotateY(var(--ry)); } .ma-die3d.rolling .ma-cube { animation: ma-roll ${ROLL_MS}ms cubic-bezier(.25,.6,.3,1) both; } @keyframes ma-roll { 0% { transform: translate3d(-46px,-70px,0) rotateX(calc(var(--rx) + 720deg)) rotateY(calc(var(--ry) + 540deg)); } 45% { transform: translate3d(0,0,0) rotateX(calc(var(--rx) + 200deg)) rotateY(calc(var(--ry) + 150deg)); } 68% { transform: translate3d(0,-16px,0) rotateX(calc(var(--rx) + 40deg)) rotateY(calc(var(--ry) + 30deg)); } 84% { transform: translate3d(0,0,0) rotateX(calc(var(--rx) - 6deg)) rotateY(calc(var(--ry) + 4deg)); } 100% { transform: translate3d(0,0,0) rotateX(var(--rx)) rotateY(var(--ry)); } } .ma-face { position: absolute; inset: 0; border-radius: 14%; background: #fffdf8; border: 2px solid #d6cfc0; box-shadow: inset 0 0 10px rgba(0,0,0,.12); backface-visibility: hidden; } .ma-face svg { width: 100%; height: 100%; display: block; } .ma-face.f1 { transform: translateZ(calc(var(--ds) / 2)); } .ma-face.f6 { transform: rotateY(180deg) translateZ(calc(var(--ds) / 2)); } .ma-face.f3 { transform: rotateY(90deg) translateZ(calc(var(--ds) / 2)); } .ma-face.f4 { transform: rotateY(-90deg) translateZ(calc(var(--ds) / 2)); } .ma-face.f2 { transform: rotateX(90deg) translateZ(calc(var(--ds) / 2)); } .ma-face.f5 { transform: rotateX(-90deg) translateZ(calc(var(--ds) / 2)); } .ma-die-shadow { position: absolute; left: 10%; right: 10%; bottom: -10px; height: 10px; border-radius: 50%; background: rgba(0,0,0,.25); filter: blur(3px); } .ma-die3d.rolling .ma-die-shadow { animation: ma-shadow ${ROLL_MS}ms ease-out both; } @keyframes ma-shadow { 0% { transform: scale(.4); opacity: .3; } 45% { transform: scale(1); opacity: 1; } 68% { transform: scale(.8); } 100% { transform: scale(1); } } .ma-die3d.dim { opacity: .55; } .ma-die3d.blank .ma-face { background: var(--surface); border-style: dashed; box-shadow: none; } .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-center .ma-opts.many { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); } .ma-center .ma-opts .btn { min-height: 46px; } .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; transition: transform .12s ease, border-color .12s ease; } button.ma-card:hover:not(:disabled) { border-color: var(--primary); transform: translateY(-3px); } .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); transform: translateY(-3px); } .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: 640px) { .ma-center { gap: 4px; padding: 4px; } .ma-title { display: none; } .ma-pill { font-size: .72rem; padding: 0 7px; } .ma-die3d { --ds: 50px; } .ma-dice-row { min-height: 58px; gap: 10px; } .ma-center .ma-panel.act { padding: 8px; gap: 6px; border-radius: 12px; } .ma-center .ma-panel.act h3 { font-size: .9rem; } .ma-center .ma-panel.act p { font-size: .78rem; } .ma-center .ma-opts { gap: 6px; } .ma-center .ma-opts .btn { min-height: 42px; font-size: .9rem; padding: 4px 6px; } .ma-now strong { font-size: .88rem; } .ma-now .small { font-size: .74rem; } .ma-podium span { font-size: .74rem; padding: 1px 6px 1px 2px; } .ma-podium i { width: 18px; height: 18px; font-size: .7rem; } .ma-ticker div { font-size: .72rem; padding: 2px 6px; } .ma-ticker div:not(:last-child) { display: none; } .ma-banner { font-size: 1.25rem; padding: 6px 14px; border-radius: 12px; } } @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); } } /* PC: fill the play column. The race board is as big as the column height allows and the log + racer list sit beside it when there is room (otherwise they wrap below as before). Without a board (draft) the panel fills the column. */ @media (min-width: 1100px) { .ma-wrap { max-width: none; flex-direction: row; flex-wrap: wrap; justify-content: center; align-items: flex-start; align-content: flex-start; } .ma-wrap > .ma-track { width: min(100%, calc((var(--play-h) - 86px) * ${(BW / WIDE.bh).toFixed(3)})); } .ma-box { max-width: 100%; } .ma-wrap > .ma-lower { flex: 1 1 340px; width: auto; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); } .ma-die3d { --ds: clamp(64px, calc(var(--play-h) * .07), 96px); } .ma-wrap:not(:has(> .ma-track)) { flex: 1 1 auto; min-height: 0; flex-direction: column; flex-wrap: nowrap; align-items: stretch; } .ma-wrap:not(:has(> .ma-track)) > .ma-panel { flex: 1 1 auto; min-height: 0; } /* Rows grow up to a third of the column but share the height when there are many cards (5 players: 10 in the draft). */ .ma-panel > .ma-cards { flex: 1 1 auto; min-height: 0; align-content: center; justify-content: center; gap: 14px; grid-template-columns: repeat(auto-fit, minmax(clamp(190px, calc(var(--play-w) * .19), 360px), clamp(190px, calc(var(--play-w) * .22), 360px))); grid-auto-rows: minmax(auto, clamp(104px, calc(var(--play-h) * .32), 380px)); } .ma-panel > .ma-cards .ma-card { padding: clamp(10px, calc(var(--play-h) * .02), 24px); gap: 10px; } .ma-panel > .ma-cards .ma-card .em { font-size: clamp(1.6rem, calc(var(--play-h) * .06), 4rem); } .ma-panel > .ma-cards .ma-card b { font-size: clamp(1.05rem, calc(var(--play-h) * .022), 1.6rem); } .ma-panel > .ma-cards .ma-card small { font-size: clamp(.875rem, calc(var(--play-h) * .016), 1.2rem); } } @media (prefers-reduced-motion: reduce) { .ma-tok { transition: none; } .ma-hop, .ma-fly, .ma-trip-anim, .ma-ring, .ma-trail, .ma-float, .ma-conf, .ma-ticker div, .ma-die3d.rolling .ma-cube, .ma-die3d.rolling .ma-die-shadow { animation: none; } } `; // ---------------------------------------------------------------- die // 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]], }; /** Cube turn that brings each face to the front (faces: 1 front, 6 back, 3 right, 4 left, 2 top, 5 bottom). */ const FACE_TURN: Record = { 1: [0, 0], 2: [-90, 0], 3: [0, -90], 4: [0, 90], 5: [90, 0], 6: [0, 180] }; function Die3D({ value, rolling, dim }: { value: number | null; rolling: boolean; dim: boolean }) { const [rx, ry] = FACE_TURN[value ?? 1]!; return ( {[1, 2, 3, 4, 5, 6].map((f) => ( {value !== null && ( {PIPS[f]!.map(([x, y], i) => ( ))} )} ))} ); } function useCompact(): boolean { const q = '(max-width: 640px)'; const [c, setC] = useState(() => typeof matchMedia !== 'undefined' && matchMedia(q).matches); useEffect(() => { if (typeof matchMedia === 'undefined') return; const m = matchMedia(q); const on = () => setC(m.matches); m.addEventListener('change', on); return () => m.removeEventListener('change', on); }, []); return c; } // ---------------------------------------------------------------- replay (the drawing walks behind the view) type Timer = ReturnType; interface Walking { racer: RacerId; path: number[]; i: number; k: number; jump: boolean; slide: boolean; } interface Drawing { q: Item[]; timer: Timer | null; dead: boolean; /** Race the drawing shows; 0 = nothing yet. */ race: number; /** Last log line queued. */ queued: number; /** Last log line shown (ticker). */ shown: number; /** Updates queued and not drawn yet (more than one → hurry). */ behind: number; pos: Map; /** Statuses as of the last update fully drawn. */ base: MaRacerView[]; trip: Map; podium: RacerId[]; turn: RacerId | null; die: { value: number; k: number; rolling: boolean; stale: boolean } | null; walk: Walking | null; k: number; } interface Float { k: number; x: number; y: number; text: string; cls: string; } const lastDie = (log: LogLine[]) => [...log].reverse().find((l) => l.die)?.die ?? null; function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) { const [, rerender] = useState(0); const bump = () => rerender((x) => x + 1); const [floats, setFloats] = useState([]); const [confetti, setConfetti] = useState(null); const [banner, setBanner] = useState<{ text: string; cls: string; k: number } | null>(null); const timers = useRef(new Set()); const live = useRef(v); live.current = v; const geo = useRef(g); geo.current = g; const d = useRef({ q: [], timer: null, dead: false, race: 0, queued: 0, shown: 0, behind: 0, pos: new Map(), base: [], trip: new Map(), podium: [], turn: null, die: null, walk: null, k: 0 }); const later = (fn: () => void, ms: number) => { const t = setTimeout(() => { timers.current.delete(t); fn(); }, fxMs(ms)); timers.current.add(t); }; useEffect(() => { const w = d.current; w.dead = false; return () => { w.dead = true; if (w.timer) clearTimeout(w.timer); w.timer = null; for (const t of timers.current) clearTimeout(t); timers.current.clear(); }; }, []); const float = (pos: number, text: string, cls: string) => { const w = d.current; const k = ++w.k; const [x, y] = cellCenter(geo.current, pos); setFloats((f) => [...f.slice(-5), { k, x, y: y - 44 * geo.current.k, text, cls }]); later(() => setFloats((f) => f.filter((z) => z.k !== k)), 1400); }; const showBanner = (text: string, cls: string) => { const k = ++d.current.k; setBanner({ text, cls, k }); later(() => setBanner((b) => (b && b.k === k ? null : b)), 1700); }; /** Everything drawn as the view says (first look, reduced motion, too far behind). */ const snap = () => { const w = d.current; const r = live.current.race; if (w.timer) clearTimeout(w.timer); w.timer = null; w.q = []; w.walk = null; w.behind = 0; w.trip.clear(); if (!r) return; const last = r.log.at(-1)?.n ?? 0; w.race = r.no; w.queued = w.shown = last; w.pos = new Map(r.racers.map((x) => [x.id, x.pos])); w.base = r.racers; w.podium = [...r.finishers]; w.turn = r.cur; const die = lastDie(r.log); w.die = die ? { value: die, k: ++w.k, rolling: false, stale: !r.roll?.value } : null; }; const posOf = (id: RacerId) => d.current.pos.get(id) ?? 0; /** Plays one item; returns how long until the next one (null: the item calls pump itself). */ const play = (it: Item): number | null => { const w = d.current; const fast = w.behind > 1; const T = (ms: number) => (fast ? Math.round(ms * 0.4) : ms); if (it.t === 'end') { w.base = it.racers; w.pos = new Map(it.racers.map((x) => [x.id, x.pos])); w.podium = [...it.finishers]; w.turn = it.cur; w.trip.clear(); w.shown = Math.max(w.shown, it.last); w.behind = Math.max(0, w.behind - 1); return 0; } w.shown = Math.max(w.shown, it.line.n); if (it.t === 'roll') { w.turn = it.line.racer ?? w.turn; const k = ++w.k; w.die = { value: it.value, k, rolling: true, stale: false }; sfx.dice(); const ms = T(ROLL_MS); later(() => { if (w.die?.k !== k) return; w.die = { ...w.die, rolling: false }; maSound.dieLand(); bump(); }, ms); return ms + T(180); } if (it.t === 'walk') { w.walk = { racer: it.racer, path: it.path, i: 0, k: ++w.k, jump: it.jump, slide: it.slide }; if (it.jump) maSound.fly(); else if (it.slide) maSound.arrow(it.path.at(-1)! > it.path[0]!); stepWalk(); return null; } const l = it.line; const id = l.racer; switch (l.kind) { case 'turn': w.turn = id ?? null; if (w.die) w.die = { ...w.die, stale: true }; return T(120); case 'power': maSound.power(); if (id && w.pos.has(id)) float(posOf(id), `✨ ${RACERS[id].name}`, 'power'); return T(l.die ? 300 : 650); case 'space': { if (!id) return T(300); const at = posOf(id); const e = live.current.spaces[live.current.race?.side ?? 'wild'].find((s) => s.pos === at)?.effect; if (e?.kind === 'star') { maSound.star(); float(at, '⭐ +1점', 'star'); } else if (e?.kind === 'rock') { maSound.trip(); w.trip.set(id, true); float(at, '🪨 꽈당!', 'trip'); } else if (e?.kind === 'arrow') float(at, e.by > 0 ? `⏩ +${e.by}` : `⏪ ${e.by}`, e.by > 0 ? 'up' : 'back'); return T(450); } case 'finish': { maSound.finish(); if (id) { const place = it.place && it.place > 0 ? it.place : w.podium.length + 1; if (!w.podium.includes(id)) w.podium = [...w.podium, id]; showBanner(`${place === 1 ? '🥇' : '🥈'} ${RACERS[id].emoji} ${RACERS[id].name} ${place}등!`, place === 1 ? 'gold' : 'silver'); setConfetti(++w.k); } return T(1100); } case 'info': if (id && l.text.includes('일어나기만')) { w.trip.set(id, false); float(posOf(id), '🙃 일어나요', 'info'); return T(450); } if (id === 'rocket' && l.text.includes('넘어졌')) { w.trip.set(id, true); maSound.trip(); float(posOf(id), '💫 꽈당!', 'trip'); return T(450); } return T(250); default: return T(250); } }; const stepMs = (c: Walking) => { const fast = d.current.behind > 1; const ms = c.jump ? 440 : c.slide ? 90 : 170; return fast ? Math.round(ms * 0.45) : ms; }; const stepWalk = () => { const w = d.current; w.timer = null; const c = w.walk; if (!c || w.dead) return; const i = c.i + 1; const to = c.path[i]!; w.walk = { ...c, i }; w.pos.set(c.racer, to); const last = i >= c.path.length - 1; if (!c.jump && !c.slide) { if (last) maSound.land(); else maSound.step(i); } bump(); const ms = stepMs(c); w.timer = setTimeout( last ? () => { w.timer = null; w.walk = null; bump(); pump(); } : stepWalk, fxMs(last ? ms + (c.jump ? 60 : 120) : ms), ); }; const pump = () => { const w = d.current; while (!w.dead && !w.timer) { const it = w.q.shift(); if (!it) { bump(); return; } const wait = play(it); if (wait === null) return; if (wait > 0) { bump(); w.timer = setTimeout(() => { w.timer = null; pump(); }, fxMs(wait)); return; } } }; // New log lines → queue. A page load / reconnect only records the race as it is. const r = v.race; const lastN = r?.log.at(-1)?.n ?? 0; useLayoutEffect(() => { const w = d.current; if (!r) return; if ((w.race === 0 && !liveStart) || reducedMotion()) { const fresh = w.race === r.no ? r.log.filter((l) => l.n > w.queued) : []; snap(); if (fresh.length) soundOnce(fresh); bump(); return; } let lines: LogLine[]; if (r.no !== w.race) { // A new race seen live: everybody back to the start line, then replay its lines. if (w.timer) clearTimeout(w.timer); w.timer = null; w.q = []; w.walk = null; w.race = r.no; w.behind = 0; w.pos = new Map(r.racers.map((x) => [x.id, 0])); w.base = r.racers.map((x) => ({ ...x, pos: 0, status: 'run', tripped: false, place: null })); w.podium = []; w.trip.clear(); w.die = null; w.turn = null; w.shown = 0; lines = r.log; showBanner(`🏁 ${r.no}번째 경주 출발!`, ''); } else { lines = r.log.filter((l) => l.n > w.queued); if (!lines.length) return; } w.queued = lastN; w.q.push(...itemsOf(lines, r.finishers), { t: 'end', racers: r.racers, finishers: r.finishers, cur: r.cur, last: lastN }); w.behind++; if (w.behind > 3) { // Far behind (a burst of computer moves): jump to now. snap(); bump(); return; } pump(); }, [r?.no, lastN]); // eslint-disable-line react-hooks/exhaustive-deps // The drawing replays the race step by step with timers: results (scores, the next race, 결과) wait for it. const w = d.current; useMotionHold(!!w.timer || w.q.length > 0 || !!w.walk || !!w.die?.rolling); return { d: d.current, floats, confetti, banner }; } /** Reduced motion: one sound per update (no walking). */ function soundOnce(added: LogLine[]) { const sp = added.filter((l) => l.kind === 'space'); if (added.some((l) => l.kind === 'finish')) maSound.finish(); else if (added.some((l) => l.kind === 'power')) maSound.power(); else if (sp.some((l) => l.text.includes('별'))) maSound.star(); else if (sp.some((l) => l.text.includes('돌'))) maSound.trip(); else if (sp.length) maSound.arrow(sp.some((l) => l.text.includes('앞 화살표'))); else if (added.some((l) => l.kind === 'move')) maSound.land(); } // ---------------------------------------------------------------- track function fxLabel(e: SpaceEffect): string { if (e.kind === 'arrow') return e.by > 0 ? `앞으로 ${e.by}칸` : `뒤로 ${-e.by}칸`; return e.kind === 'rock' ? '돌(넘어짐)' : '별(1점)'; } function cellFill(e: SpaceEffect | undefined): string { if (!e) return 'var(--surface)'; const c = e.kind === 'star' ? '#facc15' : e.kind === 'rock' ? '#78716c' : e.by > 0 ? '#22c55e' : '#ef4444'; return `color-mix(in srgb, ${c} ${e.kind === 'rock' ? 26 : 30}%, var(--surface))`; } function SpaceMark({ g, pos, e }: { g: Geo; pos: number; e: SpaceEffect }) { const c = cellOf(g, pos); const k = g.k; const [x, y] = local(c, span(g, c) - 34 * k, 30 * k); if (e.kind === 'arrow') return ( 0 ? '#16a34a' : '#dc2626'} /> {e.by > 0 ? `+${e.by}` : `−${-e.by}`} ); return ( {e.kind === 'rock' ? '🪨' : '⭐'} ); } function RaceBoard({ v, me, players, act, pending, compact, liveStart, }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; compact: boolean; /** The race showed up while the board was open: draw the first race from the start line too. */ liveStart: boolean; }) { const r = v.race!; const g = compact ? TALL : WIDE; const draw = useRaceDrawing(v, liveStart, g); const w = draw.d; const panel = ; const fx = new Map(v.spaces[r.side].map((s) => [s.pos, s.effect])); const walk = w.walk; const trail = walk && !walk.jump ? new Set(walk.path.slice(1, walk.i + 1).map((p) => p % RING)) : null; // Tokens on the track, as the drawing has them. const base = new Map(w.base.map((x) => [x.id, x])); const onTrack = r.racers .map((x) => base.get(x.id) ?? x) .filter((x) => x.status === 'run' && !w.podium.includes(x.id)) .map((x) => ({ x, at: (w.pos.get(x.id) ?? x.pos) % RING })); const groups = new Map(); for (const t of onTrack) groups.set(t.at, [...(groups.get(t.at) ?? []), t.x.id]); const turn = w.turn; const label = `${r.no}번째 경주 ${r.side === 'wild' ? '거친 판' : '순한 판'}. 출발은 오른쪽 아래, 시계 방향으로 한 바퀴(30칸)를 돌면 결승이에요. ${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: RING }, (_, i) => { const c = cellOf(g, i); const e = i === 0 ? undefined : fx.get(i); const [nx, ny] = local(c, 20 * g.k, 30 * g.k); let band: React.ReactNode = null; if (!c.corner) { const [bx, by] = local(c, 0, g.corner - BAND_W); const [ex, ey] = local(c, g.sw, g.corner); band = ; } return ( {band} {i === 0 ? ( <> 출발·결승 ) : ( {i} )} {e && } {e && {`${i}칸: ${fxLabel(e)}`}} {trail?.has(i) && } ); })} {/* direction arrows in the corners */} {g.corners.slice(1).map((p, k) => { const [x, y] = cellCenter(g, p); return ( {['⬆', '➡', '⬇'][k]} ); })} {onTrack.map(({ x, at }) => { const grp = groups.get(at)!; const n = grp.length; const [tx, ty] = spot(g, at, grp.indexOf(x.id), n); const rad = tokR(g, n); const moving = walk && walk.racer === x.id && walk.i > 0 ? walk : null; const dur = moving ? (moving.jump ? 440 : moving.slide ? 90 : 170) * (w.behind > 1 ? 0.45 : 1) : 260; const tripped = w.trip.get(x.id) ?? x.tripped; const color = seatColor(v, x.owner); const isTurn = turn === x.id && v.phase === 'race'; return ( {`${RACERS[x.id].name} (${who(players, me, x.owner)}) ${x.pos === 0 ? '출발점' : `${w.pos.get(x.id) ?? x.pos}칸`}${tripped ? ' · 넘어짐' : ''}`} {isTurn && } {RACERS[x.id].emoji} {tripped && ( 💫 )} ); })} {draw.floats.map((f) => ( {f.text} ))} {draw.confetti !== null && ( {Array.from({ length: 18 }, (_, i) => { const [cx, cy] = cellCenter(g, 0); const a = (i / 18) * Math.PI * 2; const dist = 90 + (i % 3) * 40; return ( ); })} )}
{draw.banner && (
{draw.banner.text}
)}
{r.side === 'wild' && (
⭐ 별: 멈추면 1점 🪨 돌: 멈추면 넘어짐 +3 초록: 앞으로 −3 빨강: 뒤로
)}
); } const ICON: Record = { turn: '▶', roll: '🎲', move: '👟', power: '✨', space: '🧭', finish: '🏁', info: 'ℹ️' }; /** Centre of the ring: race, die, who is moving, podium, (PC) what to do, latest lines. */ function Center({ v, me, players, draw, panel }: { v: MagicalAthleteView; me: string | null; players: Record; draw: ReturnType; panel: React.ReactNode }) { const r = v.race!; const w = draw.d; const m = v.medals[r.no - 1]!; const turn = w.turn ? r.racers.find((x) => x.id === w.turn) : undefined; const lines = r.log.filter((l) => l.n <= w.shown && l.kind !== 'turn').slice(-2); const owner = (id: RacerId) => r.racers.find((x) => x.id === id)?.owner ?? ''; return ( <>
🏃 야단법석 달리기
{r.no} / {v.races} 경주 {r.side === 'wild' ? '거친 판' : '순한 판'} 🥇{m.gold}점 · 🥈{m.silver}점
{turn ? ( <> {rname(turn.id)}
{who(players, me, turn.owner)} {w.die && !w.die.stale && !w.die.rolling ? ` · 🎲 ${w.die.value}` : ''}
) : v.phase !== 'race' ? ( 경주 끝 ) : v.prompt && r.log.some((l) => l.kind === 'turn') ? ( <> {v.prompt.owner === me ? '내 차례' : `${nick(players, v.prompt.owner)}님 차례`}
{v.prompt.step === 'go' ? '먼저 갈 선수 고르기' : '차례 시작'}
) : ( 출발 준비! )}
{w.podium.length > 0 && (
{w.podium.map((id, i) => ( {i + 1} {rname(id)} ))}
)} {panel} {lines.length > 0 && (
{lines.map((l) => (
{ICON[l.kind]} {l.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 }) { // A new choice (it can tell the roll: "다시 굴릴까요?", "4칸 가기") shows once the die and the runners have stopped; // until then the previous one stays, greyed out. const key = v.prompt ? `${v.prompt.owner}|${v.prompt.step}|${v.prompt.racer ?? ''}|${v.prompt.options.map((o) => o.key).join(',')}` : ''; const settling = useAfterMotionValue(key) !== key; const kept = useRef(v.prompt); if (!settling) kept.current = v.prompt; const pr = kept.current; if (v.phase !== 'race') return null; const mine = !!pr && pr.owner === me; return (
{pr ? ( mine ? ( <>

내 차례 · {pr.racer ? `${rname(pr.racer)} · ` : ''} {STEP_TITLE[pr.step]}

2 ? ' many' : ''}`} role="group" aria-label={STEP_TITLE[pr.step]}> {pr.options.map((o, i) => ( ))}
{v.options.turnSeconds !== null && (

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

)} ) : (

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

) ) : (

경주가 끝났어요.

)}
); } function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { // Positions, falls and places as of the last still screen (the board replays the race behind the view). const r = JSON.parse(useAfterMotionValue(JSON.stringify({ cur: v.race!.cur, racers: v.race!.racers }))) as { cur: RacerId | null; racers: MaRacerView[] }; 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}
  • ))}
); } 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 }) { // A race's result row shows once its finish has been drawn. const results = v.results.slice(0, useAfterMotionValue(v.results.length)); if (!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 (

경주 결과

{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}점
); } // ---------------------------------------------------------------- board function Board({ view: v, me, players, act, pending }: BoardProps) { const compact = useCompact(); const [announce, setAnnounce] = useState(''); /** A race already on screen when the board opened (reload, watching) is shown as it is, not replayed. */ const raceAtOpen = useRef(!!v.race); const prevLog = useRef(v.race?.log.at(-1)?.n ?? 0); const prevRace = useRef(v.race?.no ?? 0); const prevTurn = useRef(v.turnSeq); // The race log lists new lines once the board has drawn them. const [logRace, logN] = useAfterMotionValue(`${v.race?.no ?? 0}:${v.race?.log.at(-1)?.n ?? 0}`).split(':').map(Number); const logShown = { race: logRace!, n: logN! }; // New log lines → screen-reader announcement (the board draws and sounds them). 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'); prevLog.current = last; if (added.length) setAnnounce(added.slice(-4).map((l) => l.text).join(' ')); if (added.some((l) => l.kind === 'power')) haptic(30); }, [v.race?.log.at(-1)?.n, v.race?.no]); // eslint-disable-line react-hooks/exhaustive-deps // Draft picks, race selections and a new race, whoever made them. const drafted = Object.values(v.teams).flat().length; const pickedN = Object.values(v.picked).filter(Boolean).length; const prevPhase = useRef({ phase: v.phase, drafted, picked: pickedN, race: v.raceNo }); useEffect(() => { const p = prevPhase.current; prevPhase.current = { phase: v.phase, drafted, picked: pickedN, race: v.raceNo }; if (v.phase === 'race' && (p.phase !== 'race' || p.race !== v.raceNo)) return sfx.whoosh(); if (v.phase === 'draft' && drafted > p.drafted) return sfx.cardDeal(); if (v.phase === 'select' && pickedN > p.picked) sfx.chip(); }, [v.phase, drafted, pickedN, v.raceNo]); 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; // A race's end (the next race's selection, the final table, the header) shows once the board has finished // replaying it; until then the screen stays on the race. const stage = `${v.phase}:${v.raceNo}`; const shownStage = useAfterMotionValue(stage); const ready = shownStage === stage; const [phase, raceNo] = ready ? [v.phase, v.raceNo] : [shownStage.slice(0, shownStage.indexOf(':')), Number(shownStage.slice(shownStage.indexOf(':') + 1))]; const medal = v.medals[Math.min(raceNo, v.races) - 1] ?? v.medals[0]!; return (
{phase === 'finished' ? '게임 끝' : phase === 'draft' ? '선수 뽑기' : `${raceNo} / ${v.races} 경주`} {r && phase === 'race' && {r.side === 'wild' ? '거친 판' : '순한 판'}} {v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {medal.gold}점 · 2등 {medal.silver}점
{v.result && ready && } {v.phase === 'draft' && v.draft && } {v.phase === 'select' && ready &&