From 7266fc8d25b10c34dfe0b2f5fce4abc910c34a41 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 18 Oct 2026 22:11:14 +0900 Subject: [PATCH] =?UTF-8?q?5~7=EB=8B=A8=EA=B3=84=20=EA=B2=8C=EC=9E=84:=20?= =?UTF-8?q?=EC=88=A8=EA=B8=B4=20=EC=9C=A0=ED=8A=9C=EB=B8=8C=20=EB=8F=99?= =?UTF-8?q?=EA=B8=B0=ED=99=94=20=EC=9E=AC=EC=83=9D(=EC=A0=84=EC=9B=90=20?= =?UTF-8?q?=EC=A4=80=EB=B9=84=C2=B7=EB=B2=84=ED=8D=BC=EB=A7=81=EC=9D=B4?= =?UTF-8?q?=EB=A9=B4=20=EB=AA=A8=EB=91=90=20=EB=A9=88=EC=B6=A4=C2=B730?= =?UTF-8?q?=EC=B4=88=20=EB=8A=A6=EC=9D=80=20=EC=82=AC=EB=9E=8C=20=EC=A0=9C?= =?UTF-8?q?=EC=99=B8=C2=B7=EC=9E=AC=EC=83=9D=20=EC=98=A4=EB=A5=98=20?= =?UTF-8?q?=EA=B3=A1=20=EA=B5=90=EC=B2=B4),=20=EC=A0=95=EB=8B=B5=20?= =?UTF-8?q?=ED=8C=90=EC=A0=95=C2=B7=EC=A0=90=EC=88=98=C2=B7=EC=A0=95?= =?UTF-8?q?=EB=8B=B5=20=EB=B8=94=EB=A1=9D,=20=EC=9E=85=EB=A0=A5=20?= =?UTF-8?q?=EC=A4=91=C2=B7=EB=8B=A8=EC=B6=95=ED=82=A4,=20=ED=9E=8C?= =?UTF-8?q?=ED=8A=B8=C2=B7=EC=8A=A4=ED=82=B5=C2=B7=EB=8B=A4=EC=8B=9C?= =?UTF-8?q?=EB=93=A3=EA=B8=B0=20=ED=88=AC=ED=91=9C,=203=EB=AA=A8=EB=93=9C,?= =?UTF-8?q?=20=EA=B2=B0=EA=B3=BC=C2=B7=EC=9D=B4=EC=96=B4=ED=92=80=EA=B8=B0?= =?UTF-8?q?=C2=B7=EB=8B=A4=EC=8B=9C=20=ED=95=98=EA=B8=B0,=20=ED=80=B4?= =?UTF-8?q?=EC=A6=88=20=EC=A0=80=EC=9E=A5=C2=B7=EB=B6=88=EB=9F=AC=EC=98=A4?= =?UTF-8?q?=EA=B8=B0=20+=20=EB=A7=88=EC=A7=80=EB=A7=89=20=EC=82=AC?= =?UTF-8?q?=EB=9E=8C=EC=9D=B4=20=EB=82=98=EA=B0=80=EB=A9=B4=20=EB=B0=A9=20?= =?UTF-8?q?=EB=B0=94=EB=A1=9C=20=EB=8B=AB=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/admin/settings.ts | 2 + .../src/db/migrations/004_saved_quizzes.sql | 13 + apps/server/src/game.test.ts | 467 +++++++++++++++ apps/server/src/game/engine.ts | 545 ++++++++++++++++++ apps/server/src/game/saved.ts | 57 ++ apps/server/src/http/app.ts | 13 + apps/server/src/rooms.test.ts | 12 + apps/server/src/rooms/manager.ts | 199 ++++++- apps/server/src/server.ts | 8 + apps/server/src/songs/quiz.ts | 165 ++++++ apps/server/src/ws/gateway.ts | 16 + apps/web/src/components/ChatPanel.tsx | 109 +++- apps/web/src/net/player.ts | 444 ++++++++++++++ apps/web/src/net/socket.ts | 49 +- apps/web/src/pages/GameScreen.tsx | 395 +++++++++++++ apps/web/src/pages/RoomPage.tsx | 128 +++- apps/web/src/pages/admin/AdminApp.tsx | 6 + apps/web/src/styles/global.css | 94 +++ docs/10-roadmap.md | 9 +- docs/12-decisions.md | 16 + e2e/game.e2e.ts | 380 ++++++++++++ package.json | 2 +- packages/shared/src/answer.test.ts | 100 ++++ packages/shared/src/answer.ts | 183 ++++++ packages/shared/src/index.ts | 1 + packages/shared/src/lite.ts | 2 +- packages/shared/src/protocol.ts | 92 +++ 27 files changed, 3461 insertions(+), 46 deletions(-) create mode 100644 apps/server/src/db/migrations/004_saved_quizzes.sql create mode 100644 apps/server/src/game.test.ts create mode 100644 apps/server/src/game/engine.ts create mode 100644 apps/server/src/game/saved.ts create mode 100644 apps/server/src/songs/quiz.ts create mode 100644 apps/web/src/net/player.ts create mode 100644 apps/web/src/pages/GameScreen.tsx create mode 100644 e2e/game.e2e.ts create mode 100644 packages/shared/src/answer.test.ts create mode 100644 packages/shared/src/answer.ts diff --git a/apps/server/src/admin/settings.ts b/apps/server/src/admin/settings.ts index 7c7179e..bf35686 100644 --- a/apps/server/src/admin/settings.ts +++ b/apps/server/src/admin/settings.ts @@ -14,6 +14,8 @@ export const SiteSettingsSchema = z.object({ chatFloodGuard: z.boolean().default(false), chatRatePerSec: z.number().int().min(1).max(50).default(6), chatBurst: z.number().int().min(1).max(100).default(12), + /** One question's time limit for short clips (docs/05 문제 진행: 기본 60초, 관리자 설정). */ + questionLimitSec: z.number().int().min(10).max(600).default(60), }); export type SiteSettings = z.infer; diff --git a/apps/server/src/db/migrations/004_saved_quizzes.sql b/apps/server/src/db/migrations/004_saved_quizzes.sql new file mode 100644 index 0000000..4789d71 --- /dev/null +++ b/apps/server/src/db/migrations/004_saved_quizzes.sql @@ -0,0 +1,13 @@ +-- 퀴즈 저장·불러오기 (docs/12 Q8): settings, songs played so far, scores per account. Discord accounts only, 20 per account. +CREATE TABLE saved_quizzes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + config_json TEXT NOT NULL, + played_json TEXT NOT NULL, -- song ids already asked + scores_json TEXT NOT NULL, -- [{id, nickname, score, correct, totalMs}] + questions INTEGER NOT NULL, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); +CREATE INDEX saved_quizzes_user ON saved_quizzes(user_id, updated_at); diff --git a/apps/server/src/game.test.ts b/apps/server/src/game.test.ts new file mode 100644 index 0000000..2d36c44 --- /dev/null +++ b/apps/server/src/game.test.ts @@ -0,0 +1,467 @@ +/** + * Game engine over real WebSockets (docs/05, docs/12 Q1·Q3·Q4·Q5·Q8) with short timings. + * Clients play the browser's part: they report audio ready / stall / clip end like the hidden YouTube player would. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import type { ChatLine, GameView, ServerMessage } from '@mq/shared'; +import { Catalog } from './collector/catalog'; +import { Client, api, boot, discordLogin, guest, sleep } from './test-utils'; + +type Msg = Extract; +const TIMING = { countdownMs: 60, revealMs: 120, resumeLeadMs: 40, clipGraceMs: 150, lateMs: 150, tickMs: 20 }; +const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `회원${code.slice(-2)}`, avatar: null }); + +let s: ReturnType; +afterEach(async () => s && (await s.stop())); + +function seed(n: number, opts: { artist?: (i: number) => string; lyrics?: boolean } = {}) { + const c = new Catalog(s.db); + const ids: number[] = []; + for (let i = 1; i <= n; i++) { + const [id] = c.upsert({ title: `노래${i}`, artists: [{ name: opts.artist?.(i) ?? `가수${i}` }], year: 2000 + i, genres: ['kpop'], source: 't', ref: `s${i}` }); + c.autoLevel(id!, 'all', 3); + s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`vid${i}`, id!); + if (opts.lyrics) s.db.query('INSERT INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, 0)').run(id!, `첫 줄 ${i}\n둘째 줄\n노래${i} 셋째 줄\n넷째 줄\n다섯째 줄\n후렴\n후렴`, 't'); + ids.push(id!); + } + return ids; +} + +const last = (cl: Client, t: T) => [...cl.messages].reverse().find((m) => m.t === t) as Msg | undefined; +/** Wait until the latest game view matches. */ +const gameWhere = (cl: Client, pred: (g: GameView) => boolean, timeout = 3000) => + new Promise((resolve, reject) => { + const t0 = Date.now(); + const tick = () => { + const g = last(cl, 'game')?.game; + if (g && pred(g)) return resolve(g); + if (Date.now() - t0 > timeout) return reject(new Error(`no matching game view; last ${JSON.stringify(g && { phase: g.phase, n: g.n, paused: g.paused, waiting: g.waiting })}`)); + setTimeout(tick, 5); + }; + tick(); + }); +const since = (cl: Client) => cl.messages.length; +const nextOf = (cl: Client, t: T, from: number, pred: (m: Msg) => boolean = () => true, timeout = 3000) => + new Promise>((resolve, reject) => { + const t0 = Date.now(); + const tick = () => { + const m = cl.messages.slice(from).find((x) => x.t === t && pred(x as Msg)) as Msg | undefined; + if (m) return resolve(m); + if (Date.now() - t0 > timeout) return reject(new Error(`no ${t} message; last ${JSON.stringify(cl.messages.slice(-2))}`)); + setTimeout(tick, 5); + }; + tick(); + }); + +/** Pending catalog for the next room(): seeding needs the server's DB, so it runs right after boot. */ +let pendingSeed: (() => void)[] = []; +function seedLater(fn: () => void) { + pendingSeed.push(fn); +} + +async function room(players: string[], config: Record = {}, timing: Record = {}) { + s = boot({ gameTiming: { ...TIMING, ...timing }, discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' }); + for (const f of pendingSeed) f(); + pendingSeed = []; + const users = []; + for (const name of players) users.push(await guest(s.base, name)); + const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: users[0]!.cookie, body: JSON.stringify({ config }) })).body.code; + const cls: Client[] = []; + for (const u of users) { + const cl = await new Client(s.base, u.cookie).connect(); + cl.send({ t: 'join', code }); + await cl.waitFor((m) => m.t === 'room'); + cls.push(cl); + } + return { users, cls, code }; +} + +/** Act as browsers: every client reports ready for each prepare it gets. */ +function autoReady(cls: Client[], skip: Set = new Set()) { + const seen = new Map(); + const iv = setInterval(() => { + for (const cl of cls) { + if (skip.has(cl)) continue; + const from = seen.get(cl) ?? 0; + for (const m of cl.messages.slice(from)) if (m.t === 'prepare') cl.send({ t: 'audio', n: m.n, ev: 'ready' }); + seen.set(cl, cl.messages.length); + } + }, 5); + return () => clearInterval(iv); +} + +const chatLines = (cl: Client) => cl.messages.filter((m) => m.t === 'chat' || m.t === 'answer').map((m) => (m as Msg<'chat'>).line as ChatLine); + +describe('game flow', () => { + test('nothing plays until everyone is ready; then one play time for all, answers count after the 3·2·1, first correct gets +1 with the answer block', async () => { + seedLater(() => seed(3)); + const { users, cls } = await room(['방장', '철수']); + const [a, b] = cls as [Client, Client]; + const fa = since(a); + a.send({ t: 'start' }); + const pa = await nextOf(a, 'prepare', fa); + const pb = await nextOf(b, 'prepare', fa > 0 ? 0 : 0); + expect(pa).toMatchObject({ n: 1, startSec: 0 }); + expect(pa.videoId).toMatch(/^vid\d$/); + expect(pb.videoId).toBe(pa.videoId); + // the room state never carries the video id + expect(JSON.stringify(last(a, 'game'))).not.toContain(pa.videoId); + a.send({ t: 'audio', n: 1, ev: 'ready' }); + await sleep(80); + expect(a.messages.slice(fa).some((m) => m.t === 'play')).toBe(false); // 철수 is not ready + expect((await gameWhere(a, (g) => g.waiting.length === 1)).waiting[0]!.id).toBe(users[1]!.id); + const fb = since(b); + b.send({ t: 'audio', n: 1, ev: 'ready' }); + const playA = await nextOf(a, 'play', fa); + const playB = await nextOf(b, 'play', fb); + expect(playA.startAt).toBe(playB.startAt); + expect(playA.atSec).toBe(0); + // answering during the 3·2·1 is just chat + const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(pa.videoId)!.title; + b.send({ t: 'chat', text: title, n: 'early' }); + await b.waitFor((m) => m.t === 'chat' && m.line.n === 'early'); + await sleep(Math.max(0, playA.startAt - Date.now()) + 10); + b.send({ t: 'chat', text: '모르겠다' }); + b.send({ t: 'chat', text: title, n: 'win' }); + a.send({ t: 'chat', text: title }); + const ans = (await a.waitFor((m) => m.t === 'answer')) as Msg<'answer'>; + expect(ans.line).toMatchObject({ userId: users[1]!.id, text: title, n: 'win', answer: { text: expect.stringContaining(`${title} - `) } }); + // nothing sits between the answer line and its block: it is one item, and the next line has a higher seq + const lines = chatLines(a); + const i = lines.findIndex((l) => l.answer); + expect(lines[i - 1]!.text).toBe('모르겠다'); + const g = await gameWhere(a, (x) => x.phase === 'reveal'); + expect(g.scores[0]).toMatchObject({ id: users[1]!.id, score: 1, correct: 1 }); + expect(g.history[0]).toMatchObject({ n: 1, title, winnerId: users[1]!.id, how: 'correct' }); + expect(g.history[0]!.ms).toBeGreaterThanOrEqual(0); + // reveal ends → question 2 is prepared + await nextOf(a, 'prepare', fa, (m) => m.n === 2); + }); + + test('a stall pauses everyone at the same position, timers stop, and play resumes for all from there', async () => { + seedLater(() => seed(2)); + const { cls } = await room(['방장', '철수'], { listenSec: 30 }); + const [a, b] = cls as [Client, Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + const p1 = await nextOf(a, 'play', 0); + await sleep(p1.startAt - Date.now() + 120); + const fa = since(a); + b.send({ t: 'audio', n: 1, ev: 'stall' }); + await nextOf(a, 'pause', fa); + const paused = (await nextOf(a, 'game', fa, (m) => !!m.game?.paused)).game!; + expect(paused.paused).toMatchObject({ reason: 'stall' }); + expect(paused.clock.runningSince).toBeNull(); + const frozen = paused.clock.elapsedMs; + const resume = await nextOf(a, 'play', fa); + expect(resume.atSec).toBeGreaterThan(0.08); + expect(resume.atSec).toBeLessThan(0.4); + const re = await nextOf(a, 'prepare', fa); + expect(re.startSec).toBe(resume.atSec); + const after = await gameWhere(a, (g) => !g.paused && g.clock.runningSince !== null); + expect(after.clock.elapsedMs).toBe(frozen); + stop(); + }); + + test('the clip ends by reports (or grace), the question goes on until the time limit; 끝까지 ends the question with the song', async () => { + seedLater(() => seed(2)); + const { cls } = await room(['방장', '철수'], { listenSec: 1 }); + const [a, b] = cls as [Client, Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + const p = await nextOf(a, 'play', 0); + expect(p.endSec).toBe(1); + await sleep(p.startAt - Date.now() + 30); + a.send({ t: 'audio', n: 1, ev: 'clipEnd' }); + b.send({ t: 'audio', n: 1, ev: 'clipEnd' }); + const g = await gameWhere(a, (x) => x.clipOver); + expect(g.phase).toBe('play'); // still answerable + stop(); + }); + + test('time limit ends a question with no winner; the clock does not count paused time', async () => { + seedLater(() => seed(2)); + const { cls } = await room(['혼자'], { listenSec: 5 }, { limitMs: 300 }); + const [ca] = cls as [Client]; + const stop = autoReady([ca]); + ca.send({ t: 'start' }); + const p = await nextOf(ca, 'play', 0); + await sleep(p.startAt - Date.now() + 100); + ca.send({ t: 'game', action: 'pause' }); + await gameWhere(ca, (g) => g.paused?.reason === 'host'); + await sleep(400); // longer than the limit, but paused + expect(last(ca, 'game')!.game!.phase).toBe('play'); + ca.send({ t: 'game', action: 'resume' }); + const g = await gameWhere(ca, (x) => x.phase === 'reveal'); + expect(g.history[0]).toMatchObject({ how: 'timeout', winnerId: null }); + expect(chatLines(ca).find((l) => l.answer)?.answer?.none).toBe(true); + stop(); + }); + + test('someone not ready blocks the start; after 30s the host may leave them out of this question only', async () => { + seedLater(() => seed(3)); + const { users, cls } = await room(['방장', '느림']); + const [a, b] = cls as [Client, Client]; + const stop = autoReady(cls, new Set([b])); + a.send({ t: 'start' }); + await gameWhere(a, (g) => g.waiting.some((w) => w.id === users[1]!.id)); + a.send({ t: 'exclude', userId: users[1]!.id }); + expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('30초'); + await sleep(170); + b.send({ t: 'exclude', userId: users[0]!.id }); + expect(((await b.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('방장만'); + const fa = since(a); + a.send({ t: 'exclude', userId: users[1]!.id }); + await nextOf(a, 'play', fa); + const g = await gameWhere(a, (x) => x.excluded.includes(users[1]!.id)); + expect(g.phase).toBe('play'); + // excluded players cannot answer this question + const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title; + await sleep(80); + b.send({ t: 'chat', text: title, n: 'x' }); + await a.waitFor((m) => m.t === 'chat' && m.line.n === 'x'); + expect(last(a, 'game')!.game!.phase).toBe('play'); + stop(); + }); + + test('a disconnected player is not waited for', async () => { + seedLater(() => seed(2)); + const { cls } = await room(['방장', '나감']); + const [a, b] = cls as [Client, Client]; + const stop = autoReady([a]); + a.send({ t: 'start' }); + await nextOf(b, 'prepare', 0); + b.close(); + await nextOf(a, 'play', 0); + stop(); + }); + + test('player error 150 swaps the song for everyone under the same number and marks it unplayable', async () => { + seedLater(() => seed(3)); + const { cls } = await room(['방장', '철수']); + const [a, b] = cls as [Client, Client]; + a.send({ t: 'start' }); + const first = await nextOf(a, 'prepare', 0); + const fa = since(a); + b.send({ t: 'audio', n: 1, ev: 'error', code: 150 }); + const again = await nextOf(a, 'prepare', fa); + expect(again.n).toBe(1); + expect(again.videoId).not.toBe(first.videoId); + expect(s.db.query<{ youtube_status: string }, [string]>('SELECT youtube_status FROM songs WHERE youtube_id = ?').get(first.videoId)!.youtube_status).toBe('dead'); + expect((await gameWhere(a, (g) => g.n === 1)).total).toBe(2); + }); + + test('skip votes over the connected players (1/2 of 2 → 1), hint votes when 직접선택, replay restarts the clip for all', async () => { + seedLater(() => seed(3)); + const { users, cls } = await room(['방장', '철수'], { skipVotes: '2/3', hint: 'manual', hintVotes: '1', replayVotes: '1/2', listenSec: 10 }); + const [a, b] = cls as [Client, Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + const p = await nextOf(a, 'play', 0); + await sleep(p.startAt - Date.now() + 80); + let g = await gameWhere(a, (x) => x.phase === 'play'); + expect(g.need).toEqual({ skip: 2, hint: 1, replay: 1 }); + a.send({ t: 'vote', kind: 'hint' }); + g = await gameWhere(a, (x) => !!x.hint); + expect(g.hint).toMatch(/^ㄴㄹ\d+$/); + const fa = since(a); + b.send({ t: 'vote', kind: 'replay' }); + const re = await nextOf(a, 'prepare', fa); + expect(re.startSec).toBe(0); + const rp = await nextOf(a, 'play', fa); + expect(rp.atSec).toBe(0); + a.send({ t: 'vote', kind: 'skip' }); + g = await gameWhere(a, (x) => x.votes.skip.length === 1); + expect(g.phase).toBe('play'); + a.send({ t: 'vote', kind: 'skip' }); // toggle off + await gameWhere(a, (x) => x.votes.skip.length === 0); + a.send({ t: 'vote', kind: 'skip' }); + b.send({ t: 'vote', kind: 'skip' }); + g = await gameWhere(a, (x) => x.phase === 'reveal'); + expect(g.history[0]!.how).toBe('skip'); + expect(chatLines(a).find((l) => l.answer)?.text).toContain('스킵'); + expect(users.length).toBe(2); + stop(); + }); + + test('hint off / timed: the server explains instead of counting the vote', async () => { + seedLater(() => seed(2)); + const { cls } = await room(['방장'], { hint: 30 }); + const [a] = cls as [Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + await nextOf(a, 'play', 0); + a.send({ t: 'vote', kind: 'hint' }); + expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toMatch(/힌트는 \d+초 뒤에 공개돼요/); + stop(); + }); + + test('somebody joining mid-game plays from the next question', async () => { + seedLater(() => seed(3)); + const { cls, code } = await room(['방장']); + const [a] = cls as [Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + await nextOf(a, 'play', 0); + const c = await guest(s.base, '늦게옴'); + const cc = await new Client(s.base, c.cookie).connect(); + cc.send({ t: 'join', code }); + const g = await gameWhere(cc, (x) => x.phase === 'play'); + expect(g.participants).not.toContain(c.id); + expect(cc.messages.some((m) => m.t === 'prepare')).toBe(false); + stop(); + cc.close(); + }); + + test('result → 이어풀기 leaves out the songs already asked and keeps the scores; 다시 하기 goes back with scores at 0', async () => { + let ids: number[] = []; + seedLater(() => (ids = seed(4))); + const { users, cls } = await room(['방장'], { count: 10 }); + const [a] = cls as [Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + const answerAll = async (round: number) => { + for (let n = 1; ; n++) { + const p = await nextOf(a, 'play', 0, (m) => m.n === n && !a.messages.some((x) => x.t === 'answer' && false)); + await sleep(Math.max(0, p.startAt - Date.now()) + 10); + const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title; + a.send({ t: 'chat', text: title }); + const g = await gameWhere(a, (x) => x.history.length === n); + if (g.n >= g.total) return g; + await gameWhere(a, (x) => x.n === n + 1); + void round; + } + }; + let g = await answerAll(1); + expect(g.total).toBe(4); // 10 asked, only 4 songs + g = await gameWhere(a, (x) => x.phase === 'result'); + expect(g.scores[0]).toMatchObject({ id: users[0]!.id, score: 4 }); + expect(g.left).toBe(0); + a.send({ t: 'game', action: 'continue' }); + expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('모두 풀었어요'); + // two more songs appear: 이어풀기 plays only those, scores go on + const more = seed2(2); + const fa = since(a); + a.send({ t: 'game', action: 'continue' }); + await gameWhere(a, (x) => x.phase !== 'result' && x.n === 1 && x.history.length === 0); + const asked: string[] = []; + for (let n = 1; n <= 2; n++) { + const pr = await nextOf(a, 'prepare', fa, (m) => m.n === n); + asked.push(pr.videoId); + const p = await nextOf(a, 'play', fa, (m) => m.n === n); + await sleep(Math.max(0, p.startAt - Date.now()) + 10); + const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(pr.videoId)!.title; + a.send({ t: 'chat', text: title }); + await gameWhere(a, (x) => x.history.length === n); + } + expect(asked.sort()).toEqual(more.sort()); + g = await gameWhere(a, (x) => x.phase === 'result'); + expect(g.scores[0]!.score).toBe(6); + const fb = since(a); + a.send({ t: 'game', action: 'again' }); + await nextOf(a, 'game', fb, (m) => m.game === null); + expect(s.rooms.roomOf(users[0]!.id)!.status).toBe('lobby'); + expect(s.rooms.roomOf(users[0]!.id)!.quiz.scores.size).toBe(0); + expect(ids.length).toBe(4); + stop(); + + function seed2(k: number) { + const c = new Catalog(s.db); + const vids: string[] = []; + for (let i = 1; i <= k; i++) { + const [id] = c.upsert({ title: `추가곡${i}`, artists: [{ name: `추가가수${i}` }], year: 2020, genres: ['kpop'], source: 't', ref: `m${i}` }); + c.autoLevel(id!, 'all', 3); + s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`more${i}`, id!); + vids.push(`more${i}`); + } + return vids; + } + }); + + test('host can end the game; the same singer never plays twice in a row when others are left', async () => { + seedLater(() => seed(6, { artist: (i) => (i <= 3 ? '같은가수' : `가수${i}`) })); + const { cls } = await room(['방장']); + const [a] = cls as [Client]; + const stop = autoReady(cls); + a.send({ t: 'start' }); + const order: string[] = []; + for (let n = 1; n <= 6; n++) { + const pr = await nextOf(a, 'prepare', 0, (m) => m.n === n); + order.push(s.db.query<{ artist: string }, [string]>('SELECT artist FROM songs WHERE youtube_id = ?').get(pr.videoId)!.artist); + a.send({ t: 'vote', kind: 'skip' }); + await gameWhere(a, (x) => x.history.length === n); + } + for (let i = 1; i < order.length; i++) if (order[i] === '같은가수') expect(order[i - 1]).not.toBe('같은가수'); + await gameWhere(a, (x) => x.phase === 'result'); + stop(); + }); + + test('lyrics mode: no audio, a masked lyrics card, the answer still counts', async () => { + seedLater(() => seed(2, { lyrics: true })); + const { users, cls } = await room(['방장'], { mode: 'lyrics' }); + const [a] = cls as [Client]; + a.send({ t: 'start' }); + const g = await gameWhere(a, (x) => x.phase === 'play' && !!x.lyrics); + expect(a.messages.some((m) => m.t === 'prepare')).toBe(false); + expect(g.lyrics!.length).toBe(4); + expect(g.lyrics!.join('\n')).not.toMatch(/노래\d/); + expect(g.lyrics!.join('\n')).toContain('○○○'); + await sleep(Math.max(0, g.startAt! - Date.now()) + 10); + const n = /첫 줄 (\d)/.exec(g.lyrics!.join('\n'))?.[1]; + a.send({ t: 'chat', text: `노래${n}` }); + const r = await gameWhere(a, (x) => x.phase === 'reveal'); + expect(r.history[0]!.winnerId).toBe(users[0]!.id); + }); +}); + +describe('퀴즈 저장·불러오기 (docs/12 Q8)', () => { + test('guests cannot save; a Discord host saves, loads in a new room, and players keep their scores', async () => { + seedLater(() => seed(3)); + const { cls } = await room(['손님방장'], { count: 10 }); + const [g] = cls as [Client]; + g.send({ t: 'save', name: '안됨' }); + expect(((await g.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('디스코드'); + g.close(); + + const login = await discordLogin(s.base, '700000000000000011'); + const cookie = login.cookie!; + const me = (await api(s.base, '/api/me', { cookie })).body.me; + const code = (await api(s.base, '/api/rooms', { method: 'POST', cookie, body: JSON.stringify({ config: { count: 10, level: 3 } }) })).body.code; + const a = await new Client(s.base, cookie).connect(); + a.send({ t: 'join', code }); + await a.waitFor((m) => m.t === 'room'); + a.send({ t: 'save', name: '빈퀴즈' }); + expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('아직 푼 문제가'); + const stop = autoReady([a]); + a.send({ t: 'start' }); + const p = await nextOf(a, 'play', 0, (m) => m.n === 1); + await sleep(Math.max(0, p.startAt - Date.now()) + 10); + const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title; + a.send({ t: 'chat', text: title }); + await gameWhere(a, (x) => x.history.length === 1); + a.send({ t: 'save', name: '중간' }); + expect(((await a.waitFor((m) => m.t === 'error' && m.message.includes('멈춘'))) as Msg<'error'>).message).toContain('멈춘'); + a.send({ t: 'game', action: 'end' }); + await gameWhere(a, (x) => x.phase === 'result'); + a.send({ t: 'save', name: '금요일 퀴즈' }); + const saved = (await a.waitFor((m) => m.t === 'saved')) as Msg<'saved'>; + const list = (await api(s.base, '/api/quizzes', { cookie })).body.quizzes; + expect(list).toEqual([expect.objectContaining({ id: saved.id, name: '금요일 퀴즈', questions: 1, players: 1 })]); + // a new room: load → start asks only the other 2 songs, the score goes on from 1 + const fb = since(a); + a.send({ t: 'game', action: 'again' }); + await nextOf(a, 'game', fb, (m) => m.game === null); + a.send({ t: 'config', patch: { level: 5 } }); + a.send({ t: 'load', id: saved.id }); + const r = (await a.waitFor((m) => m.t === 'room' && m.room.config.level === 3 && m.room.config.count === 10)) as Msg<'room'>; + expect(r.room.config.count).toBe(10); + a.send({ t: 'start' }); + const gv = await gameWhere(a, (x) => x.phase !== 'result' && x.n === 1 && x.history.length === 0); + expect(gv.total).toBe(2); + expect(gv.scores[0]).toMatchObject({ id: me.id, score: 1 }); + stop(); + // only the owner can delete + expect((await api(s.base, `/api/quizzes/${saved.id}`, { method: 'DELETE', cookie })).res.status).toBe(200); + expect((await api(s.base, '/api/quizzes', { cookie })).body.quizzes).toEqual([]); + }); +}); diff --git a/apps/server/src/game/engine.ts b/apps/server/src/game/engine.ts new file mode 100644 index 0000000..f0cf606 --- /dev/null +++ b/apps/server/src/game/engine.ts @@ -0,0 +1,545 @@ +/** + * Quiz engine (docs/05 게임 진행, docs/12 Q1·Q3·Q4·Q5·Q8). One per running game, owned by its Room. + * + * Playback rule (docs/12 Q1): the music moves only while every player of the question can hear it. + * prepare → everyone reports ready → play{startAt} for all → stall/blocked → everyone pauses, re-prepares at the same + * position → play again. The host may leave out someone not ready for 30s, nobody is dropped automatically. + * Two clocks: the clip stops by playback position (clients), the question clock runs from the first play and stops while + * everyone is paused; it keeps running after the clip ends. + */ +import { hintText, isCorrect, voteThreshold, type GameHistoryItem, type GamePhase, type GameView, type ServerMessage } from '@mq/shared'; +import { clipOf, lyricsCard, mainArtists, markUnplayable, orderSongs, quizSong, type QuizSong } from '../songs/quiz'; +import { poolIds } from '../songs/pool'; +import type { Room } from '../rooms/manager'; + +export interface GameTiming { + /** 3·2·1 before the first play of a question. */ + countdownMs: number; + revealMs: number; + /** Lead time for a resume / replay so every client starts together (docs/12 Q1: now + 800ms). */ + resumeLeadMs: number; + /** A client that has not reported the clip end this long after the expected end gets one more stop (docs/12 Q1). */ + clipGraceMs: number; + /** After this long not ready the host may leave the player out of this question. */ + lateMs: number; + tickMs: number; + /** Tests only: replaces the site's question time limit for short clips. */ + limitMs?: number; +} +export const DEFAULT_TIMING: GameTiming = { countdownMs: 3000, revealMs: 5000, resumeLeadMs: 800, clipGraceMs: 3000, lateMs: 30_000, tickMs: 200 }; + +export interface Score { + nickname: string; + score: number; + correct: number; + totalMs: number; +} + +/** What 이어풀기 / 퀴즈 저장 carry over: songs asked so far and scores per account (docs/12 Q8). */ +export interface Quiz { + played: number[]; + scores: Map; +} +export const newQuiz = (): Quiz => ({ played: [], scores: new Map() }); + +/** Build the song order for a game. Returns an error message when nothing is left. */ +export function pickSongs(room: Room): number[] | string { + const db = room.deps.db; + const ids = poolIds(db, room.config, room.quiz.played); + if (!ids.length) return room.quiz.played.length ? '조건에 맞는 곡을 모두 풀었어요.' : '조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.'; + const recent = new Set(room.recent.flat()); + return orderSongs(ids, recent, mainArtists(db, ids), room.config.mode !== 'artist'); +} + +export class Game { + phase: GamePhase = 'prepare'; + n = 0; + total: number; + song: QuizSong | null = null; + private clip: { startSec: number; endSec: number | null } = { startSec: 0, endSec: null }; + participants = new Set(); + excluded = new Set(); + private ready = new Set(); + private waitingSince = new Map(); + private awaitingReady = false; + private hostHold = false; + private resumeAt = 0; + private clipDone = new Set(); + clipOver = false; + paused: GameView['paused'] = null; + /** Audio timeline: position `audioAtSec` at server time `audioStartAt`; `playing` while it should be running. */ + private audioStartAt = 0; + private audioAtSec = 0; + private playing = false; + startAt: number | null = null; + /** First music start of this question: answers count only after it. */ + private firstStartAt: number | null = null; + private elapsedMs = 0; + private runningSince: number | null = null; + private limitMs: number | null = null; + hint: string | null = null; + private lyrics: string[] | null = null; + votes = { skip: new Set(), hint: new Set(), replay: new Set() }; + history: GameHistoryItem[] = []; + private revealUntil: number | null = null; + private timer: ReturnType | null = null; + /** Songs this game asked, for the room's "last 3 games" list. */ + private asked: number[] = []; + + constructor( + private room: Room, + private list: number[], + private timing: GameTiming, + private now: () => number = Date.now, + ) { + const c = room.config.count; + this.total = c ? Math.min(c, list.length) : list.length; + } + + get listening(): boolean { + return this.room.config.mode !== 'lyrics'; + } + + start(): void { + this.timer = setInterval(() => this.tick(), this.timing.tickMs); + this.room.say(null, `게임을 시작해요! ${this.total}문제`); + this.next(); + } + + stop(): void { + if (this.timer) clearInterval(this.timer); + this.timer = null; + } + + // ------------------------------------------------------------------ helpers + private online(id: string): boolean { + return this.room.isOnline(id); + } + /** Players of this question who are connected and not left out. */ + active(): string[] { + return [...this.participants].filter((id) => this.online(id) && !this.excluded.has(id)); + } + private toActive(m: ServerMessage): void { + for (const id of this.active()) this.room.send(m, id); + } + elapsed(now = this.now()): number { + return this.elapsedMs + (this.runningSince !== null && now > this.runningSince ? now - this.runningSince : 0); + } + private stopClock(now: number): void { + this.elapsedMs = this.elapsed(now); + this.runningSince = null; + } + private position(now: number): number { + if (!this.playing) return this.resumeAt; + const p = this.audioAtSec + Math.max(0, now - this.audioStartAt) / 1000; + return this.clip.endSec !== null ? Math.min(p, this.clip.endSec) : p; + } + private need(kind: 'skip' | 'hint' | 'replay'): number | null { + const c = this.room.config; + const rule = kind === 'skip' ? c.skipVotes : kind === 'hint' ? (c.hint === 'manual' ? c.hintVotes : 'none') : this.listening ? c.replayVotes : 'none'; + return voteThreshold(rule, this.active().length); + } + + // ------------------------------------------------------------------ question flow + private next(): void { + this.n++; + this.setup(); + } + + /** Load question `n` (also used when a song is replaced under the same number). */ + private setup(): void { + const c = this.room.config; + this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length; + let song: QuizSong | null = null; + while (this.n <= this.total) { + song = quizSong(this.room.deps.db, this.list[this.n - 1]!); + if (song && (this.listening ? song.videoId : song.lyrics)) break; + this.list.splice(this.n - 1, 1); + this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length; + song = null; + } + if (!song) return this.finish(); + const now = this.now(); + this.song = song; + this.clip = this.listening ? clipOf(song, c) : { startSec: 0, endSec: null }; + this.participants = new Set(this.room.online()); + this.excluded.clear(); + this.ready.clear(); + this.waitingSince.clear(); + this.clipDone.clear(); + this.clipOver = false; + this.paused = null; + this.hostHold = false; + this.playing = false; + this.startAt = null; + this.firstStartAt = null; + this.elapsedMs = 0; + this.runningSince = null; + this.hint = null; + this.revealUntil = null; + for (const v of Object.values(this.votes)) v.clear(); + if (this.listening) { + this.limitMs = c.listenSec === 0 ? null : (this.timing.limitMs ?? Math.max(this.room.limitSec() * 1000, c.listenSec * 1000 + 5000)); + this.lyrics = null; + this.phase = 'prepare'; + this.prepareAll(this.clip.startSec); + } else { + this.limitMs = c.lyricsSec ? c.lyricsSec * 1000 : null; + this.lyrics = lyricsCard(song.lyrics!, song.title); + this.phase = 'play'; + this.startAt = this.firstStartAt = now + this.timing.countdownMs; + this.runningSince = this.startAt; + } + this.room.say(null, `${this.n}번째 문제`); + this.broadcast(); + } + + /** Everyone loads/seeks muted to `atSec` and reports ready (docs/12 Q1 준비 단계). */ + private prepareAll(atSec: number): void { + const now = this.now(); + this.resumeAt = atSec; + this.awaitingReady = true; + this.ready.clear(); + this.waitingSince.clear(); + for (const id of this.active()) this.waitingSince.set(id, now); + this.toActive({ t: 'prepare', code: this.room.code, n: this.n, videoId: this.song!.videoId!, startSec: atSec, endSec: this.clip.endSec }); + } + + private checkReady(): void { + if (!this.awaitingReady || this.hostHold || (this.phase !== 'prepare' && this.phase !== 'play')) return; + const act = this.active(); + if (!act.length) { + // Everyone of this question is gone: whoever is here now plays it. + const online = this.room.online(); + if (!online.length) return; + this.participants = new Set(online); + this.excluded.clear(); + return this.prepareAll(this.resumeAt); + } + if (!act.every((id) => this.ready.has(id))) return; + const now = this.now(); + const first = this.firstStartAt === null; + const startAt = now + (first ? this.timing.countdownMs : this.timing.resumeLeadMs); + this.awaitingReady = false; + this.waitingSince.clear(); + this.paused = null; + this.phase = 'play'; + this.startAt = startAt; + if (first) this.firstStartAt = startAt; + this.audioStartAt = startAt; + this.audioAtSec = this.resumeAt; + this.playing = true; + this.runningSince = startAt; + this.toActive({ t: 'play', code: this.room.code, n: this.n, startAt, atSec: this.resumeAt, endSec: this.clip.endSec }); + this.broadcast(); + } + + /** Stop everyone at the same position (buffering / no sound / host). */ + private pauseAll(reason: 'stall' | 'blocked' | 'host', who: string[]): void { + const now = this.now(); + const pos = this.position(now); + this.stopClock(now); + this.playing = false; + this.resumeAt = pos; + this.paused = { reason, who }; + this.toActive({ t: 'pause', code: this.room.code, n: this.n }); + if (reason === 'host') { + this.hostHold = true; + this.awaitingReady = false; + } else if (this.listening) this.prepareAll(pos); + this.broadcast(); + } + + private endClip(): void { + if (this.clipOver) return; + this.clipOver = true; + this.resumeAt = this.position(this.now()); + this.playing = false; + // 끝까지: the song is over, so is the question (docs/05 문제 진행). + if (this.room.config.listenSec === 0) return this.endQuestion(null, 'timeout'); + this.broadcast(); + } + + private showHint(): void { + if (this.hint || !this.song) return; + this.hint = hintText(this.song, this.room.config.answer); + if (this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1); + this.votes.hint.clear(); + this.room.say(null, `힌트가 공개됐어요: ${this.hint}`); + this.broadcast(); + } + + private replay(): void { + if (!this.listening || !this.song) return; + for (const v of Object.values(this.votes)) v.clear(); + this.clipDone.clear(); + this.clipOver = false; + // 짧은 클립: the time limit counts again from the replay (docs/12 Q4). + this.elapsedMs = 0; + this.runningSince = null; + this.playing = false; + this.paused = null; + this.hostHold = false; + this.toActive({ t: 'pause', code: this.room.code, n: this.n }); + this.room.say(null, '다 같이 다시 들어요'); + this.prepareAll(this.clip.startSec); + this.broadcast(); + } + + private endQuestion(winner: string | null, how: GameHistoryItem['how'], chat?: { text: string; n?: string }): void { + if ((this.phase !== 'prepare' && this.phase !== 'play') || !this.song) return; + const now = this.now(); + const ms = winner ? this.elapsed(now) : null; + const s = this.song; + if (winner) { + const sc = this.room.quiz.scores.get(winner) ?? { nickname: this.room.nick(winner), score: 0, correct: 0, totalMs: 0 }; + sc.nickname = this.room.nick(winner); + sc.score += 1; + sc.correct += 1; + sc.totalMs += ms!; + this.room.quiz.scores.set(winner, sc); + } + this.history.push({ + n: this.n, + title: s.title, + artist: s.artist, + year: s.year, + level: s.level, + genres: s.genres, + videoId: s.videoId, + winnerId: winner, + winner: winner ? this.room.nick(winner) : null, + ms, + how, + }); + this.room.quiz.played.push(s.id); + this.asked.push(s.id); + const answer = `${s.title} - ${s.artist}`; + if (winner) this.room.post({ userId: winner, text: chat!.text, n: chat!.n, answer: { text: answer } }); + else this.room.post({ userId: null, text: how === 'skip' ? '스킵했어요 · 정답자 없음' : '시간이 다 됐어요 · 정답자 없음', answer: { text: answer, none: true } }); + this.stopClock(now); + this.awaitingReady = false; + this.hostHold = false; + this.paused = null; + this.playing = false; + this.phase = 'reveal'; + this.revealUntil = now + this.timing.revealMs; + this.broadcast(); + } + + finish(): void { + if (this.phase === 'result') return; + this.phase = 'result'; + this.playing = false; + this.awaitingReady = false; + this.paused = null; + this.stopClock(this.now()); + this.stop(); + if (this.asked.length) { + this.room.recent.push(this.asked); + while (this.room.recent.length > 3) this.room.recent.shift(); + } + this.toActive({ t: 'pause', code: this.room.code, n: this.n }); + this.room.say(null, '게임이 끝났어요'); + this.broadcast(); + } + + tick(now = this.now()): void { + if (this.phase === 'reveal') { + if (this.revealUntil !== null && now >= this.revealUntil) { + if (this.n >= this.total) this.finish(); + else this.next(); + } + return; + } + if (this.phase !== 'play') return; + const el = this.elapsed(now); + const c = this.room.config; + if (typeof c.hint === 'number' && !this.hint && this.runningSince !== null && el >= c.hint * 1000) this.showHint(); + if (this.limitMs !== null && el >= this.limitMs) return this.endQuestion(null, 'timeout'); + if (this.playing && !this.clipOver && this.clip.endSec !== null) { + const expectedEnd = this.audioStartAt + (this.clip.endSec - this.audioAtSec) * 1000; + if (now > expectedEnd + this.timing.clipGraceMs) { + // Clients that did not report the end get one more stop; the question goes on (docs/12 Q1 재생 길이). + for (const id of this.active()) if (!this.clipDone.has(id)) this.room.send({ t: 'pause', code: this.room.code, n: this.n }, id); + this.endClip(); + } + } + } + + // ------------------------------------------------------------------ inputs + onAudio(userId: string, n: number, ev: 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error', code?: number): void { + if (n !== this.n || !this.participants.has(userId) || this.excluded.has(userId) || !this.listening) return; + if (ev === 'ready') { + if (!this.awaitingReady) return; + this.ready.add(userId); + this.waitingSince.delete(userId); + this.checkReady(); + this.broadcast(); + return; + } + if (ev === 'stall' || ev === 'blocked') { + if (this.phase !== 'play' || this.clipOver) return; + if (this.paused) { + if (!this.paused.who.includes(userId)) this.paused = { ...this.paused, who: [...this.paused.who, userId] }; + this.ready.delete(userId); + if (!this.waitingSince.has(userId) && this.awaitingReady) this.waitingSince.set(userId, this.now()); + return this.broadcast(); + } + if (!this.playing) return; + return this.pauseAll(ev, [userId]); + } + if (ev === 'clipEnd') { + if (this.phase !== 'play' || !this.playing) return; + this.clipDone.add(userId); + if (this.active().every((id) => this.clipDone.has(id))) this.endClip(); + return; + } + if (ev === 'error' && (code === 100 || code === 101 || code === 150) && (this.phase === 'prepare' || this.phase === 'play') && this.song) { + // The video is gone or may not be embedded: swap the song for everyone, same question number (docs/12 Q1). + markUnplayable(this.room.deps.db, this.song.id, code); + this.room.say(null, '이 곡은 재생할 수 없어서 다른 곡으로 바꿨어요'); + this.toActive({ t: 'pause', code: this.room.code, n: this.n }); + this.list.splice(this.n - 1, 1); + this.setup(); + } + } + + /** Is this chat line the answer? Then it becomes the 정답 줄 + 5줄 블록 (docs/06) and true is returned. */ + judge(userId: string, text: string, n?: string): boolean { + if (this.phase !== 'play' || !this.song || this.firstStartAt === null || this.now() < this.firstStartAt) return false; + if (!this.participants.has(userId) || this.excluded.has(userId)) return false; + if (!isCorrect(text, this.song, this.room.config.answer, this.room.config.strict)) return false; + this.endQuestion(userId, 'correct', { text, n }); + return true; + } + + vote(userId: string, kind: 'skip' | 'hint' | 'replay'): string | null { + if (this.phase !== 'play' && this.phase !== 'prepare') return '지금은 투표할 수 없어요.'; + if (!this.active().includes(userId)) return '이번 문제에 참가하고 있지 않아요.'; + const c = this.room.config; + if (kind === 'hint') { + if (c.hint === 'none') return '이 방은 힌트가 꺼져 있어요.'; + if (this.hint) return '이미 공개된 힌트예요.'; + if (c.hint !== 'manual') { + const left = Math.max(1, Math.ceil(c.hint - (this.elapsed() / 1000))); + return `힌트는 ${left}초 뒤에 공개돼요.`; + } + } + if (kind === 'replay') { + if (!this.listening) return '가사 모드에는 다시듣기가 없어요.'; + if (c.replayVotes === 'none') return '이 방은 다시듣기가 꺼져 있어요.'; + if (this.phase !== 'play' || this.firstStartAt === null) return '노래가 나오면 다시듣기를 누를 수 있어요.'; + } + if (kind === 'skip' && c.skipVotes === 'none') return '이 방은 스킵이 꺼져 있어요.'; + const set = this.votes[kind]; + if (set.has(userId)) set.delete(userId); + else set.add(userId); + this.checkVotes(); + this.broadcast(); + return null; + } + + private checkVotes(): void { + const act = new Set(this.active()); + for (const v of Object.values(this.votes)) for (const id of v) if (!act.has(id)) v.delete(id); + const pass = (k: 'skip' | 'hint' | 'replay') => { + const need = this.need(k); + return need !== null && this.votes[k].size >= need; + }; + if (pass('skip')) return this.endQuestion(null, 'skip'); + if (pass('hint') && this.phase === 'play') this.showHint(); + if (pass('replay') && this.phase === 'play' && this.firstStartAt !== null) this.replay(); + } + + /** A player went offline or left: do not wait for them, drop their votes (docs/05 진행 중 나간 사람). */ + onGone(userId: string): void { + if (this.phase !== 'prepare' && this.phase !== 'play') return this.broadcast(); + this.waitingSince.delete(userId); + if (this.paused?.who.includes(userId)) this.paused = { ...this.paused, who: this.paused.who.filter((x) => x !== userId) }; + this.checkVotes(); + if ((this.phase as GamePhase) !== 'play' && (this.phase as GamePhase) !== 'prepare') return; + this.checkReady(); + if (this.playing && this.active().length && this.active().every((id) => this.clipDone.has(id))) this.endClip(); + this.broadcast(); + } + + /** Host: leave out someone who has not been ready for 30s (docs/12 Q1). */ + exclude(target: string): string | null { + const since = this.waitingSince.get(target); + if (!this.awaitingReady || since === undefined) return '음원을 기다리는 사람이 아니에요.'; + if (this.now() - since < this.timing.lateMs) return '30초가 지나야 뺄 수 있어요.'; + this.excluded.add(target); + this.waitingSince.delete(target); + this.room.say(null, `${this.room.nick(target)}님은 음원을 불러오지 못해 이번 문제에서 빠져요`); + this.checkReady(); + this.broadcast(); + return null; + } + + hostPause(on: boolean): string | null { + if (this.phase !== 'play' && this.phase !== 'prepare') return '지금은 멈출 수 없어요.'; + if (on) { + if (this.hostHold) return null; + if (this.playing) { + this.pauseAll('host', []); + return null; + } + this.stopClock(this.now()); + this.hostHold = true; + this.paused = { reason: 'host', who: [] }; + this.broadcast(); + return null; + } + if (!this.hostHold) return null; + this.hostHold = false; + this.paused = null; + if (this.phase === 'play' && this.firstStartAt !== null && this.listening && !this.clipOver) this.prepareAll(this.resumeAt); + else if (this.phase === 'play' && this.firstStartAt !== null) this.runningSince = this.now(); + else this.checkReady(); + this.broadcast(); + return null; + } + + // ------------------------------------------------------------------ view + view(): GameView { + const players = new Map(); + for (const [id] of this.room.players) players.set(id, this.online(id)); + const scores = new Map(this.room.quiz.scores); + const ids = new Set([...players.keys(), ...[...scores].filter(([, s]) => s.score > 0).map(([id]) => id)]); + const c = this.room.config; + return { + phase: this.phase, + n: this.n, + total: this.total, + mode: c.mode, + participants: [...this.participants], + excluded: [...this.excluded], + waiting: this.awaitingReady ? [...this.waitingSince].map(([id, since]) => ({ id, since })) : [], + paused: this.paused, + startAt: this.startAt, + clock: { elapsedMs: this.elapsedMs, runningSince: this.runningSince, limitMs: this.limitMs }, + clipSec: this.clip.endSec !== null ? this.clip.endSec - this.clip.startSec : null, + clipOver: this.clipOver, + hint: this.hint, + hintAtSec: typeof c.hint === 'number' ? c.hint : null, + lyrics: this.lyrics, + votes: { skip: [...this.votes.skip], hint: [...this.votes.hint], replay: [...this.votes.replay] }, + need: { skip: this.need('skip'), hint: this.need('hint'), replay: this.need('replay') }, + scores: [...ids] + .map((id) => { + const s = scores.get(id); + return { id, nickname: players.has(id) ? this.room.nick(id) : (s?.nickname ?? '?'), score: s?.score ?? 0, correct: s?.correct ?? 0, avgMs: s?.correct ? Math.round(s.totalMs / s.correct) : null, online: players.get(id) ?? false }; + }) + .sort((a, b) => b.score - a.score || (a.avgMs ?? Infinity) - (b.avgMs ?? Infinity) || a.nickname.localeCompare(b.nickname)), + history: this.history, + revealUntil: this.revealUntil, + left: Math.max(0, this.list.length - this.asked.length), + }; + } + + broadcast(): void { + this.room.send({ t: 'game', code: this.room.code, game: this.view() }); + } +} + diff --git a/apps/server/src/game/saved.ts b/apps/server/src/game/saved.ts new file mode 100644 index 0000000..f6c8ce1 --- /dev/null +++ b/apps/server/src/game/saved.ts @@ -0,0 +1,57 @@ +/** 퀴즈 저장·불러오기 (docs/12 Q8): Discord accounts only, 20 per account, deleted only by the owner. */ +import type { Database } from 'bun:sqlite'; +import { applyConfigPatch, DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared'; +import type { Quiz, Score } from './engine'; + +export const SAVE_LIMIT = 20; + +export interface SavedQuizRow { + id: number; + name: string; + questions: number; + players: number; + updatedAt: number; +} + +export class SavedQuizzes { + constructor(private db: Database) {} + + list(userId: string): SavedQuizRow[] { + return this.db + .query<{ id: number; name: string; questions: number; scores_json: string; updated_at: number }, [string]>( + 'SELECT id, name, questions, scores_json, updated_at FROM saved_quizzes WHERE user_id = ? ORDER BY updated_at DESC', + ) + .all(userId) + .map((r) => ({ id: r.id, name: r.name, questions: r.questions, players: (JSON.parse(r.scores_json) as unknown[]).length, updatedAt: r.updated_at })); + } + + save(userId: string, name: string, config: RoomConfig, quiz: Quiz, now = Date.now()): number | string { + const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM saved_quizzes WHERE user_id = ?').get(userId)!.n; + if (n >= SAVE_LIMIT) return `퀴즈는 ${SAVE_LIMIT}개까지 저장할 수 있어요. 안 쓰는 퀴즈를 지워 주세요.`; + const scores = [...quiz.scores].map(([id, s]) => ({ id, ...s })); + const r = this.db + .query<{ id: number }, [string, string, string, string, string, number, number, number]>( + 'INSERT INTO saved_quizzes (user_id, name, config_json, played_json, scores_json, questions, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id', + ) + .get(userId, name, JSON.stringify(config), JSON.stringify(quiz.played), JSON.stringify(scores), quiz.played.length, now, now)!; + return r.id; + } + + load(userId: string, id: number): { name: string; config: RoomConfig; quiz: Quiz } | null { + const r = this.db + .query<{ name: string; config_json: string; played_json: string; scores_json: string }, [number, string]>( + 'SELECT name, config_json, played_json, scores_json FROM saved_quizzes WHERE id = ? AND user_id = ?', + ) + .get(id, userId); + if (!r) return null; + // Settings saved by an older version: whatever no longer validates falls back to the default. + const merged = applyConfigPatch(DEFAULT_ROOM_CONFIG, JSON.parse(r.config_json)); + const config = typeof merged === 'string' ? DEFAULT_ROOM_CONFIG : merged; + const scores = new Map((JSON.parse(r.scores_json) as ({ id: string } & Score)[]).map(({ id: uid, ...s }) => [uid, s])); + return { name: r.name, config, quiz: { played: JSON.parse(r.played_json) as number[], scores } }; + } + + remove(userId: string, id: number): boolean { + return this.db.query('DELETE FROM saved_quizzes WHERE id = ? AND user_id = ?').run(id, userId).changes > 0; + } +} diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index 6c276fe..9fde0f1 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -246,6 +246,19 @@ export function createHttpApp(d: HttpDeps) { return c.json(countPool(d.db, cfg)); }); + // ------------------------------------------------------------ saved quizzes (docs/12 Q8) + app.get('/api/quizzes', (c) => { + const u = userOf(c); + if (!u) return c.json({ error: '로그인이 필요해요.' }, 401); + return c.json({ quizzes: d.rooms.saved.list(u) }); + }); + + app.delete('/api/quizzes/:id', (c) => { + const u = userOf(c); + if (!u) return c.json({ error: '로그인이 필요해요.' }, 401); + return d.rooms.saved.remove(u, Number(c.req.param('id'))) ? c.json({ ok: true }) : c.json({ error: '저장한 퀴즈를 찾을 수 없어요.' }, 404); + }); + app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings })); app.all('/api/*', (c) => c.json({ error: '없는 주소예요.' }, 404)); diff --git a/apps/server/src/rooms.test.ts b/apps/server/src/rooms.test.ts index bb51f9e..0823fe6 100644 --- a/apps/server/src/rooms.test.ts +++ b/apps/server/src/rooms.test.ts @@ -219,6 +219,18 @@ describe('rooms over WebSocket', () => { expect(await ca.waitFor((m) => m.t === 'error' && m.n === 'blank')).toMatchObject({ message: '빈 메시지는 보낼 수 없어요.' }); }); + test('the last player leaving closes the room at once (← 방 목록 / 나가기)', async () => { + const { ca, cb, code } = await setup(); + cb.send({ t: 'leave' }); + await nextRoom(ca, (r) => r.players.length === 1); + expect(s.rooms.get(code)).toBeDefined(); + ca.send({ t: 'leave' }); + await ca.waitFor((m) => m.t === 'left'); + expect(s.rooms.get(code)).toBeUndefined(); + expect((await api(s.base, `/api/rooms/${code}`)).res.status).toBe(404); + expect((await api(s.base, '/api/rooms')).body.rooms).toEqual([]); + }); + test('a room created but never entered expires like an empty room', async () => { s = boot(); const a = await guest(s.base, '만들기만'); diff --git a/apps/server/src/rooms/manager.ts b/apps/server/src/rooms/manager.ts index a79ac4c..aa1ee7a 100644 --- a/apps/server/src/rooms/manager.ts +++ b/apps/server/src/rooms/manager.ts @@ -1,10 +1,12 @@ /** * Rooms and waiting room (docs/04, docs/05 중간 입장·퇴장·방장). In memory; unlimited players (no seats). - * Stage 4: join/leave, host, kick, ready, settings with live song count. Games start in stage 5. + * join/leave, host, kick, ready, settings with live song count; the game itself lives in game/engine.ts. */ import type { Database } from 'bun:sqlite'; import type { ServerWebSocket } from 'bun'; import { DEFAULT_ROOM_CONFIG, applyConfigPatch, configSummary, type ChatLine, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared'; +import { DEFAULT_TIMING, Game, newQuiz, pickSongs, type GameTiming, type Quiz } from '../game/engine'; +import { SavedQuizzes } from '../game/saved'; import { artistsByIds, countPool } from '../songs/pool'; import type { WsData } from '../ws/gateway'; @@ -36,12 +38,20 @@ export class Room { emptySince: number | null = null; chat: ChatLine[] = []; private seq = 0; + game: Game | null = null; + /** Songs asked and scores of this quiz: kept by 이어풀기, cleared by 다시 하기, restored by 불러오기 (docs/12 Q8). */ + quiz: Quiz = newQuiz(); + /** Songs of the room's last 3 games: pushed to the back of the next order (docs/05). */ + recent: number[][] = []; + /** Who is typing, until when (docs/06 입력 중). */ + typing = new Map(); + typingSent = ''; constructor( readonly code: string, hostId: string, config: RoomConfig, - private deps: { db: Database; user: PublicUserLookup }, + readonly deps: { db: Database; user: PublicUserLookup; limitSec?: () => number }, ) { this.hostId = hostId; this.config = config; @@ -56,6 +66,15 @@ export class Room { return [...this.players].filter(([, p]) => p.conns.size > 0).map(([id]) => id); } + isOnline(id: string): boolean { + return (this.players.get(id)?.conns.size ?? 0) > 0; + } + + /** Question time limit for short clips (site setting, docs/05). */ + limitSec(): number { + return this.deps.limitSec?.() ?? 60; + } + view(): RoomView { return { code: this.code, @@ -83,11 +102,17 @@ export class Room { /** Relays at once (docs/12 채팅 무조건 실시간). userId null = system line (입장/퇴장/방장). */ say(userId: string | null, text: string, n?: string): ChatLine { - const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId, nickname: userId ? (this.deps.user(userId)?.nickname ?? '?') : '', text }; - if (n) line.n = n; + return this.post({ userId, text, n }); + } + + /** Any log line; with `answer` it goes out as one `answer` message so nothing can come between the line and its block (docs/06). */ + post(p: { userId: string | null; text: string; n?: string; answer?: ChatLine['answer'] }): ChatLine { + const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId: p.userId, nickname: p.userId ? (this.deps.user(p.userId)?.nickname ?? '?') : '', text: p.text }; + if (p.n) line.n = p.n; + if (p.answer) line.answer = p.answer; this.chat.push(line); if (this.chat.length > CHAT_HISTORY) this.chat.shift(); - this.send({ t: 'chat', code: this.code, line }); + this.send(p.answer ? { t: 'answer', code: this.code, line } : { t: 'chat', code: this.code, line }); return line; } @@ -119,7 +144,23 @@ export class RoomManager { /** userId → room code (one room at a time). */ private where = new Map(); - constructor(private deps: { db: Database; user: PublicUserLookup; genreName: (id: string) => string; log?: (msg: string, extra?: Record) => void }) {} + readonly saved: SavedQuizzes; + private timing: GameTiming; + + constructor( + private deps: { + db: Database; + user: PublicUserLookup; + genreName: (id: string) => string; + log?: (msg: string, extra?: Record) => void; + /** Question time limit for short clips (site setting). */ + limitSec?: () => number; + timing?: Partial; + }, + ) { + this.saved = new SavedQuizzes(deps.db); + this.timing = { ...DEFAULT_TIMING, ...deps.timing }; + } private newCode(): string { for (;;) { @@ -187,7 +228,9 @@ export class RoomManager { if (!room.players.has(room.hostId)) room.hostId = userId; ws.send(JSON.stringify({ t: 'chatlog', code, lines: room.chat } satisfies ServerMessage)); room.broadcast(); - if (!already) room.say(null, `${room.nick(userId)}님이 들어왔어요`); + if (room.game) room.game.broadcast(); + else ws.send(JSON.stringify({ t: 'game', code, game: null } satisfies ServerMessage)); + if (!already) room.say(null, room.game && room.game.phase !== 'result' ? `${room.nick(userId)}님이 들어왔어요 · 다음 문제부터 같이 해요` : `${room.nick(userId)}님이 들어왔어요`); return null; } @@ -202,10 +245,12 @@ export class RoomManager { if (p.conns.size === 0) { p.offlineSince = Date.now(); p.ready = false; + room.typing.delete(ws.data.userId); const wasHost = room.hostId === ws.data.userId; if (wasHost) room.pickHost(); room.broadcast(); if (wasHost && room.hostId !== ws.data.userId) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`); + room.game?.onGone(ws.data.userId); } } @@ -220,9 +265,11 @@ export class RoomManager { room.send({ t: 'left', code: room.code, reason }, userId); for (const ws of p.conns) ws.data.roomCode = undefined; room.players.delete(userId); + room.typing.delete(userId); if (this.where.get(userId) === room.code) this.where.delete(userId); if (room.players.size === 0) { - room.emptySince = Date.now(); + // Nobody has a place any more (left, kicked out by time, went elsewhere): close the room at once. + this.close(room); return; } const wasHost = room.hostId === userId; @@ -230,6 +277,13 @@ export class RoomManager { room.broadcast(); room.say(null, `${room.nick(userId)}님이 ${reason === 'kicked' ? '내보내졌어요' : '나갔어요'}`); if (wasHost) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`); + room.game?.onGone(userId); + } + + close(room: Room): void { + room.game?.stop(); + this.rooms.delete(room.code); + this.deps.log?.('room closed', { code: room.code }); } /** Host-only actions. Returns an error message or null. */ @@ -291,21 +345,144 @@ export class RoomManager { return null; } - /** Chat line from a player in the room (docs/06). Flood guard is applied by the gateway. */ + /** Chat line from a player in the room (docs/06). Judged as an answer and relayed in the same step; flood guard is in the gateway. */ chat(ws: ServerWebSocket, text: string, n?: string): string | null { const room = this.roomOf(ws.data.userId); if (!room || ws.data.roomCode !== room.code) return '방에 들어가 있지 않아요.'; const t = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim(); if (!t) return '빈 메시지는 보낼 수 없어요.'; + room.typing.delete(ws.data.userId); + if (room.game?.judge(ws.data.userId, t, n)) return null; room.say(ws.data.userId, t, n); return null; } - /** Every 10s: drop players gone longer than the grace period, close rooms left empty. */ + private inRoom(ws: ServerWebSocket): Room | undefined { + const room = this.roomOf(ws.data.userId); + return room && ws.data.roomCode === room.code ? room : undefined; + } + + // ------------------------------------------------------------------ game (docs/05) + start(ws: ServerWebSocket): string | null { + return this.hostAction(ws, (room) => this.startGame(room)); + } + + private startGame(room: Room): string | null { + if (room.config.mode === 'artist' && !room.config.artistIds.length) return '가수를 1명 이상 골라 주세요.'; + const list = pickSongs(room); + if (typeof list === 'string') return list; + room.game?.stop(); + room.status = 'playing'; + for (const p of room.players.values()) p.ready = false; + room.game = new Game(room, list, this.timing); + room.broadcast(); + room.game.start(); + this.deps.log?.('game started', { code: room.code, songs: list.length, total: room.game.total }); + return null; + } + + audio(ws: ServerWebSocket, n: number, ev: 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error', code?: number): void { + this.inRoom(ws)?.game?.onAudio(ws.data.userId, n, ev, code); + } + + vote(ws: ServerWebSocket, kind: 'skip' | 'hint' | 'replay'): string | null { + const room = this.inRoom(ws); + if (!room?.game) return '게임 중이 아니에요.'; + return room.game.vote(ws.data.userId, kind); + } + + /** 입력 중 (docs/06): remembered for 3s, sent at most once a second by flushTyping. */ + typing(ws: ServerWebSocket, on: boolean): void { + const room = this.inRoom(ws); + if (!room) return; + if (on) room.typing.set(ws.data.userId, Date.now() + 3000); + else room.typing.delete(ws.data.userId); + } + + flushTyping(now = Date.now()): void { + for (const room of this.rooms.values()) { + for (const [id, until] of room.typing) if (until < now) room.typing.delete(id); + const ids = [...room.typing.keys()]; + const key = ids.join(','); + if (key === room.typingSent) continue; + room.typingSent = key; + room.send({ t: 'typing', code: room.code, ids }); + } + } + + gameAction(ws: ServerWebSocket, action: 'pause' | 'resume' | 'end' | 'continue' | 'again'): string | null { + const room = this.inRoom(ws); + if (!room) return '방에 들어가 있지 않아요.'; + if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.'; + const g = room.game; + if (!g) return '게임 중이 아니에요.'; + switch (action) { + case 'pause': + case 'resume': + return g.hostPause(action === 'pause'); + case 'end': + g.finish(); + return null; + case 'continue': + if (g.phase !== 'result') return '게임이 끝난 뒤에 이어 풀 수 있어요.'; + return this.startGame(room); + case 'again': + // 다시 하기: same settings, back to the waiting room, scores from 0 (docs/12 Q8). + g.stop(); + room.game = null; + room.status = 'lobby'; + room.quiz = newQuiz(); + room.recount(); + room.broadcast(); + room.send({ t: 'game', code: room.code, game: null }); + room.say(null, '대기실로 돌아왔어요'); + return null; + } + } + + exclude(ws: ServerWebSocket, target: string): string | null { + const room = this.inRoom(ws); + if (!room?.game) return '게임 중이 아니에요.'; + if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.'; + return room.game.exclude(target); + } + + /** 퀴즈 저장 (docs/12 Q8): the host with a Discord account, in the waiting room, on the results or while paused. */ + save(ws: ServerWebSocket, name: string): string | null { + const room = this.inRoom(ws); + if (!room) return '방에 들어가 있지 않아요.'; + if (room.hostId !== ws.data.userId) return '방장만 저장할 수 있어요.'; + if (this.deps.user(ws.data.userId)?.kind !== 'member') return '퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.'; + const g = room.game; + if (g && g.phase !== 'result' && !g.paused) return '게임을 잠시 멈춘 뒤나 끝난 뒤에 저장할 수 있어요.'; + if (!room.quiz.played.length) return '아직 푼 문제가 없어요.'; + const id = this.saved.save(ws.data.userId, name, room.config, room.quiz); + if (typeof id === 'string') return id; + ws.send(JSON.stringify({ t: 'saved', id, name } satisfies ServerMessage)); + room.say(null, `퀴즈를 "${name}"(으)로 저장했어요 · ${room.quiz.played.length}문제`); + return null; + } + + /** 퀴즈 불러오기: settings, songs asked and scores come back; starting skips the songs already asked. */ + load(ws: ServerWebSocket, id: number): string | null { + return this.hostAction(ws, (room) => { + const q = this.saved.load(ws.data.userId, id); + if (!q) return '저장한 퀴즈를 찾을 수 없어요.'; + room.config = { ...q.config, title: room.config.title, visibility: room.config.visibility }; + room.quiz = q.quiz; + for (const p of room.players.values()) p.ready = false; + room.recount(); + room.broadcast(); + room.say(null, `"${q.name}" 퀴즈를 불러왔어요 · 지금까지 ${q.quiz.played.length}문제, 시작하면 이어서 나와요`); + return null; + }); + } + + /** Every 10s: drop players gone longer than the grace period, close rooms created but never entered. */ sweep(now = Date.now()): void { for (const room of this.rooms.values()) { for (const [id, p] of room.players) if (p.offlineSince && now - p.offlineSince > GRACE_MS) this.removePlayer(room, id, 'closed'); - if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.rooms.delete(room.code); + if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.close(room); } } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 55130fc..ce79fb8 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -33,6 +33,8 @@ export interface StartOptions { checkEmbed?: import('./http/admin').AdminDeps['checkEmbed']; /** Upper bound for waiting on Bun's server.stop() (tests shorten it). */ stopWaitMs?: number; + /** Game pacing (tests and e2e shorten the countdown / reveal). */ + gameTiming?: Partial; } export function startServer(opts: StartOptions) { @@ -54,6 +56,8 @@ export function startServer(opts: StartOptions) { }, genreName: (id) => genreNames.get(id) ?? id, log: (msg, extra) => log('info', msg, extra), + limitSec: () => settings.getSite().questionLimitSec, + timing: opts.gameTiming, }); const gateway = new Gateway({ log, @@ -140,6 +144,8 @@ export function startServer(opts: StartOptions) { }); const roomSweeper = setInterval(() => rooms.sweep(), 10_000); + // 입력 중 goes out at most once a second (docs/06); chat itself never waits. + const typingFlush = setInterval(() => rooms.flushTyping(), 1000); // The collector runs in its own process, so lobbies re-count now and then to show newly matched songs. const roomRecount = setInterval(() => { try { @@ -161,6 +167,8 @@ export function startServer(opts: StartOptions) { ready = false; clearInterval(sweeper); clearInterval(roomSweeper); + clearInterval(typingFlush); + for (const r of rooms.rooms.values()) r.game?.stop(); clearInterval(roomRecount); gateway.shutdown(); await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]); diff --git a/apps/server/src/songs/quiz.ts b/apps/server/src/songs/quiz.ts new file mode 100644 index 0000000..af20ed0 --- /dev/null +++ b/apps/server/src/songs/quiz.ts @@ -0,0 +1,165 @@ +/** + * What a game needs about one song (docs/05): answer spellings, video, start position, reveal card, lyrics card. + */ +import type { Database } from 'bun:sqlite'; +import type { RoomConfig } from '@mq/shared'; + +export interface QuizSong { + id: number; + title: string; + artist: string; + year: number | null; + durationSec: number | null; + videoId: string | null; + highlightSec: number | null; + genres: string[]; + /** Level shown on the reveal card: the 'all' scope level when there is one. */ + level: number | null; + titleAliases: string[]; + artistAliases: string[]; + /** Main artist ids (same singer not twice in a row, docs/05 출제 목록). */ + artistIds: number[]; + lyrics: string | null; +} + +export function quizSong(db: Database, id: number): QuizSong | null { + const s = db + .query< + { id: number; title: string; artist: string; year: number | null; duration_sec: number | null; youtube_id: string | null; highlight_sec: number | null; youtube_status: string; deleted_at: number | null }, + [number] + >('SELECT id, title, artist, year, duration_sec, youtube_id, highlight_sec, youtube_status, deleted_at FROM songs WHERE id = ?') + .get(id); + if (!s || s.deleted_at) return null; + const col = (sql: string) => db.query<{ v: T }, [number]>(sql).all(id).map((r) => r.v); + return { + id: s.id, + title: s.title, + artist: s.artist, + year: s.year, + durationSec: s.duration_sec, + videoId: s.youtube_status === 'matched' ? s.youtube_id : null, + highlightSec: s.highlight_sec, + genres: col('SELECT genre_id v FROM song_genres WHERE song_id = ?'), + level: db.query<{ level: number }, [number]>("SELECT level FROM song_levels WHERE song_id = ? ORDER BY scope = 'all' DESC LIMIT 1").get(id)?.level ?? null, + titleAliases: col("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'title'"), + artistAliases: [ + ...col("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'artist'"), + ...col('SELECT x.alias v FROM song_artists sa JOIN artist_aliases x ON x.artist_id = sa.artist_id WHERE sa.song_id = ?'), + ...col('SELECT a.name v FROM song_artists sa JOIN artists a ON a.id = sa.artist_id WHERE sa.song_id = ?'), + ], + artistIds: col("SELECT artist_id v FROM song_artists WHERE song_id = ? AND role = 'main' ORDER BY artist_id"), + lyrics: db.query<{ text: string }, [number]>('SELECT text FROM lyrics WHERE song_id = ?').get(id)?.text ?? null, + }; +} + +/** First main artist per song, for spreading singers apart. */ +export function mainArtists(db: Database, ids: number[]): Map { + const out = new Map(); + for (let i = 0; i < ids.length; i += 500) { + const chunk = ids.slice(i, i + 500); + for (const r of db + .query<{ song_id: number; a: number }, number[]>(`SELECT song_id, MIN(artist_id) a FROM song_artists WHERE song_id IN (${chunk.map(() => '?').join(',')}) GROUP BY song_id`) + .all(...chunk)) + out.set(r.song_id, r.a); + } + return out; +} + +/** The video stopped working for everyone (deleted 100, embedding off 101/150): the admin sees it as 재생 불가 (docs/12 Q1). */ +export function markUnplayable(db: Database, id: number, code: number): void { + db.query("UPDATE songs SET youtube_status = 'dead', note = trim(coalesce(note, '') || ' ' || ?), updated_at = ? WHERE id = ? AND youtube_status = 'matched'").run( + `[재생 오류 ${code}]`, + Date.now(), + id, + ); +} + +/** Where playback starts and how long the clip is (docs/04 재생위치, docs/08 하이라이트). */ +export function clipOf(song: QuizSong, c: RoomConfig): { startSec: number; endSec: number | null } { + const dur = song.durationSec; + let start = 0; + if (c.startAt === 'highlight') start = song.highlightSec ?? (dur ? Math.round(dur * 0.3) : 0); + if (dur && start > dur - 5) start = 0; + if (c.listenSec === 0) return { startSec: start, endSec: dur }; + const end = start + c.listenSec; + return { startSec: start, endSec: dur ? Math.min(end, dur) : end }; +} + +/** Shuffle, push back songs from the room's last 3 games, keep the same singer apart (docs/05 출제 목록 뽑기). */ +export function orderSongs(ids: number[], recent: Set, artistOf: Map, spreadArtists: boolean, rnd = Math.random): number[] { + const shuffle = (xs: number[]) => { + for (let i = xs.length - 1; i > 0; i--) { + const j = Math.floor(rnd() * (i + 1)); + [xs[i], xs[j]] = [xs[j]!, xs[i]!]; + } + return xs; + }; + const list = [...shuffle(ids.filter((x) => !recent.has(x))), ...shuffle(ids.filter((x) => recent.has(x)))]; + if (!spreadArtists) return list; + // Greedy: keep the order, but take the first song whose singer differs from the previous one. When one singer holds more + // than half of what is left, that singer must go now or it would have to repeat later. + const count = new Map(); + for (const id of list) { + const a = artistOf.get(id); + if (a !== undefined) count.set(a, (count.get(a) ?? 0) + 1); + } + const maxInitial = Math.max(0, ...count.values()); + const rest = [...list]; + const out: number[] = []; + let prev: number | undefined; + while (rest.length) { + let pick = -1; + if (rest.length < 2 * maxInitial + 2) { + let top: number | undefined; + let topN = 0; + for (const [a, n] of count) if (n > topN) ((top = a), (topN = n)); + if (top !== undefined && top !== prev && topN > (rest.length + 1) / 2 - 1) pick = rest.findIndex((x) => artistOf.get(x) === top); + } + if (pick < 0) pick = rest.findIndex((x) => prev === undefined || artistOf.get(x) !== prev); + if (pick < 0) pick = 0; + const [id] = rest.splice(pick, 1); + const a = artistOf.get(id!); + if (a !== undefined) count.set(a, count.get(a)! - 1); + prev = a; + out.push(id!); + } + return out; +} + +const norm = (s: string) => s.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, ''); + +/** + * 가사 card (docs/08 4. 가사): verse lines (not the repeated chorus), 4 from the middle, then 2 more per hint; + * words of the title are masked with ○. + */ +export function lyricsCard(text: string, title: string, extra = 0): string[] { + const lines = text + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + const seen = new Map(); + for (const l of lines) seen.set(norm(l), (seen.get(norm(l)) ?? 0) + 1); + // first run of lines that are not repeated (verse 1) + let from = 0; + while (from < lines.length && seen.get(norm(lines[from]!))! > 1) from++; + let to = from; + while (to < lines.length && seen.get(norm(lines[to]!))! === 1) to++; + if (to - from < 4) ((from = 0), (to = lines.length)); + const verse = lines.slice(from, to); + const want = 4 + extra * 2; + const mid = Math.max(0, Math.floor((verse.length - 4) / 2)); + const picked = verse.slice(mid, mid + want); + if (picked.length < want) picked.push(...lines.slice(to, to + want - picked.length)); + return picked.map((l) => maskTitle(l, title)); +} + +export function maskTitle(line: string, title: string): string { + const bare = title.replace(/[([{【].*?[)\]}】]/g, ' ').trim(); + const words = [bare, ...bare.split(/\s+/)].filter((w) => [...w].length >= 2 || /[가-힣]/.test(w)); + let out = line; + for (const w of words.sort((a, b) => b.length - a.length)) { + const esc = w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + out = out.replace(new RegExp(esc, 'gi'), (m) => m.replace(/\S/g, '○')); + } + return out; +} diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index 0a6b623..7661a96 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -98,6 +98,22 @@ export class Gateway { return err(rooms.kick(ws, m.userId)); case 'host': return err(rooms.giveHost(ws, m.userId)); + case 'start': + return err(rooms.start(ws)); + case 'audio': + return rooms.audio(ws, m.n, m.ev, m.code); + case 'vote': + return err(rooms.vote(ws, m.kind)); + case 'typing': + return rooms.typing(ws, m.on); + case 'game': + return err(rooms.gameAction(ws, m.action)); + case 'exclude': + return err(rooms.exclude(ws, m.userId)); + case 'save': + return err(rooms.save(ws, m.name)); + case 'load': + return err(rooms.load(ws, m.id)); case 'chat': { const g = this.d.chatGuard?.(); if (g?.on) { diff --git a/apps/web/src/components/ChatPanel.tsx b/apps/web/src/components/ChatPanel.tsx index 317901c..81dd94c 100644 --- a/apps/web/src/components/ChatPanel.tsx +++ b/apps/web/src/components/ChatPanel.tsx @@ -1,26 +1,47 @@ /** - * Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom. - * Stage 4 uses it in the waiting room; the answer block and "입력 중" come with the game chat (stage 6). + * Room chat (docs/06): one-line log, system lines centred, my unconfirmed lines at the bottom, + * the 정답 줄 + 5줄 블록 drawn as one item, "입력 중" above the input. The game screen uses the big variant. */ -import { useEffect, useLayoutEffect, useRef, useState } from 'react'; +import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react'; import { CHAT_MAX, type ChatLine } from '@mq/shared/lite'; +import { userHue } from './ui'; -/** Fixed colour per user (joke-app --name-h). */ -function hue(id: string): number { - let h = 0; - for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0; - return h % 360; +export interface ChatHandle { + focus(): void; } -export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: ChatLine[]; pending: { n: string; text: string }[]; meId: string; myName: string; onSend: (text: string) => void }) { +function typingText(names: string[]): string { + if (names.length === 1) return `${names[0]}님이 입력 중…`; + if (names.length === 2) return `${names[0]}, ${names[1]}님이 입력 중…`; + return `${names[0]}, ${names[1]} 외 ${names.length - 2}명이 입력 중…`; +} + +export const ChatPanel = forwardRef< + ChatHandle, + { + lines: ChatLine[]; + pending: { n: string; text: string }[]; + meId: string; + myName: string; + onSend: (text: string) => void; + /** 입력 중 signal: true on start and every 2s while typing, false when cleared or sent. */ + onTyping?: (on: boolean) => void; + typing?: string[]; + big?: boolean; + } +>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big }, ref) { const [text, setText] = useState(''); const [stuck, setStuck] = useState(true); const [unseen, setUnseen] = useState(false); const logRef = useRef(null); + const inputRef = useRef(null); const lastSent = useRef(''); + const typingAt = useRef(0); // Changes whenever a line arrives, also once the log is capped at 200 lines. const tick = `${lines.at(-1)?.seq ?? 0}:${pending.length}`; + useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }), []); + // Auto-scroll only while the reader is at the bottom (docs/06 위로 스크롤하면 멈춤). useLayoutEffect(() => { const el = logRef.current; @@ -37,17 +58,23 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha if (el) el.scrollTop = el.scrollHeight; setStuck(true); }; + const stopTyping = () => { + if (typingAt.current) onTyping?.(false); + typingAt.current = 0; + }; const submit = () => { const t = text.trim(); if (!t) return; onSend(t.slice(0, CHAT_MAX)); lastSent.current = t; setText(''); + typingAt.current = 0; toBottom(); }; + const others = typing.filter((n) => n !== myName); return ( -
+
{lines.length === 0 && pending.length === 0 &&
아직 대화가 없어요. 먼저 인사해 보세요!
} {lines.map((l) => - l.userId === null ? ( + l.answer ? ( +
+ {l.userId ? ( +
+ {l.nickname} + {l.text} ✔ +
+ ) : ( +
— {l.text} —
+ )} +
+
+
+ {l.answer.text} +
+
+
+
+ ) : l.userId === null ? (
— {l.text} —
) : (
- {l.nickname} + {l.nickname} {l.text}
), )} {pending.map((p) => (
- {myName} + {myName} {p.text}
))} @@ -83,6 +128,20 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha 새 메시지 ↓ )} + {onTyping && ( +
+ {others.length > 0 && ( + <> + + + + + + {typingText(others)} + + )} +
+ )}
{ @@ -91,15 +150,29 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha }} > setText(e.target.value)} + autoComplete="off" + onChange={(e) => { + const v = e.target.value; + setText(v); + if (!onTyping) return; + if (!v.trim()) return stopTyping(); + if (Date.now() - typingAt.current > 2000) { + typingAt.current = Date.now(); + onTyping(true); + } + }} + onBlur={stopTyping} onKeyDown={(e) => { - if (e.key === 'Escape') setText(''); - else if (e.key === 'ArrowUp' && !text && lastSent.current) { + if (e.key === 'Escape') { + setText(''); + stopTyping(); + } else if (e.key === 'ArrowUp' && !text && lastSent.current) { e.preventDefault(); setText(lastSent.current); } @@ -111,4 +184,4 @@ export function ChatPanel({ lines, pending, meId, myName, onSend }: { lines: Cha
); -} +}); diff --git a/apps/web/src/net/player.ts b/apps/web/src/net/player.ts new file mode 100644 index 0000000..ab8ed39 --- /dev/null +++ b/apps/web/src/net/player.ts @@ -0,0 +1,444 @@ +/** + * Hidden YouTube IFrame player with server-timed playback (docs/12 Q1, prototype tools/prototypes/iframe-sync). + * - prepare: load muted at the start position, wait until really PLAYING (an ad would come first), pause, seek back → ready + * (reloads by itself at 8s and 16s) + * - play: at server time `startAt` unmute and play from `atSec`; stop by playback POSITION at `endSec` + * (checked every frame + 10ms); 0.3s drift correction every second; buffering > 0.5s → stall; muted / not playing + * 0.3s after the start → blocked + * A fake player (localStorage mq:fakePlayer = "1") lets e2e runs play 30 questions without YouTube. + */ +import { create } from 'zustand'; + +export type AudioEvent = 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error'; + +export interface PlayerState { + /** The browser let us play sound (entry click done). */ + unlocked: boolean; + /** Sound was blocked: show the big "눌러서 소리 켜기" button. */ + needsGesture: boolean; + /** Loading for this question (for "음원 준비 중…"). */ + loading: boolean; + /** Playing right now (for the LP spin). */ + playing: boolean; + /** Last known position / clip window for the progress bar. */ + pos: number; + clip: { start: number; end: number | null } | null; + volume: number; +} + +const VOLUME_KEY = 'mq:volume'; +const readVolume = () => { + try { + const v = Number(localStorage.getItem(VOLUME_KEY)); + return Number.isFinite(v) && localStorage.getItem(VOLUME_KEY) !== null ? Math.max(0, Math.min(100, v)) : 70; + } catch { + return 70; + } +}; + +export const usePlayer = create(() => ({ unlocked: false, needsGesture: false, loading: false, playing: false, pos: 0, clip: null, volume: readVolume() })); + +/** A harmless video the entry click plays at volume 0 to get sound permission (SG워너비 광, Topic — known to embed). */ +const UNLOCK_VIDEO = 'VO88htcm09E'; + +interface Engine { + init(): Promise; + unlock(): void; + load(id: string, startSec: number): void; + seek(sec: number): void; + play(): void; + pause(): void; + mute(on: boolean): void; + isMuted(): boolean; + volume(v: number): void; + time(): number; + /** YT.PlayerState: -1 unstarted, 0 ended, 1 playing, 2 paused, 3 buffering, 5 cued */ + state(): number; + videoId(): string | null; +} + +type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void }; + +// ---------------------------------------------------------------- real YouTube engine +declare global { + interface Window { + YT?: any; + onYouTubeIframeAPIReady?: () => void; + mqPlayer?: unknown; + } +} + +function youtubeEngine(l: Listener): Engine { + let player: any = null; + let ready: Promise | null = null; + let current: string | null = null; + // The player object exists before onReady, its methods only after. + const call = (m: string, ...a: unknown[]): unknown => (typeof player?.[m] === 'function' ? player[m](...a) : undefined); + return { + init() { + ready ??= new Promise((resolve) => { + const host = document.createElement('div'); + host.setAttribute('aria-hidden', 'true'); + // Off screen, not display:none (a hidden iframe may not play). + host.style.cssText = 'position:fixed;left:-10000px;top:0;width:200px;height:200px;overflow:hidden;pointer-events:none'; + const el = document.createElement('div'); + host.appendChild(el); + document.body.appendChild(host); + const make = () => { + player = new window.YT.Player(el, { + width: 200, + height: 200, + playerVars: { autoplay: 0, controls: 0, disablekb: 1, fs: 0, rel: 0, playsinline: 1, iv_load_policy: 3 }, + events: { + onReady: () => resolve(), + onStateChange: (e: { data: number }) => l.onState?.(e.data), + onError: (e: { data: number }) => l.onError?.(e.data), + onAutoplayBlocked: () => l.onBlocked?.(), + }, + }); + }; + if (window.YT?.Player) make(); + else { + const prev = window.onYouTubeIframeAPIReady; + window.onYouTubeIframeAPIReady = () => { + prev?.(); + make(); + }; + const s = document.createElement('script'); + s.src = 'https://www.youtube.com/iframe_api'; + document.head.appendChild(s); + } + }); + return ready; + }, + unlock() { + if (typeof player?.loadVideoById !== 'function') return; + // Inside the click: play something with sound on (volume 0), so later starts are allowed (docs/12 Q1 소리 허용). + player.setVolume(0); + player.unMute(); + if (current) player.playVideo(); + else { + current = UNLOCK_VIDEO; + player.loadVideoById({ videoId: UNLOCK_VIDEO, startSeconds: 30 }); + } + }, + load(id, startSec) { + current = id; + player.loadVideoById({ videoId: id, startSeconds: startSec }); + }, + seek: (sec) => call('seekTo', sec, true), + play: () => call('playVideo'), + pause: () => call('pauseVideo'), + mute: (on) => call(on ? 'mute' : 'unMute'), + isMuted: () => !!call('isMuted'), + volume: (v) => call('setVolume', v), + time: () => (call('getCurrentTime') as number | undefined) ?? 0, + state: () => (call('getPlayerState') as number | undefined) ?? -1, + videoId: () => current, + }; +} + +// ---------------------------------------------------------------- fake engine for e2e (no network) +function fakeEngine(l: Listener): Engine { + let state = -1; + let base = 0; + let since = 0; + let current: string | null = null; + let muted = false; + const set = (s: number) => { + state = s; + l.onState?.(s); + }; + const fake = { loadMs: 40, failNext: 0 as number, stallNext: false }; + (window as unknown as { mqFake: typeof fake }).mqFake = fake; + const time = () => (state === 1 ? base + (performance.now() - since) / 1000 : base); + return { + init: () => Promise.resolve(), + unlock: () => {}, + load(id, startSec) { + current = id; + base = startSec; + set(3); + if (fake.failNext) { + const code = fake.failNext; + fake.failNext = 0; + setTimeout(() => l.onError?.(code), 30); + return; + } + setTimeout(() => { + since = performance.now(); + set(1); + }, fake.loadMs); + }, + seek(sec) { + base = sec; + since = performance.now(); + }, + play() { + since = performance.now(); + if (fake.stallNext) { + fake.stallNext = false; + set(3); + return; + } + if (fake.loadMs > 100) { + // slow network: buffers before playing + set(3); + setTimeout(() => { + since = performance.now(); + set(1); + }, fake.loadMs); + return; + } + set(1); + }, + pause() { + base = time(); + set(2); + }, + mute: (on) => (muted = on), + isMuted: () => muted, + volume: () => {}, + time, + state: () => state, + videoId: () => current, + }; +} + +// ---------------------------------------------------------------- controller +let engine: Engine | null = null; +let report: (n: number, ev: AudioEvent, code?: number) => void = () => {}; +let now: () => number = Date.now; +/** Every command bumps the token; async steps of older commands stop. */ +let token = 0; +let curN = 0; +let loop: { raf: number; iv: ReturnType; drift: ReturnType } | null = null; +let bufferingSince: number | null = null; +let stallSent = false; +let pendingReady: { n: number; tk: number; at: number } | null = null; +let timeline: { startAt: number; atSec: number; endSec: number | null } | null = null; + +const useFake = () => { + try { + return localStorage.getItem('mq:fakePlayer') === '1'; + } catch { + return false; + } +}; + +function eng(): Engine { + if (!engine) { + const l: Listener = { + onState: (s) => { + if (s === 3 && timeline) bufferingSince ??= performance.now(); + else bufferingSince = null; + if (s === 0 && timeline) clipEnded(); + }, + onError: (code) => { + usePlayer.setState({ loading: false }); + report(curN, 'error', code); + }, + onBlocked: () => blocked(), + }; + engine = useFake() ? fakeEngine(l) : youtubeEngine(l); + window.mqPlayer = { pos: () => engine!.time(), state: () => engine!.state(), muted: () => engine!.isMuted(), video: () => engine!.videoId() }; + } + return engine; +} + +const waitFor = (pred: () => boolean, ms: number, tk: number) => + new Promise((res) => { + const t0 = performance.now(); + const iv = setInterval(() => { + if (tk !== token) return (clearInterval(iv), res(false)); + if (pred()) return (clearInterval(iv), res(true)); + if (performance.now() - t0 > ms) return (clearInterval(iv), res(false)); + }, 20); + }); + +function stopLoop(): void { + if (!loop) return; + cancelAnimationFrame(loop.raf); + clearInterval(loop.iv); + clearInterval(loop.drift); + loop = null; +} + +function blocked(): void { + if (!timeline) return; + usePlayer.setState({ needsGesture: true, playing: false }); + report(curN, 'blocked'); +} + +function clipEnded(): void { + if (!timeline) return; + const e = eng(); + e.pause(); + stopLoop(); + timeline = null; + usePlayer.setState({ playing: false, pos: e.time() }); + report(curN, 'clipEnd'); +} + +export const player = { + /** Wire reports to the server and the server clock. */ + setup(r: typeof report, serverNow: () => number): void { + report = r; + now = serverNow; + }, + /** Load the API early (waiting room), so the entry click can unlock at once. */ + warm(): void { + void eng().init(); + }, + /** Call inside a click: "참가 (소리 켜기)" / "눌러서 소리 켜기". */ + unlock(): void { + const e = eng(); + e.unlock(); + const held = pendingReady; + pendingReady = null; + usePlayer.setState({ unlocked: true, needsGesture: false }); + const tk = token; + const release = () => held && held.tk === token && report(held.n, 'ready'); + if (useFake()) return void release(); + void waitFor(() => e.state() === 1, 5000, tk).then(async () => { + e.volume(usePlayer.getState().volume); + if (tk !== token || timeline) return; + e.pause(); + if (!held) return; + // The question was waiting for this click: back to the position everyone resumes from, then ready. + await waitFor(() => e.state() === 2, 2000, tk); + if (tk !== token) return; + e.seek(held.at); + release(); + }); + }, + + async prepare(n: number, videoId: string, startSec: number, endSec: number | null): Promise { + const tk = ++token; + curN = n; + stopLoop(); + timeline = null; + pendingReady = null; + usePlayer.setState({ loading: true, playing: false, pos: startSec, clip: { start: startSec, end: endSec } }); + const e = eng(); + await e.init(); + if (tk !== token) return; + e.mute(true); + const load = () => { + if (e.videoId() === videoId && e.state() !== -1 && e.state() !== 5) { + e.seek(startSec); + e.play(); + } else e.load(videoId, startSec); + }; + load(); + // Not playing yet: reload at 8s and 16s (docs/12 Q1), then keep waiting for the host's decision. + let ok = await waitFor(() => e.state() === 1, 8000, tk); + if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 8000, tk))); + if (!ok && tk === token) (e.load(videoId, startSec), (ok = await waitFor(() => e.state() === 1, 600_000, tk))); + if (!ok || tk !== token) return; + e.pause(); + await waitFor(() => e.state() === 2, 3000, tk); + if (tk !== token) return; + e.seek(startSec); + usePlayer.setState({ loading: false, pos: startSec }); + if (usePlayer.getState().needsGesture) pendingReady = { n, tk, at: startSec }; + else report(n, 'ready'); + }, + + play(n: number, startAt: number, atSec: number, endSec: number | null): void { + const tk = ++token; + curN = n; + stopLoop(); + pendingReady = null; + const e = eng(); + timeline = { startAt, atSec, endSec }; + stallSent = false; + bufferingSince = null; + usePlayer.setState({ clip: { start: usePlayer.getState().clip?.start ?? atSec, end: endSec }, pos: atSec }); + const go = () => { + if (tk !== token) return; + e.volume(usePlayer.getState().volume); + e.mute(false); + if (Math.abs(e.time() - atSec) > 0.15) e.seek(atSec); + e.play(); + usePlayer.setState({ playing: true }); + // 소리 확인 (docs/12 Q1): 0.3s later it must be unmuted and playing. + setTimeout(() => { + if (tk !== token || !timeline) return; + if (e.isMuted() || (e.state() !== 1 && e.state() !== 3)) blocked(); + }, 300); + const check = () => { + if (tk !== token || !timeline) return; + const t = e.time(); + if (endSec !== null && t >= endSec) return clipEnded(); + if (bufferingSince !== null && !stallSent && performance.now() - bufferingSince > 500) { + stallSent = true; + report(n, 'stall'); + } + if (loop) loop.raf = requestAnimationFrame(check); + }; + loop = { + raf: requestAnimationFrame(check), + iv: setInterval(check, 10), + drift: setInterval(() => { + if (tk !== token || !timeline || e.state() !== 1) return; + const expected = atSec + (now() - startAt) / 1000; + const t = e.time(); + usePlayer.setState({ pos: t }); + if (Math.abs(t - expected) > 0.3) e.seek(expected); + }, 1000), + }; + }; + const wait = startAt - now(); + if (wait > 0) setTimeout(go, wait); + else go(); + }, + + pause(): void { + token++; + stopLoop(); + timeline = null; + pendingReady = null; + const e = engine; + if (e && e.state() === 1) e.pause(); + usePlayer.setState({ playing: false, loading: false, pos: e?.time() ?? 0 }); + }, + + /** 정답 공개: the music goes on for the reveal (docs/05 정답 공개), then stops. */ + reveal(ms: number): void { + const tk = ++token; + stopLoop(); + timeline = null; + const e = engine; + if (!e || !e.videoId() || e.videoId() === UNLOCK_VIDEO || usePlayer.getState().needsGesture) return; + e.volume(usePlayer.getState().volume); + e.mute(false); + e.play(); + usePlayer.setState({ playing: true, loading: false }); + setTimeout(() => { + if (tk !== token) return; + e.pause(); + usePlayer.setState({ playing: false }); + }, ms); + }, + + stop(): void { + player.pause(); + usePlayer.setState({ clip: null, pos: 0 }); + }, + + setVolume(v: number): void { + const vol = Math.max(0, Math.min(100, Math.round(v))); + usePlayer.setState({ volume: vol }); + try { + localStorage.setItem(VOLUME_KEY, String(vol)); + } catch { + /* private mode */ + } + engine?.volume(vol); + }, + + time(): number { + return engine?.time() ?? 0; + }, +}; diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index 2d74ac1..b19cf64 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -2,8 +2,9 @@ * One WebSocket per tab (docs/01): reconnects with backoff, re-joins the room, keeps the server clock offset (docs/12 Q1). */ import { create } from 'zustand'; -import type { ChatLine, RoomView, ServerMessage } from '@mq/shared/lite'; +import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite'; import { toast } from '../store/toast'; +import { player } from './player'; type Status = 'idle' | 'connecting' | 'open' | 'reconnecting'; @@ -21,6 +22,12 @@ interface RoomState { chat: ChatLine[]; /** My lines not confirmed by the server yet: always drawn at the bottom (docs/06 지연 없는 전송). */ pending: { n: string; text: string }[]; + /** The running game (docs/05), null in the waiting room. */ + game: GameView | null; + /** Who is typing (docs/06 입력 중). */ + typing: string[]; + /** Last 퀴즈 저장 result. */ + saved: { id: number; name: string } | null; } const CHAT_KEEP = 200; @@ -28,7 +35,7 @@ const CHAT_KEEP = 200; const LAST_ROOM_KEY = 'mq:lastRoom'; export const ROOM_GONE_TEXT = '서버가 업데이트되면서 방이 닫혔어요. 방을 새로 만들어 주세요.'; -export const useRoom = create(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [] })); +export const useRoom = create(() => ({ status: 'idle', code: null, room: null, offset: 0, rtt: null, joinError: null, left: null, chat: [], pending: [], game: null, typing: [], saved: null })); let ws: WebSocket | null = null; let retry = 0; @@ -37,6 +44,7 @@ let pingTimer: ReturnType | null = null; /** A join is on its way: the next error is the join's answer. */ let joining = false; let nonce = 0; +let myId = ''; function lastRoom(): string | null { try { @@ -70,6 +78,7 @@ function syncClock(): void { function onMessage(m: ServerMessage): void { switch (m.t) { case 'welcome': { + myId = m.userId; useRoom.setState({ status: 'open', offset: m.serverNow - Date.now() }); retry = 0; syncClock(); @@ -99,13 +108,40 @@ function onMessage(m: ServerMessage): void { case 'left': if (m.code === useRoom.getState().code) { setLastRoom(null); - useRoom.setState({ room: null, left: m.reason, chat: [], pending: [] }); + player.stop(); + useRoom.setState({ room: null, left: m.reason, chat: [], pending: [], game: null, typing: [] }); } return; case 'chatlog': // (Re)joined: the server's log is the truth; unconfirmed lines from before a drop are gone. if (m.code === useRoom.getState().code) useRoom.setState({ chat: m.lines.slice(-CHAT_KEEP), pending: [] }); return; + case 'game': { + if (m.code !== useRoom.getState().code) return; + const prev = useRoom.getState().game; + const g = m.game; + if (!g || g.phase === 'result') player.stop(); + else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150)); + useRoom.setState({ game: g }); + return; + } + case 'prepare': + if (m.code === useRoom.getState().code) void player.prepare(m.n, m.videoId, m.startSec, m.endSec); + return; + case 'play': + if (m.code === useRoom.getState().code) player.play(m.n, m.startAt, m.atSec, m.endSec); + return; + case 'pause': + if (m.code === useRoom.getState().code) player.pause(); + return; + case 'typing': + if (m.code === useRoom.getState().code) useRoom.setState({ typing: m.ids }); + return; + case 'saved': + useRoom.setState({ saved: { id: m.id, name: m.name } }); + toast(`"${m.name}"(으)로 저장했어요.`); + return; + case 'answer': case 'chat': if (m.code === useRoom.getState().code) { const st = useRoom.getState(); @@ -166,14 +202,15 @@ export const socket = { join(code: string, pw?: string): void { password = pw; const st = useRoom.getState(); - useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [] }) }); + useRoom.setState({ code, room: null, joinError: null, left: null, ...(st.code === code ? {} : { chat: [], pending: [], game: null, typing: [] }) }); socket.start(); sendJoin(code); }, leave(): void { send({ t: 'leave' }); setLastRoom(null); - useRoom.setState({ code: null, room: null, chat: [], pending: [] }); + player.stop(); + useRoom.setState({ code: null, room: null, chat: [], pending: [], game: null, typing: [] }); }, chat(text: string): void { const n = `${Date.now().toString(36)}${(nonce++).toString(36)}`; @@ -185,3 +222,5 @@ export const socket = { /** Server clock (ms) for countdowns and synced playback. */ export const serverNow = () => Date.now() + useRoom.getState().offset; + +player.setup((n, ev, code) => send({ t: 'audio', n, ev, code }), serverNow); diff --git a/apps/web/src/pages/GameScreen.tsx b/apps/web/src/pages/GameScreen.tsx new file mode 100644 index 0000000..b9600aa --- /dev/null +++ b/apps/web/src/pages/GameScreen.tsx @@ -0,0 +1,395 @@ +/** + * 게임 화면 (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') => send({ t: 'vote', kind }); + 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' ? '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', 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.level} +
+ {voteBtn('hint', '💡', '힌트', 'Ctrl+I')} + {voteBtn('skip', '⏭', '스킵', 'Ctrl+K')} + {listening && voteBtn('replay', '🔁', '다시듣기', 'Ctrl+R')} + {listening && ( + + )} + {isHost && ( + <> + + + + )} +
+
+ +
+
+ {reveal ? ( + + ) : ( + <> + {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 }: { item: GameHistoryItem }) { + return ( +
+ {item.videoId ? :
} +
+
{item.winner ? `🎉 ${item.winner}님 정답! · ${secs(item.ms)}` : item.how === 'skip' ? '⏭ 스킵 · 정답자 없음' : '⌛ 시간 초과 · 정답자 없음'}
+
+ {item.title} - {item.artist} +
+
+ {[item.year, ...item.genres].filter(Boolean).join(' · ')} +
+
+
+ ); +} + +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="퀴즈 이름" /> + +
+
+ )} +
+ ); +} diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index b16b097..594b90b 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -1,6 +1,6 @@ /** * 대기실 /r/:code (docs/03, docs/04): players, live "조건에 맞는 곡 N곡", settings (host edits, everyone sees it at once). - * Games start in stage 5: the start button is shown but disabled until then. + * While a game runs the same page shows the game screen (GameScreen). */ import { useEffect, useState } from 'react'; import { Link, useNavigate, useParams } from 'react-router'; @@ -9,10 +9,12 @@ import { apiCall } from '../net/api'; import { socket, useRoom } from '../net/socket'; import { useSession } from '../store/session'; import { toast } from '../store/toast'; -import { Avatar, ConfirmSheet } from '../components/ui'; +import { Avatar, ConfirmSheet, Sheet } from '../components/ui'; import { LoginBox } from '../components/LoginBox'; import { RoomSettings, type CatalogMeta } from '../components/RoomSettings'; import { ChatPanel } from '../components/ChatPanel'; +import { player, usePlayer } from '../net/player'; +import { GameScreen } from './GameScreen'; const LEFT_TEXT: Record = { kicked: '방장이 방에서 내보냈어요.', @@ -25,17 +27,29 @@ export default function RoomPage() { const { code = '' } = useParams(); const me = useSession((s) => s.me); const nav = useNavigate(); - const { room, joinError, left, status, chat, pending } = useRoom(); + const { room, joinError, left, status, chat, pending, game, typing } = useRoom(); + const unlocked = usePlayer((s) => s.unlocked); + const [confirmStart, setConfirmStart] = useState(false); + const [loadOpen, setLoadOpen] = useState(false); const [meta, setMeta] = useState(null); const [pw, setPw] = useState(''); const [confirmLeave, setConfirmLeave] = useState(false); useEffect(() => { void apiCall('GET', '/api/catalog/meta').then(setMeta).catch(() => {}); + // The YouTube player loads while people wait, so the entry click can turn the sound on at once (docs/12 Q1). + player.warm(); }, []); useEffect(() => { if (!me || !/^\d{6}$/.test(code)) return; socket.join(code); + // Going anywhere else in the app (← 방 목록, logo, browser back) leaves the room, so an empty room closes at once. + // Checked a tick later: React StrictMode re-mounts on the same path, and a refresh keeps the 60s place instead. + return () => { + setTimeout(() => { + if (location.pathname !== `/r/${code}` && useRoom.getState().code === code) socket.leave(); + }, 0); + }; }, [me, code]); useEffect(() => { if (left && left !== 'leave') { @@ -85,6 +99,8 @@ export default function RoomPage() { const link = `${location.origin}/r/${room.code}`; const needArtist = c.mode === 'artist' && c.artistIds.length === 0; const short = c.count !== 0 && room.pool.playable < c.count; + const start = () => (short && room.pool.playable > 0 ? setConfirmStart(true) : send({ t: 'start' })); + const playing = room.status === 'playing' && !!game; return ( <> @@ -109,12 +125,15 @@ export default function RoomPage() { 링크 복사
- {room.status === 'lobby' ? '대기 중' : '게임 중'} + {room.status === 'lobby' ? '대기 중' : '게임 중'} 참가 {room.players.length}명 · 제한 없음
+ {playing ? ( + + ) : (
@@ -172,7 +191,7 @@ export default function RoomPage() { {!needArtist && room.pool.playable === 0 && room.pool.total === 0 &&

이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.

}
{isHost ? ( - ) : ( @@ -181,8 +200,30 @@ export default function RoomPage() { )}
- socket.chat(t)} /> -

게임 진행(노래 재생·채팅 정답)은 다음 업데이트에서 열려요. 지금은 방을 만들고 설정을 맞추면서 대화할 수 있어요.

+ {c.mode !== 'lyrics' && !unlocked && ( +
+ 🔊 노래가 들리도록 게임 전에 한 번 눌러 주세요. 브라우저가 소리를 막을 수 있어요. + +
+ )} + {isHost && ( +
+ +
+ )} + socket.chat(t)} + onTyping={(on) => send({ t: 'typing', on })} + typing={typing.filter((id) => id !== me.id).map((id) => room.players.find((x) => x.id === id)?.nickname ?? '?')} + /> send({ t: 'password', value })} /> + )} + {confirmStart && ( + send({ t: 'start' })} + onClose={() => setConfirmStart(false)} + /> + )} + {loadOpen && setLoadOpen(false)} />} {confirmLeave && ( void }) { + const [list, setList] = useState(null); + const refresh = () => + apiCall<{ quizzes: SavedQuiz[] }>('GET', '/api/quizzes') + .then((r) => setList(r.quizzes)) + .catch(() => setList([])); + useEffect(() => { + void refresh(); + }, []); + return ( + +

퀴즈 불러오기

+

불러오면 저장할 때의 설정과 점수가 돌아오고, 시작하면 이미 나온 곡은 빼고 이어서 나와요. (계정당 20개)

+ {list === null ? ( +

불러오는 중…

+ ) : list.length === 0 ? ( +

저장한 퀴즈가 없어요. 게임이 끝난 뒤 결과 화면에서 저장할 수 있어요.

+ ) : ( +
    + {list.map((q) => ( +
  • +
    + {q.name} +
    + {q.questions}문제 · {q.players}명 · {new Date(q.updatedAt).toLocaleString('ko-KR', { dateStyle: 'short', timeStyle: 'short' })} +
    +
    + + +
  • + ))} +
+ )} +
+ ); +} + function JoinError({ text }: { text: string }) { return (
diff --git a/apps/web/src/pages/admin/AdminApp.tsx b/apps/web/src/pages/admin/AdminApp.tsx index 9e532b7..e8eb07f 100644 --- a/apps/web/src/pages/admin/AdminApp.tsx +++ b/apps/web/src/pages/admin/AdminApp.tsx @@ -159,6 +159,7 @@ interface Site { chatFloodGuard: boolean; chatRatePerSec: number; chatBurst: number; + questionLimitSec: number; } function SiteSettings() { @@ -206,6 +207,11 @@ function SiteSettings() { 금칙어 (쉼표로 구분, 닉네임·채팅에 적용)