5~7단계 게임: 숨긴 유튜브 동기화 재생(전원 준비·버퍼링이면 모두 멈춤·30초 늦은 사람 제외·재생 오류 곡 교체), 정답 판정·점수·정답 블록, 입력 중·단축키, 힌트·스킵·다시듣기 투표, 3모드, 결과·이어풀기·다시 하기, 퀴즈 저장·불러오기 + 마지막 사람이 나가면 방 바로 닫기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user