컴퓨터 난이도(쉬움 35%·보통 40%·어려움 25%)와 사람 같은 수, 서버 난수를 OS 보안 난수로

- secureRandom(): crypto.getRandomValues 53비트 실수. 서버의 Math.random(컴퓨터 수·생각 시간·AI 말·방 코드·마감 유예)을 모두 교체
- 컴퓨터 id의 ULID를 secureRandom으로 만들고, 그 무작위 부분 30비트로 난이도·말투(smart)를 정함(botDraw)
- humanBest: 오목·체스·장기·오델로·바둑에서 난이도별로 비슷한 수(slip)·사고(lapse)·꼭 둬야 할 수 놓침(miss)
- 문서 09 §9.1(확률표·게임별 기준·대국 결과), 06 §12; 테스트 bots/level.test.ts, 레벨별 완주 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-11 16:19:06 +09:00
parent 07fe46562f
commit 3cbc3698d3
20 changed files with 312 additions and 41 deletions

View File

@@ -10,6 +10,7 @@
* Moves themselves still come from each game's computer strategy (it sees only its own screen). Without a model
* (not configured, busy, down) the computers simply play as before, silently, and 마피아 uses its built-in lines.
*/
import { secureRandom } from '@bg/engine';
import { botPace, hash01 } from '@bg/games/bots';
import type { Llm } from './llm';
import { cleanLine, decide, temperOf, writeLine, type LineRequest } from './lines';
@@ -53,7 +54,7 @@ export class BotBrain {
constructor(
private room: BrainRoom,
readonly llm: Llm | null,
private random: () => number = Math.random,
private random: () => number = secureRandom,
private sleep: (ms: number) => Promise<void> = sleepReal,
) {}

View File

@@ -3,7 +3,7 @@
* After every state change the room calls `schedule()`: if the game waits on a bot, one action is planned after a
* short human-like pause and played through the room's normal action path (validated, logged as `act`).
*/
import type { AnyGameDefinition } from '@bg/engine';
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
import { isBotId } from '@bg/shared';
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, type LiveBotStrategy } from '@bg/games/bots';
@@ -45,7 +45,7 @@ export interface BotDelayInput {
* own pace, and a follow-up move of the same turn is quicker. When people may act in the same window the computer
* waits 1.5 s more so it never beats a person to a reaction just by being fast.
*/
export function defaultBotDelay(input: BotDelayInput, random: () => number = Math.random): number {
export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): number {
const { choices, withPeople, bot, followUp } = input;
let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400;
if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000;
@@ -78,7 +78,7 @@ export class BotDriver {
constructor(
private room: BotRoom,
private random: () => number = Math.random,
private random: () => number = secureRandom,
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random),
) {}
@@ -247,7 +247,7 @@ export class BotDriver {
const t0 = performance.now();
let action: unknown;
try {
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random });
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: botPersona(next.bot).level });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
action = null;

View File

@@ -1,6 +1,6 @@
/** Creates, finds, restores and garbage-collects rooms (docs/06 §11, docs/04 §3). */
import { ulid } from 'ulid';
import type { AnyGameDefinition } from '@bg/engine';
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
import { PRACTICE_PLAYERS, botsAllowed, isAllowedRoomCode, isBotId, type PublicUser } from '@bg/shared';
import { Room, type RoomConfig, type RoomDeps, type RoomSnapshot } from './room';
import type { RoomStore } from './store';
@@ -80,7 +80,7 @@ export class RoomManager {
}
private newCode(): string {
const rand = this.deps.random ?? Math.random;
const rand = this.deps.random ?? secureRandom;
for (let i = 0; i < 200; i++) {
const code = String(Math.floor(rand() * 1_000_000)).padStart(6, '0');
if (!isAllowedRoomCode(code) || this.byCode.has(code)) continue;

View File

@@ -3,7 +3,7 @@
* All mutations run on the single JS thread, so a room never sees concurrent updates.
*/
import { ulid } from 'ulid';
import { SeededRng, createSeed, seedToHex, type AnyGameDefinition, type GameResult, type RngState } from '@bg/engine';
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 { sha256Hex } from '../auth/sessions';
import { BotDriver, type BotDelayInput } from './bots';
@@ -169,7 +169,7 @@ export class Room {
now: this.now,
},
deps.ai ?? null,
deps.aiRandom ?? Math.random,
deps.aiRandom ?? secureRandom,
deps.aiSleep,
);
this.bots = new BotDriver(
@@ -193,7 +193,7 @@ export class Room {
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
brain: this.brain,
},
Math.random,
secureRandom,
deps.botDelay,
);
}
@@ -317,7 +317,7 @@ export class Room {
}
// 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(Math.random() * 30_000);
room.game.deadlineFloor = now + 30_000 + Math.floor(secureRandom() * 30_000);
room.scheduleTimer();
}
return room;
@@ -712,7 +712,8 @@ export class Room {
const used = new Set(this.seatedIds().map(botNumber));
let n = 1;
while (used.has(n)) n++;
const id = makeBotId(n, ulid(this.now()));
// 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 };
if (this.config.visibility === 'public') this.config = { ...this.config, visibility: 'private' };
this.persist({ actorId: userId, kind: 'addBot', data: { seat: target, bot: id } });