From b1b6cccad4bab68562640474e775af1f44a13ef4 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Tue, 13 Oct 2026 22:03:28 +0900 Subject: [PATCH] =?UTF-8?q?=EC=95=BC=EB=8B=A8=EB=B2=95=EC=84=9D=20?= =?UTF-8?q?=EB=8B=AC=EB=A6=AC=EA=B8=B0=20=ED=99=94=EB=A9=B4=EC=9D=84=20?= =?UTF-8?q?=EB=B6=80=EB=A3=A8=EB=A7=88=EB=B6=88=EC=B2=98=EB=9F=BC:=20?= =?UTF-8?q?=EB=84=A4=EB=AA=A8=EB=82=9C=20=EA=B3=A0=EB=A6=AC=20=ED=8C=90(PC?= =?UTF-8?q?=209=C3=978,=20=ED=9C=B4=EB=8C=80=ED=8F=B0=207=C3=9710,=20?= =?UTF-8?q?=EC=B6=9C=EB=B0=9C=20=EB=AA=A8=EC=84=9C=EB=A6=AC=EA=B0=80=20?= =?UTF-8?q?=EA=B2=B0=EC=8A=B9),=20=EA=B0=80=EC=9A=B4=EB=8D=B0=20=EC=9E=85?= =?UTF-8?q?=EC=B2=B4=20=EC=A3=BC=EC=82=AC=EC=9C=84=C2=B7=EC=8B=9C=EC=83=81?= =?UTF-8?q?=EB=8C=80=C2=B7=ED=95=A0=20=EC=9D=BC=20=EB=B2=84=ED=8A=BC,=20?= =?UTF-8?q?=EB=A7=90=EC=9D=B4=20=ED=95=9C=20=EC=B9=B8=EC=94=A9=20=EA=B1=B7?= =?UTF-8?q?=EA=B8=B0=C2=B7=ED=99=94=EC=82=B4=ED=91=9C=20=EB=AF=B8=EB=81=84?= =?UTF-8?q?=EB=9F=AC=EC=A7=90=C2=B7=EC=88=9C=EA=B0=84=EC=9D=B4=EB=8F=99=20?= =?UTF-8?q?=EB=82=A0=EA=B8=B0,=20=EB=8A=A5=EB=A0=A5=C2=B7=EB=B3=84=C2=B7?= =?UTF-8?q?=EB=8F=8C=C2=B7=EA=B2=B0=EC=8A=B9=20=ED=9A=A8=EA=B3=BC=EC=99=80?= =?UTF-8?q?=20=EC=86=8C=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 엔진: 경주 기록 줄에 화면용 mv(이동 출발·도착 칸)와 die(굴린 눈) 추가, mv만 따라가도 말 자리가 맞는지 무작위 대국 테스트. 화면: replay.ts(기록 → 주사위·걷기·효과 순서) + 테스트, 문서 §9·§10. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/games/magical-athlete/index.tsx | 1198 +++++++++++++---- .../src/games/magical-athlete/replay.test.ts | 44 + apps/web/src/games/magical-athlete/replay.ts | 41 + docs/games/magical-athlete.md | 18 +- .../magical-athlete/magical-athlete.test.ts | 38 + packages/games/src/magical-athlete/race.ts | 32 +- packages/games/src/magical-athlete/rules.ts | 12 + 7 files changed, 1095 insertions(+), 288 deletions(-) create mode 100644 apps/web/src/games/magical-athlete/replay.test.ts create mode 100644 apps/web/src/games/magical-athlete/replay.ts diff --git a/apps/web/src/games/magical-athlete/index.tsx b/apps/web/src/games/magical-athlete/index.tsx index f66ba02..9362938 100644 --- a/apps/web/src/games/magical-athlete/index.tsx +++ b/apps/web/src/games/magical-athlete/index.tsx @@ -5,12 +5,12 @@ 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, sfx, sounds, tone } from '../../lib/feedback'; +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'; -const ROLL_MS = 600; const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4']; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; @@ -20,71 +20,246 @@ const seatColor = (v: MagicalAthleteView, p: string) => COLORS[v.seats.indexOf(p 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); `d` = delay in ms (after the dice lands). */ +/** Game sounds on top of the shared palette (site volume applies). */ const maSound = { - /** Footsteps along the track. */ - steps: (d: number) => { - for (let i = 0; i < 3; i++) tone(i % 2 ? 560 : 470, 45, 'triangle', 0.09, d + i * 90); + /** 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: (d: number) => [880, 1175, 1568].forEach((f, i) => tone(f, 90, 'triangle', 0.08, d + i * 60)), + power: () => [880, 1175, 1568].forEach((f, i) => tone(f, 90, 'triangle', 0.08, i * 60)), /** Star space (+1 point). */ - star: (d: number) => { - tone(1318, 70, 'square', 0.05, d); - tone(1976, 160, 'square', 0.05, d + 70); + 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 }); }, - /** Rock space: tripped. */ - trip: (d: number) => tone(300, 200, 'sawtooth', 0.05, d, { slideTo: 150 }), /** Arrow space: slide forward / back. */ - arrow: (d: number, up: boolean) => tone(up ? 500 : 900, 220, 'sine', 0.09, d, { slideTo: up ? 1000 : 450 }), + 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: (d: number) => [784, 988, 1318].forEach((f, i) => tone(f, 130, 'triangle', 0.1, d + i * 90)), + 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; gap: 10px; } +.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); } -.ma-track { padding: 8px; overflow: hidden; } -.ma-track svg { display: block; width: 100%; height: auto; } -.ma-cell { fill: var(--surface-2); stroke: var(--border); stroke-width: 1.5; } -.ma-cell.start { fill: var(--primary-soft); } -.ma-cell.finish { fill: #fde68a; stroke: #b45309; } -.ma-cell.cur { stroke: var(--focus); stroke-width: 3; } -.ma-num { fill: var(--text-sub); font-size: 11px; font-weight: 700; } -.ma-num.fin { fill: #92400e; } -.ma-fx { font-size: 15px; } -.ma-fxt { font-size: 11px; font-weight: 900; } -.ma-tok { transition: transform .45s ease; } -.ma-tok circle { stroke: #1f2937; stroke-width: 2; } -.ma-tok.cur circle { stroke: var(--focus); stroke-width: 4; } -.ma-tok.trip { opacity: .55; } -.ma-hop { transform-box: fill-box; transform-origin: center; animation: ma-hop .45s ease-out; } -@keyframes ma-hop { 30% { transform: translateY(-10px) scale(1.12); } 60% { transform: translateY(0) scale(.96); } } -.ma-hop.tripped { animation: anim-shake .45s ease both; } -.ma-medal { transform-box: fill-box; transform-origin: center; animation: anim-pop .32s cubic-bezier(.3,1.6,.5,1) both; } -.ma-emoji { font-size: 16px; } + +/* 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-die { width: 54px; height: 54px; border-radius: 12px; background: #fffdf8; border: 3px solid #1f2937; display: inline-block; flex: none; } -.ma-die svg { width: 100%; height: 100%; display: block; } -@keyframes ma-tumble { 0% { transform: translateY(-14px) rotate(-50deg); } 60% { transform: translateY(3px) rotate(200deg); } 100% { transform: none; } } -.ma-die.rolling { animation: ma-tumble ${ROLL_MS}ms ease-out both; } -.ma-rollrow { display: flex; align-items: center; gap: 12px; } -.ma-news { display: flex; flex-direction: column; gap: 4px; } -.ma-news div { border-radius: 8px; padding: 6px 10px; font-size: .92rem; background: var(--surface-2); } -.ma-news .power { background: var(--primary-soft); font-weight: 700; } -.ma-news .space { background: var(--warning-soft); } -.ma-news .finish { background: var(--success-soft); font-weight: 800; } -@keyframes ma-pop { 0% { transform: scale(.94); opacity: 0; } 100% { transform: none; opacity: 1; } } -.ma-news .fresh { animation: ma-pop .35s ease-out both; } +.ma-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; } @@ -95,10 +270,10 @@ const CSS = ` .ma-dot { width: 14px; height: 14px; border-radius: 50%; border: 2px solid rgba(0,0,0,.45); flex: none; margin-top: 3px; display: inline-block; } .ma-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 8px; } .ma-card { display: flex; flex-direction: column; gap: 4px; padding: 10px; border-radius: var(--radius); border: 3px solid var(--border); background: var(--surface); color: var(--text); font: inherit; text-align: left; min-height: 104px; } -button.ma-card { cursor: pointer; } -button.ma-card:hover:not(:disabled) { border-color: var(--primary); } +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); } +.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; } @@ -113,143 +288,745 @@ button.ma-card:hover:not(:disabled) { border-color: var(--primary); } @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); } - .ma-panel.act { position: sticky; bottom: 0; z-index: 4; box-shadow: 0 -4px 14px rgba(0,0,0,.12); } } @media (prefers-reduced-motion: reduce) { .ma-tok { transition: none; } - .ma-die.rolling, .ma-news .fresh, .ma-hop, .ma-medal { animation: 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 Die({ value, rolling }: { value: number; rolling: boolean }) { +function Die3D({ value, rolling, dim }: { value: number | null; rolling: boolean; dim: boolean }) { + const [rx, ry] = FACE_TURN[value ?? 1]!; return ( - - - {PIPS[value]!.map(([x, y], i) => ( - + + + + {[1, 2, 3, 4, 5, 6].map((f) => ( + + {value !== null && ( + + {PIPS[f]!.map(([x, y], i) => ( + + ))} + + )} + ))} - + ); } -function useNarrow(): boolean { - const q = '(max-width: 599px)'; - const [narrow, setNarrow] = useState(() => typeof matchMedia !== 'undefined' && matchMedia(q).matches); +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 = () => setNarrow(m.matches); + const on = () => setC(m.matches); m.addEventListener('change', on); return () => m.removeEventListener('change', on); }, []); - return narrow; + 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(); + }, 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, + 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(); + }, 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 + + 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 -const CELL = 60; - -function fxText(e: SpaceEffect): string { - if (e.kind === 'arrow') return e.by > 0 ? `앞으로 ${e.by}칸 화살표` : `뒤로 ${-e.by}칸 화살표`; +function fxLabel(e: SpaceEffect): string { + if (e.kind === 'arrow') return e.by > 0 ? `앞으로 ${e.by}칸` : `뒤로 ${-e.by}칸`; return e.kind === 'rock' ? '돌(넘어짐)' : '별(1점)'; } -function Track({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { +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 narrow = useNarrow(); - const cols = narrow ? 8 : 11; - const cells = v.finish + 1; // 0..29 + finish - const rows = Math.ceil(cells / cols); - const at = (i: number) => { - const row = Math.floor(i / cols); - const k = i % cols; - const col = row % 2 === 0 ? k : cols - 1 - k; - return { x: col * CELL, y: row * CELL }; - }; + const 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 onTrack = r.racers.filter((x) => x.status !== 'out'); - const groups = new Map(); - for (const x of onTrack) groups.set(x.pos, [...(groups.get(x.pos) ?? []), x]); - const curPos = r.cur ? r.racers.find((x) => x.id === r.cur)?.pos : undefined; - const label = `${r.no}번째 경주 ${r.side === 'wild' ? '거친 판' : '순한 판'}. ${r.racers + 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: cells }, (_, i) => { - const { x, y } = at(i); - const e = fx.get(i); - const cls = `ma-cell${i === 0 ? ' start' : ''}${i === v.finish ? ' finish' : ''}${curPos === i && i !== v.finish ? ' cur' : ''}`; - return ( - - - - {i === 0 ? '출발' : i === v.finish ? '결승' : i} - - {i === v.finish && ( - - 🏁 - - )} - {e && ( - - {e.kind === 'arrow' ? ( - 0 ? 'var(--success)' : 'var(--danger)'}> - {e.by > 0 ? `▶+${e.by}` : `◀${e.by}`} +
+ + + + + + + + + + {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 ? ( + <> + + + 출발·결승 - ) : ( - - {e.kind === 'rock' ? '🪨' : '⭐'} + + ) : ( + + {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 && ( + + 💫 )} - )} - - ); - })} - {onTrack.map((x) => { - const group = groups.get(x.pos)!; - const k = group.indexOf(x); - const n = group.length; - const per = n <= 4 ? 2 : 3; - const size = n === 2 ? 12 : n <= 4 ? 11 : 9; - const { x: cx, y: cy } = at(Math.min(x.pos, v.finish)); - const ox = cx + (n === 1 ? CELL / 2 : 14 + (k % per) * ((CELL - 28) / Math.max(1, per - 1))); - // Below the space number (top-left), so a crowded space never hides it. - const oy = cy + (n === 1 ? CELL / 2 + 4 : n === 2 ? 34 : 30 + Math.floor(k / per) * (size * 2 - 6)); - const isCur = r.cur === x.id; - return ( - - {/* Remounted on every move / trip: a hop (or a stumble) while the token slides. */} - - - - {RACERS[x.id].emoji} - - {x.place && ( - - {x.place === 1 ? '🥇' : '🥈'} - - )} + ); + })} + {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' ? '출발 준비!' : '경주 끝'} + )} +
+
+ {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 }) { + const pr = v.prompt; + 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' ? '먼저 갈 선수를 고르는 중이에요' : '능력을 쓸지 고르는 중이에요'}. +

+ ) + ) : ( +

+ 경주가 끝났어요. +

+ )}
); } @@ -279,69 +1056,6 @@ function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; ); } -// ---------------------------------------------------------------- panels - -function actionFor(pr: MaPrompt, key: string): unknown { - if (pr.step === 'go') return { type: 'GO', racer: key }; - if (pr.step === 'roll' && key === 'roll') return { type: 'ROLL' }; - return { type: 'CHOOSE', key }; -} - -const STEP_TITLE: Record = { - go: '어느 선수가 먼저 갈까요?', - start: '차례 시작: 능력을 쓸까요?', - roll: '주사위를 굴려요', - reroll: '다시 굴릴까요?', - boost: '능력을 쓸까요?', -}; - -function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; rolling: boolean }) { - const r = v.race!; - const pr = v.prompt; - const mine = !!pr && pr.owner === me; - const curName = r.cur ? rname(r.cur) : ''; - return ( -
- {pr ? ( - <> -
- {r.roll?.value ? : } -
- {pr.owner === me ? '내 차례' : `${nick(players, pr.owner)}님 차례`} -
{curName ? `${curName}${r.roll?.value ? ` · 주사위 ${r.roll.value}` : ''}` : '먼저 갈 선수 고르기'}
-
-
- {mine ? ( - <> -

{STEP_TITLE[pr.step]}

-
- {pr.options.map((o, i) => ( - - ))} -
- {v.options.turnSeconds !== null && ( -

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

- )} - - ) : ( -

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

- )} - - ) : ( -

- 경주가 끝났어요. -

- )} -
- ); -} - function Draft({ v, me, players, act, pending }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean }) { const d = v.draft!; const mine = d.picker === me; @@ -492,48 +1206,18 @@ function FinalTable({ v, me, players }: { v: MagicalAthleteView; me: string | nu ); } -const ICON: Record = { turn: '▶', roll: '🎲', move: '👟', power: '✨', space: '🧭', finish: '🏁', info: 'ℹ️' }; - -function News({ lines, fresh }: { lines: LogLine[]; fresh: number }) { - if (!lines.length) return null; - return ( -
- {lines.map((l) => ( -
fresh ? ' fresh' : ''}`}> - {ICON[l.kind]} {l.text} -
- ))} -
- ); -} - // ---------------------------------------------------------------- board function Board({ view: v, me, players, act, pending }: BoardProps) { - const [rolling, setRolling] = useState(false); + const compact = useCompact(); const [announce, setAnnounce] = useState(''); - const prevRoll = useRef(v.rollSeq); + /** 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 [fresh, setFresh] = useState(prevLog.current); const prevTurn = useRef(v.turnSeq); - const soundReady = useRef(false); - const rollHeard = useRef(v.rollSeq); - useLayoutEffect(() => { - if (v.rollSeq <= prevRoll.current) { - prevRoll.current = v.rollSeq; - return; - } - prevRoll.current = v.rollSeq; - sfx.dice(); - if (reducedMotion()) return; - setRolling(true); - const t = setTimeout(() => setRolling(false), ROLL_MS); - return () => clearTimeout(t); - }, [v.rollSeq]); - - // New log lines → screen-reader announcement and the "방금 일어난 일" highlight. + // New log lines → screen-reader announcement (the board draws and sounds them). useEffect(() => { const r = v.race; if (!r) return; @@ -543,24 +1227,10 @@ function Board({ view: v, me, players, act, pending }: BoardProps l.n > prevLog.current && l.kind !== 'turn'); - setFresh(prevLog.current); prevLog.current = last; - soundReady.current = true; if (added.length) setAnnounce(added.slice(-4).map((l) => l.text).join(' ')); if (added.some((l) => l.kind === 'power')) haptic(30); - // One sound per update, after the dice lands when this update rolled (the dice has its own sound). - if (first) return; - const d = v.rollSeq > rollHeard.current && !reducedMotion() ? ROLL_MS : 0; - rollHeard.current = v.rollSeq; - const sp = added.filter((l) => l.kind === 'space'); - if (added.some((l) => l.kind === 'finish')) maSound.finish(d); - else if (added.some((l) => l.kind === 'power')) maSound.power(d); - else if (sp.some((l) => l.text.includes('별'))) maSound.star(d); - else if (sp.some((l) => l.text.includes('돌'))) maSound.trip(d); - else if (sp.length) maSound.arrow(d, sp.some((l) => l.text.includes('앞 화살표'))); - else if (added.some((l) => l.kind === 'move')) maSound.steps(d); }, [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. @@ -585,17 +1255,6 @@ function Board({ view: v, me, players, act, pending }: BoardProps { - if (!r) return []; - const lastTurn = [...r.log].reverse().find((l) => l.kind === 'turn'); - const from = lastTurn ? r.log.indexOf(lastTurn) : 0; - const prevTurnIdx = lastTurn ? [...r.log.slice(0, from)].reverse().find((l) => l.kind === 'turn') : undefined; - // Show the previous racer's turn too while the current one hasn't done anything yet. - const start = from === r.log.length - 1 && prevTurnIdx ? r.log.indexOf(prevTurnIdx) : from; - return r.log.slice(start).filter((l) => l.kind !== 'turn').slice(-6); - })(); - return (
@@ -611,21 +1270,16 @@ function Board({ view: v, me, players, act, pending }: BoardProps} {r && ( <> - {v.phase !== 'race' &&

{r.no}번째 경주가 끝났을 때 모습이에요.

} - + {v.phase !== 'race' && ( +

+ {r.no}번째 경주가 끝났을 때 모습이에요. +

+ )} +
- {v.phase === 'race' && ( -
- -
-

방금 일어난 일

- {recent.length ? :

아직 없어요.

} -
-
- )}

경주 기록

-
    +
      {[...r.log].reverse().map((l) => (
    • {ICON[l.kind]} {l.text} @@ -633,8 +1287,8 @@ function Board({ view: v, me, players, act, pending }: BoardProps
+
- )} diff --git a/apps/web/src/games/magical-athlete/replay.test.ts b/apps/web/src/games/magical-athlete/replay.test.ts new file mode 100644 index 0000000..89b12a5 --- /dev/null +++ b/apps/web/src/games/magical-athlete/replay.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, test } from 'bun:test'; +import type { LogLine } from '@bg/games/magical-athlete'; +import { itemsOf, pathOf } from './replay'; + +describe('야단법석 달리기 판 다시 그리기', () => { + test('걷는 길: 앞으로·뒤로 한 칸씩, 순간이동은 두 끝만', () => { + expect(pathOf(3, 7, false)).toEqual([3, 4, 5, 6, 7]); + expect(pathOf(12, 9, false)).toEqual([12, 11, 10, 9]); + expect(pathOf(4, 20, true)).toEqual([4, 20]); + }); + + test('주사위 → 걷기 → 화살표 칸(미끄러짐) → 도착 순서로 보여요', () => { + const lines: LogLine[] = [ + { n: 1, kind: 'turn', text: '토끼 차례예요.', racer: 'hare' }, + { n: 2, kind: 'roll', text: '토끼가 주사위를 굴려 3이(가) 나왔어요.', racer: 'hare', die: 3 }, + { n: 3, kind: 'move', text: '토끼가 5칸 가서 5칸에 왔어요.', racer: 'hare', mv: [{ racer: 'hare', from: 0, to: 5 }] }, + { n: 4, kind: 'space', text: '토끼가 앞 화살표 칸에 멈춰 3칸 앞으로 가요.', racer: 'hare' }, + { n: 5, kind: 'move', text: '토끼가 3칸 가서 8칸에 왔어요.', racer: 'hare', mv: [{ racer: 'hare', from: 5, to: 8 }] }, + { n: 6, kind: 'power', text: '마술사가 주사위를 다시 굴려 6이(가) 나왔어요.', racer: 'magician', die: 6 }, + { + n: 7, + kind: 'move', + text: '자리바꿈이가 토끼와 자리를 바꿨어요.', + racer: 'flipflop', + mv: [ + { racer: 'flipflop', from: 2, to: 8, jump: true }, + { racer: 'hare', from: 8, to: 2, jump: true }, + ], + }, + { n: 8, kind: 'finish', text: '롱다리가 1등으로 결승선을 넘었어요!', racer: 'legs' }, + ]; + const items = itemsOf(lines, ['legs']); + expect(items.map((i) => i.t)).toEqual(['line', 'roll', 'walk', 'line', 'walk', 'roll', 'line', 'walk', 'walk', 'line']); + const walks = items.filter((i) => i.t === 'walk'); + expect(walks.map((w) => [w.racer, w.path, w.slide, w.jump])).toEqual([ + ['hare', [0, 1, 2, 3, 4, 5], false, false], + ['hare', [5, 6, 7, 8], true, false], + ['flipflop', [2, 8], false, true], + ['hare', [8, 2], false, true], + ]); + expect(items.find((i) => i.t === 'roll' && i.value === 6)).toBeDefined(); + expect(items.at(-1)).toMatchObject({ t: 'line', place: 1 }); + }); +}); diff --git a/apps/web/src/games/magical-athlete/replay.ts b/apps/web/src/games/magical-athlete/replay.ts new file mode 100644 index 0000000..016ac65 --- /dev/null +++ b/apps/web/src/games/magical-athlete/replay.ts @@ -0,0 +1,41 @@ +/** + * 야단법석 달리기 board replay: new log lines → what the board shows, in order (die, token walks, effects). The view + * already has the result; the drawing follows it a beat behind so every roll, step and power can be seen. + */ +import type { LogLine, MaRacerView } from '@bg/games/magical-athlete'; +import type { RacerId } from '@bg/games/magical-athlete/racers'; + +export type Item = + | { t: 'roll'; line: LogLine; value: number } + | { t: 'walk'; line: LogLine; racer: RacerId; path: number[]; jump: boolean; slide: boolean } + | { t: 'line'; line: LogLine; place?: number } + /** The update is fully drawn: statuses, spaces and podium as the view has them. */ + | { t: 'end'; racers: MaRacerView[]; finishers: RacerId[]; cur: RacerId | null; last: number }; + +/** Spaces of a straight walk, both ends included (a jump: just both ends). */ +export function pathOf(from: number, to: number, jump: boolean): number[] { + if (jump) return [from, to]; + const out = [from]; + for (let p = from; p !== to; ) out.push((p += to > from ? 1 : -1)); + return out; +} + +/** + * Log lines → board items. A die face shows first; a move line walks each racer it moved (a space line followed by + * a move of the same racer is an arrow, so that walk slides); the other lines show as effects. `finishers` gives + * the place of a `finish` line. + */ +export function itemsOf(lines: LogLine[], finishers: RacerId[]): Item[] { + const out: Item[] = []; + let arrow: RacerId | null = null; + for (const l of lines) { + if (l.die) out.push({ t: 'roll', line: l, value: l.die }); + if (l.mv?.length) { + for (const m of l.mv) out.push({ t: 'walk', line: l, racer: m.racer, path: pathOf(m.from, m.to, !!m.jump), jump: !!m.jump, slide: arrow === m.racer }); + } else if (l.kind !== 'roll') { + out.push({ t: 'line', line: l, ...(l.kind === 'finish' && l.racer ? { place: finishers.indexOf(l.racer) + 1 } : {}) }); + } + arrow = l.kind === 'space' ? (l.racer ?? null) : null; + } + return out; +} diff --git a/docs/games/magical-athlete.md b/docs/games/magical-athlete.md index 25c3627..58fdc61 100644 --- a/docs/games/magical-athlete.md +++ b/docs/games/magical-athlete.md @@ -186,11 +186,20 @@ interface MagicalAthleteState { - 네 번째 경주가 끝나면 종료. `ranking`(같은 총점은 같은 묶음, 나간 사람은 맨 뒤), `scores`(총점), `scoreText`("N점"), `summary`(§6). ## 9. UI/UX -- PC: 위에 경주 번호·판 종류·점수표, 가운데 경주로(뱀 모양 11칸 줄, 휴대폰은 8칸 줄), 아래에 내 차례 할 일·방금 일어난 일·경주 기록· - 이번 경주 선수 카드. 오른쪽 패널에 사람별 점수(금·은·별)와 선수 칩(달린 선수는 줄 그음). +- 경주로는 부루마불처럼 네모난 고리 판이다. 오른쪽 아래 모서리가 출발이고 시계 방향으로 30칸을 한 바퀴 돌면 그 모서리가 결승선이다 + (PC 가로 9칸 × 세로 8칸, 휴대폰은 세로로 긴 7 × 10칸). 변마다 안쪽에 색 띠, 거친 판 칸은 색(별 노랑·돌 회색·앞 화살표 초록· + 뒤 화살표 빨강)과 표시(⭐·🪨·+3·−3)로 구분하고 판 아래에 뜻을 적는다. +- 판 가운데: 경주 번호·판 종류·메달 점수, 입체 주사위와 지금 움직이는 선수, 도착한 선수 시상대(1·2등), 내 차례 할 일 버튼, + 방금 일어난 일 두 줄. 판 아래에 경주 기록과 이번 경주 선수 카드, 오른쪽 패널에 사람별 점수(금·은·별)와 선수 칩(달린 선수는 줄 그음). - 뽑기: 카드(그림·이름·능력 한 줄)를 눌러 바로 뽑음. 고르기: 카드를 눌러 고른 뒤 "… 내보내기". -- 경주: 주사위 버튼, 능력 버튼("⚗️ 3 대신 4칸 가기" / "3(으)로 가기")처럼 결과가 보이는 문구. 말은 칸 사이를 미끄러지듯 움직이고 - (움직임 줄이기 설정이면 바로), 넘어진 선수는 눕혀서 흐리게. +- 경주: 주사위 버튼, 능력 버튼("⚗️ 3 대신 4칸 가기" / "3(으)로 가기")처럼 결과가 보이는 문구. +- 움직임(누가 했든 같은 연출, `replay.ts`): 화면은 결과를 바로 받지만 판은 경주 기록 순서대로 한 박자 늦게 다시 그린다. + 주사위가 공중에서 굴러 떨어져 눈이 나오고 → 말이 한 칸씩 폴짝 걸어가며(지나간 칸 반짝, 발소리) → 화살표 칸이면 미끄러지고, + 최면술사·끼어들기·자리바꿈이·시시포스는 날아서 옮겨 간다. 능력은 말 위에 "✨ 이름", 별은 "⭐ +1점", 돌은 "🪨 꽈당!"(말이 눕고 흔들림), + 결승은 큰 글자 "🥇 … 1등!"과 색종이, 경주 시작은 "🏁 N번째 경주 출발!". 지금 움직이는 말에는 깜빡이는 고리. + 밀린 업데이트가 있으면 빨리 감고, 너무 밀리면(4개 이상) 지금 모습으로 바로 맞춘다. 새로 열거나 다시 접속한 화면은 다시 그리지 않고 + 지금 모습만 보이며, 움직임 줄이기 설정이면 연출 없이 바로 바뀐다(소리는 한 번). +- 이를 위해 경주 기록 줄에 화면용 정보가 붙는다: 이동 줄 `mv`(선수·출발 칸·도착 칸, 순간이동이면 `jump`), 굴림 줄(마술사 다시 굴림 포함) `die`. - 접근성: 경주로 SVG에 전체 상황 aria-label, 기록은 `aria-live`, 모든 조작은 버튼(키보드 Tab·Enter). 다크 모드 색 변수 사용. - 도움말: [?] 지금 할 수 있는 것(`help.ts`), 30초 요약 카드 3장(`quick.tsx`), 규칙 보기에 선수 24명 표. @@ -206,6 +215,7 @@ interface MagicalAthleteState { - [x] 뱀 순서 뽑기(2명 8명씩, 4명 4명씩), 몰래 고르기(남에게는 골랐는지만), 시간 초과 기본값, 나간 사람 자동 진행, 점수표 두 가지. - [x] 엔진 공통 무작위 대국(유출 검사 포함), 빠른 무작위 대국(보존 규칙·경주 4번·차례 상한), 결정성, 시간 초과만으로 끝남, 상한 종료. - [x] 컴퓨터: 뽑기·출전·롱다리·마술사·연금술사·로켓 박사·최면술사·자리바꿈이 판단, 무작위보다 자주 이김, 2~6명 끝까지. +- [x] 화면 다시 그리기: 무작위 대국에서 이동 줄(`mv`)만 따라가도 말 자리가 실제와 같음·굴림 줄에 눈(`die`), `replay.test.ts`(걷는 길·화살표 미끄러짐·순간이동·도착 순서). - [x] 방 통합(`apps/server/src/rooms/magical-athlete.room.test.ts`): 컴퓨터와 연습 한 판을 사람이 자기 화면만 보고 끝까지, 몰래 고른 선수 비공개. - [x] E2E(`e2e/games.e2e.ts`): PC 방장 + 휴대폰, 실제 뽑기(키보드 포함)·고르기·굴리기·능력 선택으로 네 경주 끝까지, 거친 판·능력 기록 확인. diff --git a/packages/games/src/magical-athlete/magical-athlete.test.ts b/packages/games/src/magical-athlete/magical-athlete.test.ts index ff28d7a..f37fc75 100644 --- a/packages/games/src/magical-athlete/magical-athlete.test.ts +++ b/packages/games/src/magical-athlete/magical-athlete.test.ts @@ -593,6 +593,44 @@ describe('무작위 대국', () => { expect(capped).toBeLessThanOrEqual(Math.ceil(FAST / 50)); }, 120_000); + test('이동 줄(mv)만 따라가도 화면의 말 자리가 실제 자리와 같아요(굴린 줄에는 눈)', () => { + let moves = 0; + let jumps = 0; + for (let i = 1; i <= 30; i++) { + const n = 2 + (i % 5); + const rng = SeededRng.fromSeed(seedN(700 + i)); + const chooser = SeededRng.fromSeed(seedN(800 + i)); + let s = def.setup({ players: Array.from({ length: n }, (_, k) => `p${k}`), options: optionsFor(i), rng, now: 0 }); + let steps = 0; + while (!def.result(s)) { + if (++steps > 4000) throw new Error(`seed ${i}: game did not finish`); + const before = s.race; + const shown = new Map(before?.racers.map((x) => [x.id, x.pos])); + const lastN = before?.log.at(-1)?.n ?? 0; + const p = def.activePlayers(s)[chooser.int(def.activePlayers(s).length)]!; + const legal = def.legalActions!(s, p); + s = def.apply(s, p, legal[chooser.int(legal.length)]!, { rng, now: steps }).state; + const r = s.race; + if (!r) continue; + const fresh = r.no === before?.no ? r.log.filter((l) => l.n > lastN) : r.log; + if (r.no !== before?.no) shown.clear(); + for (const l of fresh) { + if (l.kind === 'roll') expect([1, 2, 3, 4, 5, 6]).toContain(l.die!); + for (const m of l.mv ?? []) { + expect(m.from).toBe(shown.get(m.racer) ?? 0); + expect(m.from === m.to && !m.jump).toBe(false); + shown.set(m.racer, m.to); + moves++; + if (m.jump) jumps++; + } + } + for (const x of r.racers) expect(shown.get(x.id) ?? 0).toBe(x.pos); + } + } + expect(moves).toBeGreaterThan(500); + expect(jumps).toBeGreaterThan(0); + }); + test('같은 시드면 같은 결과(결정성)', () => { for (let i = 1; i <= 5; i++) { const a = randomPlayout(def, { players: ['a', 'b', 'c'], seed: seedN(100 + i), maxApplyMs: 30 }); diff --git a/packages/games/src/magical-athlete/race.ts b/packages/games/src/magical-athlete/race.ts index 6565dd8..12a32cb 100644 --- a/packages/games/src/magical-athlete/race.ts +++ b/packages/games/src/magical-athlete/race.ts @@ -104,27 +104,29 @@ export class Runner { // ------------------------------------------------------------ log & powers - log(kind: LogLine['kind'], text: string, racer?: RacerId): void { + log(kind: LogLine['kind'], text: string, racer?: RacerId, more?: Pick): void { const r = this.r; r.logSeq++; - r.log.push({ n: r.logSeq, kind, text, ...(racer ? { racer } : {}) }); + const extra = { ...(racer ? { racer } : {}), ...more }; + r.log.push({ n: r.logSeq, kind, text, ...extra }); if (r.log.length > LOG_KEEP) r.log.splice(0, r.log.length - LOG_KEEP); - this.ev.push({ type: 'log', n: r.logSeq, kind, text, ...(racer ? { racer } : {}) }); + this.ev.push({ type: 'log', n: r.logSeq, kind, text, ...extra }); } /** * A racer's power happens: logged, and 꼼지락이 reacts. Returns false once the racer's power hit POWER_CAP this * racer-turn (the caller then skips an optional effect; rule powers pass `force` and still apply silently). */ - fire(id: RacerId, text: string, force = false): boolean { + fire(id: RacerId, text: string, force = false, die?: number): boolean { const r = this.r; const n = r.fired[id] ?? 0; + const more = die ? { die } : undefined; if (n >= POWER_CAP) { - if (force) this.log('power', text, id); + if (force) this.log('power', text, id, more); return false; } r.fired[id] = n + 1; - this.log('power', text, id); + this.log('power', text, id, more); const sc = this.has('scoocher'); if (sc && id !== 'scoocher') { this.enqueue([ @@ -206,7 +208,7 @@ export class Runner { .filter((y) => y !== x && y.pos > from && y.pos < target) .sort((a, b) => a.pos - b.pos); x.pos = Math.min(target, FINISH); - this.log('move', `${ga(x.id)} ${target - from}칸 가서 ${x.pos >= FINISH ? '결승선' : `${x.pos}칸`}에 왔어요.`, x.id); + this.log('move', `${ga(x.id)} ${target - from}칸 가서 ${x.pos >= FINISH ? '결승선' : `${x.pos}칸`}에 왔어요.`, x.id, { mv: [{ racer: x.id, from, to: x.pos }] }); if (target >= FINISH) this.finish(x); const tasks: Task[] = []; if (x.status === 'run') this.stopTasks(x, tasks); @@ -236,7 +238,7 @@ export class Runner { target = this.babyAdjust(x, target, 0); if (target === from) return; x.pos = target; - this.log('move', `${ga(x.id)} ${from - target}칸 뒤로 가서 ${target === 0 ? '출발점' : `${target}칸`}에 왔어요.`, x.id); + this.log('move', `${ga(x.id)} ${from - target}칸 뒤로 가서 ${target === 0 ? '출발점' : `${target}칸`}에 왔어요.`, x.id, { mv: [{ racer: x.id, from, to: target }] }); const tasks: Task[] = []; this.stopTasks(x, tasks); this.enqueue(tasks); @@ -246,8 +248,9 @@ export class Runner { warp(x: RacerState, to: number, text: string): void { if (x.status !== 'run') return; const target = this.babyAdjust(x, to, 0); + const from = x.pos; x.pos = target; - this.log('move', `${text} (${target === 0 ? '출발점' : `${target}칸`})`, x.id); + this.log('move', `${text} (${target === 0 ? '출발점' : `${target}칸`})`, x.id, { mv: [{ racer: x.id, from, to: target, jump: true }] }); const tasks: Task[] = []; this.stopTasks(x, tasks); this.enqueue(tasks); @@ -258,7 +261,12 @@ export class Runner { const pa = a.pos; a.pos = b.pos; b.pos = pa; - this.log('move', `${ga(a.id)} ${nm(b.id)}와 자리를 바꿨어요. (${a.pos}칸 ↔ ${b.pos}칸)`, a.id); + this.log('move', `${ga(a.id)} ${nm(b.id)}와 자리를 바꿨어요. (${a.pos}칸 ↔ ${b.pos}칸)`, a.id, { + mv: [ + { racer: a.id, from: pa, to: a.pos, jump: true }, + { racer: b.id, from: a.pos, to: pa, jump: true }, + ], + }); const tasks: Task[] = []; this.stopTasks(a, tasks); this.stopTasks(b, tasks); @@ -444,7 +452,7 @@ export class Runner { const value = 1 + this.rng.int(6); r.roll = { value, rerolls: 0 }; this.s.rollSeq++; - this.log('roll', `${ga(r.cur!)} 주사위를 굴려 ${value}이(가) 나왔어요.`, r.cur!); + this.log('roll', `${ga(r.cur!)} 주사위를 굴려 ${value}이(가) 나왔어요.`, r.cur!, { die: value }); this.ev.push({ type: 'rolled', racer: r.cur, value }); if (r.cur === 'magician') { r.step = 'reroll'; @@ -461,7 +469,7 @@ export class Runner { const value = 1 + this.rng.int(6); r.roll = { value, rerolls: r.roll.rerolls + 1 }; this.s.rollSeq++; - this.fire('magician', `마술사가 주사위를 다시 굴려 ${value}이(가) 나왔어요.`); + this.fire('magician', `마술사가 주사위를 다시 굴려 ${value}이(가) 나왔어요.`, false, value); this.ev.push({ type: 'rolled', racer: r.cur, value }); this.drain(); if (this.over()) return this.endRace(); diff --git a/packages/games/src/magical-athlete/rules.ts b/packages/games/src/magical-athlete/rules.ts index 17a048e..d07b775 100644 --- a/packages/games/src/magical-athlete/rules.ts +++ b/packages/games/src/magical-athlete/rules.ts @@ -118,11 +118,23 @@ export interface RacerState { export type Step = 'go' | 'start' | 'roll' | 'reroll' | 'boost'; +/** One racer's move for the screen: walked space by space (forward or back) or `jump`ed there (warp / swap). */ +export interface LogMove { + racer: RacerId; + from: number; + to: number; + jump?: true; +} + export interface LogLine { n: number; kind: 'turn' | 'roll' | 'move' | 'power' | 'space' | 'finish' | 'info'; text: string; racer?: RacerId; + /** `move` lines: who went where, so the board can walk the token (the text alone stays the record). */ + mv?: LogMove[]; + /** The die face of a roll (`roll` line, or 마술사's reroll `power` line). */ + die?: number; } export interface RaceState {