/** 클루 화면 (docs/games/clue.md §9). */ import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import type { ClueOptions, ClueView, SuggestionView } from '@bg/games/clue'; import { PASSAGES, ROOMS, ROOM_KO, SUSPECTS, SUSPECT_KO, WEAPONS, WEAPON_KO, ITEM_KO, categoryOf, distTo, itemOf, roomAt, type Item, type Pos, type Room, type Suspect, type Weapon, } from '@bg/games/clue/board'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; import { haptic, sfx, sounds, tone } from '../../lib/feedback'; 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', mustard: '#ca8a04', white: '#f5f5f4', green: '#15803d', peacock: '#2563eb', plum: '#7e22ce', }; const SUSPECT_SHORT: Record = { scarlet: '스', mustard: '머', white: '화', green: '그', peacock: '피', plum: '플' }; export const WEAPON_ICON: Record = { candlestick: '🕯️', dagger: '🗡️', pipe: '🔩', revolver: '🔫', rope: '🪢', wrench: '🔧' }; export const ROOM_ICON: Record = { kitchen: '🍳', ballroom: '💃', conservatory: '🌿', dining: '🍽️', billiard: '🎱', library: '📚', lounge: '🛋️', hall: '🚪', study: '🖋️' }; const CAT_KO = { suspect: '용의자', weapon: '흉기', room: '장소' } as const; const iconOf = (x: Item) => (categoryOf(x) === 'suspect' ? '' : categoryOf(x) === 'weapon' ? WEAPON_ICON[x as Weapon] : ROOM_ICON[x as Room]); const AREA: Record = { kitchen: 'k', ballroom: 'b', conservatory: 'c', dining: 'd', billiard: 'bi', library: 'li', lounge: 'lo', hall: 'h', study: 's' }; const DICE = ['', '⚀', '⚁', '⚂', '⚃', '⚄', '⚅']; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const triple = (x: { suspect: Suspect; weapon: Weapon; room: Room }) => `${SUSPECT_KO[x.suspect]} · ${WEAPON_KO[x.weapon]} · ${ROOM_KO[x.room]}`; /** "식당으로" / "서재로" / "홀로" (ㄹ 받침도 "로"). */ const ro = (word: string) => { const c = word.charCodeAt(word.length - 1); const jong = c >= 0xac00 && c <= 0xd7a3 ? (c - 0xac00) % 28 : 0; return `${word}${jong === 0 || jong === 8 ? '로' : '으로'}`; }; const lastOf = (xs: readonly T[]): T | undefined => xs[xs.length - 1]; /** Clock length for the timer ring (무제한 has no deadline, so the ring only shows for away players' grace). */ function totalMsOf(v: ClueView): number { if (v.phase.kind === 'refute') return 20_000; if ((v.idle[v.current] ?? 0) >= 3) return 10_000; return (v.options.turnSeconds ?? 60) * 1000; } /** Game sounds on top of the shared palette (site volume applies). */ const clSound = { /** "그건 바로…!" a suggestion is made: a low questioning motif. */ suggest: () => [330, 392, 466].forEach((f, i) => tone(f, 150, 'triangle', 0.1, i * 110)), /** Nobody could show a card: a suspenseful low "dun-dun". */ noneShown: () => { tone(196, 260, 'sawtooth', 0.05); tone(185, 420, 'sawtooth', 0.05, 280); }, /** Walking a few squares in the hallway. */ steps: (n: number) => { for (let i = 0; i < Math.min(4, n); i++) tone(i % 2 ? 520 : 440, 45, 'triangle', 0.09, i * 120); }, }; const posKey = (p: Pos) => JSON.stringify(p); /** The player the game waits on (refuter while a card is being chosen). */ const waitingOn = (v: ClueView): string => (v.phase.kind === 'refute' ? v.phase.refuter : v.current); /** Where a token in the corridor is, in words. */ function hallwayText(p: Pos): string { if ('at' in p) return p.at.startsWith('start-') ? '출발점' : ROOM_KO[p.at as Room]; let best: Room = 'hall'; for (const r of ROOMS) if (distTo(p, r) < distTo(p, best)) best = r; return `${ROOM_KO[best]}까지 ${distTo(p, best)}칸`; } /** Cards whose place the viewer knows (not in the case file): own, face up, shown to me. */ function knownCards(v: ClueView): Map { const out = new Map(); for (const c of v.myHand ?? []) out.set(itemOf(c), '내 카드'); for (const c of v.publicCards) if (!out.has(itemOf(c))) out.set(itemOf(c), '공개 카드'); return out; } const CSS = ` .cl-board { position: relative; width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; } .cl-top { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 12px; align-items: start; } .cl-map { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-rows: repeat(4, minmax(84px, auto)); grid-template-areas: "k b c" "d m bi" "d m li" "lo h s"; gap: 6px; background: var(--wood); padding: 8px; border-radius: var(--radius-lg); box-shadow: var(--shadow); } .cl-room { position: relative; display: flex; flex-direction: column; align-items: stretch; gap: 3px; text-align: left; border-radius: 10px; padding: 6px 7px; background: var(--surface); color: var(--text); border: 2px solid var(--border); font: inherit; min-width: 0; } button.cl-room { cursor: pointer; } button.cl-room:disabled { cursor: default; } .cl-room.reach { border-color: var(--success); background: color-mix(in srgb, var(--success-soft) 70%, var(--surface)); } .cl-room.far { border-style: dashed; border-color: var(--primary); } .cl-room.sel { outline: 4px solid var(--focus); outline-offset: 1px; } .cl-room.here { box-shadow: inset 0 0 0 2px var(--primary); } .cl-room:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .cl-rname { font-weight: 800; font-size: .92rem; line-height: 1.15; display: flex; gap: 4px; align-items: center; min-width: 0; } .cl-rname span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cl-room.reach .cl-rname, .cl-room.far .cl-rname { padding-right: 36px; } .cl-pass { position: absolute; right: 4px; bottom: 3px; font-size: .7rem; color: var(--text-sub); font-weight: 700; } .cl-dist { position: absolute; right: 5px; top: 4px; font-size: .75rem; font-weight: 800; border-radius: 999px; padding: 0 6px; background: var(--surface-2); } .cl-room.reach .cl-dist { background: var(--success); color: #fff; } .cl-things { display: flex; flex-wrap: wrap; gap: 3px; align-items: center; min-height: 22px; } .cl-weap { font-size: 1rem; line-height: 1; } .cl-tok { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 50%; font-size: .72rem; font-weight: 900; color: #fff; border: 2px solid rgba(0,0,0,.35); flex: none; } .cl-tok.light { color: #1c1917; } .cl-tok.me { box-shadow: 0 0 0 3px var(--focus); } .cl-mid { grid-area: m; background: color-mix(in srgb, var(--surface-2) 85%, var(--wood)); color: var(--text); border-radius: 10px; padding: 6px 8px; display: flex; flex-direction: column; gap: 4px; font-size: .8rem; min-width: 0; } .cl-mid ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 3px; } .cl-mid li { display: flex; gap: 5px; align-items: center; min-width: 0; } .cl-mid li span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cl-env { font-weight: 800; display: flex; gap: 4px; align-items: center; } .cl-panel { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 10px; } .cl-chips { display: flex; flex-wrap: wrap; gap: 6px; } .cl-chip { min-height: 44px; border-radius: 12px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font: inherit; font-weight: 700; padding: 4px 10px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; } .cl-chip[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); } .cl-chip.known { opacity: .55; } .cl-chip.known::after { content: '✗'; color: var(--danger); font-weight: 900; } .cl-chip:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .cl-btns { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; } .cl-btns .btn { min-height: 52px; } .cl-dice { font-size: 2.6rem; line-height: 1; display: flex; gap: 6px; align-items: center; } .cl-dice b { font-size: 1.2rem; margin-left: 6px; } .cl-cards { display: flex; flex-wrap: wrap; gap: 6px; } .cl-card { display: inline-flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; width: 74px; min-height: 86px; border-radius: 10px; background: linear-gradient(160deg, #fffaf0, #f1e6cf); color: #2b2118; border: 2px solid #b79c6b; padding: 4px; text-align: center; font-weight: 800; font-size: .8rem; box-shadow: 0 2px 0 rgba(0,0,0,.25); } .cl-card .ic { font-size: 1.5rem; line-height: 1.1; } .cl-card .cat { font-size: .65rem; font-weight: 700; opacity: .7; } button.cl-card { cursor: pointer; font: inherit; font-weight: 800; font-size: .8rem; } button.cl-card:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); } .cl-card.new { animation: cl-pop .6s ease-out; animation-delay: var(--anim-delay, 0ms); animation-fill-mode: both; } .cl-dice span { display: inline-block; } .cl-room.landed { animation: cl-land .7s ease-out; } .cl-banner { position: absolute; left: 50%; top: 30%; translate: -50% 0; z-index: 8; pointer-events: none; border-radius: 18px; padding: 12px 22px; font-weight: 900; font-size: 1.35rem; background: var(--surface); box-shadow: 0 10px 30px rgba(0,0,0,.35); text-align: center; white-space: nowrap; max-width: 92vw; overflow: hidden; text-overflow: ellipsis; } .cl-banner.ok { border: 4px solid var(--success); color: var(--success); } .cl-banner.bad { border: 4px solid var(--danger); color: var(--danger); } .cl-banner.info { border: 4px solid var(--primary); color: var(--text); } @keyframes cl-land { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--focus) 80%, transparent); } 100% { box-shadow: 0 0 0 12px transparent; } } @keyframes cl-pop { 0% { transform: scale(.6) rotate(-8deg); opacity: .2; } 100% { transform: none; opacity: 1; } } .cl-sec { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .cl-note { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; } .cl-note h4 { margin: 0 0 4px; font-size: .9rem; } .cl-note ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } .cl-note li { display: flex; align-items: center; gap: 6px; min-height: 34px; font-size: .9rem; } .cl-note li .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cl-note li .why { font-size: .72rem; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 7.5em; } .cl-note li.auto .nm { text-decoration: line-through; color: var(--text-sub); } .cl-mark { width: 34px; height: 30px; border-radius: 8px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font-weight: 900; cursor: pointer; flex: none; font-size: 1rem; } .cl-mark.x { color: var(--danger); } .cl-mark.o { color: var(--success); border-color: var(--success); } .cl-mark.q { color: var(--warning); } .cl-mark:disabled { cursor: default; opacity: .8; } .cl-mark:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .cl-badge { display: inline-block; border-radius: 999px; padding: 1px 8px; font-weight: 800; font-size: .75rem; background: var(--surface-2); color: var(--text); white-space: nowrap; } .cl-badge.turn { background: var(--focus); color: #1c1e21; } .cl-badge.out { background: var(--danger-soft); color: var(--danger); } .cl-badge.ok { background: var(--success-soft); color: var(--success); } .cl-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 5px; max-height: 280px; overflow: auto; font-size: .86rem; } .cl-log li { line-height: 1.35; } .cl-shown { font-weight: 800; color: var(--primary); } @media (max-width: 719px) { .cl-top { grid-template-columns: minmax(0, 1fr); } .cl-board { max-height: none; overflow: visible; } .cl-map { gap: 4px; padding: 5px; grid-template-rows: repeat(4, minmax(76px, auto)); } .cl-room { padding: 4px 5px; } .cl-rname { font-size: .8rem; } .cl-tok { width: 21px; height: 21px; font-size: .66rem; } .cl-note { grid-template-columns: minmax(0, 1fr); } .cl-card { width: 66px; min-height: 78px; } } /* PC: fill the play column. Wide screens put the map on the left and the actions, my cards and notes on the right; room text, tokens and cards grow with the play area. */ @media (min-width: 1100px) { .cl-board { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; } .cl-rname { font-size: clamp(.92rem, calc(var(--play-h) * .017), 1.25rem); } .cl-tok { width: clamp(24px, calc(var(--play-h) * .03), 34px); height: clamp(24px, calc(var(--play-h) * .03), 34px); font-size: clamp(.72rem, calc(var(--play-h) * .013), .95rem); } .cl-weap { font-size: clamp(1rem, calc(var(--play-h) * .024), 1.6rem); } .cl-mid { font-size: clamp(.8rem, calc(var(--play-h) * .014), 1rem); } .cl-card { width: clamp(74px, calc(var(--play-w) * .055), 100px); min-height: clamp(86px, calc(var(--play-w) * .064), 116px); } } @media (min-width: 1700px) { .cl-board { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto minmax(0, 1fr); grid-template-areas: "map act" "map cards" "map note"; } .cl-top { display: contents; } .cl-map { grid-area: map; grid-template-rows: repeat(4, minmax(84px, 1fr)); } .cl-top > .cl-panel { grid-area: act; } .cl-board > section.cl-sec { grid-area: cards; } .cl-board > details.cl-sec { grid-area: note; } .cl-note li { min-height: clamp(34px, calc((var(--play-h) - 400px) / 11), 48px); } } /* Tokens / weapons on the map are lifted above the rooms while they slide (see slideFrom). */ .cl-map [data-tok], .cl-map [data-weap] { position: relative; } .fx-ghost.cl-ghost { display: flex; align-items: center; justify-content: center; border-radius: 8px; background: linear-gradient(160deg, #fffaf0, #f1e6cf); border: 2px solid #b79c6b; color: #2b2118; font: 800 1.1rem/1 system-ui, sans-serif; box-shadow: 0 4px 10px rgba(0,0,0,.35); } .fx-ghost.cl-ghost.back { background: repeating-linear-gradient(45deg, #7c2d12 0 6px, #9a3412 6px 12px); border-color: #fff7ed; } @media (prefers-reduced-motion: reduce) { .cl-card.new, .cl-room.landed { animation: none; } } `; // ---------------------------------------------------------------- small pieces /** * Slides an element that just moved from (dx, dy) px away back to its place in a little hop, above the other rooms. * Returns whether it animated (the caller staggers several). */ function slideFrom(el: HTMLElement | null, dx: number, dy: number, delay: number): boolean { const d = Math.hypot(dx, dy); if (!el || d < 4 || reducedMotion() || typeof el.animate !== 'function') return false; // The CSS pop of a freshly mounted token would scale the slide; the slide replaces it. el.getAnimations().forEach((a) => a.cancel()); el.style.zIndex = '4'; const lift = Math.min(36, 10 + d * 0.15); 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; return true; } function Token({ x, me, pop, onMap }: { x: Suspect; me?: boolean; pop?: boolean; onMap?: boolean }) { return ( {SUSPECT_SHORT[x]} ); } function Card({ id, onClick, can, fresh, flip, label, delay }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; flip?: boolean; label?: string; delay?: number }) { const x = itemOf(id); const cat = categoryOf(x); const body = ( <> {cat === 'suspect' ? : iconOf(x)} {ITEM_KO[x]} {CAT_KO[cat]} ); const aria = label ?? `${CAT_KO[cat]} 카드 ${ITEM_KO[x]}`; if (onClick) return ( ); return ( {body} ); } // ---------------------------------------------------------------- board function ClueBoard({ view: v, me, players, act, pending }: BoardProps) { const amPlayer = !!me && v.seats.includes(me); const myTurn = amPlayer && v.current === me && !v.out[me!] && v.phase.kind !== 'refute' && v.phase.kind !== 'finished'; const [sel, setSel] = useState(null); const [announce, setAnnounce] = useState(''); const prevTurn = useRef(`${v.current}|${v.turnNo}`); const prevSg = useRef(JSON.stringify(lastOf(v.suggestions) ?? null)); const prevView = useRef(v); const [banner, setBanner] = useState<{ key: string; kind: 'ok' | 'bad' | 'info'; text: string } | null>(null); const [landed, setLanded] = useState<{ room: Room; key: number } | null>(null); useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]); // Tokens and weapons slide on the map from where they were (anyone's move, a suggestion pulling them into a room). // Places are kept relative to the map, so scrolling between two moves does not matter. const placeSig = JSON.stringify([v.pos, v.weaponAt]); const places = useRef | null>(null); useLayoutEffect(() => { const map = document.querySelector('.cl-map'); if (!map) return; const m = map.getBoundingClientRect(); const before = places.current; const now = new Map(); map.querySelectorAll('[data-tok], [data-weap]').forEach((el) => { const r = el.getBoundingClientRect(); now.set(el.dataset.tok ? `t:${el.dataset.tok}` : `w:${el.dataset.weap}`, { x: r.left + r.width / 2 - m.left, y: r.top + r.height / 2 - m.top }); }); places.current = now; if (!before) return; let k = 0; for (const [key, at] of now) { const was = before.get(key); if (!was) continue; const [kind, id] = [key.slice(0, 1), key.slice(2)]; const el = map.querySelector(kind === 't' ? `[data-tok="${cssEsc(id)}"]` : `[data-weap="${cssEsc(id)}"]`); if (slideFrom(el, was.x - at.x, was.y - at.y, k * 90)) k++; } }, [placeSig]); // Sounds and highlights for what anyone just did: dice, moves, passages, suggestions, answers, accusations. useEffect(() => { const p = prevView.current; prevView.current = v; if (p === v) return; if (v.dice && (!p.dice || p.turnNo !== v.turnNo || p.dice[0] !== v.dice[0] || p.dice[1] !== v.dice[1])) sfx.dice(); const mover = v.suspectOf[v.current]; let moved = false; for (const x of SUSPECTS) { if (posKey(v.pos[x]) === posKey(p.pos[x])) continue; moved = true; const r = roomAt(v.pos[x]); if (r && x === mover) setLanded({ room: r, key: Date.now() }); } const sgNew = v.suggestions.length > p.suggestions.length; if (moved && !sgNew && mover) { const from = roomAt(p.pos[mover]); const to = roomAt(v.pos[mover]); if (from && to && PASSAGES[from] === to && !v.dice) sfx.whoosh(); else if (to) sfx.piece(); else clSound.steps(v.dice ? v.dice[0] + v.dice[1] : 3); } if (sgNew) clSound.suggest(); const lastNow = lastOf(v.suggestions); const lastPrev = lastOf(p.suggestions); const tokOf = (player: string) => { const x = v.suspectOf[player]; return x ? document.querySelector(`.cl-map [data-tok="${cssEsc(x)}"]`) : null; }; // The three suggested cards fly from the suggester's token into the case file in the middle. if (sgNew && lastNow) { const from = tokOf(lastNow.by); const mid = document.querySelector('.cl-mid'); [SUSPECT_SHORT[lastNow.suspect], WEAPON_ICON[lastNow.weapon], ROOM_ICON[lastNow.room]].forEach((label, i) => flyGhost(from, mid, { label, className: 'cl-ghost', delay: 250 + i * 140, ms: 520 }), ); } if (lastNow && !sgNew && lastPrev && v.suggestions.length === p.suggestions.length && !lastPrev.refuter && lastNow.refuter) { if (lastNow.shown && (lastNow.by === me || lastNow.refuter === me)) sfx.cardFlip(); else sfx.cardDeal(); // Everyone else sees a face-down card going from the refuter to the suggester (mine flips open in the panel). if (lastNow.by !== me) flyGhost(tokOf(lastNow.refuter), tokOf(lastNow.by), { className: 'cl-ghost back', ms: 520 }); } if (lastNow && p.phase.kind === 'refute' && v.phase.kind !== 'refute' && !lastNow.refuter) clSound.noneShown(); if (lastNow && sgNew && v.phase.kind === 'afterSuggest' && !lastNow.refuter) clSound.noneShown(); if (v.accusations.length > p.accusations.length) { const a = v.accusations[v.accusations.length - 1]!; const who = a.by === me ? '내' : `${nick(players, a.by)}님의`; if (a.correct) { // The game ends here: the room plays win / lose. setBanner({ key: `a${v.accusations.length}`, kind: 'ok', text: `⚖️ ${who} 고발이 맞았어요!` }); } else { sfx.bad(); setBanner({ key: `a${v.accusations.length}`, kind: 'bad', text: `⚖️ ${who} 고발이 틀렸어요 · 탈락` }); } } }, [v]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!banner) return; const t = setTimeout(() => setBanner(null), fxMs(1700)); return () => clearTimeout(t); }, [banner]); useEffect(() => { if (!landed) return; const t = setTimeout(() => setLanded(null), fxMs(800)); return () => clearTimeout(t); }, [landed]); useEffect(() => { const key = `${v.current}|${v.turnNo}`; if (key !== prevTurn.current && v.phase.kind !== 'finished') { if (v.current === me) { haptic(40); sounds.myTurn(); setAnnounce('내 차례예요.'); } else setAnnounce(`${nick(players, v.current)}님 차례예요.`); } prevTurn.current = key; }, [v.current, v.turnNo]); // eslint-disable-line react-hooks/exhaustive-deps // Read out suggestions and their answers. const last = lastOf(v.suggestions); const sgKey = JSON.stringify(last ?? null); useEffect(() => { if (sgKey === prevSg.current) return; prevSg.current = sgKey; if (!last) return; const who = last.by === me ? '내가' : `${nick(players, last.by)}님이`; const head = `${who} ${ro(triple(last))} 추리했어요.`; if (v.phase.kind === 'refute' && v.phase.refuter === me) { haptic([30, 40, 30]); sounds.myTurn(); setAnnounce(`${head} 보여 줄 카드를 골라 주세요.`); } else if (last.refuter) setAnnounce(`${head} ${nick(players, last.refuter)}님이 카드를 보여 줬어요.${last.shown && last.by === me ? ` 보여 준 카드는 ${ITEM_KO[itemOf(last.shown)]}예요.` : ''}`); else if (v.phase.kind === 'afterSuggest' || last.passed.length) setAnnounce(`${head} 아무도 카드를 보여 주지 못했어요.`); }, [sgKey]); // eslint-disable-line react-hooks/exhaustive-deps return (
{amPlayer && } {amPlayer && } {banner && (
{banner.text}
)}

{announce}

); } function Mansion({ view: v, me, myTurn, sel, setSel, landed, }: { view: ClueView; me: string | null; myTurn: boolean; sel: Room | null; setSel: (r: Room | null) => void; landed: Room | null; }) { const mySuspect = me ? v.suspectOf[me] : undefined; const myPos = mySuspect ? v.pos[mySuspect] : null; const here = myPos ? roomAt(myPos) : null; const ph = v.phase.kind; const free = v.options.movement === 'free'; const picking = myTurn && ((ph === 'move' && free) || ph === 'moveTo'); const sum = v.dice ? v.dice[0] + v.dice[1] : 0; const owner = (x: Suspect) => v.seats.find((p) => v.suspectOf[p] === x); const inRoom = (r: Room) => SUSPECTS.filter((x) => roomAt(v.pos[x]) === r); const hall = SUSPECTS.filter((x) => !roomAt(v.pos[x])); return (
{ROOMS.map((r) => { const toks = inRoom(r); const weaps = WEAPONS.filter((w) => v.weaponAt[w] === r); const d = v.distances?.[r]; const can = picking && r !== here; const reach = can && (free || (d !== undefined && d <= sum)); const pass = PASSAGES[r]; const cls = ['cl-room', can ? (reach ? 'reach' : 'far') : '', sel === r ? 'sel' : '', r === here ? 'here' : '', landed === r ? 'landed' : ''].filter(Boolean).join(' '); const label = [ ROOM_KO[r], r === here ? '내가 있는 방' : '', can ? (free ? '갈 수 있어요' : reach ? `${d}칸, 들어갈 수 있어요` : `${d}칸, 이번에는 못 닿아요(걸어가기)`) : '', toks.length ? `말: ${toks.map((x) => SUSPECT_KO[x]).join(', ')}` : '', weaps.length ? `흉기: ${weaps.map((w) => WEAPON_KO[w]).join(', ')}` : '', pass ? `비밀 통로로 ${ROOM_KO[pass]}와 이어져요` : '', ] .filter(Boolean) .join(', '); const inner = ( <> {ROOM_ICON[r]} {ROOM_KO[r]} {can && !free && d !== undefined && {d}칸} {toks.map((x) => ( ))} {weaps.map((w) => ( {WEAPON_ICON[w]} ))} {pass && ( ↗ {ROOM_KO[pass]} )} ); return can ? ( ) : (
{inner}
); })}
📁 사건 봉투 {hall.length > 0 ? (
    {hall.map((x) => { const p = owner(x); return (
  • {hallwayText(v.pos[x])}
  • ); })}
) : ( 복도에 아무도 없어요 )}
); } function ChipRow({ label, items, value, onPick, known }: { label: string; items: readonly T[]; value: T | null; onPick: (x: T) => void; known: Map }) { return (
{label}
{items.map((x) => ( ))}
); } function AccusePanel({ act, pending, onCancel, known }: { act: (a: unknown) => void; pending: boolean; onCancel: () => void; known: Map }) { const [s, setS] = useState(null); const [w, setW] = useState(null); const [r, setR] = useState(null); const [sure, setSure] = useState(false); const done = s && w && r; return (
e.key === 'Escape' && onCancel()}> 고발하기: 봉투 속 정답을 말해요 맞히면 바로 이기고, 틀리면 탈락해요(카드 보여 주기는 계속해요). 한 사람에 한 번만 할 수 있어요. (setS(x), setSure(false))} known={known} /> (setW(x), setSure(false))} known={known} /> (setR(x), setSure(false))} known={known} />
{!sure ? ( ) : ( )}
); } function SuggestPanel({ room, act, pending, known, onAccuse }: { room: Room; act: (a: unknown) => void; pending: boolean; known: Map; onAccuse: () => void }) { const [s, setS] = useState(null); const [w, setW] = useState(null); return (
{ROOM_ICON[room]} {ROOM_KO[room]}에서 추리해요 범인과 흉기를 하나씩 고르면, 다음 사람부터 차례로 그중 가진 카드를 나에게만 보여 줘요. 고른 용의자 말과 흉기는 이 방으로 옮겨져요.
); } function LastResult({ view: v, me, players }: { view: ClueView; me: string | null; players: Record }) { const last = lastOf(v.suggestions); if (!last || last.turnNo !== v.turnNo) return null; const by = last.by === me ? '내' : `${nick(players, last.by)}님의`; return (
{by} 추리: {triple(last)} {last.passed.length > 0 && · 못 보여 준 사람: {last.passed.map((p) => (p === me ? '나' : nick(players, p))).join(', ')}} {last.refuter ? ( last.shown ? (
{last.refuter === me ? `내가 ${nick(players, last.by)}님에게 보여 준 카드` : `${nick(players, last.refuter)}님이 보여 준 카드`}
{last.by === me ? '추리 노트에 자동으로 표시했어요.' : '다른 사람은 어떤 카드인지 몰라요.'}
) : ( {nick(players, last.refuter)}님이 {last.by === me ? '나' : `${nick(players, last.by)}님`}에게 카드 한 장을 몰래 보여 줬어요. ) ) : ( v.phase.kind !== 'refute' && 아무도 카드를 보여 주지 못했어요! )}
); } function ActionPanel({ view: v, me, players, act, pending, myTurn, sel, setSel, }: { view: ClueView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; myTurn: boolean; sel: Room | null; setSel: (r: Room | null) => void; }) { const [accusing, setAccusing] = useState(false); const known = useMemo(() => { const k = knownCards(v); for (const sg of v.suggestions) if (sg.by === me && sg.shown && sg.refuter) k.set(itemOf(sg.shown), `${nick(players, sg.refuter)}님 카드`); return k; }, [v, me, players]); useEffect(() => setAccusing(false), [v.turnNo, v.phase.kind]); const ph = v.phase; if (ph.kind === 'finished') { return (
게임이 끝났어요 {v.final?.summary} {v.solution && (
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => ( ))}
)}
); } if (ph.kind === 'refute') { const sg = lastOf(v.suggestions)!; if (ph.refuter === me) { return (
{nick(players, sg.by)}님이 {ro(triple(sg))} 추리했어요 내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요.{v.options.turnSeconds === null ? '' : ' 20초 안에 안 고르면 자동으로 보여 줘요.'}
{(ph.canShow ?? []).map((c) => ( !pending && act({ type: 'show', card: c })} label={`${ITEM_KO[itemOf(c)]} 카드 보여 주기`} /> ))}
); } return (
{nick(players, ph.refuter)}님이 {sg.by === me ? '나' : `${nick(players, sg.by)}님`}에게 보여 줄 카드를 고르는 중이에요
); } if (!myTurn) { const doing: Record = { move: '이동하는 중이에요', moveTo: `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`, suggest: '추리할 카드를 고르는 중이에요', afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요', }; return (
{nick(players, v.current)}님이 {doing[ph.kind]} {me && v.seats.includes(me) && v.out[me] && 나는 고발이 틀려 탈락했어요. 다른 사람이 추리하면 카드 보여 주기는 계속해요.} 누가 무엇을 추리했고 누가 카드를 보여 줬는지 오른쪽 기록에서 볼 수 있어요.
); } if (accusing) return setAccusing(false)} known={known} />; const myPos = v.pos[v.suspectOf[me!]!]; const here = roomAt(myPos); const accuseBtn = ( ); if (ph.kind === 'suggest') return setAccusing(true)} />; if (ph.kind === 'afterSuggest') { return (
{accuseBtn}
); } const free = v.options.movement === 'free'; if (ph.kind === 'move' && !free) { const pass = here ? PASSAGES[here] : undefined; return (
내 차례예요. {here ? `지금 ${ROOM_KO[here]}에 있어요.` : `지금 복도(${hallwayText(myPos)})에 있어요.`}
{pass && ( )} {here && v.movedIn[me!] && ( )} {accuseBtn}
{here && v.movedIn[me!] && 다른 사람의 추리로 이 방에 불려 왔어요. 움직이지 않고 여기서 추리할 수 있어요.}
); } // Choosing where to go: free move, or after the dice. const sum = v.dice ? v.dice[0] + v.dice[1] : 0; const d = sel && v.distances ? v.distances[sel] : null; const enter = sel && (free || (d !== null && d <= sum)); return (
{v.dice && (
{DICE[v.dice[0]]} {DICE[v.dice[1]]} = {sum}칸
)} 지도에서 갈 방을 눌러 주세요. {free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`}
{sel && enter && ( )} {sel && !enter && d !== null && ( )} {!sel && ( )} {free && here && v.movedIn[me!] && ( )} {sel && ( )} {accuseBtn}
); } function MyCards({ view: v, me }: { view: ClueView; me: string }) { const mine = v.myHand ?? []; return (
내 카드 {mine.length}장 · {SUSPECT_KO[v.suspectOf[me]!]} 말 내 카드는 봉투에 없어요
{mine.map((c) => ( ))}
{v.publicCards.length > 0 && ( <> 모두에게 공개된 카드 {v.publicCards.length}장
{v.publicCards.map((c) => ( ))}
)}
); } // ---------------------------------------------------------------- notebook (kept on this device) type Mark = '' | 'x' | 'q' | 'o'; const NEXT: Record = { '': 'x', x: 'q', q: 'o', o: '' }; const MARK_TEXT: Record = { '': '', x: '✗', q: '?', o: '✓' }; const MARK_KO: Record = { '': '표시 없음', x: '아님(✗)', q: '모름(?)', o: '정답 같음(✓)' }; /** localStorage key: room code + game number (docs §9). Replays and other pages keep notes in memory only. */ function noteKey(gameNo: number): string | null { const m = typeof location !== 'undefined' ? /\/r\/(\d{6})/.exec(location.pathname) : null; return m ? `bg:clue:note:${m[1]}:${gameNo}` : null; } function Notebook({ view: v, me, players }: { view: ClueView; me: string; players: Record }) { const key = noteKey(v.gameNo); const [marks, setMarks] = useState>(() => { try { return key ? (JSON.parse(localStorage.getItem(key) ?? '{}') as Record) : {}; } catch { return {}; } }); const auto = useMemo(() => { const k = knownCards(v); for (const sg of v.suggestions) if (sg.by === me && sg.shown && sg.refuter && !k.has(itemOf(sg.shown))) k.set(itemOf(sg.shown), `${nick(players, sg.refuter)}님이 보여 줌`); return k; }, [v, me, players]); const set = (x: Item) => { const next = { ...marks, [x]: NEXT[marks[x] ?? ''] }; setMarks(next); try { if (key) localStorage.setItem(key, JSON.stringify(next)); } catch {} }; const group = (title: string, items: readonly Item[]) => (

{title}

    {items.map((x) => { const why = auto.get(x); const m: Mark = why ? 'x' : (marks[x] ?? ''); return (
  • {categoryOf(x) !== 'suspect' && {iconOf(x)} } {ITEM_KO[x]} {why && {why}}
  • ); })}
); return (
🗒️ 추리 노트 내 카드·공개 카드·나에게 보여 준 카드는 자동으로 ✗예요. 나머지는 눌러서 ✗ → ? → ✓ 로 바꿔요. 이 기기에만 저장돼요.
{group('범인', SUSPECTS)} {group('흉기', WEAPONS)} {group('장소', ROOMS)}
); } // ---------------------------------------------------------------- side type LogLine = { turn: number; order: number; text: string; shown?: string; mine?: boolean }; function logLines(v: ClueView, me: string | null, players: Record): LogLine[] { const who = (p: string) => (p === me ? '나' : `${nick(players, p)}님`); const subj = (p: string) => (p === me ? '내가' : `${nick(players, p)}님이`); const out: LogLine[] = []; v.suggestions.forEach((sg: SuggestionView, i) => { const answer = sg.refuter ? `${subj(sg.refuter)} 카드를 보여 줌` : v.phase.kind === 'refute' && i === v.suggestions.length - 1 ? '답을 기다리는 중' : '아무도 못 보여 줌'; const passed = sg.passed.length ? ` (못 보여 준 사람: ${sg.passed.map(who).join(', ')})` : ''; out.push({ turn: sg.turnNo, order: i, text: `🔍 ${who(sg.by)}: ${triple(sg)} → ${answer}${passed}`, shown: sg.shown ?? undefined, mine: sg.by === me || sg.refuter === me }); }); v.accusations.forEach((a, i) => out.push({ turn: a.turnNo, order: 1000 + i, text: `⚖️ ${who(a.by)} 고발: ${triple(a)} → ${a.correct ? '맞았어요!' : '틀려서 탈락'}` })); return out.sort((a, b) => a.turn - b.turn || a.order - b.order); } function ClueSide({ view: v, me, players, deadline }: BoardProps) { const running = v.phase.kind !== 'finished'; const lines = logLines(v, me, players); const wait = waitingOn(v); return ( <>
{running ? (v.phase.kind === 'refute' ? `${nick(players, wait)}님이 카드 고르는 중` : `${nick(players, v.current)}님 차례`) : '게임 끝'} {running && }
{optionsSummary(v.options)}
    {v.seats.map((p) => { const x = v.suspectOf[p]!; return (
  1. {nick(players, p)} {p === me && (나)} 카드 {v.handCounts[p]}장 {running && wait === p && {v.phase.kind === 'refute' ? '보여 주는 중' : '차례'}} {v.final?.winner === p && 승리} {v.left[p] ? 나감 : v.out[p] && 고발 실패}
  2. ); })}
{v.hands && v.solution && (
정답: {triple(v.solution)} {v.seats.map((p) => ( {nick(players, p)}: {v.hands![p]!.map((c) => ITEM_KO[itemOf(c)]).join(', ') || '없음'} ))}
)}
추리 기록 ({lines.length}) {lines.length === 0 ? (

아직 추리가 없어요.

) : (
    {[...lines].reverse().map((l, i) => (
  1. {l.text} {l.shown && [{ITEM_KO[itemOf(l.shown)]}]}
  2. ))}
)}
); } // ---------------------------------------------------------------- status function isMyTurn(v: ClueView, me: string | null): boolean { if (!me || !v.seats.includes(me) || v.phase.kind === 'finished' || v.left[me]) return false; if (v.phase.kind === 'refute') return v.phase.refuter === me; return v.current === me && !v.out[me]; } function statusText(v: ClueView, me: string | null, players: Record): string { if (v.phase.kind === 'finished') return v.final?.summary ?? '게임이 끝났어요'; if (isMyTurn(v, me)) { switch (v.phase.kind) { case 'move': return v.options.movement === 'free' ? '내 차례예요. 갈 방을 골라 주세요' : '내 차례예요. 주사위를 굴려 주세요'; case 'moveTo': return '내 차례예요. 들어갈 방을 골라 주세요'; case 'suggest': return '내 차례예요. 범인과 흉기를 골라 추리해 주세요'; case 'afterSuggest': return '내 차례예요. 고발하거나 차례를 끝내 주세요'; case 'refute': return `내 차례예요. ${nick(players, lastOf(v.suggestions)?.by ?? v.current)}님에게 보여 줄 카드를 골라 주세요`; } } const out = me && v.seats.includes(me) && v.out[me] ? '탈락 · ' : ''; if (v.phase.kind === 'refute') return `${out}${nick(players, v.phase.refuter)}님이 보여 줄 카드를 고르는 중이에요`; return `${out}${nick(players, v.current)}님 차례예요`; } // ---------------------------------------------------------------- options function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
{options.map(([k, l]) => ( ))}
); } function Options({ value: o, onChange }: OptionsProps) { const set = (patch: Partial) => onChange({ ...o, ...patch }); return (
이동 방식 set({ movement })} />
차례 제한 시간 set({ turnSeconds })} /> {o.turnSeconds === null && 차례와 카드 보여 주기에 시간 제한이 없어요. 연결이 끊긴 채 돌아오지 않는 사람만 자동으로 넘겨요.}
); } function optionsSummary(o: ClueOptions): string { return [o.movement === 'free' ? '빠른 이동' : '주사위 이동', o.turnSeconds === null ? '차례 시간 무제한' : `차례 ${o.turnSeconds}초`].join(' · '); } function Rules({ options }: { options?: ClueOptions }) { const free = options?.movement === 'free'; return (

저택에서 살인 사건이 일어났어요. 누가(범인), 무엇으로(흉기), 어디서(장소) 했는지 맞히는 추리 게임이에요. 3~6명이 할 수 있어요.

준비: 용의자 6장, 흉기 6장, 방 9장 중 종류마다 한 장씩 몰래 뽑아 사건 봉투에 넣어요. 이것이 정답이에요. 남은 18장은 모두에게 똑같이 나눠 주고, 똑같이 나누고 남는 카드(4명이면 2장, 5명이면 3장)는 모두에게 공개해요. 내 손에 있는 카드는 봉투에 없다는 뜻이에요. 각자 용의자 말 하나를 맡고, 스칼렛을 맡은 사람이 먼저 해요.

이동:{' '} {free ? '이 방은 "빠른 이동"이라 주사위 없이 아무 방이나 바로 들어가요(지금 있는 방 빼고).' : '주사위 2개를 굴려 나온 합만큼 복도를 걸어요. 지도에 칸 수가 나오고, 닿는 방(초록)에 바로 들어가요. 먼 방(점선)을 고르면 그쪽으로 걸어가다 차례가 끝나요. 모서리 방(부엌↔서재, 온실↔라운지)은 비밀 통로로 주사위 없이 바로 건너가요. 방금 있던 방에 다시 들어갈 수는 없어요.'}

추리: 방에 들어가면 "○○가, △△로, 이 방에서"라고 추리해요. 장소는 지금 있는 방이에요. 말한 용의자 말과 흉기가 그 방으로 옮겨져요. 그러면 내 다음 사람부터 차례로, 셋 중 하나라도 가진 사람이 그중 한 장을 나에게만 보여 줘요(여러 장이면 보여 주는 사람이 골라요). 한 사람이 보여 주면 거기서 멈추고, 다른 사람들은 누가 보여 줬는지만 알아요. 다른 사람의 추리로 내 말이 어떤 방에 불려 갔다면, 다음 내 차례에 움직이지 않고 그 방에서 추리할 수 있어요.

고발: 확신이 서면 내 차례 아무 때나 "범인·흉기·장소"를 말해 고발해요(장소는 어느 방이든 돼요). 한 사람에 한 번뿐이에요. 셋 다 맞으면 이기고, 틀리면 탈락해요. 탈락해도 다른 사람이 추리하면 카드는 계속 보여 줘야 해요. 모두 틀리면 아무도 못 이겨요.

추리 노트: 화면 아래 노트에 내 카드, 공개 카드, 나에게 보여 준 카드가 자동으로 ✗ 표시돼요. 나머지는 직접 눌러 ✗·?·✓를 적어 두세요(이 기기에만 저장돼요).

{options?.turnSeconds === null ? '이 방은 차례 시간이 무제한이에요. 연결이 끊긴 채 돌아오지 않으면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요(카드 보여 주기는 맞는 카드가 자동으로).' : '차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요.'}{' '} 게임 중에 나간 사람의 카드는 모두에게 공개돼요.

); } const ui: GameUI = { Board: ClueBoard, Side: ClueSide, statusText, isMyTurn, Options, optionsSummary, Rules, quickStart, helpNow, }; export default ui;