From 3cbc3698d3202182421046213d88e6cc42a847af Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 11 Oct 2026 16:19:06 +0900 Subject: [PATCH] =?UTF-8?q?=EC=BB=B4=ED=93=A8=ED=84=B0=20=EB=82=9C?= =?UTF-8?q?=EC=9D=B4=EB=8F=84(=EC=89=AC=EC=9B=80=2035%=C2=B7=EB=B3=B4?= =?UTF-8?q?=ED=86=B5=2040%=C2=B7=EC=96=B4=EB=A0=A4=EC=9B=80=2025%)?= =?UTF-8?q?=EC=99=80=20=EC=82=AC=EB=9E=8C=20=EA=B0=99=EC=9D=80=20=EC=88=98?= =?UTF-8?q?,=20=EC=84=9C=EB=B2=84=20=EB=82=9C=EC=88=98=EB=A5=BC=20OS=20?= =?UTF-8?q?=EB=B3=B4=EC=95=88=20=EB=82=9C=EC=88=98=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- apps/server/src/ai/brain.ts | 3 +- apps/server/src/rooms/bots.ts | 8 +-- apps/server/src/rooms/manager.ts | 4 +- apps/server/src/rooms/room.ts | 11 ++-- docs/06-lobby-rooms.md | 1 + docs/09-game-engine.md | 48 +++++++++++++- packages/engine/src/rng.ts | 19 ++++++ packages/games/src/baduk/bot.ts | 7 +- packages/games/src/bots/bots.test.ts | 12 ++++ packages/games/src/bots/index.ts | 11 ++-- packages/games/src/bots/level.test.ts | 93 +++++++++++++++++++++++++++ packages/games/src/bots/persona.ts | 36 ++++++++++- packages/games/src/bots/playout.ts | 5 +- packages/games/src/bots/policy.ts | 55 ++++++++++++++++ packages/games/src/bots/types.ts | 2 + packages/games/src/chess/bot.ts | 7 +- packages/games/src/janggi/bot.ts | 7 +- packages/games/src/mafia/bot.test.ts | 8 +-- packages/games/src/omok/bot.ts | 9 ++- packages/games/src/othello/bot.ts | 7 +- 20 files changed, 312 insertions(+), 41 deletions(-) create mode 100644 packages/games/src/bots/level.test.ts diff --git a/apps/server/src/ai/brain.ts b/apps/server/src/ai/brain.ts index 2552c8b..8d10508 100644 --- a/apps/server/src/ai/brain.ts +++ b/apps/server/src/ai/brain.ts @@ -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 = sleepReal, ) {} diff --git a/apps/server/src/rooms/bots.ts b/apps/server/src/rooms/bots.ts index bc65630..06a2d28 100644 --- a/apps/server/src/rooms/bots.ts +++ b/apps/server/src/rooms/bots.ts @@ -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; diff --git a/apps/server/src/rooms/manager.ts b/apps/server/src/rooms/manager.ts index 16416ee..afeb6ab 100644 --- a/apps/server/src/rooms/manager.ts +++ b/apps/server/src/rooms/manager.ts @@ -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; diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index a565d49..70fc2df 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -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 } }); diff --git a/docs/06-lobby-rooms.md b/docs/06-lobby-rooms.md index 7341026..ae4a34c 100644 --- a/docs/06-lobby-rooms.md +++ b/docs/06-lobby-rooms.md @@ -116,6 +116,7 @@ interface Room { ### 12.1 사람처럼 노는 컴퓨터 (GPU 로컬 모델, 2026-10-11) - 수 고르기는 게임별 전략(자기 화면만 봄) 그대로다. 그 위에 GPU의 로컬 언어 모델(gemma3:4b, docs/11 §8)이 말과 심리전을 맡는다(`apps/server/src/ai/`). - 성격: 컴퓨터 id로 정해지는 5가지 — 도발형·허세형·차분형·수다형·소심형 — 와 말투(똑똑한 편 존댓말, 허술한 편 반말). +- 난이도: 컴퓨터마다 쉬움 35%·보통 40%·어려움 25%로 정해지고(보안 난수), 오목·체스·장기·오델로·바둑에서는 난이도에 따라 가끔 비슷한 다른 수를 두거나 실수한다. 확률과 기준은 09 §9.1. - 보이는 행동: 수를 고르는 동안 "🤖 컴퓨터 1 생각 중…", 말할 때는 그 줄을 치는 만큼(글자 수 × 컴퓨터마다 다른 타자 속도, 0.9~6.5초) "💬 입력 중…"이 보인 뒤 채팅이 올라가고, 잠깐 뒤 수를 둔다(상태 줄과 채팅 칸, `RoomView.botActivity`). - 말하는 때: 자기 수와 함께 도발·심리전 한마디(성격별 14~38%, 방 전체 8초·컴퓨터마다 20초 간격), 사람의 수에 가끔 반응(12%), 사람이 이름을 부르거나 말을 걸면 대답(이름 부르면 꼭, 아니면 40%), 시작 인사, 끝나면 이긴 컴퓨터가 놀리거나 진 컴퓨터가 아쉬워함. - 심리전 판단: 바퀴벌레 포커에서 카드를 건넬 때 진짜를 말할지 블러핑할지를 모델이 정하고, 그걸 파는 한마디를 한다(실제 카드 이름이 들어간 말은 버림). 마피아는 컴퓨터가 계획한 대사(의심 지목·반박·반론 등)를 모델이 자기 말로 바꾼다. 모델에게 그 컴퓨터의 직업은 알려 주지 않고, "저 경찰이에요"·"나 마피아" 같은 직업 주장이 나오면 버리고 원래 대사를 쓴다. diff --git a/docs/09-game-engine.md b/docs/09-game-engine.md index a2e9d15..b045883 100644 --- a/docs/09-game-engine.md +++ b/docs/09-game-engine.md @@ -135,5 +135,51 @@ export interface GameUI { ## 9. 컴퓨터 상대 (`packages/games/src/bots/`, 06 §12) - 게임마다 `<게임>/bot.ts`의 전략 하나: `(입력: { me, view, legal, random }) => 행동`. `view`는 `view(state, me)`, `legal`은 `legalActions(state, me)`. 게임 상태는 넘기지 않는다(비공개 정보 차단). - `decideBotAction`이 고른 수를 `validate`로 다시 검사하고, 틀리면 다른 합법 수로 바꾼다. 서버는 그래도 실패하면 게임의 `onTimeout` 행동을 쓴다. -- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임. 전략은 `({ me, view, now, persona, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편과 빠르기, `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`. +- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임. 전략은 `({ me, view, now, persona, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 난이도(§9.1), 똑똑한 편/허술한 편과 빠르기, `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`. - 테스트(`bots/bots.test.ts`): 게임마다 "사람 1명은 시간 초과만, 나머지는 컴퓨터"와 "컴퓨터끼리" 판을 끝까지 돌려, 모든 수가 합법이고 컴퓨터 때문에 멈추지 않으며 한 수가 충분히 빠른지 본다. + +### 9.1 컴퓨터 난이도와 난수 (2026-10-11) + +**난수.** 서버가 고르는 것은 모두 OS 보안 난수(`crypto.getRandomValues`)를 쓴다. `Math.random`은 서버에 남아 있지 않다. + +| 무엇 | 난수 | +|---|---| +| 카드 섞기·주사위·타일 뽑기 | 판마다 256비트 OS 시드 + ChaCha20(§3) | +| 컴퓨터의 수 고르기, 생각 시간, 채팅 여부, 방 코드, 마감 유예 | `secureRandom()`(`packages/engine/src/rng.ts`, OS 난수 53비트 실수) | +| 컴퓨터의 난이도·말투 | 컴퓨터 id `bot::`의 무작위 부분(ULID를 `secureRandom`으로 만듦) 앞 6글자 = 30비트 균등 난수(`botDraw`) | + +브라우저의 닉네임 추천과 재연결 대기 시간은 보안과 상관없어 그대로 둔다. + +**난이도 확률.** 컴퓨터를 넣을 때 하나씩 정해지고, 그 컴퓨터는 서버가 다시 켜져도 같은 난이도다(`bots/persona.ts`). 화면에는 보이지 않는다. + +| 난이도 | 확률 (`BOT_LEVEL_ODDS`) | 성격·말투 (`smart`) | +|---|---|---| +| 쉬움 | 35% (`botDraw` 0~0.35) | 전부 허술한 편, 반말 | +| 보통 | 40% (0.35~0.75) | 앞 절반(0.35~0.5) 허술한 편·반말, 뒤 절반(0.5~0.75) 똑똑한 편·존댓말 | +| 어려움 | 25% (0.75~1) | 전부 똑똑한 편, 존댓말 | + +그래서 똑똑한 편과 허술한 편은 전체에서 반반이다(마피아 §13 그대로). + +**사람처럼 두기(`humanBest`, `bots/policy.ts`).** 오목·체스·장기·오델로·바둑 컴퓨터는 수마다 점수를 매긴 뒤 늘 1등 수만 두지 않는다. 한 수마다 확률(`BOT_PLAY`): + +| 난이도 | 1등 수 | 비슷한 수 (점수 차 `small`×창 이내, 상위 5개) | 사고 (점수 차 `small`×8 이내, 상위 8개) | 꼭 둬야 할 수를 놓침 | +|---|---|---|---|---| +| 쉬움 | 약 59% | 35% (창 ×2) | 6% | 12% | +| 보통 | 약 78% | 20% (창 ×1) | 2% | 3% | +| 어려움 | 약 91.5% | 8% (창 ×0.5) | 0.5% | 0% | + +- 범위 안에 고를 다른 수가 없으면 1등 수를 둔다. 아무리 사고여도 `small`×8보다 나쁜 수(퀸을 그냥 주기, 바로 지는 수 등)는 두지 않는다. +- "꼭 둬야 할 수"는 점수가 `critical` 이상인 1등 수다. 놓치면 그다음으로 좋아 보이는 수 3개 중 하나를 둔다. +- 게임별 기준: + +| 게임 | `small` (작은 실수 한 번의 크기) | `critical` (꼭 둬야 할 수) | +|---|---|---| +| 오목 | 150 (열린 2 하나 정도) | 50,000: 오목 완성, 상대 오목 막기 | +| 체스 | 40 (폰 0.4개) | 100,000: 메이트 | +| 장기 | 40 (기물 점수 0.4) | 100,000: 외통, 이기는 점수 판정 | +| 오델로 | 3 (상대가 둘 곳 2개 더) | 90: 빈 귀 잡기 | +| 바둑 | 1.5 (모양 점수) | 24: 돌 3개 이상 따내기·살리기 | + +- 다른 게임(카드·주사위 등)은 패와 주사위가 이미 무작위라 지금처럼 고른다. 생각 시간은 06 §12대로 가끔(12%) 1~3초 더 멈칫한다. +- 컴퓨터끼리 대국(무작위 시드, 선후 번갈아): 오목 어려움 대 쉬움 100판 84승 16패, 보통 대 쉬움 60판 42승 18패, 어려움 대 예전(늘 1등 수) 60판 34승 26패. 체스 어려움 대 쉬움 40판 18승 10패 12무. +- 테스트: `bots/level.test.ts`(보안 난수 분포, 난이도 확률·말투 짝, `humanBest` 확률), `bots/bots.test.ts`(다섯 게임 모두 쉬움·어려움 컴퓨터끼리 끝까지 둠). diff --git a/packages/engine/src/rng.ts b/packages/engine/src/rng.ts index fefe11d..debcb6e 100644 --- a/packages/engine/src/rng.ts +++ b/packages/engine/src/rng.ts @@ -30,6 +30,25 @@ export function createSeed(): ChaChaSeed { return [...buf] as ChaChaSeed; } +/** Pool of OS random words for `secureRandom` (one `getRandomValues` call per 256 numbers). */ +const pool = new Uint32Array(512); +let poolAt = pool.length; + +/** + * Uniform float in [0, 1) with 53 random bits from the operating system's secure source (`crypto.getRandomValues`), + * a drop-in for `Math.random` wherever the server picks something nobody should be able to predict: computer moves, + * thinking times, room codes, computer ids (2026-10-11). Game dice/cards/tiles use the seeded ChaCha20 below. + */ +export function secureRandom(): number { + if (poolAt + 2 > pool.length) { + crypto.getRandomValues(pool); + poolAt = 0; + } + const hi = pool[poolAt++]! >>> 5; // 27 bits + const lo = pool[poolAt++]! >>> 6; // 26 bits + return (hi * 67108864 + lo) / 9007199254740992; +} + export function seedToHex(seed: RngState): string { return seed.map((n) => (n >>> 0).toString(16).padStart(8, '0')).join(''); } diff --git a/packages/games/src/baduk/bot.ts b/packages/games/src/baduk/bot.ts index 64df2f2..4e22268 100644 --- a/packages/games/src/baduk/bot.ts +++ b/packages/games/src/baduk/bot.ts @@ -4,7 +4,7 @@ * agrees, after restoring the automatic suggestion if the marks were changed against it. */ import type { BotStrategy } from '../bots/types'; -import { answerRequests, best, pick, playable, typeOf } from '../bots/policy'; +import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy'; import type { BadukView } from './index'; import { emptyRegionAt, mapChains, markGroup, neighbours, regionsOf, suggestMarks, type Cell, type Stone } from './board'; @@ -35,7 +35,7 @@ function scoringAction(view: BadukView): Act { return { type: 'agreeScore' }; } -export const badukBot: BotStrategy = ({ view, legal, random }) => { +export const badukBot: BotStrategy = ({ view, legal, random, level }) => { const req = answerRequests(legal); if (req) return req; if (view.phase === 'scoring') return legal.some((a) => a.type === 'agreeScore') ? scoringAction(view) : pick(playable(legal), random); @@ -131,7 +131,8 @@ export const badukBot: BotStrategy = ({ view, legal, random }) = // Very long game (endless capture fights): wind down so it always ends. if (view.moveCount > 2 * board.length) return pass; const scores = new Map(places.map((p) => [p, score(p)])); - const top = places.length ? best(places, (p) => scores.get(p)!, random) : null; + // Small = a shape point; capturing or saving three stones or more (≥ 24) is a must-play move. + const top = places.length ? humanBest(places, (p) => scores.get(p)!, random, level, { small: 1.5, critical: 24 }) : null; // Nothing useful left (only settled areas, dame on the edge or self-atari): pass so the game can end. return top && scores.get(top)! > 1 ? top : pass; }; diff --git a/packages/games/src/bots/bots.test.ts b/packages/games/src/bots/bots.test.ts index d0fdfe4..834b6c9 100644 --- a/packages/games/src/bots/bots.test.ts +++ b/packages/games/src/bots/bots.test.ts @@ -48,3 +48,15 @@ test('decideBotAction returns null when the bot has nothing to do', () => { expect(decideBotAction(def, s, other, { now: 0 })).toBeNull(); expect(decideBotAction(def, s, waiting, { now: 0 })).not.toBeNull(); }); + +describe('levels (docs/09 §9.1)', () => { + const BOARD = ['omok', 'chess', 'janggi', 'othello', 'baduk']; + test.each(BOARD)('%s: easy and hard computers still finish a game against each other', (id) => { + const def = GAMES[id]!; + for (const level of ['easy', 'hard'] as const) { + const r = botPlayout(def, { players: seats(2, 0), seed: seedN(7), isBot, maxSteps: 30_000, level }); + expect(r.finished).toBe(true); + expect(r.botTimeouts).toBe(0); + } + }); +}); diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index a5a5723..b18ab88 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -3,7 +3,8 @@ * it hands the strategy the bot's own view and its legal actions — nothing else — so a bot can't peek at hidden * information (other hands, deck order). */ -import type { AnyGameDefinition, PlayerId } from '@bg/engine'; +import { secureRandom, type AnyGameDefinition, type PlayerId } from '@bg/engine'; +import type { BotLevel } from './persona'; import type { BotStrategy, LiveBotStrategy } from './types'; import { pick, playable, randomPolicy } from './policy'; import { omokBot } from '../omok/bot'; @@ -31,7 +32,7 @@ import { ninetyNineBot } from '../ninety-nine/bot'; import { mafiaBot } from '../mafia/bot'; export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types'; -export { botPace, botPersona, hash01, type BotPersona } from './persona'; +export { BOT_LEVEL_ODDS, botDraw, botPace, botPersona, hash01, levelOf, type BotLevel, type BotPersona } from './persona'; /** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */ export const BOT_STRATEGIES: Record = { @@ -73,18 +74,18 @@ export function decideBotAction( def: AnyGameDefinition, state: unknown, me: PlayerId, - ctx: { now: number; random?: () => number }, + ctx: { now: number; random?: () => number; level?: BotLevel }, ): unknown | null { let legal = botCandidates(def, state, me); if (!legal.length) return null; - const random = ctx.random ?? Math.random; + const random = ctx.random ?? secureRandom; const valid = (a: unknown) => def.validate(state, me, a, { now: ctx.now }).ok; const view = def.view(state, me); const strategy = BOT_STRATEGIES[def.id] ?? randomPolicy; for (let attempt = 0; attempt < 3 && legal.length; attempt++) { let action: unknown; try { - action = strategy({ me, view: structuredClone(view), legal, random }); + action = strategy({ me, view: structuredClone(view), legal, random, level: ctx.level }); } catch { break; } diff --git a/packages/games/src/bots/level.test.ts b/packages/games/src/bots/level.test.ts new file mode 100644 index 0000000..9174e88 --- /dev/null +++ b/packages/games/src/bots/level.test.ts @@ -0,0 +1,93 @@ +/** Computer levels and human-like choices (docs/09-game-engine.md §9.1). */ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, secureRandom, seedN } from '@bg/engine'; +import { BOT_PLAY, humanBest } from './policy'; +import { BOT_LEVEL_ODDS, botDraw, botPersona, levelOf, type BotLevel } from './persona'; + +const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; +const fakeUlid = (r: () => number) => '01J' + Array.from({ length: 23 }, () => CROCKFORD[Math.floor(r() * 32)]).join(''); + +describe('secureRandom', () => { + test('uniform floats in [0, 1)', () => { + const n = 100_000; + const bins = new Array(10).fill(0); + for (let i = 0; i < n; i++) { + const x = secureRandom(); + expect(x >= 0 && x < 1).toBe(true); + bins[Math.floor(x * 10)]++; + } + for (const b of bins) expect(Math.abs(b - n / 10)).toBeLessThan(n / 10 * 0.05); + }); +}); + +describe('bot level', () => { + test('the roll comes from the id’s random characters and keeps the level for the same id', () => { + const id = `bot:2:${fakeUlid(secureRandom)}`; + expect(botPersona(id)).toEqual(botPersona(id)); + expect(botDraw('bot:1:01J0000000000000000000000Z')).toBe(0); + expect(botDraw('bot:1:01J0000000ZZZZZZ0000000000')).toBeCloseTo(1, 6); + }); + + test('levels come out at the documented odds; 똑똑한 편 is half, every 쉬움 허술, every 어려움 똑똑', () => { + const rng = SeededRng.fromSeed(seedN(3)); + const n = 40_000; + const count: Record = { easy: 0, normal: 0, hard: 0 }; + let smart = 0; + for (let i = 0; i < n; i++) { + const p = botPersona(`bot:${(i % 7) + 1}:${fakeUlid(() => rng.next())}`); + count[p.level]++; + if (p.smart) smart++; + if (p.level === 'easy') expect(p.smart).toBe(false); + if (p.level === 'hard') expect(p.smart).toBe(true); + } + for (const level of ['easy', 'normal', 'hard'] as const) expect(Math.abs(count[level] / n - BOT_LEVEL_ODDS[level])).toBeLessThan(0.015); + expect(Math.abs(smart / n - 0.5)).toBeLessThan(0.015); + expect(levelOf(0.3499)).toBe('easy'); + expect(levelOf(0.35)).toBe('normal'); + expect(levelOf(0.75)).toBe('hard'); + }); +}); + +describe('humanBest', () => { + // Scores: 100 best, 95 close, 60 a slip away for easy, 0 a blunder. + const moves = ['best', 'close', 'meh', 'blunder']; + const value: Record = { best: 100, close: 95, meh: 70, blunder: 0 }; + const scale = { small: 10, critical: 1000 }; + const share = (level: BotLevel | undefined, xs = moves, v = value) => { + const rng = SeededRng.fromSeed(seedN(11)); + const n = 20_000; + const out: Record = {}; + for (let i = 0; i < n; i++) { + const m = humanBest(xs, (a) => v[a]!, () => rng.next(), level, scale); + out[m] = (out[m] ?? 0) + 1; + } + for (const k in out) out[k]! /= n; + return out; + }; + + test('without a level it is the plain best move', () => { + expect(share(undefined)).toEqual({ best: 1 }); + }); + + test('stronger levels play the best move more often and never pick a move far worse than a lapse allows', () => { + const easy = share('easy'); + const normal = share('normal'); + const hard = share('hard'); + expect(easy.best!).toBeLessThan(normal.best!); + expect(normal.best!).toBeLessThan(hard.best!); + expect(hard.best!).toBeGreaterThan(0.9); + // "meh" (30 worse = 3 × small) is past every slip window (≤ 2 × small): only a lapse (8 × small) plays it. + expect(hard.meh ?? 0).toBeLessThan(0.01); + // 100 worse is beyond every window: never played. + for (const s of [easy, normal, hard]) expect(s.blunder ?? 0).toBe(0); + // Close alternative: roughly slip share of the time. + expect(Math.abs((normal.close ?? 0) - (BOT_PLAY.normal.slip + BOT_PLAY.normal.lapse / 2))).toBeLessThan(0.03); + }); + + test('a must-play move (≥ critical) is missed only at the documented rate', () => { + const v = { ...value, best: 5000 }; + expect(share('hard', moves, v).best).toBe(1); + expect(Math.abs(1 - share('normal', moves, v).best! - BOT_PLAY.normal.miss)).toBeLessThan(0.01); + expect(Math.abs(1 - share('easy', moves, v).best! - BOT_PLAY.easy.miss)).toBeLessThan(0.015); + }); +}); diff --git a/packages/games/src/bots/persona.ts b/packages/games/src/bots/persona.ts index 459b66e..9f9e23e 100644 --- a/packages/games/src/bots/persona.ts +++ b/packages/games/src/bots/persona.ts @@ -18,8 +18,39 @@ export function botPace(bot: string): number { return 0.7 + ((h >>> 0) / 2 ** 32) * 0.8; } +/** How well a computer plays (docs/09-game-engine.md §9.1). */ +export type BotLevel = 'easy' | 'normal' | 'hard'; + +/** Share of computers at each level: 쉬움 35%, 보통 40%, 어려움 25%. */ +export const BOT_LEVEL_ODDS: Readonly> = { easy: 0.35, normal: 0.4, hard: 0.25 }; + +const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; + +/** + * The computer's own die roll in [0, 1), read straight from the random part of its id: the server makes bot ids as + * `bot::` with OS secure randomness (`secureRandom`), so the first 6 random characters are 30 uniform bits. + * Other ids (tests, hand-made) fall back to a hash. Fixed for the id, so the computer keeps its level after a restart. + */ +export function botDraw(bot: string): number { + const u = bot.split(':')[2] ?? ''; + if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(u)) return hash01(bot, 'level'); + let v = 0; + for (const ch of u.slice(10, 16)) v = v * 32 + CROCKFORD.indexOf(ch); + return v / 32 ** 6; +} + +export function levelOf(draw: number): BotLevel { + if (draw < BOT_LEVEL_ODDS.easy) return 'easy'; + return draw < BOT_LEVEL_ODDS.easy + BOT_LEVEL_ODDS.normal ? 'normal' : 'hard'; +} + export interface BotPersona { - /** 똑똑한 편(근거를 보고 추리) / 허술한 편(느낌과 분위기를 따름). About half of the computers each. */ + /** 쉬움 / 보통 / 어려움: how often it slips in board games (`humanBest`). */ + level: BotLevel; + /** + * 똑똑한 편(근거를 보고 추리, 존댓말) / 허술한 편(느낌과 분위기를 따름, 반말): half of the computers each, by the + * same roll as the level — every 쉬움 is 허술, every 어려움 똑똑, 보통 split in two. + */ smart: boolean; /** Reaction speed multiplier (`botPace`): 0.7 quick … 1.5 slow. */ pace: number; @@ -28,5 +59,6 @@ export interface BotPersona { } export function botPersona(bot: string): BotPersona { - return { smart: hash01(bot, 'smart') < 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 }; + const draw = botDraw(bot); + return { level: levelOf(draw), smart: draw >= 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 }; } diff --git a/packages/games/src/bots/playout.ts b/packages/games/src/bots/playout.ts index d2d7fc8..464c65f 100644 --- a/packages/games/src/bots/playout.ts +++ b/packages/games/src/bots/playout.ts @@ -1,6 +1,7 @@ /** Test helper: bots play a whole game the way the room would run it, next to "humans" who only time out. */ import { SeededRng, type AnyGameDefinition, type PlayerId, type RngState } from '@bg/engine'; import { botCandidates, decideBotAction } from './index'; +import type { BotLevel } from './persona'; export interface BotPlayoutReport { steps: number; @@ -24,7 +25,7 @@ const waitingOf = (def: AnyGameDefinition, s: unknown): PlayerId[] => [...new Se */ export function botPlayout( def: AnyGameDefinition, - opts: { players: PlayerId[]; options?: unknown; seed: RngState; maxSteps?: number; isBot: (p: PlayerId) => boolean }, + opts: { players: PlayerId[]; options?: unknown; seed: RngState; maxSteps?: number; isBot: (p: PlayerId) => boolean; level?: BotLevel }, ): BotPlayoutReport { const rng = SeededRng.fromSeed(opts.seed); const chooser = SeededRng.fromSeed([opts.seed[1], opts.seed[0], opts.seed[3], opts.seed[2] ^ 0x5bd1e995]); @@ -48,7 +49,7 @@ export function botPlayout( const bot = waiting.find((p) => opts.isBot(p) && botCandidates(def, state, p).length > 0); if (bot) { const t0 = performance.now(); - const action = decideBotAction(def, state, bot, { now, random }); + const action = decideBotAction(def, state, bot, { now, random, level: opts.level }); const ms = performance.now() - t0; if (action === null) throw new Error(`${def.id}: bot ${bot} found no valid action`); rep.botMoves++; diff --git a/packages/games/src/bots/policy.ts b/packages/games/src/bots/policy.ts index f61c152..cea23f9 100644 --- a/packages/games/src/bots/policy.ts +++ b/packages/games/src/bots/policy.ts @@ -1,5 +1,6 @@ /** Default "random but sensible" bot policy and small helpers shared by per-game strategies. */ import type { BotInput } from './types'; +import type { BotLevel } from './persona'; type Act = { type?: string; [k: string]: unknown }; @@ -30,6 +31,60 @@ export function best(xs: readonly A[], score: (a: A) => number, random: () => return pick(top.length ? top : xs, random); } +/** How each level slips (docs/09-game-engine.md §9.1). */ +export interface BotPlay { + /** Chance per move of a small inaccuracy: a move almost as good (within `window` × the game's `small`). */ + slip: number; + window: number; + /** Chance per move of a real blunder (사고): one of the next best few, up to `LAPSE_WINDOW` × `small` worse. */ + lapse: number; + /** Chance of overlooking a must-play move (a win, mate, blocking a five, a free corner). */ + miss: number; +} + +export const BOT_PLAY: Readonly> = { + easy: { slip: 0.35, window: 2, lapse: 0.06, miss: 0.12 }, + normal: { slip: 0.2, window: 1, lapse: 0.02, miss: 0.03 }, + hard: { slip: 0.08, window: 0.5, lapse: 0.005, miss: 0 }, +}; + +export const LAPSE_WINDOW = 8; + +/** + * Like `best`, but played by a person of `level`: usually the best move, now and then one that looked almost as good, + * rarely a real mistake, and once in a while it doesn't see the winning / saving move. `small` is what a small + * inaccuracy is worth in the game's score units; scores ≥ `critical` mark must-play moves. Without a level (tests, + * `best` callers) it is exactly `best`. + */ +export function humanBest( + xs: readonly A[], + score: (a: A) => number, + random: () => number, + level: BotLevel | undefined, + scale: { small: number; critical: number }, +): A { + if (!level || xs.length < 2) return best(xs, score, random); + const scored = xs.map((a) => ({ a, s: score(a) })); + const topScore = Math.max(...scored.map((x) => x.s)); + const top = pick(scored.filter((x) => x.s === topScore), random).a; + const rest = scored.filter((x) => x.a !== top).sort((x, y) => y.s - x.s); + const play = BOT_PLAY[level]; + const r = random(); + if (topScore >= scale.critical) { + if (r >= play.miss) return top; + // Didn't see it: plays one of the next moves that looked fine. + return pick(rest.slice(0, 3), random).a; + } + if (r < play.lapse) { + const near = rest.filter((x) => x.s >= topScore - LAPSE_WINDOW * scale.small).slice(0, 8); + if (near.length) return pick(near, random).a; + } else if (r < play.lapse + play.slip) { + const near = rest.filter((x) => x.s >= topScore - play.window * scale.small).slice(0, 5); + if (near.length) return pick(near, random).a; + } + return top; +} + /** * Answers to the human's requests: undo is accepted (it's practice), draw offers are declined. * Returns null when no request is pending. diff --git a/packages/games/src/bots/types.ts b/packages/games/src/bots/types.ts index 386e8a1..5aed748 100644 --- a/packages/games/src/bots/types.ts +++ b/packages/games/src/bots/types.ts @@ -13,6 +13,8 @@ export interface BotInput { legal: A[]; /** Uniform [0, 1). */ random: () => number; + /** The computer's level (`humanBest`); absent in tests that want the plain best move. */ + level?: import('./persona').BotLevel; } /** diff --git a/packages/games/src/chess/bot.ts b/packages/games/src/chess/bot.ts index aee6330..12cacbf 100644 --- a/packages/games/src/chess/bot.ts +++ b/packages/games/src/chess/bot.ts @@ -4,7 +4,7 @@ * (and under-promotes only when queening would stalemate). */ import type { BotStrategy } from '../bots/types'; -import { answerRequests, best, pick, playable, typeOf } from '../bots/policy'; +import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy'; import type { ChessView } from './index'; import { moveInfo, type PieceType } from './movegen'; import { PIECE_VALUE, insufficientMaterial, load, pieces } from './rules'; @@ -15,7 +15,7 @@ const NEAR_CENTER = new Set(['c3', 'd3', 'e3', 'f3', 'c4', 'f4', 'c5', 'f5', 'c6 /** Piece type of a raw generator move field (1..6). */ const TYPE = (n: number) => ' pnbrqk'[n] as PieceType; -export const chessBot: BotStrategy = ({ view, legal, random }) => { +export const chessBot: BotStrategy = ({ view, legal, random, level }) => { const req = answerRequests(legal); if (req) return req; const moves = legal.filter((a) => typeOf(a) === 'move') as Move[]; @@ -75,5 +75,6 @@ export const chessBot: BotStrategy = ({ view, legal, random }) => { c.unmake(); } }; - return best(moves, score, random); + // 100 = a pawn; mate in one (1e6) is a must-play move. + return humanBest(moves, score, random, level, { small: 40, critical: 1e5 }); }; diff --git a/packages/games/src/janggi/bot.ts b/packages/games/src/janggi/bot.ts index 9dcd7fe..a99cd1e 100644 --- a/packages/games/src/janggi/bot.ts +++ b/packages/games/src/janggi/bot.ts @@ -3,7 +3,7 @@ * prise > 장군 > activity. Knows 빅장 (judged by score), the 4th-repetition rule and when a 한수쉼 ends the game. */ import type { BotStrategy } from '../bots/types'; -import { answerRequests, best, pick, playable, typeOf } from '../bots/policy'; +import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy'; import type { JanggiView } from './index'; import { HAN_BONUS, @@ -77,7 +77,7 @@ function threat(b: Board, me: Side): number { return worst; } -export const janggiBot: BotStrategy = ({ view, legal, random }) => { +export const janggiBot: BotStrategy = ({ view, legal, random, level }) => { const req = answerRequests(legal); if (req) return req; const moves = legal.filter((a) => typeOf(a) === 'move') as Move[]; @@ -134,5 +134,6 @@ export const janggiBot: BotStrategy = ({ view, legal, random }) => { return base; }; const options: (Move | Pass)[] = pass ? [...moves, pass] : moves; - return best(options, (a) => (typeOf(a) === 'pass' ? passScore() : scoreMove(a as Move)), random); + // 100 = one point of material; 외통 (1e7) and a winning judgement (1e5) are must-play moves. + return humanBest(options, (a) => (typeOf(a) === 'pass' ? passScore() : scoreMove(a as Move)), random, level, { small: 40, critical: 1e5 }); }; diff --git a/packages/games/src/mafia/bot.test.ts b/packages/games/src/mafia/bot.test.ts index b8b45eb..cebd18c 100644 --- a/packages/games/src/mafia/bot.test.ts +++ b/packages/games/src/mafia/bot.test.ts @@ -88,7 +88,7 @@ describe('whole games', () => { players: seats(7, 0), seed: seedN(s), isBot, - personaOf: (p, st): BotPersona => ({ smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }), + personaOf: (p, st): BotPersona => ({ level: 'normal', smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }), }); if ((r.state as MafiaState).winner === 'town') town++; } @@ -128,8 +128,8 @@ describe('timing and answers', () => { const { st, players } = toPhase('vote'); const names = Object.fromEntries(players.map((p, i) => [p, i ? `컴퓨터 ${i + 1}` : '철수'])); const bot = players[2]!; - const quick = firstAction(st, bot, { smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!; - const slow = firstAction(st, bot, { smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!; + const quick = firstAction(st, bot, { level: 'hard', smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!; + const slow = firstAction(st, bot, { level: 'hard', smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!; expect(quick.at).toBeLessThan(slow.at); expect(slow.at).toBeLessThan(st.options.voteSeconds * 1000); }); @@ -142,7 +142,7 @@ describe('timing and answers', () => { const memory: Record = {}; let answer: { text: string; at: number } | null = null; for (let t = now + 1000; t < now + 20_000 && !answer; ) { - const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { smart: true, pace: 1, chatty: 0.8 }, names, memory }); + const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { level: 'hard', smart: true, pace: 1, chatty: 0.8 }, names, memory }); const a = d.action as { type: string; text?: string } | null; if (a?.type === 'chat' && memory.done && Object.keys(memory.done as object).some((k) => k.includes(':r:'))) answer = { text: a.text!, at: t - now - 1000 }; t += Math.max(50, d.next); diff --git a/packages/games/src/omok/bot.ts b/packages/games/src/omok/bot.ts index 118bbee..93cb15f 100644 --- a/packages/games/src/omok/bot.ts +++ b/packages/games/src/omok/bot.ts @@ -1,6 +1,6 @@ /** 오목 computer player: win > block a five > open four > block open three > build lines near the stones. */ import type { BotStrategy } from '../bots/types'; -import { answerRequests, best, pick, playable, typeOf } from '../bots/policy'; +import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy'; import type { OmokView } from './index'; type Place = { type: 'place'; x: number; y: number }; @@ -40,7 +40,7 @@ function lineValue(board: number[], size: number, x: number, y: number, color: n return total; } -export const omokBot: BotStrategy = ({ view, legal, random }) => { +export const omokBot: BotStrategy = ({ view, legal, random, level }) => { const req = answerRequests(legal); if (req) return req; const places = legal.filter((a) => typeOf(a) === 'place') as Place[]; @@ -62,7 +62,8 @@ export const omokBot: BotStrategy = ({ view, legal, random }) => { // "exact five"; assume the default "five or more"). const overline = (c: number) => view.ruleSet === 'free' || (view.ruleSet === 'renju' && c === 2); const center = (size - 1) / 2; - return best( + // A person now and then plays a slightly different shape or misses a threat (≥ 50,000: win or block a five). + return humanBest( close.length ? close : places, (p) => lineValue(board, size, p.x, p.y, me, overline(me)) * 1.1 + @@ -70,5 +71,7 @@ export const omokBot: BotStrategy = ({ view, legal, random }) => { (Math.abs(p.x - center) + Math.abs(p.y - center)) * 0.1 + random() * 0.5, random, + level, + { small: 150, critical: 50_000 }, ); }; diff --git a/packages/games/src/othello/bot.ts b/packages/games/src/othello/bot.ts index 97f4347..207695f 100644 --- a/packages/games/src/othello/bot.ts +++ b/packages/games/src/othello/bot.ts @@ -3,13 +3,13 @@ * corner, keep the opponent's choices few; flip counts only matter near the end. */ import type { BotStrategy } from '../bots/types'; -import { answerRequests, best, pick, playable, typeOf } from '../bots/policy'; +import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy'; import type { OthelloView } from './index'; import { CORNERS, legalMoves, type Cell, type Disc } from './rules'; type Place = { type: 'place'; x: number; y: number }; -export const othelloBot: BotStrategy = ({ view, legal, random }) => { +export const othelloBot: BotStrategy = ({ view, legal, random, level }) => { const req = answerRequests(legal); if (req) return req; const places = legal.filter((a) => typeOf(a) === 'place') as Place[]; @@ -44,5 +44,6 @@ export const othelloBot: BotStrategy = ({ view, legal, random }) => else if (edgeX || edgeY) v += 10; return v; }; - return best(places, score, random); + // 1.5 = one more reply for the opponent; a free corner (+100) is a must-play move. + return humanBest(places, score, random, level, { small: 3, critical: 90 }); };