5~7단계 게임: 숨긴 유튜브 동기화 재생(전원 준비·버퍼링이면 모두 멈춤·30초 늦은 사람 제외·재생 오류 곡 교체), 정답 판정·점수·정답 블록, 입력 중·단축키, 힌트·스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기 + 마지막 사람이 나가면 방 바로 닫기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 22:11:14 +09:00
parent af2dce5b50
commit 7266fc8d25
27 changed files with 3461 additions and 46 deletions

View File

@@ -0,0 +1,165 @@
/**
* What a game needs about one song (docs/05): answer spellings, video, start position, reveal card, lyrics card.
*/
import type { Database } from 'bun:sqlite';
import type { RoomConfig } from '@mq/shared';
export interface QuizSong {
id: number;
title: string;
artist: string;
year: number | null;
durationSec: number | null;
videoId: string | null;
highlightSec: number | null;
genres: string[];
/** Level shown on the reveal card: the 'all' scope level when there is one. */
level: number | null;
titleAliases: string[];
artistAliases: string[];
/** Main artist ids (same singer not twice in a row, docs/05 출제 목록). */
artistIds: number[];
lyrics: string | null;
}
export function quizSong(db: Database, id: number): QuizSong | null {
const s = db
.query<
{ id: number; title: string; artist: string; year: number | null; duration_sec: number | null; youtube_id: string | null; highlight_sec: number | null; youtube_status: string; deleted_at: number | null },
[number]
>('SELECT id, title, artist, year, duration_sec, youtube_id, highlight_sec, youtube_status, deleted_at FROM songs WHERE id = ?')
.get(id);
if (!s || s.deleted_at) return null;
const col = <T>(sql: string) => db.query<{ v: T }, [number]>(sql).all(id).map((r) => r.v);
return {
id: s.id,
title: s.title,
artist: s.artist,
year: s.year,
durationSec: s.duration_sec,
videoId: s.youtube_status === 'matched' ? s.youtube_id : null,
highlightSec: s.highlight_sec,
genres: col<string>('SELECT genre_id v FROM song_genres WHERE song_id = ?'),
level: db.query<{ level: number }, [number]>("SELECT level FROM song_levels WHERE song_id = ? ORDER BY scope = 'all' DESC LIMIT 1").get(id)?.level ?? null,
titleAliases: col<string>("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'title'"),
artistAliases: [
...col<string>("SELECT alias v FROM song_aliases WHERE song_id = ? AND part = 'artist'"),
...col<string>('SELECT x.alias v FROM song_artists sa JOIN artist_aliases x ON x.artist_id = sa.artist_id WHERE sa.song_id = ?'),
...col<string>('SELECT a.name v FROM song_artists sa JOIN artists a ON a.id = sa.artist_id WHERE sa.song_id = ?'),
],
artistIds: col<number>("SELECT artist_id v FROM song_artists WHERE song_id = ? AND role = 'main' ORDER BY artist_id"),
lyrics: db.query<{ text: string }, [number]>('SELECT text FROM lyrics WHERE song_id = ?').get(id)?.text ?? null,
};
}
/** First main artist per song, for spreading singers apart. */
export function mainArtists(db: Database, ids: number[]): Map<number, number> {
const out = new Map<number, number>();
for (let i = 0; i < ids.length; i += 500) {
const chunk = ids.slice(i, i + 500);
for (const r of db
.query<{ song_id: number; a: number }, number[]>(`SELECT song_id, MIN(artist_id) a FROM song_artists WHERE song_id IN (${chunk.map(() => '?').join(',')}) GROUP BY song_id`)
.all(...chunk))
out.set(r.song_id, r.a);
}
return out;
}
/** The video stopped working for everyone (deleted 100, embedding off 101/150): the admin sees it as 재생 불가 (docs/12 Q1). */
export function markUnplayable(db: Database, id: number, code: number): void {
db.query("UPDATE songs SET youtube_status = 'dead', note = trim(coalesce(note, '') || ' ' || ?), updated_at = ? WHERE id = ? AND youtube_status = 'matched'").run(
`[재생 오류 ${code}]`,
Date.now(),
id,
);
}
/** Where playback starts and how long the clip is (docs/04 재생위치, docs/08 하이라이트). */
export function clipOf(song: QuizSong, c: RoomConfig): { startSec: number; endSec: number | null } {
const dur = song.durationSec;
let start = 0;
if (c.startAt === 'highlight') start = song.highlightSec ?? (dur ? Math.round(dur * 0.3) : 0);
if (dur && start > dur - 5) start = 0;
if (c.listenSec === 0) return { startSec: start, endSec: dur };
const end = start + c.listenSec;
return { startSec: start, endSec: dur ? Math.min(end, dur) : end };
}
/** Shuffle, push back songs from the room's last 3 games, keep the same singer apart (docs/05 출제 목록 뽑기). */
export function orderSongs(ids: number[], recent: Set<number>, artistOf: Map<number, number>, spreadArtists: boolean, rnd = Math.random): number[] {
const shuffle = (xs: number[]) => {
for (let i = xs.length - 1; i > 0; i--) {
const j = Math.floor(rnd() * (i + 1));
[xs[i], xs[j]] = [xs[j]!, xs[i]!];
}
return xs;
};
const list = [...shuffle(ids.filter((x) => !recent.has(x))), ...shuffle(ids.filter((x) => recent.has(x)))];
if (!spreadArtists) return list;
// Greedy: keep the order, but take the first song whose singer differs from the previous one. When one singer holds more
// than half of what is left, that singer must go now or it would have to repeat later.
const count = new Map<number, number>();
for (const id of list) {
const a = artistOf.get(id);
if (a !== undefined) count.set(a, (count.get(a) ?? 0) + 1);
}
const maxInitial = Math.max(0, ...count.values());
const rest = [...list];
const out: number[] = [];
let prev: number | undefined;
while (rest.length) {
let pick = -1;
if (rest.length < 2 * maxInitial + 2) {
let top: number | undefined;
let topN = 0;
for (const [a, n] of count) if (n > topN) ((top = a), (topN = n));
if (top !== undefined && top !== prev && topN > (rest.length + 1) / 2 - 1) pick = rest.findIndex((x) => artistOf.get(x) === top);
}
if (pick < 0) pick = rest.findIndex((x) => prev === undefined || artistOf.get(x) !== prev);
if (pick < 0) pick = 0;
const [id] = rest.splice(pick, 1);
const a = artistOf.get(id!);
if (a !== undefined) count.set(a, count.get(a)! - 1);
prev = a;
out.push(id!);
}
return out;
}
const norm = (s: string) => s.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');
/**
* 가사 card (docs/08 4. 가사): verse lines (not the repeated chorus), 4 from the middle, then 2 more per hint;
* words of the title are masked with ○.
*/
export function lyricsCard(text: string, title: string, extra = 0): string[] {
const lines = text
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
const seen = new Map<string, number>();
for (const l of lines) seen.set(norm(l), (seen.get(norm(l)) ?? 0) + 1);
// first run of lines that are not repeated (verse 1)
let from = 0;
while (from < lines.length && seen.get(norm(lines[from]!))! > 1) from++;
let to = from;
while (to < lines.length && seen.get(norm(lines[to]!))! === 1) to++;
if (to - from < 4) ((from = 0), (to = lines.length));
const verse = lines.slice(from, to);
const want = 4 + extra * 2;
const mid = Math.max(0, Math.floor((verse.length - 4) / 2));
const picked = verse.slice(mid, mid + want);
if (picked.length < want) picked.push(...lines.slice(to, to + want - picked.length));
return picked.map((l) => maskTitle(l, title));
}
export function maskTitle(line: string, title: string): string {
const bare = title.replace(/[([{【].*?[)\]}】]/g, ' ').trim();
const words = [bare, ...bare.split(/\s+/)].filter((w) => [...w].length >= 2 || /[가-힣]/.test(w));
let out = line;
for (const w of words.sort((a, b) => b.length - a.length)) {
const esc = w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
out = out.replace(new RegExp(esc, 'gi'), (m) => m.replace(/\S/g, '○'));
}
return out;
}