5~7단계 게임: 숨긴 유튜브 동기화 재생(전원 준비·버퍼링이면 모두 멈춤·30초 늦은 사람 제외·재생 오류 곡 교체), 정답 판정·점수·정답 블록, 입력 중·단축키, 힌트·스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기 + 마지막 사람이 나가면 방 바로 닫기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,6 +14,8 @@ export const SiteSettingsSchema = z.object({
|
||||
chatFloodGuard: z.boolean().default(false),
|
||||
chatRatePerSec: z.number().int().min(1).max(50).default(6),
|
||||
chatBurst: z.number().int().min(1).max(100).default(12),
|
||||
/** One question's time limit for short clips (docs/05 문제 진행: 기본 60초, 관리자 설정). */
|
||||
questionLimitSec: z.number().int().min(10).max(600).default(60),
|
||||
});
|
||||
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;
|
||||
|
||||
|
||||
13
apps/server/src/db/migrations/004_saved_quizzes.sql
Normal file
13
apps/server/src/db/migrations/004_saved_quizzes.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
-- 퀴즈 저장·불러오기 (docs/12 Q8): settings, songs played so far, scores per account. Discord accounts only, 20 per account.
|
||||
CREATE TABLE saved_quizzes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
config_json TEXT NOT NULL,
|
||||
played_json TEXT NOT NULL, -- song ids already asked
|
||||
scores_json TEXT NOT NULL, -- [{id, nickname, score, correct, totalMs}]
|
||||
questions INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX saved_quizzes_user ON saved_quizzes(user_id, updated_at);
|
||||
467
apps/server/src/game.test.ts
Normal file
467
apps/server/src/game.test.ts
Normal file
@@ -0,0 +1,467 @@
|
||||
/**
|
||||
* Game engine over real WebSockets (docs/05, docs/12 Q1·Q3·Q4·Q5·Q8) with short timings.
|
||||
* Clients play the browser's part: they report audio ready / stall / clip end like the hidden YouTube player would.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import type { ChatLine, GameView, ServerMessage } from '@mq/shared';
|
||||
import { Catalog } from './collector/catalog';
|
||||
import { Client, api, boot, discordLogin, guest, sleep } from './test-utils';
|
||||
|
||||
type Msg<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
|
||||
const TIMING = { countdownMs: 60, revealMs: 120, resumeLeadMs: 40, clipGraceMs: 150, lateMs: 150, tickMs: 20 };
|
||||
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()));
|
||||
|
||||
function seed(n: number, opts: { artist?: (i: number) => string; lyrics?: boolean } = {}) {
|
||||
const c = new Catalog(s.db);
|
||||
const ids: number[] = [];
|
||||
for (let i = 1; i <= n; i++) {
|
||||
const [id] = c.upsert({ title: `노래${i}`, artists: [{ name: opts.artist?.(i) ?? `가수${i}` }], year: 2000 + i, genres: ['kpop'], source: 't', ref: `s${i}` });
|
||||
c.autoLevel(id!, 'all', 3);
|
||||
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`vid${i}`, id!);
|
||||
if (opts.lyrics) s.db.query('INSERT INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, 0)').run(id!, `첫 줄 ${i}\n둘째 줄\n노래${i} 셋째 줄\n넷째 줄\n다섯째 줄\n후렴\n후렴`, 't');
|
||||
ids.push(id!);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
const last = <T extends ServerMessage['t']>(cl: Client, t: T) => [...cl.messages].reverse().find((m) => m.t === t) as Msg<T> | undefined;
|
||||
/** Wait until the latest game view matches. */
|
||||
const gameWhere = (cl: Client, pred: (g: GameView) => boolean, timeout = 3000) =>
|
||||
new Promise<GameView>((resolve, reject) => {
|
||||
const t0 = Date.now();
|
||||
const tick = () => {
|
||||
const g = last(cl, 'game')?.game;
|
||||
if (g && pred(g)) return resolve(g);
|
||||
if (Date.now() - t0 > timeout) return reject(new Error(`no matching game view; last ${JSON.stringify(g && { phase: g.phase, n: g.n, paused: g.paused, waiting: g.waiting })}`));
|
||||
setTimeout(tick, 5);
|
||||
};
|
||||
tick();
|
||||
});
|
||||
const since = (cl: Client) => cl.messages.length;
|
||||
const nextOf = <T extends ServerMessage['t']>(cl: Client, t: T, from: number, pred: (m: Msg<T>) => boolean = () => true, timeout = 3000) =>
|
||||
new Promise<Msg<T>>((resolve, reject) => {
|
||||
const t0 = Date.now();
|
||||
const tick = () => {
|
||||
const m = cl.messages.slice(from).find((x) => x.t === t && pred(x as Msg<T>)) as Msg<T> | undefined;
|
||||
if (m) return resolve(m);
|
||||
if (Date.now() - t0 > timeout) return reject(new Error(`no ${t} message; last ${JSON.stringify(cl.messages.slice(-2))}`));
|
||||
setTimeout(tick, 5);
|
||||
};
|
||||
tick();
|
||||
});
|
||||
|
||||
/** Pending catalog for the next room(): seeding needs the server's DB, so it runs right after boot. */
|
||||
let pendingSeed: (() => void)[] = [];
|
||||
function seedLater(fn: () => void) {
|
||||
pendingSeed.push(fn);
|
||||
}
|
||||
|
||||
async function room(players: string[], config: Record<string, unknown> = {}, timing: Record<string, number> = {}) {
|
||||
s = boot({ gameTiming: { ...TIMING, ...timing }, discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
|
||||
for (const f of pendingSeed) f();
|
||||
pendingSeed = [];
|
||||
const users = [];
|
||||
for (const name of players) users.push(await guest(s.base, name));
|
||||
const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: users[0]!.cookie, body: JSON.stringify({ config }) })).body.code;
|
||||
const cls: Client[] = [];
|
||||
for (const u of users) {
|
||||
const cl = await new Client(s.base, u.cookie).connect();
|
||||
cl.send({ t: 'join', code });
|
||||
await cl.waitFor((m) => m.t === 'room');
|
||||
cls.push(cl);
|
||||
}
|
||||
return { users, cls, code };
|
||||
}
|
||||
|
||||
/** Act as browsers: every client reports ready for each prepare it gets. */
|
||||
function autoReady(cls: Client[], skip: Set<Client> = new Set()) {
|
||||
const seen = new Map<Client, number>();
|
||||
const iv = setInterval(() => {
|
||||
for (const cl of cls) {
|
||||
if (skip.has(cl)) continue;
|
||||
const from = seen.get(cl) ?? 0;
|
||||
for (const m of cl.messages.slice(from)) if (m.t === 'prepare') cl.send({ t: 'audio', n: m.n, ev: 'ready' });
|
||||
seen.set(cl, cl.messages.length);
|
||||
}
|
||||
}, 5);
|
||||
return () => clearInterval(iv);
|
||||
}
|
||||
|
||||
const chatLines = (cl: Client) => cl.messages.filter((m) => m.t === 'chat' || m.t === 'answer').map((m) => (m as Msg<'chat'>).line as ChatLine);
|
||||
|
||||
describe('game flow', () => {
|
||||
test('nothing plays until everyone is ready; then one play time for all, answers count after the 3·2·1, first correct gets +1 with the answer block', async () => {
|
||||
seedLater(() => seed(3));
|
||||
const { users, cls } = await room(['방장', '철수']);
|
||||
const [a, b] = cls as [Client, Client];
|
||||
const fa = since(a);
|
||||
a.send({ t: 'start' });
|
||||
const pa = await nextOf(a, 'prepare', fa);
|
||||
const pb = await nextOf(b, 'prepare', fa > 0 ? 0 : 0);
|
||||
expect(pa).toMatchObject({ n: 1, startSec: 0 });
|
||||
expect(pa.videoId).toMatch(/^vid\d$/);
|
||||
expect(pb.videoId).toBe(pa.videoId);
|
||||
// the room state never carries the video id
|
||||
expect(JSON.stringify(last(a, 'game'))).not.toContain(pa.videoId);
|
||||
a.send({ t: 'audio', n: 1, ev: 'ready' });
|
||||
await sleep(80);
|
||||
expect(a.messages.slice(fa).some((m) => m.t === 'play')).toBe(false); // 철수 is not ready
|
||||
expect((await gameWhere(a, (g) => g.waiting.length === 1)).waiting[0]!.id).toBe(users[1]!.id);
|
||||
const fb = since(b);
|
||||
b.send({ t: 'audio', n: 1, ev: 'ready' });
|
||||
const playA = await nextOf(a, 'play', fa);
|
||||
const playB = await nextOf(b, 'play', fb);
|
||||
expect(playA.startAt).toBe(playB.startAt);
|
||||
expect(playA.atSec).toBe(0);
|
||||
// answering during the 3·2·1 is just chat
|
||||
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(pa.videoId)!.title;
|
||||
b.send({ t: 'chat', text: title, n: 'early' });
|
||||
await b.waitFor((m) => m.t === 'chat' && m.line.n === 'early');
|
||||
await sleep(Math.max(0, playA.startAt - Date.now()) + 10);
|
||||
b.send({ t: 'chat', text: '모르겠다' });
|
||||
b.send({ t: 'chat', text: title, n: 'win' });
|
||||
a.send({ t: 'chat', text: title });
|
||||
const ans = (await a.waitFor((m) => m.t === 'answer')) as Msg<'answer'>;
|
||||
expect(ans.line).toMatchObject({ userId: users[1]!.id, text: title, n: 'win', answer: { text: expect.stringContaining(`${title} - `) } });
|
||||
// nothing sits between the answer line and its block: it is one item, and the next line has a higher seq
|
||||
const lines = chatLines(a);
|
||||
const i = lines.findIndex((l) => l.answer);
|
||||
expect(lines[i - 1]!.text).toBe('모르겠다');
|
||||
const g = await gameWhere(a, (x) => x.phase === 'reveal');
|
||||
expect(g.scores[0]).toMatchObject({ id: users[1]!.id, score: 1, correct: 1 });
|
||||
expect(g.history[0]).toMatchObject({ n: 1, title, winnerId: users[1]!.id, how: 'correct' });
|
||||
expect(g.history[0]!.ms).toBeGreaterThanOrEqual(0);
|
||||
// reveal ends → question 2 is prepared
|
||||
await nextOf(a, 'prepare', fa, (m) => m.n === 2);
|
||||
});
|
||||
|
||||
test('a stall pauses everyone at the same position, timers stop, and play resumes for all from there', async () => {
|
||||
seedLater(() => seed(2));
|
||||
const { cls } = await room(['방장', '철수'], { listenSec: 30 });
|
||||
const [a, b] = cls as [Client, Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
const p1 = await nextOf(a, 'play', 0);
|
||||
await sleep(p1.startAt - Date.now() + 120);
|
||||
const fa = since(a);
|
||||
b.send({ t: 'audio', n: 1, ev: 'stall' });
|
||||
await nextOf(a, 'pause', fa);
|
||||
const paused = (await nextOf(a, 'game', fa, (m) => !!m.game?.paused)).game!;
|
||||
expect(paused.paused).toMatchObject({ reason: 'stall' });
|
||||
expect(paused.clock.runningSince).toBeNull();
|
||||
const frozen = paused.clock.elapsedMs;
|
||||
const resume = await nextOf(a, 'play', fa);
|
||||
expect(resume.atSec).toBeGreaterThan(0.08);
|
||||
expect(resume.atSec).toBeLessThan(0.4);
|
||||
const re = await nextOf(a, 'prepare', fa);
|
||||
expect(re.startSec).toBe(resume.atSec);
|
||||
const after = await gameWhere(a, (g) => !g.paused && g.clock.runningSince !== null);
|
||||
expect(after.clock.elapsedMs).toBe(frozen);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('the clip ends by reports (or grace), the question goes on until the time limit; 끝까지 ends the question with the song', async () => {
|
||||
seedLater(() => seed(2));
|
||||
const { cls } = await room(['방장', '철수'], { listenSec: 1 });
|
||||
const [a, b] = cls as [Client, Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
const p = await nextOf(a, 'play', 0);
|
||||
expect(p.endSec).toBe(1);
|
||||
await sleep(p.startAt - Date.now() + 30);
|
||||
a.send({ t: 'audio', n: 1, ev: 'clipEnd' });
|
||||
b.send({ t: 'audio', n: 1, ev: 'clipEnd' });
|
||||
const g = await gameWhere(a, (x) => x.clipOver);
|
||||
expect(g.phase).toBe('play'); // still answerable
|
||||
stop();
|
||||
});
|
||||
|
||||
test('time limit ends a question with no winner; the clock does not count paused time', async () => {
|
||||
seedLater(() => seed(2));
|
||||
const { cls } = await room(['혼자'], { listenSec: 5 }, { limitMs: 300 });
|
||||
const [ca] = cls as [Client];
|
||||
const stop = autoReady([ca]);
|
||||
ca.send({ t: 'start' });
|
||||
const p = await nextOf(ca, 'play', 0);
|
||||
await sleep(p.startAt - Date.now() + 100);
|
||||
ca.send({ t: 'game', action: 'pause' });
|
||||
await gameWhere(ca, (g) => g.paused?.reason === 'host');
|
||||
await sleep(400); // longer than the limit, but paused
|
||||
expect(last(ca, 'game')!.game!.phase).toBe('play');
|
||||
ca.send({ t: 'game', action: 'resume' });
|
||||
const g = await gameWhere(ca, (x) => x.phase === 'reveal');
|
||||
expect(g.history[0]).toMatchObject({ how: 'timeout', winnerId: null });
|
||||
expect(chatLines(ca).find((l) => l.answer)?.answer?.none).toBe(true);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('someone not ready blocks the start; after 30s the host may leave them out of this question only', async () => {
|
||||
seedLater(() => seed(3));
|
||||
const { users, cls } = await room(['방장', '느림']);
|
||||
const [a, b] = cls as [Client, Client];
|
||||
const stop = autoReady(cls, new Set([b]));
|
||||
a.send({ t: 'start' });
|
||||
await gameWhere(a, (g) => g.waiting.some((w) => w.id === users[1]!.id));
|
||||
a.send({ t: 'exclude', userId: users[1]!.id });
|
||||
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('30초');
|
||||
await sleep(170);
|
||||
b.send({ t: 'exclude', userId: users[0]!.id });
|
||||
expect(((await b.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('방장만');
|
||||
const fa = since(a);
|
||||
a.send({ t: 'exclude', userId: users[1]!.id });
|
||||
await nextOf(a, 'play', fa);
|
||||
const g = await gameWhere(a, (x) => x.excluded.includes(users[1]!.id));
|
||||
expect(g.phase).toBe('play');
|
||||
// excluded players cannot answer this question
|
||||
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title;
|
||||
await sleep(80);
|
||||
b.send({ t: 'chat', text: title, n: 'x' });
|
||||
await a.waitFor((m) => m.t === 'chat' && m.line.n === 'x');
|
||||
expect(last(a, 'game')!.game!.phase).toBe('play');
|
||||
stop();
|
||||
});
|
||||
|
||||
test('a disconnected player is not waited for', async () => {
|
||||
seedLater(() => seed(2));
|
||||
const { cls } = await room(['방장', '나감']);
|
||||
const [a, b] = cls as [Client, Client];
|
||||
const stop = autoReady([a]);
|
||||
a.send({ t: 'start' });
|
||||
await nextOf(b, 'prepare', 0);
|
||||
b.close();
|
||||
await nextOf(a, 'play', 0);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('player error 150 swaps the song for everyone under the same number and marks it unplayable', async () => {
|
||||
seedLater(() => seed(3));
|
||||
const { cls } = await room(['방장', '철수']);
|
||||
const [a, b] = cls as [Client, Client];
|
||||
a.send({ t: 'start' });
|
||||
const first = await nextOf(a, 'prepare', 0);
|
||||
const fa = since(a);
|
||||
b.send({ t: 'audio', n: 1, ev: 'error', code: 150 });
|
||||
const again = await nextOf(a, 'prepare', fa);
|
||||
expect(again.n).toBe(1);
|
||||
expect(again.videoId).not.toBe(first.videoId);
|
||||
expect(s.db.query<{ youtube_status: string }, [string]>('SELECT youtube_status FROM songs WHERE youtube_id = ?').get(first.videoId)!.youtube_status).toBe('dead');
|
||||
expect((await gameWhere(a, (g) => g.n === 1)).total).toBe(2);
|
||||
});
|
||||
|
||||
test('skip votes over the connected players (1/2 of 2 → 1), hint votes when 직접선택, replay restarts the clip for all', async () => {
|
||||
seedLater(() => seed(3));
|
||||
const { users, cls } = await room(['방장', '철수'], { skipVotes: '2/3', hint: 'manual', hintVotes: '1', replayVotes: '1/2', listenSec: 10 });
|
||||
const [a, b] = cls as [Client, Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
const p = await nextOf(a, 'play', 0);
|
||||
await sleep(p.startAt - Date.now() + 80);
|
||||
let g = await gameWhere(a, (x) => x.phase === 'play');
|
||||
expect(g.need).toEqual({ skip: 2, hint: 1, replay: 1 });
|
||||
a.send({ t: 'vote', kind: 'hint' });
|
||||
g = await gameWhere(a, (x) => !!x.hint);
|
||||
expect(g.hint).toMatch(/^ㄴㄹ\d+$/);
|
||||
const fa = since(a);
|
||||
b.send({ t: 'vote', kind: 'replay' });
|
||||
const re = await nextOf(a, 'prepare', fa);
|
||||
expect(re.startSec).toBe(0);
|
||||
const rp = await nextOf(a, 'play', fa);
|
||||
expect(rp.atSec).toBe(0);
|
||||
a.send({ t: 'vote', kind: 'skip' });
|
||||
g = await gameWhere(a, (x) => x.votes.skip.length === 1);
|
||||
expect(g.phase).toBe('play');
|
||||
a.send({ t: 'vote', kind: 'skip' }); // toggle off
|
||||
await gameWhere(a, (x) => x.votes.skip.length === 0);
|
||||
a.send({ t: 'vote', kind: 'skip' });
|
||||
b.send({ t: 'vote', kind: 'skip' });
|
||||
g = await gameWhere(a, (x) => x.phase === 'reveal');
|
||||
expect(g.history[0]!.how).toBe('skip');
|
||||
expect(chatLines(a).find((l) => l.answer)?.text).toContain('스킵');
|
||||
expect(users.length).toBe(2);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('hint off / timed: the server explains instead of counting the vote', async () => {
|
||||
seedLater(() => seed(2));
|
||||
const { cls } = await room(['방장'], { hint: 30 });
|
||||
const [a] = cls as [Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
await nextOf(a, 'play', 0);
|
||||
a.send({ t: 'vote', kind: 'hint' });
|
||||
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toMatch(/힌트는 \d+초 뒤에 공개돼요/);
|
||||
stop();
|
||||
});
|
||||
|
||||
test('somebody joining mid-game plays from the next question', async () => {
|
||||
seedLater(() => seed(3));
|
||||
const { cls, code } = await room(['방장']);
|
||||
const [a] = cls as [Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
await nextOf(a, 'play', 0);
|
||||
const c = await guest(s.base, '늦게옴');
|
||||
const cc = await new Client(s.base, c.cookie).connect();
|
||||
cc.send({ t: 'join', code });
|
||||
const g = await gameWhere(cc, (x) => x.phase === 'play');
|
||||
expect(g.participants).not.toContain(c.id);
|
||||
expect(cc.messages.some((m) => m.t === 'prepare')).toBe(false);
|
||||
stop();
|
||||
cc.close();
|
||||
});
|
||||
|
||||
test('result → 이어풀기 leaves out the songs already asked and keeps the scores; 다시 하기 goes back with scores at 0', async () => {
|
||||
let ids: number[] = [];
|
||||
seedLater(() => (ids = seed(4)));
|
||||
const { users, cls } = await room(['방장'], { count: 10 });
|
||||
const [a] = cls as [Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
const answerAll = async (round: number) => {
|
||||
for (let n = 1; ; n++) {
|
||||
const p = await nextOf(a, 'play', 0, (m) => m.n === n && !a.messages.some((x) => x.t === 'answer' && false));
|
||||
await sleep(Math.max(0, p.startAt - Date.now()) + 10);
|
||||
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title;
|
||||
a.send({ t: 'chat', text: title });
|
||||
const g = await gameWhere(a, (x) => x.history.length === n);
|
||||
if (g.n >= g.total) return g;
|
||||
await gameWhere(a, (x) => x.n === n + 1);
|
||||
void round;
|
||||
}
|
||||
};
|
||||
let g = await answerAll(1);
|
||||
expect(g.total).toBe(4); // 10 asked, only 4 songs
|
||||
g = await gameWhere(a, (x) => x.phase === 'result');
|
||||
expect(g.scores[0]).toMatchObject({ id: users[0]!.id, score: 4 });
|
||||
expect(g.left).toBe(0);
|
||||
a.send({ t: 'game', action: 'continue' });
|
||||
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('모두 풀었어요');
|
||||
// two more songs appear: 이어풀기 plays only those, scores go on
|
||||
const more = seed2(2);
|
||||
const fa = since(a);
|
||||
a.send({ t: 'game', action: 'continue' });
|
||||
await gameWhere(a, (x) => x.phase !== 'result' && x.n === 1 && x.history.length === 0);
|
||||
const asked: string[] = [];
|
||||
for (let n = 1; n <= 2; n++) {
|
||||
const pr = await nextOf(a, 'prepare', fa, (m) => m.n === n);
|
||||
asked.push(pr.videoId);
|
||||
const p = await nextOf(a, 'play', fa, (m) => m.n === n);
|
||||
await sleep(Math.max(0, p.startAt - Date.now()) + 10);
|
||||
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(pr.videoId)!.title;
|
||||
a.send({ t: 'chat', text: title });
|
||||
await gameWhere(a, (x) => x.history.length === n);
|
||||
}
|
||||
expect(asked.sort()).toEqual(more.sort());
|
||||
g = await gameWhere(a, (x) => x.phase === 'result');
|
||||
expect(g.scores[0]!.score).toBe(6);
|
||||
const fb = since(a);
|
||||
a.send({ t: 'game', action: 'again' });
|
||||
await nextOf(a, 'game', fb, (m) => m.game === null);
|
||||
expect(s.rooms.roomOf(users[0]!.id)!.status).toBe('lobby');
|
||||
expect(s.rooms.roomOf(users[0]!.id)!.quiz.scores.size).toBe(0);
|
||||
expect(ids.length).toBe(4);
|
||||
stop();
|
||||
|
||||
function seed2(k: number) {
|
||||
const c = new Catalog(s.db);
|
||||
const vids: string[] = [];
|
||||
for (let i = 1; i <= k; i++) {
|
||||
const [id] = c.upsert({ title: `추가곡${i}`, artists: [{ name: `추가가수${i}` }], year: 2020, genres: ['kpop'], source: 't', ref: `m${i}` });
|
||||
c.autoLevel(id!, 'all', 3);
|
||||
s.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`more${i}`, id!);
|
||||
vids.push(`more${i}`);
|
||||
}
|
||||
return vids;
|
||||
}
|
||||
});
|
||||
|
||||
test('host can end the game; the same singer never plays twice in a row when others are left', async () => {
|
||||
seedLater(() => seed(6, { artist: (i) => (i <= 3 ? '같은가수' : `가수${i}`) }));
|
||||
const { cls } = await room(['방장']);
|
||||
const [a] = cls as [Client];
|
||||
const stop = autoReady(cls);
|
||||
a.send({ t: 'start' });
|
||||
const order: string[] = [];
|
||||
for (let n = 1; n <= 6; n++) {
|
||||
const pr = await nextOf(a, 'prepare', 0, (m) => m.n === n);
|
||||
order.push(s.db.query<{ artist: string }, [string]>('SELECT artist FROM songs WHERE youtube_id = ?').get(pr.videoId)!.artist);
|
||||
a.send({ t: 'vote', kind: 'skip' });
|
||||
await gameWhere(a, (x) => x.history.length === n);
|
||||
}
|
||||
for (let i = 1; i < order.length; i++) if (order[i] === '같은가수') expect(order[i - 1]).not.toBe('같은가수');
|
||||
await gameWhere(a, (x) => x.phase === 'result');
|
||||
stop();
|
||||
});
|
||||
|
||||
test('lyrics mode: no audio, a masked lyrics card, the answer still counts', async () => {
|
||||
seedLater(() => seed(2, { lyrics: true }));
|
||||
const { users, cls } = await room(['방장'], { mode: 'lyrics' });
|
||||
const [a] = cls as [Client];
|
||||
a.send({ t: 'start' });
|
||||
const g = await gameWhere(a, (x) => x.phase === 'play' && !!x.lyrics);
|
||||
expect(a.messages.some((m) => m.t === 'prepare')).toBe(false);
|
||||
expect(g.lyrics!.length).toBe(4);
|
||||
expect(g.lyrics!.join('\n')).not.toMatch(/노래\d/);
|
||||
expect(g.lyrics!.join('\n')).toContain('○○○');
|
||||
await sleep(Math.max(0, g.startAt! - Date.now()) + 10);
|
||||
const n = /첫 줄 (\d)/.exec(g.lyrics!.join('\n'))?.[1];
|
||||
a.send({ t: 'chat', text: `노래${n}` });
|
||||
const r = await gameWhere(a, (x) => x.phase === 'reveal');
|
||||
expect(r.history[0]!.winnerId).toBe(users[0]!.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('퀴즈 저장·불러오기 (docs/12 Q8)', () => {
|
||||
test('guests cannot save; a Discord host saves, loads in a new room, and players keep their scores', async () => {
|
||||
seedLater(() => seed(3));
|
||||
const { cls } = await room(['손님방장'], { count: 10 });
|
||||
const [g] = cls as [Client];
|
||||
g.send({ t: 'save', name: '안됨' });
|
||||
expect(((await g.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('디스코드');
|
||||
g.close();
|
||||
|
||||
const login = await discordLogin(s.base, '700000000000000011');
|
||||
const cookie = login.cookie!;
|
||||
const me = (await api(s.base, '/api/me', { cookie })).body.me;
|
||||
const code = (await api(s.base, '/api/rooms', { method: 'POST', cookie, body: JSON.stringify({ config: { count: 10, level: 3 } }) })).body.code;
|
||||
const a = await new Client(s.base, cookie).connect();
|
||||
a.send({ t: 'join', code });
|
||||
await a.waitFor((m) => m.t === 'room');
|
||||
a.send({ t: 'save', name: '빈퀴즈' });
|
||||
expect(((await a.waitFor((m) => m.t === 'error')) as Msg<'error'>).message).toContain('아직 푼 문제가');
|
||||
const stop = autoReady([a]);
|
||||
a.send({ t: 'start' });
|
||||
const p = await nextOf(a, 'play', 0, (m) => m.n === 1);
|
||||
await sleep(Math.max(0, p.startAt - Date.now()) + 10);
|
||||
const title = s.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(last(a, 'prepare')!.videoId)!.title;
|
||||
a.send({ t: 'chat', text: title });
|
||||
await gameWhere(a, (x) => x.history.length === 1);
|
||||
a.send({ t: 'save', name: '중간' });
|
||||
expect(((await a.waitFor((m) => m.t === 'error' && m.message.includes('멈춘'))) as Msg<'error'>).message).toContain('멈춘');
|
||||
a.send({ t: 'game', action: 'end' });
|
||||
await gameWhere(a, (x) => x.phase === 'result');
|
||||
a.send({ t: 'save', name: '금요일 퀴즈' });
|
||||
const saved = (await a.waitFor((m) => m.t === 'saved')) as Msg<'saved'>;
|
||||
const list = (await api(s.base, '/api/quizzes', { cookie })).body.quizzes;
|
||||
expect(list).toEqual([expect.objectContaining({ id: saved.id, name: '금요일 퀴즈', questions: 1, players: 1 })]);
|
||||
// a new room: load → start asks only the other 2 songs, the score goes on from 1
|
||||
const fb = since(a);
|
||||
a.send({ t: 'game', action: 'again' });
|
||||
await nextOf(a, 'game', fb, (m) => m.game === null);
|
||||
a.send({ t: 'config', patch: { level: 5 } });
|
||||
a.send({ t: 'load', id: saved.id });
|
||||
const r = (await a.waitFor((m) => m.t === 'room' && m.room.config.level === 3 && m.room.config.count === 10)) as Msg<'room'>;
|
||||
expect(r.room.config.count).toBe(10);
|
||||
a.send({ t: 'start' });
|
||||
const gv = await gameWhere(a, (x) => x.phase !== 'result' && x.n === 1 && x.history.length === 0);
|
||||
expect(gv.total).toBe(2);
|
||||
expect(gv.scores[0]).toMatchObject({ id: me.id, score: 1 });
|
||||
stop();
|
||||
// only the owner can delete
|
||||
expect((await api(s.base, `/api/quizzes/${saved.id}`, { method: 'DELETE', cookie })).res.status).toBe(200);
|
||||
expect((await api(s.base, '/api/quizzes', { cookie })).body.quizzes).toEqual([]);
|
||||
});
|
||||
});
|
||||
545
apps/server/src/game/engine.ts
Normal file
545
apps/server/src/game/engine.ts
Normal file
@@ -0,0 +1,545 @@
|
||||
/**
|
||||
* Quiz engine (docs/05 게임 진행, docs/12 Q1·Q3·Q4·Q5·Q8). One per running game, owned by its Room.
|
||||
*
|
||||
* Playback rule (docs/12 Q1): the music moves only while every player of the question can hear it.
|
||||
* prepare → everyone reports ready → play{startAt} for all → stall/blocked → everyone pauses, re-prepares at the same
|
||||
* position → play again. The host may leave out someone not ready for 30s, nobody is dropped automatically.
|
||||
* Two clocks: the clip stops by playback position (clients), the question clock runs from the first play and stops while
|
||||
* everyone is paused; it keeps running after the clip ends.
|
||||
*/
|
||||
import { hintText, isCorrect, voteThreshold, type GameHistoryItem, type GamePhase, type GameView, type ServerMessage } from '@mq/shared';
|
||||
import { clipOf, lyricsCard, mainArtists, markUnplayable, orderSongs, quizSong, type QuizSong } from '../songs/quiz';
|
||||
import { poolIds } from '../songs/pool';
|
||||
import type { Room } from '../rooms/manager';
|
||||
|
||||
export interface GameTiming {
|
||||
/** 3·2·1 before the first play of a question. */
|
||||
countdownMs: number;
|
||||
revealMs: number;
|
||||
/** Lead time for a resume / replay so every client starts together (docs/12 Q1: now + 800ms). */
|
||||
resumeLeadMs: number;
|
||||
/** A client that has not reported the clip end this long after the expected end gets one more stop (docs/12 Q1). */
|
||||
clipGraceMs: number;
|
||||
/** After this long not ready the host may leave the player out of this question. */
|
||||
lateMs: number;
|
||||
tickMs: number;
|
||||
/** Tests only: replaces the site's question time limit for short clips. */
|
||||
limitMs?: number;
|
||||
}
|
||||
export const DEFAULT_TIMING: GameTiming = { countdownMs: 3000, revealMs: 5000, resumeLeadMs: 800, clipGraceMs: 3000, lateMs: 30_000, tickMs: 200 };
|
||||
|
||||
export interface Score {
|
||||
nickname: string;
|
||||
score: number;
|
||||
correct: number;
|
||||
totalMs: number;
|
||||
}
|
||||
|
||||
/** What 이어풀기 / 퀴즈 저장 carry over: songs asked so far and scores per account (docs/12 Q8). */
|
||||
export interface Quiz {
|
||||
played: number[];
|
||||
scores: Map<string, Score>;
|
||||
}
|
||||
export const newQuiz = (): Quiz => ({ played: [], scores: new Map() });
|
||||
|
||||
/** Build the song order for a game. Returns an error message when nothing is left. */
|
||||
export function pickSongs(room: Room): number[] | string {
|
||||
const db = room.deps.db;
|
||||
const ids = poolIds(db, room.config, room.quiz.played);
|
||||
if (!ids.length) return room.quiz.played.length ? '조건에 맞는 곡을 모두 풀었어요.' : '조건에 맞는 곡이 없어요. 장르·연도·난이도를 넓혀 보세요.';
|
||||
const recent = new Set(room.recent.flat());
|
||||
return orderSongs(ids, recent, mainArtists(db, ids), room.config.mode !== 'artist');
|
||||
}
|
||||
|
||||
export class Game {
|
||||
phase: GamePhase = 'prepare';
|
||||
n = 0;
|
||||
total: number;
|
||||
song: QuizSong | null = null;
|
||||
private clip: { startSec: number; endSec: number | null } = { startSec: 0, endSec: null };
|
||||
participants = new Set<string>();
|
||||
excluded = new Set<string>();
|
||||
private ready = new Set<string>();
|
||||
private waitingSince = new Map<string, number>();
|
||||
private awaitingReady = false;
|
||||
private hostHold = false;
|
||||
private resumeAt = 0;
|
||||
private clipDone = new Set<string>();
|
||||
clipOver = false;
|
||||
paused: GameView['paused'] = null;
|
||||
/** Audio timeline: position `audioAtSec` at server time `audioStartAt`; `playing` while it should be running. */
|
||||
private audioStartAt = 0;
|
||||
private audioAtSec = 0;
|
||||
private playing = false;
|
||||
startAt: number | null = null;
|
||||
/** First music start of this question: answers count only after it. */
|
||||
private firstStartAt: number | null = null;
|
||||
private elapsedMs = 0;
|
||||
private runningSince: number | null = null;
|
||||
private limitMs: number | null = null;
|
||||
hint: string | null = null;
|
||||
private lyrics: string[] | null = null;
|
||||
votes = { skip: new Set<string>(), hint: new Set<string>(), replay: new Set<string>() };
|
||||
history: GameHistoryItem[] = [];
|
||||
private revealUntil: number | null = null;
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
/** Songs this game asked, for the room's "last 3 games" list. */
|
||||
private asked: number[] = [];
|
||||
|
||||
constructor(
|
||||
private room: Room,
|
||||
private list: number[],
|
||||
private timing: GameTiming,
|
||||
private now: () => number = Date.now,
|
||||
) {
|
||||
const c = room.config.count;
|
||||
this.total = c ? Math.min(c, list.length) : list.length;
|
||||
}
|
||||
|
||||
get listening(): boolean {
|
||||
return this.room.config.mode !== 'lyrics';
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.timer = setInterval(() => this.tick(), this.timing.tickMs);
|
||||
this.room.say(null, `게임을 시작해요! ${this.total}문제`);
|
||||
this.next();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
private online(id: string): boolean {
|
||||
return this.room.isOnline(id);
|
||||
}
|
||||
/** Players of this question who are connected and not left out. */
|
||||
active(): string[] {
|
||||
return [...this.participants].filter((id) => this.online(id) && !this.excluded.has(id));
|
||||
}
|
||||
private toActive(m: ServerMessage): void {
|
||||
for (const id of this.active()) this.room.send(m, id);
|
||||
}
|
||||
elapsed(now = this.now()): number {
|
||||
return this.elapsedMs + (this.runningSince !== null && now > this.runningSince ? now - this.runningSince : 0);
|
||||
}
|
||||
private stopClock(now: number): void {
|
||||
this.elapsedMs = this.elapsed(now);
|
||||
this.runningSince = null;
|
||||
}
|
||||
private position(now: number): number {
|
||||
if (!this.playing) return this.resumeAt;
|
||||
const p = this.audioAtSec + Math.max(0, now - this.audioStartAt) / 1000;
|
||||
return this.clip.endSec !== null ? Math.min(p, this.clip.endSec) : p;
|
||||
}
|
||||
private need(kind: 'skip' | 'hint' | 'replay'): number | null {
|
||||
const c = this.room.config;
|
||||
const rule = kind === 'skip' ? c.skipVotes : kind === 'hint' ? (c.hint === 'manual' ? c.hintVotes : 'none') : this.listening ? c.replayVotes : 'none';
|
||||
return voteThreshold(rule, this.active().length);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ question flow
|
||||
private next(): void {
|
||||
this.n++;
|
||||
this.setup();
|
||||
}
|
||||
|
||||
/** Load question `n` (also used when a song is replaced under the same number). */
|
||||
private setup(): void {
|
||||
const c = this.room.config;
|
||||
this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length;
|
||||
let song: QuizSong | null = null;
|
||||
while (this.n <= this.total) {
|
||||
song = quizSong(this.room.deps.db, this.list[this.n - 1]!);
|
||||
if (song && (this.listening ? song.videoId : song.lyrics)) break;
|
||||
this.list.splice(this.n - 1, 1);
|
||||
this.total = c.count ? Math.min(c.count, this.list.length) : this.list.length;
|
||||
song = null;
|
||||
}
|
||||
if (!song) return this.finish();
|
||||
const now = this.now();
|
||||
this.song = song;
|
||||
this.clip = this.listening ? clipOf(song, c) : { startSec: 0, endSec: null };
|
||||
this.participants = new Set(this.room.online());
|
||||
this.excluded.clear();
|
||||
this.ready.clear();
|
||||
this.waitingSince.clear();
|
||||
this.clipDone.clear();
|
||||
this.clipOver = false;
|
||||
this.paused = null;
|
||||
this.hostHold = false;
|
||||
this.playing = false;
|
||||
this.startAt = null;
|
||||
this.firstStartAt = null;
|
||||
this.elapsedMs = 0;
|
||||
this.runningSince = null;
|
||||
this.hint = null;
|
||||
this.revealUntil = null;
|
||||
for (const v of Object.values(this.votes)) v.clear();
|
||||
if (this.listening) {
|
||||
this.limitMs = c.listenSec === 0 ? null : (this.timing.limitMs ?? Math.max(this.room.limitSec() * 1000, c.listenSec * 1000 + 5000));
|
||||
this.lyrics = null;
|
||||
this.phase = 'prepare';
|
||||
this.prepareAll(this.clip.startSec);
|
||||
} else {
|
||||
this.limitMs = c.lyricsSec ? c.lyricsSec * 1000 : null;
|
||||
this.lyrics = lyricsCard(song.lyrics!, song.title);
|
||||
this.phase = 'play';
|
||||
this.startAt = this.firstStartAt = now + this.timing.countdownMs;
|
||||
this.runningSince = this.startAt;
|
||||
}
|
||||
this.room.say(null, `${this.n}번째 문제`);
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
/** Everyone loads/seeks muted to `atSec` and reports ready (docs/12 Q1 준비 단계). */
|
||||
private prepareAll(atSec: number): void {
|
||||
const now = this.now();
|
||||
this.resumeAt = atSec;
|
||||
this.awaitingReady = true;
|
||||
this.ready.clear();
|
||||
this.waitingSince.clear();
|
||||
for (const id of this.active()) this.waitingSince.set(id, now);
|
||||
this.toActive({ t: 'prepare', code: this.room.code, n: this.n, videoId: this.song!.videoId!, startSec: atSec, endSec: this.clip.endSec });
|
||||
}
|
||||
|
||||
private checkReady(): void {
|
||||
if (!this.awaitingReady || this.hostHold || (this.phase !== 'prepare' && this.phase !== 'play')) return;
|
||||
const act = this.active();
|
||||
if (!act.length) {
|
||||
// Everyone of this question is gone: whoever is here now plays it.
|
||||
const online = this.room.online();
|
||||
if (!online.length) return;
|
||||
this.participants = new Set(online);
|
||||
this.excluded.clear();
|
||||
return this.prepareAll(this.resumeAt);
|
||||
}
|
||||
if (!act.every((id) => this.ready.has(id))) return;
|
||||
const now = this.now();
|
||||
const first = this.firstStartAt === null;
|
||||
const startAt = now + (first ? this.timing.countdownMs : this.timing.resumeLeadMs);
|
||||
this.awaitingReady = false;
|
||||
this.waitingSince.clear();
|
||||
this.paused = null;
|
||||
this.phase = 'play';
|
||||
this.startAt = startAt;
|
||||
if (first) this.firstStartAt = startAt;
|
||||
this.audioStartAt = startAt;
|
||||
this.audioAtSec = this.resumeAt;
|
||||
this.playing = true;
|
||||
this.runningSince = startAt;
|
||||
this.toActive({ t: 'play', code: this.room.code, n: this.n, startAt, atSec: this.resumeAt, endSec: this.clip.endSec });
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
/** Stop everyone at the same position (buffering / no sound / host). */
|
||||
private pauseAll(reason: 'stall' | 'blocked' | 'host', who: string[]): void {
|
||||
const now = this.now();
|
||||
const pos = this.position(now);
|
||||
this.stopClock(now);
|
||||
this.playing = false;
|
||||
this.resumeAt = pos;
|
||||
this.paused = { reason, who };
|
||||
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
|
||||
if (reason === 'host') {
|
||||
this.hostHold = true;
|
||||
this.awaitingReady = false;
|
||||
} else if (this.listening) this.prepareAll(pos);
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
private endClip(): void {
|
||||
if (this.clipOver) return;
|
||||
this.clipOver = true;
|
||||
this.resumeAt = this.position(this.now());
|
||||
this.playing = false;
|
||||
// 끝까지: the song is over, so is the question (docs/05 문제 진행).
|
||||
if (this.room.config.listenSec === 0) return this.endQuestion(null, 'timeout');
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
private showHint(): void {
|
||||
if (this.hint || !this.song) return;
|
||||
this.hint = hintText(this.song, this.room.config.answer);
|
||||
if (this.lyrics && this.song.lyrics) this.lyrics = lyricsCard(this.song.lyrics, this.song.title, 1);
|
||||
this.votes.hint.clear();
|
||||
this.room.say(null, `힌트가 공개됐어요: ${this.hint}`);
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
private replay(): void {
|
||||
if (!this.listening || !this.song) return;
|
||||
for (const v of Object.values(this.votes)) v.clear();
|
||||
this.clipDone.clear();
|
||||
this.clipOver = false;
|
||||
// 짧은 클립: the time limit counts again from the replay (docs/12 Q4).
|
||||
this.elapsedMs = 0;
|
||||
this.runningSince = null;
|
||||
this.playing = false;
|
||||
this.paused = null;
|
||||
this.hostHold = false;
|
||||
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
|
||||
this.room.say(null, '다 같이 다시 들어요');
|
||||
this.prepareAll(this.clip.startSec);
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
private endQuestion(winner: string | null, how: GameHistoryItem['how'], chat?: { text: string; n?: string }): void {
|
||||
if ((this.phase !== 'prepare' && this.phase !== 'play') || !this.song) return;
|
||||
const now = this.now();
|
||||
const ms = winner ? this.elapsed(now) : null;
|
||||
const s = this.song;
|
||||
if (winner) {
|
||||
const sc = this.room.quiz.scores.get(winner) ?? { nickname: this.room.nick(winner), score: 0, correct: 0, totalMs: 0 };
|
||||
sc.nickname = this.room.nick(winner);
|
||||
sc.score += 1;
|
||||
sc.correct += 1;
|
||||
sc.totalMs += ms!;
|
||||
this.room.quiz.scores.set(winner, sc);
|
||||
}
|
||||
this.history.push({
|
||||
n: this.n,
|
||||
title: s.title,
|
||||
artist: s.artist,
|
||||
year: s.year,
|
||||
level: s.level,
|
||||
genres: s.genres,
|
||||
videoId: s.videoId,
|
||||
winnerId: winner,
|
||||
winner: winner ? this.room.nick(winner) : null,
|
||||
ms,
|
||||
how,
|
||||
});
|
||||
this.room.quiz.played.push(s.id);
|
||||
this.asked.push(s.id);
|
||||
const answer = `${s.title} - ${s.artist}`;
|
||||
if (winner) this.room.post({ userId: winner, text: chat!.text, n: chat!.n, answer: { text: answer } });
|
||||
else this.room.post({ userId: null, text: how === 'skip' ? '스킵했어요 · 정답자 없음' : '시간이 다 됐어요 · 정답자 없음', answer: { text: answer, none: true } });
|
||||
this.stopClock(now);
|
||||
this.awaitingReady = false;
|
||||
this.hostHold = false;
|
||||
this.paused = null;
|
||||
this.playing = false;
|
||||
this.phase = 'reveal';
|
||||
this.revealUntil = now + this.timing.revealMs;
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
finish(): void {
|
||||
if (this.phase === 'result') return;
|
||||
this.phase = 'result';
|
||||
this.playing = false;
|
||||
this.awaitingReady = false;
|
||||
this.paused = null;
|
||||
this.stopClock(this.now());
|
||||
this.stop();
|
||||
if (this.asked.length) {
|
||||
this.room.recent.push(this.asked);
|
||||
while (this.room.recent.length > 3) this.room.recent.shift();
|
||||
}
|
||||
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
|
||||
this.room.say(null, '게임이 끝났어요');
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
tick(now = this.now()): void {
|
||||
if (this.phase === 'reveal') {
|
||||
if (this.revealUntil !== null && now >= this.revealUntil) {
|
||||
if (this.n >= this.total) this.finish();
|
||||
else this.next();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.phase !== 'play') return;
|
||||
const el = this.elapsed(now);
|
||||
const c = this.room.config;
|
||||
if (typeof c.hint === 'number' && !this.hint && this.runningSince !== null && el >= c.hint * 1000) this.showHint();
|
||||
if (this.limitMs !== null && el >= this.limitMs) return this.endQuestion(null, 'timeout');
|
||||
if (this.playing && !this.clipOver && this.clip.endSec !== null) {
|
||||
const expectedEnd = this.audioStartAt + (this.clip.endSec - this.audioAtSec) * 1000;
|
||||
if (now > expectedEnd + this.timing.clipGraceMs) {
|
||||
// Clients that did not report the end get one more stop; the question goes on (docs/12 Q1 재생 길이).
|
||||
for (const id of this.active()) if (!this.clipDone.has(id)) this.room.send({ t: 'pause', code: this.room.code, n: this.n }, id);
|
||||
this.endClip();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ inputs
|
||||
onAudio(userId: string, n: number, ev: 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error', code?: number): void {
|
||||
if (n !== this.n || !this.participants.has(userId) || this.excluded.has(userId) || !this.listening) return;
|
||||
if (ev === 'ready') {
|
||||
if (!this.awaitingReady) return;
|
||||
this.ready.add(userId);
|
||||
this.waitingSince.delete(userId);
|
||||
this.checkReady();
|
||||
this.broadcast();
|
||||
return;
|
||||
}
|
||||
if (ev === 'stall' || ev === 'blocked') {
|
||||
if (this.phase !== 'play' || this.clipOver) return;
|
||||
if (this.paused) {
|
||||
if (!this.paused.who.includes(userId)) this.paused = { ...this.paused, who: [...this.paused.who, userId] };
|
||||
this.ready.delete(userId);
|
||||
if (!this.waitingSince.has(userId) && this.awaitingReady) this.waitingSince.set(userId, this.now());
|
||||
return this.broadcast();
|
||||
}
|
||||
if (!this.playing) return;
|
||||
return this.pauseAll(ev, [userId]);
|
||||
}
|
||||
if (ev === 'clipEnd') {
|
||||
if (this.phase !== 'play' || !this.playing) return;
|
||||
this.clipDone.add(userId);
|
||||
if (this.active().every((id) => this.clipDone.has(id))) this.endClip();
|
||||
return;
|
||||
}
|
||||
if (ev === 'error' && (code === 100 || code === 101 || code === 150) && (this.phase === 'prepare' || this.phase === 'play') && this.song) {
|
||||
// The video is gone or may not be embedded: swap the song for everyone, same question number (docs/12 Q1).
|
||||
markUnplayable(this.room.deps.db, this.song.id, code);
|
||||
this.room.say(null, '이 곡은 재생할 수 없어서 다른 곡으로 바꿨어요');
|
||||
this.toActive({ t: 'pause', code: this.room.code, n: this.n });
|
||||
this.list.splice(this.n - 1, 1);
|
||||
this.setup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Is this chat line the answer? Then it becomes the 정답 줄 + 5줄 블록 (docs/06) and true is returned. */
|
||||
judge(userId: string, text: string, n?: string): boolean {
|
||||
if (this.phase !== 'play' || !this.song || this.firstStartAt === null || this.now() < this.firstStartAt) return false;
|
||||
if (!this.participants.has(userId) || this.excluded.has(userId)) return false;
|
||||
if (!isCorrect(text, this.song, this.room.config.answer, this.room.config.strict)) return false;
|
||||
this.endQuestion(userId, 'correct', { text, n });
|
||||
return true;
|
||||
}
|
||||
|
||||
vote(userId: string, kind: 'skip' | 'hint' | 'replay'): string | null {
|
||||
if (this.phase !== 'play' && this.phase !== 'prepare') return '지금은 투표할 수 없어요.';
|
||||
if (!this.active().includes(userId)) return '이번 문제에 참가하고 있지 않아요.';
|
||||
const c = this.room.config;
|
||||
if (kind === 'hint') {
|
||||
if (c.hint === 'none') return '이 방은 힌트가 꺼져 있어요.';
|
||||
if (this.hint) return '이미 공개된 힌트예요.';
|
||||
if (c.hint !== 'manual') {
|
||||
const left = Math.max(1, Math.ceil(c.hint - (this.elapsed() / 1000)));
|
||||
return `힌트는 ${left}초 뒤에 공개돼요.`;
|
||||
}
|
||||
}
|
||||
if (kind === 'replay') {
|
||||
if (!this.listening) return '가사 모드에는 다시듣기가 없어요.';
|
||||
if (c.replayVotes === 'none') return '이 방은 다시듣기가 꺼져 있어요.';
|
||||
if (this.phase !== 'play' || this.firstStartAt === null) return '노래가 나오면 다시듣기를 누를 수 있어요.';
|
||||
}
|
||||
if (kind === 'skip' && c.skipVotes === 'none') return '이 방은 스킵이 꺼져 있어요.';
|
||||
const set = this.votes[kind];
|
||||
if (set.has(userId)) set.delete(userId);
|
||||
else set.add(userId);
|
||||
this.checkVotes();
|
||||
this.broadcast();
|
||||
return null;
|
||||
}
|
||||
|
||||
private checkVotes(): void {
|
||||
const act = new Set(this.active());
|
||||
for (const v of Object.values(this.votes)) for (const id of v) if (!act.has(id)) v.delete(id);
|
||||
const pass = (k: 'skip' | 'hint' | 'replay') => {
|
||||
const need = this.need(k);
|
||||
return need !== null && this.votes[k].size >= need;
|
||||
};
|
||||
if (pass('skip')) return this.endQuestion(null, 'skip');
|
||||
if (pass('hint') && this.phase === 'play') this.showHint();
|
||||
if (pass('replay') && this.phase === 'play' && this.firstStartAt !== null) this.replay();
|
||||
}
|
||||
|
||||
/** A player went offline or left: do not wait for them, drop their votes (docs/05 진행 중 나간 사람). */
|
||||
onGone(userId: string): void {
|
||||
if (this.phase !== 'prepare' && this.phase !== 'play') return this.broadcast();
|
||||
this.waitingSince.delete(userId);
|
||||
if (this.paused?.who.includes(userId)) this.paused = { ...this.paused, who: this.paused.who.filter((x) => x !== userId) };
|
||||
this.checkVotes();
|
||||
if ((this.phase as GamePhase) !== 'play' && (this.phase as GamePhase) !== 'prepare') return;
|
||||
this.checkReady();
|
||||
if (this.playing && this.active().length && this.active().every((id) => this.clipDone.has(id))) this.endClip();
|
||||
this.broadcast();
|
||||
}
|
||||
|
||||
/** Host: leave out someone who has not been ready for 30s (docs/12 Q1). */
|
||||
exclude(target: string): string | null {
|
||||
const since = this.waitingSince.get(target);
|
||||
if (!this.awaitingReady || since === undefined) return '음원을 기다리는 사람이 아니에요.';
|
||||
if (this.now() - since < this.timing.lateMs) return '30초가 지나야 뺄 수 있어요.';
|
||||
this.excluded.add(target);
|
||||
this.waitingSince.delete(target);
|
||||
this.room.say(null, `${this.room.nick(target)}님은 음원을 불러오지 못해 이번 문제에서 빠져요`);
|
||||
this.checkReady();
|
||||
this.broadcast();
|
||||
return null;
|
||||
}
|
||||
|
||||
hostPause(on: boolean): string | null {
|
||||
if (this.phase !== 'play' && this.phase !== 'prepare') return '지금은 멈출 수 없어요.';
|
||||
if (on) {
|
||||
if (this.hostHold) return null;
|
||||
if (this.playing) {
|
||||
this.pauseAll('host', []);
|
||||
return null;
|
||||
}
|
||||
this.stopClock(this.now());
|
||||
this.hostHold = true;
|
||||
this.paused = { reason: 'host', who: [] };
|
||||
this.broadcast();
|
||||
return null;
|
||||
}
|
||||
if (!this.hostHold) return null;
|
||||
this.hostHold = false;
|
||||
this.paused = null;
|
||||
if (this.phase === 'play' && this.firstStartAt !== null && this.listening && !this.clipOver) this.prepareAll(this.resumeAt);
|
||||
else if (this.phase === 'play' && this.firstStartAt !== null) this.runningSince = this.now();
|
||||
else this.checkReady();
|
||||
this.broadcast();
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ view
|
||||
view(): GameView {
|
||||
const players = new Map<string, boolean>();
|
||||
for (const [id] of this.room.players) players.set(id, this.online(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 c = this.room.config;
|
||||
return {
|
||||
phase: this.phase,
|
||||
n: this.n,
|
||||
total: this.total,
|
||||
mode: c.mode,
|
||||
participants: [...this.participants],
|
||||
excluded: [...this.excluded],
|
||||
waiting: this.awaitingReady ? [...this.waitingSince].map(([id, since]) => ({ id, since })) : [],
|
||||
paused: this.paused,
|
||||
startAt: this.startAt,
|
||||
clock: { elapsedMs: this.elapsedMs, runningSince: this.runningSince, limitMs: this.limitMs },
|
||||
clipSec: this.clip.endSec !== null ? this.clip.endSec - this.clip.startSec : null,
|
||||
clipOver: this.clipOver,
|
||||
hint: this.hint,
|
||||
hintAtSec: typeof c.hint === 'number' ? c.hint : null,
|
||||
lyrics: this.lyrics,
|
||||
votes: { skip: [...this.votes.skip], hint: [...this.votes.hint], replay: [...this.votes.replay] },
|
||||
need: { skip: this.need('skip'), hint: this.need('hint'), replay: this.need('replay') },
|
||||
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 };
|
||||
})
|
||||
.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: Math.max(0, this.list.length - this.asked.length),
|
||||
};
|
||||
}
|
||||
|
||||
broadcast(): void {
|
||||
this.room.send({ t: 'game', code: this.room.code, game: this.view() });
|
||||
}
|
||||
}
|
||||
|
||||
57
apps/server/src/game/saved.ts
Normal file
57
apps/server/src/game/saved.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
/** 퀴즈 저장·불러오기 (docs/12 Q8): Discord accounts only, 20 per account, deleted only by the owner. */
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { applyConfigPatch, DEFAULT_ROOM_CONFIG, type RoomConfig } from '@mq/shared';
|
||||
import type { Quiz, Score } from './engine';
|
||||
|
||||
export const SAVE_LIMIT = 20;
|
||||
|
||||
export interface SavedQuizRow {
|
||||
id: number;
|
||||
name: string;
|
||||
questions: number;
|
||||
players: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export class SavedQuizzes {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
list(userId: string): SavedQuizRow[] {
|
||||
return this.db
|
||||
.query<{ id: number; name: string; questions: number; scores_json: string; updated_at: number }, [string]>(
|
||||
'SELECT id, name, questions, scores_json, updated_at FROM saved_quizzes WHERE user_id = ? ORDER BY updated_at DESC',
|
||||
)
|
||||
.all(userId)
|
||||
.map((r) => ({ id: r.id, name: r.name, questions: r.questions, players: (JSON.parse(r.scores_json) as unknown[]).length, updatedAt: r.updated_at }));
|
||||
}
|
||||
|
||||
save(userId: string, name: string, config: RoomConfig, quiz: Quiz, now = Date.now()): number | string {
|
||||
const n = this.db.query<{ n: number }, [string]>('SELECT COUNT(*) n FROM saved_quizzes WHERE user_id = ?').get(userId)!.n;
|
||||
if (n >= SAVE_LIMIT) return `퀴즈는 ${SAVE_LIMIT}개까지 저장할 수 있어요. 안 쓰는 퀴즈를 지워 주세요.`;
|
||||
const scores = [...quiz.scores].map(([id, s]) => ({ id, ...s }));
|
||||
const r = this.db
|
||||
.query<{ id: number }, [string, string, string, string, string, number, number, number]>(
|
||||
'INSERT INTO saved_quizzes (user_id, name, config_json, played_json, scores_json, questions, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id',
|
||||
)
|
||||
.get(userId, name, JSON.stringify(config), JSON.stringify(quiz.played), JSON.stringify(scores), quiz.played.length, now, now)!;
|
||||
return r.id;
|
||||
}
|
||||
|
||||
load(userId: string, id: number): { name: string; config: RoomConfig; quiz: Quiz } | null {
|
||||
const r = this.db
|
||||
.query<{ name: string; config_json: string; played_json: string; scores_json: string }, [number, string]>(
|
||||
'SELECT name, config_json, played_json, scores_json FROM saved_quizzes WHERE id = ? AND user_id = ?',
|
||||
)
|
||||
.get(id, userId);
|
||||
if (!r) return null;
|
||||
// Settings saved by an older version: whatever no longer validates falls back to the default.
|
||||
const merged = applyConfigPatch(DEFAULT_ROOM_CONFIG, JSON.parse(r.config_json));
|
||||
const config = typeof merged === 'string' ? DEFAULT_ROOM_CONFIG : merged;
|
||||
const scores = new Map<string, Score>((JSON.parse(r.scores_json) as ({ id: string } & Score)[]).map(({ id: uid, ...s }) => [uid, s]));
|
||||
return { name: r.name, config, quiz: { played: JSON.parse(r.played_json) as number[], scores } };
|
||||
}
|
||||
|
||||
remove(userId: string, id: number): boolean {
|
||||
return this.db.query('DELETE FROM saved_quizzes WHERE id = ? AND user_id = ?').run(id, userId).changes > 0;
|
||||
}
|
||||
}
|
||||
@@ -246,6 +246,19 @@ export function createHttpApp(d: HttpDeps) {
|
||||
return c.json(countPool(d.db, cfg));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ saved quizzes (docs/12 Q8)
|
||||
app.get('/api/quizzes', (c) => {
|
||||
const u = userOf(c);
|
||||
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
|
||||
return c.json({ quizzes: d.rooms.saved.list(u) });
|
||||
});
|
||||
|
||||
app.delete('/api/quizzes/:id', (c) => {
|
||||
const u = userOf(c);
|
||||
if (!u) return c.json({ error: '로그인이 필요해요.' }, 401);
|
||||
return d.rooms.saved.remove(u, Number(c.req.param('id'))) ? c.json({ ok: true }) : c.json({ error: '저장한 퀴즈를 찾을 수 없어요.' }, 404);
|
||||
});
|
||||
|
||||
app.route('/api/admin', createAdminApp({ ...d.admin, users: d.users, sessions: d.sessions, roles: d.roles, settings: d.settings }));
|
||||
|
||||
app.all('/api/*', (c) => c.json({ error: '없는 주소예요.' }, 404));
|
||||
|
||||
@@ -219,6 +219,18 @@ describe('rooms over WebSocket', () => {
|
||||
expect(await ca.waitFor((m) => m.t === 'error' && m.n === 'blank')).toMatchObject({ message: '빈 메시지는 보낼 수 없어요.' });
|
||||
});
|
||||
|
||||
test('the last player leaving closes the room at once (← 방 목록 / 나가기)', async () => {
|
||||
const { ca, cb, code } = await setup();
|
||||
cb.send({ t: 'leave' });
|
||||
await nextRoom(ca, (r) => r.players.length === 1);
|
||||
expect(s.rooms.get(code)).toBeDefined();
|
||||
ca.send({ t: 'leave' });
|
||||
await ca.waitFor((m) => m.t === 'left');
|
||||
expect(s.rooms.get(code)).toBeUndefined();
|
||||
expect((await api(s.base, `/api/rooms/${code}`)).res.status).toBe(404);
|
||||
expect((await api(s.base, '/api/rooms')).body.rooms).toEqual([]);
|
||||
});
|
||||
|
||||
test('a room created but never entered expires like an empty room', async () => {
|
||||
s = boot();
|
||||
const a = await guest(s.base, '만들기만');
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
/**
|
||||
* Rooms and waiting room (docs/04, docs/05 중간 입장·퇴장·방장). In memory; unlimited players (no seats).
|
||||
* Stage 4: join/leave, host, kick, ready, settings with live song count. Games start in stage 5.
|
||||
* join/leave, host, kick, ready, settings with live song count; the game itself lives in game/engine.ts.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { DEFAULT_ROOM_CONFIG, applyConfigPatch, configSummary, type ChatLine, type RoomConfig, type RoomView, type ServerMessage } from '@mq/shared';
|
||||
import { DEFAULT_TIMING, Game, newQuiz, pickSongs, type GameTiming, type Quiz } from '../game/engine';
|
||||
import { SavedQuizzes } from '../game/saved';
|
||||
import { artistsByIds, countPool } from '../songs/pool';
|
||||
import type { WsData } from '../ws/gateway';
|
||||
|
||||
@@ -36,12 +38,20 @@ export class Room {
|
||||
emptySince: number | null = null;
|
||||
chat: ChatLine[] = [];
|
||||
private seq = 0;
|
||||
game: Game | 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). */
|
||||
recent: number[][] = [];
|
||||
/** Who is typing, until when (docs/06 입력 중). */
|
||||
typing = new Map<string, number>();
|
||||
typingSent = '';
|
||||
|
||||
constructor(
|
||||
readonly code: string,
|
||||
hostId: string,
|
||||
config: RoomConfig,
|
||||
private deps: { db: Database; user: PublicUserLookup },
|
||||
readonly deps: { db: Database; user: PublicUserLookup; limitSec?: () => number },
|
||||
) {
|
||||
this.hostId = hostId;
|
||||
this.config = config;
|
||||
@@ -56,6 +66,15 @@ export class Room {
|
||||
return [...this.players].filter(([, p]) => p.conns.size > 0).map(([id]) => id);
|
||||
}
|
||||
|
||||
isOnline(id: string): boolean {
|
||||
return (this.players.get(id)?.conns.size ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** Question time limit for short clips (site setting, docs/05). */
|
||||
limitSec(): number {
|
||||
return this.deps.limitSec?.() ?? 60;
|
||||
}
|
||||
|
||||
view(): RoomView {
|
||||
return {
|
||||
code: this.code,
|
||||
@@ -83,11 +102,17 @@ export class Room {
|
||||
|
||||
/** Relays at once (docs/12 채팅 무조건 실시간). userId null = system line (입장/퇴장/방장). */
|
||||
say(userId: string | null, text: string, n?: string): ChatLine {
|
||||
const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId, nickname: userId ? (this.deps.user(userId)?.nickname ?? '?') : '', text };
|
||||
if (n) line.n = n;
|
||||
return this.post({ userId, text, n });
|
||||
}
|
||||
|
||||
/** Any log line; with `answer` it goes out as one `answer` message so nothing can come between the line and its block (docs/06). */
|
||||
post(p: { userId: string | null; text: string; n?: string; answer?: ChatLine['answer'] }): ChatLine {
|
||||
const line: ChatLine = { seq: ++this.seq, at: Date.now(), userId: p.userId, nickname: p.userId ? (this.deps.user(p.userId)?.nickname ?? '?') : '', text: p.text };
|
||||
if (p.n) line.n = p.n;
|
||||
if (p.answer) line.answer = p.answer;
|
||||
this.chat.push(line);
|
||||
if (this.chat.length > CHAT_HISTORY) this.chat.shift();
|
||||
this.send({ t: 'chat', code: this.code, line });
|
||||
this.send(p.answer ? { t: 'answer', code: this.code, line } : { t: 'chat', code: this.code, line });
|
||||
return line;
|
||||
}
|
||||
|
||||
@@ -119,7 +144,23 @@ export class RoomManager {
|
||||
/** userId → room code (one room at a time). */
|
||||
private where = new Map<string, string>();
|
||||
|
||||
constructor(private deps: { db: Database; user: PublicUserLookup; genreName: (id: string) => string; log?: (msg: string, extra?: Record<string, unknown>) => void }) {}
|
||||
readonly saved: SavedQuizzes;
|
||||
private timing: GameTiming;
|
||||
|
||||
constructor(
|
||||
private deps: {
|
||||
db: Database;
|
||||
user: PublicUserLookup;
|
||||
genreName: (id: string) => string;
|
||||
log?: (msg: string, extra?: Record<string, unknown>) => void;
|
||||
/** Question time limit for short clips (site setting). */
|
||||
limitSec?: () => number;
|
||||
timing?: Partial<GameTiming>;
|
||||
},
|
||||
) {
|
||||
this.saved = new SavedQuizzes(deps.db);
|
||||
this.timing = { ...DEFAULT_TIMING, ...deps.timing };
|
||||
}
|
||||
|
||||
private newCode(): string {
|
||||
for (;;) {
|
||||
@@ -187,7 +228,9 @@ export class RoomManager {
|
||||
if (!room.players.has(room.hostId)) room.hostId = userId;
|
||||
ws.send(JSON.stringify({ t: 'chatlog', code, lines: room.chat } satisfies ServerMessage));
|
||||
room.broadcast();
|
||||
if (!already) room.say(null, `${room.nick(userId)}님이 들어왔어요`);
|
||||
if (room.game) room.game.broadcast();
|
||||
else ws.send(JSON.stringify({ t: 'game', code, game: null } satisfies ServerMessage));
|
||||
if (!already) room.say(null, room.game && room.game.phase !== 'result' ? `${room.nick(userId)}님이 들어왔어요 · 다음 문제부터 같이 해요` : `${room.nick(userId)}님이 들어왔어요`);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -202,10 +245,12 @@ export class RoomManager {
|
||||
if (p.conns.size === 0) {
|
||||
p.offlineSince = Date.now();
|
||||
p.ready = false;
|
||||
room.typing.delete(ws.data.userId);
|
||||
const wasHost = room.hostId === ws.data.userId;
|
||||
if (wasHost) room.pickHost();
|
||||
room.broadcast();
|
||||
if (wasHost && room.hostId !== ws.data.userId) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
|
||||
room.game?.onGone(ws.data.userId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,9 +265,11 @@ export class RoomManager {
|
||||
room.send({ t: 'left', code: room.code, reason }, userId);
|
||||
for (const ws of p.conns) ws.data.roomCode = undefined;
|
||||
room.players.delete(userId);
|
||||
room.typing.delete(userId);
|
||||
if (this.where.get(userId) === room.code) this.where.delete(userId);
|
||||
if (room.players.size === 0) {
|
||||
room.emptySince = Date.now();
|
||||
// Nobody has a place any more (left, kicked out by time, went elsewhere): close the room at once.
|
||||
this.close(room);
|
||||
return;
|
||||
}
|
||||
const wasHost = room.hostId === userId;
|
||||
@@ -230,6 +277,13 @@ export class RoomManager {
|
||||
room.broadcast();
|
||||
room.say(null, `${room.nick(userId)}님이 ${reason === 'kicked' ? '내보내졌어요' : '나갔어요'}`);
|
||||
if (wasHost) room.say(null, `방장이 ${room.nick(room.hostId)}님으로 바뀌었어요`);
|
||||
room.game?.onGone(userId);
|
||||
}
|
||||
|
||||
close(room: Room): void {
|
||||
room.game?.stop();
|
||||
this.rooms.delete(room.code);
|
||||
this.deps.log?.('room closed', { code: room.code });
|
||||
}
|
||||
|
||||
/** Host-only actions. Returns an error message or null. */
|
||||
@@ -291,21 +345,144 @@ export class RoomManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Chat line from a player in the room (docs/06). Flood guard is applied by the gateway. */
|
||||
/** Chat line from a player in the room (docs/06). Judged as an answer and relayed in the same step; flood guard is in the gateway. */
|
||||
chat(ws: ServerWebSocket<WsData>, text: string, n?: string): string | null {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
if (!room || ws.data.roomCode !== room.code) return '방에 들어가 있지 않아요.';
|
||||
const t = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
||||
if (!t) return '빈 메시지는 보낼 수 없어요.';
|
||||
room.typing.delete(ws.data.userId);
|
||||
if (room.game?.judge(ws.data.userId, t, n)) return null;
|
||||
room.say(ws.data.userId, t, n);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every 10s: drop players gone longer than the grace period, close rooms left empty. */
|
||||
private inRoom(ws: ServerWebSocket<WsData>): Room | undefined {
|
||||
const room = this.roomOf(ws.data.userId);
|
||||
return room && ws.data.roomCode === room.code ? room : undefined;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ game (docs/05)
|
||||
start(ws: ServerWebSocket<WsData>): string | null {
|
||||
return this.hostAction(ws, (room) => this.startGame(room));
|
||||
}
|
||||
|
||||
private startGame(room: Room): string | null {
|
||||
if (room.config.mode === 'artist' && !room.config.artistIds.length) return '가수를 1명 이상 골라 주세요.';
|
||||
const list = 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.broadcast();
|
||||
room.game.start();
|
||||
this.deps.log?.('game started', { code: room.code, songs: list.length, total: room.game.total });
|
||||
return null;
|
||||
}
|
||||
|
||||
audio(ws: ServerWebSocket<WsData>, n: number, ev: 'ready' | 'blocked' | 'stall' | 'clipEnd' | 'error', code?: number): void {
|
||||
this.inRoom(ws)?.game?.onAudio(ws.data.userId, n, ev, code);
|
||||
}
|
||||
|
||||
vote(ws: ServerWebSocket<WsData>, kind: 'skip' | 'hint' | 'replay'): string | null {
|
||||
const room = this.inRoom(ws);
|
||||
if (!room?.game) return '게임 중이 아니에요.';
|
||||
return room.game.vote(ws.data.userId, kind);
|
||||
}
|
||||
|
||||
/** 입력 중 (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);
|
||||
if (!room) return;
|
||||
if (on) room.typing.set(ws.data.userId, Date.now() + 3000);
|
||||
else room.typing.delete(ws.data.userId);
|
||||
}
|
||||
|
||||
flushTyping(now = Date.now()): void {
|
||||
for (const room of this.rooms.values()) {
|
||||
for (const [id, until] of room.typing) if (until < now) room.typing.delete(id);
|
||||
const ids = [...room.typing.keys()];
|
||||
const key = ids.join(',');
|
||||
if (key === room.typingSent) continue;
|
||||
room.typingSent = key;
|
||||
room.send({ t: 'typing', code: room.code, ids });
|
||||
}
|
||||
}
|
||||
|
||||
gameAction(ws: ServerWebSocket<WsData>, action: 'pause' | 'resume' | 'end' | 'continue' | 'again'): string | null {
|
||||
const room = this.inRoom(ws);
|
||||
if (!room) return '방에 들어가 있지 않아요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
||||
const g = room.game;
|
||||
if (!g) return '게임 중이 아니에요.';
|
||||
switch (action) {
|
||||
case 'pause':
|
||||
case 'resume':
|
||||
return g.hostPause(action === 'pause');
|
||||
case 'end':
|
||||
g.finish();
|
||||
return null;
|
||||
case 'continue':
|
||||
if (g.phase !== 'result') return '게임이 끝난 뒤에 이어 풀 수 있어요.';
|
||||
return this.startGame(room);
|
||||
case 'again':
|
||||
// 다시 하기: same settings, back to the waiting room, scores from 0 (docs/12 Q8).
|
||||
g.stop();
|
||||
room.game = null;
|
||||
room.status = 'lobby';
|
||||
room.quiz = newQuiz();
|
||||
room.recount();
|
||||
room.broadcast();
|
||||
room.send({ t: 'game', code: room.code, game: null });
|
||||
room.say(null, '대기실로 돌아왔어요');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
exclude(ws: ServerWebSocket<WsData>, target: string): string | null {
|
||||
const room = this.inRoom(ws);
|
||||
if (!room?.game) return '게임 중이 아니에요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 할 수 있어요.';
|
||||
return room.game.exclude(target);
|
||||
}
|
||||
|
||||
/** 퀴즈 저장 (docs/12 Q8): the host with a Discord account, in the waiting room, on the results or while paused. */
|
||||
save(ws: ServerWebSocket<WsData>, name: string): string | null {
|
||||
const room = this.inRoom(ws);
|
||||
if (!room) return '방에 들어가 있지 않아요.';
|
||||
if (room.hostId !== ws.data.userId) return '방장만 저장할 수 있어요.';
|
||||
if (this.deps.user(ws.data.userId)?.kind !== 'member') return '퀴즈 저장은 디스코드로 로그인하면 쓸 수 있어요.';
|
||||
const g = room.game;
|
||||
if (g && g.phase !== 'result' && !g.paused) return '게임을 잠시 멈춘 뒤나 끝난 뒤에 저장할 수 있어요.';
|
||||
if (!room.quiz.played.length) return '아직 푼 문제가 없어요.';
|
||||
const id = this.saved.save(ws.data.userId, name, room.config, room.quiz);
|
||||
if (typeof id === 'string') return id;
|
||||
ws.send(JSON.stringify({ t: 'saved', id, name } satisfies ServerMessage));
|
||||
room.say(null, `퀴즈를 "${name}"(으)로 저장했어요 · ${room.quiz.played.length}문제`);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 퀴즈 불러오기: settings, songs asked and scores come back; starting skips the songs already asked. */
|
||||
load(ws: ServerWebSocket<WsData>, id: number): string | null {
|
||||
return this.hostAction(ws, (room) => {
|
||||
const q = this.saved.load(ws.data.userId, id);
|
||||
if (!q) return '저장한 퀴즈를 찾을 수 없어요.';
|
||||
room.config = { ...q.config, title: room.config.title, visibility: room.config.visibility };
|
||||
room.quiz = q.quiz;
|
||||
for (const p of room.players.values()) p.ready = false;
|
||||
room.recount();
|
||||
room.broadcast();
|
||||
room.say(null, `"${q.name}" 퀴즈를 불러왔어요 · 지금까지 ${q.quiz.played.length}문제, 시작하면 이어서 나와요`);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Every 10s: drop players gone longer than the grace period, close rooms created but never entered. */
|
||||
sweep(now = Date.now()): void {
|
||||
for (const room of this.rooms.values()) {
|
||||
for (const [id, p] of room.players) if (p.offlineSince && now - p.offlineSince > GRACE_MS) this.removePlayer(room, id, 'closed');
|
||||
if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.rooms.delete(room.code);
|
||||
if (room.players.size === 0 && room.emptySince && now - room.emptySince > EMPTY_ROOM_MS) this.close(room);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface StartOptions {
|
||||
checkEmbed?: import('./http/admin').AdminDeps['checkEmbed'];
|
||||
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
|
||||
stopWaitMs?: number;
|
||||
/** Game pacing (tests and e2e shorten the countdown / reveal). */
|
||||
gameTiming?: Partial<import('./game/engine').GameTiming>;
|
||||
}
|
||||
|
||||
export function startServer(opts: StartOptions) {
|
||||
@@ -54,6 +56,8 @@ export function startServer(opts: StartOptions) {
|
||||
},
|
||||
genreName: (id) => genreNames.get(id) ?? id,
|
||||
log: (msg, extra) => log('info', msg, extra),
|
||||
limitSec: () => settings.getSite().questionLimitSec,
|
||||
timing: opts.gameTiming,
|
||||
});
|
||||
const gateway = new Gateway({
|
||||
log,
|
||||
@@ -140,6 +144,8 @@ export function startServer(opts: StartOptions) {
|
||||
});
|
||||
|
||||
const roomSweeper = setInterval(() => rooms.sweep(), 10_000);
|
||||
// 입력 중 goes out at most once a second (docs/06); chat itself never waits.
|
||||
const typingFlush = setInterval(() => rooms.flushTyping(), 1000);
|
||||
// The collector runs in its own process, so lobbies re-count now and then to show newly matched songs.
|
||||
const roomRecount = setInterval(() => {
|
||||
try {
|
||||
@@ -161,6 +167,8 @@ export function startServer(opts: StartOptions) {
|
||||
ready = false;
|
||||
clearInterval(sweeper);
|
||||
clearInterval(roomSweeper);
|
||||
clearInterval(typingFlush);
|
||||
for (const r of rooms.rooms.values()) r.game?.stop();
|
||||
clearInterval(roomRecount);
|
||||
gateway.shutdown();
|
||||
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
|
||||
|
||||
165
apps/server/src/songs/quiz.ts
Normal file
165
apps/server/src/songs/quiz.ts
Normal 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;
|
||||
}
|
||||
@@ -98,6 +98,22 @@ export class Gateway {
|
||||
return err(rooms.kick(ws, m.userId));
|
||||
case 'host':
|
||||
return err(rooms.giveHost(ws, m.userId));
|
||||
case 'start':
|
||||
return err(rooms.start(ws));
|
||||
case 'audio':
|
||||
return rooms.audio(ws, m.n, m.ev, m.code);
|
||||
case 'vote':
|
||||
return err(rooms.vote(ws, m.kind));
|
||||
case 'typing':
|
||||
return rooms.typing(ws, m.on);
|
||||
case 'game':
|
||||
return err(rooms.gameAction(ws, m.action));
|
||||
case 'exclude':
|
||||
return err(rooms.exclude(ws, m.userId));
|
||||
case 'save':
|
||||
return err(rooms.save(ws, m.name));
|
||||
case 'load':
|
||||
return err(rooms.load(ws, m.id));
|
||||
case 'chat': {
|
||||
const g = this.d.chatGuard?.();
|
||||
if (g?.on) {
|
||||
|
||||
Reference in New Issue
Block a user