이지선다 모드: 조회수가 더 높은 곡 고르기. 이지선다 퀴즈는 조회수가 든 파일로 만들고(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':

View File

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

View File

@@ -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 (
<div className="settings card ink">
<div className="hd">
@@ -275,7 +291,12 @@ export function RoomSettings({
aria-label="방 이름"
/>
</Section>
{allowQuiz && (
{allowQuiz && duel && (
<Section title="이지선다 퀴즈" tip="조회수가 든 파일로 만든 이지선다 퀴즈만 고를 수 있어요">
<QuizPicker kind="duel" chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />
</Section>
)}
{allowQuiz && !duel && (
<Section title="문제 고르기">
<Seg
label="문제 고르기"
@@ -295,20 +316,48 @@ export function RoomSettings({
{ v: 'quiz', label: '📋 제작된 퀴즈' },
]}
/>
{quiz && <QuizPicker chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />}
{quiz && <QuizPicker kind="normal" chosen={c.quizId ? { id: c.quizId, name: c.quizName } : null} songs={pool.playable} ro={ro} onPick={(quizId) => onPatch({ quizId })} />}
</Section>
)}
<Section title="모드">
<Seg
label="모드"
value={c.mode}
disabled={ro || quiz}
onChange={(mode) => 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 && <p className="muted small" style={{ marginTop: 6 }}>제작된 퀴즈는 듣고맞추기로만 할 수 있어요.</p>}
{quiz && !duel && <p className="muted small" style={{ marginTop: 6 }}>제작된 퀴즈는 듣고맞추기로 해요. 다른 모드를 고르면 직접 선택으로 바뀌어요.</p>}
{duel && <p className="muted small" style={{ marginTop: 6 }}>두 곡 중 유튜브 조회수가 더 높은 곡을 고르는 모드예요. 카드를 누르면 그 노래가 나오고, 그 카드를 고른 게 돼요.</p>}
<div className="subbox">
{listening ? (
{duel ? (
<>
<div>
<div className="label">제한 시간</div>
<Seg label="제한 시간" value={c.duelSec} disabled={ro} onChange={(duelSec) => onPatch({ duelSec })} options={DUEL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</div>
<div>
<div className="label">진행 방식</div>
<Seg label="진행 방식" value={c.duelFlow} disabled={ro} onChange={(duelFlow) => onPatch({ duelFlow })} options={DUEL_FLOWS.map((f) => ({ v: f.id, label: f.label }))} />
<p className="muted small" style={{ marginTop: 6 }}>
{c.duelFlow === 'chain' ? '조회수가 더 높은 곡이 조회수를 보여 준 채 남고, 새 곡과 다시 비교해요.' : '문제마다 새로운 두 곡이 나와요.'}
</p>
</div>
<div>
<div className="label">재생위치</div>
<Seg
label="재생위치"
value={c.startAt}
disabled={ro}
onChange={(startAt) => onPatch({ startAt })}
options={[
{ v: 'start', label: '처음부터' },
{ v: 'highlight', label: '하이라이트부터' },
]}
/>
</div>
</>
) : listening ? (
<>
<div>
<div className="label">듣고맞출시간</div>
@@ -394,8 +443,18 @@ export function RoomSettings({
</Section>
</>
)}
<PlayRules c={c} ro={ro} listening={listening} onPatch={onPatch} />
{quiz ? (
<PlayRules c={c} ro={ro} listening={listening} duel={duel} onPatch={onPatch} />
{duel ? (
<Section title="문제 수">
<Seg
label="문제 수"
value={c.count}
disabled={ro}
onChange={(count) => onPatch({ count })}
options={COUNTS.map((v) => ({ v, label: v ? String(v) : `전부(${duelMax.toLocaleString()})` }))}
/>
</Section>
) : quiz ? (
<Section title="문제 수">
<p className="small" style={{ margin: 0 }}>{c.quizId ? `퀴즈에 든 곡 전부 (${pool.playable.toLocaleString()}문제)` : '퀴즈를 고르면 그 퀴즈의 곡 전부가 나와요'}</p>
</Section>
@@ -459,14 +518,28 @@ export function PlayRules({
c,
ro,
listening,
duel = false,
onPatch,
}: {
c: Pick<RoomConfig, 'answer' | 'strict' | 'hint' | 'hintVotes' | 'skipVotes' | 'replayVotes' | 'revealSec' | 'nextVotes'>;
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 = (
<>
<Section title="다음 문제까지" tip={duel ? '결과(조회수)를 보여 준 뒤 다음 문제로 넘어가기까지 기다리는 시간' : '정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요'}>
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</Section>
<Section title="다음문제인원(이상)" tip={duel ? '결과를 보는 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정' : '정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정'}>
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
</Section>
</>
);
if (duel) return after;
return (
<>
<Section title="정답방식">
@@ -521,12 +594,7 @@ export function PlayRules({
<Seg label="다시듣기인원" value={c.replayVotes} disabled={ro} onChange={(replayVotes) => onPatch({ replayVotes })} options={vote(VOTE_RULES)} />
</Section>
)}
<Section title="다음 문제까지" tip="정답을 공개한 뒤 다음 문제로 넘어가기까지 기다리는 시간. 그동안 노래는 계속 나와요">
<Seg label="다음 문제까지" value={c.revealSec} disabled={ro} onChange={(revealSec) => onPatch({ revealSec })} options={REVEAL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</Section>
<Section title="다음문제인원(이상)" tip="정답 공개 중에 바로 다음 문제로 넘어가려면 다음 문제를 눌러야하는 인원 설정">
<Seg label="다음문제인원" value={c.nextVotes} disabled={ro} onChange={(nextVotes) => onPatch({ nextVotes })} options={vote(VOTE_RULES)} />
</Section>
{after}
</>
);
}
@@ -534,7 +602,7 @@ export function PlayRules({
const VIS: Record<string, string> = { 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<QuizSummary[] | null>(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:
<>
<input className="input" value={q} onChange={(e) => setQ(e.target.value)} placeholder="퀴즈 이름 검색" aria-label="퀴즈 이름 검색" />
{error && <span className="field-error small">{error}</span>}
<div className="quiz-pick" role="listbox" aria-label="제작된 퀴즈 목록">
{list?.length === 0 && <span className="muted small" style={{ padding: 10 }}>{q.trim() ? '검색 결과가 없어요.' : '고를 수 있는 퀴즈가 없어요.'}</span>}
<div className="quiz-pick" role="listbox" aria-label={kind === 'duel' ? '이지선다 퀴즈 목록' : '제작된 퀴즈 목록'}>
{list?.length === 0 && (
<span className="muted small" style={{ padding: 10 }}>
{q.trim() ? '검색 결과가 없어요.' : kind === 'duel' ? '고를 수 있는 이지선다 퀴즈가 없어요. 관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만들 수 있어요.' : '고를 수 있는 퀴즈가 없어요.'}
</span>
)}
{list?.map((x) => (
<button key={x.id} type="button" role="option" aria-selected={chosen?.id === x.id} className="quiz-pick-item" onClick={() => onPick(x.id)}>
<span className="row" style={{ gap: 6 }}>

View File

@@ -0,0 +1,162 @@
/**
* 이지선다 cards: every player listens on their own screen (no shared timeline, docs: 이지선다).
* One hidden player per card, both loaded muted when a question starts, so tapping a card plays it at once and going back
* to the other card goes on where it stopped. Tapping the card that is playing pauses it. A song that stays for the next
* question (연속 방식) keeps its player and position.
*/
import { create } from 'zustand';
import type { DuelSide } from '@mq/shared/lite';
import { cardEngine, usePlayer, type Engine } from './player';
export interface DuelPlayerState {
/** The card playing right now. */
playing: DuelSide | null;
/** Videos that cannot be played here (deleted / embedding off), by video id. */
broken: Record<string, number>;
}
export const useDuelPlayer = create<DuelPlayerState>(() => ({ playing: null, broken: {} }));
interface Slot {
engine: Engine;
ready: Promise<void>;
videoId: string | null;
startSec: number;
gain: number;
/** The video was asked for (preload or a tap): a tap plays it instead of loading it again. */
loaded: boolean;
/** Bumped by every command, so an older preload stops before pausing a song the player started meanwhile. */
tk: number;
}
const slots = new Map<DuelSide, Slot>();
let key = '';
function make(): Slot {
const s: Slot = {
engine: null as unknown as Engine,
ready: Promise.resolve(),
videoId: null,
startSec: 0,
gain: 1,
loaded: false,
tk: 0,
};
s.engine = cardEngine({
onError: (code) => {
if (!s.videoId) return;
useDuelPlayer.setState((st) => ({ broken: { ...st.broken, [s.videoId!]: code }, playing: st.playing && slots.get(st.playing) === s ? null : st.playing }));
},
onState: (state) => {
// the song ended by itself
if (state === 0 && useDuelPlayer.getState().playing && slots.get(useDuelPlayer.getState().playing!) === s) useDuelPlayer.setState({ playing: null });
},
});
s.ready = s.engine.init();
return s;
}
const waitFor = (pred: () => boolean, ms: number, s: Slot, tk: number) =>
new Promise<boolean>((res) => {
const t0 = performance.now();
const iv = setInterval(() => {
if (tk !== s.tk) return (clearInterval(iv), res(false));
if (pred()) return (clearInterval(iv), res(true));
if (performance.now() - t0 > ms) return (clearInterval(iv), res(false));
}, 30);
});
/** Load muted and stop at the start position, so the first tap starts right away. */
async function preload(s: Slot): Promise<void> {
const tk = ++s.tk;
await s.ready;
if (tk !== s.tk || !s.videoId) return;
const e = s.engine;
e.mute(true);
e.load(s.videoId, s.startSec);
s.loaded = true;
if (!(await waitFor(() => e.state() === 1, 15_000, s, tk))) return;
e.pause();
await waitFor(() => e.state() === 2, 3000, s, tk);
if (tk !== s.tk) return;
e.seek(s.startSec);
}
// for e2e checks, like window.mqPlayer
(window as unknown as { mqDuel: unknown }).mqDuel = {
state: (side: DuelSide) => slots.get(side)?.engine.state() ?? null,
time: (side: DuelSide) => slots.get(side)?.engine.time() ?? null,
muted: (side: DuelSide) => slots.get(side)?.engine.isMuted() ?? null,
video: (side: DuelSide) => slots.get(side)?.videoId ?? null,
};
const volumeOf = (s: Slot) => Math.round(usePlayer.getState().volume * s.gain);
usePlayer.subscribe((st, prev) => {
if (st.volume === prev.volume) return;
for (const s of slots.values()) s.engine.volume(volumeOf(s));
});
export const duelPlayer = {
/** A new question (`k` changes): both cards load muted at their start position; a song still on the cards keeps its player. */
setup(k: string, cards: { side: DuelSide; videoId: string; startSec: number; gain: number }[]): void {
if (k === key) return;
key = k;
const old = new Map(slots);
for (const s of old.values()) {
s.tk++;
s.engine.pause();
}
useDuelPlayer.setState({ playing: null });
const next = new Map<DuelSide, Slot>();
const free = [...old.values()].filter((s) => !cards.some((c) => c.videoId === s.videoId));
for (const c of cards) {
const same = [...old.values()].find((s) => s.videoId === c.videoId);
if (same) {
next.set(c.side, same);
continue;
}
const s = free.shift() ?? make();
s.videoId = c.videoId;
s.startSec = c.startSec;
s.gain = c.gain;
s.loaded = false;
next.set(c.side, s);
void preload(s);
}
slots.clear();
for (const [side, s] of next) slots.set(side, s);
},
/** Tap on a card: play it (from where it stopped), stop the other one; the card that is playing pauses. */
toggle(side: DuelSide): void {
const s = slots.get(side);
if (!s?.videoId) return;
const st = useDuelPlayer.getState();
if (st.playing === side) {
s.engine.pause();
useDuelPlayer.setState({ playing: null });
return;
}
for (const [other, o] of slots) if (other !== side) o.engine.pause();
const tk = ++s.tk;
const e = s.engine;
const id = s.videoId;
e.volume(volumeOf(s));
e.mute(false);
if (s.loaded) e.play();
else {
s.loaded = true;
void s.ready.then(() => tk === s.tk && e.load(id, s.startSec));
}
useDuelPlayer.setState({ playing: side });
},
stop(): void {
key = '';
for (const s of slots.values()) {
s.tk++;
s.engine.pause();
}
useDuelPlayer.setState({ playing: null });
},
};

View File

@@ -45,7 +45,7 @@ export const usePlayer = create<PlayerState>(() => ({ unlocked: false, needsGest
/** A harmless video the entry click plays at volume 0 to get sound permission (SG워너비 광, Topic — known to embed). */
const UNLOCK_VIDEO = 'VO88htcm09E';
interface Engine {
export interface Engine {
init(): Promise<void>;
unlock(): void;
load(id: string, startSec: number): void;
@@ -61,7 +61,7 @@ interface Engine {
videoId(): string | null;
}
type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
export type Listener = { onState?: (s: number) => void; onError?: (code: number) => void; onBlocked?: () => void };
// ---------------------------------------------------------------- real YouTube engine
declare global {
@@ -301,6 +301,11 @@ function fakeEngine(l: Listener): Engine {
};
}
/** A player of its own (이지선다 cards: one per card, so switching cards goes on where each stopped). */
export function cardEngine(l: Listener): Engine {
return useFake() ? fakeEngine(l) : youtubeEngine(l);
}
// ---------------------------------------------------------------- controller
let engine: Engine | null = null;
let report: (n: number, ev: AudioEvent, code?: number) => void = () => {};

View File

@@ -5,6 +5,7 @@ import { create } from 'zustand';
import type { ChatLine, GameView, RoomView, ServerMessage } from '@mq/shared/lite';
import { toast } from '../store/toast';
import { player } from './player';
import { duelPlayer } from './duel-player';
import { noteServerBuild } from './update';
type Status = 'idle' | 'connecting' | 'open' | 'reconnecting';
@@ -111,6 +112,7 @@ function onMessage(m: ServerMessage): void {
if (m.code === useRoom.getState().code) {
setLastRoom(null);
player.stop();
duelPlayer.stop();
useRoom.setState({ room: null, left: m.reason, chat: [], pending: [], game: null, typing: [] });
}
return;
@@ -122,8 +124,8 @@ function onMessage(m: ServerMessage): void {
if (m.code !== useRoom.getState().code) return;
const prev = useRoom.getState().game;
const g = m.game;
if (!g || g.phase === 'result') player.stop();
else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150));
if (!g || g.phase === 'result') (player.stop(), duelPlayer.stop());
else if (g.phase === 'reveal' && prev?.phase !== 'reveal' && g.mode !== 'lyrics' && g.mode !== 'duel' && g.participants.includes(myId)) player.reveal(Math.max(0, (g.revealUntil ?? 0) - serverNow() - 150));
useRoom.setState({ game: g });
return;
}
@@ -215,6 +217,7 @@ export const socket = {
send({ t: 'leave' });
setLastRoom(null);
player.stop();
duelPlayer.stop();
useRoom.setState({ code: null, room: null, chat: [], pending: [], game: null, typing: [] });
},
chat(text: string): void {

View File

@@ -0,0 +1,251 @@
/**
* 이지선다 게임 화면: two cards A and B. Tapping a card plays that song on this screen and is the pick (it can change
* until the time is up); everyone's picks show as small avatars under the cards. After the time the views come out,
* the higher card wins and points go to the players on it (역배: alone against 2 or more = 2 points).
*/
import { useEffect, useRef, useState } from 'react';
import { viewsLabel, type DuelCard, type GameView, type RoomView } from '@mq/shared/lite';
import { serverNow, socket, useRoom } from '../net/socket';
import { player, usePlayer } from '../net/player';
import { duelPlayer, useDuelPlayer } from '../net/duel-player';
import { useSession } from '../store/session';
import { Avatar, ConfirmSheet } from '../components/ui';
import { ChatPanel, type ChatHandle } from '../components/ChatPanel';
import { ResultScreen } from './GameScreen';
function useNow(ms: number): number {
const [, set] = useState(0);
useEffect(() => {
const iv = setInterval(() => set((x) => x + 1), ms);
return () => clearInterval(iv);
}, [ms]);
return serverNow();
}
const views = (n: number) => `${viewsLabel(n)}회`;
export function DuelScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const { chat, pending, typing, code } = useRoom();
const volume = usePlayer((s) => s.volume);
const { playing, broken } = useDuelPlayer();
const now = useNow(200);
const chatRef = useRef<ChatHandle>(null);
const [confirmEnd, setConfirmEnd] = useState(false);
const isHost = room.hostId === me.id;
const c = room.config;
const d = game.duel!;
const send = (m: unknown) => socket.send(m);
const name = (id: string) => room.players.find((x) => x.id === id)?.nickname ?? game.scores.find((x) => x.id === id)?.nickname ?? '?';
const user = (id: string) => ({ id, nickname: name(id), avatar: room.players.find((x) => x.id === id)?.avatar ?? null });
const result = game.phase === 'reveal' ? d.result : null;
const mine = d.cards.find((x) => x.picks.includes(me.id))?.side ?? null;
// a new question: both cards load (muted) on this screen; leaving the game stops them
const qKey = `${code}:${game.n}:${d.cards.map((x) => x.videoId).join(',')}`;
useEffect(() => {
if (game.phase === 'result') return duelPlayer.stop();
duelPlayer.setup(qKey, d.cards);
}, [qKey, game.phase]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => () => duelPlayer.stop(), []);
// Ctrl+K during the reveal = 다음 문제; any other key goes to the chat
const phaseRef = useRef(game.phase);
phaseRef.current = game.phase;
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') {
e.preventDefault();
if (phaseRef.current === 'reveal') send({ t: 'vote', kind: 'next' });
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
const t = e.target as HTMLElement | null;
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.tagName === 'BUTTON' || t.isContentEditable)) return;
if (document.querySelector('.sheet')) return;
if (e.key.length === 1 || e.key === 'Enter') chatRef.current?.focus();
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
if (game.phase === 'result') return <ResultScreen room={room} game={game} />;
const elapsed = game.clock.elapsedMs + (game.clock.runningSince !== null ? Math.max(0, now - game.clock.runningSince) : 0);
const limit = game.clock.limitMs ?? 30_000;
const left = Math.max(0, Math.ceil((limit - elapsed) / 1000));
const revealLeft = Math.max(0, Math.ceil(((game.revealUntil ?? now) - now) / 1000));
const tap = (card: DuelCard) => {
duelPlayer.toggle(card.side);
if (game.phase === 'play' && !game.paused && mine !== card.side) send({ t: 'pick', n: game.n, side: card.side });
};
const need = game.need.next;
const nextOn = game.votes.next.includes(me.id);
return (
<main className="game duel">
<div className="gbar" role="toolbar" aria-label="게임 조작">
<div className="q">
문제 {game.n} <span>/ {game.total}</span>
</div>
<span className="badge dark">
🆚 이지선다 · {c.duelSec}초 · {d.flow === 'chain' ? '이긴 곡이 남기' : '매번 새 두 곡'}
</span>
{c.quizId && <span className="badge dark">📋 {c.quizName}</span>}
<div className="grow" />
{result && (
<button type="button" className={`btn btn-sm gbtn ${nextOn ? 'on' : ''}`} aria-pressed={nextOn} disabled={need === null} onClick={() => send({ t: 'vote', kind: 'next' })}>
⏭ 다음 문제
{need !== null && (
<span className="mono">
{' '}
{game.votes.next.length}/{need}
</span>
)}
<span className="kbd">Ctrl+K</span>
</button>
)}
<label className="vol" title="볼륨">
🔊
<input type="range" min={0} max={100} value={volume} onChange={(e) => player.setVolume(Number(e.target.value))} aria-label="볼륨" />
</label>
{isHost && (
<>
<button type="button" className="btn btn-sm gbtn" disabled={game.phase !== 'play'} onClick={() => send({ t: 'game', action: game.paused ? 'resume' : 'pause' })}>
{game.paused ? '▶ 계속' : '⏸ 일시정지'}
</button>
<button type="button" className="btn btn-sm gbtn" onClick={() => setConfirmEnd(true)}>
⏹ 끝내기
</button>
</>
)}
</div>
<div className="ggrid">
<aside className="side scoreboard" aria-label="점수판">
<h2>점수판 · {game.scores.length}명</h2>
{/* phone: the list scrolls sideways, so it takes keyboard focus (axe scrollable-region-focusable) */}
<ol tabIndex={0} aria-label="순위">
{game.scores.map((s, i) => {
const rank = 1 + game.scores.findIndex((o) => o.score === s.score && o.avgMs === s.avgMs);
const gain = result?.gains.find((g) => g.id === s.id);
return (
<li key={s.id} className={`sb ${s.id === me.id ? 'me' : ''} ${i === 0 && s.score > 0 ? 'first' : ''} ${s.online ? '' : 'off'}`}>
<span className="rk">{rank}</span>
<Avatar user={user(s.id)} size={26} />
<span className="nm">
{s.nickname}
{s.id === me.id && ' (나)'}
{s.id === room.hostId && <span title="방장"> 👑</span>}
</span>
{gain && <span className={`gain ${gain.reverse ? 'rev' : ''}`}>+{gain.points}</span>}
<span className="sc mono">{s.score}</span>
</li>
);
})}
</ol>
</aside>
<div className="gcenter">
<section className="stage duel-stage" aria-live="polite">
<div className="duel-head">
<div className="big">{result ? (result.winner === 'both' ? '조회수가 똑같아요! 둘 다 정답' : `${result.winner === 'a' ? 'A' : 'B'}의 조회수가 더 높아요!`) : '어느 곡의 유튜브 조회수가 더 높을까요?'}</div>
{result ? (
<div className="small muted">
{result.gains.find((g) => g.reverse) ? `⚡ 역배 성공! ${name(result.gains.find((g) => g.reverse)!.id)}님 +2점 · ` : ''}
{game.n >= game.total ? '결과까지' : '다음 문제까지'} <b className="mono">{revealLeft}초</b>
</div>
) : game.paused ? (
<div className="small muted">⏸ 방장이 잠시 멈췄어요</div>
) : (
<>
<div className="bar" aria-hidden>
<i style={{ width: `${Math.min(100, (elapsed / limit) * 100)}%` }} />
</div>
<div className="small muted">
남은 시간 <b className="mono">{left}초</b> · 카드를 누르면 그 노래가 나오고 그 카드를 고른 거예요. 시간 안에는 몇 번이든 바꿀 수 있어요.
</div>
</>
)}
</div>
<div className="duel-cards">
{d.cards.map((card) => {
const won = result && (result.winner === 'both' || result.winner === card.side);
return (
<button
key={card.side}
type="button"
className={`duel-card ${mine === card.side ? 'mine' : ''} ${playing === card.side ? 'playing' : ''} ${result ? (won ? 'won' : 'lost') : ''}`}
aria-pressed={mine === card.side}
aria-label={`${card.side.toUpperCase()} ${card.title} ${card.artist}${mine === card.side ? ' (내가 고른 곡)' : ''}`}
onClick={() => tap(card)}
>
<span className="duel-side" aria-hidden>
{card.side.toUpperCase()}
</span>
<img className="duel-thumb" src={`https://i.ytimg.com/vi/${card.videoId}/hqdefault.jpg`} alt="" />
<span className="duel-title">{card.title}</span>
{card.artist && <span className="duel-artist muted">{card.artist}</span>}
<span className="duel-views" title={card.views !== null ? `${card.views.toLocaleString('ko-KR')}회` : undefined}>
{card.views !== null ? `조회수 ${views(card.views)}` : '조회수 ?'}
</span>
<span className="duel-state small">
{broken[card.videoId]
? '이 영상은 여기서 재생할 수 없어요 (고를 수는 있어요)'
: playing === card.side
? '♪ 재생 중 · 다시 누르면 멈춰요'
: mine === card.side
? '✔ 내가 고른 곡 · 눌러서 듣기'
: '▶ 눌러서 듣고 고르기'}
</span>
<span className="duel-picks" aria-label={`${card.side.toUpperCase()}를 고른 사람 ${card.picks.length}명`}>
{card.picks.map((id) => {
const g = result?.gains.find((x) => x.id === id);
return (
<span key={id} className="duel-pick" title={name(id)}>
<Avatar user={user(id)} size={24} />
{g && <b className={`gain ${g.reverse ? 'rev' : ''}`}>+{g.points}</b>}
</span>
);
})}
</span>
</button>
);
})}
</div>
</section>
<ChatPanel
ref={chatRef}
big
placeholder="채팅 입력 (Enter)"
lines={chat}
pending={pending}
meId={me.id}
myName={me.nickname}
onSend={(t) => socket.chat(t)}
onTyping={(on) => send({ t: 'typing', on })}
typing={typing.filter((id) => id !== me.id).map(name)}
/>
</div>
<aside className="side hist" aria-label="지난 문제">
<h2>지난 문제</h2>
{game.history.length === 0 && <p className="small muted">아직 없어요</p>}
{[...game.history].reverse().map((h) => {
const x = h.duel!;
return (
<div key={h.n} className="h">
<span className="n">{h.n}</span>
{x.cards.map((cd, i) => (
<span key={cd.side} className={x.winner === 'both' || x.winner === cd.side ? 't' : 'muted'}>
{i > 0 && <span className="muted"> vs </span>}
{cd.title} <span className="small">({views(cd.views)})</span>
</span>
))}
<div className="m">{x.gains.length ? x.gains.map((g) => `${g.nickname} +${g.points}${g.reverse ? ' 역배' : ''}`).join(', ') : '맞힌 사람 없음'}</div>
</div>
);
})}
</aside>
</div>
{confirmEnd && <ConfirmSheet title="게임을 끝낼까요?" body="지금까지 점수로 결과를 보여 줘요." confirm="끝내기" danger onConfirm={() => send({ t: 'game', action: 'end' })} onClose={() => setConfirmEnd(false)} />}
</main>
);
}

View File

@@ -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 }) {
<div className="ggrid">
<aside className="side scoreboard" aria-label="점수판">
<h2>점수판 · {game.scores.length}명</h2>
<ol>
{/* phone: the list scrolls sideways, so it takes keyboard focus (axe scrollable-region-focusable) */}
<ol tabIndex={0} aria-label="순위">
{game.scores.map((s, i) => {
// ties share a rank (same score and same average time)
const rank = 1 + game.scores.findIndex((o) => o.score === s.score && o.avgMs === s.avgMs);
@@ -304,12 +305,13 @@ function RevealCard({ item, left, last }: { item: GameHistoryItem; left: number;
);
}
function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
export function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
const me = useSession((s) => s.me)!;
const isHost = room.hostId === me.id;
const [save, setSave] = useState(false);
const [name, setName] = useState('');
const send = (m: unknown) => socket.send(m);
const duel = game.mode === 'duel';
const fastest = new Map<string, GameHistoryItem>();
for (const h of game.history) if (h.winnerId && h.ms !== null && (!fastest.get(h.winnerId) || fastest.get(h.winnerId)!.ms! > h.ms)) fastest.set(h.winnerId, h);
return (
@@ -325,8 +327,8 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
<th>순위</th>
<th>이름</th>
<th>점수</th>
<th>맞힌 곡</th>
<th>가장 빨리 맞힌 곡</th>
<th>{duel ? '맞힌 문제' : '맞힌 곡'}</th>
<th>{duel ? '역배 성공' : '가장 빨리 맞힌 곡'}</th>
</tr>
</thead>
<tbody>
@@ -338,7 +340,7 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
<td>{s.nickname}</td>
<td className="mono">{s.score}</td>
<td className="mono">{s.correct}</td>
<td>{f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
<td>{duel ? <span className="mono">{s.reverse ?? 0}</span> : f ? `${f.title} · ${secs(f.ms)}` : '-'}</td>
</tr>
);
})}
@@ -369,7 +371,23 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
<section className="card">
<h2 style={{ marginBottom: 10 }}>이번 게임 곡 목록</h2>
<ol className="songlist">
{game.history.map((h) => (
{game.history.map((h) =>
h.duel ? (
<li key={h.n}>
<span className="mono muted">{h.n}.</span>{' '}
{h.duel.cards.map((cd, i) => (
<span key={cd.side}>
{i > 0 && ' vs '}
{h.duel!.winner === 'both' || h.duel!.winner === cd.side ? <b>{cd.title}</b> : cd.title}
{cd.artist && ` - ${cd.artist}`} <span className="small muted">({viewsLabel(cd.views)}회)</span>{' '}
<a href={`https://youtu.be/${cd.videoId}`} target="_blank" rel="noreferrer" className="small">
영상
</a>
</span>
))}{' '}
<span className="small muted">{h.duel.gains.length ? h.duel.gains.map((g) => `${g.nickname} +${g.points}${g.reverse ? ' 역배' : ''}`).join(', ') : '맞힌 사람 없음'}</span>
</li>
) : (
<li key={h.n}>
<span className="mono muted">{h.n}.</span> <b>{h.title}</b> - {h.artist} <Stars n={h.level} />{' '}
{h.videoId && (
@@ -379,7 +397,8 @@ function ResultScreen({ room, game }: { room: RoomView; game: GameView }) {
)}{' '}
<span className="small muted">{h.winner ? `${h.winner} ${secs(h.ms)}` : h.how === 'skip' ? '스킵' : '시간 초과'}</span>
</li>
))}
),
)}
</ol>
</section>
{save && (

View File

@@ -15,6 +15,7 @@ import { RoomSettings, type CatalogMeta } from '../components/RoomSettings';
import { ChatPanel } from '../components/ChatPanel';
import { player, usePlayer } from '../net/player';
import { GameScreen } from './GameScreen';
import { DuelScreen } from './DuelScreen';
const LEFT_TEXT: Record<string, string> = {
kicked: '방장이 방에서 내보냈어요.',
@@ -100,7 +101,11 @@ export default function RoomPage() {
const genreName = (id: string) => meta?.genres.find((g) => g.id === id)?.name ?? id;
const link = `${location.origin}/r/${room.code}`;
const needArtist = c.mode === 'artist' && c.artistIds.length === 0;
const needQuiz = quizPicking && !c.quizId;
const duel = c.mode === 'duel';
const needQuiz = (quizPicking || duel) && !c.quizId;
// 이지선다: two songs a question (매번 새 두 곡) or one new song after the first two (연속)
const duelMax = duel ? (c.duelFlow === 'chain' ? Math.max(0, room.pool.playable - 1) : Math.floor(room.pool.playable / 2)) : 0;
const questions = duel ? (c.count ? Math.min(c.count, duelMax) : duelMax) : c.quizId ? room.pool.playable : c.count;
const short = !c.quizId && c.count !== 0 && room.pool.playable < c.count;
const start = () => (short && room.pool.playable > 0 ? setConfirmStart(true) : send({ t: 'start' }));
const playing = room.status === 'playing' && !!game;
@@ -135,7 +140,7 @@ export default function RoomPage() {
</button>
</section>
{playing ? (
<GameScreen room={room} game={game} />
game.mode === 'duel' ? <DuelScreen room={room} game={game} /> : <GameScreen room={room} game={game} />
) : (
<main className="room-main">
<div className="stack" style={{ minWidth: 0 }}>
@@ -183,20 +188,21 @@ export default function RoomPage() {
<h2>
{c.quizId ? '퀴즈 곡' : '조건에 맞는 곡'} <span className="mono">{room.pool.playable.toLocaleString()}</span>곡
</h2>
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.quizId ? `${room.pool.playable}문제` : c.count ? `${c.count}문제` : '무제한'}</p>
<p className="small">{configSummary(c, genreName).join(' · ')} · {c.quizId || questions ? `${questions}문제` : '무제한'}</p>
{room.pool.total > room.pool.playable && (
<p className="small" style={{ opacity: 0.85 }}>
원곡 확인 중인 곡 {(room.pool.total - room.pool.playable).toLocaleString()}곡은 확인이 끝나면 나와요
</p>
)}
{needArtist && <p className="small">가수를 1명 이상 골라 주세요.</p>}
{needQuiz && <p className="small">방 설정에서 제작된 퀴즈를 골라 주세요.</p>}
{needQuiz && <p className="small">{duel ? '방 설정에서 이지선다 퀴즈를 골라 주세요.' : '방 설정에서 제작된 퀴즈를 골라 주세요.'}</p>}
{duel && !!c.quizId && room.pool.playable === 1 && <p className="small">이지선다에는 조회수가 있는 곡이 2곡 이상 있어야 해요.</p>}
{!needArtist && short && room.pool.playable > 0 && <p className="small">문제 수보다 곡이 적어서 {room.pool.playable}문제만 나와요.</p>}
{!needArtist && !c.quizId && room.pool.playable === 0 && room.pool.total === 0 && <p className="small">이 조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.</p>}
{!!c.quizId && room.pool.playable === 0 && <p className="small">이 퀴즈에는 아직 곡이 없어요.</p>}
</div>
{isHost ? (
<button className="btn btn-mustard btn-lg" disabled={needArtist || needQuiz || room.pool.playable === 0} onClick={start}>
<button className="btn btn-mustard btn-lg" disabled={needArtist || needQuiz || room.pool.playable === 0 || (duel && duelMax === 0)} onClick={start}>
게임 시작
</button>
) : (
@@ -205,7 +211,7 @@ export default function RoomPage() {
</button>
)}
</section>
{c.mode !== 'lyrics' && !unlocked && (
{c.mode !== 'lyrics' && !duel && !unlocked && (
<section className="card sound-card row">
<span className="grow">🔊 노래가 들리도록 게임 전에 한 번 눌러 주세요. 브라우저가 소리를 막을 수 있어요.</span>
<button type="button" className="btn btn-mustard" onClick={() => player.unlock()}>

View File

@@ -5,7 +5,10 @@
*/
import { useMemo, useState } from 'react';
import {
DUEL_COLUMN_LABEL,
QUIZ_COLUMN_LABEL,
QUIZ_FILE_COLUMNS,
viewsLabel,
guessColumns,
headerRow,
parseQuizRows,
@@ -15,13 +18,15 @@ import {
writeXlsx,
type QuizColumn,
type QuizItem,
type QuizKind,
type Sheet,
} from '@mq/shared/lite';
import { toast } from '../../store/toast';
import { ConfirmSheet } from '../../components/ui';
import { Seg } from '../../components/RoomSettings';
const MAX_BYTES = 20 * 1024 * 1024;
const COLUMN_ORDER: QuizColumn[] = ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'];
const colLabel = (c: QuizColumn, kind: QuizKind) => (kind === 'duel' ? (DUEL_COLUMN_LABEL[c] ?? QUIZ_COLUMN_LABEL[c]) : QUIZ_COLUMN_LABEL[c]);
function download(name: string, bytes: Uint8Array) {
const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
@@ -35,18 +40,19 @@ function download(name: string, bytes: Uint8Array) {
}
/** 엑셀로 내보내기: the songs as a file this screen reads back. */
export function exportQuiz(name: string, items: QuizItem[]) {
const { rows, widths } = quizToRows(items);
export function exportQuiz(name: string, items: QuizItem[], kind: QuizKind = 'normal') {
const { rows, widths } = quizToRows(items, kind);
download(name, writeXlsx(name, rows, widths));
}
export function downloadTemplate() {
const { rows, widths } = quizTemplateRows();
download('퀴즈 양식', writeXlsx('퀴즈', rows, widths));
export function downloadTemplate(kind: QuizKind = 'normal') {
const { rows, widths } = quizTemplateRows(kind);
download(kind === 'duel' ? '이지선다 양식' : '퀴즈 양식', writeXlsx(kind === 'duel' ? '이지선다' : '퀴즈', rows, widths));
}
export function QuizFileImport({
mode,
kind: fixedKind,
existing = [],
onCreate,
onApply,
@@ -54,8 +60,10 @@ export function QuizFileImport({
}: {
/** create: 파일로 만들기 (new quiz) · into: 파일에서 가져오기 (the open quiz). */
mode: 'create' | 'into';
/** The open quiz's kind (into); 파일로 만들기 picks it (a 조회수 column means 이지선다). */
kind?: QuizKind;
existing?: QuizItem[];
onCreate?: (name: string, items: QuizItem[]) => Promise<void>;
onCreate?: (name: string, items: QuizItem[], kind: QuizKind) => Promise<void>;
onApply?: (items: QuizItem[], replace: boolean) => void;
onClose: () => void;
}) {
@@ -66,13 +74,18 @@ export function QuizFileImport({
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const [confirmReplace, setConfirmReplace] = useState(false);
const [chosenKind, setChosenKind] = useState<QuizKind>(fixedKind ?? 'normal');
const kind = fixedKind ?? chosenKind;
const pickSheet = (sheets: Sheet[], i: number) => {
const rows = sheets[i]?.rows ?? [];
const h = headerRow(rows);
setSheetIdx(i);
setHeaderAt(h);
setColumns(guessColumns(rows[h] ?? []));
const cols = guessColumns(rows[h] ?? []);
setColumns(cols);
// a 조회수 column: this is an 이지선다 file
if (!fixedKind) setChosenKind(cols.includes('views') ? 'duel' : 'normal');
};
const open = async (f: File) => {
if (f.size > MAX_BYTES) return toast('파일이 너무 커요(20MB까지).', 'error');
@@ -91,8 +104,9 @@ export function QuizFileImport({
const sheet = file?.sheets[sheetIdx];
const header = sheet?.rows[headerAt] ?? [];
const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt) : null), [sheet, columns, headerAt]);
const missing = (['link', 'answer'] as const).filter((c) => !columns.includes(c));
const parsed = useMemo(() => (sheet ? parseQuizRows(sheet.rows, columns, headerAt, kind) : null), [sheet, columns, headerAt, kind]);
const missing = (kind === 'duel' ? (['link', 'answer', 'views'] as const) : (['link', 'answer'] as const)).filter((c) => !columns.includes(c));
const duel = kind === 'duel';
const bad = parsed?.rows.filter((r) => r.problem) ?? [];
const items = parsed?.items ?? [];
const inList = new Set(existing.map((x) => x.videoId));
@@ -113,7 +127,7 @@ export function QuizFileImport({
if (!onCreate || !name.trim() || !items.length) return;
setBusy(true);
try {
await onCreate(name.trim(), items);
await onCreate(name.trim(), items, kind);
} finally {
setBusy(false);
}
@@ -122,11 +136,26 @@ export function QuizFileImport({
return (
<div className="card stack" style={{ gap: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<b>📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}</b>
<b>
📄 {mode === 'create' ? '파일로 만들기' : '파일에서 가져오기'}
{fixedKind === 'duel' && ' (이지선다)'}
</b>
<button type="button" className="btn btn-sm btn-ghost" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
{!fixedKind && (
<Seg
label="퀴즈 종류"
value={chosenKind}
disabled={false}
onChange={setChosenKind}
options={[
{ v: 'normal', label: '🎧 일반 퀴즈 (듣고맞추기)' },
{ v: 'duel', label: '🆚 이지선다 (조회수 비교)' },
]}
/>
)}
<div className="row">
<label className="btn btn-primary">
{file ? '다른 파일 고르기' : '파일 고르기 (.xlsx, .csv)'}
@@ -142,12 +171,18 @@ export function QuizFileImport({
}}
/>
</label>
<button type="button" className="btn" onClick={downloadTemplate}>
<button type="button" className="btn" onClick={() => downloadTemplate(kind)}>
📥 빈 양식 받기
</button>
{file && <span className="muted small">{file.name}</span>}
</div>
{!file && (
{!file && duel && (
<p className="muted small" style={{ margin: 0 }}>
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>, <b>제목</b>, <b>조회수</b>는 꼭 있어야 하고 <b>가수</b>는 카드에 같이 보여요. 조회수는 1234567, 1,234,567,
123만, 1.2억처럼 써도 돼요. 게임에서는 곡을 무작위로 두 개씩 짝지어 A/B 카드로 보여 줘요.
</p>
)}
{!file && !duel && (
<p className="muted small" style={{ margin: 0 }}>
한 줄에 한 곡씩, 첫 줄은 열 이름이에요. <b>유튜브 영상 링크</b>와 <b>정답</b>(예: 게임 제목)은 꼭 있어야 하고, <b>설명</b>(예: 노래 제목)은 정답을 공개할 때 같이
보여요. <b>힌트</b> 열은 문제마다 먼저 나오고, 그다음 힌트로 초성이 나와요. <b>순번</b> 열이 있으면 그 순서대로 넣어요. 적힌 값은 고치지 않고 그대로 써요.
@@ -177,16 +212,17 @@ export function QuizFileImport({
</span>
<select className="input sm" value={columns[i] ?? ''} onChange={(e) => setColumn(i, (e.target.value || null) as QuizColumn | null)} aria-label={`${header[i] || `${i + 1}번째 열`} 쓰임`}>
<option value="">안 씀</option>
{COLUMN_ORDER.map((c) => (
{QUIZ_FILE_COLUMNS[kind].map((c) => (
<option key={c} value={c}>
{QUIZ_COLUMN_LABEL[c]}
{colLabel(c, kind)}
</option>
))}
{columns[i] && !QUIZ_FILE_COLUMNS[kind].includes(columns[i]!) && <option value={columns[i]!}>{colLabel(columns[i]!, kind)} (이 종류에서는 안 씀)</option>}
</select>
</label>
))}
</div>
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => QUIZ_COLUMN_LABEL[c]).join(', ')} 열을 골라 주세요.</span>}
{missing.length > 0 && <span className="warn-text small">{missing.map((c) => colLabel(c, kind)).join(', ')} 열을 골라 주세요.</span>}
</div>
{!missing.length && parsed && (
<>
@@ -227,9 +263,9 @@ export function QuizFileImport({
<thead>
<tr>
<th style={{ width: 44 }}>#</th>
<th>정답</th>
<th>설명</th>
<th>힌트</th>
<th>{duel ? '제목' : '정답'}</th>
<th>{duel ? '가수' : '설명'}</th>
<th>{duel ? '조회수' : '힌트'}</th>
<th>영상</th>
</tr>
</thead>
@@ -242,7 +278,13 @@ export function QuizFileImport({
{it.titleAnswers.length > 0 && <div className="muted small">또는 {it.titleAnswers.join(', ')}</div>}
</td>
<td className="small">{it.artist || <span className="muted">-</span>}</td>
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
{duel ? (
<td className="small mono" title={`${it.views?.toLocaleString('ko-KR')}회`}>
{viewsLabel(it.views ?? 0)}회
</td>
) : (
<td className="small">{[...it.hints, '초성'].join(' → ')}</td>
)}
<td className="small">
<a href={`https://youtu.be/${it.videoId}`} target="_blank" rel="noreferrer">
{it.videoId} ↗
@@ -266,8 +308,8 @@ export function QuizFileImport({
퀴즈 이름
<input className="input grow" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} aria-label="퀴즈 이름" />
</label>
<button className="btn btn-primary" disabled={busy || !name.trim() || !items.length}>
{busy ? '만드는 중…' : `${items.length}곡으로 만들기`}
<button className="btn btn-primary" disabled={busy || !name.trim() || items.length < (duel ? 2 : 1)}>
{busy ? '만드는 중…' : `${items.length}곡으로 ${duel ? '이지선다 ' : ''}만들기`}
</button>
</form>
) : (

View File

@@ -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() {
</label>
)}
</div>
<p className="muted">직접 만든 퀴즈예요. 방 설정에서 "제작된 퀴즈"를 고르면 이 퀴즈의 곡이 순서대로(또는 섞어서) 전부 나와요. 듣고맞추기에서만 쓸 수 있어요.</p>
<p className="muted">
직접 만든 퀴즈예요. 일반 퀴즈는 방 설정에서 "제작된 퀴즈"를 고르면 곡이 순서대로(또는 섞어서) 전부 나오고, 듣고맞추기에서만 쓸 수 있어요. 🆚 이지선다 퀴즈는 조회수가 든 파일로 만들고, 이지선다
모드에서만 쓸 수 있어요.
</p>
{fromFile && (
<QuizFileImport
mode="create"
onClose={() => 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() {
<b className="nm">{q.name}</b>
{q.description && <span className="muted small clamp2">{q.description}</span>}
<span className="row small" style={{ gap: 6 }}>
{q.kind === 'duel' && <span className="badge teal">🆚 이지선다</span>}
<span className={`badge ${VIS_CLASS[q.visibility]}`}>{VIS_LABEL[q.visibility]}</span>
<span className="muted">
{q.songs}곡 · 플레이 {q.plays}번{all ? ` · ${q.ownerName}` : ''}
@@ -123,7 +132,7 @@ export function QuizzesPage() {
{!fromFile && (
<button type="button" className="quiz-card add plus" onClick={() => setFromFile(true)}>
<span aria-hidden>📄</span> 파일로 만들기
<small className="muted">엑셀(.xlsx)·CSV</small>
<small className="muted">엑셀(.xlsx)·CSV · 일반 / 이지선다</small>
</button>
)}
</div>
@@ -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<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec'>;
const fresh = (it: NewSong): QuizItem => ({ ...it, titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, auto: true, startSec: null, highlightSec: null });
type NewSong = Omit<QuizItem, 'titleAnswers' | 'artistAnswers' | 'hints' | 'fromFile' | 'auto' | 'startSec' | 'highlightSec' | 'views'>;
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<string | null>(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 <p className="muted">불러오는 중…</p>;
const set = (p: Partial<Draft>) => 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() {
</Link>
<h1 className="grow">{draft.name || '이름 없는 퀴즈'}</h1>
{dirty ? <span className="badge warn" role="status">● 저장하지 않은 변경이 있어요</span> : <span className="muted small">저장됨</span>}
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
<button type="button" className="btn" disabled={!draft.items.length} onClick={() => exportQuiz(draft.name, draft.items, kind)} title="곡 목록을 다시 올릴 수 있는 엑셀 파일로 받아요">
📥 엑셀로 내보내기
</button>
<button type="button" className="btn btn-primary" disabled={busy || !dirty} onClick={() => void save()} title="Ctrl+S">
@@ -311,7 +321,8 @@ export function QuizEditor() {
</div>
{owner && (
<p className="muted small" style={{ marginTop: -8 }}>
만든 사람 {owner.ownerName} · {draft.items.length}곡 · 플레이 {owner.plays}번 · <span className={`badge ${VIS_CLASS[draft.visibility]}`}>{VIS_LABEL[draft.visibility]}</span>
{kind === 'duel' && <span className="badge teal">🆚 이지선다</span>} 만든 사람 {owner.ownerName} · {draft.items.length}곡 · 플레이 {owner.plays}번 ·{' '}
<span className={`badge ${VIS_CLASS[draft.visibility]}`}>{VIS_LABEL[draft.visibility]}</span>
</p>
)}
<div className="seg" role="tablist" style={{ maxWidth: 360 }}>
@@ -340,6 +351,7 @@ export function QuizEditor() {
)}
{tab === 'songs' ? (
<SongsTab
kind={kind}
items={draft.items}
db={db}
settings={draft.settings}
@@ -351,7 +363,7 @@ export function QuizEditor() {
onHints={() => draft.settings.hint === 'none' && set({ settings: { ...draft.settings, hint: 'manual' } })}
/>
) : (
<SettingsTab draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
<SettingsTab kind={kind} draft={draft} onChange={set} onDelete={() => setConfirmDelete(true)} />
)}
{leaveTo && (
<Sheet label="저장하지 않은 변경" onClose={() => setLeaveTo(null)}>
@@ -444,6 +456,7 @@ interface VideoInfo {
const looksLikeUrl = (s: string) => /^(https?:\/\/|www\.|youtu\.?be|m\.youtube|music\.youtube)/i.test(s.trim()) || /^[\w-]{11}$/.test(s.trim());
function SongsTab({
kind,
items,
db,
settings,
@@ -454,6 +467,7 @@ function SongsTab({
setFileOpen,
onHints,
}: {
kind: QuizKind;
items: DraftItem[];
db: Record<number, DbInfo | null>;
settings: QuizSettings;
@@ -469,6 +483,7 @@ function SongsTab({
const [dragKey, setDragKey] = useState<string | null>(null);
const [overKey, setOverKey] = useState<string | null>(null);
const selected = items.find((i) => i.key === sel) ?? null;
const duel = kind === 'duel';
const add = (it: NewSong) => {
if (items.some((x) => x.videoId === it.videoId || (it.songId && x.songId === it.songId))) {
toast('이미 목록에 있는 곡이에요.', 'error');
@@ -497,6 +512,7 @@ function SongsTab({
{fileOpen ? (
<QuizFileImport
mode="into"
kind={kind}
existing={items}
onClose={() => setFileOpen(false)}
onApply={(rows, replace) => {
@@ -535,13 +551,18 @@ function SongsTab({
<p className="muted">아직 곡이 없어요. 위에서 제목·가수로 찾거나 유튜브 주소를 붙여 넣어 추가해 주세요.</p>
) : (
<div className="table-wrap">
{duel && items.some((i) => i.views === null) && (
<p className="warn-text small" style={{ margin: '8px 10px' }}>
조회수가 없는 곡 {items.filter((i) => i.views === null).length}곡은 게임에 나오지 않아요. 곡을 눌러 조회수를 넣어 주세요.
</p>
)}
<table className="data-table quiz-songs">
<thead>
<tr>
<th style={{ width: 28 }} aria-label="순서 옮기기" />
<th style={{ width: 44 }}>번호</th>
<th>노래</th>
<th>추가 정답</th>
<th>{duel ? '조회수' : '추가 정답'}</th>
<th>길이</th>
<th>재생 위치</th>
<th style={{ width: 120 }} />
@@ -585,7 +606,13 @@ function SongsTab({
</div>
{it.hints.length > 0 && <div className="muted small">힌트: {it.hints.join(' → ')}</div>}
</td>
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
{duel ? (
<td className="mono small" title={it.views !== null ? `${it.views.toLocaleString('ko-KR')}회` : undefined}>
{it.views !== null ? `${viewsLabel(it.views)}회` : <span className="warn-text">없음</span>}
</td>
) : (
<td className="small">{[...it.titleAnswers, ...it.artistAnswers].join(', ') || <span className="muted">-</span>}</td>
)}
<td className="mono small">{mmss(it.durationSec ?? (it.songId ? db[it.songId]?.durationSec : null))}</td>
<td className="small">{it.auto ? <span className="muted">자동</span> : `처음 ${mmss(it.startSec ?? 0)} · 하이라이트 ${mmss(it.highlightSec)}`}</td>
<td onClick={(e) => e.stopPropagation()}>
@@ -611,6 +638,7 @@ function SongsTab({
{selected && (
<ItemPanel
key={selected.key}
duel={duel}
item={selected}
index={items.indexOf(selected)}
total={items.length}
@@ -1011,6 +1039,7 @@ function ChipsInput({ values, onChange, label, placeholder }: { values: string[]
}
function ItemPanel({
duel,
item,
index,
total,
@@ -1022,6 +1051,7 @@ function ItemPanel({
onClose,
isDuplicate,
}: {
duel: boolean;
item: DraftItem;
index: number;
total: number;
@@ -1037,6 +1067,8 @@ function ItemPanel({
const [url, setUrl] = useState('');
const [pos, setPos] = useState(String(index + 1));
useEffect(() => setPos(String(index + 1)), [index]);
const [viewsText, setViewsText] = useState(item.views === null ? '' : String(item.views));
const viewsBad = parseViews(viewsText) === undefined;
const changeVideo = async () => {
try {
const v = await apiCall<VideoInfo>('POST', '/api/admin/quizzes/pick/video', { url: url.trim() });
@@ -1068,13 +1100,32 @@ function ItemPanel({
onChange={onPatch}
/>
<label className="field">
제목 (정답)
{duel ? '제목 (카드에 보여요)' : '제목 (정답)'}
<input className="input" value={item.title} maxLength={200} onChange={(e) => onPatch({ title: e.target.value })} />
</label>
<label className="field">
{item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
{duel ? '가수' : item.fromFile ? '설명 (정답과 같이 공개돼요)' : '가수'}
<input className="input" value={item.artist} maxLength={200} onChange={(e) => onPatch({ artist: e.target.value })} />
</label>
{duel && (
<label className="field">
조회수 (예: 1234567, 123만, 1.2억)
<input
className="input"
value={viewsText}
inputMode="numeric"
onChange={(e) => {
setViewsText(e.target.value);
const v = parseViews(e.target.value);
if (v !== undefined) onPatch({ views: v });
}}
aria-invalid={viewsBad}
/>
{viewsBad ? <span className="field-error small">조회수를 읽을 수 없어요.</span> : item.views !== null && <span className="muted small">{item.views.toLocaleString('ko-KR')}회</span>}
</label>
)}
{!duel && (
<>
<div className="field">
힌트 (적은 순서대로 하나씩 나오고, 마지막에 초성 힌트가 나와요)
<ChipsInput values={item.hints} onChange={(hints) => onPatch({ hints: hints.slice(0, 5) })} label="힌트" placeholder="힌트 입력 후 Enter (예: 액션 RPG)" />
@@ -1087,6 +1138,8 @@ function ItemPanel({
가수 추가 정답
<ChipsInput values={item.artistAnswers} onChange={(artistAnswers) => onPatch({ artistAnswers })} label="가수 추가 정답" placeholder="다른 표기 입력 후 Enter (예: IU)" />
</div>
</>
)}
{item.fromFile ? (
<p className="muted small">파일에서 넣은 곡이에요. 적힌 값 그대로 쓰고, 서버 노래 DB 검토에는 올라가지 않아요.</p>
) : item.songId ? (
@@ -1144,7 +1197,8 @@ function ItemPanel({
}
// ------------------------------------------------------------------ 설정
function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p: Partial<Draft>) => void; onDelete: () => void }) {
function SettingsTab({ kind, draft, onChange, onDelete }: { kind: QuizKind; draft: Draft; onChange: (p: Partial<Draft>) => void; onDelete: () => void }) {
const duel = kind === 'duel';
const s = draft.settings;
const setS = (p: Partial<QuizSettings>) => onChange({ settings: { ...s, ...p } });
const vis = useMemo(() => QUIZ_VISIBILITIES.find((v) => v.id === draft.visibility)!, [draft.visibility]);
@@ -1169,6 +1223,16 @@ function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p
{vis.help}
</p>
</Section>
{duel ? (
<>
<Section title="제한 시간" tip="카드를 고를 수 있는 시간. 그 안에는 몇 번이든 바꿀 수 있어요">
<Seg label="제한 시간" value={s.duelSec} disabled={false} onChange={(duelSec) => setS({ duelSec })} options={DUEL_SECS.map((v) => ({ v, label: `${v}초` }))} />
</Section>
<Section title="진행 방식" tip="곡은 늘 무작위로 짝지어요">
<Seg label="진행 방식" value={s.duelFlow} disabled={false} onChange={(duelFlow) => setS({ duelFlow })} options={DUEL_FLOWS.map((f) => ({ v: f.id, label: f.label }))} />
</Section>
</>
) : (
<Section title="문제 순서" tip="문제 수는 퀴즈에 든 곡 전부예요">
<Seg
label="문제 순서"
@@ -1181,6 +1245,7 @@ function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p
]}
/>
</Section>
)}
<Section title="재생위치 기본" tip="곡마다 정한 '처음' 위치 또는 '하이라이트' 위치에서 틀어요">
<Seg
label="재생위치 기본"
@@ -1193,10 +1258,12 @@ function SettingsTab({ draft, onChange, onDelete }: { draft: Draft; onChange: (p
]}
/>
</Section>
<Section title="듣고맞출시간">
<Seg label="듣고맞출시간" value={s.listenSec} disabled={false} onChange={(listenSec) => setS({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
</Section>
<PlayRules c={s} ro={false} listening onPatch={(p) => setS(p as Partial<QuizSettings>)} />
{!duel && (
<Section title="듣고맞출시간">
<Seg label="듣고맞출시간" value={s.listenSec} disabled={false} onChange={(listenSec) => setS({ listenSec })} options={LISTEN_SECS.map((v) => ({ v, label: listenLabel(v) }))} />
</Section>
)}
<PlayRules c={s} ro={false} listening duel={duel} onPatch={(p) => setS(p as Partial<QuizSettings>)} />
<section className="sec">
<button type="button" className="btn btn-danger btn-sm" onClick={onDelete}>
퀴즈 지우기

View File

@@ -473,6 +473,33 @@ input.input.sm { width: 76px; }
.songlist a { font-size: 0.85rem; }
.saved-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 50vh; overflow-y: auto; }
.saved-list li { display: flex; align-items: center; gap: 8px; border: 1.5px solid var(--line); border-radius: 10px; padding: 8px 10px; }
/* 이지선다: two cards A / B, avatars of who picked each */
.duel-stage { flex-direction: column; align-items: stretch; gap: 14px; padding: 16px 20px; }
.duel-head .big { font-size: 1.45rem; font-weight: 850; letter-spacing: -0.03em; margin-bottom: 8px; }
.duel-head .bar { margin-bottom: 6px; }
.duel-cards { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.duel-card { position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 4px; padding: 12px; text-align: left; font: inherit; color: var(--text); background: var(--surface); border: 2px solid var(--ink); border-radius: var(--radius); box-shadow: 4px 4px 0 var(--ink); cursor: pointer; min-width: 0; transition: transform 0.1s, box-shadow 0.1s; }
.duel-card:hover { background: color-mix(in srgb, var(--primary-soft) 45%, var(--surface)); }
.duel-card:active { transform: translate(2px, 2px); box-shadow: 2px 2px 0 var(--ink); }
.duel-card.mine { background: var(--primary-soft); border-color: var(--primary); box-shadow: 4px 4px 0 var(--primary); }
.duel-card.playing .duel-thumb { outline: 4px solid var(--mustard); }
.duel-card.won { border-color: var(--correct); box-shadow: 4px 4px 0 var(--correct); background: var(--correct-soft); }
.duel-card.lost { background: var(--surface-2); box-shadow: 2px 2px 0 var(--ink); }
.duel-side { position: absolute; top: -12px; left: -10px; width: 34px; height: 34px; border-radius: 50%; background: var(--mustard); color: #1e1b18; border: 2px solid var(--ink); display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 1.05rem; z-index: 1; }
.duel-thumb { width: 100%; aspect-ratio: 16 / 9; object-fit: cover; border-radius: 10px; border: 1.5px solid var(--line); background: var(--surface-2); margin-bottom: 4px; }
.duel-title { font-weight: 850; font-size: 1.12rem; letter-spacing: -0.02em; line-height: 1.3; overflow-wrap: anywhere; }
.duel-artist { font-size: 0.9rem; font-weight: 650; }
.duel-views { margin-top: 2px; font-weight: 850; font-size: 1.05rem; color: var(--primary); }
.duel-card.won .duel-views { color: var(--correct); }
.duel-state { color: var(--text-sub); font-weight: 700; }
.duel-picks { display: flex; flex-wrap: wrap; gap: 4px; min-height: 26px; margin-top: 4px; }
.duel-pick { display: inline-flex; align-items: center; gap: 2px; }
.gain { font-weight: 900; font-size: 0.82rem; color: var(--correct); }
.gain.rev { color: #9a4510; }
:root[data-theme='dark'] .gain.rev { color: var(--mustard); }
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .gain.rev { color: var(--mustard); } }
.sb .gain { margin-left: 4px; }
@media (max-width: 1100px) {
.ggrid { grid-template-columns: minmax(0, 1fr); }
.ggrid .side { max-height: none; }
@@ -491,6 +518,10 @@ input.input.sm { width: 76px; }
.sinfo .big { font-size: 1.2rem; margin: 2px 0 6px; }
.countdown { font-size: 2.2rem; }
.chat.big .chat-log { max-height: 46vh; }
.duel-cards { gap: 10px; }
.duel-card { padding: 8px; }
.duel-title { font-size: 0.98rem; }
.duel-head .big { font-size: 1.1rem; }
}
/* ---------------------------------------------------------------- responsive */

View File

@@ -42,6 +42,12 @@
- **보고맞출시간**: 문제당 제한 시간. "무제한"이면 정답·스킵까지
- 가사 4줄 → 시간이 갈수록 2줄씩 추가, 제목 단어는 ○로 가림
### 이지선다 (조회수가 더 높은 곡 고르기)
- 이지선다 퀴즈(관리자 → 퀴즈 → 파일로 만들기에서 조회수가 든 파일로 만든 퀴즈)로만 한다. 일반 퀴즈·직접 선택은 고를 수 없다
- **제한 시간**: 10·15·20·30(기본)·45·60·90초. **진행 방식**: 매번 새 두 곡 / 이긴 곡이 남기(연속). **재생위치**: 처음부터 / 하이라이트부터
- 문제 수: 10~100 또는 전부(매번 새 두 곡 = 곡 수÷2, 연속 = 곡 수-1). 다음 문제까지·다음문제인원은 그대로, 정답방식·힌트·스킵·다시듣기는 없다
- 규칙은 12 문서 "이지선다"
## 장르 (여러 개 선택)
멜론 장르 분류와 노라보세 분류를 합쳐 정리. 곡 하나가 여러 장르를 가질 수 있다.

View File

@@ -33,3 +33,4 @@
- 2026-10-22 원곡 찾기 후보 자동 확정 기준 정리(12 문서), 후보 282곡 확정. 제작된 퀴즈 1~3단계: 관리자 퀴즈 편집(곡 추가·검색·순서·복수정답→DB 별칭·수동 저장·설정·공개방식·제한), 곡별 처음·하이라이트 위치 편집기, 방 설정 "제작된 퀴즈 / 직접 선택"과 실제 플레이. 서버 테스트 130개, e2e 전체 통과
- 2026-10-22 제작된 퀴즈 4~6단계: 플레이리스트 가져오기(.6 Lavalink, 유튜브·스포티파이), 검토 대기(전체공개 퀴즈 → 서버 DB, 난이도 조정), 통계 상세(힌트·오답·다시듣기·퀴즈별). 서버 테스트 132개, e2e 전체 통과
- 2026-10-23 퀴즈 파일 A단계: 관리자 → 퀴즈 "파일로 만들기"(.xlsx·.csv, 라이브러리 없이 브라우저가 읽음 — `packages/shared/src/sheet.ts`), 열 이름으로 링크·정답·설명·힌트·순번 등을 찾고(`quiz-file.ts`) 못 찾은 열만 고름, 시트 고르기, 잘못된 링크·같은 영상 줄 표시. 편집 화면 "파일에서 가져오기"(뒤에 추가·목록 바꾸기), "엑셀로 내보내기"(다시 올릴 수 있는 형식)·빈 양식. 파일 곡은 적힌 값 그대로(서버 DB 연결·검토 대기 없음, 설명 비어도 됨). 곡별 힌트(`custom_quiz_items.hints`): 힌트를 하나씩 → 마지막에 초성(자동은 N초마다, 직접선택은 투표마다). 사용자 BGM 파일 390곡 그대로 생성 확인. 테스트 140개, e2e quiz·game·admin·a11y 통과
- 2026-10-23 이지선다(B단계): 모드 "이지선다"와 이지선다 퀴즈(파일의 조회수, `kind`/`views` 013 마이그레이션). 서버 `game/duel.ts`(A/B 카드, 고르기·바꾸기, 시간 끝나면 조회수 공개, 1점·역배 2점, 매번 새 두 곡/연속), 화면 `DuelScreen.tsx`(카드마다 숨은 플레이어 `net/duel-player.ts`로 각자 듣고 이어 듣기, 고른 사람 프로필), 방 설정(제한 시간·진행 방식·재생위치·문제 수), 관리자 파일로 만들기 종류 선택·조회수 편집·내보내기. 테스트 146개, e2e duel(실제 유튜브 이어 듣기 포함)·game·quiz·admin·rooms·login·a11y 통과

View File

@@ -182,6 +182,14 @@
11. 검토 대기(관리자 → 검토 대기): 전체공개로 저장하면 서버 DB에 없는 곡과 DB와 영상·제목·가수·직접 정한 하이라이트가 다른 곡이 올라간다. 다른 값은 항목마다 "DB 유지 / 퀴즈 값"을 고르고, 없는 곡은 연도·장르·난이도를 채워 추가한다(퀴즈 곡이 그 DB 곡과 연결됨). 복수정답은 DB 별칭에 들어가고, 한 번 정한 값(항목+값)은 다시 묻지 않는다
12. 플레이 통계: 문제마다 힌트(시간/투표), 정답이 아닌 입력 수와 사람 수, 다시듣기 수, 제작된 퀴즈·곡을 함께 저장(DB에 없는 퀴즈 곡도 퀴즈 통계에 들어감). 관리자 통계는 곡별·퀴즈별 탭. 난이도 제안은 힌트도 본다(80% 넘게 8초 안에 힌트 30% 미만 → 쉽게, 30% 이하 또는 50% 이하+힌트 60% 이상 → 어렵게)이고 검토 대기 → 난이도 조정에 근거와 함께 나온다. "반영 안 함"은 5번 더 나온 뒤 다시 계산
## 이지선다 (2026-10-22~23, 사용자 답변)
1. 조회수가 더 높은 곡을 고르는 모드. 곡 목록과 조회수는 사용자가 파일(.xlsx·.csv: 영상 링크·제목·가수·조회수, 조회수는 1,234,567·123만·1.2억도 읽음)로 올린다. 서버가 조회수를 모으지 않는다. 조회수 없는 줄은 빠진다
2. 이지선다 퀴즈(`custom_quizzes.kind = 'duel'`, `custom_quiz_items.views`)는 이지선다에서만, 일반 퀴즈는 듣고맞추기에서만 쓴다. 파일로 만들기에서 조회수 열이 있으면 이지선다로 골라진다
3. 문제마다 곡 2개를 무작위로 A/B 카드(썸네일·제목·가수)에 놓는다. 진행 방식은 방에서 고른다: 매번 새 두 곡 / 연속(조회수가 더 높은 곡이 조회수를 보인 채 A로 남고 새 곡이 B로 들어옴, 같으면 A가 남음). 틀려도 탈락 없이 곡이 떨어질 때까지 계속
4. 카드를 누르면 그 곡이 자기 화면에서만 재생되고(모두 같은 순간에 듣지 않음), 누른 카드가 그 사람의 선택이다. 다른 카드를 누르면 그 곡으로 바뀌고, 다시 누르면 멈춘 곳부터 이어서 나온다(카드마다 숨은 플레이어 하나). 재생 중인 카드를 또 누르면 멈춘다. 선택은 제한 시간 전까지 몇 번이든 바꿀 수 있고, 고른 사람의 프로필이 카드 밑에 바로 보인다
5. 제한 시간 기본 30초(방 설정). 시간이 끝나면 두 곡의 조회수를 공개하고 높은 쪽을 고른 사람이 1점. 역배: 맞힌 사람이 딱 1명이고 반대쪽에 2명 이상이면 2점(4:1에서 혼자 맞히면 2점, 1:1·3:2는 1점). 안 고른 사람은 0점(감점 없음), 조회수가 같으면 둘 다 정답
6. 결과 화면은 점수·맞힌 문제·역배 성공 수, 곡 목록에 두 곡과 조회수와 받은 점수
## 원곡 찾기 자동 확정 기준 (2026-10-22)
1. 제목 일치 + 가수 일치(라틴 악센트 무시 JAŸ-Z=JAY-Z, `및`·with·feat 구분, 앞 The 무시, 확정곡 2곡 이상에서 확인된 한글/영문 이름 짝 태연=TAEYEON) + 길이 차이 15초 이내 + 커버·노래방·라이브·다른 버전 아님. "Radio Edit/Original Version"은 같은 녹음으로 본다
2. 쌓인 후보는 `cli.ts reconfirm-youtube`로 저장된 검색 결과를 다시 비교했다(2,313곡 중 282곡 확정). 관리자 원곡 찾기 목록은 채널 이름 대신 실제 가수와 확정 안 된 이유를 보여 준다

253
e2e/duel.e2e.ts Normal file
View File

@@ -0,0 +1,253 @@
/**
* 이지선다 in real browsers (fake player, no YouTube):
* - 관리자 → 퀴즈 → 파일로 만들기: a CSV with a 조회수 column is taken as 이지선다 (rows without views left out), 엑셀로 내보내기
* - 방 설정 → 이지선다 → only 이지선다 퀴즈 are listed; 2 questions from 4 songs
* - three players: tapping a card plays it and picks it, picks move, avatars show under the cards, the views come at
* the end, alone on the higher card against two = 역배 +2; results with the 역배 column (phone screen too)
* - real YouTube: tapping A plays it with sound, B stops A and plays, A again goes on where it stopped
* Run: bun run build && bun e2e/duel.e2e.ts (needs /usr/bin/google-chrome; the YouTube step needs internet, skip with E2E_NO_YT=1)
*/
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright-core';
import { mkdirSync, mkdtempSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { readXlsx } from '../packages/shared/src/sheet';
const PORT = Number(process.env.E2E_PORT ?? 4629);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
const TMP = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-'));
const SUPER = '900000000000000001';
const app = startServer({
config: loadConfig({ PORT: String(PORT), DB_PATH: join(TMP, 'app.db'), PUBLIC_ORIGIN: ORIGIN, SUPERADMIN_DISCORD_IDS: SUPER, DISCORD_CLIENT_ID: '1561284577564037140', DISCORD_CLIENT_SECRET: 'e2e' }),
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
stopWaitMs: 200,
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '사금향', avatar: null }),
gameTiming: { limitMs: 9000, revealMs: 6000 },
});
const db = app.db;
const VIEWS: Record<string, number> = { '노래1': 120_000_000, '노래2': 34_000_000, '노래3': 5_000_000, '노래4': 12_345 };
const browser: Browser = await chromium.launch({
executablePath: process.env.CHROME ?? '/usr/bin/google-chrome',
headless: true,
args: ['--autoplay-policy=document-user-activation-required'],
});
const errors: string[] = [];
const step = async (name: string, fn: () => Promise<void>) => {
const t0 = performance.now();
try {
await fn();
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
} catch (e) {
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
throw e;
}
};
const expect = (ok: unknown, msg: string) => {
if (!ok) throw new Error(msg);
};
async function fakeDiscord(ctx: BrowserContext, discordId: string) {
await ctx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
const res = await fetch(route.request().url(), { redirect: 'manual', headers: { cookie: (await route.request().headerValue('cookie')) ?? '' } });
const consent = new URL(res.headers.get('location')!);
const back = `${ORIGIN}/api/auth/discord/callback?code=${discordId}&state=${consent.searchParams.get('state')}`;
await route.fulfill({ status: 200, headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' }, body: `<script>location.replace(${JSON.stringify(back)})</script>` });
});
}
async function guestPage(name: string, opts: { width?: number; height?: number; mobile?: boolean; fake?: boolean } = {}): Promise<Page> {
const ctx = await browser.newContext({ viewport: { width: opts.width ?? 1440, height: opts.height ?? 900 }, locale: 'ko-KR', isMobile: opts.mobile, hasTouch: opts.mobile });
if (opts.fake !== false) await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
const p = await ctx.newPage();
p.on('pageerror', (e) => errors.push(`${name}: ${e.message}`));
await p.goto(ORIGIN + '/');
await p.getByLabel('게스트 닉네임 (2~12자)').fill(name);
await p.getByRole('button', { name: '게스트로 시작' }).click();
await p.getByRole('button', { name: `내 계정: ${name}` }).waitFor();
return p;
}
const AXE = readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8');
/** axe-core on this screen (docs/03 접근성): no violations allowed. */
async function audit(page: Page, name: string) {
await page.addScriptTag({ content: AXE });
const res = await page.evaluate(async () => (window as any).axe.run(document, { resultTypes: ['violations'] }));
const v = res.violations as { id: string; impact: string; nodes: { target: string[] }[] }[];
expect(v.length === 0, `접근성 ${name}: ${v.map((x) => `${x.id}[${x.impact}](${x.nodes.length}) ${x.nodes[0]?.target?.join(' ')}`).join('; ')}`);
}
const card = (p: Page, side: 'A' | 'B') => p.locator('.duel-card').nth(side === 'A' ? 0 : 1);
const cardTitle = async (p: Page, side: 'A' | 'B') => (await card(p, side).locator('.duel-title').innerText()).trim();
let failed = false;
try {
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
await fakeDiscord(ctx, SUPER);
const host = await ctx.newPage();
host.on('pageerror', (e) => errors.push(`host: ${e.message}`));
await host.goto(`${ORIGIN}/api/auth/discord/start`);
await host.waitForURL(`${ORIGIN}/**`);
let quizId = 0;
await step('파일로 만들기: 조회수 열이 있는 CSV → 이지선다로 골라짐, 조회수 없는 줄은 빠짐 → 4곡으로 만들기 → 내보내기', async () => {
const csv = ['유튜브 링크,제목,가수,조회수', 'https://youtu.be/duelvid0001,노래1,가수1,1.2억', 'duelvid0002,노래2,가수2,"34,000,000"', 'https://youtu.be/duelvid0003,노래3,가수3,500만', 'https://youtu.be/duelvid0004,노래4,가수4,12345회', 'https://youtu.be/duelvid0005,노래5,가수5,'].join('\n');
await host.goto(`${ORIGIN}/admin/quizzes`);
await host.getByRole('button', { name: /파일로 만들기/ }).click();
await host.getByLabel('퀴즈 파일').setInputFiles({ name: '조회수 대결.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) });
await host.getByText('빠지는 줄 1개').waitFor();
expect((await host.getByRole('radio', { name: /이지선다/ }).getAttribute('aria-checked')) === 'true', '조회수 열이 있는데 이지선다로 골라지지 않음');
await host.getByText('조회수가 비어 있어요').waitFor();
await host.locator('td', { hasText: '1.2억회' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-file-preview.png'), fullPage: true });
await host.getByRole('button', { name: '4곡으로 이지선다 만들기' }).click();
await host.waitForURL(/\/admin\/quizzes\/\d+$/);
quizId = Number(new URL(host.url()).pathname.split('/').pop());
await host.locator('.quiz-songs tbody tr').nth(3).waitFor();
const q = db.query<{ kind: string }, [number]>('SELECT kind FROM custom_quizzes WHERE id = ?').get(quizId)!;
const views = db.query<{ title: string; views: number }, [number]>('SELECT title, views FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos').all(quizId);
expect(q.kind === 'duel', `퀴즈 종류: ${q.kind}`);
expect(JSON.stringify(views) === JSON.stringify(Object.entries(VIEWS).map(([title, v]) => ({ title, views: v }))), `저장된 조회수: ${JSON.stringify(views)}`);
await host.getByText('🆚 이지선다').first().waitFor();
const [dl] = await Promise.all([host.waitForEvent('download'), host.getByRole('button', { name: /엑셀로 내보내기/ }).click()]);
const back = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows;
expect(back[0]!.includes('조회수') && back[1]![4] === '120000000', `내보낸 내용: ${JSON.stringify(back.slice(0, 2))}`);
});
let code = '';
const g1 = await guestPage('철수');
const g2 = await guestPage('영희', { width: 390, height: 844, mobile: true });
const all = [host, g1, g2];
await step('방 설정 → 이지선다: 이지선다 퀴즈만 보이고 고르면 "퀴즈 곡 4곡 · 2문제", 손님 2명 입장', async () => {
code = await host.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()).code as string);
await host.goto(`${ORIGIN}/r/${code}`);
await host.locator('.pool-banner').waitFor();
await host.getByRole('radio', { name: '🆚 이지선다' }).click();
await host.getByText('방 설정에서 이지선다 퀴즈를 골라 주세요.').waitFor();
const list = host.getByRole('listbox', { name: '이지선다 퀴즈 목록' });
await list.getByRole('option').first().waitFor();
expect((await list.getByRole('option').count()) === 1, '이지선다 퀴즈가 아닌 것도 보임');
await list.getByRole('option', { name: /조회수 대결/ }).click();
await host.getByText('퀴즈 곡 4곡').waitFor();
await host.locator('.pool-banner', { hasText: '2문제' }).waitFor();
expect((await host.getByRole('radiogroup', { name: '제한 시간' }).getByRole('radio', { name: '30초' }).getAttribute('aria-checked')) === 'true', '제한 시간 기본값이 30초가 아님');
for (const p of [g1, g2]) {
await p.goto(`${ORIGIN}/r/${code}`);
await p.locator('.pool-banner').waitFor();
}
await host.locator('.pl', { hasText: '영희' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-room.png'), fullPage: true });
});
await step('1번: 카드를 누르면 그 곡이 나오고 고른 게 됨, 바꾸기, 고른 사람 프로필이 카드 밑에', async () => {
await host.getByRole('button', { name: '게임 시작' }).click();
for (const p of all) await p.locator('.duel-card').nth(1).waitFor({ timeout: 8000 });
const a = await cardTitle(host, 'A');
const b = await cardTitle(host, 'B');
expect(VIEWS[a] && VIEWS[b], `모르는 곡: ${a}, ${b}`);
expect((await card(host, 'A').locator('.duel-views').innerText()).includes('?'), '시간 전에 조회수가 보임');
const high = VIEWS[a]! > VIEWS[b]! ? 'A' : 'B';
const low = high === 'A' ? 'B' : 'A';
// 철수 goes high first, then changes to low; 영희 picks low; the host alone on high
await card(g1, high).click();
await card(host, high).locator('.duel-pick').first().waitFor();
await card(g1, low).click();
await card(g2, low).click();
await card(host, high).click();
await host.waitForFunction(([h, l]) => {
const cards = document.querySelectorAll('.duel-card');
const n = (i: number) => cards[i]?.querySelectorAll('.duel-pick').length;
return n(h as number) === 1 && n(l as number) === 2;
}, [high === 'A' ? 0 : 1, low === 'A' ? 0 : 1]);
expect(await card(host, high).getAttribute('aria-pressed') === 'true', '방장이 고른 카드 표시가 없음');
await card(host, high).locator('.duel-state', { hasText: '재생 중' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-play.png'), fullPage: true });
await g2.screenshot({ path: join(SHOTS, 'duel-play-phone.png'), fullPage: true });
await audit(host, 'PC 카드 고르기');
await audit(g2, '폰 카드 고르기');
await host.locator('.duel-card.won').waitFor({ timeout: 15000 });
expect((await card(host, high).getAttribute('class'))!.includes('won'), '높은 카드가 이긴 걸로 안 보임');
await host.getByText('역배 성공').first().waitFor();
const views = await card(host, high).locator('.duel-views').innerText();
expect(views.includes('조회수') && !views.includes('?'), `결과 때 조회수가 안 보임: ${views}`);
await card(host, high).locator('.gain', { hasText: '+2' }).waitFor();
await host.locator('.sb.me .sc', { hasText: '2' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-reveal.png'), fullPage: true });
await g2.screenshot({ path: join(SHOTS, 'duel-reveal-phone.png'), fullPage: true });
await audit(host, 'PC 결과 공개');
await g1.emulateMedia({ colorScheme: 'dark' });
await audit(g1, 'PC 다크 결과 공개');
await g1.screenshot({ path: join(SHOTS, 'duel-reveal-dark.png'), fullPage: true });
});
await step('2번: 새 두 곡, 아무도 안 고르면 0점 → 결과 화면에 역배 성공 1', async () => {
await host.locator('.gbar .q', { hasText: '문제 2 / 2' }).waitFor({ timeout: 12000 });
const titles = [await cardTitle(host, 'A'), await cardTitle(host, 'B')];
expect(titles.every((t) => VIEWS[t]), `2번 곡: ${titles}`);
await host.getByRole('heading', { name: '🏁 게임 결과' }).waitFor({ timeout: 25000 });
const row = host.locator('.data-table.rank tbody tr').first();
const cells = await row.locator('td').allInnerTexts();
expect(cells[1] === '사금향' && cells[2] === '2' && cells[3] === '1' && cells[4] === '1', `결과 첫 줄: ${cells}`);
await host.locator('.songlist li', { hasText: '역배' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-result.png'), fullPage: true });
await audit(host, 'PC 게임 결과');
});
if (!process.env.E2E_NO_YT) {
await step('실제 유튜브: A를 누르면 소리 나게 재생, B를 누르면 A가 멈추고 B 재생, 다시 A는 멈춘 곳부터 이어서', async () => {
const r = await host.evaluate(async () => {
const item = (videoId: string, title: string, views: number) => ({ songId: null, videoId, title, artist: '가수', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views });
const res = await fetch('/api/admin/quizzes/file', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name: '유튜브 대결', kind: 'duel', items: [item('VO88htcm09E', '광', 10), item('Q7Q_qavUPdM', '가져가', 20)] }),
});
return (await res.json()).id as number;
});
db.query("UPDATE custom_quizzes SET visibility = 'public' WHERE id = ?").run(r);
const x = await guestPage('유튜브손님', { fake: false });
const rc = await x.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()).code as string);
await x.goto(`${ORIGIN}/r/${rc}`);
await x.getByRole('radio', { name: '🆚 이지선다' }).click();
await x.getByRole('listbox', { name: '이지선다 퀴즈 목록' }).getByRole('option', { name: /유튜브 대결/ }).click();
await x.getByText('퀴즈 곡 2곡').waitFor();
await x.getByRole('button', { name: '게임 시작' }).click();
await x.locator('.duel-card').nth(1).waitFor({ timeout: 8000 });
const st = (side: 'a' | 'b') => x.evaluate((sd) => ({ state: (window as any).mqDuel.state(sd), time: (window as any).mqDuel.time(sd), muted: (window as any).mqDuel.muted(sd) }), side);
// both cards load muted first
await x.waitForFunction(() => (window as any).mqDuel?.state('a') === 2 && (window as any).mqDuel?.state('b') === 2, null, { timeout: 20000 });
await card(x, 'A').click();
await x.waitForFunction(() => (window as any).mqDuel.state('a') === 1 && (window as any).mqDuel.time('a') > 1.2, null, { timeout: 8000 });
const a1 = await st('a');
expect(!a1.muted, `A가 소리 없이 재생 ${JSON.stringify(a1)}`);
await card(x, 'B').click();
await x.waitForFunction(() => (window as any).mqDuel.state('b') === 1 && (window as any).mqDuel.state('a') === 2, null, { timeout: 8000 });
const aStop = (await st('a')).time;
const b1 = await st('b');
expect(!b1.muted, `B가 소리 없이 재생 ${JSON.stringify(b1)}`);
await x.waitForTimeout(600);
await card(x, 'A').click();
await x.waitForFunction(() => (window as any).mqDuel.state('a') === 1 && (window as any).mqDuel.state('b') === 2, null, { timeout: 8000 });
const a2 = await st('a');
console.log(` A 멈춘 위치 ${aStop.toFixed(2)}초 → 다시 눌렀을 때 ${a2.time.toFixed(2)}초`);
expect(a2.time >= aStop - 0.3 && !a2.muted, `A가 이어서 나오지 않음 ${JSON.stringify({ aStop, a2 })}`);
await card(x, 'A').locator('.duel-state', { hasText: '재생 중' }).waitFor();
await x.screenshot({ path: join(SHOTS, 'duel-youtube.png') });
await x.context().close();
});
}
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
} catch (e) {
console.log(e instanceof Error ? e.message.slice(0, 400) : e);
for (const pg of browser.contexts().flatMap((c) => c.pages())) await pg.screenshot({ path: join(SHOTS, `duel-fail-${Math.random().toString(36).slice(2, 6)}.png`) }).catch(() => {});
failed = true;
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);

View File

@@ -11,7 +11,7 @@
"build": "bun run --filter '@mq/web' build",
"typecheck": "tsc -p packages/shared && tsc -p apps/server && tsc -p apps/web",
"test": "bun test --timeout 20000",
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts && bun e2e/quiz.e2e.ts && bun e2e/a11y.e2e.ts && bun e2e/load.ts"
"e2e": "bun run build && bun e2e/login.e2e.ts && bun e2e/rooms.e2e.ts && bun e2e/game.e2e.ts && bun e2e/admin.e2e.ts && bun e2e/quiz.e2e.ts && bun e2e/duel.e2e.ts && bun e2e/a11y.e2e.ts && bun e2e/load.ts"
},
"devDependencies": {
"@types/bun": "1.4.2",

View File

@@ -4,7 +4,12 @@ import { DEFAULT_QUIZ_SETTINGS, QUIZ_ROOM_KEYS, type QuizSettings } from './cust
const roomPart = RoomConfigSchema.pick(Object.fromEntries(QUIZ_ROOM_KEYS.map((k) => [k, true])) as { [K in (typeof QUIZ_ROOM_KEYS)[number]]: true });
export const QuizSettingsSchema = roomPart.extend({ order: z.enum(['ordered', 'random']) });
export const QuizSettingsSchema = roomPart.extend({
order: z.enum(['ordered', 'random']),
// added with 이지선다: settings saved before have none
duelSec: RoomConfigSchema.shape.duelSec.default(DEFAULT_QUIZ_SETTINGS.duelSec),
duelFlow: RoomConfigSchema.shape.duelFlow.default(DEFAULT_QUIZ_SETTINGS.duelFlow),
});
const answers = z.array(z.string().trim().min(1).max(200)).max(30);
const sec = z.number().min(0).max(36000).nullable();
@@ -24,6 +29,7 @@ export const QuizItemSchema = z.object({
auto: z.boolean(),
startSec: sec,
highlightSec: sec,
views: z.number().int().min(0).max(1e15).nullable().default(null),
}).refine((it) => it.fromFile || it.artist.length > 0, { path: ['artist'], message: '가수를 넣어 주세요.' });
export const QuizSaveSchema = z.object({

View File

@@ -12,8 +12,11 @@ export const QUIZ_VISIBILITIES = [
] as const;
export type QuizVisibility = (typeof QUIZ_VISIBILITIES)[number]['id'];
/** 일반 퀴즈 (듣고맞추기) or 이지선다 퀴즈 (조회수가 더 높은 곡 고르기): each is played only in its own mode. */
export type QuizKind = 'normal' | 'duel';
/** Room settings a quiz carries as its defaults (the host may still change them in the room). */
export const QUIZ_ROOM_KEYS = ['listenSec', 'startAt', 'answer', 'strict', 'hint', 'hintVotes', 'skipVotes', 'replayVotes', 'revealSec', 'nextVotes'] as const;
export const QUIZ_ROOM_KEYS = ['listenSec', 'startAt', 'answer', 'strict', 'hint', 'hintVotes', 'skipVotes', 'replayVotes', 'revealSec', 'nextVotes', 'duelSec', 'duelFlow'] as const;
export type QuizRoomDefaults = Pick<RoomConfig, (typeof QUIZ_ROOM_KEYS)[number]>;
export interface QuizSettings extends QuizRoomDefaults {
@@ -46,10 +49,13 @@ export interface QuizItem {
auto: boolean;
startSec: number | null;
highlightSec: number | null;
/** 이지선다 퀴즈: the video's view count as written in the file (null = not given; such songs are left out of games). */
views: number | null;
}
export interface QuizSummary {
id: number;
kind: QuizKind;
name: string;
description: string;
visibility: QuizVisibility;

View File

@@ -2,7 +2,7 @@
export * from './nickname';
export * from './types';
export * from './room-config';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase } from './protocol';
export type { ChatLine, RoomView, RoomPlayerView, ServerMessage, GameView, GameScore, GameHistoryItem, GamePhase, DuelCard, DuelResult, DuelSide, DuelView } from './protocol';
export * from './custom-quiz';
export * from './quiz-file';
export * from './sheet';

View File

@@ -31,6 +31,8 @@ export const ClientMessage = z.discriminatedUnion('t', [
/** Vote toggles (docs/05 스킵·힌트, docs/12 Q3·Q4). */
z.object({ t: z.literal('vote'), kind: z.enum(['skip', 'hint', 'replay', 'next']) }),
z.object({ t: z.literal('typing'), on: z.boolean() }),
/** 이지선다: pick card A or B (again until the time is up; the same card again keeps it). */
z.object({ t: z.literal('pick'), n: z.number().int().min(1), side: z.enum(['a', 'b']) }),
/** Host game controls: pause/resume, end now, 이어풀기, 다시 하기 (back to the waiting room). */
z.object({ t: z.literal('game'), action: z.enum(['pause', 'resume', 'end', 'continue', 'again']) }),
/** Host: leave this player out of this question only (not ready for 30s, docs/12 Q1). */
@@ -88,6 +90,36 @@ export interface GameScore {
/** Average answer time of the questions this player got (tie-break, docs/05 점수). */
avgMs: number | null;
online: boolean;
/** 이지선다: 역배 wins (alone on the right card against 2 or more). */
reverse?: number;
}
export type DuelSide = 'a' | 'b';
/** One card of an 이지선다 question. `views` is hidden until the reveal (연속 방식: the song that stayed shows its own). */
export interface DuelCard {
side: DuelSide;
videoId: string;
title: string;
artist: string;
/** Where this song starts playing (재생위치) and its volume factor (소리 크기 맞추기). */
startSec: number;
gain: number;
views: number | null;
/** Who is on this card right now. */
picks: string[];
}
/** What the reveal of an 이지선다 question shows: the higher card (both when equal) and the points everyone got. */
export interface DuelResult {
winner: DuelSide | 'both';
gains: { id: string; points: number; reverse: boolean }[];
}
export interface DuelView {
flow: import('./room-config').DuelFlow;
cards: DuelCard[];
result: DuelResult | null;
}
export interface GameHistoryItem {
@@ -102,6 +134,12 @@ export interface GameHistoryItem {
winner: string | null;
ms: number | null;
how: 'correct' | 'skip' | 'timeout' | 'end';
/** 이지선다: both songs with their views, the higher one and who got points. */
duel?: {
cards: { side: DuelSide; title: string; artist: string; videoId: string; views: number }[];
winner: DuelSide | 'both';
gains: { id: string; nickname: string; points: number; reverse: boolean }[];
};
}
/** Game state for everyone (docs/05). Never has the video id or the answer of the running question. */
@@ -143,6 +181,8 @@ export interface GameView {
revealUntil: number | null;
/** 이어풀기 possible: songs left that this quiz has not played. */
left: number;
/** 이지선다 only: the two cards of this question. */
duel?: DuelView;
}
export type ServerMessage =

View File

@@ -2,7 +2,7 @@
import { expect, test } from 'bun:test';
import { decodeCsv, parseCsv, readSheetFile, readXlsx, writeXlsx } from './sheet';
import { deflatedZip } from './zip-fixture';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, quizTemplateRows, quizToRows } from './quiz-file';
import { guessColumns, headerRow, parseQuizRows, parseSec, parseVideoId, parseViews, quizTemplateRows, quizToRows } from './quiz-file';
test('reads an Excel-style workbook: shared strings, rich text, numbers, gaps, sheet order and names', async () => {
const x = deflatedZip({
@@ -74,8 +74,8 @@ test('rows → quiz songs: as written, 순번 order, bad links / no answer / rep
test('our export reads back to the same songs (answers, own positions, several hints) and the template is valid', () => {
const items = [
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5 },
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null },
{ songId: null, videoId: 'iIIjS6yDMQo', title: '감옥탈출', artist: '트레일러', titleAnswers: ['구토할배'], artistAnswers: ['trailer'], hints: ['방탈출', '플래시'], fromFile: true, durationSec: null, auto: false, startSec: 12, highlightSec: 61.5, views: null },
{ songId: 3, videoId: 'x0-xFqvJ-U8', title: '갓 오브 워 2', artist: '', titleAnswers: [], artistAnswers: [], hints: [], fromFile: false, durationSec: 200, auto: true, startSec: null, highlightSec: null, views: null },
];
const { rows } = quizToRows(items);
const text = rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
@@ -96,3 +96,43 @@ test('video links and times', () => {
expect(parseVideoId('https://example.com/watch?v=VO88htcm09E')).toBeNull();
expect([parseSec('95'), parseSec('1:35'), parseSec('01:01:01'), parseSec('1분 5초'), parseSec(''), parseSec('조금')]).toEqual([95, 95, 3661, 65, null, undefined]);
});
test('조회수 as people write it', () => {
expect(parseViews('1234567')).toBe(1234567);
expect(parseViews('1,234,567')).toBe(1234567);
expect(parseViews('1,234,567회')).toBe(1234567);
expect(parseViews('123만')).toBe(1230000);
expect(parseViews('1.2억')).toBe(120000000);
expect(parseViews('1억 2,345만')).toBe(123450000);
expect(parseViews('3.4M')).toBe(3400000);
expect(parseViews('12K views')).toBe(12000);
expect(parseViews('1.2345E+9')).toBe(1234500000);
expect(parseViews('')).toBeNull();
expect(parseViews('많음')).toBeUndefined();
});
test('이지선다 파일: 제목·가수·조회수, rows without views are left out, export and template read back', () => {
const rows = [
['순번', '유튜브 링크', '제목', '가수', '조회수'],
['2', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출', '트레일러', '1.2억'],
['1', 'x0-xFqvJ-U8', '갓 오브 워', '', '3,456,789'],
['3', 'https://youtu.be/Es6JbQQE79g', '조회수 없음', '누구', ''],
['4', 'https://youtu.be/VO88htcm09E', '이상한 값', '누구', '많음'],
];
const cols = guessColumns(rows[0]!);
expect(cols).toEqual(['order', 'link', 'answer', 'desc', 'views']);
const p = parseQuizRows(rows, cols, 0, 'duel');
expect(p.items.map((i) => [i.title, i.artist, i.views])).toEqual([
['갓 오브 워', '', 3456789],
['감옥탈출', '트레일러', 120000000],
]);
expect(p.rows.filter((r) => r.problem).map((r) => [r.line, r.problem])).toEqual([
[4, '조회수가 비어 있어요'],
[5, '조회수를 읽을 수 없어요 (많음)'],
]);
const { rows: out } = quizToRows(p.items, 'duel');
const text = out.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(parseQuizRows(text, guessColumns(text[0]!), 0, 'duel').items).toEqual(p.items);
const t = quizTemplateRows('duel').rows.map((r) => r.map((c) => (c === null ? '' : String(c))));
expect(parseQuizRows(t, guessColumns(t[0]!), 0, 'duel').items).toHaveLength(1);
});

View File

@@ -3,9 +3,9 @@
* Values are used as written (no DB lookup): 정답 = the answer, 설명 = shown with it on the reveal, 힌트 columns in order
* before the 초성 hint.
*/
import type { QuizItem } from './custom-quiz';
import type { QuizItem, QuizKind } from './custom-quiz';
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight';
export type QuizColumn = 'link' | 'answer' | 'desc' | 'hint' | 'answers' | 'descAnswers' | 'order' | 'start' | 'highlight' | 'views';
export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
link: '유튜브 영상 링크',
@@ -17,8 +17,33 @@ export const QUIZ_COLUMN_LABEL: Record<QuizColumn, string> = {
order: '순번',
start: '시작(초)',
highlight: '하이라이트(초)',
views: '조회수',
};
/** 이지선다 퀴즈 files call the same columns 제목 / 가수 (shown on the cards). */
export const DUEL_COLUMN_LABEL: Partial<Record<QuizColumn, string>> = { answer: '제목', desc: '가수' };
/** The columns each kind of quiz file uses, in the order the column pickers list them. */
export const QUIZ_FILE_COLUMNS: Record<QuizKind, QuizColumn[]> = {
normal: ['link', 'answer', 'desc', 'hint', 'answers', 'descAnswers', 'order', 'start', 'highlight'],
duel: ['link', 'answer', 'desc', 'views', 'order', 'start', 'highlight'],
};
/**
* 조회수 as people write it: 1234567 · 1,234,567 · 1234567회 · 123만 · 1.2억 · 1억 2,345만 · 3.4M · 12K (Excel's 1.2E+9 too).
* '' → null; anything else → undefined (invalid).
*/
export function parseViews(s: string): number | null | undefined {
const t = s.trim().replace(/[,\s]/g, '').replace(/(회|views?|조회수?)$/i, '');
if (!t) return null;
if (/^\d+(\.\d+)?(e\+?\d+)?$/i.test(t)) return Math.round(Number(t));
const en = /^(\d+(?:\.\d+)?)([kmb])$/i.exec(t);
if (en) return Math.round(Number(en[1]) * { k: 1e3, m: 1e6, b: 1e9 }[en[2]!.toLowerCase() as 'k' | 'm' | 'b']);
const ko = /^(?:(\d+(?:\.\d+)?)억)?(?:(\d+(?:\.\d+)?)만)?(?:(\d+(?:\.\d+)?)천)?(\d+)?$/.exec(t);
if (ko && (ko[1] || ko[2] || ko[3])) return Math.round(Number(ko[1] ?? 0) * 1e8 + Number(ko[2] ?? 0) * 1e4 + Number(ko[3] ?? 0) * 1e3 + Number(ko[4] ?? 0));
return undefined;
}
/** Accepts https://youtu.be/ID, youtube.com/watch?v=ID, /shorts/ID, /embed/ID, /live/ID, music.youtube.com or the bare ID. */
export function parseVideoId(s: string): string | null {
const t = s.trim();
@@ -43,6 +68,7 @@ export function guessColumns(header: string[]): (QuizColumn | null)[] {
const out: (QuizColumn | null)[] = header.map(() => null);
const taken = new Set<QuizColumn>();
const rules: [QuizColumn, RegExp][] = [
['views', /조회수|조회|재생수|views?|viewcount/],
['order', /순번|순서|^order$|^no\.?$/],
['link', /링크|주소|url|영상|유튜브|youtube|video|link/],
['descAnswers', /(설명|가수|노래|artist).*(다른|추가|복수)정답|(다른|추가|복수)정답.*(설명|가수|노래|artist)/],
@@ -107,8 +133,10 @@ export interface ParsedQuizFile {
/**
* Sheet rows (header at `headerAt`) → quiz songs. Empty rows are skipped silently; rows with a bad link, no answer or a
* video already used above are listed with the reason and left out. A 순번 column decides the order (rows without one last).
* 이지선다 (`kind` duel): 정답 = 제목, 설명 = 가수, and every song needs its 조회수.
*/
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0): ParsedQuizFile {
export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[], headerAt = 0, kind: QuizKind = 'normal'): ParsedQuizFile {
const duel = kind === 'duel';
const at = (c: QuizColumn) => columns.indexOf(c);
const hintCols = columns.flatMap((c, i) => (c === 'hint' ? [i] : []));
const cell = (r: string[], i: number) => (i >= 0 ? (r[i] ?? '').trim() : '');
@@ -130,15 +158,22 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
const link = cell(r, at('link'));
const videoId = parseVideoId(link);
const title = cell(r, at('answer')).slice(0, 200);
const views = duel ? parseViews(cell(r, at('views'))) : null;
const problem = !link
? '링크가 비어 있어요'
: !videoId
? '유튜브 링크가 아니에요'
: !title
? '정답이 비어 있어요'
: seen.has(videoId)
? `${seen.get(videoId)}번째 줄과 같은 영상이에요`
: null;
? duel
? '제목이 비어 있어요'
: '정답이 비어 있어요'
: views === null && duel
? '조회수가 비어 있어요'
: views === undefined
? `조회수를 읽을 수 없어요 (${cell(r, at('views')).slice(0, 30)})`
: seen.has(videoId)
? `${seen.get(videoId)}번째 줄과 같은 영상이에요`
: null;
if (problem) {
out.push({ line, item: null, problem, link });
continue;
@@ -156,14 +191,15 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
videoId: videoId!,
title,
artist: cell(r, at('desc')).slice(0, 200),
titleAnswers: splitAnswers(cell(r, at('answers'))).filter((a) => a !== title),
artistAnswers: splitAnswers(cell(r, at('descAnswers'))),
hints: hintCols.map((i) => cell(r, i).slice(0, 200)).filter(Boolean).slice(0, 5),
titleAnswers: duel ? [] : splitAnswers(cell(r, at('answers'))).filter((a) => a !== title),
artistAnswers: duel ? [] : splitAnswers(cell(r, at('descAnswers'))),
hints: duel ? [] : hintCols.map((i) => cell(r, i).slice(0, 200)).filter(Boolean).slice(0, 5),
fromFile: true,
durationSec: null,
auto: !own,
startSec: own ? (start ?? 0) : null,
highlightSec: own ? (highlight ?? null) : null,
views: duel ? (views ?? null) : null,
},
});
}
@@ -171,7 +207,12 @@ export function parseQuizRows(rows: string[][], columns: (QuizColumn | null)[],
}
/** Quiz songs → sheet rows with the headers this file format reads back (내보내기, 빈 양식). */
export function quizToRows(items: QuizItem[]): { rows: (string | number | null)[][]; widths: number[] } {
export function quizToRows(items: QuizItem[], kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
if (kind === 'duel') {
const header = ['순번', QUIZ_COLUMN_LABEL.link, '제목', '가수', '조회수', '시작(초)', '하이라이트(초)'];
const rows = items.map((it, i) => [i + 1, `https://youtu.be/${it.videoId}`, it.title, it.artist, it.views, it.auto ? null : (it.startSec ?? 0), it.auto ? null : it.highlightSec]);
return { rows: [header, ...rows], widths: [6, 32, 30, 24, 16, 10, 14] };
}
const hintN = Math.max(1, ...items.map((i) => i.hints.length));
const hintHeads = hintN === 1 ? ['힌트'] : Array.from({ length: hintN }, (_, i) => `힌트${i + 1}`);
const header = ['순번', QUIZ_COLUMN_LABEL.link, '정답', '설명', ...hintHeads, '다른 정답(;로 구분)', '설명 다른 정답(;로 구분)', '시작(초)', '하이라이트(초)'];
@@ -190,7 +231,14 @@ export function quizToRows(items: QuizItem[]): { rows: (string | number | null)[
}
/** 빈 양식: the headers and one example row. */
export function quizTemplateRows(): { rows: (string | number | null)[][]; widths: number[] } {
export function quizTemplateRows(kind: QuizKind = 'normal'): { rows: (string | number | null)[][]; widths: number[] } {
if (kind === 'duel')
return quizToRows(
[
{ songId: null, videoId: 'v7bnOxV4jAc', title: '라일락', artist: '아이유', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: 123456789 },
],
'duel',
);
return quizToRows([
{
songId: null,
@@ -205,6 +253,7 @@ export function quizTemplateRows(): { rows: (string | number | null)[][]; widths
auto: true,
startSec: null,
highlightSec: null,
views: null,
},
]);
}

View File

@@ -1,11 +1,11 @@
import { z } from 'zod';
import { COUNTS, DEFAULT_ROOM_CONFIG, HINT_TIMES, LISTEN_SECS, LYRICS_SECS, REVEAL_SECS, VOTE_RULES, type RoomConfig } from './room-config';
import { COUNTS, DEFAULT_ROOM_CONFIG, DUEL_SECS, HINT_TIMES, LISTEN_SECS, LYRICS_SECS, REVEAL_SECS, VOTE_RULES, type RoomConfig } from './room-config';
const lit = <T extends readonly (string | number)[]>(xs: T) => z.union(xs.map((x) => z.literal(x)) as unknown as [z.ZodLiteral<T[number]>, z.ZodLiteral<T[number]>]);
export const RoomConfigSchema = z.object({
title: z.string().trim().max(40),
mode: z.enum(['listen', 'artist', 'lyrics']),
mode: z.enum(['listen', 'artist', 'lyrics', 'duel']),
listenSec: lit(LISTEN_SECS),
startAt: z.enum(['start', 'highlight']),
artistIds: z.array(z.number().int().positive()).max(50),
@@ -24,6 +24,8 @@ export const RoomConfigSchema = z.object({
nextVotes: z.enum(VOTE_RULES),
count: lit(COUNTS),
visibility: z.enum(['public', 'private', 'password']),
duelSec: lit(DUEL_SECS),
duelFlow: z.enum(['pairs', 'chain']),
quizId: z.number().int().positive().nullable(),
quizName: z.string().max(60),
});
@@ -36,7 +38,7 @@ export function applyConfigPatch(cur: RoomConfig, patch: unknown): RoomConfig |
if (!r.success) return `설정 값이 올바르지 않아요: ${r.error.issues.map((i) => i.path.join('.')).join(', ')}`;
const c = r.data as RoomConfig;
if (c.yearFrom && c.yearTo && c.yearFrom > c.yearTo) return '시작 연도가 끝 연도보다 늦어요.';
if (c.quizId && c.mode !== 'listen') return '제작된 퀴즈는 듣고맞추기에서만 할 수 있어요.';
if (c.quizId && c.mode !== 'listen' && c.mode !== 'duel') return '제작된 퀴즈는 듣고맞추기나 이지선다에서만 할 수 있어요.';
return c;
}

View File

@@ -7,6 +7,7 @@ export const MODES = [
{ id: 'listen', label: '듣고맞추기', icon: '🎧' },
{ id: 'artist', label: '가수노래 맞추기', icon: '🎤' },
{ id: 'lyrics', label: '가사보고 맞추기', icon: '📜' },
{ id: 'duel', label: '이지선다', icon: '🆚' },
] as const;
export type Mode = (typeof MODES)[number]['id'];
@@ -22,6 +23,14 @@ export type VoteRule = (typeof VOTE_RULES)[number];
export const COUNTS = [10, 20, 30, 50, 100, 0] as const;
/** 다음 문제까지: seconds the answer stays on screen (the music goes on) before the next question. */
export const REVEAL_SECS = [5, 10, 15, 30] as const;
/** 이지선다 제한 시간: seconds to pick a card. */
export const DUEL_SECS = [10, 15, 20, 30, 45, 60, 90] as const;
/** 이지선다 진행: pairs = 매번 새 두 곡, chain = 조회수가 더 높은 곡이 남고 새 곡과 다시 비교. */
export const DUEL_FLOWS = [
{ id: 'pairs', label: '매번 새 두 곡' },
{ id: 'chain', label: '이긴 곡이 남기 (연속)' },
] as const;
export type DuelFlow = (typeof DUEL_FLOWS)[number]['id'];
export interface RoomConfig {
title: string;
@@ -49,7 +58,10 @@ export interface RoomConfig {
nextVotes: VoteRule;
count: (typeof COUNTS)[number];
visibility: 'public' | 'private' | 'password';
/** 제작된 퀴즈: the chosen quiz (listen mode only, every song of it); null = 직접 선택 (장르·연도·난이도). */
/** 이지선다: seconds to pick (the cards can be changed until then). */
duelSec: (typeof DUEL_SECS)[number];
duelFlow: DuelFlow;
/** 제작된 퀴즈: the chosen quiz (일반 퀴즈 = listen mode, 이지선다 퀴즈 = duel mode); null = 직접 선택 (장르·연도·난이도). */
quizId: number | null;
/** Name of that quiz, filled in by the server for room cards. */
quizName: string;
@@ -76,6 +88,8 @@ export const DEFAULT_ROOM_CONFIG: RoomConfig = {
nextVotes: '1/3',
count: 30,
visibility: 'public',
duelSec: 30,
duelFlow: 'pairs',
quizId: null,
quizName: '',
};
@@ -113,6 +127,11 @@ export function listenLabel(s: number): string {
/** One-line summary for room cards (docs/03 열린 방 목록). */
export function configSummary(c: RoomConfig, genreName: (id: string) => string = (x) => x): string[] {
const out: string[] = [];
if (c.mode === 'duel') {
out.push(`🆚 이지선다 · ${c.duelSec}초`, c.duelFlow === 'chain' ? '이긴 곡이 남기' : '매번 새 두 곡');
if (c.quizId) out.unshift(`📋 ${c.quizName || '이지선다 퀴즈'}`);
return out;
}
if (c.quizId) {
out.push(`📋 ${c.quizName || '제작된 퀴즈'}`, `🎧 ${listenLabel(c.listenSec)}${c.startAt === 'highlight' ? ' · 하이라이트' : ''}`);
if (c.answer !== 'title') out.push(c.answer === 'both' ? '제목+가수' : '가수만');
@@ -128,3 +147,10 @@ export function configSummary(c: RoomConfig, genreName: (id: string) => string =
out.push(`공개 ${c.revealSec}초`);
return out;
}
/** 조회수 for people: 1.2억 · 3,456만 · 9,999 (exact numbers go in a tooltip). */
export function viewsLabel(n: number): string {
if (n >= 1e8) return `${(Math.floor(n / 1e7) / 10).toLocaleString('ko-KR')}억`;
if (n >= 1e4) return `${Math.floor(n / 1e4).toLocaleString('ko-KR')}만`;
return n.toLocaleString('ko-KR');
}