- 난이도 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>
131 lines
5.4 KiB
TypeScript
131 lines
5.4 KiB
TypeScript
/** 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 };
|
||
|
||
/** Actions a bot never starts on its own: requests to the human, resigning, chatting, editing tricks. */
|
||
const META = new Set(['requestUndo', 'offerDraw', 'claimDraw', 'resign', 'concede', 'leave', 'undoDraft', 'report', 'chat', 'reaction', 'emote', 'adjustTime']);
|
||
|
||
export const pick = <T>(xs: readonly T[], random: () => number): T => xs[Math.floor(random() * xs.length)]!;
|
||
|
||
export const typeOf = (a: unknown): string => String((a as Act | null)?.type ?? '');
|
||
|
||
/** Legal actions minus meta ones (kept if nothing else is left). */
|
||
export function playable<A>(legal: A[]): A[] {
|
||
const out = legal.filter((a) => !META.has(typeOf(a)));
|
||
return out.length ? out : legal;
|
||
}
|
||
|
||
/** Highest-scoring action; ties broken at random. */
|
||
export function best<A>(xs: readonly A[], score: (a: A) => number, random: () => number): A {
|
||
let top: A[] = [];
|
||
let topScore = -Infinity;
|
||
for (const a of xs) {
|
||
const s = score(a);
|
||
if (s > topScore) {
|
||
topScore = s;
|
||
top = [a];
|
||
} else if (s === topScore) top.push(a);
|
||
}
|
||
return pick(top.length ? top : xs, random);
|
||
}
|
||
|
||
/** 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;
|
||
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;
|
||
}
|
||
|
||
/**
|
||
* 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;
|
||
|
||
/**
|
||
* 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<A>(
|
||
xs: readonly A[],
|
||
score: (a: A) => number,
|
||
random: () => number,
|
||
level: BotLevel | undefined,
|
||
scale: { small: number; critical: number },
|
||
): A {
|
||
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 = botPlay(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.
|
||
*/
|
||
export function answerRequests<A>(legal: A[]): A | null {
|
||
for (const a of legal) {
|
||
const t = typeOf(a);
|
||
if (t === 'respondUndo') return { ...(a as object), accept: true } as A;
|
||
if (t === 'respondDraw') return { ...(a as object), accept: false } as A;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** Random legal action, preferring to answer requests and skipping meta actions. */
|
||
export function randomPolicy<A>({ legal, random }: BotInput<unknown, A>): A {
|
||
return answerRequests(legal) ?? pick(playable(legal), random);
|
||
}
|
||
|
||
/** Random action, but "pass"-like actions only when nothing else is possible. */
|
||
export function preferPlay<A>(input: BotInput<unknown, A>, passTypes: string[] = ['pass', 'draw']): A {
|
||
const req = answerRequests(input.legal);
|
||
if (req) return req;
|
||
const all = playable(input.legal);
|
||
const plays = all.filter((a) => !passTypes.includes(typeOf(a)));
|
||
return pick(plays.length ? plays : all, input.random);
|
||
}
|