/** Each computer's character, fixed by its id (docs/09-game-engine.md §9). */ /** FNV-1a of the parts → [0, 1). Stable: the same bot decides the same way about the same thing. */ export function hash01(...parts: (string | number)[]): number { let h = 2166136261; const s = parts.join('\u0001'); for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return (h >>> 0) / 2 ** 32; } /** * Each computer's own pace (0.7 quick … 1.5 careful), fixed for the bot id so "컴퓨터 2" keeps its character for the * whole game, while a new room's 컴퓨터 2 (new id) may be different. */ export function botPace(bot: string): number { let h = 2166136261; for (let i = 0; i < bot.length; i++) h = Math.imul(h ^ bot.charCodeAt(i), 16777619); return 0.7 + ((h >>> 0) / 2 ** 32) * 0.8; } /** * 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'; /** * A fixed roll in [0, 1) for a bot 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. 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] ?? ''; 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; } /** 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 { /** * 똑똑한 편(근거를 보고 추리, 존댓말) / 허술한 편(느낌과 분위기를 따름, 반말): 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. */ pace: number; /** 0.5 … 1: how likely it speaks up. */ chatty: number; } /** `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 }; }