Files
joke-app/apps/web/src/games/liar/index.tsx
EJClaw f793391b79 제한 시간 보정 2: 같은 마감 안에서는 투표로 답할 사람이 줄어도 준 시간 유지, 마감은 남은 답할 사람 중 가장 늦은 화면 기준, 자체 시계를 쓰는 게임도 늘어난 마감을 표시
- room: reveal 단계 키를 게임 마감만으로, clockExtra = max(본인, 답할 사람들)
- 라이어·마피아·아발론 시계, 뱅 반응·차례 타이머, 바둑 계가·마작 울기 타이머가 방 마감(연출 시간 포함)을 따름
- 아발론 암살 마감: 당겨진 마감은 숨기고 늘어난 마감은 보여 줌(무제한이면 그대로 숨김)
- 테스트: 공통 재투표(대표자 A·느린 B·A 투표 후 유지), e2e 라이어 화면 시계 = 방 마감

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:25 +09:00

1123 lines
56 KiB
TypeScript

/**
* 라이어 게임 화면 (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, useChatSound } from '../../lib/feedback';
import { cssEsc, useBanner, type BannerTone } from '../card-fx';
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
import { useStickToBottom } from '../../lib/useStickToBottom';
import { keepFocus, useTypingSignal } from '../../lib/chat-input';
import { useRoom } from '../../net/socket';
import { BotActivity } from '../../components/BotActivity';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
type Kind = LiarView['phase']['kind'];
// ---------------------------------------------------------------- topics (admins may add or delete some)
type TopicChoice = { id: string; ko: string };
/** The topics new games can use; the code's list until the server answers. */
let topicChoices: TopicChoice[] = TOPIC_IDS.map((id) => ({ id, ko: TOPIC_KO[id] }));
let topicsLoad: Promise<TopicChoice[]> | null = null;
function loadTopics(): Promise<TopicChoice[]> {
topicsLoad ??= fetch('/api/liar/topics', { credentials: 'same-origin' })
.then((r) => (r.ok ? (r.json() as Promise<{ topics: TopicChoice[] }>) : Promise.reject(new Error(String(r.status)))))
.then((d) => (topicChoices = d.topics))
.catch(() => ((topicsLoad = null), topicChoices));
return topicsLoad;
}
const topicName = (id: string) => topicChoices.find((t) => t.id === id)?.ko ?? (TOPIC_KO as Record<string, string>)[id] ?? '관리자가 고른 주제';
function useTopicChoices(): TopicChoice[] {
const [list, setList] = useState(topicChoices);
useEffect(() => {
let on = true;
void loadTopics().then((x) => on && setList(x));
return () => {
on = false;
};
}, []);
return list;
}
const PHASE_KO: Record<Kind, string> = {
reveal: '제시어 확인',
describe: '한 사람씩 설명',
discussion: '자유 토론',
vote: '라이어 지목 투표',
guess: '라이어의 정답 맞히기',
ended: '게임 끝',
};
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
const userOf = (players: Record<string, PublicUser>, 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]}`;
}
/**
* The last event number as of the last still screen, and whether a newer announcement (vote result, accused, the
* liar's answer, the end) is still playing out: what it reveals waits until its vote rows, spotlight and banners are done.
*/
function useShownEvents(v: LiarView): { shownN: number; settling: boolean } {
const shownN = useAfterMotionValue(v.events.at(-1)?.n ?? 0);
return { shownN, settling: v.events.some((e) => e.n > shownN && e.t !== 'phase' && e.t !== 'left') };
}
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: clamp(236px, 17%, 340px) minmax(0, 1fr) clamp(290px, 20%, 400px); 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-chat .bot-activity { padding: 4px 10px 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; max-height: min(420px, 50vh); overflow-y: auto; }
.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 (
<span className="lg-clock lg-unl" role="timer" aria-label="시간 제한 없음">
∞<small>무제한</small>
</span>
);
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 (
<span className="lg-clock" data-warn={sec <= 5} role="timer" aria-label={`남은 시간 ${sec}초`}>
{text}
</span>
);
}
function useHold(): [boolean, Record<string, unknown>] {
const [show, setShow] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | 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<HTMLElement>) => {
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 (
<button
type="button"
className="lg-card"
data-show={show}
data-liar={liar}
aria-label={show ? label : '내 제시어 보기. 누르고 있는 동안만 보여요'}
{...handlers}
>
{show ? liar ? <span className="w">🤥 나는 라이어</span> : <span className="w">🔑 {my.word}</span> : '🂠 내 제시어 (꾹 누르기)'}
</button>
);
}
function eventText(e: PublicEvent, players: Record<string, PublicUser>): 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, shownN, finalShown }: { v: LiarView; players: Record<string, PublicUser>; shownN: number; finalShown: boolean }) {
// The vote rows are the animation itself; what comes after them (accused, the answer) waits for it.
const news = latestNews(v.events).filter((e) => e.t === 'vote' || e.n <= shownN);
if (!news.length || finalShown) return null;
const title = news.some((e) => e.t === 'accused') ? '투표 결과' : news.some((e) => e.t === 'vote') ? '투표 결과' : '알림';
return (
<section className="lg-news" key={news[0]!.n} aria-label={title} role="status">
<h2>📢 {title}</h2>
{news.map((e) =>
e.t === 'vote' ? (
<VoteBars key={e.n} e={e} players={players} />
) : (
<span key={e.n} className="big">
{eventText(e, players)}
</span>
),
)}
</section>
);
}
/** Delay between two vote rows appearing (ms). */
const BAR_GAP = 350;
function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; players: Record<string, PublicUser> }) {
const rows = Object.entries(e.tally).sort((a, b) => b[1] - a[1]);
const max = Math.max(1, ...rows.map((r) => r[1]));
return (
<>
<span className="big">{eventText(e, players)}</span>
{rows.length > 0 && (
<div className="lg-bars" role="list" aria-label="득표">
{/* Least votes first, so the top one lands last (one row every 0.35 s). */}
{rows.map(([id, n], i) => (
<div key={id} className="lg-bar" data-top={id === e.accused} role="listitem" aria-label={`${nick(players, id)} ${n}표`} style={{ '--d': `${(rows.length - 1 - i) * BAR_GAP}ms` } as CSSProperties}>
<span className="nm">{nick(players, id)}</span>
<span className="tr" aria-hidden>
<i style={{ width: `${(n / max) * 100}%` }} />
</span>
<span className="ct">{n}표</span>
</div>
))}
</div>
)}
{Object.keys(e.votes).length > 0 && (
<span className="small muted">
{Object.entries(e.votes)
.map(([from, to]) => `${nick(players, from)} → ${nick(players, to)}`)
.join(' · ')}
</span>
)}
</>
);
}
// ---------------------------------------------------------------- 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<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; spot: string | null }) {
const ph = v.phase;
// Who was accused / who is the liar shows only after the result has played out.
const accused = useAfterMotionValue(v.final?.accused ?? ph.liar ?? '') || null;
const liars = useAfterMotionValue(v.players.filter((p) => p.liar === true).map((p) => p.id).join(',')).split(',');
return (
<section className="lg-box" aria-label="사람들과 말하는 순서">
<h2>
사람들 <span className="small muted">말하는 순서대로</span>
</h2>
<div className="lg-tiles">
{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 = (
<>
<span className="no" aria-hidden>
{i + 1}
</span>
<Avatar user={u} size={30} />
<span className="nm">
{u.nickname}
{id === me ? ' (나)' : ''}
</span>
{speaking && <span className="lg-tag say">말하는 중</span>}
{ph.kind === 'vote' && p.voted && <span className="lg-tag ok anim-pop">투표함</span>}
{liars.includes(id) && <span className="lg-tag liar anim-pop">🤥 라이어</span>}
{p.left && <span className="lg-tag">나감</span>}
</>
);
const label = [
`${i + 1}번째, ${u.nickname}${id === me ? '(나)' : ''}`,
speaking ? '지금 설명하는 사람' : '',
ph.kind === 'vote' && p.voted ? '투표함' : '',
liars.includes(id) ? '라이어' : '',
p.left ? '나감' : '',
]
.filter(Boolean)
.join(', ');
if (pick && can) {
const chosen = pick.chosen === id;
return (
<button key={id} type="button" className={cls} data-target="ok" data-player={id} aria-pressed={chosen} disabled={pending} aria-label={`${label}. ${chosen ? '고른 사람' : '지목하기'}`} onClick={() => pick.onPick(id)}>
{body}
</button>
);
}
return (
<div key={id} className={cls} data-target={pick ? 'no' : undefined} data-player={id} role="group" aria-label={label}>
{body}
</div>
);
})}
</div>
</section>
);
}
// ---------------------------------------------------------------- descriptions + chat
function Descriptions({ v, players, me }: { v: LiarView; players: Record<string, PublicUser>; 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<HTMLDivElement>();
return (
<section className="lg-box" aria-label="설명 기록">
<h2>📝 설명 기록</h2>
<div ref={listRef} style={{ maxHeight: 340, overflowY: 'auto' }} aria-live="polite">
{v.descriptions.length === 0 && v.phase.kind !== 'describe' && <p className="muted small" style={{ margin: 0 }}>제시어를 확인하면 첫 번째 사람부터 한 문장씩 설명해요.</p>}
{rounds.map((r) => (
<div key={r}>
{v.rounds > 1 && <div className="lg-round">{r}바퀴째{r === 2 ? ' (거꾸로)' : ''}</div>}
<ol className="lg-desc">
{v.descriptions
.filter((d) => d.round === r)
.map((d) => (
<li key={d.n} className={`${d.from === me ? 'mine' : ''}${d.text === null ? ' skip' : ''} anim-slide-up`} style={{ '--name-h': nameHue(d.from) } as CSSProperties}>
<strong>{nick(players, d.from)}</strong>
{d.text ?? (v.options.describeSeconds === null ? '(자리를 비워 넘어갔어요)' : '(시간이 지나 넘어갔어요)')}
</li>
))}
{v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && (
<li className="now" style={{ '--name-h': nameHue(v.phase.speaker) } as CSSProperties}>
<strong>{nick(players, v.phase.speaker)}</strong>
{v.phase.speaker === me ? '내 차례예요. 한 문장으로 설명해 주세요…' : '설명하는 중…'}
</li>
)}
</ol>
</div>
))}
</div>
</section>
);
}
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, shownN }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; shownN: number }) {
const [text, setText] = useState('');
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
const send = (t: string) => act({ type: 'chat', text: t });
const lines: Line[] = [
...v.events.filter((e) => e.n <= shownN && (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 canWrite = !!v.my?.canChat;
const typing = useTypingSignal('game', canWrite);
// Who is typing sits right above the input, inside the chat (not on the status row: `typingInChat`).
const room = useRoom((s) => s.room);
const inputRef = useRef<HTMLInputElement>(null);
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : (v.my.chatWhy ?? '');
return (
<section className="lg-box lg-chat" aria-label="토론 채팅">
<h2>💬 토론 채팅</h2>
<div ref={listRef} className="lg-msgs" aria-live="polite">
{lines.length === 0 && <p className="muted small" style={{ margin: 0 }}>아직 메시지가 없어요.</p>}
{lines.map((l, i) =>
l.k === 'sys' ? (
<div key={`e${l.e.n}`} className="lg-msg sys">
📢 {eventText(l.e, players)}
</div>
) : (
<ChatMessage key={l.key} className="lg-msg" from={l.from} name={nick(players, l.from)} mine={l.from === me} cont={sameRun(runKey(lines[i - 1]), runKey(l))}>
{l.text}
</ChatMessage>
),
)}
</div>
{room && <BotActivity room={room} only="typing" ch="game" hideBots={v.phase.kind === 'describe' && v.phase.speaker ? [v.phase.speaker] : undefined} />}
{canWrite ? (
<form
className="lg-form"
onSubmit={(e) => {
e.preventDefault();
const t = text.trim();
if (!t) return;
send(t.slice(0, 200));
setText('');
typing.stop();
pin();
inputRef.current?.focus();
}}
>
<input
ref={inputRef}
className="input"
value={text}
onChange={(e) => {
setText(e.target.value);
typing.onText(e.target.value);
}}
onBlur={typing.stop}
maxLength={200}
placeholder={v.my?.canDescribe ? '여기는 채팅이에요. 설명은 [말하기] 칸에 써 주세요' : '누가 라이어일까요?'}
aria-label="토론 채팅 메시지"
enterKeyHint="send"
/>
<button className="btn btn-primary btn-sm" {...keepFocus}>
보내기
</button>
</form>
) : (
why && <p className="lg-why">{why}</p>
)}
</section>
);
}
// ---------------------------------------------------------------- actions
function DescribeForm({ act, pending }: { act: (a: unknown) => void; pending: boolean }) {
const [text, setText] = useState('');
const ref = useRef<HTMLInputElement>(null);
useEffect(() => ref.current?.focus(), []);
return (
<form
className="lg-form"
onSubmit={(e) => {
e.preventDefault();
const t = text.trim();
if (!t) return;
act({ type: 'describe', text: t.slice(0, 80) });
}}
>
<input ref={ref} className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={80} placeholder="예: 여름이면 생각나요" aria-label="내 설명 (한 문장)" enterKeyHint="send" />
<button className="btn btn-primary btn-sm" disabled={pending}>
말하기
</button>
</form>
);
}
function GuessForm({ v, act, pending }: { v: LiarView; act: (a: unknown) => void; pending: boolean }) {
const [text, setText] = useState('');
if (v.options.guessMode === 'choice') {
return (
<div className="lg-choices" role="group" aria-label={`${v.topicKo} 단어 목록`}>
{v.phase.choices.map((w) => (
<button key={w} type="button" className="lg-choice" disabled={pending} onClick={() => act({ type: 'guess', text: w })}>
{w}
</button>
))}
</div>
);
}
return (
<form
className="lg-form"
onSubmit={(e) => {
e.preventDefault();
const t = text.trim();
if (t) act({ type: 'guess', text: t.slice(0, 20) });
}}
>
<input className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={20} placeholder="제시어" aria-label="제시어 맞히기" enterKeyHint="send" autoFocus />
<button className="btn btn-primary btn-sm" disabled={pending}>
정답!
</button>
</form>
);
}
function Actions({ v, players, me, act, pending, settling }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; pending: boolean; settling: boolean }) {
const my = v.my;
const ph = v.phase;
const n = (id: string) => `${nick(players, id)}님`;
let body: ReactNode = null;
if (settling) {
// The next step (guess, re-vote, the end) gives the result away: it shows once the result has played out.
body = <p className="lg-prompt">결과를 공개하는 중이에요…</p>;
} else if (!my) {
body = <p className="lg-prompt">관전 중이에요. 주제는 {v.topicKo}이고, 제시어는 게임이 끝나면 공개돼요.</p>;
} else if (ph.kind === 'ended') {
body = <p className="lg-prompt">게임이 끝났어요. 라이어와 제시어가 공개됐어요.</p>;
} else if (v.players.find((p) => p.id === me)?.left) {
body = <p className="lg-prompt">게임에서 나갔어요.</p>;
} else if (ph.kind === 'reveal') {
body = (
<>
<p className="lg-prompt">{my.role === 'liar' ? `나는 라이어예요! 주제는 ${v.topicKo}이에요.` : '위의 "내 제시어" 카드를 꾹 눌러 제시어를 확인해 주세요.'}</p>
<span className="small">{my.role === 'liar' ? '다른 사람 설명을 듣고 제시어를 아는 척해 보세요. 들키지 않거나, 걸려도 제시어를 맞히면 이겨요.' : '제시어를 직접 말하지 말고, 라이어가 눈치채지 못하게 애매하게 설명해요.'}</span>
<div className="lg-big">
<button type="button" className="btn btn-primary" disabled={pending || !my.canReady} onClick={() => act({ type: 'ready' })}>
{my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `확인했어요 (${ph.readyCount}/${ph.readyNeeded})`}
</button>
</div>
</>
);
} else if (ph.kind === 'describe') {
body = my.canDescribe ? (
<>
<p className="lg-prompt">내 차례예요! 한 문장으로 설명해 주세요</p>
<span className="small">
{my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'}
{ph.endsAt === null ? ' 시간 제한은 없어요.' : ''}
</span>
<DescribeForm key={`${ph.round}-${ph.turn}`} act={act} pending={pending} />
</>
) : (
<>
<p className="lg-prompt">{ph.speaker ? `${josa(n(ph.speaker), ['이', '가'])} 설명하는 중이에요` : '설명하는 중이에요'}</p>
<span className="small muted">
{v.rounds > 1 ? `${ph.round}/${v.rounds}바퀴 · ` : ''}
{ph.turn + 1}번째 차례
</span>
</>
);
} else if (ph.kind === 'discussion') {
body = (
<>
<p className="lg-prompt">자유 토론이에요. 누가 라이어일까요?</p>
<span className="small">설명이 어색했던 사람을 이야기해 봐요. 제시어는 직접 말할 수 없어요.</span>
<div className="lg-big">
<button type="button" className="btn btn-primary" disabled={pending || !my.canReady} onClick={() => act({ type: 'ready' })}>
{my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `토론 끝내기 (${ph.readyCount}/${ph.readyNeeded})`}
</button>
</div>
<span className="small muted">{ph.endsAt === null ? '토론 시간이 무제한이에요. ' : ''}모두 누르면 바로 투표로 넘어가요.</span>
</>
);
} else if (ph.kind === 'vote') {
body =
my.voteTargets.length > 0 ? (
<>
<p className="lg-prompt">{ph.voteRound === 2 ? '동점이라 다시 투표해요. 동점인 사람 중에서 골라 주세요' : '라이어로 의심되는 사람을 골라 주세요'}</p>
<span className="small">초록 테두리 사람을 누르면 지목해요. 모두 투표하면 바로 결과가 나와요.</span>
<strong>{my.vote ? `${josa(n(my.vote), ['을', '를'])} 지목했어요` : '아직 고르지 않았어요'}</strong>
<span className="small muted">
투표한 사람 {ph.votedCount}명 {ph.voteRound === 2 ? '· 또 동점이면 라이어가 이겨요' : '· 동점이면 동점인 사람끼리 한 번 더 투표해요'}
</span>
</>
) : (
<p className="lg-prompt">다른 사람들이 투표하고 있어요.</p>
);
} else if (ph.kind === 'guess') {
body = my.canGuess ? (
<>
<p className="lg-prompt">들켰어요! 제시어를 맞히면 그래도 이겨요</p>
<span className="small">
주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'}
{ph.endsAt === null ? ' 시간 제한은 없어요.' : ''}
</span>
<GuessForm v={v} act={act} pending={pending} />
</>
) : (
<>
<p className="lg-prompt">{ph.liar ? `${josa(n(ph.liar), ['이', '가'])} 라이어였어요!` : '라이어를 찾았어요!'}</p>
<span className="small">라이어가 제시어를 맞히는 중이에요. 못 맞히면 시민이 이겨요.</span>
</>
);
}
return (
<section className="lg-box" aria-label="할 일">
<h2>{ph.kind === 'ended' && !settling ? '🏁 결과' : '🎯 할 일'}</h2>
{body}
</section>
);
}
const REASON_KO: Record<LiarFinal['reason'], string> = {
caught: '라이어를 찾았고, 라이어가 제시어를 못 맞혔어요',
guessed: '라이어가 지목됐지만 제시어를 맞혔어요',
escaped: '라이어가 아닌 사람이 지목됐어요',
tie: '투표가 두 번 동점이었어요',
liarLeft: '라이어가 게임을 나갔어요',
citizensLeft: '시민이 모두 나갔어요',
};
function FinalReveal({ v, players }: { v: LiarView; players: Record<string, PublicUser> }) {
const f = v.final!;
return (
<section className="lg-box lg-final" aria-label="최종 공개">
<h2>🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}</h2>
<span>{REASON_KO[f.reason]}.</span>
<span>
제시어 <span className="word">{f.word}</span> · 주제 {f.topicKo ?? topicName(f.topic)}
{f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''}
{f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''}
</span>
<table>
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">역할</th>
<th scope="col">점수</th>
</tr>
</thead>
<tbody>
{v.order.map((id) => {
const won = (f.winner === 'liar') === (id === f.liar) && !v.players.find((p) => p.id === id)?.left;
return (
<tr key={id}>
<th scope="row">
{won ? '🏆 ' : ''}
{nick(players, id)}
</th>
<td>{id === f.liar ? '🤥 라이어' : '🙂 시민'}</td>
<td>{f.scores[id] ?? 0}점</td>
</tr>
);
})}
</tbody>
</table>
</section>
);
}
// ---------------------------------------------------------------- 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<string, PublicUser>, showBanner: (text: string, tone?: BannerTone, sub?: string) => void, setSpot: (s: Spot | null) => void): void {
const prev = useRef(v);
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
useEffect(() => () => timers.current.forEach(clearTimeout), []);
// The result plays with timers (quiet gaps between the vote rows, spotlight and banners): results wait for it all.
const [staging, setStaging] = useState(false);
useMotionHold(staging);
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, fxMs(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));
}
}
setStaging(true);
later(t, () => setStaging(false));
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, deadline }: BoardProps<LiarView>) {
// The room chat is closed while playing, so the 토론 chat lines play the chat sound.
useChatSound(v.chat.at(-1)?.n);
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<Spot | null>(null);
useLiarFx(v, me, players, showBanner, setSpot);
const { shownN, settling } = useShownEvents(v);
const finalShown = useMotionSettled(!!v.final && !settling);
const pick: Pick = !settling && my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null;
const hot = !settling && (ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe));
const sub = useAfterMotionValue(
ph.kind === 'describe' && ph.speaker
? `${nick(players, ph.speaker)}님 차례 · 주제: ${v.topicKo}`
: ph.kind === 'ended'
? (v.final?.summary ?? '')
: `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`,
);
// The phase title (라이어 맞히기, 게임 끝) would give the result away: it changes once the screen is still.
const title = useAfterMotionValue(phaseTitle(v));
return (
<div className="lg">
<style>{CSS}</style>
<section className="lg-banner" data-time={finalShown ? 'end' : 'play'} data-hot={hot} aria-label="진행 상황">
<span className="lg-ph">
<span className="d">🤥 라이어 게임</span>
<strong key={title} className="anim-slide-up">
{title}
</strong>
<span className="s">{sub}</span>
</span>
{/* The room's deadline is the phase clock plus the time the screens took to finish animating (it only moves later). */}
<Clock endsAt={ph.endsAt === null ? null : Math.max(ph.endsAt, deadline ?? ph.endsAt)} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
{my && <WordCard v={v} always={finalShown} />}
</section>
<News v={v} players={players} shownN={shownN} finalShown={finalShown} />
{finalShown && <FinalReveal v={v} players={players} />}
<div className="lg-grid">
<div className="lg-col lg-players">
<Players v={v} players={players} me={me} pick={pick} pending={pending} spot={spot?.id ?? null} />
</div>
<div className="lg-col lg-talk">
<Descriptions v={v} players={players} me={me} />
<ChatBox v={v} players={players} me={me} act={act} shownN={shownN} />
</div>
<div className="lg-col lg-actions">
<Actions v={v} players={players} me={me} act={act} pending={pending} settling={settling} />
</div>
</div>
<p className="sr-only" aria-live="polite">
{announce}
</p>
{spot && spot.x !== null && <div key={spot.key} className="lg-spot" aria-hidden style={{ '--x': `${spot.x}px`, '--y': `${spot.y}px` } as CSSProperties} />}
{banner}
</div>
);
}
// ---------------------------------------------------------------- side
function LiarSide({ view: v, players }: BoardProps<LiarView>) {
// Announcements join the log once the board has played them out.
const { shownN } = useShownEvents(v);
const log = v.events.filter((e) => e.t !== 'phase' && e.n <= shownN);
const title = useAfterMotionValue(phaseTitle(v));
return (
<>
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>라이어 게임 · {title}</strong>
<span className="small">주제: {v.topicKo}</span>
<span className="small muted">{optionsSummary(v.options)}</span>
</div>
{log.length > 0 && (
<details className="card wide-open" open style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>발표 기록</summary>
<ol style={{ listStyle: 'none', margin: '6px 0 0', padding: 0, display: 'grid', gap: 3 }}>
{[...log].reverse().map((e) => (
<li key={e.n} className="small">
{eventText(e, players)}
</li>
))}
</ol>
</details>
)}
<p className="small muted" style={{ margin: 0 }}>
게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요. 음성 채팅으로 제시어를 말하지 않기로 해요.
</p>
</>
);
}
// ---------------------------------------------------------------- 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, PublicUser>): 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<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label} style={{ flexWrap: 'wrap' }}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
{children}
{help && <span className="small muted">{help}</span>}
</div>
);
}
const onOff: [boolean, string][] = [
[true, '켜기'],
[false, '끄기'],
];
const secs = <T extends number>(...v: T[]): [T | null, string][] => [...v.map((x): [T, string] => [x, `${x}초`]), [null, '무제한']];
function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
const [more, setMore] = useState(false);
const topics = useTopicChoices();
// A topic an admin deleted plays as 무작위 (shown as such so the host isn't left with a hidden choice).
const topic = o.topic === 'random' || topics.some((t) => t.id === o.topic) ? o.topic : 'random';
const set = (patch: Partial<LiarOptions>) => onChange({ ...o, ...patch });
return (
<div className="stack" style={{ gap: 16 }}>
<Field label="주제">
<Seg<string> label="주제" value={topic} options={[['random', '무작위'], ...topics.map((t): [string, string] => [t.id, t.ko])]} onChange={(next) => set({ topic: next })} />
</Field>
<Field label="바보 모드" help="켜면 라이어도 제시어와 비슷한 다른 단어(같은 묶음)를 받고, 자기가 라이어인지 몰라요.">
<Seg label="바보 모드" value={o.foolMode} options={onOff} onChange={(foolMode) => set({ foolMode })} />
</Field>
<Field label="설명 바퀴 수" help="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요.">
<Seg
label="설명 바퀴 수"
value={o.rounds}
options={[
[1, '한 바퀴'],
[2, '두 바퀴'],
]}
onChange={(rounds) => set({ rounds })}
/>
</Field>
<Field label="라이어의 정답 맞히기">
<Seg
label="정답 맞히기 방식"
value={o.guessMode}
options={[
['text', '직접 적기'],
['choice', '목록에서 고르기'],
]}
onChange={(guessMode) => set({ guessMode })}
/>
</Field>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
</button>
{more && (
<>
<Field label="한 사람 설명 시간" help={o.describeSeconds === null ? '설명을 보낼 때까지 기다려요.' : undefined}>
<Seg label="설명 시간" value={o.describeSeconds} options={secs(15, 20, 30, 45, 60)} onChange={(describeSeconds) => set({ describeSeconds })} />
</Field>
<Field label="자유 토론 시간" help={o.discussionSeconds === null ? '모두 [토론 끝내기]를 누르면 투표로 넘어가요.' : undefined}>
<Seg label="토론 시간" value={o.discussionSeconds} options={secs(30, 60, 90, 120, 180)} onChange={(discussionSeconds) => set({ discussionSeconds })} />
</Field>
<Field label="투표 시간" help={o.voteSeconds === null ? '모두 투표하면 결과가 나와요.' : undefined}>
<Seg label="투표 시간" value={o.voteSeconds} options={secs(15, 20, 30, 45)} onChange={(voteSeconds) => set({ voteSeconds })} />
</Field>
<Field label="정답 맞히기 시간" help={o.guessSeconds === null ? '라이어가 답할 때까지 기다려요.' : undefined}>
<Seg label="정답 맞히기 시간" value={o.guessSeconds} options={secs(20, 30, 45, 60)} onChange={(guessSeconds) => set({ guessSeconds })} />
</Field>
{[o.describeSeconds, o.discussionSeconds, o.voteSeconds, o.guessSeconds].includes(null) && (
<span className="small muted">무제한이어도 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 넘어가요(설명 넘김, 표 없음, 답 없음).</span>
)}
<Field label="고운 말 필터(욕설·링크·전화번호 막기)">
<Seg label="고운 말 필터" value={o.kidSafeChat} options={onOff} onChange={(kidSafeChat) => set({ kidSafeChat })} />
</Field>
</>
)}
</div>
);
}
function optionsSummary(o: LiarOptions): string {
void loadTopics();
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${topicName(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 (
<div className="stack">
<p>
3~10명이 같은 <strong>제시어</strong>를 받는데, 몰래 뽑힌 <strong>라이어</strong> 한 명만 주제만 알고 제시어는 몰라요. 시민은 라이어를 찾고, 라이어는 들키지 않거나 제시어를 맞히면 이겨요.
</p>
<p>
<strong>흐름</strong>: 제시어 확인 → 정해진 순서대로 한 사람씩 한 문장 설명(두 바퀴면 두 번째는 거꾸로) → 자유 토론 → 라이어 지목 투표 → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
</p>
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>
<li>제시어를 직접 말하면 안 돼요(띄어쓰기를 무시하고 막아요). 설명 차례에 시간이 지나면 넘어가요.</li>
<li>토론 채팅은 게임 내내 열려 있어요. 설명하는 중에도 언제든 이야기할 수 있어요.</li>
<li>투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.</li>
<li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li>
<li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li>
<li>바보 모드: 라이어도 제시어와 비슷한 다른 단어(같은 주제, 같은 묶음)를 받고, 자기가 라이어인지 몰라요.</li>
<li>시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.</li>
</ul>
<p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p>
</div>
);
}
const ui: GameUI<LiarView, LiarOptions> = {
Board: LiarBoard,
Side: LiarSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
ownChat: true,
typingInChat: true,
};
export default ui;