Files
joke-app/apps/web/src/games/clue/index.tsx

1089 lines
52 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 클루 화면 (docs/games/clue.md §9). */
import { useEffect, 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 type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
export const SUSPECT_COLOR: Record<Suspect, string> = {
scarlet: '#dc2626',
mustard: '#ca8a04',
white: '#f5f5f4',
green: '#15803d',
peacock: '#2563eb',
plum: '#7e22ce',
};
const SUSPECT_SHORT: Record<Suspect, string> = { scarlet: '스', mustard: '머', white: '화', green: '그', peacock: '피', plum: '플' };
export const WEAPON_ICON: Record<Weapon, string> = { candlestick: '🕯️', dagger: '🗡️', pipe: '🔩', revolver: '🔫', rope: '🪢', wrench: '🔧' };
export const ROOM_ICON: Record<Room, string> = { 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<Room, string> = { kitchen: 'k', ballroom: 'b', conservatory: 'c', dining: 'd', billiard: 'bi', library: 'li', lounge: 'lo', hall: 'h', study: 's' };
const DICE = ['', '⚀', '⚁', '⚂', '⚃', '⚄', '⚅'];
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' };
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 = <T,>(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<Item, string> {
const out = new Map<Item, string>();
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; }
}
@media (prefers-reduced-motion: reduce) { .cl-card.new, .cl-room.landed { animation: none; } }
`;
// ---------------------------------------------------------------- small pieces
function Token({ x, me, pop }: { x: Suspect; me?: boolean; pop?: boolean }) {
return (
<span className={`cl-tok${x === 'white' ? ' light' : ''}${me ? ' me' : ''}${pop ? ' anim-pop' : ''}`} style={{ background: SUSPECT_COLOR[x] }} title={SUSPECT_KO[x]} aria-hidden>
{SUSPECT_SHORT[x]}
</span>
);
}
function Card({ id, onClick, can, fresh, label, delay }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string; delay?: number }) {
const x = itemOf(id);
const cat = categoryOf(x);
const body = (
<>
<span className="ic" aria-hidden>
{cat === 'suspect' ? <Token x={x as Suspect} /> : iconOf(x)}
</span>
<span>{ITEM_KO[x]}</span>
<span className="cat">{CAT_KO[cat]}</span>
</>
);
const aria = label ?? `${CAT_KO[cat]} 카드 ${ITEM_KO[x]}`;
if (onClick)
return (
<button type="button" className={`cl-card${can ? ' can' : ''}`} onClick={onClick} aria-label={aria}>
{body}
</button>
);
return (
<span className={`cl-card${fresh ? ' new' : ''}`} role="img" aria-label={aria} style={delay ? ({ '--anim-delay': `${delay}ms` } as CSSProperties) : undefined}>
{body}
</span>
);
}
// ---------------------------------------------------------------- board
function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>) {
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<Room | null>(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]);
// 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);
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();
}
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), 1700);
return () => clearTimeout(t);
}, [banner]);
useEffect(() => {
if (!landed) return;
const t = setTimeout(() => setLanded(null), 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 (
<div className="cl-board" role="region" aria-label="클루 판">
<style>{CSS}</style>
<div className="cl-top">
<Mansion view={v} me={me} myTurn={myTurn && !pending} sel={sel} setSel={setSel} landed={landed?.room ?? null} />
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} setSel={setSel} />
</div>
{amPlayer && <MyCards view={v} me={me!} />}
{amPlayer && <Notebook view={v} me={me!} players={players} />}
{banner && (
<div key={banner.key} className={`cl-banner anim-banner ${banner.kind}`} aria-hidden>
{banner.text}
</div>
)}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
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 (
<div className="cl-map" role="group" aria-label="저택 지도">
{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 = (
<>
<span className="cl-rname">
<span aria-hidden>{ROOM_ICON[r]}</span>
<span>{ROOM_KO[r]}</span>
</span>
{can && !free && d !== undefined && <span className="cl-dist">{d}칸</span>}
<span className="cl-things">
{toks.map((x) => (
<Token key={x} x={x} me={x === mySuspect} pop />
))}
{weaps.map((w) => (
<span key={w} className="cl-weap anim-pop" title={WEAPON_KO[w]} aria-hidden>
{WEAPON_ICON[w]}
</span>
))}
</span>
{pass && (
<span className="cl-pass" aria-hidden>
↗ {ROOM_KO[pass]}
</span>
)}
</>
);
return can ? (
<button key={r} type="button" className={cls} style={{ gridArea: AREA[r] }} aria-pressed={sel === r} aria-label={label} onClick={() => setSel(sel === r ? null : r)}>
{inner}
</button>
) : (
<div key={r} className={cls} style={{ gridArea: AREA[r] }} role="img" aria-label={label}>
{inner}
</div>
);
})}
<div className="cl-mid" aria-label="복도와 사건 봉투">
<span className="cl-env">
<span aria-hidden>📁</span> 사건 봉투
</span>
{hall.length > 0 ? (
<ul aria-label="복도에 있는 말">
{hall.map((x) => {
const p = owner(x);
return (
<li key={x} style={p ? undefined : { opacity: 0.6 }} aria-label={`${SUSPECT_KO[x]}${p ? '' : '(맡은 사람 없음)'}: ${hallwayText(v.pos[x])}`}>
<Token key={posKey(v.pos[x])} x={x} me={x === mySuspect} pop />
<span aria-hidden>{hallwayText(v.pos[x])}</span>
</li>
);
})}
</ul>
) : (
<span className="muted">복도에 아무도 없어요</span>
)}
</div>
</div>
);
}
function ChipRow<T extends Item>({ label, items, value, onPick, known }: { label: string; items: readonly T[]; value: T | null; onPick: (x: T) => void; known: Map<Item, string> }) {
return (
<div className="stack" style={{ gap: 4 }}>
<strong className="small">{label}</strong>
<div className="cl-chips" role="group" aria-label={label}>
{items.map((x) => (
<button
key={x}
type="button"
className={`cl-chip${known.has(x) ? ' known' : ''}`}
aria-pressed={value === x}
aria-label={`${ITEM_KO[x]}${known.has(x) ? `, ${known.get(x)}` : ''}`}
onClick={() => onPick(x)}
>
{categoryOf(x) === 'suspect' ? <Token x={x as Suspect} /> : <span aria-hidden>{iconOf(x)}</span>}
{ITEM_KO[x]}
</button>
))}
</div>
</div>
);
}
function AccusePanel({ act, pending, onCancel, known }: { act: (a: unknown) => void; pending: boolean; onCancel: () => void; known: Map<Item, string> }) {
const [s, setS] = useState<Suspect | null>(null);
const [w, setW] = useState<Weapon | null>(null);
const [r, setR] = useState<Room | null>(null);
const [sure, setSure] = useState(false);
const done = s && w && r;
return (
<div className="cl-panel" role="group" aria-label="고발하기" onKeyDown={(e) => e.key === 'Escape' && onCancel()}>
<strong>고발하기: 봉투 속 정답을 말해요</strong>
<span className="small muted">맞히면 바로 이기고, 틀리면 탈락해요(카드 보여 주기는 계속해요). 한 사람에 한 번만 할 수 있어요.</span>
<ChipRow label="범인" items={SUSPECTS} value={s} onPick={(x) => (setS(x), setSure(false))} known={known} />
<ChipRow label="흉기" items={WEAPONS} value={w} onPick={(x) => (setW(x), setSure(false))} known={known} />
<ChipRow label="장소" items={ROOMS} value={r} onPick={(x) => (setR(x), setSure(false))} known={known} />
<div className="cl-btns">
<button type="button" className="btn btn-secondary" onClick={onCancel}>
취소
</button>
{!sure ? (
<button type="button" className="btn btn-primary" disabled={!done || pending} onClick={() => setSure(true)}>
{done ? `${triple({ suspect: s, weapon: w, room: r })} 고발` : '셋 다 골라 주세요'}
</button>
) : (
<button type="button" className="btn btn-danger" disabled={pending} onClick={() => act({ type: 'accuse', suspect: s, weapon: w, room: r })}>
정말 고발해요 (틀리면 탈락)
</button>
)}
</div>
</div>
);
}
function SuggestPanel({ room, act, pending, known, onAccuse }: { room: Room; act: (a: unknown) => void; pending: boolean; known: Map<Item, string>; onAccuse: () => void }) {
const [s, setS] = useState<Suspect | null>(null);
const [w, setW] = useState<Weapon | null>(null);
return (
<div className="cl-panel" role="group" aria-label="추리하기">
<strong>
{ROOM_ICON[room]} {ROOM_KO[room]}에서 추리해요
</strong>
<span className="small muted">범인과 흉기를 하나씩 고르면, 다음 사람부터 차례로 그중 가진 카드를 나에게만 보여 줘요. 고른 용의자 말과 흉기는 이 방으로 옮겨져요.</span>
<ChipRow label="범인" items={SUSPECTS} value={s} onPick={setS} known={known} />
<ChipRow label="흉기" items={WEAPONS} value={w} onPick={setW} known={known} />
<div className="cl-btns">
<button type="button" className="btn btn-primary" disabled={!s || !w || pending} onClick={() => act({ type: 'suggest', suspect: s, weapon: w })}>
{s && w ? `추리하기: ${triple({ suspect: s, weapon: w, room })}` : '범인과 흉기를 골라 주세요'}
</button>
</div>
<div className="cl-btns">
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'end' })}>
추리 안 하고 차례 끝내기
</button>
<button type="button" className="btn btn-ghost" disabled={pending} onClick={onAccuse}>
⚖️ 고발하기…
</button>
</div>
</div>
);
}
function LastResult({ view: v, me, players }: { view: ClueView; me: string | null; players: Record<string, PublicUser> }) {
const last = lastOf(v.suggestions);
if (!last || last.turnNo !== v.turnNo) return null;
const by = last.by === me ? '내' : `${nick(players, last.by)}님의`;
return (
<div className="stack" style={{ gap: 6 }} aria-live="polite">
<span className="small">
{by} 추리: <strong>{triple(last)}</strong>
{last.passed.length > 0 && <span className="muted"> · 못 보여 준 사람: {last.passed.map((p) => (p === me ? '나' : nick(players, p))).join(', ')}</span>}
</span>
{last.refuter ? (
last.shown ? (
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
<Card id={last.shown} fresh label={`${last.refuter === me ? '내가 보여 준' : `${nick(players, last.refuter)}님이 보여 준`} 카드: ${ITEM_KO[itemOf(last.shown)]}`} />
<span>
<strong>{last.refuter === me ? `내가 ${nick(players, last.by)}님에게 보여 준 카드` : `${nick(players, last.refuter)}님이 보여 준 카드`}</strong>
<br />
<span className="small muted">{last.by === me ? '추리 노트에 자동으로 표시했어요.' : '다른 사람은 어떤 카드인지 몰라요.'}</span>
</span>
</div>
) : (
<span>
<strong>{nick(players, last.refuter)}님</strong>이 {last.by === me ? '나' : `${nick(players, last.by)}님`}에게 카드 한 장을 몰래 보여 줬어요.
</span>
)
) : (
v.phase.kind !== 'refute' && <strong style={{ color: 'var(--success)' }}>아무도 카드를 보여 주지 못했어요!</strong>
)}
</div>
);
}
function ActionPanel({
view: v,
me,
players,
act,
pending,
myTurn,
sel,
setSel,
}: {
view: ClueView;
me: string | null;
players: Record<string, PublicUser>;
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 (
<div className="cl-panel" aria-live="polite">
<strong>게임이 끝났어요</strong>
<span>{v.final?.summary}</span>
{v.solution && (
<div className="cl-cards" aria-label="사건 봉투 속 정답">
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => (
<Card key={x} id={`card-${x}`} fresh delay={i * 250} />
))}
</div>
)}
</div>
);
}
if (ph.kind === 'refute') {
const sg = lastOf(v.suggestions)!;
if (ph.refuter === me) {
return (
<div className="cl-panel" role="group" aria-label="카드 보여 주기">
<strong>
{nick(players, sg.by)}님이 {ro(triple(sg))} 추리했어요
</strong>
<span className="small muted">내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요.{v.options.turnSeconds === null ? '' : ' 20초 안에 안 고르면 자동으로 보여 줘요.'}</span>
<div className="cl-cards">
{(ph.canShow ?? []).map((c) => (
<Card key={c} id={c} can onClick={() => !pending && act({ type: 'show', card: c })} label={`${ITEM_KO[itemOf(c)]} 카드 보여 주기`} />
))}
</div>
</div>
);
}
return (
<div className="cl-panel">
<LastResult view={v} me={me} players={players} />
<strong>
{nick(players, ph.refuter)}님이 {sg.by === me ? '나' : `${nick(players, sg.by)}님`}에게 보여 줄 카드를 고르는 중이에요
</strong>
</div>
);
}
if (!myTurn) {
const doing: Record<string, string> = {
move: '이동하는 중이에요',
moveTo: `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`,
suggest: '추리할 카드를 고르는 중이에요',
afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요',
};
return (
<div className="cl-panel">
<LastResult view={v} me={me} players={players} />
<strong>
{nick(players, v.current)}님이 {doing[ph.kind]}
</strong>
{me && v.seats.includes(me) && v.out[me] && <span className="small muted">나는 고발이 틀려 탈락했어요. 다른 사람이 추리하면 카드 보여 주기는 계속해요.</span>}
<span className="small muted">누가 무엇을 추리했고 누가 카드를 보여 줬는지 오른쪽 기록에서 볼 수 있어요.</span>
</div>
);
}
if (accusing) return <AccusePanel act={act} pending={pending} onCancel={() => setAccusing(false)} known={known} />;
const myPos = v.pos[v.suspectOf[me!]!];
const here = roomAt(myPos);
const accuseBtn = (
<button type="button" className="btn btn-ghost" disabled={pending} onClick={() => setAccusing(true)}>
⚖️ 고발하기…
</button>
);
if (ph.kind === 'suggest') return <SuggestPanel room={ph.room} act={act} pending={pending} known={known} onAccuse={() => setAccusing(true)} />;
if (ph.kind === 'afterSuggest') {
return (
<div className="cl-panel">
<LastResult view={v} me={me} players={players} />
<div className="cl-btns">
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'end' })}>
차례 끝내기
</button>
{accuseBtn}
</div>
</div>
);
}
const free = v.options.movement === 'free';
if (ph.kind === 'move' && !free) {
const pass = here ? PASSAGES[here] : undefined;
return (
<div className="cl-panel">
<strong>내 차례예요. {here ? `지금 ${ROOM_KO[here]}에 있어요.` : `지금 복도(${hallwayText(myPos)})에 있어요.`}</strong>
<div className="cl-btns">
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'roll' })}>
🎲 주사위 굴리기
</button>
{pass && (
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'passage' })}>
🕳️ 비밀 통로로 {ROOM_KO[pass]} 가기
</button>
)}
{here && v.movedIn[me!] && (
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'stay' })}>
🔍 여기({ROOM_KO[here]})서 추리하기
</button>
)}
{accuseBtn}
</div>
{here && v.movedIn[me!] && <span className="small muted">다른 사람의 추리로 이 방에 불려 왔어요. 움직이지 않고 여기서 추리할 수 있어요.</span>}
</div>
);
}
// 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 (
<div className="cl-panel">
{v.dice && (
<div className="cl-dice" role="img" aria-label={`주사위 ${v.dice[0]}과 ${v.dice[1]}, 합 ${sum}`}>
<span key={`a${v.turnNo}-${v.dice[0]}`} className="anim-roll" aria-hidden>
{DICE[v.dice[0]]}
</span>
<span key={`b${v.turnNo}-${v.dice[1]}`} className="anim-roll" style={{ animationDelay: '80ms' }} aria-hidden>
{DICE[v.dice[1]]}
</span>
<b aria-hidden>= {sum}칸</b>
</div>
)}
<strong>지도에서 갈 방을 눌러 주세요.</strong>
<span className="small muted">
{free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`}
</span>
<div className="cl-btns">
{sel && enter && (
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'go', room: sel })}>
{ROOM_ICON[sel]} {ro(ROOM_KO[sel])} 들어가기
</button>
)}
{sel && !enter && d !== null && (
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'walk', room: sel })}>
{ROOM_KO[sel]} 쪽으로 걸어가기 (남는 거리 {d - sum}칸)
</button>
)}
{!sel && (
<button type="button" className="btn btn-primary" disabled>
방을 골라 주세요
</button>
)}
{free && here && v.movedIn[me!] && (
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'stay' })}>
🔍 여기({ROOM_KO[here]})서 추리하기
</button>
)}
{sel && (
<button type="button" className="btn btn-secondary" onClick={() => setSel(null)}>
다시 고르기
</button>
)}
{accuseBtn}
</div>
</div>
);
}
function MyCards({ view: v, me }: { view: ClueView; me: string }) {
const mine = v.myHand ?? [];
return (
<section className="cl-sec" aria-label="내 카드">
<div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline' }}>
<strong>
내 카드 {mine.length}장 · <Token x={v.suspectOf[me]!} /> {SUSPECT_KO[v.suspectOf[me]!]} 말
</strong>
<span className="small muted">내 카드는 봉투에 없어요</span>
</div>
<div className="cl-cards">
{mine.map((c) => (
<Card key={c} id={c} />
))}
</div>
{v.publicCards.length > 0 && (
<>
<strong className="small">모두에게 공개된 카드 {v.publicCards.length}장</strong>
<div className="cl-cards">
{v.publicCards.map((c) => (
<Card key={c} id={c} />
))}
</div>
</>
)}
</section>
);
}
// ---------------------------------------------------------------- notebook (kept on this device)
type Mark = '' | 'x' | 'q' | 'o';
const NEXT: Record<Mark, Mark> = { '': 'x', x: 'q', q: 'o', o: '' };
const MARK_TEXT: Record<Mark, string> = { '': '', x: '✗', q: '?', o: '✓' };
const MARK_KO: Record<Mark, string> = { '': '표시 없음', 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<string, PublicUser> }) {
const key = noteKey(v.gameNo);
const [marks, setMarks] = useState<Record<string, Mark>>(() => {
try {
return key ? (JSON.parse(localStorage.getItem(key) ?? '{}') as Record<string, Mark>) : {};
} 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[]) => (
<div>
<h4>{title}</h4>
<ul>
{items.map((x) => {
const why = auto.get(x);
const m: Mark = why ? 'x' : (marks[x] ?? '');
return (
<li key={x} className={why ? 'auto' : ''}>
<button
type="button"
className={`cl-mark ${m}`}
disabled={!!why}
aria-label={`${ITEM_KO[x]}: ${why ? `${why}, 자동 표시` : `${MARK_KO[m]}, 눌러서 바꾸기`}`}
onClick={() => set(x)}
>
{MARK_TEXT[m]}
</button>
<span className="nm">
{categoryOf(x) !== 'suspect' && <span aria-hidden>{iconOf(x)} </span>}
{ITEM_KO[x]}
</span>
{why && <span className="why">{why}</span>}
</li>
);
})}
</ul>
</div>
);
return (
<details className="cl-sec" open>
<summary style={{ cursor: 'pointer', fontWeight: 800 }}>🗒️ 추리 노트</summary>
<span className="small muted">내 카드·공개 카드·나에게 보여 준 카드는 자동으로 ✗예요. 나머지는 눌러서 ✗ → ? → ✓ 로 바꿔요. 이 기기에만 저장돼요.</span>
<div className="cl-note">
{group('범인', SUSPECTS)}
{group('흉기', WEAPONS)}
{group('장소', ROOMS)}
</div>
</details>
);
}
// ---------------------------------------------------------------- side
type LogLine = { turn: number; order: number; text: string; shown?: string; mine?: boolean };
function logLines(v: ClueView, me: string | null, players: Record<string, PublicUser>): 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<ClueView>) {
const running = v.phase.kind !== 'finished';
const lines = logLines(v, me, players);
const wait = waitingOn(v);
return (
<>
<style>{CSS}</style>
<div className="card stack" style={{ gap: 8, padding: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong>{running ? (v.phase.kind === 'refute' ? `${nick(players, wait)}님이 카드 고르는 중` : `${nick(players, v.current)}님 차례`) : '게임 끝'}</strong>
{running && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine={isMyTurn(v, me)} size={36} />}
</div>
<span className="small muted">{optionsSummary(v.options)}</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 5 }} aria-label="참가자">
{v.seats.map((p) => {
const x = v.suspectOf[p]!;
return (
<li key={p} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: v.out[p] || v.left[p] ? 0.6 : 1 }}>
<Avatar user={userOf(players, p)} size={24} />
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p === me ? 800 : 600 }}>
{nick(players, p)}
{p === me && <span className="muted"> (나)</span>}
</span>
<Token x={x} me={p === me} />
<span className="small muted" style={{ whiteSpace: 'nowrap' }}>
카드 {v.handCounts[p]}장
</span>
{running && wait === p && <span className="cl-badge turn">{v.phase.kind === 'refute' ? '보여 주는 중' : '차례'}</span>}
{v.final?.winner === p && <span className="cl-badge ok">승리</span>}
{v.left[p] ? <span className="cl-badge out">나감</span> : v.out[p] && <span className="cl-badge out">고발 실패</span>}
</li>
);
})}
</ol>
</div>
{v.hands && v.solution && (
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>정답: {triple(v.solution)}</strong>
{v.seats.map((p) => (
<span key={p} className="small">
{nick(players, p)}: {v.hands![p]!.map((c) => ITEM_KO[itemOf(c)]).join(', ') || '없음'}
</span>
))}
</div>
)}
<details className="card" open style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>추리 기록 ({lines.length})</summary>
{lines.length === 0 ? (
<p className="small muted" style={{ margin: '8px 0 0' }}>
아직 추리가 없어요.
</p>
) : (
<ol className="cl-log" style={{ marginTop: 8 }} tabIndex={0} aria-label="추리 기록 목록">
{[...lines].reverse().map((l, i) => (
<li key={lines.length - i}>
{l.text}
{l.shown && <span className="cl-shown"> [{ITEM_KO[itemOf(l.shown)]}]</span>}
</li>
))}
</ol>
)}
</details>
</>
);
}
// ---------------------------------------------------------------- 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, PublicUser>): 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<T extends string | number | 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}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Options({ value: o, onChange }: OptionsProps<ClueOptions>) {
const set = (patch: Partial<ClueOptions>) => onChange({ ...o, ...patch });
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>이동 방식</strong>
<Seg
label="이동 방식"
value={o.movement}
options={[
['dice', '주사위 2개로 복도 이동(원작처럼)'],
['free', '빠르게(아무 방이나 바로)'],
]}
onChange={(movement) => set({ movement })}
/>
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>차례 제한 시간</strong>
<Seg
label="차례 제한 시간"
value={o.turnSeconds}
options={[
[30, '30초'],
[45, '45초'],
[60, '60초'],
[90, '90초'],
[null, '무제한'],
]}
onChange={(turnSeconds) => set({ turnSeconds })}
/>
{o.turnSeconds === null && <span className="small muted">차례와 카드 보여 주기에 시간 제한이 없어요. 연결이 끊긴 채 돌아오지 않는 사람만 자동으로 넘겨요.</span>}
</div>
</div>
);
}
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 (
<div className="stack">
<p>
저택에서 살인 사건이 일어났어요. <strong>누가(범인), 무엇으로(흉기), 어디서(장소)</strong> 했는지 맞히는 추리 게임이에요. 3~6명이 할 수 있어요.
</p>
<p>
<strong>준비</strong>: 용의자 6장, 흉기 6장, 방 9장 중 종류마다 한 장씩 몰래 뽑아 <strong>사건 봉투</strong>에 넣어요. 이것이 정답이에요. 남은 18장은 모두에게 똑같이 나눠 주고,
똑같이 나누고 남는 카드(4명이면 2장, 5명이면 3장)는 모두에게 공개해요. 내 손에 있는 카드는 봉투에 없다는 뜻이에요. 각자 용의자 말 하나를 맡고, 스칼렛을 맡은 사람이 먼저 해요.
</p>
<p>
<strong>이동</strong>:{' '}
{free
? '이 방은 "빠른 이동"이라 주사위 없이 아무 방이나 바로 들어가요(지금 있는 방 빼고).'
: '주사위 2개를 굴려 나온 합만큼 복도를 걸어요. 지도에 칸 수가 나오고, 닿는 방(초록)에 바로 들어가요. 먼 방(점선)을 고르면 그쪽으로 걸어가다 차례가 끝나요. 모서리 방(부엌↔서재, 온실↔라운지)은 비밀 통로로 주사위 없이 바로 건너가요. 방금 있던 방에 다시 들어갈 수는 없어요.'}
</p>
<p>
<strong>추리</strong>: 방에 들어가면 "○○가, △△로, 이 방에서"라고 추리해요. 장소는 지금 있는 방이에요. 말한 용의자 말과 흉기가 그 방으로 옮겨져요. 그러면 내 다음 사람부터 차례로, 셋 중 하나라도 가진
사람이 <strong>그중 한 장을 나에게만</strong> 보여 줘요(여러 장이면 보여 주는 사람이 골라요). 한 사람이 보여 주면 거기서 멈추고, 다른 사람들은 누가 보여 줬는지만 알아요. 다른 사람의 추리로 내 말이 어떤 방에
불려 갔다면, 다음 내 차례에 움직이지 않고 그 방에서 추리할 수 있어요.
</p>
<p>
<strong>고발</strong>: 확신이 서면 내 차례 아무 때나 "범인·흉기·장소"를 말해 고발해요(장소는 어느 방이든 돼요). 한 사람에 한 번뿐이에요. 셋 다 맞으면 이기고, 틀리면 탈락해요. 탈락해도 다른 사람이 추리하면
카드는 계속 보여 줘야 해요. 모두 틀리면 아무도 못 이겨요.
</p>
<p>
<strong>추리 노트</strong>: 화면 아래 노트에 내 카드, 공개 카드, 나에게 보여 준 카드가 자동으로 ✗ 표시돼요. 나머지는 직접 눌러 ✗·?·✓를 적어 두세요(이 기기에만 저장돼요).
</p>
<p className="muted">
{options?.turnSeconds === null
? '이 방은 차례 시간이 무제한이에요. 연결이 끊긴 채 돌아오지 않으면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요(카드 보여 주기는 맞는 카드가 자동으로).'
: '차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요.'}{' '}
게임 중에 나간 사람의 카드는 모두에게 공개돼요.
</p>
</div>
);
}
const ui: GameUI<ClueView, ClueOptions> = {
Board: ClueBoard,
Side: ClueSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;