Files
joke-app/packages/games/src/liar/liar.test.ts
EJClaw 74a7daa4d3 새 게임 라이어 게임: 규칙 엔진·말하는 컴퓨터·화면·도움말·문서·E2E
- packages/games/src/liar: 주제 10개 제시어 은행, 설명(두 번째 바퀴 거꾸로)·자유 토론·투표(동점 재투표 한 번, 또 동점이면 라이어 승리)·라이어 정답 맞히기(띄어쓰기·다른 표기 무시), 바보 모드
- 컴퓨터: 마피아처럼 live 전략, 레벨 1~60을 LiveBotInput.level 로 받음(서버 BotDriver 가 넘김), BOT_CHAT_REQUIRED 에 추가
- 웹: 꾹 누르는 제시어 카드, 설명 기록·토론 채팅·투표 화면, 30초 요약, [?] 도움말
- 문서 docs/games/liar.md, 등록(GAMES·CATALOG·BOT_GAMES·registry·아이콘), 서버 방 테스트, E2E(거절 알림이 저절로 사라지는지 확인 포함)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:17:14 +09:00

406 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN, type PlayerId } from '@bg/engine';
import { normalize } from '../catchmind/text';
import { chatProblem } from '../mafia';
import {
DESCRIBE_MAX,
REVEAL_MS,
TOPIC_IDS,
TOPICS,
isCorrectGuess,
liar,
roundOrder,
saysWord,
topicById,
type LiarAction,
type LiarOptions,
type LiarState,
type LiarView,
type PublicEvent,
} from './index';
// ---------------------------------------------------------------- helpers
const T0 = 1_000_000;
const opts = (o: Record<string, unknown> = {}): LiarOptions => liar.optionsSchema.parse(o);
const ids = (n: number) => Array.from({ length: n }, (_, i) => `P${i}`);
const rng = SeededRng.fromSeed([9, 9, 9, 9]);
/** Game with a fixed liar, word and order P0, P1, … (still in the reveal phase). */
function rig(n: number, o: Record<string, unknown> = {}, { liarIdx = n - 1, word = '수박', fake = '참외' } = {}): LiarState {
const s = liar.setup({ players: ids(n), options: opts({ topic: 'fruit', ...o }), rng: SeededRng.fromSeed(seedN(1)), now: T0 });
s.topic = 'fruit';
s.word = word;
s.liar = `P${liarIdx}`;
s.liarWord = s.options.foolMode ? fake : null;
s.order = ids(n);
return s;
}
function at(s: LiarState): number {
return s.phase.kind === 'ended' ? T0 : Math.max(T0, s.phase.startedAt + 1) + s.seq * 1000;
}
function act(s: LiarState, actor: PlayerId, a: LiarAction, now = at(s)): LiarState {
const v = liar.validate(s, actor, a, { now });
if (!v.ok) throw new Error(`${actor} ${JSON.stringify(a)} rejected: ${v.reason}`);
return liar.apply(s, actor, a, { rng, now }).state;
}
function reject(s: LiarState, actor: PlayerId, a: LiarAction, now?: number): string {
const v = liar.validate(s, actor, a, now === undefined ? undefined : { now });
if (v.ok) throw new Error(`${actor} ${JSON.stringify(a)} was accepted`);
return v.reason;
}
const tick = (s: LiarState) => {
if (s.phase.kind === 'ended') throw new Error('tick after the end');
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt);
};
function until(s: LiarState, kind: LiarState['phase']['kind']): LiarState {
for (let i = 0; i < 60 && s.phase.kind !== kind && s.phase.kind !== 'ended'; i++) s = tick(s);
if (s.phase.kind !== kind) throw new Error(`never reached ${kind} (now ${s.phase.kind})`);
return s;
}
const speaker = (s: LiarState) => liar.view(s, null).phase.speaker;
const lastEv = <K extends PublicEvent['t']>(s: LiarState, t: K) => s.events.filter((e) => e.t === t).at(-1) as Extract<PublicEvent, { t: K }> | undefined;
function votes(s: LiarState, v: Record<string, string>): LiarState {
for (const [p, t] of Object.entries(v)) s = act(s, p, { type: 'vote', target: t });
return s;
}
// ---------------------------------------------------------------- word bank
describe('제시어 은행 (§3)', () => {
test('주제 10개 이상 × 단어 15개 이상 × 설명 4개 이상, 옵션의 주제와 같아요', () => {
expect(TOPICS.length).toBeGreaterThanOrEqual(10);
expect(TOPICS.map((t) => t.id)).toEqual([...TOPIC_IDS]);
for (const t of TOPICS) {
expect(t.words.length, t.id).toBeGreaterThanOrEqual(15);
expect(t.generic.length, t.id).toBeGreaterThanOrEqual(4);
expect(new Set(t.words.map((w) => normalize(w.word))).size, t.id).toBe(t.words.length);
for (const w of t.words) {
expect(w.hints.length, w.word).toBeGreaterThanOrEqual(4);
expect([...w.word].length, w.word).toBeGreaterThanOrEqual(2);
expect(new Set(w.hints).size, w.word).toBe(w.hints.length);
}
}
});
test('설명 문장에 그 단어(다른 표기 포함)가 없고, 무난한 말에는 주제의 어떤 단어도 없어요. 고운 말 필터도 통과', () => {
for (const t of TOPICS) {
for (const w of t.words) {
for (const h of w.hints) {
expect(saysWord(h, t.id, w.word), `${w.word}: ${h}`).toBe(false);
expect(chatProblem(h, true), h).toBeNull();
expect([...h].length).toBeLessThanOrEqual(DESCRIBE_MAX);
}
}
for (const g of t.generic) {
for (const w of t.words) expect(saysWord(g, t.id, w.word), `${t.id} generic: ${g}`).toBe(false);
expect(chatProblem(g, true)).toBeNull();
}
}
});
test('정답 비교: 띄어쓰기·대소문자·문장 부호·"~요" 무시, 다른 표기도 정답', () => {
expect(isCorrectGuess('수박', 'fruit', '수박')).toBe(true);
expect(isCorrectGuess(' 수 박!! ', 'fruit', '수박')).toBe(true);
expect(isCorrectGuess('수박이요', 'fruit', '수박')).toBe(false); // "이요" is not a polite ending on its own
expect(isCorrectGuess('수박요', 'fruit', '수박')).toBe(true);
expect(isCorrectGuess('참외', 'fruit', '수박')).toBe(false);
expect(isCorrectGuess('tv', 'thing', '텔레비전')).toBe(true);
expect(isCorrectGuess('핸드 폰', 'thing', '휴대폰')).toBe(true);
expect(isCorrectGuess('파인 애플', 'fruit', '파인애플')).toBe(true);
});
});
// ---------------------------------------------------------------- setup and secrecy
describe('준비와 비밀 (§4, §8.3)', () => {
test('무작위 주제·단어·라이어·첫 발언자, 순서는 자리 순서를 돌린 것', () => {
const liars = new Set<string>();
const firsts = new Set<string>();
const topics = new Set<string>();
for (let i = 1; i <= 60; i++) {
const s = liar.setup({ players: ids(5), options: opts(), rng: SeededRng.fromSeed(seedN(i)), now: T0 });
liars.add(s.liar);
firsts.add(s.order[0]!);
topics.add(s.topic);
expect(topicById(s.topic).words.some((w) => w.word === s.word)).toBe(true);
const k = ids(5).indexOf(s.order[0]!);
expect(s.order).toEqual([...ids(5).slice(k), ...ids(5).slice(0, k)]);
expect(s.liarWord).toBeNull();
expect(s.phase).toEqual({ kind: 'reveal', startedAt: T0, endsAt: T0 + REVEAL_MS, ready: [] });
}
expect(liars.size).toBe(5);
expect(firsts.size).toBe(5);
expect(topics.size).toBeGreaterThan(5);
});
test('시민은 제시어, 라이어는 주제만, 관전자는 주제만. 누가 라이어인지는 어디에도 없어요', () => {
const s = rig(5);
const citizen = liar.view(s, 'P0');
expect(citizen.my).toMatchObject({ role: 'citizen', word: '수박' });
const lv = liar.view(s, 'P4');
expect(lv.my).toMatchObject({ role: 'liar', word: null });
expect(lv.topicKo).toBe('과일');
expect(JSON.stringify(lv)).not.toContain('수박');
expect(JSON.stringify(liar.view(s, null))).not.toContain('수박');
for (const v of [citizen, lv, liar.view(s, null)]) for (const p of v.players) expect(p.liar).toBeNull();
});
test('시민 화면은 누가 라이어든 똑같아요(라이어가 바뀌어도 한 글자도 안 바뀜)', () => {
let a = rig(6, {}, { liarIdx: 3 });
let b = rig(6, {}, { liarIdx: 5 });
// Same moves on both: reveal → two descriptions → discussion → votes.
const step = (f: (s: LiarState) => LiarState) => {
a = f(a);
b = f(b);
};
step(tick);
step((s) => act(s, speaker(s)!, { type: 'chat', text: '여름에 생각나요' }));
step(tick);
step((s) => until(s, 'discussion'));
step((s) => act(s, 'P1', { type: 'chat', text: '다들 애매하네요' }));
step((s) => until(s, 'vote'));
step((s) => act(s, 'P0', { type: 'vote', target: 'P2' }));
for (const viewer of ['P0', 'P1', 'P2', null]) expect(liar.view(a, viewer)).toEqual(liar.view(b, viewer));
});
test('바보 모드: 라이어도 다른 단어를 받고 "시민"으로 보여요. 화면 모양이 시민과 똑같아요', () => {
const s = rig(5, { foolMode: true });
const lv = liar.view(s, 'P4');
const cv = liar.view(s, 'P0');
expect(lv.my).toMatchObject({ role: 'citizen', word: '참외' });
expect(JSON.stringify(lv)).not.toContain('수박');
for (const v of [cv, liar.view(s, 'P1'), liar.view(s, null)]) expect(JSON.stringify(v)).not.toContain('참외');
const shape = (v: LiarView) => JSON.stringify({ ...v, me: 'X', my: { ...v.my, word: 'W' } });
expect(shape(lv)).toBe(shape(cv));
expect(liar.secretsOf!(s, 'P4')).toEqual(['참외']);
expect(() => checkNoLeak(liar, s, 'P0', ids(5))).not.toThrow();
});
test('라이어가 드러나면(정답 맞히기) 모두가 알고, 바보 모드 라이어도 자기가 라이어인 걸 알아요', () => {
let s = until(rig(4, { foolMode: true }), 'vote');
s = votes(s, { P0: 'P3', P1: 'P3', P2: 'P3', P3: 'P0' });
expect(s.phase.kind).toBe('guess');
expect(liar.view(s, 'P3').my).toMatchObject({ role: 'liar', canGuess: true });
expect(liar.view(s, 'P0').players.find((p) => p.id === 'P3')!.liar).toBe(true);
expect(liar.view(s, null).phase.liar).toBe('P3');
expect(liar.secretsOf!(s, 'P3')).toEqual([]);
// The real word is still hidden from the liar until the end.
expect(JSON.stringify(liar.view(s, 'P3'))).not.toContain('수박');
});
});
// ---------------------------------------------------------------- describing
describe('차례대로 설명 (§5.2)', () => {
test('확인 시간 → 순서대로 한 문장씩, 두 번째 바퀴는 거꾸로, 그다음 자유 토론', () => {
let s = rig(3);
s = act(s, 'P0', { type: 'ready' });
s = act(s, 'P1', { type: 'ready' });
expect(s.phase.kind).toBe('reveal');
s = act(s, 'P2', { type: 'ready' });
expect(s.phase).toMatchObject({ kind: 'describe', round: 1, turn: 0 });
const spoken: string[] = [];
while (s.phase.kind === 'describe') {
const sp = speaker(s)!;
spoken.push(sp);
for (const other of ids(3).filter((x) => x !== sp)) expect(reject(s, other, { type: 'chat', text: '저도요' })).toBe('지금은 설명 차례인 사람만 말할 수 있어요.');
s = act(s, sp, { type: 'chat', text: `설명 ${spoken.length}` });
}
expect(spoken).toEqual(['P0', 'P1', 'P2', 'P2', 'P1', 'P0']);
expect(roundOrder(s, 2)).toEqual(['P2', 'P1', 'P0']);
expect(s.phase.kind).toBe('discussion');
expect(s.descriptions.map((d) => [d.round, d.from, d.text])).toEqual([
[1, 'P0', '설명 1'],
[1, 'P1', '설명 2'],
[1, 'P2', '설명 3'],
[2, 'P2', '설명 4'],
[2, 'P1', '설명 5'],
[2, 'P0', '설명 6'],
]);
});
test('첫 바퀴 마지막 사람은 바로 이어서 두 번째 바퀴 첫 설명을 할 수 있어요(채팅 간격 제한 없음)', () => {
let s = tick(rig(3));
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'chat', text: `${p} 설명` }, T0 + 20_000);
expect(speaker(s)).toBe('P2');
s = act(s, 'P2', { type: 'chat', text: '또 설명' }, T0 + 20_000);
expect(speaker(s)).toBe('P1');
});
test('한 바퀴 옵션, 시간 초과는 넘김, 설명은 80자까지', () => {
let s = tick(rig(3, { rounds: 1, describeSeconds: 15 }));
expect(s.phase.kind === 'describe' && s.phase.endsAt - s.phase.startedAt).toBe(15_000);
expect(reject(s, 'P0', { type: 'chat', text: '가'.repeat(81) })).toContain('80자');
s = tick(s);
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
s = act(s, 'P1', { type: 'chat', text: '좋아요' });
s = tick(s);
expect(s.phase.kind).toBe('discussion');
});
test('제시어를 직접 말하면 안 돼요(띄어쓰기 무시). 라이어는 막지 않아요(막으면 정답이 새요)', () => {
let s = tick(rig(3, { rounds: 1 }, { liarIdx: 1 }));
expect(reject(s, 'P0', { type: 'chat', text: '수 박 맛있어요' })).toBe('제시어를 직접 말하면 안 돼요.');
s = act(s, 'P0', { type: 'chat', text: '여름이면 생각나요' });
s = act(s, 'P1', { type: 'chat', text: '수박 같아요' }); // the liar's guess-like line goes through
expect(s.descriptions.at(-1)!.text).toBe('수박 같아요');
});
test('바보 모드 라이어는 자기 단어를 직접 말하면 막혀요(시민과 똑같이)', () => {
const s = tick(rig(3, { foolMode: true, rounds: 1 }, { liarIdx: 0 }));
expect(reject(s, 'P0', { type: 'chat', text: '참외' })).toBe('제시어를 직접 말하면 안 돼요.');
});
test('확인 시간·정답 맞히기 중에는 채팅을 못 쓰고, 토론·투표 중에는 모두 써요', () => {
let s = rig(3);
expect(reject(s, 'P0', { type: 'chat', text: '안녕' })).toContain('확인하는 중');
s = until(s, 'discussion');
s = act(s, 'P1', { type: 'chat', text: '누구지' });
expect(reject(s, 'P1', { type: 'chat', text: '또' }, at(s) - 1000 + 100)).toBe('조금 천천히 보내 주세요.');
s = until(s, 'vote');
s = act(s, 'P2', { type: 'chat', text: '투표해요' });
expect(s.chat.map((m) => m.text)).toEqual(['누구지', '투표해요']);
});
});
// ---------------------------------------------------------------- discussion and vote
describe('토론과 투표 (§5.3~5.5)', () => {
test('토론은 모두 [토론 끝내기]를 누르면 바로 투표로', () => {
let s = until(rig(3), 'discussion');
s = act(s, 'P0', { type: 'ready' });
s = act(s, 'P1', { type: 'ready' });
expect(liar.view(s, 'P2').phase).toMatchObject({ readyCount: 2, readyNeeded: 3 });
s = act(s, 'P2', { type: 'ready' });
expect(s.phase).toMatchObject({ kind: 'vote', round: 1 });
});
test('모두 투표하면 바로 집계, 시민이 지목되면 라이어 승리', () => {
let s = until(rig(4), 'vote');
expect(reject(s, 'P0', { type: 'vote', target: 'P0' })).toBe('나 자신은 지목할 수 없어요.');
s = votes(s, { P0: 'P1', P1: 'P2', P2: 'P1' });
expect(liar.view(s, 'P0').players.map((p) => p.voted)).toEqual([true, true, true, false]);
expect(liar.view(s, 'P0').phase.votedCount).toBe(3);
s = votes(s, { P3: 'P1' });
expect(s.phase.kind).toBe('ended');
expect(lastEv(s, 'vote')).toMatchObject({ round: 1, accused: 'P1', tally: { P1: 3, P2: 1 } });
expect(lastEv(s, 'accused')).toMatchObject({ p: 'P1', liar: false });
expect(s.final).toMatchObject({ winner: 'liar', reason: 'escaped', liar: 'P3', word: '수박' });
const r = liar.result(s)!;
expect(r.ranking).toEqual([['P3'], ['P0', 'P1', 'P2']]);
expect(r.scoreText).toEqual({ P0: '시민 · 0점', P1: '시민 · 0점', P2: '시민 · 0점', P3: '라이어 · 2점' });
expect(r.summary).toBe("라이어 승리! 라이어가 아닌 사람이 지목됐어요. 제시어는 '수박'이었어요.");
});
test('동점이면 동점자끼리 재투표 한 번, 또 동점이면 라이어 승리', () => {
let s = until(rig(4), 'vote');
s = votes(s, { P0: 'P1', P1: 'P0', P2: 'P3', P3: 'P2' });
expect(s.phase).toMatchObject({ kind: 'vote', round: 2, candidates: ['P0', 'P1', 'P2', 'P3'] });
s = until(rig(4), 'vote');
s = votes(s, { P0: 'P1', P1: 'P0', P2: 'P1', P3: 'P0' });
expect(s.phase).toMatchObject({ kind: 'vote', round: 2, candidates: ['P0', 'P1'] });
expect(lastEv(s, 'vote')).toMatchObject({ accused: null, tied: ['P0', 'P1'] });
expect(reject(s, 'P2', { type: 'vote', target: 'P3' })).toBe('재투표는 동점인 사람 중에서만 골라요.');
// P0 and P1 can only vote for each other.
expect(liar.view(s, 'P0').my!.voteTargets).toEqual(['P1']);
s = votes(s, { P0: 'P1', P1: 'P0', P2: 'P0', P3: 'P1' });
expect(s.final).toMatchObject({ winner: 'liar', reason: 'tie' });
});
test('아무도 투표하지 않으면 모두 동점: 재투표, 또 없으면 라이어 승리', () => {
let s = until(rig(3), 'vote');
s = tick(s);
expect(s.phase).toMatchObject({ kind: 'vote', round: 2, candidates: ['P0', 'P1', 'P2'] });
s = tick(s);
expect(s.final).toMatchObject({ winner: 'liar', reason: 'tie' });
});
test('라이어가 지목되면 정답 맞히기: 맞히면 라이어, 틀리거나 시간이 지나면 시민 승리', () => {
const toGuess = (o: Record<string, unknown> = {}) => votes(until(rig(4, o), 'vote'), { P0: 'P3', P1: 'P3', P2: 'P3', P3: 'P0' });
let s = toGuess();
expect(s.phase.kind).toBe('guess');
expect(lastEv(s, 'accused')).toMatchObject({ p: 'P3', liar: true });
expect(reject(s, 'P0', { type: 'guess', text: '수박' })).toBe('라이어만 맞힐 수 있어요.');
expect(reject(s, 'P0', { type: 'chat', text: '힌트' })).toContain('맞히는 중');
const right = act(s, 'P3', { type: 'guess', text: ' 수 박 ' });
expect(right.final).toMatchObject({ winner: 'liar', reason: 'guessed', guess: '수 박' });
expect(liar.result(right)!.ranking).toEqual([['P3'], ['P0', 'P1', 'P2']]);
const wrong = act(s, 'P3', { type: 'guess', text: '참외' });
expect(wrong.final).toMatchObject({ winner: 'citizens', reason: 'caught' });
expect(liar.result(wrong)!.scoreText!.P0).toBe('시민 · 1점');
expect(liar.result(wrong)!.summary).toBe("시민 승리! 라이어를 찾아냈고, 라이어가 제시어 '수박'을 맞히지 못했어요.");
s = tick(s);
expect(s.final).toMatchObject({ winner: 'citizens', reason: 'caught', guess: null });
expect(lastEv(s, 'guess')).toMatchObject({ text: null, correct: false });
// Choice mode: only words of the topic.
s = toGuess({ guessMode: 'choice' });
const choices = liar.view(s, 'P3').phase.choices;
expect(choices).toContain('수박');
expect(choices).toHaveLength(topicById('fruit').words.length);
expect(reject(s, 'P3', { type: 'guess', text: '고양이' })).toBe('목록에 있는 단어를 골라 주세요.');
expect(act(s, 'P3', { type: 'guess', text: '수박' }).final!.winner).toBe('liar');
});
});
// ---------------------------------------------------------------- leaving
describe('나가기 (§8.5)', () => {
test('설명 차례인 사람이 나가면 다음 사람, 이후 차례·투표에서 빠져요', () => {
let s = tick(rig(4, { rounds: 1 }));
s = act(s, 'P0', { type: 'leave' });
expect(speaker(s)).toBe('P1');
s = until(s, 'vote');
expect(liar.view(s, 'P1').my!.voteTargets).toEqual(['P2', 'P3']);
s = votes(s, { P1: 'P3', P2: 'P3', P3: 'P1' });
expect(s.phase.kind).toBe('guess');
});
test('라이어가 나가면 시민 승리, 시민이 모두 나가면 라이어 승리', () => {
const s = tick(rig(3));
expect(act(s, 'P2', { type: 'leave' }).final).toMatchObject({ winner: 'citizens', reason: 'liarLeft' });
const t = act(act(s, 'P0', { type: 'leave' }), 'P1', { type: 'leave' });
expect(t.final).toMatchObject({ winner: 'liar', reason: 'citizensLeft' });
expect(liar.result(t)!.ranking).toEqual([['P2'], ['P0', 'P1']]);
});
test('투표 중 나가면 그 사람 표와 그 사람에게 간 표가 빠지고, 남은 사람이 다 투표하면 바로 집계', () => {
let s = until(rig(4), 'vote');
s = votes(s, { P1: 'P0', P2: 'P3', P3: 'P2' });
s = act(s, 'P0', { type: 'leave' });
expect(s.phase.kind === 'vote' && s.phase.votes).toEqual({ P2: 'P3', P3: 'P2' });
expect(liar.view(s, 'P1').my!.vote).toBeNull();
s = votes(s, { P1: 'P3' });
expect(s.phase.kind).toBe('guess');
// Everybody else already voted: the leaver's departure closes the vote at once.
let t = until(rig(4), 'vote');
t = votes(t, { P1: 'P3', P2: 'P3', P3: 'P1' });
t = act(t, 'P0', { type: 'leave' });
expect(t.phase.kind).toBe('guess');
});
});
// ---------------------------------------------------------------- engine checks
describe('무작위 대국 (엔진 공통 검사)', () => {
const variants: Record<string, unknown>[] = [{}, { foolMode: true }, { rounds: 1, guessMode: 'choice' }, { foolMode: true, topic: 'fairy', guessMode: 'choice' }];
for (const [i, o] of variants.entries()) {
test(`옵션 ${JSON.stringify(o)}: 3~10명, 끝까지·유출 없음·JSON 왕복`, () => {
for (let k = 1; k <= playoutSeeds(40); k++) {
const n = 3 + (k % 8);
const r = randomPlayout(liar, { players: ids(n), options: opts(o), seed: seedN(i * 1000 + k), maxSteps: 3000 });
expect(r.finished).toBe(true);
const res = liar.result(r.finalState as LiarState)!;
expect(res.ranking.flat().sort()).toEqual(ids(n).sort());
}
});
}
test('결정적: 같은 시드면 같은 판', () => {
const a = randomPlayout(liar, { players: ids(5), seed: seedN(7) });
const b = randomPlayout(liar, { players: ids(5), seed: seedN(7) });
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
});
});