Files
joke-app/packages/games/src/liar/bot.ts
EJClaw 1bd69200fd 라이어 게임: 관리자 화면에서 주제·제시어 추가/수정/삭제, 바보 모드 라이어는 비슷한 단어(같은 묶음)
- 제시어 1,519개를 주제별 '비슷한 단어 묶음' 391개로 정리(bank/*.ts groups). 바보 모드 라이어는 제시어와 같은 묶음의 다른 단어를 받음
- 관리자 → 라이어 제시어(/admin/liar): 주제 추가·이름 변경·삭제(내장 주제는 다시 살리기/처음 값으로), 제시어·묶음·다른 표기·컴퓨터 설명 편집, 저장 시 topicProblems 검사
- 저장: liar_topics(바뀐 주제), liar_bank_versions(판본). 새 판 옵션에 bank 판본을 붙여(prepareOptions) 다시 보기·복구가 같은 은행 사용
- 판 상태에 주제 이름·단어 목록·다른 표기를 복사해 진행 중 판은 관리자 수정의 영향을 받지 않음
- 대기실 주제 목록은 GET /api/liar/topics, 관리자 API /api/admin/liar/topics, 기록 liar.topic.*
- 테스트: 엔진(묶음·바보 모드·판본·검사), 서버(관리자 API·새 판·재시작), E2E(관리자 편집 → 대기실 새 주제)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 04:16:17 +09:00

517 lines
21 KiB
TypeScript

/**
* 라이어 게임 computer players (docs/games/liar.md §13). A live bot like 마피아: the server asks each computer again and
* again on its own timer; it sees only its own screen (`view`) and either does one thing (describe, talk, vote, guess,
* press "확인"/"토론 끝내기") or keeps watching.
*
* Every line is fixed text from the word bank or the lines below: no language model rewrites it (a model could let the
* word slip, or a liar computer could say something it cannot know).
*
* - 시민: describes with a sentence of the word's bank it has not heard yet (똑똑한 편 the vaguest first, 허술한 편 any),
* then suspects whoever's descriptions fit the word worst.
* - 라이어: guesses the word from the descriptions so far (character-pair overlap with each word's bank, rarer pairs
* weigh more) and describes that word, vaguely; before anyone spoke it says something that fits the whole topic.
* When caught it names the same guess. It never points at itself.
* - 바보 모드 라이어 doesn't know: it plays as a citizen of its own word.
* The level (1~60) sets how sharp the reading is: noise on every judgement shrinks as the level grows.
*/
import type { PlayerId } from '@bg/engine';
import { normalize } from '../catchmind/text';
import { hash01 } from '../bots/persona';
import type { LiveBotDecision, LiveBotInput } from '../bots/types';
import type { Description, LiarAction, LiarView } from './types';
import { topicById, type LiarTopic } from './words';
type In = LiveBotInput<LiarView>;
type Done = Record<string, true>;
interface Intent {
key: string;
due: number;
make: () => LiarAction | null;
}
// ---------------------------------------------------------------- Korean helpers
function batchim(word: string): boolean {
const c = word.trim().at(-1) ?? '';
const code = c.charCodeAt(0);
if (code >= 0xac00 && code <= 0xd7a3) return (code - 0xac00) % 28 !== 0;
if (/[0-9]/.test(c)) return '013678'.includes(c);
return /[lmnr]/i.test(c);
}
const JOSA: Record<string, [string, string]> = { 이: ['이', '가'], 은: ['은', '는'], 을: ['을', '를'], 이랑: ['이랑', '랑'] };
/** `{X}` name, `{X:이}` name + 이/가 (also 은, 을, 이랑). */
function fill(t: string, vars: Record<string, string>): string {
return t.replace(/\{(\w)(?::([^}]+))?\}/g, (_, k: string, j?: string) => {
const w = vars[k] ?? '';
if (!j) return w;
const pair = JOSA[j];
return pair ? w + (batchim(w) ? pair[0] : pair[1]) : w + j;
});
}
// ---------------------------------------------------------------- lines (smart: 존댓말, dumb: 반말)
const L = {
accuse: {
smart: ['{X} 설명이 좀 애매했어요', '제 생각엔 {X:이} 라이어 같아요', '{X:은} 다른 걸 설명한 것 같아요', '{X} 설명이 너무 무난했어요. 조금 의심돼요'],
dumb: ['{X} 라이어 아님?', '{X} 설명 뭐임ㅋㅋ', '{X} 수상함', '난 {X} 찍을거임', '{X} 뭔가 이상해'],
},
unsure: {
smart: ['다들 비슷하게 설명해서 어렵네요', '조금 더 이야기해 봐요', '아직 잘 모르겠어요. 다들 어떻게 생각해요?'],
dumb: ['다 수상해ㅋㅋ', '모르겠다', '누구지...', '흠'],
},
defend: {
smart: ['저 아니에요! 제 설명 다시 보세요', '저는 제시어 알아요. 오히려 {Y:이} 수상해요', '억울해요. 저 진짜 시민이에요', '일부러 애매하게 말한 거예요. {Y} 쪽을 봐 주세요'],
dumb: ['나 아님ㅋㅋ', '왜 나야;;', '나 시민임 진짜', '{Y} 의심해라', '억울하다'],
},
agree: { smart: ['저도 {X:이} 수상하다고 봐요', '동의해요. {X} 설명이 좀 이상했어요'], dumb: ['ㅇㅈ {X} 수상', '{X} 맞는듯', 'ㄹㅇ {X} 이상함'] },
disagree: { smart: ['{X:은} 맞게 설명한 것 같은데요', '{X}보다는 {Y:이} 더 수상해요'], dumb: ['{X:은} 아닌듯?', '에이 {X:은} 아니지'] },
called: { smart: ['네?', '저요? 왜요?'], dumb: ['왜', 'ㅇ?', '부름?'] },
/** Describing when the bank ran out: lean on someone else's description. */
echo: { smart: ['{X} 설명에 한 표예요', '{X:이랑} 같은 생각이에요'], dumb: ['{X:이랑} 같은 생각', '{X} 말 ㅇㅈ'] },
};
type LineKey = keyof typeof L;
// ---------------------------------------------------------------- reading descriptions
/** Character pairs of the text (spaces and punctuation out). */
function grams(text: string): Set<string> {
const t = [...normalize(text)];
const out = new Set<string>();
for (let i = 0; i + 1 < t.length; i++) out.add(t[i]! + t[i + 1]!);
return out;
}
interface TopicModel {
topic: LiarTopic;
/** Pairs of each word's bank sentences. */
corpus: Map<string, Set<string>>;
/** Rarer pairs (in fewer words) say more. */
idf: Map<string, number>;
}
const models = new Map<string, TopicModel>();
/** The game's topic in the bank version it was set up with (a topic missing there: no sentences, the bot leans on others). */
function model(v: Pick<LiarView, 'topic' | 'topicKo' | 'options'>): TopicModel {
const key = `${v.options.bank ?? ''}|${v.topic}`;
const hit = models.get(key);
if (hit) return hit;
const topic = topicById(v.topic, v.options.bank) ?? { id: v.topic, ko: v.topicKo, generic: [], words: [] };
const corpus = new Map<string, Set<string>>();
const df = new Map<string, number>();
for (const w of topic.words) {
const set = new Set<string>();
for (const h of w.hints) for (const g of grams(h)) set.add(g);
corpus.set(w.word, set);
for (const g of set) df.set(g, (df.get(g) ?? 0) + 1);
}
const n = topic.words.length;
const idf = new Map<string, number>();
for (const [g, d] of df) idf.set(g, Math.log((n + 1) / d) - 0.15);
const m = { topic, corpus, idf };
if (models.size > 200) models.clear();
models.set(key, m);
return m;
}
/** How well a description matches each word of the topic, 0..1 (1 = the best match). */
function matchAll(m: TopicModel, text: string): Map<string, number> {
const gs = grams(text);
const raw = new Map<string, number>();
let best = 0;
for (const [word, set] of m.corpus) {
let s = 0;
for (const g of gs) if (set.has(g)) s += Math.max(0, m.idf.get(g) ?? 0);
raw.set(word, s);
best = Math.max(best, s);
}
const out = new Map<string, number>();
for (const [word, s] of raw) out.set(word, best > 0.5 ? s / best : 0);
return out;
}
// ---------------------------------------------------------------- the bot
/** How a computer paces a 무제한 phase: like the default clock of that phase. */
const UNLIMITED_PACE_MS: Record<Exclude<LiarView['phase']['kind'], 'ended'>, number> = {
reveal: 10_000,
describe: 30_000,
discussion: 90_000,
vote: 30_000,
guess: 30_000,
};
class LiarBot {
readonly v: LiarView;
readonly me: PlayerId;
readonly smart: boolean;
/** 0 (level 1) … 1 (level 60). */
readonly q: number;
private pace: number;
private phaseId: string;
private m: TopicModel;
constructor(private input: In) {
this.v = input.view;
this.me = input.me;
this.smart = input.persona.smart;
this.pace = input.persona.pace;
const level = input.level ?? (this.smart ? 45 : 15);
this.q = Math.min(1, Math.max(0, (level - 1) / 59));
const ph = this.v.phase;
this.phaseId = `${ph.kind}:${ph.round}:${ph.turn}:${ph.voteRound ?? 0}:${ph.startedAt}`;
this.m = model(this.v);
}
private h(...k: (string | number)[]): number {
return hash01(this.me, this.v.order.join(','), ...k);
}
private get my() {
return this.v.my!;
}
/** Thinks it is the liar (normal mode, or after the reveal). */
private get isLiar(): boolean {
return this.my.role === 'liar';
}
private name(id: PlayerId): string {
const n = this.input.names[id] ?? '누군가';
if (this.smart) return `${n}님`;
const m = /^컴퓨터 (\d+)$/.exec(n);
return m ? `${m[1]}번` : n;
}
private line(key: LineKey, salt: string | number, vars: Record<string, string> = {}): string {
const pool = this.smart ? L[key].smart : L[key].dumb;
const used = new Set([...this.v.chat.filter((c) => c.from === this.me).map((c) => c.text), ...this.v.chat.slice(-8).map((c) => c.text)]);
const first = Math.floor(this.h('line', key, salt) * pool.length);
for (let i = 0; i < pool.length; i++) {
const text = fill(pool[(first + i) % pool.length]!, vars);
if (!used.has(text) && this.safe(text)) return text;
}
return fill(pool[first]!, vars);
}
/** Never says its own word (a name may contain it). */
private safe(text: string): boolean {
const w = this.my.word;
return !w || !normalize(text).includes(normalize(w));
}
private react(baseMs: number, key: string): number {
return Math.round(baseMs * (0.6 + this.h('react', key) * 0.9) * this.pace);
}
private get phaseStart(): number {
return this.v.phase.startedAt;
}
/** Phase length; 무제한 phases are paced like the default clock (so a computer neither rushes nor stalls). */
private get phaseLen(): number {
const ph = this.v.phase;
if (ph.endsAt === null && ph.kind !== 'ended') return UNLIMITED_PACE_MS[ph.kind];
return Math.max(1000, (ph.endsAt ?? this.phaseStart) - this.phaseStart);
}
/** `lo..hi` seconds into the phase (scaled by pace), never later than `cap` of it. */
private inPhase(lo: number, hi: number, key: string, cap = 0.8): number {
const ms = (lo + (hi - lo) * this.h('t', key, this.phaseId)) * 1000 * this.pace;
return this.phaseStart + Math.min(ms, this.phaseLen * cap);
}
private others(): PlayerId[] {
return this.v.players.filter((p) => !p.left && p.id !== this.me).map((p) => p.id);
}
private said(): Description[] {
return this.v.descriptions.filter((d) => d.text !== null);
}
// ---------------------------------------------------------------- judgement
/**
* The liar's guess of the word: per word, the share of the descriptions it understood that point at it (noisy at low
* levels). A weaker computer catches fewer descriptions (`understood`) and reads them with more noise.
*/
guessScores(): Map<string, number> {
const out = new Map<string, number>();
for (const w of this.m.topic.words) out.set(w.word, 0);
let heard = 0;
for (const d of this.said()) {
if (d.from === this.me || this.h('understand', d.n) > 0.3 + 0.65 * this.q) continue;
const fit = matchAll(this.m, d.text!);
if (Math.max(0, ...fit.values()) === 0) continue;
heard++;
for (const [w, s] of fit) out.set(w, out.get(w)! + s);
}
if (!heard) return new Map();
// 바보 모드 after the reveal: my own word is certainly not it.
if (this.my.word) out.delete(this.my.word);
const noise = 0.3 + 1.1 * (1 - this.q);
for (const [w, s] of out) out.set(w, s / heard + (this.h('guess', w) - 0.5) * noise);
return out;
}
/** Best guess of the word, or null before anyone said anything useful. */
guessWord(): string | null {
let best: string | null = null;
let bs = -Infinity;
for (const [w, s] of this.guessScores()) {
if (s > bs) {
bs = s;
best = w;
}
}
return best;
}
/** The word I judge others by: mine, or (liar) my guess. */
private judgeWord(): string | null {
return this.isLiar ? this.guessWord() : this.my.word;
}
/** 0..1: how well `x`'s descriptions fit `word` (skips and words of no word count as weak). */
fit(x: PlayerId, word: string | null): number {
const ds = this.v.descriptions.filter((d) => d.from === x);
if (!ds.length || !word) return 0.5;
let sum = 0;
for (const d of ds) {
if (d.text === null) {
sum += 0.15;
continue;
}
const fit = matchAll(this.m, d.text);
const best = Math.max(0, ...fit.values());
sum += best === 0 ? 0.4 : (fit.get(word) ?? 0);
}
return sum / ds.length;
}
/** Higher = more likely the liar, in this computer's eyes. */
sus(x: PlayerId): number {
const noise = (this.h('noise', x) - 0.5) * (0.2 + 1.4 * (1 - this.q));
let s = 1 - this.fit(x, this.judgeWord()) + noise;
// The chat: people others point at (the liar computer leans on it to blend in; careless ones follow the crowd).
const pile = this.accusedInChat().get(x) ?? 0;
s += pile * (this.isLiar ? 0.25 : this.smart ? 0.05 : 0.2);
return s;
}
private suspect(among = this.others()): PlayerId | null {
let best: PlayerId | null = null;
let bs = -Infinity;
for (const x of among) {
if (x === this.me) continue;
const s = this.sus(x);
if (s > bs) {
bs = s;
best = x;
}
}
return best;
}
// ---------------------------------------------------------------- reading the chat
private nameRes: { id: PlayerId; re: RegExp }[] | null = null;
/** Mentions in a line: who, and the text right after (up to the next mention). */
private mentions(text: string): { id: PlayerId; tail: string }[] {
this.nameRes ??= this.v.players.map((p) => {
const n = this.input.names[p.id] ?? p.id;
const m = /^컴퓨터 (\d+)$/.exec(n);
const alts = (m ? [n, `컴퓨터${m[1]}`, `컴${m[1]}`, `${m[1]}번`] : [n]).map((a) => a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
return { id: p.id, re: new RegExp(`(?<![0-9])(${alts.join('|')})(?![0-9])`, 'g') };
});
const hits: { id: PlayerId; at: number; end: number }[] = [];
for (const { id, re } of this.nameRes) {
re.lastIndex = 0;
for (let x = re.exec(text); x; x = re.exec(text)) hits.push({ id, at: x.index, end: x.index + x[0].length });
}
hits.sort((a, b) => a.at - b.at);
return hits.map((x, i) => ({ id: x.id, tail: text.slice(x.end, hits[i + 1]?.at ?? text.length).slice(0, 24) }));
}
stance(text: string): { accused: PlayerId[]; cleared: PlayerId[] } {
const accused: PlayerId[] = [];
const cleared: PlayerId[] = [];
for (const m of this.mentions(text)) {
if (/라이어\s*(아니(야|에요|지|냐)?\s*\?|아냐|아닌가|아님\?)/.test(m.tail)) accused.push(m.id);
else if (/^\s*(님)?\s*보다/.test(m.tail) || /아니|아닌|아님|시민|믿|맞게|딱/.test(m.tail)) cleared.push(m.id);
else if (/라이어|수상|의심|찍|이상|애매|거짓|너지|뭐임|무난/.test(m.tail)) accused.push(m.id);
}
return { accused, cleared };
}
private pileCache: Map<PlayerId, number> | null = null;
private accusedInChat(): Map<PlayerId, number> {
if (this.pileCache) return this.pileCache;
const out = new Map<PlayerId, number>();
for (const c of this.v.chat) {
if (c.from === this.me) continue;
for (const x of this.stance(c.text).accused) if (x !== c.from) out.set(x, (out.get(x) ?? 0) + 1);
}
return (this.pileCache = out);
}
// ---------------------------------------------------------------- what to do
intents(): Intent[] {
const v = this.v;
const my = this.my;
const key = (s: string) => `${this.phaseId}:${s}`;
const out: Intent[] = [];
switch (v.phase.kind) {
case 'reveal':
if (my.canReady) out.push({ key: key('ready'), due: this.inPhase(2, 5, 'ready', 0.6), make: () => ({ type: 'ready' }) });
break;
case 'describe':
if (my.canDescribe) {
out.push({
key: key('describe'),
// Leave room for typing ("입력 중…" up to ~6초 on the server) inside the turn.
due: this.inPhase(1.5, 5, 'describe', 0.3),
make: () => ({ type: 'describe', text: this.description() }),
});
}
break;
case 'discussion': {
const cap = 3;
const chat = (text: string) => (this.v.chat.filter((c) => c.from === this.me && c.at >= this.phaseStart).length < cap && my.canChat ? ({ type: 'chat', text } as LiarAction) : null);
if (this.h('open') < 0.5 + 0.5 * this.input.persona.chatty) {
out.push({
key: key('open'),
due: this.inPhase(3, 12, 'open', 0.45),
make: () => {
const x = this.suspect();
const sure = x !== null && this.sus(x) > 0.55;
return chat(sure ? this.line('accuse', 'open', { X: this.name(x!) }) : this.line('unsure', 'open'));
},
});
}
out.push(...this.replies(key, chat));
if (my.canReady) out.push({ key: key('ready'), due: this.phaseStart + this.phaseLen * (0.55 + 0.25 * this.h('ready', this.phaseId)), make: () => ({ type: 'ready' }) });
break;
}
case 'vote':
if (my.voteTargets.length && my.vote === null) {
out.push({
key: key('vote'),
due: this.inPhase(2, 8, 'vote', 0.6),
make: () => {
const t = this.suspect(my.voteTargets) ?? my.voteTargets[0]!;
return { type: 'vote', target: t };
},
});
}
break;
case 'guess':
if (my.canGuess) {
out.push({
key: key('guess'),
due: this.inPhase(3, 8, 'guess', 0.5),
make: () => ({ type: 'guess', text: this.finalGuess() }),
});
}
break;
case 'ended':
break;
}
return out;
}
/** One sentence for my turn. */
description(): string {
const heard = new Set(this.v.descriptions.map((d) => d.text).filter((t): t is string => !!t));
const fresh = (xs: readonly string[]) => xs.filter((x) => !heard.has(x) && this.safe(x));
const word = this.judgeWord();
// A liar dares to describe its guess only now and then at low levels (otherwise something that fits the topic).
const dare = !this.isLiar || this.h('dare', this.v.descriptions.length) < 0.35 + 0.6 * this.q;
const hints = word && dare ? fresh(this.m.topic.words.find((w) => w.word === word)?.hints ?? []) : [];
if (hints.length) {
// Smart ones start vague; careless ones (and a liar without a clue) pick any.
const i = this.smart && !this.isLiar ? 0 : Math.floor(this.h('hint', this.v.descriptions.length) * hints.length);
return hints[i]!;
}
// Nothing of my own left (or the liar has no clue yet): something that fits the whole topic, or lean on someone.
const generic = fresh(this.m.topic.generic);
const trusted = this.others()
.filter((x) => this.v.descriptions.some((d) => d.from === x && d.text))
.sort((a, b) => this.fit(b, word) - this.fit(a, word))[0];
if (trusted && (word || !generic.length) && this.h('echo', this.v.descriptions.length) < 0.6) return this.line('echo', this.v.descriptions.length, { X: this.name(trusted) });
if (generic.length) return generic[Math.floor(this.h('generic', this.v.descriptions.length) * generic.length)]!;
return this.smart ? '음… 말로 하기 어렵네요' : '음 뭐라 하지';
}
/** The liar's answer: the best guess, or any word of the topic. */
finalGuess(): string {
const g = this.guessWord();
if (g) return g;
const words = this.m.topic.words.map((w) => w.word).filter((w) => w !== this.my.word);
return words[Math.floor(this.h('blind') * words.length)] ?? (this.smart ? '모르겠어요' : '몰라');
}
private replies(key: (s: string) => string, chat: (t: string) => LiarAction | null): Intent[] {
const out: Intent[] = [];
const recent = this.v.chat.filter((c) => c.from !== this.me && c.at >= this.phaseStart && c.at >= this.input.now - 25_000);
for (const c of recent) {
const st = this.stance(c.text);
const named = this.mentions(c.text).some((x) => x.id === this.me);
const delay = (base: number) => c.at + this.react(base + 60 * [...c.text].length, `${c.n}`);
if (named) {
out.push({
key: key(`r:${c.n}`),
due: delay(2500),
make: () => {
if (st.accused.includes(this.me)) {
const y = this.suspect(this.others().filter((x) => x !== c.from)) ?? c.from;
return chat(this.line('defend', c.n, { Y: this.name(y) }));
}
return st.cleared.includes(this.me) ? chat(this.smart ? '감사해요!' : 'ㅇㅇ 고마움') : chat(this.line('called', c.n));
},
});
continue;
}
const x = st.accused.find((id) => id !== this.me && id !== c.from);
if (!x || this.h('chime', c.n) > (this.smart ? 0.3 : 0.4)) continue;
out.push({
key: key(`a:${c.n}`),
due: delay(3500),
make: () => {
const mine = this.suspect();
if (mine === x || this.sus(x) > 0.6 || (!this.smart && this.h('follow', c.n) < 0.6)) return chat(this.line('agree', c.n, { X: this.name(x) }));
return chat(this.line('disagree', c.n, { X: this.name(x), Y: mine ? this.name(mine) : '다른 사람' }));
},
});
}
return out;
}
}
/** Live strategy: at most one action per call; asks again soon so it can answer the chat. */
export function liarBot(input: In): LiveBotDecision<LiarAction> {
const v = input.view;
if (v.phase.kind === 'ended' || !v.my) return { action: null, next: 5000 };
const bot = new LiarBot(input);
const done = ((input.memory.done as Done | undefined) ??= {});
const list = bot.intents().sort((a, b) => a.due - b.due);
let soonest = Infinity;
for (const it of list) {
if (done[it.key]) continue;
if (it.due > input.now) {
soonest = Math.min(soonest, it.due);
continue;
}
done[it.key] = true;
const action = it.make();
if (action) return { action, next: Math.round(400 + 600 * input.persona.pace) };
}
const idle = 1500;
const wait = soonest === Infinity ? idle : soonest - input.now;
return { action: null, next: Math.max(250, Math.min(idle * input.persona.pace, wait)) };
}
export const _internal = { fill, grams, matchAll, model, LiarBot };