Merge branch 'm9/bots' into codex/owner/grp_discord_joke-app

This commit is contained in:
EJClaw
2026-10-06 13:35:33 +09:00
73 changed files with 5355 additions and 38 deletions

View File

@@ -4,8 +4,9 @@
*/
import { ulid } from 'ulid';
import { SeededRng, createSeed, seedToHex, type AnyGameDefinition, type GameResult, type RngState } from '@bg/engine';
import { maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { sha256Hex } from '../auth/sessions';
import { BotDriver } from './bots';
import type { LogEntry, RoomStore } from './store';
import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings';
@@ -79,6 +80,8 @@ export interface RoomDeps {
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?: (choices: number, withPeople: boolean) => number;
}
const CHAT_HISTORY = 30;
@@ -113,6 +116,8 @@ export class Room {
private lastChatAt = new Map<string, number>();
private consecutiveErrors = 0;
private readonly now: () => number;
/** Plays the computer players' moves (docs/06 §12). */
readonly bots: BotDriver;
constructor(
readonly id: string,
@@ -125,6 +130,28 @@ export class Room {
this.seats = new Array(config.maxPlayers).fill(null);
this.now = deps.now ?? Date.now;
this.lastActiveAt = this.now();
const room = this;
this.bots = new BotDriver(
{
get status() {
return room.status;
},
get game() {
return room.game;
},
get def() {
return room.def;
},
now: this.now,
run: (bot, action) => {
const parsed = this.def.actionSchema.safeParse(action);
return parsed.success ? this.runAction(bot, parsed.data, undefined, false) : '잘못된 요청이에요.';
},
log: deps.log,
},
Math.random,
deps.botDelay,
);
}
get def(): AnyGameDefinition {
@@ -169,6 +196,10 @@ export class Room {
return !!this.game && !this.game.finished && this.game.players.includes(userId);
}
hasBots(): boolean {
return this.seats.some((s) => !!s && isBotId(s.userId));
}
// ---------------------------------------------------------------- snapshot
snapshot(): RoomSnapshot {
@@ -203,7 +234,8 @@ export class Room {
room.game = snap.game;
const now = room.now();
for (const s of room.seats) {
if (s) room.presence.set(s.userId, { connected: false, since: now, joinedAt: snap.joinedAt[s.userId] ?? now });
// 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;
@@ -262,6 +294,8 @@ export class Room {
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;
@@ -417,6 +451,11 @@ export class Room {
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);
@@ -434,7 +473,7 @@ export class Room {
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()[0] ?? [...this.spectators][0];
const next = candidates[0]?.[0] ?? this.seatedIds().find((u) => !isBotId(u)) ?? [...this.spectators][0];
if (next) this.hostId = next;
}
@@ -503,6 +542,8 @@ export class Room {
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);
@@ -545,6 +586,7 @@ export class Room {
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);
@@ -556,6 +598,7 @@ export class Room {
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 } });
@@ -563,6 +606,39 @@ export class Room {
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()));
this.seats[target] = { userId: id, ready: true };
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);
this.persist({ actorId: userId, kind: 'removeBot', data: { bot: botId } });
this.broadcastRoom();
return null;
}
chat(userId: string, text: string): string | null {
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
@@ -607,6 +683,8 @@ export class Room {
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.startGame(players);
}
@@ -616,7 +694,7 @@ export class Room {
this.rematchVotes.add(userId);
const seated = this.seatedIds();
const range = this.playerRange();
if (seated.length >= range.min && seated.every((u) => this.rematchVotes.has(u))) {
if (seated.length >= range.min && seated.every((u) => isBotId(u) || this.rematchVotes.has(u))) {
return this.startGame(this.orderedPlayers());
}
this.persist(null);
@@ -774,6 +852,7 @@ export class Room {
endReason: voided ? 'void' : result.reason,
result,
players,
practice: g.players.some(isBotId),
});
const allFirst = players.every((p) => p.rank === 1);
if (!voided) {
@@ -830,16 +909,21 @@ export class Room {
}
scheduleTimer(): void {
this.clearTimer();
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. */