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