405 lines
19 KiB
TypeScript
405 lines
19 KiB
TypeScript
/**
|
|
* 게임 화면 (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 (
|
|
<span className="mini-stars" role="img" aria-label={`난이도 ${n}단계`}>
|
|
<svg viewBox="0 0 24 24" aria-hidden>
|
|
<path fill={color} d="M12 2l3 6.9 7.5.7-5.7 5 1.7 7.4L12 18.3 5.5 22l1.7-7.4-5.7-5 7.5-.7z" />
|
|
</svg>
|
|
{n}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
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<ChatHandle>(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 <ResultScreen room={room} game={game} />;
|
|
|
|
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 (
|
|
<button type="button" className={`btn btn-sm gbtn ${on ? 'on' : ''}`} aria-pressed={on} disabled={kind === 'replay' && need === null} onClick={() => vote(kind)} title={off ? `${label}가 꺼져 있어요` : undefined}>
|
|
{icon} {label}
|
|
{need !== null && (
|
|
<span className="mono">
|
|
{' '}
|
|
{n}/{need}
|
|
</span>
|
|
)}
|
|
<span className="kbd">{key}</span>
|
|
</button>
|
|
);
|
|
};
|
|
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 (
|
|
<main className="game">
|
|
<div className="gbar" role="toolbar" aria-label="게임 조작">
|
|
<div className="q">
|
|
문제 {game.n} <span>/ {game.total}</span>
|
|
</div>
|
|
<span className="badge dark">
|
|
{game.mode === 'lyrics'
|
|
? `📜 가사보고 맞추기 · ${c.lyricsSec ? `${c.lyricsSec}초` : '무제한'}`
|
|
: `${game.mode === 'artist' ? '🎤 가수노래' : '🎧 듣고맞추기'} · ${listenLabel(c.listenSec)} · ${c.startAt === 'highlight' ? '하이라이트부터' : '처음부터'}`}
|
|
</span>
|
|
<span className="badge dark">정답: {c.answer === 'title' ? '제목만' : c.answer === 'artist' ? '가수만' : '제목+가수'}</span>
|
|
<span className="badge dark">{c.quizId ? `📋 ${c.quizName}` : `★${c.level}`}</span>
|
|
<div className="grow" />
|
|
{voteBtn('hint', '💡', '힌트', 'Ctrl+I')}
|
|
{reveal ? voteBtn('next', '⏭', '다음 문제', 'Ctrl+K') : voteBtn('skip', '⏭', '스킵', 'Ctrl+K')}
|
|
{listening && voteBtn('replay', '🔁', '다시듣기', 'Ctrl+R')}
|
|
{listening && (
|
|
<label className="vol" title="볼륨">
|
|
🔊
|
|
<input type="range" min={0} max={100} value={p.volume} onChange={(e) => player.setVolume(Number(e.target.value))} aria-label="볼륨" />
|
|
</label>
|
|
)}
|
|
{isHost && (
|
|
<>
|
|
<button type="button" className="btn btn-sm gbtn" onClick={() => send({ t: 'game', action: game.paused?.reason === 'host' ? 'resume' : 'pause' })}>
|
|
{game.paused?.reason === 'host' ? '▶ 계속' : '⏸ 일시정지'}
|
|
</button>
|
|
<button type="button" className="btn btn-sm gbtn" onClick={() => setConfirmEnd(true)}>
|
|
⏹ 끝내기
|
|
</button>
|
|
</>
|
|
)}
|
|
</div>
|
|
<div className="ggrid">
|
|
<aside className="side scoreboard" aria-label="점수판">
|
|
<h2>점수판 · {game.scores.length}명</h2>
|
|
<ol>
|
|
{game.scores.map((s, i) => {
|
|
// ties share a rank (same score and same average time)
|
|
const rank = 1 + game.scores.findIndex((o) => o.score === s.score && o.avgMs === s.avgMs);
|
|
return (
|
|
<li key={s.id} className={`sb ${s.id === me.id ? 'me' : ''} ${i === 0 && s.score > 0 ? 'first' : ''} ${s.online ? '' : 'off'}`}>
|
|
<span className="rk">{rank}</span>
|
|
<Avatar user={{ id: s.id, nickname: s.nickname, avatar: room.players.find((x) => x.id === s.id)?.avatar ?? null }} size={26} />
|
|
<span className="nm">
|
|
{s.nickname}
|
|
{s.id === me.id && ' (나)'}
|
|
{game.votes.skip.includes(s.id) && <span title="스킵"> ⏭</span>}
|
|
{s.id === room.hostId && <span title="방장"> 👑</span>}
|
|
</span>
|
|
<span className="sc mono">{s.score}</span>
|
|
</li>
|
|
);
|
|
})}
|
|
</ol>
|
|
</aside>
|
|
<div className="gcenter">
|
|
<section className={`stage ${reveal ? 'revealed' : ''}`} aria-live="polite">
|
|
{reveal ? (
|
|
<RevealCard item={reveal} left={Math.max(0, Math.ceil(((game.revealUntil ?? now) - now) / 1000))} last={game.n >= game.total} />
|
|
) : (
|
|
<>
|
|
{listening ? <div className={`lp ${p.playing && !game.paused ? 'spin' : ''}`} aria-hidden /> : null}
|
|
<div className="sinfo">
|
|
<div className="mode">
|
|
{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}번째 가사`}
|
|
</div>
|
|
{game.mode === 'artist' && room.artists.length > 0 && <div className="small muted">선택한 가수: {room.artists.map((a) => a.name).join(', ')}</div>}
|
|
{countdown ? <div className="countdown mono">{countdown}</div> : <div className="big">{question}</div>}
|
|
{game.lyrics && (
|
|
<div className="lyrics-card">
|
|
{game.lyrics.map((l, i) => (
|
|
<div key={i}>{l}</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
{listening && clipLen !== null && (
|
|
<>
|
|
<div className="bar" aria-hidden>
|
|
<i style={{ width: `${Math.min(100, (clipPos / Math.max(0.1, clipLen)) * 100)}%` }} />
|
|
</div>
|
|
<div className="times small">
|
|
<span>{fmt(clipPos)}</span>
|
|
<span>{fmt(clipLen)}</span>
|
|
</div>
|
|
</>
|
|
)}
|
|
{game.clock.limitMs !== null && game.phase === 'play' && (
|
|
<div className="limit small muted">
|
|
남은 시간 <b className="mono">{Math.max(0, Math.ceil((game.clock.limitMs - elapsed) / 1000))}초</b>
|
|
</div>
|
|
)}
|
|
<div className="row" style={{ marginTop: 8 }}>
|
|
{game.hint ? (
|
|
<span className="hint">
|
|
{game.hint} <small>초성 힌트</small>
|
|
</span>
|
|
) : game.hintAtSec !== null && game.phase === 'play' ? (
|
|
<span className="small muted">힌트는 {Math.max(0, Math.ceil(game.hintAtSec - elapsed / 1000))}초 뒤에 공개돼요</span>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
</>
|
|
)}
|
|
{!inQuestion && game.phase !== 'reveal' && (
|
|
<div className="stage-note">{game.excluded.includes(me.id) ? '음원을 불러오지 못해 이번 문제는 빠졌어요. 다음 문제부터 다시 같이 해요.' : '다음 문제부터 같이 해요. 지금은 채팅만 할 수 있어요.'}</div>
|
|
)}
|
|
{late.length > 0 && (
|
|
<div className="late">
|
|
{late.map((w) => (
|
|
<button key={w.id} type="button" className="btn btn-sm" onClick={() => send({ t: 'exclude', userId: w.id })}>
|
|
{name(w.id)}님 빼고 이번 문제 진행
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</section>
|
|
<ChatPanel
|
|
ref={chatRef}
|
|
big
|
|
lines={chat}
|
|
pending={pending}
|
|
meId={me.id}
|
|
myName={me.nickname}
|
|
onSend={(t) => socket.chat(t)}
|
|
onTyping={(on) => send({ t: 'typing', on })}
|
|
typing={typing.filter((id) => id !== me.id).map(name)}
|
|
/>
|
|
</div>
|
|
<aside className="side hist" aria-label="지난 문제">
|
|
<h2>지난 문제</h2>
|
|
{game.history.length === 0 && <p className="small muted">아직 없어요</p>}
|
|
{[...game.history].reverse().map((h) => (
|
|
<div key={h.n} className="h">
|
|
<span className="n">{h.n}</span>
|
|
<span className="t">{h.title}</span> - {h.artist}
|
|
<div className="m">
|
|
<Stars n={h.level} />
|
|
{h.winner ? `${h.winner} · ${secs(h.ms)}` : h.how === 'skip' ? '스킵됨 (정답자 없음)' : '시간 초과 (정답자 없음)'}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</aside>
|
|
</div>
|
|
{listening && (!p.unlocked || p.needsGesture) && inQuestion && (
|
|
<div className="unlock-overlay">
|
|
<button type="button" className="btn btn-mustard btn-lg" onClick={() => player.unlock()} autoFocus>
|
|
🔊 {p.needsGesture ? '눌러서 소리 켜기' : '참가 (소리 켜기)'}
|
|
</button>
|
|
<p className="small">브라우저가 소리를 막지 않도록 한 번 눌러 주세요.</p>
|
|
</div>
|
|
)}
|
|
{confirmEnd && <ConfirmSheet title="게임을 끝낼까요?" body="지금까지 점수로 결과를 보여 줘요." confirm="끝내기" danger onConfirm={() => send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
function RevealCard({ item, left, last }: { item: GameHistoryItem; left: number; last: boolean }) {
|
|
return (
|
|
<div className="reveal">
|
|
{item.videoId ? <img className="art" src={`https://i.ytimg.com/vi/${item.videoId}/hqdefault.jpg`} alt="" /> : <div className="art lp" aria-hidden />}
|
|
<div className="sinfo">
|
|
<div className="mode">{item.winner ? `🎉 ${item.winner}님 정답! · ${secs(item.ms)}` : item.how === 'skip' ? '⏭ 스킵 · 정답자 없음' : '⌛ 시간 초과 · 정답자 없음'}</div>
|
|
<div className="big">
|
|
{item.title} <span className="muted">- {item.artist}</span>
|
|
</div>
|
|
<div className="small muted">
|
|
{[item.year, ...item.genres].filter(Boolean).join(' · ')} <Stars n={item.level} />
|
|
</div>
|
|
<div className="small muted next-in">
|
|
{last ? '결과까지' : '다음 문제까지'} <b className="mono">{left}초</b>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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<string, GameHistoryItem>();
|
|
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 (
|
|
<main className="page result stack">
|
|
<div className="row">
|
|
<h1>🏁 게임 결과</h1>
|
|
<span className="muted">{game.history.length}문제</span>
|
|
</div>
|
|
<section className="card ink">
|
|
<table className="data-table rank">
|
|
<thead>
|
|
<tr>
|
|
<th>순위</th>
|
|
<th>이름</th>
|
|
<th>점수</th>
|
|
<th>맞힌 곡</th>
|
|
<th>가장 빨리 맞힌 곡</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{game.scores.map((s, i) => {
|
|
const f = fastest.get(s.id);
|
|
return (
|
|
<tr key={s.id} className={s.id === me.id ? 'sel' : ''}>
|
|
<td className="mono">{i === 0 && s.score > 0 ? '🥇' : i === 1 && s.score > 0 ? '🥈' : i === 2 && s.score > 0 ? '🥉' : i + 1}</td>
|
|
<td>{s.nickname}</td>
|
|
<td className="mono">{s.score}</td>
|
|
<td className="mono">{s.correct}</td>
|
|
<td>{f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</section>
|
|
<div className="row">
|
|
{isHost ? (
|
|
<>
|
|
<button className="btn btn-mustard btn-lg" disabled={game.left === 0} title={game.left === 0 ? '조건에 맞는 곡을 모두 풀었어요' : undefined} onClick={() => send({ t: 'game', action: 'continue' })}>
|
|
▶ 이어풀기 {game.left > 0 && <span className="small">(남은 곡 {game.left})</span>}
|
|
</button>
|
|
<button className="btn btn-lg" onClick={() => send({ t: 'game', action: 'again' })}>
|
|
↺ 다시 하기
|
|
</button>
|
|
<button
|
|
className="btn btn-lg"
|
|
onClick={() => (me.kind === 'member' ? setSave(true) : toast('진행 저장은 디스코드로 로그인하면 쓸 수 있어요.', 'error'))}
|
|
>
|
|
💾 진행 저장
|
|
</button>
|
|
</>
|
|
) : (
|
|
<span className="muted">방장이 이어풀기나 다시 하기를 고르면 바로 시작돼요.</span>
|
|
)}
|
|
<div className="grow" />
|
|
</div>
|
|
<section className="card">
|
|
<h2 style={{ marginBottom: 10 }}>이번 게임 곡 목록</h2>
|
|
<ol className="songlist">
|
|
{game.history.map((h) => (
|
|
<li key={h.n}>
|
|
<span className="mono muted">{h.n}.</span> <b>{h.title}</b> - {h.artist} <Stars n={h.level} />{' '}
|
|
{h.videoId && (
|
|
<a href={`https://youtu.be/${h.videoId}`} target="_blank" rel="noreferrer">
|
|
https://youtu.be/{h.videoId}
|
|
</a>
|
|
)}{' '}
|
|
<span className="small muted">{h.winner ? `${h.winner} ${secs(h.ms)}` : h.how === 'skip' ? '스킵' : '시간 초과'}</span>
|
|
</li>
|
|
))}
|
|
</ol>
|
|
</section>
|
|
{save && (
|
|
<Sheet label="진행 저장" onClose={() => setSave(false)}>
|
|
<h2>진행 저장</h2>
|
|
<p className="muted small">방 설정, 지금까지 나온 곡, 참가자 점수를 내 계정에 저장해요. 불러오면 나온 곡은 빼고 이어서 할 수 있어요.</p>
|
|
<form
|
|
className="stack"
|
|
onSubmit={(e) => {
|
|
e.preventDefault();
|
|
if (!name.trim()) return;
|
|
send({ t: 'save', name: name.trim() });
|
|
setSave(false);
|
|
}}
|
|
>
|
|
<input className="input" autoFocus maxLength={40} placeholder="퀴즈 이름 (예: 금요일 발라드)" value={name} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
|
|
<button className="btn btn-primary btn-block" disabled={!name.trim()}>
|
|
저장
|
|
</button>
|
|
</form>
|
|
</Sheet>
|
|
)}
|
|
</main>
|
|
);
|
|
}
|