컴퓨터 난이도 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:
@@ -7,6 +7,7 @@
|
||||
".": "./src/index.ts",
|
||||
"./rummikub/rules": "./src/rummikub/rules.ts",
|
||||
"./marble/board": "./src/marble/board.ts",
|
||||
"./bots/luck": "./src/bots/luck.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -51,9 +51,9 @@ test('decideBotAction returns null when the bot has nothing to do', () => {
|
||||
|
||||
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) => {
|
||||
test.each(BOARD)('%s: the weakest and strongest computers still finish a game against each other', (id) => {
|
||||
const def = GAMES[id]!;
|
||||
for (const level of ['easy', 'hard'] as const) {
|
||||
for (const level of [1, 60]) {
|
||||
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);
|
||||
|
||||
@@ -32,7 +32,8 @@ import { ninetyNineBot } from '../ninety-nine/bot';
|
||||
import { mafiaBot } from '../mafia/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { BOT_LEVEL_ODDS, botDraw, botPace, botPersona, hash01, levelOf, type BotLevel, type BotPersona } from './persona';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
export { botPlay } from './policy';
|
||||
|
||||
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
|
||||
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/** 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';
|
||||
import { BOT_PLAY_ANCHORS, botPlay, humanBest } from './policy';
|
||||
import { botDraw, botPersona, idLevel, type BotLevel } from './persona';
|
||||
|
||||
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||
const fakeUlid = (r: () => number) => '01J' + Array.from({ length: 23 }, () => CROCKFORD[Math.floor(r() * 32)]).join('');
|
||||
@@ -21,30 +21,47 @@ describe('secureRandom', () => {
|
||||
});
|
||||
|
||||
describe('bot level', () => {
|
||||
test('the roll comes from the id’s random characters and keeps the level for the same id', () => {
|
||||
test('a computer without a saved level gets one from its id’s random characters, the same every time', () => {
|
||||
const id = `bot:2:${fakeUlid(secureRandom)}`;
|
||||
expect(botPersona(id)).toEqual(botPersona(id));
|
||||
expect(idLevel(id)).toBe(idLevel(id));
|
||||
expect(botDraw('bot:1:01J0000000000000000000000Z')).toBe(0);
|
||||
expect(botDraw('bot:1:01J0000000ZZZZZZ0000000000')).toBeCloseTo(1, 6);
|
||||
expect(idLevel('bot:1:01J0000000000000000000000Z')).toBe(1);
|
||||
expect(idLevel('bot:1:01J0000000ZZZZZZ0000000000')).toBe(60);
|
||||
});
|
||||
|
||||
test('levels come out at the documented odds; 똑똑한 편 is half, every 쉬움 허술, every 어려움 똑똑', () => {
|
||||
test('id levels are uniform over 1~60; 똑똑한 편 (start above 30) is half', () => {
|
||||
const rng = SeededRng.fromSeed(seedN(3));
|
||||
const n = 40_000;
|
||||
const count: Record<BotLevel, number> = { easy: 0, normal: 0, hard: 0 };
|
||||
const n = 60_000;
|
||||
const bands = [0, 0, 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);
|
||||
const id = `bot:${(i % 7) + 1}:${fakeUlid(() => rng.next())}`;
|
||||
const level = idLevel(id);
|
||||
expect(level >= 1 && level <= 60).toBe(true);
|
||||
bands[Math.floor((level - 1) / 20)]!++;
|
||||
if (botPersona(id).smart) smart++;
|
||||
}
|
||||
for (const level of ['easy', 'normal', 'hard'] as const) expect(Math.abs(count[level] / n - BOT_LEVEL_ODDS[level])).toBeLessThan(0.015);
|
||||
for (const b of bands) expect(Math.abs(b / n - 1 / 3)).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');
|
||||
expect(botPersona('bot:1:x', 30).smart).toBe(false);
|
||||
expect(botPersona('bot:1:x', 31).smart).toBe(true);
|
||||
});
|
||||
|
||||
test('play settings move steadily from level 1 to 60 and hit the anchors', () => {
|
||||
for (const [level, play] of BOT_PLAY_ANCHORS) {
|
||||
const p = botPlay(level);
|
||||
for (const k of ['slip', 'window', 'lapse', 'miss'] as const) expect(p[k]).toBeCloseTo(play[k], 9);
|
||||
}
|
||||
for (let l = 2; l <= 60; l++) {
|
||||
const a = botPlay(l - 1);
|
||||
const b = botPlay(l);
|
||||
expect(b.slip).toBeLessThanOrEqual(a.slip);
|
||||
expect(b.lapse).toBeLessThanOrEqual(a.lapse);
|
||||
expect(b.miss).toBeLessThanOrEqual(a.miss);
|
||||
}
|
||||
expect(botPlay(0)).toEqual(botPlay(1));
|
||||
expect(botPlay(99)).toEqual(botPlay(60));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,24 +87,29 @@ describe('humanBest', () => {
|
||||
});
|
||||
|
||||
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');
|
||||
const weakest = share(1);
|
||||
const easy = share(10);
|
||||
const normal = share(30);
|
||||
const hard = share(50);
|
||||
const strongest = share(60);
|
||||
expect(weakest.best!).toBeLessThan(easy.best!);
|
||||
expect(hard.best!).toBeLessThan(strongest.best!);
|
||||
expect(strongest.best!).toBeGreaterThan(0.96);
|
||||
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);
|
||||
for (const s of [weakest, easy, normal, hard, strongest]) 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);
|
||||
expect(Math.abs((normal.close ?? 0) - (botPlay(30).slip + botPlay(30).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);
|
||||
expect(share(50, moves, v).best).toBe(1);
|
||||
expect(share(60, moves, v).best).toBe(1);
|
||||
for (const level of [1, 10, 30, 41]) expect(Math.abs(1 - share(level, moves, v).best! - botPlay(level).miss)).toBeLessThan(0.015);
|
||||
});
|
||||
});
|
||||
|
||||
81
packages/games/src/bots/luck.test.ts
Normal file
81
packages/games/src/bots/luck.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
/** Computers' luck: choosing the shuffle (docs/04 §5.1, docs/09 §9.1). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN, type ChaChaSeed } from '@bg/engine';
|
||||
import { GAMES } from '../index';
|
||||
import { BOT_STRATEGIES } from './index';
|
||||
import { chooseLuckySeed, luckApplies, playOutScores, shufflesFor, type LuckJob } from './luck';
|
||||
|
||||
const words = (r: SeededRng) => Array.from({ length: 8 }, () => Math.floor(r.next() * 2 ** 32) >>> 0) as ChaChaSeed;
|
||||
|
||||
function setup(n: number) {
|
||||
const r = SeededRng.fromSeed(seedN(n));
|
||||
return { makeSeed: () => words(r), random: () => r.next() };
|
||||
}
|
||||
|
||||
const job = (gameId: string, luck: Record<string, number>, players = ['human', 'bot:1:a']): LuckJob => ({
|
||||
gameId,
|
||||
players,
|
||||
options: GAMES[gameId]!.defaultOptions,
|
||||
now: 1_700_000_000_000,
|
||||
gameNo: 1,
|
||||
luck,
|
||||
levels: { 'bot:1:a': 30 },
|
||||
budgetMs: 60_000,
|
||||
});
|
||||
|
||||
describe('luck', () => {
|
||||
test('how many shuffles: none near 0, up to 5 at ±1, the strongest luck at the table counts', () => {
|
||||
expect(shufflesFor([])).toBe(1);
|
||||
expect(shufflesFor([0.1, -0.12])).toBe(1);
|
||||
expect(shufflesFor([0.5])).toBe(3);
|
||||
expect(shufflesFor([-1])).toBe(5);
|
||||
expect(shufflesFor([0.2, -0.9])).toBe(5);
|
||||
});
|
||||
|
||||
test('luck is for games with cards, tiles, dice or hidden roles — not for board games', () => {
|
||||
for (const id of ['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'mafia', 'dobble']) expect(luckApplies(id)).toBe(false);
|
||||
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor'].includes(g))) {
|
||||
expect(luckApplies(id)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('tries one shuffle without luck or in a board game, more with luck, and keeps one of them', () => {
|
||||
const { makeSeed, random } = setup(1);
|
||||
expect(chooseLuckySeed(GAMES['one-card']!, job('one-card', { 'bot:1:a': 0 }), makeSeed, random).tried).toBe(1);
|
||||
expect(chooseLuckySeed(GAMES.omok!, job('omok', { 'bot:1:a': 1 }), makeSeed, random).tried).toBe(1);
|
||||
const made: string[] = [];
|
||||
const tracked = () => {
|
||||
const s = makeSeed();
|
||||
made.push(s.join(','));
|
||||
return s;
|
||||
};
|
||||
const r = chooseLuckySeed(GAMES['one-card']!, job('one-card', { 'bot:1:a': -1 }), tracked, random);
|
||||
expect(r.tried).toBe(5);
|
||||
expect(made).toHaveLength(5);
|
||||
expect(made).toContain(r.seed.join(','));
|
||||
});
|
||||
|
||||
test('a played-out game gives every player a place score in [0, 1]', () => {
|
||||
const { makeSeed, random } = setup(2);
|
||||
const s = playOutScores(GAMES['one-card']!, { ...job('one-card', {}, ['a', 'b', 'c']), seed: makeSeed(), random });
|
||||
expect(s).not.toBeNull();
|
||||
expect(Object.keys(s!).sort()).toEqual(['a', 'b', 'c']);
|
||||
for (const v of Object.values(s!)) expect(v >= 0 && v <= 1).toBe(true);
|
||||
});
|
||||
|
||||
test('lucky computers do better than unlucky ones (원카드, 1:1)', () => {
|
||||
const { makeSeed, random } = setup(3);
|
||||
const def = GAMES['one-card']!;
|
||||
const mean = (luck: number) => {
|
||||
let sum = 0;
|
||||
const n = 50;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const { seed } = chooseLuckySeed(def, job('one-card', { 'bot:1:a': luck }), makeSeed, random);
|
||||
// The real game: the same deal, but every choice made afresh.
|
||||
sum += playOutScores(def, { ...job('one-card', {}), seed, random })?.['bot:1:a'] ?? 0.5;
|
||||
}
|
||||
return sum / n;
|
||||
};
|
||||
expect(mean(1) - mean(-1)).toBeGreaterThan(0.15);
|
||||
});
|
||||
});
|
||||
123
packages/games/src/bots/luck.ts
Normal file
123
packages/games/src/bots/luck.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Computers' luck (docs/04-stability-security.md §5.1, docs/09-game-engine.md §9.1). Before a game with computers the
|
||||
* server may try a few shuffles (seeds) instead of one: each is played out once to the end by computers in every
|
||||
* seat, and the one that suits the computers' luck best is kept — a lucky computer tends to get the deal it did well
|
||||
* with, an unlucky one the deal it did badly with. The kept seed's hash is published before the first move as always,
|
||||
* so nothing changes during the game. Board games without dice or cards are left alone.
|
||||
*/
|
||||
import { SeededRng, type AnyGameDefinition, type ChaChaSeed, type PlayerId } from '@bg/engine';
|
||||
import { BOT_STRATEGIES, decideBotAction } from './index';
|
||||
import type { BotLevel } from './persona';
|
||||
|
||||
/** Games where everything is in view from the start: a shuffle only decides who goes first, so luck stays out. */
|
||||
const NO_LUCK = new Set(['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor']);
|
||||
|
||||
export const luckApplies = (gameId: string): boolean => gameId in BOT_STRATEGIES && !NO_LUCK.has(gameId);
|
||||
|
||||
/** Most shuffles tried for the luckiest (or unluckiest) computer, luck ±1. */
|
||||
export const MAX_SHUFFLES = 5;
|
||||
|
||||
/** Shuffles to try: 1 (no choice) for luck near 0, up to `MAX_SHUFFLES` for ±1; the strongest luck at the table counts. */
|
||||
export function shufflesFor(lucks: readonly number[]): number {
|
||||
const m = Math.max(0, ...lucks.map((l) => Math.min(1, Math.abs(l))));
|
||||
return 1 + Math.round(m * (MAX_SHUFFLES - 1));
|
||||
}
|
||||
|
||||
/** Simulated players stand in for people at this level. */
|
||||
const PERSON_LEVEL = 30;
|
||||
|
||||
/**
|
||||
* Plays the game from `seed` to the end with a computer in every seat (`levels[p]`, people as level 30) and returns
|
||||
* each player's place as a score in [0, 1] (1 = first, 0 = last, ties share), or null if it didn't finish.
|
||||
*/
|
||||
export function playOutScores(
|
||||
def: AnyGameDefinition,
|
||||
input: { players: PlayerId[]; options: unknown; seed: ChaChaSeed; now: number; gameNo: number; levels: Record<PlayerId, BotLevel>; random: () => number; maxSteps?: number },
|
||||
): Record<PlayerId, number> | null {
|
||||
const { players, random } = input;
|
||||
const rng = SeededRng.fromSeed(input.seed);
|
||||
let now = input.now;
|
||||
let state = def.setup({ players, options: input.options, rng, now, gameNo: input.gameNo });
|
||||
const maxSteps = input.maxSteps ?? 20_000;
|
||||
for (let step = 0; step < maxSteps; step++) {
|
||||
const result = def.result(state);
|
||||
if (result) {
|
||||
const out: Record<PlayerId, number> = {};
|
||||
let at = 0;
|
||||
for (const group of result.ranking) {
|
||||
const place = at + (group.length - 1) / 2;
|
||||
for (const p of group) out[p] = players.length > 1 ? 1 - place / (players.length - 1) : 1;
|
||||
at += group.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
now += 500;
|
||||
const waiting = [...new Set([...def.activePlayers(state), ...(def.timeoutPlayers?.(state) ?? [])])];
|
||||
let acted = false;
|
||||
for (const p of waiting) {
|
||||
const action = decideBotAction(def, state, p, { now, random, level: input.levels[p] ?? PERSON_LEVEL });
|
||||
if (action === null) continue;
|
||||
state = def.apply(state, p, action, { rng, now }).state;
|
||||
acted = true;
|
||||
break;
|
||||
}
|
||||
if (acted) continue;
|
||||
// Nobody can move: let the clock run out like the room timer would.
|
||||
const timed = def.timeoutPlayers ? def.timeoutPlayers(state) : def.activePlayers(state);
|
||||
const who = timed[0] ?? waiting[0];
|
||||
if (!who) return null;
|
||||
now = Math.max(now, def.deadline?.(state) ?? now);
|
||||
state = def.apply(state, who, def.onTimeout(state, who), { rng, now }).state;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface LuckJob {
|
||||
gameId: string;
|
||||
players: PlayerId[];
|
||||
options: unknown;
|
||||
now: number;
|
||||
gameNo: number;
|
||||
/** Each computer's luck in [-1, 1]; people are not listed. */
|
||||
luck: Record<PlayerId, number>;
|
||||
levels: Record<PlayerId, BotLevel>;
|
||||
/** Stop trying more shuffles after this long (the first one is always played out). */
|
||||
budgetMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the seed for a game: `shufflesFor(luck)` fresh seeds from `makeSeed`, each played out once; keeps the one with
|
||||
* the highest Σ luck × score over the computers. Returns the seed and how many were tried.
|
||||
*/
|
||||
export function chooseLuckySeed(
|
||||
def: AnyGameDefinition,
|
||||
job: LuckJob,
|
||||
makeSeed: () => ChaChaSeed,
|
||||
random: () => number,
|
||||
): { seed: ChaChaSeed; tried: number } {
|
||||
const want = luckApplies(def.id) ? shufflesFor(Object.values(job.luck)) : 1;
|
||||
let best = makeSeed();
|
||||
if (want <= 1) return { seed: best, tried: 1 };
|
||||
const t0 = performance.now();
|
||||
let bestValue = -Infinity;
|
||||
let tried = 0;
|
||||
for (let i = 0; i < want; i++) {
|
||||
if (i > 0 && performance.now() - t0 > job.budgetMs) break;
|
||||
const seed = i === 0 ? best : makeSeed();
|
||||
tried++;
|
||||
let scores: Record<PlayerId, number> | null = null;
|
||||
try {
|
||||
scores = playOutScores(def, { ...job, seed, random });
|
||||
} catch {
|
||||
scores = null;
|
||||
}
|
||||
if (!scores) continue;
|
||||
let value = 0;
|
||||
for (const [bot, luck] of Object.entries(job.luck)) value += luck * (scores[bot] ?? 0.5);
|
||||
if (value > bestValue) {
|
||||
bestValue = value;
|
||||
best = seed;
|
||||
}
|
||||
}
|
||||
return { seed: best, tried };
|
||||
}
|
||||
@@ -18,18 +18,18 @@ 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<Record<BotLevel, number>> = { easy: 0.35, normal: 0.4, hard: 0.25 };
|
||||
/**
|
||||
* How well a computer plays: level 1 (weakest) … 60 (strongest), docs/09-game-engine.md §9.1. 1~20 쉬움, 21~40 보통,
|
||||
* 41~60 어려움. The room keeps each computer's level (it drifts a little between games); see `botPlay`.
|
||||
*/
|
||||
export type BotLevel = number;
|
||||
|
||||
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:<n>:<ULID>` 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.
|
||||
* A fixed roll in [0, 1) for a bot id: the server makes bot ids as `bot:<n>:<ULID>` 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. Only used for computers saved before rooms kept a level per computer (and in tests).
|
||||
*/
|
||||
export function botDraw(bot: string): number {
|
||||
const u = bot.split(':')[2] ?? '';
|
||||
@@ -39,17 +39,13 @@ export function botDraw(bot: string): number {
|
||||
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';
|
||||
}
|
||||
/** Level 1~60 from the id alone, for computers without a saved level. */
|
||||
export const idLevel = (bot: string): BotLevel => 1 + Math.floor(botDraw(bot) * 60);
|
||||
|
||||
export interface BotPersona {
|
||||
/** 쉬움 / 보통 / 어려움: 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.
|
||||
* 똑똑한 편(근거를 보고 추리, 존댓말) / 허술한 편(느낌과 분위기를 따름, 반말): the computer's starting level is
|
||||
* above 30 (the upper half of 보통 and every 어려움) or not, so a random computer is either with even odds.
|
||||
*/
|
||||
smart: boolean;
|
||||
/** Reaction speed multiplier (`botPace`): 0.7 quick … 1.5 slow. */
|
||||
@@ -58,7 +54,7 @@ export interface BotPersona {
|
||||
chatty: number;
|
||||
}
|
||||
|
||||
export function botPersona(bot: string): BotPersona {
|
||||
const draw = botDraw(bot);
|
||||
return { level: levelOf(draw), smart: draw >= 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
|
||||
/** `base` = the level the computer started with (the room's), or one from the id. */
|
||||
export function botPersona(bot: string, base: BotLevel = idLevel(bot)): BotPersona {
|
||||
return { smart: base > 30, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export function best<A>(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). */
|
||||
/** How a 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;
|
||||
@@ -42,11 +42,28 @@ export interface BotPlay {
|
||||
miss: number;
|
||||
}
|
||||
|
||||
export const BOT_PLAY: Readonly<Record<BotLevel, BotPlay>> = {
|
||||
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 },
|
||||
};
|
||||
/**
|
||||
* Anchor levels; levels in between are interpolated. The middle of each band plays like the old three levels:
|
||||
* 10 = 쉬움, 30 = 보통, 50 = 어려움. Level 1 slips the most, level 60 almost never.
|
||||
*/
|
||||
export const BOT_PLAY_ANCHORS: readonly (readonly [number, BotPlay])[] = [
|
||||
[1, { slip: 0.45, window: 3, lapse: 0.1, miss: 0.2 }],
|
||||
[10, { slip: 0.35, window: 2, lapse: 0.06, miss: 0.12 }],
|
||||
[30, { slip: 0.2, window: 1, lapse: 0.02, miss: 0.03 }],
|
||||
[50, { slip: 0.08, window: 0.5, lapse: 0.005, miss: 0 }],
|
||||
[60, { slip: 0.03, window: 0.25, lapse: 0, miss: 0 }],
|
||||
];
|
||||
|
||||
export function botPlay(level: BotLevel): BotPlay {
|
||||
const L = Math.min(Math.max(level, 1), 60);
|
||||
let i = 0;
|
||||
while (i < BOT_PLAY_ANCHORS.length - 2 && L > BOT_PLAY_ANCHORS[i + 1]![0]) i++;
|
||||
const [l0, a] = BOT_PLAY_ANCHORS[i]!;
|
||||
const [l1, b] = BOT_PLAY_ANCHORS[i + 1]!;
|
||||
const t = (L - l0) / (l1 - l0);
|
||||
const mix = (k: keyof BotPlay) => a[k] + (b[k] - a[k]) * t;
|
||||
return { slip: mix('slip'), window: mix('window'), lapse: mix('lapse'), miss: mix('miss') };
|
||||
}
|
||||
|
||||
export const LAPSE_WINDOW = 8;
|
||||
|
||||
@@ -63,12 +80,12 @@ export function humanBest<A>(
|
||||
level: BotLevel | undefined,
|
||||
scale: { small: number; critical: number },
|
||||
): A {
|
||||
if (!level || xs.length < 2) return best(xs, score, random);
|
||||
if (level === undefined || 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 play = botPlay(level);
|
||||
const r = random();
|
||||
if (topScore >= scale.critical) {
|
||||
if (r >= play.miss) return top;
|
||||
|
||||
@@ -88,7 +88,7 @@ describe('whole games', () => {
|
||||
players: seats(7, 0),
|
||||
seed: seedN(s),
|
||||
isBot,
|
||||
personaOf: (p, st): BotPersona => ({ level: 'normal', smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }),
|
||||
personaOf: (p, st): BotPersona => ({ 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, { 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')!;
|
||||
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')!;
|
||||
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<string, unknown> = {};
|
||||
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: { level: 'hard', 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: { 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);
|
||||
|
||||
@@ -55,3 +55,30 @@ export const BOT_GAMES: readonly string[] = [
|
||||
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6 };
|
||||
|
||||
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
|
||||
|
||||
/**
|
||||
* Computer levels 1~60 (docs/09-game-engine.md §9.1): 1~20 쉬움, 21~40 보통, 41~60 어려움. The host can pick a band
|
||||
* for each computer after adding it; the exact level inside the band is drawn at random and stays hidden until the
|
||||
* game is over (fairness check).
|
||||
*/
|
||||
export const BOT_LEVEL_MAX = 60;
|
||||
export type BotBand = 'easy' | 'normal' | 'hard';
|
||||
export type BotPick = 'random' | BotBand;
|
||||
export const BOT_PICKS: readonly BotPick[] = ['random', 'easy', 'normal', 'hard'];
|
||||
export const BOT_BANDS: Readonly<Record<BotBand, readonly [number, number]>> = { easy: [1, 20], normal: [21, 40], hard: [41, 60] };
|
||||
export const BOT_PICK_LABEL: Readonly<Record<BotPick, string>> = { random: '랜덤', easy: '쉬움', normal: '보통', hard: '어려움' };
|
||||
|
||||
export function bandOf(level: number): BotBand {
|
||||
return level <= BOT_BANDS.easy[1] ? 'easy' : level <= BOT_BANDS.normal[1] ? 'normal' : 'hard';
|
||||
}
|
||||
|
||||
/**
|
||||
* Luck in [-1, 1] as people read it. A computer's luck decides how many shuffles the server tries before a game and
|
||||
* whether it keeps the best or the worst one for that computer (docs/04-stability-security.md §5.1).
|
||||
*/
|
||||
export function luckLabel(luck: number): string {
|
||||
if (luck <= -0.6) return '아주 나쁨';
|
||||
if (luck <= -0.2) return '나쁨';
|
||||
if (luck < 0.2) return '보통';
|
||||
return luck < 0.6 ? '좋음' : '아주 좋음';
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export const ClientMessage = z.discriminatedUnion('t', [
|
||||
z.object({ t: z.literal('host'), userId }),
|
||||
z.object({ t: z.literal('addBot'), seat: z.number().int().min(0).max(31).optional() }),
|
||||
z.object({ t: z.literal('removeBot'), userId }),
|
||||
z.object({ t: z.literal('botLevel'), userId, pick: z.enum(['random', 'easy', 'normal', 'hard']) }),
|
||||
z.object({ t: z.literal('act'), cs: z.number().int().min(1), a: z.unknown() }),
|
||||
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX) }),
|
||||
z.object({ t: z.literal('emote'), id: z.string().max(20) }),
|
||||
|
||||
@@ -58,6 +58,14 @@ export interface RoomView {
|
||||
lastGamePk: string | null;
|
||||
/** Computers doing something people can see (docs/06 §12.1): "생각 중…" / "입력 중…". */
|
||||
botActivity?: Record<string, 'thinking' | 'typing'>;
|
||||
/** Difficulty the host picked for each computer (랜덤/쉬움/보통/어려움, docs/06 §12). */
|
||||
botPicks?: Record<string, 'random' | 'easy' | 'normal' | 'hard'>;
|
||||
/** Shuffling before the game started (computers' luck, docs/04 §5.1). */
|
||||
starting?: boolean;
|
||||
/** After a game with computers: each computer's level (1~60) and luck in that game, for the fairness check. */
|
||||
lastBots?: Record<string, { level: number; luck: number }>;
|
||||
/** How many shuffles were tried for the computers' luck in that game (1 = the first one, no choice). */
|
||||
lastShuffles?: number;
|
||||
}
|
||||
|
||||
export interface GameResultView {
|
||||
@@ -70,7 +78,7 @@ export interface GameResultView {
|
||||
}
|
||||
|
||||
export type ServerMessage =
|
||||
| { t: 'welcome'; me: PublicUser; serverTime: number; protocol: number; activeRoom: string | null }
|
||||
| { t: 'welcome'; me: PublicUser; serverTime: number; protocol: number; activeRoom: string | null; build?: string | null }
|
||||
| { t: 'room'; seq: number; room: RoomView }
|
||||
| {
|
||||
t: 'state';
|
||||
|
||||
Reference in New Issue
Block a user