Files
music_quiz/apps/server/src/game/duel.ts

356 lines
14 KiB
TypeScript

/**
* 이지선다 engine (조회수가 더 높은 곡 고르기): the game of a room in mode duel, with an 이지선다 퀴즈.
*
* Every question shows two cards, A and B. Each player plays them on their own screen (no shared timeline): tapping a
* card plays that song and is the pick, and the pick can change until the time is up. Then the card with more views wins
* (equal views: both), everyone on it gets 1 point — 2 points (역배) when exactly one person is right against two or more
* on the other card. Nobody loses points; no pick = 0.
* 진행: 매번 새 두 곡 (pairs) or 연속 (chain: the higher song stays as A with its views shown, a new song comes as B).
*/
import { viewsLabel, voteThreshold, type DuelCard, type DuelResult, type DuelSide, type GameHistoryItem, type GamePhase, type GameView, type QuizItem, type ServerMessage } from '@mq/shared';
import { clipOf, loudnessGain, orderSongs, quizItemSong } from '../songs/quiz';
import type { Room } from '../rooms/manager';
import type { GameTiming } from './engine';
/** Who gets what: everyone on the winning card 1 point, or 2 (역배) when alone there against 2 or more. */
export function duelGains(picks: Map<string, DuelSide>, winner: DuelSide | 'both'): Map<string, { points: number; reverse: boolean }> {
const right = [...picks].filter(([, s]) => winner === 'both' || s === winner).map(([id]) => id);
const wrong = picks.size - right.length;
const reverse = right.length === 1 && wrong >= 2;
return new Map(right.map((id) => [id, { points: reverse ? 2 : 1, reverse }]));
}
export function duelWinner(a: number, b: number): DuelSide | 'both' {
return a === b ? 'both' : a > b ? 'a' : 'b';
}
/** Song order of an 이지선다 game: the quiz's songs with a view count that this room has not played yet, shuffled. */
export function pickDuelSongs(room: Room): number[] | string {
const q = room.config.quizId ? room.deps.quizzes.get(room.config.quizId) : null;
if (!room.config.quizId) return '이지선다 퀴즈를 골라 주세요.';
if (!q) return '고른 퀴즈를 찾을 수 없어요. 다른 퀴즈를 골라 주세요.';
if (q.kind !== 'duel') return '이지선다에서는 이지선다 퀴즈만 할 수 있어요.';
const played = new Set(room.quiz.played);
const ids = q.items.filter((i) => i.views !== null && !played.has(i.id!)).map((i) => i.id!);
if (ids.length < 2) return room.quiz.played.length ? '이 퀴즈의 곡을 모두 풀었어요.' : '이지선다에는 조회수가 있는 곡이 2곡 이상 있어야 해요.';
return orderSongs(ids, new Set(), new Map(), false);
}
interface Card {
item: QuizItem;
startSec: number;
gain: number;
/** 연속 방식: the song that stayed shows its views during the question. */
open: boolean;
}
export class DuelGame {
phase: GamePhase = 'play';
n = 0;
total: number;
paused: GameView['paused'] = null;
private items: Map<number, QuizItem>;
private cards: [Card, Card] | null = null;
/** Index in `list` of the next song not used yet. */
private at = 0;
private picks = new Map<string, { side: DuelSide; ms: number }>();
private result: DuelResult | null = null;
private elapsedMs = 0;
private runningSince: number | null = null;
private limitMs = 30_000;
private nextVotes = new Set<string>();
history: GameHistoryItem[] = [];
private revealUntil: number | null = null;
private timer: ReturnType<typeof setInterval> | null = null;
readonly gameId = crypto.randomUUID();
constructor(
private room: Room,
private list: number[],
private timing: GameTiming,
private now: () => number = Date.now,
) {
const q = room.deps.quizzes.get(room.config.quizId!);
this.items = new Map((q?.items ?? []).map((i) => [i.id!, i]));
const possible = room.config.duelFlow === 'chain' ? list.length - 1 : Math.floor(list.length / 2);
this.total = room.config.count ? Math.min(room.config.count, possible) : possible;
}
start(): void {
this.timer = setInterval(() => this.tick(), this.timing.tickMs);
this.room.say(null, `이지선다를 시작해요! ${this.total}문제 · 조회수가 더 높은 곡을 골라 주세요`);
this.nextQuestion();
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
private elapsed(now = this.now()): number {
return this.elapsedMs + (this.runningSince !== null && now > this.runningSince ? now - this.runningSince : 0);
}
private card(id: number, open = false): Card | null {
const item = this.items.get(id);
if (!item || item.views === null) return null;
const song = quizItemSong(this.room.deps.db, this.room.config.quizId!, id);
return {
item,
startSec: song ? clipOf(song, { ...this.room.config, listenSec: 0 }).startSec : 0,
gain: loudnessGain(song?.loudness ?? null),
open,
};
}
/** The next unused song of the list as a card (songs removed from the quiz meanwhile are skipped). */
private take(): Card | null {
while (this.at < this.list.length) {
const id = this.list[this.at++]!;
const c = this.card(id);
if (c) {
this.room.quiz.played.push(id);
return c;
}
}
return null;
}
private nextQuestion(): void {
this.n++;
if (this.n > this.total) return this.finish();
let cards: [Card, Card] | null = null;
const prev = this.cards;
if (this.room.config.duelFlow === 'chain' && prev && this.result) {
// the higher song stays (equal: the one that was A), shown as A with its views
const stay = this.result.winner === 'b' ? prev[1] : prev[0];
const b = this.take();
if (b) cards = [{ ...stay, open: true }, b];
} else {
const a = this.take();
const b = a && this.take();
if (a && b) cards = [a, b];
}
if (!cards) {
this.n--;
return this.finish();
}
this.cards = cards;
this.picks.clear();
this.result = null;
this.nextVotes.clear();
this.revealUntil = null;
this.paused = null;
this.phase = 'play';
this.elapsedMs = 0;
this.runningSince = this.now();
this.limitMs = this.timing.limitMs ?? this.room.config.duelSec * 1000;
this.room.say(null, `${this.n}번째 문제`);
this.broadcast();
}
/** Time is up: the higher card wins, points go out, the views are shown. */
private endQuestion(): void {
if (this.phase !== 'play' || !this.cards) return;
const now = this.now();
this.elapsedMs = this.elapsed(now);
this.runningSince = null;
this.paused = null;
const [a, b] = this.cards;
const winner = duelWinner(a.item.views!, b.item.views!);
const sides = new Map([...this.picks].map(([id, p]) => [id, p.side]));
const gains = duelGains(sides, winner);
for (const [id, g] of gains) {
const sc = this.room.quiz.scores.get(id) ?? { nickname: this.room.nick(id), score: 0, correct: 0, totalMs: 0 };
sc.nickname = this.room.nick(id);
sc.score += g.points;
sc.correct += 1;
sc.totalMs += this.picks.get(id)!.ms;
sc.reverse = (sc.reverse ?? 0) + (g.reverse ? 1 : 0);
this.room.quiz.scores.set(id, sc);
}
this.result = { winner, gains: [...gains].map(([id, g]) => ({ id, ...g })) };
const cardOf = (c: Card, side: DuelSide) => ({ side, title: c.item.title, artist: c.item.artist, videoId: c.item.videoId, views: c.item.views! });
this.history.push({
n: this.n,
title: `${a.item.title} vs ${b.item.title}`,
artist: '',
year: null,
level: null,
genres: [],
videoId: null,
winnerId: null,
winner: null,
ms: null,
how: 'timeout',
duel: {
cards: [cardOf(a, 'a'), cardOf(b, 'b')],
winner,
gains: this.result.gains.map((g) => ({ ...g, nickname: this.room.nick(g.id) })),
},
});
const label = (c: Card) => `${c.item.title}${c.item.artist ? ` - ${c.item.artist}` : ''} (${viewsLabel(c.item.views!)}회)`;
const top = winner === 'both' ? `조회수가 같아요: ${label(a)} = ${label(b)}` : `더 높은 곡: ${label(winner === 'a' ? a : b)}`;
const rev = this.result.gains.find((g) => g.reverse);
const who = gains.size ? `맞힌 사람 ${gains.size}명${rev ? ` · 역배 성공 ${this.room.nick(rev.id)}님 +2점` : ''}` : '맞힌 사람이 없어요';
this.room.post({ userId: null, text: `⏱ 시간 끝! ${who}`, answer: { text: top, none: gains.size === 0 } });
this.phase = 'reveal';
this.revealUntil = now + (this.timing.revealMs ?? this.room.config.revealSec * 1000);
this.broadcast();
}
private afterReveal(): void {
if (this.phase !== 'reveal') return;
if (this.n >= this.total) this.finish();
else this.nextQuestion();
}
finish(): void {
if (this.phase === 'result') return;
this.phase = 'result';
this.runningSince = null;
this.paused = null;
this.stop();
this.room.say(null, '게임이 끝났어요');
this.broadcast();
}
tick(now = this.now()): void {
if (this.phase === 'reveal') {
if (this.revealUntil !== null && now >= this.revealUntil) this.afterReveal();
return;
}
if (this.phase === 'play' && this.elapsed(now) >= this.limitMs) this.endQuestion();
}
// ------------------------------------------------------------------ inputs
/** Tap on card A or B of question `n`: that is the pick until another tap (the same card again changes nothing). */
pick(userId: string, n: number, side: DuelSide): string | null {
if (n !== this.n || this.phase !== 'play') return null; // a late tap of the last question: nothing to do
if (!this.room.isOnline(userId)) return '방에 접속해 있지 않아요.';
if (this.paused) return '방장이 잠시 멈췄어요. 다시 시작하면 고를 수 있어요.';
if (this.picks.get(userId)?.side === side) return null;
this.picks.set(userId, { side, ms: this.elapsed() });
this.broadcast();
return null;
}
vote(userId: string, kind: 'skip' | 'hint' | 'replay' | 'next'): string | null {
if (kind !== 'next') return '이지선다에는 없는 기능이에요.';
if (this.phase !== 'reveal') return '결과가 공개된 뒤에 누를 수 있어요.';
if (this.room.config.nextVotes === 'none') return '이 방은 바로 다음 문제가 꺼져 있어요.';
if (!this.room.isOnline(userId)) return '방에 접속해 있지 않아요.';
if (this.nextVotes.has(userId)) this.nextVotes.delete(userId);
else this.nextVotes.add(userId);
this.checkNext();
if (this.phase === 'reveal') this.broadcast();
return null;
}
private needNext(): number | null {
return voteThreshold(this.room.config.nextVotes, this.room.online().length);
}
private checkNext(): void {
if (this.phase !== 'reveal') return;
for (const id of this.nextVotes) if (!this.room.isOnline(id)) this.nextVotes.delete(id);
const need = this.needNext();
if (need !== null && this.nextVotes.size >= need) this.afterReveal();
}
hostPause(on: boolean): string | null {
if (this.phase !== 'play') return '지금은 멈출 수 없어요.';
if (on && !this.paused) {
this.elapsedMs = this.elapsed();
this.runningSince = null;
this.paused = { reason: 'host', who: [] };
} else if (!on && this.paused) {
this.paused = null;
this.runningSince = this.now();
}
this.broadcast();
return null;
}
onGone(_userId: string): void {
if (this.phase === 'reveal') this.checkNext();
if (this.phase !== 'result') this.broadcast();
}
/** Everyone plays on their own screen: a player who comes back just gets the view. */
rejoin(_userId: string, _send: (m: ServerMessage) => void): void {}
onAudio(): void {}
judge(): boolean {
return false;
}
exclude(): string | null {
return '이지선다에는 없는 기능이에요.';
}
// ------------------------------------------------------------------ view
view(): GameView {
const players = new Map<string, boolean>();
for (const [id] of this.room.players) players.set(id, this.room.isOnline(id));
const scores = new Map(this.room.quiz.scores);
const ids = new Set([...players.keys(), ...[...scores].filter(([, s]) => s.score > 0).map(([id]) => id)]);
const shown = this.phase === 'reveal' || this.phase === 'result';
const cards: DuelCard[] = (this.cards ?? []).map((c, i) => {
const side: DuelSide = i === 0 ? 'a' : 'b';
return {
side,
videoId: c.item.videoId,
title: c.item.title,
artist: c.item.artist,
startSec: c.startSec,
gain: c.gain,
views: shown || c.open ? c.item.views : null,
picks: [...this.picks].filter(([, p]) => p.side === side).map(([id]) => id),
};
});
const online = this.room.online();
return {
phase: this.phase,
n: this.n,
total: this.total,
mode: 'duel',
participants: online,
excluded: [],
waiting: [],
paused: this.paused,
startAt: null,
clock: { elapsedMs: this.elapsedMs, runningSince: this.runningSince, limitMs: this.limitMs },
clipSec: null,
clipOver: false,
hint: null,
hints: [],
hintMore: false,
hintAtSec: null,
lyrics: null,
votes: { skip: [], hint: [], replay: [], next: [...this.nextVotes] },
need: { skip: null, hint: null, replay: null, next: this.needNext() },
scores: [...ids]
.map((id) => {
const s = scores.get(id);
return {
id,
nickname: players.has(id) ? this.room.nick(id) : (s?.nickname ?? '?'),
score: s?.score ?? 0,
correct: s?.correct ?? 0,
avgMs: s?.correct ? Math.round(s.totalMs / s.correct) : null,
online: players.get(id) ?? false,
reverse: s?.reverse ?? 0,
};
})
.sort((a, b) => b.score - a.score || (a.avgMs ?? Infinity) - (b.avgMs ?? Infinity) || a.nickname.localeCompare(b.nickname)),
history: this.history,
revealUntil: this.revealUntil,
left: this.list.length - this.at >= 2 ? this.list.length - this.at : 0,
duel: { flow: this.room.config.duelFlow, cards, result: this.result },
};
}
broadcast(): void {
this.room.send({ t: 'game', code: this.room.code, game: this.view() });
}
}