라이어 게임: 관리자 화면에서 주제·제시어 추가/수정/삭제, 바보 모드 라이어는 비슷한 단어(같은 묶음)

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 04:16:17 +09:00
parent 5a878ba991
commit 1bd69200fd
46 changed files with 1639 additions and 75 deletions

View File

@@ -22,7 +22,7 @@
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 36개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만. - 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 36개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드. - 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드. - 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록. - 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
## 개발 ## 개발
```bash ```bash

View File

@@ -2,6 +2,8 @@
import { afterEach, describe, expect, test } from 'bun:test'; import { afterEach, describe, expect, test } from 'bun:test';
import { Client, TEST_SUPERADMINS, api, boot, guest, sleep } from './test-utils'; import { Client, TEST_SUPERADMINS, api, boot, guest, sleep } from './test-utils';
import { GUEST_IDLE_MS } from './server'; import { GUEST_IDLE_MS } from './server';
import { TOPICS, bankTopics, liarBankRef, setLiarBank, setLiarBankResolver, type LiarState } from '@bg/games/liar';
import type { Conn, Room } from './rooms/room';
const [SUPER, SUPER2] = TEST_SUPERADMINS; const [SUPER, SUPER2] = TEST_SUPERADMINS;
type Booted = ReturnType<typeof boot>; type Booted = ReturnType<typeof boot>;
@@ -11,6 +13,9 @@ const clients: Client[] = [];
afterEach(async () => { afterEach(async () => {
for (const c of clients.splice(0)) c.close(); for (const c of clients.splice(0)) c.close();
for (const s of running.splice(0)) await s.stop(); for (const s of running.splice(0)) await s.stop();
// The 라이어 word bank is process-wide (the game module holds it): back to the code's for the next test.
setLiarBank(TOPICS, null);
setLiarBankResolver(null);
}); });
function start(): Booted { function start(): Booted {
@@ -142,6 +147,109 @@ describe('game settings', () => {
}); });
}); });
describe('라이어 게임 제시어 (§4.1)', () => {
const topic = {
ko: '우리 반',
generic: ['교실에 있어요', '매일 봐요'],
words: [
{ word: '칠판', hints: ['앞에 걸려 있어요', '분필로 써요'], aliases: ['흑판'], group: '앞' },
{ word: '교탁', hints: ['선생님 자리예요'], group: '앞' },
{ word: '사물함', hints: ['뒤에 있어요', '자물쇠를 달아요'], group: '뒤' },
{ word: '청소함', hints: ['빗자루가 들어 있어요'], group: '뒤' },
],
};
const send = (s: Booted, cookie: string, method: string, path: string, body?: unknown) =>
api(s.base, `/api/admin/liar${path}`, { method, cookie, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
test('추가·수정·삭제·되돌리기, 잘못된 단어는 이유와 함께 거절, 일반 사용자는 403, 모두 기록', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);
const plain = await discordLogin(s, '111111111111111111');
expect((await send(s, plain.cookie, 'GET', '/topics')).res.status).toBe(403);
expect((await send(s, plain.cookie, 'POST', '/topics', topic)).res.status).toBe(403);
const list = await send(s, sup.cookie, 'GET', '/topics');
expect(list.body.topics.map((t: any) => t.id)).toEqual(TOPICS.map((t) => t.id));
expect(list.body.topics[0]).toMatchObject({ id: 'fruit', builtin: true, modified: false, deleted: false });
expect(list.body.topics[0].words[0].group).toBeTruthy();
// Problems come back in Korean: the word inside its own hint, and one word inside another.
const bad = await send(s, sup.cookie, 'POST', '/topics', { ...topic, words: [...topic.words, { word: '큰칠판', hints: ['큰 칠판이에요'] }] });
expect(bad.res.status).toBe(400);
expect(bad.body.error).toContain("'큰칠판'의 설명");
expect(bad.body.error).toContain("'칠판'가 '큰칠판' 안에");
const made = await send(s, sup.cookie, 'POST', '/topics', topic);
expect(made.res.status).toBe(200);
const id = made.body.topic.id as string;
expect(id).toMatch(/^c_[a-z0-9]+$/);
expect(made.body.topic).toMatchObject({ ko: '우리 반', builtin: false, deleted: false });
expect((await api(s.base, '/api/liar/topics')).body.topics.at(-1)).toEqual({ id, ko: '우리 반', words: 4 });
// Edit a built-in topic (drop 수박), then reset it.
const fruit = list.body.topics[0];
const edited = await send(s, sup.cookie, 'PUT', '/topics/fruit', { ko: fruit.ko, generic: fruit.generic, words: fruit.words.filter((w: any) => w.word !== '수박') });
expect(edited.res.status).toBe(200);
expect(edited.body.topic).toMatchObject({ builtin: true, modified: true });
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(false);
expect((await send(s, sup.cookie, 'POST', '/topics/fruit/reset')).body.topic.modified).toBe(false);
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(true);
// Delete: a built-in topic is hidden (and can come back), an admin's own is gone.
expect((await send(s, sup.cookie, 'DELETE', '/topics/person')).res.status).toBe(200);
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(false);
expect((await send(s, sup.cookie, 'GET', '/topics')).body.topics.find((t: any) => t.id === 'person')).toMatchObject({ deleted: true });
await send(s, sup.cookie, 'POST', '/topics/person/reset');
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(true);
expect((await send(s, sup.cookie, 'DELETE', `/topics/${id}`)).res.status).toBe(200);
expect((await send(s, sup.cookie, 'PUT', `/topics/${id}`, topic)).res.status).toBe(404);
expect(liarBankRef()).toBeNull();
const audit = await api(s.base, '/api/admin/audit', { cookie: sup.cookie });
expect(audit.body.entries.map((e: any) => e.action)).toEqual(['liar.topic.delete', 'liar.topic.reset', 'liar.topic.delete', 'liar.topic.reset', 'liar.topic.update', 'liar.topic.create']);
});
test('새 판은 고친 은행을 쓰고 그 판본을 옵션에 남겨요. 은행을 또 고쳐도 지난 판본은 남고, 서버를 다시 켜도 그대로', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);
const id = (await send(s, sup.cookie, 'POST', '/topics', topic)).body.topic.id as string;
const ref = liarBankRef()!;
expect(ref).toBeTruthy();
const host = await guest(s.base, '방장');
const room = s.rooms.createPractice(host.id, 'liar') as Room;
const conn: Conn = { userId: host.id, send: () => {}, close: () => {} };
room.join(conn, 'player');
expect(room.configure(host.id, { options: { ...(room.config.options as object), topic: id, foolMode: true } })).toBeNull();
expect(room.start(host.id)).toBeNull();
for (let i = 0; i < 200 && !room.game; i++) await sleep(10);
const st = room.game!.state as LiarState;
expect(st.topic).toBe(id);
expect(st.options.bank).toBe(ref);
expect(st.words).toEqual(['칠판', '교탁', '사물함', '청소함']);
// 바보 모드: the liar's word is from the same group.
const group = (w: string) => topic.words.find((x) => x.word === w)!.group;
expect(group(st.liarWord!)).toBe(group(st.word));
const stored = s.db.query<{ options_json: string }, []>("SELECT options_json FROM games WHERE game_id = 'liar'").get()!;
expect(JSON.parse(stored.options_json).bank).toBe(ref);
// Another change: a new version; the old one is still found (replays).
await send(s, sup.cookie, 'PUT', `/topics/${id}`, { ...topic, words: topic.words.slice(0, 2) });
expect(liarBankRef()).not.toBe(ref);
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
expect(bankTopics(liarBankRef()).find((t) => t.id === id)!.words).toHaveLength(2);
// Restart on the same database: same bank, same version name.
const now = liarBankRef();
await s.stop();
running.splice(running.indexOf(s), 1);
setLiarBank(TOPICS, null);
const again = boot(s.dbPath);
running.push(again);
expect(liarBankRef()).toBe(now);
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
});
});
describe('admin-only options (threat guides)', () => { describe('admin-only options (threat guides)', () => {
test('off by default; the host cannot turn them on; the admin default always wins and is not shown as a lock', async () => { test('off by default; the host cannot turn them on; the admin default always wins and is not shown as a lock', async () => {
const s = start(); const s = start();

View File

@@ -0,0 +1,153 @@
/**
* 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1): admins replace, delete or add whole topics.
* The changes live in `liar_topics`; the merged bank is handed to the game module (`setLiarBank`) with a version name
* (hash of the changes) that new games carry in their options. Every version is kept in `liar_bank_versions` so a replay
* (or a game restored after a restart) sets up from the bank it started with.
*/
import type { Database } from 'bun:sqlite';
import { z } from 'zod';
import { TOPICS, mergeBank, setLiarBank, setLiarBankResolver, topicProblems, type LiarTopic, type TopicOverride } from '@bg/games/liar';
import { sha256Hex } from '../auth/sessions';
const line = (max: number) => z.string().trim().min(1).max(max);
export const LiarTopicInputSchema = z.object({
ko: line(20),
generic: z.array(line(80)).max(20),
words: z
.array(
z.object({
word: line(20),
aliases: z.array(line(20)).max(10).optional(),
hints: z.array(line(80)).max(10),
group: z.string().trim().max(20).optional(),
}),
)
.max(300),
});
export type LiarTopicInput = z.infer<typeof LiarTopicInputSchema>;
/** Most topics an admin may add. */
export const CUSTOM_TOPICS_MAX = 100;
export interface AdminLiarTopic extends Omit<LiarTopic, 'groups'> {
builtin: boolean;
/** Built-in topic changed by an admin (can be reset). */
modified: boolean;
/** Built-in topic an admin deleted (can be restored). */
deleted: boolean;
}
/** Drops empty optional fields so the stored JSON stays small and stable. */
function clean(t: LiarTopicInput): NonNullable<TopicOverride['topic']> {
return {
ko: t.ko,
generic: t.generic,
words: t.words.map((x) => ({
word: x.word,
hints: x.hints,
...(x.aliases?.length ? { aliases: x.aliases } : {}),
...(x.group ? { group: x.group } : {}),
})),
};
}
export class LiarBankStore {
private rows: TopicOverride[] = [];
private versions = new Map<string, readonly LiarTopic[]>();
constructor(private db: Database) {
this.load();
setLiarBankResolver((ref) => this.version(ref));
}
private load(): void {
this.rows = this.db
.query<{ id: string; json: string }, []>('SELECT id, json FROM liar_topics ORDER BY created_at, id')
.all()
.map((r) => ({ id: r.id, ...(JSON.parse(r.json) as Omit<TopicOverride, 'id'>) }));
const ref = this.rows.length ? sha256Hex(JSON.stringify(this.rows)).slice(0, 16) : null;
const topics = mergeBank(this.rows);
if (ref) {
this.db.query('INSERT OR IGNORE INTO liar_bank_versions (ref, json, created_at) VALUES (?, ?, ?)').run(ref, JSON.stringify(this.rows), Date.now());
this.versions.set(ref, topics);
}
setLiarBank(topics, ref);
}
/** A stored bank version (null if unknown: the game falls back to the bank in the code). */
private version(ref: string): readonly LiarTopic[] | null {
const hit = this.versions.get(ref);
if (hit) return hit;
const row = this.db.query<{ json: string }, [string]>('SELECT json FROM liar_bank_versions WHERE ref = ?').get(ref);
if (!row) return null;
const topics = mergeBank(JSON.parse(row.json) as TopicOverride[]);
if (this.versions.size > 50) this.versions.clear();
this.versions.set(ref, topics);
return topics;
}
/** Every topic for the admin screen: the bank in use (code order, then the admins' own), then deleted built-in ones. */
list(): AdminLiarTopic[] {
const by = new Map(this.rows.map((r) => [r.id, r]));
const out: AdminLiarTopic[] = mergeBank(this.rows).map((t) => {
const builtin = TOPICS.some((b) => b.id === t.id);
return { id: t.id, ko: t.ko, generic: t.generic, words: t.words, builtin, modified: builtin && !!by.get(t.id)?.topic, deleted: false };
});
for (const b of TOPICS) if (by.get(b.id)?.deleted) out.push({ id: b.id, ko: b.ko, generic: b.generic, words: b.words, builtin: true, modified: false, deleted: true });
return out;
}
get(id: string): AdminLiarTopic | null {
return this.list().find((t) => t.id === id) ?? null;
}
/** Problems (Korean) with a topic as typed, or none. */
problems(t: LiarTopicInput): string[] {
return topicProblems(clean(t));
}
private write(id: string, value: Omit<TopicOverride, 'id'>, by: string, now: number): void {
this.db
.query(
'INSERT INTO liar_topics (id, json, created_at, updated_by, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at',
)
.run(id, JSON.stringify(value), now, by, now);
this.load();
}
private remove(id: string): void {
this.db.query('DELETE FROM liar_topics WHERE id = ?').run(id);
this.load();
}
/** Replaces a topic (built-in or the admins' own, also a deleted built-in one: that restores it). Validate first. */
save(id: string, t: LiarTopicInput, by: string, now = Date.now()): void {
this.write(id, { topic: clean(t) }, by, now);
}
/** Adds a topic of the admins' own; returns its id, or null when there are too many. */
create(t: LiarTopicInput, by: string, now = Date.now()): string | null {
if (this.rows.filter((r) => !TOPICS.some((b) => b.id === r.id)).length >= CUSTOM_TOPICS_MAX) return null;
let id: string;
do id = `c_${now.toString(36)}${Math.floor(Math.random() * 36 ** 3).toString(36)}`;
while (this.rows.some((r) => r.id === id));
this.write(id, { topic: clean(t) }, by, now);
return id;
}
/** Deletes a topic: a built-in one is hidden (can be restored), an admin's own is gone. */
delete(id: string, by: string, now = Date.now()): void {
if (TOPICS.some((b) => b.id === id)) this.write(id, { deleted: true }, by, now);
else this.remove(id);
}
/** A built-in topic back to the code's words (undoes a change or a delete). */
reset(id: string): void {
this.remove(id);
}
/** Topics new rooms can pick, for the lobby. */
static choices(topics: readonly LiarTopic[]): { id: string; ko: string; words: number }[] {
return topics.map((t) => ({ id: t.id, ko: t.ko, words: t.words.length }));
}
}

View File

@@ -0,0 +1,5 @@
-- 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1).
-- One row per changed topic: a built-in topic replaced ({"topic":…}) or deleted ({"deleted":true}), or an admin's own topic (id c_…).
CREATE TABLE liar_topics (id TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL, updated_by TEXT, updated_at INTEGER NOT NULL);
-- Every set of changes games were started with (options.bank = ref), so replays set up from the same bank.
CREATE TABLE liar_bank_versions (ref TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL);

View File

@@ -5,6 +5,7 @@ import type { AnyGameDefinition } from '@bg/engine';
import { botProfile, nicknameError, normalizeNickname } from '@bg/shared'; import { botProfile, nicknameError, normalizeNickname } from '@bg/shared';
import type { Audit, Role, Roles } from '../admin/roles'; import type { Audit, Role, Roles } from '../admin/roles';
import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings'; import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings';
import { LiarTopicInputSchema, type LiarBankStore } from '../admin/liar-bank';
import type { Sessions } from '../auth/sessions'; import type { Sessions } from '../auth/sessions';
import { toPublicUser, type Users } from '../auth/users'; import { toPublicUser, type Users } from '../auth/users';
import type { RoomManager } from '../rooms/manager'; import type { RoomManager } from '../rooms/manager';
@@ -19,6 +20,7 @@ export interface AdminDeps {
audit: Audit; audit: Audit;
settings: SettingsStore; settings: SettingsStore;
games: Record<string, AnyGameDefinition>; games: Record<string, AnyGameDefinition>;
liarBank: LiarBankStore;
disconnectUser: (userId: string) => void; disconnectUser: (userId: string) => void;
/** When an idle guest will be deleted; null for members and for guests still online or seated. */ /** When an idle guest will be deleted; null for members and for guests still online or seated. */
guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null; guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null;
@@ -85,6 +87,57 @@ export function createAdminApp(d: AdminDeps) {
return c.json({ effective: d.settings.game(id), raw: {} }); return c.json({ effective: d.settings.game(id), raw: {} });
}); });
// ------------------------------------------------------------ 라이어 게임 topics and words (docs/14-admin.md §4.1)
app.get('/liar/topics', (c) => c.json({ topics: d.liarBank.list() }));
/** Parses and checks a topic as typed; the error response, or the topic. */
const liarInput = async (c: Context<Env>) => {
const parsed = LiarTopicInputSchema.safeParse(await body(c));
if (!parsed.success) return { error: c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join(', ')}` }, 400) };
const problems = d.liarBank.problems(parsed.data);
if (problems.length) return { error: c.json({ error: problems.slice(0, 30).join('\n'), problems }, 400) };
return { topic: parsed.data };
};
app.post('/liar/topics', async (c) => {
const r = await liarInput(c);
if (r.error) return r.error;
const id = d.liarBank.create(r.topic, actor(c));
if (!id) return c.json({ error: '주제는 100개까지 더할 수 있어요.' }, 400);
d.audit.log(actor(c), 'liar.topic.create', id, null, r.topic);
return c.json({ topic: d.liarBank.get(id) });
});
app.put('/liar/topics/:id', async (c) => {
const id = c.req.param('id');
const before = d.liarBank.get(id);
if (!before) return c.json({ error: '없는 주제예요.' }, 404);
const r = await liarInput(c);
if (r.error) return r.error;
d.liarBank.save(id, r.topic, actor(c));
d.audit.log(actor(c), 'liar.topic.update', id, before, r.topic);
return c.json({ topic: d.liarBank.get(id) });
});
app.delete('/liar/topics/:id', (c) => {
const id = c.req.param('id');
const before = d.liarBank.get(id);
if (!before || before.deleted) return c.json({ error: '없는 주제예요.' }, 404);
if (d.liarBank.list().filter((t) => !t.deleted).length <= 1) return c.json({ error: '주제가 하나는 있어야 해요.' }, 400);
d.liarBank.delete(id, actor(c));
d.audit.log(actor(c), 'liar.topic.delete', id, before, null);
return c.json({ ok: true });
});
app.post('/liar/topics/:id/reset', (c) => {
const id = c.req.param('id');
const before = d.liarBank.get(id);
if (!before?.builtin) return c.json({ error: '처음부터 있던 주제만 되돌릴 수 있어요.' }, 400);
d.liarBank.reset(id);
d.audit.log(actor(c), 'liar.topic.reset', id, before, null);
return c.json({ topic: d.liarBank.get(id) });
});
// ------------------------------------------------------------ site // ------------------------------------------------------------ site
app.get('/site', (c) => c.json({ site: d.settings.getSite() })); app.get('/site', (c) => c.json({ site: d.settings.getSite() }));
app.put('/site', async (c) => { app.put('/site', async (c) => {

View File

@@ -2,6 +2,7 @@
import { Hono, type Context } from 'hono'; import { Hono, type Context } from 'hono';
import { deleteCookie, getCookie, setCookie } from 'hono/cookie'; import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
import { z } from 'zod'; import { z } from 'zod';
import { bankTopics, liarBankRef } from '@bg/games/liar';
import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared'; import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared';
import type { Config } from '../config'; import type { Config } from '../config';
import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord'; import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord';
@@ -102,6 +103,9 @@ export function createHttpApp(d: HttpDeps) {
}); });
}); });
// 라이어 게임 topics new games can use (admins may add or delete some): the lobby's 주제 choices.
app.get('/api/liar/topics', (c) => c.json({ topics: bankTopics(liarBankRef()).map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })) }));
app.post('/api/auth/guest', async (c) => { app.post('/api/auth/guest', async (c) => {
if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429); if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null)); const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null));

View File

@@ -904,7 +904,8 @@ export class Room {
if (countErr) return countErr; if (countErr) return countErr;
const eff = this.deps.settings?.game(def.id); const eff = this.deps.settings?.game(def.id);
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.'; if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
return { options: parsed.data }; // Data the server decides (e.g. the admin-edited 라이어 word-bank version) goes with the options, so replays match.
return { options: def.prepareOptions ? def.prepareOptions(parsed.data) : parsed.data };
} }
/** /**

View File

@@ -18,6 +18,7 @@ import { Replays } from './rooms/replay';
import { Gateway, type WsData } from './ws/gateway'; import { Gateway, type WsData } from './ws/gateway';
import { Audit, Roles } from './admin/roles'; import { Audit, Roles } from './admin/roles';
import { SettingsStore } from './admin/settings'; import { SettingsStore } from './admin/settings';
import { LiarBankStore } from './admin/liar-bank';
/** A guest who closed the site and stayed away this long is deleted. */ /** A guest who closed the site and stayed away this long is deleted. */
export const GUEST_IDLE_MS = 24 * 3600_000; export const GUEST_IDLE_MS = 24 * 3600_000;
@@ -57,6 +58,8 @@ export function startServer(opts: StartOptions) {
return u ? toPublicUser(u) : null; return u ? toPublicUser(u) : null;
}; };
const settings = new SettingsStore(db, GAMES); const settings = new SettingsStore(db, GAMES);
// 라이어 게임 words the admins changed: loaded before rooms are restored (their games may use an edited bank).
const liarBank = new LiarBankStore(db);
const roles = new Roles(db, config.superadminDiscordIds); const roles = new Roles(db, config.superadminDiscordIds);
const audit = new Audit(db); const audit = new Audit(db);
const startedAt = Date.now(); const startedAt = Date.now();
@@ -131,6 +134,7 @@ export function startServer(opts: StartOptions) {
admin: { admin: {
audit, audit,
games: GAMES, games: GAMES,
liarBank,
disconnectUser: (id) => gateway.disconnectUser(id), disconnectUser: (id) => gateway.disconnectUser(id),
guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS), guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS),
stats: () => { stats: () => {

View File

@@ -25,6 +25,32 @@ import { fxMs } from '../../lib/motion';
type Kind = LiarView['phase']['kind']; type Kind = LiarView['phase']['kind'];
// ---------------------------------------------------------------- topics (admins may add or delete some)
type TopicChoice = { id: string; ko: string };
/** The topics new games can use; the code's list until the server answers. */
let topicChoices: TopicChoice[] = TOPIC_IDS.map((id) => ({ id, ko: TOPIC_KO[id] }));
let topicsLoad: Promise<TopicChoice[]> | null = null;
function loadTopics(): Promise<TopicChoice[]> {
topicsLoad ??= fetch('/api/liar/topics', { credentials: 'same-origin' })
.then((r) => (r.ok ? (r.json() as Promise<{ topics: TopicChoice[] }>) : Promise.reject(new Error(String(r.status)))))
.then((d) => (topicChoices = d.topics))
.catch(() => ((topicsLoad = null), topicChoices));
return topicsLoad;
}
const topicName = (id: string) => topicChoices.find((t) => t.id === id)?.ko ?? (TOPIC_KO as Record<string, string>)[id] ?? '관리자가 고른 주제';
function useTopicChoices(): TopicChoice[] {
const [list, setList] = useState(topicChoices);
useEffect(() => {
let on = true;
void loadTopics().then((x) => on && setList(x));
return () => {
on = false;
};
}, []);
return list;
}
const PHASE_KO: Record<Kind, string> = { const PHASE_KO: Record<Kind, string> = {
reveal: '제시어 확인', reveal: '제시어 확인',
describe: '한 사람씩 설명', describe: '한 사람씩 설명',
@@ -662,7 +688,7 @@ function FinalReveal({ v, players }: { v: LiarView; players: Record<string, Publ
<h2>🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}</h2> <h2>🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}</h2>
<span>{REASON_KO[f.reason]}.</span> <span>{REASON_KO[f.reason]}.</span>
<span> <span>
제시어 <span className="word">{f.word}</span> · 주제 {TOPIC_KO[f.topic]} 제시어 <span className="word">{f.word}</span> · 주제 {f.topicKo ?? topicName(f.topic)}
{f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''} {f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''}
{f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''} {f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''}
</span> </span>
@@ -954,13 +980,16 @@ const secs = <T extends number>(...v: T[]): [T | null, string][] => [...v.map((x
function Options({ value: o, onChange }: OptionsProps<LiarOptions>) { function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
const [more, setMore] = useState(false); const [more, setMore] = useState(false);
const topics = useTopicChoices();
// A topic an admin deleted plays as 무작위 (shown as such so the host isn't left with a hidden choice).
const topic = o.topic === 'random' || topics.some((t) => t.id === o.topic) ? o.topic : 'random';
const set = (patch: Partial<LiarOptions>) => onChange({ ...o, ...patch }); const set = (patch: Partial<LiarOptions>) => onChange({ ...o, ...patch });
return ( return (
<div className="stack" style={{ gap: 16 }}> <div className="stack" style={{ gap: 16 }}>
<Field label="주제"> <Field label="주제">
<Seg<LiarOptions['topic']> label="주제" value={o.topic} options={[['random', '무작위'], ...TOPIC_IDS.map((t): [LiarOptions['topic'], string] => [t, TOPIC_KO[t]])]} onChange={(topic) => set({ topic })} /> <Seg<string> label="주제" value={topic} options={[['random', '무작위'], ...topics.map((t): [string, string] => [t.id, t.ko])]} onChange={(next) => set({ topic: next })} />
</Field> </Field>
<Field label="바보 모드" help="켜면 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요."> <Field label="바보 모드" help="켜면 라이어도 제시어와 비슷한 다른 단어(같은 묶음)를 받고, 자기가 라이어인지 몰라요.">
<Seg label="바보 모드" value={o.foolMode} options={onOff} onChange={(foolMode) => set({ foolMode })} /> <Seg label="바보 모드" value={o.foolMode} options={onOff} onChange={(foolMode) => set({ foolMode })} />
</Field> </Field>
<Field label="설명 바퀴 수" help="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요."> <Field label="설명 바퀴 수" help="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요.">
@@ -1015,7 +1044,8 @@ function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
} }
function optionsSummary(o: LiarOptions): string { function optionsSummary(o: LiarOptions): string {
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`]; void loadTopics();
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${topicName(o.topic)}`];
if (o.foolMode) parts.push('바보 모드'); if (o.foolMode) parts.push('바보 모드');
parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기'); parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기');
return parts.join(' · '); return parts.join(' · ');
@@ -1038,7 +1068,7 @@ function Rules() {
<li>투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.</li> <li>투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.</li>
<li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li> <li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li>
<li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li> <li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li>
<li>바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.</li> <li>바보 모드: 라이어도 제시어와 비슷한 다른 단어(같은 주제, 같은 묶음)를 받고, 자기가 라이어인지 몰라요.</li>
<li>시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.</li> <li>시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.</li>
</ul> </ul>
<p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p> <p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p>

View File

@@ -7,6 +7,7 @@ import { apiCall, discordLoginUrl, type Role } from '../../net/api';
import { useSession } from '../../store/session'; import { useSession } from '../../store/session';
import { toast } from '../../store/toast'; import { toast } from '../../store/toast';
import { SchemaForm, type JsonSchema } from './SchemaForm'; import { SchemaForm, type JsonSchema } from './SchemaForm';
import { LiarTopicEditor, LiarTopics } from './LiarWords';
import { gameName } from '../../components/GameNotice'; import { gameName } from '../../components/GameNotice';
import { RecordCell, record, recordText, resultLabel, sumStats } from '../../components/PlayerCard'; import { RecordCell, record, recordText, resultLabel, sumStats } from '../../components/PlayerCard';
import type { GameStat } from '../../net/api'; import type { GameStat } from '../../net/api';
@@ -53,6 +54,7 @@ export default function AdminApp() {
const tabs: [string, string, boolean][] = [ const tabs: [string, string, boolean][] = [
['', '대시보드', true], ['', '대시보드', true],
['games', '게임', true], ['games', '게임', true],
['liar', '라이어 제시어', true],
['rooms', '방', true], ['rooms', '방', true],
['site', '사이트', true], ['site', '사이트', true],
['users', '사용자', sup], ['users', '사용자', sup],
@@ -81,6 +83,8 @@ export default function AdminApp() {
<Route index element={<Dashboard />} /> <Route index element={<Dashboard />} />
<Route path="games" element={<Games />} /> <Route path="games" element={<Games />} />
<Route path="games/:id" element={<GameEditor />} /> <Route path="games/:id" element={<GameEditor />} />
<Route path="liar" element={<LiarTopics />} />
<Route path="liar/:id" element={<LiarTopicEditor />} />
<Route path="rooms" element={<Rooms />} /> <Route path="rooms" element={<Rooms />} />
<Route path="site" element={<Site />} /> <Route path="site" element={<Site />} />
{sup && <Route path="users" element={<Users />} />} {sup && <Route path="users" element={<Users />} />}
@@ -851,6 +855,10 @@ const ACTION_KO: Record<string, string> = {
'user.delete': '계정 삭제', 'user.delete': '계정 삭제',
'admin.add': '어드민 추가', 'admin.add': '어드민 추가',
'admin.remove': '어드민 삭제', 'admin.remove': '어드민 삭제',
'liar.topic.create': '라이어 주제 추가',
'liar.topic.update': '라이어 주제·제시어 수정',
'liar.topic.delete': '라이어 주제 삭제',
'liar.topic.reset': '라이어 주제 되돌리기',
}; };
function Audit() { function Audit() {

View File

@@ -0,0 +1,338 @@
/** 관리자: 라이어 게임 주제와 제시어 (docs/14-admin.md §4.1). Changes apply to games started afterwards. */
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router';
import { ConfirmSheet } from '../../components/ui';
import { apiCall } from '../../net/api';
import { toast } from '../../store/toast';
interface Word {
word: string;
aliases?: string[];
hints: string[];
group?: string;
}
interface Topic {
id: string;
ko: string;
generic: string[];
words: Word[];
builtin: boolean;
modified: boolean;
deleted: boolean;
}
const api = (m: 'GET' | 'POST' | 'PUT' | 'DELETE', p: string, b?: unknown) => apiCall<{ topics?: Topic[]; topic?: Topic }>(m, `/api/admin/liar${p}`, b);
const lines = (s: string) =>
s
.split('\n')
.map((x) => x.trim())
.filter(Boolean);
const commas = (s: string) =>
s
.split(',')
.map((x) => x.trim())
.filter(Boolean);
/** `key`: reload when it changes (the editor moves from 'new' to the created topic's id). */
function useTopics(key = ''): [Topic[] | null, () => void] {
const [d, setD] = useState<Topic[] | null>(null);
const load = useCallback(() => {
api('GET', '/topics').then(
(r) => setD(r.topics ?? []),
(e) => toast((e as Error).message, 'error'),
);
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(load, [load]);
return [d, load];
}
function badge(t: Topic): string {
if (t.deleted) return '삭제됨';
if (!t.builtin) return '관리자가 더함';
return t.modified ? '고침' : '기본';
}
export function LiarTopics() {
const nav = useNavigate();
const [topics, reload] = useTopics();
const [ask, setAsk] = useState<{ t: Topic; kind: 'delete' | 'reset' } | null>(null);
if (!topics) return <p className="muted">불러오는 중…</p>;
const live = topics.filter((t) => !t.deleted);
return (
<div className="stack" style={{ gap: 16 }}>
<h1>라이어 게임 제시어</h1>
<p className="muted small">
주제 {live.length}개 · 제시어 {live.reduce((n, t) => n + t.words.length, 0)}개. 바꾼 내용은 새로 시작하는 판부터 쓰여요. 바보 모드의 라이어는 제시어와 같은 &quot;묶음&quot;의 다른 단어를 받아요(묶음이 없거나 혼자면 같은 주제의 아무
단어).
</p>
<button className="btn btn-primary" style={{ alignSelf: 'flex-start' }} onClick={() => nav('/admin/liar/new')}>
+ 새 주제
</button>
<div className="stack" style={{ gap: 8 }}>
{topics.map((t) => (
<div key={t.id} className="card row" style={{ justifyContent: 'space-between', padding: 12, opacity: t.deleted ? 0.6 : 1 }}>
<div className="stack" style={{ gap: 2 }}>
<strong>{t.ko}</strong>
<span className="muted small">
{badge(t)} · 제시어 {t.words.length}개 · 묶음 {new Set(t.words.map((w) => w.group).filter(Boolean)).size}개 · ID {t.id}
</span>
</div>
<div className="row" style={{ gap: 6 }}>
{!t.deleted && (
<button className="btn btn-secondary btn-sm" onClick={() => nav(`/admin/liar/${t.id}`)}>
편집
</button>
)}
{t.builtin && (t.modified || t.deleted) && (
<button className="btn btn-secondary btn-sm" onClick={() => setAsk({ t, kind: 'reset' })}>
{t.deleted ? '다시 살리기' : '처음 값으로'}
</button>
)}
{!t.deleted && (
<button className="btn btn-danger btn-sm" onClick={() => setAsk({ t, kind: 'delete' })}>
삭제
</button>
)}
</div>
</div>
))}
</div>
{ask && (
<ConfirmSheet
title={ask.kind === 'delete' ? `'${ask.t.ko}' 주제를 삭제할까요?` : ask.t.deleted ? `'${ask.t.ko}' 주제를 다시 살릴까요?` : `'${ask.t.ko}' 주제를 처음 값으로 되돌릴까요?`}
body={
ask.kind === 'delete'
? ask.t.builtin
? '새 판에서 이 주제가 나오지 않아요. 나중에 [다시 살리기]로 되돌릴 수 있어요.'
: '관리자가 더한 주제라 지우면 되돌릴 수 없어요.'
: '관리자가 고친 내용이 지워지고 처음부터 있던 제시어로 돌아가요.'
}
confirm={ask.kind === 'delete' ? '삭제' : '되돌리기'}
danger={ask.kind === 'delete'}
onConfirm={async () => {
try {
if (ask.kind === 'delete') await api('DELETE', `/topics/${ask.t.id}`);
else await api('POST', `/topics/${ask.t.id}/reset`);
toast(ask.kind === 'delete' ? '삭제했어요.' : '되돌렸어요.');
} catch (e) {
toast((e as Error).message, 'error', 6000);
}
reload();
}}
onClose={() => setAsk(null)}
/>
)}
</div>
);
}
/** One word as typed in the editor. */
interface WordForm {
word: string;
group: string;
aliases: string;
hints: string;
}
const toForm = (w: Word): WordForm => ({ word: w.word, group: w.group ?? '', aliases: (w.aliases ?? []).join(', '), hints: w.hints.join('\n') });
const fromForm = (f: WordForm): Word => ({ word: f.word.trim(), group: f.group.trim() || undefined, aliases: commas(f.aliases), hints: lines(f.hints) });
const EMPTY: WordForm = { word: '', group: '', aliases: '', hints: '' };
function WordEditor({ value, groups, onSave, onCancel }: { value: WordForm; groups: string[]; onSave: (f: WordForm) => void; onCancel: () => void }) {
const [f, setF] = useState(value);
return (
<div className="card stack" style={{ gap: 10, padding: 12 }}>
<div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
<label className="field" style={{ flex: '1 1 140px' }}>
제시어(두 글자 이상)
<input className="input" value={f.word} maxLength={20} onChange={(e) => setF({ ...f, word: e.target.value })} autoFocus />
</label>
<label className="field" style={{ flex: '1 1 140px' }}>
비슷한 단어 묶음
<input className="input" value={f.group} maxLength={20} list="liar-groups" placeholder="예: 감귤류" onChange={(e) => setF({ ...f, group: e.target.value })} />
</label>
</div>
<label className="field">
정답으로 쳐 줄 다른 표기(쉼표로 구분)
<input className="input" value={f.aliases} placeholder="예: 핸드폰, 스마트폰" onChange={(e) => setF({ ...f, aliases: e.target.value })} />
</label>
<label className="field">
컴퓨터가 쓸 설명(한 줄에 하나, 덜 구체적인 것부터, 제시어는 넣지 않기)
<textarea className="input" style={{ minHeight: 110, padding: 12 }} value={f.hints} onChange={(e) => setF({ ...f, hints: e.target.value })} />
</label>
<datalist id="liar-groups">
{groups.map((g) => (
<option key={g} value={g} />
))}
</datalist>
<div className="row" style={{ gap: 8 }}>
<button className="btn btn-primary btn-sm" disabled={!f.word.trim()} onClick={() => onSave(f)}>
확인
</button>
<button className="btn btn-ghost btn-sm" onClick={onCancel}>
취소
</button>
</div>
</div>
);
}
export function LiarTopicEditor() {
const { id = 'new' } = useParams();
const nav = useNavigate();
const [topics] = useTopics(id);
const isNew = id === 'new';
const t = topics?.find((x) => x.id === id);
const [ko, setKo] = useState('');
const [generic, setGeneric] = useState('');
const [words, setWords] = useState<Word[]>([]);
const [editing, setEditing] = useState<number | 'new' | null>(null);
const [q, setQ] = useState('');
const [errors, setErrors] = useState<string[]>([]);
const [dirty, setDirty] = useState(false);
useEffect(() => {
if (t) {
setKo(t.ko);
setGeneric(t.generic.join('\n'));
setWords(t.words);
}
}, [t]);
const groups = useMemo(() => [...new Set(words.map((w) => w.group).filter((g): g is string => !!g))].sort((x, y) => x.localeCompare(y, 'ko')), [words]);
if (!topics) return <p className="muted">불러오는 중…</p>;
if (!isNew && !t) return <p>없는 주제예요.</p>;
const change = (next: Word[]) => {
setWords(next);
setDirty(true);
};
const putWord = (i: number | 'new', f: WordForm) => {
const w = fromForm(f);
const dup = words.findIndex((x, j) => j !== i && x.word.replace(/\s/g, '') === w.word.replace(/\s/g, ''));
if (dup >= 0) return toast(`'${w.word}'는 이미 있어요.`, 'error');
change(i === 'new' ? [w, ...words] : words.map((x, j) => (j === i ? w : x)));
setEditing(null);
};
const save = async () => {
const body = { ko: ko.trim(), generic: lines(generic), words: words.map((w) => ({ ...w, aliases: w.aliases?.length ? w.aliases : undefined })) };
try {
const r = isNew ? await api('POST', '/topics', body) : await api('PUT', `/topics/${id}`, body);
setErrors([]);
setDirty(false);
toast('저장했어요. 새로 시작하는 판부터 쓰여요.');
if (isNew && r.topic) nav(`/admin/liar/${r.topic.id}`, { replace: true });
} catch (e) {
const msg = (e as Error).message;
setErrors(msg.split('\n'));
toast('저장하지 못했어요. 아래 문제를 고쳐 주세요.', 'error', 6000);
}
};
const norm = q.trim();
const shown = words.map((w, i) => ({ w, i })).filter(({ w }) => !norm || w.word.includes(norm) || (w.group ?? '').includes(norm) || (w.aliases ?? []).some((a) => a.includes(norm)));
const noGroup = words.filter((w) => !w.group).length;
const lonely = groups.filter((g) => words.filter((w) => w.group === g).length < 2);
return (
<div className="stack" style={{ gap: 16 }}>
<button
className="btn btn-ghost"
style={{ alignSelf: 'flex-start' }}
onClick={() => {
if (!dirty || confirm('저장하지 않은 내용이 있어요. 나갈까요?')) nav('/admin/liar');
}}
>
← 주제 목록
</button>
<h1>{isNew ? '새 주제' : `${t!.ko} 주제`}</h1>
<section className="card stack">
<label className="field">
주제 이름(게임 화면에 보여요)
<input
className="input"
value={ko}
maxLength={20}
onChange={(e) => {
setKo(e.target.value);
setDirty(true);
}}
/>
</label>
<label className="field">
무난한 말(한 줄에 하나): 아직 아무 설명도 못 들은 라이어 컴퓨터가 써요. 어느 제시어에나 맞는 말로, 제시어는 넣지 않기
<textarea
className="input"
style={{ minHeight: 100, padding: 12 }}
value={generic}
onChange={(e) => {
setGeneric(e.target.value);
setDirty(true);
}}
/>
</label>
</section>
<section className="card stack">
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
<h2>
제시어 {words.length}개 · 묶음 {groups.length}개
</h2>
<button className="btn btn-secondary btn-sm" onClick={() => setEditing('new')}>
+ 제시어 더하기
</button>
</div>
{(noGroup > 0 || lonely.length > 0) && (
<p className="muted small">
{noGroup > 0 && `묶음이 없는 제시어 ${noGroup}개. `}
{lonely.length > 0 && `혼자인 묶음: ${lonely.join(', ')}. `}
바보 모드에서 이런 제시어가 나오면 라이어는 같은 주제의 아무 단어나 받아요.
</p>
)}
{editing === 'new' && <WordEditor value={EMPTY} groups={groups} onSave={(f) => putWord('new', f)} onCancel={() => setEditing(null)} />}
<input className="input" placeholder="제시어·묶음·다른 표기로 찾기" value={q} onChange={(e) => setQ(e.target.value)} />
<div className="stack" style={{ gap: 6 }}>
{shown.map(({ w, i }) =>
editing === i ? (
<WordEditor key={i} value={toForm(w)} groups={groups} onSave={(f) => putWord(i, f)} onCancel={() => setEditing(null)} />
) : (
<div key={i} className="row" style={{ justifyContent: 'space-between', gap: 8, padding: '6px 4px', borderBottom: '1px solid var(--border, #ddd)' }}>
<div className="stack" style={{ gap: 2, minWidth: 0 }}>
<span>
<strong>{w.word}</strong>
{w.group && <span className="badge" style={{ marginLeft: 6 }}>{w.group}</span>}
{!!w.aliases?.length && <span className="muted small"> · {w.aliases.join(', ')}</span>}
</span>
<span className="muted small" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
설명 {w.hints.length}개{w.hints[0] ? ` · ${w.hints[0]}` : ''}
</span>
</div>
<div className="row" style={{ gap: 6, flexShrink: 0 }}>
<button className="btn btn-secondary btn-sm" onClick={() => setEditing(i)}>
수정
</button>
<button className="btn btn-danger btn-sm" aria-label={`${w.word} 삭제`} onClick={() => change(words.filter((_, j) => j !== i))}>
삭제
</button>
</div>
</div>
),
)}
{shown.length === 0 && <p className="muted small">{words.length ? '찾는 제시어가 없어요.' : '아직 제시어가 없어요. [+ 제시어 더하기]로 넣어 주세요(2개 이상).'}</p>}
</div>
</section>
{errors.length > 0 && (
<section className="card stack" role="alert" style={{ borderColor: 'var(--danger, #c33)' }}>
<strong>저장하지 못했어요</strong>
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>
{errors.map((e, i) => (
<li key={i}>{e}</li>
))}
</ul>
</section>
)}
<div className="bottom-bar sticky-save">
<div className="bottom-bar-inner">
<button className="btn btn-primary" onClick={save}>
저장{dirty ? ' (바뀐 내용 있음)' : ''}
</button>
</div>
</div>
</div>
);
}

View File

@@ -22,6 +22,7 @@
|---|---|---|---| |---|---|---|---|
| 대시보드 | ○ | ○ | 접속 수, 진행 중 방, 오늘/전체 판 수, 사용자 수(게스트/디스코드), 서버 가동 시간·메모리 | | 대시보드 | ○ | ○ | 접속 수, 진행 중 방, 오늘/전체 판 수, 사용자 수(게스트/디스코드), 서버 가동 시간·메모리 |
| 게임 | ○ | ○ | 게임별 설정(4절) | | 게임 | ○ | ○ | 게임별 설정(4절) |
| 라이어 제시어 | ○ | ○ | 라이어 게임 주제·제시어 추가/수정/삭제(4.1절) |
| 방 | ○ | ○ | 열린 방 목록(코드, 게임, 상태, 자리, 관전 수, 만든 시각), 방 닫기 | | 방 | ○ | ○ | 열린 방 목록(코드, 게임, 상태, 자리, 관전 수, 만든 시각), 방 닫기 |
| 사이트 | ○ | ○ | 사이트 설정(5절) | | 사이트 | ○ | ○ | 사이트 설정(5절) |
| 사용자 | × | ○ | 검색(닉네임/ID/디스코드 ID), 상세(전적·로그인 방식·접속 시각), 닉네임 변경, 이용 제한/해제, 모든 기기 로그아웃, 삭제 | | 사용자 | × | ○ | 검색(닉네임/ID/디스코드 ID), 상세(전적·로그인 방식·접속 시각), 닉네임 변경, 이용 제한/해제, 모든 기기 로그아웃, 삭제 |
@@ -46,6 +47,12 @@
- 저장할 때 스키마로 검사하고, 통과하지 못하면 저장하지 않는다. - 저장할 때 스키마로 검사하고, 통과하지 못하면 저장하지 않는다.
- 바꾼 설정은 **새로 만드는 방과 새로 시작하는 판**부터 적용된다. 진행 중인 판의 규칙은 중간에 바뀌지 않는다(공정성). - 바꾼 설정은 **새로 만드는 방과 새로 시작하는 판**부터 적용된다. 진행 중인 판의 규칙은 중간에 바뀌지 않는다(공정성).
### 4.1 라이어 게임 제시어
- 주제 목록(기본 / 고침 / 관리자가 더함 / 삭제됨, 제시어 수, 묶음 수) → [편집]·[삭제]·[처음 값으로]·[다시 살리기], [+ 새 주제].
- 주제 편집: 주제 이름, 무난한 말(한 줄에 하나), 제시어 목록(찾기), 제시어마다 비슷한 단어 묶음·다른 표기·컴퓨터 설명. [저장]하면 검사 후 저장, 문제가 있으면 이유 목록.
- 새로 시작하는 판부터 적용, 진행 중인 판은 그대로. 자세한 규칙은 `docs/games/liar.md` §3.1.
- 저장: `liar_topics`(바뀐 주제), `liar_bank_versions`(판본, 다시 보기용). 기록: `liar.topic.create/update/delete/reset`.
## 5. 사이트 설정 ## 5. 사이트 설정
| 항목 | 기본값 | 효과 | | 항목 | 기본값 | 효과 |
|---|---|---| |---|---|---|
@@ -90,6 +97,9 @@ ALTER TABLE users ADD COLUMN banned_reason TEXT;
| PUT | `/api/admin/games/:id` | 어드민+ | | PUT | `/api/admin/games/:id` | 어드민+ |
| POST | `/api/admin/games/:id/reset` | 어드민+ | | POST | `/api/admin/games/:id/reset` | 어드민+ |
| GET / PUT | `/api/admin/site` | 어드민+ | | GET / PUT | `/api/admin/site` | 어드민+ |
| GET / POST | `/api/admin/liar/topics` | 어드민+ (라이어 주제 목록 / 새 주제) |
| PUT / DELETE | `/api/admin/liar/topics/:id` | 어드민+ (주제 통째로 저장 / 삭제) |
| POST | `/api/admin/liar/topics/:id/reset` | 어드민+ (코드에 있던 주제 되돌리기) |
| GET | `/api/admin/rooms` | 어드민+ | | GET | `/api/admin/rooms` | 어드민+ |
| POST | `/api/admin/rooms/:code/close` | 어드민+ | | POST | `/api/admin/rooms/:code/close` | 어드민+ |
| GET | `/api/admin/audit` | 어드민+ | | GET | `/api/admin/audit` | 어드민+ |

View File

@@ -11,8 +11,8 @@
## 2. 모드와 옵션 ## 2. 모드와 옵션
| 옵션 키 | 설명 | 선택지 | 기본값 | | 옵션 키 | 설명 | 선택지 | 기본값 |
|---|---|---|---| |---|---|---|---|
| `topic` | 주제 | `random` / 과일·동물·직업·음식·장소·운동·탈것·물건·나라·동화 주인공·채소·바다 생물·간식·옷·몸·자연·날씨·게임·영화·유명 인물·브랜드·캐릭터·악기·랜드마크 | `random` | | `topic` | 주제 | `random` / 과일·동물·직업·음식·장소·운동·탈것·물건·나라·동화 주인공·채소·바다 생물·간식·옷·몸·자연·날씨·게임·영화·유명 인물·브랜드·캐릭터·악기·랜드마크 / 관리자가 더한 주제(`c_…`). 지워진 주제는 무작위로 | `random` |
| `foolMode` | 바보 모드: 라이어도 같은 주제의 다른 단어를 받고 자기가 라이어인지 모른다 | on / off | off | | `foolMode` | 바보 모드: 라이어도 제시어와 비슷한 다른 단어(같은 주제, 같은 묶음)를 받고 자기가 라이어인지 모른다 | on / off | off |
| `rounds` | 설명 바퀴 수(두 번째 바퀴는 거꾸로) | 1 / 2 | 2 | | `rounds` | 설명 바퀴 수(두 번째 바퀴는 거꾸로) | 1 / 2 | 2 |
| `describeSeconds` | 한 사람 설명 시간 | 15 / 20 / 30 / 45 / 60 / 무제한 | 30 | | `describeSeconds` | 한 사람 설명 시간 | 15 / 20 / 30 / 45 / 60 / 무제한 | 30 |
| `discussionSeconds` | 자유 토론 시간 | 30 / 60 / 90 / 120 / 180 / 무제한 | 90 | | `discussionSeconds` | 자유 토론 시간 | 30 / 60 / 90 / 120 / 180 / 무제한 | 90 |
@@ -26,12 +26,20 @@
- 한 주제 안에서 어떤 단어도 다른 단어 안에 들어 있지 않다(고래/범고래 같은 짝 없음, 테스트로 확인). - 한 주제 안에서 어떤 단어도 다른 단어 안에 들어 있지 않다(고래/범고래 같은 짝 없음, 테스트로 확인).
- 단어마다 컴퓨터가 쓸 설명 문장 5개(`hints`, 앞쪽일수록 덜 구체적)와 정답으로 쳐 줄 다른 표기(`aliases`, 예: 휴대폰 ↔ 핸드폰·스마트폰, 텔레비전 ↔ 티비·TV). - 단어마다 컴퓨터가 쓸 설명 문장 5개(`hints`, 앞쪽일수록 덜 구체적)와 정답으로 쳐 줄 다른 표기(`aliases`, 예: 휴대폰 ↔ 핸드폰·스마트폰, 텔레비전 ↔ 티비·TV).
- 주제마다 어느 단어에나 맞는 무난한 말(`generic`) 5개: 아직 아무 설명도 못 들은 라이어 컴퓨터가 쓴다. - 주제마다 어느 단어에나 맞는 무난한 말(`generic`) 5개: 아직 아무 설명도 못 들은 라이어 컴퓨터가 쓴다.
- **비슷한 단어 묶음**(`groups`, 2026-10-18 사용자 요청 "바보모드에서 라이어한테는 비슷한 주제를 주도록 단어 분석해서 정리"): 주제마다 설명할 때 비슷한 말이 나올 단어끼리 묶었다(예: 과일 → 감귤류·베리류·여름 박과 과일, 동물 → 고양이과 맹수·가금류, 유명 인물 → 걸그룹·트로트 가수·예능 MC). 23개 주제에 묶음 391개, 묶음 하나에 2~8개. 모든 단어가 정확히 한 묶음에 들어 있다(테스트, `bun scripts/liar-groups-check.ts`).
- 테스트가 확인: 설명 문장에 그 단어(다른 표기 포함, 띄어쓰기 무시)가 없음, 무난한 말에 주제의 어떤 단어도 없음, 모두 고운 말 필터 통과, 80자 이하. - 테스트가 확인: 설명 문장에 그 단어(다른 표기 포함, 띄어쓰기 무시)가 없음, 무난한 말에 주제의 어떤 단어도 없음, 모두 고운 말 필터 통과, 80자 이하.
- 한 글자 단어(배, 귤, 컵 …)는 넣지 않았다: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막는다. - 한 글자 단어(배, 귤, 컵 …)는 넣지 않았다: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막는다.
### 3.1 관리자가 고치는 제시어 (2026-10-18 사용자 요청: "관리자 페이지에서 라이어게임 주제랑 제시어 추가, 삭제, 수정")
- 관리자 화면 → **라이어 제시어**(`/admin/liar`): 주제 추가·이름 바꾸기·삭제, 제시어 추가·수정·삭제(제시어, 비슷한 단어 묶음, 정답으로 쳐 줄 다른 표기, 컴퓨터가 쓸 설명), 무난한 말. 코드에 있던 주제는 지워도 [다시 살리기], 고쳐도 [처음 값으로]로 되돌릴 수 있다.
- 저장할 때 위 테스트와 같은 검사(`topicProblems`)를 한다: 제시어 2개 이상·두 글자 이상·20자 이하·중복 없음·서로 포함 없음, 설명과 무난한 말에 제시어 없음, 고운 말, 80자 이하. 걸리면 이유를 모두 보여 주고 저장하지 않는다.
- 저장: 바뀐 주제만 통째로 `liar_topics`에 둔다(나머지 주제는 코드 그대로라 코드 업데이트가 반영된다). 서버는 합친 은행과 그 판본 이름(바뀐 내용의 해시)을 게임 모듈에 알려 주고(`setLiarBank`), 새 판의 옵션에 `bank: 판본`을 붙인다(`prepareOptions`). 모든 판본은 `liar_bank_versions`에 남아 다시 보기와 재시작 뒤 복구가 같은 은행으로 다시 돌린다.
- 판이 시작되면 그 판에 필요한 것(주제 이름, 주제 단어 목록, 다른 표기)을 상태에 복사한다. 그래서 진행 중에 관리자가 고쳐도 그 판은 바뀌지 않고, 바꾼 내용은 **새로 시작하는 판부터** 쓰인다.
- 대기실의 주제 목록은 `GET /api/liar/topics`(주제 ID·이름·제시어 수)에서 받는다.
## 4. 준비(셋업) ## 4. 준비(셋업)
1. 주제(무작위면 23개 중 하나), 그 주제의 제시어 하나, 라이어 한 명을 서버 시드 난수로 뽑는다. 1. 주제(무작위면 지금 은행의 주제 중 하나), 그 주제의 제시어 하나, 라이어 한 명을 서버 시드 난수로 뽑는다.
2. 바보 모드면 라이어에게 같은 주제의 다른 단어 하나를 준다. 2. 바보 모드면 라이어에게 제시어와 **같은 묶음**의 다른 단어 하나를 준다. 묶음이 없거나 혼자인 단어(관리자가 묶음을 안 적은 경우)면 같은 주제의 아무 다른 단어.
3. 첫 발언자를 무작위로 정하고, 그 사람부터 자리 순서대로 돈다. 라이어도 첫 발언자가 될 수 있다(라이어를 빼면 "첫 사람은 시민"이라는 정보가 생기므로). 3. 첫 발언자를 무작위로 정하고, 그 사람부터 자리 순서대로 돈다. 라이어도 첫 발언자가 될 수 있다(라이어를 빼면 "첫 사람은 시민"이라는 정보가 생기므로).
## 5. 진행 규칙 ## 5. 진행 규칙
@@ -85,7 +93,8 @@
### 8.1 상태(State) ### 8.1 상태(State)
```ts ```ts
interface LiarState { interface LiarState {
options; players: { id; left }[]; topic; word; liar; liarWord /* 바보 모드 */; order /* 1바퀴 순서 */; options /* + bank: 제시어 은행 판본 */; players: { id; left }[]; topic; topicKo; words /* 주제 단어 */; aliases /* 다른 표기 */;
word; liar; liarWord /* 바보 모드 */; order /* 1바퀴 순서 */;
phase: reveal{ready} | describe{round, turn} | discussion{ready} | vote{round 1|2, candidates, votes} | guess | ended; phase: reveal{ready} | describe{round, turn} | discussion{ready} | vote{round 1|2, candidates, votes} | guess | ended;
descriptions: { n, round, from, text | null }[]; chat: { n, from, text, at }[]; descriptions: { n, round, from, text | null }[]; chat: { n, from, text, at }[];
events: PublicEvent[]; accused; guess; seq; final: LiarFinal | null; events: PublicEvent[]; accused; guess; seq; final: LiarFinal | null;
@@ -134,6 +143,8 @@ interface LiarState {
## 10. 테스트 체크리스트 ## 10. 테스트 체크리스트
- [x] 제시어 은행: 주제 23개, 단어 50개 이상, 주제 안 단어끼리 포함 관계 없음, 설명 4개 이상, 설명에 단어 없음, 고운 말 필터 (`liar.test.ts`) - [x] 제시어 은행: 주제 23개, 단어 50개 이상, 주제 안 단어끼리 포함 관계 없음, 설명 4개 이상, 설명에 단어 없음, 고운 말 필터 (`liar.test.ts`)
- [x] 비슷한 단어 묶음: 모든 단어가 한 묶음, 묶음 2개 이상, 바보 모드 라이어 단어가 같은 묶음
- [x] 관리자 수정: 판본을 옵션에 붙임, 진행 중 판은 은행이 바뀌어도 그대로, 지난 판본으로 다시 보기, 지워진 주제는 무작위, 잘못된 주제 거절 (`liar.test.ts`, `apps/server/src/admin.test.ts`, `e2e/admin.e2e.ts`)
- [x] 정답 비교(띄어쓰기·대소문자·다른 표기) - [x] 정답 비교(띄어쓰기·대소문자·다른 표기)
- [x] 라이어·관전 화면에 제시어 없음, 시민 화면은 라이어가 누구든 같음, 바보 모드 화면 모양 같음 - [x] 라이어·관전 화면에 제시어 없음, 시민 화면은 라이어가 누구든 같음, 바보 모드 화면 모양 같음
- [x] 설명 순서(두 번째 바퀴 거꾸로), 넘김, 80자, 제시어 금지(라이어는 안 막음) - [x] 설명 순서(두 번째 바퀴 거꾸로), 넘김, 80자, 제시어 금지(라이어는 안 막음)

View File

@@ -144,10 +144,61 @@ try {
if (cfg !== 150) throw new Error(`chatSound not saved: ${cfg}`); if (cfg !== 150) throw new Error(`chatSound not saved: ${cfg}`);
}); });
await step('라이어 제시어: 과일에 제시어 더하기(묶음·다른 표기·설명) → 저장 → 새 주제 추가', async () => {
await a.locator('.admin-side').getByRole('link', { name: '라이어 제시어', exact: true }).click();
await a.getByRole('heading', { name: '라이어 게임 제시어' }).waitFor();
await a.locator('.card:has(strong:text-is("과일"))').getByRole('button', { name: '편집' }).click();
await a.getByRole('heading', { name: '과일 주제' }).waitFor();
await a.getByRole('button', { name: '+ 제시어 더하기' }).click();
await a.getByLabel('제시어(두 글자 이상)').fill('람부탄');
await a.getByLabel('비슷한 단어 묶음').fill('열대 과일');
await a.getByLabel(/정답으로 쳐 줄 다른 표기/).fill('람부땅');
await a.getByLabel(/컴퓨터가 쓸 설명/).fill('겉에 털 같은 가시가 있어요\n껍질을 까면 하얀 속살이 나와요');
await a.getByRole('button', { name: '확인', exact: true }).click();
await a.getByText('설명 2개 · 겉에 털 같은 가시가 있어요').waitFor();
await a.screenshot({ path: join(SHOTS, 'admin-7-liar-words.png') });
await a.getByRole('button', { name: /^저장/ }).click();
await a.getByText('저장했어요. 새로 시작하는 판부터 쓰여요.').waitFor();
const fruit = await a.evaluate(async () => (await (await fetch('/api/admin/liar/topics')).json()).topics.find((t: any) => t.id === 'fruit'));
const w = fruit.words.find((x: any) => x.word === '람부탄');
if (!fruit.modified || w?.group !== '열대 과일' || w.aliases?.[0] !== '람부땅') throw new Error(`liar word not saved: ${JSON.stringify(w)}`);
// A word inside its own hint is refused with the reason.
await a.getByRole('button', { name: '+ 제시어 더하기' }).click();
await a.getByLabel('제시어(두 글자 이상)').fill('잭프루트');
await a.getByLabel(/컴퓨터가 쓸 설명/).fill('잭프루트는 아주 커요');
await a.getByRole('button', { name: '확인', exact: true }).click();
await a.getByRole('button', { name: /^저장/ }).click();
await a.getByRole('alert').getByText(/'잭프루트'의 설명/).waitFor();
await a.getByRole('button', { name: '잭프루트 삭제' }).click();
await a.getByRole('button', { name: /^저장/ }).click();
await a.getByText('저장했어요. 새로 시작하는 판부터 쓰여요.').last().waitFor();
await a.getByRole('button', { name: '← 주제 목록' }).click();
await a.getByRole('button', { name: '+ 새 주제' }).click();
await a.getByLabel('주제 이름(게임 화면에 보여요)').fill('우리 반');
for (const [word, hint] of [
['칠판', '앞에 걸려 있어요'],
['사물함', '뒤에 있어요'],
]) {
await a.getByRole('button', { name: '+ 제시어 더하기' }).click();
await a.getByLabel('제시어(두 글자 이상)').fill(word!);
await a.getByLabel(/컴퓨터가 쓸 설명/).fill(hint!);
await a.getByRole('button', { name: '확인', exact: true }).click();
}
await a.getByRole('button', { name: /^저장/ }).click();
await a.waitForURL(/\/admin\/liar\/c_/);
const topics = await a.evaluate(async () => (await (await fetch('/api/liar/topics')).json()).topics);
if (topics.at(-1)?.ko !== '우리 반' || topics.at(-1)?.words !== 2) throw new Error(`new topic missing: ${JSON.stringify(topics.at(-1))}`);
await a.getByRole('button', { name: '← 주제 목록' }).click();
await a.getByText('관리자가 더함 · 제시어 2개').waitFor();
await a.screenshot({ path: join(SHOTS, 'admin-8-liar-topics.png') });
});
await step('기록 탭에 변경 내역', async () => { await step('기록 탭에 변경 내역', async () => {
await a.locator('.admin-side').getByRole('link', { name: '기록', exact: true }).click(); await a.locator('.admin-side').getByRole('link', { name: '기록', exact: true }).click();
await a.getByText('어드민 추가').waitFor(); await a.getByText('어드민 추가').waitFor();
await a.getByText('게임 설정 변경').waitFor(); await a.getByText('게임 설정 변경').waitFor();
await a.getByText('라이어 주제 추가').waitFor();
}); });
await step('게스트의 새 오목 방: 렌주룰 · 45초 + 잠금 안내', async () => { await step('게스트의 새 오목 방: 렌주룰 · 45초 + 잠금 안내', async () => {
@@ -175,6 +226,23 @@ try {
await g.getByText('권한이 없어요').waitFor(); await g.getByText('권한이 없어요').waitFor();
}); });
await step('게스트의 새 라이어 방: 관리자가 더한 주제를 고를 수 있어요', async () => {
const g = await (await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ko-KR' })).newPage();
g.on('pageerror', (e) => errors.push(e.message));
await g.goto(ORIGIN + '/');
await g.getByRole('button', { name: '+ 방 만들기' }).click();
await g.getByRole('dialog', { name: '게임 고르기' }).getByRole('button', { name: /라이어 게임/ }).click();
await g.getByLabel('내 이름(닉네임)').fill('손님둘');
await g.getByRole('button', { name: '이 이름으로 시작하기' }).click();
await g.waitForURL(/\/r\/\d{6}$/);
await g.getByRole('button', { name: '설정 바꾸기' }).click();
await g.getByRole('group', { name: '주제' }).getByRole('button', { name: '우리 반' }).click();
await g.waitForTimeout(300);
await g.screenshot({ path: join(SHOTS, 'admin-9-liar-lobby.png') });
await g.getByRole('button', { name: '닫기' }).click();
await g.getByText(/주제 우리 반/).first().waitFor();
});
if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`); if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`);
} catch (e) { } catch (e) {
failed = true; failed = true;

View File

@@ -60,6 +60,11 @@ export interface GameDefinition<S, A, V, O> {
ownChat?: boolean; ownChat?: boolean;
/** Extra player-count rule `playersFor` cannot express (e.g. even counts only); Korean reason or null. */ /** Extra player-count rule `playersFor` cannot express (e.g. even counts only); Korean reason or null. */
playerCountError?(options: O, count: number): string | null; playerCountError?(options: O, count: number): string | null;
/**
* Server only, right before a game starts: adds data the server decides to the (already validated) options, e.g. the
* version of an admin-edited word bank. The result is stored with the game, so a replay sets up from the same data.
*/
prepareOptions?(options: O): O;
setup(ctx: SetupContext<O>): S; setup(ctx: SetupContext<O>): S;
/** `ctx.now` is passed by the server (real-time games may rate-limit with it); tests may omit it. */ /** `ctx.now` is passed by the server (real-time games may rate-limit with it); tests may omit it. */
validate(state: S, actor: PlayerId, action: A, ctx?: ValidateContext): Validation; validate(state: S, actor: PlayerId, action: A, ctx?: ValidateContext): Validation;

View File

@@ -4,6 +4,30 @@ export const animal: LiarTopic = {
id: 'animal', id: 'animal',
ko: '동물', ko: '동물',
generic: ['동물원에서 볼 수 있어요', '귀여운 편이에요', '먹이를 잘 먹어요', '사진 찍으면 예쁘게 나와요', '아이들이 좋아해요'], generic: ['동물원에서 볼 수 있어요', '귀여운 편이에요', '먹이를 잘 먹어요', '사진 찍으면 예쁘게 나와요', '아이들이 좋아해요'],
groups: {
반려동물: ['고양이', '강아지', '햄스터', '토끼'],
'고양이과 맹수': ['사자', '호랑이', '표범', '치타'],
'개과 야생동물': ['늑대', '여우', '하이에나', '너구리'],
'초원의 큰 동물': ['코끼리', '코뿔소', '하마', '기린'],
'타고 다니는 동물': ['얼룩말', '당나귀', '조랑말', '낙타'],
'초식 야생동물': ['사슴', '알파카', '캥거루'],
'농장 가축': ['젖소', '돼지', '염소'],
영장류: ['원숭이', '고릴라', '침팬지'],
곰류: ['판다', '북극곰', '코알라'],
느림보: ['나무늘보', '거북이', '달팽이'],
'밤에 다니는 작은 동물': ['박쥐', '두더지', '고슴도치'],
'작은 야생동물': ['다람쥐', '미어캣', '스컹크'],
'헤엄치는 동물': ['돌고래', '수달', '펭귄'],
가금류: ['병아리', '오리', '거위', '칠면조', '수탉'],
'물가 새': ['백조', '홍학', '두루미', '갈매기'],
'이국적인 새': ['공작', '타조', '앵무새'],
'동네 새': ['참새', '비둘기', '까치', '까마귀', '제비', '딱따구리'],
맹금류: ['독수리', '부엉이', '올빼미'],
'날개가 예쁜 곤충': ['나비', '잠자리', '꿀벌', '반딧불이', '무당벌레'],
'풀숲 곤충': ['매미', '메뚜기', '귀뚜라미', '사마귀', '장수풍뎅이'],
'작은 벌레': ['개미', '거미', '지렁이', '모기', '파리'],
'파충류·양서류': ['악어', '도마뱀', '카멜레온', '코브라', '개구리'],
},
words: [ words: [
w('고양이', ['혼자서도 잘 지내요', '높은 곳을 좋아해요', '상자만 보면 들어가요', '밤에 눈이 빛나요', '혀로 털을 자주 골라요'], ['냥이']), w('고양이', ['혼자서도 잘 지내요', '높은 곳을 좋아해요', '상자만 보면 들어가요', '밤에 눈이 빛나요', '혀로 털을 자주 골라요'], ['냥이']),
w('강아지', ['산책을 정말 좋아해요', '꼬리를 흔들어요', '주인이 오면 반겨요', '사람을 잘 따라요', '집을 잘 지켜요'], ['멍멍이']), w('강아지', ['산책을 정말 좋아해요', '꼬리를 흔들어요', '주인이 오면 반겨요', '사람을 잘 따라요', '집을 잘 지켜요'], ['멍멍이']),

View File

@@ -4,6 +4,21 @@ export const body: LiarTopic = {
id: 'body', id: 'body',
ko: '몸', ko: '몸',
generic: ['우리 몸에 있어요', '다치면 아파요', '깨끗이 씻어야 해요', '사람마다 조금씩 달라요', '소중히 지켜야 해요'], generic: ['우리 몸에 있어요', '다치면 아파요', '깨끗이 씻어야 해요', '사람마다 조금씩 달라요', '소중히 지켜야 해요'],
groups: {
눈: ['눈썹', '눈동자', '눈꺼풀'],
'입 속': ['이빨', '잇몸', '혓바닥', '목구멍', '목젖'],
'입 주변': ['입술', '인중', '보조개', '수염'],
'얼굴 부위': ['이마', '콧구멍', '귓불', '관자놀이'],
'머리·목': ['머리카락', '뒤통수', '정수리', '목덜미'],
팔: ['어깨', '팔꿈치', '손목', '겨드랑이'],
손: ['손바닥', '손가락', '손톱', '손등', '지문'],
발: ['발목', '발바닥', '발가락', '발톱', '발뒤꿈치'],
다리: ['허벅지', '무릎', '종아리', '정강이'],
몸통: ['허리', '엉덩이', '배꼽', '가슴'],
'몸속 장기': ['심장', '허파', '위장', '콩팥', '두뇌', '맹장'],
뼈: ['갈비뼈', '척추', '두개골', '쇄골'],
'온몸에 있는 것': ['근육', '피부', '혈관'],
},
words: [ words: [
w('눈썹', ['털이 나 있어요', '두 줄로 나란히 있어요', '화나면 찡그려져요', '그리거나 다듬기도 해요', '눈 바로 위에 있어요']), w('눈썹', ['털이 나 있어요', '두 줄로 나란히 있어요', '화나면 찡그려져요', '그리거나 다듬기도 해요', '눈 바로 위에 있어요']),
w('눈동자', ['반짝반짝 빛나요', '까만색이나 갈색이에요', '동그랗게 생겼어요', '어두우면 커져요', '눈 한가운데에 있어요']), w('눈동자', ['반짝반짝 빛나요', '까만색이나 갈색이에요', '동그랗게 생겼어요', '어두우면 커져요', '눈 한가운데에 있어요']),

View File

@@ -4,6 +4,24 @@ export const brand: LiarTopic = {
id: 'brand', id: 'brand',
ko: '브랜드', ko: '브랜드',
generic: ['로고를 보면 바로 알아요', '광고에서 자주 봐요', '이름을 들으면 다 알아요', '많은 사람이 알고 있어요', '물건이나 간판에 이름이 적혀 있어요'], generic: ['로고를 보면 바로 알아요', '광고에서 자주 봐요', '이름을 들으면 다 알아요', '많은 사람이 알고 있어요', '물건이나 간판에 이름이 적혀 있어요'],
groups: {
'전자 회사': ['삼성', '엘지', '애플', '소니'],
'IT 회사': ['구글', '네이버', '카카오', '마이크로소프트'],
'앱·서비스': ['유튜브', '인스타그램', '넷플릭스', '쿠팡', '배달의민족'],
'대중 자동차': ['현대자동차', '기아', '테슬라'],
'수입 고급차': ['벤츠', '비엠더블유', '페라리', '람보르기니'],
'옷·신발 브랜드': ['나이키', '아디다스', '뉴발란스', '휠라', '푸마', '유니클로'],
명품: ['샤넬', '구찌', '루이비통'],
'햄버거 가게': ['맥도날드', '버거킹', '롯데리아', '맘스터치'],
'치킨 가게': ['케이에프씨', '교촌치킨', '비비큐', '굽네치킨'],
'카페·디저트': ['스타벅스', '이디야', '배스킨라빈스'],
빵집: ['파리바게뜨', '뚜레쥬르', '던킨'],
'식품 회사': ['코카콜라', '펩시', '농심', '오리온'],
'피자·샌드위치': ['도미노피자', '피자헛', '서브웨이'],
'게임·장난감·만화': ['닌텐도', '레고', '디즈니'],
'대형 매장': ['이마트', '코스트코', '이케아'],
생활용품: ['다이소', '올리브영', '모나미'],
},
words: [ words: [
w('삼성', ['우리나라에서 아주 큰 회사예요', '파란색 로고를 써요', '냉장고와 텔레비전을 만들어요', '야구단 라이온즈가 있어요', '갤럭시 휴대폰을 만들어요'], ['samsung']), w('삼성', ['우리나라에서 아주 큰 회사예요', '파란색 로고를 써요', '냉장고와 텔레비전을 만들어요', '야구단 라이온즈가 있어요', '갤럭시 휴대폰을 만들어요'], ['samsung']),
w('엘지', ['집에서 쓰는 가전제품을 만들어요', '우리나라 큰 회사예요', '빨간색 동그란 로고예요', '그램 노트북을 만들어요', '야구단 이름이 트윈스예요'], ['lg']), w('엘지', ['집에서 쓰는 가전제품을 만들어요', '우리나라 큰 회사예요', '빨간색 동그란 로고예요', '그램 노트북을 만들어요', '야구단 이름이 트윈스예요'], ['lg']),

View File

@@ -4,6 +4,24 @@ export const character: LiarTopic = {
id: 'character', id: 'character',
ko: '캐릭터', ko: '캐릭터',
generic: ['아이들이 아주 좋아해요', '인형이나 장난감으로도 나와요', '만화나 영화에서 봤어요', '그림이 그려진 물건이 많아요', '이름을 들으면 다들 알아요'], generic: ['아이들이 아주 좋아해요', '인형이나 장난감으로도 나와요', '만화나 영화에서 봤어요', '그림이 그려진 물건이 많아요', '이름을 들으면 다들 알아요'],
groups: {
'뽀로로 친구들': ['뽀로로', '크롱', '루피', '포비'],
'탈것 캐릭터': ['타요', '로보카폴리', '토마스'],
'유아 동요·애니': ['핑크퐁', '아기상어', '텔레토비', '라바'],
'일본 만화 주인공': ['짱구', '도라에몽', '코난', '나루토', '세일러문', '호빵맨', '케로로'],
포켓몬: ['피카츄', '꼬부기', '잠만보'],
'게임 캐릭터': ['마리오', '루이지', '소닉', '커비'],
'고전 서양 만화': ['미키마우스', '도널드덕', '스누피', '가필드', '스머프'],
'귀여운 하얀 캐릭터': ['헬로키티', '마이멜로디', '쿠로미', '시나모롤', '미피'],
'스폰지밥 친구들': ['스폰지밥', '뚱이', '징징이'],
'우리나라 캐릭터': ['둘리', '또치', '펭수'],
'메신저 캐릭터': ['춘식이', '어피치', '라이언', '브라운'],
'푸근한 곰 캐릭터': ['리락쿠마', '패딩턴', '토토로'],
'디즈니 영화': ['엘사', '올라프', '심바', '스티치'],
'애니메이션 영화': ['우디', '버즈', '니모', '슈렉', '미니언'],
'마블 히어로': ['아이언맨', '스파이더맨', '헐크', '캡틴아메리카', '토르'],
'DC 히어로': ['배트맨', '슈퍼맨', '원더우먼'],
},
words: [ words: [
w('뽀로로', ['눈 덮인 마을에 살아요', '파란 모자를 써요', '동그란 안경을 써요', '노는 게 제일 좋아요', '꼬마 펭귄이에요']), w('뽀로로', ['눈 덮인 마을에 살아요', '파란 모자를 써요', '동그란 안경을 써요', '노는 게 제일 좋아요', '꼬마 펭귄이에요']),
w('크롱', ['초록색이에요', '말을 잘 못하고 이름만 외쳐요', '알에서 태어났어요', '뽀로로랑 같이 살아요', '꼬마 공룡이에요']), w('크롱', ['초록색이에요', '말을 잘 못하고 이름만 외쳐요', '알에서 태어났어요', '뽀로로랑 같이 살아요', '꼬마 공룡이에요']),

View File

@@ -4,6 +4,25 @@ export const clothes: LiarTopic = {
id: 'clothes', id: 'clothes',
ko: '옷', ko: '옷',
generic: ['몸에 걸쳐요', '색깔과 크기가 여러 가지예요', '외출하기 전에 챙겨요', '유행을 타요', '선물로 주기도 해요'], generic: ['몸에 걸쳐요', '색깔과 크기가 여러 가지예요', '외출하기 전에 챙겨요', '유행을 타요', '선물로 주기도 해요'],
groups: {
상의: ['티셔츠', '와이셔츠', '후드티', '맨투맨', '니트', '블라우스'],
'가벼운 겉옷': ['조끼', '카디건', '바람막이', '우비'],
'겨울 외투': ['패딩', '코트', '점퍼', '망토'],
하의: ['청바지', '반바지', '치마', '레깅스'],
'격식 옷': ['정장', '턱시도', '드레스', '원피스'],
단체복: ['교복', '군복', '체육복'],
'전통 옷': ['한복', '저고리', '고무신'],
'속옷·잠옷': ['잠옷', '내복', '기저귀', '양말'],
특수복: ['수영복', '우주복'],
'운동화·실내화': ['운동화', '축구화', '실내화'],
'여름 신발': ['슬리퍼', '샌들'],
'구두·부츠': ['구두', '하이힐', '부츠', '장화'],
'방한 소품': ['장갑', '목도리', '귀마개', '스카프'],
'머리 장식': ['모자', '머리띠', '머리핀'],
'얼굴에 쓰는 것': ['안경', '선글라스', '마스크'],
장신구: ['귀걸이', '목걸이', '반지', '팔찌', '손목시계'],
'매는 것': ['넥타이', '벨트', '멜빵'],
},
words: [ words: [
w('티셔츠', ['편하게 입어요', '머리를 넣어 쑥 입어요', '여름에 반팔로 많이 입어요', '앞에 그림이나 글씨가 있기도 해요', '둥근 목이 많아요']), w('티셔츠', ['편하게 입어요', '머리를 넣어 쑥 입어요', '여름에 반팔로 많이 입어요', '앞에 그림이나 글씨가 있기도 해요', '둥근 목이 많아요']),
w('와이셔츠', ['회사원이 많이 입어요', '단추가 앞에 쭉 있어요', '칼라가 빳빳해요', '넥타이를 매기 좋아요', '다림질을 해야 해요']), w('와이셔츠', ['회사원이 많이 입어요', '단추가 앞에 쭉 있어요', '칼라가 빳빳해요', '넥타이를 매기 좋아요', '다림질을 해야 해요']),

View File

@@ -4,6 +4,27 @@ export const country: LiarTopic = {
id: 'country', id: 'country',
ko: '나라', ko: '나라',
generic: ['비행기를 타고 가야 해요', '꼭 한번 가 보고 싶어요', '유명한 음식이 있어요', '사람이 많이 살아요', '뉴스에서 자주 봐요'], generic: ['비행기를 타고 가야 해요', '꼭 한번 가 보고 싶어요', '유명한 음식이 있어요', '사람이 많이 살아요', '뉴스에서 자주 봐요'],
groups: {
동아시아: ['한국', '중국', '일본', '대만'],
'초원·중앙아시아': ['몽골', '우즈베키스탄', '카자흐스탄'],
'동남아 휴양지': ['태국', '필리핀', '말레이시아'],
인도차이나: ['베트남', '캄보디아', '라오스', '미얀마'],
남아시아: ['인도', '네팔', '스리랑카', '몰디브'],
'사막 나라': ['이집트', '모로코', '사우디아라비아', '아랍에미리트', '카타르'],
북미: ['미국', '캐나다', '멕시코'],
'카리브 섬나라': ['쿠바', '자메이카'],
'남미 축구 강국': ['브라질', '아르헨티나', '우루과이', '칠레'],
'안데스 나라': ['페루', '볼리비아', '에콰도르', '콜롬비아'],
오세아니아: ['호주', '뉴질랜드', '피지'],
'사파리 나라': ['케냐', '탄자니아', '마다가스카르'],
'아프리카 큰 나라': ['남아프리카공화국', '나이지리아', '에티오피아'],
서유럽: ['프랑스', '영국', '독일', '네덜란드', '벨기에', '아일랜드'],
지중해: ['이탈리아', '스페인', '포르투갈', '그리스', '크로아티아', '튀르키예'],
'도시 국가': ['모나코', '바티칸', '싱가포르'],
중부유럽: ['스위스', '오스트리아', '체코', '헝가리'],
북유럽: ['스웨덴', '노르웨이', '핀란드', '덴마크', '아이슬란드'],
동유럽: ['러시아', '우크라이나', '폴란드'],
},
words: [ words: [
w('미국', ['자유의 여신상이 있어요', '달러를 써요', '할리우드가 있어요', '땅이 아주 넓어요', '햄버거가 생각나요'], ['아메리카']), w('미국', ['자유의 여신상이 있어요', '달러를 써요', '할리우드가 있어요', '땅이 아주 넓어요', '햄버거가 생각나요'], ['아메리카']),
w('중국', ['만리장성이 있어요', '인구가 아주 많아요', '빨간색을 좋아한대요', '판다가 살아요', '베이징이 수도예요']), w('중국', ['만리장성이 있어요', '인구가 아주 많아요', '빨간색을 좋아한대요', '판다가 살아요', '베이징이 수도예요']),

View File

@@ -4,6 +4,23 @@ export const fairy: LiarTopic = {
id: 'fairy', id: 'fairy',
ko: '동화 주인공', ko: '동화 주인공',
generic: ['어릴 때 읽었어요', '아주 유명한 이야기예요', '그림책으로 봤어요', '교훈이 있는 이야기예요', '엄마가 읽어 줬어요'], generic: ['어릴 때 읽었어요', '아주 유명한 이야기예요', '그림책으로 봤어요', '교훈이 있는 이야기예요', '엄마가 읽어 줬어요'],
groups: {
'공주 이야기': ['신데렐라', '백설공주', '잠자는숲속의공주', '라푼젤', '인어공주', '엄지공주'],
'형제·자매 전래동화': ['흥부', '놀부', '콩쥐', '팥쥐'],
'하늘나라 인연': ['선녀', '나무꾼', '우렁각시', '견우', '직녀'],
'산속 전래동화': ['도깨비', '산신령', '혹부리영감', '호랑이'],
'옛이야기 주인공': ['심청이', '온달'],
'영웅·의적': ['홍길동', '손오공', '로빈후드'],
아라비안나이트: ['알리바바', '신밧드', '알라딘'],
'동물 이야기': ['곰돌이푸', '베짱이', '거북이', '시골쥐', '별주부', '청개구리'],
'늑대·마녀 이야기': ['빨간모자', '헨젤과그레텔', '아기돼지삼형제', '양치기소년'],
'외롭고 추운 이야기': ['성냥팔이소녀', '미운오리새끼', '행복한왕자', '눈의여왕'],
'마법 걸린 왕자': ['개구리왕자', '야수'],
'속임수 이야기': ['장화신은고양이', '벌거벗은임금님', '피리부는사나이'],
'신기한 세계 여행': ['앨리스', '도로시', '허수아비', '걸리버'],
'소년 주인공': ['피터팬', '피노키오', '어린왕자'],
'고아 소녀 성장기': ['하이디', '빨강머리앤', '키다리아저씨'],
},
words: [ words: [
w('신데렐라', ['밤 열두 시가 되면 큰일 나요', '유리 구두를 잃어버려요', '호박이 마차가 돼요', '새엄마랑 언니들이 괴롭혀요', '요정 할머니가 도와줘요']), w('신데렐라', ['밤 열두 시가 되면 큰일 나요', '유리 구두를 잃어버려요', '호박이 마차가 돼요', '새엄마랑 언니들이 괴롭혀요', '요정 할머니가 도와줘요']),
w('백설공주', ['피부가 아주 하얘요', '독이 든 사과를 먹어요', '일곱 난쟁이랑 살아요', '왕비가 거울에게 물어봐요', '숲으로 도망쳐요']), w('백설공주', ['피부가 아주 하얘요', '독이 든 사과를 먹어요', '일곱 난쟁이랑 살아요', '왕비가 거울에게 물어봐요', '숲으로 도망쳐요']),

View File

@@ -4,6 +4,29 @@ export const food: LiarTopic = {
id: 'food', id: 'food',
ko: '음식', ko: '음식',
generic: ['맛있어요', '배고플 때 생각나요', '친구랑 같이 먹으면 좋아요', '집에서도 만들 수 있어요', '사람마다 좋아하는 맛이 달라요'], generic: ['맛있어요', '배고플 때 생각나요', '친구랑 같이 먹으면 좋아요', '집에서도 만들 수 있어요', '사람마다 좋아하는 맛이 달라요'],
groups: {
분식: ['떡볶이', '김밥', '순대', '어묵', '쫄면', '라면'],
'배달 패스트푸드': ['피자', '치킨', '햄버거'],
'외국 간편식': ['타코', '케밥', '샌드위치', '샐러드'],
'중국집 메뉴': ['짜장면', '짬뽕', '탕수육', '깐풍기'],
'얼얼한 중국 요리': ['마라탕', '양꼬치', '마파두부'],
'데쳐 먹는 전골': ['훠궈', '샤브샤브'],
만두류: ['만두', '딤섬'],
'밥 요리': ['비빔밥', '주먹밥', '볶음밥', '오므라이스', '카레'],
고기구이: ['삼겹살', '불고기', '곱창', '바비큐'],
'매콤한 볶음': ['제육볶음', '오징어볶음', '닭갈비'],
'야식 고기': ['보쌈', '족발'],
찌개: ['된장찌개', '순두부찌개', '부대찌개', '청국장'],
국: ['미역국', '떡국', '육개장'],
'뽀얀 국물 탕': ['설렁탕', '곰탕', '국밥', '삼계탕'],
'찜·볶음탕': ['갈비찜', '찜닭', '닭볶음탕', '감자탕'],
'따뜻한 국수': ['칼국수', '잔치국수', '수제비', '쌀국수'],
'여름 시원한 음식': ['냉면', '콩국수', '아이스크림'],
반찬: ['김치', '깍두기', '멸치볶음', '장조림', '계란말이', '계란찜', '생선구이'],
'전·잔치 음식': ['파전', '빈대떡', '동그랑땡', '잡채'],
양식: ['스파게티', '리조또', '그라탕', '라자냐', '미트볼', '스테이크', '수프'],
일식: ['초밥', '돈가스', '우동'],
},
words: [ words: [
w('김치', ['매일 밥상에 올라와요', '겨울에 많이 담가요', '익을수록 시어져요', '빨간 것도 있고 하얀 것도 있어요', '배추로 많이 만들어요']), w('김치', ['매일 밥상에 올라와요', '겨울에 많이 담가요', '익을수록 시어져요', '빨간 것도 있고 하얀 것도 있어요', '배추로 많이 만들어요']),
w('라면', ['끓는 물에 넣어요', '밤에 먹으면 얼굴이 부어요', '꼬불꼬불해요', '봉지에 들어 있어요', '계란을 넣기도 해요']), w('라면', ['끓는 물에 넣어요', '밤에 먹으면 얼굴이 부어요', '꼬불꼬불해요', '봉지에 들어 있어요', '계란을 넣기도 해요']),

View File

@@ -4,6 +4,21 @@ export const fruit: LiarTopic = {
id: 'fruit', id: 'fruit',
ko: '과일', ko: '과일',
generic: ['저는 좋아하는 편이에요', '마트에서 쉽게 볼 수 있어요', '달콤한 맛이 나요', '껍질이 있어요', '제철에 먹으면 더 맛있어요'], generic: ['저는 좋아하는 편이에요', '마트에서 쉽게 볼 수 있어요', '달콤한 맛이 나요', '껍질이 있어요', '제철에 먹으면 더 맛있어요'],
groups: {
감귤류: ['감귤', '한라봉', '천혜향', '레드향', '황금향', '오렌지', '금귤'],
'새콤한 시트러스': ['레몬', '라임', '자몽'],
'여름 박과 과일': ['수박', '참외', '멜론'],
감: ['홍시', '곶감', '단감'],
'차로 마시는 열매': ['유자', '모과', '오미자', '대추'],
포도류: ['포도', '거봉', '샤인머스캣', '머루'],
베리류: ['블루베리', '크랜베리', '라즈베리', '블랙베리', '복분자', '아로니아', '오디'],
'작고 빨간 과일': ['딸기', '체리', '앵두', '버찌'],
'씨가 큰 여름 열매': ['복숭아', '자두', '살구', '매실'],
'열대 과일': ['바나나', '파인애플', '망고', '파파야', '구아바', '패션후르츠'],
'이색 열대 과일': ['두리안', '리치', '용과', '코코넛'],
'초록 속살': ['키위', '다래', '아보카도'],
'가을 과일': ['사과', '서양배', '석류', '무화과'],
},
words: [ words: [
w('수박', ['여름이면 생각나요', '겉이랑 속 색깔이 완전히 달라요', '씨를 뱉으면서 먹어요', '혼자 다 먹기엔 너무 커요', '두드려 보고 골라요']), w('수박', ['여름이면 생각나요', '겉이랑 속 색깔이 완전히 달라요', '씨를 뱉으면서 먹어요', '혼자 다 먹기엔 너무 커요', '두드려 보고 골라요']),
w('사과', ['아침에 먹으면 좋다고 해요', '껍질째 먹기도 해요', '빨간 것도 있고 초록인 것도 있어요', '잼이나 주스로도 많이 만들어요', '깎다가 껍질이 길게 이어지면 기분 좋아요']), w('사과', ['아침에 먹으면 좋다고 해요', '껍질째 먹기도 해요', '빨간 것도 있고 초록인 것도 있어요', '잼이나 주스로도 많이 만들어요', '깎다가 껍질이 길게 이어지면 기분 좋아요']),

View File

@@ -4,6 +4,24 @@ export const game: LiarTopic = {
id: 'game', id: 'game',
ko: '게임', ko: '게임',
generic: ['많은 사람이 해 봤어요', '친구랑 같이 하면 더 재밌어요', '하다 보면 시간 가는 줄 몰라요', '이기면 정말 기분 좋아요', '규칙을 알면 금방 할 수 있어요'], generic: ['많은 사람이 해 봤어요', '친구랑 같이 하면 더 재밌어요', '하다 보면 시간 가는 줄 몰라요', '이기면 정말 기분 좋아요', '규칙을 알면 금방 할 수 있어요'],
groups: {
'총 게임': ['배틀그라운드', '오버워치', '포트나이트', '서든어택', '발로란트'],
'전략·대전 게임': ['리그오브레전드', '스타크래프트', '클래시오브클랜', '브롤스타즈', '하스스톤'],
RPG: ['메이플스토리', '바람의나라', '디아블로', '월드오브워크래프트', '던전앤파이터', '원신'],
'만들고 꾸미는 게임': ['마인크래프트', '로블록스', '동물의숲', '심즈'],
'닌텐도 모험': ['젤다의전설', '별의커비', '스플래툰'],
'몸으로 하는 게임': ['링피트', '저스트댄스'],
'고전 게임': ['팩맨', '갤러그', '동키콩', '슈퍼마리오'],
'스포츠·레이싱': ['피파', '카트라이더', '마리오카트'],
'파티 게임': ['폴가이즈', '어몽어스', '테일즈런너', '크레이지아케이드'],
'퍼즐 게임': ['테트리스', '애니팡', '캔디크러시', '수박게임', '지뢰찾기'],
'모바일 게임': ['앵그리버드', '쿠키런', '플래피버드', '지오메트리대시', '포켓몬고'],
'격투 게임': ['철권', '스트리트파이터'],
보드게임: ['부루마블', '모두의마블', '윷놀이'],
'테이블 게임': ['루미큐브', '할리갈리', '우노', '젠가'],
'두뇌 게임': ['체스', '바둑', '스도쿠'],
'말로 하는 놀이': ['끝말잇기', '마피아게임'],
},
words: [ words: [
w('리그오브레전드', ['컴퓨터로 하는 게임이에요', '다섯 명이 한 팀이 돼요', '챔피언을 골라서 싸워요', '상대 넥서스를 부수면 이겨요', '페이커 선수가 유명해요'], ['lol']), w('리그오브레전드', ['컴퓨터로 하는 게임이에요', '다섯 명이 한 팀이 돼요', '챔피언을 골라서 싸워요', '상대 넥서스를 부수면 이겨요', '페이커 선수가 유명해요'], ['lol']),
w('스타크래프트', ['컴퓨터로 하는 게임이에요', '우주를 배경으로 싸워요', '일꾼으로 자원을 모아요', '테란, 저그, 프로토스가 나와요', '옛날 피시방에서 정말 인기였어요'], ['starcraft']), w('스타크래프트', ['컴퓨터로 하는 게임이에요', '우주를 배경으로 싸워요', '일꾼으로 자원을 모아요', '테란, 저그, 프로토스가 나와요', '옛날 피시방에서 정말 인기였어요'], ['starcraft']),

View File

@@ -4,6 +4,21 @@ export const instrument: LiarTopic = {
id: 'instrument', id: 'instrument',
ko: '악기', ko: '악기',
generic: ['예쁜 소리가 나요', '음악 시간에 볼 수 있어요', '연습을 많이 해야 잘해요', '공연에서 연주해요', '배우는 학원도 있어요'], generic: ['예쁜 소리가 나요', '음악 시간에 볼 수 있어요', '연습을 많이 해야 잘해요', '공연에서 연주해요', '배우는 학원도 있어요'],
groups: {
'활 현악기': ['바이올린', '비올라', '첼로', '콘트라베이스'],
'튕기는 현악기': ['기타', '우쿨렐레', '반조', '만돌린', '하프'],
'목관 악기': ['플루트', '피콜로', '클라리넷', '오보에', '바순', '색소폰'],
'작은 관악기': ['리코더', '오카리나', '하모니카', '백파이프'],
'금관 악기': ['트럼펫', '트롬본', '호른', '튜바'],
'건반 악기': ['피아노', '오르간', '신시사이저', '아코디언', '멜로디언'],
북: ['드럼', '팀파니', '봉고', '젬베', '카혼'],
'흔드는 타악기': ['마라카스', '탬버린', '핸드벨'],
'작은 타악기': ['우드블록', '트라이앵글', '캐스터네츠', '심벌즈'],
'두드리는 건반 타악기': ['실로폰', '마림바', '비브라폰', '칼림바'],
'국악 현악기': ['가야금', '거문고', '해금', '아쟁', '양금'],
'국악 관악기': ['대금', '단소', '피리', '태평소', '생황'],
'국악 타악기': ['장구', '꽹과리', '소고', '편경', '편종'],
},
words: [ words: [
w('바이올린', ['줄이 네 개 있어요', '활로 줄을 문질러요', '턱에 끼우고 연주해요', '오케스트라에서 제일 많아요', '첼로보다 훨씬 작아요']), w('바이올린', ['줄이 네 개 있어요', '활로 줄을 문질러요', '턱에 끼우고 연주해요', '오케스트라에서 제일 많아요', '첼로보다 훨씬 작아요']),
w('비올라', ['나무로 만든 현악기예요', '활로 켜서 소리를 내요', '어깨에 올려놓고 연주해요', '바이올린보다 조금 더 커요', '바이올린과 첼로 사이 소리를 내요']), w('비올라', ['나무로 만든 현악기예요', '활로 켜서 소리를 내요', '어깨에 올려놓고 연주해요', '바이올린보다 조금 더 커요', '바이올린과 첼로 사이 소리를 내요']),

View File

@@ -4,6 +4,32 @@ export const job: LiarTopic = {
id: 'job', id: 'job',
ko: '직업', ko: '직업',
generic: ['일하는 사람이에요', '꼭 필요한 일이에요', '힘들지만 보람 있대요', '주변에서 볼 수 있어요', '어릴 때 꿈이었던 사람도 많아요'], generic: ['일하는 사람이에요', '꼭 필요한 일이에요', '힘들지만 보람 있대요', '주변에서 볼 수 있어요', '어릴 때 꿈이었던 사람도 많아요'],
groups: {
'병원 직업': ['의사', '간호사', '약사', '물리치료사', '안경사'],
'가르치고 돕는 일': ['선생님', '교수', '사서', '영양사', '사회복지사'],
수사: ['경찰관', '형사', '탐정'],
'지키는 일': ['경호원', '경비원', '군인', '소방관'],
'법·정치': ['변호사', '판사', '검사', '국회의원'],
'외국어 직업': ['통역사', '번역가', '외교관'],
'음식 만드는 일': ['요리사', '제빵사', '바리스타'],
연예인: ['가수', '배우', '댄서', '개그맨', '모델', '마술사'],
방송: ['아나운서', '기상캐스터', '기자', '성우'],
촬영: ['영화감독', '사진작가', '유튜버'],
작가: ['소설가', '시인', '웹툰작가'],
미술: ['화가', '조각가', '도예가', '디자이너'],
음악: ['작곡가', '피아니스트', '지휘자'],
'꾸며 주는 일': ['미용사', '네일아티스트'],
'거리를 다니는 일': ['우체부', '택배기사', '배달원', '환경미화원'],
운전: ['버스기사', '택시기사', '기관사', '카레이서'],
'하늘 직업': ['조종사', '승무원', '우주비행사'],
'바다 직업': ['선장', '어부', '해녀', '등대지기'],
'자연을 돌보는 일': ['농부', '정원사', '사육사'],
'짓고 고치는 일': ['건축가', '목수', '배관공', '정비사', '대장장이'],
'연구·탐사': ['과학자', '고고학자', '광부'],
'돈 다루는 일': ['은행원', '회계사', '계산원'],
'컴퓨터 직업': ['프로그래머', '프로게이머'],
'스포츠 직업': ['축구선수', '야구선수', '심판', '헬스트레이너'],
},
words: [ words: [
w('의사', ['아플 때 만나요', '하얀 가운을 입어요', '청진기를 써요', '공부를 오래 해야 해요', '처방전을 써 줘요']), w('의사', ['아플 때 만나요', '하얀 가운을 입어요', '청진기를 써요', '공부를 오래 해야 해요', '처방전을 써 줘요']),
w('간호사', ['병원에서 일해요', '주사를 놓아 줘요', '밤에도 환자를 돌봐요', '체온이랑 혈압을 재 줘요', '교대 근무를 해요']), w('간호사', ['병원에서 일해요', '주사를 놓아 줘요', '밤에도 환자를 돌봐요', '체온이랑 혈압을 재 줘요', '교대 근무를 해요']),

View File

@@ -4,6 +4,23 @@ export const landmark: LiarTopic = {
id: 'landmark', id: 'landmark',
ko: '랜드마크', ko: '랜드마크',
generic: ['관광객이 많이 찾아와요', '사진을 많이 찍는 곳이에요', '아주 유명한 곳이에요', '여행 가면 꼭 들러요', '텔레비전에서 본 적 있어요'], generic: ['관광객이 많이 찾아와요', '사진을 많이 찍는 곳이에요', '아주 유명한 곳이에요', '여행 가면 꼭 들러요', '텔레비전에서 본 적 있어요'],
groups: {
'조선 궁궐·성': ['경복궁', '창덕궁', '덕수궁', '수원화성'],
'서울 도심 명소': ['숭례문', '흥인지문', '광화문', '청계천'],
'높은 빌딩·타워': ['남산타워', '롯데월드타워', '63빌딩', '도쿄타워', '부르즈할리파', '마리나베이샌즈'],
'경주 신라 유적': ['첨성대', '불국사', '석굴암', '다보탑', '석가탑'],
'높은 산': ['한라산', '백두산', '설악산', '후지산'],
'국내 바다·섬 명소': ['독도', '성산일출봉', '해운대', '광안대교', '남이섬'],
'파리 명소': ['에펠탑', '개선문', '루브르박물관', '몽생미셸'],
'런던 명소': ['빅벤', '런던아이', '타워브리지', '버킹엄궁전'],
'미국 도시 명소': ['타임스스퀘어', '금문교', '백악관', '엠파이어스테이트빌딩'],
'거대한 자연 경관': ['그랜드캐니언', '나이아가라폭포', '우유니소금사막', '하롱베이'],
'이탈리아·그리스 유적': ['콜로세움', '피사의사탑', '트레비분수', '파르테논신전'],
'독특한 건축물': ['사그라다파밀리아', '노이슈반슈타인성', '성바실리대성당', '시드니오페라하우스'],
'거대한 석상': ['자유의여신상', '구원의예수상', '모아이석상'],
'고대 유적': ['피라미드', '스핑크스', '마추픽추', '앙코르와트', '스톤헨지'],
'아시아 옛 건축': ['타지마할', '만리장성', '자금성'],
},
words: [ words: [
w('경복궁', ['서울 한가운데에 있어요', '조선 시대에 지어졌어요', '한복을 입고 가면 공짜로 들어가요', '근정전과 경회루가 있어요', '조선에서 가장 먼저 지은 궁궐이에요']), w('경복궁', ['서울 한가운데에 있어요', '조선 시대에 지어졌어요', '한복을 입고 가면 공짜로 들어가요', '근정전과 경회루가 있어요', '조선에서 가장 먼저 지은 궁궐이에요']),
w('창덕궁', ['서울에 있는 옛 궁궐이에요', '조선 시대에 지어졌어요', '세계문화유산이에요', '아름다운 후원이 있어요', '정문 이름이 돈화문이에요']), w('창덕궁', ['서울에 있는 옛 궁궐이에요', '조선 시대에 지어졌어요', '세계문화유산이에요', '아름다운 후원이 있어요', '정문 이름이 돈화문이에요']),

View File

@@ -4,6 +4,23 @@ export const movie: LiarTopic = {
id: 'movie', id: 'movie',
ko: '영화', ko: '영화',
generic: ['극장에서 봤어요', '팝콘 먹으면서 보면 좋아요', '아주 유명한 작품이에요', '여러 번 봐도 재밌어요', '주인공이 기억에 남아요'], generic: ['극장에서 봤어요', '팝콘 먹으면서 보면 좋아요', '아주 유명한 작품이에요', '여러 번 봐도 재밌어요', '주인공이 기억에 남아요'],
groups: {
'노래하는 애니': ['겨울왕국', '모아나', '코코'],
'픽사 애니': ['토이스토리', '니모를찾아서', '인사이드아웃', '몬스터주식회사', '엘리멘탈'],
'동물·캐릭터 애니': ['라이온킹', '주토피아', '쿵푸팬더', '아이스에이지', '미니언즈'],
'일본 애니': ['센과치히로의행방불명', '이웃집토토로', '하울의움직이는성', '너의이름은'],
'마법 판타지': ['해리포터', '반지의제왕', '나니아연대기'],
'가족 코미디': ['나홀로집에', '박물관이살아있다', '찰리와초콜릿공장'],
'우주·시간 SF': ['스타워즈', '아바타', '인터스텔라', '백투더퓨처'],
'SF 액션': ['매트릭스', '터미네이터', '인셉션', '트랜스포머'],
'액션 블록버스터': ['어벤져스', '미션임파서블', '탑건', '캐리비안의해적'],
'무서운 영화': ['죠스', '쥬라기공원', '부산행', '파묘'],
'음악 영화': ['맘마미아', '라라랜드', '위대한쇼맨', '보헤미안랩소디'],
'감동 명작': ['타이타닉', '쇼생크탈출', '포레스트검프', '조커'],
'한국 역사 영화': ['명량', '광해', '택시운전사', '서울의봄', '태극기휘날리며', '국제시장'],
'한국 범죄·스릴러': ['기생충', '범죄도시', '올드보이', '극한직업'],
'한국 판타지 코미디': ['신과함께', '수상한그녀'],
},
words: [ words: [
w('겨울왕국', ['자매가 나오는 이야기예요', '눈사람이 말을 해요', '손에서 얼음이 나와요', '렛잇고 노래가 유명해요', '엘사와 안나가 주인공이에요'], ['프로즌']), w('겨울왕국', ['자매가 나오는 이야기예요', '눈사람이 말을 해요', '손에서 얼음이 나와요', '렛잇고 노래가 유명해요', '엘사와 안나가 주인공이에요'], ['프로즌']),
w('토이스토리', ['주인이 없을 때 움직여요', '장난감들이 주인공이에요', '카우보이 인형이 나와요', '우주 전사 버즈가 나와요', '우디가 앤디를 아주 좋아해요']), w('토이스토리', ['주인이 없을 때 움직여요', '장난감들이 주인공이에요', '카우보이 인형이 나와요', '우주 전사 버즈가 나와요', '우디가 앤디를 아주 좋아해요']),

View File

@@ -4,6 +4,24 @@ export const nature: LiarTopic = {
id: 'nature', id: 'nature',
ko: '자연·날씨', ko: '자연·날씨',
generic: ['밖에 나가면 볼 수 있어요', '계절과 관련이 있어요', '사진으로 남기기도 해요', '자연에서 일어나요', '날씨 뉴스에 나오기도 해요'], generic: ['밖에 나가면 볼 수 있어요', '계절과 관련이 있어요', '사진으로 남기기도 해요', '자연에서 일어나요', '날씨 뉴스에 나오기도 해요'],
groups: {
비: ['소나기', '장마', '홍수'],
폭풍: ['태풍', '회오리', '번개', '천둥'],
'눈·우박': ['함박눈', '우박', '눈보라', '진눈깨비'],
'차가운 아침': ['서리', '이슬', '고드름'],
'얼음 지형': ['빙하', '빙산'],
'뿌연 공기': ['안개', '황사', '미세먼지', '아지랑이'],
더위: ['폭염', '열대야', '가뭄'],
추위: ['한파', '꽃샘추위'],
'하늘 풍경': ['무지개', '노을', '해돋이', '구름', '오로라'],
'달과 별': ['보름달', '초승달', '북극성', '별자리', '은하수'],
우주: ['태양', '혜성', '별똥별'],
자연재해: ['지진', '화산', '용암', '산불', '산사태'],
물가: ['폭포', '계곡', '호수', '시냇물', '온천'],
'먼 나라 자연': ['사막', '오아시스', '정글', '초원'],
'산과 들': ['동굴', '절벽', '언덕', '들판', '바위', '메아리'],
'가을 풍경': ['단풍', '낙엽'],
},
words: [ words: [
w('무지개', ['보면 기분이 좋아져요', '반원 모양으로 떠요', '비 그친 뒤에 잘 보여요', '일곱 가지 색이에요', '빨주노초파남보예요']), w('무지개', ['보면 기분이 좋아져요', '반원 모양으로 떠요', '비 그친 뒤에 잘 보여요', '일곱 가지 색이에요', '빨주노초파남보예요']),
w('태풍', ['여름 끝 무렵에 와요', '창문에 테이프를 붙여요', '이름이 붙어서 와요', '중심에 눈이 있어요', '강한 비바람이 몰아쳐요']), w('태풍', ['여름 끝 무렵에 와요', '창문에 테이프를 붙여요', '이름이 붙어서 와요', '중심에 눈이 있어요', '강한 비바람이 몰아쳐요']),

View File

@@ -4,6 +4,22 @@ export const person: LiarTopic = {
id: 'person', id: 'person',
ko: '유명 인물', ko: '유명 인물',
generic: ['이름을 들으면 다들 알아요', 'TV에서 자주 봤어요', '팬이 아주 많아요', '사진이 기사에 자주 나와요', '화면이나 무대에서 활약해요'], generic: ['이름을 들으면 다들 알아요', 'TV에서 자주 봤어요', '팬이 아주 많아요', '사진이 기사에 자주 나와요', '화면이나 무대에서 활약해요'],
groups: {
걸그룹: ['블랙핑크', '트와이스', '소녀시대', '아이브', '에스파', '레드벨벳'],
보이그룹: ['방탄소년단', '세븐틴', '동방신기', '엑소'],
'트로트 가수': ['임영웅', '장윤정', '송가인'],
'레전드 가수': ['조용필', '서태지', '나훈아'],
'감성 보컬': ['아이유', '태연', '성시경', '악동뮤지션', '이승기'],
'댄스 가수': ['이효리', '엄정화', '싸이', '박진영', '김종국'],
'예능 MC': ['유재석', '강호동', '신동엽', '전현무'],
'개그맨·예능인': ['이경규', '박명수', '이영자', '이광수'],
'영화 남자 배우': ['송강호', '이병헌', '이정재', '마동석', '황정민', '최민식', '유해진'],
'드라마 남자 배우': ['현빈', '송중기', '박보검', '박서준', '이민호', '조인성', '차승원', '이서진'],
'톱 여배우': ['손예진', '전지현', '송혜교', '이영애', '김태희'],
'연기파 여배우': ['김혜수', '윤여정', '김고은', '전도연', '박은빈'],
'할리우드 배우': ['톰크루즈', '키아누리브스', '레오나르도디카프리오', '엠마왓슨'],
'팝 가수': ['테일러스위프트', '브루노마스'],
},
words: [ words: [
// 가수 // 가수
w('아이유', ['노래도 하고 연기도 해요', '팬클럽 이름이 유애나예요', '삼단 고음으로 유명해졌어요', '드라마 호텔 델루나에 나왔어요', '좋은 날과 밤편지를 불렀어요'], ['이지은']), w('아이유', ['노래도 하고 연기도 해요', '팬클럽 이름이 유애나예요', '삼단 고음으로 유명해졌어요', '드라마 호텔 델루나에 나왔어요', '좋은 날과 밤편지를 불렀어요'], ['이지은']),

View File

@@ -4,6 +4,30 @@ export const place: LiarTopic = {
id: 'place', id: 'place',
ko: '장소', ko: '장소',
generic: ['사람들이 많이 가요', '가 본 적 있어요', '주말에 붐벼요', '우리 동네에도 있어요', '가면 기분이 달라져요'], generic: ['사람들이 많이 가요', '가 본 적 있어요', '주말에 붐벼요', '우리 동네에도 있어요', '가면 기분이 달라져요'],
groups: {
'어린이 공간': ['유치원', '어린이집', '놀이터'],
학교: ['학교', '교실', '보건실', '학원'],
'책 있는 곳': ['도서관', '서점', '독서실', '문구점'],
'병원·약국': ['병원', '치과', '한의원', '약국', '안경점'],
'관공서·은행': ['시청', '주민센터', '우체국', '은행'],
'경찰·법': ['경찰서', '소방서', '법원', '교도소'],
교통: ['공항', '기차역', '지하철역', '정류장', '터미널', '항구'],
'차 관련': ['주유소', '주차장', '세차장', '휴게소'],
'관람 장소': ['박물관', '미술관', '과학관', '궁궐'],
'생물 구경': ['동물원', '수족관', '식물원'],
나들이: ['놀이공원', '스키장', '스케이트장', '캠핑장'],
'실내 오락': ['노래방', '피시방', '오락실', '볼링장', '영화관'],
물놀이: ['바다', '워터파크', '수영장'],
'씻는 곳': ['찜질방', '목욕탕', '화장실'],
'운동 장소': ['체육관', '헬스장', '야구장', '축구장'],
'동네 서비스 가게': ['미용실', '이발소', '세탁소', '사진관'],
'동네 가게': ['편의점', '정육점', '꽃집', '빵집'],
외식: ['식당', '분식집', '중국집', '카페'],
쇼핑: ['백화점', '마트', '시장', '쇼핑몰'],
'종교·예식': ['교회', '성당', '결혼식장'],
'높은 건물': ['아파트', '호텔', '사무실'],
일터: ['공장', '방송국', '농장'],
},
words: [ words: [
w('학교', ['종이 울려요', '운동장이 있어요', '급식을 먹어요', '친구를 매일 만나요', '시험이 있어요']), w('학교', ['종이 울려요', '운동장이 있어요', '급식을 먹어요', '친구를 매일 만나요', '시험이 있어요']),
w('병원', ['소독약 냄새가 나요', '번호표 받고 기다려요', '아플 때 가요', '하얀 침대가 있어요', '면회 시간이 정해져 있어요']), w('병원', ['소독약 냄새가 나요', '번호표 받고 기다려요', '아플 때 가요', '하얀 침대가 있어요', '면회 시간이 정해져 있어요']),

View File

@@ -4,6 +4,23 @@ export const sea: LiarTopic = {
id: 'sea', id: 'sea',
ko: '바다 생물', ko: '바다 생물',
generic: ['바닷속에서 살아요', '수족관에서 볼 수 있어요', '물이 없으면 힘들어요', '사진으로 본 적 있어요', '아이들이 신기해해요'], generic: ['바닷속에서 살아요', '수족관에서 볼 수 있어요', '물이 없으면 힘들어요', '사진으로 본 적 있어요', '아이들이 신기해해요'],
groups: {
'큰 바다 생물': ['상어', '고래', '가오리'],
'바다 포유류': ['물개', '바다사자', '바다코끼리', '해달'],
'오징어·문어류': ['오징어', '문어', '낙지', '주꾸미', '꼴뚜기'],
'게·새우': ['꽃게', '대게', '킹크랩', '랍스터', '새우'],
'조개·고둥': ['조개', '가리비', '홍합', '바지락', '전복', '소라'],
'오돌토돌 해산물': ['멍게', '해삼', '성게', '개불'],
'바닷속 무척추동물': ['해파리', '산호', '말미잘', '불가사리'],
해초: ['미역', '다시마', '파래'],
'신기한 작은 물고기': ['해마', '흰동가리', '날치'],
'등 푸른 생선': ['고등어', '꽁치', '삼치', '청어', '전어', '멸치'],
'큰 회 생선': ['참치', '방어', '연어'],
'흰살 생선': ['명태', '대구', '조기'],
'길쭉한 물고기': ['갈치', '장어', '곰치'],
횟감: ['광어', '우럭', '도미', '숭어'],
'특이한 생김새': ['복어', '아귀', '쥐치', '개복치'],
},
words: [ words: [
w('상어', ['바다의 무법자로 불려요', '이빨이 여러 줄로 나 있어요', '등지느러미가 물 위로 보여요', '피 냄새를 멀리서도 맡아요', '뚜루루뚜루 노래에 가족이 나와요']), w('상어', ['바다의 무법자로 불려요', '이빨이 여러 줄로 나 있어요', '등지느러미가 물 위로 보여요', '피 냄새를 멀리서도 맡아요', '뚜루루뚜루 노래에 가족이 나와요']),
w('고래', ['바다에서 제일 큰 동물이에요', '물고기가 아니라 포유류예요', '머리 위 구멍으로 물을 뿜어요', '노래 같은 소리를 내요', '칭찬하면 춤춘다는 말이 있어요']), w('고래', ['바다에서 제일 큰 동물이에요', '물고기가 아니라 포유류예요', '머리 위 구멍으로 물을 뿜어요', '노래 같은 소리를 내요', '칭찬하면 춤춘다는 말이 있어요']),

View File

@@ -4,6 +4,22 @@ export const snack: LiarTopic = {
id: 'snack', id: 'snack',
ko: '간식', ko: '간식',
generic: ['출출할 때 생각나요', '친구랑 나눠 먹기 좋아요', '가게에서 쉽게 살 수 있어요', '좋아하는 사람이 많아요', '종류가 여러 가지예요'], generic: ['출출할 때 생각나요', '친구랑 나눠 먹기 좋아요', '가게에서 쉽게 살 수 있어요', '좋아하는 사람이 많아요', '종류가 여러 가지예요'],
groups: {
'틀에 굽는 길거리 간식': ['붕어빵', '호떡', '계란빵', '타코야키'],
'구워 먹는 군것질': ['군고구마', '군밤', '옥수수'],
'꼬치 간식': ['닭꼬치', '떡꼬치', '핫도그', '회오리감자', '탕후루'],
'달콤한 군것질': ['솜사탕', '달고나', '캐러멜', '풍선껌', '마시멜로', '젤리', '초콜릿'],
'바삭한 과자': ['뻥튀기', '팝콘', '감자칩', '누룽지', '감자튀김'],
'튀긴 빵·와플': ['츄러스', '꽈배기', '도넛', '와플'],
'빵집 빵': ['식빵', '단팥빵', '소보로빵', '크루아상', '베이글'],
'구움 디저트': ['머핀', '에그타르트', '마카롱', '쿠키', '케이크', '카스텔라'],
'떠먹는 디저트': ['푸딩', '티라미수', '요거트', '빙수'],
'떡·한과': ['송편', '인절미', '가래떡', '꿀떡', '백설기', '시루떡', '찹쌀떡', '약과'],
'전통 음료': ['식혜', '수정과', '미숫가루'],
'우유 음료': ['우유', '두유', '버블티'],
'따뜻한 차': ['커피', '녹차', '코코아'],
'시원한 음료': ['콜라', '사이다', '주스', '레모네이드', '스무디'],
},
words: [ words: [
w('붕어빵', ['겨울 길거리에서 팔아요', '봉투에 담아 따끈하게 줘요', '머리부터 먹을지 꼬리부터 먹을지 고민해요', '안에 팥이 들어 있어요', '물고기 모양 틀에 구워요']), w('붕어빵', ['겨울 길거리에서 팔아요', '봉투에 담아 따끈하게 줘요', '머리부터 먹을지 꼬리부터 먹을지 고민해요', '안에 팥이 들어 있어요', '물고기 모양 틀에 구워요']),
w('호떡', ['겨울 포장마차에서 팔아요', '납작하게 꾹 눌러 구워요', '종이컵에 끼워 줘요', '속에 흑설탕 꿀이 흘러요', '씨앗을 넣은 부산식도 있어요']), w('호떡', ['겨울 포장마차에서 팔아요', '납작하게 꾹 눌러 구워요', '종이컵에 끼워 줘요', '속에 흑설탕 꿀이 흘러요', '씨앗을 넣은 부산식도 있어요']),

View File

@@ -4,6 +4,24 @@ export const sport: LiarTopic = {
id: 'sport', id: 'sport',
ko: '운동', ko: '운동',
generic: ['몸을 움직여요', '하고 나면 땀이 나요', '친구들이랑 하면 재밌어요', '올림픽에서도 봤어요', '규칙을 알아야 해요'], generic: ['몸을 움직여요', '하고 나면 땀이 나요', '친구들이랑 하면 재밌어요', '올림픽에서도 봤어요', '규칙을 알아야 해요'],
groups: {
'발로 하는 구기': ['축구', '풋살', '족구'],
'손으로 하는 구기': ['농구', '핸드볼', '배구', '럭비'],
'라켓 운동': ['배드민턴', '테니스', '탁구'],
'치거나 굴리는 공': ['야구', '골프', '당구', '볼링'],
무도: ['태권도', '유도', '검도', '합기도', '펜싱'],
'맞붙는 격투기': ['복싱', '레슬링', '씨름'],
'얼음 종목': ['스케이트', '피겨스케이팅', '쇼트트랙', '아이스하키', '컬링'],
'눈 종목': ['스키', '스노보드', '봅슬레이'],
'물 종목': ['수영', '다이빙', '서핑', '카누'],
육상: ['마라톤', '멀리뛰기', '높이뛰기'],
'운동회 종목': ['줄다리기', '이어달리기', '박터뜨리기', '공굴리기', '이인삼각', '피구'],
'맨몸 운동': ['팔굽혀펴기', '윗몸일으키기', '스쿼트', '플랭크', '턱걸이'],
'몸 푸는 운동': ['요가', '필라테스', '스트레칭', '에어로빅'],
'놀이 운동': ['줄넘기', '훌라후프', '제기차기', '닭싸움'],
'올림픽 개인 종목': ['양궁', '사격', '역도', '체조'],
'야외 운동': ['등산', '사이클', '승마', '클라이밍'],
},
words: [ words: [
w('축구', ['공을 발로 차요', '월드컵이 있어요', '골키퍼만 손을 써요', '한 팀에 열한 명이에요', '전반전과 후반전이 있어요']), w('축구', ['공을 발로 차요', '월드컵이 있어요', '골키퍼만 손을 써요', '한 팀에 열한 명이에요', '전반전과 후반전이 있어요']),
w('야구', ['방망이를 휘둘러요', '홈런이 나오면 신나요', '글러브를 껴요', '9회까지 해요', '삼진 아웃이 있어요']), w('야구', ['방망이를 휘둘러요', '홈런이 나오면 신나요', '글러브를 껴요', '9회까지 해요', '삼진 아웃이 있어요']),

View File

@@ -4,6 +4,35 @@ export const thing: LiarTopic = {
id: 'thing', id: 'thing',
ko: '물건', ko: '물건',
generic: ['집에 하나쯤 있어요', '매일 써요', '잃어버리면 곤란해요', '선물로도 줘요', '가게에서 쉽게 살 수 있어요'], generic: ['집에 하나쯤 있어요', '매일 써요', '잃어버리면 곤란해요', '선물로도 줘요', '가게에서 쉽게 살 수 있어요'],
groups: {
'조리 도구': ['냄비', '프라이팬', '주전자', '밥솥', '도마'],
식기: ['숟가락', '젓가락', '국자', '접시', '빨대'],
'큰 가전': ['냉장고', '세탁기', '전자레인지', '청소기'],
'바람 가전': ['선풍기', '에어컨', '가습기', '드라이기'],
'옷 손질': ['다리미', '옷걸이'],
'청소 도구': ['빗자루', '쓰레받기', '걸레', '쓰레기통'],
욕실용품: ['칫솔', '치약', '비누', '샴푸', '수건', '휴지'],
'렌즈·거울': ['안경', '돋보기', '거울'],
'자르는 도구': ['가위', '손톱깎이'],
필기구: ['연필', '볼펜', '지우개', '필통'],
'미술 준비물': ['크레파스', '물감', '색종이'],
사무용품: ['테이프', '스테이플러', '계산기'],
'종이 묶음': ['공책', '달력'],
가구: ['책상', '의자', '소파', '침대'],
침구: ['베개', '이불'],
컴퓨터: ['컴퓨터', '노트북', '키보드', '마우스'],
'TV·라디오': ['텔레비전', '라디오', '리모컨'],
'휴대 기기': ['휴대폰', '카메라', '이어폰'],
'전기 소품': ['건전지', '충전기', '전구'],
불빛: ['손전등', '양초'],
잠금: ['열쇠', '자물쇠'],
'들고 다니는 것': ['지갑', '우산', '텀블러'],
'몸에 차는 것': ['장갑', '모자', '시계'],
공구: ['망치', '사다리', '자석'],
장난감: ['풍선', '주사위', '인형'],
'담는 것': ['바구니', '상자', '화분', '저금통'],
구급용품: ['체온계', '반창고'],
},
words: [ words: [
w('우산', ['비 오는 날 꼭 필요해요', '펼치고 접어요', '잃어버리기 쉬워요', '편의점에서 급히 사기도 해요', '바람 불면 뒤집혀요']), w('우산', ['비 오는 날 꼭 필요해요', '펼치고 접어요', '잃어버리기 쉬워요', '편의점에서 급히 사기도 해요', '바람 불면 뒤집혀요']),
w('휴대폰', ['매일 손에 들고 다녀요', '밤마다 충전해요', '알람을 맞춰요', '사진을 찍어요', '화면이 깨지면 속상해요'], ['핸드폰', '스마트폰', '휴대전화']), w('휴대폰', ['매일 손에 들고 다녀요', '밤마다 충전해요', '알람을 맞춰요', '사진을 찍어요', '화면이 깨지면 속상해요'], ['핸드폰', '스마트폰', '휴대전화']),

View File

@@ -4,6 +4,24 @@ export const vegetable: LiarTopic = {
id: 'vegetable', id: 'vegetable',
ko: '채소', ko: '채소',
generic: ['밭에서 키워요', '반찬으로 자주 먹어요', '몸에 좋다고 해요', '마트 채소 코너에서 팔아요', '편식하는 아이들이 남기기도 해요'], generic: ['밭에서 키워요', '반찬으로 자주 먹어요', '몸에 좋다고 해요', '마트 채소 코너에서 팔아요', '편식하는 아이들이 남기기도 해요'],
groups: {
'감자·고구마': ['감자', '고구마', '토란'],
'색깔 뿌리채소': ['당근', '비트', '콜라비'],
'양념 채소': ['양파', '마늘', '생강'],
'파 종류': ['대파', '쪽파', '부추'],
'김치 채소': ['배추', '열무', '총각무', '봄동'],
'쌈·샐러드 채소': ['상추', '깻잎', '케일', '치커리', '루꼴라'],
'데쳐 먹는 잎채소': ['시금치', '근대', '청경채'],
'향 채소': ['미나리', '쑥갓', '고수', '셀러리'],
'오이·호박류': ['오이', '애호박', '단호박', '가지'],
'고추·토마토': ['고추', '피망', '파프리카', '토마토'],
'서양 채소': ['브로콜리', '콜리플라워', '아스파라거스'],
'길쭉한 뿌리': ['우엉', '도라지', '더덕', '연근'],
나물: ['고사리', '시래기', '냉이', '달래', '두릅'],
'싹 채소': ['콩나물', '숙주', '죽순'],
버섯: ['팽이버섯', '표고버섯', '양송이'],
'콩·옥수수': ['옥수수', '완두콩', '강낭콩'],
},
words: [ words: [
w('감자', ['땅속에서 자라요', '강원도가 유명해요', '삶아서 소금 찍어 먹어요', '싹이 나면 독이 생겨서 도려내요', '길게 잘라 튀기면 프렌치프라이가 돼요']), w('감자', ['땅속에서 자라요', '강원도가 유명해요', '삶아서 소금 찍어 먹어요', '싹이 나면 독이 생겨서 도려내요', '길게 잘라 튀기면 프렌치프라이가 돼요']),
w('고구마', ['겨울 간식으로 많이 먹어요', '땅속에서 자라고 껍질이 자주색이에요', '군밤처럼 길거리에서 구워 팔아요', '먹으면 목이 막혀서 우유랑 먹어요', '답답한 사람을 이걸로 비유해요']), w('고구마', ['겨울 간식으로 많이 먹어요', '땅속에서 자라고 껍질이 자주색이에요', '군밤처럼 길거리에서 구워 팔아요', '먹으면 목이 막혀서 우유랑 먹어요', '답답한 사람을 이걸로 비유해요']),

View File

@@ -4,6 +4,24 @@ export const vehicle: LiarTopic = {
id: 'vehicle', id: 'vehicle',
ko: '탈것', ko: '탈것',
generic: ['타고 다녀요', '어디 갈 때 써요', '빠른 편이에요', '어릴 때 장난감으로 갖고 놀았어요', '사람을 태워요'], generic: ['타고 다녀요', '어디 갈 때 써요', '빠른 편이에요', '어릴 때 장난감으로 갖고 놀았어요', '사람을 태워요'],
groups: {
'도로 대중교통': ['버스', '택시', '승합차'],
철도: ['지하철', '기차', '모노레일', '케이블카'],
승용차: ['자동차', '리무진', '스포츠카', '오픈카', '캠핑카'],
'긴급 차량': ['구급차', '소방차', '경찰차'],
'짐 싣는 차': ['트럭', '청소차', '견인차'],
'공사장 차량': ['포크레인', '지게차', '레미콘', '불도저'],
농기계: ['경운기', '트랙터'],
'군용 탈것': ['탱크', '전투기', '항공모함', '잠수함'],
'바퀴 달린 개인 탈것': ['자전거', '오토바이', '킥보드', '스케이트보드'],
'하늘 탈것': ['비행기', '헬리콥터', '열기구'],
'우주 탈것': ['로켓', '우주선'],
'작은 배': ['카누', '보트', '오리배', '뗏목'],
'큰 배': ['유람선', '여객선', '어선', '요트'],
'옛날 배': ['돛단배', '해적선', '거북선'],
'끌거나 메는 탈것': ['마차', '가마', '썰매', '유모차'],
놀이기구: ['회전목마', '롤러코스터', '바이킹', '범퍼카', '대관람차'],
},
words: [ words: [
w('자동차', ['바퀴가 네 개예요', '면허가 있어야 해요', '주유소에 들러요', '주차할 곳이 늘 고민이에요', '안전벨트를 매요'], ['승용차']), w('자동차', ['바퀴가 네 개예요', '면허가 있어야 해요', '주유소에 들러요', '주차할 곳이 늘 고민이에요', '안전벨트를 매요'], ['승용차']),
w('버스', ['정류장에서 기다려요', '번호를 보고 타요', '카드를 찍고 타요', '내릴 때 벨을 눌러요', '손잡이를 잡고 서 있기도 해요']), w('버스', ['정류장에서 기다려요', '번호를 보고 타요', '카드를 찍고 타요', '내릴 때 벨을 눌러요', '손잡이를 잡고 서 있기도 해요']),

View File

@@ -4,13 +4,21 @@ export interface LiarWord {
word: string; word: string;
aliases?: string[]; aliases?: string[];
hints: string[]; hints: string[];
/** 비슷한 단어 묶음 이름: 바보 모드의 라이어는 제시어와 같은 묶음의 다른 단어를 받아요. */
group?: string;
} }
export interface LiarTopic { export interface LiarTopic {
id: TopicId; /** Built-in topics use a `TopicId`; topics an admin adds get their own id (`c_…`). */
id: TopicId | (string & {});
ko: string; ko: string;
generic: string[]; generic: string[];
words: LiarWord[]; words: LiarWord[];
/**
* Built-in bank only: 비슷한 단어 묶음 (묶음 이름 → 단어들). Every word is in exactly one group of 2+ words.
* `words.ts` copies it onto each word's `group`.
*/
groups?: Record<string, string[]>;
} }
export const w = (word: string, hints: string[], aliases?: string[]): LiarWord => (aliases ? { word, hints, aliases } : { word, hints }); export const w = (word: string, hints: string[], aliases?: string[]): LiarWord => (aliases ? { word, hints, aliases } : { word, hints });

View File

@@ -113,7 +113,7 @@ describe('reading', () => {
st.word = '수박'; st.word = '수박';
st.liar = players[4]!; st.liar = players[4]!;
st.order = [...players]; st.order = [...players];
const hints = topicById('fruit').words.find((w) => w.word === '수박')!.hints; const hints = topicById('fruit')!.words.find((w) => w.word === '수박')!.hints;
const rng = SeededRng.fromSeed(seedN(4)); const rng = SeededRng.fromSeed(seedN(4));
let now = 0; let now = 0;
st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now: (now = st.phase.kind === 'reveal' ? st.phase.endsAt : 0) }).state; st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now: (now = st.phase.kind === 'reveal' ? st.phase.endsAt : 0) }).state;
@@ -149,6 +149,6 @@ describe('reading', () => {
st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng: SeededRng.fromSeed(seedN(6)), now: 10_000 }).state; 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 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: {} }); 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()); expect(topicById('animal')!.generic).toContain(bot.description());
}); });
}); });

View File

@@ -92,10 +92,12 @@ interface TopicModel {
} }
const models = new Map<string, TopicModel>(); const models = new Map<string, TopicModel>();
function model(id: LiarView['topic']): TopicModel { /** The game's topic in the bank version it was set up with (a topic missing there: no sentences, the bot leans on others). */
const hit = models.get(id); function model(v: Pick<LiarView, 'topic' | 'topicKo' | 'options'>): TopicModel {
const key = `${v.options.bank ?? ''}|${v.topic}`;
const hit = models.get(key);
if (hit) return hit; if (hit) return hit;
const topic = topicById(id); const topic = topicById(v.topic, v.options.bank) ?? { id: v.topic, ko: v.topicKo, generic: [], words: [] };
const corpus = new Map<string, Set<string>>(); const corpus = new Map<string, Set<string>>();
const df = new Map<string, number>(); const df = new Map<string, number>();
for (const w of topic.words) { for (const w of topic.words) {
@@ -108,7 +110,8 @@ function model(id: LiarView['topic']): TopicModel {
const idf = new Map<string, number>(); const idf = new Map<string, number>();
for (const [g, d] of df) idf.set(g, Math.log((n + 1) / d) - 0.15); for (const [g, d] of df) idf.set(g, Math.log((n + 1) / d) - 0.15);
const m = { topic, corpus, idf }; const m = { topic, corpus, idf };
models.set(id, m); if (models.size > 200) models.clear();
models.set(key, m);
return m; return m;
} }
@@ -158,7 +161,7 @@ class LiarBot {
this.q = Math.min(1, Math.max(0, (level - 1) / 59)); this.q = Math.min(1, Math.max(0, (level - 1) / 59));
const ph = this.v.phase; const ph = this.v.phase;
this.phaseId = `${ph.kind}:${ph.round}:${ph.turn}:${ph.voteRound ?? 0}:${ph.startedAt}`; this.phaseId = `${ph.kind}:${ph.round}:${ph.turn}:${ph.voteRound ?? 0}:${ph.startedAt}`;
this.m = model(this.v.topic); this.m = model(this.v);
} }
private h(...k: (string | number)[]): number { private h(...k: (string | number)[]): number {
@@ -447,7 +450,7 @@ class LiarBot {
const g = this.guessWord(); const g = this.guessWord();
if (g) return g; if (g) return g;
const words = this.m.topic.words.map((w) => w.word).filter((w) => w !== this.my.word); 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)]!; return words[Math.floor(this.h('blind') * words.length)] ?? (this.smart ? '모르겠어요' : '몰라');
} }
private replies(key: (s: string) => string, chat: (t: string) => LiarAction | null): Intent[] { private replies(key: (s: string) => string, chat: (t: string) => LiarAction | null): Intent[] {

View File

@@ -9,14 +9,16 @@
* 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과. * 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
* *
* Secrecy (§8.3): the view gives citizens the word and the liar only the topic (바보 모드: a different word of the topic, * 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. * from the same 비슷한 단어 묶음 when it has one, and the liar is told "시민" like everybody else). Who the liar is never
* appears in any view before the reveal.
*
* Word bank: setup reads the bank version stamped on the options (`bank`, admin edits) and copies what the game needs
* (topic name, its words and their other spellings) into the state, so nothing after setup reads the bank.
*/ */
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine'; import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine';
import { judge, normalize } from '../catchmind/text'; import { judge, normalize } from '../catchmind/text';
import { chatProblem, cleanChat } from '../mafia'; import { chatProblem, cleanChat } from '../mafia';
import { import {
TOPIC_IDS,
TOPIC_KO,
liarActionSchema, liarActionSchema,
liarOptionsSchema, liarOptionsSchema,
type LiarAction, type LiarAction,
@@ -28,13 +30,28 @@ import {
type Phase, type Phase,
type PlayerState, type PlayerState,
type PublicEvent, type PublicEvent,
type TopicId,
type WinReason, type WinReason,
} from './types'; } from './types';
import { TOPICS, topicById, wordEntry } from './words'; import { TOPICS, bankTopics, liarBankRef, spokenForms, wordEntry, type LiarTopic } from './words';
export * from './types'; export * from './types';
export { TOPICS, topicById, wordEntry, type LiarTopic, type LiarWord } from './words'; export {
TOPICS,
HINT_MAX,
TOPIC_MIN_WORDS,
WORD_MAX,
bankTopics,
liarBankRef,
mergeBank,
setLiarBank,
setLiarBankResolver,
topicById,
topicProblems,
wordEntry,
type LiarTopic,
type LiarWord,
type TopicOverride,
} from './words';
export const REVEAL_MS = 10_000; export const REVEAL_MS = 10_000;
export const CHAT_MAX = 200; export const CHAT_MAX = 200;
@@ -56,26 +73,49 @@ function batchim(word: string): boolean {
return code >= 0xac00 && code <= 0xd7a3 && (code - 0xac00) % 28 !== 0; return code >= 0xac00 && code <= 0xd7a3 && (code - 0xac00) % 28 !== 0;
} }
/** Words that count as saying `word` (the word and its 2+ letter aliases), normalized. */ /** Does the text say the word or one of its other spellings (spaces, punctuation and case ignored)? */
function spoken(topic: TopicId, word: string): string[] { function says(text: string, word: string, aliases: readonly string[] = []): boolean {
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); const t = normalize(text);
return spoken(topic, word).some((x) => t.includes(x)); return spokenForms(word, aliases).some((x) => t.includes(x));
} }
/** Is `text` the word (or an alias), ignoring spaces, case and a polite ending ("수박이요")? */ /** Does the text say the word of a topic in the bank (version `ref`, default the code's)? */
export function isCorrectGuess(text: string, topic: TopicId, word: string): boolean { export function saysWord(text: string, topic: string, word: string, ref?: string | null): boolean {
const e = wordEntry(topic, word); return says(text, word, wordEntry(topic, word, ref)?.aliases);
return judge(text, [word, ...(e?.aliases ?? [])], false) === 'correct'; }
/** Is `text` the word (or an alias), ignoring spaces, case and a polite ending ("수박요")? */
function correct(text: string, word: string, aliases: readonly string[] = []): boolean {
return judge(text, [word, ...aliases], false) === 'correct';
}
/** `correct` for a word of a topic in the bank (version `ref`, default the code's). */
export function isCorrectGuess(text: string, topic: string, word: string, ref?: string | null): boolean {
return correct(text, word, wordEntry(topic, word, ref)?.aliases);
}
/**
* 바보 모드: the liar's word. Another word of the same 비슷한 단어 묶음 when there is one, else any other word of the topic.
* Exported for tests.
*/
export function pickLiarWord(topic: Pick<LiarTopic, 'words'>, wi: number, int: (n: number) => number): string {
const word = topic.words[wi]!;
const near = word.group ? topic.words.filter((x, i) => i !== wi && x.group === word.group) : [];
const pool = near.length ? near : topic.words.filter((_, i) => i !== wi);
return pool[int(pool.length)]!.word;
} }
// ---------------------------------------------------------------- helpers // ---------------------------------------------------------------- helpers
/**
* What the game copied from the bank. Games that were running when this was added (2026-10-18) don't have it in their
* state, so those read the bank in the code instead.
*/
const old = (s: LiarState) => s as Partial<Pick<LiarState, 'aliases' | 'words' | 'topicKo'>> & LiarState;
const aliasesOf = (s: LiarState, word: string): string[] => old(s).aliases?.[word] ?? wordEntry(s.topic, word)?.aliases ?? [];
const wordsOf = (s: LiarState): string[] => old(s).words ?? TOPICS.find((t) => t.id === s.topic)?.words.map((x) => x.word) ?? [];
const topicKoOf = (s: LiarState): string => old(s).topicKo ?? TOPICS.find((t) => t.id === s.topic)?.ko ?? s.topic;
const P = (s: LiarState, id: PlayerId): PlayerState | undefined => s.players.find((p) => p.id === id); 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 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; const isPresent = (s: LiarState, id: PlayerId | null | undefined) => !!id && !!P(s, id) && !P(s, id)!.left;
@@ -190,7 +230,7 @@ function finish(s: LiarState, now: number, winner: 'liar' | 'citizens', reason:
const isLiar = p.id === s.liar; const isLiar = p.id === s.liar;
scores[p.id] = p.left ? 0 : winner === 'liar' ? (isLiar ? LIAR_POINTS : 0) : isLiar ? 0 : CITIZEN_POINTS; 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.final = { winner, reason, liar: s.liar, topic: s.topic, topicKo: topicKoOf(s), word, liarWord: s.liarWord, accused: s.accused, guess: s.guess, scores, summary: summary[reason] };
s.phase = { kind: 'ended' }; s.phase = { kind: 'ended' };
pushEvent(s, now, { t: 'end', winner }); pushEvent(s, now, { t: 'end', winner });
} }
@@ -226,9 +266,9 @@ function resolveVote(s: LiarState, now: number): void {
function resolveGuess(s: LiarState, now: number, text: string | null): void { function resolveGuess(s: LiarState, now: number, text: string | null): void {
s.guess = text; s.guess = text;
const correct = text !== null && isCorrectGuess(text, s.topic, s.word); const right = text !== null && correct(text, s.word, aliasesOf(s, s.word));
pushEvent(s, now, { t: 'guess', text, correct }); pushEvent(s, now, { t: 'guess', text, correct: right });
finish(s, now, correct ? 'liar' : 'citizens', correct ? 'guessed' : 'caught'); finish(s, now, right ? 'liar' : 'citizens', right ? 'guessed' : 'caught');
} }
/** The phase timer ran out (or everyone agreed to move on). */ /** The phase timer ran out (or everyone agreed to move on). */
@@ -303,7 +343,7 @@ function textProblem(s: LiarState, actor: PlayerId, text: string): string | null
const why = chatProblem(text, s.options.kidSafeChat); const why = chatProblem(text, s.options.kidSafeChat);
if (why) return why; if (why) return why;
const mine = wordOf(s, actor); const mine = wordOf(s, actor);
if (mine && saysWord(text, s.topic, mine)) return '제시어를 직접 말하면 안 돼요.'; if (mine && says(text, mine, aliasesOf(s, mine))) return '제시어를 직접 말하면 안 돼요.';
return null; return null;
} }
@@ -355,7 +395,7 @@ function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: num
const text = cleanChat(a.text); const text = cleanChat(a.text);
if (!text) return fail('제시어를 적어 주세요.'); if (!text) return fail('제시어를 적어 주세요.');
if ([...text].length > GUESS_MAX) return fail(`${GUESS_MAX}자까지 적을 수 있어요.`); 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('목록에 있는 단어를 골라 주세요.'); if (s.options.guessMode === 'choice' && !wordsOf(s).includes(text)) return fail('목록에 있는 단어를 골라 주세요.');
return ok; return ok;
} }
} }
@@ -392,7 +432,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView {
me: me?.id ?? null, me: me?.id ?? null,
options: s.options, options: s.options,
topic: s.topic, topic: s.topic,
topicKo: TOPIC_KO[s.topic], topicKo: topicKoOf(s),
phase: { phase: {
kind: ph.kind, kind: ph.kind,
startedAt: ph.kind === 'ended' ? 0 : ph.startedAt, startedAt: ph.kind === 'ended' ? 0 : ph.startedAt,
@@ -407,7 +447,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView {
candidates: ph.kind === 'vote' ? [...ph.candidates] : [], candidates: ph.kind === 'vote' ? [...ph.candidates] : [],
votedCount: ph.kind === 'vote' ? voters(s).filter((p) => hasVoted(ph, p.id)).length : 0, votedCount: ph.kind === 'vote' ? voters(s).filter((p) => hasVoted(ph, p.id)).length : 0,
liar: ph.kind === 'guess' ? s.liar : null, 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')) : [], choices: ph.kind === 'guess' && s.options.guessMode === 'choice' ? wordsOf(s).sort((a, b) => a.localeCompare(b, 'ko')) : [],
}, },
rounds: s.options.rounds, rounds: s.options.rounds,
order: [...s.order], order: [...s.order],
@@ -458,23 +498,34 @@ export const liar: Def = {
actionSchema: liarActionSchema as unknown as Def['actionSchema'], actionSchema: liarActionSchema as unknown as Def['actionSchema'],
ownChat: true, ownChat: true,
/** Stamps the version of the (admin-edited) word bank this game uses (null = the bank in the code: nothing to stamp). */
prepareOptions(options) {
const ref = liarBankRef();
const { bank: _old, ...rest } = options;
return ref ? { ...rest, bank: ref } : rest;
},
setup({ players, options, rng, now }) { setup({ players, options, rng, now }) {
const topic: TopicId = options.topic === 'random' ? TOPIC_IDS[rng.int(TOPIC_IDS.length)]! : options.topic; const topics = bankTopics(options.bank).filter((t) => t.words.length >= 2);
const words = topicById(topic).words; // A topic the admin removed (or a bank without it) plays as 무작위.
const fixed = options.topic === 'random' ? undefined : topics.find((t) => t.id === options.topic);
const topic = fixed ?? topics[rng.int(topics.length)]!;
const words = topic.words;
const wi = rng.int(words.length); const wi = rng.int(words.length);
const liarId = players[rng.int(players.length)]!; const liarId = players[rng.int(players.length)]!;
let liarWord: string | null = null; const liarWord = options.foolMode ? pickLiarWord(topic, wi, (n) => rng.int(n)) : null;
if (options.foolMode) { const aliases: Record<string, string[]> = {};
const rest = words.filter((_, i) => i !== wi); for (const x of words) if (x.aliases?.length) aliases[x.word] = [...x.aliases];
liarWord = rest[rng.int(rest.length)]!.word;
}
// Seats in order, starting from a random first speaker. // Seats in order, starting from a random first speaker.
const first = rng.int(players.length); const first = rng.int(players.length);
const order = [...players.slice(first), ...players.slice(0, first)]; const order = [...players.slice(first), ...players.slice(0, first)];
return { return {
options, options,
players: players.map((id) => ({ id, left: false })), players: players.map((id) => ({ id, left: false })),
topic, topic: topic.id,
topicKo: topic.ko,
words: words.map((x) => x.word),
aliases,
word: words[wi]!.word, word: words[wi]!.word,
liar: liarId, liar: liarId,
liarWord, liarWord,
@@ -591,7 +642,7 @@ export const liar: Def = {
if (me.canReady) out.push({ type: 'ready' }); if (me.canReady) out.push({ type: 'ready' });
for (const t of me.voteTargets) out.push({ type: 'vote', target: t }); for (const t of me.voteTargets) out.push({ type: 'vote', target: t });
if (me.canGuess) { if (me.canGuess) {
if (s.options.guessMode === 'choice') for (const x of topicById(s.topic).words) out.push({ type: 'guess', text: x.word }); if (s.options.guessMode === 'choice') for (const x of wordsOf(s)) out.push({ type: 'guess', text: x });
else out.push({ type: 'guess', text: s.word }, { type: 'guess', text: `${s.word} 아님` }); else out.push({ type: 'guess', text: s.word }, { type: 'guess', text: `${s.word} 아님` });
} }
return out.filter((a) => validate(s, player, a).ok); return out.filter((a) => validate(s, player, a).ok);

View File

@@ -1,4 +1,4 @@
import { describe, expect, test } from 'bun:test'; import { afterEach, describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN, type PlayerId } from '@bg/engine'; import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN, type PlayerId } from '@bg/engine';
import { normalize } from '../catchmind/text'; import { normalize } from '../catchmind/text';
import { chatProblem } from '../mafia'; import { chatProblem } from '../mafia';
@@ -9,6 +9,12 @@ import {
TOPICS, TOPICS,
isCorrectGuess, isCorrectGuess,
liar, liar,
mergeBank,
pickLiarWord,
setLiarBank,
setLiarBankResolver,
topicProblems,
type LiarTopic,
roundOrder, roundOrder,
saysWord, saysWord,
topicById, topicById,
@@ -131,7 +137,7 @@ describe('준비와 비밀 (§4, §8.3)', () => {
liars.add(s.liar); liars.add(s.liar);
firsts.add(s.order[0]!); firsts.add(s.order[0]!);
topics.add(s.topic); topics.add(s.topic);
expect(topicById(s.topic).words.some((w) => w.word === s.word)).toBe(true); expect(topicById(s.topic)!.words.some((w) => w.word === s.word)).toBe(true);
const k = ids(5).indexOf(s.order[0]!); const k = ids(5).indexOf(s.order[0]!);
expect(s.order).toEqual([...ids(5).slice(k), ...ids(5).slice(0, k)]); expect(s.order).toEqual([...ids(5).slice(k), ...ids(5).slice(0, k)]);
expect(s.liarWord).toBeNull(); expect(s.liarWord).toBeNull();
@@ -361,7 +367,7 @@ describe('토론과 투표 (§5.3~5.5)', () => {
s = toGuess({ guessMode: 'choice' }); s = toGuess({ guessMode: 'choice' });
const choices = liar.view(s, 'P3').phase.choices; const choices = liar.view(s, 'P3').phase.choices;
expect(choices).toContain('수박'); expect(choices).toContain('수박');
expect(choices).toHaveLength(topicById('fruit').words.length); expect(choices).toHaveLength(topicById('fruit')!.words.length);
expect(reject(s, 'P3', { type: 'guess', text: '고양이' })).toBe('목록에 있는 단어를 골라 주세요.'); expect(reject(s, 'P3', { type: 'guess', text: '고양이' })).toBe('목록에 있는 단어를 골라 주세요.');
expect(act(s, 'P3', { type: 'guess', text: '수박' }).final!.winner).toBe('liar'); expect(act(s, 'P3', { type: 'guess', text: '수박' }).final!.winner).toBe('liar');
}); });
@@ -474,3 +480,116 @@ describe('무작위 대국 (엔진 공통 검사)', () => {
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState)); expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
}); });
}); });
// ---------------------------------------------------------------- 비슷한 단어 묶음 (바보 모드)
describe('비슷한 단어 묶음과 바보 모드 (§3, §4)', () => {
test('모든 단어가 묶음 하나에 들어 있고, 묶음마다 2개 이상이에요', () => {
for (const t of TOPICS) {
const sizes = new Map<string, number>();
for (const w of t.words) {
expect(w.group, `${t.id}: ${w.word}`).toBeTruthy();
sizes.set(w.group!, (sizes.get(w.group!) ?? 0) + 1);
}
for (const [g, n] of sizes) expect(n, `${t.id}: ${g}`).toBeGreaterThanOrEqual(2);
}
});
test('관리자 화면 검사(topicProblems)도 코드의 제시어 은행을 모두 통과시켜요', () => {
for (const t of TOPICS) expect(topicProblems(t), t.id).toEqual([]);
});
test('바보 모드의 라이어는 제시어와 같은 묶음의 다른 단어를 받아요', () => {
for (let i = 1; i <= 300; i++) {
const s = liar.setup({ players: ids(4), options: opts({ foolMode: true }), rng: SeededRng.fromSeed(seedN(i)), now: T0 });
const t = topicById(s.topic)!;
const group = (x: string) => t.words.find((w) => w.word === x)!.group;
expect(s.liarWord).not.toBe(s.word);
expect(group(s.liarWord!), `${s.word} → ${s.liarWord}`).toBe(group(s.word));
}
});
test('묶음이 없거나 혼자인 단어는 같은 주제의 아무 다른 단어', () => {
const t = { words: [{ word: '가나', hints: [], group: 'a' }, { word: '다라', hints: [] }, { word: '마바', hints: [], group: 'b' }] };
const got = new Set<string>();
for (let k = 0; k < 2; k++) got.add(pickLiarWord(t, 0, () => k));
expect([...got].sort()).toEqual(['다라', '마바']);
expect(pickLiarWord({ words: [...t.words, { word: '사아', hints: [], group: 'a' }] }, 0, () => 0)).toBe('사아');
});
});
// ---------------------------------------------------------------- 관리자가 고친 제시어 은행
describe('관리자가 고친 제시어 은행 (§3.1)', () => {
afterEach(() => {
setLiarBank(TOPICS, null);
setLiarBankResolver(null);
});
const mine: Omit<LiarTopic, 'id'> = {
ko: '우리 반',
generic: ['우리 반에 있어요'],
words: [
{ word: '칠판', hints: ['앞에 걸려 있어요'], aliases: ['흑판'], group: '앞' },
{ word: '교탁', hints: ['선생님 자리예요'], group: '앞' },
{ word: '사물함', hints: ['뒤에 있어요'] },
],
};
test('mergeBank: 내장 주제 바꾸기·지우기, 관리자 주제는 뒤에', () => {
const bank = mergeBank([{ id: 'c_x', topic: mine }, { id: 'fruit', topic: { ...mine, ko: '과일2' } }, { id: 'person', deleted: true }]);
expect(bank.map((t) => t.id)).toEqual([...TOPIC_IDS.filter((x) => x !== 'person'), 'c_x']);
expect(bank.find((t) => t.id === 'fruit')!.ko).toBe('과일2');
});
test('새 판은 그 판본을 옵션에 붙이고(prepareOptions), 판이 시작되면 은행이 바뀌어도 그 판은 그대로예요', () => {
expect(liar.prepareOptions!(opts())).toEqual(opts());
setLiarBank(mergeBank([{ id: 'c_x', topic: mine }]), 'v1');
const o = liar.prepareOptions!(opts({ topic: 'c_x' }));
expect(o.bank).toBe('v1');
const s = liar.setup({ players: ids(3), options: o, rng: SeededRng.fromSeed(seedN(3)), now: T0 });
expect(s.topic).toBe('c_x');
expect(s.topicKo).toBe('우리 반');
expect(s.words).toEqual(['칠판', '교탁', '사물함']);
expect(s.aliases).toEqual({ 칠판: ['흑판'] });
// The bank changes (the topic is deleted): the running game keeps its words, other spellings and topic name.
setLiarBank(TOPICS, null);
const g = { ...s, word: '칠판', liar: 'P2', order: ids(3) };
expect(liar.validate(g, 'P0', { type: 'chat', text: '흑판 아닐까요' }, { now: T0 })).toEqual({ ok: false, reason: '제시어를 직접 말하면 안 돼요.' });
expect(liar.view(g, null).topicKo).toBe('우리 반');
});
test('다시 보기: 지난 판본은 resolver로 찾아 같은 판을 다시 만들어요. 없는 주제는 무작위', () => {
const v1 = mergeBank([{ id: 'c_x', topic: mine }]);
setLiarBank(v1, 'v1');
const o = liar.prepareOptions!(opts({ topic: 'c_x', foolMode: true }));
const a = liar.setup({ players: ids(3), options: o, rng: SeededRng.fromSeed(seedN(5)), now: T0 });
setLiarBank(TOPICS, null);
setLiarBankResolver((ref) => (ref === 'v1' ? v1 : null));
const b = liar.setup({ players: ids(3), options: o, rng: SeededRng.fromSeed(seedN(5)), now: T0 });
expect(b).toEqual(a);
if (a.word !== '사물함') expect(['칠판', '교탁'].filter((x) => x !== a.word)).toEqual([a.liarWord!]);
// A topic that isn't in the bank plays as 무작위 from the topics that are.
setLiarBankResolver(null);
const c = liar.setup({ players: ids(3), options: o, rng: SeededRng.fromSeed(seedN(5)), now: T0 });
expect(TOPIC_IDS as readonly string[]).toContain(c.topic);
});
test('topicProblems: 제시어가 설명·무난한 말에 들어가거나, 서로 포함되거나, 너무 적으면 막아요', () => {
expect(topicProblems(mine)).toEqual([]);
const bad = topicProblems({
ko: '',
generic: ['칠판이 있어요'],
words: [
{ word: '칠판', hints: ['칠 판 앞에서'] },
{ word: '큰칠판', hints: [] },
{ word: '가', hints: [] },
],
});
expect(bad.join('\n')).toContain('주제 이름');
expect(bad.join('\n')).toContain("'칠판'의 설명");
expect(bad.join('\n')).toContain("'칠판'가 '큰칠판' 안에");
expect(bad.join('\n')).toContain('두 글자 이상');
expect(bad.join('\n')).toContain('무난한 말');
expect(topicProblems({ ...mine, words: mine.words.slice(0, 1) }).join()).toContain('2개 이상');
});
});

View File

@@ -1,7 +1,7 @@
/** 라이어 게임 options, actions, state and view types (docs/games/liar.md §2, §8). */ /** 라이어 게임 options, actions, state and view types (docs/games/liar.md §2, §8). */
import { z } from 'zod'; import { z } from 'zod';
import type { PlayerId } from '@bg/engine'; import type { PlayerId } from '@bg/engine';
import { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics'; import { TOPIC_IDS, TOPIC_KO } from './topics';
export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics'; export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
@@ -12,11 +12,13 @@ const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v,
const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl }); const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl });
export const liarOptionsSchema = z.object({ export const liarOptionsSchema = z.object({
/** `random`, a built-in topic id, or the id of a topic an admin added (`c_…`); a topic that is gone plays as `random`. */
topic: z topic: z
.enum(['random', ...TOPIC_IDS]) .string()
.regex(/^[a-z0-9_-]{1,40}$/)
.default('random') .default('random')
.meta({ title: '주제', labels: { random: '무작위', ...TOPIC_KO } }), .meta({ title: `주제(random = 무작위, 또는 주제 ID: ${TOPIC_IDS.map((t) => `${t} ${TOPIC_KO[t]}`).join(', ')}, 관리자가 더한 주제는 c_로 시작)` }),
foolMode: z.boolean().default(false).meta({ title: '바보 모드(라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요)' }), foolMode: z.boolean().default(false).meta({ title: '바보 모드(라이어도 제시어와 비슷한 다른 단어를 받고, 자기가 라이어인지 몰라요)' }),
rounds: lit(1, 2) rounds: lit(1, 2)
.default(2) .default(2)
.meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }), .meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }),
@@ -39,7 +41,8 @@ export const liarOptionsSchema = z.object({
.meta({ title: '정답 맞히기 시간', labels: secLabelsU('무제한(라이어가 답할 때까지)', 20, 30, 45, 60) }), .meta({ title: '정답 맞히기 시간', labels: secLabelsU('무제한(라이어가 답할 때까지)', 20, 30, 45, 60) }),
kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }), kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }),
}); });
export type LiarOptions = z.infer<typeof liarOptionsSchema>; /** `bank`: the word-bank version the server stamped on this game (`prepareOptions`); absent = the bank in the code. */
export type LiarOptions = z.infer<typeof liarOptionsSchema> & { bank?: string };
const pid = z.string().min(1).max(64); const pid = z.string().min(1).max(64);
export const liarActionSchema = z.discriminatedUnion('type', [ export const liarActionSchema = z.discriminatedUnion('type', [
@@ -107,7 +110,8 @@ export interface LiarFinal {
winner: 'liar' | 'citizens'; winner: 'liar' | 'citizens';
reason: WinReason; reason: WinReason;
liar: PlayerId; liar: PlayerId;
topic: TopicId; topic: string;
topicKo: string;
word: string; word: string;
/** 바보 모드: the word the liar got. */ /** 바보 모드: the word the liar got. */
liarWord: string | null; liarWord: string | null;
@@ -120,7 +124,13 @@ export interface LiarFinal {
export interface LiarState { export interface LiarState {
options: LiarOptions; options: LiarOptions;
players: PlayerState[]; players: PlayerState[];
topic: TopicId; /** Topic id (built-in `TopicId` or an admin's `c_…`). The game keeps what it needs of the bank, so an admin change mid-game can't touch it. */
topic: string;
topicKo: string;
/** Every word of the topic (the guess list in 고르기 mode). */
words: string[];
/** Other spellings of the topic's words (only words that have some). */
aliases: Record<string, string[]>;
word: string; word: string;
liar: PlayerId; liar: PlayerId;
/** 바보 모드: the liar's own (wrong) word; null otherwise. */ /** 바보 모드: the liar's own (wrong) word; null otherwise. */
@@ -170,7 +180,7 @@ export interface MyView {
export interface LiarView { export interface LiarView {
me: PlayerId | null; me: PlayerId | null;
options: LiarOptions; options: LiarOptions;
topic: TopicId; topic: string;
topicKo: string; topicKo: string;
phase: { phase: {
kind: PhaseKind; kind: PhaseKind;

View File

@@ -5,10 +5,16 @@
* 단어 자체(띄어쓰기 무시)는 절대 들어가지 않아요(테스트로 확인). * 단어 자체(띄어쓰기 무시)는 절대 들어가지 않아요(테스트로 확인).
* - `aliases`: 라이어가 맞힐 때 정답으로 쳐 주는 다른 표기(핸드폰/휴대폰 등). * - `aliases`: 라이어가 맞힐 때 정답으로 쳐 주는 다른 표기(핸드폰/휴대폰 등).
* - 주제의 `generic`: 그 주제 어디에나 맞는 무난한 말. 아직 아무 설명도 못 들은 라이어 컴퓨터가 써요. * - 주제의 `generic`: 그 주제 어디에나 맞는 무난한 말. 아직 아무 설명도 못 들은 라이어 컴퓨터가 써요.
* - 주제의 `groups`: 비슷한 단어 묶음. 바보 모드의 라이어는 제시어와 같은 묶음의 다른 단어를 받아요.
* 주제마다 파일 하나(`bank/<주제>.ts`). * 주제마다 파일 하나(`bank/<주제>.ts`).
* 한 글자 단어(배, 귤, 컵 …)는 넣지 않아요: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막아 버려서요. * 한 글자 단어(배, 귤, 컵 …)는 넣지 않아요: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막아 버려서요.
*
* 관리자 수정 (docs/games/liar.md §3.1): 관리자는 주제를 통째로 고치거나(내장 주제 덮어쓰기), 지우거나, 새 주제를 더해요.
* 서버가 그 결과(`mergeBank`)를 `setLiarBank`로 알려 주고, 새 판의 옵션에 그 판본 이름(`bank`)을 붙여요.
* 다시 보기는 같은 판본으로 다시 돌려야 해서, 지난 판본은 `setLiarBankResolver`로 찾아요.
*/ */
import type { TopicId } from './types'; import { normalize } from '../catchmind/text';
import { chatProblem } from '../mafia';
import type { LiarTopic, LiarWord } from './bank/w'; import type { LiarTopic, LiarWord } from './bank/w';
import { fruit } from './bank/fruit'; import { fruit } from './bank/fruit';
import { animal } from './bank/animal'; import { animal } from './bank/animal';
@@ -36,10 +42,112 @@ import { landmark } from './bank/landmark';
export type { LiarTopic, LiarWord } from './bank/w'; export type { LiarTopic, LiarWord } from './bank/w';
export const TOPICS: readonly LiarTopic[] = [fruit, animal, job, food, place, sport, vehicle, thing, country, fairy, vegetable, sea, snack, clothes, body, nature, game, movie, person, brand, character, instrument, landmark]; /** Copies the topic's `groups` onto each word's `group`. */
function withGroups(t: LiarTopic): LiarTopic {
export const topicById = (id: TopicId): LiarTopic => TOPICS.find((t) => t.id === id)!; const groupOf = new Map<string, string>();
for (const [g, ws] of Object.entries(t.groups ?? {})) for (const x of ws) groupOf.set(x, g);
export function wordEntry(topic: TopicId, word: string): LiarWord | undefined { const { groups: _g, ...rest } = t;
return topicById(topic).words.find((x) => x.word === word); return { ...rest, words: t.words.map((x) => (groupOf.has(x.word) ? { ...x, group: groupOf.get(x.word)! } : x)) };
}
/** The bank in the code (before any admin change). */
export const TOPICS: readonly LiarTopic[] = [fruit, animal, job, food, place, sport, vehicle, thing, country, fairy, vegetable, sea, snack, clothes, body, nature, game, movie, person, brand, character, instrument, landmark].map(withGroups);
// ---------------------------------------------------------------- admin changes
/** One admin change: a built-in topic replaced or deleted, or a topic of the admin's own (`c_…`). */
export interface TopicOverride {
id: string;
deleted?: boolean;
topic?: Omit<LiarTopic, 'id' | 'groups'>;
}
/** The bank the game uses: built-in topics in code order (replaced or dropped by overrides), then the admin's own. */
export function mergeBank(overrides: readonly TopicOverride[]): LiarTopic[] {
const by = new Map(overrides.map((o) => [o.id, o]));
const out: LiarTopic[] = [];
for (const t of TOPICS) {
const o = by.get(t.id);
if (o?.deleted) continue;
out.push(o?.topic ? { id: t.id, ...o.topic } : t);
}
for (const o of overrides) if (!o.deleted && o.topic && !TOPICS.some((t) => t.id === o.id)) out.push({ id: o.id, ...o.topic });
return out;
}
let live: { ref: string | null; topics: readonly LiarTopic[] } = { ref: null, topics: TOPICS };
let resolver: ((ref: string) => readonly LiarTopic[] | null) | null = null;
/** The server's current bank and its version name (null = the bank in the code). New games use it. */
export function setLiarBank(topics: readonly LiarTopic[], ref: string | null): void {
live = { ref, topics };
}
/** Finds an older bank version (for replays and games that started before an admin change). */
export function setLiarBankResolver(fn: ((ref: string) => readonly LiarTopic[] | null) | null): void {
resolver = fn;
}
/** Version name of the current bank (null = the bank in the code). */
export const liarBankRef = (): string | null => live.ref;
/** The bank of a version (null/undefined = the bank in the code; an unknown version falls back to it too). */
export function bankTopics(ref?: string | null): readonly LiarTopic[] {
if (!ref) return TOPICS;
if (ref === live.ref) return live.topics;
return resolver?.(ref) ?? TOPICS;
}
export const topicById = (id: string, ref?: string | null): LiarTopic | undefined => bankTopics(ref).find((t) => t.id === id);
export function wordEntry(topic: string, word: string, ref?: string | null): LiarWord | undefined {
return topicById(topic, ref)?.words.find((x) => x.word === word);
}
// ---------------------------------------------------------------- checks (tests and the admin editor)
export const WORD_MAX = 20;
export const HINT_MAX = 80;
/** A topic needs two words at least (바보 모드 gives the liar another one). */
export const TOPIC_MIN_WORDS = 2;
/** Words that count as saying `word` (the word and its 2+ letter aliases), normalized. */
export function spokenForms(word: string, aliases: readonly string[] = []): string[] {
return [word, ...aliases].map(normalize).filter((x) => [...x].length >= 2);
}
/**
* What is wrong with a topic (Korean, empty = fine): 단어 2글자 이상·중복 없음·서로 포함 없음, 설명에 그 단어 없음,
* 무난한 말에 주제의 어떤 단어도 없음, 고운 말, 길이.
*/
export function topicProblems(t: Pick<LiarTopic, 'ko' | 'generic' | 'words'>): string[] {
const out: string[] = [];
if (!t.ko.trim()) out.push('주제 이름을 적어 주세요.');
if (t.words.length < TOPIC_MIN_WORDS) out.push(`제시어가 ${TOPIC_MIN_WORDS}개 이상 있어야 해요.`);
const seen = new Map<string, string>();
for (const x of t.words) {
const n = normalize(x.word);
if ([...n].length < 2) out.push(`'${x.word}': 제시어는 두 글자 이상이어야 해요(한 글자면 다른 말까지 막혀요).`);
if ([...x.word].length > WORD_MAX) out.push(`'${x.word}': 제시어는 ${WORD_MAX}자까지예요.`);
if (seen.has(n)) out.push(`'${x.word}': 같은 제시어가 두 번 있어요.`);
seen.set(n, x.word);
for (const a of x.aliases ?? []) if ([...a].length > WORD_MAX) out.push(`'${x.word}'의 다른 표기 '${a}': ${WORD_MAX}자까지예요.`);
const forms = spokenForms(x.word, x.aliases);
for (const h of x.hints) {
const hn = normalize(h);
if (forms.some((f) => hn.includes(f))) out.push(`'${x.word}'의 설명 "${h}"에 제시어가 들어 있어요.`);
if ([...h].length > HINT_MAX) out.push(`'${x.word}'의 설명 "${h}": ${HINT_MAX}자까지예요.`);
const bad = chatProblem(h, true);
if (bad) out.push(`'${x.word}'의 설명 "${h}": ${bad}`);
}
}
const ns = [...seen.keys()];
for (const a of ns) for (const b of ns) if (a !== b && b.includes(a)) out.push(`'${seen.get(a)}'가 '${seen.get(b)}' 안에 들어 있어요(헷갈리지 않게 둘 중 하나를 빼 주세요).`);
for (const g of t.generic) {
const gn = normalize(g);
const hit = t.words.find((x) => spokenForms(x.word, x.aliases).some((f) => gn.includes(f)));
if (hit) out.push(`무난한 말 "${g}"에 제시어 '${hit.word}'가 들어 있어요.`);
if ([...g].length > HINT_MAX) out.push(`무난한 말 "${g}": ${HINT_MAX}자까지예요.`);
const bad = chatProblem(g, true);
if (bad) out.push(`무난한 말 "${g}": ${bad}`);
}
return out;
} }

View File

@@ -0,0 +1,30 @@
/** Checks the 비슷한 단어 묶음 (`groups`) of the 라이어 게임 word bank: bun scripts/liar-groups-check.ts [topicId...] */
import { readdirSync } from 'node:fs';
const dir = new URL('../packages/games/src/liar/bank/', import.meta.url).pathname;
const want = process.argv.slice(2);
let bad = 0;
for (const f of readdirSync(dir).filter((f) => f.endsWith('.ts') && f !== 'w.ts')) {
const mod = await import(dir + f);
const t = Object.values(mod)[0] as { id: string; words: { word: string }[]; groups?: Record<string, string[]> };
if (want.length && !want.includes(t.id)) continue;
const errs: string[] = [];
if (!t.groups) errs.push('groups 없음');
else {
const seen = new Map<string, string>();
const words = new Set(t.words.map((x) => x.word));
for (const [g, ws] of Object.entries(t.groups)) {
if (ws.length < 2) errs.push(`'${g}' 묶음이 ${ws.length}개(2개 이상 필요)`);
for (const x of ws) {
if (!words.has(x)) errs.push(`'${g}'의 '${x}'는 주제에 없는 단어`);
if (seen.has(x)) errs.push(`'${x}'가 '${seen.get(x)}'와 '${g}' 두 묶음에 있음`);
seen.set(x, g);
}
}
for (const x of words) if (!seen.has(x)) errs.push(`'${x}'가 어느 묶음에도 없음`);
const sizes = Object.values(t.groups).map((x) => x.length);
console.log(`${t.id}: 단어 ${words.size}, 묶음 ${sizes.length}개 (크기 ${Math.min(...sizes)}~${Math.max(...sizes)})${errs.length ? ' ❌' : ' ✅'}`);
}
for (const e of errs) console.log(' - ' + e);
bad += errs.length;
}
process.exit(bad ? 1 : 0);