/** * 라이어 게임 화면 (docs/games/liar.md §9). * * Like 마피아 the board carries its own chat: the room chat panel and quick reactions are closed while the game runs * (`ownChat`), so nobody can hint the word around the game. The word sits on a hold-to-see card (screen sharing, * people next to you). Descriptions are a separate, round-by-round list next to the free-talk chat. */ import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; import type { LiarFinal, LiarOptions, LiarView, PublicEvent } from '@bg/games/liar'; import { TOPIC_IDS, TOPIC_KO } from '@bg/games/liar/topics'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { useServerNow } from '../../components/TurnTimer'; import { haptic, sfx, sounds, tone } from '../../lib/feedback'; import { cssEsc, useBanner, type BannerTone } from '../card-fx'; import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage'; import { useStickToBottom } from '../../lib/useStickToBottom'; import { useChatOutbox, useTypingSignal } from '../../lib/chat-input'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; type Kind = LiarView['phase']['kind']; const PHASE_KO: Record = { reveal: '제시어 확인', describe: '한 사람씩 설명', discussion: '자유 토론', vote: '라이어 지목 투표', guess: '라이어의 정답 맞히기', ended: '게임 끝', }; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; /** "~이에요/예요", "~을/를", "~이/가", "~은/는" after a word. */ function josa(word: string, pair: [string, string]): string { const c = word.charCodeAt(word.length - 1) - 0xac00; return `${word}${c >= 0 && c < 11172 && c % 28 !== 0 ? pair[0] : pair[1]}`; } function phaseTitle(v: LiarView): string { const ph = v.phase; if (ph.kind === 'describe') return v.rounds > 1 ? `${ph.round}바퀴째 설명` : PHASE_KO.describe; if (ph.kind === 'vote' && ph.voteRound === 2) return '동점자 재투표'; return PHASE_KO[ph.kind]; } // ---------------------------------------------------------------- styles const CSS = ` .lg { width: 100%; height: 100%; min-height: 0; display: flex; flex-direction: column; gap: 10px; } .lg-banner { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; border-radius: 16px; padding: 10px 14px; box-shadow: var(--shadow); background: linear-gradient(135deg, #ede9fe, #c4b5fd); color: #2e1065; border: 2px solid #7c3aed; } .lg-banner[data-hot='true'] { background: linear-gradient(135deg, #fee2e2, #fecaca); color: #450a0a; border-color: #dc2626; } .lg-banner[data-time='end'] { background: linear-gradient(135deg, #ecfdf5, #bbf7d0); color: #052e16; border-color: #16a34a; } .lg-ph { display: flex; flex-direction: column; min-width: 0; flex: 1 1 200px; } .lg-ph .d { font-size: .85rem; font-weight: 800; opacity: .85; } .lg-ph strong { font-size: 1.4rem; line-height: 1.2; } .lg-ph .s { font-size: .9rem; font-weight: 600; } .lg-clock { font-size: 2.3rem; font-weight: 900; font-variant-numeric: tabular-nums; line-height: 1; min-width: 3.2ch; text-align: center; } .lg-clock[data-warn='true'] { color: #dc2626; } .lg-card { min-height: 52px; min-width: 150px; border-radius: 12px; border: 2px dashed currentColor; background: rgba(255,255,255,.35); color: inherit; font: inherit; font-weight: 800; padding: 4px 12px; cursor: pointer; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: none; } .lg-card[data-show='true'] { color: #fff; border-style: solid; background: #6d28d9; border-color: #6d28d9; } .lg-card[data-show='true'][data-liar='true'] { background: #b91c1c; border-color: #b91c1c; } .lg-card .w { font-size: 1.25rem; } .lg-card:focus-visible, .lg-tile:focus-visible, .lg-choice:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .lg-news { border-radius: 16px; padding: 10px 14px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); border: 3px solid var(--focus); display: flex; flex-direction: column; gap: 6px; animation: lg-pop .35s ease-out; } .lg-news h2 { margin: 0; font-size: 1.05rem; } .lg-news .big { font-size: 1.12rem; font-weight: 800; } .lg-bars { display: grid; gap: 4px; } .lg-bar { display: grid; grid-template-columns: minmax(70px, 140px) 1fr 2.2em; gap: 6px; align-items: center; font-size: .88rem; font-weight: 700; } .lg-bar .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .lg-bar .tr { height: 14px; border-radius: 7px; background: var(--surface-2); overflow: hidden; } .lg-bar .tr i { display: block; height: 100%; background: #8b5cf6; border-radius: 7px; animation: lg-grow .7s ease-out; transform-origin: left; } .lg-bar[data-top='true'] .tr i { background: #dc2626; } .lg-grid { flex: 1; min-height: 0; display: grid; gap: 10px; grid-template-columns: 236px minmax(0, 1fr) 290px; grid-template-areas: 'players talk actions'; } .lg-col { min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 8px; } .lg-players { grid-area: players; } .lg-talk { grid-area: talk; } .lg-actions { grid-area: actions; } .lg-box { background: var(--surface); color: var(--text); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .lg-box h2 { margin: 0; font-size: 1rem; } .lg-tiles { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; } .lg-tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 6px 4px; border-radius: 12px; min-height: 76px; background: var(--surface-2); color: var(--text); border: 3px solid transparent; font: inherit; text-align: center; } button.lg-tile { cursor: pointer; } .lg-tile .nm { font-weight: 800; font-size: .86rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .lg-tile .no { position: absolute; top: 3px; left: 6px; font-size: .75rem; font-weight: 900; color: var(--text-sub); } .lg-tile.me { border-color: var(--primary); } .lg-tile.left { filter: grayscale(1); opacity: .55; } .lg-tile.speaking { border-color: #7c3aed; box-shadow: 0 0 0 3px rgba(124,58,237,.35); } .lg-tile.accused { border-color: #dc2626; box-shadow: 0 0 0 3px rgba(220,38,38,.35); } .lg-tile[data-target='ok'] { border-color: var(--success); box-shadow: 0 0 0 3px rgba(21,128,61,.35); } .lg-tile[data-target='ok'][aria-pressed='true'] { background: #15803d; color: #fff; border-color: #15803d; box-shadow: 0 0 0 4px rgba(21,128,61,.55); } .lg-tile[data-target='no'] { opacity: .5; } .lg-tag { display: inline-block; border-radius: 999px; padding: 0 7px; font-size: .72rem; font-weight: 800; line-height: 1.6; color: #fff; background: #4b5563; white-space: nowrap; } .lg-tag.say { background: #7c3aed; } .lg-tag.ok { background: #15803d; } .lg-tag.liar { background: #b91c1c; } .lg-desc { margin: 0; padding: 0; list-style: none; display: grid; gap: 5px; } .lg-desc li { background: var(--surface-2); border-radius: 10px; padding: 6px 10px; line-height: 1.4; overflow-wrap: anywhere; } .lg-desc li strong { display: block; font-size: .8rem; font-weight: 800; color: hsl(var(--name-h, 212) 70% var(--chat-name-l)); } .lg-desc li.mine { background: var(--primary-soft); } .lg-desc li.skip { color: var(--text-sub); font-style: italic; } .lg-desc li.now { border: 2px dashed #7c3aed; background: transparent; color: var(--text-sub); } .lg-round { font-size: .82rem; font-weight: 800; color: var(--text-sub); margin-top: 2px; } .lg-chat { flex: 1; min-height: 0; padding: 0; overflow: hidden; gap: 0; } .lg-chat h2 { padding: 10px 12px 6px; border-bottom: 1px solid var(--border); } .lg-msgs { flex: 1; min-height: 140px; overflow-y: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 5px; } .lg-msg.sys { font-size: .86rem; font-weight: 700; color: var(--text-sub); background: var(--surface-2); border-radius: 8px; padding: 3px 8px; } .lg-form { display: flex; gap: 6px; padding: 8px; border-top: 1px solid var(--border); flex-wrap: nowrap; } .lg-form .input { flex: 1; min-height: 44px; min-width: 0; } .lg-actions .lg-form { padding: 0; border: 0; } .lg-why { padding: 8px 10px; border-top: 1px solid var(--border); font-size: .88rem; color: var(--text-sub); font-weight: 600; margin: 0; } .lg-big { display: flex; flex-wrap: wrap; gap: 8px; } .lg-big .btn { flex: 1 1 auto; min-height: 52px; } .lg-prompt { margin: 0; font-weight: 800; font-size: 1.02rem; } .lg-choices { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 6px; } .lg-choice { min-height: 44px; border-radius: 10px; border: 2px solid var(--border); background: var(--surface-2); color: var(--text); font: inherit; font-weight: 700; cursor: pointer; } .lg-choice:hover { border-color: var(--primary); } .lg-final { border: 3px solid #16a34a; } .lg-final table { border-collapse: collapse; width: 100%; font-size: .9rem; } .lg-final td, .lg-final th { padding: 4px 6px; text-align: left; border-bottom: 1px solid var(--border); } .lg-final .word { font-size: 1.3rem; font-weight: 900; } .lg-log { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 3px; max-height: 320px; overflow: auto; } @keyframes lg-pop { from { transform: scale(.96); opacity: 0; } to { transform: none; opacity: 1; } } .lg-unl { font-size: 1.6rem; } .lg-unl small { display: block; font-size: .7rem; font-weight: 800; } .lg-tile[aria-pressed='true'] { animation: lg-pick .28s ease-out; } .lg-tile.accused { animation: anim-shake .45s ease both; } @keyframes lg-pick { 50% { transform: scale(1.07); } } .lg-card[data-show='true'] { animation: anim-flip .35s ease both; } @keyframes lg-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } } /* Vote results come in one row at a time (--d = the row's delay). */ .lg-bar { animation: anim-slide-up .3s ease-out both; animation-delay: var(--d, 0ms); } .lg-bar .tr i { animation-delay: var(--d, 0ms); animation-fill-mode: both; } .lg-bar .ct { animation: anim-pop .32s cubic-bezier(.3, 1.6, .5, 1) both; animation-delay: calc(var(--d, 0ms) + 450ms); } /* Spotlight on the accused: the screen darkens around their tile (never takes clicks), the tile glows and shakes. */ .lg-spot { position: fixed; inset: 0; z-index: 55; pointer-events: none; animation: lg-spot 1.8s ease both; background: radial-gradient(circle at var(--x) var(--y), rgba(0,0,0,0) 0, rgba(0,0,0,0) 70px, rgba(8,8,20,.72) 150px); } @keyframes lg-spot { 0% { opacity: 0; } 18% { opacity: 1; } 75% { opacity: 1; } 100% { opacity: 0; } } .lg-tile.spot { z-index: 1; animation: anim-shake .45s ease .25s both, lg-glow 1.5s ease both; } @keyframes lg-glow { 0%, 100% { box-shadow: 0 0 0 3px rgba(220,38,38,.35); } 30%, 70% { box-shadow: 0 0 0 5px #fde047, 0 0 28px 6px rgba(253,224,71,.75); } } @media (max-width: 1099px) { .lg { height: auto; } .lg-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: 'actions players' 'talk talk'; } .lg-col { overflow: visible; } .lg-msgs { max-height: 380px; } } @media (max-width: 719px) { .lg-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'actions' 'players' 'talk'; } .lg-banner { padding: 8px 10px; gap: 8px; } .lg-ph strong { font-size: 1.15rem; } .lg-clock { font-size: 2rem; } .lg-card { min-width: 120px; min-height: 48px; font-size: .9rem; } .lg-tiles { grid-template-columns: repeat(3, minmax(0, 1fr)); } .lg-tile { min-height: 70px; } .lg-msgs { min-height: 160px; max-height: 300px; } } @media (prefers-reduced-motion: reduce) { .lg-news, .lg-bar, .lg-bar .tr i, .lg-bar .ct, .lg-tile[aria-pressed='true'], .lg-tile.accused, .lg-tile.spot, .lg-card[data-show='true'] { animation: none; } .lg-spot { display: none; } } `; // ---------------------------------------------------------------- small parts function Clock({ endsAt, unlimited }: { endsAt: number | null; unlimited: boolean }) { const now = useServerNow(500); if (unlimited) return ( ∞무제한 ); if (endsAt === null) return null; const sec = Math.max(0, Math.ceil((endsAt - now) / 1000)); const text = sec >= 60 ? `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}` : `${sec}`; return ( {text} ); } function useHold(): [boolean, Record] { const [show, setShow] = useState(false); const timer = useRef | null>(null); useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []); return [ show, { // Pointer capture: the release always comes back to the card, even if the layout moved under the finger. onPointerDown: (e: React.PointerEvent) => { e.currentTarget.setPointerCapture?.(e.pointerId); setShow(true); }, onPointerUp: () => setShow(false), onLostPointerCapture: () => setShow(false), onPointerLeave: () => setShow(false), onPointerCancel: () => setShow(false), onContextMenu: (e: React.MouseEvent) => e.preventDefault(), onKeyDown: (e: KeyboardEvent) => { if (e.key !== 'Enter' && e.key !== ' ') return; e.preventDefault(); setShow(true); if (timer.current) clearTimeout(timer.current); timer.current = setTimeout(() => setShow(false), 2500); }, }, ]; } /** "내 제시어" — only visible while held (screen sharing / people next to you). */ function WordCard({ v, always }: { v: LiarView; always: boolean }) { const [held, handlers] = useHold(); const my = v.my!; const show = held || always; const liar = my.role === 'liar'; const label = liar ? `나는 라이어예요. 주제는 ${v.topicKo}. 제시어는 몰라요` : `내 제시어: ${my.word}. 주제는 ${v.topicKo}`; return ( ); } function eventText(e: PublicEvent, players: Record): string { const n = (id: string) => `${nick(players, id)}님`; switch (e.t) { case 'phase': if (e.kind === 'describe') return `${e.round}바퀴째 설명이 시작됐어요`; if (e.kind === 'vote') return e.round === 2 ? '동점이라 동점인 사람끼리 다시 투표해요' : '라이어 지목 투표 시간이에요'; return `${PHASE_KO[e.kind]} 시간이에요`; case 'vote': if (e.accused) return `${josa(n(e.accused), ['이', '가'])} ${e.tally[e.accused]}표로 지목됐어요`; return e.round === 1 ? `동점이에요 (${e.tied.map(n).join(', ')})` : '또 동점이라 아무도 지목되지 않았어요'; case 'accused': return e.liar ? `${josa(n(e.p), ['은', '는'])} 라이어가 맞아요!` : `${josa(n(e.p), ['은', '는'])} 라이어가 아니었어요`; case 'guess': return e.text === null ? '라이어가 답하지 못했어요' : `라이어의 답: "${e.text}" — ${e.correct ? '정답!' : '틀렸어요'}`; case 'left': return `${josa(n(e.p), ['이', '가'])} 게임을 나갔어요`; case 'end': return e.winner === 'liar' ? '라이어 승리!' : '시민 승리!'; } } /** Announcements since the previous phase change (vote result, reveal, the liar's answer). */ function latestNews(events: PublicEvent[]): PublicEvent[] { let i = events.length - 1; while (i >= 0 && events[i]!.t === 'phase') i--; const out: PublicEvent[] = []; for (; i >= 0 && events[i]!.t !== 'phase'; i--) if (events[i]!.t !== 'left') out.unshift(events[i]!); return out; } function News({ v, players }: { v: LiarView; players: Record }) { const news = latestNews(v.events); if (!news.length || v.final) return null; const title = news.some((e) => e.t === 'accused') ? '투표 결과' : news.some((e) => e.t === 'vote') ? '투표 결과' : '알림'; return (

📢 {title}

{news.map((e) => e.t === 'vote' ? ( ) : ( {eventText(e, players)} ), )}
); } /** Delay between two vote rows appearing (ms). */ const BAR_GAP = 350; function VoteBars({ e, players }: { e: Extract; players: Record }) { const rows = Object.entries(e.tally).sort((a, b) => b[1] - a[1]); const max = Math.max(1, ...rows.map((r) => r[1])); return ( <> {eventText(e, players)} {rows.length > 0 && (
{/* Least votes first, so the top one lands last (one row every 0.35 s). */} {rows.map(([id, n], i) => (
{nick(players, id)} {n}표
))}
)} {Object.keys(e.votes).length > 0 && ( {Object.entries(e.votes) .map(([from, to]) => `${nick(players, from)} → ${nick(players, to)}`) .join(' · ')} )} ); } // ---------------------------------------------------------------- players type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void } | null; function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players: Record; me: string | null; pick: Pick; pending: boolean; spot: string | null }) { const ph = v.phase; const accused = v.final?.accused ?? ph.liar; return (

사람들 말하는 순서대로

{v.order.map((id, i) => { const p = v.players.find((x) => x.id === id)!; const u = userOf(players, id); const speaking = ph.speaker === id; const cls = `lg-tile${id === me ? ' me' : ''}${p.left ? ' left' : ''}${speaking ? ' speaking' : ''}${spot === id ? ' spot' : accused === id ? ' accused' : ''}`; const can = pick?.ids.includes(id) ?? false; const body = ( <> {i + 1} {u.nickname} {id === me ? ' (나)' : ''} {speaking && 말하는 중} {ph.kind === 'vote' && p.voted && 투표함} {p.liar === true && 🤥 라이어} {p.left && 나감} ); const label = [ `${i + 1}번째, ${u.nickname}${id === me ? '(나)' : ''}`, speaking ? '지금 설명하는 사람' : '', ph.kind === 'vote' && p.voted ? '투표함' : '', p.liar === true ? '라이어' : '', p.left ? '나감' : '', ] .filter(Boolean) .join(', '); if (pick && can) { const chosen = pick.chosen === id; return ( ); } return (
{body}
); })}
); } // ---------------------------------------------------------------- descriptions + chat function Descriptions({ v, players, me }: { v: LiarView; players: Record; me: string | null }) { const rounds = Array.from({ length: v.rounds }, (_, i) => i + 1).filter((r) => r === 1 || v.descriptions.some((d) => d.round === r) || (v.phase.kind === 'describe' && v.phase.round >= r)); const { ref: listRef } = useStickToBottom(); return (

📝 설명 기록

{v.descriptions.length === 0 && v.phase.kind !== 'describe' &&

제시어를 확인하면 첫 번째 사람부터 한 문장씩 설명해요.

} {rounds.map((r) => (
{v.rounds > 1 &&
{r}바퀴째{r === 2 ? ' (거꾸로)' : ''}
}
    {v.descriptions .filter((d) => d.round === r) .map((d) => (
  1. {nick(players, d.from)} {d.text ?? (v.options.describeSeconds === null ? '(자리를 비워 넘어갔어요)' : '(시간이 지나 넘어갔어요)')}
  2. ))} {v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && (
  3. {nick(players, v.phase.speaker)} {v.phase.speaker === me ? '내 차례예요. 한 문장으로 설명해 주세요…' : '설명하는 중…'}
  4. )}
))}
); } type Line = ({ k: 'chat'; text: string; from: string; key: string } | { k: 'sys'; e: PublicEvent }) & { at: number }; const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.from : null, at: l.at }; function ChatBox({ v, players, me, act }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void }) { const [text, setText] = useState(''); const { ref: listRef, pin } = useStickToBottom(); const send = useChatOutbox((t: string) => act({ type: 'chat', text: t }), 750); const lines: Line[] = [ ...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })), ...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })), // Stable sort: same moment keeps the event order, announcements before chat. ].sort((a, b) => a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1)); const talk = v.phase.kind === 'discussion' || v.phase.kind === 'vote'; const canWrite = !!v.my?.canChat && talk; const typing = useTypingSignal('game', canWrite); const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? ''); return (

💬 토론 채팅

{lines.length === 0 &&

아직 메시지가 없어요.

} {lines.map((l, i) => l.k === 'sys' ? (
📢 {eventText(l.e, players)}
) : ( {l.text} ), )}
{canWrite ? (
{ e.preventDefault(); const t = text.trim(); if (!t) return; send(t.slice(0, 200)); setText(''); typing.stop(); pin(); }} > { setText(e.target.value); typing.onText(e.target.value); }} onBlur={typing.stop} maxLength={200} placeholder="누가 라이어일까요?" aria-label="토론 채팅 메시지" enterKeyHint="send" />
) : ( why &&

{why}

)}
); } // ---------------------------------------------------------------- actions function DescribeForm({ act, pending }: { act: (a: unknown) => void; pending: boolean }) { const [text, setText] = useState(''); const ref = useRef(null); useEffect(() => ref.current?.focus(), []); return (
{ e.preventDefault(); const t = text.trim(); if (!t) return; act({ type: 'chat', text: t.slice(0, 80) }); }} > setText(e.target.value)} maxLength={80} placeholder="예: 여름이면 생각나요" aria-label="내 설명 (한 문장)" enterKeyHint="send" />
); } function GuessForm({ v, act, pending }: { v: LiarView; act: (a: unknown) => void; pending: boolean }) { const [text, setText] = useState(''); if (v.options.guessMode === 'choice') { return (
{v.phase.choices.map((w) => ( ))}
); } return (
{ e.preventDefault(); const t = text.trim(); if (t) act({ type: 'guess', text: t.slice(0, 20) }); }} > setText(e.target.value)} maxLength={20} placeholder="제시어" aria-label="제시어 맞히기" enterKeyHint="send" autoFocus />
); } function Actions({ v, players, me, act, pending }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void; pending: boolean }) { const my = v.my; const ph = v.phase; const n = (id: string) => `${nick(players, id)}님`; let body: ReactNode = null; if (!my) { body =

관전 중이에요. 주제는 {v.topicKo}이고, 제시어는 게임이 끝나면 공개돼요.

; } else if (ph.kind === 'ended') { body =

게임이 끝났어요. 라이어와 제시어가 공개됐어요.

; } else if (v.players.find((p) => p.id === me)?.left) { body =

게임에서 나갔어요.

; } else if (ph.kind === 'reveal') { body = ( <>

{my.role === 'liar' ? `나는 라이어예요! 주제는 ${v.topicKo}이에요.` : '위의 "내 제시어" 카드를 꾹 눌러 제시어를 확인해 주세요.'}

{my.role === 'liar' ? '다른 사람 설명을 듣고 제시어를 아는 척해 보세요. 들키지 않거나, 걸려도 제시어를 맞히면 이겨요.' : '제시어를 직접 말하지 말고, 라이어가 눈치채지 못하게 애매하게 설명해요.'}
); } else if (ph.kind === 'describe') { body = my.canDescribe ? ( <>

내 차례예요! 한 문장으로 설명해 주세요

{my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'} {ph.endsAt === null ? ' 시간 제한은 없어요.' : ''} ) : ( <>

{ph.speaker ? `${josa(n(ph.speaker), ['이', '가'])} 설명하는 중이에요` : '설명하는 중이에요'}

{v.rounds > 1 ? `${ph.round}/${v.rounds}바퀴 · ` : ''} {ph.turn + 1}번째 차례 ); } else if (ph.kind === 'discussion') { body = ( <>

자유 토론이에요. 누가 라이어일까요?

설명이 어색했던 사람을 이야기해 봐요. 제시어는 직접 말할 수 없어요.
{ph.endsAt === null ? '토론 시간이 무제한이에요. ' : ''}모두 누르면 바로 투표로 넘어가요. ); } else if (ph.kind === 'vote') { body = my.voteTargets.length > 0 ? ( <>

{ph.voteRound === 2 ? '동점이라 다시 투표해요. 동점인 사람 중에서 골라 주세요' : '라이어로 의심되는 사람을 골라 주세요'}

초록 테두리 사람을 누르면 지목해요. 모두 투표하면 바로 결과가 나와요. {my.vote ? `${josa(n(my.vote), ['을', '를'])} 지목했어요` : '아직 고르지 않았어요'} 투표한 사람 {ph.votedCount}명 {ph.voteRound === 2 ? '· 또 동점이면 라이어가 이겨요' : '· 동점이면 동점인 사람끼리 한 번 더 투표해요'} ) : (

다른 사람들이 투표하고 있어요.

); } else if (ph.kind === 'guess') { body = my.canGuess ? ( <>

들켰어요! 제시어를 맞히면 그래도 이겨요

주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'} {ph.endsAt === null ? ' 시간 제한은 없어요.' : ''} ) : ( <>

{ph.liar ? `${josa(n(ph.liar), ['이', '가'])} 라이어였어요!` : '라이어를 찾았어요!'}

라이어가 제시어를 맞히는 중이에요. 못 맞히면 시민이 이겨요. ); } return (

{ph.kind === 'ended' ? '🏁 결과' : '🎯 할 일'}

{body}
); } const REASON_KO: Record = { caught: '라이어를 찾았고, 라이어가 제시어를 못 맞혔어요', guessed: '라이어가 지목됐지만 제시어를 맞혔어요', escaped: '라이어가 아닌 사람이 지목됐어요', tie: '투표가 두 번 동점이었어요', liarLeft: '라이어가 게임을 나갔어요', citizensLeft: '시민이 모두 나갔어요', }; function FinalReveal({ v, players }: { v: LiarView; players: Record }) { const f = v.final!; return (

🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}

{REASON_KO[f.reason]}. 제시어 {f.word} · 주제 {TOPIC_KO[f.topic]} {f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''} {f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''} {v.order.map((id) => { const won = (f.winner === 'liar') === (id === f.liar) && !v.players.find((p) => p.id === id)?.left; return ( ); })}
이름 역할 점수
{won ? '🏆 ' : ''} {nick(players, id)} {id === f.liar ? '🤥 라이어' : '🙂 시민'} {f.scores[id] ?? 0}점
); } // ---------------------------------------------------------------- board /** Game sounds on top of the shared palette (site volume applies). */ const lgSound = { /** Someone else's description lands. */ said: () => tone(660, 70, 'triangle', 0.09), /** The accused really is the liar. */ caught: () => [523, 784].forEach((f, i) => tone(f, 140, 'square', 0.07, i * 120)), }; /** The accused's tile glows; `x/y` (screen px) only when the tile is on screen, for the darkened-room spotlight. */ type Spot = { id: string; x: number | null; y: number | null; key: number }; /** * Sounds and motion for what anyone did: descriptions, votes being cast, results (the room plays win / lose at the end). * A result plays out in order: the vote rows come in one by one, then the spotlight falls on the accused, then the * banners (caught / escaped, the liar's answer, the winner). A newer announcement cancels whatever is still queued. */ function useLiarFx(v: LiarView, me: string | null, players: Record, showBanner: (text: string, tone?: BannerTone, sub?: string) => void, setSpot: (s: Spot | null) => void): void { const prev = useRef(v); const timers = useRef[]>([]); useEffect(() => () => timers.current.forEach(clearTimeout), []); useEffect(() => { const p = prev.current; prev.current = v; if (p === v) return; const last = p.events.at(-1)?.n ?? 0; const fresh = v.events.filter((e) => e.n > last); if (fresh.some((e) => 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 name = (id: string) => `${nick(players, id)}님`; let t = 0; const vote = fresh.find((e) => e.t === 'vote'); if (vote) { const rows = Object.keys(vote.tally).length; // A soft chip per row as it lands (the rows themselves are timed in CSS). for (let i = 0; i < Math.min(rows, 8); i++) sfx.chip(i * BAR_GAP + 300); t = Math.max(1, rows) * BAR_GAP + 350; if (!vote.accused) { later(t, () => (vote.round === 1 ? showBanner('동점!', 'gold', '동점인 사람끼리 다시 투표해요') : showBanner('또 동점!', 'dark', '아무도 지목되지 않았어요'))); t += 1500; } } for (const e of fresh) { if (e.t === 'accused') { later(t, () => { const r = document.querySelector(`.lg-tile[data-player="${cssEsc(e.p)}"]`)?.getBoundingClientRect(); const seen = !!r && r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth; setSpot({ id: e.p, x: seen ? r.left + r.width / 2 : null, y: seen ? r.top + r.height / 2 : null, key: e.n }); tone(220, 90, 'triangle', 0.08); tone(220, 90, 'triangle', 0.08, 160); }); later(t + 1800, () => setSpot(null)); t += 750; later(t, () => { if (e.liar) { lgSound.caught(); showBanner('잡았다!', 'green', `${josa(name(e.p), ['이', '가'])} 라이어였어요`); } else { sfx.bad(); showBanner('헛다리!', 'dark', `${josa(name(e.p), ['은', '는'])} 라이어가 아니에요`); } }); t += 1500; } else if (e.t === 'guess') { later(t, () => { if (e.correct) { sfx.alarm(); showBanner('정답!', 'red', `라이어의 답: "${e.text ?? ''}"`); } else { sfx.good(); showBanner('땡!', 'green', e.text === null ? '라이어가 답하지 못했어요' : `라이어의 답: "${e.text}"`); } }); t += 1500; } else if (e.t === 'end') { // The room plays the win / lose sound; this is only the picture. const liar = v.final?.liar; later(t, () => showBanner(e.winner === 'liar' ? '라이어 승리!' : '시민 승리!', e.winner === 'liar' ? 'red' : 'blue', liar ? `라이어는 ${nick(players, liar)}님` : undefined)); } } return; } if (fresh.some((e) => e.t === 'left')) return sfx.whoosh(); const newDesc = v.descriptions.slice(p.descriptions.length); if (newDesc.some((d) => d.from !== me)) return newDesc.some((d) => d.text === null) ? sfx.tick() : lgSound.said(); if (v.my?.vote !== p.my?.vote && v.my?.vote) return sfx.select(); const same = v.phase.kind === p.phase.kind && v.phase.voteRound === p.phase.voteRound; if (same && (v.phase.votedCount > p.phase.votedCount || v.phase.readyCount > p.phase.readyCount)) sfx.chip(); }, [v]); // eslint-disable-line react-hooks/exhaustive-deps } function LiarBoard({ view: v, me, players, act, pending }: BoardProps) { const ph = v.phase; const my = v.my; const [announce, setAnnounce] = useState(''); const phaseKey = `${ph.kind}-${ph.round}-${ph.turn}-${ph.voteRound}`; const first = useRef(true); useEffect(() => { if (first.current) { first.current = false; return; } setAnnounce(ph.kind === 'describe' && ph.speaker ? `${phaseTitle(v)}: ${nick(players, ph.speaker)}님 차례` : phaseTitle(v)); if (my && ((ph.kind === 'describe' && my.canDescribe) || (ph.kind === 'vote' && my.voteTargets.length > 0) || my.canGuess)) { haptic(40); sounds.myTurn(); } }, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps const [banner, showBanner] = useBanner(); const [spot, setSpot] = useState(null); useLiarFx(v, me, players, showBanner, setSpot); const pick: Pick = my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null; const hot = ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe); const sub = ph.kind === 'describe' && ph.speaker ? `${nick(players, ph.speaker)}님 차례 · 주제: ${v.topicKo}` : ph.kind === 'ended' ? (v.final?.summary ?? '') : `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`; return (
🤥 라이어 게임 {phaseTitle(v)} {sub} {my && }
{v.final && }

{announce}

{spot && spot.x !== null &&
} {banner}
); } // ---------------------------------------------------------------- side function LiarSide({ view: v, players }: BoardProps) { const log = v.events.filter((e) => e.t !== 'phase'); return ( <>
라이어 게임 · {phaseTitle(v)} 주제: {v.topicKo} {optionsSummary(v.options)}
{log.length > 0 && (
발표 기록
    {[...log].reverse().map((e) => (
  1. {eventText(e, players)}
  2. ))}
)}

게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요. 음성 채팅으로 제시어를 말하지 않기로 해요.

); } // ---------------------------------------------------------------- status function isMyTurn(v: LiarView, me: string | null): boolean { const my = v.my; if (!me || !my || v.final) return false; switch (v.phase.kind) { case 'describe': return my.canDescribe; case 'vote': return my.voteTargets.length > 0 && my.vote === null; case 'guess': return my.canGuess; default: return false; } } function statusText(v: LiarView, me: string | null, players: Record): string { if (v.final) return v.final.summary; const ph = v.phase; switch (ph.kind) { case 'reveal': return `제시어를 확인해 주세요 · 주제: ${v.topicKo}`; case 'describe': return isMyTurn(v, me) ? '내 차례예요 · 한 문장으로 설명해 주세요' : `${ph.speaker ? nick(players, ph.speaker) : '다른 사람'}님이 설명하는 중이에요`; case 'discussion': return '자유 토론 시간이에요 · 누가 라이어일까요?'; case 'vote': return isMyTurn(v, me) ? '내 차례예요 · 라이어로 의심되는 사람을 골라 주세요' : ph.voteRound === 2 ? '동점자 재투표 중이에요' : '라이어 지목 투표 중이에요'; case 'guess': return isMyTurn(v, me) ? '내 차례예요 · 제시어를 맞혀 보세요' : '라이어가 제시어를 맞히는 중이에요'; case 'ended': return '게임이 끝났어요'; } } // ---------------------------------------------------------------- options function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
{options.map(([k, l]) => ( ))}
); } function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) { return (
{label} {children} {help && {help}}
); } const onOff: [boolean, string][] = [ [true, '켜기'], [false, '끄기'], ]; const secs = (...v: T[]): [T | null, string][] => [...v.map((x): [T, string] => [x, `${x}초`]), [null, '무제한']]; function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); return (
label="주제" value={o.topic} options={[['random', '무작위'], ...TOPIC_IDS.map((t): [LiarOptions['topic'], string] => [t, TOPIC_KO[t]])]} onChange={(topic) => set({ topic })} /> set({ foolMode })} /> set({ rounds })} /> set({ guessMode })} /> {more && ( <> set({ describeSeconds })} /> set({ discussionSeconds })} /> set({ voteSeconds })} /> set({ guessSeconds })} /> {[o.describeSeconds, o.discussionSeconds, o.voteSeconds, o.guessSeconds].includes(null) && ( 무제한이어도 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 넘어가요(설명 넘김, 표 없음, 답 없음). )} set({ kidSafeChat })} /> )}
); } function optionsSummary(o: LiarOptions): string { const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`]; if (o.foolMode) parts.push('바보 모드'); parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기'); return parts.join(' · '); } // ---------------------------------------------------------------- rules function Rules() { return (

3~10명이 같은 제시어를 받는데, 몰래 뽑힌 라이어 한 명만 주제만 알고 제시어는 몰라요. 시민은 라이어를 찾고, 라이어는 들키지 않거나 제시어를 맞히면 이겨요.

흐름: 제시어 확인 → 정해진 순서대로 한 사람씩 한 문장 설명(두 바퀴면 두 번째는 거꾸로) → 자유 토론 → 라이어 지목 투표 → 지목된 사람이 라이어면 제시어 맞히기 → 결과.

  • 제시어를 직접 말하면 안 돼요(띄어쓰기를 무시하고 막아요). 설명 차례에 시간이 지나면 넘어가요.
  • 투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.
  • 라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.
  • 점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.
  • 바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.
  • 시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.

내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.

); } const ui: GameUI = { Board: LiarBoard, Side: LiarSide, statusText, isMyTurn, Options, optionsSummary, Rules, quickStart, helpNow, ownChat: true, }; export default ui;