/** 다빈치 코드 화면 (docs/games/davinci-code.md §9). */ import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react'; import type { DavinciGuess, DavinciOptions, DavinciTileView, DavinciView, PhaseKind, TColor, TileValue } from '@bg/games/davinci-code'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; const COLOR_KO: Record = { black: '검은색', white: '흰색' }; const COLOR_SHORT: Record = { black: '검정', white: '흰색' }; const NUMBERS = Array.from({ length: 12 }, (_, i) => i); const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const valueKo = (v: TileValue) => (v === 'joker' ? '조커' : String(v)); const faceOf = (v: TileValue) => (v === 'joker' ? '−' : String(v)); const hiddenLeft = (row: DavinciTileView[]) => row.filter((t) => !t.revealed).length; /** Standing number-tile sounds (synthesized; the site volume is applied by feedback.ts). */ const snd = { /** A tile taken from the face-down pile. */ draw: () => { noise(120, 0.08, 0, 'bandpass', 1200, 0.7); tone(330, 60, 'triangle', 0.07, 100); }, /** A tile slotted into a row: a solid "딸깍". */ set: (delay = 0) => { noise(30, 0.15, delay, 'bandpass', 2600, 2); tone(950, 38, 'triangle', 0.09, delay); tone(260, 70, 'sine', 0.08, delay + 10); }, /** A tile tipped over face up. */ flip: (delay = 0) => { noise(45, 0.11, delay, 'highpass', 3000); tone(620, 70, 'triangle', 0.08, delay + 25, { slideTo: 1240 }); }, /** Somebody guessed my tile right. */ ouch: (delay = 0) => tone(520, 200, 'triangle', 0.1, delay, { slideTo: 300 }), /** A joker goes into a row (only when the viewer can see it is a joker). */ joker: (delay = 0) => [1568, 2093, 2637].forEach((f, i) => tone(f, 90, 'triangle', 0.05, delay + i * 60)), /** A player is out. */ out: (delay = 0) => [523, 440, 349].forEach((f, i) => tone(f, 170, 'triangle', 0.09, delay + i * 130)), }; /** A value that shows for `ms` and then clears itself (timer cleaned up on unmount). */ function useTimed(): [T | null, (v: T, ms: number) => void] { const [val, setVal] = useState(null); const timer = useRef | undefined>(undefined); useEffect(() => () => clearTimeout(timer.current), []); const set = useCallback((v: T, ms: number) => { clearTimeout(timer.current); setVal(v); timer.current = setTimeout(() => setVal(null), ms); }, []); return [val, set]; } /** Wraps a number that bumps (anim-bump) whenever it changes after the first render. */ function Bump({ value, children }: { value: number; children: React.ReactNode }) { const prev = useRef(value); const n = useRef(0); if (prev.current !== value) { prev.current = value; n.current += 1; } return ( {children} ); } function totalMsOf(v: DavinciView): number { if (v.phase === 'chooseStart') return 15_000; if ((v.idle[v.current] ?? 0) >= 3) return 5_000; return v.phase === 'guess' ? (v.options.turnSeconds ?? 30) * 1000 : 10_000; } /** Seats starting with the one after `me` (clockwise); spectators see everyone. */ function opponentsOf(v: DavinciView, me: string | null): string[] { const i = me ? v.seats.indexOf(me) : -1; if (i < 0) return v.seats; return v.seats.map((_, k) => v.seats[(i + 1 + k) % v.seats.length]!).filter((p) => p !== me); } /** Colour+number combinations the viewer can already see (for the "impossible guess" warning). */ function visibleCombos(v: DavinciView): Set { const out = new Set(); for (const row of Object.values(v.rows)) for (const t of row) if (t.n !== undefined) out.add(`${t.color}:${t.n}`); if (v.pending?.n !== undefined) out.add(`${v.pending.color}:${v.pending.n}`); return out; } function guessLine(g: DavinciGuess, players: Record): string { return `${nick(players, g.by)} → ${nick(players, g.target)} ${g.index + 1}번째 ${COLOR_SHORT[g.color]} = ${valueKo(g.said)} (${g.correct ? '맞힘' : '틀림'}${g.auto ? ', 시간 초과' : ''})`; } const CSS = ` .dv-bump { display: inline-block; } .dv-banner { position: fixed; z-index: 40; top: 34%; left: 0; right: 0; margin: 0 auto; width: max-content; max-width: 92vw; text-align: center; padding: 12px 26px; border-radius: 18px; font-size: clamp(1.4rem, 5vw, 2.2rem); font-weight: 900; background: linear-gradient(160deg, #42454d, #141519); color: #fff; border: 2px solid #050505; box-shadow: 0 4px 0 rgba(0,0,0,.45), 0 12px 30px rgba(0,0,0,.35); } .dv-board { width: 100%; max-width: 980px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; } .dv-opps { display: grid; gap: 10px; } .dv-player { background: var(--surface); border-radius: var(--radius-lg); padding: 10px 12px; box-shadow: var(--shadow); border: 3px solid transparent; } .dv-player.turn { border-color: var(--focus); } .dv-player.out { opacity: .7; } .dv-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-height: 32px; } .dv-name { font-weight: 800; max-width: 12em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .dv-badge { display: inline-block; border-radius: 999px; padding: 1px 9px; font-weight: 800; font-size: .8rem; background: var(--surface-2); color: var(--text); } .dv-badge.turn { background: var(--focus); color: #1c1e21; } .dv-badge.out { background: var(--danger-soft); color: var(--danger); } .dv-badge.ok { background: var(--success-soft); color: var(--success); } .dv-row { --lift: 34px; display: flex; flex-wrap: wrap; gap: 6px; align-items: flex-end; padding-top: calc(8px + var(--lift)); } .dv-me .dv-row { --lift: 40px; } .dv-slot { display: flex; flex-direction: column; align-items: center; gap: 2px; } .dv-pos { font-size: .75rem; color: var(--text-sub); font-variant-numeric: tabular-nums; line-height: 1; } .dv-tile { --w: 46px; width: var(--w); height: calc(var(--w) * 1.42); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: calc(var(--w) * .56); line-height: 1; position: relative; user-select: none; font-variant-numeric: tabular-nums; box-shadow: 0 3px 0 rgba(0,0,0,.35); transition: transform .15s ease; } .dv-tile.black { background: linear-gradient(160deg, #42454d, #141519); color: #fff; border: 2px solid color-mix(in srgb, var(--text) 30%, #050505); } .dv-tile.white { background: linear-gradient(160deg, #ffffff, #e2ded3); color: #15161a; border: 2px solid #9d978a; } .dv-tile.back.black { background: repeating-linear-gradient(45deg, #2a2c33 0 5px, #1b1c21 5px 10px); } .dv-tile.back.white { background: repeating-linear-gradient(45deg, #fbf9f4 0 5px, #e6e1d6 5px 10px); } .dv-tile .q { opacity: .45; font-size: .62em; } .dv-slot.open > .dv-pick { position: relative; top: calc(-1 * var(--lift)); } .dv-slot.open > .dv-pick::after { content: ''; position: absolute; left: 12%; right: 12%; bottom: -7px; height: 5px; border-radius: 3px; background: #f59e0b; } .dv-tile.secret { outline: 3px dashed var(--primary); outline-offset: 2px; } .dv-tile.sm { --w: 30px; } .dv-tile.lg { --w: 54px; } .dv-tile.hit { animation: dv-flip .5s ease-out both, dv-hit 1.2s ease-out both; } .dv-tile.miss { animation: dv-flip .5s ease-out both, dv-miss 1.2s ease-out both; animation-delay: var(--anim-delay, 0ms); } .dv-tile.new { animation: dv-drop .38s ease-out both; animation-delay: var(--anim-delay, 0ms); } .dv-tile.shake { animation: anim-shake .45s ease, dv-miss 1.2s ease-out; } .dv-tile.deal { animation: anim-deal .38s cubic-bezier(0.2, 0.8, 0.3, 1.15) both; animation-delay: var(--anim-delay, 0ms); } .dv-tile.reveal { animation: dv-flip .45s ease-out both; animation-delay: var(--anim-delay, 0ms); } @keyframes dv-flip { 0% { transform: perspective(500px) rotateY(90deg); } 60% { transform: perspective(500px) rotateY(-12deg); } 100% { transform: perspective(500px) rotateY(0); } } @keyframes dv-hit { 0%, 60% { box-shadow: 0 0 0 4px #22c55e, 0 0 18px 6px rgba(34,197,94,.7); } 100% { box-shadow: 0 3px 0 rgba(0,0,0,.35); } } @keyframes dv-miss { 0%, 60% { box-shadow: 0 0 0 4px #ef4444, 0 0 18px 6px rgba(239,68,68,.6); } 100% { box-shadow: 0 3px 0 rgba(0,0,0,.35); } } @keyframes dv-drop { 0% { transform: translateY(-34px) scale(.85); opacity: .2; } 70% { transform: translateY(3px); opacity: 1; } 100% { transform: translateY(0); } } .dv-pick { background: none; border: 0; padding: 3px; border-radius: 11px; cursor: pointer; color: inherit; } .dv-pick:disabled { cursor: default; } .dv-pick.can { box-shadow: 0 0 0 3px var(--primary); } .dv-pick.can:hover .dv-tile { transform: translateY(-3px); } .dv-pick.sel { box-shadow: 0 0 0 4px var(--focus); } .dv-pick.sel .dv-tile { transform: translateY(-6px); } .dv-pick:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .dv-gap { align-self: stretch; min-width: 28px; min-height: 48px; border: 2px dashed var(--primary); background: var(--primary-soft); color: var(--text); border-radius: 8px; font-weight: 800; cursor: pointer; padding: 0 2px; font-size: .8rem; } .dv-gap:focus-visible { outline: 3px solid var(--focus); } .dv-mid { display: grid; grid-template-columns: minmax(0, 260px) minmax(0, 1fr); gap: 12px; align-items: start; } .dv-center { background: var(--felt); color: #fff; border-radius: var(--radius-lg); padding: 12px; display: flex; flex-direction: column; gap: 10px; align-items: center; } .dv-piles { display: flex; gap: 12px; justify-content: center; } .dv-pile { display: flex; flex-direction: column; align-items: center; gap: 4px; background: rgba(0,0,0,.18); border: 2px solid transparent; border-radius: 12px; padding: 8px 10px; color: #fff; font-weight: 800; min-width: 92px; min-height: 48px; cursor: pointer; font-size: .9rem; } .dv-pile:disabled { cursor: default; opacity: .8; } .dv-pile.can { border-color: #fde047; background: rgba(253,224,71,.15); } .dv-pile:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .dv-stack { position: relative; width: 44px; height: 50px; } .dv-stack .dv-tile { position: absolute; left: 0; } .dv-pending { display: flex; align-items: center; gap: 10px; font-size: .9rem; } .dv-panel { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 10px; } .dv-pad { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; } .dv-pad button { min-height: 56px; font-size: 1.35rem; font-weight: 900; border-radius: 12px; border: 2px solid var(--border); background: var(--surface); color: var(--text); cursor: pointer; font-variant-numeric: tabular-nums; } .dv-pad button.unlikely { opacity: .4; } .dv-pad button[aria-pressed='true'] { background: var(--primary); color: var(--primary-text); border-color: var(--primary); opacity: 1; } .dv-pad button:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .dv-pad .joker { grid-column: 1 / -1; font-size: 1.1rem; } .dv-big { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } .dv-big .btn { min-height: 64px; font-size: 1.15rem; } .dv-split { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; } .dv-split button { min-height: 56px; border-radius: 12px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font-weight: 700; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 6px; padding: 4px 8px; } .dv-split button[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); } .dv-split button:disabled { opacity: .4; cursor: not-allowed; } .dv-split button:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .dv-mini { display: inline-block; width: 12px; height: 17px; border-radius: 3px; vertical-align: middle; } .dv-mini.black { background: #1b1c21; border: 1px solid #000; } .dv-mini.white { background: #fff; border: 1px solid #8f8a7e; } .dv-me { border-color: var(--primary); } .dv-legend { font-size: .85rem; color: var(--text-sub); display: flex; gap: 6px 16px; flex-wrap: wrap; align-items: center; } .dv-legend > span { display: inline-flex; align-items: center; gap: 7px; } .dv-me .dv-slot { gap: 6px; } .dv-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 3px; max-height: 220px; overflow: auto; font-size: .9rem; } .dv-log li.hit::before { content: '✓ '; color: var(--success); font-weight: 900; } .dv-log li.miss::before { content: '✗ '; color: var(--danger); font-weight: 900; } @media (max-width: 719px) { .dv-tile { --w: 34px; border-radius: 6px; } .dv-tile.lg { --w: 37px; } .dv-row { gap: 4px; --lift: 26px; } .dv-me .dv-row { --lift: 28px; } .dv-mid { grid-template-columns: minmax(0, 1fr); } .dv-board { max-height: none; overflow: visible; } } @media (prefers-reduced-motion: reduce) { .dv-tile.hit, .dv-tile.miss, .dv-tile.new, .dv-tile.shake, .dv-tile.deal, .dv-tile.reveal { animation: none; } .dv-banner { display: none; } } `; // ---------------------------------------------------------------- tiles type FxKind = 'hit' | 'miss' | 'new' | 'shake' | 'deal' | 'reveal'; /** One tile's animation: kind, start delay, and a sequence number so the same kind can replay. */ interface Fx { k: FxKind; d: number; s: number; } function Tile({ color, n, revealed, mine, size, fx }: { color: TColor; n?: TileValue; revealed: boolean; mine?: boolean; size?: 'sm' | 'lg'; fx?: Fx }) { const known = n !== undefined; const cls = ['dv-tile', color, known ? '' : 'back', revealed ? 'open' : '', mine && !revealed ? 'secret' : '', size ?? '', fx?.k ?? ''].filter(Boolean).join(' '); return ( {known ? faceOf(n) : ?} ); } function tileLabel(t: DavinciTileView, pos: number, mine: boolean): string { const what = t.n === undefined ? '숨김' : t.n === 'joker' ? '조커' : `${t.n}`; return `${pos + 1}번째, ${COLOR_KO[t.color]} ${what}${t.revealed ? ', 공개됨' : mine ? ', 나만 보임' : ''}${t.wrong.length ? `, 틀린 추리 ${t.wrong.map(valueKo).join('·')}` : ''}`; } // ---------------------------------------------------------------- board const NO_FX = new Map(); interface Sel { target: string; index: number; } function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardProps) { const amPlayer = !!me && v.seats.includes(me); const myTurn = amPlayer && v.current === me && !!v.alive[me!] && v.phase !== 'chooseStart' && v.phase !== 'finished'; const [sel, setSel] = useState(null); const [val, setVal] = useState(null); const [fx, setFx] = useTimed>(); const [pendFx, setPendFx] = useTimed(); const [banner, setBanner] = useTimed<{ text: string; s: number }>(); const [announce, setAnnounce] = useState(''); const seq = useRef(0); const snap = useRef<{ hist: number; phase: PhaseKind; pending: boolean; elim: number; picked: number; rows: Record } | null>(null); const prevTurn = useRef(`${v.current}|${v.phase === 'chooseStart'}`); const resetKey = `${v.phase}|${v.current}|${v.history.length}`; useEffect(() => { setSel(null); setVal(null); }, [resetKey]); // Sounds, tile animations and screen-reader text for what anybody did, from view changes only // (the first view after mounting is just recorded, so joining / reconnecting is silent). useEffect(() => { const now = { hist: v.history.length, phase: v.phase, pending: !!v.pending, elim: v.eliminationOrder.length, picked: v.picked ? Object.values(v.picked).filter(Boolean).length : 0, rows: Object.fromEntries(v.seats.map((p) => [p, (v.rows[p] ?? []).map((t) => t.revealed)])), }; const prev = snap.current; snap.current = now; if (!prev) return; const next = new Map(); const put = (key: string, k: FxKind, d = 0) => next.set(key, { k, d, s: ++seq.current }); if (prev.phase === 'chooseStart' && v.phase !== 'chooseStart') { // Start tiles dealt into every row. let k = 0; for (const p of v.seats) (v.rows[p] ?? []).forEach((_, i) => put(`${p}:${i}`, 'deal', Math.min(k++ * 60, 900))); sfx.deal(Math.min(k, 10), 60); } else { if (v.phase === 'chooseStart' && now.picked > prev.picked) sfx.click(); if (!prev.pending && v.pending) { snd.draw(); setPendFx({ k: 'deal', d: 0, s: ++seq.current }, 700); } let t = 0; // delay of the next sound, so a miss and the tile it costs are heard one after another const g = now.hist === prev.hist + 1 ? v.history[v.history.length - 1]! : null; if (g) { if (g.correct) { put(`${g.target}:${g.index}`, 'hit'); snd.flip(); if (g.target === me) snd.ouch(140); else sfx.good(); if (g.by === me) haptic(30); } else { put(`${g.target}:${g.index}`, 'shake'); sfx.bad(); t = 320; } setAnnounce(`${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리해서 ${g.correct ? '맞혔어요' : '틀렸어요'}.`); } for (const p of v.seats) { const a = prev.rows[p] ?? []; const b = now.rows[p] ?? []; const lp = v.lastPlaced; if (b.length === a.length + 1 && lp?.player === p) { // A tile slotted into the row (after 멈추기, a miss, a joker, or at the game end). put(`${p}:${lp.index}`, lp.revealed ? 'miss' : 'new', t); if (lp.revealed) snd.flip(t); else snd.set(t); if (v.rows[p]?.[lp.index]?.n === 'joker') snd.joker(t + 90); } else if (b.length === a.length) { // Own tile shown after a miss with an empty pile, or all tiles opened when someone leaves. let opened = 0; b.forEach((r, i) => { if (r && !a[i] && !(g?.correct && g.target === p && g.index === i)) put(`${p}:${i}`, 'miss', t + opened++ * 80); }); if (opened) snd.flip(t); } } if (now.elim > prev.elim) { const out = v.eliminationOrder[v.eliminationOrder.length - 1]!; if (!v.left[out]) { setBanner({ text: out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`, s: ++seq.current }, 1700); // The match result sound itself is played by the room page. if (v.phase !== 'finished') snd.out(t + 250); } } if (prev.phase !== 'finished' && v.phase === 'finished') { // Game over: every tile that was still hidden from me is turned over. let k = 0; for (const p of v.seats) { if (p === me) continue; (v.rows[p] ?? []).forEach((r, i) => { if (!r.revealed && !next.has(`${p}:${i}`)) put(`${p}:${i}`, 'reveal', Math.min(400 + k++ * 50, 1000)); }); } } } if (next.size) setFx(next, 1700); }, [v]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { const key = `${v.current}|${v.phase === 'chooseStart'}`; if (key !== prevTurn.current && v.phase !== 'chooseStart' && v.phase !== 'finished') { if (v.current === me) { haptic(40); sounds.myTurn(); setAnnounce('내 차례예요.'); } else setAnnounce(`${nick(players, v.current)}님 차례예요.`); } prevTurn.current = key; }, [v.current, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps const canGuess = myTurn && v.phase === 'guess' && !pending; const pick = (target: string, index: number) => { sfx.select(); if (sel && sel.target === target && sel.index === index) { setSel(null); setVal(null); } else { setSel({ target, index }); setVal(null); } }; return (
{opponentsOf(v, me).map((p) => ( ))}
(setSel(null), setVal(null))} />
{amPlayer && }

{announce}

{banner && (
{banner.text}
)}
); } function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view: DavinciView; me: string | null; players: Record; deadline: number | null }) { const u = userOf(players, id); const row = v.rows[id] ?? []; const st = v.stats[id] ?? { guesses: 0, correct: 0 }; const outRank = v.eliminationOrder.indexOf(id); const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id; const choosing = v.phase === 'chooseStart' && v.alive[id] && v.picked && !v.picked[id]; return (
{u.nickname} {id === me && (나)} {isTurn && 차례} {v.final?.winner === id && 승리} {!v.alive[id] && {v.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${v.seats.length - outRank}위` : ''}} {v.alive[id] && (v.idle[id] ?? 0) >= 3 && 자리 비움} {v.phase === 'chooseStart' && v.alive[id] && {choosing ? '고르는 중' : '다 골랐어요'}} {v.phase !== 'chooseStart' && ( <> 숨은 타일 {hiddenLeft(row)}개 ·{' '} )} 맞힘 {st.correct}/{st.guesses} {(isTurn || choosing) && }
); } function PlayerRow({ id, view: v, me, players, deadline, fx, canPick, sel, onPick, }: { id: string; view: DavinciView; me: string | null; players: Record; deadline: number | null; fx: Map; canPick: boolean; sel: Sel | null; onPick: (target: string, index: number) => void; }) { const row = v.rows[id] ?? []; const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id; const name = nick(players, id); return (
{row.length === 0 && {v.phase === 'chooseStart' ? '시작 타일을 기다리는 중이에요' : '타일이 없어요'}} {row.map((t, i) => { const can = canPick && !t.revealed; const selected = sel?.target === id && sel.index === i; return (
{i + 1}
); })}
); } function MyRow({ view: v, me, players, act, pending, myTurn, deadline, fx, }: { view: DavinciView; me: string; players: Record; act: (a: unknown) => void; pending: boolean; myTurn: boolean; deadline: number | null; fx: Map; }) { const row = v.rows[me] ?? []; const placing = myTurn && v.phase === 'placeJoker' && !pending; const revealing = myTurn && v.phase === 'revealOwn' && !pending; const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === me; const gap = (index: number) => placing && ( ); return (
{row.length === 0 && {v.phase === 'chooseStart' ? '시작 타일 색을 고르면 여기에 놓여요' : '타일이 없어요'}} {row.map((t, i) => { const can = revealing && !t.revealed; return [ gap(i),
{can ? ( ) : ( )} {i + 1}
, ]; })} {gap(row.length)}
{row.length > 0 && (
점선: 상대에게 숨김 반 칸 위 + 아래 노란 줄: 모두에게 공개됨
)}
); } function Center({ view: v, me, players, act, pending, myTurn, pendFx, }: { view: DavinciView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; myTurn: boolean; pendFx: Fx | null; }) { const drawing = myTurn && v.phase === 'draw' && !pending; const total = v.pool.black + v.pool.white; const last = v.history[v.history.length - 1]; return (
{v.options.chooseColors ? (
{(['black', 'white'] as const).map((c) => { const can = drawing && v.pool[c] > 0; return ( ); })}
) : ( )} {v.pending ? (
{v.current === me ? '내가 가져온 타일' : `${nick(players, v.current)}님이 가져온 타일`}
{v.current === me ? '나만 보여요' : '색만 보여요'}
) : ( v.phase !== 'chooseStart' && v.phase !== 'finished' && total === 0 && 더미가 비었어요. 가져오지 않고 바로 추리해요. )} {last && ( 최근: {guessLine(last, players)} )}
); } function ActionPanel({ view: v, me, players, act, pending, myTurn, sel, val, setVal, onCancel, }: { view: DavinciView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; myTurn: boolean; sel: Sel | null; val: TileValue | null; setVal: (v: TileValue | null) => void; onCancel: () => void; }) { if (v.phase === 'finished') { return (
게임이 끝났어요 {v.final?.summary} 모든 타일을 공개했어요.
); } if (v.phase === 'chooseStart') return ; if (!myTurn) { const who = nick(players, v.current); const doing: Record = { chooseStart: '', draw: '타일을 가져오는 중이에요', guess: '추리하는 중이에요', afterCorrect: '맞혔어요! 계속할지 고르는 중이에요', placeJoker: '타일을 놓는 중이에요', // never shown: the server hides this phase from the others revealOwn: '틀려서 자기 타일을 공개하는 중이에요', finished: '', }; return (
{who}님이 {doing[v.phase]} {me && v.seats.includes(me) && !v.alive[me] && 나는 탈락했어요. 끝까지 구경할 수 있어요.} 공개된 숫자와 타일 위치, 추리 기록을 보고 상대의 숫자를 짐작해 보세요.
); } switch (v.phase) { case 'draw': return (
더미에서 타일을 하나 가져와 주세요. {v.options.chooseColors ? '검정과 흰색 중 원하는 색 더미를 누르세요. ' : ''}가져온 타일의 숫자는 나만 봐요.
); case 'guess': return sel ? : (
맞힐 상대 타일을 눌러 주세요. 파란 테두리가 있는 숨은 타일만 고를 수 있어요. 틀리면 {v.pending ? '가져온 타일이 공개돼요' : v.options.emptyPoolPenalty === 'reveal-own' ? '내 타일 하나를 공개해야 해요' : '차례가 넘어가요'}.
); case 'afterCorrect': return (
맞혔어요!
{v.pending ? '멈추면 가져온 타일이 숨겨진 채로 들어가요. 계속하다 틀리면 가져온 타일이 공개돼요.' : '멈추면 차례가 끝나요. 계속하다 틀리면 벌칙이 있을 수 있어요.'}
); case 'placeJoker': return (
조커를 넣을 자리를 골라 주세요. 내 줄의 "여기" 버튼 중 하나를 누르세요. 조커는 어느 틈에나 넣을 수 있고, 한 번 놓으면 옮길 수 없어요.
); case 'revealOwn': return (
틀렸어요. 공개할 내 타일을 하나 골라 주세요. 더미가 비어서 가져온 타일 대신 내 숨은 타일 하나를 공개해요. 내 줄에서 파란 테두리 타일을 누르세요.
); default: return null; } } function NumberPad({ view: v, players, act, pending, sel, val, setVal, onCancel, }: { view: DavinciView; players: Record; act: (a: unknown) => void; pending: boolean; sel: Sel; val: TileValue | null; setVal: (v: TileValue | null) => void; onCancel: () => void; }) { const tile = v.rows[sel.target]?.[sel.index]; const padRef = useRef(null); useEffect(() => { padRef.current?.querySelector('button')?.focus({ preventScroll: true }); }, [sel.target, sel.index]); if (!tile) return null; const seen = visibleCombos(v); const cands = tile.candidates ? new Set(tile.candidates.map(String)) : null; const values: TileValue[] = [...NUMBERS, ...(v.options.jokers ? ['joker' as const] : [])]; const impossible = (x: TileValue) => seen.has(`${tile.color}:${x}`) || tile.wrong.includes(x) || (!!cands && !cands.has(String(x))); const warn = val === null ? null : seen.has(`${tile.color}:${val}`) ? `${COLOR_SHORT[tile.color]} ${valueKo(val)}은(는) 이미 보이는 곳에 있어요.` : tile.wrong.includes(val) ? '이 타일에 이미 틀린 숫자예요.' : cands && !cands.has(String(val)) ? '공개된 정보로 보면 어려운 숫자예요.' : null; return (
{ if (e.key === 'Escape') onCancel(); }} > {nick(players, sel.target)}님 {sel.index + 1}번째 타일({COLOR_SHORT[tile.color]})은 몇일까요? {tile.wrong.length > 0 && 이미 틀린 추리: {tile.wrong.map(valueKo).join(', ')}}
{values.map((x) => ( ))}
{warn ? `${warn} 그래도 말할 수 있어요.` : ''}
); } function StartChooser({ view: v, me, act, pending }: { view: DavinciView; me: string | null; act: (a: unknown) => void; pending: boolean }) { const n = v.startCount; const lim = v.pickLimits ?? { black: n, white: n }; const fallbackBlack = Math.min(Math.ceil(n / 2), lim.black); const [black, setBlack] = useState(fallbackBlack); const done = v.picked ? Object.values(v.picked).filter(Boolean).length : 0; const total = v.picked ? v.seats.filter((p) => v.alive[p]).length : 0; if (!me || !v.seats.includes(me) || !v.alive[me]) { return (
모두 시작 타일 색을 고르는 중이에요 ({done}/{total})
); } if (v.myPick) { return (
검정 {v.myPick.black}개 · 흰색 {v.myPick.white}개를 골랐어요. 다른 사람을 기다리는 중이에요 ({done}/{total}). 다 고르면 숫자가 정해져 내 줄에 놓여요.
); } const okPick = (b: number) => b <= lim.black && n - b <= lim.white; const chosen = okPick(black) ? black : null; return (
시작 타일 {n}개의 색을 골라 주세요. 숫자는 고른 색 안에서 무작위로 정해져요. 15초 안에 고르지 않으면 반반으로 정해져요.
{Array.from({ length: n + 1 }, (_, i) => n - i).map((b) => ( ))}
{(lim.black < n || lim.white < n) && ( 먼저 고른 사람 때문에 검정은 {lim.black}개, 흰색은 {lim.white}개까지 고를 수 있어요. )}
); } // ---------------------------------------------------------------- side function DavinciSide({ view: v, me, players, deadline }: BoardProps) { const running = v.phase !== 'finished'; const ranking = v.final?.ranking ?? null; return ( <>
{running ? (v.phase === 'chooseStart' ? '시작 타일 고르기' : `${nick(players, v.current)}님 차례`) : '게임 끝'} {running && }
{optionsSummary(v.options)}
    {v.seats.map((p) => { const st = v.stats[p] ?? { guesses: 0, correct: 0 }; const out = v.eliminationOrder.indexOf(p); return (
  1. {nick(players, p)} {running && v.phase !== 'chooseStart' && v.current === p ? ' · 차례' : ''} {v.final?.winner === p ? ' · 1위' : out >= 0 ? ` · ${v.left[p] ? '나감' : '탈락'} ${v.seats.length - out}위` : ''} 숨김 {hiddenLeft(v.rows[p] ?? [])} · 맞힘 {st.correct}/{st.guesses}
  2. ); })}
{ranking && (
최종 순위 {ranking.map((g, i) => ( {i + 1}위 {g.map((id) => `${nick(players, id)} (맞힘 ${v.stats[id]?.correct ?? 0} / 추리 ${v.stats[id]?.guesses ?? 0})`).join(', ')} ))}
)}
추리 기록 ({v.history.length}) {v.history.length === 0 ? (

아직 추리가 없어요.

) : (
    {[...v.history].reverse().map((g, i) => (
  1. {guessLine(g, players)}
  2. ))}
)}
정렬 규칙
); } function SortPicture({ tieOrder }: { tieOrder: DavinciOptions['tieOrder'] }) { const tiles: [TColor, number][] = tieOrder === 'black-left' ? [['black', 2], ['black', 5], ['white', 5], ['white', 9]] : [['black', 2], ['white', 5], ['black', 5], ['white', 9]]; return (
`${COLOR_SHORT[c]} ${n}`).join(', ')}`}> {tiles.map(([c, n], i) => ( ))}
작은 수가 왼쪽이에요. 같은 숫자면 {tieOrder === 'black-left' ? '검정' : '흰색'}이 왼쪽이에요. 새 타일은 서버가 알맞은 자리에 끼워 줘요.
); } // ---------------------------------------------------------------- status function isMyTurn(v: DavinciView, me: string | null): boolean { if (!me || !v.seats.includes(me) || v.phase === 'finished' || !v.alive[me]) return false; if (v.phase === 'chooseStart') return !!v.picked && !v.picked[me]; return v.current === me; } function statusText(v: DavinciView, me: string | null, players: Record): string { if (v.phase === 'finished') return v.final?.summary ?? '게임이 끝났어요'; if (v.phase === 'chooseStart') return isMyTurn(v, me) ? '내 차례예요. 시작 타일 색을 골라 주세요' : '다른 사람이 시작 타일 색을 고르는 중이에요'; if (isMyTurn(v, me)) { switch (v.phase) { case 'draw': return '내 차례예요. 더미에서 타일을 가져와 주세요'; case 'guess': return '내 차례예요. 상대 타일을 골라 숫자를 맞혀 보세요'; case 'afterCorrect': return '내 차례예요. 맞혔어요! 한 번 더 할지 멈출지 골라 주세요'; case 'placeJoker': return '내 차례예요. 조커를 넣을 자리를 골라 주세요'; case 'revealOwn': return '내 차례예요. 공개할 내 타일을 골라 주세요'; } } const out = !!me && v.seats.includes(me) && !v.alive[me] ? '탈락했어요 · ' : ''; return `${out}${nick(players, v.current)}님 차례예요`; } // ---------------------------------------------------------------- options function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
{options.map(([k, l]) => ( ))}
); } function Field({ label, children }: { label: string; children: React.ReactNode }) { return (
{label} {children}
); } function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); return (
set({ jokers })} /> set({ startTiles })} /> set({ turnSeconds: k === 'none' ? null : (Number(k) as 20 | 30 | 45 | 60) })} /> set({ deductionHelper })} /> {more && ( <> set({ tieOrder })} /> set({ chooseColors })} /> set({ emptyPoolPenalty })} /> )}
); } function optionsSummary(o: DavinciOptions): string { return [ o.jokers ? '조커 사용' : '조커 없음', o.startTiles === 'auto' ? '시작 타일 자동' : `시작 타일 ${o.startTiles}개`, o.chooseColors ? '색 골라 가져오기' : '무작위로 가져오기', o.turnSeconds === null ? '시간 무제한' : `추리 ${o.turnSeconds}초`, ...(o.tieOrder === 'white-left' ? ['같은 숫자는 흰색 먼저'] : []), ...(o.deductionHelper ? ['후보 표시'] : []), ].join(' · '); } function Rules({ options }: { options?: DavinciOptions }) { const o = options; return (

검은색과 흰색 숫자 타일(0~11)을 작은 수부터 큰 수 순서로 세워 두고, 상대 타일의 숫자를 추리해 맞히는 게임이에요. 2~4명이 할 수 있어요. 숨은 타일이 모두 드러나면 탈락하고, 마지막까지 숨은 타일이 남은 사람이 이겨요.

준비: 각자 시작 타일 {o && o.startTiles !== 'auto' ? `${o.startTiles}개` : '(2·3명은 4개, 4명은 3개)'}를 받아요. {o?.chooseColors === false ? ' 색은 무작위로 정해져요.' : ' 검정과 흰색을 몇 개씩 받을지 직접 골라요.'} 타일 뒷면이 그 타일의 색이라서, 숨은 타일도 색은 모두에게 보이고 숫자만 숨겨져요.

정렬: 내 줄은 왼쪽에서 오른쪽으로 숫자가 커져요. 같은 숫자면 {o?.tieOrder === 'white-left' ? '흰색' : '검정'}이 왼쪽이에요. 새 타일은 알맞은 자리에 저절로 끼워지고, 이미 놓인 타일의 순서는 바뀌지 않아요.

내 차례: ① 더미에서 타일을 하나 가져와요(숫자는 나만 봐요). ② 상대의 숨은 타일 하나를 눌러 숫자를 말해요.

  • 맞히면 그 타일이 공개돼요. "한 번 더 맞히기"로 계속하거나 "여기서 멈추기"로 끝낼 수 있어요. 멈추면 가져온 타일이 숨겨진 채로 내 줄에 들어가요.
  • 틀리면 가져온 타일이 공개된 채로 내 줄에 들어가고 차례가 끝나요.

더미가 비면 가져오지 않고 바로 추리해요. 이때 틀리면{' '} {o?.emptyPoolPenalty === 'none' ? '벌칙 없이 차례만 넘어가요.' : '내 숨은 타일 하나를 골라 공개해야 해요. 마지막 숨은 타일을 공개하면 탈락해요.'}

{o?.jokers && (

조커: 숫자 대신 "−"가 그려진 타일이에요(검정·흰색 각 1개). 시작 타일에는 들어가지 않아요. 조커를 가져오면 내 줄의 원하는 틈에 직접 넣고, 한 번 놓으면 옮길 수 없어요. 추리할 때 "조커"라고 말할 수도 있어요.

)}

이미 공개된 같은 색·같은 숫자를 말하는 것처럼 말이 안 되는 추리도 할 수는 있어요(화면에서 알려 줘요). 오른쪽 추리 기록에서 누가 어떤 숫자를 말했는지 다시 볼 수 있어요.

{o?.turnSeconds === null ? '시간 제한이 없어서 천천히 생각해도 돼요. 연결이 끊긴 채로 오래 지나면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요.' : '시간 안에 추리하지 않으면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.'}{' '} 결과 화면에는 각자 맞힌 횟수와 추리 횟수가 나와요.

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