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

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

View File

@@ -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);
}
}