- 서버: SiteSettings.gameSpeed, /api/config에 노출, 컴퓨터 생각 시간(defaultBotDelay)과 마피아·라이어 컴퓨터가 살펴보는 간격에 BOT_SLOWDOWN(1.5)/배율. 게임이 정한 반응 시각(원카드 외치기)은 그대로 - 웹: lib/motion.ts — .game-layout 안 CSS 애니메이션·트랜지션은 useMotionScope가 playbackRate로, Web Animations는 fxAnim, 연출 타이머(배너 유지·다음 단계·복사본 정리·숫자 세기·다시 보기 한 칸)는 fxMs. 채팅·role="timer"·규칙 시간·꾹 눌러 보기는 제외 - 관리자 사이트 탭에 배율 버튼(1/16~16)과 직접 입력 - 테스트: 배율 검증(API 400/200, 열린 방 즉시 반영), 컴퓨터 생각 시간 배율, motion 단위 테스트, e2e/speed.e2e.ts(돌 애니메이션 재생 배율·컴퓨터 응답 시간), 관리자 e2e에 배율 저장 - 문서: 14-admin §5, 07-ui-ux, 06-lobby-rooms, 13-decisions, README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1245 lines
52 KiB
TypeScript
1245 lines
52 KiB
TypeScript
/**
|
|
* One room: seats, spectators, chat, game runner, timers (docs/06, docs/03, docs/09 §4).
|
|
* All mutations run on the single JS thread, so a room never sees concurrent updates.
|
|
*/
|
|
import { ulid } from 'ulid';
|
|
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
|
|
import { botChatRequired, clampGameSpeed, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
|
import { botPersona } from '@bg/games/bots';
|
|
import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck';
|
|
import { sha256Hex } from '../auth/sessions';
|
|
import { BOT_SLOWDOWN, BotDriver, type BotDelayInput } from './bots';
|
|
import { drift, newBotProfile, profileFromId, repick, type BotProfile } from './bot-profile';
|
|
import { BotBrain, type BotActivity } from '../ai/brain';
|
|
import type { Llm } from '../ai/llm';
|
|
import type { LogEntry, RoomStore } from './store';
|
|
import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings';
|
|
import { TokenBucket } from '../ws/rate-limit';
|
|
|
|
export interface Conn {
|
|
userId: string;
|
|
send(msg: ServerMessage): void;
|
|
close(code: number, reason: string): void;
|
|
}
|
|
|
|
export interface RoomConfig {
|
|
gameId: string;
|
|
options: unknown;
|
|
maxPlayers: number;
|
|
visibility: 'private' | 'public';
|
|
allowSpectators: boolean;
|
|
chatEnabled: boolean;
|
|
chatFilter: boolean;
|
|
/** Computers chat on their own (docs/06 §12.1). Off unless the host turns it on; rooms saved before it existed read as off. */
|
|
botChat?: boolean;
|
|
/** Seconds a disconnected player keeps their turn timer before auto actions kick in (docs/03 §6.2). */
|
|
graceSec: number;
|
|
}
|
|
|
|
export interface Seat {
|
|
userId: string;
|
|
ready: boolean;
|
|
}
|
|
|
|
interface Presence {
|
|
connected: boolean;
|
|
since: number;
|
|
joinedAt: number;
|
|
}
|
|
|
|
interface GameSlot {
|
|
gameId: string;
|
|
stateVersion: number;
|
|
state: unknown;
|
|
rng: RngState;
|
|
gamePk: string;
|
|
seedHex: string;
|
|
seedHash: string;
|
|
startedAt: number;
|
|
players: string[];
|
|
finished: boolean;
|
|
/** After a restore, deadlines are not enforced before this time (docs/04 §3.3). */
|
|
deadlineFloor: number | null;
|
|
/** Each computer's level and luck in this game (shown in the fairness check afterwards). */
|
|
bots?: Record<string, { level: number; luck: number }>;
|
|
/** Shuffles tried for the computers' luck (docs/04 §5.1); 1 or absent = the first one. */
|
|
shuffles?: number;
|
|
}
|
|
|
|
/** Shape persisted to room_state.state_json. */
|
|
export interface RoomSnapshot {
|
|
v: 1;
|
|
config: RoomConfig;
|
|
hostId: string;
|
|
status: Room['status'];
|
|
seats: (Seat | null)[];
|
|
gameNo: number;
|
|
sessionStats: Record<string, { played: number; wins: number }>;
|
|
rematchVotes: string[];
|
|
lastSeed: string | null;
|
|
lastResult: GameResult | null;
|
|
game: GameSlot | null;
|
|
joinedAt: Record<string, number>;
|
|
/** Computers' level and luck (absent in rooms saved before 2026-10-11: then fixed by the bot id). */
|
|
bots?: Record<string, BotProfile>;
|
|
}
|
|
|
|
export interface RoomDeps {
|
|
store: RoomStore;
|
|
games: Record<string, AnyGameDefinition>;
|
|
users: { publicUser(id: string): PublicUser | null };
|
|
now?: () => number;
|
|
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
|
/** The last connection went away: `leave` = someone left on purpose, `disconnect` = a socket dropped or the page was left. */
|
|
onEmpty?: (room: Room, why: 'leave' | 'disconnect') => void;
|
|
onSeatChange?: (room: Room, userId: string, seated: boolean) => void;
|
|
/** Admin settings (docs/14-admin.md). Optional so unit tests can run without them. */
|
|
settings?: { game(id: string): EffectiveGame | null; getSite(): SiteSettings };
|
|
/** Computer players' thinking time (ms) for a decision with `choices` options; tests may pin it. */
|
|
botDelay?: (input: BotDelayInput) => number;
|
|
/** Local language model for the computers' talk and play-like-people behaviour (docs/06 §12.1); null = off. */
|
|
ai?: Llm | null;
|
|
/** Waiting inside the computers' talk (typing time); tests may make it instant. */
|
|
aiSleep?: (ms: number) => Promise<void>;
|
|
/** Dice for the computers' talk (whether to speak now); tests may pin it. */
|
|
aiRandom?: () => number;
|
|
/**
|
|
* Tries shuffles for the computers' luck off the main thread (docs/04 §5.1). Absent (tests): every game starts at
|
|
* once with one fresh seed.
|
|
*/
|
|
luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>;
|
|
}
|
|
|
|
const CHAT_HISTORY = 30;
|
|
/** Time the luck worker may spend on more shuffles (the first is always played out), docs/04 §5.1. */
|
|
export const LUCK_BUDGET_MS = 1500;
|
|
const ERROR_LIMIT = 3;
|
|
/** Streaming actions (drawing) are logged in batches: at most this long between snapshot writes. */
|
|
const STREAM_FLUSH_MS = 1000;
|
|
|
|
export class Room {
|
|
status: 'lobby' | 'playing' | 'finished' | 'paused' | 'broken' = 'lobby';
|
|
seq = 0;
|
|
hostId: string;
|
|
seats: (Seat | null)[];
|
|
spectators = new Set<string>();
|
|
presence = new Map<string, Presence>();
|
|
conns = new Map<string, Conn>();
|
|
/** Seated people still on the site but away from the room page (no room messages; still count as connected). */
|
|
detached = new Map<string, Conn>();
|
|
kicked = new Set<string>();
|
|
/** Players who left during a game; their seat is freed when the game ends. */
|
|
leftDuringGame = new Set<string>();
|
|
gameNo = 0;
|
|
sessionStats: Record<string, { played: number; wins: number }> = {};
|
|
rematchVotes = new Set<string>();
|
|
lastSeed: string | null = null;
|
|
lastResult: GameResult | null = null;
|
|
game: GameSlot | null = null;
|
|
/** Computers' level and luck (docs/09 §9.1), by bot id. */
|
|
botProfiles: Record<string, BotProfile> = {};
|
|
/** The computers' shuffles are being tried; the game starts when they're done. */
|
|
starting = false;
|
|
/** Shut down or closed: late callbacks (the luck worker) must not touch it. */
|
|
private closed = false;
|
|
chatLog: Extract<ServerMessage, { t: 'chat' }>[] = [];
|
|
lastActiveAt: number;
|
|
/** When the last connection went away (null while someone is connected). */
|
|
emptySince: number | null;
|
|
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
/** Log entries of streaming actions not yet written (flushed with the next snapshot). */
|
|
private pendingLogs: LogEntry[] = [];
|
|
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private recentCs = new Map<string, number[]>();
|
|
private lastChatAt = new Map<string, number>();
|
|
private chatBuckets = new Map<string, TokenBucket>();
|
|
/** When each person last said they were typing (to drop repeats within a second). */
|
|
private typingAt = new Map<string, number>();
|
|
private consecutiveErrors = 0;
|
|
private readonly now: () => number;
|
|
/** Plays the computer players' moves (docs/06 §12). */
|
|
readonly bots: BotDriver;
|
|
/** The computers' talk and visible activity with the local model (docs/06 §12.1). */
|
|
readonly brain: BotBrain;
|
|
private botActivity = new Map<string, BotActivity>();
|
|
|
|
constructor(
|
|
readonly id: string,
|
|
readonly code: string,
|
|
public config: RoomConfig,
|
|
hostId: string,
|
|
private deps: RoomDeps,
|
|
) {
|
|
this.hostId = hostId;
|
|
this.seats = new Array(config.maxPlayers).fill(null);
|
|
this.now = deps.now ?? Date.now;
|
|
this.lastActiveAt = this.now();
|
|
this.emptySince = this.now();
|
|
const room = this;
|
|
this.brain = new BotBrain(
|
|
{
|
|
gameId: () => this.config.gameId,
|
|
gameName: () => this.def.nameKo,
|
|
nameOf: (id) => this.nick(id),
|
|
humans: () => (this.game && !this.game.finished ? this.game.players : this.seatedIds()).filter((u) => !isBotId(u)),
|
|
bots: () => (this.game && !this.game.finished ? this.game.players : this.seatedIds()).filter(isBotId),
|
|
playing: () => this.status === 'playing',
|
|
roomChat: (bot, text) => {
|
|
this.chat(bot, text);
|
|
},
|
|
setActivity: (bot, a) => {
|
|
if ((this.botActivity.get(bot) ?? null) === a) return;
|
|
if (a) this.botActivity.set(bot, a);
|
|
else this.botActivity.delete(bot);
|
|
this.broadcastRoom();
|
|
},
|
|
recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })),
|
|
smart: (bot) => botPersona(bot, this.profile(bot).base).smart,
|
|
chatty: () => this.botChatOn(),
|
|
now: this.now,
|
|
view: (viewer) => (this.game && !this.game.finished ? this.def.view(this.game.state, viewer) : null),
|
|
},
|
|
deps.ai ?? null,
|
|
deps.aiRandom ?? secureRandom,
|
|
deps.aiSleep,
|
|
);
|
|
this.bots = new BotDriver(
|
|
{
|
|
get status() {
|
|
return room.status;
|
|
},
|
|
get game() {
|
|
return room.game;
|
|
},
|
|
get def() {
|
|
return room.def;
|
|
},
|
|
now: this.now,
|
|
deadline: () => this.effectiveDeadline(),
|
|
run: (bot, action) => {
|
|
const parsed = this.def.actionSchema.safeParse(action);
|
|
return parsed.success ? this.runAction(bot, parsed.data, undefined, false) : '잘못된 요청이에요.';
|
|
},
|
|
log: deps.log,
|
|
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
|
|
profile: (bot) => this.profile(bot),
|
|
brain: this.brain,
|
|
timeScale: () => BOT_SLOWDOWN / this.gameSpeed(),
|
|
},
|
|
secureRandom,
|
|
deps.botDelay,
|
|
);
|
|
}
|
|
|
|
/** The computers' own chat: the room setting, or always where the game needs it (마피아). */
|
|
private botChatOn(): boolean {
|
|
return botChatRequired(this.config.gameId) || this.config.botChat === true;
|
|
}
|
|
|
|
get def(): AnyGameDefinition {
|
|
const d = this.deps.games[this.config.gameId];
|
|
if (!d) throw new Error(`unknown game ${this.config.gameId}`);
|
|
return d;
|
|
}
|
|
|
|
playerRange(): { min: number; max: number } {
|
|
return this.rangeFor(this.config.gameId, this.config.options);
|
|
}
|
|
|
|
/** Game's own range (per options) intersected with the admin-configured range. */
|
|
private rangeFor(gameId: string, options: unknown): { min: number; max: number } {
|
|
const d = this.deps.games[gameId]!;
|
|
const base = d.playersFor ? d.playersFor(options) : { min: d.minPlayers, max: d.maxPlayers };
|
|
const eff = this.deps.settings?.game(gameId);
|
|
if (!eff) return base;
|
|
const min = Math.max(base.min, eff.minPlayers);
|
|
const max = Math.min(base.max, eff.maxPlayers);
|
|
return min <= max ? { min, max } : base;
|
|
}
|
|
|
|
/** Options forced to the admin value: admin-locked ones plus the game's admin-only options (e.g. threat guides). */
|
|
private locked(gameId: string): { defaults: unknown; paths: string[] } {
|
|
const eff = this.deps.settings?.game(gameId);
|
|
const adminOnly = this.deps.games[gameId]?.adminOnlyOptions ?? [];
|
|
return {
|
|
defaults: eff?.defaultOptions ?? this.deps.games[gameId]?.defaultOptions,
|
|
paths: [...new Set([...(eff?.lockedOptions ?? []), ...adminOnly])],
|
|
};
|
|
}
|
|
|
|
seatOf(userId: string): number {
|
|
return this.seats.findIndex((s) => s?.userId === userId);
|
|
}
|
|
|
|
isParticipant(userId: string): boolean {
|
|
return this.seatOf(userId) >= 0 || this.spectators.has(userId);
|
|
}
|
|
|
|
seatedIds(): string[] {
|
|
return this.seats.filter((s): s is Seat => s !== null).map((s) => s.userId);
|
|
}
|
|
|
|
inGame(userId: string): boolean {
|
|
return !!this.game && !this.game.finished && this.game.players.includes(userId);
|
|
}
|
|
|
|
hasBots(): boolean {
|
|
return this.seats.some((s) => !!s && isBotId(s.userId));
|
|
}
|
|
|
|
/** A person still holds a seat (not counting people who already left a running game). */
|
|
hasPeopleSeated(): boolean {
|
|
return this.seats.some((s) => !!s && !isBotId(s.userId) && !this.leftDuringGame.has(s.userId));
|
|
}
|
|
|
|
/**
|
|
* Since when every seated person has been off the site, or null while one of them is still on it (in this room or
|
|
* on any other page) or nobody is seated. `offlineSince(u)` is null while u has the site open. Computer players,
|
|
* people who already left a running game, and spectators don't count.
|
|
*/
|
|
playersOfflineSince(offlineSince: (userId: string) => number | null): number | null {
|
|
let since: number | null = null;
|
|
for (const s of this.seats) {
|
|
if (!s || isBotId(s.userId) || this.leftDuringGame.has(s.userId)) continue;
|
|
const p = this.presence.get(s.userId);
|
|
const off = offlineSince(s.userId);
|
|
if (p?.connected || off === null) return null;
|
|
since = Math.max(since ?? 0, p?.since ?? 0, off);
|
|
}
|
|
return since;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- snapshot
|
|
|
|
snapshot(): RoomSnapshot {
|
|
const joinedAt: Record<string, number> = {};
|
|
for (const [u, p] of this.presence) if (this.seatOf(u) >= 0) joinedAt[u] = p.joinedAt;
|
|
return {
|
|
v: 1,
|
|
config: this.config,
|
|
hostId: this.hostId,
|
|
status: this.status,
|
|
seats: this.seats,
|
|
gameNo: this.gameNo,
|
|
sessionStats: this.sessionStats,
|
|
rematchVotes: [...this.rematchVotes],
|
|
lastSeed: this.lastSeed,
|
|
lastResult: this.lastResult,
|
|
game: this.game,
|
|
joinedAt,
|
|
bots: this.botProfiles,
|
|
};
|
|
}
|
|
|
|
static restore(id: string, code: string, seq: number, snap: RoomSnapshot, deps: RoomDeps): Room {
|
|
const room = new Room(id, code, snap.config, snap.hostId, deps);
|
|
room.seq = seq;
|
|
room.status = snap.status;
|
|
room.seats = snap.seats;
|
|
room.gameNo = snap.gameNo;
|
|
room.sessionStats = snap.sessionStats;
|
|
room.rematchVotes = new Set(snap.rematchVotes);
|
|
room.lastSeed = snap.lastSeed;
|
|
room.lastResult = snap.lastResult;
|
|
room.game = snap.game;
|
|
room.botProfiles = snap.bots ?? {};
|
|
const now = room.now();
|
|
for (const s of room.seats) {
|
|
// Computer players have no connection (and so no reconnect grace period).
|
|
if (s && !isBotId(s.userId)) room.presence.set(s.userId, { connected: false, since: now, joinedAt: snap.joinedAt[s.userId] ?? now });
|
|
}
|
|
if (room.game && !room.game.finished) {
|
|
const def = room.def;
|
|
if (def.stateVersion !== room.game.stateVersion) {
|
|
if (!def.migrate) throw new Error(`state version mismatch for ${def.id}`);
|
|
room.game.state = def.migrate(room.game.state, room.game.stateVersion);
|
|
room.game.stateVersion = def.stateVersion;
|
|
}
|
|
// 30s to reconnect, plus up to 30s jitter so thousands of restored rooms don't all time out
|
|
// in the same instant (thundering herd after a restart, docs/04 §3).
|
|
room.game.deadlineFloor = now + 30_000 + Math.floor(secureRandom() * 30_000);
|
|
room.scheduleTimer();
|
|
}
|
|
return room;
|
|
}
|
|
|
|
/** `log.at` defaults to the current time; game actions pass the exact `now` they were applied with (replays, docs/09 §8). */
|
|
private persist(log: { actorId: string | null; kind: string; data: unknown; at?: number } | null): void {
|
|
const nextSeq = this.seq + 1;
|
|
const entry = log ? { seq: nextSeq, gameNo: this.gameNo, at: this.now(), ...log } : null;
|
|
const logs = this.pendingLogs.length ? [...this.pendingLogs, ...(entry ? [entry] : [])] : entry;
|
|
this.deps.store.save(
|
|
this.id,
|
|
nextSeq,
|
|
JSON.stringify(this.snapshot()),
|
|
{ hostId: this.hostId, gameId: this.config.gameId, status: this.status, visibility: this.config.visibility, config: this.config },
|
|
logs,
|
|
);
|
|
this.pendingLogs = [];
|
|
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
this.flushTimer = null;
|
|
this.seq = nextSeq;
|
|
this.lastActiveAt = this.now();
|
|
}
|
|
|
|
/**
|
|
* Streaming actions (e.g. 그림 맞히기 strokes, ~20/s) get a seq and a log entry right away, but the snapshot
|
|
* is written at most every STREAM_FLUSH_MS (or with the next regular persist) instead of once per message.
|
|
*/
|
|
private persistStream(log: { actorId: string | null; kind: string; data: unknown; at: number }): void {
|
|
this.seq += 1;
|
|
this.pendingLogs.push({ seq: this.seq, gameNo: this.gameNo, ...log });
|
|
this.lastActiveAt = this.now();
|
|
this.flushTimer ??= setTimeout(() => this.flushStream(), STREAM_FLUSH_MS);
|
|
}
|
|
|
|
/** Writes pending streamed log entries and the snapshot. Public for tests and shutdown. */
|
|
flushStream(): void {
|
|
this.flushTimer = null;
|
|
if (this.pendingLogs.length) this.persist(null);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- views
|
|
|
|
roomView(): RoomView {
|
|
const pub = (id: string): PublicUser => this.deps.users.publicUser(id) ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
|
const seats: (SeatView | null)[] = this.seats.map((s) => {
|
|
if (!s) return null;
|
|
// Computer players are always there and ready.
|
|
if (isBotId(s.userId)) return { user: pub(s.userId), ready: true, connected: true, away: false };
|
|
const p = this.presence.get(s.userId);
|
|
const connected = !!p?.connected;
|
|
const away = !connected && !!p && this.now() - p.since > this.config.graceSec * 1000;
|
|
return { user: pub(s.userId), ready: s.ready, connected, away };
|
|
});
|
|
const range = this.playerRange();
|
|
return {
|
|
code: this.code,
|
|
hostId: this.hostId,
|
|
gameId: this.config.gameId,
|
|
options: this.config.options,
|
|
maxPlayers: this.config.maxPlayers,
|
|
minPlayers: range.min,
|
|
visibility: this.config.visibility,
|
|
turnSeconds: null,
|
|
allowSpectators: this.config.allowSpectators,
|
|
chatEnabled: this.config.chatEnabled,
|
|
chatFilter: this.config.chatFilter,
|
|
botChat: this.botChatOn(),
|
|
seats,
|
|
spectators: [...this.spectators].map(pub),
|
|
status: this.status,
|
|
gameNo: this.gameNo,
|
|
rematchVotes: [...this.rematchVotes],
|
|
sessionStats: this.sessionStats,
|
|
seedHash: this.game?.seedHash ?? null,
|
|
lockedOptions: this.deps.settings?.game(this.config.gameId)?.lockedOptions ?? [],
|
|
lastSeed: this.lastSeed,
|
|
lastGamePk: this.game?.finished ? this.game.gamePk : null,
|
|
...(this.botActivity.size ? { botActivity: Object.fromEntries(this.botActivity) } : {}),
|
|
...(this.hasBots() ? { botPicks: Object.fromEntries(this.seatedIds().filter(isBotId).map((b) => [b, this.profile(b).pick])) } : {}),
|
|
...(this.starting ? { starting: true } : {}),
|
|
// Levels are revealed only once the game is over (fairness check).
|
|
...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}),
|
|
gameSpeed: this.gameSpeed(),
|
|
};
|
|
}
|
|
|
|
/** `sync`: full view for (re)join / resync (`syncView`, e.g. the whole drawing). */
|
|
private stateMessage(viewer: string, cs?: number, sync = false): ServerMessage | null {
|
|
if (!this.game) return null;
|
|
const def = this.def;
|
|
const asPlayer = this.game.players.includes(viewer) ? viewer : null;
|
|
let view: unknown;
|
|
try {
|
|
view = sync && def.syncView ? def.syncView(this.game.state, asPlayer) : def.view(this.game.state, asPlayer);
|
|
} catch (err) {
|
|
this.deps.log?.('error', 'view failed', { room: this.code, viewer, err: String(err) });
|
|
return { t: 'error', code: 'view-failed', message: '화면을 그리는 중 오류가 발생했어요.' };
|
|
}
|
|
return {
|
|
t: 'state',
|
|
seq: this.seq,
|
|
view,
|
|
events: [],
|
|
active: this.game.finished ? [] : def.activePlayers(this.game.state),
|
|
deadline: this.game.finished ? null : this.effectiveDeadline(),
|
|
...(cs !== undefined ? { cs } : {}),
|
|
};
|
|
}
|
|
|
|
broadcastRoom(): void {
|
|
const msg: ServerMessage = { t: 'room', seq: this.seq, room: this.roomView() };
|
|
for (const c of this.conns.values()) c.send(msg);
|
|
}
|
|
|
|
private broadcastState(events: unknown[], actor?: string, cs?: number): void {
|
|
if (!this.game) return;
|
|
let spectatorMsg: ServerMessage | null = null;
|
|
for (const c of this.conns.values()) {
|
|
let msg: ServerMessage | null;
|
|
if (this.game.players.includes(c.userId)) {
|
|
msg = this.stateMessage(c.userId, c.userId === actor ? cs : undefined);
|
|
} else {
|
|
spectatorMsg ??= this.stateMessage('');
|
|
msg = spectatorMsg;
|
|
}
|
|
if (msg && msg.t === 'state') c.send({ ...msg, events });
|
|
else if (msg) c.send(msg);
|
|
}
|
|
}
|
|
|
|
notice(code: string, message: string): void {
|
|
for (const c of this.conns.values()) c.send({ t: 'notice', code, message });
|
|
}
|
|
|
|
// ---------------------------------------------------------------- membership
|
|
|
|
/** Returns an error message, or null on success. */
|
|
join(conn: Conn, as: 'player' | 'spectator'): string | null {
|
|
const u = conn.userId;
|
|
if (this.kicked.has(u)) return '방장이 내보낸 방에는 다시 들어갈 수 없어요.';
|
|
if (this.status === 'broken') return '서버 업데이트로 이 게임을 이어갈 수 없어요. 새로 시작해 주세요.';
|
|
const old = this.conns.get(u);
|
|
if (old && old !== conn) {
|
|
old.send({ t: 'bye', reason: 'replaced' });
|
|
old.close(4000, 'replaced');
|
|
}
|
|
const now = this.now();
|
|
const wasSeated = this.seatOf(u) >= 0;
|
|
if (!wasSeated && !this.spectators.has(u)) {
|
|
const seatable = as === 'player' && (this.status === 'lobby' || this.status === 'finished') && this.seats.some((s) => s === null);
|
|
if (seatable) {
|
|
const idx = this.seats.findIndex((s) => s === null);
|
|
this.seats[idx] = { userId: u, ready: false };
|
|
this.deps.onSeatChange?.(this, u, true);
|
|
} else {
|
|
if (!this.config.allowSpectators && !this.inGame(u)) return '이 방은 가득 찼어요.';
|
|
this.spectators.add(u);
|
|
}
|
|
}
|
|
const prev = this.presence.get(u);
|
|
this.leftDuringGame.delete(u);
|
|
this.presence.set(u, { connected: true, since: now, joinedAt: prev?.joinedAt || now });
|
|
this.conns.set(u, conn);
|
|
this.detached.delete(u);
|
|
this.emptySince = null;
|
|
if (wasSeated && prev && !prev.connected && this.inGame(u)) {
|
|
this.notice('reconnected', `${this.nick(u)}님이 다시 연결됐어요.`);
|
|
}
|
|
this.persist(wasSeated ? null : { actorId: u, kind: 'join', data: { as } });
|
|
this.broadcastRoom();
|
|
const st = this.stateMessage(u, undefined, true);
|
|
if (st) conn.send(st);
|
|
if (this.status === 'finished' && this.lastResult) conn.send({ t: 'result', seq: this.seq, result: this.lastResult });
|
|
for (const m of this.chatLog) conn.send(m);
|
|
this.scheduleTimer();
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Left the room page but still on the site (홈, 규칙…): no more room messages and the room no longer counts the
|
|
* connection, but the seat stays and the person still counts as connected (no "연결 끊김", no auto moves).
|
|
*/
|
|
detach(conn: Conn): void {
|
|
const u = conn.userId;
|
|
if (this.conns.get(u) !== conn) return;
|
|
if (this.spectators.has(u)) return this.disconnect(conn);
|
|
this.conns.delete(u);
|
|
this.detached.set(u, conn);
|
|
if (this.conns.size === 0) this.becameEmpty('disconnect');
|
|
}
|
|
|
|
/** Connection dropped (not an intentional leave). */
|
|
disconnect(conn: Conn): void {
|
|
const u = conn.userId;
|
|
if (this.detached.get(u) === conn) this.detached.delete(u);
|
|
else if (this.conns.get(u) === conn) this.conns.delete(u);
|
|
else return;
|
|
const p = this.presence.get(u);
|
|
if (p) {
|
|
p.connected = false;
|
|
p.since = this.now();
|
|
}
|
|
if (this.spectators.has(u)) {
|
|
this.spectators.delete(u);
|
|
this.presence.delete(u);
|
|
} else if (this.inGame(u)) {
|
|
this.notice('disconnected', `${this.nick(u)}님의 연결이 끊겼어요.`);
|
|
}
|
|
this.broadcastRoom();
|
|
this.scheduleTimer();
|
|
if (this.conns.size === 0) this.becameEmpty('disconnect');
|
|
}
|
|
|
|
leave(userId: string): void {
|
|
const conn = this.conns.get(userId);
|
|
this.conns.delete(userId);
|
|
this.detached.delete(userId);
|
|
this.spectators.delete(userId);
|
|
this.presence.delete(userId);
|
|
const seat = this.seatOf(userId);
|
|
if (seat >= 0) {
|
|
if (this.inGame(userId)) {
|
|
// Stay in the seat as "away" until the game ends so the game state stays consistent.
|
|
this.leftDuringGame.add(userId);
|
|
this.presence.set(userId, { connected: false, since: 0, joinedAt: 0 });
|
|
const action = this.def.onLeave?.(this.game!.state, userId);
|
|
if (action) this.runAction(userId, action, undefined, true);
|
|
// Only computer players left: nobody to practise with, so the game ends uncounted.
|
|
const g = this.game;
|
|
if (g && !g.finished && g.players.every((u) => isBotId(u) || this.leftDuringGame.has(u))) {
|
|
this.finishGame({ ranking: [g.players], summary: '모두 나가서 연습 게임을 끝냈어요.', reason: 'abandoned' }, true);
|
|
}
|
|
} else {
|
|
this.seats[seat] = null;
|
|
this.rematchVotes.delete(userId);
|
|
this.deps.onSeatChange?.(this, userId, false);
|
|
}
|
|
}
|
|
if (this.hostId === userId) this.pickNewHost();
|
|
this.persist({ actorId: userId, kind: 'leave', data: null });
|
|
this.broadcastRoom();
|
|
conn?.send({ t: 'bye', reason: 'closed' });
|
|
if (this.conns.size === 0) this.becameEmpty('leave');
|
|
}
|
|
|
|
private becameEmpty(why: 'leave' | 'disconnect'): void {
|
|
this.emptySince ??= this.now();
|
|
this.deps.onEmpty?.(this, why);
|
|
}
|
|
|
|
private pickNewHost(): void {
|
|
const candidates = [...this.presence.entries()]
|
|
.filter(([u, p]) => this.seatOf(u) >= 0 && p.connected)
|
|
.sort((a, b) => a[1].joinedAt - b[1].joinedAt);
|
|
const next = candidates[0]?.[0] ?? this.seatedIds().find((u) => !isBotId(u)) ?? [...this.spectators][0];
|
|
if (next) this.hostId = next;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- lobby commands
|
|
|
|
private requireLobby(): string | null {
|
|
if (this.starting) return '게임을 준비하고 있어요.';
|
|
return this.status === 'lobby' || this.status === 'finished' ? null : '게임 중에는 바꿀 수 없어요.';
|
|
}
|
|
|
|
/** A computer's level and luck; computers saved without one get it from their id. */
|
|
/** Admin game speed (docs/14 §5), read live so a change reaches running games too. */
|
|
gameSpeed(): number {
|
|
return clampGameSpeed(this.deps.settings?.getSite().gameSpeed);
|
|
}
|
|
|
|
profile(bot: string): BotProfile {
|
|
return (this.botProfiles[bot] ??= profileFromId(bot));
|
|
}
|
|
|
|
seat(userId: string, seat?: number): string | null {
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
const target = seat ?? this.seats.findIndex((s) => s === null);
|
|
if (target < 0 || target >= this.seats.length) return '빈자리가 없어요.';
|
|
if (this.seats[target] && this.seats[target]!.userId !== userId) return '이미 다른 사람이 앉은 자리예요.';
|
|
const cur = this.seatOf(userId);
|
|
if (cur === target) return null;
|
|
const ready = cur >= 0 ? this.seats[cur]!.ready : false;
|
|
if (cur >= 0) this.seats[cur] = null;
|
|
this.seats[target] = { userId, ready };
|
|
this.spectators.delete(userId);
|
|
if (cur < 0) this.deps.onSeatChange?.(this, userId, true);
|
|
this.persist({ actorId: userId, kind: 'seat', data: { seat: target } });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
unseat(userId: string): string | null {
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
const cur = this.seatOf(userId);
|
|
if (cur < 0) return null;
|
|
if (!this.config.allowSpectators) return '이 방은 관전을 허용하지 않아요.';
|
|
this.seats[cur] = null;
|
|
this.spectators.add(userId);
|
|
this.rematchVotes.delete(userId);
|
|
this.deps.onSeatChange?.(this, userId, false);
|
|
this.persist({ actorId: userId, kind: 'unseat', data: null });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
ready(userId: string, ready: boolean): string | null {
|
|
const cur = this.seatOf(userId);
|
|
if (cur < 0) return '자리에 앉아야 준비할 수 있어요.';
|
|
if (this.requireLobby()) return this.requireLobby();
|
|
this.seats[cur]!.ready = ready;
|
|
this.persist(null);
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
configure(
|
|
userId: string,
|
|
patch: Partial<Omit<RoomConfig, 'graceSec'>> & { gameId?: string },
|
|
): string | null {
|
|
if (userId !== this.hostId) return '방장만 설정을 바꿀 수 있어요.';
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
const next: RoomConfig = { ...this.config };
|
|
if (patch.gameId !== undefined && patch.gameId !== this.config.gameId) {
|
|
const def = this.deps.games[patch.gameId];
|
|
const eff = this.deps.settings?.game(patch.gameId);
|
|
if (!def || (eff && !eff.enabled)) return '없는 게임이에요.';
|
|
next.gameId = patch.gameId;
|
|
next.options = eff?.defaultOptions ?? def.defaultOptions;
|
|
next.maxPlayers = eff?.maxPlayers ?? def.maxPlayers;
|
|
}
|
|
if (this.hasBots() && !botsAllowed(next.gameId)) return '컴퓨터는 이 게임을 할 수 없어요. 컴퓨터를 먼저 빼 주세요.';
|
|
if (this.hasBots() && patch.visibility === 'public') return '컴퓨터가 있는 방은 공개할 수 없어요.';
|
|
const def = this.deps.games[next.gameId]!;
|
|
if (patch.options !== undefined) {
|
|
const parsed = def.optionsSchema.safeParse(patch.options);
|
|
if (!parsed.success) return '설정 값이 올바르지 않아요.';
|
|
next.options = parsed.data;
|
|
}
|
|
// Admin-locked options always keep the admin value (docs/14-admin.md §4).
|
|
const lk = this.locked(next.gameId);
|
|
if (lk.paths.length) next.options = def.optionsSchema.parse(applyLocks(next.options, lk.defaults, lk.paths));
|
|
const range = this.rangeFor(next.gameId, next.options);
|
|
if (patch.maxPlayers !== undefined) next.maxPlayers = patch.maxPlayers;
|
|
// A room that had every seat its game allows keeps doing so when an option changes the range (e.g. 윷놀이 팀전 8명).
|
|
else if (next.gameId === this.config.gameId && this.config.maxPlayers === this.playerRange().max) next.maxPlayers = range.max;
|
|
next.maxPlayers = Math.min(Math.max(next.maxPlayers, range.min), range.max);
|
|
if (next.maxPlayers < this.seatedIds().length) return `이미 ${this.seatedIds().length}명이 앉아 있어요.`;
|
|
for (const k of ['visibility', 'allowSpectators', 'chatEnabled', 'chatFilter', 'botChat'] as const) {
|
|
if (patch[k] !== undefined) (next as unknown as Record<string, unknown>)[k] = patch[k];
|
|
}
|
|
// Resize seats, compacting occupied seats to the front if needed.
|
|
if (next.maxPlayers !== this.seats.length) {
|
|
const occupied = this.seats.filter((s): s is Seat => s !== null);
|
|
const seats: (Seat | null)[] = new Array(next.maxPlayers).fill(null);
|
|
let i = 0;
|
|
for (let k = 0; k < this.seats.length && k < next.maxPlayers; k++) if (this.seats[k]) seats[k] = this.seats[k]!;
|
|
const placed = new Set(seats.filter(Boolean).map((s) => s!.userId));
|
|
for (const s of occupied) {
|
|
if (placed.has(s.userId)) continue;
|
|
while (seats[i]) i++;
|
|
seats[i] = s;
|
|
}
|
|
this.seats = seats;
|
|
}
|
|
this.config = next;
|
|
for (const s of this.seats) if (s) s.ready = false;
|
|
this.persist({ actorId: userId, kind: 'config', data: patch });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
kick(userId: string, target: string): string | null {
|
|
if (userId !== this.hostId) return '방장만 내보낼 수 있어요.';
|
|
if (target === userId) return '자기 자신은 내보낼 수 없어요.';
|
|
if (isBotId(target)) return this.removeBot(userId, target);
|
|
if (!this.isParticipant(target)) return '방에 없는 사람이에요.';
|
|
const conn = this.conns.get(target);
|
|
this.kicked.add(target);
|
|
this.leave(target);
|
|
conn?.send({ t: 'bye', reason: 'kicked' });
|
|
conn?.close(4001, 'kicked');
|
|
return null;
|
|
}
|
|
|
|
transferHost(userId: string, target: string): string | null {
|
|
if (userId !== this.hostId) return '방장만 넘길 수 있어요.';
|
|
if (isBotId(target)) return '컴퓨터에게는 방장을 넘길 수 없어요.';
|
|
if (this.seatOf(target) < 0 && !this.spectators.has(target)) return '방에 없는 사람이에요.';
|
|
this.hostId = target;
|
|
this.persist({ actorId: userId, kind: 'host', data: { target } });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
/** Host seats a computer player on an empty seat (docs/06 §12). Rooms with computers are private practice rooms. */
|
|
addBot(userId: string, seat?: number): string | null {
|
|
if (userId !== this.hostId) return '방장만 컴퓨터를 넣을 수 있어요.';
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
if (!botsAllowed(this.config.gameId)) return '이 게임은 컴퓨터와 할 수 없어요.';
|
|
const target = seat ?? this.seats.findIndex((s) => s === null);
|
|
if (target < 0 || target >= this.seats.length) return '빈자리가 없어요.';
|
|
if (this.seats[target]) return '이미 다른 사람이 앉은 자리예요.';
|
|
const used = new Set(this.seatedIds().map(botNumber));
|
|
let n = 1;
|
|
while (used.has(n)) n++;
|
|
const id = makeBotId(n, ulid(this.now(), secureRandom));
|
|
this.seats[target] = { userId: id, ready: true };
|
|
// Any level 1~60 and its own luck, from OS randomness; the host may pick 쉬움/보통/어려움 afterwards.
|
|
this.botProfiles[id] = newBotProfile();
|
|
if (this.config.visibility === 'public') this.config = { ...this.config, visibility: 'private' };
|
|
this.persist({ actorId: userId, kind: 'addBot', data: { seat: target, bot: id } });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
removeBot(userId: string, botId: string): string | null {
|
|
if (userId !== this.hostId) return '방장만 컴퓨터를 뺄 수 있어요.';
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
const seat = this.seatOf(botId);
|
|
if (seat < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
|
|
this.seats[seat] = null;
|
|
this.rematchVotes.delete(botId);
|
|
delete this.botProfiles[botId];
|
|
this.persist({ actorId: userId, kind: 'removeBot', data: { bot: botId } });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
/** Host picks a computer's difficulty: a new level from that range (랜덤 = any), hidden until the game is over. */
|
|
setBotLevel(userId: string, botId: string, pick: BotPick): string | null {
|
|
if (userId !== this.hostId) return '방장만 난이도를 바꿀 수 있어요.';
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
if (this.seatOf(botId) < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
|
|
this.botProfiles[botId] = repick(this.profile(botId), pick);
|
|
this.persist({ actorId: userId, kind: 'botLevel', data: { bot: botId, pick } });
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
chat(userId: string, text: string): string | null {
|
|
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
|
|
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
|
|
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
|
|
const now = this.now();
|
|
// A few lines in a row go through (people often send 2~3 quick lines); a flood still stops.
|
|
let bucket = this.chatBuckets.get(userId);
|
|
if (!bucket) this.chatBuckets.set(userId, (bucket = new TokenBucket(2, 4, now)));
|
|
if (!bucket.take(now)) return '조금 천천히 보내 주세요.';
|
|
this.typingAt.delete(userId);
|
|
const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
|
if (!clean) return null;
|
|
const msg: Extract<ServerMessage, { t: 'chat' }> = {
|
|
t: 'chat',
|
|
from: this.deps.users.publicUser(userId),
|
|
text: this.config.chatFilter ? maskProfanity(clean, this.deps.settings?.getSite().bannedWords ?? []) : clean,
|
|
at: now,
|
|
};
|
|
this.chatLog.push(msg);
|
|
if (this.chatLog.length > CHAT_HISTORY) this.chatLog.shift();
|
|
for (const c of this.conns.values()) c.send(msg);
|
|
if (!isBotId(userId)) this.brain.onHumanChat(userId, msg.text);
|
|
return null;
|
|
}
|
|
|
|
/** Games with their own chat channels (마피아) close the room chat while playing, so nothing leaks around them. */
|
|
private gameChatOnly(): boolean {
|
|
return (this.status === 'playing' || this.status === 'paused') && !!this.def.ownChat;
|
|
}
|
|
|
|
/**
|
|
* "입력 중" for people, like the computers'. Room chat: only while the room chat is open. Game chat: only in games
|
|
* with their own chat, and the client only sends it from the public channel (마피아 낮, 라이어 토론).
|
|
*/
|
|
typing(userId: string, on: boolean, ch: 'room' | 'game'): void {
|
|
if (!this.isParticipant(userId)) return;
|
|
if (ch === 'room' ? !this.config.chatEnabled || this.gameChatOnly() : !this.gameChatOnly()) return;
|
|
const now = this.now();
|
|
if (on) {
|
|
if (now - (this.typingAt.get(userId) ?? -Infinity) < 1000) return;
|
|
this.typingAt.set(userId, now);
|
|
} else this.typingAt.delete(userId);
|
|
for (const [id, c] of this.conns) if (id !== userId) c.send({ t: 'typing', from: userId, on, ch });
|
|
}
|
|
|
|
emote(userId: string, id: string): void {
|
|
if (!this.isParticipant(userId) || this.gameChatOnly()) return;
|
|
const now = this.now();
|
|
if (now - (this.lastChatAt.get(`e:${userId}`) ?? 0) < 500) return;
|
|
this.lastChatAt.set(`e:${userId}`, now);
|
|
for (const c of this.conns.values()) c.send({ t: 'emote', from: userId, id });
|
|
}
|
|
|
|
// ---------------------------------------------------------------- game lifecycle
|
|
|
|
start(userId: string): string | null {
|
|
if (userId !== this.hostId) return '방장만 시작할 수 있어요.';
|
|
const err = this.requireLobby();
|
|
if (err) return err;
|
|
const players = this.orderedPlayers();
|
|
const range = this.playerRange();
|
|
if (players.length < range.min) return `${range.min - players.length}명 더 필요해요.`;
|
|
if (players.length > range.max) return `최대 ${range.max}명까지 할 수 있어요.`;
|
|
if (this.hasBots() && !botsAllowed(this.config.gameId)) return '컴퓨터는 이 게임을 할 수 없어요.';
|
|
if (players.every(isBotId)) return '사람이 한 명은 앉아야 해요.';
|
|
return this.beginGame(players);
|
|
}
|
|
|
|
rematch(userId: string): string | null {
|
|
if (this.status !== 'finished') return '게임이 끝난 뒤에 누를 수 있어요.';
|
|
if (this.starting) return '게임을 준비하고 있어요.';
|
|
if (this.seatOf(userId) < 0) return '자리에 앉아야 해요.';
|
|
this.rematchVotes.add(userId);
|
|
const seated = this.seatedIds();
|
|
const range = this.playerRange();
|
|
if (seated.length >= range.min && seated.every((u) => isBotId(u) || this.rematchVotes.has(u))) {
|
|
return this.beginGame(this.orderedPlayers());
|
|
}
|
|
this.persist(null);
|
|
this.broadcastRoom();
|
|
return null;
|
|
}
|
|
|
|
/** Seated players in seat order, rotated so the host (if seated) comes first. */
|
|
private orderedPlayers(): string[] {
|
|
const ids = this.seatedIds();
|
|
const h = ids.indexOf(this.hostId);
|
|
return h > 0 ? [...ids.slice(h), ...ids.slice(0, h)] : ids;
|
|
}
|
|
|
|
/** The options the game would start with, or why it can't start. */
|
|
private startOptions(players: string[]): { options: unknown } | string {
|
|
const def = this.def;
|
|
const lk = this.locked(def.id);
|
|
const parsed = def.optionsSchema.safeParse(lk.paths.length ? applyLocks(this.config.options, lk.defaults, lk.paths) : this.config.options);
|
|
if (!parsed.success) return '설정 값이 올바르지 않아요.';
|
|
const countErr = def.playerCountError?.(parsed.data, players.length);
|
|
if (countErr) return countErr;
|
|
const eff = this.deps.settings?.game(def.id);
|
|
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
|
|
return { options: parsed.data };
|
|
}
|
|
|
|
/**
|
|
* Starts a game. With computers in a game of chance, a few shuffles are tried first for their luck (docs/04 §5.1)
|
|
* on the luck worker; the room shows "섞는 중" and starts when they are done (well under a few seconds). If the
|
|
* seats changed meanwhile, nothing starts and the host can press start again.
|
|
*/
|
|
private beginGame(players: string[]): string | null {
|
|
const ok = this.startOptions(players);
|
|
if (typeof ok === 'string') return ok;
|
|
const bots = players.filter(isBotId);
|
|
const luckSeed = this.deps.luckSeed;
|
|
if (!luckSeed || !luckApplies(this.def.id) || shufflesFor(bots.map((b) => this.profile(b).luck)) <= 1) return this.startGame(players, null);
|
|
const job: LuckJob = {
|
|
gameId: this.def.id,
|
|
players,
|
|
options: ok.options,
|
|
now: this.now(),
|
|
gameNo: this.gameNo + 1,
|
|
luck: Object.fromEntries(bots.map((b) => [b, this.profile(b).luck])),
|
|
levels: Object.fromEntries(bots.map((b) => [b, this.profile(b).level])),
|
|
budgetMs: LUCK_BUDGET_MS,
|
|
};
|
|
this.starting = true;
|
|
this.broadcastRoom();
|
|
const gameNo = this.gameNo;
|
|
void luckSeed(job)
|
|
.catch((err) => {
|
|
this.deps.log?.('warn', 'luck shuffle failed', { room: this.code, err: String(err) });
|
|
return null;
|
|
})
|
|
.then((picked) => {
|
|
this.starting = false;
|
|
if (this.closed) return;
|
|
const same = this.gameNo === gameNo && this.requireLobby() === null && this.orderedPlayers().join() === players.join();
|
|
const err = same ? this.startGame(players, picked) : null;
|
|
if (err) this.notice('start-failed', err);
|
|
if (!same || err) this.broadcastRoom();
|
|
});
|
|
return null;
|
|
}
|
|
|
|
private startGame(players: string[], picked: { seed: ChaChaSeed; tried: number } | null): string | null {
|
|
const def = this.def;
|
|
const ok = this.startOptions(players);
|
|
if (typeof ok === 'string') return ok;
|
|
this.config = { ...this.config, options: ok.options };
|
|
const seed = picked?.seed ?? createSeed();
|
|
const seedHex = seedToHex(seed);
|
|
const rng = SeededRng.fromSeed(seed);
|
|
const now = this.now();
|
|
const gameNo = this.gameNo + 1;
|
|
let state: unknown;
|
|
try {
|
|
state = def.setup({ players, options: ok.options, rng, now, gameNo });
|
|
} catch (err) {
|
|
this.deps.log?.('error', 'setup failed', { room: this.code, err: String(err) });
|
|
return '게임을 시작하지 못했어요.';
|
|
}
|
|
const gamePk = ulid(now);
|
|
const seedHash = sha256Hex(seedHex);
|
|
// From the second game on, each computer's level moves a little around where it started (docs/09 §9.1).
|
|
const bots: Record<string, { level: number; luck: number }> = {};
|
|
for (const b of players.filter(isBotId)) {
|
|
const p = (this.botProfiles[b] = drift(this.profile(b)));
|
|
bots[b] = { level: p.level, luck: p.luck };
|
|
}
|
|
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: ok.options, seedHash, startedAt: now });
|
|
this.gameNo = gameNo;
|
|
this.game = {
|
|
gameId: def.id,
|
|
stateVersion: def.stateVersion,
|
|
state,
|
|
rng: rng.state(),
|
|
gamePk,
|
|
seedHex,
|
|
seedHash,
|
|
startedAt: now,
|
|
players,
|
|
finished: false,
|
|
deadlineFloor: null,
|
|
...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}),
|
|
};
|
|
this.status = 'playing';
|
|
this.rematchVotes.clear();
|
|
this.lastResult = null;
|
|
this.consecutiveErrors = 0;
|
|
for (const s of this.seats) if (s) s.ready = false;
|
|
this.persist({ actorId: this.hostId, kind: 'start', data: { gameId: def.id, players, seedHash, stateVersion: def.stateVersion }, at: now });
|
|
this.broadcastRoom();
|
|
this.broadcastState([{ type: 'gameStarted' }]);
|
|
this.scheduleTimer();
|
|
this.brain.onGameStart();
|
|
return null;
|
|
}
|
|
|
|
/** Client action entry. `cs` dedupes retransmissions (docs/03 §5). */
|
|
act(userId: string, cs: number, action: unknown): void {
|
|
const conn = this.conns.get(userId);
|
|
const reject = (reason: string) => conn?.send({ t: 'reject', cs, reason });
|
|
const recent = this.recentCs.get(userId) ?? [];
|
|
if (recent.includes(cs)) return;
|
|
recent.push(cs);
|
|
if (recent.length > 50) recent.shift();
|
|
this.recentCs.set(userId, recent);
|
|
if (!this.game || this.game.finished || this.status !== 'playing') return reject('진행 중인 게임이 없어요.');
|
|
if (!this.game.players.includes(userId)) return reject('이 게임의 플레이어가 아니에요.');
|
|
const parsed = this.def.actionSchema.safeParse(action);
|
|
if (!parsed.success) return reject('잘못된 요청이에요.');
|
|
const err = this.runAction(userId, parsed.data, cs, false);
|
|
if (err) reject(err);
|
|
}
|
|
|
|
/** Validates and applies one action; returns an error message on rejection. */
|
|
private runAction(userId: string, action: unknown, cs: number | undefined, system: boolean): string | null {
|
|
const g = this.game;
|
|
if (!g || g.finished) return '진행 중인 게임이 없어요.';
|
|
const def = this.def;
|
|
let next: { state: unknown; events: unknown[] };
|
|
const rng = new SeededRng(g.rng);
|
|
const now = this.now();
|
|
try {
|
|
const v = def.validate(g.state, userId, action, { now });
|
|
if (!v.ok) return v.reason;
|
|
next = def.apply(g.state, userId, action, { rng, now });
|
|
} catch (err) {
|
|
this.consecutiveErrors++;
|
|
this.deps.log?.('error', 'game apply failed', { room: this.code, game: def.id, seq: this.seq, action, err: String(err), stack: (err as Error)?.stack });
|
|
if (this.consecutiveErrors >= ERROR_LIMIT) {
|
|
this.status = 'paused';
|
|
this.clearTimer();
|
|
this.persist({ actorId: null, kind: 'paused', data: null });
|
|
this.broadcastRoom();
|
|
this.notice('paused', '오류가 반복되어 게임을 멈췄어요. 방장은 게임을 끝낼 수 있어요.');
|
|
}
|
|
return '알 수 없는 오류가 발생했어요.';
|
|
}
|
|
this.consecutiveErrors = 0;
|
|
g.state = next.state;
|
|
g.rng = rng.state();
|
|
g.deadlineFloor = null;
|
|
if (!system && def.isStreamAction?.(action)) {
|
|
// Relay the (public) events only; views are not recomputed per stroke batch (docs/games/catchmind.md §5.5).
|
|
this.persistStream({ actorId: userId, kind: 'act', data: action, at: now });
|
|
const msg: ServerMessage = { t: 'stream', seq: this.seq, events: next.events };
|
|
for (const c of this.conns.values()) c.send(c.userId === userId && cs !== undefined ? { ...msg, cs } : msg);
|
|
} else {
|
|
this.persist({ actorId: userId, kind: system ? 'auto' : 'act', data: action, at: now });
|
|
this.broadcastState(next.events, userId, cs);
|
|
this.brain.onAction(userId, action);
|
|
}
|
|
const result = def.result(g.state);
|
|
if (result) this.finishGame(result);
|
|
else this.scheduleTimer();
|
|
return null;
|
|
}
|
|
|
|
/** Host ends a paused/broken game without counting it. */
|
|
voidGame(userId: string): string | null {
|
|
if (userId !== this.hostId) return '방장만 할 수 있어요.';
|
|
if (!this.game || this.game.finished) return '진행 중인 게임이 없어요.';
|
|
this.finishGame({ ranking: [this.game.players], summary: '게임이 무효 처리됐어요.', reason: 'abandoned' }, true);
|
|
return null;
|
|
}
|
|
|
|
private finishGame(result: GameResult, voided = false): void {
|
|
const g = this.game!;
|
|
g.finished = true;
|
|
this.clearTimer();
|
|
const rankOf = new Map<string, number>();
|
|
let rank = 1;
|
|
for (const group of result.ranking) {
|
|
for (const u of group) rankOf.set(u, rank);
|
|
rank += group.length;
|
|
}
|
|
const players = g.players.map((u) => ({
|
|
userId: u,
|
|
seat: this.seatOf(u),
|
|
rank: rankOf.get(u) ?? null,
|
|
score: result.scores?.[u] ?? null,
|
|
}));
|
|
this.deps.store.finishGame({
|
|
id: g.gamePk,
|
|
gameId: g.gameId,
|
|
seed: g.seedHex,
|
|
endedAt: this.now(),
|
|
endReason: voided ? 'void' : result.reason,
|
|
result,
|
|
players,
|
|
practice: g.players.some(isBotId),
|
|
});
|
|
const allFirst = players.every((p) => p.rank === 1);
|
|
if (!voided) {
|
|
for (const p of players) {
|
|
const st = (this.sessionStats[p.userId] ??= { played: 0, wins: 0 });
|
|
st.played++;
|
|
if (p.rank === 1 && !allFirst) st.wins++;
|
|
}
|
|
}
|
|
this.lastSeed = g.seedHex;
|
|
this.lastResult = result;
|
|
this.status = 'finished';
|
|
// Players who left during the game lose their seat now.
|
|
for (let i = 0; i < this.seats.length; i++) {
|
|
const s = this.seats[i];
|
|
if (s && this.leftDuringGame.has(s.userId)) {
|
|
this.seats[i] = null;
|
|
this.presence.delete(s.userId);
|
|
this.deps.onSeatChange?.(this, s.userId, false);
|
|
}
|
|
}
|
|
this.leftDuringGame.clear();
|
|
this.persist({ actorId: null, kind: 'finish', data: { result, voided } });
|
|
this.broadcastState([{ type: 'gameOver' }]);
|
|
for (const c of this.conns.values()) c.send({ t: 'result', seq: this.seq, result });
|
|
if (this.botActivity.size) this.botActivity.clear();
|
|
this.broadcastRoom();
|
|
if (!voided) this.brain.onGameEnd(result.ranking);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- timers
|
|
|
|
/** Earliest time any timed player must be auto-acted for. */
|
|
effectiveDeadline(): number | null {
|
|
const g = this.game;
|
|
if (!g || g.finished || this.status !== 'playing') return null;
|
|
const def = this.def;
|
|
const base = def.deadline?.(g.state) ?? null;
|
|
const notBefore = def.timeoutNotBefore?.(g.state) ?? null;
|
|
const timed = def.timeoutPlayers ? def.timeoutPlayers(g.state) : def.activePlayers(g.state);
|
|
const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000;
|
|
let best: number | null = null;
|
|
for (const u of timed) {
|
|
let d = base;
|
|
const p = this.presence.get(u);
|
|
if (p && !p.connected) {
|
|
const grace = p.since + graceMs;
|
|
d = d === null ? grace : Math.min(d, grace);
|
|
}
|
|
if (d === null) continue;
|
|
if (g.deadlineFloor !== null) d = Math.max(d, g.deadlineFloor);
|
|
if (notBefore !== null) d = Math.max(d, notBefore);
|
|
best = best === null ? d : Math.min(best, d);
|
|
}
|
|
return best;
|
|
}
|
|
|
|
scheduleTimer(): void {
|
|
if (this.timer) clearTimeout(this.timer);
|
|
this.timer = null;
|
|
// A computer move already planned stays planned (it re-reads the state when it fires).
|
|
this.bots.schedule();
|
|
const at = this.effectiveDeadline();
|
|
if (at === null) return;
|
|
const delay = Math.max(0, at - this.now());
|
|
this.timer = setTimeout(() => this.onTimer(), Math.min(delay, 2 ** 31 - 1));
|
|
}
|
|
|
|
/** Clears the turn timer and any planned computer move. */
|
|
clearTimer(): void {
|
|
if (this.timer) clearTimeout(this.timer);
|
|
this.timer = null;
|
|
this.bots.cancel();
|
|
}
|
|
|
|
/** Fires due timeouts. Public for tests. */
|
|
onTimer(): void {
|
|
this.timer = null;
|
|
const g = this.game;
|
|
if (!g || g.finished || this.status !== 'playing') return;
|
|
const def = this.def;
|
|
const now = this.now();
|
|
const base = def.deadline?.(g.state) ?? null;
|
|
const notBefore = def.timeoutNotBefore?.(g.state) ?? null;
|
|
const timed = def.timeoutPlayers ? def.timeoutPlayers(g.state) : def.activePlayers(g.state);
|
|
const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000;
|
|
for (const u of timed) {
|
|
let d = base;
|
|
const p = this.presence.get(u);
|
|
if (p && !p.connected) {
|
|
const grace = p.since + graceMs;
|
|
d = d === null ? grace : Math.min(d, grace);
|
|
}
|
|
if (g.deadlineFloor !== null && d !== null) d = Math.max(d, g.deadlineFloor);
|
|
if (notBefore !== null && d !== null) d = Math.max(d, notBefore);
|
|
if (d === null || d > now) continue;
|
|
const action = def.onTimeout(g.state, u);
|
|
const err = this.runAction(u, action, undefined, true);
|
|
if (err) this.deps.log?.('warn', 'timeout action rejected', { room: this.code, user: u, err });
|
|
break; // state changed; re-evaluate via scheduleTimer
|
|
}
|
|
if (!this.game?.finished) this.scheduleTimer();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- misc
|
|
|
|
private nick(u: string): string {
|
|
return this.deps.users.publicUser(u)?.nickname ?? '알 수 없음';
|
|
}
|
|
|
|
sendSync(conn: Conn): void {
|
|
conn.send({ t: 'room', seq: this.seq, room: this.roomView() });
|
|
const st = this.stateMessage(conn.userId, undefined, true);
|
|
if (st) conn.send(st);
|
|
}
|
|
|
|
/** Admin closes the room: void any running game, tell everyone, disconnect. */
|
|
closeByAdmin(): void {
|
|
this.closeWith('관리자가 방을 닫아 무효 처리됐어요.', '관리자가 방을 닫았어요.');
|
|
}
|
|
|
|
/** Ends a running game uncounted and sends everyone still in the room away (the manager then closes it). */
|
|
closeWith(summary: string, notice: string): void {
|
|
this.closed = true;
|
|
if (this.game && !this.game.finished) {
|
|
this.finishGame({ ranking: [this.game.players], summary, reason: 'abandoned' }, true);
|
|
}
|
|
this.notice('closed', notice);
|
|
this.clearTimer();
|
|
for (const c of this.conns.values()) {
|
|
c.send({ t: 'bye', reason: 'closed' });
|
|
c.close(4002, 'closed');
|
|
}
|
|
this.conns.clear();
|
|
}
|
|
|
|
shutdown(): void {
|
|
this.closed = true;
|
|
this.flushStream();
|
|
this.clearTimer();
|
|
for (const c of this.conns.values()) {
|
|
c.send({ t: 'bye', reason: 'restart' });
|
|
c.close(1012, 'restart');
|
|
}
|
|
}
|
|
}
|