Files
joke-app/apps/web/src/games/magical-athlete/index.tsx
EJClaw 4e0eb4d52c 모든 게임: 결과·팝업은 애니메이션이 끝난 뒤에, 증강 윷놀이: 이의있음!이 다음 판에도 뜨게, 증강 고르는 목록·나오게 할 증강을 팝업 목록으로
- lib/motion: motionBusy / useMotionHold / useMotionSettled / useAfterMotionValue / AfterMotion
- 방 화면: 결과 창과 상태 줄은 판이 멈춘 뒤에(실시간 게임은 상태 줄 그대로), 새 판마다 판 화면을 새로 그림
  (결과 창에 둔 채 다음 판이 시작되면 이전 판의 효과 번호가 남아 이의있음!·알림이 안 뜨던 문제)
- 41개 게임: 결과 패널·배너·점수·팝업이 마지막 움직임 뒤에 나오도록 게임별로 정리
- 증강 윷놀이: 명탐정·배달·손버릇·따라쟁이·착각 대상은 아이콘과 설명이 다 보이는 목록에서,
  방 설정의 나오게 할 증강은 팝업 목록에서 스위치로 켜고 끔
- e2e: 늦게 바뀌는 상태 줄·결과 창과 새 증강 화면에 맞춤

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:22 +09:00

1588 lines
72 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 야단법석 달리기 화면 (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<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
const userOf = (players: Record<string, PublicUser>, 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<string, PublicUser>, 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<number, [number, number][]> = {
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<number, [number, number]> = { 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 (
<span className={`ma-die3d${rolling ? ' rolling' : ''}${dim && !rolling ? ' dim' : ''}${value === null ? ' blank' : ''}`} style={{ '--rx': `${rx}deg`, '--ry': `${ry}deg` } as React.CSSProperties} aria-hidden>
<span className="ma-die-shadow" />
<span className="ma-cube">
{[1, 2, 3, 4, 5, 6].map((f) => (
<span key={f} className={`ma-face f${f}`}>
{value !== null && (
<svg viewBox="0 0 100 100">
{PIPS[f]!.map(([x, y], i) => (
<circle key={i} cx={x} cy={y} r={f === 1 ? 14 : 10} fill={f === 1 ? '#c81e1e' : '#1f2937'} />
))}
</svg>
)}
</span>
))}
</span>
</span>
);
}
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<typeof setTimeout>;
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<RacerId, number>;
/** Statuses as of the last update fully drawn. */
base: MaRacerView[];
trip: Map<RacerId, boolean>;
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<Float[]>([]);
const [confetti, setConfetti] = useState<number | null>(null);
const [banner, setBanner] = useState<{ text: string; cls: string; k: number } | null>(null);
const timers = useRef(new Set<Timer>());
const live = useRef(v);
live.current = v;
const geo = useRef(g);
geo.current = g;
const d = useRef<Drawing>({ 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 (
<g aria-hidden>
<rect x={x - 25 * k} y={y - 16 * k} width={50 * k} height={32 * k} rx={16 * k} fill={e.by > 0 ? '#16a34a' : '#dc2626'} />
<text x={x} y={y + 8 * k} textAnchor="middle" fontSize={22 * k} fontWeight={900} fill="#fff">
{e.by > 0 ? `+${e.by}` : `−${-e.by}`}
</text>
</g>
);
return (
<text x={x} y={y + 12 * k} textAnchor="middle" fontSize={34 * k} aria-hidden>
{e.kind === 'rock' ? '🪨' : '⭐'}
</text>
);
}
function RaceBoard({
v,
me,
players,
act,
pending,
compact,
liveStart,
}: {
v: MagicalAthleteView;
me: string | null;
players: Record<string, PublicUser>;
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 = <RacePanel v={v} me={me} players={players} act={act} pending={pending} rolling={!!w.die?.rolling} />;
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<number, RacerId[]>();
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 (
<>
<section className="card ma-track" aria-label="경주로">
<div className={`ma-box${compact ? ' tall' : ''}`}>
<svg className="ma-svg" viewBox={`0 0 ${BW} ${g.bh}`} role="img" aria-label={label}>
<defs>
<pattern id="ma-check" width="24" height="24" patternUnits="userSpaceOnUse">
<rect width="24" height="24" fill="#fff" />
<rect width="12" height="12" fill="#1f2937" />
<rect x="12" y="12" width="12" height="12" fill="#1f2937" />
</pattern>
</defs>
<rect x={0} y={0} width={BW} height={g.bh} rx={18} fill="var(--surface-2)" />
{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 = <rect x={Math.min(bx, ex)} y={Math.min(by, ey)} width={Math.abs(ex - bx)} height={Math.abs(ey - by)} fill={BANDS[c.side]} />;
}
return (
<g key={i}>
<rect className="ma-cell" x={c.x} y={c.y} width={c.w} height={c.h} style={{ fill: i === 0 ? 'var(--primary-soft)' : cellFill(e) }} />
{band}
{i === 0 ? (
<>
<rect x={c.x + 6} y={c.y + 6} width={c.w - 12} height={18} fill="url(#ma-check)" opacity={0.85} />
<text x={c.x + c.w / 2} y={c.y + c.h - 14} textAnchor="middle" fontSize={Math.min(24 * g.k, 27)} fontWeight={900} fill="var(--text)">
출발·결승
</text>
</>
) : (
<text className="ma-num" x={nx} y={ny + 7 * g.k} textAnchor="middle" fontSize={20 * g.k}>
{i}
</text>
)}
{e && <SpaceMark g={g} pos={i} e={e} />}
{e && <title>{`${i}칸: ${fxLabel(e)}`}</title>}
{trail?.has(i) && <rect key={`t${walk!.k}`} className="ma-trail" x={c.x} y={c.y} width={c.w} height={c.h} fill="var(--focus)" opacity={0} />}
</g>
);
})}
{/* direction arrows in the corners */}
{g.corners.slice(1).map((p, k) => {
const [x, y] = cellCenter(g, p);
return (
<text key={p} x={x} y={y + 12 * g.k} textAnchor="middle" fontSize={34 * g.k} fill="var(--text-sub)" opacity={0.35} aria-hidden>
{['⬆', '➡', '⬇'][k]}
</text>
);
})}
{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 (
<g key={x.id} className="ma-tok" style={{ transform: `translate(${tx}px, ${ty}px)`, transitionDuration: `${Math.round(dur)}ms`, transitionTimingFunction: moving?.jump ? 'ease-in-out' : 'linear' }}>
<title>{`${RACERS[x.id].name} (${who(players, me, x.owner)}) ${x.pos === 0 ? '출발점' : `${w.pos.get(x.id) ?? x.pos}칸`}${tripped ? ' · 넘어짐' : ''}`}</title>
{isTurn && <circle className="ma-ring" r={rad + 9} fill="none" stroke={color} strokeWidth={5} />}
<ellipse cx={0} cy={rad * 0.92} rx={rad * 0.85} ry={rad * 0.28} fill="#000" opacity={0.22} />
<g
key={moving ? `${moving.k}-${moving.i}` : tripped ? 'trip' : 'still'}
className={`ma-body${moving ? (moving.jump ? ' ma-fly' : moving.slide ? '' : ' ma-hop') : tripped ? ' ma-trip-anim' : ''}`}
style={{ '--ma-dur': `${Math.round(dur)}ms` } as React.CSSProperties}
>
<g opacity={tripped ? 0.6 : 1}>
<circle r={rad} fill={color} stroke="#fff" strokeWidth={3} />
<circle r={rad * 0.74} fill="#fffdf8" />
</g>
<text textAnchor="middle" dy={rad * 0.34} fontSize={rad * 0.95} transform={tripped ? 'rotate(90)' : undefined}>
{RACERS[x.id].emoji}
</text>
{tripped && (
<text x={rad * 0.7} y={-rad * 0.6} fontSize={rad * 0.75} textAnchor="middle">
💫
</text>
)}
</g>
</g>
);
})}
{draw.floats.map((f) => (
<text key={f.k} className={`ma-float ${f.cls}`} x={f.x} y={f.y} textAnchor="middle" aria-hidden>
{f.text}
</text>
))}
{draw.confetti !== null && (
<g key={draw.confetti} aria-hidden>
{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 (
<rect
key={i}
className="ma-conf"
x={cx - 5}
y={cy - 8}
width={10}
height={16}
rx={2}
fill={COLORS[i % COLORS.length]}
style={{ '--dx': `${Math.round(Math.cos(a) * dist)}px`, '--dy': `${Math.round(Math.sin(a) * dist - 40)}px`, '--rot': `${(i % 2 ? 1 : -1) * (180 + i * 20)}deg` } as React.CSSProperties}
/>
);
})}
</g>
)}
</svg>
<div
className="ma-center"
style={{
left: `${(g.corner / BW) * 100}%`,
top: `${(g.corner / g.bh) * 100}%`,
width: `${((BW - 2 * g.corner) / BW) * 100}%`,
height: `${((g.bh - 2 * g.corner) / g.bh) * 100}%`,
}}
>
<Center v={v} me={me} players={players} draw={draw} panel={panel} />
</div>
{draw.banner && (
<div className="ma-banner-wrap" aria-hidden>
<div key={draw.banner.k} className={`ma-banner anim-banner ${draw.banner.cls}`}>
{draw.banner.text}
</div>
</div>
)}
</div>
{r.side === 'wild' && (
<div className="ma-key" aria-hidden>
<span>⭐ 별: 멈추면 1점</span>
<span>🪨 돌: 멈추면 넘어짐</span>
<span>+3 초록: 앞으로</span>
<span>−3 빨강: 뒤로</span>
</div>
)}
</section>
</>
);
}
const ICON: Record<LogLine['kind'], string> = { 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<string, PublicUser>; draw: ReturnType<typeof useRaceDrawing>; 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 (
<>
<div className="ma-title" aria-hidden>
🏃 야단법석 달리기
</div>
<div className="ma-meta">
<span className="ma-pill">
{r.no} / {v.races} 경주
</span>
<span className={`ma-pill ma-side-tag ${r.side}`}>{r.side === 'wild' ? '거친 판' : '순한 판'}</span>
<span className="ma-pill">
🥇{m.gold}점 · 🥈{m.silver}점
</span>
</div>
<div className="ma-dice-row">
<Die3D value={w.die?.value ?? null} rolling={!!w.die?.rolling} dim={!!w.die?.stale} />
<div className="ma-now">
{turn ? (
<>
<strong>{rname(turn.id)}</strong>
<div className="small">
<span className="ma-dot" style={{ background: seatColor(v, turn.owner), width: 10, height: 10, marginTop: 0, marginRight: 4, verticalAlign: '-1px' }} aria-hidden />
{who(players, me, turn.owner)}
{w.die && !w.die.stale && !w.die.rolling ? ` · 🎲 ${w.die.value}` : ''}
</div>
</>
) : v.phase !== 'race' ? (
<strong>경주 끝</strong>
) : v.prompt && r.log.some((l) => l.kind === 'turn') ? (
<>
<strong>{v.prompt.owner === me ? '내 차례' : `${nick(players, v.prompt.owner)}님 차례`}</strong>
<div className="small">{v.prompt.step === 'go' ? '먼저 갈 선수 고르기' : '차례 시작'}</div>
</>
) : (
<strong>출발 준비!</strong>
)}
</div>
</div>
{w.podium.length > 0 && (
<div className="ma-podium" aria-label="도착한 선수">
{w.podium.map((id, i) => (
<span key={id} className="anim-pop" style={{ borderColor: seatColor(v, owner(id)) }}>
<i style={{ background: i === 0 ? '#d97706' : '#64748b' }}>{i + 1}</i>
{rname(id)}
</span>
))}
</div>
)}
{panel}
{lines.length > 0 && (
<div className="ma-ticker" aria-hidden>
{lines.map((l) => (
<div key={l.n} className={l.kind}>
{ICON[l.kind]} {l.text}
</div>
))}
</div>
)}
</>
);
}
// ---------------------------------------------------------------- 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<MaPrompt['step'], string> = {
go: '어느 선수가 먼저 갈까요?',
start: '차례 시작: 능력을 쓸까요?',
roll: '주사위를 굴려요',
reroll: '다시 굴릴까요?',
boost: '능력을 쓸까요?',
};
function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser>; 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 (
<section className={`card ma-panel act${mine ? ' mine' : ''}`} aria-label="내 차례 할 일">
{pr ? (
mine ? (
<>
<h3>
내 차례 · {pr.racer ? `${rname(pr.racer)} · ` : ''}
{STEP_TITLE[pr.step]}
</h3>
<div className={`ma-opts${pr.options.length > 2 ? ' many' : ''}`} role="group" aria-label={STEP_TITLE[pr.step]}>
{pr.options.map((o, i) => (
<button key={o.key} type="button" className={`btn ${i === 0 ? 'btn-primary' : 'btn-secondary'} btn-block`} disabled={pending || rolling || settling} onClick={() => act(actionFor(pr, o.key))}>
{pr.step === 'roll' && o.key === 'roll' ? `🎲 ${o.label}` : o.label}
</button>
))}
</div>
{v.options.turnSeconds !== null && (
<p className="small muted" style={{ margin: 0 }}>
시간이 지나면 {pr.timeoutText}.
</p>
)}
</>
) : (
<p className="muted small" style={{ margin: 0 }}>
{nick(players, pr.owner)}님이 {pr.step === 'roll' ? '주사위를 굴릴 차례예요' : pr.step === 'go' ? '먼저 갈 선수를 고르는 중이에요' : '능력을 쓸지 고르는 중이에요'}.
</p>
)
) : (
<p className="muted" style={{ margin: 0 }}>
경주가 끝났어요.
</p>
)}
</section>
);
}
function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
// 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 (
<section className="card ma-panel" aria-label="이번 경주 선수">
<h3>이번 경주 선수</h3>
<ul className="ma-legend">
{r.racers.map((x) => (
<li key={x.id} className={`${r.cur === x.id ? 'cur' : ''}${x.status !== 'run' ? ' gone' : ''}`}>
<span className="ma-dot" style={{ background: seatColor(v, x.owner) }} aria-hidden />
<div style={{ minWidth: 0 }}>
<div>
<strong>{rname(x.id)}</strong> <span className="small muted">· {who(players, me, x.owner)}</span>
</div>
<div className="small">
{x.status === 'done' ? `🏁 ${x.place}등 도착` : x.status === 'out' ? '탈락' : `${x.pos === 0 ? '출발점' : `${x.pos}칸`}${x.tripped ? ' · 넘어짐(다음 차례 쉼)' : ''}`}
</div>
<div className="small muted">{RACERS[x.id].text}</div>
</div>
</li>
))}
</ul>
</section>
);
}
function Draft({ v, me, players, act, pending }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
const d = v.draft!;
const mine = d.picker === me;
return (
<section className="card ma-panel" aria-label="선수 뽑기">
<h3>
선수 뽑기 {d.round}/{d.rounds}바퀴 · {mine ? '내가 고를 차례예요' : `${nick(players, d.picker)}님이 고르는 중`}
</h3>
<p className="small muted" style={{ margin: 0 }}>
순서: {[d.picker, ...d.next].map((p) => who(players, me, p)).join(' → ')} (남은 선수 더미 {v.deckCount}명)
</p>
<div className="ma-cards" role="group" aria-label="펼쳐진 선수">
{d.line.map((id) => (
<button key={id} type="button" className="ma-card anim-deal" disabled={!mine || pending} aria-label={`${RACERS[id].name}: ${RACERS[id].text}${mine ? ' 누르면 뽑아요' : ''}`} onClick={() => act({ type: 'DRAFT', racer: id })}>
<span className="em" aria-hidden>
{RACERS[id].emoji}
</span>
<b>{RACERS[id].name}</b>
<small>{RACERS[id].text}</small>
</button>
))}
</div>
</section>
);
}
function Select({ v, me, players, act, pending }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
const [sel, setSel] = useState<RacerId[]>([]);
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 (
<section className="card ma-panel" aria-label="출전 선수 고르기">
<h3>
{v.raceNo}번째 경주({side}, 1등 {m.gold}점 · 2등 {m.silver}점)에 내보낼 선수 {v.perRace}명
</h3>
<p className="small muted" style={{ margin: 0 }}>
다른 사람에게는 고른 선수가 경주가 시작될 때까지 보이지 않아요. 고른 사람: {v.seats.filter((p) => v.picked[p]).map((p) => who(players, me, p)).join(', ') || '아직 없음'}
</p>
{seated && !done && (
<>
<div className="ma-cards" role="group" aria-label="내 선수">
{team.map((id) => {
const u = used.includes(id);
return (
<button key={id} type="button" className={`ma-card${u ? ' used' : ''}`} disabled={u || pending} aria-pressed={sel.includes(id)} aria-label={`${RACERS[id].name}${u ? '(이미 달렸어요)' : ''}: ${RACERS[id].text}`} onClick={() => toggle(id)}>
<span className="em" aria-hidden>
{RACERS[id].emoji}
</span>
<b>{RACERS[id].name}</b>
<small>{u ? '이미 달렸어요' : RACERS[id].text}</small>
</button>
);
})}
</div>
<button className="btn btn-primary btn-block" disabled={pending || sel.length !== v.perRace} onClick={() => act({ type: 'SELECT', racers: sel })}>
{sel.length === v.perRace ? `${sel.map(rname).join(', ')} 내보내기` : `선수 ${v.perRace}명을 골라 주세요`}
</button>
</>
)}
{done && <p style={{ margin: 0 }}>내가 고른 선수: {done.racers.map(rname).join(', ')}. 다른 사람을 기다려요.</p>}
</section>
);
}
function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
// 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 (
<>
<span className="ma-dot" style={{ background: seatColor(v, o), marginRight: 4, verticalAlign: '-2px' }} aria-hidden />
{rname(id)} <span className="muted small">({who(players, me, o)})</span>
</>
);
};
return (
<section className="card ma-panel" aria-label="경주 결과">
<h3>경주 결과</h3>
<table className="ma-table">
<thead>
<tr>
<th scope="col">경주</th>
<th scope="col">🥇 1등</th>
<th scope="col">🥈 2등</th>
</tr>
</thead>
<tbody>
{results.map((rr) => (
<tr key={rr.no}>
<td>
{rr.no}
{rr.capped && <div className="small muted">시간 다 됨</div>}
</td>
<td className="l">{cell(rr.gold, rr)}</td>
<td className="l">{cell(rr.silver, rr)}</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
function FinalTable({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
const r = v.result!;
return (
<section className="card ma-panel" aria-label="최종 결과">
<h3>최종 결과</h3>
<table className="ma-table">
<thead>
<tr>
<th scope="col">순위</th>
<th scope="col">이름</th>
<th scope="col">🥇</th>
<th scope="col">🥈</th>
<th scope="col">⭐ 보너스</th>
<th scope="col">합계</th>
</tr>
</thead>
<tbody>
{r.ranking.map((row) => (
<tr key={row.player}>
<td>{row.rank}등</td>
<td className="l">
<span className="ma-dot" style={{ background: seatColor(v, row.player), marginRight: 4, verticalAlign: '-2px' }} aria-hidden />
{who(players, me, row.player)}
{row.left && <span className="muted small"> (나감)</span>}
</td>
<td>{row.gold}</td>
<td>{row.silver}</td>
<td>{row.bonus}</td>
<td>
<strong>{row.total}점</strong>
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
// ---------------------------------------------------------------- board
function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthleteView>) {
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<number>(v.race?.log.at(-1)?.n ?? 0);
const prevRace = useRef<number>(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 (
<div className="ma-wrap">
<style>{CSS}</style>
<div className="card ma-head">
<strong>{phase === 'finished' ? '게임 끝' : phase === 'draft' ? '선수 뽑기' : `${raceNo} / ${v.races} 경주`}</strong>
{r && phase === 'race' && <span className={`ma-side-tag ${r.side}`}>{r.side === 'wild' ? '거친 판' : '순한 판'}</span>}
<span className="small muted">
{v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {medal.gold}점 · 2등 {medal.silver}점
</span>
</div>
{v.result && ready && <FinalTable v={v} me={me} players={players} />}
{v.phase === 'draft' && v.draft && <Draft v={v} me={me} players={players} act={act} pending={pending} />}
{v.phase === 'select' && ready && <Select v={v} me={me} players={players} act={act} pending={pending} />}
{r && (
<>
{v.phase !== 'race' && ready && (
<p className="small muted" style={{ margin: 0 }}>
{r.no}번째 경주가 끝났을 때 모습이에요.
</p>
)}
<RaceBoard v={v} me={me} players={players} act={act} pending={pending} compact={compact} liveStart={!raceAtOpen.current} />
<div className="ma-lower">
<section className="card ma-panel" aria-label="경주 기록">
<h3>경주 기록</h3>
<ul className="ma-log" tabIndex={0} aria-label="경주 기록 (최신이 위)">
{[...r.log.filter((l) => logShown.race === r.no && l.n <= logShown.n)].reverse().map((l) => (
<li key={l.n} className={l.kind}>
{ICON[l.kind]} {l.text}
</li>
))}
</ul>
</section>
<Legend v={v} me={me} players={players} />
</div>
</>
)}
<Results v={v} me={me} players={players} />
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
// ---------------------------------------------------------------- side panel
function Side({ view: v, me, players, act, deadline, active }: BoardProps<MagicalAthleteView>) {
const [ask, setAsk] = useState(false);
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
const playing = v.phase !== 'finished';
// Points change once the finish / star that gave them has been drawn.
const scoreKey = v.seats.map((p) => [v.scores[p]!.gold, v.scores[p]!.silver, v.scores[p]!.bonus, v.scores[p]!.total].join(',')).join('|');
const shownScores = useAfterMotionValue(scoreKey).split('|');
return (
<>
<section className="card stack" style={{ padding: 12, gap: 8 }} aria-label="참가자">
{v.seats.map((p, i) => {
const [gold, silver, bonus, tot] = (shownScores[i] ?? '').split(',').map(Number);
const sc = shownScores.length === v.seats.length ? { gold: gold!, silver: silver!, bonus: bonus!, total: tot! } : v.scores[p]!;
const on = active.includes(p);
return (
<div key={p} style={{ padding: '4px 6px', borderRadius: 10, border: `3px solid ${on ? 'var(--focus)' : 'transparent'}` }}>
<div className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
<span className="ma-dot" style={{ background: seatColor(v, p) }} aria-hidden />
<Avatar user={userOf(players, p)} size={28} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{nick(players, p)}
{p === me && <span className="muted small"> (나)</span>}
</div>
<div className="small muted">
{v.left.includes(p) ? '나감(자동)' : v.away.includes(p) ? '자리 비움' : `🥇${sc.gold} 🥈${sc.silver}${sc.bonus ? ` ⭐${sc.bonus}` : ''}`}
</div>
</div>
<strong style={{ fontSize: '1.15rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} ${sc.total}점`}>
{sc.total}점
</strong>
{on && playing && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={36} />}
</div>
<div className="ma-chips" style={{ marginTop: 4 }} aria-label={`${nick(players, p)}의 선수`}>
{v.teams[p]!.map((id) => (
<span key={id} className={`ma-chip${v.used[p]!.includes(id) && !(v.race && v.phase === 'race' && v.race.racers.some((x) => x.id === id)) ? ' used' : ''}`} title={RACERS[id].text}>
{rname(id)}
</span>
))}
</div>
</div>
);
})}
</section>
{playing && me && v.seats.includes(me) && !v.left.includes(me) && (
<button className="btn btn-danger btn-sm" onClick={() => setAsk(true)}>
🏳 그만하고 나가기
</button>
)}
{ask && (
<ConfirmSheet
title="그만할까요?"
body="내 선수는 남은 경주를 자동으로 달리고, 나는 맨 뒤 순위가 돼요."
confirm="그만하기"
danger
onConfirm={() => act({ type: 'LEAVE' })}
onClose={() => setAsk(false)}
/>
)}
</>
);
}
// ---------------------------------------------------------------- status
function isMyTurn(v: MagicalAthleteView, me: string | null): boolean {
if (!me || v.phase === 'finished' || v.left.includes(me)) return false;
if (v.phase === 'draft') return v.draft?.picker === me;
if (v.phase === 'select') return v.seats.includes(me) && !v.picked[me];
return v.prompt?.owner === me;
}
function statusText(v: MagicalAthleteView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
if (me && v.left.includes(me)) return '나갔어요. 구경하는 중이에요';
if (v.phase === 'draft') return isMyTurn(v, me) ? '내 차례예요. 선수를 한 명 뽑아 주세요' : `${nick(players, v.draft!.picker)}님이 선수를 뽑는 중이에요`;
if (v.phase === 'select') return isMyTurn(v, me) ? `내 차례예요. ${v.raceNo}번째 경주에 내보낼 선수를 골라 주세요` : '모두 출전 선수를 고르는 중이에요';
const pr = v.prompt;
if (!pr) return '잠시만 기다려 주세요';
if (pr.owner === me) return pr.step === 'roll' ? `내 차례예요. ${pr.racer ? RACERS[pr.racer].name : ''} 주사위를 굴려 주세요` : '내 차례예요. 어떻게 할지 골라 주세요';
return `${nick(players, pr.owner)}님 차례예요 · ${v.raceNo}/${v.races} 경주`;
}
// ---------------------------------------------------------------- options
function Seg<T extends string | number>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
{children}
</div>
);
}
function Options({ value: o, onChange }: OptionsProps<MagicalAthleteOptions>) {
const set = (patch: Partial<MagicalAthleteOptions>) => onChange({ ...o, ...patch });
return (
<div className="stack" style={{ gap: 16 }}>
<Field label="경주로">
<Seg
label="경주로"
value={o.track}
options={[
['alternate', '순한·거친 번갈아'],
['mild', '모두 순한 판'],
['wild', '모두 거친 판'],
]}
onChange={(track) => set({ track })}
/>
</Field>
<Field label="점수표">
<Seg
label="점수표"
value={o.scoring}
options={[
['flat', '1등 3점·2등 1점'],
['rising', '갈수록 커져요'],
]}
onChange={(scoring) => set({ scoring })}
/>
</Field>
<Field label="2~3명일 때 선수 둘씩">
<Seg
label="2~3명일 때 선수 둘씩"
value={o.twoRacers}
options={[
['auto', '켜기(원작)'],
['off', '끄기'],
]}
onChange={(twoRacers) => set({ twoRacers })}
/>
</Field>
<Field label="고르기·굴리기 제한 시간">
<Seg
label="고르기·굴리기 제한 시간"
value={o.turnSeconds === null ? 'none' : String(o.turnSeconds)}
options={[
['20', '20초'],
['30', '30초'],
['60', '60초'],
['none', '무제한'],
]}
onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 20 | 30 | 60) })}
/>
</Field>
</div>
);
}
function optionsSummary(o: MagicalAthleteOptions): string {
return [
o.track === 'alternate' ? '순한·거친 번갈아' : o.track === 'mild' ? '모두 순한 판' : '모두 거친 판',
o.scoring === 'flat' ? '1등 3점·2등 1점' : '점수 갈수록 커짐',
o.twoRacers === 'auto' ? '2~3명은 선수 둘씩' : '선수 한 명씩',
o.turnSeconds === null ? '시간 제한 없음' : `${o.turnSeconds}초`,
].join(' · ');
}
// ---------------------------------------------------------------- rules
function Rules({ options }: { options?: MagicalAthleteOptions }) {
const rising = options?.scoring === 'rising';
return (
<div className="stack">
<style>{CSS}</style>
<p>
저마다 엉뚱한 능력을 가진 선수를 뽑아 <strong>경주 4번</strong>을 벌여요. 경주마다 <strong>1등은 {rising ? '3·4·5·6점' : '3점'}</strong>,{' '}
<strong>2등은 {rising ? '1·1·2·2점' : '1점'}</strong>을 받고, 네 경주가 끝나면 점수가 가장 많은 사람이 이겨요. 같으면 함께 이겨요.
</p>
<p>
<strong>선수 뽑기</strong>: (사람 수 × 2)명의 선수를 펼치고 뱀 순서(1→끝, 끝→1)로 한 명씩 뽑아요. 시작하는 사람을 바꿔 한 번 더 해서 각자 4명을
가져요. 2~3명이면 이걸 네 번 해서 8명씩 가지고, 경주마다 선수 둘을 내보내요.
</p>
<p>
<strong>출전</strong>: 경주마다 아직 안 달린 내 선수 중에서 몰래 골라요. 모두 고르면 함께 공개돼요. 선수마다 한 번만 달려요.
</p>
<p>
<strong>경주</strong>: 출발점부터 결승선까지 30칸이에요. 내 차례에 주사위를 굴려 그만큼 가요. 선수 능력이 수시로 끼어들어요. 두 번째 선수가 결승선을
넘는 순간 경주가 끝나요. 다음 경주는 가장 뒤처진 선수의 주인부터 시작해요.
</p>
<p>
<strong>거친 판</strong>(2·4번째 경주): <span aria-hidden>▶</span>화살표 칸에 멈추면 그 방향으로 더 가고, 🪨 돌 칸에 멈추면 넘어지고(다음 주사위 이동을
쉬어요), ⭐ 별 칸에 멈추면 1점을 받아요.
</p>
<p>
<strong>능력 순서</strong>: 한 가지 일로 여러 능력이 일어나면 칸 효과 → 지금 차례인 사람의 선수 → 시계 방향 다른 사람 선수 순서로 처리하고, 그 능력이 또
일으킨 일은 그 뒤에 이어서 처리해요. 한 선수의 능력은 한 차례에 다섯 번까지만 일어나요.
</p>
<h3 style={{ margin: '8px 0 0' }}>선수 24명</h3>
<ul className="ma-legend">
{Object.values(RACERS).map((r) => (
<li key={r.id}>
<span style={{ fontSize: '1.4rem' }} aria-hidden>
{r.emoji}
</span>
<div>
<strong>{r.name}</strong>
{r.optional && <span className="small muted"> (고를 수 있음)</span>}
<div className="small">{r.text}</div>
</div>
</li>
))}
</ul>
<p className="muted">시간이 지나면 고를 수 있는 능력은 쓰지 않고, 굴릴 차례면 주사위를 굴려요. 뽑기는 펼쳐진 선수 중 하나를, 출전은 남은 선수를 차례대로 내보내요.</p>
<p className="muted small">점수는 이 방에서만 쓰는 놀이용 점수예요.</p>
</div>
);
}
const ui: GameUI<MagicalAthleteView, MagicalAthleteOptions> = {
Board,
Side,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;