From 666c236a8e28e9bf799d4b1f8f183f8daa8898df Mon Sep 17 00:00:00 2001 From: EJClaw Date: Fri, 23 Oct 2026 21:02:43 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9D=B4=EC=A7=80=EC=84=A0=EB=8B=A4=20?= =?UTF-8?q?=EB=AA=A8=EB=93=9C:=20=EC=A1=B0=ED=9A=8C=EC=88=98=EA=B0=80=20?= =?UTF-8?q?=EB=8D=94=20=EB=86=92=EC=9D=80=20=EA=B3=A1=20=EA=B3=A0=EB=A5=B4?= =?UTF-8?q?=EA=B8=B0.=20=EC=9D=B4=EC=A7=80=EC=84=A0=EB=8B=A4=20=ED=80=B4?= =?UTF-8?q?=EC=A6=88=EB=8A=94=20=EC=A1=B0=ED=9A=8C=EC=88=98=EA=B0=80=20?= =?UTF-8?q?=EB=93=A0=20=ED=8C=8C=EC=9D=BC=EB=A1=9C=20=EB=A7=8C=EB=93=A4?= =?UTF-8?q?=EA=B3=A0(custom=5Fquizzes.kind=3D'duel',=20custom=5Fquiz=5Fite?= =?UTF-8?q?ms.views,=20013=20=EB=A7=88=EC=9D=B4=EA=B7=B8=EB=A0=88=EC=9D=B4?= =?UTF-8?q?=EC=85=98;=201,234,567=C2=B7123=EB=A7=8C=C2=B71.2=EC=96=B5?= =?UTF-8?q?=EB=8F=84=20=EC=9D=BD=EC=9D=8C,=20=EC=A1=B0=ED=9A=8C=EC=88=98?= =?UTF-8?q?=20=EC=97=86=EB=8A=94=20=EC=A4=84=EC=9D=80=20=EB=B9=A0=EC=A7=90?= =?UTF-8?q?)=20=EC=9D=B4=EC=A7=80=EC=84=A0=EB=8B=A4=EC=97=90=EC=84=9C?= =?UTF-8?q?=EB=A7=8C,=20=EC=9D=BC=EB=B0=98=20=ED=80=B4=EC=A6=88=EB=8A=94?= =?UTF-8?q?=20=EB=93=A3=EA=B3=A0=EB=A7=9E=EC=B6=94=EA=B8=B0=EC=97=90?= =?UTF-8?q?=EC=84=9C=EB=A7=8C=20=EC=93=B4=EB=8B=A4.=20=EC=84=9C=EB=B2=84?= =?UTF-8?q?=20game/duel.ts:=20=EB=AC=B8=EC=A0=9C=EB=A7=88=EB=8B=A4=20A/B?= =?UTF-8?q?=20=EC=B9=B4=EB=93=9C,=20=EC=B9=B4=EB=93=9C=EB=A5=BC=20?= =?UTF-8?q?=EB=88=84=EB=A5=B4=EB=A9=B4=20=EA=B3=A0=EB=A5=B8=20=EA=B2=83(?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=20=EC=A0=84=EA=B9=8C=EC=A7=80=20=EB=B0=94?= =?UTF-8?q?=EA=BE=B8=EA=B8=B0),=20=EC=8B=9C=EA=B0=84=EC=9D=B4=20=EB=81=9D?= =?UTF-8?q?=EB=82=98=EB=A9=B4=20=EC=A1=B0=ED=9A=8C=EC=88=98=20=EA=B3=B5?= =?UTF-8?q?=EA=B0=9C=C2=B7=EB=86=92=EC=9D=80=20=EC=AA=BD=201=EC=A0=90?= =?UTF-8?q?=C2=B7=EC=97=AD=EB=B0=B0(=ED=98=BC=EC=9E=90=20=EB=A7=9E?= =?UTF-8?q?=ED=9E=88=EA=B3=A0=20=EB=B0=98=EB=8C=80=EC=AA=BD=202=EB=AA=85?= =?UTF-8?q?=20=EC=9D=B4=EC=83=81)=202=EC=A0=90=C2=B7=EA=B0=99=EC=9C=BC?= =?UTF-8?q?=EB=A9=B4=20=EB=91=98=20=EB=8B=A4=20=EC=A0=95=EB=8B=B5,=20?= =?UTF-8?q?=EB=A7=A4=EB=B2=88=20=EC=83=88=20=EB=91=90=20=EA=B3=A1/?= =?UTF-8?q?=EC=97=B0=EC=86=8D(=EC=9D=B4=EA=B8=B4=20=EA=B3=A1=EC=9D=B4=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=EC=88=98=EB=A5=BC=20=EB=B3=B4=EC=9D=B8=20?= =?UTF-8?q?=EC=B1=84=20A=EB=A1=9C=20=EB=82=A8=EC=9D=8C).=20=ED=99=94?= =?UTF-8?q?=EB=A9=B4=20DuelScreen:=20=EA=B3=A0=EB=A5=B8=20=EC=82=AC?= =?UTF-8?q?=EB=9E=8C=20=ED=94=84=EB=A1=9C=ED=95=84=EC=9D=B4=20=EC=B9=B4?= =?UTF-8?q?=EB=93=9C=20=EB=B0=91=EC=97=90,=20=EC=B9=B4=EB=93=9C=EB=A7=88?= =?UTF-8?q?=EB=8B=A4=20=EC=88=A8=EC=9D=80=20=ED=94=8C=EB=A0=88=EC=9D=B4?= =?UTF-8?q?=EC=96=B4(net/duel-player.ts)=EB=A1=9C=20=EA=B0=81=EC=9E=90=20?= =?UTF-8?q?=EB=93=A3=EA=B3=A0=20=EB=8B=A4=EC=8B=9C=20=EB=88=84=EB=A5=B4?= =?UTF-8?q?=EB=A9=B4=20=EB=A9=88=EC=B6=98=20=EA=B3=B3=EB=B6=80=ED=84=B0=20?= =?UTF-8?q?=EC=9D=B4=EC=96=B4=EC=84=9C.=20=EB=B0=A9=20=EC=84=A4=EC=A0=95?= =?UTF-8?q?=20=EC=9D=B4=EC=A7=80=EC=84=A0=EB=8B=A4(=EC=A0=9C=ED=95=9C=20?= =?UTF-8?q?=EC=8B=9C=EA=B0=84=20=EA=B8=B0=EB=B3=B8=2030=EC=B4=88=C2=B7?= =?UTF-8?q?=EC=A7=84=ED=96=89=20=EB=B0=A9=EC=8B=9D=C2=B7=EC=9E=AC=EC=83=9D?= =?UTF-8?q?=EC=9C=84=EC=B9=98=C2=B7=EB=AC=B8=EC=A0=9C=20=EC=88=98,=20?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=EC=84=A0=EB=8B=A4=20=ED=80=B4=EC=A6=88?= =?UTF-8?q?=EB=A7=8C=20=EB=AA=A9=EB=A1=9D=EC=97=90),=20=EA=B2=B0=EA=B3=BC?= =?UTF-8?q?=20=ED=99=94=EB=A9=B4=20=EC=97=AD=EB=B0=B0=20=EC=84=B1=EA=B3=B5?= =?UTF-8?q?=20=EC=88=98.=20=EA=B4=80=EB=A6=AC=EC=9E=90=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=EB=A1=9C=20=EB=A7=8C=EB=93=A4=EA=B8=B0=20=EC=A2=85?= =?UTF-8?q?=EB=A5=98=20=EC=84=A0=ED=83=9D(=EC=A1=B0=ED=9A=8C=EC=88=98=20?= =?UTF-8?q?=EC=97=B4=EC=9D=B4=20=EC=9E=88=EC=9C=BC=EB=A9=B4=20=EC=9D=B4?= =?UTF-8?q?=EC=A7=80=EC=84=A0=EB=8B=A4),=20=EC=A1=B0=ED=9A=8C=EC=88=98=20?= =?UTF-8?q?=ED=8E=B8=EC=A7=91=C2=B7=EB=82=B4=EB=B3=B4=EB=82=B4=EA=B8=B0?= =?UTF-8?q?=C2=B7=EB=B9=88=20=EC=96=91=EC=8B=9D.=20=ED=8F=B0=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=ED=8C=90=20=EA=B0=80=EB=A1=9C=20=EC=8A=A4=ED=81=AC?= =?UTF-8?q?=EB=A1=A4=20=ED=82=A4=EB=B3=B4=EB=93=9C=20=EC=A0=91=EA=B7=BC(ax?= =?UTF-8?q?e).=20=EC=84=9C=EB=B2=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20146?= =?UTF-8?q?=EA=B0=9C,=20e2e=20duel(=EC=8B=A4=EC=A0=9C=20=EC=9C=A0=ED=8A=9C?= =?UTF-8?q?=EB=B8=8C=20=EC=9D=B4=EC=96=B4=20=EB=93=A3=EA=B8=B0=20=ED=8F=AC?= =?UTF-8?q?=ED=95=A8)=C2=B7game=C2=B7quiz=C2=B7admin=C2=B7rooms=C2=B7login?= =?UTF-8?q?=C2=B7a11y=20=ED=86=B5=EA=B3=BC?= 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/db/migrations/013_duel.sql | 4 + apps/server/src/duel.test.ts | 164 ++++++++++ apps/server/src/game/duel.ts | 355 +++++++++++++++++++++ apps/server/src/game/engine.ts | 2 + apps/server/src/http/admin-quizzes.ts | 13 +- apps/server/src/http/app.ts | 2 +- apps/server/src/quizzes/store.ts | 37 ++- apps/server/src/rooms/manager.ts | 31 +- apps/server/src/ws/gateway.ts | 2 + apps/web/src/components/ChatPanel.tsx | 6 +- apps/web/src/components/RoomSettings.tsx | 116 +++++-- apps/web/src/net/duel-player.ts | 162 ++++++++++ apps/web/src/net/player.ts | 9 +- apps/web/src/net/socket.ts | 7 +- apps/web/src/pages/DuelScreen.tsx | 251 +++++++++++++++ apps/web/src/pages/GameScreen.tsx | 35 +- apps/web/src/pages/RoomPage.tsx | 18 +- apps/web/src/pages/admin/QuizFile.tsx | 88 +++-- apps/web/src/pages/admin/QuizzesPage.tsx | 109 +++++-- apps/web/src/styles/global.css | 31 ++ docs/04-room-settings.md | 6 + docs/10-roadmap.md | 1 + docs/12-decisions.md | 8 + e2e/duel.e2e.ts | 253 +++++++++++++++ package.json | 2 +- packages/shared/src/custom-quiz-schema.ts | 8 +- packages/shared/src/custom-quiz.ts | 8 +- packages/shared/src/lite.ts | 2 +- packages/shared/src/protocol.ts | 40 +++ packages/shared/src/quiz-file.test.ts | 46 ++- packages/shared/src/quiz-file.ts | 73 ++++- packages/shared/src/room-config-schema.ts | 8 +- packages/shared/src/room-config.ts | 28 +- 33 files changed, 1789 insertions(+), 136 deletions(-) create mode 100644 apps/server/src/db/migrations/013_duel.sql create mode 100644 apps/server/src/duel.test.ts create mode 100644 apps/server/src/game/duel.ts create mode 100644 apps/web/src/net/duel-player.ts create mode 100644 apps/web/src/pages/DuelScreen.tsx create mode 100644 e2e/duel.e2e.ts diff --git a/apps/server/src/db/migrations/013_duel.sql b/apps/server/src/db/migrations/013_duel.sql new file mode 100644 index 0000000..0b67a61 --- /dev/null +++ b/apps/server/src/db/migrations/013_duel.sql @@ -0,0 +1,4 @@ +-- 이지선다: a quiz is either 일반 (듣고맞추기) or 이지선다 (조회수가 더 높은 곡 고르기), and 이지선다 songs carry the view +-- count written in the file. +ALTER TABLE custom_quizzes ADD COLUMN kind TEXT NOT NULL DEFAULT 'normal' CHECK (kind IN ('normal','duel')); +ALTER TABLE custom_quiz_items ADD COLUMN views INTEGER; diff --git a/apps/server/src/duel.test.ts b/apps/server/src/duel.test.ts new file mode 100644 index 0000000..1259176 --- /dev/null +++ b/apps/server/src/duel.test.ts @@ -0,0 +1,164 @@ +/** 이지선다: points (역배), quiz kinds kept apart, a game in both 진행 방식 (매번 새 두 곡 / 연속). */ +import { afterEach, expect, test } from 'bun:test'; +import type { DuelSide, GameView, ServerMessage } from '@mq/shared'; +import { duelGains, duelWinner } from './game/duel'; +import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest } from './test-utils'; + +type Msg = Extract; +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())); + +test('points: everyone right gets 1; 역배 (alone right against 2 or more) gets 2; equal views = both right', () => { + const picks = (xs: [string, DuelSide][]) => new Map(xs); + const pts = (m: Map) => Object.fromEntries([...m].map(([id, g]) => [id, g.points])); + // 4:1, the one is right + expect(pts(duelGains(picks([['a', 'b'], ['b', 'a'], ['c', 'a'], ['d', 'a'], ['e', 'a']]), 'b'))).toEqual({ a: 2 }); + // 4:1, the four are right + expect(pts(duelGains(picks([['a', 'b'], ['b', 'a'], ['c', 'a'], ['d', 'a'], ['e', 'a']]), 'a'))).toEqual({ b: 1, c: 1, d: 1, e: 1 }); + // 1:1 and 3:2: no 역배 + expect(pts(duelGains(picks([['a', 'a'], ['b', 'b']]), 'a'))).toEqual({ a: 1 }); + expect(pts(duelGains(picks([['a', 'a'], ['b', 'a'], ['c', 'b'], ['d', 'b'], ['e', 'b']]), 'a'))).toEqual({ a: 1, b: 1 }); + // alone, nobody else picked: 1 + expect(pts(duelGains(picks([['a', 'a']]), 'a'))).toEqual({ a: 1 }); + // equal views: whoever picked is right + expect(pts(duelGains(picks([['a', 'a'], ['b', 'b'], ['c', 'b']]), 'both'))).toEqual({ a: 1, b: 1, c: 1 }); + expect(duelGains(picks([['a', 'a'], ['b', 'b'], ['c', 'b']]), 'a').get('a')).toEqual({ points: 2, reverse: true }); + expect([duelWinner(5, 3), duelWinner(3, 5), duelWinner(4, 4)]).toEqual(['a', 'b', 'both']); +}); + +const VIEWS: Record = { vvvvvvvvv01: 1000, vvvvvvvvv02: 5000, vvvvvvvvv03: 300, vvvvvvvvv04: 90000 }; +const duelItem = (videoId: string) => ({ songId: null, videoId, title: `곡${videoId.slice(-2)}`, artist: '가수', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: VIEWS[videoId] }); + +async function setup() { + s = boot({ gameTiming: { countdownMs: 40, revealMs: 120, resumeLeadMs: 30, clipGraceMs: 150, lateMs: 150, tickMs: 20, limitMs: 400 }, discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' }); + const sa = (await discordLogin(s.base, TEST_SUPERADMINS[0])).cookie!; + const file = (body: Record) => api(s.base, '/api/admin/quizzes/file', { method: 'POST', cookie: sa, body: JSON.stringify(body) }); + // views are required for an 이지선다 quiz + expect((await file({ name: 'x', kind: 'duel', items: [{ ...duelItem('vvvvvvvvv01'), views: null }, duelItem('vvvvvvvvv02')] })).res.status).toBe(400); + const duel = await file({ name: '조회수 대결', kind: 'duel', items: Object.keys(VIEWS).map(duelItem) }); + expect(duel.res.status).toBe(200); + const normal = await file({ name: '일반 퀴즈', items: [{ ...duelItem('nnnnnnnnn01'), views: 5 }] }); + const detail = (await api(s.base, `/api/admin/quizzes/${duel.body.id}`, { cookie: sa })).body.quiz; + expect(detail.kind).toBe('duel'); + expect(detail.items.map((i: { views: number }) => i.views)).toEqual([1000, 5000, 300, 90000]); + // a 일반 퀴즈 file keeps no views + expect((await api(s.base, `/api/admin/quizzes/${normal.body.id}`, { cookie: sa })).body.quiz.items[0].views).toBeNull(); + // each kind is listed only for its own mode + const list = async (kind: string) => (await api(s.base, `/api/made-quizzes?kind=${kind}`, { cookie: sa })).body.quizzes.map((q: { name: string }) => q.name); + expect(await list('duel')).toEqual(['조회수 대결']); + expect(await list('normal')).toEqual(['일반 퀴즈']); + return { sa, duelId: duel.body.id as number, normalId: normal.body.id as number }; +} + +async function room(host: string, players: string[]) { + const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: host, body: '{}' })).body.code; + const cls = await Promise.all([host, ...players].map((c) => new Client(s.base, c).connect())); + for (const cl of cls) { + cl.send({ t: 'join', code }); + await cl.waitFor((m) => m.t === 'room'); + } + return { code, cls }; +} + +const gameOf = (m: ServerMessage) => (m.t === 'game' ? m.game : null); + +test('quiz kinds: picking an 이지선다 퀴즈 makes the room 이지선다; another mode drops it; no quiz, no start', async () => { + const { sa, duelId, normalId } = await setup(); + const { cls } = await room(sa, []); + const host = cls[0]!; + host.send({ t: 'config', patch: { mode: 'duel' } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.mode === 'duel'); + host.send({ t: 'start' }); + await host.waitFor((m) => m.t === 'error' && m.message.includes('이지선다 퀴즈를 골라')); + host.send({ t: 'config', patch: { quizId: duelId } }); + const r = (await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === duelId)) as Msg<'room'>; + expect(r.room.config).toMatchObject({ mode: 'duel', quizName: '조회수 대결', duelSec: 30, duelFlow: 'pairs' }); + expect(r.room.pool.playable).toBe(4); + // back to 듣고맞추기: the 이지선다 퀴즈 does not fit any more + host.send({ t: 'config', patch: { mode: 'listen' } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.mode === 'listen' && m.room.config.quizId === null); + // a 일반 퀴즈 is played as 듣고맞추기, switching to 이지선다 drops it + host.send({ t: 'config', patch: { quizId: normalId } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === normalId && m.room.config.mode === 'listen'); + host.send({ t: 'config', patch: { mode: 'duel' } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.mode === 'duel' && m.room.config.quizId === null); + host.send({ t: 'config', patch: { duelSec: 15, duelFlow: 'chain' } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.duelSec === 15 && m.room.config.duelFlow === 'chain'); + host.close(); +}); + +test('매번 새 두 곡: picks show under the cards and can change, views come at the end, 역배 gets 2 points', async () => { + const { sa, duelId } = await setup(); + const g1 = await guest(s.base, '손님1'); + const g2 = await guest(s.base, '손님2'); + const { cls } = await room(sa, [g1.cookie, g2.cookie]); + const [host, p1, p2] = cls as [Client, Client, Client]; + host.send({ t: 'config', patch: { quizId: duelId } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === duelId); + host.send({ t: 'start' }); + const q1 = gameOf(await host.waitFor((m) => gameOf(m)?.n === 1 && gameOf(m)?.phase === 'play'))!; + expect(q1.total).toBe(2); + const cards = q1.duel!.cards; + expect(cards.map((c) => c.side)).toEqual(['a', 'b']); + expect(cards.every((c) => c.views === null && c.picks.length === 0)).toBe(true); + const high: DuelSide = VIEWS[cards[0]!.videoId]! > VIEWS[cards[1]!.videoId]! ? 'a' : 'b'; + const low: DuelSide = high === 'a' ? 'b' : 'a'; + // the host first goes with the others, then changes to the right card alone + host.send({ t: 'pick', n: 1, side: low }); + p1.send({ t: 'pick', n: 1, side: low }); + p2.send({ t: 'pick', n: 1, side: low }); + await host.waitFor((m) => gameOf(m)?.duel?.cards.find((c) => c.side === low)?.picks.length === 3); + host.send({ t: 'pick', n: 1, side: high }); + const moved = gameOf(await host.waitFor((m) => gameOf(m)?.duel?.cards.find((c) => c.side === high)?.picks.length === 1))!; + expect(moved.duel!.cards.find((c) => c.side === low)!.picks).toHaveLength(2); + const rev = gameOf(await host.waitFor((m) => gameOf(m)?.phase === 'reveal'))!; + expect(rev.duel!.cards.map((c) => c.views)).toEqual(cards.map((c) => VIEWS[c.videoId]!)); + expect(rev.duel!.result!.winner).toBe(high); + expect(rev.duel!.result!.gains).toHaveLength(1); + expect(rev.duel!.result!.gains[0]).toMatchObject({ points: 2, reverse: true }); + expect(rev.scores[0]).toMatchObject({ score: 2, correct: 1, reverse: 1 }); + expect(rev.history[0]!.duel!.winner).toBe(high); + const answer = (await host.waitFor((m) => m.t === 'answer')) as Msg<'answer'>; + expect(answer.line.text).toContain('역배 성공'); + // question 2: two new songs; nobody picks → nobody gets points; then the results + const q2 = gameOf(await host.waitFor((m) => gameOf(m)?.n === 2 && gameOf(m)?.phase === 'play'))!; + expect(new Set([...cards, ...q2.duel!.cards].map((c) => c.videoId)).size).toBe(4); + // a late tap for question 1 changes nothing + p1.send({ t: 'pick', n: 1, side: 'a' }); + const end = gameOf(await host.waitFor((m) => gameOf(m)?.phase === 'result'))!; + expect(end.history).toHaveLength(2); + expect(end.history[1]!.duel!.gains).toEqual([]); + expect(end.left).toBe(0); + for (const c of cls) c.close(); +}); + +test('연속: the higher song stays as A with its views shown, a new song comes as B', async () => { + const { sa, duelId } = await setup(); + const { cls } = await room(sa, []); + const host = cls[0]!; + host.send({ t: 'config', patch: { quizId: duelId, duelFlow: 'chain' } }); + await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === duelId && m.room.config.duelFlow === 'chain'); + host.send({ t: 'start' }); + const seen: GameView[] = []; + for (let n = 1; n <= 3; n++) { + const q = gameOf(await host.waitFor((m) => gameOf(m)?.n === n && gameOf(m)?.phase === 'play'))!; + seen.push(q); + host.send({ t: 'pick', n, side: 'a' }); + await host.waitFor((m) => gameOf(m)?.n === n && gameOf(m)?.phase === 'reveal'); + } + expect(seen[0]!.total).toBe(3); + expect(seen[0]!.duel!.cards[0]!.views).toBeNull(); + for (let i = 1; i < 3; i++) { + const prev = seen[i - 1]!.duel!.cards; + const stay = VIEWS[prev[0]!.videoId]! >= VIEWS[prev[1]!.videoId]! ? prev[0]! : prev[1]!; + const [a, b] = seen[i]!.duel!.cards; + expect(a!.videoId).toBe(stay.videoId); + expect(a!.views).toBe(VIEWS[stay.videoId]!); + expect(b!.views).toBeNull(); + } + const end = gameOf(await host.waitFor((m) => gameOf(m)?.phase === 'result'))!; + expect(end.history).toHaveLength(3); + host.close(); +}); diff --git a/apps/server/src/game/duel.ts b/apps/server/src/game/duel.ts new file mode 100644 index 0000000..7ddbb99 --- /dev/null +++ b/apps/server/src/game/duel.ts @@ -0,0 +1,355 @@ +/** + * 이지선다 engine (조회수가 더 높은 곡 고르기): the game of a room in mode duel, with an 이지선다 퀴즈. + * + * Every question shows two cards, A and B. Each player plays them on their own screen (no shared timeline): tapping a + * card plays that song and is the pick, and the pick can change until the time is up. Then the card with more views wins + * (equal views: both), everyone on it gets 1 point — 2 points (역배) when exactly one person is right against two or more + * on the other card. Nobody loses points; no pick = 0. + * 진행: 매번 새 두 곡 (pairs) or 연속 (chain: the higher song stays as A with its views shown, a new song comes as B). + */ +import { viewsLabel, voteThreshold, type DuelCard, type DuelResult, type DuelSide, type GameHistoryItem, type GamePhase, type GameView, type QuizItem, type ServerMessage } from '@mq/shared'; +import { clipOf, loudnessGain, orderSongs, quizItemSong } from '../songs/quiz'; +import type { Room } from '../rooms/manager'; +import type { GameTiming } from './engine'; + +/** Who gets what: everyone on the winning card 1 point, or 2 (역배) when alone there against 2 or more. */ +export function duelGains(picks: Map, winner: DuelSide | 'both'): Map { + const right = [...picks].filter(([, s]) => winner === 'both' || s === winner).map(([id]) => id); + const wrong = picks.size - right.length; + const reverse = right.length === 1 && wrong >= 2; + return new Map(right.map((id) => [id, { points: reverse ? 2 : 1, reverse }])); +} + +export function duelWinner(a: number, b: number): DuelSide | 'both' { + return a === b ? 'both' : a > b ? 'a' : 'b'; +} + +/** Song order of an 이지선다 game: the quiz's songs with a view count that this room has not played yet, shuffled. */ +export function pickDuelSongs(room: Room): number[] | string { + const q = room.config.quizId ? room.deps.quizzes.get(room.config.quizId) : null; + if (!room.config.quizId) return '이지선다 퀴즈를 골라 주세요.'; + if (!q) return '고른 퀴즈를 찾을 수 없어요. 다른 퀴즈를 골라 주세요.'; + if (q.kind !== 'duel') return '이지선다에서는 이지선다 퀴즈만 할 수 있어요.'; + const played = new Set(room.quiz.played); + const ids = q.items.filter((i) => i.views !== null && !played.has(i.id!)).map((i) => i.id!); + if (ids.length < 2) return room.quiz.played.length ? '이 퀴즈의 곡을 모두 풀었어요.' : '이지선다에는 조회수가 있는 곡이 2곡 이상 있어야 해요.'; + return orderSongs(ids, new Set(), new Map(), false); +} + +interface Card { + item: QuizItem; + startSec: number; + gain: number; + /** 연속 방식: the song that stayed shows its views during the question. */ + open: boolean; +} + +export class DuelGame { + phase: GamePhase = 'play'; + n = 0; + total: number; + paused: GameView['paused'] = null; + private items: Map; + private cards: [Card, Card] | null = null; + /** Index in `list` of the next song not used yet. */ + private at = 0; + private picks = new Map(); + private result: DuelResult | null = null; + private elapsedMs = 0; + private runningSince: number | null = null; + private limitMs = 30_000; + private nextVotes = new Set(); + history: GameHistoryItem[] = []; + private revealUntil: number | null = null; + private timer: ReturnType | null = null; + readonly gameId = crypto.randomUUID(); + + constructor( + private room: Room, + private list: number[], + private timing: GameTiming, + private now: () => number = Date.now, + ) { + const q = room.deps.quizzes.get(room.config.quizId!); + this.items = new Map((q?.items ?? []).map((i) => [i.id!, i])); + const possible = room.config.duelFlow === 'chain' ? list.length - 1 : Math.floor(list.length / 2); + this.total = room.config.count ? Math.min(room.config.count, possible) : possible; + } + + start(): void { + this.timer = setInterval(() => this.tick(), this.timing.tickMs); + this.room.say(null, `이지선다를 시작해요! ${this.total}문제 · 조회수가 더 높은 곡을 골라 주세요`); + this.nextQuestion(); + } + + stop(): void { + if (this.timer) clearInterval(this.timer); + this.timer = null; + } + + private elapsed(now = this.now()): number { + return this.elapsedMs + (this.runningSince !== null && now > this.runningSince ? now - this.runningSince : 0); + } + + private card(id: number, open = false): Card | null { + const item = this.items.get(id); + if (!item || item.views === null) return null; + const song = quizItemSong(this.room.deps.db, this.room.config.quizId!, id); + return { + item, + startSec: song ? clipOf(song, { ...this.room.config, listenSec: 0 }).startSec : 0, + gain: loudnessGain(song?.loudness ?? null), + open, + }; + } + + /** The next unused song of the list as a card (songs removed from the quiz meanwhile are skipped). */ + private take(): Card | null { + while (this.at < this.list.length) { + const id = this.list[this.at++]!; + const c = this.card(id); + if (c) { + this.room.quiz.played.push(id); + return c; + } + } + return null; + } + + private nextQuestion(): void { + this.n++; + if (this.n > this.total) return this.finish(); + let cards: [Card, Card] | null = null; + const prev = this.cards; + if (this.room.config.duelFlow === 'chain' && prev && this.result) { + // the higher song stays (equal: the one that was A), shown as A with its views + const stay = this.result.winner === 'b' ? prev[1] : prev[0]; + const b = this.take(); + if (b) cards = [{ ...stay, open: true }, b]; + } else { + const a = this.take(); + const b = a && this.take(); + if (a && b) cards = [a, b]; + } + if (!cards) { + this.n--; + return this.finish(); + } + this.cards = cards; + this.picks.clear(); + this.result = null; + this.nextVotes.clear(); + this.revealUntil = null; + this.paused = null; + this.phase = 'play'; + this.elapsedMs = 0; + this.runningSince = this.now(); + this.limitMs = this.timing.limitMs ?? this.room.config.duelSec * 1000; + this.room.say(null, `${this.n}번째 문제`); + this.broadcast(); + } + + /** Time is up: the higher card wins, points go out, the views are shown. */ + private endQuestion(): void { + if (this.phase !== 'play' || !this.cards) return; + const now = this.now(); + this.elapsedMs = this.elapsed(now); + this.runningSince = null; + this.paused = null; + const [a, b] = this.cards; + const winner = duelWinner(a.item.views!, b.item.views!); + const sides = new Map([...this.picks].map(([id, p]) => [id, p.side])); + const gains = duelGains(sides, winner); + for (const [id, g] of gains) { + const sc = this.room.quiz.scores.get(id) ?? { nickname: this.room.nick(id), score: 0, correct: 0, totalMs: 0 }; + sc.nickname = this.room.nick(id); + sc.score += g.points; + sc.correct += 1; + sc.totalMs += this.picks.get(id)!.ms; + sc.reverse = (sc.reverse ?? 0) + (g.reverse ? 1 : 0); + this.room.quiz.scores.set(id, sc); + } + this.result = { winner, gains: [...gains].map(([id, g]) => ({ id, ...g })) }; + const cardOf = (c: Card, side: DuelSide) => ({ side, title: c.item.title, artist: c.item.artist, videoId: c.item.videoId, views: c.item.views! }); + this.history.push({ + n: this.n, + title: `${a.item.title} vs ${b.item.title}`, + artist: '', + year: null, + level: null, + genres: [], + videoId: null, + winnerId: null, + winner: null, + ms: null, + how: 'timeout', + duel: { + cards: [cardOf(a, 'a'), cardOf(b, 'b')], + winner, + gains: this.result.gains.map((g) => ({ ...g, nickname: this.room.nick(g.id) })), + }, + }); + const label = (c: Card) => `${c.item.title}${c.item.artist ? ` - ${c.item.artist}` : ''} (${viewsLabel(c.item.views!)}회)`; + const top = winner === 'both' ? `조회수가 같아요: ${label(a)} = ${label(b)}` : `더 높은 곡: ${label(winner === 'a' ? a : b)}`; + const rev = this.result.gains.find((g) => g.reverse); + const who = gains.size ? `맞힌 사람 ${gains.size}명${rev ? ` · 역배 성공 ${this.room.nick(rev.id)}님 +2점` : ''}` : '맞힌 사람이 없어요'; + this.room.post({ userId: null, text: `⏱ 시간 끝! ${who}`, answer: { text: top, none: gains.size === 0 } }); + this.phase = 'reveal'; + this.revealUntil = now + (this.timing.revealMs ?? this.room.config.revealSec * 1000); + this.broadcast(); + } + + private afterReveal(): void { + if (this.phase !== 'reveal') return; + if (this.n >= this.total) this.finish(); + else this.nextQuestion(); + } + + finish(): void { + if (this.phase === 'result') return; + this.phase = 'result'; + this.runningSince = null; + this.paused = null; + this.stop(); + this.room.say(null, '게임이 끝났어요'); + this.broadcast(); + } + + tick(now = this.now()): void { + if (this.phase === 'reveal') { + if (this.revealUntil !== null && now >= this.revealUntil) this.afterReveal(); + return; + } + if (this.phase === 'play' && this.elapsed(now) >= this.limitMs) this.endQuestion(); + } + + // ------------------------------------------------------------------ inputs + /** Tap on card A or B of question `n`: that is the pick until another tap (the same card again changes nothing). */ + pick(userId: string, n: number, side: DuelSide): string | null { + if (n !== this.n || this.phase !== 'play') return null; // a late tap of the last question: nothing to do + if (!this.room.isOnline(userId)) return '방에 접속해 있지 않아요.'; + if (this.paused) return '방장이 잠시 멈췄어요. 다시 시작하면 고를 수 있어요.'; + if (this.picks.get(userId)?.side === side) return null; + this.picks.set(userId, { side, ms: this.elapsed() }); + this.broadcast(); + return null; + } + + vote(userId: string, kind: 'skip' | 'hint' | 'replay' | 'next'): string | null { + if (kind !== 'next') return '이지선다에는 없는 기능이에요.'; + if (this.phase !== 'reveal') return '결과가 공개된 뒤에 누를 수 있어요.'; + if (this.room.config.nextVotes === 'none') return '이 방은 바로 다음 문제가 꺼져 있어요.'; + if (!this.room.isOnline(userId)) return '방에 접속해 있지 않아요.'; + if (this.nextVotes.has(userId)) this.nextVotes.delete(userId); + else this.nextVotes.add(userId); + this.checkNext(); + if (this.phase === 'reveal') this.broadcast(); + return null; + } + + private needNext(): number | null { + return voteThreshold(this.room.config.nextVotes, this.room.online().length); + } + + private checkNext(): void { + if (this.phase !== 'reveal') return; + for (const id of this.nextVotes) if (!this.room.isOnline(id)) this.nextVotes.delete(id); + const need = this.needNext(); + if (need !== null && this.nextVotes.size >= need) this.afterReveal(); + } + + hostPause(on: boolean): string | null { + if (this.phase !== 'play') return '지금은 멈출 수 없어요.'; + if (on && !this.paused) { + this.elapsedMs = this.elapsed(); + this.runningSince = null; + this.paused = { reason: 'host', who: [] }; + } else if (!on && this.paused) { + this.paused = null; + this.runningSince = this.now(); + } + this.broadcast(); + return null; + } + + onGone(_userId: string): void { + if (this.phase === 'reveal') this.checkNext(); + if (this.phase !== 'result') this.broadcast(); + } + + /** Everyone plays on their own screen: a player who comes back just gets the view. */ + rejoin(_userId: string, _send: (m: ServerMessage) => void): void {} + onAudio(): void {} + judge(): boolean { + return false; + } + exclude(): string | null { + return '이지선다에는 없는 기능이에요.'; + } + + // ------------------------------------------------------------------ view + view(): GameView { + const players = new Map(); + for (const [id] of this.room.players) players.set(id, this.room.isOnline(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 shown = this.phase === 'reveal' || this.phase === 'result'; + const cards: DuelCard[] = (this.cards ?? []).map((c, i) => { + const side: DuelSide = i === 0 ? 'a' : 'b'; + return { + side, + videoId: c.item.videoId, + title: c.item.title, + artist: c.item.artist, + startSec: c.startSec, + gain: c.gain, + views: shown || c.open ? c.item.views : null, + picks: [...this.picks].filter(([, p]) => p.side === side).map(([id]) => id), + }; + }); + const online = this.room.online(); + return { + phase: this.phase, + n: this.n, + total: this.total, + mode: 'duel', + participants: online, + excluded: [], + waiting: [], + paused: this.paused, + startAt: null, + clock: { elapsedMs: this.elapsedMs, runningSince: this.runningSince, limitMs: this.limitMs }, + clipSec: null, + clipOver: false, + hint: null, + hints: [], + hintMore: false, + hintAtSec: null, + lyrics: null, + votes: { skip: [], hint: [], replay: [], next: [...this.nextVotes] }, + need: { skip: null, hint: null, replay: null, next: this.needNext() }, + 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, + reverse: s?.reverse ?? 0, + }; + }) + .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: this.list.length - this.at >= 2 ? this.list.length - this.at : 0, + duel: { flow: this.room.config.duelFlow, cards, result: this.result }, + }; + } + + broadcast(): void { + this.room.send({ t: 'game', code: this.room.code, game: this.view() }); + } +} diff --git a/apps/server/src/game/engine.ts b/apps/server/src/game/engine.ts index ddd392b..21df463 100644 --- a/apps/server/src/game/engine.ts +++ b/apps/server/src/game/engine.ts @@ -34,6 +34,8 @@ export interface Score { score: number; correct: number; totalMs: number; + /** 이지선다: 역배 wins. */ + reverse?: number; } /** What 이어풀기 / 퀴즈 저장 carry over: songs asked so far and scores per account (docs/12 Q8). */ diff --git a/apps/server/src/http/admin-quizzes.ts b/apps/server/src/http/admin-quizzes.ts index aeb740e..f740122 100644 --- a/apps/server/src/http/admin-quizzes.ts +++ b/apps/server/src/http/admin-quizzes.ts @@ -65,18 +65,23 @@ export function mountQuizAdmin(app: Hono, d: QuizAdminDeps, h: { actor: (c: /** 파일로 만들기: a new quiz with the songs read from a file (the browser reads the file; values used as written). */ app.post('/quizzes/file', async (c) => { - const p = z.object({ name: z.string().trim().min(1).max(60), items: QuizSaveSchema.shape.items.min(1) }).safeParse(await h.body(c)); + const p = z + .object({ name: z.string().trim().min(1).max(60), kind: z.enum(['normal', 'duel']).default('normal'), items: QuizSaveSchema.shape.items.min(1) }) + .safeParse(await h.body(c)); if (!p.success) return c.json({ error: `만들 내용이 올바르지 않아요: ${p.error.issues.slice(0, 3).map((i) => i.path.join('.') || i.message).join(', ')}` }, 400); + const duel = p.data.kind === 'duel'; + if (duel && p.data.items.length < 2) return c.json({ error: '이지선다 퀴즈에는 곡이 2곡 이상 있어야 해요.' }, 400); + if (duel && p.data.items.some((it) => it.views === null)) return c.json({ error: '이지선다 퀴즈의 곡에는 모두 조회수가 있어야 해요.' }, 400); const limits = d.limits(); if (limits.maxSongs && p.data.items.length > limits.maxSongs) return c.json({ error: `퀴즈 하나에는 곡을 ${limits.maxSongs}곡까지 넣을 수 있어요.` }, 400); - const id = d.quizzes.create(h.actor(c), p.data.name, limits); + const id = d.quizzes.create(h.actor(c), p.data.name, limits, Date.now(), p.data.kind); if (typeof id === 'string') return c.json({ error: id }, 400); - const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true })); + const items = p.data.items.map((it) => ({ ...it, id: undefined, songId: null, fromFile: true, ...(duel ? {} : { views: null }) })); // songs with their own hints: hints come by vote unless the maker changes it in 설정 const settings = { ...DEFAULT_QUIZ_SETTINGS, ...(items.some((it) => it.hints.length) ? { hint: 'manual' as const } : {}) }; const saved = d.quizzes.save(id, { name: p.data.name, description: '', visibility: 'private', settings, items }, limits); if (typeof saved === 'string') return c.json({ error: saved }, 400); - d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name, songs: items.length, from: 'file' }); + d.audit.log(h.actor(c), 'quiz.create', String(id), null, { name: p.data.name, songs: items.length, from: 'file', kind: p.data.kind }); d.onChange?.(); return c.json({ id }); }); diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index ce5216a..52625e3 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -269,7 +269,7 @@ export function createHttpApp(d: HttpDeps) { const u = userOf(c); if (!u) return c.json({ error: '로그인이 필요해요.' }, 401); const q = (c.req.query('q') ?? '').trim().slice(0, 60); - return c.json({ quizzes: d.rooms.quizzes.forRoom(u, d.roles.roleOf(u), q) }); + return c.json({ quizzes: d.rooms.quizzes.forRoom(u, d.roles.roleOf(u), q, c.req.query('kind') === 'duel' ? 'duel' : 'normal') }); }); // ------------------------------------------------------------ saved quizzes (docs/12 Q8) diff --git a/apps/server/src/quizzes/store.ts b/apps/server/src/quizzes/store.ts index 97ffcc9..0562900 100644 --- a/apps/server/src/quizzes/store.ts +++ b/apps/server/src/quizzes/store.ts @@ -3,10 +3,11 @@ * Saving is all at once (the editor saves by hand): name, settings, visibility and the whole song list. */ import type { Database } from 'bun:sqlite'; -import { parseQuizSettings, type QuizDetail, type QuizItem, type QuizSave, type QuizSummary, type QuizVisibility, type Role } from '@mq/shared'; +import { parseQuizSettings, type QuizDetail, type QuizItem, type QuizKind, type QuizSave, type QuizSummary, type QuizVisibility, type Role } from '@mq/shared'; interface QuizRow { id: number; + kind: QuizKind; owner_id: string; owner_name: string | null; name: string; @@ -32,9 +33,12 @@ interface ItemRow { auto: number; start_sec: number | null; highlight_sec: number | null; + views: number | null; } -const SELECT = `SELECT q.id, q.owner_id, u.nickname owner_name, q.name, q.description, q.visibility, q.settings_json, q.plays, q.updated_at, +const ITEM_COLS = 'id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec, views'; + +const SELECT = `SELECT q.id, q.kind, q.owner_id, u.nickname owner_name, q.name, q.description, q.visibility, q.settings_json, q.plays, q.updated_at, (SELECT COUNT(*) FROM custom_quiz_items i WHERE i.quiz_id = q.id) songs FROM custom_quizzes q LEFT JOIN users u ON u.id = q.owner_id`; @@ -46,6 +50,7 @@ export interface QuizLimits { const summary = (r: QuizRow): QuizSummary => ({ id: r.id, + kind: r.kind, name: r.name, description: r.description, visibility: r.visibility, @@ -70,6 +75,7 @@ const item = (r: ItemRow): QuizItem => ({ auto: !!r.auto, startSec: r.start_sec, highlightSec: r.highlight_sec, + views: r.views, }); /** Who may pick a quiz for a room: 비공개 the maker, 일부공개 the maker and admins, 전체공개 everyone. */ @@ -91,16 +97,16 @@ export class CustomQuizzes { .map(summary); } - create(ownerId: string, name: string, limits: QuizLimits, now = Date.now()): number | string { + create(ownerId: string, name: string, limits: QuizLimits, now = Date.now(), kind: QuizKind = 'normal'): number | string { if (limits.maxPerUser) { const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM custom_quizzes WHERE owner_id = ? AND deleted_at IS NULL').get(ownerId)!.n; if (n >= limits.maxPerUser) return `퀴즈는 한 계정에 ${limits.maxPerUser}개까지 만들 수 있어요.`; } return this.db - .query<{ id: number }, [string, string, number, number]>( - "INSERT INTO custom_quizzes (owner_id, name, visibility, settings_json, created_at, updated_at) VALUES (?, ?, 'private', '{}', ?, ?) RETURNING id", + .query<{ id: number }, [string, string, string, number, number]>( + "INSERT INTO custom_quizzes (owner_id, kind, name, visibility, settings_json, created_at, updated_at) VALUES (?, ?, ?, 'private', '{}', ?, ?) RETURNING id", ) - .get(ownerId, name, now, now)!.id; + .get(ownerId, kind, name, now, now)!.id; } row(id: number): QuizRow | null { @@ -116,7 +122,7 @@ export class CustomQuizzes { items(id: number): QuizItem[] { return this.db .query( - 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id', + `SELECT ${ITEM_COLS} FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos, id`, ) .all(id) .map(item); @@ -125,7 +131,7 @@ export class CustomQuizzes { item(quizId: number, itemId: number): QuizItem | null { const r = this.db .query( - 'SELECT id, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec FROM custom_quiz_items WHERE quiz_id = ? AND id = ?', + `SELECT ${ITEM_COLS} FROM custom_quiz_items WHERE quiz_id = ? AND id = ?`, ) .get(quizId, itemId); return r ? item(r) : null; @@ -146,12 +152,12 @@ export class CustomQuizzes { .run(data.name, data.description, data.visibility, JSON.stringify(data.settings), now, id); const keep = new Set(); const ins = this.db.query( - `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO custom_quiz_items (quiz_id, pos, song_id, video_id, title, artist, title_answers, artist_answers, hints, from_file, duration_sec, auto, start_sec, highlight_sec, views) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ); const upd = this.db.query( `UPDATE custom_quiz_items SET pos = ?, song_id = ?, video_id = ?, title = ?, artist = ?, title_answers = ?, artist_answers = ?, hints = ?, from_file = ?, duration_sec = ?, auto = ?, - start_sec = ?, highlight_sec = ? WHERE id = ? AND quiz_id = ?`, + start_sec = ?, highlight_sec = ?, views = ? WHERE id = ? AND quiz_id = ?`, ); const alias = this.db.query("INSERT OR IGNORE INTO song_aliases (song_id, part, alias, source) VALUES (?, ?, ?, 'quiz')"); for (const [pos, it] of data.items.entries()) { @@ -171,6 +177,7 @@ export class CustomQuizzes { it.auto ? 1 : 0, it.auto ? null : it.startSec, it.auto ? null : it.highlightSec, + it.views ?? null, ] as const; if (it.id && existing.has(it.id)) { upd.run(pos, ...args, it.id, id); @@ -191,15 +198,15 @@ export class CustomQuizzes { } /** 방 설정 → 제작된 퀴즈: what this player may pick, not-public ones first (marked), then by plays. */ - forRoom(userId: string, role: Role, q = ''): QuizSummary[] { + forRoom(userId: string, role: Role, q = '', kind: QuizKind = 'normal'): QuizSummary[] { const like = `%${q.replace(/[%_\\]/g, (m) => '\\' + m)}%`; return this.db - .query( - `${SELECT} WHERE q.deleted_at IS NULL AND (q.name LIKE ? ESCAPE '\\' OR q.description LIKE ? ESCAPE '\\') + .query( + `${SELECT} WHERE q.deleted_at IS NULL AND q.kind = ? AND (q.name LIKE ? ESCAPE '\\' OR q.description LIKE ? ESCAPE '\\') AND EXISTS (SELECT 1 FROM custom_quiz_items i WHERE i.quiz_id = q.id) ORDER BY q.visibility = 'public', q.owner_id <> ?, q.plays DESC, q.updated_at DESC LIMIT 500`, ) - .all(like, like, userId) + .all(kind, like, like, userId) .filter((r) => canPlay(r, userId, role)) .map(summary); } diff --git a/apps/server/src/rooms/manager.ts b/apps/server/src/rooms/manager.ts index 65d88d4..2dff2b4 100644 --- a/apps/server/src/rooms/manager.ts +++ b/apps/server/src/rooms/manager.ts @@ -6,6 +6,7 @@ import type { Database } from 'bun:sqlite'; import type { ServerWebSocket } from 'bun'; import { DEFAULT_ROOM_CONFIG, QUIZ_ROOM_KEYS, applyConfigPatch, configSummary, type ChatLine, type Role, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared'; import { DEFAULT_TIMING, Game, newQuiz, pickSongs, type GameTiming, type Quiz } from '../game/engine'; +import { DuelGame, pickDuelSongs } from '../game/duel'; import { SavedQuizzes } from '../game/saved'; import { artistsByIds, countPool } from '../songs/pool'; import type { AudioLinks } from '../songs/audio'; @@ -43,7 +44,7 @@ export class Room { emptySince: number | null = null; chat: ChatLine[] = []; private seq = 0; - game: Game | null = null; + game: Game | DuelGame | 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). */ @@ -65,8 +66,10 @@ export class Room { recount(): void { if (this.config.quizId) { - // 제작된 퀴즈: every song of it - const n = this.deps.db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ?').get(this.config.quizId)!.n; + // 제작된 퀴즈: every song of it (이지선다: the songs that have a view count) + const n = this.deps.db + .query<{ n: number }, [number, number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ? AND (? = 0 OR views IS NOT NULL)') + .get(this.config.quizId, this.config.mode === 'duel' ? 1 : 0)!.n; this.pool = { playable: n, total: n }; } else this.pool = countPool(this.deps.db, this.config); } @@ -345,7 +348,7 @@ export class RoomManager { const { quizName: _, ...p } = patch; let merged: Record = p; // songs asked so far are quiz items or DB songs: switching between them starts over - const switching = p.quizId !== undefined && p.quizId !== room.config.quizId; + let switching = p.quizId !== undefined && p.quizId !== room.config.quizId; if (switching) { if (p.quizId === null) merged = { ...p, quizName: '' }; else { @@ -354,8 +357,13 @@ export class RoomManager { // the quiz's own settings become the room's (except what the site locked); a new quiz starts from its first song const s = this.quizzes.get(q.id)!.settings; const defaults = Object.fromEntries(QUIZ_ROOM_KEYS.filter((k) => !locks.has(k)).map((k) => [k, s[k]])); - merged = { ...defaults, ...p, mode: 'listen', quizName: q.name }; + // 일반 퀴즈 → 듣고맞추기, 이지선다 퀴즈 → 이지선다 + merged = { ...defaults, ...p, mode: q.kind === 'duel' ? 'duel' : 'listen', quizName: q.name }; } + } else if (p.mode !== undefined && room.config.quizId && (p.mode === 'duel') !== (this.quizzes.row(room.config.quizId)?.kind === 'duel')) { + // the other kind of game: the chosen quiz does not fit it any more + merged = { ...p, quizId: null, quizName: '' }; + switching = true; } const next = applyConfigPatch(room.config, merged); if (typeof next === 'string') return next; @@ -430,12 +438,14 @@ export class RoomManager { private startGame(room: Room): string | null { if (room.config.mode === 'artist' && !room.config.artistIds.length) return '가수를 1명 이상 골라 주세요.'; - const list = pickSongs(room); + const duel = room.config.mode === 'duel'; + if (!duel && room.config.quizId && this.quizzes.row(room.config.quizId)?.kind === 'duel') return '이지선다 퀴즈는 이지선다 모드에서만 할 수 있어요.'; + const list = duel ? pickDuelSongs(room) : 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.game = duel ? new DuelGame(room, list, this.timing) : new Game(room, list, this.timing); if (room.config.quizId) this.quizzes.countPlay(room.config.quizId); room.broadcast(); room.game.start(); @@ -453,6 +463,13 @@ export class RoomManager { return room.game.vote(ws.data.userId, kind); } + /** 이지선다: card A or B. */ + pick(ws: ServerWebSocket, n: number, side: 'a' | 'b'): string | null { + const g = this.inRoom(ws)?.game; + if (!(g instanceof DuelGame)) return '이지선다 게임 중이 아니에요.'; + return g.pick(ws.data.userId, n, side); + } + /** 입력 중 (docs/06): remembered for 3s, sent at most once a second by flushTyping. */ typing(ws: ServerWebSocket, on: boolean): void { const room = this.inRoom(ws); diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index 7e490d8..6a3c034 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -108,6 +108,8 @@ export class Gateway { return err(rooms.vote(ws, m.kind)); case 'typing': return rooms.typing(ws, m.on); + case 'pick': + return err(rooms.pick(ws, m.n, m.side)); case 'game': return err(rooms.gameAction(ws, m.action)); case 'exclude': diff --git a/apps/web/src/components/ChatPanel.tsx b/apps/web/src/components/ChatPanel.tsx index 81dd94c..053cb30 100644 --- a/apps/web/src/components/ChatPanel.tsx +++ b/apps/web/src/components/ChatPanel.tsx @@ -28,8 +28,10 @@ export const ChatPanel = forwardRef< onTyping?: (on: boolean) => void; typing?: string[]; big?: boolean; + /** Input hint (the game screen: 정답이나 채팅; 이지선다 has no answers to type). */ + placeholder?: string; } ->(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big }, ref) { +>(function ChatPanel({ lines, pending, meId, myName, onSend, onTyping, typing = [], big, placeholder }, ref) { const [text, setText] = useState(''); const [stuck, setStuck] = useState(true); const [unseen, setUnseen] = useState(false); @@ -154,7 +156,7 @@ export const ChatPanel = forwardRef< className="input" value={text} maxLength={CHAT_MAX} - placeholder={big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)'} + placeholder={placeholder ?? (big ? '정답이나 채팅 입력 (Enter)' : '메시지 입력 (Enter)')} aria-label="채팅 입력" autoComplete="off" onChange={(e) => { diff --git a/apps/web/src/components/RoomSettings.tsx b/apps/web/src/components/RoomSettings.tsx index 57c6098..ce58647 100644 --- a/apps/web/src/components/RoomSettings.tsx +++ b/apps/web/src/components/RoomSettings.tsx @@ -5,6 +5,8 @@ import { useEffect, useRef, useState, type ReactNode } from 'react'; import { COUNTS, + DUEL_FLOWS, + DUEL_SECS, HINT_TIMES, LEVELS, LISTEN_SECS, @@ -14,6 +16,7 @@ import { VOTE_RULES, listenLabel, voteLabel, + type QuizKind, type QuizSummary, type RoomConfig, type VoteRule, @@ -244,7 +247,8 @@ export function RoomSettings({ ['테마', 'theme'], ]; const toggleGenre = (id: string) => onPatch({ genres: c.genres.includes(id) ? c.genres.filter((g) => g !== id) : [...c.genres, id] }); - const listening = c.mode !== 'lyrics'; + const duel = c.mode === 'duel'; + const listening = c.mode !== 'lyrics' && !duel; // 제작된 퀴즈 chosen but no quiz picked yet: only on this screen until a quiz is picked const [pickingOwn, setPickingOwn] = useState(false); const picking = pickingProp ?? pickingOwn; @@ -252,8 +256,20 @@ export function RoomSettings({ useEffect(() => { if (c.quizId) setPicking(false); }, [c.quizId]); // eslint-disable-line react-hooks/exhaustive-deps - const source: 'pick' | 'quiz' = c.quizId || picking ? 'quiz' : 'pick'; + const source: 'pick' | 'quiz' = c.quizId || picking || duel ? 'quiz' : 'pick'; const quiz = source === 'quiz'; + const duelMax = c.duelFlow === 'chain' ? Math.max(0, pool.playable - 1) : Math.floor(pool.playable / 2); + // 일반 퀴즈 → 듣고맞추기 only, 이지선다 → 이지선다 퀴즈 only: another mode leaves the chosen quiz (the server drops it) + const pickMode = (mode: RoomConfig['mode']) => { + if (mode === c.mode) return; + if (mode === 'duel') { + setPicking(true); + onPatch({ mode }); + } else if (duel || (quiz && mode !== 'listen')) { + setPicking(false); + onPatch(c.quizId && !duel ? { mode, quizId: null } : { mode }); + } else onPatch({ mode }); + }; return (
@@ -275,7 +291,12 @@ export function RoomSettings({ aria-label="방 이름" /> - {allowQuiz && ( + {allowQuiz && duel && ( +
+ onPatch({ quizId })} /> +
+ )} + {allowQuiz && !duel && (
- {quiz && onPatch({ quizId })} />} + {quiz && onPatch({ quizId })} />}
)}
onPatch({ mode })} - options={MODES.map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))} + disabled={ro} + onChange={pickMode} + options={MODES.filter((m) => allowQuiz || m.id !== 'duel').map((m) => ({ v: m.id, label: `${m.icon} ${m.label}` }))} /> - {quiz &&

제작된 퀴즈는 듣고맞추기로만 할 수 있어요.

} + {quiz && !duel &&

제작된 퀴즈는 듣고맞추기로 해요. 다른 모드를 고르면 직접 선택으로 바뀌어요.

} + {duel &&

두 곡 중 유튜브 조회수가 더 높은 곡을 고르는 모드예요. 카드를 누르면 그 노래가 나오고, 그 카드를 고른 게 돼요.

}
- {listening ? ( + {duel ? ( + <> +
+
제한 시간
+ onPatch({ duelSec })} options={DUEL_SECS.map((v) => ({ v, label: `${v}초` }))} /> +
+
+
진행 방식
+ onPatch({ duelFlow })} options={DUEL_FLOWS.map((f) => ({ v: f.id, label: f.label }))} /> +

+ {c.duelFlow === 'chain' ? '조회수가 더 높은 곡이 조회수를 보여 준 채 남고, 새 곡과 다시 비교해요.' : '문제마다 새로운 두 곡이 나와요.'} +

+
+
+
재생위치
+ onPatch({ startAt })} + options={[ + { v: 'start', label: '처음부터' }, + { v: 'highlight', label: '하이라이트부터' }, + ]} + /> +
+ + ) : listening ? ( <>
듣고맞출시간
@@ -394,8 +443,18 @@ export function RoomSettings({
)} - - {quiz ? ( + + {duel ? ( +
+ onPatch({ count })} + options={COUNTS.map((v) => ({ v, label: v ? String(v) : `전부(${duelMax.toLocaleString()})` }))} + /> +
+ ) : quiz ? (

{c.quizId ? `퀴즈에 든 곡 전부 (${pool.playable.toLocaleString()}문제)` : '퀴즈를 고르면 그 퀴즈의 곡 전부가 나와요'}

@@ -459,14 +518,28 @@ export function PlayRules({ c, ro, listening, + duel = false, onPatch, }: { c: Pick; ro: boolean; listening: boolean; + /** 이지선다: no answers to type, hints, skip or replay — only how long the result stays. */ + duel?: boolean; onPatch: (p: Patch) => void; }) { const vote = (rules: readonly VoteRule[]) => rules.map((v) => ({ v, label: voteLabel(v) })); + const after = ( + <> +
+ onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} /> +
+
+ onPatch({ nextVotes })} options={vote(VOTE_RULES)} /> +
+ + ); + if (duel) return after; return ( <>
@@ -521,12 +594,7 @@ export function PlayRules({ onPatch({ replayVotes })} options={vote(VOTE_RULES)} />
)} -
- onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} /> -
-
- onPatch({ nextVotes })} options={vote(VOTE_RULES)} /> -
+ {after} ); } @@ -534,7 +602,7 @@ export function PlayRules({ const VIS: Record = { private: '비공개', partial: '일부공개' }; /** 제작된 퀴즈 list with a search box; not-public quizzes come first, marked. */ -function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name: string } | null; songs: number; ro: boolean; onPick: (id: number) => void }) { +function QuizPicker({ kind, chosen, songs, ro, onPick }: { kind: QuizKind; chosen: { id: number; name: string } | null; songs: number; ro: boolean; onPick: (id: number) => void }) { const [open, setOpen] = useState(!chosen); const [q, setQ] = useState(''); const [list, setList] = useState(null); @@ -542,12 +610,12 @@ function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name: useEffect(() => { if (!open || ro) return; const t = setTimeout(() => { - apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/made-quizzes?q=${encodeURIComponent(q.trim())}`) + apiCall<{ quizzes: QuizSummary[] }>('GET', `/api/made-quizzes?kind=${kind}&q=${encodeURIComponent(q.trim())}`) .then((r) => (setList(r.quizzes), setError(null))) .catch((e: Error) => setError(e.message)); }, 200); return () => clearTimeout(t); - }, [q, open, ro]); + }, [q, open, ro, kind]); useEffect(() => { if (chosen) setOpen(false); }, [chosen?.id]); // eslint-disable-line react-hooks/exhaustive-deps @@ -571,8 +639,12 @@ function QuizPicker({ chosen, songs, ro, onPick }: { chosen: { id: number; name: <> setQ(e.target.value)} placeholder="퀴즈 이름 검색" aria-label="퀴즈 이름 검색" /> {error && {error}} -
- {list?.length === 0 && {q.trim() ? '검색 결과가 없어요.' : '고를 수 있는 퀴즈가 없어요.'}} +
+ {list?.length === 0 && ( + + {q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'} + + )} {list?.map((x) => ( + )} + + {isHost && ( + <> + + + + )} +
+
+ +
+
+
+
{result ? (result.winner === 'both' ? '조회수가 똑같아요! 둘 다 정답' : `${result.winner === 'a' ? 'A' : 'B'}의 조회수가 더 높아요!`) : '어느 곡의 유튜브 조회수가 더 높을까요?'}
+ {result ? ( +
+ {result.gains.find((g) => g.reverse) ? `⚡ 역배 성공! ${name(result.gains.find((g) => g.reverse)!.id)}님 +2점 · ` : ''} + {game.n >= game.total ? '결과까지' : '다음 문제까지'} {revealLeft}초 +
+ ) : game.paused ? ( +
⏸ 방장이 잠시 멈췄어요
+ ) : ( + <> +
+ +
+
+ 남은 시간 {left}초 · 카드를 누르면 그 노래가 나오고 그 카드를 고른 거예요. 시간 안에는 몇 번이든 바꿀 수 있어요. +
+ + )} +
+
+ {d.cards.map((card) => { + const won = result && (result.winner === 'both' || result.winner === card.side); + return ( + + ); + })} +
+
+ socket.chat(t)} + onTyping={(on) => send({ t: 'typing', on })} + typing={typing.filter((id) => id !== me.id).map(name)} + /> +
+ +
+ {confirmEnd && send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />} + + ); +} diff --git a/apps/web/src/pages/GameScreen.tsx b/apps/web/src/pages/GameScreen.tsx index 1ba4166..1ee45da 100644 --- a/apps/web/src/pages/GameScreen.tsx +++ b/apps/web/src/pages/GameScreen.tsx @@ -3,7 +3,7 @@ * 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 { listenLabel, viewsLabel, 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'; @@ -146,7 +146,8 @@ export function GameScreen({ room, game }: { room: RoomView; game: GameView }) {
+ {!fixedKind && ( + + )}
- {file && {file.name}}
- {!file && ( + {!file && duel && ( +

+ 한 줄에 한 곡씩, 첫 줄은 열 이름이에요. 유튜브 영상 링크, 제목, 조회수는 꼭 있어야 하고 가수는 카드에 같이 보여요. 조회수는 1234567, 1,234,567, + 123만, 1.2억처럼 써도 돼요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요. +

+ )} + {!file && !duel && (

한 줄에 한 곡씩, 첫 줄은 열 이름이에요. 유튜브 영상 링크와 정답(예: 게임 제목)은 꼭 있어야 하고, 설명(예: 노래 제목)은 정답을 공개할 때 같이 보여요. 힌트 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. 순번 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요. @@ -177,16 +212,17 @@ export function QuizFileImport({ ))}

- {missing.length > 0 && {missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.} + {missing.length > 0 && {missing.map((c) => colLabel(c, kind)).join(', ')} 열을 골라 주세요.}
{!missing.length && parsed && ( <> @@ -227,9 +263,9 @@ export function QuizFileImport({ # - 정답 - 설명 - 힌트 + {duel ? '제목' : '정답'} + {duel ? '가수' : '설명'} + {duel ? '조회수' : '힌트'} 영상 @@ -242,7 +278,13 @@ export function QuizFileImport({ {it.titleAnswers.length > 0 &&
또는 {it.titleAnswers.join(', ')}
} {it.artist || -} - {[...it.hints, '초성'].join(' → ')} + {duel ? ( + + {viewsLabel(it.views ?? 0)}회 + + ) : ( + {[...it.hints, '초성'].join(' → ')} + )} {it.videoId} ↗ @@ -266,8 +308,8 @@ export function QuizFileImport({ 퀴즈 이름 setName(e.target.value)} aria-label="퀴즈 이름" /> - ) : ( diff --git a/apps/web/src/pages/admin/QuizzesPage.tsx b/apps/web/src/pages/admin/QuizzesPage.tsx index dad173c..50cc6e3 100644 --- a/apps/web/src/pages/admin/QuizzesPage.tsx +++ b/apps/web/src/pages/admin/QuizzesPage.tsx @@ -7,11 +7,16 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Link, useNavigate, useParams, useSearchParams } from 'react-router'; import { DEFAULT_QUIZ_SETTINGS, + DUEL_FLOWS, + DUEL_SECS, LISTEN_SECS, QUIZ_VISIBILITIES, listenLabel, + parseViews, + viewsLabel, type QuizDetail, type QuizItem, + type QuizKind, type QuizSettings, type QuizSummary, type QuizVisibility, @@ -64,15 +69,18 @@ export function QuizzesPage() { )}
-

직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.

+

+ 직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 조회수가 든 파일로 만들고, 이지선다 + 모드에서만 쓸 수 있어요. +

{fromFile && ( setFromFile(false)} - onCreate={async (quizName, items) => { + onCreate={async (quizName, items, kind) => { try { - const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items }); - toast(`"${quizName}" 퀴즈를 ${items.length}곡으로 만들었어요.`); + const r = await apiCall<{ id: number }>('POST', '/api/admin/quizzes/file', { name: quizName, items, kind }); + toast(`"${quizName}" ${kind === 'duel' ? '이지선다 ' : ''}퀴즈를 ${items.length}곡으로 만들었어요.`); nav(`/admin/quizzes/${r.id}`); } catch (e) { toast((e as Error).message, 'error'); @@ -86,6 +94,7 @@ export function QuizzesPage() { {q.name} {q.description && {q.description}} + {q.kind === 'duel' && 🆚 이지선다} {VIS_LABEL[q.visibility]} {q.songs}곡 · 플레이 {q.plays}번{all ? ` · ${q.ownerName}` : ''} @@ -123,7 +132,7 @@ export function QuizzesPage() { {!fromFile && ( )} @@ -150,8 +159,8 @@ export interface DbInfo { } /** A song picked in the editor (search, address, playlist): answers, hints and positions start empty. */ -type NewSong = Omit; -const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null }); +type NewSong = Omit; +const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null, views: null }); let keySeq = 0; const newKey = () => `k${++keySeq}`; @@ -176,7 +185,7 @@ export function QuizEditor() { const [busy, setBusy] = useState(false); const [leaveTo, setLeaveTo] = useState(null); const [confirmDelete, setConfirmDelete] = useState(false); - const [owner, setOwner] = useState<{ ownerName: string; plays: number } | null>(null); + const [owner, setOwner] = useState<{ ownerName: string; plays: number; kind: QuizKind } | null>(null); const [importOpen, setImportOpen] = useState(false); const [fileOpen, setFileOpen] = useState(false); @@ -187,7 +196,7 @@ export function QuizEditor() { setDraft(d); setSaved(JSON.stringify(payload(d))); setDb(r.db); - setOwner({ ownerName: r.quiz.ownerName, plays: r.quiz.plays }); + setOwner({ ownerName: r.quiz.ownerName, plays: r.quiz.plays, kind: r.quiz.kind }); }) .catch((e: Error) => toast(e.message, 'error')); }, [id]); @@ -292,6 +301,7 @@ export function QuizEditor() { if (!draft) return

불러오는 중…

; const set = (p: Partial) => setDraft({ ...draft, ...p }); + const kind: QuizKind = owner?.kind ?? 'normal'; const isNew = params.get('new') === '1' && draft.items.length === 0; return ( @@ -302,7 +312,7 @@ export function QuizEditor() {

{draft.name || '이름 없는 퀴즈'}

{dirty ? ● 저장하지 않은 변경이 있어요 : 저장됨} -