diff --git a/apps/server/src/rooms/bots.room.test.ts b/apps/server/src/rooms/bots.room.test.ts index f2a5eeb..ff64173 100644 --- a/apps/server/src/rooms/bots.room.test.ts +++ b/apps/server/src/rooms/bots.room.test.ts @@ -1,7 +1,8 @@ /** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */ import { afterEach, describe, expect, test } from 'bun:test'; import { GAMES } from '@bg/games'; -import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES } from '@bg/games/bots'; +import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES, botReactionAt } from '@bg/games/bots'; +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 { botPace, defaultBotDelay, type BotDelayInput } from './bots'; @@ -338,6 +339,63 @@ describe('playing with bots', () => { }); }); +describe('원카드: computers call and catch on their own reaction clock', () => { + test('a computer that played down to one card calls at its reaction time; a person can catch only after 2 s', () => { + const h = harness(undefined, undefined, (input) => defaultBotDelay(input, () => 0.5)); + const room = h.manager.createPractice('A', 'one-card') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = bots(room)[0]!; + // Rig: the computer's turn with [♥9, ♣3] on ♥5; the person is next. + const s = room.game!.state as OneCardState; + const deck = classicDeck(1); + const take = (ids: string[]) => ids.map((id) => deck.find((c) => c.id === id)!); + s.hands = { A: take(['S4', 'S6', 'D8']), [bot]: take(['H9', 'C3']) }; + s.discard = take(['H5']); + s.drawPile = deck.filter((c) => !['S4', 'S6', 'D8', 'H9', 'C3', 'H5'].includes(c.id)); + s.current = bot; + s.phase = { kind: 'turn' }; + s.pendingAttack = 0; + s.declaredSuit = null; + s.oneCardWindow = null; + room.bots.cancel(); + room.scheduleTimer(); + for (let k = 0; k < 5 && !(room.game!.state as OneCardState).oneCardWindow; k++) { + h.clock.advance(Math.max(0, (room.bots.dueAt ?? h.clock.now()) - h.clock.now())); + room.bots.fire(); + } + let st = room.game!.state as OneCardState; + expect(st.oneCardWindow).toMatchObject({ player: bot, declared: false }); + expect(st.current).toBe('A'); + const opened = st.oneCardWindow!.openedAt!; + // Planned exactly at its reaction time (not squeezed by the turn clock, no thinking chat). + const at = botReactionAt(room.def, st, bot, room.profile(bot).level) as number; + expect(at).toBeGreaterThanOrEqual(opened + 500); + expect(room.bots.dueAt).toBe(at); + const rejects = () => a.msgs.filter((m) => m.t === 'reject').length; + const before = rejects(); + room.act('A', 101, { type: 'declareOneCard' }); + expect(rejects()).toBe(before + 1); + if (at > opened + 2000) { + // Slow this time: the person catches it first and the planned call is dropped. + h.clock.advance(opened + 2000 - h.clock.now()); + room.act('A', 102, { type: 'declareOneCard' }); + st = room.game!.state as OneCardState; + expect(st.oneCardWindow).toBeNull(); + expect(st.hands[bot]).toHaveLength(2); + expect(room.bots.dueAt).toBeNull(); + } else { + h.clock.advance(at - h.clock.now()); + room.bots.fire(); + st = room.game!.state as OneCardState; + expect(st.oneCardWindow).toMatchObject({ player: bot, declared: true }); + expect(st.hands[bot]).toHaveLength(1); + } + }); +}); + describe('practice rooms close once nobody is there', () => { function finishedPractice() { const h = harness(); diff --git a/apps/server/src/rooms/bots.ts b/apps/server/src/rooms/bots.ts index 1a60c07..dbb8a1a 100644 --- a/apps/server/src/rooms/bots.ts +++ b/apps/server/src/rooms/bots.ts @@ -5,7 +5,7 @@ */ import { secureRandom, type AnyGameDefinition } from '@bg/engine'; import { isBotId } from '@bg/shared'; -import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots'; +import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, botReactionAt, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots'; import type { BotBrain } from '../ai/brain'; @@ -39,6 +39,8 @@ export interface BotDelayInput { bot: string; /** The same bot just acted and is still on (e.g. yacht keep → roll): it already knows what it wants. */ followUp: boolean; + /** An out-of-turn reaction the game timed itself (원카드 외치기·잡기, `botReactionAt`): wait exactly this long. */ + reactMs?: number; } /** @@ -49,6 +51,7 @@ export interface BotDelayInput { */ export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): 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); @@ -68,6 +71,8 @@ export class BotDriver { dueAt: number | null = null; /** Bot the planned action is for. */ private planned: string | null = null; + /** The planned action is that bot's out-of-turn reaction due at this time (not its normal move). */ + private plannedReact: number | null = null; /** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */ private acting: string | null = null; /** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */ @@ -87,26 +92,65 @@ export class BotDriver { /** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */ schedule(): void { if (this.liveStrategy()) return this.scheduleLive(); - if (this.dueAt !== null || this.busy) return; + if (this.busy) return; + if (this.dueAt !== null) { + // A planned reaction the moment has passed for (someone called first): plan again; anything else stays planned. + if (this.plannedReact === null || this.reactionDue()?.bot === this.planned) return; + if (this.timer) clearTimeout(this.timer); + this.timer = null; + this.dueAt = null; + this.planned = null; + this.plannedReact = null; + } const next = this.next(); - if (!next) return; - // People can see it think: "생각 중…" until it moves. - if (this.room.brain?.enabled()) this.room.brain.thinking(next.bot, true); + const react = this.reactionDue(); + if (!next && !react) return; const now = this.room.now(); - let ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting }); - const deadline = this.room.deadline?.() ?? null; - if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE)); + let ms = Infinity; + if (next) { + ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting }); + const deadline = this.room.deadline?.() ?? null; + if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE)); + } + // An out-of-turn reaction (원카드!) comes first when it is due earlier; it is not squeezed by the turn clock, so a + // slow computer can really be late. + if (react) { + const rms = this.delay({ choices: 1, withPeople: true, bot: react.bot, followUp: false, reactMs: react.at - now }); + if (rms <= ms) { + this.dueAt = now + rms; + this.planned = react.bot; + this.plannedReact = react.at; + return this.arm(); + } + } + // People can see it think: "생각 중…" until it moves. + if (this.room.brain?.enabled()) this.room.brain.thinking(next!.bot, true); this.dueAt = now + ms; - this.planned = next.bot; + this.planned = next!.bot; + this.plannedReact = null; this.arm(); } + /** The earliest out-of-turn reaction of a computer that may act now (games with `BOT_REACTIONS`). */ + private reactionDue(): { bot: string; at: number } | null { + const g = this.room.game; + if (!g || g.finished || this.room.status !== 'playing') return null; + let best: { bot: string; at: number } | null = null; + for (const p of g.players) { + if (!isBotId(p)) continue; + const at = botReactionAt(this.room.def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)); + if (typeof at === 'number' && (!best || at < best.at)) best = { bot: p, at }; + } + return best; + } + cancel(): void { if (this.timer) clearTimeout(this.timer); this.timer = null; if (this.planned) this.room.brain?.thinking(this.planned, false); this.dueAt = null; this.planned = null; + this.plannedReact = null; this.liveDue.clear(); } @@ -219,8 +263,11 @@ export class BotDriver { const active = def.activePlayers(g.state); const waiting = new Set([...active, ...(def.timeoutPlayers?.(g.state) ?? [])]); const withPeople = active.some((p) => !isBotId(p)); + const timed = new Set(def.timeoutPlayers?.(g.state) ?? active); for (const p of g.players) { if (!isBotId(p) || !waiting.has(p)) continue; + // Only there to react out of turn (원카드!): `reactionDue` times that, not the thinking time. + if (!timed.has(p) && botReactionAt(def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)) !== null) continue; const choices = botCandidates(def, g.state, p).length; if (choices > 0) return { bot: p, choices, withPeople }; } @@ -239,13 +286,16 @@ export class BotDriver { return this.fireLive(live); } const planned = this.planned; + const wasReact = this.plannedReact !== null; this.dueAt = null; this.planned = null; - const next = this.next(); + this.plannedReact = null; + const react = wasReact ? this.reactionDue() : null; + const next = wasReact ? (react && react.bot === planned ? { bot: react.bot } : null) : this.next(); const g = this.room.game; - if (!next || !g) return; - // Another bot's turn came up meanwhile: give it its own thinking time. - if (next.bot !== planned) return this.schedule(); + if (!g) return; + // Another bot's turn came up meanwhile (or the reaction is moot): give it its own thinking time. + if (!next || next.bot !== planned) return this.schedule(); const def = this.room.def; const t0 = performance.now(); let action: unknown; @@ -258,7 +308,8 @@ 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) }); const brain = this.room.brain; - if (brain && action != null && brain.enabled()) { + // A reaction (원카드!) is a reflex: no chat before it. + if (brain && action != null && brain.enabled() && !wasReact) { // Like a person: maybe type something first (the model writes it; "입력 중…" while typing), then move. const bot = next.bot; this.busy = bot; diff --git a/apps/web/src/games/one-card/fx.tsx b/apps/web/src/games/one-card/fx.tsx new file mode 100644 index 0000000..1f26e19 --- /dev/null +++ b/apps/web/src/games/one-card/fx.tsx @@ -0,0 +1,385 @@ +/** + * 원카드 소리·움직임 (docs/games/one-card.md §9). Everything reacts to new public log lines, so other players' moves + * sound and move too, and each change plays once (lines are handled by their `seq`). + */ +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'; + +export interface Banner { + key: number; + text: string; + sub?: string; + kind: 'attack' | 'call' | 'caught' | 'info' | 'win' | 'suit' | 'block'; + /** Text / glow colour for suit and colour changes. */ + color?: string; +} + +export interface Fx { + banners: Banner[]; + /** Colour wash over the table (colour cards: the chosen colour). */ + flash: { key: number; color: string } | null; + /** Bumps when the direction changes (the arrow spins). */ + spin: number; + /** Bumps when the discard pile is shuffled back (the deck shakes). */ + shuffle: number; + /** Where the newest discard flew in from (px, relative to the discard pile). */ + playFrom: { discard: number; x: number; y: number } | null; + /** My cards that just arrived, with their animation delay (ms). */ + arrived: Record; +} + +const SUIT_HEX: Record = { S: '#111827', H: '#dc2626', D: '#dc2626', C: '#111827' }; +const SUIT_SYM: Record = { S: '♠', H: '♥', D: '◆', C: '♣' }; +const SUIT_KO: Record = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' }; +const COLOR_HEX: Record = { R: '#dc2626', Y: '#eab308', G: '#16a34a', B: '#2563eb' }; +const COLOR_KO: Record = { R: '빨강', Y: '노랑', G: '초록', B: '파랑' }; + +const DRAW_WHY: Record['why'], string> = { + normal: '', + attack: '공격을 못 막았어요', + penalty: '원카드 벌칙!', + bonus: '원카드를 먼저 외쳐서', + draw2: '+2를 맞았어요', + wild4: '색 바꾸기+4를 맞았어요', + challenge: '의심 결과', + start: '시작 카드가 +2', +}; + +/** Game sounds built on the shared palette (no audio files). */ +const ocSound = { + attack: (big: boolean) => { + tone(196, 140, 'sawtooth', 0.05, 0, { slideTo: big ? 660 : 440 }); + noise(160, 0.1, 40, 'lowpass', 700); + if (big) tone(880, 160, 'square', 0.04, 160); + }, + reverse: () => { + sfx.whoosh(); + tone(620, 130, 'triangle', 0.1, 0, { slideTo: 360 }); + tone(360, 130, 'triangle', 0.1, 140, { slideTo: 620 }); + }, + skip: () => { + sfx.whoosh(); + tone(988, 60, 'square', 0.04, 80); + tone(1318, 60, 'square', 0.04, 150); + }, + suit: () => { + sfx.pop(); + tone(1046, 140, 'triangle', 0.1, 110); + tone(1568, 160, 'triangle', 0.08, 220); + }, + call: () => { + sfx.fanfare(); + noise(220, 0.06, 0, 'highpass', 3500); + }, + block: () => { + tone(1400, 50, 'square', 0.05); + noise(90, 0.14, 0, 'bandpass', 3000, 3); + sfx.good(); + }, + oneLeft: () => { + tone(1175, 90, 'square', 0.05); + tone(1175, 90, 'square', 0.05, 160); + }, +}; + +const reduced = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; +const rectOf = (root: HTMLElement, sel: string) => root.querySelector(sel)?.getBoundingClientRect() ?? null; +const center = (r: DOMRect) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 }); +const seatSel = (p: string) => `[data-seat="${CSS.escape(p)}"]`; + +/** Flight time of one card from the deck (ms). */ +const FLY_MS = 480; + +/** + * Card backs flying from the deck to a hand / seat, one after another (pure DOM, never blocks clicks). Each card + * makes its own little sound as it leaves the deck and lands, a little higher each time, so a big penalty is heard + * card by card. Returns the gap between cards (ms; 0 when nothing flew). + */ +function flyCards(root: HTMLElement, layer: HTMLElement, to: string, n: number, mode: OneCardView['mode'], delay0 = 0, quiet = false): number { + const from = rectOf(root, '.oc-pile'); + const target = rectOf(root, to); + const base = layer.getBoundingClientRect(); + const shown = Math.min(n, 12); + const gap = shown > 8 ? 70 : shown > 4 ? 85 : 110; + if (!quiet) + for (let i = 0; i < shown; i++) { + sfx.cardDeal(delay0 + i * gap); + tone(520 + i * 45, 45, 'triangle', 0.05, delay0 + i * gap + FLY_MS - 40); + } + if (!from || !target || reduced()) return 0; + const a = center(from); + const b = center(target); + const w = Math.min(from.width * 0.8, 64); + for (let i = 0; i < shown; i++) { + const el = document.createElement('div'); + el.className = `oc-fly${mode === 'uno-style' ? ' uno' : ''}`; + el.style.width = `${w}px`; + el.style.height = `${w * 1.4}px`; + layer.appendChild(el); + const x0 = a.x - base.left - w / 2; + const y0 = a.y - base.top - (w * 1.4) / 2; + // Spread the arrivals a little across the target so a pile of cards reads as many cards. + const spread = Math.min(target.width * 0.35, 60) * (shown > 1 ? i / (shown - 1) - 0.5 : 0); + const x1 = b.x - base.left - w / 2 + spread; + const y1 = b.y - base.top - (w * 1.4) / 2; + const lift = Math.min(90, Math.abs(y1 - y0) * 0.35 + 30); + if (typeof el.animate !== 'function') { + el.remove(); + continue; + } + const anim = 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(); + } + return gap; +} + +/** A big penalty lands: the table shakes and flashes red (the harder, the bigger). Starts when the first card lands. */ +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( + [ + { transform: 'none' }, + { transform: `translateX(${-d}px) rotate(-1deg)`, offset: 0.15 }, + { transform: `translateX(${d}px) rotate(1deg)`, offset: 0.35 }, + { transform: `translateX(${-d * 0.6}px)`, offset: 0.55 }, + { transform: `translateX(${d * 0.4}px)`, offset: 0.75 }, + { transform: 'none' }, + ], + { duration: 520, delay, easing: 'ease-out' }, + ); + 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 { + view: OneCardView; + me: string | null; + nick: (id: string) => string; +} + +/** + * Watches the view and returns what the board should show (banners, flashes, arrived cards). `root` is the board, + * `layer` an absolutely positioned overlay inside it for the flying cards. + */ +export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject, layer: RefObject): Fx { + const [fx, setFx] = useState({ banners: [], flash: null, spin: 0, shuffle: 0, playFrom: null, arrived: {} }); + const seen = useRef(null); + const hand = useRef | null>(null); + const round = useRef(v.round); + const keyRef = useRef(1); + const timers = useRef([]); + + useLayoutEffect(() => () => timers.current.forEach((t) => clearTimeout(t)), []); + + useLayoutEffect(() => { + const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0; + const myHand = v.my?.hand ?? []; + const first = seen.current === null; + const fresh = first ? [] : v.log.filter((e) => e.seq > seen.current!); + seen.current = Math.max(seen.current ?? 0, lastSeq); + const banners: Banner[] = []; + const next: Partial = {}; + const sounds = new Set(); + let drawGap = 0; + let myDraw = 0; + const banner = (b: Omit) => banners.push({ ...b, key: keyRef.current++ }); + const who = (p: string) => (p === me ? '내가' : `${nick(p)}님이`); + const rootEl = root.current; + const layerEl = layer.current; + let draws = 0; + let myAt = 0; + for (const e of fresh) { + switch (e.t) { + case 'play': { + sounds.add('play'); + const c = e.cards[0] as CardFace; + if (rootEl) { + const from = rectOf(rootEl, e.p === me ? '.oc-hand' : seatSel(e.p)); + const to = rectOf(rootEl, '.oc-discard'); + if (from && to) { + const a = center(from); + const b = center(to); + next.playFrom = { discard: v.discardCount, x: a.x - b.x, y: a.y - b.y }; + } + } + if (c.kind === 'std' && c.rank === 7 && e.suit) { + sounds.add('suit'); + banner({ text: `${SUIT_SYM[e.suit]}`, sub: `${who(e.p)} ${SUIT_KO[e.suit]}로 바꿨어요`, kind: 'suit', color: SUIT_HEX[e.suit] }); + } else if (e.color) { + sounds.add('suit'); + next.flash = { key: keyRef.current++, color: COLOR_HEX[e.color]! }; + banner({ text: COLOR_KO[e.color]!, sub: `${who(e.p)} 색을 바꿨어요`, kind: 'suit', color: COLOR_HEX[e.color] }); + } + if (c.kind === 'joker') { + sounds.add('bigAttack'); + banner({ text: '조커!', sub: `+${v.pendingAttack}장 공격`, kind: 'attack' }); + } else if ((c.kind === 'std' && (c.rank === 1 || c.rank === 2)) || c.kind === 'draw2' || c.kind === 'wild4') { + if (v.pendingAttack > 0) sounds.add(v.pendingAttack >= 5 ? 'bigAttack' : 'attack'); + } + if (c.kind === 'std' && c.rank === 13 && v.extraTurn && v.current === e.p) banner({ text: 'K! 한 번 더', kind: 'info' }); + if (e.p === me && myHand.length === 1 && v.oneCardWindow?.player === me && !v.oneCardWindow.declared) { + sounds.add('oneLeft'); + haptic([40, 40, 40]); + } + break; + } + case 'draw': { + if (e.n <= 0) break; + // Several eaters at once (원카드 보너스): one after another, not on top of each other. + const at = 260 * draws++; + if (rootEl && layerEl) { + const gap = flyCards(rootEl, layerEl, e.p === me ? '.oc-hand' : seatSel(e.p), e.n, v.mode, at); + if (e.p === me) { + drawGap = gap; + myAt = at; + } + const big = e.n >= 4 || e.why === 'penalty'; + if (big) hitTable(rootEl, e.n, at + FLY_MS - 80); + } + if (e.p === me) myDraw += e.n; + if (e.n >= 2 || e.why === 'penalty' || e.why === 'bonus') { + banner({ text: `+${e.n}장`, sub: `${who(e.p)} 먹어요${DRAW_WHY[e.why] ? ` · ${DRAW_WHY[e.why]}` : ''}`, kind: e.n >= 4 || e.why === 'penalty' ? 'attack' : 'info' }); + if (e.n >= 5 || e.why === 'penalty') sounds.add('alarm'); + } + break; + } + case 'declare': + sounds.add('call'); + banner({ text: '원카드!', sub: `${who(e.p)} 외쳤어요`, kind: 'call' }); + break; + case 'caught': + sounds.add('caught'); + banner({ text: '잡았다!', sub: `${who(e.by)} 먼저 외쳐서 ${who(e.p)} ${e.n}장`, kind: 'caught' }); + break; + case 'blocked': + sounds.add('block'); + banner({ text: '막았다!', sub: `${nick(e.p)}님이 3으로 공격을 막았어요`, kind: 'block' }); + break; + case 'reverse': + sounds.add('reverse'); + next.spin = (next.spin ?? fx.spin) + 1; + banner({ text: '⇄ 방향 바뀜', kind: 'info' }); + break; + case 'skip': + sounds.add('skip'); + banner({ text: '건너뛰기!', sub: `${nick(e.p)}님 차례를 건너뛰어요`, kind: 'info' }); + break; + case 'reshuffle': + sounds.add('shuffle'); + next.shuffle = (next.shuffle ?? fx.shuffle) + 1; + break; + case 'out': + if (v.phase !== 'finished') sounds.add('out'); + banner({ text: `${e.place}등!`, sub: `${who(e.p)} 카드를 모두 냈어요`, kind: 'win' }); + break; + case 'bankrupt': + sounds.add('bad'); + banner({ text: '파산!', sub: `${who(e.p)} 탈락했어요`, kind: 'caught' }); + break; + case 'challenge': + sounds.add(e.illegal ? 'good' : 'bad'); + banner({ text: e.illegal ? '의심 성공!' : '의심 실패', kind: e.illegal ? 'block' : 'caught' }); + break; + case 'round': + banner({ text: `${e.round}판 끝`, sub: e.winner ? `${nick(e.winner)}님 +${e.points}점` : undefined, kind: 'win' }); + break; + } + } + // A new round (or the first deal of the game) deals my cards in. + // The first look at a game nobody has moved in yet, or a new round (색깔 카드 점수제): deal everyone in. + const untouched = !v.log.some((e) => e.t === 'play' || e.t === 'pass' || (e.t === 'draw' && e.why !== 'start')); + const dealing = (first && untouched && v.phase !== 'finished') || v.round !== round.current; + round.current = v.round; + const prev = hand.current; + hand.current = new Set(myHand.map((c) => c.id)); + const arrived: Record = {}; + if (dealing) { + sfx.shuffle(); + next.shuffle = (next.shuffle ?? fx.shuffle) + 1; + const seats = v.seats.filter((s) => s.status === 'playing'); + // A few backs to every seat in turn (quiet: one shared dealing sound), then my own cards land one by one. + if (rootEl && layerEl) seats.forEach((s, k) => flyCards(rootEl, layerEl, s.id === me ? '.oc-hand' : seatSel(s.id), 3, v.mode, 300 + k * 140, true)); + const start = 300 + seats.length * 140; + myHand.forEach((c, i) => (arrived[c.id] = start + i * 70)); + for (let i = 0; i < Math.min(seats.length * 3, 14); i++) sfx.cardDeal(300 + i * 70); + } else if (prev && myDraw > 0) { + const gap = drawGap || 90; + let i = 0; + for (const c of myHand) if (!prev.has(c.id)) arrived[c.id] = myAt + FLY_MS - 100 + i++ * gap; + } + if (Object.keys(arrived).length) next.arrived = arrived; + + if (sounds.has('play')) sfx.cardPlay(); + if (sounds.has('bigAttack')) ocSound.attack(true); + else if (sounds.has('attack')) ocSound.attack(false); + if (sounds.has('suit')) ocSound.suit(); + if (sounds.has('reverse')) ocSound.reverse(); + if (sounds.has('skip')) ocSound.skip(); + if (sounds.has('block')) ocSound.block(); + if (sounds.has('shuffle')) sfx.shuffle(); + if (sounds.has('caught')) sfx.alarm(); + else if (sounds.has('alarm')) sfx.alarm(); + if (sounds.has('call')) ocSound.call(); + if (sounds.has('oneLeft')) ocSound.oneLeft(); + if (sounds.has('out')) sfx.fanfare(); + if (sounds.has('good')) sfx.good(); + if (sounds.has('bad')) sfx.bad(); + if (myDraw >= 2) haptic([30, 30, 30]); + + if (banners.length || Object.keys(next).length) { + setFx((f) => ({ ...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); + timers.current.push(t); + } + } + timers.current = timers.current.slice(-20); + }, [v.log.length ? v.log[v.log.length - 1]!.seq : 0, v.round, v.my?.hand.length]); // eslint-disable-line react-hooks/exhaustive-deps + + return fx; +} + +export const FX_CSS = ` +.oc { position: relative; } +.oc-fxlayer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; z-index: 30; } +.oc-fly { position: absolute; left: 0; top: 0; border-radius: 8px; border: 3px solid #fff; box-shadow: 0 6px 14px rgba(0,0,0,.35); + background: repeating-linear-gradient(45deg, #1e3a8a 0 6px, #2547b8 6px 12px); will-change: transform; } +.oc-fly.uno { background: radial-gradient(ellipse 38% 48% at center, #dc2626 0 98%, transparent 100%), #111827; } +.oc-banners { position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%); display: flex; flex-direction: column; align-items: center; gap: 6px; + pointer-events: none; z-index: 31; } +.oc-banner { display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 6px 22px; border-radius: 18px; color: #fff; background: rgba(17,24,39,.86); + box-shadow: 0 10px 28px rgba(0,0,0,.4); text-align: center; max-width: 92%; } +.oc-banner b { font-size: clamp(1.9rem, 7vw, 3.2rem); font-weight: 900; line-height: 1.1; letter-spacing: .02em; text-shadow: 0 3px 0 rgba(0,0,0,.35); } +.oc-banner span { font-size: .95rem; font-weight: 700; opacity: .95; } +.oc-banner.attack { background: linear-gradient(135deg, #b91c1c, #f97316); } +.oc-banner.attack b { font-size: clamp(2.4rem, 10vw, 4.4rem); } +.oc-banner.call { background: linear-gradient(135deg, #f59e0b, #fde047); color: #1f2937; } +.oc-banner.call b { text-shadow: 0 3px 0 rgba(255,255,255,.5); } +.oc-banner.caught { background: linear-gradient(135deg, #7f1d1d, #dc2626); } +.oc-banner.win { background: linear-gradient(135deg, #15803d, #22c55e); } +.oc-banner.block { background: linear-gradient(135deg, #1d4ed8, #38bdf8); } +.oc-banner.suit { background: #fffef9; color: var(--suit, #111827); border: 4px solid var(--suit, #111827); } +.oc-flash { position: absolute; inset: -8px; border-radius: 24px; pointer-events: none; animation: oc-flash .7s ease-out both; z-index: 1; } +@keyframes oc-flash { 0% { box-shadow: inset 0 0 0 0 var(--c), 0 0 0 0 var(--c); opacity: 1; } 40% { box-shadow: inset 0 0 60px 16px var(--c), 0 0 26px 6px var(--c); } 100% { box-shadow: inset 0 0 0 0 var(--c), 0 0 0 0 var(--c); opacity: 0; } } +.oc-spin { display: inline-block; animation: oc-spin .6s cubic-bezier(.3,.7,.3,1) both; } +@keyframes oc-spin { from { transform: rotate(-360deg) scale(1.6); } } +.oc-attack { position: relative; } +.oc-attack.grow { animation: anim-pop .32s cubic-bezier(.3,1.6,.5,1) both, oc-burn 1.2s ease-in-out .32s infinite; } +@keyframes oc-burn { 50% { box-shadow: 0 0 0 4px rgba(249,115,22,.55), 0 0 22px rgba(239,68,68,.8); } } +.oc-attack small { display: block; font-size: .8rem; font-weight: 800; opacity: .9; } +.oc-card.oc-in { animation: anim-deal .38s cubic-bezier(.2,.8,.3,1.15) backwards; animation-delay: var(--anim-delay, 0ms); --from-y: -90px; } +.oc-pile.shake { animation: anim-shake .45s ease both; } +`; diff --git a/apps/web/src/games/one-card/help.test.ts b/apps/web/src/games/one-card/help.test.ts index 2844abb..de93f92 100644 --- a/apps/web/src/games/one-card/help.test.ts +++ b/apps/web/src/games/one-card/help.test.ts @@ -47,6 +47,17 @@ test('원카드: 7로 정한 무늬, 원카드 잡기', () => { state.hands[other] = [state.hands[other][0]]; expect(helpNow(view(state, other), other, users)).toContain('[원카드!] 버튼을 빨리 눌러요'); expect(helpNow(view(state, cur), cur, users)).toContain(`${nickOf(other)}님이 1장 남았는데`); + expect(helpNow(view(state, cur), cur, users)).toContain('2초가 지나면 [원카드!]를 먼저 눌러 잡을 수 있어요'); +}); + +test('원카드: 끝에서 두 번째 카드를 낼 때는 원카드를 따로 누르라고 안내', () => { + const { state } = setupGame('one-card', 3); + const cur = state.current as string; + state.discard.push({ id: 'H8', kind: 'std', suit: 'H', rank: 8 }); + state.hands[cur] = [{ id: 'H9', kind: 'std', suit: 'H', rank: 9 }, { id: 'C5', kind: 'std', suit: 'C', rank: 5 }]; + const t = helpNow(view(state, cur), cur, users); + expect(t).toContain('카드를 낸 다음 동그란 [원카드!] 버튼을 따로 꼭 눌러요'); + expect(t).not.toContain('내면서'); }); test('색깔 카드: 색 바꾸기+4 의심하기', () => { @@ -68,7 +79,9 @@ test('원카드: 끝나면 결과 안내', () => { let { state: s } = setupGame('one-card', 2, { handSize: 5 }); for (let i = 0; i < 2000 && !def.result(s); i++) { const actor = def.activePlayers(s)[0]!; - s = applyAction('one-card', s, actor, def.legalActions!(s, actor)[0]); + // The clock here stands still, so a catch (only after the protection time) is never allowed: skip it. + const legal = def.legalActions!(s, actor).filter((a) => def.validate(s, actor, a, { now: 1_700_000_100_000 }).ok); + s = applyAction('one-card', s, actor, legal[0]); } expect(def.result(s)).toBeTruthy(); expect(helpNow(view(s, 'A'), 'A', usersOf(['A', 'B']))).toContain('게임이 끝났어요'); diff --git a/apps/web/src/games/one-card/help.ts b/apps/web/src/games/one-card/help.ts index 717e2a4..3c7639c 100644 --- a/apps/web/src/games/one-card/help.ts +++ b/apps/web/src/games/one-card/help.ts @@ -63,7 +63,7 @@ function myTurn(v: OneCardView): string[] { lines.push('낼 수 있는 카드가 없어요. [1장 먹기]를 누르거나 카드 더미를 눌러 주세요.'); } if (hand.length === 1 && legal === 0 && v.mode === 'classic' && v.options.lastCardRule !== 'none') lines.push(LAST_CARD[v.options.lastCardRule]); - if (hand.length === 2 && !v.options.autoDeclare && legal > 0) lines.push('내고 나면 1장이 남아요. [내면서 원카드 외치기]에 체크돼 있는지 확인해요.'); + if (hand.length === 2 && !v.options.autoDeclare && legal > 0) lines.push('내고 나면 1장이 남아요. 카드를 낸 다음 동그란 [원카드!] 버튼을 따로 꼭 눌러요.'); return lines; } @@ -83,11 +83,12 @@ export function helpNow(v: OneCardView, me: string | null, players: Record { if (!my?.canDeclare || !w || w.declared) return ''; - if (w.player === me) return `카드가 1장 남았어요! 동그란 [원카드!] 버튼을 빨리 눌러요. 다른 사람이 먼저 누르면 ${v.penalty}장을 먹어요.`; - return `${nm(players, w.player)}이 1장 남았는데 아직 원카드를 안 외쳤어요. [원카드!]를 먼저 누르면 ${nm(players, w.player)}이 ${v.penalty}장을 먹어요.`; + const grace = v.options.oneCardGrace; + if (w.player === me) return `카드가 1장 남았어요! 동그란 [원카드!] 버튼을 빨리 눌러요. ${grace}초가 지나면 다른 사람이 먼저 눌러 잡을 수 있고, 잡히면 ${v.penalty}장을 먹어요.`; + return `${nm(players, w.player)}이 1장 남았는데 아직 원카드를 안 외쳤어요. ${grace}초가 지나면 [원카드!]를 먼저 눌러 잡을 수 있어요. 잡으면 ${nm(players, w.player)}이 ${v.penalty}장을 먹어요.`; })(); const withCatch = (lines: string[]) => (catchLine ? [catchLine, ...lines] : lines).join('\n'); diff --git a/apps/web/src/games/one-card/index.tsx b/apps/web/src/games/one-card/index.tsx index abbf490..5b85673 100644 --- a/apps/web/src/games/one-card/index.tsx +++ b/apps/web/src/games/one-card/index.tsx @@ -3,14 +3,15 @@ import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type import type { Card, CardFace, Color, LogEntry, OneCardOptions, OneCardView, SeatView, Suit } from '@bg/games/one-card'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar, Sheet } from '../../components/ui'; -import { TurnTimer } from '../../components/TurnTimer'; +import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { PlayingCard } from '../../components/cards/PlayingCard'; -import { haptic, sounds } from '../../lib/feedback'; +import { haptic, sounds, tone } from '../../lib/feedback'; import { useSeatRows } from '../../lib/seat-rows'; import type { BoardProps, GameUI, OptionsProps } from '../types'; 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'; const SUITS: Suit[] = ['S', 'H', 'D', 'C']; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; @@ -71,7 +72,7 @@ const CSS = ` .oc-pile .cnt { position: absolute; right: -6px; bottom: -8px; background: #111827; color: #fff; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .85rem; } .oc-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); } .oc-discard > .oc-face { position: absolute; inset: 0; } -.oc-discard > .oc-face.top { animation: oc-fly .28s ease-out; } +.oc-discard > .oc-face.top { animation: oc-fly .32s cubic-bezier(.2,.8,.3,1.1); } .oc-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 4px; border-radius: 10px; } .oc-info { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); } .oc-info .row { gap: 6px; } @@ -101,6 +102,11 @@ const CSS = ` font-weight: 900; font-size: 1.02rem; line-height: 1.1; padding: 0; cursor: pointer; box-shadow: 0 3px 8px rgba(0,0,0,.25); } .oc-onebtn:disabled { background: var(--surface-2); color: var(--text-sub); border-color: var(--border); box-shadow: none; cursor: not-allowed; } .oc-onebtn:not(:disabled) { animation: oc-shake .3s ease-in-out 3; } +.oc-onebtn.urgent { animation: oc-shake .3s ease-in-out 3, oc-urgent 1s ease-in-out .9s infinite; } +.oc-onebtn.wait { font-size: .85rem; } +@keyframes oc-urgent { 50% { transform: scale(1.1); box-shadow: 0 0 0 6px rgba(251,191,36,.55), 0 0 22px rgba(245,158,11,.9); } } +.oc-shuf { display: block; width: 100%; height: 100%; animation: oc-shuffle .6s ease both; } +@keyframes oc-shuffle { 20% { transform: translateX(-10px) rotate(-8deg); } 40% { transform: translateX(10px) rotate(8deg); } 60% { transform: translateX(-6px) rotate(-4deg); } 80% { transform: translateY(-6px); } } .oc-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; } .oc-tools .segmented button { min-height: 40px; padding: 0 12px; } .oc-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 8px; } @@ -112,7 +118,7 @@ const CSS = ` .oc-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; } .oc-rules td, .oc-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); } .oc-rules .oc-face { width: 34px; height: 48px; } -@keyframes oc-fly { from { transform: translate(-40px, 30px) scale(.8); opacity: .3; } to { transform: none; opacity: 1; } } +@keyframes oc-fly { from { transform: translate(var(--fx, -40px), var(--fy, 30px)) rotate(-25deg) scale(.75); opacity: .4; } } @keyframes oc-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } } @keyframes oc-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } } /* PC/tablet: many players stack into even rows (9 → 5 + 4) instead of scrolling sideways. Phones keep one swipeable row. */ @@ -158,7 +164,7 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView const u = userOf(players, s.id); const place = v.result?.players.find((p) => p.player === s.id)?.rank; return ( -
  • +
  • {u.nickname} @@ -186,8 +192,43 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView // ---------------------------------------------------------------- table -function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView; players: Record; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void }) { +/** The stacked attack: counts up card by card (with a rising tick) when someone adds to it, and grows with the count. */ +function AttackCount({ n, uno }: { n: number; uno: boolean }) { + const [shown, setShown] = useState(n); + const prev = useRef(n); + useEffect(() => { + const from = prev.current; + prev.current = n; + if (n <= from) { + setShown(n); + return; + } + let k = Math.max(from, 1); + setShown(k); + if (k >= n) return; + const id = window.setInterval( + () => { + k += 1; + setShown(k); + tone(320 + k * 45, 55, 'square', 0.035); + if (k >= n) window.clearInterval(id); + }, + Math.max(45, Math.min(110, 420 / (n - from))), + ); + return () => window.clearInterval(id); + }, [n]); + if (n <= 0) return null; + return ( + + +{shown}장! + {uno ? '먹을 카드' : '공격 누적'} + + ); +} + +function TableArea({ v, players, canDraw, onDraw, onDropCard, fx }: { v: OneCardView; players: Record; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void; fx: Fx }) { const [over, setOver] = useState(false); + const from = fx.playFrom && fx.playFrom.discard === v.discardCount ? fx.playFrom : null; const pw = 'clamp(64px, 9vw, 92px)'; const recent = v.recent; const top = recent[recent.length - 1]; @@ -202,7 +243,9 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView onClick={onDraw} aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`} > - + + + {v.drawPileCount} @@ -228,21 +271,23 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView const last = i === arr.length - 1; const rot = last ? 0 : (i - arr.length + 1) * 9; return ( - + ); })}
    - {v.pendingAttack > 0 && ( - - +{v.pendingAttack}장! - - )} +
    - ↻ + + ↻ + {v.direction === 1 ? '시계 방향' : '반대 방향'} {v.extraTurn && K: 한 번 더} @@ -272,6 +317,15 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView )}
    + {fx.flash &&
    } +
    + {fx.banners.map((b) => ( +
    + {b.text} + {b.sub && {b.sub}} +
    + ))} +
    ); } @@ -297,11 +351,10 @@ interface PickState { kind: 'suit' | 'color'; } -function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record }) { +function MyHand({ v, act, pending, players, arrived }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record; arrived: Record }) { const my = v.my!; const [sortBy, setSortBy] = useState<'suit' | 'rank'>('suit'); const [sel, setSel] = useState([]); - const [declare, setDeclare] = useState(true); const [hints, setHints] = useState(true); const [pick, setPick] = useState(null); const [note, setNote] = useState(''); @@ -314,15 +367,14 @@ function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown setPick(null); setNote(''); }, [turnKey]); - useEffect(() => setDeclare(true), [v.turnNo]); const byId = (id: string) => my.hand.find((c) => c.id === id); const sameRank = (a: Card, b: Card) => a.kind === 'std' && b.kind === 'std' && a.rank === b.rank; - const leavesOne = my.hand.length - Math.max(1, sel.length) === 1; + const leavesOne = sel.length > 0 && my.hand.length - sel.length === 1 && !v.options.autoDeclare; + // Playing never calls "원카드!" (§5.3): that is the round button's own press afterwards. const send = (ids: string[], extra: Record = {}) => { - const leaves = my.hand.length - ids.length === 1; - act({ type: 'play', cardIds: ids, ...extra, ...(leaves && declare ? { declareOneCard: true } : {}) }); + act({ type: 'play', cardIds: ids, ...extra }); setSel([]); setPick(null); }; @@ -410,7 +462,8 @@ function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown )} {myTurn && leavesOne && ( - + + 내고 나면 1장이 남아요. 낸 다음 [원카드!]를 따로 눌러요. + )} - +
    ); } +/** + * ms until others may catch the open window's owner (0 = now / not waiting). The owner may call at once; everyone + * else waits out the protection time (`oneCardGrace`), counted on the server clock. + */ +function useCatchWait(v: OneCardView): number { + const now = useServerNow(200); + const w = v.oneCardWindow; + if (!w || w.declared || w.player === v.me) return 0; + // A little margin so a press right at the end is not refused for clock drift. + return Math.max(0, w.catchFrom + 100 - now); +} + +/** The round "원카드!" button: call my own one card, or catch someone who forgot (after the protection time). */ +function OneCardButton({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record }) { + const my = v.my!; + const w = v.oneCardWindow; + const wait = useCatchWait(v); + const mine = !!w && w.player === v.me; + const can = my.canDeclare && !pending && wait === 0; + const secs = Math.ceil(wait / 1000); + const label = !my.canDeclare || !w ? '원카드 (지금은 누를 수 없어요)' : mine ? '원카드 외치기' : wait > 0 ? `${nick(players, w.player)}님 잡기, ${secs}초 뒤에 누를 수 있어요` : `${nick(players, w.player)}님 잡기`; + return ( + + ); +} + +/** For players already out of the round: they may still catch. */ +function CatchButton({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record }) { + const wait = useCatchWait(v); + const who = v.oneCardWindow ? nick(players, v.oneCardWindow.player) : ''; + return ( + + ); +} + // ---------------------------------------------------------------- prompts function Wild4Panel({ v, players, act, pending }: { v: OneCardView; players: Record; act: (a: unknown) => void; pending: boolean }) { @@ -673,9 +764,12 @@ function OneCardBoard({ view: v, me, players, act, pending, deadline }: BoardPro const opps = useSeatRows(others.length); const canDraw = !!v.my?.canDraw && !pending; const meSeat = v.seats.find((s) => s.id === me); + const rootRef = useRef(null); + const layerRef = useRef(null); + const fx = useOneCardFx({ view: v, me, nick: (id) => nick(players, id) }, rootRef, layerRef); return ( -
    - +
    +