Files
joke-app/packages/games/src/liar/liar.test.ts

477 lines
24 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('주제 23개 이상 × 단어 50개 이상 × 설명 4개 이상, 옵션의 주제와 같아요', () => {
expect(TOPICS.length).toBeGreaterThanOrEqual(23);
expect(TOPICS.map((t) => t.id)).toEqual([...TOPIC_IDS]);
for (const t of TOPICS) {
expect(t.words.length, t.id).toBeGreaterThanOrEqual(50);
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) {
const ns = t.words.map((w) => normalize(w.word));
for (const a of ns) for (const b of ns) if (a !== b) expect(b.includes(a), `${t.id}: ${a} ⊂ ${b}`).toBe(false);
}
});
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: 'describe', 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: 'describe', text: '저도요' })).toBe('지금은 설명 차례인 사람만 설명할 수 있어요.');
s = act(s, sp, { type: 'describe', 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: 'describe', text: `${p} 설명` }, T0 + 20_000);
expect(speaker(s)).toBe('P2');
s = act(s, 'P2', { type: 'describe', 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: 'describe', text: '가'.repeat(81) })).toContain('80자');
s = tick(s);
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
s = act(s, 'P1', { type: 'describe', 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: 'describe', text: '수 박 맛있어요' })).toBe('제시어를 직접 말하면 안 돼요.');
expect(reject(s, 'P2', { type: 'chat', text: '수 박 맛있어요' })).toBe('제시어를 직접 말하면 안 돼요.');
s = act(s, 'P0', { type: 'describe', text: '여름이면 생각나요' });
s = act(s, 'P1', { type: 'describe', 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: 'describe', text: '참외' })).toBe('제시어를 직접 말하면 안 돼요.');
expect(reject(s, 'P0', { type: 'chat', text: '참외' })).toBe('제시어를 직접 말하면 안 돼요.');
});
test('토론 채팅은 게임 내내 열려 있어요: 확인 시간·설명 중(말하는 사람 포함)에도 쓰고, 설명으로 치지 않아요', () => {
let s = rig(3);
s = act(s, 'P0', { type: 'chat', text: '안녕' });
expect(s.phase.kind).toBe('reveal');
s = tick(s);
expect(speaker(s)).toBe('P0');
s = act(s, 'P1', { type: 'chat', text: '첫 사람 누구예요' });
s = act(s, 'P0', { type: 'chat', text: '저요 잠깐만요' });
expect(speaker(s)).toBe('P0');
expect(s.descriptions).toEqual([]);
expect(liar.view(s, 'P2').my).toMatchObject({ canChat: true, chatWhy: null, canDescribe: false });
expect(reject(s, 'P1', { type: 'describe', text: '저도요' })).toBe('지금은 설명 차례인 사람만 설명할 수 있어요.');
expect(s.chat.map((m) => m.text)).toEqual(['안녕', '첫 사람 누구예요', '저요 잠깐만요']);
s = until(s, 'discussion');
expect(reject(s, 'P0', { type: 'describe', text: '늦은 설명' })).toBe('지금은 설명하는 때가 아니에요.');
s = { ...s, chat: [] };
const t = at(s);
// No pace limit: any number of lines at the same moment all go through.
for (let i = 0; i < 20; i++) s = act(s, 'P1', { type: 'chat', text: `누구지 ${i}` }, t);
s = until(s, 'vote');
s = act(s, 'P2', { type: 'chat', text: '투표해요' });
expect(s.chat.map((m) => m.text)).toEqual([...Array.from({ length: 20 }, (_, i) => `누구지 ${i}`), '투표해요']);
});
});
// ---------------------------------------------------------------- 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('라이어만 맞힐 수 있어요.');
s = act(s, 'P0', { type: 'chat', text: '못 맞힐걸요' }); // the chat stays open while the liar guesses
expect(s.phase.kind).toBe('guess');
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');
});
});
describe('시간 무제한 (§8.5)', () => {
const U = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null };
test('설명·토론·투표·맞히기 모두 무제한: 마감 없이 할 일을 마칠 때까지, 기다리는 사람만 시간 초과 대상', () => {
let s = tick(rig(3, { ...U, rounds: 1 }));
expect(s.phase.kind === 'describe' && s.phase.endsAt).toBeNull();
expect(liar.deadline!(s)).toBeNull();
expect(liar.timeoutPlayers!(s)).toEqual(['P0']);
expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.');
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'describe', text: `${p} 설명` }, T0 + 3_600_000);
expect(s.phase.kind).toBe('discussion');
expect(liar.timeoutPlayers!(s)).toEqual(['P0', 'P1', 'P2']);
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'ready' });
expect(s.phase.kind).toBe('vote');
s = votes(s, { P0: 'P2', P1: 'P2' });
expect(liar.timeoutPlayers!(s)).toEqual(['P2']);
s = act(s, 'P2', { type: 'vote', target: 'P0' });
expect(s.phase.kind).toBe('guess');
expect(liar.timeoutPlayers!(s)).toEqual(['P2']);
s = act(s, 'P2', { type: 'guess', text: '수박' }, T0 + 7_200_000);
expect(s.final!.reason).toBe('guessed');
});
test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김: 설명 넘김·토론 끝·표 없음·답 없음', () => {
let s = tick(rig(4, { ...U, rounds: 1 }));
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'describe', text: `${p} 설명` });
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'ready' });
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
expect(s.phase.kind).toBe('vote');
s = votes(s, { P1: 'P3', P2: 'P3', P3: 'P1' });
expect(liar.view(s, null).players.find((p) => p.id === 'P0')!.voted).toBe(false);
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
expect(lastEv(s, 'vote')).toMatchObject({ accused: 'P3', votes: { P1: 'P3', P2: 'P3', P3: 'P1' } });
s = act(s, 'P3', liar.onTimeout(s, 'P3'));
expect(s.final).toMatchObject({ winner: 'citizens', reason: 'caught', guess: null });
});
test('무작위 대국(모두 무제한)도 끝나요', () => {
for (let k = 1; k <= playoutSeeds(40); k++) {
const n = 3 + (k % 8);
const r = randomPlayout(liar, { players: ids(n), options: opts(U), seed: seedN(5000 + k), maxSteps: 3000 });
expect(r.finished).toBe(true);
}
});
});
// ---------------------------------------------------------------- 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));
});
});