새 게임 라이어 게임: 규칙 엔진·말하는 컴퓨터·화면·도움말·문서·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>
This commit is contained in:
@@ -9,6 +9,7 @@
|
||||
"./marble/board": "./src/marble/board.ts",
|
||||
"./clue/board": "./src/clue/board.ts",
|
||||
"./bots/luck": "./src/bots/luck.ts",
|
||||
"./liar/topics": "./src/liar/topics.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -35,6 +35,7 @@ import { appleBot } from '../apple/bot';
|
||||
import { clueBot } from '../clue/bot';
|
||||
import { connectFourBot } from '../connect-four/bot';
|
||||
import { unoBot } from '../uno/bot';
|
||||
import { liarBot } from '../liar/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
@@ -106,8 +107,9 @@ export function decideBotAction(
|
||||
return rest.length ? pick(playable(rest), random) : null;
|
||||
}
|
||||
|
||||
/** Live strategies (games where everybody acts at once: 마피아 talks, 사과 게임 races on its own board); also in `BOT_GAMES`. */
|
||||
/** Live strategies (games where everybody acts at once: 마피아·라이어 게임 talk, 사과 게임 races on its own board); also in `BOT_GAMES`. */
|
||||
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
|
||||
mafia: mafiaBot,
|
||||
apple: appleBot,
|
||||
liar: liarBot,
|
||||
};
|
||||
|
||||
@@ -33,8 +33,8 @@ export function liveBotPlayout(
|
||||
names?: Record<PlayerId, string>;
|
||||
/** Override characters (tests): called once after setup with the game state. */
|
||||
personaOf?: (p: PlayerId, state: unknown) => BotPersona;
|
||||
/** Each computer's level (default: none, the strategy's own default). */
|
||||
levelOf?: (p: PlayerId) => BotLevel;
|
||||
/** Each computer's level 1~60 (default: none, the strategy's own default). */
|
||||
levelOf?: (p: PlayerId, state: unknown) => BotLevel;
|
||||
maxMs?: number;
|
||||
},
|
||||
): LivePlayoutReport {
|
||||
@@ -48,6 +48,7 @@ export function liveBotPlayout(
|
||||
const bots = opts.players.filter(opts.isBot);
|
||||
const persona = new Map(bots.map((b) => [b, opts.personaOf?.(b, state) ?? botPersona(b)]));
|
||||
const memory = new Map(bots.map((b) => [b, {} as Record<string, unknown>]));
|
||||
const level = new Map(bots.map((b) => [b, opts.levelOf?.(b, state)]));
|
||||
const due = new Map(bots.map((b) => [b, now + 500 + random() * 1000]));
|
||||
const rep: LivePlayoutReport = { finished: false, state, actions: 0, rejected: [], chat: [], maxBotMs: 0, elapsed: 0 };
|
||||
const maxMs = opts.maxMs ?? 3 * 3600_000;
|
||||
@@ -74,7 +75,7 @@ export function liveBotPlayout(
|
||||
if (bot === null) throw new Error(`${def.id}: stalled`);
|
||||
now = Math.max(now, due.get(bot)!);
|
||||
const t0 = performance.now();
|
||||
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, level: opts.levelOf?.(bot), names, memory: memory.get(bot)! });
|
||||
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, level: level.get(bot), names, memory: memory.get(bot)! });
|
||||
rep.maxBotMs = Math.max(rep.maxBotMs, performance.now() - t0);
|
||||
due.set(bot, now + Math.max(50, d.next));
|
||||
if (d.action) {
|
||||
|
||||
@@ -30,6 +30,7 @@ import { apple } from './apple';
|
||||
import { clue } from './clue';
|
||||
import { connectFour } from './connect-four';
|
||||
import { uno } from './uno';
|
||||
import { liar } from './liar';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -63,4 +64,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[clue.id]: clue,
|
||||
[connectFour.id]: connectFour,
|
||||
[uno.id]: uno,
|
||||
[liar.id]: liar,
|
||||
};
|
||||
|
||||
142
packages/games/src/liar/bot.test.ts
Normal file
142
packages/games/src/liar/bot.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
/** 라이어 게임 computers (docs/games/liar.md §13): legal, never stuck, never leak, and higher levels play better. */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { botPace, botPersona, type BotPersona } from '../bots/persona';
|
||||
import { liveBotPlayout } from '../bots/live-playout';
|
||||
import { chatProblem } from '../mafia';
|
||||
import { _internal, liarBot } from './bot';
|
||||
import { liar, liarOptionsSchema, saysWord, topicById, type LiarOptions, type LiarState } from './index';
|
||||
|
||||
const { LiarBot, fill } = _internal;
|
||||
const isBot = (p: string) => p.startsWith('bot:');
|
||||
const seats = (n: number, humans: number) => Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:t${i}`));
|
||||
const opts = (o: Partial<LiarOptions> = {}) => liarOptionsSchema.parse(o);
|
||||
const persona = (smart: boolean, p: string): BotPersona => ({ smart, pace: botPace(p), chatty: 0.8 });
|
||||
|
||||
describe('lines', () => {
|
||||
test('josa follows the name', () => {
|
||||
expect(fill('{X:이} 라이어 같아요', { X: '컴퓨터 3님' })).toBe('컴퓨터 3님이 라이어 같아요');
|
||||
expect(fill('{X:이랑} 같은 생각', { X: '철수' })).toBe('철수랑 같은 생각');
|
||||
expect(fill('{X:은} 아닌듯?', { X: '3번' })).toBe('3번은 아닌듯?');
|
||||
});
|
||||
});
|
||||
|
||||
describe('whole games', () => {
|
||||
const variants: [string, Partial<LiarOptions>][] = [
|
||||
['default', {}],
|
||||
['바보 모드, 한 바퀴, 고르기', { foolMode: true, rounds: 1, guessMode: 'choice' }],
|
||||
['짧은 시간', { describeSeconds: 15, discussionSeconds: 30, voteSeconds: 15, guessSeconds: 20, topic: 'fairy' }],
|
||||
];
|
||||
for (const [label, o] of variants) {
|
||||
test(`${label}: 3~10명, 사람 1명(가만히) + 컴퓨터, 컴퓨터만 — 모두 끝나고, 거절된 행동 없음, 제시어를 말하지 않음`, () => {
|
||||
for (const n of [3, 5, 8, 10]) {
|
||||
for (const humans of [1, 0]) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(n, humans), options: opts(o), seed: seedN(n * 10 + humans), isBot });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
expect(r.maxBotMs).toBeLessThan(50);
|
||||
const st = r.state as LiarState;
|
||||
for (const line of r.chat) {
|
||||
expect(chatProblem(line.text, true)).toBeNull();
|
||||
expect(line.text).not.toMatch(/undefined|null|NaN|\{|bot:/);
|
||||
// Nobody says their own word (the game refuses it; bots never even try).
|
||||
const own = line.from === st.liar ? st.liarWord : st.word;
|
||||
if (own) expect(saysWord(line.text, st.topic, own)).toBe(false);
|
||||
}
|
||||
// Every computer described on its turn (none ran out of time).
|
||||
const bots = st.players.filter((p) => isBot(p.id)).map((p) => p.id);
|
||||
for (const d of st.descriptions) if (bots.includes(d.from)) expect(d.text).not.toBeNull();
|
||||
expect(st.descriptions.length).toBe(n * st.options.rounds);
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test('컴퓨터는 토론 때 말하고, 라이어 컴퓨터는 자기를 지목하지 않아요', () => {
|
||||
for (let s = 1; s <= 10; s++) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(6, 0), seed: seedN(300 + s), isBot });
|
||||
const st = r.state as LiarState;
|
||||
expect(st.chat.length).toBeGreaterThan(0);
|
||||
const lastVote = st.events.filter((e) => e.t === 'vote').at(-1);
|
||||
if (lastVote && lastVote.t === 'vote') expect(lastVote.votes[st.liar]).not.toBe(st.liar);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('레벨이 높은 컴퓨터가 더 잘해요: 똑똑한 시민이 라이어를 더 자주 잡고, 똑똑한 라이어가 더 자주 맞혀요', () => {
|
||||
const run = (citizenLevel: number, liarLevel: number) => {
|
||||
let citizens = 0;
|
||||
let guessed = 0;
|
||||
let caught = 0;
|
||||
const n = 40;
|
||||
for (let s = 1; s <= n; s++) {
|
||||
const r = liveBotPlayout(liar, liarBot, {
|
||||
players: seats(5, 0),
|
||||
seed: seedN(1000 + s),
|
||||
isBot,
|
||||
personaOf: (p, st) => persona(((st as LiarState).liar === p ? liarLevel : citizenLevel) > 30, p),
|
||||
levelOf: (p, st) => ((st as LiarState).liar === p ? liarLevel : citizenLevel),
|
||||
});
|
||||
const f = (r.state as LiarState).final!;
|
||||
if (f.winner === 'citizens') citizens++;
|
||||
if (f.accused === f.liar) caught++;
|
||||
if (f.reason === 'guessed') guessed++;
|
||||
}
|
||||
return { citizens: citizens / n, caught: caught / n, guessed };
|
||||
};
|
||||
const strongTown = run(60, 1);
|
||||
const weakTown = run(1, 60);
|
||||
expect(strongTown.caught).toBeGreaterThan(weakTown.caught);
|
||||
expect(strongTown.citizens - weakTown.citizens).toBeGreaterThan(0.2);
|
||||
// A strong liar who is caught names the word more often than a weak one.
|
||||
const strongLiar = run(30, 60);
|
||||
const weakLiar = run(30, 1);
|
||||
expect(strongLiar.guessed).toBeGreaterThan(weakLiar.guessed);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe('reading', () => {
|
||||
function atDiscussion(o: Partial<LiarOptions> = {}) {
|
||||
const players = seats(5, 0);
|
||||
let st = liar.setup({ players, options: opts({ topic: 'fruit', rounds: 1, ...o }), rng: SeededRng.fromSeed(seedN(3)), now: 0 });
|
||||
st.word = '수박';
|
||||
st.liar = players[4]!;
|
||||
st.order = [...players];
|
||||
const hints = topicById('fruit').words.find((w) => w.word === '수박')!.hints;
|
||||
const rng = SeededRng.fromSeed(seedN(4));
|
||||
let now = 0;
|
||||
st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now: (now = st.phase.kind === 'reveal' ? st.phase.endsAt : 0) }).state;
|
||||
for (let i = 0; i < 4; i++) st = liar.apply(st, players[i]!, { type: 'chat', text: hints[i]! }, { rng, now: (now += 2000) }).state;
|
||||
st = liar.apply(st, players[4]!, { type: 'chat', text: '저는 좋아하는 편이에요' }, { rng, now: (now += 2000) }).state;
|
||||
const names = Object.fromEntries(players.map((p, i) => [p, `컴퓨터 ${i + 1}`]));
|
||||
return { st, players, names, now };
|
||||
}
|
||||
|
||||
test('라이어 컴퓨터(높은 레벨)는 설명을 듣고 제시어를 맞혀요', () => {
|
||||
const { st, players, names, now } = atDiscussion();
|
||||
const me = players[4]!;
|
||||
const bot = new LiarBot({ me, view: liar.view(st, me), now, random: Math.random, persona: botPersona(me, 50), level: 60, names, memory: {} });
|
||||
expect(bot.guessWord()).toBe('수박');
|
||||
});
|
||||
|
||||
test('시민 컴퓨터(높은 레벨)는 제시어와 안 맞는 설명을 한 사람을 가장 의심해요', () => {
|
||||
const { st, players, names, now } = atDiscussion();
|
||||
const me = players[0]!;
|
||||
const bot = new LiarBot({ me, view: liar.view(st, me), now, random: Math.random, persona: botPersona(me, 50), level: 60, names, memory: {} });
|
||||
const others = players.slice(1);
|
||||
const top = others.sort((a, b) => bot.sus(b) - bot.sus(a))[0];
|
||||
expect(top).toBe(players[4]);
|
||||
expect(bot.stance('컴퓨터 5 라이어 아니야?').accused).toEqual([players[4]!]);
|
||||
expect(bot.stance('컴퓨터 2님은 맞게 설명한 것 같아요').cleared).toEqual([players[1]!]);
|
||||
});
|
||||
|
||||
test('라이어 컴퓨터가 먼저 말하면 주제에 다 맞는 무난한 말을 해요', () => {
|
||||
const players = seats(4, 0);
|
||||
let st = liar.setup({ players, options: opts({ topic: 'animal' }), rng: SeededRng.fromSeed(seedN(5)), now: 0 });
|
||||
st.order = [...players];
|
||||
st.liar = players[0]!;
|
||||
st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng: SeededRng.fromSeed(seedN(6)), now: 10_000 }).state;
|
||||
const names = Object.fromEntries(players.map((p, i) => [p, `컴퓨터 ${i + 1}`]));
|
||||
const bot = new LiarBot({ me: players[0]!, view: liar.view(st, players[0]!), now: 10_000, random: Math.random, persona: botPersona(players[0]!, 50), level: 50, names, memory: {} });
|
||||
expect(topicById('animal').generic).toContain(bot.description());
|
||||
});
|
||||
});
|
||||
501
packages/games/src/liar/bot.ts
Normal file
501
packages/games/src/liar/bot.ts
Normal file
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* 라이어 게임 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>();
|
||||
|
||||
function model(id: LiarView['topic']): TopicModel {
|
||||
const hit = models.get(id);
|
||||
if (hit) return hit;
|
||||
const topic = topicById(id);
|
||||
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 };
|
||||
models.set(id, 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
|
||||
|
||||
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.topic);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private get phaseLen(): number {
|
||||
return Math.max(1000, (this.v.phase.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: 'chat', 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)]!;
|
||||
}
|
||||
|
||||
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 };
|
||||
562
packages/games/src/liar/index.ts
Normal file
562
packages/games/src/liar/index.ts
Normal file
@@ -0,0 +1,562 @@
|
||||
/**
|
||||
* 라이어 게임 (docs/games/liar.md). Pure and deterministic; state is JSON.
|
||||
*
|
||||
* Phases run on the server clock like 마피아: every phase has `endsAt`, and the room applies the system-only
|
||||
* `phaseTimeout` there (one "driver" player; `timeoutNotBefore` keeps an away driver from firing it early).
|
||||
* 제시어 확인 → 차례대로 한 문장 설명(바퀴 수만큼, 두 번째 바퀴는 거꾸로) → 자유 토론 → 투표(동점이면 동점자끼리 재투표 한 번,
|
||||
* 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
|
||||
*
|
||||
* Secrecy (§8.3): the view gives citizens the word and the liar only the topic (바보 모드: a different word of the topic,
|
||||
* and the liar is told "시민" like everybody else). Who the liar is never appears in any view before the reveal.
|
||||
*/
|
||||
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine';
|
||||
import { judge, normalize } from '../catchmind/text';
|
||||
import { chatProblem, cleanChat } from '../mafia';
|
||||
import {
|
||||
TOPIC_IDS,
|
||||
TOPIC_KO,
|
||||
liarActionSchema,
|
||||
liarOptionsSchema,
|
||||
type LiarAction,
|
||||
type LiarFinal,
|
||||
type LiarOptions,
|
||||
type LiarState,
|
||||
type LiarView,
|
||||
type MyView,
|
||||
type Phase,
|
||||
type PlayerState,
|
||||
type PublicEvent,
|
||||
type TopicId,
|
||||
type WinReason,
|
||||
} from './types';
|
||||
import { TOPICS, topicById, wordEntry } from './words';
|
||||
|
||||
export * from './types';
|
||||
export { TOPICS, topicById, wordEntry, type LiarTopic, type LiarWord } from './words';
|
||||
|
||||
export const REVEAL_MS = 10_000;
|
||||
export const CHAT_MAX = 200;
|
||||
/** One description is one sentence. */
|
||||
export const DESCRIBE_MAX = 80;
|
||||
export const CHAT_GAP_MS = 700;
|
||||
export const GUESS_MAX = 20;
|
||||
/** Points (docs §6): a citizen win gives every citizen 1, a liar win gives the liar 2. */
|
||||
export const CITIZEN_POINTS = 1;
|
||||
export const LIAR_POINTS = 2;
|
||||
const CHAT_KEEP = 300;
|
||||
const CHAT_VIEW = 150;
|
||||
const EVENTS_VIEW = 100;
|
||||
|
||||
// ---------------------------------------------------------------- Korean helpers
|
||||
|
||||
/** Does the word end in a consonant (받침)? Words of the bank are Hangul. */
|
||||
function batchim(word: string): boolean {
|
||||
const code = (word.trim().at(-1) ?? '').charCodeAt(0);
|
||||
return code >= 0xac00 && code <= 0xd7a3 && (code - 0xac00) % 28 !== 0;
|
||||
}
|
||||
|
||||
/** Words that count as saying `word` (the word and its 2+ letter aliases), normalized. */
|
||||
function spoken(topic: TopicId, word: string): string[] {
|
||||
const e = wordEntry(topic, word);
|
||||
return [word, ...(e?.aliases ?? [])].map(normalize).filter((x) => [...x].length >= 2);
|
||||
}
|
||||
|
||||
/** Does the text say the word (spaces, punctuation and case ignored)? */
|
||||
export function saysWord(text: string, topic: TopicId, word: string): boolean {
|
||||
const t = normalize(text);
|
||||
return spoken(topic, word).some((x) => t.includes(x));
|
||||
}
|
||||
|
||||
/** Is `text` the word (or an alias), ignoring spaces, case and a polite ending ("수박이요")? */
|
||||
export function isCorrectGuess(text: string, topic: TopicId, word: string): boolean {
|
||||
const e = wordEntry(topic, word);
|
||||
return judge(text, [word, ...(e?.aliases ?? [])], false) === 'correct';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
const P = (s: LiarState, id: PlayerId): PlayerState | undefined => s.players.find((p) => p.id === id);
|
||||
const present = (s: LiarState) => s.players.filter((p) => !p.left);
|
||||
const isPresent = (s: LiarState, id: PlayerId | null | undefined) => !!id && !!P(s, id) && !P(s, id)!.left;
|
||||
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
|
||||
|
||||
function pushEvent(s: LiarState, now: number, e: DistributiveOmit<PublicEvent, 'n' | 'at'>): void {
|
||||
s.events.push({ ...e, n: s.events.length + 1, at: now } as PublicEvent);
|
||||
}
|
||||
|
||||
/** Speaking order of a round: round 2 runs round 1 backwards. */
|
||||
export function roundOrder(s: Pick<LiarState, 'order'>, round: number): PlayerId[] {
|
||||
return round % 2 === 1 ? [...s.order] : [...s.order].reverse();
|
||||
}
|
||||
|
||||
function speakerOf(s: LiarState): PlayerId | null {
|
||||
const ph = s.phase;
|
||||
return ph.kind === 'describe' ? (roundOrder(s, ph.round)[ph.turn] ?? null) : null;
|
||||
}
|
||||
|
||||
/** The liar is known to everybody once accused (guess phase) or at the end. */
|
||||
const liarKnown = (s: LiarState) => s.phase.kind === 'guess' || s.final !== null;
|
||||
|
||||
/** Starts the describe turn at `turn` of `round` (skipping people who left), or the next round, or the discussion. */
|
||||
function nextTurn(s: LiarState, now: number, round: number, turn: number): void {
|
||||
for (let r = round; r <= s.options.rounds; r++) {
|
||||
const order = roundOrder(s, r);
|
||||
for (let t = r === round ? turn : 0; t < order.length; t++) {
|
||||
if (!isPresent(s, order[t])) continue;
|
||||
const fresh = s.phase.kind !== 'describe' || s.phase.round !== r;
|
||||
s.phase = { kind: 'describe', startedAt: now, endsAt: now + s.options.describeSeconds * 1000, round: r, turn: t };
|
||||
if (fresh) pushEvent(s, now, { t: 'phase', kind: 'describe', round: r });
|
||||
return;
|
||||
}
|
||||
}
|
||||
s.phase = { kind: 'discussion', startedAt: now, endsAt: now + s.options.discussionSeconds * 1000, ready: [] };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'discussion' });
|
||||
}
|
||||
|
||||
function startVote(s: LiarState, now: number, round: 1 | 2, candidates: PlayerId[]): void {
|
||||
s.phase = { kind: 'vote', startedAt: now, endsAt: now + s.options.voteSeconds * 1000, round, candidates, votes: {} };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'vote', round });
|
||||
}
|
||||
|
||||
/** Who `voter` may vote for now. */
|
||||
function voteTargets(s: LiarState, voter: PlayerId): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
if (ph.kind !== 'vote' || !isPresent(s, voter)) return [];
|
||||
return ph.candidates.filter((c) => c !== voter && isPresent(s, c));
|
||||
}
|
||||
|
||||
/** Present players who can vote (someone whose only candidate is themselves sits the revote out). */
|
||||
const voters = (s: LiarState) => present(s).filter((p) => voteTargets(s, p.id).length > 0);
|
||||
|
||||
const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && s.phase.votes[p.id] !== undefined);
|
||||
|
||||
function finish(s: LiarState, now: number, winner: 'liar' | 'citizens', reason: WinReason): void {
|
||||
const word = s.word;
|
||||
const tail = `제시어는 '${word}'${batchim(word) ? '이었어요' : '였어요'}.`;
|
||||
const summary: Record<WinReason, string> = {
|
||||
caught: `시민 승리! 라이어를 찾아냈고, 라이어가 제시어 '${word}'${batchim(word) ? '을' : '를'} 맞히지 못했어요.`,
|
||||
guessed: `라이어 승리! 라이어가 지목됐지만 제시어 '${word}'${batchim(word) ? '을' : '를'} 맞혔어요.`,
|
||||
escaped: `라이어 승리! 라이어가 아닌 사람이 지목됐어요. ${tail}`,
|
||||
tie: `라이어 승리! 투표가 두 번 동점이라 아무도 지목되지 않았어요. ${tail}`,
|
||||
liarLeft: `시민 승리! 라이어가 게임을 나갔어요. ${tail}`,
|
||||
citizensLeft: `라이어 승리! 시민이 모두 나갔어요. ${tail}`,
|
||||
};
|
||||
const scores: Record<PlayerId, number> = {};
|
||||
for (const p of s.players) {
|
||||
const isLiar = p.id === s.liar;
|
||||
scores[p.id] = p.left ? 0 : winner === 'liar' ? (isLiar ? LIAR_POINTS : 0) : isLiar ? 0 : CITIZEN_POINTS;
|
||||
}
|
||||
s.final = { winner, reason, liar: s.liar, topic: s.topic, word, liarWord: s.liarWord, accused: s.accused, guess: s.guess, scores, summary: summary[reason] };
|
||||
s.phase = { kind: 'ended' };
|
||||
pushEvent(s, now, { t: 'end', winner });
|
||||
}
|
||||
|
||||
function resolveVote(s: LiarState, now: number): void {
|
||||
const ph = s.phase as Extract<Phase, { kind: 'vote' }>;
|
||||
const cands = ph.candidates.filter((c) => isPresent(s, c));
|
||||
const tally: Record<PlayerId, number> = {};
|
||||
const votes: Record<PlayerId, PlayerId> = {};
|
||||
for (const p of present(s)) {
|
||||
const v = ph.votes[p.id];
|
||||
if (!v || !cands.includes(v) || v === p.id) continue;
|
||||
votes[p.id] = v;
|
||||
tally[v] = (tally[v] ?? 0) + 1;
|
||||
}
|
||||
const max = Math.max(0, ...Object.values(tally));
|
||||
// Nobody voted: everybody is tied.
|
||||
const tops = cands.length === 1 ? cands : max === 0 ? cands : cands.filter((c) => tally[c] === max);
|
||||
const accused = tops.length === 1 ? tops[0]! : null;
|
||||
pushEvent(s, now, { t: 'vote', round: ph.round, tally, votes, accused, tied: accused ? [] : tops });
|
||||
if (!accused) {
|
||||
if (ph.round === 1 && tops.length >= 2) startVote(s, now, 2, tops);
|
||||
else finish(s, now, 'liar', 'tie');
|
||||
return;
|
||||
}
|
||||
s.accused = accused;
|
||||
const isLiar = accused === s.liar;
|
||||
pushEvent(s, now, { t: 'accused', p: accused, liar: isLiar });
|
||||
if (!isLiar) return finish(s, now, 'liar', 'escaped');
|
||||
s.phase = { kind: 'guess', startedAt: now, endsAt: now + s.options.guessSeconds * 1000 };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'guess' });
|
||||
}
|
||||
|
||||
function resolveGuess(s: LiarState, now: number, text: string | null): void {
|
||||
s.guess = text;
|
||||
const correct = text !== null && isCorrectGuess(text, s.topic, s.word);
|
||||
pushEvent(s, now, { t: 'guess', text, correct });
|
||||
finish(s, now, correct ? 'liar' : 'citizens', correct ? 'guessed' : 'caught');
|
||||
}
|
||||
|
||||
/** The phase timer ran out (or everyone agreed to move on). */
|
||||
function advance(s: LiarState, now: number): void {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return nextTurn(s, now, 1, 0);
|
||||
case 'describe': {
|
||||
s.descriptions.push({ n: s.descriptions.length + 1, round: ph.round, from: speakerOf(s)!, text: null, at: now });
|
||||
return nextTurn(s, now, ph.round, ph.turn + 1);
|
||||
}
|
||||
case 'discussion':
|
||||
return startVote(
|
||||
s,
|
||||
now,
|
||||
1,
|
||||
present(s).map((p) => p.id),
|
||||
);
|
||||
case 'vote':
|
||||
return resolveVote(s, now);
|
||||
case 'guess':
|
||||
return resolveGuess(s, now, null);
|
||||
case 'ended':
|
||||
throw new Error('liar: advance after the end');
|
||||
}
|
||||
}
|
||||
|
||||
/** A player leaves mid-game: skipped from then on, the phase is repaired (§8.5). */
|
||||
function leave(s: LiarState, now: number, p: PlayerState): void {
|
||||
p.left = true;
|
||||
pushEvent(s, now, { t: 'left', p: p.id });
|
||||
if (p.id === s.liar) return finish(s, now, 'citizens', 'liarLeft');
|
||||
if (!present(s).some((x) => x.id !== s.liar)) return finish(s, now, 'liar', 'citizensLeft');
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
case 'discussion':
|
||||
ph.ready = ph.ready.filter((x) => x !== p.id);
|
||||
if (ph.ready.length > 0 && present(s).every((x) => ph.ready.includes(x.id))) advance(s, now);
|
||||
return;
|
||||
case 'describe':
|
||||
if (speakerOf(s) === p.id) nextTurn(s, now, ph.round, ph.turn + 1);
|
||||
return;
|
||||
case 'vote':
|
||||
delete ph.votes[p.id];
|
||||
for (const [k, v] of Object.entries(ph.votes)) if (v === p.id) delete ph.votes[k];
|
||||
ph.candidates = ph.candidates.filter((c) => c !== p.id);
|
||||
if (ph.candidates.length <= 1 || allVoted(s)) resolveVote(s, now);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- permissions
|
||||
|
||||
/** The word `p` holds: citizens the word, the liar nothing (바보 모드: the other word). */
|
||||
function wordOf(s: LiarState, id: PlayerId): string | null {
|
||||
return id === s.liar ? s.liarWord : s.word;
|
||||
}
|
||||
|
||||
/** Why `p` cannot write now (Korean), or null. */
|
||||
function chatBlock(s: LiarState, p: PlayerState): string | null {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'ended') return '게임이 끝났어요.';
|
||||
if (p.left) return '게임에서 나갔어요.';
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return '제시어를 확인하는 중이에요. 곧 설명이 시작돼요.';
|
||||
case 'describe':
|
||||
return speakerOf(s) === p.id ? null : '지금은 설명 차례인 사람만 말할 수 있어요.';
|
||||
case 'guess':
|
||||
return '라이어가 제시어를 맞히는 중이에요.';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- validate
|
||||
|
||||
function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: number }): Validation {
|
||||
const p = P(s, actor);
|
||||
if (!p) return fail('이 게임의 플레이어가 아니에요.');
|
||||
const ph = s.phase;
|
||||
if (s.final || ph.kind === 'ended') return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok;
|
||||
case 'leave':
|
||||
return p.left ? fail('이미 나갔어요.') : ok;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (p.left) return fail('게임에서 나갔어요.');
|
||||
switch (a.type) {
|
||||
case 'chat': {
|
||||
const block = chatBlock(s, p);
|
||||
if (block) return fail(block);
|
||||
const text = cleanChat(a.text);
|
||||
const max = ph.kind === 'describe' ? DESCRIBE_MAX : CHAT_MAX;
|
||||
if (ph.kind === 'describe' && [...text].length > max) return fail(`설명은 한 문장, ${max}자까지 쓸 수 있어요.`);
|
||||
const why = chatProblem(text, s.options.kidSafeChat);
|
||||
if (why) return fail(why);
|
||||
const mine = wordOf(s, actor);
|
||||
if (mine && saysWord(text, s.topic, mine)) return fail('제시어를 직접 말하면 안 돼요.');
|
||||
// Pace limit for free talk only: a description is one per turn anyway.
|
||||
if (ph.kind !== 'describe' && ctx && ctx.now - (s.lastChatAt[actor] ?? -Infinity) < CHAT_GAP_MS) return fail('조금 천천히 보내 주세요.');
|
||||
return ok;
|
||||
}
|
||||
case 'ready':
|
||||
if (ph.kind !== 'reveal' && ph.kind !== 'discussion') return fail('지금은 넘길 수 있는 때가 아니에요.');
|
||||
return ph.ready.includes(actor) ? fail('이미 눌렀어요. 다른 사람을 기다려 주세요.') : ok;
|
||||
case 'vote':
|
||||
if (ph.kind !== 'vote') return fail('지금은 투표 시간이 아니에요.');
|
||||
if (a.target === actor) return fail('나 자신은 지목할 수 없어요.');
|
||||
if (!voteTargets(s, actor).includes(a.target)) return fail(ph.round === 2 ? '재투표는 동점인 사람 중에서만 골라요.' : '이 게임에 있는 사람만 지목할 수 있어요.');
|
||||
return ok;
|
||||
case 'guess': {
|
||||
if (ph.kind !== 'guess') return fail('지금은 제시어를 맞히는 시간이 아니에요.');
|
||||
if (actor !== s.liar) return fail('라이어만 맞힐 수 있어요.');
|
||||
const text = cleanChat(a.text);
|
||||
if (!text) return fail('제시어를 적어 주세요.');
|
||||
if ([...text].length > GUESS_MAX) return fail(`${GUESS_MAX}자까지 적을 수 있어요.`);
|
||||
if (s.options.guessMode === 'choice' && !topicById(s.topic).words.some((x) => x.word === text)) return fail('목록에 있는 단어를 골라 주세요.');
|
||||
return ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
function myView(s: LiarState, me: PlayerState): MyView {
|
||||
const ph = s.phase;
|
||||
const isLiar = me.id === s.liar;
|
||||
const knowsLiar = isLiar && (!s.options.foolMode || liarKnown(s));
|
||||
const block = chatBlock(s, me);
|
||||
const readyPhase = ph.kind === 'reveal' || ph.kind === 'discussion';
|
||||
return {
|
||||
role: knowsLiar ? 'liar' : 'citizen',
|
||||
word: wordOf(s, me.id),
|
||||
canDescribe: ph.kind === 'describe' && !me.left && speakerOf(s) === me.id,
|
||||
canChat: !block,
|
||||
chatWhy: block,
|
||||
canReady: readyPhase && !me.left && !ph.ready.includes(me.id),
|
||||
ready: readyPhase && ph.ready.includes(me.id),
|
||||
vote: ph.kind === 'vote' ? (ph.votes[me.id] ?? null) : null,
|
||||
voteTargets: voteTargets(s, me.id),
|
||||
canGuess: ph.kind === 'guess' && isLiar && !me.left,
|
||||
};
|
||||
}
|
||||
|
||||
function view(s: LiarState, viewer: PlayerId | null): LiarView {
|
||||
const me = viewer ? (P(s, viewer) ?? null) : null;
|
||||
const ph = s.phase;
|
||||
const known = liarKnown(s);
|
||||
const readyPhase = ph.kind === 'reveal' || ph.kind === 'discussion';
|
||||
return {
|
||||
me: me?.id ?? null,
|
||||
options: s.options,
|
||||
topic: s.topic,
|
||||
topicKo: TOPIC_KO[s.topic],
|
||||
phase: {
|
||||
kind: ph.kind,
|
||||
startedAt: ph.kind === 'ended' ? 0 : ph.startedAt,
|
||||
endsAt: ph.kind === 'ended' ? null : ph.endsAt,
|
||||
round: ph.kind === 'describe' ? ph.round : 0,
|
||||
speaker: speakerOf(s),
|
||||
turnOrder: ph.kind === 'describe' ? roundOrder(s, ph.round) : [],
|
||||
turn: ph.kind === 'describe' ? ph.turn : 0,
|
||||
readyCount: readyPhase ? ph.ready.length : 0,
|
||||
readyNeeded: readyPhase ? present(s).length : 0,
|
||||
voteRound: ph.kind === 'vote' ? ph.round : null,
|
||||
candidates: ph.kind === 'vote' ? [...ph.candidates] : [],
|
||||
votedCount: ph.kind === 'vote' ? Object.keys(ph.votes).length : 0,
|
||||
liar: ph.kind === 'guess' ? s.liar : null,
|
||||
choices: ph.kind === 'guess' && s.options.guessMode === 'choice' ? topicById(s.topic).words.map((x) => x.word).sort((a, b) => a.localeCompare(b, 'ko')) : [],
|
||||
},
|
||||
rounds: s.options.rounds,
|
||||
order: [...s.order],
|
||||
players: s.players.map((p) => ({
|
||||
id: p.id,
|
||||
left: p.left,
|
||||
voted: ph.kind === 'vote' && ph.votes[p.id] !== undefined,
|
||||
liar: known ? p.id === s.liar : null,
|
||||
})),
|
||||
descriptions: s.descriptions.map((d) => ({ ...d })),
|
||||
chat: s.chat.slice(-CHAT_VIEW).map((m) => ({ ...m })),
|
||||
events: s.events.slice(-EVENTS_VIEW),
|
||||
my: me ? myView(s, me) : null,
|
||||
final: s.final,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definition
|
||||
|
||||
function activePlayers(s: LiarState): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'ended':
|
||||
return [];
|
||||
case 'describe':
|
||||
return [speakerOf(s)!];
|
||||
case 'guess':
|
||||
return [s.liar];
|
||||
case 'vote':
|
||||
return voters(s)
|
||||
.filter((p) => ph.votes[p.id] === undefined)
|
||||
.map((p) => p.id);
|
||||
default:
|
||||
return present(s).map((p) => p.id);
|
||||
}
|
||||
}
|
||||
|
||||
type Def = GameDefinition<LiarState, LiarAction, LiarView, LiarOptions>;
|
||||
|
||||
export const liar: Def = {
|
||||
id: 'liar',
|
||||
nameKo: '라이어 게임',
|
||||
minPlayers: 3,
|
||||
maxPlayers: 10,
|
||||
stateVersion: 1,
|
||||
defaultOptions: liarOptionsSchema.parse({}),
|
||||
optionsSchema: liarOptionsSchema as unknown as Def['optionsSchema'],
|
||||
actionSchema: liarActionSchema as unknown as Def['actionSchema'],
|
||||
ownChat: true,
|
||||
|
||||
setup({ players, options, rng, now }) {
|
||||
const topic: TopicId = options.topic === 'random' ? TOPIC_IDS[rng.int(TOPIC_IDS.length)]! : options.topic;
|
||||
const words = topicById(topic).words;
|
||||
const wi = rng.int(words.length);
|
||||
const liarId = players[rng.int(players.length)]!;
|
||||
let liarWord: string | null = null;
|
||||
if (options.foolMode) {
|
||||
const rest = words.filter((_, i) => i !== wi);
|
||||
liarWord = rest[rng.int(rest.length)]!.word;
|
||||
}
|
||||
// Seats in order, starting from a random first speaker.
|
||||
const first = rng.int(players.length);
|
||||
const order = [...players.slice(first), ...players.slice(0, first)];
|
||||
return {
|
||||
options,
|
||||
players: players.map((id) => ({ id, left: false })),
|
||||
topic,
|
||||
word: words[wi]!.word,
|
||||
liar: liarId,
|
||||
liarWord,
|
||||
order,
|
||||
phase: { kind: 'reveal', startedAt: now, endsAt: now + REVEAL_MS, ready: [] },
|
||||
descriptions: [],
|
||||
chat: [],
|
||||
lastChatAt: {},
|
||||
events: [],
|
||||
accused: null,
|
||||
guess: null,
|
||||
seq: 0,
|
||||
final: null,
|
||||
};
|
||||
},
|
||||
|
||||
validate,
|
||||
|
||||
apply(prev, actor, a, { now }) {
|
||||
const s = structuredClone(prev);
|
||||
const before = s.events.length;
|
||||
s.seq += 1;
|
||||
const p = P(s, actor)!;
|
||||
const ph = s.phase;
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
advance(s, now);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, now, p);
|
||||
break;
|
||||
case 'chat': {
|
||||
const text = cleanChat(a.text);
|
||||
if (ph.kind === 'describe') {
|
||||
s.descriptions.push({ n: s.descriptions.length + 1, round: ph.round, from: actor, text, at: now });
|
||||
nextTurn(s, now, ph.round, ph.turn + 1);
|
||||
} else {
|
||||
s.lastChatAt[actor] = now;
|
||||
s.chat.push({ n: (s.chat.at(-1)?.n ?? 0) + 1, from: actor, text, at: now });
|
||||
if (s.chat.length > CHAT_KEEP) s.chat.splice(0, s.chat.length - CHAT_KEEP);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'ready':
|
||||
if (ph.kind !== 'reveal' && ph.kind !== 'discussion') throw new Error('liar: ready outside reveal/discussion');
|
||||
ph.ready.push(actor);
|
||||
if (present(s).every((x) => ph.ready.includes(x.id))) advance(s, now);
|
||||
break;
|
||||
case 'vote':
|
||||
if (ph.kind !== 'vote') throw new Error('liar: vote outside the vote phase');
|
||||
ph.votes[actor] = a.target;
|
||||
if (allVoted(s)) resolveVote(s, now);
|
||||
break;
|
||||
case 'guess':
|
||||
resolveGuess(s, now, cleanChat(a.text));
|
||||
break;
|
||||
}
|
||||
const events: GameEvent[] = s.events.slice(before).map((e) => ({ ...e, type: e.t }));
|
||||
return { state: s, events };
|
||||
},
|
||||
|
||||
view,
|
||||
|
||||
activePlayers,
|
||||
|
||||
deadline(s) {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** One player drives the phase clock (the deadline is shared by everybody). */
|
||||
timeoutPlayers(s) {
|
||||
return s.phase.kind === 'ended' ? [] : [s.players[0]!.id];
|
||||
},
|
||||
|
||||
/** An away driver must not end a phase early. */
|
||||
timeoutNotBefore(s) {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** Phases end on the clock: a missing description is "넘김", a missing vote is no vote, a missing guess is wrong. */
|
||||
onTimeout() {
|
||||
return { type: 'phaseTimeout' };
|
||||
},
|
||||
|
||||
onLeave(s, player) {
|
||||
const p = P(s, player);
|
||||
if (!p || p.left || s.final) return null;
|
||||
return { type: 'leave' };
|
||||
},
|
||||
|
||||
result(s): GameResult | null {
|
||||
const f = s.final;
|
||||
if (!f) return null;
|
||||
const won = (id: PlayerId) => !P(s, id)!.left && (f.winner === 'liar') === (id === f.liar);
|
||||
const ids = s.players.map((p) => p.id);
|
||||
const winners = ids.filter(won);
|
||||
const losers = ids.filter((id) => !won(id));
|
||||
return {
|
||||
ranking: [winners, losers].filter((g) => g.length > 0),
|
||||
scores: { ...f.scores },
|
||||
scoreText: Object.fromEntries(ids.map((id) => [id, `${id === f.liar ? '라이어' : '시민'} · ${f.scores[id] ?? 0}점`])),
|
||||
summary: f.summary,
|
||||
reason: 'normal',
|
||||
};
|
||||
},
|
||||
|
||||
/** Test helper: every legal move plus the phase clock and one short message where the player may write. */
|
||||
legalActions(s, player) {
|
||||
const p = P(s, player);
|
||||
if (!p || s.final || s.phase.kind === 'ended') return [];
|
||||
const out: LiarAction[] = [{ type: 'phaseTimeout' }];
|
||||
if (p.left) return out;
|
||||
const me = myView(s, p);
|
||||
if (me.canChat) out.push({ type: 'chat', text: `m${s.seq}-${player}` });
|
||||
if (me.canReady) out.push({ type: 'ready' });
|
||||
for (const t of me.voteTargets) out.push({ type: 'vote', target: t });
|
||||
if (me.canGuess) {
|
||||
if (s.options.guessMode === 'choice') for (const x of topicById(s.topic).words) out.push({ type: 'guess', text: x.word });
|
||||
else out.push({ type: 'guess', text: s.word }, { type: 'guess', text: `${s.word} 아님` });
|
||||
}
|
||||
return out.filter((a) => validate(s, player, a).ok);
|
||||
},
|
||||
|
||||
/** 바보 모드: the liar's own word belongs to the liar alone until the reveal. */
|
||||
secretsOf(s, player) {
|
||||
if (liarKnown(s) || player !== s.liar || !s.liarWord) return [];
|
||||
return [s.liarWord];
|
||||
},
|
||||
};
|
||||
|
||||
export const _internal = { roundOrder, speakerOf, voteTargets, chatBlock, liarKnown, TOPICS };
|
||||
405
packages/games/src/liar/liar.test.ts
Normal file
405
packages/games/src/liar/liar.test.ts
Normal file
@@ -0,0 +1,405 @@
|
||||
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));
|
||||
});
|
||||
});
|
||||
15
packages/games/src/liar/topics.ts
Normal file
15
packages/games/src/liar/topics.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
/** 라이어 게임 topics (no dependencies: the web screen imports this alone, without the word bank). */
|
||||
export const TOPIC_IDS = ['fruit', 'animal', 'job', 'food', 'place', 'sport', 'vehicle', 'thing', 'country', 'fairy'] as const;
|
||||
export type TopicId = (typeof TOPIC_IDS)[number];
|
||||
export const TOPIC_KO: Record<TopicId, string> = {
|
||||
fruit: '과일',
|
||||
animal: '동물',
|
||||
job: '직업',
|
||||
food: '음식',
|
||||
place: '장소',
|
||||
sport: '운동',
|
||||
vehicle: '탈것',
|
||||
thing: '물건',
|
||||
country: '나라',
|
||||
fairy: '동화 주인공',
|
||||
};
|
||||
197
packages/games/src/liar/types.ts
Normal file
197
packages/games/src/liar/types.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
/** 라이어 게임 options, actions, state and view types (docs/games/liar.md §2, §8). */
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
const lit = <T extends number>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`]));
|
||||
|
||||
export const liarOptionsSchema = z.object({
|
||||
topic: z
|
||||
.enum(['random', ...TOPIC_IDS])
|
||||
.default('random')
|
||||
.meta({ title: '주제', labels: { random: '무작위', ...TOPIC_KO } }),
|
||||
foolMode: z.boolean().default(false).meta({ title: '바보 모드(라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요)' }),
|
||||
rounds: lit(1, 2)
|
||||
.default(2)
|
||||
.meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }),
|
||||
describeSeconds: lit(15, 20, 30, 45, 60)
|
||||
.default(30)
|
||||
.meta({ title: '한 사람 설명 시간', labels: secLabels(15, 20, 30, 45, 60) }),
|
||||
discussionSeconds: lit(30, 60, 90, 120, 180)
|
||||
.default(90)
|
||||
.meta({ title: '자유 토론 시간', labels: secLabels(30, 60, 90, 120, 180) }),
|
||||
voteSeconds: lit(15, 20, 30, 45)
|
||||
.default(30)
|
||||
.meta({ title: '투표 시간', labels: secLabels(15, 20, 30, 45) }),
|
||||
guessMode: z
|
||||
.enum(['text', 'choice'])
|
||||
.default('text')
|
||||
.meta({ title: '라이어의 정답 맞히기', labels: { text: '직접 적기', choice: '주제 단어 목록에서 고르기' } }),
|
||||
guessSeconds: lit(20, 30, 45, 60)
|
||||
.default(30)
|
||||
.meta({ title: '정답 맞히기 시간', labels: secLabels(20, 30, 45, 60) }),
|
||||
kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }),
|
||||
});
|
||||
export type LiarOptions = z.infer<typeof liarOptionsSchema>;
|
||||
|
||||
const pid = z.string().min(1).max(64);
|
||||
export const liarActionSchema = z.discriminatedUnion('type', [
|
||||
/** Describe phase: the speaker's one sentence. Discussion / vote: free talk. */
|
||||
z.object({ type: z.literal('chat'), text: z.string().max(400) }),
|
||||
z.object({ type: z.literal('ready') }),
|
||||
z.object({ type: z.literal('vote'), target: pid }),
|
||||
z.object({ type: z.literal('guess'), text: z.string().max(60) }),
|
||||
]);
|
||||
export type LiarClientAction = z.infer<typeof liarActionSchema>;
|
||||
/** Client actions plus the system-only ones (phase timer, leaving) that are not in the schema. */
|
||||
export type LiarAction = LiarClientAction | { type: 'phaseTimeout' } | { type: 'leave' };
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
export type Phase =
|
||||
| { kind: 'reveal'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'describe'; startedAt: number; endsAt: number; round: number; turn: number }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number; round: 1 | 2; candidates: PlayerId[]; votes: Record<PlayerId, PlayerId> }
|
||||
| { kind: 'guess'; startedAt: number; endsAt: number }
|
||||
| { kind: 'ended' };
|
||||
export type PhaseKind = Phase['kind'];
|
||||
|
||||
export interface PlayerState {
|
||||
id: PlayerId;
|
||||
/** Left the game: skipped from then on (turns, votes, "모두 동의"). */
|
||||
left: boolean;
|
||||
}
|
||||
|
||||
export interface Description {
|
||||
n: number;
|
||||
round: number;
|
||||
from: PlayerId;
|
||||
/** null = the time ran out (넘김). */
|
||||
text: string | null;
|
||||
at: number;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
n: number;
|
||||
from: PlayerId;
|
||||
text: string;
|
||||
at: number;
|
||||
}
|
||||
|
||||
export type WinReason = 'escaped' | 'tie' | 'guessed' | 'caught' | 'liarLeft' | 'citizensLeft';
|
||||
|
||||
/** Public announcement. */
|
||||
export type PublicEvent = { n: number; at: number } & (
|
||||
| { t: 'phase'; kind: Exclude<PhaseKind, 'ended'>; round?: number }
|
||||
| { t: 'vote'; round: 1 | 2; tally: Record<PlayerId, number>; votes: Record<PlayerId, PlayerId>; accused: PlayerId | null; tied: PlayerId[] }
|
||||
| { t: 'accused'; p: PlayerId; liar: boolean }
|
||||
| { t: 'guess'; text: string | null; correct: boolean }
|
||||
| { t: 'left'; p: PlayerId }
|
||||
| { t: 'end'; winner: 'liar' | 'citizens' }
|
||||
);
|
||||
export type PublicEventKind = PublicEvent['t'];
|
||||
|
||||
export interface LiarFinal {
|
||||
winner: 'liar' | 'citizens';
|
||||
reason: WinReason;
|
||||
liar: PlayerId;
|
||||
topic: TopicId;
|
||||
word: string;
|
||||
/** 바보 모드: the word the liar got. */
|
||||
liarWord: string | null;
|
||||
accused: PlayerId | null;
|
||||
guess: string | null;
|
||||
scores: Record<PlayerId, number>;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface LiarState {
|
||||
options: LiarOptions;
|
||||
players: PlayerState[];
|
||||
topic: TopicId;
|
||||
word: string;
|
||||
liar: PlayerId;
|
||||
/** 바보 모드: the liar's own (wrong) word; null otherwise. */
|
||||
liarWord: string | null;
|
||||
/** Round-1 speaking order (round 2 runs it backwards). */
|
||||
order: PlayerId[];
|
||||
phase: Phase;
|
||||
descriptions: Description[];
|
||||
chat: ChatMessage[];
|
||||
lastChatAt: Record<PlayerId, number>;
|
||||
events: PublicEvent[];
|
||||
accused: PlayerId | null;
|
||||
guess: string | null;
|
||||
seq: number;
|
||||
final: LiarFinal | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export interface PlayerView {
|
||||
id: PlayerId;
|
||||
left: boolean;
|
||||
/** Vote phase: has voted (not whom). */
|
||||
voted: boolean;
|
||||
/** Known only after the reveal: is the liar. null = unknown to this viewer. */
|
||||
liar: boolean | null;
|
||||
}
|
||||
|
||||
export interface MyView {
|
||||
/**
|
||||
* What I know of myself: 'liar' (normal mode, or after the reveal) / 'citizen'. In 바보 모드 the liar sees
|
||||
* 'citizen' and a word, exactly like everybody else, until the reveal.
|
||||
*/
|
||||
role: 'liar' | 'citizen';
|
||||
/** My word; null for a (normal-mode) liar. */
|
||||
word: string | null;
|
||||
canDescribe: boolean;
|
||||
canChat: boolean;
|
||||
/** Korean reason I can't write now, or null. */
|
||||
chatWhy: string | null;
|
||||
canReady: boolean;
|
||||
ready: boolean;
|
||||
vote: PlayerId | null;
|
||||
voteTargets: PlayerId[];
|
||||
canGuess: boolean;
|
||||
}
|
||||
|
||||
export interface LiarView {
|
||||
me: PlayerId | null;
|
||||
options: LiarOptions;
|
||||
topic: TopicId;
|
||||
topicKo: string;
|
||||
phase: {
|
||||
kind: PhaseKind;
|
||||
startedAt: number;
|
||||
endsAt: number | null;
|
||||
/** Describe: 1-based round and the speaker. */
|
||||
round: number;
|
||||
speaker: PlayerId | null;
|
||||
/** Who speaks in this round, in order (describe phase). */
|
||||
turnOrder: PlayerId[];
|
||||
turn: number;
|
||||
readyCount: number;
|
||||
readyNeeded: number;
|
||||
voteRound: 1 | 2 | null;
|
||||
candidates: PlayerId[];
|
||||
votedCount: number;
|
||||
/** Guess phase: the revealed liar, and (choice mode) the words to pick from. */
|
||||
liar: PlayerId | null;
|
||||
choices: string[];
|
||||
};
|
||||
rounds: number;
|
||||
/** Round-1 order. */
|
||||
order: PlayerId[];
|
||||
players: PlayerView[];
|
||||
descriptions: Description[];
|
||||
chat: ChatMessage[];
|
||||
events: PublicEvent[];
|
||||
my: MyView | null;
|
||||
final: LiarFinal | null;
|
||||
}
|
||||
265
packages/games/src/liar/words.ts
Normal file
265
packages/games/src/liar/words.ts
Normal file
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* 라이어 게임 제시어 은행 (docs/games/liar.md §3). 주제마다 단어 15개 이상, 단어마다 컴퓨터가 쓸 설명 문장 4개 이상.
|
||||
*
|
||||
* - `hints`: 애매하지만 시민끼리는 알아들을 만한 한 문장. 앞쪽일수록 덜 구체적이에요(똑똑한 컴퓨터는 앞에서부터 써요).
|
||||
* 단어 자체(띄어쓰기 무시)는 절대 들어가지 않아요(테스트로 확인).
|
||||
* - `aliases`: 라이어가 맞힐 때 정답으로 쳐 주는 다른 표기(핸드폰/휴대폰 등).
|
||||
* - 주제의 `generic`: 그 주제 어디에나 맞는 무난한 말. 아직 아무 설명도 못 들은 라이어 컴퓨터가 써요.
|
||||
* 한 글자 단어(배, 귤, 컵 …)는 넣지 않아요: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막아 버려서요.
|
||||
*/
|
||||
import type { TopicId } from './types';
|
||||
|
||||
export interface LiarWord {
|
||||
word: string;
|
||||
aliases?: string[];
|
||||
hints: string[];
|
||||
}
|
||||
|
||||
export interface LiarTopic {
|
||||
id: TopicId;
|
||||
ko: string;
|
||||
generic: string[];
|
||||
words: LiarWord[];
|
||||
}
|
||||
|
||||
const w = (word: string, hints: string[], aliases?: string[]): LiarWord => (aliases ? { word, hints, aliases } : { word, hints });
|
||||
|
||||
export const TOPICS: readonly LiarTopic[] = [
|
||||
{
|
||||
id: 'fruit',
|
||||
ko: '과일',
|
||||
generic: ['저는 좋아하는 편이에요', '마트에서 쉽게 볼 수 있어요', '달콤한 맛이 나요', '껍질이 있어요', '제철에 먹으면 더 맛있어요'],
|
||||
words: [
|
||||
w('수박', ['여름이면 생각나요', '겉이랑 속 색깔이 완전히 달라요', '씨를 뱉으면서 먹어요', '혼자 다 먹기엔 너무 커요', '두드려 보고 골라요']),
|
||||
w('사과', ['아침에 먹으면 좋다고 해요', '껍질째 먹기도 해요', '빨간 것도 있고 초록인 것도 있어요', '잼이나 주스로도 많이 만들어요', '깎다가 껍질이 길게 이어지면 기분 좋아요']),
|
||||
w('바나나', ['손으로 쉽게 껍질을 벗겨요', '시간이 지나면 갈색 점이 생겨요', '원숭이가 좋아한다고 하죠', '길쭉하게 휘어 있어요', '송이째로 팔아요']),
|
||||
w('딸기', ['겨울부터 봄까지 많이 나와요', '케이크 위에 자주 올라가요', '겉에 작은 씨가 콕콕 박혀 있어요', '우유랑 같이 갈아 먹어요', '빨갛고 작아요']),
|
||||
w('포도', ['알이 동글동글 모여 있어요', '한 알씩 떼어 먹어요', '보라색이 많아요', '주스나 와인으로 만들어요', '씨 없는 것도 있어요']),
|
||||
w('복숭아', ['여름에 나오고 아주 물러요', '겉에 털이 살짝 있어요', '분홍빛이 돌아요', '통조림으로도 먹어요', '알레르기가 있는 사람도 있어요']),
|
||||
w('오렌지', ['주스로 많이 마셔요', '비타민이 많아요', '껍질이 두꺼워서 까기 조금 힘들어요', '동그랗고 새콤달콤해요', '외국에서 많이 들어와요']),
|
||||
w('참외', ['여름에 많이 먹어요', '노란 겉에 하얀 줄이 있어요', '속에 씨가 가득해요', '성주가 유명해요', '아삭아삭 씹혀요']),
|
||||
w('파인애플', ['겉이 울퉁불퉁하고 따가워요', '머리에 뾰족한 잎이 있어요', '먹으면 혀가 따끔할 때가 있어요', '피자 위에 올리면 싸움이 나요', '더운 나라에서 자라요']),
|
||||
w('망고', ['노랗고 아주 달아요', '더운 나라에서 많이 와요', '가운데 납작하고 큰 씨가 있어요', '빙수에 많이 올려요', '말린 것도 간식으로 팔아요']),
|
||||
w('체리', ['꼭지가 길게 달려 있어요', '작고 빨개서 장식으로 많이 써요', '그림에서는 보통 두 개씩 붙어 있어요', '씨를 뱉어야 해요', '조금 비싼 편이에요']),
|
||||
w('레몬', ['엄청 시어요', '그냥 먹기보다는 즙을 짜서 써요', '노랗고 타원형이에요', '차나 음료에 한 조각 넣어요', '생선 요리에 뿌려요']),
|
||||
w('키위', ['겉이 갈색이고 털이 있어요', '반으로 자르면 속이 초록색이에요', '숟가락으로 떠먹기도 해요', '새 이름이랑 같아요', '뉴질랜드가 유명해요']),
|
||||
w('블루베리', ['아주 작은 알갱이예요', '눈에 좋다고 해요', '요거트에 넣어 먹어요', '파란빛이 도는 보라색이에요', '머핀에 콕콕 박혀 있어요']),
|
||||
w('자두', ['새콤해서 침이 고여요', '여름 과일이에요', '빨갛거나 보랏빛이에요', '말린 것도 있어요', '한 입 크기예요']),
|
||||
w('멜론', ['겉에 그물 무늬가 있어요', '아이스크림 맛으로도 유명해요', '비싼 선물용도 있어요', '연두색 속살이 달아요', '반으로 갈라 씨를 긁어내요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'animal',
|
||||
ko: '동물',
|
||||
generic: ['동물원에서 볼 수 있어요', '귀여운 편이에요', '먹이를 잘 먹어요', '사진 찍으면 예쁘게 나와요', '아이들이 좋아해요'],
|
||||
words: [
|
||||
w('고양이', ['혼자서도 잘 지내요', '높은 곳을 좋아해요', '상자만 보면 들어가요', '밤에 눈이 빛나요', '혀로 털을 자주 골라요'], ['냥이']),
|
||||
w('강아지', ['산책을 정말 좋아해요', '꼬리를 흔들어요', '주인이 오면 반겨요', '사람을 잘 따라요', '집을 잘 지켜요'], ['멍멍이']),
|
||||
w('코끼리', ['정말 커요', '코가 손 역할을 해요', '귀가 부채처럼 커요', '기억력이 좋다고 해요', '상아가 있어요']),
|
||||
w('기린', ['목이 엄청 길어요', '높은 나뭇잎을 먹어요', '점박이 무늬가 있어요', '서서 자기도 해요', '혀가 길고 까매요']),
|
||||
w('사자', ['동물의 왕이라고 불려요', '수컷은 갈기가 있어요', '무리 지어 살아요', '초원에서 사냥해요', '어흥 하고 울어요']),
|
||||
w('호랑이', ['줄무늬가 멋있어요', '옛이야기에 자주 나와요', '곶감을 무서워했다는 이야기가 있어요', '산에 사는 큰 고양이과예요', '올림픽 마스코트였던 적이 있어요']),
|
||||
w('토끼', ['귀가 길어요', '깡충깡충 뛰어요', '당근을 좋아한다고 하죠', '달에서 떡방아를 찧는대요', '앞니가 계속 자라요']),
|
||||
w('펭귄', ['날개가 있지만 못 날아요', '추운 곳에 살아요', '뒤뚱뒤뚱 걸어요', '턱시도를 입은 것 같아요', '물속에서는 엄청 빨라요']),
|
||||
w('원숭이', ['나무를 잘 타요', '흉내를 잘 내요', '바나나 하면 떠올라요', '엉덩이가 빨간 것도 있어요', '사람이랑 꽤 닮았어요']),
|
||||
w('돌고래', ['물속에 살지만 숨은 밖에서 쉬어요', '똑똑하기로 유명해요', '쇼에서 점프를 해요', '초음파로 대화해요', '웃는 얼굴처럼 보여요']),
|
||||
w('거북이', ['아주 느려요', '등에 집을 지고 다녀요', '오래 살아요', '토끼랑 경주했어요', '위험하면 머리를 쏙 넣어요'], ['거북']),
|
||||
w('판다', ['흑백이에요', '대나무를 먹어요', '눈 주위가 까매요', '중국에서 왔어요', '데굴데굴 구르는 게 귀여워요'], ['팬더']),
|
||||
w('다람쥐', ['볼에 먹이를 넣어요', '도토리를 모아요', '꼬리가 복슬복슬해요', '작고 재빨라요', '쳇바퀴를 돌려요']),
|
||||
w('캥거루', ['배에 주머니가 있어요', '뒷다리로 껑충 뛰어요', '호주에 살아요', '권투를 한다는 이야기가 있어요', '꼬리로 몸을 받쳐요']),
|
||||
w('하마', ['입이 엄청 커요', '물속에 오래 있어요', '덩치가 크고 동글동글해요', '생각보다 무서운 동물이래요', '아프리카 강에 살아요']),
|
||||
w('낙타', ['등에 혹이 있어요', '사막에 살아요', '물 없이 오래 버텨요', '사람을 태우고 다녀요', '속눈썹이 길어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'job',
|
||||
ko: '직업',
|
||||
generic: ['일하는 사람이에요', '꼭 필요한 일이에요', '힘들지만 보람 있대요', '주변에서 볼 수 있어요', '어릴 때 꿈이었던 사람도 많아요'],
|
||||
words: [
|
||||
w('의사', ['아플 때 만나요', '하얀 가운을 입어요', '청진기를 써요', '공부를 오래 해야 해요', '처방전을 써 줘요']),
|
||||
w('간호사', ['병원에서 일해요', '주사를 놓아 줘요', '밤에도 환자를 돌봐요', '체온이랑 혈압을 재 줘요', '교대 근무를 해요']),
|
||||
w('선생님', ['학교에 가면 만나요', '칠판 앞에 서요', '숙제를 내 줘요', '방학이 있어요', '출석을 불러요'], ['선생', '교사']),
|
||||
w('경찰관', ['제복을 입어요', '도둑을 잡아요', '길을 잃으면 도와줘요', '112에 전화하면 와요', '순찰차를 타요'], ['경찰']),
|
||||
w('소방관', ['불이 나면 달려가요', '빨간 차를 타요', '119에 전화하면 와요', '무거운 장비를 메요', '사람을 구조해요'], ['소방수']),
|
||||
w('요리사', ['주방에서 일해요', '하얀 모자를 써요', '칼을 잘 다뤄요', '맛을 계속 봐요', '메뉴를 만들어요'], ['셰프']),
|
||||
w('가수', ['무대에 서요', '마이크를 들어요', '앨범을 내요', '콘서트를 해요', '목 관리가 중요해요']),
|
||||
w('배우', ['다른 사람인 척해요', '대본을 외워요', '드라마나 영화에 나와요', '우는 연기도 해요', '시상식에서 상을 받아요']),
|
||||
w('화가', ['붓을 써요', '옷에 물감이 묻어요', '전시회를 열어요', '캔버스 앞에 오래 앉아 있어요', '고흐가 유명해요']),
|
||||
w('미용사', ['가위를 들고 일해요', '머리를 만져 줘요', '파마도 해 줘요', '거울 앞에서 일해요', '손님이랑 수다를 떨어요']),
|
||||
w('우체부', ['집집마다 다녀요', '편지를 가져다줘요', '소포도 전해 줘요', '오토바이를 타고 다녀요', '빨간 우체통이랑 관계있어요'], ['집배원']),
|
||||
w('농부', ['밭에서 일해요', '새벽부터 일어나요', '날씨를 많이 신경 써요', '쌀이나 채소를 길러요', '가을에 제일 바빠요']),
|
||||
w('조종사', ['하늘에서 일해요', '공항으로 출근해요', '제복 모자에 날개 모양 배지가 있어요', '안내 방송을 해요', '시력이 좋아야 해요'], ['파일럿', '기장']),
|
||||
w('과학자', ['실험실에서 일해요', '하얀 가운에 보안경을 써요', '연구를 오래 해요', '노벨상을 받기도 해요', '가설을 세우고 확인해요']),
|
||||
w('택배기사', ['상자를 날라요', '문 앞에 두고 가요', '하루에 엄청 많은 집을 가요', '트럭을 몰아요', '명절 전에 제일 바빠요'], ['택배원']),
|
||||
w('프로그래머', ['컴퓨터 앞에 오래 앉아 있어요', '버그를 잡아요', '키보드를 많이 쳐요', '앱을 만들어요', '밤샘을 하기도 해요'], ['개발자']),
|
||||
w('기자', ['뉴스를 써요', '현장에 마이크를 들고 가요', '질문을 많이 해요', '사건이 생기면 바로 달려가요', '취재 수첩이 있어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'food',
|
||||
ko: '음식',
|
||||
generic: ['맛있어요', '배고플 때 생각나요', '친구랑 같이 먹으면 좋아요', '집에서도 만들 수 있어요', '사람마다 좋아하는 맛이 달라요'],
|
||||
words: [
|
||||
w('김치', ['매일 밥상에 올라와요', '겨울에 많이 담가요', '익을수록 시어져요', '빨간 것도 있고 하얀 것도 있어요', '배추로 많이 만들어요']),
|
||||
w('라면', ['끓는 물에 넣어요', '밤에 먹으면 얼굴이 부어요', '꼬불꼬불해요', '봉지에 들어 있어요', '계란을 넣기도 해요']),
|
||||
w('떡볶이', ['학교 앞에서 많이 팔아요', '매콤달콤해요', '어묵이랑 같이 먹어요', '쫄깃쫄깃해요', '빨간 국물이에요']),
|
||||
w('피자', ['배달로 많이 시켜요', '치즈가 쭉 늘어나요', '여러 조각으로 잘라요', '이탈리아에서 왔어요', '끝 부분 빵을 남기는 사람도 있어요']),
|
||||
w('치킨', ['양념이냐 후라이드냐 고민해요', '바삭바삭해요', '다리가 인기 많아요', '맥주랑 같이 먹어요', '무를 같이 줘요'], ['통닭']),
|
||||
w('햄버거', ['패스트푸드예요', '감자튀김이랑 세트예요', '빵 사이에 고기가 있어요', '높이 쌓을수록 먹기 힘들어요', '콜라랑 잘 어울려요']),
|
||||
w('김밥', ['소풍 갈 때 싸 가요', '둥글게 썰어요', '꼬다리가 맛있어요', '겉은 까맣고 속은 알록달록해요', '돌돌 말아요']),
|
||||
w('비빔밥', ['여러 나물이 들어가요', '고추장을 넣어 섞어요', '계란 하나 올리면 좋아요', '돌솥에 담기도 해요', '전주가 유명해요']),
|
||||
w('불고기', ['달달한 간장 양념이에요', '외국인이 좋아해요', '얇게 썬 고기예요', '버섯이랑 같이 볶아요', '불판에 국물이 자작해요']),
|
||||
w('짜장면', ['중국집에서 시켜요', '이사하는 날 먹어요', '까만 소스예요', '단무지랑 같이 나와요', '입가에 묻기 쉬워요'], ['자장면']),
|
||||
w('삼겹살', ['불판에 구워요', '상추에 싸 먹어요', '기름이 많아요', '층층이 줄이 있어요', '회식 메뉴로 많이 나와요']),
|
||||
w('초밥', ['밥 위에 생선이 올라가요', '회전하는 가게가 있어요', '와사비를 넣어요', '간장에 살짝 찍어요', '한 입에 쏙 들어가요']),
|
||||
w('냉면', ['여름에 시원하게 먹어요', '면을 가위로 잘라요', '물이랑 비빔이 있어요', '고기 먹고 후식으로 먹어요', '식초랑 겨자를 넣어요']),
|
||||
w('떡국', ['설날 아침에 먹어요', '먹으면 나이를 한 살 먹는대요', '하얀 떡을 동그랗게 썰어요', '국물이 뽀얘요', '지단을 올려요']),
|
||||
w('아이스크림', ['차갑고 달아요', '콘이나 컵에 담아요', '빨리 안 먹으면 녹아요', '여름에 많이 먹어요', '맛을 고르는 게 고민돼요']),
|
||||
w('스파게티', ['포크로 돌돌 말아요', '토마토나 크림 소스예요', '이탈리아 음식이에요', '면이 길어요', '면을 벽에 던져서 익었는지 본대요'], ['파스타']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'place',
|
||||
ko: '장소',
|
||||
generic: ['사람들이 많이 가요', '가 본 적 있어요', '주말에 붐벼요', '우리 동네에도 있어요', '가면 기분이 달라져요'],
|
||||
words: [
|
||||
w('학교', ['종이 울려요', '운동장이 있어요', '급식을 먹어요', '친구를 매일 만나요', '시험이 있어요']),
|
||||
w('병원', ['소독약 냄새가 나요', '번호표 받고 기다려요', '아플 때 가요', '하얀 침대가 있어요', '면회 시간이 정해져 있어요']),
|
||||
w('공항', ['큰 가방을 끌고 가요', '여권이 필요해요', '출국이랑 입국이 있어요', '면세점이 있어요', '하늘로 떠나는 곳이에요']),
|
||||
w('도서관', ['조용히 해야 해요', '빌렸다가 돌려줘요', '반납 기한이 있어요', '공부하는 사람이 많아요', '책장이 줄줄이 있어요']),
|
||||
w('영화관', ['불이 꺼지고 어두워요', '팝콘을 사요', '화면이 아주 커요', '휴대폰을 꺼 달라고 해요', '좌석을 미리 골라요'], ['극장']),
|
||||
w('놀이공원', ['줄을 오래 서요', '롤러코스터가 있어요', '머리띠를 사서 써요', '퍼레이드를 해요', '자유이용권을 사요'], ['놀이동산']),
|
||||
w('바다', ['파도가 쳐요', '물이 짜요', '모래사장이 있어요', '여름 휴가로 많이 가요', '갈매기가 날아다녀요']),
|
||||
w('수영장', ['수영모를 써야 해요', '소독약 냄새가 나요', '튜브를 끼고 놀아요', '깊은 곳이랑 얕은 곳이 있어요', '들어가기 전에 샤워해요']),
|
||||
w('은행', ['번호표를 뽑아요', '통장을 만들어요', '창구에서 일을 봐요', '현금인출기가 있어요', '오후 네 시면 문을 닫아요']),
|
||||
w('편의점', ['24시간 열어요', '삼각김밥을 팔아요', '동네마다 있어요', '아르바이트생이 많아요', '1+1 행사를 해요']),
|
||||
w('경찰서', ['신고하러 가요', '순찰차가 서 있어요', '분실물을 찾으러 가기도 해요', '유치장이 있어요', '제복 입은 사람이 많아요'], ['파출소']),
|
||||
w('동물원', ['먹이를 주면 안 돼요', '사육사가 있어요', '우리 안을 구경해요', '소풍으로 많이 가요', '냄새가 좀 나요']),
|
||||
w('찜질방', ['양머리 수건을 써요', '식혜랑 구운 계란을 먹어요', '아주 뜨거운 방이 있어요', '바닥에 누워서 쉬어요', '같은 옷을 입고 다녀요']),
|
||||
w('노래방', ['마이크를 잡아요', '점수가 나와요', '탬버린을 흔들어요', '시간이 추가되면 기뻐요', '방마다 화면이 있어요']),
|
||||
w('캠핑장', ['텐트를 쳐요', '모닥불을 피워요', '밤에 별이 잘 보여요', '고기를 구워 먹어요', '벌레가 많아요']),
|
||||
w('박물관', ['옛날 물건이 많아요', '유리장 안에 있어요', '만지지 말라고 해요', '견학으로 많이 가요', '해설을 들을 수 있어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'sport',
|
||||
ko: '운동',
|
||||
generic: ['몸을 움직여요', '하고 나면 땀이 나요', '친구들이랑 하면 재밌어요', '올림픽에서도 봤어요', '규칙을 알아야 해요'],
|
||||
words: [
|
||||
w('축구', ['공을 발로 차요', '월드컵이 있어요', '골키퍼만 손을 써요', '한 팀에 열한 명이에요', '전반전과 후반전이 있어요']),
|
||||
w('야구', ['방망이를 휘둘러요', '홈런이 나오면 신나요', '글러브를 껴요', '9회까지 해요', '삼진 아웃이 있어요']),
|
||||
w('농구', ['키 큰 사람이 유리해요', '공을 튀기면서 달려요', '골대가 높이 달려 있어요', '3점슛이 있어요', '덩크를 하면 멋있어요']),
|
||||
w('배구', ['네트 너머로 넘겨요', '공이 바닥에 떨어지면 안 돼요', '스파이크를 때려요', '리베로가 있어요', '한 팀에 여섯 명이에요']),
|
||||
w('수영', ['물속에서 해요', '자유형이랑 평영이 있어요', '수경을 써요', '레인을 따라가요', '숨 쉬는 게 어려워요']),
|
||||
w('탁구', ['작고 가벼운 공을 써요', '테이블 위에서 해요', '핑퐁이라고도 해요', '라켓이 작아요', '공이 통통 튀어요']),
|
||||
w('테니스', ['노란 공을 써요', '점수를 러브라고 불러요', '잔디 코트도 있어요', '서브를 세게 넣어요', '라켓 줄이 팽팽해요']),
|
||||
w('볼링', ['무거운 공을 굴려요', '핀을 쓰러뜨려요', '스트라이크가 최고예요', '신발을 빌려 신어요', '손가락 구멍이 세 개예요']),
|
||||
w('골프', ['넓은 잔디에서 해요', '작은 구멍에 넣어요', '적게 칠수록 좋아요', '18홀이 있어요', '채가 여러 개예요']),
|
||||
w('태권도', ['도복을 입어요', '띠 색깔이 바뀌어요', '발차기가 멋있어요', '우리나라 무술이에요', '송판을 깨요']),
|
||||
w('스키', ['눈 위에서 해요', '리프트를 타고 올라가요', '겨울에 해요', '폴을 짚어요', '넘어지면 일어나기 힘들어요']),
|
||||
w('마라톤', ['아주 오래 달려요', '42킬로미터가 넘어요', '중간에 물을 마셔요', '끝까지 가는 게 목표예요', '기록을 재요']),
|
||||
w('줄넘기', ['체육 시간에 해요', '이단뛰기가 있어요', '혼자도 여럿도 할 수 있어요', '발이 걸리면 끝나요', '숫자를 세면서 해요']),
|
||||
w('배드민턴', ['공원에서 많이 해요', '깃털 달린 공을 쳐요', '바람이 불면 힘들어요', '네트를 사이에 두고 쳐요', '라켓이 가벼워요']),
|
||||
w('씨름', ['모래판에서 해요', '샅바를 잡아요', '천하장사가 있어요', '상대를 넘어뜨려요', '명절에 텔레비전에서 해요']),
|
||||
w('스케이트', ['얼음 위에서 타요', '날 달린 신발을 신어요', '빙상장에서 해요', '넘어지기 쉬워요', '빙글빙글 돌기도 해요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'vehicle',
|
||||
ko: '탈것',
|
||||
generic: ['타고 다녀요', '어디 갈 때 써요', '빠른 편이에요', '어릴 때 장난감으로 갖고 놀았어요', '사람을 태워요'],
|
||||
words: [
|
||||
w('자동차', ['바퀴가 네 개예요', '면허가 있어야 해요', '주유소에 들러요', '주차할 곳이 늘 고민이에요', '안전벨트를 매요'], ['승용차']),
|
||||
w('버스', ['정류장에서 기다려요', '번호를 보고 타요', '카드를 찍고 타요', '내릴 때 벨을 눌러요', '손잡이를 잡고 서 있기도 해요']),
|
||||
w('지하철', ['땅속으로 다녀요', '노선마다 색깔이 달라요', '환승을 해요', '출퇴근 시간엔 꽉 차요', '스크린도어가 있어요'], ['전철']),
|
||||
w('기차', ['선로 위를 달려요', '역에서 타요', '창밖 풍경을 보며 가요', '도시 사이를 빠르게 이어 줘요', '칸이 길게 이어져 있어요'], ['열차']),
|
||||
w('비행기', ['날개가 있어요', '구름 위로 가요', '귀가 먹먹해져요', '기내식을 줘요', '창가 자리가 인기예요']),
|
||||
w('유람선', ['물 위를 떠다녀요', '강이나 바다를 구경해요', '갑판에 나가요', '뱃멀미가 날 수 있어요', '밤에 불빛이 예뻐요']),
|
||||
w('자전거', ['페달을 밟아요', '바퀴가 두 개예요', '헬멧을 쓰면 좋아요', '처음엔 보조 바퀴를 달아요', '체인이 빠지면 곤란해요']),
|
||||
w('오토바이', ['헬멧을 꼭 써요', '배달할 때 많이 타요', '두 바퀴인데 엔진이 있어요', '부릉부릉 소리가 커요', '가죽 재킷이랑 어울려요'], ['바이크']),
|
||||
w('택시', ['손을 흔들어서 세워요', '미터기가 돌아가요', '기사님께 목적지를 말해요', '밤늦게 많이 타요', '앱으로 부르기도 해요']),
|
||||
w('헬리콥터', ['프로펠러가 위에 있어요', '제자리에 떠 있을 수 있어요', '옥상에 내려요', '다다다 소리가 나요', '구조할 때 많이 써요'], ['헬기']),
|
||||
w('트럭', ['짐을 많이 실어요', '크고 무거워요', '이사할 때 불러요', '뒤에 짐칸이 있어요', '고속도로에서 많이 봐요']),
|
||||
w('구급차', ['사이렌을 울려요', '아픈 사람을 태워요', '길을 비켜 줘야 해요', '하얀 차에 빨간 줄이 있어요', '병원으로 급히 가요']),
|
||||
w('소방차', ['빨간색이에요', '긴 사다리가 있어요', '물을 뿌려요', '사이렌을 울리며 달려요', '호스가 감겨 있어요']),
|
||||
w('잠수함', ['물속으로 다녀요', '잠망경이 있어요', '군대에서 써요', '창문이 거의 없어요', '물 위로 떠오르기도 해요']),
|
||||
w('로켓', ['우주로 가요', '카운트다운을 해요', '불을 뿜으며 위로 올라가요', '발사대에 세워 둬요', '나로호가 생각나요']),
|
||||
w('킥보드', ['한 발로 밀고 가요', '서서 타요', '전동도 있어요', '공유해서 빌려 타요', '손잡이가 길어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'thing',
|
||||
ko: '물건',
|
||||
generic: ['집에 하나쯤 있어요', '매일 써요', '잃어버리면 곤란해요', '선물로도 줘요', '가게에서 쉽게 살 수 있어요'],
|
||||
words: [
|
||||
w('우산', ['비 오는 날 꼭 필요해요', '펼치고 접어요', '잃어버리기 쉬워요', '편의점에서 급히 사기도 해요', '바람 불면 뒤집혀요']),
|
||||
w('휴대폰', ['매일 손에 들고 다녀요', '밤마다 충전해요', '알람을 맞춰요', '사진을 찍어요', '화면이 깨지면 속상해요'], ['핸드폰', '스마트폰', '휴대전화']),
|
||||
w('안경', ['코 위에 걸쳐요', '눈이 나쁘면 써요', '김이 서려요', '알이 두 개예요', '닦아도 금방 뿌예져요']),
|
||||
w('시계', ['째깍째깍 소리가 나요', '손목에 차요', '바늘이 돌아가요', '벽에도 걸어요', '건전지가 다 되면 멈춰요']),
|
||||
w('거울', ['나를 비춰 줘요', '화장실에 있어요', '깨지면 위험해요', '왼쪽 오른쪽이 바뀌어 보여요', '마법 이야기에도 나와요']),
|
||||
w('가위', ['종이를 잘라요', '바위 보랑 같이 나와요', '손가락 넣는 구멍이 있어요', '날이 두 개예요', '미술 시간에 써요']),
|
||||
w('연필', ['깎아서 써요', '심이 부러지기도 해요', '시험 볼 때 써요', '노란색이 많아요', '지울 수 있게 써요']),
|
||||
w('지우개', ['틀린 걸 없애 줘요', '쓰면 가루가 나와요', '말랑말랑해요', '쓸수록 작아져요', '필통에 꼭 있어요']),
|
||||
w('칫솔', ['하루 세 번 써요', '치약이랑 짝이에요', '화장실 컵에 꽂아 둬요', '석 달마다 바꾸래요', '솔이 벌어지면 바꿔요']),
|
||||
w('베개', ['잘 때 머리를 대요', '푹신해요', '높이가 맞아야 잘 자요', '수학여행 밤에 던지면서 놀아요', '침대 위에 있어요']),
|
||||
w('냉장고', ['부엌에 있어요', '안이 차가워요', '문 열고 한참 고민해요', '반찬을 넣어 둬요', '자석을 붙여요']),
|
||||
w('텔레비전', ['거실에 있어요', '리모컨으로 켜요', '채널을 돌려요', '드라마를 봐요', '화면이 점점 커져요'], ['티비', 'TV', '텔레비젼']),
|
||||
w('열쇠', ['문을 열어요', '고리에 달아 둬요', '잃어버리면 곤란해요', '자물쇠랑 짝이에요', '요즘은 번호로 많이 바뀌었어요']),
|
||||
w('지갑', ['돈을 넣어요', '카드를 꽂아요', '주머니에 넣고 다녀요', '가죽으로 많이 만들어요', '잃어버리면 정말 곤란해요']),
|
||||
w('장갑', ['겨울에 껴요', '손가락이 다섯 개예요', '한 짝만 잃어버리기 쉬워요', '끼고 눈싸움을 해요', '설거지할 때도 껴요']),
|
||||
w('모자', ['머리 위에 써요', '햇빛을 가려 줘요', '챙이 있어요', '벗으면 머리가 눌려 있어요', '야구장에서 많이 써요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'country',
|
||||
ko: '나라',
|
||||
generic: ['비행기를 타고 가야 해요', '꼭 한번 가 보고 싶어요', '유명한 음식이 있어요', '사람이 많이 살아요', '뉴스에서 자주 봐요'],
|
||||
words: [
|
||||
w('미국', ['자유의 여신상이 있어요', '달러를 써요', '할리우드가 있어요', '땅이 아주 넓어요', '햄버거가 생각나요'], ['아메리카']),
|
||||
w('중국', ['만리장성이 있어요', '인구가 아주 많아요', '빨간색을 좋아한대요', '판다가 살아요', '베이징이 수도예요']),
|
||||
w('일본', ['가까운 섬나라예요', '벚꽃이 유명해요', '초밥이 생각나요', '후지산이 있어요', '온천이 많아요']),
|
||||
w('프랑스', ['에펠탑이 있어요', '바게트 빵이 유명해요', '파리가 수도예요', '패션의 나라예요', '와인이 유명해요']),
|
||||
w('영국', ['홍차를 많이 마셔요', '이층 버스가 있어요', '런던이 수도예요', '여왕이 유명했어요', '시계탑이 있어요']),
|
||||
w('이탈리아', ['파스타가 유명해요', '지도에서 장화처럼 생겼어요', '로마가 수도예요', '콜로세움이 있어요', '피사의 사탑이 있어요']),
|
||||
w('브라질', ['축구를 엄청 잘해요', '삼바 축제가 있어요', '아마존 숲이 있어요', '남미에 있어요', '커피가 많이 나요']),
|
||||
w('호주', ['캥거루가 살아요', '코알라가 있어요', '오페라하우스가 있어요', '여름에 크리스마스를 보내요', '섬 하나가 대륙이에요']),
|
||||
w('인도', ['카레가 유명해요', '타지마할이 있어요', '사람이 아주 많아요', '요가가 시작된 곳이에요', '소를 아낀대요']),
|
||||
w('이집트', ['피라미드가 있어요', '사막이 넓어요', '미라가 생각나요', '나일강이 흘러요', '스핑크스가 있어요']),
|
||||
w('캐나다', ['단풍잎이 국기에 있어요', '메이플 시럽이 유명해요', '겨울이 아주 추워요', '미국 바로 위에 있어요', '나이아가라 폭포가 있어요']),
|
||||
w('러시아', ['땅이 세계에서 제일 넓어요', '아주 추워요', '모스크바가 수도예요', '인형 안에 인형이 들어 있어요', '양파 모양 지붕이 있어요']),
|
||||
w('독일', ['소시지랑 맥주가 유명해요', '자동차를 잘 만들어요', '베를린이 수도예요', '축구를 잘해요', '맥주 축제가 있어요']),
|
||||
w('스페인', ['투우가 유명했어요', '플라멩코 춤이 있어요', '파에야를 먹어요', '마드리드가 수도예요', '축구 팀들이 유명해요']),
|
||||
w('멕시코', ['타코를 먹어요', '챙 넓은 모자가 생각나요', '선인장이 많아요', '매운 음식을 좋아해요', '미국 바로 아래에 있어요']),
|
||||
w('태국', ['코끼리를 아껴요', '똠얌꿍이 유명해요', '방콕이 수도예요', '따뜻한 휴양지가 많아요', '쌀국수 같은 면 요리가 많아요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fairy',
|
||||
ko: '동화 주인공',
|
||||
generic: ['어릴 때 읽었어요', '아주 유명한 이야기예요', '그림책으로 봤어요', '교훈이 있는 이야기예요', '엄마가 읽어 줬어요'],
|
||||
words: [
|
||||
w('신데렐라', ['밤 열두 시가 되면 큰일 나요', '유리 구두를 잃어버려요', '호박이 마차가 돼요', '새엄마랑 언니들이 괴롭혀요', '요정 할머니가 도와줘요']),
|
||||
w('백설공주', ['피부가 아주 하얘요', '독이 든 사과를 먹어요', '일곱 난쟁이랑 살아요', '왕비가 거울에게 물어봐요', '숲으로 도망쳐요']),
|
||||
w('피노키오', ['거짓말을 하면 코가 길어져요', '나무로 만든 인형이에요', '제페토 할아버지가 만들었어요', '고래 뱃속에 들어가요', '진짜 아이가 되고 싶어 해요']),
|
||||
w('피터팬', ['어른이 되지 않아요', '하늘을 날아다녀요', '후크 선장이랑 싸워요', '작은 요정 친구가 있어요', '네버랜드에 살아요']),
|
||||
w('인어공주', ['바닷속에 살아요', '목소리를 잃어요', '다리가 생겨요', '마지막에 물거품이 돼요', '왕자를 구해 줘요']),
|
||||
w('라푼젤', ['머리카락이 엄청 길어요', '높은 탑에 갇혀 있어요', '머리카락을 내려 줘요', '마녀가 키웠어요', '창문으로 밖을 내다봐요']),
|
||||
w('앨리스', ['토끼를 따라가요', '이상한 나라에 가요', '작아졌다 커졌다 해요', '카드 여왕을 만나요', '모자 장수랑 차를 마셔요']),
|
||||
w('빨간모자', ['할머니 댁에 심부름을 가요', '숲속에서 늑대를 만나요', '할머니 귀가 왜 이렇게 크냐고 물어요', '사냥꾼이 구해 줘요', '바구니를 들고 가요'], ['빨간망토', '빨간두건']),
|
||||
w('흥부', ['착한 동생이에요', '제비 다리를 고쳐 줘요', '박을 타니 보물이 나와요', '식구가 아주 많아요', '형한테 쫓겨나요']),
|
||||
w('놀부', ['욕심이 많은 형이에요', '제비 다리를 일부러 부러뜨려요', '박에서 도깨비가 나와요', '동생을 쫓아내요', '나중에 반성해요']),
|
||||
w('심청이', ['아버지 눈을 뜨게 하고 싶어 해요', '바다에 몸을 던져요', '연꽃을 타고 돌아와요', '효녀로 유명해요', '공양미 삼백 석이 나와요'], ['심청']),
|
||||
w('콩쥐', ['밑 빠진 독에 물을 부어야 해요', '두꺼비가 도와줘요', '새엄마가 괴롭혀요', '꽃신을 잃어버려요', '이름이 곡식이랑 비슷한 자매가 있어요']),
|
||||
w('나무꾼', ['산에서 나무를 해요', '사슴을 숨겨 줘요', '날개옷을 감춰요', '하늘로 올라간 가족을 그리워해요', '연못에 도끼를 빠뜨린 이야기도 있어요']),
|
||||
w('별주부', ['용왕님을 위해 육지로 가요', '토끼의 간을 구하러 가요', '바닷속에서 왔어요', '토끼에게 속아요', '등껍질이 있어요'], ['자라']),
|
||||
w('혹부리영감', ['얼굴에 커다란 혹이 있어요', '도깨비들 앞에서 노래해요', '노래 주머니라고 속여요', '욕심쟁이 이웃은 혹을 하나 더 받아요', '산속 빈집에서 밤을 보내요'], ['혹부리']),
|
||||
w('알라딘', ['요술 램프를 문질러요', '소원을 세 가지 들어줘요', '하늘을 나는 양탄자를 타요', '원숭이 친구가 있어요', '사막 나라 이야기예요']),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const topicById = (id: TopicId): LiarTopic => TOPICS.find((t) => t.id === id)!;
|
||||
|
||||
export function wordEntry(topic: TopicId, word: string): LiarWord | undefined {
|
||||
return topicById(topic).words.find((x) => x.word === word);
|
||||
}
|
||||
@@ -24,7 +24,8 @@ export function botProfile(id: string): PublicUser | null {
|
||||
/**
|
||||
* Games that offer computer players. Real-time and drawing games (도블, 할리갈리, 그림 맞히기) don't: a bot there is
|
||||
* either unbeatable or meaningless. 마피아 has talking computers (2026-10-11). 사과 게임 is a race where everyone solves
|
||||
* their own copy of the board, so a computer simply races too at its level's speed (2026-10-12).
|
||||
* their own copy of the board, so a computer simply races too at its level's speed (2026-10-12). 라이어 게임 has
|
||||
* talking computers like 마피아 (2026-10-12).
|
||||
*/
|
||||
export const BOT_GAMES: readonly string[] = [
|
||||
'omok',
|
||||
@@ -55,18 +56,19 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'clue',
|
||||
'connect-four',
|
||||
'uno',
|
||||
'liar',
|
||||
];
|
||||
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */
|
||||
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6 };
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */
|
||||
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6, liar: 5 };
|
||||
|
||||
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
|
||||
|
||||
/**
|
||||
* Games where computers must talk to play at all (마피아 토론): their computers always speak, whatever the room's
|
||||
* Games where computers must talk to play at all (마피아 토론, 라이어 게임 설명·토론): their computers always speak, whatever the room's
|
||||
* "컴퓨터 채팅" setting says. In every other game the computers' small talk is off unless the host turns it on.
|
||||
*/
|
||||
export const BOT_CHAT_REQUIRED: readonly string[] = ['mafia'];
|
||||
export const BOT_CHAT_REQUIRED: readonly string[] = ['mafia', 'liar'];
|
||||
|
||||
export const botChatRequired = (gameId: string): boolean => BOT_CHAT_REQUIRED.includes(gameId);
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
|
||||
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
|
||||
{ id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true },
|
||||
{ id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true },
|
||||
];
|
||||
|
||||
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);
|
||||
|
||||
Reference in New Issue
Block a user