컴퓨터 난이도 1~60단계·방장 선택·판마다 변화·운, 공정성 확인에 표기, 업데이트 알림 팝업

- 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위
- 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말)
- humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60)
- 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로
- 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수
- 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕]
- 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-11 17:46:13 +09:00
parent 3cbc3698d3
commit 84d64b27f2
40 changed files with 1349 additions and 133 deletions

View File

@@ -3,10 +3,13 @@
* 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 GameResult, type RngState } from '@bg/engine';
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
import { 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 { 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';
@@ -54,6 +57,10 @@ interface GameSlot {
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. */
@@ -70,6 +77,8 @@ export interface RoomSnapshot {
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 {
@@ -91,9 +100,16 @@ export interface RoomDeps {
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;
@@ -117,6 +133,12 @@ export class Room {
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). */
@@ -166,6 +188,7 @@ export class Room {
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,
now: this.now,
},
deps.ai ?? null,
@@ -191,6 +214,7 @@ export class Room {
},
log: deps.log,
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
profile: (bot) => this.profile(bot),
brain: this.brain,
},
secureRandom,
@@ -289,6 +313,7 @@ export class Room {
lastResult: this.lastResult,
game: this.game,
joinedAt,
bots: this.botProfiles,
};
}
@@ -303,6 +328,7 @@ export class Room {
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).
@@ -396,6 +422,10 @@ export class Room {
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 } : {}),
};
}
@@ -574,9 +604,15 @@ export class Room {
// ---------------------------------------------------------------- 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. */
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;
@@ -712,9 +748,10 @@ export class Room {
const used = new Set(this.seatedIds().map(botNumber));
let n = 1;
while (used.has(n)) n++;
// The id's random part is the computer's level roll (`botDraw`): uniform OS randomness.
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();
@@ -729,11 +766,24 @@ export class Room {
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 '방에 들어와야 채팅할 수 있어요.';
@@ -781,17 +831,18 @@ export class Room {
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);
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.startGame(this.orderedPlayers());
return this.beginGame(this.orderedPlayers());
}
this.persist(null);
this.broadcastRoom();
@@ -805,7 +856,8 @@ export class Room {
return h > 0 ? [...ids.slice(h), ...ids.slice(0, h)] : ids;
}
private startGame(players: string[]): string | null {
/** 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);
@@ -814,22 +866,75 @@ export class Room {
if (countErr) return countErr;
const eff = this.deps.settings?.game(def.id);
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
this.config = { ...this.config, options: parsed.data };
const seed = createSeed();
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: parsed.data, rng, now, gameNo });
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);
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: parsed.data, seedHash, startedAt: now });
// 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,
@@ -843,6 +948,7 @@ export class Room {
players,
finished: false,
deadlineFloor: null,
...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}),
};
this.status = 'playing';
this.rematchVotes.clear();
@@ -1074,6 +1180,7 @@ export class Room {
/** 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);
}
@@ -1087,6 +1194,7 @@ export class Room {
}
shutdown(): void {
this.closed = true;
this.flushStream();
this.clearTimer();
for (const c of this.conns.values()) {