/** * 게임 화면 (docs/03 게임 화면, docs/05, docs/06): black top bar with votes, stage (LP / lyrics card / hint), big chat, * scoreboard on the left, past questions on the right, results at the end. */ import { useEffect, useRef, useState } from 'react'; import { listenLabel, type GameHistoryItem, type GameView, type RoomView } from '@mq/shared/lite'; import { serverNow, socket, useRoom } from '../net/socket'; import { player, usePlayer } from '../net/player'; import { useSession } from '../store/session'; import { toast } from '../store/toast'; import { Avatar, ConfirmSheet, Sheet } from '../components/ui'; import { ChatPanel, type ChatHandle } from '../components/ChatPanel'; const LATE_MS = 30_000; /** Re-render every `ms` (timers, countdown). */ function useNow(ms: number): number { const [, set] = useState(0); useEffect(() => { const iv = setInterval(() => set((x) => x + 1), ms); return () => clearInterval(iv); }, [ms]); return serverNow(); } const fmt = (sec: number) => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, '0')}`; const secs = (ms: number | null) => (ms === null ? '' : `${(ms / 1000).toFixed(1)}초`); function Stars({ n }: { n: number | null }) { if (!n) return null; const color = n <= 3 ? 'var(--star-1)' : n <= 6 ? 'var(--star-2)' : n <= 8 ? 'var(--star-3)' : 'var(--star-4)'; return ( {n} ); } export function GameScreen({ room, game }: { room: RoomView; game: GameView }) { const me = useSession((s) => s.me)!; const { chat, pending, typing } = useRoom(); const p = usePlayer(); const now = useNow(200); const chatRef = useRef(null); const [confirmEnd, setConfirmEnd] = useState(false); const isHost = room.hostId === me.id; const c = room.config; const send = (m: unknown) => socket.send(m); const vote = (kind: 'skip' | 'hint' | 'replay' | 'next') => send({ t: 'vote', kind }); // Ctrl+K during the reveal = 다음 문제 (the shortcut handler is set up once, so it reads the phase from a ref). const phaseRef = useRef(game.phase); phaseRef.current = game.phase; const name = (id: string) => room.players.find((x) => x.id === id)?.nickname ?? game.scores.find((x) => x.id === id)?.nickname ?? '?'; const inQuestion = game.participants.includes(me.id) && !game.excluded.includes(me.id); const listening = game.mode !== 'lyrics'; useEffect(() => { player.warm(); }, []); // Shortcuts (docs/06): Ctrl+I 힌트, Ctrl+K 스킵, Ctrl+R 다시듣기 — only on the game screen; any key focuses the chat. useEffect(() => { const onKey = (e: KeyboardEvent) => { if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) { const k = e.key.toLowerCase(); const kind = k === 'i' ? 'hint' : k === 'k' ? (phaseRef.current === 'reveal' ? 'next' : 'skip') : k === 'r' ? 'replay' : null; if (kind) { e.preventDefault(); vote(kind); } return; } const t = e.target as HTMLElement | null; if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return; if (document.querySelector('.sheet')) return; if (e.key.length === 1 || e.key === 'Enter') chatRef.current?.focus(); }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, []); // eslint-disable-line react-hooks/exhaustive-deps if (game.phase === 'result') return ; const elapsed = game.clock.elapsedMs + (game.clock.runningSince !== null ? Math.max(0, now - game.clock.runningSince) : 0); const countdown = game.startAt !== null && now < game.startAt && !game.paused ? Math.ceil((game.startAt - now) / 1000) : 0; const reveal = game.phase === 'reveal' ? game.history.at(-1) : undefined; const voteBtn = (kind: 'skip' | 'hint' | 'replay' | 'next', icon: string, label: string, key: string) => { const need = game.need[kind]; const n = game.votes[kind].length; const on = game.votes[kind].includes(me.id); const off = need === null && (kind !== 'hint' || c.hint === 'none'); return ( ); }; const question = c.answer === 'title' ? '이 노래 제목은?' : c.answer === 'artist' ? '이 노래 부른 가수는?' : '제목과 가수를 한 줄에!'; const clipLen = game.clipSec; const clipPos = p.clip ? Math.max(0, p.pos - p.clip.start) : 0; const late = isHost ? game.waiting.filter((w) => now - w.since >= LATE_MS) : []; return (
문제 {game.n} / {game.total}
{game.mode === 'lyrics' ? `📜 가사보고 맞추기 · ${c.lyricsSec ? `${c.lyricsSec}초` : '무제한'}` : `${game.mode === 'artist' ? '🎤 가수노래' : '🎧 듣고맞추기'} · ${listenLabel(c.listenSec)} · ${c.startAt === 'highlight' ? '하이라이트부터' : '처음부터'}`} 정답: {c.answer === 'title' ? '제목만' : c.answer === 'artist' ? '가수만' : '제목+가수'} {c.quizId ? `📋 ${c.quizName}` : `★${c.level}`}
{voteBtn('hint', '💡', '힌트', 'Ctrl+I')} {reveal ? voteBtn('next', '⏭', '다음 문제', 'Ctrl+K') : voteBtn('skip', '⏭', '스킵', 'Ctrl+K')} {listening && voteBtn('replay', '🔁', '다시듣기', 'Ctrl+R')} {listening && ( )} {isHost && ( <> )}
{reveal ? ( = game.total} /> ) : ( <> {listening ?
: null}
{game.paused ? game.paused.reason === 'host' ? '⏸ 방장이 잠시 멈췄어요' : `⏸ 잠시 멈춤 — ${game.paused.who.map(name).join(', ') || '누군가'}님 ${game.paused.reason === 'blocked' ? '소리 켜는 중' : '버퍼링 중'}` : game.phase === 'prepare' ? game.waiting.length ? `${game.waiting.map((w) => name(w.id)).slice(0, 3).join(', ')}${game.waiting.length > 3 ? ` 외 ${game.waiting.length - 3}명` : ''}님 음원 준비 중…` : '음원 준비 중…' : countdown ? `${game.n}번째 문제` : listening ? game.clipOver ? '재생이 끝났어요 · 계속 맞혀 보세요' : `${game.n}번째 곡 재생 중 · 앨범아트와 제목은 정답 뒤에 공개` : `${game.n}번째 가사`}
{game.mode === 'artist' && room.artists.length > 0 &&
선택한 가수: {room.artists.map((a) => a.name).join(', ')}
} {countdown ?
{countdown}
:
{question}
} {game.lyrics && (
{game.lyrics.map((l, i) => (
{l}
))}
)} {listening && clipLen !== null && ( <>
{fmt(clipPos)} {fmt(clipLen)}
)} {game.clock.limitMs !== null && game.phase === 'play' && (
남은 시간 {Math.max(0, Math.ceil((game.clock.limitMs - elapsed) / 1000))}초
)}
{game.hint ? ( {game.hint} 초성 힌트 ) : game.hintAtSec !== null && game.phase === 'play' ? ( 힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요 ) : null}
)} {!inQuestion && game.phase !== 'reveal' && (
{game.excluded.includes(me.id) ? '음원을 불러오지 못해 이번 문제는 빠졌어요. 다음 문제부터 다시 같이 해요.' : '다음 문제부터 같이 해요. 지금은 채팅만 할 수 있어요.'}
)} {late.length > 0 && (
{late.map((w) => ( ))}
)}
socket.chat(t)} onTyping={(on) => send({ t: 'typing', on })} typing={typing.filter((id) => id !== me.id).map(name)} />
{listening && (!p.unlocked || p.needsGesture) && inQuestion && (

브라우저가 소리를 막지 않도록 한 번 눌러 주세요.

)} {confirmEnd && send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
); } function RevealCard({ item, left, last }: { item: GameHistoryItem; left: number; last: boolean }) { return (
{item.videoId ? :
}
{item.winner ? `🎉 ${item.winner}님 정답! · ${secs(item.ms)}` : item.how === 'skip' ? '⏭ 스킵 · 정답자 없음' : '⌛ 시간 초과 · 정답자 없음'}
{item.title} - {item.artist}
{[item.year, ...item.genres].filter(Boolean).join(' · ')}
{last ? '결과까지' : '다음 문제까지'} {left}초
); } function ResultScreen({ room, game }: { room: RoomView; game: GameView }) { const me = useSession((s) => s.me)!; const isHost = room.hostId === me.id; const [save, setSave] = useState(false); const [name, setName] = useState(''); const send = (m: unknown) => socket.send(m); const fastest = new Map(); for (const h of game.history) if (h.winnerId && h.ms !== null && (!fastest.get(h.winnerId) || fastest.get(h.winnerId)!.ms! > h.ms)) fastest.set(h.winnerId, h); return (

🏁 게임 결과

{game.history.length}문제
{game.scores.map((s, i) => { const f = fastest.get(s.id); return ( ); })}
순위 이름 점수 맞힌 곡 가장 빨리 맞힌 곡
{i === 0 && s.score > 0 ? '🥇' : i === 1 && s.score > 0 ? '🥈' : i === 2 && s.score > 0 ? '🥉' : i + 1} {s.nickname} {s.score} {s.correct} {f ? `${f.title} · ${secs(f.ms)}` : '-'}
{isHost ? ( <> ) : ( 방장이 이어풀기나 다시 하기를 고르면 바로 시작돼요. )}

이번 게임 곡 목록

    {game.history.map((h) => (
  1. {h.n}. {h.title} - {h.artist} {' '} {h.videoId && ( https://youtu.be/{h.videoId} )}{' '} {h.winner ? `${h.winner} ${secs(h.ms)}` : h.how === 'skip' ? '스킵' : '시간 초과'}
  2. ))}
{save && ( setSave(false)}>

진행 저장

방 설정, 지금까지 나온 곡, 참가자 점수를 내 계정에 저장해요. 불러오면 나온 곡은 빼고 이어서 할 수 있어요.

{ e.preventDefault(); if (!name.trim()) return; send({ t: 'save', name: name.trim() }); setSave(false); }} > setName(e.target.value)} aria-label="퀴즈 이름" />
)}
); }