diff --git a/README.md b/README.md index c3f48b4..0a76769 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ - 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)을 뺀 30개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만. - 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드. - 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드. -- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 사용자·방 관리, 계정별 기록. +- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록. ## 개발 ```bash @@ -48,6 +48,7 @@ bun e2e/pwa.e2e.ts # PWA: 매니페스트·아이콘, 서비스 bun e2e/bots.e2e.ts # 컴퓨터 상대, 방 나가기, 게스트 로그아웃 bun e2e/replay.e2e.ts # 다시 보기 bun e2e/tutorial.e2e.ts # 처음 하는 사람용 규칙 요약 +bun e2e/speed.e2e.ts # 게임 속도 배율: 판 애니메이션 재생 속도와 컴퓨터 응답 시간 bun scripts/loadtest.ts --help # 부하·장애 주입 (docs/reports 참고) ``` diff --git a/apps/server/src/admin.test.ts b/apps/server/src/admin.test.ts index 8a47fa8..bb30891 100644 --- a/apps/server/src/admin.test.ts +++ b/apps/server/src/admin.test.ts @@ -196,6 +196,33 @@ describe('site settings, rooms, users', () => { expect((await chat).text).toBe('너 **야'); }); + test('game speed: 1/16~16 (default 1), shown in /api/config, out of range rejected', async () => { + const s = start(); + const sup = await discordLogin(s, SUPER); + const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site; + expect(site.gameSpeed).toBe(1); + expect((await api(s.base, '/api/config')).body.gameSpeed).toBe(1); + for (const bad of [0, 1 / 32, 17, -1]) { + const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: bad }) }); + expect(r.res.status).toBe(400); + } + for (const ok of [1 / 16, 16, 0.75]) { + const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: ok }) }); + expect(r.res.status).toBe(200); + expect((await api(s.base, '/api/config')).body.gameSpeed).toBe(ok); + } + // An open room gets the new speed at once (its screen's animations follow it). + const g = await guest(s.base, '방장님'); + const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) }); + const c = await new Client(s.base, g.cookie, g.id).connect(); + clients.push(c); + c.send({ t: 'join', code: room.body.code, as: 'player' }); + expect((await c.next('room')).room.gameSpeed).toBe(0.75); + const next = c.next('room'); + await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: 2 }) }); + expect((await next).room.gameSpeed).toBe(2); + }); + test('admin closes a room: everyone is told and disconnected from it', async () => { const s = start(); const sup = await discordLogin(s, SUPER); diff --git a/apps/server/src/admin/settings.ts b/apps/server/src/admin/settings.ts index b53133d..1a349e8 100644 --- a/apps/server/src/admin/settings.ts +++ b/apps/server/src/admin/settings.ts @@ -5,7 +5,7 @@ import type { Database } from 'bun:sqlite'; import { z } from 'zod'; import type { AnyGameDefinition } from '@bg/engine'; -import { CATALOG, type CatalogEntry } from '@bg/shared'; +import { CATALOG, GAME_SPEED_DEFAULT, GAME_SPEED_MAX, GAME_SPEED_MIN, type CatalogEntry } from '@bg/shared'; export const SiteSettingsSchema = z.object({ siteName: z.string().trim().min(1).max(40).default('같이 놀자 보드게임'), @@ -17,6 +17,8 @@ export const SiteSettingsSchema = z.object({ graceSec: z.number().int().min(10).max(600).default(60), chatEnabledDefault: z.boolean().default(true), chatFilterDefault: z.boolean().default(true), + /** Animations and the computers' thinking time are divided by this (applies at once, also to running games). */ + gameSpeed: z.number().min(GAME_SPEED_MIN).max(GAME_SPEED_MAX).default(GAME_SPEED_DEFAULT), }); export type SiteSettings = z.infer; diff --git a/apps/server/src/http/admin.ts b/apps/server/src/http/admin.ts index 0c6b6ba..3a74515 100644 --- a/apps/server/src/http/admin.ts +++ b/apps/server/src/http/admin.ts @@ -93,6 +93,8 @@ export function createAdminApp(d: AdminDeps) { const before = d.settings.getSite(); d.settings.setSite(parsed.data, actor(c)); d.audit.log(actor(c), 'site.update', null, before, parsed.data); + // The game speed applies at once: open rooms get it with a fresh room view (their animations follow it). + if (before.gameSpeed !== parsed.data.gameSpeed) for (const r of d.rooms.all()) r.broadcastRoom(); return c.json({ site: parsed.data }); }); diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index d838514..28d9fa1 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -97,6 +97,7 @@ export function createHttpApp(d: HttpDeps) { siteName: site.siteName, announcement: site.announcement, maintenance: site.maintenance, + gameSpeed: site.gameSpeed, }); }); diff --git a/apps/server/src/rooms/bots.room.test.ts b/apps/server/src/rooms/bots.room.test.ts index ff64173..5f23b93 100644 --- a/apps/server/src/rooms/bots.room.test.ts +++ b/apps/server/src/rooms/bots.room.test.ts @@ -5,6 +5,7 @@ import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES, botReactionAt } from '@bg/games/bo import { classicDeck, type OneCardState } from '@bg/games/one-card'; import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared'; import { openDb } from '../db'; +import { SiteSettingsSchema, type SettingsStore } from '../admin/settings'; import { botPace, defaultBotDelay, type BotDelayInput } from './bots'; import { RoomManager } from './manager'; import { Room, type Conn, type RoomSnapshot } from './room'; @@ -89,6 +90,41 @@ describe('bot list', () => { } }); + test('game speed scales the thinking time, but not a reaction the game timed itself', () => { + const bot = 'bot:1:01J0000000000000000000000'; + const r = () => 0.5; + const input = { choices: 4, withPeople: true, bot, followUp: false }; + expect(defaultBotDelay(input, r, 3)).toBe(Math.round((2600 * botPace(bot) + 1500) * 3)); + expect(defaultBotDelay(input, r, 0.25)).toBe(Math.round((2600 * botPace(bot) + 1500) * 0.25)); + expect(defaultBotDelay({ ...input, reactMs: 800 }, r, 3)).toBe(800); + }); + + test('the admin game speed reaches the computers (×1.5 slower base) and the room view', () => { + let speed = 1 / 16; + const db = openDb(':memory:'); + let now = 1_000_000; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const settings = { game: () => null, getSite: () => SiteSettingsSchema.parse({ gameSpeed: speed }) } as unknown as SettingsStore; + const manager = new RoomManager({ store: new RoomStore(db), games: GAMES, users, now: () => now, settings }); + const play = () => { + const room = manager.createPractice('A', 'omok') as Room; + rooms.push(room); + room.join({ userId: 'A', send: () => {}, close: () => {} }, 'player'); + room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } }); + expect(room.start('A')).toBeNull(); + room.act('A', 1, { type: 'place', x: 7, y: 7 }); + expect(room.roomView().gameSpeed).toBe(speed); + return room.bots.dueAt! - now; + }; + // 1/16: at least the shortest thought (0.49 s) × 1.5 × 16, though never past half the 30 s turn timer. + const slow = play(); + expect(slow).toBeGreaterThanOrEqual(11_000); + expect(slow).toBeLessThanOrEqual(15_000); + speed = 16; + // ×16: at most the longest thought (10.4 s) × 1.5 / 16. + expect(play()).toBeLessThanOrEqual(1000); + }); + test('thinking never takes more than half of the time left on the turn timer', () => { const h = harness(undefined, undefined, () => 60 * 60_000); const room = h.manager.createPractice('A', 'omok') as Room; diff --git a/apps/server/src/rooms/bots.ts b/apps/server/src/rooms/bots.ts index dbb8a1a..9d39f19 100644 --- a/apps/server/src/rooms/bots.ts +++ b/apps/server/src/rooms/bots.ts @@ -27,6 +27,8 @@ export interface BotRoom { profile?(bot: string): { level: number; base: number }; /** The computers' talk and visible activity with the local model (docs/06 §12.1). */ brain?: BotBrain; + /** Multiplies the computers' thinking time and live games' look intervals (game speed, docs/14 §5); absent = 1. */ + timeScale?(): number; } /** What a planned computer move looks like, for its thinking time. */ @@ -47,18 +49,23 @@ export interface BotDelayInput { * Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer * the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its * own pace, and a follow-up move of the same turn is quicker. When people may act in the same window the computer - * waits 1.5 s more so it never beats a person to a reaction just by being fast. + * waits 1.5 s more so it never beats a person to a reaction just by being fast. `scale` (game speed, `BOT_SLOWDOWN / + * speed`) multiplies the whole thinking time; a reaction the game timed itself (`reactMs`) is never scaled, so who + * calls first stays fair. */ -export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): number { +export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom, scale = 1): number { const { choices, withPeople, bot, followUp } = input; if (input.reactMs !== undefined) return Math.max(0, Math.round(input.reactMs)); let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400; if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000; ms *= botPace(bot); if (followUp) ms *= 0.5; - return Math.round(withPeople ? ms + 1500 : ms); + return Math.round((withPeople ? ms + 1500 : ms) * scale); } +/** At game speed ×1 the computers take this much longer than `defaultBotDelay`'s base times (2026-10-14: a bit slower). */ +export const BOT_SLOWDOWN = 1.5; + /** Never use more than this share of the time left on the turn timer for thinking. */ export const BOT_DEADLINE_SHARE = 0.5; @@ -86,7 +93,7 @@ export class BotDriver { constructor( private room: BotRoom, private random: () => number = secureRandom, - private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random), + private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random, room.timeScale?.() ?? 1), ) {} /** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */ @@ -154,6 +161,10 @@ export class BotDriver { this.liveDue.clear(); } + private timeScale(): number { + return this.room.timeScale?.() ?? 1; + } + private liveStrategy(): LiveBotStrategy | null { return LIVE_BOT_STRATEGIES[this.room.def.id] ?? null; } @@ -177,7 +188,7 @@ export class BotDriver { } const now = this.room.now(); for (const p of g.players) { - if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p))); + if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p) * this.timeScale())); } const next = Math.min(...this.liveDue.values()); this.dueAt = Number.isFinite(next) ? next : null; @@ -210,7 +221,7 @@ export class BotDriver { } const ms = performance.now() - t0; if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) }); - this.liveDue.set(bot, now + Math.max(100, decision.next)); + this.liveDue.set(bot, now + Math.max(100, Math.round(decision.next * this.timeScale()))); if (decision.action == null) continue; if (!def.validate(g.state, bot, decision.action, { now }).ok) continue; // the moment passed (phase changed); look again later const brain = this.room.brain; diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index ceb0b7d..32b8eba 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -4,11 +4,11 @@ */ import { ulid } from 'ulid'; import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine'; -import { botChatRequired, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared'; +import { botChatRequired, clampGameSpeed, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared'; import { botPersona } from '@bg/games/bots'; import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck'; import { sha256Hex } from '../auth/sessions'; -import { BotDriver, type BotDelayInput } from './bots'; +import { BOT_SLOWDOWN, BotDriver, type BotDelayInput } from './bots'; import { drift, newBotProfile, profileFromId, repick, type BotProfile } from './bot-profile'; import { BotBrain, type BotActivity } from '../ai/brain'; import type { Llm } from '../ai/llm'; @@ -224,6 +224,7 @@ export class Room { nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가', profile: (bot) => this.profile(bot), brain: this.brain, + timeScale: () => BOT_SLOWDOWN / this.gameSpeed(), }, secureRandom, deps.botDelay, @@ -440,6 +441,7 @@ export class Room { ...(this.starting ? { starting: true } : {}), // Levels are revealed only once the game is over (fairness check). ...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}), + gameSpeed: this.gameSpeed(), }; } @@ -623,6 +625,11 @@ export class Room { } /** A computer's level and luck; computers saved without one get it from their id. */ + /** Admin game speed (docs/14 §5), read live so a change reaches running games too. */ + gameSpeed(): number { + return clampGameSpeed(this.deps.settings?.getSite().gameSpeed); + } + profile(bot: string): BotProfile { return (this.botProfiles[bot] ??= profileFromId(bot)); } diff --git a/apps/web/src/games/apple/index.tsx b/apps/web/src/games/apple/index.tsx index fece8c3..971b980 100644 --- a/apps/web/src/games/apple/index.tsx +++ b/apps/web/src/games/apple/index.tsx @@ -9,6 +9,7 @@ import { socket } from '../../net/socket'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; /** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */ const ROWS = 10; @@ -231,7 +232,7 @@ function AppleBoard({ view: v, me, players, act }: BoardProps) { }, [v.cells]); useEffect(() => { if (!intro) return; - const t = setTimeout(() => setIntro(false), 900); + const t = setTimeout(() => setIntro(false), fxMs(900)); return () => clearTimeout(t); }, [intro]); useEffect(() => { @@ -259,12 +260,12 @@ function AppleBoard({ view: v, me, players, act }: BoardProps) { }, [canPlay]); useEffect(() => { if (!pops.length) return; - const t = setTimeout(() => setPops((p) => p.slice(1)), 450); + const t = setTimeout(() => setPops((p) => p.slice(1)), fxMs(450)); return () => clearTimeout(t); }, [pops]); useEffect(() => { if (!flash) return; - const t = setTimeout(() => setFlash(null), 900); + const t = setTimeout(() => setFlash(null), fxMs(900)); return () => clearTimeout(t); }, [flash]); diff --git a/apps/web/src/games/baduk/index.tsx b/apps/web/src/games/baduk/index.tsx index 8b49638..a5ca000 100644 --- a/apps/web/src/games/baduk/index.tsx +++ b/apps/web/src/games/baduk/index.tsx @@ -10,6 +10,7 @@ import { reducedMotion, useBanner } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; type Color = 'black' | 'white'; const COLOR_KO: Record = { black: '흑', white: '백' }; @@ -78,8 +79,9 @@ function CountUp({ to, live }: { to: number; live: boolean }) { if (!animate) return setShown(null); let raf = 0; const t0 = performance.now(); + const len = fxMs(1000); const step = (t: number) => { - const k = Math.min(1, (t - t0) / 1000); + const k = Math.min(1, (t - t0) / len); setShown(k < 1 ? Math.floor(to * (1 - (1 - k) ** 3)) : null); if (k < 1) raf = requestAnimationFrame(step); }; @@ -184,13 +186,13 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps if (diff.size === 0) return; sfx.click(); setChanged(diff); - const t = setTimeout(() => setChanged(new Set()), 2500); + const t = setTimeout(() => setChanged(new Set()), fxMs(2500)); return () => clearTimeout(t); }, [dead]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!bubble) return; - const t = setTimeout(() => setBubble(null), 2500); + const t = setTimeout(() => setBubble(null), fxMs(2500)); return () => clearTimeout(t); }, [bubble]); diff --git a/apps/web/src/games/bang/index.tsx b/apps/web/src/games/bang/index.tsx index c6d3ec3..0b6cc7b 100644 --- a/apps/web/src/games/bang/index.tsx +++ b/apps/web/src/games/bang/index.tsx @@ -9,6 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxAnim, fxMs } from '../../lib/motion'; // ---------------------------------------------------------------- names (display names live only here, docs §12) @@ -243,13 +244,13 @@ const bangSfx = { /** 판정 card / role badge turning face up (Web Animations, no layout change). */ function flip(el: Element | null | undefined, delay = 0): void { if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return; - (el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], { + fxAnim((el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], { duration: 380, delay, easing: 'ease-out', fill: 'backwards', composite: 'add', - }); + })); } const sameFace = (a: CardFace, b: CardFace) => a.kind === b.kind && a.suit === b.suit && a.rank === b.rank; @@ -1153,7 +1154,7 @@ function useBangFx(v: BangView, me: string | null, players: Record void) => (ms > 0 ? setTimeout(f, ms) : f()); + const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f()); const toPile = (from: Element | DOMRect | null, f: CardFace | null, delay: number) => flyGhost(from, pile, { delay, ms: 420, ...(f ? faceGhost(f) : BACK_GHOST) }); const toMe = (from: Element | null, at: number) => (handSrc.current = { from, at }); const others = (p: string) => v.players.filter((x) => x.alive && x.id !== p).map((x) => x.id); diff --git a/apps/web/src/games/card-fx.tsx b/apps/web/src/games/card-fx.tsx index cf2ccf8..df23319 100644 --- a/apps/web/src/games/card-fx.tsx +++ b/apps/web/src/games/card-fx.tsx @@ -3,12 +3,14 @@ * * - Everything reacts to *view changes*, so the other players' moves animate and sound too, and skips the first * render: joining, reloading or a replay jump (the replay page remounts the board) never replays old moves. - * - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s), - * and flying copies ("ghosts") never take clicks, so nothing waits for an animation. + * - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s at + * the written lengths; the game speed scales them, lib/motion), and flying copies ("ghosts") never take clicks, so + * nothing waits for an animation. * - Respects `prefers-reduced-motion` (Web Animations are not covered by the global CSS rule, so it is checked here). * - Sounds stay in `lib/feedback` (`sfx`, `tone`, `noise`); game-specific ones live in each game folder. */ import { useLayoutEffect, useRef, useState, type ReactNode } from 'react'; +import { fxAnim, fxMs } from '../lib/motion'; export const reducedMotion = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; @@ -48,12 +50,14 @@ export function flyFrom(el: Element | null | undefined, from: Where, o: FlyOpts const dx = p.x - q.x; const dy = p.y - q.y; if (Math.abs(dx) + Math.abs(dy) < 4) return; - (el as HTMLElement).animate( - [ - { transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 }, - { transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 }, - ], - { duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' }, + fxAnim( + (el as HTMLElement).animate( + [ + { transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 }, + { transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 }, + ], + { duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' }, + ), ); } @@ -97,20 +101,22 @@ export function flyGhost(from: Where, to: Where, o: GhostOpts = {}): void { g.style.top = `${p.y - h / 2}px`; document.body.appendChild(g); const jitter = n > 1 ? (i - (n - 1) / 2) * 6 : 0; - const anim = g.animate( - [ - { transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 }, - { opacity: 1, offset: 0.15 }, - { transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 }, - { transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 }, - ], - { duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' }, + const anim = fxAnim( + g.animate( + [ + { transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 }, + { opacity: 1, offset: 0.15 }, + { transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 }, + { transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 }, + ], + { duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' }, + ), ); const done = () => g.remove(); anim.onfinish = done; anim.oncancel = done; // Safety net (a background tab may never finish the animation). - setTimeout(done, (o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70) + 1500); + setTimeout(done, fxMs((o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70)) + 1500); } } @@ -127,7 +133,7 @@ export function bump(el: Element | null | undefined, kind: 'pop' | 'shake' = 'po { transform: 'translateX(-4px) rotate(-1deg)', offset: 0.75 }, { transform: 'translateX(0px)' }, ]; - (el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' }); + fxAnim((el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' })); } // ---------------------------------------------------------------- hooks @@ -177,7 +183,7 @@ export function useBanner(): [ReactNode, (text: string, tone?: BannerTone, sub?: ensureCss(); if (timer.current) clearTimeout(timer.current); setB((old) => ({ id: (old?.id ?? 0) + 1, text, tone, sub })); - timer.current = setTimeout(() => setB(null), 1700); + timer.current = setTimeout(() => setB(null), fxMs(1700)); }; useLayoutEffect(() => () => { if (timer.current) clearTimeout(timer.current); diff --git a/apps/web/src/games/catchmind/index.tsx b/apps/web/src/games/catchmind/index.tsx index 774d2f4..c1566e7 100644 --- a/apps/web/src/games/catchmind/index.tsx +++ b/apps/web/src/games/catchmind/index.tsx @@ -11,6 +11,7 @@ import { socket } from '../../net/socket'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; // ---------------------------------------------------------------- constants (mirror packages/games/src/catchmind/types.ts) @@ -682,7 +683,7 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string sounds.ding(); haptic(60); if (popTimer.current) clearTimeout(popTimer.current); - popTimer.current = setTimeout(() => setPop(null), 1600); + popTimer.current = setTimeout(() => setPop(null), fxMs(1600)); } prevRole.current = v.role; prevTurn.current = v.turnNo; @@ -945,7 +946,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st if (mine) { setClose(true); if (closeTimer.current) clearTimeout(closeTimer.current); - closeTimer.current = setTimeout(() => setClose(false), 2200); + closeTimer.current = setTimeout(() => setClose(false), fxMs(2200)); } }, [lastId, v.chat, me]); useEffect(() => () => void (closeTimer.current && clearTimeout(closeTimer.current)), []); diff --git a/apps/web/src/games/clue/index.tsx b/apps/web/src/games/clue/index.tsx index ec99b2e..01c4776 100644 --- a/apps/web/src/games/clue/index.tsx +++ b/apps/web/src/games/clue/index.tsx @@ -28,6 +28,7 @@ import { cssEsc, flyGhost, reducedMotion } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxAnim, fxMs } from '../../lib/motion'; export const SUSPECT_COLOR: Record = { scarlet: '#dc2626', @@ -213,14 +214,14 @@ function slideFrom(el: HTMLElement | null, dx: number, dy: number, delay: number el.getAnimations().forEach((a) => a.cancel()); el.style.zIndex = '4'; const lift = Math.min(36, 10 + d * 0.15); - const anim = el.animate( + const anim = fxAnim(el.animate( [ { transform: `translate(${dx}px, ${dy}px)` }, { transform: `translate(${dx / 2}px, ${dy / 2 - lift}px) scale(1.2)`, offset: 0.5 }, { transform: 'translate(0px, 0px)' }, ], { duration: Math.min(720, 300 + d * 0.8), delay, easing: 'ease-in-out', fill: 'backwards' }, - ); + )); const done = () => (el.style.zIndex = ''); anim.onfinish = done; anim.oncancel = done; @@ -368,12 +369,12 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps) useEffect(() => { if (!banner) return; - const t = setTimeout(() => setBanner(null), 1700); + const t = setTimeout(() => setBanner(null), fxMs(1700)); return () => clearTimeout(t); }, [banner]); useEffect(() => { if (!landed) return; - const t = setTimeout(() => setLanded(null), 800); + const t = setTimeout(() => setLanded(null), fxMs(800)); return () => clearTimeout(t); }, [landed]); diff --git a/apps/web/src/games/cockroach-poker/index.tsx b/apps/web/src/games/cockroach-poker/index.tsx index eeb4364..308dc94 100644 --- a/apps/web/src/games/cockroach-poker/index.tsx +++ b/apps/web/src/games/cockroach-poker/index.tsx @@ -9,6 +9,7 @@ import { bump, flyGhost, seatEl, useBanner } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; // Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod. const KINDS: Kind[] = ['cockroach', 'bat', 'fly', 'toad', 'rat', 'scorpion', 'spider', 'stinkbug']; @@ -786,7 +787,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP if (flip) { const rv = v.lastReveal!; sfx.cardFlip(); - setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), 260); + setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), fxMs(260)); showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`); flyGhost(document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 380, ms: 480, className: 'cp-ghost' }); setTimeout(() => { @@ -794,7 +795,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP const n = v.fronts[rv.takenBy]?.counts[rv.kind] ?? 0; if (!over && n >= v.loseCount - 1) cpSfx.danger(); else cpSfx.splat(); - }, 820); + }, fxMs(820)); } if (over && !p.over && v.final) { const f = v.final; @@ -802,7 +803,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined); cpSfx.danger(); bump(seatEl(f.loser), 'shake'); - }, flip ? 1300 : 0); + }, flip ? fxMs(1300) : 0); } if (flip) { const rv = v.lastReveal!; @@ -822,12 +823,12 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP for (const s of v.said) if (s.seq > p.said) add[s.player] = PHRASE_KO[s.phrase]; sfx.pop(); setBubbles((b) => ({ ...b, ...add })); - setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), 3500); + setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), fxMs(3500)); } prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w, peek: peekKey, over }; if (slide || flip) { setFresh({ slide, flip }); - const t = setTimeout(() => setFresh({ slide: false, flip: false }), 700); + const t = setTimeout(() => setFresh({ slide: false, flip: false }), fxMs(700)); return () => clearTimeout(t); } return undefined; diff --git a/apps/web/src/games/dalmuti/index.tsx b/apps/web/src/games/dalmuti/index.tsx index 48b2db0..5a60fe6 100644 --- a/apps/web/src/games/dalmuti/index.tsx +++ b/apps/web/src/games/dalmuti/index.tsx @@ -9,6 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxAnim, fxMs } from '../../lib/motion'; const JESTER = 13; /** Same names as the rules module (kept here so the screen chunk does not pull in the rules code). */ @@ -95,7 +96,7 @@ const rememberPlay = (rank: number) => { /** Brief dim of a seat (pass). */ function dim(el: Element | null): void { if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return; - (el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' }); + fxAnim((el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' })); } const CSS = ` @@ -776,7 +777,7 @@ const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e /** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record, showBanner: ReturnType[1]) { - const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f()); + const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f()); const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`); // A new round (or the very first deal): cards go from the middle to everyone. const deal = (delay = 0) => { diff --git a/apps/web/src/games/davinci-code/index.tsx b/apps/web/src/games/davinci-code/index.tsx index 58f37cd..9905535 100644 --- a/apps/web/src/games/davinci-code/index.tsx +++ b/apps/web/src/games/davinci-code/index.tsx @@ -8,6 +8,7 @@ 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 { fxMs } from '../../lib/motion'; const COLOR_KO: Record = { black: '검은색', white: '흰색' }; const COLOR_SHORT: Record = { black: '검정', white: '흰색' }; @@ -54,7 +55,7 @@ function useTimed(): [T | null, (v: T, ms: number) => void] { const set = useCallback((v: T, ms: number) => { clearTimeout(timer.current); setVal(v); - timer.current = setTimeout(() => setVal(null), ms); + timer.current = setTimeout(() => setVal(null), fxMs(ms)); }, []); return [val, set]; } diff --git a/apps/web/src/games/dobble/index.tsx b/apps/web/src/games/dobble/index.tsx index 990b8c5..bc505bf 100644 --- a/apps/web/src/games/dobble/index.tsx +++ b/apps/web/src/games/dobble/index.tsx @@ -11,6 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { ICON_NAMES, SymbolArt } from './art'; +import { fxMs } from '../../lib/motion'; /** Taps this soon after one of the two cards changed are dropped as late (they were aimed at the previous card). */ const TAP_GRACE_MS = 250; @@ -391,17 +392,17 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps { if (!bubble) return; - const t = setTimeout(() => setBubble(null), bubble.kind === 'late' ? 1300 : 1700); + const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1700)); return () => clearTimeout(t); }, [bubble]); useEffect(() => { if (!shake) return; - const t = setTimeout(() => setShake(false), 450); + const t = setTimeout(() => setShake(false), fxMs(450)); return () => clearTimeout(t); }, [shake]); useEffect(() => { if (hitArt === null) return; - const t = setTimeout(() => setHitArt(null), 500); + const t = setTimeout(() => setHitArt(null), fxMs(500)); return () => clearTimeout(t); }, [hitArt]); diff --git a/apps/web/src/games/gostop/index.tsx b/apps/web/src/games/gostop/index.tsx index 06d960b..58687d4 100644 --- a/apps/web/src/games/gostop/index.tsx +++ b/apps/web/src/games/gostop/index.tsx @@ -11,6 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxAnim, fxMs } from '../../lib/motion'; const nick = (players: Record, id: string | null | undefined) => (id ? (players[id]?.nickname ?? '알 수 없음') : ''); const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; @@ -843,7 +844,7 @@ function rememberPlay(card: number | 'dummy'): void { myPlayRect = card === 'dummy' ? null : (document.querySelector(`.gs-hcard[data-gs-hand$="c${card}"]`)?.getBoundingClientRect() ?? null); } -const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f()); +const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f()); const byAttr = (attr: string, key: string | number): Element | null => document.querySelector(`[${attr}="${cssEsc(String(key))}"]`); const slotEl = (month: number) => (month > 0 ? byAttr('data-gs-month', month) : null); const capEl = (id: string) => byAttr('data-fx-cap', id) ?? seatEl(id); @@ -852,10 +853,10 @@ const CAP_KINDS = ['gwang', 'yeol', 'tti', 'pi'] as const; /** A card turned face up (Web Animations, composite add, so it can run together with a fly-in). */ function flipIn(el: Element | null | undefined, delay = 0): void { if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return; - (el as HTMLElement).animate( + fxAnim((el as HTMLElement).animate( [{ transform: 'perspective(600px) rotateY(90deg)' }, { transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 }, { transform: 'perspective(600px) rotateY(0deg)' }], { duration: 380, delay, easing: 'ease', fill: 'backwards', composite: 'add' }, - ); + )); } function capOwners(v: GostopView): Map { diff --git a/apps/web/src/games/halli-galli/index.tsx b/apps/web/src/games/halli-galli/index.tsx index 220d5b4..001f0cf 100644 --- a/apps/web/src/games/halli-galli/index.tsx +++ b/apps/web/src/games/halli-galli/index.tsx @@ -9,6 +9,7 @@ import { socket, useRoom } from '../../net/socket'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; const FRUITS: Fruit[] = ['strawberry', 'banana', 'lime', 'plum']; const FRUIT_KO: Record = { strawberry: '딸기', banana: '바나나', lime: '라임', plum: '자두' }; @@ -536,19 +537,19 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps { if (!ghosts.length) return; - const t = setTimeout(() => setGhosts([]), 1000); + const t = setTimeout(() => setGhosts([]), fxMs(1000)); return () => clearTimeout(t); }, [ghosts]); useEffect(() => { if (!shake) return; - const t = setTimeout(() => setShake(null), 500); + const t = setTimeout(() => setShake(null), fxMs(500)); return () => clearTimeout(t); }, [shake]); useEffect(() => { if (!bubble) return; - const t = setTimeout(() => setBubble(null), bubble.kind === 'late' ? 1300 : 1900); + const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1900)); return () => clearTimeout(t); }, [bubble]); diff --git a/apps/web/src/games/janggi/index.tsx b/apps/web/src/games/janggi/index.tsx index ca2da83..1398487 100644 --- a/apps/web/src/games/janggi/index.tsx +++ b/apps/web/src/games/janggi/index.tsx @@ -11,6 +11,7 @@ import { addedPieces, janggiCues, janggiMotion } from './fx'; import { helpNow } from './help'; import { nopeSound, pickSound, playJanggi, setupSound } from './sound'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; const SIDE_KO: Record = { cho: '초', han: '한' }; const INK: Record = { cho: '#1d4ed8', han: '#c0262d' }; @@ -246,7 +247,7 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps { if (!bubble) return; - const t = setTimeout(() => setBubble(null), 1600); + const t = setTimeout(() => setBubble(null), fxMs(1600)); return () => clearTimeout(t); }, [bubble]); diff --git a/apps/web/src/games/las-vegas/index.tsx b/apps/web/src/games/las-vegas/index.tsx index 8610201..88695a4 100644 --- a/apps/web/src/games/las-vegas/index.tsx +++ b/apps/web/src/games/las-vegas/index.tsx @@ -8,6 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; const ROLL_MS = 650; const HOUSE = 'house'; @@ -308,7 +309,7 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps { setRolling(false); setFlick(null); - }, ROLL_MS); + }, fxMs(ROLL_MS)); return () => { clearInterval(t); clearTimeout(end); @@ -382,17 +383,17 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps { if (!drop) return; - const t = setTimeout(() => setDrop(null), 900); + const t = setTimeout(() => setDrop(null), fxMs(900)); return () => clearTimeout(t); }, [drop]); useEffect(() => { if (dealt === null) return; - const t = setTimeout(() => setDealt(null), 1500); + const t = setTimeout(() => setDealt(null), fxMs(1500)); return () => clearTimeout(t); }, [dealt]); useEffect(() => { if (!banner) return; - const t = setTimeout(() => setBanner(null), 1700); + const t = setTimeout(() => setBanner(null), fxMs(1700)); return () => clearTimeout(t); }, [banner]); diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index 208d232..30b2824 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -19,6 +19,7 @@ import { useChatOutbox, useTypingSignal } from '../../lib/chat-input'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; type Kind = LiarView['phase']['kind']; @@ -714,7 +715,7 @@ function useLiarFx(v: LiarView, me: string | null, players: Record e.t !== 'phase' && e.t !== 'left')) { timers.current.forEach(clearTimeout); timers.current = []; - const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, ms)) : f()); + const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f()); const name = (id: string) => `${nick(players, id)}님`; let t = 0; const vote = fresh.find((e) => e.t === 'vote'); diff --git a/apps/web/src/games/mafia/index.tsx b/apps/web/src/games/mafia/index.tsx index 375fe9a..a3a5711 100644 --- a/apps/web/src/games/mafia/index.tsx +++ b/apps/web/src/games/mafia/index.tsx @@ -19,6 +19,7 @@ import { useChatOutbox, useTypingSignal } from '../../lib/chat-input'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; // ---------------------------------------------------------------- names (original names only, docs §12) @@ -820,7 +821,7 @@ function useMafiaFx(v: MafiaView, players: Record, showBanne if (fresh.length) { timers.current.forEach(clearTimeout); timers.current = []; - const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, ms)) : f()); + const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f()); const start = isNight(p) && !isNight(v) ? 900 : 0; if (dying.length || saved.length) { later(start, () => setTileFx({ dying, saved })); @@ -882,7 +883,7 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps setSky(null), 1800); + const t = setTimeout(() => setSky(null), fxMs(1800)); return () => clearTimeout(t); }, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/apps/web/src/games/magical-athlete/index.tsx b/apps/web/src/games/magical-athlete/index.tsx index 52b1724..88156a6 100644 --- a/apps/web/src/games/magical-athlete/index.tsx +++ b/apps/web/src/games/magical-athlete/index.tsx @@ -10,6 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { itemsOf, type Item } from './replay'; +import { fxMs } from '../../lib/motion'; const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4']; @@ -428,7 +429,7 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) { const t = setTimeout(() => { timers.current.delete(t); fn(); - }, ms); + }, fxMs(ms)); timers.current.add(t); }; useEffect(() => { @@ -600,7 +601,7 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) { pump(); } : stepWalk, - last ? ms + (c.jump ? 60 : 120) : ms, + fxMs(last ? ms + (c.jump ? 60 : 120) : ms), ); }; @@ -619,7 +620,7 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) { w.timer = setTimeout(() => { w.timer = null; pump(); - }, wait); + }, fxMs(wait)); return; } } diff --git a/apps/web/src/games/mahjong/index.tsx b/apps/web/src/games/mahjong/index.tsx index e059532..84fae35 100644 --- a/apps/web/src/games/mahjong/index.tsx +++ b/apps/web/src/games/mahjong/index.tsx @@ -9,6 +9,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { MAHJONG_TILE_CREDIT, Tile, tileName, tileOrder, tileShort } from './Tile'; +import { fxMs } from '../../lib/motion'; const WIND = ['동', '남', '서', '북']; const POS_KO = ['나', '오른쪽', '맞은편', '왼쪽']; @@ -1120,13 +1121,13 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm }, [hand, v.phase]); useEffect(() => { if (!dealing) return; - const t = setTimeout(() => setDealing(false), 900); + const t = setTimeout(() => setDealing(false), fxMs(900)); return () => clearTimeout(t); }, [dealing]); useEffect(() => { if (!banner) return; - const t = setTimeout(() => setBanner((b) => (b && b.key === banner.key ? null : b)), 1700); + const t = setTimeout(() => setBanner((b) => (b && b.key === banner.key ? null : b)), fxMs(1700)); return () => clearTimeout(t); }, [banner]); @@ -1140,7 +1141,7 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm }, [mine]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!callout) return; - const t = setTimeout(() => setCallout((x) => (x && x.seq === callout.seq ? null : x)), 1300); + const t = setTimeout(() => setCallout((x) => (x && x.seq === callout.seq ? null : x)), fxMs(1300)); return () => clearTimeout(t); }, [callout]); useEffect(() => { diff --git a/apps/web/src/games/marble/index.tsx b/apps/web/src/games/marble/index.tsx index 9a5f19d..4ba66eb 100644 --- a/apps/web/src/games/marble/index.tsx +++ b/apps/web/src/games/marble/index.tsx @@ -10,6 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { newEvents, toSegments, type Seg } from './events'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; type GameEvent = MarbleView['log'][number]; @@ -391,7 +392,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps { timers.current.delete(t); fn(); - }, ms); + }, fxMs(ms)); timers.current.add(t); }; useEffect(() => { @@ -526,7 +527,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps x + 1); - w.timer = setTimeout(step, seg.walk ? stepMs(seg) : 160); + w.timer = setTimeout(step, fxMs(seg.walk ? stepMs(seg) : 160)); return; } }; @@ -555,7 +556,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps setRolling((x) => (x === seq ? null : x)), ROLL_MS); - walker.current.hold = Date.now() + ROLL_MS; + walker.current.hold = Date.now() + fxMs(ROLL_MS); } const thirdDouble = added?.some((e) => e.type === 'toIsland' && e.why === 'doubles'); if (r.double && !thirdDouble) @@ -1188,7 +1189,7 @@ function PlayerCard({ p, v, me, players, deadline }: { p: MarblePlayerView; v: M prev.current = p.cash; if (d === 0) return; setDelta({ n: d, k: Date.now() }); - const t = setTimeout(() => setDelta(null), 1600); + const t = setTimeout(() => setDelta(null), fxMs(1600)); return () => clearTimeout(t); }, [p.cash]); const status: string[] = []; diff --git a/apps/web/src/games/ninety-nine/index.tsx b/apps/web/src/games/ninety-nine/index.tsx index 0787c27..7cb1a0b 100644 --- a/apps/web/src/games/ninety-nine/index.tsx +++ b/apps/web/src/games/ninety-nine/index.tsx @@ -11,6 +11,7 @@ import { useSeatRows } from '../../lib/seat-rows'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow, resolvedHandSize } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; const MODE_KO: Record = { 'kr-product': '전용 카드', classic: '트럼프 카드' }; const SUIT_KO: Record = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' }; @@ -55,8 +56,9 @@ function useCountUp(target: number): number { } let raf = 0; const t0 = performance.now(); + const len = fxMs(420); const step = (t: number) => { - const k = Math.min(1, (t - t0) / 420); + const k = Math.min(1, (t - t0) / len); setShown(Math.round(start + (target - start) * (1 - (1 - k) * (1 - k)))); if (k < 1) raf = requestAnimationFrame(step); }; @@ -635,7 +637,7 @@ const nnLogKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`; /** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record, showBanner: ReturnType[1]) { - const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f()); + const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f()); const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`); const dealAll = (delay: number) => { const deck = fxEl('nn-deck'); diff --git a/apps/web/src/games/old-maid/index.tsx b/apps/web/src/games/old-maid/index.tsx index fb1a85b..4ed2e9d 100644 --- a/apps/web/src/games/old-maid/index.tsx +++ b/apps/web/src/games/old-maid/index.tsx @@ -12,6 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import { fanCard, fanLayout, type FanLayout } from './fan'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxAnim, fxMs } from '../../lib/motion'; // Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod. const JOKER = 'X1'; @@ -72,7 +73,7 @@ function liftFly(from: DOMRect, to: Element | null | undefined, delay: number): const dy = b.top + b.height / 2 - (from.top + from.height / 2); // Onto a card in my hand: shrink to its size. Onto a seat: a small card. const s = b.width <= 120 ? Math.max(0.4, Math.min(1.2, b.width / from.width)) : 0.6; - const anim = g.animate( + const anim = fxAnim(g.animate( [ { transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 }, { transform: 'translate(0px, -28px) scale(1.08) rotate(-4deg)', opacity: 1, offset: 0.3 }, @@ -80,11 +81,11 @@ function liftFly(from: DOMRect, to: Element | null | undefined, delay: number): { transform: `translate(${dx}px, ${dy}px) scale(${s}) rotate(0deg)`, opacity: 0 }, ], { duration: LIFT_MS, delay, easing: 'cubic-bezier(.35,.6,.3,1)', fill: 'both' }, - ); + )); const done = () => g.remove(); anim.onfinish = done; anim.oncancel = done; - setTimeout(done, LIFT_MS + delay + 1500); + setTimeout(done, fxMs(LIFT_MS + delay) + 1500); return true; } @@ -92,8 +93,8 @@ function liftFly(from: DOMRect, to: Element | null | undefined, delay: number): function reveal(el: Element, delay: number): void { const h = el as HTMLElement; if (typeof h.animate !== 'function') return; - h.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 120, delay, fill: 'backwards' }); - h.animate([{ transform: 'scale(.8)' }, { transform: 'scale(1.1)', offset: 0.6 }, { transform: 'scale(1)' }], { duration: 280, delay, easing: 'ease-out', composite: 'add' }); + fxAnim(h.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 120, delay, fill: 'backwards' })); + fxAnim(h.animate([{ transform: 'scale(.8)' }, { transform: 'scale(1.1)', offset: 0.6 }, { transform: 'scale(1)' }], { duration: 280, delay, easing: 'ease-out', composite: 'add' })); } const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; @@ -618,10 +619,10 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: const dx = a[0] - b[0]; const dy = a[1] - b[1]; if (Math.abs(dx) + Math.abs(dy) < 2 || typeof c.animate !== 'function') continue; - c.animate( + fxAnim(c.animate( [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: `translate(${dx / 2}px, ${dy / 2 - 18}px)`, offset: 0.45 }, { transform: 'translate(0px, 0px)' }], { duration: 480, delay: n++ * 14, easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'backwards', composite: 'add' }, - ); + )); } }, [order, width, l.wrap]); return ( @@ -729,12 +730,12 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm if (msgs.length) setAnnounce(msgs.join(' ')); if (Object.keys(bub).length) { setBubbles((b) => ({ ...b, ...bub })); - setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), 2500); + setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500)); } prev.current = { logCount: v.logCount, hand, turn: v.turn }; if (shuffled) { setRiffle(true); - const t = setTimeout(() => setRiffle(false), 1000); + const t = setTimeout(() => setRiffle(false), fxMs(1000)); return () => clearTimeout(t); } return undefined; @@ -767,7 +768,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record void) => (ms ? setTimeout(f, ms) : f()); + const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f()); /** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */ const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p)); const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i })); @@ -858,7 +859,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record { bump(seatEl(thief), 'shake'); bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop'); - }, 200); + }, fxMs(200)); }); const started = useRef(false); useLayoutEffect(() => { @@ -867,7 +868,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record sfx.deal(8, 60), 300); + setTimeout(() => sfx.deal(8, 60), fxMs(300)); // Next frame: the card rows lay themselves out once their width is known (useWidth), so measure after that. requestAnimationFrame(() => { const table = fxEl('om-table'); diff --git a/apps/web/src/games/omok/index.tsx b/apps/web/src/games/omok/index.tsx index c8e1039..5ccf462 100644 --- a/apps/web/src/games/omok/index.tsx +++ b/apps/web/src/games/omok/index.tsx @@ -10,6 +10,7 @@ import { bump, useBanner } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; type Color = 'black' | 'white'; const COLOR_KO: Record = { black: '흑', white: '백' }; @@ -59,7 +60,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps) const [banner, showBanner] = useBanner(); useEffect(() => { if (!refused) return; - const t = setTimeout(() => setRefused(null), 950); + const t = setTimeout(() => setRefused(null), fxMs(950)); return () => clearTimeout(t); }, [refused]); diff --git a/apps/web/src/games/one-card/fx.tsx b/apps/web/src/games/one-card/fx.tsx index 1f26e19..ffaae7c 100644 --- a/apps/web/src/games/one-card/fx.tsx +++ b/apps/web/src/games/one-card/fx.tsx @@ -5,6 +5,7 @@ import { useLayoutEffect, useRef, useState, type RefObject } from 'react'; import type { CardFace, LogEntry, OneCardView } from '@bg/games/one-card'; import { haptic, noise, sfx, tone } from '../../lib/feedback'; +import { fxAnim, fxMs } from '../../lib/motion'; export interface Banner { key: number; @@ -128,14 +129,14 @@ function flyCards(root: HTMLElement, layer: HTMLElement, to: string, n: number, el.remove(); continue; } - const anim = el.animate( + const anim = fxAnim(el.animate( [ { transform: `translate(${x0}px, ${y0}px) rotate(0deg) scale(1)`, opacity: 1 }, { transform: `translate(${(x0 + x1) / 2}px, ${Math.min(y0, y1) - lift}px) rotate(${i % 2 ? 160 : -160}deg) scale(1.08)`, opacity: 1, offset: 0.55 }, { transform: `translate(${x1}px, ${y1}px) rotate(${i % 2 ? 350 : -350}deg) scale(0.7)`, opacity: 0.85 }, ], { duration: FLY_MS, delay: delay0 + i * gap, easing: 'cubic-bezier(.3,.6,.35,1)', fill: 'both' }, - ); + )); anim.onfinish = () => el.remove(); anim.oncancel = () => el.remove(); } @@ -147,7 +148,7 @@ function hitTable(root: HTMLElement, n: number, delay: number): void { const table = root.querySelector('.oc-table'); if (!table || reduced() || typeof table.animate !== 'function') return; const d = Math.min(14, 4 + n); - table.animate( + fxAnim(table.animate( [ { transform: 'none' }, { transform: `translateX(${-d}px) rotate(-1deg)`, offset: 0.15 }, @@ -157,11 +158,11 @@ function hitTable(root: HTMLElement, n: number, delay: number): void { { transform: 'none' }, ], { duration: 520, delay, easing: 'ease-out' }, - ); - table.animate( + )); + fxAnim(table.animate( [{ boxShadow: '0 0 0 0 rgba(239,68,68,0), inset 0 0 0 0 rgba(239,68,68,0)' }, { boxShadow: '0 0 30px 10px rgba(239,68,68,.85), inset 0 0 70px 20px rgba(239,68,68,.6)', offset: 0.3 }, { boxShadow: '0 0 0 0 rgba(239,68,68,0), inset 0 0 0 0 rgba(239,68,68,0)' }], { duration: 700, delay }, - ); + )); } interface Ctx { @@ -342,7 +343,7 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) })); for (const b of banners) { - const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), 1700); + const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700)); timers.current.push(t); } } diff --git a/apps/web/src/games/one-card/index.tsx b/apps/web/src/games/one-card/index.tsx index e58ceba..94adf2e 100644 --- a/apps/web/src/games/one-card/index.tsx +++ b/apps/web/src/games/one-card/index.tsx @@ -12,6 +12,7 @@ import { helpNow } from './help'; import { quickStart } from './quick'; import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard'; import { FX_CSS, useOneCardFx, type Fx } from './fx'; +import { fxMs } from '../../lib/motion'; const SUITS: Suit[] = ['S', 'H', 'D', 'C']; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; @@ -213,7 +214,7 @@ function AttackCount({ n, uno }: { n: number; uno: boolean }) { tone(320 + k * 45, 55, 'square', 0.035); if (k >= n) window.clearInterval(id); }, - Math.max(45, Math.min(110, 420 / (n - from))), + fxMs(Math.max(45, Math.min(110, 420 / (n - from)))), ); return () => window.clearInterval(id); }, [n]); diff --git a/apps/web/src/games/poker/index.tsx b/apps/web/src/games/poker/index.tsx index 5207c82..03349b2 100644 --- a/apps/web/src/games/poker/index.tsx +++ b/apps/web/src/games/poker/index.tsx @@ -11,6 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxAnim, fxMs } from '../../lib/motion'; const MODE_KO: Record = { holdem: '텍사스 홀덤', @@ -308,19 +309,19 @@ const pokerSfx = { declare: (delay = 0) => tone(660, 120, 'triangle', 0.1, delay, { slideTo: 990 }), }; -const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f()); +const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f()); /** Card turned over in place (WAAPI so React's own style/transform stays). */ function flipIn(el: Element | null | undefined, delay = 0): void { if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return; - (el as HTMLElement).animate( + fxAnim((el as HTMLElement).animate( [ { transform: 'perspective(600px) rotateY(90deg)' }, { transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 }, { transform: 'perspective(600px) rotateY(0deg)' }, ], { duration: 420, delay, easing: 'ease', fill: 'backwards', composite: 'add' }, - ); + )); } /** @@ -337,19 +338,19 @@ function turnOver(el: Element | null | undefined, delay = 0): void { back.setAttribute('aria-hidden', 'true'); Object.assign(back.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` }); document.body.appendChild(back); - const a = back.animate([{ transform: 'perspective(600px) rotateY(0deg)' }, { transform: 'perspective(600px) rotateY(-90deg)' }], { duration: half, delay, easing: 'ease-in', fill: 'both' }); + const a = fxAnim(back.animate([{ transform: 'perspective(600px) rotateY(0deg)' }, { transform: 'perspective(600px) rotateY(-90deg)' }], { duration: half, delay, easing: 'ease-in', fill: 'both' })); const done = () => back.remove(); a.onfinish = done; a.oncancel = done; - setTimeout(done, delay + half + 1500); - (el as HTMLElement).animate( + setTimeout(done, fxMs(delay + half) + 1500); + fxAnim((el as HTMLElement).animate( [ { transform: 'perspective(600px) rotateY(90deg)' }, { transform: 'perspective(600px) rotateY(-12deg)', offset: 0.65 }, { transform: 'perspective(600px) rotateY(0deg)' }, ], { duration: 300, delay: delay + half, easing: 'ease-out', fill: 'backwards', composite: 'add' }, - ); + )); } /** The card elements of a seat on the table (forehead, hole, choice, up — same order as SeatCards). */ diff --git a/apps/web/src/games/rummikub/index.tsx b/apps/web/src/games/rummikub/index.tsx index c698bca..f5091dd 100644 --- a/apps/web/src/games/rummikub/index.tsx +++ b/apps/web/src/games/rummikub/index.tsx @@ -11,6 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useNewEntries import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; @@ -52,7 +53,7 @@ function useTimed(): [T | null, (v: T, ms: number) => void] { const set = useCallback((v: T, ms: number) => { clearTimeout(timer.current); setVal(v); - timer.current = setTimeout(() => setVal(null), ms); + timer.current = setTimeout(() => setVal(null), fxMs(ms)); }, []); return [val, set]; } @@ -372,7 +373,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr const iWon = top.includes(me ?? ''); const text = iWon ? '승리!' : top.length ? `${top.map((p) => nick(players, p)).join(', ')}님 승리` : '게임 끝'; clearTimeout(winTimer.current); - winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? 1500 : 0); + winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? fxMs(1500) : 0); } }, [v]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/apps/web/src/games/seotda/board.tsx b/apps/web/src/games/seotda/board.tsx index 971e6c5..4ef9c09 100644 --- a/apps/web/src/games/seotda/board.tsx +++ b/apps/web/src/games/seotda/board.tsx @@ -13,6 +13,7 @@ import { HwatuCard } from '../../components/cards/HwatuCard'; import { haptic, sfx, sounds } from '../../lib/feedback'; import { usePhone } from '../../lib/media'; import type { BoardProps } from '../types'; +import { fxMs } from '../../lib/motion'; export const BET_KO: Record = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' }; /** Number keys like 한게임 섯다 (콜 7, 다이 8, 삥 4, 체크 5, 따당 1, 하프 0); 쿼터 2 and 풀 9 are ours. */ @@ -408,7 +409,7 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb const add: Fly[] = Array.from({ length: n }, (_, i) => ({ id: ++flyId.current, sx: a.x + (i % 2 ? 6 : -6), sy: a.y, dx: b.x - a.x, dy: b.y - a.y, d: i * 70 })); setFlies((f) => [...f, ...add]); const ids = new Set(add.map((x) => x.id)); - setTimeout(() => setFlies((f) => f.filter((x) => !ids.has(x.id))), 700 + n * 70); + setTimeout(() => setFlies((f) => f.filter((x) => !ids.has(x.id))), fxMs(700 + n * 70)); }; useEffect(() => { @@ -435,7 +436,7 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb sfx.chips(n); launch(e.p, 'pot', n); } - }, i * 220); + }, fxMs(i * 220)); }); // Result: reveal, payout, banner. if (v.handPhase === 'handEnd' && prev.phase !== 'handEnd') { @@ -456,13 +457,13 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb sounds.win(); haptic([40, 30, 80]); } else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose(); - }, v.showdown ? 450 : 150); + }, fxMs(v.showdown ? 450 : 150)); } }); // every render: cheap comparisons against the refs useEffect(() => { if (!banner) return undefined; - const t = setTimeout(() => setBanner(null), 1700); + const t = setTimeout(() => setBanner(null), fxMs(1700)); return () => clearTimeout(t); }, [banner]); diff --git a/apps/web/src/games/splendor/index.tsx b/apps/web/src/games/splendor/index.tsx index 64b9e78..2859d29 100644 --- a/apps/web/src/games/splendor/index.tsx +++ b/apps/web/src/games/splendor/index.tsx @@ -22,6 +22,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, useBanner, useChange, useNewEntr import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; // Type-only imports above keep the rules module out of the bundle; the few constants live here. const COLORS: Color[] = ['W', 'U', 'G', 'R', 'K']; @@ -438,7 +439,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board useEffect(() => { if (!shake) return; - const t = setTimeout(() => setShake(null), 400); + const t = setTimeout(() => setShake(null), fxMs(400)); return () => clearTimeout(t); }, [shake]); @@ -946,7 +947,7 @@ function gemSpot(p: string, c: TokenColor, me: string | null): Element | null { * previous view). Nothing on the first render (join, reload, replay jump). */ function useSplendorFx(v: SplendorView, me: string | null, players: Record, showBanner: ReturnType[1]) { - const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f()); + const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f()); // Board of the previous view (slot key → card id) to know where a bought / reserved card was. const prevBoard = useRef | null>(null); // Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still diff --git a/apps/web/src/games/uno/index.tsx b/apps/web/src/games/uno/index.tsx index 7904bb3..4c607fb 100644 --- a/apps/web/src/games/uno/index.tsx +++ b/apps/web/src/games/uno/index.tsx @@ -11,6 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; @@ -705,7 +706,7 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps, showBanner: ReturnType[1]) { - const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f()); + const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f()); useNewEntries(v.log, logKey, (fresh) => { let t = 0; for (const e of fresh) { @@ -781,7 +782,7 @@ function useUnoFx(v: UnoView, me: string | null, players: Record { const deck = fxEl('uno-deck'); sfx.shuffle(); - setTimeout(() => sfx.deal(7, 60), 300); + setTimeout(() => sfx.deal(7, 60), fxMs(300)); if (myHand) document.querySelectorAll('.un-hand .un-card').forEach((el, i) => flyFrom(el, deck, { delay: 280 + i * 60, rotate: 10 })); for (const s of v.seats) if (s.id !== me && !s.left) flyGhost(deck, seatEl(s.id), { count: 3, gap: 90, delay: 280 }); }; diff --git a/apps/web/src/games/yacht/index.tsx b/apps/web/src/games/yacht/index.tsx index d008600..9f303a7 100644 --- a/apps/web/src/games/yacht/index.tsx +++ b/apps/web/src/games/yacht/index.tsx @@ -8,6 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { fxMs } from '../../lib/motion'; // The client draws from the view only; names and hints live here so the rules module isn't bundled. const NAME: Record = { @@ -245,7 +246,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro const end = setTimeout(() => { setAnim(null); setFlick(null); - }, ROLL_MS); + }, fxMs(ROLL_MS)); return () => { clearInterval(t); clearTimeout(end); @@ -254,7 +255,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro useEffect(() => { if (!flash) return; - const t = setTimeout(() => setFlash(null), 1600); + const t = setTimeout(() => setFlash(null), fxMs(1600)); return () => clearTimeout(t); }, [flash]); diff --git a/apps/web/src/games/yut/index.tsx b/apps/web/src/games/yut/index.tsx index 217d5d3..a031b52 100644 --- a/apps/web/src/games/yut/index.tsx +++ b/apps/web/src/games/yut/index.tsx @@ -10,6 +10,7 @@ import { helpNow } from './help'; import { houseRules, optionsSummary } from './house-rules'; import { quickStart } from './quick'; import { HOP_MS, moveSound, throwSound } from './sound'; +import { fxMs } from '../../lib/motion'; type From = number | 'home'; /** A source the player can pick: a stack (`"7"`, or `"7#2"` when stacks stand apart on 7) or the waiting pieces (`"home"`). */ @@ -217,7 +218,7 @@ function Sticks({ view: v, players }: { view: YutView; players: Record setTossing(false), 820); + const t = setTimeout(() => setTossing(false), fxMs(820)); return () => clearTimeout(t); }, [lt?.no]); // eslint-disable-line react-hooks/exhaustive-deps const sticks = lt?.sticks ?? [false, true, false, true]; @@ -338,22 +339,22 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps { if (!anim) return; if (anim.i >= anim.pts.length - 1) { - const t = setTimeout(() => setAnim(null), 120); + const t = setTimeout(() => setAnim(null), fxMs(120)); return () => clearTimeout(t); } - const t = setTimeout(() => setAnim((a) => (a && a.no === anim.no ? { ...a, i: a.i + 1 } : a)), 170); + const t = setTimeout(() => setAnim((a) => (a && a.no === anim.no ? { ...a, i: a.i + 1 } : a)), fxMs(170)); return () => clearTimeout(t); }, [anim]); useEffect(() => { if (!landing) return; - const t = setTimeout(() => setLanding((l) => (l && l.no === landing.no ? null : l)), landing.delayMs + 700); + const t = setTimeout(() => setLanding((l) => (l && l.no === landing.no ? null : l)), fxMs(landing.delayMs + 700)); return () => clearTimeout(t); }, [landing]); useEffect(() => { if (!flash) return; - const t = setTimeout(() => setFlash(null), 1100); + const t = setTimeout(() => setFlash(null), fxMs(1100)); return () => clearTimeout(t); }, [flash]); diff --git a/apps/web/src/lib/motion.test.ts b/apps/web/src/lib/motion.test.ts new file mode 100644 index 0000000..a3b87c0 --- /dev/null +++ b/apps/web/src/lib/motion.test.ts @@ -0,0 +1,33 @@ +import { afterEach, expect, test } from 'bun:test'; +import { BASE_SLOWDOWN, fxAnim, fxMs, gameSpeed, motionScale, setGameSpeed } from './motion'; + +afterEach(() => setGameSpeed(1)); + +test('speed ×1 is a little slower than the written lengths; the admin speed divides them', () => { + expect(BASE_SLOWDOWN).toBe(1.5); + expect(fxMs(1000)).toBe(1500); + setGameSpeed(2); + expect(fxMs(1000)).toBe(750); + setGameSpeed(1 / 16); + expect(fxMs(1000)).toBe(24_000); + setGameSpeed(16); + expect(fxMs(1600)).toBe(150); +}); + +test('out-of-range or broken speeds are clamped / ignored', () => { + setGameSpeed(100); + expect(gameSpeed()).toBe(16); + setGameSpeed(0.001); + expect(gameSpeed()).toBe(1 / 16); + setGameSpeed('fast'); + expect(gameSpeed()).toBe(1); + setGameSpeed(undefined); + expect(motionScale()).toBe(1.5); +}); + +test('fxAnim plays a Web Animation at the game speed (delay and duration together)', () => { + const anim = { playbackRate: 1 } as Animation; + setGameSpeed(3); + expect(fxAnim(anim).playbackRate).toBe(2); + expect(fxAnim(null)).toBeNull(); +}); diff --git a/apps/web/src/lib/motion.ts b/apps/web/src/lib/motion.ts new file mode 100644 index 0000000..daa7464 --- /dev/null +++ b/apps/web/src/lib/motion.ts @@ -0,0 +1,79 @@ +/** + * Game speed on screen (admin setting `gameSpeed`, docs/14-admin.md §5; docs/07-ui-ux.md). + * Everything that moves in a game takes `motionScale()` times the length written in the code: + * - CSS animations and transitions inside the game screen: `useMotionScope` sets their `playbackRate` + * (delays and staggers included), so game CSS keeps its plain durations. + * - Web Animations (`el.animate(...)`): wrap them in `fxAnim` (flying copies live on , outside the scope). + * - Timers that stage effects (how long a banner stays, the next step of a sequence, removing a flying copy): `fxMs`. + * Real-time things (turn timers, `[role="timer"]` bars, the drawing stream) and the chat are not scaled. + */ +import { useEffect, type RefObject } from 'react'; +import { clampGameSpeed, GAME_SPEED_DEFAULT } from '@bg/shared/lite'; + +/** At speed ×1 everything takes this much longer than the durations written in the code (2026-10-14: a bit slower). */ +export const BASE_SLOWDOWN = 1.5; + +/** Animations inside these are left alone (real time / not part of the game). */ +const SKIP = '.chat-panel, [role="timer"]'; + +let speed = GAME_SPEED_DEFAULT; +const listeners = new Set<() => void>(); + +/** Sets the speed from /api/config or the room view (out-of-range values are clamped). */ +export function setGameSpeed(x: unknown): void { + const v = clampGameSpeed(x); + if (v === speed) return; + speed = v; + for (const f of listeners) f(); +} + +export const gameSpeed = (): number => speed; + +/** How many times longer than written: `BASE_SLOWDOWN / speed`. */ +export const motionScale = (): number => BASE_SLOWDOWN / speed; + +/** A staging delay / duration in ms at the current game speed. */ +export const fxMs = (ms: number): number => Math.round(ms * motionScale()); + +/** Plays a Web Animation at the current game speed (its duration, delay and staggers all scale). */ +export function fxAnim(anim: T): T { + if (anim) anim.playbackRate = 1 / motionScale(); + return anim; +} + +function targetOf(a: Animation): Element | null { + const t = a.effect instanceof KeyframeEffect ? a.effect.target : null; + return t instanceof Element ? t : null; +} + +/** Sets the playback rate of every animation under `root` (except chat / timers). Exported for tests. */ +export function applyMotion(root: Element): void { + const rate = 1 / motionScale(); + for (const a of root.getAnimations({ subtree: true })) { + if (a.playbackRate === rate) continue; + const t = targetOf(a); + if (t && t.closest(SKIP)) continue; + a.playbackRate = rate; + } +} + +/** + * Keeps the CSS animations and transitions under `ref` (the game screen) at the game speed. Game animations start + * from DOM changes (a new element, a class, a style); the mutation observer runs before the next frame, so a new + * animation never plays a frame at the wrong speed. + */ +export function useMotionScope(ref: RefObject): void { + useEffect(() => { + const root = ref.current; + if (!root || typeof MutationObserver === 'undefined' || typeof root.getAnimations !== 'function') return; + const run = () => applyMotion(root); + const obs = new MutationObserver(run); + obs.observe(root, { subtree: true, childList: true, attributes: true }); + listeners.add(run); + run(); + return () => { + obs.disconnect(); + listeners.delete(run); + }; + }, [ref]); +} diff --git a/apps/web/src/net/api.ts b/apps/web/src/net/api.ts index e25170f..98e2283 100644 --- a/apps/web/src/net/api.ts +++ b/apps/web/src/net/api.ts @@ -67,7 +67,7 @@ export interface RoomPreview { export const api = { config: () => - call<{ discord: boolean; catalog: (CatalogEntry & { notice?: string })[]; siteName: string; announcement: string; maintenance: boolean }>('GET', '/api/config'), + call<{ discord: boolean; catalog: (CatalogEntry & { notice?: string })[]; siteName: string; announcement: string; maintenance: boolean; gameSpeed?: number }>('GET', '/api/config'), me: () => call('GET', '/api/me'), guest: (nickname: string) => call<{ me: PublicUser }>('POST', '/api/auth/guest', { nickname }), updateMe: (patch: { nickname?: string; useAvatar?: boolean; settings?: Settings }) => call<{ me: PublicUser }>('PATCH', '/api/me', patch), diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index ddece7e..fe8a610 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -6,6 +6,7 @@ import { create } from 'zustand'; import { PROTOCOL, type GameResultView, type PublicUser, type RoomView, type ServerMessage } from '@bg/shared/lite'; import { toast } from '../store/toast'; import { markOutdated, noteServerBuild } from '../lib/update'; +import { setGameSpeed } from '../lib/motion'; export type ConnStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'replaced' | 'offline'; @@ -277,6 +278,7 @@ class GameSocket { } case 'room': if (m.seq >= st.roomSeq || m.room.code !== st.room?.code) { + if (m.room.gameSpeed !== undefined) setGameSpeed(m.room.gameSpeed); useRoom.setState({ room: m.room, roomSeq: m.seq, joinError: null }); if (m.room.status === 'playing' && st.result) useRoom.setState({ result: null }); } diff --git a/apps/web/src/pages/ReplayPage.tsx b/apps/web/src/pages/ReplayPage.tsx index a270f36..f246e68 100644 --- a/apps/web/src/pages/ReplayPage.tsx +++ b/apps/web/src/pages/ReplayPage.tsx @@ -12,6 +12,7 @@ import { useSession } from '../store/session'; import { loadGameUI } from '../games/registry'; import type { GameUI } from '../games/types'; import { useWide } from '../lib/media'; +import { fxMs, useMotionScope } from '../lib/motion'; const STEP_MS = 1000; @@ -106,6 +107,8 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: () // The board is remounted on jumps (처음/끝/slider) so its move animations and sounds only follow single steps. const [mount, setMount] = useState(0); const at = useRef(0); + const layout = useRef(null); + useMotionScope(layout); const go = (n: number, keepPlaying = false) => { const t = Math.max(0, Math.min(last, n)); @@ -120,7 +123,7 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: () useEffect(() => { if (!playing) return; if (i >= last) return setPlaying(false); - const t = setTimeout(() => goRef.current(i + 1, true), STEP_MS); + const t = setTimeout(() => goRef.current(i + 1, true), fxMs(STEP_MS)); return () => clearTimeout(t); }, [playing, i, last]); @@ -236,7 +239,7 @@ function Player({ data, ui, onBack }: { data: ReplayData; ui: GameUI; onBack: () {when} -
+
{!wide && status}
diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index 50cf15d..07f75bc 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -19,6 +19,7 @@ import { VolumeControl } from '../components/VolumeControl'; import { useWide } from '../lib/media'; import { GameHelp } from '../components/GameHelp'; import { PlayerName } from '../components/PlayerCard'; +import { useMotionScope } from '../lib/motion'; export default function RoomPage() { const { code = '' } = useParams(); @@ -640,6 +641,8 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui const game = useRoom((s) => s.game)!; const tapConfirm = useSession((s) => s.settings.tapConfirm); const wide = useWide(); + const layout = useRef(null); + useMotionScope(layout); const myTurn = ui.isMyTurn(game.view, me.id); const isPlayer = room.seats.some((s) => s?.user.id === me.id) && game.active !== undefined; const props = { @@ -692,7 +695,7 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui ); return ( -
+
{!wide && statusRow} diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx index 77f3b9c..585856a 100644 --- a/apps/web/src/pages/admin/AdminApp.tsx +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -1,7 +1,7 @@ /** 관리자 사이트 (docs/14-admin.md). Downloaded only when /admin is opened. */ import { useCallback, useEffect, useState, type ReactNode } from 'react'; import { NavLink, Route, Routes, useNavigate, useParams } from 'react-router'; -import { formatRoomCode, type MyGameSummary } from '@bg/shared/lite'; +import { formatRoomCode, GAME_SPEED_MAX, GAME_SPEED_MIN, type MyGameSummary } from '@bg/shared/lite'; import { ConfirmSheet, Sheet } from '../../components/ui'; import { apiCall, discordLoginUrl, type Role } from '../../net/api'; import { useSession } from '../../store/session'; @@ -351,6 +351,14 @@ function Rooms() { // ------------------------------------------------------------------ site +const SPEED_PRESETS = [1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16]; +/** 0.25 → "1/4배", 1.5 → "1.5배". */ +function speedLabel(x: number): string { + if (!Number.isFinite(x) || x <= 0) return '-'; + if (x < 1 && Number.isInteger(Math.round((1 / x) * 1000) / 1000)) return `1/${Math.round(1 / x)}배`; + return `${Math.round(x * 1000) / 1000}배`; +} + function Site() { const [d] = useLoad<{ site: any }>('/site'); const [s, setS] = useState(null); @@ -400,6 +408,38 @@ function Site() { {bool('maintenance', '점검 모드(새 방 만들기 막기)', '점검 중', '정상')} +
+
+ + 게임 속도 배율 (1/16~16배, 기본 1배) + +

+ 게임 화면의 애니메이션과 컴퓨터가 생각하는 시간이 이 배율만큼 빨라져요. 2배는 두 배 빠르게, 1/2배는 두 배 느리게. 저장하면 진행 중인 방에도 바로 적용돼요. 턴 제한 시간 같은 규칙 시간은 바뀌지 않아요. +

+
+ {SPEED_PRESETS.map((x) => ( + + ))} +
+ + + 지금 값: {speedLabel(s.gameSpeed)} + +
+
{num('maxRoomsPerUser', '사용자당 동시에 만들 수 있는 방', 1, 50)} {num('maxRooms', '서버 전체 방 수 제한', 10, 20000)} diff --git a/apps/web/src/store/session.ts b/apps/web/src/store/session.ts index 5497d59..d5542ee 100644 --- a/apps/web/src/store/session.ts +++ b/apps/web/src/store/session.ts @@ -3,6 +3,7 @@ import { create } from 'zustand'; import type { CatalogEntry, PublicUser } from '@bg/shared/lite'; import { api, type Settings } from '../net/api'; import { socket } from '../net/socket'; +import { setGameSpeed } from '../lib/motion'; const LS_KEY = 'bg.settings'; @@ -75,13 +76,14 @@ export const useSession = create((set, get) => ({ hasDiscordAvatar: false, async refresh() { const [cfg, me] = await Promise.all([ - api.config().catch(() => ({ discord: false, catalog: [] as CatalogEntry[], siteName: '같이 놀자 보드게임', announcement: '', maintenance: false })), + api.config().catch(() => ({ discord: false, catalog: [] as CatalogEntry[], siteName: '같이 놀자 보드게임', announcement: '', maintenance: false, gameSpeed: 1 })), api.me().catch(() => ({ me: null }) as Awaited>), ]); const settings = { ...get().settings, ...withoutDeviceOnly(me.settings ?? {}) }; applySettings(settings); localStorage.setItem(LS_KEY, JSON.stringify(settings)); document.title = cfg.siteName; + setGameSpeed(cfg.gameSpeed); set({ loaded: true, me: me.me, diff --git a/docs/06-lobby-rooms.md b/docs/06-lobby-rooms.md index bb90920..eb9c75f 100644 --- a/docs/06-lobby-rooms.md +++ b/docs/06-lobby-rooms.md @@ -110,7 +110,7 @@ interface Room { - 난이도(2026-10-11): 컴퓨터를 넣으면 1~60단계 중 아무 단계나 정해진다(랜덤). 방장은 컴퓨터 자리 아래의 [랜덤][쉬움][보통][어려움]으로 바꿀 수 있고(대기실에서만, `botLevel`), 고르면 그 범위(쉬움 1~20, 보통 21~40, 어려움 41~60) 안에서 단계가 다시 무작위로 정해진다. 다른 사람에게는 고른 이름("난이도 쉬움")만 보이고 정확한 단계는 게임이 끝난 뒤 "공정성 확인"에 보인다. 다음 판마다 처음 정한 단계 근처에서 조금씩 바뀐다(한 판에 최대 2단계, 처음 단계 ±5 안, 같은 범위 안). 컴퓨터마다 운도 다르다(04 §5.1). 자세한 것은 09 §9.1. - 컴퓨터가 앉은 방은 연습 방이다: 공개로 바꿀 수 없고, 공개 방 목록·빠른 시작에 나오지 않는다. 결과는 남지만 전적(`user_stats`)에는 넣지 않는다. 화면에 "연습 게임이에요. 기록에는 남지 않아요." 표시. - 컴퓨터가 할 수 있는 게임: 실시간·그림 게임(도블, 할리갈리, 그림 맞히기)을 뺀 전부(`packages/shared/src/bots.ts`의 `BOT_GAMES`). 마피아는 말하는 컴퓨터(2026-10-11, games/mafia.md §13), 연습 방은 6명으로 시작. -- 움직임: 서버의 `BotDriver`(`apps/server/src/rooms/bots.ts`)가 게임이 컴퓨터를 기다릴 때(차례, 반응 창, 동시 선택, 다음 판 준비) 사람처럼 생각할 시간을 두고 한 수를 둔다(2026-10-11). 할 게 하나뿐이면 0.7~1.3초, 고를 게 있으면 1.6~3.9초(고를 수가 많을수록 길게), 가끔(12%) 1~3초 더 멈칫한다. 컴퓨터마다 빠르기가 달라서(`botPace`: 0.7배 빠른 편~1.5배 신중한 편, 컴퓨터 id로 고정) 같은 판에서도 반응 속도가 다르다. 같은 컴퓨터가 이어서 두는 동작(요트 굴리기 → 고르기 등)은 절반 시간, 사람도 함께 반응할 수 있는 창(원카드 외치기 등)은 1.5초 더. 차례 시간이 있으면 남은 시간의 절반을 넘기지 않는다. 사람과 같은 행동 경로(검사·기록)를 거치고, 서버가 다시 켜져도 이어서 둔다. +- 움직임: 서버의 `BotDriver`(`apps/server/src/rooms/bots.ts`)가 게임이 컴퓨터를 기다릴 때(차례, 반응 창, 동시 선택, 다음 판 준비) 사람처럼 생각할 시간을 두고 한 수를 둔다(2026-10-11). 할 게 하나뿐이면 0.7~1.3초, 고를 게 있으면 1.6~3.9초(고를 수가 많을수록 길게), 가끔(12%) 1~3초 더 멈칫한다. 컴퓨터마다 빠르기가 달라서(`botPace`: 0.7배 빠른 편~1.5배 신중한 편, 컴퓨터 id로 고정) 같은 판에서도 반응 속도가 다르다. 같은 컴퓨터가 이어서 두는 동작(요트 굴리기 → 고르기 등)은 절반 시간, 사람도 함께 반응할 수 있는 창(원카드 외치기 등)은 1.5초 더. 차례 시간이 있으면 남은 시간의 절반을 넘기지 않는다. 사람과 같은 행동 경로(검사·기록)를 거치고, 서버가 다시 켜져도 이어서 둔다. 위 시간들은 게임 속도 배율(관리자 사이트 설정, 14-admin.md §5)에 따라 `1.5 ÷ 배율`배가 된다(2026-10-14, 1배일 때 위 값의 1.5배). 마피아·라이어의 컴퓨터가 다시 살펴보는 간격도 같다. 게임이 정한 반응 시각(원카드 외치기 등)은 사람과 공정하게 겨루도록 바꾸지 않는다. - 수 고르기: `packages/games/src/<게임>/bot.ts`. 자기 화면(`view(state, 나)`)과 둘 수 있는 수만 보고 고르므로 남의 패를 볼 수 없다. 강하지 않지만 엉뚱하지 않게(오목은 4를 막고, 오셀로는 귀를 잡고, 카드 게임은 패 세기에 맞게). - 사람이 모두 나가면 게임은 무효로 끝난다. diff --git a/docs/07-ui-ux.md b/docs/07-ui-ux.md index 43882a8..f0d1f11 100644 --- a/docs/07-ui-ux.md +++ b/docs/07-ui-ux.md @@ -8,6 +8,7 @@ 5. **실수 방지.** 큰 결정(기권, 나가기, 올인, 다이)은 확인. 단, 매 턴 확인창은 금지(느려짐) — 대신 "두 번 눌러 확정" 옵션(바둑·오목 오착 방지, 기본 켜짐: 첫 탭은 미리보기 돌, 같은 곳을 다시 탭하면 착수). 6. **기다림을 보여 준다.** 남은 시간 링, "OO님이 생각 중…", 연결 상태. 7. **가볍게.** 장식 이미지 최소, 애니메이션은 짧게(150~250ms), `prefers-reduced-motion` 존중. + - 게임 속도(2026-10-14): 코드에 적힌 길이는 그대로 두고, 게임 화면 안의 모든 움직임을 `lib/motion.ts`가 `1.5 ÷ 관리자 게임 속도 배율`배로 늘인다(1배여도 적힌 길이보다 1.5배 천천히). CSS 애니메이션·트랜지션은 `.game-layout` 안에서 `useMotionScope`가 재생 속도(`playbackRate`)를 맞추고, Web Animations는 `fxAnim(...)`, 연출 타이머(배너 유지, 다음 단계, 날아가는 복사본 정리, 숫자 세기)는 `fxMs(ms)`로 감싼다. 채팅 칸과 `role="timer"`(남은 시간 막대)는 실제 시간이라 빼고, 주사위 숫자 깜빡임 간격·그림 스트림·두 번 눌러 확인하는 창도 그대로. 8. **한눈에 들어오게 (2026-10-09, "한 화면에 정보가 너무 많다" 피드백).** 참고: NN/g 점진적 공개(자주 쓰는 것만 첫 단계, 나머지는 이름이 분명한 두 번째 단계, 최대 2단계), 토스 "한 화면 한 가지", Board Game Arena 화면 지침(판이 가운데, 정보는 묶어서, 드문 정보는 버튼·접기 뒤로), Hick의 법칙(고를 것이 많으면 묶음 탭으로 나눈다). - 같은 정보를 두 곳에 두지 않는다(방 안에서는 사이트 메뉴를 숨기고 방 막대 한 줄만, 대기실의 규칙 전문은 [📖 규칙]으로). - 목록 카드는 이름 + 한 줄 정보만. 설명·난이도는 들어간 다음 화면에서. diff --git a/docs/13-decisions.md b/docs/13-decisions.md index 5aaae5f..4af37be 100644 --- a/docs/13-decisions.md +++ b/docs/13-decisions.md @@ -24,6 +24,9 @@ - 화투 그림: Wikimedia Commons "SVG Hwatu"(Marcus Richert·Spenĉjo, CC BY-SA 4.0). 섯다·고스톱 규칙 화면과 `components/cards/hwatu/ATTRIBUTION.txt`에 출처 표시. - 컴퓨터 채팅: 이름("컴퓨터 1", "컴1", "1번")·이어 말하기면 매번 대답, 모델이 2.5초 넘거나 없으면 내장 대답, 한 사람당 1분 8번까지. 혼잣말은 눈에 띈 수에만(방 40초·컴퓨터 90초 간격), 시작 인사·사람 대화 끼어들기 없음. 수와 어긋난 말(센 베팅에 "쫄" 등)은 수 종류별 내장 한마디로 바꾼다. +## 0-3. 확정된 결정 (2026-10-14) +- 게임 속도: 전체가 빠르다는 요청으로 1배에서도 애니메이션·연출과 컴퓨터 생각 시간을 예전의 1.5배로 늘렸다. 관리자 사이트 설정 "게임 속도 배율"(1/16~16배, 기본 1배)로 둘 다 나눠서 조절하고, 저장하면 열린 방에도 바로 적용한다. 턴 제한 시간·결과 화면 대기 같은 규칙 시간과 반응 경쟁(원카드 외치기, 할리갈리·도블 판정)은 공정성 때문에 배율과 무관하다. + ## 1. 운영 (진행에 꼭 필요) | # | 항목 | 기본안 | 필요한 것 | |---|---|---|---| diff --git a/docs/14-admin.md b/docs/14-admin.md index 601353b..2c0aa6b 100644 --- a/docs/14-admin.md +++ b/docs/14-admin.md @@ -57,6 +57,7 @@ | 서버 전체 방 수 | 2000 | 방 만들기 제한 | | 연결 끊김 유예(초) | 60 | 새 방의 기본값 | | 채팅 기본값 | 켜짐 / 필터 켜짐 | 새 방의 기본값 | +| 게임 속도 배율 | 1배 | 1/16~16배. 게임 화면의 애니메이션·연출(배너가 떠 있는 시간, 차례로 이어지는 연출, 다시 보기 한 칸)과 컴퓨터가 생각하는 시간을 이 배율로 나눈다(2배 = 두 배 빠르게). 저장하면 열린 방에도 바로 적용(방 정보 `RoomView.gameSpeed`로 다시 보냄). 턴 제한 시간·결과 화면 대기 같은 규칙 시간, 원카드 외치기 같은 반응 경쟁, 실시간 게임의 판정 시간은 그대로 | ## 6. 사용자 관리 (슈퍼어드민) - **이용 제한**: 사유와 함께 설정. 즉시 그 사용자의 모든 세션 삭제와 접속 종료. 제한된 디스코드 계정은 다시 로그인할 수 없다("이용이 제한된 계정이에요"). 해제하면 다시 로그인 가능. diff --git a/e2e/admin.e2e.ts b/e2e/admin.e2e.ts index 7429b28..ce67fbe 100644 --- a/e2e/admin.e2e.ts +++ b/e2e/admin.e2e.ts @@ -105,6 +105,19 @@ try { await a.screenshot({ path: join(SHOTS, 'admin-3-admins.png') }); }); + await step('사이트 탭: 게임 속도 배율 2배 저장 → /api/config 반영', async () => { + await a.locator('.admin-side').getByRole('link', { name: '사이트', exact: true }).click(); + const speed = a.getByRole('group', { name: /게임 속도 배율/ }); + await speed.getByRole('button', { name: '2배', exact: true }).click(); + await a.getByText('지금 값: 2배').waitFor(); + await a.getByLabel('직접 입력(배)').evaluate((el) => el.scrollIntoView({ block: 'center' })); + await a.screenshot({ path: join(SHOTS, 'admin-4-speed.png') }); + await a.getByRole('button', { name: '저장', exact: true }).click(); + await a.getByText('저장했어요.').waitFor(); + const cfg = await a.evaluate(async () => (await (await fetch('/api/config')).json()).gameSpeed); + if (cfg !== 2) throw new Error(`gameSpeed not saved: ${cfg}`); + }); + await step('기록 탭에 변경 내역', async () => { await a.locator('.admin-side').getByRole('link', { name: '기록', exact: true }).click(); await a.getByText('어드민 추가').waitFor(); diff --git a/e2e/speed.e2e.ts b/e2e/speed.e2e.ts new file mode 100644 index 0000000..1d842c3 --- /dev/null +++ b/e2e/speed.e2e.ts @@ -0,0 +1,82 @@ +/** + * E2E (docs/14-admin.md §5 게임 속도 배율): the admin game speed reaches the screen and the computers. + * For each speed the site setting is changed and an 오목 practice game is played for one move, then + * - the stone animations on the board run at playbackRate = speed / 1.5 (×1 is a bit slower than the written CSS), + * - the computer's answer takes about 1.5 / speed times its usual thinking time. + * Run: E2E_PORT=4544 bun e2e/speed.e2e.ts (needs apps/web/dist built) + */ +import { chromium, type Browser, type Page } from 'playwright-core'; +import { mkdtempSync } from 'node:fs'; +import { join } from 'node:path'; +import { loadConfig } from '../apps/server/src/config'; +import { startServer } from '../apps/server/src/server'; + +const PORT = Number(process.env.E2E_PORT ?? 4544); +const ORIGIN = `http://localhost:${PORT}`; +const PAD = 0.9; + +async function clickCell(p: Page, x: number, y: number) { + const box = (await p.locator('svg[role="grid"]').boundingBox())!; + const span = 14 + 2 * PAD; + await p.mouse.click(box.x + ((x + PAD) / span) * box.width, box.y + ((y + PAD) / span) * box.height); +} +const stoneCount = (p: Page) => p.locator('svg[role="grid"] g:not([opacity="0.55"]) > circle[r="0.46"]').count(); + +/** Plays one move against the computer; returns the stone animation's playback rate and the computer's answer time. */ +async function run(browser: Browser, speed: number): Promise<{ rate: number; answerMs: number }> { + app.settings.setSite({ ...app.settings.getSite(), gameSpeed: speed }, 'e2e'); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR' }); + await ctx.addInitScript(() => localStorage.setItem('bg:qs:omok', '1')); + try { + const p = await ctx.newPage(); + await p.goto(`${ORIGIN}/g/omok`); + await p.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click(); + await p.getByLabel('내 이름(닉네임)').fill('속도'); + await p.getByRole('button', { name: '이 이름으로 시작하기' }).click(); + await p.waitForURL(/\/r\/\d{6}$/); + await p.getByRole('button', { name: '▶ 게임 시작' }).click(); + await p.locator('svg[role="grid"]').waitFor(); + // Black moves first; if the computer is black, wait for its first stone. + await p.waitForFunction(() => /내 차례예요/.test(document.querySelector('.turn-status')?.textContent ?? ''), null, { timeout: 60_000 }); + const before = await stoneCount(p); + await clickCell(p, before ? 8 : 7, 7); + // My stone lands with `bm-place`: read its rate while it plays. + const rate = await p.waitForFunction(() => { + const root = document.querySelector('.game-layout'); + const a = root?.getAnimations({ subtree: true }).find((x) => (x as CSSAnimation).animationName === 'bm-place'); + return a ? a.playbackRate : null; + }, null, { timeout: 5000, polling: 'raf' }); + const t0 = Date.now(); + await p.waitForFunction((n) => document.querySelectorAll('svg[role="grid"] g:not([opacity="0.55"]) > circle[r="0.46"]').length >= n + 2, before, { timeout: 60_000 }); + return { rate: (await rate.jsonValue()) as number, answerMs: Date.now() - t0 }; + } finally { + await ctx.close(); + } +} + +const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-')); +const app = startServer({ + config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN }), + log: () => {}, + staticDir: join(import.meta.dir, '../apps/web/dist'), +}); + +const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true }); +let failed = false; +try { + for (const [speed, check] of [ + [1, (ms: number) => ms >= 2000], + [4, (ms: number) => ms <= 4500], + [1 / 4, (ms: number) => ms >= 7000], + ] as const) { + const { rate, answerMs } = await run(browser, speed); + const want = speed / 1.5; + const ok = Math.abs(rate - want) < 1e-6 && check(answerMs); + if (!ok) failed = true; + console.log(`${ok ? '✓' : '✗'} 속도 ${speed}배: 돌 애니메이션 재생 배율 ${rate.toFixed(3)} (기대 ${want.toFixed(3)}), 컴퓨터 응답 ${answerMs}ms`); + } +} finally { + await browser.close(); + await app.stop(); +} +process.exit(failed ? 1 : 0); diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 91aac37..2924252 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -3,6 +3,19 @@ export const PROTOCOL = 1; export const MAX_CLIENT_MESSAGE_BYTES = 16 * 1024; export const CHAT_MAX = 200; +/** + * Game speed (admin site setting, docs/14-admin.md §5): animations, staged effects and the computers' thinking time + * are divided by it. 1 is the normal pace; the range is 1/16 ~ 16. + */ +export const GAME_SPEED_MIN = 1 / 16; +export const GAME_SPEED_MAX = 16; +export const GAME_SPEED_DEFAULT = 1; +/** Clamps a speed from the network / settings into the range (anything not a positive number → 1). */ +export function clampGameSpeed(x: unknown): number { + if (typeof x !== 'number' || !Number.isFinite(x) || x <= 0) return GAME_SPEED_DEFAULT; + return Math.min(GAME_SPEED_MAX, Math.max(GAME_SPEED_MIN, x)); +} + export const EMOTES = ['thumbs', 'laugh', 'wow', 'sad', 'clap', 'nice', 'hurry', 'gg'] as const; export const EMOTE_LABEL: Record<(typeof EMOTES)[number], string> = { thumbs: '👍', @@ -68,6 +81,8 @@ export interface RoomView { lastBots?: Record; /** How many shuffles were tried for the computers' luck in that game (1 = the first one, no choice). */ lastShuffles?: number; + /** Game speed set by the admin (1/16 ~ 16, 1 = normal): the screen's animations follow it. */ + gameSpeed?: number; } export interface GameResultView {