이지선다 모드: 조회수가 더 높은 곡 고르기. 이지선다 퀴즈는 조회수가 든 파일로 만들고(custom_quizzes.kind='duel', custom_quiz_items.views, 013 마이그레이션; 1,234,567·123만·1.2억도 읽음, 조회수 없는 줄은 빠짐) 이지선다에서만, 일반 퀴즈는 듣고맞추기에서만 쓴다. 서버 game/duel.ts: 문제마다 A/B 카드, 카드를 누르면 고른 것(시간 전까지 바꾸기), 시간이 끝나면 조회수 공개·높은 쪽 1점·역배(혼자 맞히고 반대쪽 2명 이상) 2점·같으면 둘 다 정답, 매번 새 두 곡/연속(이긴 곡이 조회수를 보인 채 A로 남음). 화면 DuelScreen: 고른 사람 프로필이 카드 밑에, 카드마다 숨은 플레이어(net/duel-player.ts)로 각자 듣고 다시 누르면 멈춘 곳부터 이어서. 방 설정 이지선다(제한 시간 기본 30초·진행 방식·재생위치·문제 수, 이지선다 퀴즈만 목록에), 결과 화면 역배 성공 수. 관리자 파일로 만들기 종류 선택(조회수 열이 있으면 이지선다), 조회수 편집·내보내기·빈 양식. 폰 점수판 가로 스크롤 키보드 접근(axe). 서버 테스트 146개, e2e duel(실제 유튜브 이어 듣기 포함)·game·quiz·admin·rooms·login·a11y 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-23 21:02:43 +09:00
parent 3c5e26f9b7
commit 666c236a8e
33 changed files with 1789 additions and 136 deletions

View File

@@ -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;

View File

@@ -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<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `회원${code.slice(-2)}`, avatar: null });
let s: ReturnType<typeof boot>;
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<string, { points: number; reverse: boolean }>) => 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<string, number> = { 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<string, unknown>) => 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();
});

View File

@@ -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<string, DuelSide>, winner: DuelSide | 'both'): Map<string, { points: number; reverse: boolean }> {
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<number, QuizItem>;
private cards: [Card, Card] | null = null;
/** Index in `list` of the next song not used yet. */
private at = 0;
private picks = new Map<string, { side: DuelSide; ms: number }>();
private result: DuelResult | null = null;
private elapsedMs = 0;
private runningSince: number | null = null;
private limitMs = 30_000;
private nextVotes = new Set<string>();
history: GameHistoryItem[] = [];
private revealUntil: number | null = null;
private timer: ReturnType<typeof setInterval> | 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<string, boolean>();
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() });
}
}

View File

@@ -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). */

View File

@@ -65,18 +65,23 @@ export function mountQuizAdmin(app: Hono<Env>, 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 });
});

View File

@@ -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)

View File

@@ -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<ItemRow, [number]>(
'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<ItemRow, [number, number]>(
'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<number>();
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<QuizRow, [string, string, string]>(
`${SELECT} WHERE q.deleted_at IS NULL AND (q.name LIKE ? ESCAPE '\\' OR q.description LIKE ? ESCAPE '\\')
.query<QuizRow, [string, string, string, string]>(
`${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);
}

View File

@@ -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<string, unknown> = 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<WsData>, 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<WsData>, on: boolean): void {
const room = this.inRoom(ws);

View File

@@ -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':