새 게임 라이어 게임: 규칙 엔진·말하는 컴퓨터·화면·도움말·문서·E2E
- packages/games/src/liar: 주제 10개 제시어 은행, 설명(두 번째 바퀴 거꾸로)·자유 토론·투표(동점 재투표 한 번, 또 동점이면 라이어 승리)·라이어 정답 맞히기(띄어쓰기·다른 표기 무시), 바보 모드 - 컴퓨터: 마피아처럼 live 전략, 레벨 1~60을 LiveBotInput.level 로 받음(서버 BotDriver 가 넘김), BOT_CHAT_REQUIRED 에 추가 - 웹: 꾹 누르는 제시어 카드, 설명 기록·토론 채팅·투표 화면, 30초 요약, [?] 도움말 - 문서 docs/games/liar.md, 등록(GAMES·CATALOG·BOT_GAMES·registry·아이콘), 서버 방 테스트, E2E(거절 알림이 저절로 사라지는지 확인 포함) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
117
apps/server/src/rooms/liar.room.test.ts
Normal file
117
apps/server/src/rooms/liar.room.test.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* 라이어 게임 through a real Room with computers: one person and computers play a whole game with the real bot driver
|
||||
* and the room clock. The person's connection never learns the word (when they are the liar) or who the liar is (when
|
||||
* they are a citizen) before the reveal, and the room chat stays closed while the game runs.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { LiarState, LiarView } from '@bg/games/liar';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Conn, Room } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function practice(person = 'A') {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const logs: string[] = [];
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: '철수', avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0, log: (level, msg) => level !== 'info' && logs.push(msg) });
|
||||
const room = manager.createPractice(person, 'liar') as Room;
|
||||
rooms.push(room);
|
||||
const msgs: ServerMessage[] = [];
|
||||
const conn: Conn & { msgs: ServerMessage[] } = { userId: person, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(conn, 'player');
|
||||
const state = () => room.game!.state as LiarState;
|
||||
const lastView = () => (msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as LiarView;
|
||||
/** Lets the computers act (their own timers) and the room clock run, until `stop` or the end. */
|
||||
const run = (stop: () => boolean = () => false, maxSteps = 4000) => {
|
||||
for (let i = 0; i < maxSteps && !room.game!.finished && !stop(); i++) {
|
||||
const next = Math.min(room.bots.dueAt ?? Infinity, room.effectiveDeadline() ?? Infinity);
|
||||
expect(Number.isFinite(next)).toBe(true);
|
||||
clock.advance(Math.max(0, next - clock.now()));
|
||||
room.bots.fire();
|
||||
room.onTimer();
|
||||
}
|
||||
};
|
||||
return { room, clock, msgs, conn, state, lastView, run, logs };
|
||||
}
|
||||
|
||||
describe('라이어 게임 room flow with computers', () => {
|
||||
test('연습 방은 사람 1 + 컴퓨터 4, 컴퓨터 채팅은 항상 켜짐', () => {
|
||||
const { room } = practice();
|
||||
expect(room.seatedIds().filter(isBotId)).toHaveLength(4);
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.game!.players).toHaveLength(5);
|
||||
});
|
||||
|
||||
test('사람이 차례에 설명하고 토론·투표하면 컴퓨터와 한 판이 끝까지 가요', () => {
|
||||
const { room, state, lastView, msgs, run, logs } = practice();
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.chat('A', '안녕')).toBe('게임 중에는 게임 화면의 채팅을 써 주세요.');
|
||||
const s0 = state();
|
||||
const iAmLiar = s0.liar === 'A';
|
||||
// Nothing the person receives names the liar or (if they are the liar) the word, until the reveal.
|
||||
const leaks = () => {
|
||||
const all = JSON.stringify(msgs.filter((m) => m.t === 'state').map((m) => ({ ...(m as { view: LiarView }).view, final: null, events: [] })));
|
||||
if (iAmLiar) expect(all).not.toContain(`"${s0.word}"`);
|
||||
expect(all).not.toContain('"liar":true');
|
||||
};
|
||||
let cs = 1;
|
||||
let described = 0;
|
||||
// Reveal: the person confirms; the computers confirm on their own.
|
||||
room.act('A', cs++, { type: 'ready' });
|
||||
run(() => state().phase.kind !== 'reveal');
|
||||
expect(state().phase.kind).toBe('describe');
|
||||
const speaker = () => GAMES.liar!.view(state(), null).phase.speaker;
|
||||
while (state().phase.kind === 'describe') {
|
||||
if (speaker() === 'A') {
|
||||
room.act('A', cs++, { type: 'chat', text: iAmLiar ? '저는 좋아하는 편이에요' : '음 다들 아실 거예요' });
|
||||
described++;
|
||||
}
|
||||
run(() => state().phase.kind !== 'describe' || speaker() === 'A');
|
||||
}
|
||||
leaks();
|
||||
expect(described).toBe(state().options.rounds);
|
||||
// Every computer described in its turn.
|
||||
for (const d of state().descriptions) if (d.from !== 'A') expect(d.text).not.toBeNull();
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
room.act('A', cs++, { type: 'chat', text: '누가 라이어일까요' });
|
||||
room.act('A', cs++, { type: 'ready' });
|
||||
run(() => state().phase.kind !== 'discussion');
|
||||
// The computers talked in the discussion.
|
||||
expect(state().chat.some((m) => isBotId(m.from))).toBe(true);
|
||||
leaks();
|
||||
while (state().phase.kind === 'vote') {
|
||||
const v = lastView();
|
||||
if (v.my!.voteTargets.length && v.my!.vote === null) room.act('A', cs++, { type: 'vote', target: v.my!.voteTargets[0]! });
|
||||
run(() => state().phase.kind !== 'vote' || (state().phase.kind === 'vote' && (state().phase as { round: number }).round !== v.phase.voteRound));
|
||||
}
|
||||
if (state().phase.kind === 'guess' && state().liar === 'A') room.act('A', cs++, { type: 'guess', text: '모르겠어요' });
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const f = state().final!;
|
||||
expect(f.summary).toMatch(/^(라이어|시민) 승리!/);
|
||||
const end = lastView();
|
||||
expect(end.final!.liar).toBe(s0.liar);
|
||||
expect(end.players.find((p) => p.id === s0.liar)!.liar).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
test('사람이 아무것도 안 해도(시간 초과만) 끝나요', () => {
|
||||
const { room, run, state, logs } = practice();
|
||||
room.start('A');
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(31);
|
||||
expect(IDS).toHaveLength(32);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
49
apps/web/src/games/liar/help.test.ts
Normal file
49
apps/web/src/games/liar/help.test.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { applyAction, seatIds, setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const ids = seatIds(4);
|
||||
const users = usersOf(ids);
|
||||
const view = (s: unknown, who: string | null) => GAMES.liar!.view(s, who) as any;
|
||||
const T = 1_700_000_000_000;
|
||||
|
||||
function game(options: Record<string, unknown> = {}) {
|
||||
const { state } = setupGame('liar', 4, { topic: 'fruit', ...options });
|
||||
state.word = '수박';
|
||||
state.liar = 'D';
|
||||
state.order = [...ids];
|
||||
if (state.options.foolMode) state.liarWord = '참외';
|
||||
return state;
|
||||
}
|
||||
const tick = (s: any) => GAMES.liar!.apply(s, 'A', { type: 'phaseTimeout' }, { rng: undefined as never, now: s.phase.endsAt }).state;
|
||||
|
||||
test('라이어 게임: 제시어 확인 — 시민·라이어·관전자에게 맞는 안내, 제시어는 새지 않아요', () => {
|
||||
const s = game();
|
||||
const c = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(c).toContain('[내 제시어] 카드를 꾹');
|
||||
expect(c).toContain('주제는 과일이에요');
|
||||
const l = helpNow(view(s, 'D'), 'D', users);
|
||||
expect(l).toContain('나는 라이어예요');
|
||||
const spec = helpNow(view(s, null), null, users);
|
||||
expect(spec).toContain('관전 중에는 제시어가 보이지 않아요');
|
||||
for (const t of [c, l, spec]) expect(t).not.toContain('수박');
|
||||
});
|
||||
|
||||
test('라이어 게임: 바보 모드 라이어는 시민과 같은 안내를 받아요', () => {
|
||||
const s = game({ foolMode: true });
|
||||
expect(helpNow(view(s, 'D'), 'D', users)).toBe(helpNow(view(s, 'A'), 'A', users));
|
||||
});
|
||||
|
||||
test('라이어 게임: 설명 차례, 투표, 정답 맞히기', () => {
|
||||
let s = tick(game());
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('내 차례예요');
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain(`${users.A!.nickname}님이 설명하는 중`);
|
||||
s = { ...s, phase: { kind: 'vote', startedAt: T, endsAt: T + 30_000, round: 1, candidates: [...ids], votes: {} } };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('동점이면 동점인 사람끼리');
|
||||
s = applyAction('liar', s, 'A', { type: 'vote', target: 'D' }, undefined, T + 1000);
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain(`${users.D!.nickname}님을 골랐어요`);
|
||||
s = { ...s, phase: { kind: 'guess', startedAt: T, endsAt: T + 30_000 } };
|
||||
expect(helpNow(view(s, 'D'), 'D', users)).toContain('[정답!]');
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain(`${users.D!.nickname}님이 라이어였어요`);
|
||||
});
|
||||
65
apps/web/src/games/liar/help.ts
Normal file
65
apps/web/src/games/liar/help.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 라이어 게임 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view.
|
||||
* Only what this viewer may know: the word for citizens, "나는 라이어" for the liar, and in 바보 모드 the liar is told
|
||||
* the same as everybody else until the reveal.
|
||||
*/
|
||||
import type { LiarView } from '@bg/games/liar';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
/** "~이/가", "~을/를", "~은/는", "~이에요/예요" after a word. */
|
||||
function josa(word: string, pair: [string, string]): string {
|
||||
const c = word.charCodeAt(word.length - 1) - 0xac00;
|
||||
return `${word}${c >= 0 && c < 11172 && c % 28 !== 0 ? pair[0] : pair[1]}`;
|
||||
}
|
||||
|
||||
const WIN = '라이어가 아닌 사람이 지목되거나, 지목된 라이어가 제시어를 맞히면 라이어가 이겨요. 라이어를 지목하고 제시어도 지키면 시민이 이겨요.';
|
||||
|
||||
export function helpNow(v: LiarView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const n = (id: string) => `${players[id]?.nickname ?? '다른 사람'}님`;
|
||||
const ph = v.phase;
|
||||
const topic = `주제는 ${josa(v.topicKo, ['이에요', '예요'])}.`;
|
||||
if (ph.kind === 'ended' || v.final) {
|
||||
return `게임이 끝났어요. ${v.final?.summary ?? ''}`.trim() + '\n최종 공개에서 라이어와 제시어, 점수를 볼 수 있어요. [한 판 더]로 새 제시어를 받을 수 있어요.';
|
||||
}
|
||||
const my = v.my;
|
||||
if (!my) {
|
||||
const what: Record<string, string> = {
|
||||
reveal: '모두 자기 제시어를 확인하고 있어요.',
|
||||
describe: ph.speaker ? `${josa(n(ph.speaker), ['이', '가'])} 한 문장으로 설명하고 있어요.` : '한 사람씩 설명하고 있어요.',
|
||||
discussion: '누가 라이어인지 토론하고 있어요.',
|
||||
vote: '라이어로 의심되는 사람에게 투표하고 있어요.',
|
||||
guess: '지목된 라이어가 제시어를 맞히고 있어요.',
|
||||
};
|
||||
return `${topic} ${what[ph.kind] ?? ''}\n관전 중에는 제시어가 보이지 않아요. 게임이 끝나면 공개돼요.`;
|
||||
}
|
||||
if (v.players.find((p) => p.id === me)?.left) return '게임에서 나갔어요. 남은 사람들이 계속해요.';
|
||||
const liar = my.role === 'liar';
|
||||
const mine = liar ? `나는 라이어예요. 제시어는 모르고 주제만 알아요.` : `내 제시어는 위의 [내 제시어] 카드를 꾹 누르면 보여요.`;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return `${topic} ${mine}\n확인했으면 [확인했어요]를 눌러요. 모두 누르면 바로 설명이 시작돼요(${ph.readyCount}/${ph.readyNeeded}).\n${WIN}`;
|
||||
case 'describe': {
|
||||
if (my.canDescribe) {
|
||||
const tip = liar ? '앞사람 설명을 듣고 아는 척해요. 너무 구체적으로 말하면 틀릴 수 있어요.' : '제시어를 직접 말하면 안 돼요. 라이어가 알아채지 못하게 애매하게, 시민은 알아듣게 말해요.';
|
||||
return `${topic} 내 차례예요! 오른쪽 칸에 한 문장(80자까지)으로 설명하고 [말하기]를 눌러요.\n${tip} 시간이 지나면 넘어가요.`;
|
||||
}
|
||||
const round = v.rounds > 1 ? ` ${ph.round}/${v.rounds}바퀴예요${ph.round === 2 ? '(두 번째 바퀴는 거꾸로 돌아요)' : ''}.` : '';
|
||||
return `${topic} ${ph.speaker ? josa(n(ph.speaker), ['이', '가']) : '다른 사람이'} 설명하는 중이에요.${round}\n설명 기록을 잘 보고 어색한 사람을 기억해 둬요. ${mine}`;
|
||||
}
|
||||
case 'discussion':
|
||||
return `${topic} 자유 토론 시간이에요. [토론 채팅]으로 누가 라이어 같은지 이야기해요. 제시어는 직접 말할 수 없어요.\n다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 투표로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).`;
|
||||
case 'vote': {
|
||||
if (!my.voteTargets.length) return `${topic} 동점인 사람끼리 다시 투표하고 있어요. 결과를 기다려 주세요.`;
|
||||
const now = my.vote ? `지금 ${josa(n(my.vote), ['을', '를'])} 골랐어요. 시간 안에는 바꿀 수 있어요.` : '아직 고르지 않았어요.';
|
||||
const tie = ph.voteRound === 2 ? '또 동점이면 라이어가 이겨요.' : '동점이면 동점인 사람끼리 한 번 더 투표해요.';
|
||||
return `${topic} '사람들'에서 초록 테두리 사람을 눌러 라이어로 의심되는 사람을 골라요.\n${now} 표가 가장 많은 한 명이 지목돼요. ${tie}`;
|
||||
}
|
||||
case 'guess':
|
||||
if (my.canGuess) {
|
||||
const how = v.options.guessMode === 'choice' ? '목록에서 단어 하나를 눌러요.' : '입력칸에 제시어를 적고 [정답!]을 눌러요. 띄어쓰기는 상관없어요.';
|
||||
return `${topic} 들켰어요! 제시어를 맞히면 그래도 라이어가 이겨요. ${how} 기회는 한 번이에요.`;
|
||||
}
|
||||
return `${topic} ${ph.liar ? josa(n(ph.liar), ['이', '가']) : '지목된 사람이'} 라이어였어요! 라이어가 제시어를 맞히는 중이에요. 못 맞히면 시민이 이겨요.`;
|
||||
}
|
||||
return topic;
|
||||
}
|
||||
901
apps/web/src/games/liar/index.tsx
Normal file
901
apps/web/src/games/liar/index.tsx
Normal file
@@ -0,0 +1,901 @@
|
||||
/**
|
||||
* 라이어 게임 화면 (docs/games/liar.md §9).
|
||||
*
|
||||
* Like 마피아 the board carries its own chat: the room chat panel and quick reactions are closed while the game runs
|
||||
* (`ownChat`), so nobody can hint the word around the game. The word sits on a hold-to-see card (screen sharing,
|
||||
* people next to you). Descriptions are a separate, round-by-round list next to the free-talk chat.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { LiarFinal, LiarOptions, LiarView, PublicEvent } from '@bg/games/liar';
|
||||
import { TOPIC_IDS, TOPIC_KO } from '@bg/games/liar/topics';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
type Kind = LiarView['phase']['kind'];
|
||||
|
||||
const PHASE_KO: Record<Kind, string> = {
|
||||
reveal: '제시어 확인',
|
||||
describe: '한 사람씩 설명',
|
||||
discussion: '자유 토론',
|
||||
vote: '라이어 지목 투표',
|
||||
guess: '라이어의 정답 맞히기',
|
||||
ended: '게임 끝',
|
||||
};
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
|
||||
/** "~이에요/예요", "~을/를", "~이/가", "~은/는" after a word. */
|
||||
function josa(word: string, pair: [string, string]): string {
|
||||
const c = word.charCodeAt(word.length - 1) - 0xac00;
|
||||
return `${word}${c >= 0 && c < 11172 && c % 28 !== 0 ? pair[0] : pair[1]}`;
|
||||
}
|
||||
|
||||
function phaseTitle(v: LiarView): string {
|
||||
const ph = v.phase;
|
||||
if (ph.kind === 'describe') return v.rounds > 1 ? `${ph.round}바퀴째 설명` : PHASE_KO.describe;
|
||||
if (ph.kind === 'vote' && ph.voteRound === 2) return '동점자 재투표';
|
||||
return PHASE_KO[ph.kind];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- styles
|
||||
|
||||
const CSS = `
|
||||
.lg { width: 100%; height: 100%; min-height: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.lg-banner { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; border-radius: 16px; padding: 10px 14px; box-shadow: var(--shadow);
|
||||
background: linear-gradient(135deg, #ede9fe, #c4b5fd); color: #2e1065; border: 2px solid #7c3aed; }
|
||||
.lg-banner[data-hot='true'] { background: linear-gradient(135deg, #fee2e2, #fecaca); color: #450a0a; border-color: #dc2626; }
|
||||
.lg-banner[data-time='end'] { background: linear-gradient(135deg, #ecfdf5, #bbf7d0); color: #052e16; border-color: #16a34a; }
|
||||
.lg-ph { display: flex; flex-direction: column; min-width: 0; flex: 1 1 200px; }
|
||||
.lg-ph .d { font-size: .85rem; font-weight: 800; opacity: .85; }
|
||||
.lg-ph strong { font-size: 1.4rem; line-height: 1.2; }
|
||||
.lg-ph .s { font-size: .9rem; font-weight: 600; }
|
||||
.lg-clock { font-size: 2.3rem; font-weight: 900; font-variant-numeric: tabular-nums; line-height: 1; min-width: 3.2ch; text-align: center; }
|
||||
.lg-clock[data-warn='true'] { color: #dc2626; }
|
||||
.lg-card { min-height: 52px; min-width: 150px; border-radius: 12px; border: 2px dashed currentColor; background: rgba(255,255,255,.35); color: inherit;
|
||||
font: inherit; font-weight: 800; padding: 4px 12px; cursor: pointer; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: none; }
|
||||
.lg-card[data-show='true'] { color: #fff; border-style: solid; background: #6d28d9; border-color: #6d28d9; }
|
||||
.lg-card[data-show='true'][data-liar='true'] { background: #b91c1c; border-color: #b91c1c; }
|
||||
.lg-card .w { font-size: 1.25rem; }
|
||||
.lg-card:focus-visible, .lg-tile:focus-visible, .lg-choice:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.lg-news { border-radius: 16px; padding: 10px 14px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); border: 3px solid var(--focus);
|
||||
display: flex; flex-direction: column; gap: 6px; animation: lg-pop .35s ease-out; }
|
||||
.lg-news h2 { margin: 0; font-size: 1.05rem; }
|
||||
.lg-news .big { font-size: 1.12rem; font-weight: 800; }
|
||||
.lg-bars { display: grid; gap: 4px; }
|
||||
.lg-bar { display: grid; grid-template-columns: minmax(70px, 140px) 1fr 2.2em; gap: 6px; align-items: center; font-size: .88rem; font-weight: 700; }
|
||||
.lg-bar .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lg-bar .tr { height: 14px; border-radius: 7px; background: var(--surface-2); overflow: hidden; }
|
||||
.lg-bar .tr i { display: block; height: 100%; background: #8b5cf6; border-radius: 7px; animation: lg-grow .7s ease-out; transform-origin: left; }
|
||||
.lg-bar[data-top='true'] .tr i { background: #dc2626; }
|
||||
.lg-grid { flex: 1; min-height: 0; display: grid; gap: 10px; grid-template-columns: 236px minmax(0, 1fr) 290px; grid-template-areas: 'players talk actions'; }
|
||||
.lg-col { min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 8px; }
|
||||
.lg-players { grid-area: players; }
|
||||
.lg-talk { grid-area: talk; }
|
||||
.lg-actions { grid-area: actions; }
|
||||
.lg-box { background: var(--surface); color: var(--text); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.lg-box h2 { margin: 0; font-size: 1rem; }
|
||||
.lg-tiles { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
|
||||
.lg-tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 6px 4px; border-radius: 12px; min-height: 76px;
|
||||
background: var(--surface-2); color: var(--text); border: 3px solid transparent; font: inherit; text-align: center; }
|
||||
button.lg-tile { cursor: pointer; }
|
||||
.lg-tile .nm { font-weight: 800; font-size: .86rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lg-tile .no { position: absolute; top: 3px; left: 6px; font-size: .75rem; font-weight: 900; color: var(--text-sub); }
|
||||
.lg-tile.me { border-color: var(--primary); }
|
||||
.lg-tile.left { filter: grayscale(1); opacity: .55; }
|
||||
.lg-tile.speaking { border-color: #7c3aed; box-shadow: 0 0 0 3px rgba(124,58,237,.35); }
|
||||
.lg-tile.accused { border-color: #dc2626; box-shadow: 0 0 0 3px rgba(220,38,38,.35); }
|
||||
.lg-tile[data-target='ok'] { border-color: var(--success); box-shadow: 0 0 0 3px rgba(21,128,61,.35); }
|
||||
.lg-tile[data-target='ok'][aria-pressed='true'] { background: #15803d; color: #fff; border-color: #15803d; box-shadow: 0 0 0 4px rgba(21,128,61,.55); }
|
||||
.lg-tile[data-target='no'] { opacity: .5; }
|
||||
.lg-tag { display: inline-block; border-radius: 999px; padding: 0 7px; font-size: .72rem; font-weight: 800; line-height: 1.6; color: #fff; background: #4b5563; white-space: nowrap; }
|
||||
.lg-tag.say { background: #7c3aed; }
|
||||
.lg-tag.ok { background: #15803d; }
|
||||
.lg-tag.liar { background: #b91c1c; }
|
||||
.lg-desc { margin: 0; padding: 0; list-style: none; display: grid; gap: 5px; }
|
||||
.lg-desc li { background: var(--surface-2); border-radius: 10px; padding: 6px 10px; line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.lg-desc li strong { margin-right: 6px; }
|
||||
.lg-desc li.mine strong { color: var(--primary); }
|
||||
.lg-desc li.skip { color: var(--text-sub); font-style: italic; }
|
||||
.lg-desc li.now { border: 2px dashed #7c3aed; background: transparent; color: var(--text-sub); }
|
||||
.lg-round { font-size: .82rem; font-weight: 800; color: var(--text-sub); margin-top: 2px; }
|
||||
.lg-chat { flex: 1; min-height: 0; padding: 0; overflow: hidden; gap: 0; }
|
||||
.lg-chat h2 { padding: 10px 12px 6px; border-bottom: 1px solid var(--border); }
|
||||
.lg-msgs { flex: 1; min-height: 140px; overflow-y: auto; padding: 8px 10px; display: flex; flex-direction: column; gap: 5px; }
|
||||
.lg-msg { line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.lg-msg strong { margin-right: 6px; }
|
||||
.lg-msg.mine strong { color: var(--primary); }
|
||||
.lg-msg.sys { font-size: .86rem; font-weight: 700; color: var(--text-sub); background: var(--surface-2); border-radius: 8px; padding: 3px 8px; }
|
||||
.lg-form { display: flex; gap: 6px; padding: 8px; border-top: 1px solid var(--border); flex-wrap: nowrap; }
|
||||
.lg-form .input { flex: 1; min-height: 44px; min-width: 0; }
|
||||
.lg-actions .lg-form { padding: 0; border: 0; }
|
||||
.lg-why { padding: 8px 10px; border-top: 1px solid var(--border); font-size: .88rem; color: var(--text-sub); font-weight: 600; margin: 0; }
|
||||
.lg-big { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.lg-big .btn { flex: 1 1 auto; min-height: 52px; }
|
||||
.lg-prompt { margin: 0; font-weight: 800; font-size: 1.02rem; }
|
||||
.lg-choices { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 6px; }
|
||||
.lg-choice { min-height: 44px; border-radius: 10px; border: 2px solid var(--border); background: var(--surface-2); color: var(--text); font: inherit; font-weight: 700; cursor: pointer; }
|
||||
.lg-choice:hover { border-color: var(--primary); }
|
||||
.lg-final { border: 3px solid #16a34a; }
|
||||
.lg-final table { border-collapse: collapse; width: 100%; font-size: .9rem; }
|
||||
.lg-final td, .lg-final th { padding: 4px 6px; text-align: left; border-bottom: 1px solid var(--border); }
|
||||
.lg-final .word { font-size: 1.3rem; font-weight: 900; }
|
||||
.lg-log { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 3px; max-height: 320px; overflow: auto; }
|
||||
@keyframes lg-pop { from { transform: scale(.96); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||
@keyframes lg-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
|
||||
@media (max-width: 1099px) {
|
||||
.lg { height: auto; }
|
||||
.lg-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: 'actions players' 'talk talk'; }
|
||||
.lg-col { overflow: visible; }
|
||||
.lg-msgs { max-height: 380px; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.lg-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'actions' 'players' 'talk'; }
|
||||
.lg-banner { padding: 8px 10px; gap: 8px; }
|
||||
.lg-ph strong { font-size: 1.15rem; }
|
||||
.lg-clock { font-size: 2rem; }
|
||||
.lg-card { min-width: 120px; min-height: 48px; font-size: .9rem; }
|
||||
.lg-tiles { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.lg-tile { min-height: 70px; }
|
||||
.lg-msgs { min-height: 160px; max-height: 300px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lg-news, .lg-bar .tr i { animation: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- small parts
|
||||
|
||||
function Clock({ endsAt }: { endsAt: number | null }) {
|
||||
const now = useServerNow(500);
|
||||
if (endsAt === null) return null;
|
||||
const sec = Math.max(0, Math.ceil((endsAt - now) / 1000));
|
||||
const text = sec >= 60 ? `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}` : `${sec}`;
|
||||
return (
|
||||
<span className="lg-clock" data-warn={sec <= 5} role="timer" aria-label={`남은 시간 ${sec}초`}>
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function useHold(): [boolean, Record<string, unknown>] {
|
||||
const [show, setShow] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);
|
||||
return [
|
||||
show,
|
||||
{
|
||||
// Pointer capture: the release always comes back to the card, even if the layout moved under the finger.
|
||||
onPointerDown: (e: React.PointerEvent<HTMLElement>) => {
|
||||
e.currentTarget.setPointerCapture?.(e.pointerId);
|
||||
setShow(true);
|
||||
},
|
||||
onPointerUp: () => setShow(false),
|
||||
onLostPointerCapture: () => setShow(false),
|
||||
onPointerLeave: () => setShow(false),
|
||||
onPointerCancel: () => setShow(false),
|
||||
onContextMenu: (e: React.MouseEvent) => e.preventDefault(),
|
||||
onKeyDown: (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||
e.preventDefault();
|
||||
setShow(true);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => setShow(false), 2500);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** "내 제시어" — only visible while held (screen sharing / people next to you). */
|
||||
function WordCard({ v, always }: { v: LiarView; always: boolean }) {
|
||||
const [held, handlers] = useHold();
|
||||
const my = v.my!;
|
||||
const show = held || always;
|
||||
const liar = my.role === 'liar';
|
||||
const label = liar ? `나는 라이어예요. 주제는 ${v.topicKo}. 제시어는 몰라요` : `내 제시어: ${my.word}. 주제는 ${v.topicKo}`;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="lg-card"
|
||||
data-show={show}
|
||||
data-liar={liar}
|
||||
aria-label={show ? label : '내 제시어 보기. 누르고 있는 동안만 보여요'}
|
||||
{...handlers}
|
||||
>
|
||||
{show ? liar ? <span className="w">🤥 나는 라이어</span> : <span className="w">🔑 {my.word}</span> : '🂠 내 제시어 (꾹 누르기)'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function eventText(e: PublicEvent, players: Record<string, PublicUser>): string {
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
switch (e.t) {
|
||||
case 'phase':
|
||||
if (e.kind === 'describe') return `${e.round}바퀴째 설명이 시작됐어요`;
|
||||
if (e.kind === 'vote') return e.round === 2 ? '동점이라 동점인 사람끼리 다시 투표해요' : '라이어 지목 투표 시간이에요';
|
||||
return `${PHASE_KO[e.kind]} 시간이에요`;
|
||||
case 'vote':
|
||||
if (e.accused) return `${josa(n(e.accused), ['이', '가'])} ${e.tally[e.accused]}표로 지목됐어요`;
|
||||
return e.round === 1 ? `동점이에요 (${e.tied.map(n).join(', ')})` : '또 동점이라 아무도 지목되지 않았어요';
|
||||
case 'accused':
|
||||
return e.liar ? `${josa(n(e.p), ['은', '는'])} 라이어가 맞아요!` : `${josa(n(e.p), ['은', '는'])} 라이어가 아니었어요`;
|
||||
case 'guess':
|
||||
return e.text === null ? '라이어가 시간 안에 답하지 못했어요' : `라이어의 답: "${e.text}" — ${e.correct ? '정답!' : '틀렸어요'}`;
|
||||
case 'left':
|
||||
return `${josa(n(e.p), ['이', '가'])} 게임을 나갔어요`;
|
||||
case 'end':
|
||||
return e.winner === 'liar' ? '라이어 승리!' : '시민 승리!';
|
||||
}
|
||||
}
|
||||
|
||||
/** Announcements since the previous phase change (vote result, reveal, the liar's answer). */
|
||||
function latestNews(events: PublicEvent[]): PublicEvent[] {
|
||||
let i = events.length - 1;
|
||||
while (i >= 0 && events[i]!.t === 'phase') i--;
|
||||
const out: PublicEvent[] = [];
|
||||
for (; i >= 0 && events[i]!.t !== 'phase'; i--) if (events[i]!.t !== 'left') out.unshift(events[i]!);
|
||||
return out;
|
||||
}
|
||||
|
||||
function News({ v, players }: { v: LiarView; players: Record<string, PublicUser> }) {
|
||||
const news = latestNews(v.events);
|
||||
if (!news.length || v.final) return null;
|
||||
const title = news.some((e) => e.t === 'accused') ? '투표 결과' : news.some((e) => e.t === 'vote') ? '투표 결과' : '알림';
|
||||
return (
|
||||
<section className="lg-news" key={news[0]!.n} aria-label={title} role="status">
|
||||
<h2>📢 {title}</h2>
|
||||
{news.map((e) =>
|
||||
e.t === 'vote' ? (
|
||||
<VoteBars key={e.n} e={e} players={players} />
|
||||
) : (
|
||||
<span key={e.n} className="big">
|
||||
{eventText(e, players)}
|
||||
</span>
|
||||
),
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; players: Record<string, PublicUser> }) {
|
||||
const rows = Object.entries(e.tally).sort((a, b) => b[1] - a[1]);
|
||||
const max = Math.max(1, ...rows.map((r) => r[1]));
|
||||
return (
|
||||
<>
|
||||
<span className="big">{eventText(e, players)}</span>
|
||||
{rows.length > 0 && (
|
||||
<div className="lg-bars" role="list" aria-label="득표">
|
||||
{rows.map(([id, n]) => (
|
||||
<div key={id} className="lg-bar" data-top={id === e.accused} role="listitem" aria-label={`${nick(players, id)} ${n}표`}>
|
||||
<span className="nm">{nick(players, id)}</span>
|
||||
<span className="tr" aria-hidden>
|
||||
<i style={{ width: `${(n / max) * 100}%` }} />
|
||||
</span>
|
||||
<span>{n}표</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{Object.keys(e.votes).length > 0 && (
|
||||
<span className="small muted">
|
||||
{Object.entries(e.votes)
|
||||
.map(([from, to]) => `${nick(players, from)} → ${nick(players, to)}`)
|
||||
.join(' · ')}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- players
|
||||
|
||||
type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void } | null;
|
||||
|
||||
function Players({ v, players, me, pick, pending }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean }) {
|
||||
const ph = v.phase;
|
||||
const accused = v.final?.accused ?? ph.liar;
|
||||
return (
|
||||
<section className="lg-box" aria-label="사람들과 말하는 순서">
|
||||
<h2>
|
||||
사람들 <span className="small muted">말하는 순서대로</span>
|
||||
</h2>
|
||||
<div className="lg-tiles">
|
||||
{v.order.map((id, i) => {
|
||||
const p = v.players.find((x) => x.id === id)!;
|
||||
const u = userOf(players, id);
|
||||
const speaking = ph.speaker === id;
|
||||
const cls = `lg-tile${id === me ? ' me' : ''}${p.left ? ' left' : ''}${speaking ? ' speaking' : ''}${accused === id ? ' accused' : ''}`;
|
||||
const can = pick?.ids.includes(id) ?? false;
|
||||
const body = (
|
||||
<>
|
||||
<span className="no" aria-hidden>
|
||||
{i + 1}
|
||||
</span>
|
||||
<Avatar user={u} size={30} />
|
||||
<span className="nm">
|
||||
{u.nickname}
|
||||
{id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
{speaking && <span className="lg-tag say">말하는 중</span>}
|
||||
{ph.kind === 'vote' && p.voted && <span className="lg-tag ok">투표함</span>}
|
||||
{p.liar === true && <span className="lg-tag liar">🤥 라이어</span>}
|
||||
{p.left && <span className="lg-tag">나감</span>}
|
||||
</>
|
||||
);
|
||||
const label = [
|
||||
`${i + 1}번째, ${u.nickname}${id === me ? '(나)' : ''}`,
|
||||
speaking ? '지금 설명하는 사람' : '',
|
||||
ph.kind === 'vote' && p.voted ? '투표함' : '',
|
||||
p.liar === true ? '라이어' : '',
|
||||
p.left ? '나감' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
if (pick && can) {
|
||||
const chosen = pick.chosen === id;
|
||||
return (
|
||||
<button key={id} type="button" className={cls} data-target="ok" data-player={id} aria-pressed={chosen} disabled={pending} aria-label={`${label}. ${chosen ? '고른 사람' : '지목하기'}`} onClick={() => pick.onPick(id)}>
|
||||
{body}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div key={id} className={cls} data-target={pick ? 'no' : undefined} data-player={id} role="group" aria-label={label}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- descriptions + chat
|
||||
|
||||
function Descriptions({ v, players, me }: { v: LiarView; players: Record<string, PublicUser>; me: string | null }) {
|
||||
const rounds = Array.from({ length: v.rounds }, (_, i) => i + 1).filter((r) => r === 1 || v.descriptions.some((d) => d.round === r) || (v.phase.kind === 'describe' && v.phase.round >= r));
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [v.descriptions.length]);
|
||||
return (
|
||||
<section className="lg-box" aria-label="설명 기록">
|
||||
<h2>📝 설명 기록</h2>
|
||||
<div ref={listRef} style={{ maxHeight: 340, overflowY: 'auto' }} aria-live="polite">
|
||||
{v.descriptions.length === 0 && v.phase.kind !== 'describe' && <p className="muted small" style={{ margin: 0 }}>제시어를 확인하면 첫 번째 사람부터 한 문장씩 설명해요.</p>}
|
||||
{rounds.map((r) => (
|
||||
<div key={r}>
|
||||
{v.rounds > 1 && <div className="lg-round">{r}바퀴째{r === 2 ? ' (거꾸로)' : ''}</div>}
|
||||
<ol className="lg-desc">
|
||||
{v.descriptions
|
||||
.filter((d) => d.round === r)
|
||||
.map((d) => (
|
||||
<li key={d.n} className={`${d.from === me ? 'mine' : ''}${d.text === null ? ' skip' : ''}`}>
|
||||
<strong>{nick(players, d.from)}</strong>
|
||||
{d.text ?? '(시간이 지나 넘어갔어요)'}
|
||||
</li>
|
||||
))}
|
||||
{v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && (
|
||||
<li className="now">
|
||||
<strong>{nick(players, v.phase.speaker)}</strong>
|
||||
{v.phase.speaker === me ? '내 차례예요. 한 문장으로 설명해 주세요…' : '설명하는 중…'}
|
||||
</li>
|
||||
)}
|
||||
</ol>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type Line = ({ k: 'chat'; text: string; from: string; key: string } | { k: 'sys'; e: PublicEvent }) & { at: number };
|
||||
|
||||
function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
|
||||
const [text, setText] = useState('');
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const lines: Line[] = [
|
||||
...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })),
|
||||
...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })),
|
||||
// Stable sort: same moment keeps the event order, announcements before chat.
|
||||
].sort((a, b) => a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1));
|
||||
useEffect(() => {
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [v.chat.length, v.events.length]);
|
||||
const talk = v.phase.kind === 'discussion' || v.phase.kind === 'vote';
|
||||
const canWrite = !!v.my?.canChat && talk;
|
||||
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? '');
|
||||
return (
|
||||
<section className="lg-box lg-chat" aria-label="토론 채팅">
|
||||
<h2>💬 토론 채팅</h2>
|
||||
<div ref={listRef} className="lg-msgs" aria-live="polite">
|
||||
{lines.length === 0 && <p className="muted small" style={{ margin: 0 }}>아직 메시지가 없어요.</p>}
|
||||
{lines.map((l) =>
|
||||
l.k === 'sys' ? (
|
||||
<div key={`e${l.e.n}`} className="lg-msg sys">
|
||||
📢 {eventText(l.e, players)}
|
||||
</div>
|
||||
) : (
|
||||
<div key={l.key} className={`lg-msg${l.from === me ? ' mine' : ''}`}>
|
||||
<strong>{nick(players, l.from)}</strong>
|
||||
{l.text}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
{canWrite ? (
|
||||
<form
|
||||
className="lg-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const t = text.trim();
|
||||
if (!t) return;
|
||||
act({ type: 'chat', text: t.slice(0, 200) });
|
||||
setText('');
|
||||
}}
|
||||
>
|
||||
<input className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={200} placeholder="누가 라이어일까요?" aria-label="토론 채팅 메시지" enterKeyHint="send" />
|
||||
<button className="btn btn-primary btn-sm">보내기</button>
|
||||
</form>
|
||||
) : (
|
||||
why && <p className="lg-why">{why}</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
function DescribeForm({ act, pending }: { act: (a: unknown) => void; pending: boolean }) {
|
||||
const [text, setText] = useState('');
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => ref.current?.focus(), []);
|
||||
return (
|
||||
<form
|
||||
className="lg-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const t = text.trim();
|
||||
if (!t) return;
|
||||
act({ type: 'chat', text: t.slice(0, 80) });
|
||||
}}
|
||||
>
|
||||
<input ref={ref} className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={80} placeholder="예: 여름이면 생각나요" aria-label="내 설명 (한 문장)" enterKeyHint="send" />
|
||||
<button className="btn btn-primary btn-sm" disabled={pending}>
|
||||
말하기
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function GuessForm({ v, act, pending }: { v: LiarView; act: (a: unknown) => void; pending: boolean }) {
|
||||
const [text, setText] = useState('');
|
||||
if (v.options.guessMode === 'choice') {
|
||||
return (
|
||||
<div className="lg-choices" role="group" aria-label={`${v.topicKo} 단어 목록`}>
|
||||
{v.phase.choices.map((w) => (
|
||||
<button key={w} type="button" className="lg-choice" disabled={pending} onClick={() => act({ type: 'guess', text: w })}>
|
||||
{w}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form
|
||||
className="lg-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const t = text.trim();
|
||||
if (t) act({ type: 'guess', text: t.slice(0, 20) });
|
||||
}}
|
||||
>
|
||||
<input className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={20} placeholder="제시어" aria-label="제시어 맞히기" enterKeyHint="send" autoFocus />
|
||||
<button className="btn btn-primary btn-sm" disabled={pending}>
|
||||
정답!
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Actions({ v, players, me, act, pending }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; pending: boolean }) {
|
||||
const my = v.my;
|
||||
const ph = v.phase;
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
let body: ReactNode = null;
|
||||
if (!my) {
|
||||
body = <p className="lg-prompt">관전 중이에요. 주제는 {v.topicKo}이고, 제시어는 게임이 끝나면 공개돼요.</p>;
|
||||
} else if (ph.kind === 'ended') {
|
||||
body = <p className="lg-prompt">게임이 끝났어요. 라이어와 제시어가 공개됐어요.</p>;
|
||||
} else if (v.players.find((p) => p.id === me)?.left) {
|
||||
body = <p className="lg-prompt">게임에서 나갔어요.</p>;
|
||||
} else if (ph.kind === 'reveal') {
|
||||
body = (
|
||||
<>
|
||||
<p className="lg-prompt">{my.role === 'liar' ? `나는 라이어예요! 주제는 ${v.topicKo}이에요.` : '위의 "내 제시어" 카드를 꾹 눌러 제시어를 확인해 주세요.'}</p>
|
||||
<span className="small">{my.role === 'liar' ? '다른 사람 설명을 듣고 제시어를 아는 척해 보세요. 들키지 않거나, 걸려도 제시어를 맞히면 이겨요.' : '제시어를 직접 말하지 말고, 라이어가 눈치채지 못하게 애매하게 설명해요.'}</span>
|
||||
<div className="lg-big">
|
||||
<button type="button" className="btn btn-primary" disabled={pending || !my.canReady} onClick={() => act({ type: 'ready' })}>
|
||||
{my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `확인했어요 (${ph.readyCount}/${ph.readyNeeded})`}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'describe') {
|
||||
body = my.canDescribe ? (
|
||||
<>
|
||||
<p className="lg-prompt">내 차례예요! 한 문장으로 설명해 주세요</p>
|
||||
<span className="small">{my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'}</span>
|
||||
<DescribeForm key={`${ph.round}-${ph.turn}`} act={act} pending={pending} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="lg-prompt">{ph.speaker ? `${josa(n(ph.speaker), ['이', '가'])} 설명하는 중이에요` : '설명하는 중이에요'}</p>
|
||||
<span className="small muted">
|
||||
{v.rounds > 1 ? `${ph.round}/${v.rounds}바퀴 · ` : ''}
|
||||
{ph.turn + 1}번째 차례
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'discussion') {
|
||||
body = (
|
||||
<>
|
||||
<p className="lg-prompt">자유 토론이에요. 누가 라이어일까요?</p>
|
||||
<span className="small">설명이 어색했던 사람을 이야기해 봐요. 제시어는 직접 말할 수 없어요.</span>
|
||||
<div className="lg-big">
|
||||
<button type="button" className="btn btn-primary" disabled={pending || !my.canReady} onClick={() => act({ type: 'ready' })}>
|
||||
{my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `토론 끝내기 (${ph.readyCount}/${ph.readyNeeded})`}
|
||||
</button>
|
||||
</div>
|
||||
<span className="small muted">모두 누르면 바로 투표로 넘어가요.</span>
|
||||
</>
|
||||
);
|
||||
} else if (ph.kind === 'vote') {
|
||||
body =
|
||||
my.voteTargets.length > 0 ? (
|
||||
<>
|
||||
<p className="lg-prompt">{ph.voteRound === 2 ? '동점이라 다시 투표해요. 동점인 사람 중에서 골라 주세요' : '라이어로 의심되는 사람을 골라 주세요'}</p>
|
||||
<span className="small">초록 테두리 사람을 누르면 지목해요. 모두 투표하면 바로 결과가 나와요.</span>
|
||||
<strong>{my.vote ? `${josa(n(my.vote), ['을', '를'])} 지목했어요` : '아직 고르지 않았어요'}</strong>
|
||||
<span className="small muted">
|
||||
투표한 사람 {ph.votedCount}명 {ph.voteRound === 2 ? '· 또 동점이면 라이어가 이겨요' : '· 동점이면 동점인 사람끼리 한 번 더 투표해요'}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<p className="lg-prompt">다른 사람들이 투표하고 있어요.</p>
|
||||
);
|
||||
} else if (ph.kind === 'guess') {
|
||||
body = my.canGuess ? (
|
||||
<>
|
||||
<p className="lg-prompt">들켰어요! 제시어를 맞히면 그래도 이겨요</p>
|
||||
<span className="small">주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'}</span>
|
||||
<GuessForm v={v} act={act} pending={pending} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="lg-prompt">{ph.liar ? `${josa(n(ph.liar), ['이', '가'])} 라이어였어요!` : '라이어를 찾았어요!'}</p>
|
||||
<span className="small">라이어가 제시어를 맞히는 중이에요. 못 맞히면 시민이 이겨요.</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="lg-box" aria-label="할 일">
|
||||
<h2>{ph.kind === 'ended' ? '🏁 결과' : '🎯 할 일'}</h2>
|
||||
{body}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const REASON_KO: Record<LiarFinal['reason'], string> = {
|
||||
caught: '라이어를 찾았고, 라이어가 제시어를 못 맞혔어요',
|
||||
guessed: '라이어가 지목됐지만 제시어를 맞혔어요',
|
||||
escaped: '라이어가 아닌 사람이 지목됐어요',
|
||||
tie: '투표가 두 번 동점이었어요',
|
||||
liarLeft: '라이어가 게임을 나갔어요',
|
||||
citizensLeft: '시민이 모두 나갔어요',
|
||||
};
|
||||
|
||||
function FinalReveal({ v, players }: { v: LiarView; players: Record<string, PublicUser> }) {
|
||||
const f = v.final!;
|
||||
return (
|
||||
<section className="lg-box lg-final" aria-label="최종 공개">
|
||||
<h2>🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}</h2>
|
||||
<span>{REASON_KO[f.reason]}.</span>
|
||||
<span>
|
||||
제시어 <span className="word">{f.word}</span> · 주제 {TOPIC_KO[f.topic]}
|
||||
{f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''}
|
||||
{f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''}
|
||||
</span>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">이름</th>
|
||||
<th scope="col">역할</th>
|
||||
<th scope="col">점수</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{v.order.map((id) => {
|
||||
const won = (f.winner === 'liar') === (id === f.liar) && !v.players.find((p) => p.id === id)?.left;
|
||||
return (
|
||||
<tr key={id}>
|
||||
<th scope="row">
|
||||
{won ? '🏆 ' : ''}
|
||||
{nick(players, id)}
|
||||
</th>
|
||||
<td>{id === f.liar ? '🤥 라이어' : '🙂 시민'}</td>
|
||||
<td>{f.scores[id] ?? 0}점</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>) {
|
||||
const ph = v.phase;
|
||||
const my = v.my;
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const phaseKey = `${ph.kind}-${ph.round}-${ph.turn}-${ph.voteRound}`;
|
||||
const first = useRef(true);
|
||||
useEffect(() => {
|
||||
if (first.current) {
|
||||
first.current = false;
|
||||
return;
|
||||
}
|
||||
setAnnounce(ph.kind === 'describe' && ph.speaker ? `${phaseTitle(v)}: ${nick(players, ph.speaker)}님 차례` : phaseTitle(v));
|
||||
if (my && ((ph.kind === 'describe' && my.canDescribe) || (ph.kind === 'vote' && my.voteTargets.length > 0) || my.canGuess)) {
|
||||
haptic(40);
|
||||
sounds.myTurn();
|
||||
}
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const pick: Pick = my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null;
|
||||
const hot = ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe);
|
||||
const sub =
|
||||
ph.kind === 'describe' && ph.speaker
|
||||
? `${nick(players, ph.speaker)}님 차례 · 주제: ${v.topicKo}`
|
||||
: ph.kind === 'ended'
|
||||
? (v.final?.summary ?? '')
|
||||
: `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`;
|
||||
return (
|
||||
<div className="lg">
|
||||
<style>{CSS}</style>
|
||||
<section className="lg-banner" data-time={ph.kind === 'ended' ? 'end' : 'play'} data-hot={hot} aria-label="진행 상황">
|
||||
<span className="lg-ph">
|
||||
<span className="d">🤥 라이어 게임</span>
|
||||
<strong>{phaseTitle(v)}</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} />
|
||||
{my && <WordCard v={v} always={ph.kind === 'ended'} />}
|
||||
</section>
|
||||
<News v={v} players={players} />
|
||||
{v.final && <FinalReveal v={v} players={players} />}
|
||||
<div className="lg-grid">
|
||||
<div className="lg-col lg-players">
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} />
|
||||
</div>
|
||||
<div className="lg-col lg-talk">
|
||||
<Descriptions v={v} players={players} me={me} />
|
||||
<ChatBox v={v} players={players} me={me} act={act} />
|
||||
</div>
|
||||
<div className="lg-col lg-actions">
|
||||
<Actions v={v} players={players} me={me} act={act} pending={pending} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function LiarSide({ view: v, players }: BoardProps<LiarView>) {
|
||||
const log = v.events.filter((e) => e.t !== 'phase');
|
||||
return (
|
||||
<>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>라이어 게임 · {phaseTitle(v)}</strong>
|
||||
<span className="small">주제: {v.topicKo}</span>
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
</div>
|
||||
{log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>발표 기록</summary>
|
||||
<ol style={{ listStyle: 'none', margin: '6px 0 0', padding: 0, display: 'grid', gap: 3 }}>
|
||||
{[...log].reverse().map((e) => (
|
||||
<li key={e.n} className="small">
|
||||
{eventText(e, players)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요. 음성 채팅으로 제시어를 말하지 않기로 해요.
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status
|
||||
|
||||
function isMyTurn(v: LiarView, me: string | null): boolean {
|
||||
const my = v.my;
|
||||
if (!me || !my || v.final) return false;
|
||||
switch (v.phase.kind) {
|
||||
case 'describe':
|
||||
return my.canDescribe;
|
||||
case 'vote':
|
||||
return my.voteTargets.length > 0 && my.vote === null;
|
||||
case 'guess':
|
||||
return my.canGuess;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function statusText(v: LiarView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.final) return v.final.summary;
|
||||
const ph = v.phase;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return `제시어를 확인해 주세요 · 주제: ${v.topicKo}`;
|
||||
case 'describe':
|
||||
return isMyTurn(v, me) ? '내 차례예요 · 한 문장으로 설명해 주세요' : `${ph.speaker ? nick(players, ph.speaker) : '다른 사람'}님이 설명하는 중이에요`;
|
||||
case 'discussion':
|
||||
return '자유 토론 시간이에요 · 누가 라이어일까요?';
|
||||
case 'vote':
|
||||
return isMyTurn(v, me) ? '내 차례예요 · 라이어로 의심되는 사람을 골라 주세요' : ph.voteRound === 2 ? '동점자 재투표 중이에요' : '라이어 지목 투표 중이에요';
|
||||
case 'guess':
|
||||
return isMyTurn(v, me) ? '내 차례예요 · 제시어를 맞혀 보세요' : '라이어가 제시어를 맞히는 중이에요';
|
||||
case 'ended':
|
||||
return '게임이 끝났어요';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label} style={{ flexWrap: 'wrap' }}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{label}</strong>
|
||||
{children}
|
||||
{help && <span className="small muted">{help}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const onOff: [boolean, string][] = [
|
||||
[true, '켜기'],
|
||||
[false, '끄기'],
|
||||
];
|
||||
const secs = <T extends number>(...v: T[]): [T, string][] => v.map((x) => [x, `${x}초`]);
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
const [more, setMore] = useState(false);
|
||||
const set = (patch: Partial<LiarOptions>) => onChange({ ...o, ...patch });
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<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 })} />
|
||||
</Field>
|
||||
<Field label="바보 모드" help="켜면 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.">
|
||||
<Seg label="바보 모드" value={o.foolMode} options={onOff} onChange={(foolMode) => set({ foolMode })} />
|
||||
</Field>
|
||||
<Field label="설명 바퀴 수" help="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요.">
|
||||
<Seg
|
||||
label="설명 바퀴 수"
|
||||
value={o.rounds}
|
||||
options={[
|
||||
[1, '한 바퀴'],
|
||||
[2, '두 바퀴'],
|
||||
]}
|
||||
onChange={(rounds) => set({ rounds })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="라이어의 정답 맞히기">
|
||||
<Seg
|
||||
label="정답 맞히기 방식"
|
||||
value={o.guessMode}
|
||||
options={[
|
||||
['text', '직접 적기'],
|
||||
['choice', '목록에서 고르기'],
|
||||
]}
|
||||
onChange={(guessMode) => set({ guessMode })}
|
||||
/>
|
||||
</Field>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||
</button>
|
||||
{more && (
|
||||
<>
|
||||
<Field label="한 사람 설명 시간">
|
||||
<Seg label="설명 시간" value={o.describeSeconds} options={secs(15, 20, 30, 45, 60)} onChange={(describeSeconds) => set({ describeSeconds })} />
|
||||
</Field>
|
||||
<Field label="자유 토론 시간">
|
||||
<Seg label="토론 시간" value={o.discussionSeconds} options={secs(30, 60, 90, 120, 180)} onChange={(discussionSeconds) => set({ discussionSeconds })} />
|
||||
</Field>
|
||||
<Field label="투표 시간">
|
||||
<Seg label="투표 시간" value={o.voteSeconds} options={secs(15, 20, 30, 45)} onChange={(voteSeconds) => set({ voteSeconds })} />
|
||||
</Field>
|
||||
<Field label="정답 맞히기 시간">
|
||||
<Seg label="정답 맞히기 시간" value={o.guessSeconds} options={secs(20, 30, 45, 60)} onChange={(guessSeconds) => set({ guessSeconds })} />
|
||||
</Field>
|
||||
<Field label="고운 말 필터(욕설·링크·전화번호 막기)">
|
||||
<Seg label="고운 말 필터" value={o.kidSafeChat} options={onOff} onChange={(kidSafeChat) => set({ kidSafeChat })} />
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: LiarOptions): string {
|
||||
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`];
|
||||
if (o.foolMode) parts.push('바보 모드');
|
||||
parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', `설명 ${o.describeSeconds}초`, `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기');
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function Rules() {
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
3~10명이 같은 <strong>제시어</strong>를 받는데, 몰래 뽑힌 <strong>라이어</strong> 한 명만 주제만 알고 제시어는 몰라요. 시민은 라이어를 찾고, 라이어는 들키지 않거나 제시어를 맞히면 이겨요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>흐름</strong>: 제시어 확인 → 정해진 순서대로 한 사람씩 한 문장 설명(두 바퀴면 두 번째는 거꾸로) → 자유 토론 → 라이어 지목 투표 → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
|
||||
</p>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>
|
||||
<li>제시어를 직접 말하면 안 돼요(띄어쓰기를 무시하고 막아요). 설명 차례에 시간이 지나면 넘어가요.</li>
|
||||
<li>투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.</li>
|
||||
<li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li>
|
||||
<li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li>
|
||||
<li>바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.</li>
|
||||
</ul>
|
||||
<p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<LiarView, LiarOptions> = {
|
||||
Board: LiarBoard,
|
||||
Side: LiarSide,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
ownChat: true,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
41
apps/web/src/games/liar/quick.tsx
Normal file
41
apps/web/src/games/liar/quick.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 라이어 게임 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** Big emoji composition on a soft panel (no images). */
|
||||
function Scene({ bg, rows }: { bg: string; rows: { e: string; label?: string }[][] }) {
|
||||
return (
|
||||
<div aria-hidden style={{ width: 240, height: 150, borderRadius: 14, background: bg, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 6, padding: 8, boxSizing: 'border-box' }}>
|
||||
{rows.map((row, i) => (
|
||||
<div key={i} style={{ display: 'flex', justifyContent: 'center', gap: 12 }}>
|
||||
{row.map((c, j) => (
|
||||
<div key={j} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 44 }}>
|
||||
<span style={{ fontSize: 34, lineHeight: 1.1 }}>{c.e}</span>
|
||||
{c.label && <span style={{ fontSize: 13, fontWeight: 700, color: '#111827', background: 'rgba(255,255,255,.85)', borderRadius: 6, padding: '0 4px' }}>{c.label}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <Scene bg="linear-gradient(#ede9fe, #ddd6fe)" rows={[[{ e: '🍉', label: '수박' }, { e: '🍉', label: '수박' }, { e: '❓', label: '라이어' }]]} />,
|
||||
alt: '두 사람은 제시어 수박을 받고, 한 사람은 물음표만 받았어요',
|
||||
title: '한 명만 제시어를 몰라요',
|
||||
text: '모두 같은 제시어를 받지만 라이어 한 명은 주제만 알아요. 내 제시어는 카드를 꾹 눌러 확인해요.',
|
||||
},
|
||||
{
|
||||
pic: <Scene bg="linear-gradient(#fef3c7, #fde68a)" rows={[[{ e: '🙂', label: '여름' }, { e: '😃', label: '줄무늬' }, { e: '😅', label: '달아요' }]]} />,
|
||||
alt: '세 사람이 차례대로 여름, 줄무늬, 달아요라고 설명해요',
|
||||
title: '한 문장씩 설명',
|
||||
text: '순서대로 한 문장씩 설명해요. 제시어는 직접 말하면 안 되고, 라이어는 아는 척해요.',
|
||||
},
|
||||
{
|
||||
pic: <Scene bg="linear-gradient(#fee2e2, #dcfce7)" rows={[[{ e: '👉' }, { e: '🤥', label: '라이어' }, { e: '✍️', label: '정답?' }]]} />,
|
||||
alt: '모두가 라이어를 가리키고, 라이어가 정답을 적어요',
|
||||
title: '투표로 라이어 찾기',
|
||||
text: '토론 뒤 투표로 한 명을 지목해요. 라이어가 지목돼도 제시어를 맞히면 라이어가 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -33,6 +33,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
apple: () => import('./apple'),
|
||||
clue: () => import('./clue'),
|
||||
uno: () => import('./uno'),
|
||||
liar: () => import('./liar'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
@@ -30,6 +30,7 @@ export const GAME_ICON: Record<string, string> = {
|
||||
clue: '🔎',
|
||||
'connect-four': '🔴',
|
||||
uno: '🌈',
|
||||
liar: '🤥',
|
||||
};
|
||||
|
||||
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
|
||||
@@ -39,5 +40,5 @@ export const UPCOMING: string[] = [];
|
||||
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'clue'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'apple'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] },
|
||||
];
|
||||
|
||||
@@ -135,7 +135,7 @@ export interface GameUI<V> {
|
||||
## 9. 컴퓨터 상대 (`packages/games/src/bots/`, 06 §12)
|
||||
- 게임마다 `<게임>/bot.ts`의 전략 하나: `(입력: { me, view, legal, random }) => 행동`. `view`는 `view(state, me)`, `legal`은 `legalActions(state, me)`. 게임 상태는 넘기지 않는다(비공개 정보 차단).
|
||||
- `decideBotAction`이 고른 수를 `validate`로 다시 검사하고, 틀리면 다른 합법 수로 바꾼다. 서버는 그래도 실패하면 게임의 `onTimeout` 행동을 쓴다.
|
||||
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아·사과 게임): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임(사과 게임은 각자 자기 판을 푸는 경주). 전략은 `({ me, view, now, persona, level, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편(§9.1)과 빠르기, `level`은 지금 레벨(1~60), `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아·라이어 게임·사과 게임): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임(사과 게임은 각자 자기 판을 푸는 경주). 전략은 `({ me, view, now, persona, level, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편(§9.1)과 빠르기, `level`은 지금 레벨(1~60), `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||
- 테스트(`bots/bots.test.ts`): 게임마다 "사람 1명은 시간 초과만, 나머지는 컴퓨터"와 "컴퓨터끼리" 판을 끝까지 돌려, 모든 수가 합법이고 컴퓨터 때문에 멈추지 않으며 한 수가 충분히 빠른지 본다.
|
||||
|
||||
### 9.1 컴퓨터 난이도와 난수 (2026-10-11)
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
| `connect-four` | 커넥트 포(사목) | 2 | M9 |
|
||||
| `old-maid` | 도둑잡기 | 2~8 | M9 |
|
||||
| `uno` | 우노 | 2~10 | M9 |
|
||||
| `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
156
docs/games/liar.md
Normal file
156
docs/games/liar.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# 라이어 게임 (`liar`)
|
||||
|
||||
> 마일스톤: 2026-10 새 게임 · 인원: 최소 3 ~ 최대 10명 · 예상 시간: 약 5~15분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 모두 같은 제시어를 받았는데 몰래 뽑힌 **라이어** 한 명만 주제만 알고 제시어를 모른다. 돌아가며 한 문장씩 제시어를 설명하는 사이 라이어를 찾아내는 말놀이 파티 게임. 준비물 없이 말로만 하는 국내 놀이로 널리 알려져 있고, 해외 상품 '카멜레온(The Chameleon, 2017)', '스파이폴(Spyfall, 2014)'과 같은 계열이다. 만든 사람과 어느 방송에서 널리 알려졌는지는 확인하지 못했다.
|
||||
- 원작 상품이 따로 없어 사이트·방송마다 규칙이 조금씩 다르다. 이 문서의 규칙이 우리 사이트 규칙이고, 화면의 [규칙]과 [?] 도움말에도 같은 내용을 적었다.
|
||||
- 인원 근거: 3명 미만이면 투표가 성립하지 않고(1대1), 10명을 넘으면 설명 두 바퀴가 너무 길어진다.
|
||||
- 마피아처럼 게임 자체 채팅(`ownChat`)과 서버가 돌리는 단계·타이머를 쓴다(진행자 불필요).
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `topic` | 주제 | `random` / 과일·동물·직업·음식·장소·운동·탈것·물건·나라·동화 주인공 | `random` |
|
||||
| `foolMode` | 바보 모드: 라이어도 같은 주제의 다른 단어를 받고 자기가 라이어인지 모른다 | on / off | off |
|
||||
| `rounds` | 설명 바퀴 수(두 번째 바퀴는 거꾸로) | 1 / 2 | 2 |
|
||||
| `describeSeconds` | 한 사람 설명 시간 | 15 / 20 / 30 / 45 / 60 | 30 |
|
||||
| `discussionSeconds` | 자유 토론 시간 | 30 / 60 / 90 / 120 / 180 | 90 |
|
||||
| `voteSeconds` | 투표 시간(재투표도 같은 시간) | 15 / 20 / 30 / 45 | 30 |
|
||||
| `guessMode` | 라이어의 정답 맞히기 | `text`(직접 적기) / `choice`(주제 단어 목록에서 고르기) | `text` |
|
||||
| `guessSeconds` | 정답 맞히기 시간 | 20 / 30 / 45 / 60 | 30 |
|
||||
| `kidSafeChat` | 고운 말 필터(욕설·링크·전화번호 막기, 마피아와 같은 필터) | on / off | on |
|
||||
|
||||
## 3. 구성물
|
||||
- 제시어 은행 `packages/games/src/liar/words.ts`: 주제 10개 × 단어 16~17개(모두 두 글자 이상).
|
||||
- 단어마다 컴퓨터가 쓸 설명 문장 5개(`hints`, 앞쪽일수록 덜 구체적)와 정답으로 쳐 줄 다른 표기(`aliases`, 예: 휴대폰 ↔ 핸드폰·스마트폰, 텔레비전 ↔ 티비·TV).
|
||||
- 주제마다 어느 단어에나 맞는 무난한 말(`generic`) 5개: 아직 아무 설명도 못 들은 라이어 컴퓨터가 쓴다.
|
||||
- 테스트가 확인: 설명 문장에 그 단어(다른 표기 포함, 띄어쓰기 무시)가 없음, 무난한 말에 주제의 어떤 단어도 없음, 모두 고운 말 필터 통과, 80자 이하.
|
||||
- 한 글자 단어(배, 귤, 컵 …)는 넣지 않았다: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막는다.
|
||||
|
||||
## 4. 준비(셋업)
|
||||
1. 주제(무작위면 10개 중 하나), 그 주제의 제시어 하나, 라이어 한 명을 서버 시드 난수로 뽑는다.
|
||||
2. 바보 모드면 라이어에게 같은 주제의 다른 단어 하나를 준다.
|
||||
3. 첫 발언자를 무작위로 정하고, 그 사람부터 자리 순서대로 돈다. 라이어도 첫 발언자가 될 수 있다(라이어를 빼면 "첫 사람은 시민"이라는 정보가 생기므로).
|
||||
|
||||
## 5. 진행 규칙
|
||||
### 5.1 단계
|
||||
제시어 확인(10초) → 설명(바퀴 수만큼) → 자유 토론 → 투표(필요하면 재투표) → 정답 맞히기(라이어가 지목됐을 때만) → 결과.
|
||||
|
||||
### 5.2 제시어 확인과 설명
|
||||
- 확인 시간: 시민 화면에는 "제시어 + 주제", 라이어 화면에는 "나는 라이어 + 주제"만. 모두 [확인했어요]를 누르면 바로 넘어간다.
|
||||
- 설명: 순서대로 한 사람씩, 자기 차례에만 한 문장(80자까지)을 쓴다. 보내면 바로 다음 사람 차례. 시간이 지나면 "넘김"으로 기록하고 다음 사람.
|
||||
- 두 바퀴면 두 번째 바퀴는 거꾸로 돈다(처음에 아무것도 모르고 말한 사람이 마지막에 말한다). 첫 바퀴 마지막 사람은 두 번 이어서 말한다.
|
||||
- **제시어를 직접 말하면 안 된다**: 자기 단어(다른 표기 포함)가 띄어쓰기·대소문자·문장 부호를 무시하고 들어 있으면 서버가 거절한다("제시어를 직접 말하면 안 돼요."). 설명과 토론 채팅 모두.
|
||||
- 라이어(보통 모드)는 막지 않는다. 막으면 "이 말은 거절됐다 = 정답"이 새기 때문. 바보 모드 라이어는 자기 단어가 막힌다(시민과 똑같이 보이려고).
|
||||
- 설명 중에는 설명할 차례인 사람만 쓸 수 있다(다른 사람 채팅은 닫힘). 확인 시간·정답 맞히기 중에도 채팅은 닫힌다(라이어에게 힌트를 주지 못하게).
|
||||
|
||||
### 5.3 자유 토론
|
||||
- 모두 [토론 채팅]에 자유롭게 쓴다(200자, 0.7초 간격). 모두 [토론 끝내기]를 누르면 바로 투표(마피아와 같은 "모두 동의" 방식, 방장 혼자서는 못 끝냄).
|
||||
|
||||
### 5.4 투표
|
||||
- 나를 뺀 한 명을 고른다. 시간 안에는 바꿀 수 있고, 모두 투표하면 바로 집계한다. 투표하지 않으면 그 사람 표는 없다.
|
||||
- 투표 중에도 토론 채팅을 쓸 수 있다. 누가 투표했는지는 보이고, 누구를 골랐는지는 집계 때 공개.
|
||||
- 가장 많이 받은 한 명이 지목된다.
|
||||
- **동점**: 동점인 사람끼리 **재투표 한 번**(후보는 동점자만, 동점자 본인은 자기 말고 다른 동점자에게). 또 동점이면 **라이어 승리**. 아무도 투표하지 않으면 모두가 동점으로 본다(재투표 후보 = 모두).
|
||||
- 근거: 국내 진행에서 가장 흔한 "동점이면 다시 투표"를 한 번만 하고, 끝까지 못 고르면 라이어를 못 찾은 것으로 본다(카멜레온·스파이폴도 지목에 실패하면 숨은 쪽이 이긴다).
|
||||
|
||||
### 5.5 정답 맞히기
|
||||
- 지목된 사람이 라이어가 아니면 바로 라이어 승리.
|
||||
- 라이어면 모두에게 라이어가 공개되고, 라이어가 제시어를 **한 번** 맞힌다.
|
||||
- `text`: 직접 적는다(20자). 띄어쓰기·대소문자·문장 부호를 무시하고, 다른 표기(aliases)도 정답, 끝에 "요/다/이다/입니다"가 붙어도 정답(그림 맞히기와 같은 비교 함수 `judge`).
|
||||
- `choice`: 그 주제 단어 목록(가나다순)에서 하나를 고른다. 목록에 없는 말은 거절.
|
||||
- 시간이 지나면 틀린 것으로 본다.
|
||||
- 바보 모드: 지목되어 공개된 뒤에야 라이어가 자기가 라이어인 걸 안다. 자기가 받은 단어는 정답이 아니다.
|
||||
|
||||
## 6. 승패와 점수 계산
|
||||
| 결과 | 승리 | 점수 |
|
||||
|---|---|---|
|
||||
| 라이어가 아닌 사람이 지목됨 | 라이어 | 라이어 2점 |
|
||||
| 재투표도 동점 | 라이어 | 라이어 2점 |
|
||||
| 라이어가 지목됐지만 제시어를 맞힘 | 라이어 | 라이어 2점 |
|
||||
| 라이어가 지목되고 제시어도 못 맞힘 | 시민 | 시민마다 1점 |
|
||||
| 라이어가 게임을 나감 | 시민 | 시민마다 1점 |
|
||||
| 시민이 모두 나감 | 라이어 | 라이어 2점 |
|
||||
|
||||
- 결과 화면 순위: 이긴 쪽 / 진 쪽 두 묶음. 점수 글(scoreText)은 "라이어 · 2점", "시민 · 1점" 처럼 역할과 함께. 나간 사람은 0점이고 진 쪽에 넣는다.
|
||||
- 여러 판 연속은 방의 [한 판 더]로 한다(새 주제·제시어·라이어).
|
||||
|
||||
## 7. 지역 룰 / 하우스 룰
|
||||
- 바보 모드(옵션). 설명 바퀴 수, 각 시간, 정답 맞히기 방식(옵션).
|
||||
- 일부러 뺀 것: 라이어 2명, 최후 변론 단계(토론에서 충분히 말할 수 있어서), 방장 혼자 토론 끝내기, 사용자 단어 목록, 음성 설명.
|
||||
|
||||
## 8. 엔진 설계
|
||||
### 8.1 상태(State)
|
||||
```ts
|
||||
interface LiarState {
|
||||
options; players: { id; left }[]; topic; word; liar; liarWord /* 바보 모드 */; order /* 1바퀴 순서 */;
|
||||
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 }[]; lastChatAt;
|
||||
events: PublicEvent[]; accused; guess; seq; final: LiarFinal | null;
|
||||
}
|
||||
```
|
||||
### 8.2 액션
|
||||
| type | payload | 누가 / 언제 | 검증 조건 |
|
||||
|---|---|---|---|
|
||||
| `chat` | `text` | 설명 차례인 사람(설명) / 모두(토론·투표) | 채팅 열린 단계, 80자(설명)·200자, 고운 말, 자기 단어 금지, 0.7초 간격 |
|
||||
| `ready` | — | 확인 시간·토론 | 아직 안 누름 |
|
||||
| `vote` | `target` | 투표 | 나 말고, 후보(재투표는 동점자) 중 |
|
||||
| `guess` | `text` | 정답 맞히기의 라이어 | 1~20자, `choice`면 주제 단어 |
|
||||
| `phaseTimeout` | — | 서버(시계) | `endsAt` 이후 |
|
||||
| `leave` | — | 서버(나감) | 아직 안 나감 |
|
||||
|
||||
### 8.3 공개/비공개 정보 (view)
|
||||
- `my.word`: 시민은 제시어, 라이어는 null, 바보 모드 라이어는 자기 단어. `my.role`: 라이어(보통 모드, 또는 공개 뒤) / 시민. 바보 모드 라이어의 화면은 단어만 다르고 시민 화면과 모양이 똑같다(테스트).
|
||||
- `players[].liar`: 정답 맞히기 단계(라이어 지목) 또는 끝나기 전까지 모두 null. 시민 화면은 누가 라이어든 한 글자도 다르지 않다(테스트: 라이어만 바꾼 두 판의 시민·관전 화면이 같음).
|
||||
- 관전자는 주제만 보고 제시어는 끝나야 본다. `final`(라이어·제시어·바보 모드 단어·라이어의 답·점수)은 끝난 뒤에만.
|
||||
- 정답 고르기 목록(`phase.choices`)은 정답 맞히기 단계에만 들어간다.
|
||||
- `secretsOf`: 바보 모드 라이어의 단어(공개 전까지 라이어만). 보통 모드 제시어는 시민 모두가 보므로 따로 테스트로 확인(라이어·관전 화면에 없음).
|
||||
|
||||
### 8.4 랜덤 요소 (시드 RNG 사용 지점)
|
||||
주제(무작위일 때), 제시어, 라이어, 바보 모드 단어, 첫 발언자. 모두 `ctx.rng`.
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||
- 모든 단계에 `endsAt`. 마피아처럼 첫 자리 사람이 시계를 대표하고(`timeoutPlayers`), `timeoutNotBefore`로 자리 비운 사람이 단계를 일찍 끝내지 못한다.
|
||||
- 시간 초과: 확인 → 첫 설명, 설명 → 넘김, 토론 → 투표, 투표 → 집계, 정답 맞히기 → 틀림.
|
||||
- 나가기(`onLeave`): 그 사람은 이후 차례·투표·"모두 동의"에서 빠진다. 설명 차례였으면 다음 사람. 투표 중이면 그 사람 표와 그 사람이 받은 표를 지우고, 남은 사람이 다 투표했으면 바로 집계. 라이어가 나가면 시민 승리, 시민이 모두 나가면 라이어 승리.
|
||||
|
||||
### 8.6 종료 조건과 결과(GameResult)
|
||||
6절 표. `reason: 'normal'`, `summary` 예: "라이어 승리! 라이어가 아닌 사람이 지목됐어요. 제시어는 '수박'이었어요."
|
||||
|
||||
## 9. UI/UX
|
||||
- 위: 단계 배너(단계 이름, 주제, 지금 말하는 사람, 큰 남은 시간) + **"내 제시어" 카드**(꾹 누르는 동안만 보임, 키보드 Enter로 2.5초). 라이어는 "🤥 나는 라이어".
|
||||
- 발표 상자: 투표 막대그래프와 누가 누구를 골랐는지, 지목된 사람이 라이어인지, 라이어의 답.
|
||||
- PC 세 칸: 사람들(말하는 순서 번호, 말하는 중·투표함·라이어·나감 표시, 투표 때 초록 테두리로 고르기) / 설명 기록(바퀴별) + 토론 채팅 / 할 일(확인·설명 입력·토론 끝내기·투표 안내·정답 입력 또는 단어 목록). 좁은 화면은 할 일 → 사람들 → 설명·채팅 순으로 쌓인다(320px까지).
|
||||
- 게임 중 방 채팅·빠른 반응은 닫힌다(`ownChat`). 끝나면 최종 공개 표(역할·점수).
|
||||
- 30초 요약 카드 3장, [?] 도움말은 보는 사람에 맞게(라이어/시민/관전, 바보 모드 라이어는 시민과 똑같은 글).
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 제시어 은행: 주제 10개, 단어 15개 이상, 설명 4개 이상, 설명에 단어 없음, 고운 말 필터 (`liar.test.ts`)
|
||||
- [x] 정답 비교(띄어쓰기·대소문자·다른 표기)
|
||||
- [x] 라이어·관전 화면에 제시어 없음, 시민 화면은 라이어가 누구든 같음, 바보 모드 화면 모양 같음
|
||||
- [x] 설명 순서(두 번째 바퀴 거꾸로), 넘김, 80자, 제시어 금지(라이어는 안 막음)
|
||||
- [x] 토론 모두 동의, 투표 즉시 집계, 동점 → 재투표 → 또 동점 라이어 승리, 아무도 안 찍음
|
||||
- [x] 정답 맞히기(맞힘·틀림·시간 초과·고르기), 나가기(설명 차례·투표 중·라이어·시민 전원)
|
||||
- [x] 엔진 무작위 대국(3~10명, 4가지 옵션, 유출·JSON·결정성), 결과 점수 글
|
||||
- [x] 컴퓨터: 3~10명 끝까지, 거절 0, 제시어 안 말함, 높은 레벨이 더 잘함 (`bot.test.ts`)
|
||||
- [x] 실제 방: 사람 1 + 컴퓨터 4로 끝까지(사람이 설명·토론·투표 / 사람이 가만히) (`apps/server/src/rooms/liar.room.test.ts`)
|
||||
- [x] E2E: PC 1 + 휴대폰 2, 실제 화면 조작으로 끝까지 (`e2e/games.e2e.ts liar`)
|
||||
|
||||
## 11. 참고 자료
|
||||
- 규칙 메모: 새 게임 설명 문서 39절(라이어 게임).
|
||||
- 비슷한 게임: The Chameleon(Big Potato, 2017), Spyfall(Hobby World, 2014) — 지목 실패 시 숨은 쪽 승리, 숨은 쪽이 들켜도 정답을 맞히면 승리.
|
||||
|
||||
## 12. 메모 (상표·법적 주의 등)
|
||||
- 국내 놀이 이름이라 상표 걱정은 적다. 동화 주인공 주제는 저작권이 끝난 옛이야기(전래 동화·고전 동화) 인물만 넣었다.
|
||||
|
||||
## 13. 컴퓨터 플레이어 (2026-10-12)
|
||||
- 마피아처럼 live 전략(`LIVE_BOT_STRATEGIES.liar`, `packages/games/src/liar/bot.ts`): 각 컴퓨터가 자기 시계로 자기 화면만 보고 한 번에 한 가지를 한다. 연습 방은 5명(사람 1 + 컴퓨터 4).
|
||||
- 이 게임은 컴퓨터가 말해야 진행되므로 `BOT_CHAT_REQUIRED`에 넣었다(방의 "컴퓨터 채팅" 설정과 상관없이 항상 켜짐).
|
||||
- **로컬 모델(LLM)로 문장을 바꾸지 않는다**(`hint` 없음): 정해 둔 문장만 쓴다. 모델이 제시어를 흘리거나, 라이어 컴퓨터가 모를 말을 할 위험이 있어서. 서버는 모델이 켜져 있으면 "입력 중…"을 글자 수만큼 보여 준 뒤 그대로 보낸다(`typeLive`, hint 없으면 문장을 바꾸지 않음).
|
||||
- 시민 컴퓨터: 자기 단어의 설명 문장 중 아직 아무도 안 쓴 것(똑똑한 편은 덜 구체적인 앞쪽부터). 다 쓰였으면 다른 사람 설명에 한 표("OO님 설명에 한 표예요") 또는 주제의 무난한 말.
|
||||
- 라이어 컴퓨터: 지금까지 나온 설명을 주제의 단어마다 설명 은행과 글자쌍(두 글자씩)으로 맞춰 보고(드문 글자쌍일수록 무게), 가장 맞는 단어를 추정해 그 단어의 설명 문장으로 말한다. 아무 설명도 못 들었으면 무난한 말. 지목되면 같은 추정으로 정답을 적거나 고른다.
|
||||
- 투표: 설명이 (자기 단어 또는 라이어의 추정 단어와) 덜 맞는 사람, 넘긴 사람을 의심. 라이어 컴퓨터는 자기를 지목하지 않고, 채팅에서 많이 의심받는 사람 쪽으로 기운다.
|
||||
- 토론: 정해 둔 문장으로 의심 지목, 동의·반박, 지목당하면 반박, 이름이 불리면 대답. 토론 후반에 [토론 끝내기].
|
||||
- 레벨(1~60): 라이어가 알아듣는 설명의 비율(30%~95%)과 추정·의심의 잡음 크기, 라이어가 추정 단어로 설명할 용기(35%~95%). 레벨이 높을수록 시민은 라이어를 더 잘 찾고 라이어는 더 잘 맞힌다(테스트: 레벨 60 시민 대 레벨 1 라이어 → 시민 승률이 반대 경우보다 20%p 넘게 높음).
|
||||
- 컴퓨터가 쓰는 레벨은 서버가 `LiveBotInput.level`로 넘긴다(방의 컴퓨터 레벨, 없으면 id로 정한 레벨).
|
||||
129
e2e/games.e2e.ts
129
e2e/games.e2e.ts
@@ -1042,6 +1042,39 @@ async function clueStep(p: Page, st: Record<string, number>, accuseAfter: number
|
||||
return 'end';
|
||||
}
|
||||
return null;
|
||||
|
||||
/** 라이어 게임: nicknames of the E2E pages (host first). */
|
||||
const LIAR_NICKS = ['방장', '친구', '친구2'];
|
||||
|
||||
/** 라이어 게임: shows the hold-to-see word card (keyboard Enter) and reads it: the word, or null for the liar. */
|
||||
async function liarWordOf(p: Page): Promise<string | null> {
|
||||
const card = p.locator('.lg-card');
|
||||
if (!(await card.getAttribute('aria-label'))!.startsWith('내 제시어 보기')) throw new Error('word card shows the word before it is held');
|
||||
await card.focus();
|
||||
await p.keyboard.press('Enter');
|
||||
const label = (await card.getAttribute('aria-label'))!;
|
||||
if (label.startsWith('나는 라이어')) return null;
|
||||
const m = /^내 제시어: (.+)\. 주제는/.exec(label);
|
||||
if (!m) throw new Error(`unexpected word card: ${label}`);
|
||||
return m[1]!;
|
||||
}
|
||||
|
||||
async function liarBanner(p: Page, phase: string | RegExp, timeout = 40_000) {
|
||||
await p.locator('.lg-banner .lg-ph strong', { hasText: phase }).waitFor({ timeout });
|
||||
}
|
||||
|
||||
async function liarShots(pages: Page[], name: string, dark = false) {
|
||||
const [host, phone] = pages as [Page, Page];
|
||||
await host.screenshot({ path: join(SHOTS, `liar-${name}-pc.png`) });
|
||||
await phone.screenshot({ path: join(SHOTS, `liar-${name}-phone.png`), fullPage: true });
|
||||
if (!dark) return;
|
||||
await host.emulateMedia({ colorScheme: 'dark' });
|
||||
await phone.emulateMedia({ colorScheme: 'dark' });
|
||||
await host.waitForTimeout(250);
|
||||
await host.screenshot({ path: join(SHOTS, `liar-${name}-pc-dark.png`) });
|
||||
await phone.screenshot({ path: join(SHOTS, `liar-${name}-phone-dark.png`), fullPage: true });
|
||||
await host.emulateMedia({ colorScheme: 'light' });
|
||||
await phone.emulateMedia({ colorScheme: 'light' });
|
||||
}
|
||||
|
||||
const PLANS: Record<string, Plan> = {
|
||||
@@ -2362,6 +2395,102 @@ const PLANS: Record<string, Plan> = {
|
||||
console.log(` catchmind: drew and guessed ${words.join(', ')}; both 12 points (10 + 2)`);
|
||||
},
|
||||
},
|
||||
liar: {
|
||||
// PC host + 2 phone guests, one round of descriptions. Real flow through the UI: hold-to-see word card (the liar
|
||||
// sees only "나는 라이어"), confirm, each describes in turn (a citizen saying the word is refused), discussion chat,
|
||||
// "토론 끝내기", the citizens vote the liar out, the liar names the word with spaces in it and wins.
|
||||
// Checks: the liar's screen never shows the word, the room chat is closed during the game.
|
||||
players: 3,
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '설명 바퀴 수' }).getByRole('button', { name: '한 바퀴' }).click();
|
||||
await host.getByText(/한 바퀴 · 설명 30초/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, phone] = pages as [Page, Page, Page];
|
||||
for (const p of pages) await liarBanner(p, '제시어 확인');
|
||||
if (await host.locator('.chat-panel').count()) throw new Error('room chat panel is visible during the game');
|
||||
if (await phone.getByRole('button', { name: /^채팅/ }).count()) throw new Error('room chat button is visible on the phone during the game');
|
||||
const words = await Promise.all(pages.map(liarWordOf));
|
||||
const L = words.indexOf(null);
|
||||
const word = words.find((w) => w !== null)!;
|
||||
if (L < 0 || words.filter((w) => w === null).length !== 1 || words.some((w) => w !== null && w !== word)) throw new Error(`unexpected words ${words.join(',')}`);
|
||||
console.log(` liar: word ${word}, liar ${LIAR_NICKS[L]}`);
|
||||
const liarClean = async (when: string) => {
|
||||
if ((await pages[L]!.content()).includes(word)) throw new Error(`the liar's screen shows the word (${when})`);
|
||||
};
|
||||
await liarClean('reveal');
|
||||
await liarShots(pages, '1-reveal');
|
||||
// The card hides again by itself (2.5 s after the key press).
|
||||
await host.waitForFunction(() => document.querySelector('.lg-card')?.getAttribute('aria-label')?.startsWith('내 제시어 보기'), null, { timeout: 5000 });
|
||||
for (const p of pages) await p.getByRole('button', { name: /^확인했어요/ }).click();
|
||||
|
||||
for (const p of pages) await liarBanner(p, '한 사람씩 설명');
|
||||
let refused = -1;
|
||||
for (let turn = 0; turn < 3; turn++) {
|
||||
let speaker = -1;
|
||||
for (let t = 0; t < 100 && speaker < 0; t++) {
|
||||
for (const [i, p] of pages.entries()) if (await p.getByLabel('내 설명 (한 문장)').count()) speaker = i;
|
||||
if (speaker < 0) await host.waitForTimeout(100);
|
||||
}
|
||||
if (speaker < 0) throw new Error(`nobody can describe (turn ${turn + 1})`);
|
||||
const p = pages[speaker]!;
|
||||
const input = p.getByLabel('내 설명 (한 문장)');
|
||||
if (refused < 0 && speaker !== L) {
|
||||
await input.fill(`${[...word].join(' ')} 맞죠`);
|
||||
await input.press('Enter');
|
||||
await p.getByText('제시어를 직접 말하면 안 돼요.').first().waitFor({ timeout: 10_000 });
|
||||
refused = speaker;
|
||||
}
|
||||
const text = speaker === L ? '저는 좋아하는 편이에요' : `${LIAR_NICKS[speaker]}의 설명이에요`;
|
||||
if (turn === 1) await liarShots(pages, '2-describe', true);
|
||||
await input.fill(text);
|
||||
await input.press('Enter');
|
||||
for (const q of pages) await q.locator('.lg-desc li', { hasText: text }).waitFor({ timeout: 15_000 });
|
||||
}
|
||||
if (refused < 0) throw new Error('saying the word was never tried');
|
||||
// The refusal toast goes away by itself (3 s).
|
||||
await pages[refused]!.locator('.toast', { hasText: '제시어를 직접 말하면 안 돼요.' }).waitFor({ state: 'detached', timeout: 6000 });
|
||||
await liarClean('describe');
|
||||
for (const [i, p] of pages.entries()) {
|
||||
const hidden = await p
|
||||
.waitForFunction(() => document.querySelector('.lg-card')?.getAttribute('aria-label')?.startsWith('내 제시어 보기'), null, { timeout: 4000 })
|
||||
.then(() => true, () => false);
|
||||
if (!hidden) throw new Error(`${LIAR_NICKS[i]}: word card stays open after the descriptions`);
|
||||
}
|
||||
|
||||
for (const p of pages) await liarBanner(p, '자유 토론');
|
||||
const citizen = (L + 1) % 3;
|
||||
await pages[citizen]!.getByLabel('토론 채팅 메시지').fill(`${LIAR_NICKS[L]}님이 수상해요`);
|
||||
await pages[citizen]!.getByLabel('토론 채팅 메시지').press('Enter');
|
||||
for (const p of pages) await p.locator('.lg-msgs .lg-msg', { hasText: '님이 수상해요' }).waitFor({ timeout: 15_000 });
|
||||
await liarShots(pages, '3-discussion', true);
|
||||
await liarClean('discussion');
|
||||
for (const p of pages) await p.getByRole('button', { name: /^토론 끝내기/ }).click();
|
||||
|
||||
for (const p of pages) await liarBanner(p, '라이어 지목 투표', 15_000);
|
||||
const pickTile = async (p: Page, nick: string) => {
|
||||
const name = p.locator('.nm', { hasText: new RegExp(`^${nick}( \\(나\\))?$`) });
|
||||
await p.locator('button.lg-tile[data-target="ok"]', { has: name }).click();
|
||||
};
|
||||
await liarShots(pages, '4-vote');
|
||||
for (const [i, p] of pages.entries()) await pickTile(p, LIAR_NICKS[i === L ? (L + 1) % 3 : L]!);
|
||||
|
||||
await liarBanner(pages[L]!, '라이어의 정답 맞히기', 15_000);
|
||||
for (const p of pages) await p.locator('.lg-news', { hasText: '라이어가 맞아요!' }).waitFor();
|
||||
await pages[citizen]!.locator('.lg-tag.liar').first().waitFor();
|
||||
await liarShots(pages, '5-guess');
|
||||
const guess = pages[L]!.getByLabel('제시어 맞히기');
|
||||
await guess.fill(` ${[...word].join(' ')} `);
|
||||
await guess.press('Enter');
|
||||
|
||||
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
|
||||
for (const p of pages) await p.locator('.lg-final', { hasText: '라이어 승리' }).waitFor();
|
||||
await host.waitForTimeout(500);
|
||||
await host.screenshot({ path: join(SHOTS, 'liar-6-result-pc.png') });
|
||||
await phone.screenshot({ path: join(SHOTS, 'liar-6-result-phone.png') });
|
||||
console.log(' liar: describe (word refused) → discussion → vote → liar caught → named the word → liar won');
|
||||
},
|
||||
},
|
||||
mafia: {
|
||||
// PC host + 3 phone guests (마피아·경찰·의사·시민), short phases via the lobby. Real flow through the UI: role card,
|
||||
// greeting chat in 전체, night (mafia chat + target, police investigates the mafia, doctor guards themself), the
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"./marble/board": "./src/marble/board.ts",
|
||||
"./clue/board": "./src/clue/board.ts",
|
||||
"./bots/luck": "./src/bots/luck.ts",
|
||||
"./liar/topics": "./src/liar/topics.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -35,6 +35,7 @@ import { appleBot } from '../apple/bot';
|
||||
import { clueBot } from '../clue/bot';
|
||||
import { connectFourBot } from '../connect-four/bot';
|
||||
import { unoBot } from '../uno/bot';
|
||||
import { liarBot } from '../liar/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
@@ -106,8 +107,9 @@ export function decideBotAction(
|
||||
return rest.length ? pick(playable(rest), random) : null;
|
||||
}
|
||||
|
||||
/** Live strategies (games where everybody acts at once: 마피아 talks, 사과 게임 races on its own board); also in `BOT_GAMES`. */
|
||||
/** Live strategies (games where everybody acts at once: 마피아·라이어 게임 talk, 사과 게임 races on its own board); also in `BOT_GAMES`. */
|
||||
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
|
||||
mafia: mafiaBot,
|
||||
apple: appleBot,
|
||||
liar: liarBot,
|
||||
};
|
||||
|
||||
@@ -33,8 +33,8 @@ export function liveBotPlayout(
|
||||
names?: Record<PlayerId, string>;
|
||||
/** Override characters (tests): called once after setup with the game state. */
|
||||
personaOf?: (p: PlayerId, state: unknown) => BotPersona;
|
||||
/** Each computer's level (default: none, the strategy's own default). */
|
||||
levelOf?: (p: PlayerId) => BotLevel;
|
||||
/** Each computer's level 1~60 (default: none, the strategy's own default). */
|
||||
levelOf?: (p: PlayerId, state: unknown) => BotLevel;
|
||||
maxMs?: number;
|
||||
},
|
||||
): LivePlayoutReport {
|
||||
@@ -48,6 +48,7 @@ export function liveBotPlayout(
|
||||
const bots = opts.players.filter(opts.isBot);
|
||||
const persona = new Map(bots.map((b) => [b, opts.personaOf?.(b, state) ?? botPersona(b)]));
|
||||
const memory = new Map(bots.map((b) => [b, {} as Record<string, unknown>]));
|
||||
const level = new Map(bots.map((b) => [b, opts.levelOf?.(b, state)]));
|
||||
const due = new Map(bots.map((b) => [b, now + 500 + random() * 1000]));
|
||||
const rep: LivePlayoutReport = { finished: false, state, actions: 0, rejected: [], chat: [], maxBotMs: 0, elapsed: 0 };
|
||||
const maxMs = opts.maxMs ?? 3 * 3600_000;
|
||||
@@ -74,7 +75,7 @@ export function liveBotPlayout(
|
||||
if (bot === null) throw new Error(`${def.id}: stalled`);
|
||||
now = Math.max(now, due.get(bot)!);
|
||||
const t0 = performance.now();
|
||||
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, level: opts.levelOf?.(bot), names, memory: memory.get(bot)! });
|
||||
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, level: level.get(bot), names, memory: memory.get(bot)! });
|
||||
rep.maxBotMs = Math.max(rep.maxBotMs, performance.now() - t0);
|
||||
due.set(bot, now + Math.max(50, d.next));
|
||||
if (d.action) {
|
||||
|
||||
@@ -30,6 +30,7 @@ import { apple } from './apple';
|
||||
import { clue } from './clue';
|
||||
import { connectFour } from './connect-four';
|
||||
import { uno } from './uno';
|
||||
import { liar } from './liar';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -63,4 +64,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[clue.id]: clue,
|
||||
[connectFour.id]: connectFour,
|
||||
[uno.id]: uno,
|
||||
[liar.id]: liar,
|
||||
};
|
||||
|
||||
142
packages/games/src/liar/bot.test.ts
Normal file
142
packages/games/src/liar/bot.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
/** 라이어 게임 computers (docs/games/liar.md §13): legal, never stuck, never leak, and higher levels play better. */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { botPace, botPersona, type BotPersona } from '../bots/persona';
|
||||
import { liveBotPlayout } from '../bots/live-playout';
|
||||
import { chatProblem } from '../mafia';
|
||||
import { _internal, liarBot } from './bot';
|
||||
import { liar, liarOptionsSchema, saysWord, topicById, type LiarOptions, type LiarState } from './index';
|
||||
|
||||
const { LiarBot, fill } = _internal;
|
||||
const isBot = (p: string) => p.startsWith('bot:');
|
||||
const seats = (n: number, humans: number) => Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:t${i}`));
|
||||
const opts = (o: Partial<LiarOptions> = {}) => liarOptionsSchema.parse(o);
|
||||
const persona = (smart: boolean, p: string): BotPersona => ({ smart, pace: botPace(p), chatty: 0.8 });
|
||||
|
||||
describe('lines', () => {
|
||||
test('josa follows the name', () => {
|
||||
expect(fill('{X:이} 라이어 같아요', { X: '컴퓨터 3님' })).toBe('컴퓨터 3님이 라이어 같아요');
|
||||
expect(fill('{X:이랑} 같은 생각', { X: '철수' })).toBe('철수랑 같은 생각');
|
||||
expect(fill('{X:은} 아닌듯?', { X: '3번' })).toBe('3번은 아닌듯?');
|
||||
});
|
||||
});
|
||||
|
||||
describe('whole games', () => {
|
||||
const variants: [string, Partial<LiarOptions>][] = [
|
||||
['default', {}],
|
||||
['바보 모드, 한 바퀴, 고르기', { foolMode: true, rounds: 1, guessMode: 'choice' }],
|
||||
['짧은 시간', { describeSeconds: 15, discussionSeconds: 30, voteSeconds: 15, guessSeconds: 20, topic: 'fairy' }],
|
||||
];
|
||||
for (const [label, o] of variants) {
|
||||
test(`${label}: 3~10명, 사람 1명(가만히) + 컴퓨터, 컴퓨터만 — 모두 끝나고, 거절된 행동 없음, 제시어를 말하지 않음`, () => {
|
||||
for (const n of [3, 5, 8, 10]) {
|
||||
for (const humans of [1, 0]) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(n, humans), options: opts(o), seed: seedN(n * 10 + humans), isBot });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
expect(r.maxBotMs).toBeLessThan(50);
|
||||
const st = r.state as LiarState;
|
||||
for (const line of r.chat) {
|
||||
expect(chatProblem(line.text, true)).toBeNull();
|
||||
expect(line.text).not.toMatch(/undefined|null|NaN|\{|bot:/);
|
||||
// Nobody says their own word (the game refuses it; bots never even try).
|
||||
const own = line.from === st.liar ? st.liarWord : st.word;
|
||||
if (own) expect(saysWord(line.text, st.topic, own)).toBe(false);
|
||||
}
|
||||
// Every computer described on its turn (none ran out of time).
|
||||
const bots = st.players.filter((p) => isBot(p.id)).map((p) => p.id);
|
||||
for (const d of st.descriptions) if (bots.includes(d.from)) expect(d.text).not.toBeNull();
|
||||
expect(st.descriptions.length).toBe(n * st.options.rounds);
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test('컴퓨터는 토론 때 말하고, 라이어 컴퓨터는 자기를 지목하지 않아요', () => {
|
||||
for (let s = 1; s <= 10; s++) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(6, 0), seed: seedN(300 + s), isBot });
|
||||
const st = r.state as LiarState;
|
||||
expect(st.chat.length).toBeGreaterThan(0);
|
||||
const lastVote = st.events.filter((e) => e.t === 'vote').at(-1);
|
||||
if (lastVote && lastVote.t === 'vote') expect(lastVote.votes[st.liar]).not.toBe(st.liar);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('레벨이 높은 컴퓨터가 더 잘해요: 똑똑한 시민이 라이어를 더 자주 잡고, 똑똑한 라이어가 더 자주 맞혀요', () => {
|
||||
const run = (citizenLevel: number, liarLevel: number) => {
|
||||
let citizens = 0;
|
||||
let guessed = 0;
|
||||
let caught = 0;
|
||||
const n = 40;
|
||||
for (let s = 1; s <= n; s++) {
|
||||
const r = liveBotPlayout(liar, liarBot, {
|
||||
players: seats(5, 0),
|
||||
seed: seedN(1000 + s),
|
||||
isBot,
|
||||
personaOf: (p, st) => persona(((st as LiarState).liar === p ? liarLevel : citizenLevel) > 30, p),
|
||||
levelOf: (p, st) => ((st as LiarState).liar === p ? liarLevel : citizenLevel),
|
||||
});
|
||||
const f = (r.state as LiarState).final!;
|
||||
if (f.winner === 'citizens') citizens++;
|
||||
if (f.accused === f.liar) caught++;
|
||||
if (f.reason === 'guessed') guessed++;
|
||||
}
|
||||
return { citizens: citizens / n, caught: caught / n, guessed };
|
||||
};
|
||||
const strongTown = run(60, 1);
|
||||
const weakTown = run(1, 60);
|
||||
expect(strongTown.caught).toBeGreaterThan(weakTown.caught);
|
||||
expect(strongTown.citizens - weakTown.citizens).toBeGreaterThan(0.2);
|
||||
// A strong liar who is caught names the word more often than a weak one.
|
||||
const strongLiar = run(30, 60);
|
||||
const weakLiar = run(30, 1);
|
||||
expect(strongLiar.guessed).toBeGreaterThan(weakLiar.guessed);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe('reading', () => {
|
||||
function atDiscussion(o: Partial<LiarOptions> = {}) {
|
||||
const players = seats(5, 0);
|
||||
let st = liar.setup({ players, options: opts({ topic: 'fruit', rounds: 1, ...o }), rng: SeededRng.fromSeed(seedN(3)), now: 0 });
|
||||
st.word = '수박';
|
||||
st.liar = players[4]!;
|
||||
st.order = [...players];
|
||||
const hints = topicById('fruit').words.find((w) => w.word === '수박')!.hints;
|
||||
const rng = SeededRng.fromSeed(seedN(4));
|
||||
let now = 0;
|
||||
st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now: (now = st.phase.kind === 'reveal' ? st.phase.endsAt : 0) }).state;
|
||||
for (let i = 0; i < 4; i++) st = liar.apply(st, players[i]!, { type: 'chat', text: hints[i]! }, { rng, now: (now += 2000) }).state;
|
||||
st = liar.apply(st, players[4]!, { type: 'chat', text: '저는 좋아하는 편이에요' }, { rng, now: (now += 2000) }).state;
|
||||
const names = Object.fromEntries(players.map((p, i) => [p, `컴퓨터 ${i + 1}`]));
|
||||
return { st, players, names, now };
|
||||
}
|
||||
|
||||
test('라이어 컴퓨터(높은 레벨)는 설명을 듣고 제시어를 맞혀요', () => {
|
||||
const { st, players, names, now } = atDiscussion();
|
||||
const me = players[4]!;
|
||||
const bot = new LiarBot({ me, view: liar.view(st, me), now, random: Math.random, persona: botPersona(me, 50), level: 60, names, memory: {} });
|
||||
expect(bot.guessWord()).toBe('수박');
|
||||
});
|
||||
|
||||
test('시민 컴퓨터(높은 레벨)는 제시어와 안 맞는 설명을 한 사람을 가장 의심해요', () => {
|
||||
const { st, players, names, now } = atDiscussion();
|
||||
const me = players[0]!;
|
||||
const bot = new LiarBot({ me, view: liar.view(st, me), now, random: Math.random, persona: botPersona(me, 50), level: 60, names, memory: {} });
|
||||
const others = players.slice(1);
|
||||
const top = others.sort((a, b) => bot.sus(b) - bot.sus(a))[0];
|
||||
expect(top).toBe(players[4]);
|
||||
expect(bot.stance('컴퓨터 5 라이어 아니야?').accused).toEqual([players[4]!]);
|
||||
expect(bot.stance('컴퓨터 2님은 맞게 설명한 것 같아요').cleared).toEqual([players[1]!]);
|
||||
});
|
||||
|
||||
test('라이어 컴퓨터가 먼저 말하면 주제에 다 맞는 무난한 말을 해요', () => {
|
||||
const players = seats(4, 0);
|
||||
let st = liar.setup({ players, options: opts({ topic: 'animal' }), rng: SeededRng.fromSeed(seedN(5)), now: 0 });
|
||||
st.order = [...players];
|
||||
st.liar = players[0]!;
|
||||
st = liar.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng: SeededRng.fromSeed(seedN(6)), now: 10_000 }).state;
|
||||
const names = Object.fromEntries(players.map((p, i) => [p, `컴퓨터 ${i + 1}`]));
|
||||
const bot = new LiarBot({ me: players[0]!, view: liar.view(st, players[0]!), now: 10_000, random: Math.random, persona: botPersona(players[0]!, 50), level: 50, names, memory: {} });
|
||||
expect(topicById('animal').generic).toContain(bot.description());
|
||||
});
|
||||
});
|
||||
501
packages/games/src/liar/bot.ts
Normal file
501
packages/games/src/liar/bot.ts
Normal file
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* 라이어 게임 computer players (docs/games/liar.md §13). A live bot like 마피아: the server asks each computer again and
|
||||
* again on its own timer; it sees only its own screen (`view`) and either does one thing (describe, talk, vote, guess,
|
||||
* press "확인"/"토론 끝내기") or keeps watching.
|
||||
*
|
||||
* Every line is fixed text from the word bank or the lines below: no language model rewrites it (a model could let the
|
||||
* word slip, or a liar computer could say something it cannot know).
|
||||
*
|
||||
* - 시민: describes with a sentence of the word's bank it has not heard yet (똑똑한 편 the vaguest first, 허술한 편 any),
|
||||
* then suspects whoever's descriptions fit the word worst.
|
||||
* - 라이어: guesses the word from the descriptions so far (character-pair overlap with each word's bank, rarer pairs
|
||||
* weigh more) and describes that word, vaguely; before anyone spoke it says something that fits the whole topic.
|
||||
* When caught it names the same guess. It never points at itself.
|
||||
* - 바보 모드 라이어 doesn't know: it plays as a citizen of its own word.
|
||||
* The level (1~60) sets how sharp the reading is: noise on every judgement shrinks as the level grows.
|
||||
*/
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import { normalize } from '../catchmind/text';
|
||||
import { hash01 } from '../bots/persona';
|
||||
import type { LiveBotDecision, LiveBotInput } from '../bots/types';
|
||||
import type { Description, LiarAction, LiarView } from './types';
|
||||
import { topicById, type LiarTopic } from './words';
|
||||
|
||||
type In = LiveBotInput<LiarView>;
|
||||
type Done = Record<string, true>;
|
||||
interface Intent {
|
||||
key: string;
|
||||
due: number;
|
||||
make: () => LiarAction | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Korean helpers
|
||||
|
||||
function batchim(word: string): boolean {
|
||||
const c = word.trim().at(-1) ?? '';
|
||||
const code = c.charCodeAt(0);
|
||||
if (code >= 0xac00 && code <= 0xd7a3) return (code - 0xac00) % 28 !== 0;
|
||||
if (/[0-9]/.test(c)) return '013678'.includes(c);
|
||||
return /[lmnr]/i.test(c);
|
||||
}
|
||||
const JOSA: Record<string, [string, string]> = { 이: ['이', '가'], 은: ['은', '는'], 을: ['을', '를'], 이랑: ['이랑', '랑'] };
|
||||
|
||||
/** `{X}` name, `{X:이}` name + 이/가 (also 은, 을, 이랑). */
|
||||
function fill(t: string, vars: Record<string, string>): string {
|
||||
return t.replace(/\{(\w)(?::([^}]+))?\}/g, (_, k: string, j?: string) => {
|
||||
const w = vars[k] ?? '';
|
||||
if (!j) return w;
|
||||
const pair = JOSA[j];
|
||||
return pair ? w + (batchim(w) ? pair[0] : pair[1]) : w + j;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- lines (smart: 존댓말, dumb: 반말)
|
||||
|
||||
const L = {
|
||||
accuse: {
|
||||
smart: ['{X} 설명이 좀 애매했어요', '제 생각엔 {X:이} 라이어 같아요', '{X:은} 다른 걸 설명한 것 같아요', '{X} 설명이 너무 무난했어요. 조금 의심돼요'],
|
||||
dumb: ['{X} 라이어 아님?', '{X} 설명 뭐임ㅋㅋ', '{X} 수상함', '난 {X} 찍을거임', '{X} 뭔가 이상해'],
|
||||
},
|
||||
unsure: {
|
||||
smart: ['다들 비슷하게 설명해서 어렵네요', '조금 더 이야기해 봐요', '아직 잘 모르겠어요. 다들 어떻게 생각해요?'],
|
||||
dumb: ['다 수상해ㅋㅋ', '모르겠다', '누구지...', '흠'],
|
||||
},
|
||||
defend: {
|
||||
smart: ['저 아니에요! 제 설명 다시 보세요', '저는 제시어 알아요. 오히려 {Y:이} 수상해요', '억울해요. 저 진짜 시민이에요', '일부러 애매하게 말한 거예요. {Y} 쪽을 봐 주세요'],
|
||||
dumb: ['나 아님ㅋㅋ', '왜 나야;;', '나 시민임 진짜', '{Y} 의심해라', '억울하다'],
|
||||
},
|
||||
agree: { smart: ['저도 {X:이} 수상하다고 봐요', '동의해요. {X} 설명이 좀 이상했어요'], dumb: ['ㅇㅈ {X} 수상', '{X} 맞는듯', 'ㄹㅇ {X} 이상함'] },
|
||||
disagree: { smart: ['{X:은} 맞게 설명한 것 같은데요', '{X}보다는 {Y:이} 더 수상해요'], dumb: ['{X:은} 아닌듯?', '에이 {X:은} 아니지'] },
|
||||
called: { smart: ['네?', '저요? 왜요?'], dumb: ['왜', 'ㅇ?', '부름?'] },
|
||||
/** Describing when the bank ran out: lean on someone else's description. */
|
||||
echo: { smart: ['{X} 설명에 한 표예요', '{X:이랑} 같은 생각이에요'], dumb: ['{X:이랑} 같은 생각', '{X} 말 ㅇㅈ'] },
|
||||
};
|
||||
type LineKey = keyof typeof L;
|
||||
|
||||
// ---------------------------------------------------------------- reading descriptions
|
||||
|
||||
/** Character pairs of the text (spaces and punctuation out). */
|
||||
function grams(text: string): Set<string> {
|
||||
const t = [...normalize(text)];
|
||||
const out = new Set<string>();
|
||||
for (let i = 0; i + 1 < t.length; i++) out.add(t[i]! + t[i + 1]!);
|
||||
return out;
|
||||
}
|
||||
|
||||
interface TopicModel {
|
||||
topic: LiarTopic;
|
||||
/** Pairs of each word's bank sentences. */
|
||||
corpus: Map<string, Set<string>>;
|
||||
/** Rarer pairs (in fewer words) say more. */
|
||||
idf: Map<string, number>;
|
||||
}
|
||||
const models = new Map<string, TopicModel>();
|
||||
|
||||
function model(id: LiarView['topic']): TopicModel {
|
||||
const hit = models.get(id);
|
||||
if (hit) return hit;
|
||||
const topic = topicById(id);
|
||||
const corpus = new Map<string, Set<string>>();
|
||||
const df = new Map<string, number>();
|
||||
for (const w of topic.words) {
|
||||
const set = new Set<string>();
|
||||
for (const h of w.hints) for (const g of grams(h)) set.add(g);
|
||||
corpus.set(w.word, set);
|
||||
for (const g of set) df.set(g, (df.get(g) ?? 0) + 1);
|
||||
}
|
||||
const n = topic.words.length;
|
||||
const idf = new Map<string, number>();
|
||||
for (const [g, d] of df) idf.set(g, Math.log((n + 1) / d) - 0.15);
|
||||
const m = { topic, corpus, idf };
|
||||
models.set(id, m);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** How well a description matches each word of the topic, 0..1 (1 = the best match). */
|
||||
function matchAll(m: TopicModel, text: string): Map<string, number> {
|
||||
const gs = grams(text);
|
||||
const raw = new Map<string, number>();
|
||||
let best = 0;
|
||||
for (const [word, set] of m.corpus) {
|
||||
let s = 0;
|
||||
for (const g of gs) if (set.has(g)) s += Math.max(0, m.idf.get(g) ?? 0);
|
||||
raw.set(word, s);
|
||||
best = Math.max(best, s);
|
||||
}
|
||||
const out = new Map<string, number>();
|
||||
for (const [word, s] of raw) out.set(word, best > 0.5 ? s / best : 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the bot
|
||||
|
||||
class LiarBot {
|
||||
readonly v: LiarView;
|
||||
readonly me: PlayerId;
|
||||
readonly smart: boolean;
|
||||
/** 0 (level 1) … 1 (level 60). */
|
||||
readonly q: number;
|
||||
private pace: number;
|
||||
private phaseId: string;
|
||||
private m: TopicModel;
|
||||
|
||||
constructor(private input: In) {
|
||||
this.v = input.view;
|
||||
this.me = input.me;
|
||||
this.smart = input.persona.smart;
|
||||
this.pace = input.persona.pace;
|
||||
const level = input.level ?? (this.smart ? 45 : 15);
|
||||
this.q = Math.min(1, Math.max(0, (level - 1) / 59));
|
||||
const ph = this.v.phase;
|
||||
this.phaseId = `${ph.kind}:${ph.round}:${ph.turn}:${ph.voteRound ?? 0}:${ph.startedAt}`;
|
||||
this.m = model(this.v.topic);
|
||||
}
|
||||
|
||||
private h(...k: (string | number)[]): number {
|
||||
return hash01(this.me, this.v.order.join(','), ...k);
|
||||
}
|
||||
|
||||
private get my() {
|
||||
return this.v.my!;
|
||||
}
|
||||
|
||||
/** Thinks it is the liar (normal mode, or after the reveal). */
|
||||
private get isLiar(): boolean {
|
||||
return this.my.role === 'liar';
|
||||
}
|
||||
|
||||
private name(id: PlayerId): string {
|
||||
const n = this.input.names[id] ?? '누군가';
|
||||
if (this.smart) return `${n}님`;
|
||||
const m = /^컴퓨터 (\d+)$/.exec(n);
|
||||
return m ? `${m[1]}번` : n;
|
||||
}
|
||||
|
||||
private line(key: LineKey, salt: string | number, vars: Record<string, string> = {}): string {
|
||||
const pool = this.smart ? L[key].smart : L[key].dumb;
|
||||
const used = new Set([...this.v.chat.filter((c) => c.from === this.me).map((c) => c.text), ...this.v.chat.slice(-8).map((c) => c.text)]);
|
||||
const first = Math.floor(this.h('line', key, salt) * pool.length);
|
||||
for (let i = 0; i < pool.length; i++) {
|
||||
const text = fill(pool[(first + i) % pool.length]!, vars);
|
||||
if (!used.has(text) && this.safe(text)) return text;
|
||||
}
|
||||
return fill(pool[first]!, vars);
|
||||
}
|
||||
|
||||
/** Never says its own word (a name may contain it). */
|
||||
private safe(text: string): boolean {
|
||||
const w = this.my.word;
|
||||
return !w || !normalize(text).includes(normalize(w));
|
||||
}
|
||||
|
||||
private react(baseMs: number, key: string): number {
|
||||
return Math.round(baseMs * (0.6 + this.h('react', key) * 0.9) * this.pace);
|
||||
}
|
||||
|
||||
private get phaseStart(): number {
|
||||
return this.v.phase.startedAt;
|
||||
}
|
||||
|
||||
private get phaseLen(): number {
|
||||
return Math.max(1000, (this.v.phase.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
}
|
||||
|
||||
/** `lo..hi` seconds into the phase (scaled by pace), never later than `cap` of it. */
|
||||
private inPhase(lo: number, hi: number, key: string, cap = 0.8): number {
|
||||
const ms = (lo + (hi - lo) * this.h('t', key, this.phaseId)) * 1000 * this.pace;
|
||||
return this.phaseStart + Math.min(ms, this.phaseLen * cap);
|
||||
}
|
||||
|
||||
private others(): PlayerId[] {
|
||||
return this.v.players.filter((p) => !p.left && p.id !== this.me).map((p) => p.id);
|
||||
}
|
||||
|
||||
private said(): Description[] {
|
||||
return this.v.descriptions.filter((d) => d.text !== null);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- judgement
|
||||
|
||||
/**
|
||||
* The liar's guess of the word: per word, the share of the descriptions it understood that point at it (noisy at low
|
||||
* levels). A weaker computer catches fewer descriptions (`understood`) and reads them with more noise.
|
||||
*/
|
||||
guessScores(): Map<string, number> {
|
||||
const out = new Map<string, number>();
|
||||
for (const w of this.m.topic.words) out.set(w.word, 0);
|
||||
let heard = 0;
|
||||
for (const d of this.said()) {
|
||||
if (d.from === this.me || this.h('understand', d.n) > 0.3 + 0.65 * this.q) continue;
|
||||
const fit = matchAll(this.m, d.text!);
|
||||
if (Math.max(0, ...fit.values()) === 0) continue;
|
||||
heard++;
|
||||
for (const [w, s] of fit) out.set(w, out.get(w)! + s);
|
||||
}
|
||||
if (!heard) return new Map();
|
||||
// 바보 모드 after the reveal: my own word is certainly not it.
|
||||
if (this.my.word) out.delete(this.my.word);
|
||||
const noise = 0.3 + 1.1 * (1 - this.q);
|
||||
for (const [w, s] of out) out.set(w, s / heard + (this.h('guess', w) - 0.5) * noise);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Best guess of the word, or null before anyone said anything useful. */
|
||||
guessWord(): string | null {
|
||||
let best: string | null = null;
|
||||
let bs = -Infinity;
|
||||
for (const [w, s] of this.guessScores()) {
|
||||
if (s > bs) {
|
||||
bs = s;
|
||||
best = w;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** The word I judge others by: mine, or (liar) my guess. */
|
||||
private judgeWord(): string | null {
|
||||
return this.isLiar ? this.guessWord() : this.my.word;
|
||||
}
|
||||
|
||||
/** 0..1: how well `x`'s descriptions fit `word` (skips and words of no word count as weak). */
|
||||
fit(x: PlayerId, word: string | null): number {
|
||||
const ds = this.v.descriptions.filter((d) => d.from === x);
|
||||
if (!ds.length || !word) return 0.5;
|
||||
let sum = 0;
|
||||
for (const d of ds) {
|
||||
if (d.text === null) {
|
||||
sum += 0.15;
|
||||
continue;
|
||||
}
|
||||
const fit = matchAll(this.m, d.text);
|
||||
const best = Math.max(0, ...fit.values());
|
||||
sum += best === 0 ? 0.4 : (fit.get(word) ?? 0);
|
||||
}
|
||||
return sum / ds.length;
|
||||
}
|
||||
|
||||
/** Higher = more likely the liar, in this computer's eyes. */
|
||||
sus(x: PlayerId): number {
|
||||
const noise = (this.h('noise', x) - 0.5) * (0.2 + 1.4 * (1 - this.q));
|
||||
let s = 1 - this.fit(x, this.judgeWord()) + noise;
|
||||
// The chat: people others point at (the liar computer leans on it to blend in; careless ones follow the crowd).
|
||||
const pile = this.accusedInChat().get(x) ?? 0;
|
||||
s += pile * (this.isLiar ? 0.25 : this.smart ? 0.05 : 0.2);
|
||||
return s;
|
||||
}
|
||||
|
||||
private suspect(among = this.others()): PlayerId | null {
|
||||
let best: PlayerId | null = null;
|
||||
let bs = -Infinity;
|
||||
for (const x of among) {
|
||||
if (x === this.me) continue;
|
||||
const s = this.sus(x);
|
||||
if (s > bs) {
|
||||
bs = s;
|
||||
best = x;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- reading the chat
|
||||
|
||||
private nameRes: { id: PlayerId; re: RegExp }[] | null = null;
|
||||
/** Mentions in a line: who, and the text right after (up to the next mention). */
|
||||
private mentions(text: string): { id: PlayerId; tail: string }[] {
|
||||
this.nameRes ??= this.v.players.map((p) => {
|
||||
const n = this.input.names[p.id] ?? p.id;
|
||||
const m = /^컴퓨터 (\d+)$/.exec(n);
|
||||
const alts = (m ? [n, `컴퓨터${m[1]}`, `컴${m[1]}`, `${m[1]}번`] : [n]).map((a) => a.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
||||
return { id: p.id, re: new RegExp(`(?<![0-9])(${alts.join('|')})(?![0-9])`, 'g') };
|
||||
});
|
||||
const hits: { id: PlayerId; at: number; end: number }[] = [];
|
||||
for (const { id, re } of this.nameRes) {
|
||||
re.lastIndex = 0;
|
||||
for (let x = re.exec(text); x; x = re.exec(text)) hits.push({ id, at: x.index, end: x.index + x[0].length });
|
||||
}
|
||||
hits.sort((a, b) => a.at - b.at);
|
||||
return hits.map((x, i) => ({ id: x.id, tail: text.slice(x.end, hits[i + 1]?.at ?? text.length).slice(0, 24) }));
|
||||
}
|
||||
|
||||
stance(text: string): { accused: PlayerId[]; cleared: PlayerId[] } {
|
||||
const accused: PlayerId[] = [];
|
||||
const cleared: PlayerId[] = [];
|
||||
for (const m of this.mentions(text)) {
|
||||
if (/라이어\s*(아니(야|에요|지|냐)?\s*\?|아냐|아닌가|아님\?)/.test(m.tail)) accused.push(m.id);
|
||||
else if (/^\s*(님)?\s*보다/.test(m.tail) || /아니|아닌|아님|시민|믿|맞게|딱/.test(m.tail)) cleared.push(m.id);
|
||||
else if (/라이어|수상|의심|찍|이상|애매|거짓|너지|뭐임|무난/.test(m.tail)) accused.push(m.id);
|
||||
}
|
||||
return { accused, cleared };
|
||||
}
|
||||
|
||||
private pileCache: Map<PlayerId, number> | null = null;
|
||||
private accusedInChat(): Map<PlayerId, number> {
|
||||
if (this.pileCache) return this.pileCache;
|
||||
const out = new Map<PlayerId, number>();
|
||||
for (const c of this.v.chat) {
|
||||
if (c.from === this.me) continue;
|
||||
for (const x of this.stance(c.text).accused) if (x !== c.from) out.set(x, (out.get(x) ?? 0) + 1);
|
||||
}
|
||||
return (this.pileCache = out);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- what to do
|
||||
|
||||
intents(): Intent[] {
|
||||
const v = this.v;
|
||||
const my = this.my;
|
||||
const key = (s: string) => `${this.phaseId}:${s}`;
|
||||
const out: Intent[] = [];
|
||||
switch (v.phase.kind) {
|
||||
case 'reveal':
|
||||
if (my.canReady) out.push({ key: key('ready'), due: this.inPhase(2, 5, 'ready', 0.6), make: () => ({ type: 'ready' }) });
|
||||
break;
|
||||
case 'describe':
|
||||
if (my.canDescribe) {
|
||||
out.push({
|
||||
key: key('describe'),
|
||||
// Leave room for typing ("입력 중…" up to ~6초 on the server) inside the turn.
|
||||
due: this.inPhase(1.5, 5, 'describe', 0.3),
|
||||
make: () => ({ type: 'chat', text: this.description() }),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 'discussion': {
|
||||
const cap = 3;
|
||||
const chat = (text: string) => (this.v.chat.filter((c) => c.from === this.me && c.at >= this.phaseStart).length < cap && my.canChat ? ({ type: 'chat', text } as LiarAction) : null);
|
||||
if (this.h('open') < 0.5 + 0.5 * this.input.persona.chatty) {
|
||||
out.push({
|
||||
key: key('open'),
|
||||
due: this.inPhase(3, 12, 'open', 0.45),
|
||||
make: () => {
|
||||
const x = this.suspect();
|
||||
const sure = x !== null && this.sus(x) > 0.55;
|
||||
return chat(sure ? this.line('accuse', 'open', { X: this.name(x!) }) : this.line('unsure', 'open'));
|
||||
},
|
||||
});
|
||||
}
|
||||
out.push(...this.replies(key, chat));
|
||||
if (my.canReady) out.push({ key: key('ready'), due: this.phaseStart + this.phaseLen * (0.55 + 0.25 * this.h('ready', this.phaseId)), make: () => ({ type: 'ready' }) });
|
||||
break;
|
||||
}
|
||||
case 'vote':
|
||||
if (my.voteTargets.length && my.vote === null) {
|
||||
out.push({
|
||||
key: key('vote'),
|
||||
due: this.inPhase(2, 8, 'vote', 0.6),
|
||||
make: () => {
|
||||
const t = this.suspect(my.voteTargets) ?? my.voteTargets[0]!;
|
||||
return { type: 'vote', target: t };
|
||||
},
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 'guess':
|
||||
if (my.canGuess) {
|
||||
out.push({
|
||||
key: key('guess'),
|
||||
due: this.inPhase(3, 8, 'guess', 0.5),
|
||||
make: () => ({ type: 'guess', text: this.finalGuess() }),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case 'ended':
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** One sentence for my turn. */
|
||||
description(): string {
|
||||
const heard = new Set(this.v.descriptions.map((d) => d.text).filter((t): t is string => !!t));
|
||||
const fresh = (xs: readonly string[]) => xs.filter((x) => !heard.has(x) && this.safe(x));
|
||||
const word = this.judgeWord();
|
||||
// A liar dares to describe its guess only now and then at low levels (otherwise something that fits the topic).
|
||||
const dare = !this.isLiar || this.h('dare', this.v.descriptions.length) < 0.35 + 0.6 * this.q;
|
||||
const hints = word && dare ? fresh(this.m.topic.words.find((w) => w.word === word)?.hints ?? []) : [];
|
||||
if (hints.length) {
|
||||
// Smart ones start vague; careless ones (and a liar without a clue) pick any.
|
||||
const i = this.smart && !this.isLiar ? 0 : Math.floor(this.h('hint', this.v.descriptions.length) * hints.length);
|
||||
return hints[i]!;
|
||||
}
|
||||
// Nothing of my own left (or the liar has no clue yet): something that fits the whole topic, or lean on someone.
|
||||
const generic = fresh(this.m.topic.generic);
|
||||
const trusted = this.others()
|
||||
.filter((x) => this.v.descriptions.some((d) => d.from === x && d.text))
|
||||
.sort((a, b) => this.fit(b, word) - this.fit(a, word))[0];
|
||||
if (trusted && (word || !generic.length) && this.h('echo', this.v.descriptions.length) < 0.6) return this.line('echo', this.v.descriptions.length, { X: this.name(trusted) });
|
||||
if (generic.length) return generic[Math.floor(this.h('generic', this.v.descriptions.length) * generic.length)]!;
|
||||
return this.smart ? '음… 말로 하기 어렵네요' : '음 뭐라 하지';
|
||||
}
|
||||
|
||||
/** The liar's answer: the best guess, or any word of the topic. */
|
||||
finalGuess(): string {
|
||||
const g = this.guessWord();
|
||||
if (g) return g;
|
||||
const words = this.m.topic.words.map((w) => w.word).filter((w) => w !== this.my.word);
|
||||
return words[Math.floor(this.h('blind') * words.length)]!;
|
||||
}
|
||||
|
||||
private replies(key: (s: string) => string, chat: (t: string) => LiarAction | null): Intent[] {
|
||||
const out: Intent[] = [];
|
||||
const recent = this.v.chat.filter((c) => c.from !== this.me && c.at >= this.phaseStart && c.at >= this.input.now - 25_000);
|
||||
for (const c of recent) {
|
||||
const st = this.stance(c.text);
|
||||
const named = this.mentions(c.text).some((x) => x.id === this.me);
|
||||
const delay = (base: number) => c.at + this.react(base + 60 * [...c.text].length, `${c.n}`);
|
||||
if (named) {
|
||||
out.push({
|
||||
key: key(`r:${c.n}`),
|
||||
due: delay(2500),
|
||||
make: () => {
|
||||
if (st.accused.includes(this.me)) {
|
||||
const y = this.suspect(this.others().filter((x) => x !== c.from)) ?? c.from;
|
||||
return chat(this.line('defend', c.n, { Y: this.name(y) }));
|
||||
}
|
||||
return st.cleared.includes(this.me) ? chat(this.smart ? '감사해요!' : 'ㅇㅇ 고마움') : chat(this.line('called', c.n));
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const x = st.accused.find((id) => id !== this.me && id !== c.from);
|
||||
if (!x || this.h('chime', c.n) > (this.smart ? 0.3 : 0.4)) continue;
|
||||
out.push({
|
||||
key: key(`a:${c.n}`),
|
||||
due: delay(3500),
|
||||
make: () => {
|
||||
const mine = this.suspect();
|
||||
if (mine === x || this.sus(x) > 0.6 || (!this.smart && this.h('follow', c.n) < 0.6)) return chat(this.line('agree', c.n, { X: this.name(x) }));
|
||||
return chat(this.line('disagree', c.n, { X: this.name(x), Y: mine ? this.name(mine) : '다른 사람' }));
|
||||
},
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/** Live strategy: at most one action per call; asks again soon so it can answer the chat. */
|
||||
export function liarBot(input: In): LiveBotDecision<LiarAction> {
|
||||
const v = input.view;
|
||||
if (v.phase.kind === 'ended' || !v.my) return { action: null, next: 5000 };
|
||||
const bot = new LiarBot(input);
|
||||
const done = ((input.memory.done as Done | undefined) ??= {});
|
||||
const list = bot.intents().sort((a, b) => a.due - b.due);
|
||||
let soonest = Infinity;
|
||||
for (const it of list) {
|
||||
if (done[it.key]) continue;
|
||||
if (it.due > input.now) {
|
||||
soonest = Math.min(soonest, it.due);
|
||||
continue;
|
||||
}
|
||||
done[it.key] = true;
|
||||
const action = it.make();
|
||||
if (action) return { action, next: Math.round(400 + 600 * input.persona.pace) };
|
||||
}
|
||||
const idle = 1500;
|
||||
const wait = soonest === Infinity ? idle : soonest - input.now;
|
||||
return { action: null, next: Math.max(250, Math.min(idle * input.persona.pace, wait)) };
|
||||
}
|
||||
|
||||
export const _internal = { fill, grams, matchAll, model, LiarBot };
|
||||
562
packages/games/src/liar/index.ts
Normal file
562
packages/games/src/liar/index.ts
Normal file
@@ -0,0 +1,562 @@
|
||||
/**
|
||||
* 라이어 게임 (docs/games/liar.md). Pure and deterministic; state is JSON.
|
||||
*
|
||||
* Phases run on the server clock like 마피아: every phase has `endsAt`, and the room applies the system-only
|
||||
* `phaseTimeout` there (one "driver" player; `timeoutNotBefore` keeps an away driver from firing it early).
|
||||
* 제시어 확인 → 차례대로 한 문장 설명(바퀴 수만큼, 두 번째 바퀴는 거꾸로) → 자유 토론 → 투표(동점이면 동점자끼리 재투표 한 번,
|
||||
* 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
|
||||
*
|
||||
* Secrecy (§8.3): the view gives citizens the word and the liar only the topic (바보 모드: a different word of the topic,
|
||||
* and the liar is told "시민" like everybody else). Who the liar is never appears in any view before the reveal.
|
||||
*/
|
||||
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine';
|
||||
import { judge, normalize } from '../catchmind/text';
|
||||
import { chatProblem, cleanChat } from '../mafia';
|
||||
import {
|
||||
TOPIC_IDS,
|
||||
TOPIC_KO,
|
||||
liarActionSchema,
|
||||
liarOptionsSchema,
|
||||
type LiarAction,
|
||||
type LiarFinal,
|
||||
type LiarOptions,
|
||||
type LiarState,
|
||||
type LiarView,
|
||||
type MyView,
|
||||
type Phase,
|
||||
type PlayerState,
|
||||
type PublicEvent,
|
||||
type TopicId,
|
||||
type WinReason,
|
||||
} from './types';
|
||||
import { TOPICS, topicById, wordEntry } from './words';
|
||||
|
||||
export * from './types';
|
||||
export { TOPICS, topicById, wordEntry, type LiarTopic, type LiarWord } from './words';
|
||||
|
||||
export const REVEAL_MS = 10_000;
|
||||
export const CHAT_MAX = 200;
|
||||
/** One description is one sentence. */
|
||||
export const DESCRIBE_MAX = 80;
|
||||
export const CHAT_GAP_MS = 700;
|
||||
export const GUESS_MAX = 20;
|
||||
/** Points (docs §6): a citizen win gives every citizen 1, a liar win gives the liar 2. */
|
||||
export const CITIZEN_POINTS = 1;
|
||||
export const LIAR_POINTS = 2;
|
||||
const CHAT_KEEP = 300;
|
||||
const CHAT_VIEW = 150;
|
||||
const EVENTS_VIEW = 100;
|
||||
|
||||
// ---------------------------------------------------------------- Korean helpers
|
||||
|
||||
/** Does the word end in a consonant (받침)? Words of the bank are Hangul. */
|
||||
function batchim(word: string): boolean {
|
||||
const code = (word.trim().at(-1) ?? '').charCodeAt(0);
|
||||
return code >= 0xac00 && code <= 0xd7a3 && (code - 0xac00) % 28 !== 0;
|
||||
}
|
||||
|
||||
/** Words that count as saying `word` (the word and its 2+ letter aliases), normalized. */
|
||||
function spoken(topic: TopicId, word: string): string[] {
|
||||
const e = wordEntry(topic, word);
|
||||
return [word, ...(e?.aliases ?? [])].map(normalize).filter((x) => [...x].length >= 2);
|
||||
}
|
||||
|
||||
/** Does the text say the word (spaces, punctuation and case ignored)? */
|
||||
export function saysWord(text: string, topic: TopicId, word: string): boolean {
|
||||
const t = normalize(text);
|
||||
return spoken(topic, word).some((x) => t.includes(x));
|
||||
}
|
||||
|
||||
/** Is `text` the word (or an alias), ignoring spaces, case and a polite ending ("수박이요")? */
|
||||
export function isCorrectGuess(text: string, topic: TopicId, word: string): boolean {
|
||||
const e = wordEntry(topic, word);
|
||||
return judge(text, [word, ...(e?.aliases ?? [])], false) === 'correct';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
const P = (s: LiarState, id: PlayerId): PlayerState | undefined => s.players.find((p) => p.id === id);
|
||||
const present = (s: LiarState) => s.players.filter((p) => !p.left);
|
||||
const isPresent = (s: LiarState, id: PlayerId | null | undefined) => !!id && !!P(s, id) && !P(s, id)!.left;
|
||||
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
|
||||
|
||||
function pushEvent(s: LiarState, now: number, e: DistributiveOmit<PublicEvent, 'n' | 'at'>): void {
|
||||
s.events.push({ ...e, n: s.events.length + 1, at: now } as PublicEvent);
|
||||
}
|
||||
|
||||
/** Speaking order of a round: round 2 runs round 1 backwards. */
|
||||
export function roundOrder(s: Pick<LiarState, 'order'>, round: number): PlayerId[] {
|
||||
return round % 2 === 1 ? [...s.order] : [...s.order].reverse();
|
||||
}
|
||||
|
||||
function speakerOf(s: LiarState): PlayerId | null {
|
||||
const ph = s.phase;
|
||||
return ph.kind === 'describe' ? (roundOrder(s, ph.round)[ph.turn] ?? null) : null;
|
||||
}
|
||||
|
||||
/** The liar is known to everybody once accused (guess phase) or at the end. */
|
||||
const liarKnown = (s: LiarState) => s.phase.kind === 'guess' || s.final !== null;
|
||||
|
||||
/** Starts the describe turn at `turn` of `round` (skipping people who left), or the next round, or the discussion. */
|
||||
function nextTurn(s: LiarState, now: number, round: number, turn: number): void {
|
||||
for (let r = round; r <= s.options.rounds; r++) {
|
||||
const order = roundOrder(s, r);
|
||||
for (let t = r === round ? turn : 0; t < order.length; t++) {
|
||||
if (!isPresent(s, order[t])) continue;
|
||||
const fresh = s.phase.kind !== 'describe' || s.phase.round !== r;
|
||||
s.phase = { kind: 'describe', startedAt: now, endsAt: now + s.options.describeSeconds * 1000, round: r, turn: t };
|
||||
if (fresh) pushEvent(s, now, { t: 'phase', kind: 'describe', round: r });
|
||||
return;
|
||||
}
|
||||
}
|
||||
s.phase = { kind: 'discussion', startedAt: now, endsAt: now + s.options.discussionSeconds * 1000, ready: [] };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'discussion' });
|
||||
}
|
||||
|
||||
function startVote(s: LiarState, now: number, round: 1 | 2, candidates: PlayerId[]): void {
|
||||
s.phase = { kind: 'vote', startedAt: now, endsAt: now + s.options.voteSeconds * 1000, round, candidates, votes: {} };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'vote', round });
|
||||
}
|
||||
|
||||
/** Who `voter` may vote for now. */
|
||||
function voteTargets(s: LiarState, voter: PlayerId): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
if (ph.kind !== 'vote' || !isPresent(s, voter)) return [];
|
||||
return ph.candidates.filter((c) => c !== voter && isPresent(s, c));
|
||||
}
|
||||
|
||||
/** Present players who can vote (someone whose only candidate is themselves sits the revote out). */
|
||||
const voters = (s: LiarState) => present(s).filter((p) => voteTargets(s, p.id).length > 0);
|
||||
|
||||
const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && s.phase.votes[p.id] !== undefined);
|
||||
|
||||
function finish(s: LiarState, now: number, winner: 'liar' | 'citizens', reason: WinReason): void {
|
||||
const word = s.word;
|
||||
const tail = `제시어는 '${word}'${batchim(word) ? '이었어요' : '였어요'}.`;
|
||||
const summary: Record<WinReason, string> = {
|
||||
caught: `시민 승리! 라이어를 찾아냈고, 라이어가 제시어 '${word}'${batchim(word) ? '을' : '를'} 맞히지 못했어요.`,
|
||||
guessed: `라이어 승리! 라이어가 지목됐지만 제시어 '${word}'${batchim(word) ? '을' : '를'} 맞혔어요.`,
|
||||
escaped: `라이어 승리! 라이어가 아닌 사람이 지목됐어요. ${tail}`,
|
||||
tie: `라이어 승리! 투표가 두 번 동점이라 아무도 지목되지 않았어요. ${tail}`,
|
||||
liarLeft: `시민 승리! 라이어가 게임을 나갔어요. ${tail}`,
|
||||
citizensLeft: `라이어 승리! 시민이 모두 나갔어요. ${tail}`,
|
||||
};
|
||||
const scores: Record<PlayerId, number> = {};
|
||||
for (const p of s.players) {
|
||||
const isLiar = p.id === s.liar;
|
||||
scores[p.id] = p.left ? 0 : winner === 'liar' ? (isLiar ? LIAR_POINTS : 0) : isLiar ? 0 : CITIZEN_POINTS;
|
||||
}
|
||||
s.final = { winner, reason, liar: s.liar, topic: s.topic, word, liarWord: s.liarWord, accused: s.accused, guess: s.guess, scores, summary: summary[reason] };
|
||||
s.phase = { kind: 'ended' };
|
||||
pushEvent(s, now, { t: 'end', winner });
|
||||
}
|
||||
|
||||
function resolveVote(s: LiarState, now: number): void {
|
||||
const ph = s.phase as Extract<Phase, { kind: 'vote' }>;
|
||||
const cands = ph.candidates.filter((c) => isPresent(s, c));
|
||||
const tally: Record<PlayerId, number> = {};
|
||||
const votes: Record<PlayerId, PlayerId> = {};
|
||||
for (const p of present(s)) {
|
||||
const v = ph.votes[p.id];
|
||||
if (!v || !cands.includes(v) || v === p.id) continue;
|
||||
votes[p.id] = v;
|
||||
tally[v] = (tally[v] ?? 0) + 1;
|
||||
}
|
||||
const max = Math.max(0, ...Object.values(tally));
|
||||
// Nobody voted: everybody is tied.
|
||||
const tops = cands.length === 1 ? cands : max === 0 ? cands : cands.filter((c) => tally[c] === max);
|
||||
const accused = tops.length === 1 ? tops[0]! : null;
|
||||
pushEvent(s, now, { t: 'vote', round: ph.round, tally, votes, accused, tied: accused ? [] : tops });
|
||||
if (!accused) {
|
||||
if (ph.round === 1 && tops.length >= 2) startVote(s, now, 2, tops);
|
||||
else finish(s, now, 'liar', 'tie');
|
||||
return;
|
||||
}
|
||||
s.accused = accused;
|
||||
const isLiar = accused === s.liar;
|
||||
pushEvent(s, now, { t: 'accused', p: accused, liar: isLiar });
|
||||
if (!isLiar) return finish(s, now, 'liar', 'escaped');
|
||||
s.phase = { kind: 'guess', startedAt: now, endsAt: now + s.options.guessSeconds * 1000 };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'guess' });
|
||||
}
|
||||
|
||||
function resolveGuess(s: LiarState, now: number, text: string | null): void {
|
||||
s.guess = text;
|
||||
const correct = text !== null && isCorrectGuess(text, s.topic, s.word);
|
||||
pushEvent(s, now, { t: 'guess', text, correct });
|
||||
finish(s, now, correct ? 'liar' : 'citizens', correct ? 'guessed' : 'caught');
|
||||
}
|
||||
|
||||
/** The phase timer ran out (or everyone agreed to move on). */
|
||||
function advance(s: LiarState, now: number): void {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return nextTurn(s, now, 1, 0);
|
||||
case 'describe': {
|
||||
s.descriptions.push({ n: s.descriptions.length + 1, round: ph.round, from: speakerOf(s)!, text: null, at: now });
|
||||
return nextTurn(s, now, ph.round, ph.turn + 1);
|
||||
}
|
||||
case 'discussion':
|
||||
return startVote(
|
||||
s,
|
||||
now,
|
||||
1,
|
||||
present(s).map((p) => p.id),
|
||||
);
|
||||
case 'vote':
|
||||
return resolveVote(s, now);
|
||||
case 'guess':
|
||||
return resolveGuess(s, now, null);
|
||||
case 'ended':
|
||||
throw new Error('liar: advance after the end');
|
||||
}
|
||||
}
|
||||
|
||||
/** A player leaves mid-game: skipped from then on, the phase is repaired (§8.5). */
|
||||
function leave(s: LiarState, now: number, p: PlayerState): void {
|
||||
p.left = true;
|
||||
pushEvent(s, now, { t: 'left', p: p.id });
|
||||
if (p.id === s.liar) return finish(s, now, 'citizens', 'liarLeft');
|
||||
if (!present(s).some((x) => x.id !== s.liar)) return finish(s, now, 'liar', 'citizensLeft');
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
case 'discussion':
|
||||
ph.ready = ph.ready.filter((x) => x !== p.id);
|
||||
if (ph.ready.length > 0 && present(s).every((x) => ph.ready.includes(x.id))) advance(s, now);
|
||||
return;
|
||||
case 'describe':
|
||||
if (speakerOf(s) === p.id) nextTurn(s, now, ph.round, ph.turn + 1);
|
||||
return;
|
||||
case 'vote':
|
||||
delete ph.votes[p.id];
|
||||
for (const [k, v] of Object.entries(ph.votes)) if (v === p.id) delete ph.votes[k];
|
||||
ph.candidates = ph.candidates.filter((c) => c !== p.id);
|
||||
if (ph.candidates.length <= 1 || allVoted(s)) resolveVote(s, now);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- permissions
|
||||
|
||||
/** The word `p` holds: citizens the word, the liar nothing (바보 모드: the other word). */
|
||||
function wordOf(s: LiarState, id: PlayerId): string | null {
|
||||
return id === s.liar ? s.liarWord : s.word;
|
||||
}
|
||||
|
||||
/** Why `p` cannot write now (Korean), or null. */
|
||||
function chatBlock(s: LiarState, p: PlayerState): string | null {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'ended') return '게임이 끝났어요.';
|
||||
if (p.left) return '게임에서 나갔어요.';
|
||||
switch (ph.kind) {
|
||||
case 'reveal':
|
||||
return '제시어를 확인하는 중이에요. 곧 설명이 시작돼요.';
|
||||
case 'describe':
|
||||
return speakerOf(s) === p.id ? null : '지금은 설명 차례인 사람만 말할 수 있어요.';
|
||||
case 'guess':
|
||||
return '라이어가 제시어를 맞히는 중이에요.';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- validate
|
||||
|
||||
function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: number }): Validation {
|
||||
const p = P(s, actor);
|
||||
if (!p) return fail('이 게임의 플레이어가 아니에요.');
|
||||
const ph = s.phase;
|
||||
if (s.final || ph.kind === 'ended') return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok;
|
||||
case 'leave':
|
||||
return p.left ? fail('이미 나갔어요.') : ok;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (p.left) return fail('게임에서 나갔어요.');
|
||||
switch (a.type) {
|
||||
case 'chat': {
|
||||
const block = chatBlock(s, p);
|
||||
if (block) return fail(block);
|
||||
const text = cleanChat(a.text);
|
||||
const max = ph.kind === 'describe' ? DESCRIBE_MAX : CHAT_MAX;
|
||||
if (ph.kind === 'describe' && [...text].length > max) return fail(`설명은 한 문장, ${max}자까지 쓸 수 있어요.`);
|
||||
const why = chatProblem(text, s.options.kidSafeChat);
|
||||
if (why) return fail(why);
|
||||
const mine = wordOf(s, actor);
|
||||
if (mine && saysWord(text, s.topic, mine)) return fail('제시어를 직접 말하면 안 돼요.');
|
||||
// Pace limit for free talk only: a description is one per turn anyway.
|
||||
if (ph.kind !== 'describe' && ctx && ctx.now - (s.lastChatAt[actor] ?? -Infinity) < CHAT_GAP_MS) return fail('조금 천천히 보내 주세요.');
|
||||
return ok;
|
||||
}
|
||||
case 'ready':
|
||||
if (ph.kind !== 'reveal' && ph.kind !== 'discussion') return fail('지금은 넘길 수 있는 때가 아니에요.');
|
||||
return ph.ready.includes(actor) ? fail('이미 눌렀어요. 다른 사람을 기다려 주세요.') : ok;
|
||||
case 'vote':
|
||||
if (ph.kind !== 'vote') return fail('지금은 투표 시간이 아니에요.');
|
||||
if (a.target === actor) return fail('나 자신은 지목할 수 없어요.');
|
||||
if (!voteTargets(s, actor).includes(a.target)) return fail(ph.round === 2 ? '재투표는 동점인 사람 중에서만 골라요.' : '이 게임에 있는 사람만 지목할 수 있어요.');
|
||||
return ok;
|
||||
case 'guess': {
|
||||
if (ph.kind !== 'guess') return fail('지금은 제시어를 맞히는 시간이 아니에요.');
|
||||
if (actor !== s.liar) return fail('라이어만 맞힐 수 있어요.');
|
||||
const text = cleanChat(a.text);
|
||||
if (!text) return fail('제시어를 적어 주세요.');
|
||||
if ([...text].length > GUESS_MAX) return fail(`${GUESS_MAX}자까지 적을 수 있어요.`);
|
||||
if (s.options.guessMode === 'choice' && !topicById(s.topic).words.some((x) => x.word === text)) return fail('목록에 있는 단어를 골라 주세요.');
|
||||
return ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
function myView(s: LiarState, me: PlayerState): MyView {
|
||||
const ph = s.phase;
|
||||
const isLiar = me.id === s.liar;
|
||||
const knowsLiar = isLiar && (!s.options.foolMode || liarKnown(s));
|
||||
const block = chatBlock(s, me);
|
||||
const readyPhase = ph.kind === 'reveal' || ph.kind === 'discussion';
|
||||
return {
|
||||
role: knowsLiar ? 'liar' : 'citizen',
|
||||
word: wordOf(s, me.id),
|
||||
canDescribe: ph.kind === 'describe' && !me.left && speakerOf(s) === me.id,
|
||||
canChat: !block,
|
||||
chatWhy: block,
|
||||
canReady: readyPhase && !me.left && !ph.ready.includes(me.id),
|
||||
ready: readyPhase && ph.ready.includes(me.id),
|
||||
vote: ph.kind === 'vote' ? (ph.votes[me.id] ?? null) : null,
|
||||
voteTargets: voteTargets(s, me.id),
|
||||
canGuess: ph.kind === 'guess' && isLiar && !me.left,
|
||||
};
|
||||
}
|
||||
|
||||
function view(s: LiarState, viewer: PlayerId | null): LiarView {
|
||||
const me = viewer ? (P(s, viewer) ?? null) : null;
|
||||
const ph = s.phase;
|
||||
const known = liarKnown(s);
|
||||
const readyPhase = ph.kind === 'reveal' || ph.kind === 'discussion';
|
||||
return {
|
||||
me: me?.id ?? null,
|
||||
options: s.options,
|
||||
topic: s.topic,
|
||||
topicKo: TOPIC_KO[s.topic],
|
||||
phase: {
|
||||
kind: ph.kind,
|
||||
startedAt: ph.kind === 'ended' ? 0 : ph.startedAt,
|
||||
endsAt: ph.kind === 'ended' ? null : ph.endsAt,
|
||||
round: ph.kind === 'describe' ? ph.round : 0,
|
||||
speaker: speakerOf(s),
|
||||
turnOrder: ph.kind === 'describe' ? roundOrder(s, ph.round) : [],
|
||||
turn: ph.kind === 'describe' ? ph.turn : 0,
|
||||
readyCount: readyPhase ? ph.ready.length : 0,
|
||||
readyNeeded: readyPhase ? present(s).length : 0,
|
||||
voteRound: ph.kind === 'vote' ? ph.round : null,
|
||||
candidates: ph.kind === 'vote' ? [...ph.candidates] : [],
|
||||
votedCount: ph.kind === 'vote' ? Object.keys(ph.votes).length : 0,
|
||||
liar: ph.kind === 'guess' ? s.liar : null,
|
||||
choices: ph.kind === 'guess' && s.options.guessMode === 'choice' ? topicById(s.topic).words.map((x) => x.word).sort((a, b) => a.localeCompare(b, 'ko')) : [],
|
||||
},
|
||||
rounds: s.options.rounds,
|
||||
order: [...s.order],
|
||||
players: s.players.map((p) => ({
|
||||
id: p.id,
|
||||
left: p.left,
|
||||
voted: ph.kind === 'vote' && ph.votes[p.id] !== undefined,
|
||||
liar: known ? p.id === s.liar : null,
|
||||
})),
|
||||
descriptions: s.descriptions.map((d) => ({ ...d })),
|
||||
chat: s.chat.slice(-CHAT_VIEW).map((m) => ({ ...m })),
|
||||
events: s.events.slice(-EVENTS_VIEW),
|
||||
my: me ? myView(s, me) : null,
|
||||
final: s.final,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definition
|
||||
|
||||
function activePlayers(s: LiarState): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'ended':
|
||||
return [];
|
||||
case 'describe':
|
||||
return [speakerOf(s)!];
|
||||
case 'guess':
|
||||
return [s.liar];
|
||||
case 'vote':
|
||||
return voters(s)
|
||||
.filter((p) => ph.votes[p.id] === undefined)
|
||||
.map((p) => p.id);
|
||||
default:
|
||||
return present(s).map((p) => p.id);
|
||||
}
|
||||
}
|
||||
|
||||
type Def = GameDefinition<LiarState, LiarAction, LiarView, LiarOptions>;
|
||||
|
||||
export const liar: Def = {
|
||||
id: 'liar',
|
||||
nameKo: '라이어 게임',
|
||||
minPlayers: 3,
|
||||
maxPlayers: 10,
|
||||
stateVersion: 1,
|
||||
defaultOptions: liarOptionsSchema.parse({}),
|
||||
optionsSchema: liarOptionsSchema as unknown as Def['optionsSchema'],
|
||||
actionSchema: liarActionSchema as unknown as Def['actionSchema'],
|
||||
ownChat: true,
|
||||
|
||||
setup({ players, options, rng, now }) {
|
||||
const topic: TopicId = options.topic === 'random' ? TOPIC_IDS[rng.int(TOPIC_IDS.length)]! : options.topic;
|
||||
const words = topicById(topic).words;
|
||||
const wi = rng.int(words.length);
|
||||
const liarId = players[rng.int(players.length)]!;
|
||||
let liarWord: string | null = null;
|
||||
if (options.foolMode) {
|
||||
const rest = words.filter((_, i) => i !== wi);
|
||||
liarWord = rest[rng.int(rest.length)]!.word;
|
||||
}
|
||||
// Seats in order, starting from a random first speaker.
|
||||
const first = rng.int(players.length);
|
||||
const order = [...players.slice(first), ...players.slice(0, first)];
|
||||
return {
|
||||
options,
|
||||
players: players.map((id) => ({ id, left: false })),
|
||||
topic,
|
||||
word: words[wi]!.word,
|
||||
liar: liarId,
|
||||
liarWord,
|
||||
order,
|
||||
phase: { kind: 'reveal', startedAt: now, endsAt: now + REVEAL_MS, ready: [] },
|
||||
descriptions: [],
|
||||
chat: [],
|
||||
lastChatAt: {},
|
||||
events: [],
|
||||
accused: null,
|
||||
guess: null,
|
||||
seq: 0,
|
||||
final: null,
|
||||
};
|
||||
},
|
||||
|
||||
validate,
|
||||
|
||||
apply(prev, actor, a, { now }) {
|
||||
const s = structuredClone(prev);
|
||||
const before = s.events.length;
|
||||
s.seq += 1;
|
||||
const p = P(s, actor)!;
|
||||
const ph = s.phase;
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
advance(s, now);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, now, p);
|
||||
break;
|
||||
case 'chat': {
|
||||
const text = cleanChat(a.text);
|
||||
if (ph.kind === 'describe') {
|
||||
s.descriptions.push({ n: s.descriptions.length + 1, round: ph.round, from: actor, text, at: now });
|
||||
nextTurn(s, now, ph.round, ph.turn + 1);
|
||||
} else {
|
||||
s.lastChatAt[actor] = now;
|
||||
s.chat.push({ n: (s.chat.at(-1)?.n ?? 0) + 1, from: actor, text, at: now });
|
||||
if (s.chat.length > CHAT_KEEP) s.chat.splice(0, s.chat.length - CHAT_KEEP);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'ready':
|
||||
if (ph.kind !== 'reveal' && ph.kind !== 'discussion') throw new Error('liar: ready outside reveal/discussion');
|
||||
ph.ready.push(actor);
|
||||
if (present(s).every((x) => ph.ready.includes(x.id))) advance(s, now);
|
||||
break;
|
||||
case 'vote':
|
||||
if (ph.kind !== 'vote') throw new Error('liar: vote outside the vote phase');
|
||||
ph.votes[actor] = a.target;
|
||||
if (allVoted(s)) resolveVote(s, now);
|
||||
break;
|
||||
case 'guess':
|
||||
resolveGuess(s, now, cleanChat(a.text));
|
||||
break;
|
||||
}
|
||||
const events: GameEvent[] = s.events.slice(before).map((e) => ({ ...e, type: e.t }));
|
||||
return { state: s, events };
|
||||
},
|
||||
|
||||
view,
|
||||
|
||||
activePlayers,
|
||||
|
||||
deadline(s) {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** One player drives the phase clock (the deadline is shared by everybody). */
|
||||
timeoutPlayers(s) {
|
||||
return s.phase.kind === 'ended' ? [] : [s.players[0]!.id];
|
||||
},
|
||||
|
||||
/** An away driver must not end a phase early. */
|
||||
timeoutNotBefore(s) {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** Phases end on the clock: a missing description is "넘김", a missing vote is no vote, a missing guess is wrong. */
|
||||
onTimeout() {
|
||||
return { type: 'phaseTimeout' };
|
||||
},
|
||||
|
||||
onLeave(s, player) {
|
||||
const p = P(s, player);
|
||||
if (!p || p.left || s.final) return null;
|
||||
return { type: 'leave' };
|
||||
},
|
||||
|
||||
result(s): GameResult | null {
|
||||
const f = s.final;
|
||||
if (!f) return null;
|
||||
const won = (id: PlayerId) => !P(s, id)!.left && (f.winner === 'liar') === (id === f.liar);
|
||||
const ids = s.players.map((p) => p.id);
|
||||
const winners = ids.filter(won);
|
||||
const losers = ids.filter((id) => !won(id));
|
||||
return {
|
||||
ranking: [winners, losers].filter((g) => g.length > 0),
|
||||
scores: { ...f.scores },
|
||||
scoreText: Object.fromEntries(ids.map((id) => [id, `${id === f.liar ? '라이어' : '시민'} · ${f.scores[id] ?? 0}점`])),
|
||||
summary: f.summary,
|
||||
reason: 'normal',
|
||||
};
|
||||
},
|
||||
|
||||
/** Test helper: every legal move plus the phase clock and one short message where the player may write. */
|
||||
legalActions(s, player) {
|
||||
const p = P(s, player);
|
||||
if (!p || s.final || s.phase.kind === 'ended') return [];
|
||||
const out: LiarAction[] = [{ type: 'phaseTimeout' }];
|
||||
if (p.left) return out;
|
||||
const me = myView(s, p);
|
||||
if (me.canChat) out.push({ type: 'chat', text: `m${s.seq}-${player}` });
|
||||
if (me.canReady) out.push({ type: 'ready' });
|
||||
for (const t of me.voteTargets) out.push({ type: 'vote', target: t });
|
||||
if (me.canGuess) {
|
||||
if (s.options.guessMode === 'choice') for (const x of topicById(s.topic).words) out.push({ type: 'guess', text: x.word });
|
||||
else out.push({ type: 'guess', text: s.word }, { type: 'guess', text: `${s.word} 아님` });
|
||||
}
|
||||
return out.filter((a) => validate(s, player, a).ok);
|
||||
},
|
||||
|
||||
/** 바보 모드: the liar's own word belongs to the liar alone until the reveal. */
|
||||
secretsOf(s, player) {
|
||||
if (liarKnown(s) || player !== s.liar || !s.liarWord) return [];
|
||||
return [s.liarWord];
|
||||
},
|
||||
};
|
||||
|
||||
export const _internal = { roundOrder, speakerOf, voteTargets, chatBlock, liarKnown, TOPICS };
|
||||
405
packages/games/src/liar/liar.test.ts
Normal file
405
packages/games/src/liar/liar.test.ts
Normal file
@@ -0,0 +1,405 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN, type PlayerId } from '@bg/engine';
|
||||
import { normalize } from '../catchmind/text';
|
||||
import { chatProblem } from '../mafia';
|
||||
import {
|
||||
DESCRIBE_MAX,
|
||||
REVEAL_MS,
|
||||
TOPIC_IDS,
|
||||
TOPICS,
|
||||
isCorrectGuess,
|
||||
liar,
|
||||
roundOrder,
|
||||
saysWord,
|
||||
topicById,
|
||||
type LiarAction,
|
||||
type LiarOptions,
|
||||
type LiarState,
|
||||
type LiarView,
|
||||
type PublicEvent,
|
||||
} from './index';
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
const T0 = 1_000_000;
|
||||
const opts = (o: Record<string, unknown> = {}): LiarOptions => liar.optionsSchema.parse(o);
|
||||
const ids = (n: number) => Array.from({ length: n }, (_, i) => `P${i}`);
|
||||
const rng = SeededRng.fromSeed([9, 9, 9, 9]);
|
||||
|
||||
/** Game with a fixed liar, word and order P0, P1, … (still in the reveal phase). */
|
||||
function rig(n: number, o: Record<string, unknown> = {}, { liarIdx = n - 1, word = '수박', fake = '참외' } = {}): LiarState {
|
||||
const s = liar.setup({ players: ids(n), options: opts({ topic: 'fruit', ...o }), rng: SeededRng.fromSeed(seedN(1)), now: T0 });
|
||||
s.topic = 'fruit';
|
||||
s.word = word;
|
||||
s.liar = `P${liarIdx}`;
|
||||
s.liarWord = s.options.foolMode ? fake : null;
|
||||
s.order = ids(n);
|
||||
return s;
|
||||
}
|
||||
|
||||
function at(s: LiarState): number {
|
||||
return s.phase.kind === 'ended' ? T0 : Math.max(T0, s.phase.startedAt + 1) + s.seq * 1000;
|
||||
}
|
||||
function act(s: LiarState, actor: PlayerId, a: LiarAction, now = at(s)): LiarState {
|
||||
const v = liar.validate(s, actor, a, { now });
|
||||
if (!v.ok) throw new Error(`${actor} ${JSON.stringify(a)} rejected: ${v.reason}`);
|
||||
return liar.apply(s, actor, a, { rng, now }).state;
|
||||
}
|
||||
function reject(s: LiarState, actor: PlayerId, a: LiarAction, now?: number): string {
|
||||
const v = liar.validate(s, actor, a, now === undefined ? undefined : { now });
|
||||
if (v.ok) throw new Error(`${actor} ${JSON.stringify(a)} was accepted`);
|
||||
return v.reason;
|
||||
}
|
||||
const tick = (s: LiarState) => {
|
||||
if (s.phase.kind === 'ended') throw new Error('tick after the end');
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt);
|
||||
};
|
||||
function until(s: LiarState, kind: LiarState['phase']['kind']): LiarState {
|
||||
for (let i = 0; i < 60 && s.phase.kind !== kind && s.phase.kind !== 'ended'; i++) s = tick(s);
|
||||
if (s.phase.kind !== kind) throw new Error(`never reached ${kind} (now ${s.phase.kind})`);
|
||||
return s;
|
||||
}
|
||||
const speaker = (s: LiarState) => liar.view(s, null).phase.speaker;
|
||||
const lastEv = <K extends PublicEvent['t']>(s: LiarState, t: K) => s.events.filter((e) => e.t === t).at(-1) as Extract<PublicEvent, { t: K }> | undefined;
|
||||
function votes(s: LiarState, v: Record<string, string>): LiarState {
|
||||
for (const [p, t] of Object.entries(v)) s = act(s, p, { type: 'vote', target: t });
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- word bank
|
||||
|
||||
describe('제시어 은행 (§3)', () => {
|
||||
test('주제 10개 이상 × 단어 15개 이상 × 설명 4개 이상, 옵션의 주제와 같아요', () => {
|
||||
expect(TOPICS.length).toBeGreaterThanOrEqual(10);
|
||||
expect(TOPICS.map((t) => t.id)).toEqual([...TOPIC_IDS]);
|
||||
for (const t of TOPICS) {
|
||||
expect(t.words.length, t.id).toBeGreaterThanOrEqual(15);
|
||||
expect(t.generic.length, t.id).toBeGreaterThanOrEqual(4);
|
||||
expect(new Set(t.words.map((w) => normalize(w.word))).size, t.id).toBe(t.words.length);
|
||||
for (const w of t.words) {
|
||||
expect(w.hints.length, w.word).toBeGreaterThanOrEqual(4);
|
||||
expect([...w.word].length, w.word).toBeGreaterThanOrEqual(2);
|
||||
expect(new Set(w.hints).size, w.word).toBe(w.hints.length);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('설명 문장에 그 단어(다른 표기 포함)가 없고, 무난한 말에는 주제의 어떤 단어도 없어요. 고운 말 필터도 통과', () => {
|
||||
for (const t of TOPICS) {
|
||||
for (const w of t.words) {
|
||||
for (const h of w.hints) {
|
||||
expect(saysWord(h, t.id, w.word), `${w.word}: ${h}`).toBe(false);
|
||||
expect(chatProblem(h, true), h).toBeNull();
|
||||
expect([...h].length).toBeLessThanOrEqual(DESCRIBE_MAX);
|
||||
}
|
||||
}
|
||||
for (const g of t.generic) {
|
||||
for (const w of t.words) expect(saysWord(g, t.id, w.word), `${t.id} generic: ${g}`).toBe(false);
|
||||
expect(chatProblem(g, true)).toBeNull();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('정답 비교: 띄어쓰기·대소문자·문장 부호·"~요" 무시, 다른 표기도 정답', () => {
|
||||
expect(isCorrectGuess('수박', 'fruit', '수박')).toBe(true);
|
||||
expect(isCorrectGuess(' 수 박!! ', 'fruit', '수박')).toBe(true);
|
||||
expect(isCorrectGuess('수박이요', 'fruit', '수박')).toBe(false); // "이요" is not a polite ending on its own
|
||||
expect(isCorrectGuess('수박요', 'fruit', '수박')).toBe(true);
|
||||
expect(isCorrectGuess('참외', 'fruit', '수박')).toBe(false);
|
||||
expect(isCorrectGuess('tv', 'thing', '텔레비전')).toBe(true);
|
||||
expect(isCorrectGuess('핸드 폰', 'thing', '휴대폰')).toBe(true);
|
||||
expect(isCorrectGuess('파인 애플', 'fruit', '파인애플')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- setup and secrecy
|
||||
|
||||
describe('준비와 비밀 (§4, §8.3)', () => {
|
||||
test('무작위 주제·단어·라이어·첫 발언자, 순서는 자리 순서를 돌린 것', () => {
|
||||
const liars = new Set<string>();
|
||||
const firsts = new Set<string>();
|
||||
const topics = new Set<string>();
|
||||
for (let i = 1; i <= 60; i++) {
|
||||
const s = liar.setup({ players: ids(5), options: opts(), rng: SeededRng.fromSeed(seedN(i)), now: T0 });
|
||||
liars.add(s.liar);
|
||||
firsts.add(s.order[0]!);
|
||||
topics.add(s.topic);
|
||||
expect(topicById(s.topic).words.some((w) => w.word === s.word)).toBe(true);
|
||||
const k = ids(5).indexOf(s.order[0]!);
|
||||
expect(s.order).toEqual([...ids(5).slice(k), ...ids(5).slice(0, k)]);
|
||||
expect(s.liarWord).toBeNull();
|
||||
expect(s.phase).toEqual({ kind: 'reveal', startedAt: T0, endsAt: T0 + REVEAL_MS, ready: [] });
|
||||
}
|
||||
expect(liars.size).toBe(5);
|
||||
expect(firsts.size).toBe(5);
|
||||
expect(topics.size).toBeGreaterThan(5);
|
||||
});
|
||||
|
||||
test('시민은 제시어, 라이어는 주제만, 관전자는 주제만. 누가 라이어인지는 어디에도 없어요', () => {
|
||||
const s = rig(5);
|
||||
const citizen = liar.view(s, 'P0');
|
||||
expect(citizen.my).toMatchObject({ role: 'citizen', word: '수박' });
|
||||
const lv = liar.view(s, 'P4');
|
||||
expect(lv.my).toMatchObject({ role: 'liar', word: null });
|
||||
expect(lv.topicKo).toBe('과일');
|
||||
expect(JSON.stringify(lv)).not.toContain('수박');
|
||||
expect(JSON.stringify(liar.view(s, null))).not.toContain('수박');
|
||||
for (const v of [citizen, lv, liar.view(s, null)]) for (const p of v.players) expect(p.liar).toBeNull();
|
||||
});
|
||||
|
||||
test('시민 화면은 누가 라이어든 똑같아요(라이어가 바뀌어도 한 글자도 안 바뀜)', () => {
|
||||
let a = rig(6, {}, { liarIdx: 3 });
|
||||
let b = rig(6, {}, { liarIdx: 5 });
|
||||
// Same moves on both: reveal → two descriptions → discussion → votes.
|
||||
const step = (f: (s: LiarState) => LiarState) => {
|
||||
a = f(a);
|
||||
b = f(b);
|
||||
};
|
||||
step(tick);
|
||||
step((s) => act(s, speaker(s)!, { type: 'chat', text: '여름에 생각나요' }));
|
||||
step(tick);
|
||||
step((s) => until(s, 'discussion'));
|
||||
step((s) => act(s, 'P1', { type: 'chat', text: '다들 애매하네요' }));
|
||||
step((s) => until(s, 'vote'));
|
||||
step((s) => act(s, 'P0', { type: 'vote', target: 'P2' }));
|
||||
for (const viewer of ['P0', 'P1', 'P2', null]) expect(liar.view(a, viewer)).toEqual(liar.view(b, viewer));
|
||||
});
|
||||
|
||||
test('바보 모드: 라이어도 다른 단어를 받고 "시민"으로 보여요. 화면 모양이 시민과 똑같아요', () => {
|
||||
const s = rig(5, { foolMode: true });
|
||||
const lv = liar.view(s, 'P4');
|
||||
const cv = liar.view(s, 'P0');
|
||||
expect(lv.my).toMatchObject({ role: 'citizen', word: '참외' });
|
||||
expect(JSON.stringify(lv)).not.toContain('수박');
|
||||
for (const v of [cv, liar.view(s, 'P1'), liar.view(s, null)]) expect(JSON.stringify(v)).not.toContain('참외');
|
||||
const shape = (v: LiarView) => JSON.stringify({ ...v, me: 'X', my: { ...v.my, word: 'W' } });
|
||||
expect(shape(lv)).toBe(shape(cv));
|
||||
expect(liar.secretsOf!(s, 'P4')).toEqual(['참외']);
|
||||
expect(() => checkNoLeak(liar, s, 'P0', ids(5))).not.toThrow();
|
||||
});
|
||||
|
||||
test('라이어가 드러나면(정답 맞히기) 모두가 알고, 바보 모드 라이어도 자기가 라이어인 걸 알아요', () => {
|
||||
let s = until(rig(4, { foolMode: true }), 'vote');
|
||||
s = votes(s, { P0: 'P3', P1: 'P3', P2: 'P3', P3: 'P0' });
|
||||
expect(s.phase.kind).toBe('guess');
|
||||
expect(liar.view(s, 'P3').my).toMatchObject({ role: 'liar', canGuess: true });
|
||||
expect(liar.view(s, 'P0').players.find((p) => p.id === 'P3')!.liar).toBe(true);
|
||||
expect(liar.view(s, null).phase.liar).toBe('P3');
|
||||
expect(liar.secretsOf!(s, 'P3')).toEqual([]);
|
||||
// The real word is still hidden from the liar until the end.
|
||||
expect(JSON.stringify(liar.view(s, 'P3'))).not.toContain('수박');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- describing
|
||||
|
||||
describe('차례대로 설명 (§5.2)', () => {
|
||||
test('확인 시간 → 순서대로 한 문장씩, 두 번째 바퀴는 거꾸로, 그다음 자유 토론', () => {
|
||||
let s = rig(3);
|
||||
s = act(s, 'P0', { type: 'ready' });
|
||||
s = act(s, 'P1', { type: 'ready' });
|
||||
expect(s.phase.kind).toBe('reveal');
|
||||
s = act(s, 'P2', { type: 'ready' });
|
||||
expect(s.phase).toMatchObject({ kind: 'describe', round: 1, turn: 0 });
|
||||
const spoken: string[] = [];
|
||||
while (s.phase.kind === 'describe') {
|
||||
const sp = speaker(s)!;
|
||||
spoken.push(sp);
|
||||
for (const other of ids(3).filter((x) => x !== sp)) expect(reject(s, other, { type: 'chat', text: '저도요' })).toBe('지금은 설명 차례인 사람만 말할 수 있어요.');
|
||||
s = act(s, sp, { type: 'chat', text: `설명 ${spoken.length}` });
|
||||
}
|
||||
expect(spoken).toEqual(['P0', 'P1', 'P2', 'P2', 'P1', 'P0']);
|
||||
expect(roundOrder(s, 2)).toEqual(['P2', 'P1', 'P0']);
|
||||
expect(s.phase.kind).toBe('discussion');
|
||||
expect(s.descriptions.map((d) => [d.round, d.from, d.text])).toEqual([
|
||||
[1, 'P0', '설명 1'],
|
||||
[1, 'P1', '설명 2'],
|
||||
[1, 'P2', '설명 3'],
|
||||
[2, 'P2', '설명 4'],
|
||||
[2, 'P1', '설명 5'],
|
||||
[2, 'P0', '설명 6'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('첫 바퀴 마지막 사람은 바로 이어서 두 번째 바퀴 첫 설명을 할 수 있어요(채팅 간격 제한 없음)', () => {
|
||||
let s = tick(rig(3));
|
||||
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'chat', text: `${p} 설명` }, T0 + 20_000);
|
||||
expect(speaker(s)).toBe('P2');
|
||||
s = act(s, 'P2', { type: 'chat', text: '또 설명' }, T0 + 20_000);
|
||||
expect(speaker(s)).toBe('P1');
|
||||
});
|
||||
|
||||
test('한 바퀴 옵션, 시간 초과는 넘김, 설명은 80자까지', () => {
|
||||
let s = tick(rig(3, { rounds: 1, describeSeconds: 15 }));
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt - s.phase.startedAt).toBe(15_000);
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '가'.repeat(81) })).toContain('80자');
|
||||
s = tick(s);
|
||||
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
|
||||
s = act(s, 'P1', { type: 'chat', text: '좋아요' });
|
||||
s = tick(s);
|
||||
expect(s.phase.kind).toBe('discussion');
|
||||
});
|
||||
|
||||
test('제시어를 직접 말하면 안 돼요(띄어쓰기 무시). 라이어는 막지 않아요(막으면 정답이 새요)', () => {
|
||||
let s = tick(rig(3, { rounds: 1 }, { liarIdx: 1 }));
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '수 박 맛있어요' })).toBe('제시어를 직접 말하면 안 돼요.');
|
||||
s = act(s, 'P0', { type: 'chat', text: '여름이면 생각나요' });
|
||||
s = act(s, 'P1', { type: 'chat', text: '수박 같아요' }); // the liar's guess-like line goes through
|
||||
expect(s.descriptions.at(-1)!.text).toBe('수박 같아요');
|
||||
});
|
||||
|
||||
test('바보 모드 라이어는 자기 단어를 직접 말하면 막혀요(시민과 똑같이)', () => {
|
||||
const s = tick(rig(3, { foolMode: true, rounds: 1 }, { liarIdx: 0 }));
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '참외' })).toBe('제시어를 직접 말하면 안 돼요.');
|
||||
});
|
||||
|
||||
test('확인 시간·정답 맞히기 중에는 채팅을 못 쓰고, 토론·투표 중에는 모두 써요', () => {
|
||||
let s = rig(3);
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '안녕' })).toContain('확인하는 중');
|
||||
s = until(s, 'discussion');
|
||||
s = act(s, 'P1', { type: 'chat', text: '누구지' });
|
||||
expect(reject(s, 'P1', { type: 'chat', text: '또' }, at(s) - 1000 + 100)).toBe('조금 천천히 보내 주세요.');
|
||||
s = until(s, 'vote');
|
||||
s = act(s, 'P2', { type: 'chat', text: '투표해요' });
|
||||
expect(s.chat.map((m) => m.text)).toEqual(['누구지', '투표해요']);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- discussion and vote
|
||||
|
||||
describe('토론과 투표 (§5.3~5.5)', () => {
|
||||
test('토론은 모두 [토론 끝내기]를 누르면 바로 투표로', () => {
|
||||
let s = until(rig(3), 'discussion');
|
||||
s = act(s, 'P0', { type: 'ready' });
|
||||
s = act(s, 'P1', { type: 'ready' });
|
||||
expect(liar.view(s, 'P2').phase).toMatchObject({ readyCount: 2, readyNeeded: 3 });
|
||||
s = act(s, 'P2', { type: 'ready' });
|
||||
expect(s.phase).toMatchObject({ kind: 'vote', round: 1 });
|
||||
});
|
||||
|
||||
test('모두 투표하면 바로 집계, 시민이 지목되면 라이어 승리', () => {
|
||||
let s = until(rig(4), 'vote');
|
||||
expect(reject(s, 'P0', { type: 'vote', target: 'P0' })).toBe('나 자신은 지목할 수 없어요.');
|
||||
s = votes(s, { P0: 'P1', P1: 'P2', P2: 'P1' });
|
||||
expect(liar.view(s, 'P0').players.map((p) => p.voted)).toEqual([true, true, true, false]);
|
||||
expect(liar.view(s, 'P0').phase.votedCount).toBe(3);
|
||||
s = votes(s, { P3: 'P1' });
|
||||
expect(s.phase.kind).toBe('ended');
|
||||
expect(lastEv(s, 'vote')).toMatchObject({ round: 1, accused: 'P1', tally: { P1: 3, P2: 1 } });
|
||||
expect(lastEv(s, 'accused')).toMatchObject({ p: 'P1', liar: false });
|
||||
expect(s.final).toMatchObject({ winner: 'liar', reason: 'escaped', liar: 'P3', word: '수박' });
|
||||
const r = liar.result(s)!;
|
||||
expect(r.ranking).toEqual([['P3'], ['P0', 'P1', 'P2']]);
|
||||
expect(r.scoreText).toEqual({ P0: '시민 · 0점', P1: '시민 · 0점', P2: '시민 · 0점', P3: '라이어 · 2점' });
|
||||
expect(r.summary).toBe("라이어 승리! 라이어가 아닌 사람이 지목됐어요. 제시어는 '수박'이었어요.");
|
||||
});
|
||||
|
||||
test('동점이면 동점자끼리 재투표 한 번, 또 동점이면 라이어 승리', () => {
|
||||
let s = until(rig(4), 'vote');
|
||||
s = votes(s, { P0: 'P1', P1: 'P0', P2: 'P3', P3: 'P2' });
|
||||
expect(s.phase).toMatchObject({ kind: 'vote', round: 2, candidates: ['P0', 'P1', 'P2', 'P3'] });
|
||||
s = until(rig(4), 'vote');
|
||||
s = votes(s, { P0: 'P1', P1: 'P0', P2: 'P1', P3: 'P0' });
|
||||
expect(s.phase).toMatchObject({ kind: 'vote', round: 2, candidates: ['P0', 'P1'] });
|
||||
expect(lastEv(s, 'vote')).toMatchObject({ accused: null, tied: ['P0', 'P1'] });
|
||||
expect(reject(s, 'P2', { type: 'vote', target: 'P3' })).toBe('재투표는 동점인 사람 중에서만 골라요.');
|
||||
// P0 and P1 can only vote for each other.
|
||||
expect(liar.view(s, 'P0').my!.voteTargets).toEqual(['P1']);
|
||||
s = votes(s, { P0: 'P1', P1: 'P0', P2: 'P0', P3: 'P1' });
|
||||
expect(s.final).toMatchObject({ winner: 'liar', reason: 'tie' });
|
||||
});
|
||||
|
||||
test('아무도 투표하지 않으면 모두 동점: 재투표, 또 없으면 라이어 승리', () => {
|
||||
let s = until(rig(3), 'vote');
|
||||
s = tick(s);
|
||||
expect(s.phase).toMatchObject({ kind: 'vote', round: 2, candidates: ['P0', 'P1', 'P2'] });
|
||||
s = tick(s);
|
||||
expect(s.final).toMatchObject({ winner: 'liar', reason: 'tie' });
|
||||
});
|
||||
|
||||
test('라이어가 지목되면 정답 맞히기: 맞히면 라이어, 틀리거나 시간이 지나면 시민 승리', () => {
|
||||
const toGuess = (o: Record<string, unknown> = {}) => votes(until(rig(4, o), 'vote'), { P0: 'P3', P1: 'P3', P2: 'P3', P3: 'P0' });
|
||||
let s = toGuess();
|
||||
expect(s.phase.kind).toBe('guess');
|
||||
expect(lastEv(s, 'accused')).toMatchObject({ p: 'P3', liar: true });
|
||||
expect(reject(s, 'P0', { type: 'guess', text: '수박' })).toBe('라이어만 맞힐 수 있어요.');
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '힌트' })).toContain('맞히는 중');
|
||||
const right = act(s, 'P3', { type: 'guess', text: ' 수 박 ' });
|
||||
expect(right.final).toMatchObject({ winner: 'liar', reason: 'guessed', guess: '수 박' });
|
||||
expect(liar.result(right)!.ranking).toEqual([['P3'], ['P0', 'P1', 'P2']]);
|
||||
const wrong = act(s, 'P3', { type: 'guess', text: '참외' });
|
||||
expect(wrong.final).toMatchObject({ winner: 'citizens', reason: 'caught' });
|
||||
expect(liar.result(wrong)!.scoreText!.P0).toBe('시민 · 1점');
|
||||
expect(liar.result(wrong)!.summary).toBe("시민 승리! 라이어를 찾아냈고, 라이어가 제시어 '수박'을 맞히지 못했어요.");
|
||||
s = tick(s);
|
||||
expect(s.final).toMatchObject({ winner: 'citizens', reason: 'caught', guess: null });
|
||||
expect(lastEv(s, 'guess')).toMatchObject({ text: null, correct: false });
|
||||
// Choice mode: only words of the topic.
|
||||
s = toGuess({ guessMode: 'choice' });
|
||||
const choices = liar.view(s, 'P3').phase.choices;
|
||||
expect(choices).toContain('수박');
|
||||
expect(choices).toHaveLength(topicById('fruit').words.length);
|
||||
expect(reject(s, 'P3', { type: 'guess', text: '고양이' })).toBe('목록에 있는 단어를 골라 주세요.');
|
||||
expect(act(s, 'P3', { type: 'guess', text: '수박' }).final!.winner).toBe('liar');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- leaving
|
||||
|
||||
describe('나가기 (§8.5)', () => {
|
||||
test('설명 차례인 사람이 나가면 다음 사람, 이후 차례·투표에서 빠져요', () => {
|
||||
let s = tick(rig(4, { rounds: 1 }));
|
||||
s = act(s, 'P0', { type: 'leave' });
|
||||
expect(speaker(s)).toBe('P1');
|
||||
s = until(s, 'vote');
|
||||
expect(liar.view(s, 'P1').my!.voteTargets).toEqual(['P2', 'P3']);
|
||||
s = votes(s, { P1: 'P3', P2: 'P3', P3: 'P1' });
|
||||
expect(s.phase.kind).toBe('guess');
|
||||
});
|
||||
|
||||
test('라이어가 나가면 시민 승리, 시민이 모두 나가면 라이어 승리', () => {
|
||||
const s = tick(rig(3));
|
||||
expect(act(s, 'P2', { type: 'leave' }).final).toMatchObject({ winner: 'citizens', reason: 'liarLeft' });
|
||||
const t = act(act(s, 'P0', { type: 'leave' }), 'P1', { type: 'leave' });
|
||||
expect(t.final).toMatchObject({ winner: 'liar', reason: 'citizensLeft' });
|
||||
expect(liar.result(t)!.ranking).toEqual([['P2'], ['P0', 'P1']]);
|
||||
});
|
||||
|
||||
test('투표 중 나가면 그 사람 표와 그 사람에게 간 표가 빠지고, 남은 사람이 다 투표하면 바로 집계', () => {
|
||||
let s = until(rig(4), 'vote');
|
||||
s = votes(s, { P1: 'P0', P2: 'P3', P3: 'P2' });
|
||||
s = act(s, 'P0', { type: 'leave' });
|
||||
expect(s.phase.kind === 'vote' && s.phase.votes).toEqual({ P2: 'P3', P3: 'P2' });
|
||||
expect(liar.view(s, 'P1').my!.vote).toBeNull();
|
||||
s = votes(s, { P1: 'P3' });
|
||||
expect(s.phase.kind).toBe('guess');
|
||||
// Everybody else already voted: the leaver's departure closes the vote at once.
|
||||
let t = until(rig(4), 'vote');
|
||||
t = votes(t, { P1: 'P3', P2: 'P3', P3: 'P1' });
|
||||
t = act(t, 'P0', { type: 'leave' });
|
||||
expect(t.phase.kind).toBe('guess');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- engine checks
|
||||
|
||||
describe('무작위 대국 (엔진 공통 검사)', () => {
|
||||
const variants: Record<string, unknown>[] = [{}, { foolMode: true }, { rounds: 1, guessMode: 'choice' }, { foolMode: true, topic: 'fairy', guessMode: 'choice' }];
|
||||
for (const [i, o] of variants.entries()) {
|
||||
test(`옵션 ${JSON.stringify(o)}: 3~10명, 끝까지·유출 없음·JSON 왕복`, () => {
|
||||
for (let k = 1; k <= playoutSeeds(40); k++) {
|
||||
const n = 3 + (k % 8);
|
||||
const r = randomPlayout(liar, { players: ids(n), options: opts(o), seed: seedN(i * 1000 + k), maxSteps: 3000 });
|
||||
expect(r.finished).toBe(true);
|
||||
const res = liar.result(r.finalState as LiarState)!;
|
||||
expect(res.ranking.flat().sort()).toEqual(ids(n).sort());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('결정적: 같은 시드면 같은 판', () => {
|
||||
const a = randomPlayout(liar, { players: ids(5), seed: seedN(7) });
|
||||
const b = randomPlayout(liar, { players: ids(5), seed: seedN(7) });
|
||||
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
|
||||
});
|
||||
});
|
||||
15
packages/games/src/liar/topics.ts
Normal file
15
packages/games/src/liar/topics.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
/** 라이어 게임 topics (no dependencies: the web screen imports this alone, without the word bank). */
|
||||
export const TOPIC_IDS = ['fruit', 'animal', 'job', 'food', 'place', 'sport', 'vehicle', 'thing', 'country', 'fairy'] as const;
|
||||
export type TopicId = (typeof TOPIC_IDS)[number];
|
||||
export const TOPIC_KO: Record<TopicId, string> = {
|
||||
fruit: '과일',
|
||||
animal: '동물',
|
||||
job: '직업',
|
||||
food: '음식',
|
||||
place: '장소',
|
||||
sport: '운동',
|
||||
vehicle: '탈것',
|
||||
thing: '물건',
|
||||
country: '나라',
|
||||
fairy: '동화 주인공',
|
||||
};
|
||||
197
packages/games/src/liar/types.ts
Normal file
197
packages/games/src/liar/types.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
/** 라이어 게임 options, actions, state and view types (docs/games/liar.md §2, §8). */
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
const lit = <T extends number>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`]));
|
||||
|
||||
export const liarOptionsSchema = z.object({
|
||||
topic: z
|
||||
.enum(['random', ...TOPIC_IDS])
|
||||
.default('random')
|
||||
.meta({ title: '주제', labels: { random: '무작위', ...TOPIC_KO } }),
|
||||
foolMode: z.boolean().default(false).meta({ title: '바보 모드(라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요)' }),
|
||||
rounds: lit(1, 2)
|
||||
.default(2)
|
||||
.meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }),
|
||||
describeSeconds: lit(15, 20, 30, 45, 60)
|
||||
.default(30)
|
||||
.meta({ title: '한 사람 설명 시간', labels: secLabels(15, 20, 30, 45, 60) }),
|
||||
discussionSeconds: lit(30, 60, 90, 120, 180)
|
||||
.default(90)
|
||||
.meta({ title: '자유 토론 시간', labels: secLabels(30, 60, 90, 120, 180) }),
|
||||
voteSeconds: lit(15, 20, 30, 45)
|
||||
.default(30)
|
||||
.meta({ title: '투표 시간', labels: secLabels(15, 20, 30, 45) }),
|
||||
guessMode: z
|
||||
.enum(['text', 'choice'])
|
||||
.default('text')
|
||||
.meta({ title: '라이어의 정답 맞히기', labels: { text: '직접 적기', choice: '주제 단어 목록에서 고르기' } }),
|
||||
guessSeconds: lit(20, 30, 45, 60)
|
||||
.default(30)
|
||||
.meta({ title: '정답 맞히기 시간', labels: secLabels(20, 30, 45, 60) }),
|
||||
kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }),
|
||||
});
|
||||
export type LiarOptions = z.infer<typeof liarOptionsSchema>;
|
||||
|
||||
const pid = z.string().min(1).max(64);
|
||||
export const liarActionSchema = z.discriminatedUnion('type', [
|
||||
/** Describe phase: the speaker's one sentence. Discussion / vote: free talk. */
|
||||
z.object({ type: z.literal('chat'), text: z.string().max(400) }),
|
||||
z.object({ type: z.literal('ready') }),
|
||||
z.object({ type: z.literal('vote'), target: pid }),
|
||||
z.object({ type: z.literal('guess'), text: z.string().max(60) }),
|
||||
]);
|
||||
export type LiarClientAction = z.infer<typeof liarActionSchema>;
|
||||
/** Client actions plus the system-only ones (phase timer, leaving) that are not in the schema. */
|
||||
export type LiarAction = LiarClientAction | { type: 'phaseTimeout' } | { type: 'leave' };
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
export type Phase =
|
||||
| { kind: 'reveal'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'describe'; startedAt: number; endsAt: number; round: number; turn: number }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number; round: 1 | 2; candidates: PlayerId[]; votes: Record<PlayerId, PlayerId> }
|
||||
| { kind: 'guess'; startedAt: number; endsAt: number }
|
||||
| { kind: 'ended' };
|
||||
export type PhaseKind = Phase['kind'];
|
||||
|
||||
export interface PlayerState {
|
||||
id: PlayerId;
|
||||
/** Left the game: skipped from then on (turns, votes, "모두 동의"). */
|
||||
left: boolean;
|
||||
}
|
||||
|
||||
export interface Description {
|
||||
n: number;
|
||||
round: number;
|
||||
from: PlayerId;
|
||||
/** null = the time ran out (넘김). */
|
||||
text: string | null;
|
||||
at: number;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
n: number;
|
||||
from: PlayerId;
|
||||
text: string;
|
||||
at: number;
|
||||
}
|
||||
|
||||
export type WinReason = 'escaped' | 'tie' | 'guessed' | 'caught' | 'liarLeft' | 'citizensLeft';
|
||||
|
||||
/** Public announcement. */
|
||||
export type PublicEvent = { n: number; at: number } & (
|
||||
| { t: 'phase'; kind: Exclude<PhaseKind, 'ended'>; round?: number }
|
||||
| { t: 'vote'; round: 1 | 2; tally: Record<PlayerId, number>; votes: Record<PlayerId, PlayerId>; accused: PlayerId | null; tied: PlayerId[] }
|
||||
| { t: 'accused'; p: PlayerId; liar: boolean }
|
||||
| { t: 'guess'; text: string | null; correct: boolean }
|
||||
| { t: 'left'; p: PlayerId }
|
||||
| { t: 'end'; winner: 'liar' | 'citizens' }
|
||||
);
|
||||
export type PublicEventKind = PublicEvent['t'];
|
||||
|
||||
export interface LiarFinal {
|
||||
winner: 'liar' | 'citizens';
|
||||
reason: WinReason;
|
||||
liar: PlayerId;
|
||||
topic: TopicId;
|
||||
word: string;
|
||||
/** 바보 모드: the word the liar got. */
|
||||
liarWord: string | null;
|
||||
accused: PlayerId | null;
|
||||
guess: string | null;
|
||||
scores: Record<PlayerId, number>;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface LiarState {
|
||||
options: LiarOptions;
|
||||
players: PlayerState[];
|
||||
topic: TopicId;
|
||||
word: string;
|
||||
liar: PlayerId;
|
||||
/** 바보 모드: the liar's own (wrong) word; null otherwise. */
|
||||
liarWord: string | null;
|
||||
/** Round-1 speaking order (round 2 runs it backwards). */
|
||||
order: PlayerId[];
|
||||
phase: Phase;
|
||||
descriptions: Description[];
|
||||
chat: ChatMessage[];
|
||||
lastChatAt: Record<PlayerId, number>;
|
||||
events: PublicEvent[];
|
||||
accused: PlayerId | null;
|
||||
guess: string | null;
|
||||
seq: number;
|
||||
final: LiarFinal | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export interface PlayerView {
|
||||
id: PlayerId;
|
||||
left: boolean;
|
||||
/** Vote phase: has voted (not whom). */
|
||||
voted: boolean;
|
||||
/** Known only after the reveal: is the liar. null = unknown to this viewer. */
|
||||
liar: boolean | null;
|
||||
}
|
||||
|
||||
export interface MyView {
|
||||
/**
|
||||
* What I know of myself: 'liar' (normal mode, or after the reveal) / 'citizen'. In 바보 모드 the liar sees
|
||||
* 'citizen' and a word, exactly like everybody else, until the reveal.
|
||||
*/
|
||||
role: 'liar' | 'citizen';
|
||||
/** My word; null for a (normal-mode) liar. */
|
||||
word: string | null;
|
||||
canDescribe: boolean;
|
||||
canChat: boolean;
|
||||
/** Korean reason I can't write now, or null. */
|
||||
chatWhy: string | null;
|
||||
canReady: boolean;
|
||||
ready: boolean;
|
||||
vote: PlayerId | null;
|
||||
voteTargets: PlayerId[];
|
||||
canGuess: boolean;
|
||||
}
|
||||
|
||||
export interface LiarView {
|
||||
me: PlayerId | null;
|
||||
options: LiarOptions;
|
||||
topic: TopicId;
|
||||
topicKo: string;
|
||||
phase: {
|
||||
kind: PhaseKind;
|
||||
startedAt: number;
|
||||
endsAt: number | null;
|
||||
/** Describe: 1-based round and the speaker. */
|
||||
round: number;
|
||||
speaker: PlayerId | null;
|
||||
/** Who speaks in this round, in order (describe phase). */
|
||||
turnOrder: PlayerId[];
|
||||
turn: number;
|
||||
readyCount: number;
|
||||
readyNeeded: number;
|
||||
voteRound: 1 | 2 | null;
|
||||
candidates: PlayerId[];
|
||||
votedCount: number;
|
||||
/** Guess phase: the revealed liar, and (choice mode) the words to pick from. */
|
||||
liar: PlayerId | null;
|
||||
choices: string[];
|
||||
};
|
||||
rounds: number;
|
||||
/** Round-1 order. */
|
||||
order: PlayerId[];
|
||||
players: PlayerView[];
|
||||
descriptions: Description[];
|
||||
chat: ChatMessage[];
|
||||
events: PublicEvent[];
|
||||
my: MyView | null;
|
||||
final: LiarFinal | null;
|
||||
}
|
||||
265
packages/games/src/liar/words.ts
Normal file
265
packages/games/src/liar/words.ts
Normal file
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* 라이어 게임 제시어 은행 (docs/games/liar.md §3). 주제마다 단어 15개 이상, 단어마다 컴퓨터가 쓸 설명 문장 4개 이상.
|
||||
*
|
||||
* - `hints`: 애매하지만 시민끼리는 알아들을 만한 한 문장. 앞쪽일수록 덜 구체적이에요(똑똑한 컴퓨터는 앞에서부터 써요).
|
||||
* 단어 자체(띄어쓰기 무시)는 절대 들어가지 않아요(테스트로 확인).
|
||||
* - `aliases`: 라이어가 맞힐 때 정답으로 쳐 주는 다른 표기(핸드폰/휴대폰 등).
|
||||
* - 주제의 `generic`: 그 주제 어디에나 맞는 무난한 말. 아직 아무 설명도 못 들은 라이어 컴퓨터가 써요.
|
||||
* 한 글자 단어(배, 귤, 컵 …)는 넣지 않아요: "제시어를 직접 말하면 안 돼요" 검사가 다른 말까지 막아 버려서요.
|
||||
*/
|
||||
import type { TopicId } from './types';
|
||||
|
||||
export interface LiarWord {
|
||||
word: string;
|
||||
aliases?: string[];
|
||||
hints: string[];
|
||||
}
|
||||
|
||||
export interface LiarTopic {
|
||||
id: TopicId;
|
||||
ko: string;
|
||||
generic: string[];
|
||||
words: LiarWord[];
|
||||
}
|
||||
|
||||
const w = (word: string, hints: string[], aliases?: string[]): LiarWord => (aliases ? { word, hints, aliases } : { word, hints });
|
||||
|
||||
export const TOPICS: readonly LiarTopic[] = [
|
||||
{
|
||||
id: 'fruit',
|
||||
ko: '과일',
|
||||
generic: ['저는 좋아하는 편이에요', '마트에서 쉽게 볼 수 있어요', '달콤한 맛이 나요', '껍질이 있어요', '제철에 먹으면 더 맛있어요'],
|
||||
words: [
|
||||
w('수박', ['여름이면 생각나요', '겉이랑 속 색깔이 완전히 달라요', '씨를 뱉으면서 먹어요', '혼자 다 먹기엔 너무 커요', '두드려 보고 골라요']),
|
||||
w('사과', ['아침에 먹으면 좋다고 해요', '껍질째 먹기도 해요', '빨간 것도 있고 초록인 것도 있어요', '잼이나 주스로도 많이 만들어요', '깎다가 껍질이 길게 이어지면 기분 좋아요']),
|
||||
w('바나나', ['손으로 쉽게 껍질을 벗겨요', '시간이 지나면 갈색 점이 생겨요', '원숭이가 좋아한다고 하죠', '길쭉하게 휘어 있어요', '송이째로 팔아요']),
|
||||
w('딸기', ['겨울부터 봄까지 많이 나와요', '케이크 위에 자주 올라가요', '겉에 작은 씨가 콕콕 박혀 있어요', '우유랑 같이 갈아 먹어요', '빨갛고 작아요']),
|
||||
w('포도', ['알이 동글동글 모여 있어요', '한 알씩 떼어 먹어요', '보라색이 많아요', '주스나 와인으로 만들어요', '씨 없는 것도 있어요']),
|
||||
w('복숭아', ['여름에 나오고 아주 물러요', '겉에 털이 살짝 있어요', '분홍빛이 돌아요', '통조림으로도 먹어요', '알레르기가 있는 사람도 있어요']),
|
||||
w('오렌지', ['주스로 많이 마셔요', '비타민이 많아요', '껍질이 두꺼워서 까기 조금 힘들어요', '동그랗고 새콤달콤해요', '외국에서 많이 들어와요']),
|
||||
w('참외', ['여름에 많이 먹어요', '노란 겉에 하얀 줄이 있어요', '속에 씨가 가득해요', '성주가 유명해요', '아삭아삭 씹혀요']),
|
||||
w('파인애플', ['겉이 울퉁불퉁하고 따가워요', '머리에 뾰족한 잎이 있어요', '먹으면 혀가 따끔할 때가 있어요', '피자 위에 올리면 싸움이 나요', '더운 나라에서 자라요']),
|
||||
w('망고', ['노랗고 아주 달아요', '더운 나라에서 많이 와요', '가운데 납작하고 큰 씨가 있어요', '빙수에 많이 올려요', '말린 것도 간식으로 팔아요']),
|
||||
w('체리', ['꼭지가 길게 달려 있어요', '작고 빨개서 장식으로 많이 써요', '그림에서는 보통 두 개씩 붙어 있어요', '씨를 뱉어야 해요', '조금 비싼 편이에요']),
|
||||
w('레몬', ['엄청 시어요', '그냥 먹기보다는 즙을 짜서 써요', '노랗고 타원형이에요', '차나 음료에 한 조각 넣어요', '생선 요리에 뿌려요']),
|
||||
w('키위', ['겉이 갈색이고 털이 있어요', '반으로 자르면 속이 초록색이에요', '숟가락으로 떠먹기도 해요', '새 이름이랑 같아요', '뉴질랜드가 유명해요']),
|
||||
w('블루베리', ['아주 작은 알갱이예요', '눈에 좋다고 해요', '요거트에 넣어 먹어요', '파란빛이 도는 보라색이에요', '머핀에 콕콕 박혀 있어요']),
|
||||
w('자두', ['새콤해서 침이 고여요', '여름 과일이에요', '빨갛거나 보랏빛이에요', '말린 것도 있어요', '한 입 크기예요']),
|
||||
w('멜론', ['겉에 그물 무늬가 있어요', '아이스크림 맛으로도 유명해요', '비싼 선물용도 있어요', '연두색 속살이 달아요', '반으로 갈라 씨를 긁어내요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'animal',
|
||||
ko: '동물',
|
||||
generic: ['동물원에서 볼 수 있어요', '귀여운 편이에요', '먹이를 잘 먹어요', '사진 찍으면 예쁘게 나와요', '아이들이 좋아해요'],
|
||||
words: [
|
||||
w('고양이', ['혼자서도 잘 지내요', '높은 곳을 좋아해요', '상자만 보면 들어가요', '밤에 눈이 빛나요', '혀로 털을 자주 골라요'], ['냥이']),
|
||||
w('강아지', ['산책을 정말 좋아해요', '꼬리를 흔들어요', '주인이 오면 반겨요', '사람을 잘 따라요', '집을 잘 지켜요'], ['멍멍이']),
|
||||
w('코끼리', ['정말 커요', '코가 손 역할을 해요', '귀가 부채처럼 커요', '기억력이 좋다고 해요', '상아가 있어요']),
|
||||
w('기린', ['목이 엄청 길어요', '높은 나뭇잎을 먹어요', '점박이 무늬가 있어요', '서서 자기도 해요', '혀가 길고 까매요']),
|
||||
w('사자', ['동물의 왕이라고 불려요', '수컷은 갈기가 있어요', '무리 지어 살아요', '초원에서 사냥해요', '어흥 하고 울어요']),
|
||||
w('호랑이', ['줄무늬가 멋있어요', '옛이야기에 자주 나와요', '곶감을 무서워했다는 이야기가 있어요', '산에 사는 큰 고양이과예요', '올림픽 마스코트였던 적이 있어요']),
|
||||
w('토끼', ['귀가 길어요', '깡충깡충 뛰어요', '당근을 좋아한다고 하죠', '달에서 떡방아를 찧는대요', '앞니가 계속 자라요']),
|
||||
w('펭귄', ['날개가 있지만 못 날아요', '추운 곳에 살아요', '뒤뚱뒤뚱 걸어요', '턱시도를 입은 것 같아요', '물속에서는 엄청 빨라요']),
|
||||
w('원숭이', ['나무를 잘 타요', '흉내를 잘 내요', '바나나 하면 떠올라요', '엉덩이가 빨간 것도 있어요', '사람이랑 꽤 닮았어요']),
|
||||
w('돌고래', ['물속에 살지만 숨은 밖에서 쉬어요', '똑똑하기로 유명해요', '쇼에서 점프를 해요', '초음파로 대화해요', '웃는 얼굴처럼 보여요']),
|
||||
w('거북이', ['아주 느려요', '등에 집을 지고 다녀요', '오래 살아요', '토끼랑 경주했어요', '위험하면 머리를 쏙 넣어요'], ['거북']),
|
||||
w('판다', ['흑백이에요', '대나무를 먹어요', '눈 주위가 까매요', '중국에서 왔어요', '데굴데굴 구르는 게 귀여워요'], ['팬더']),
|
||||
w('다람쥐', ['볼에 먹이를 넣어요', '도토리를 모아요', '꼬리가 복슬복슬해요', '작고 재빨라요', '쳇바퀴를 돌려요']),
|
||||
w('캥거루', ['배에 주머니가 있어요', '뒷다리로 껑충 뛰어요', '호주에 살아요', '권투를 한다는 이야기가 있어요', '꼬리로 몸을 받쳐요']),
|
||||
w('하마', ['입이 엄청 커요', '물속에 오래 있어요', '덩치가 크고 동글동글해요', '생각보다 무서운 동물이래요', '아프리카 강에 살아요']),
|
||||
w('낙타', ['등에 혹이 있어요', '사막에 살아요', '물 없이 오래 버텨요', '사람을 태우고 다녀요', '속눈썹이 길어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'job',
|
||||
ko: '직업',
|
||||
generic: ['일하는 사람이에요', '꼭 필요한 일이에요', '힘들지만 보람 있대요', '주변에서 볼 수 있어요', '어릴 때 꿈이었던 사람도 많아요'],
|
||||
words: [
|
||||
w('의사', ['아플 때 만나요', '하얀 가운을 입어요', '청진기를 써요', '공부를 오래 해야 해요', '처방전을 써 줘요']),
|
||||
w('간호사', ['병원에서 일해요', '주사를 놓아 줘요', '밤에도 환자를 돌봐요', '체온이랑 혈압을 재 줘요', '교대 근무를 해요']),
|
||||
w('선생님', ['학교에 가면 만나요', '칠판 앞에 서요', '숙제를 내 줘요', '방학이 있어요', '출석을 불러요'], ['선생', '교사']),
|
||||
w('경찰관', ['제복을 입어요', '도둑을 잡아요', '길을 잃으면 도와줘요', '112에 전화하면 와요', '순찰차를 타요'], ['경찰']),
|
||||
w('소방관', ['불이 나면 달려가요', '빨간 차를 타요', '119에 전화하면 와요', '무거운 장비를 메요', '사람을 구조해요'], ['소방수']),
|
||||
w('요리사', ['주방에서 일해요', '하얀 모자를 써요', '칼을 잘 다뤄요', '맛을 계속 봐요', '메뉴를 만들어요'], ['셰프']),
|
||||
w('가수', ['무대에 서요', '마이크를 들어요', '앨범을 내요', '콘서트를 해요', '목 관리가 중요해요']),
|
||||
w('배우', ['다른 사람인 척해요', '대본을 외워요', '드라마나 영화에 나와요', '우는 연기도 해요', '시상식에서 상을 받아요']),
|
||||
w('화가', ['붓을 써요', '옷에 물감이 묻어요', '전시회를 열어요', '캔버스 앞에 오래 앉아 있어요', '고흐가 유명해요']),
|
||||
w('미용사', ['가위를 들고 일해요', '머리를 만져 줘요', '파마도 해 줘요', '거울 앞에서 일해요', '손님이랑 수다를 떨어요']),
|
||||
w('우체부', ['집집마다 다녀요', '편지를 가져다줘요', '소포도 전해 줘요', '오토바이를 타고 다녀요', '빨간 우체통이랑 관계있어요'], ['집배원']),
|
||||
w('농부', ['밭에서 일해요', '새벽부터 일어나요', '날씨를 많이 신경 써요', '쌀이나 채소를 길러요', '가을에 제일 바빠요']),
|
||||
w('조종사', ['하늘에서 일해요', '공항으로 출근해요', '제복 모자에 날개 모양 배지가 있어요', '안내 방송을 해요', '시력이 좋아야 해요'], ['파일럿', '기장']),
|
||||
w('과학자', ['실험실에서 일해요', '하얀 가운에 보안경을 써요', '연구를 오래 해요', '노벨상을 받기도 해요', '가설을 세우고 확인해요']),
|
||||
w('택배기사', ['상자를 날라요', '문 앞에 두고 가요', '하루에 엄청 많은 집을 가요', '트럭을 몰아요', '명절 전에 제일 바빠요'], ['택배원']),
|
||||
w('프로그래머', ['컴퓨터 앞에 오래 앉아 있어요', '버그를 잡아요', '키보드를 많이 쳐요', '앱을 만들어요', '밤샘을 하기도 해요'], ['개발자']),
|
||||
w('기자', ['뉴스를 써요', '현장에 마이크를 들고 가요', '질문을 많이 해요', '사건이 생기면 바로 달려가요', '취재 수첩이 있어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'food',
|
||||
ko: '음식',
|
||||
generic: ['맛있어요', '배고플 때 생각나요', '친구랑 같이 먹으면 좋아요', '집에서도 만들 수 있어요', '사람마다 좋아하는 맛이 달라요'],
|
||||
words: [
|
||||
w('김치', ['매일 밥상에 올라와요', '겨울에 많이 담가요', '익을수록 시어져요', '빨간 것도 있고 하얀 것도 있어요', '배추로 많이 만들어요']),
|
||||
w('라면', ['끓는 물에 넣어요', '밤에 먹으면 얼굴이 부어요', '꼬불꼬불해요', '봉지에 들어 있어요', '계란을 넣기도 해요']),
|
||||
w('떡볶이', ['학교 앞에서 많이 팔아요', '매콤달콤해요', '어묵이랑 같이 먹어요', '쫄깃쫄깃해요', '빨간 국물이에요']),
|
||||
w('피자', ['배달로 많이 시켜요', '치즈가 쭉 늘어나요', '여러 조각으로 잘라요', '이탈리아에서 왔어요', '끝 부분 빵을 남기는 사람도 있어요']),
|
||||
w('치킨', ['양념이냐 후라이드냐 고민해요', '바삭바삭해요', '다리가 인기 많아요', '맥주랑 같이 먹어요', '무를 같이 줘요'], ['통닭']),
|
||||
w('햄버거', ['패스트푸드예요', '감자튀김이랑 세트예요', '빵 사이에 고기가 있어요', '높이 쌓을수록 먹기 힘들어요', '콜라랑 잘 어울려요']),
|
||||
w('김밥', ['소풍 갈 때 싸 가요', '둥글게 썰어요', '꼬다리가 맛있어요', '겉은 까맣고 속은 알록달록해요', '돌돌 말아요']),
|
||||
w('비빔밥', ['여러 나물이 들어가요', '고추장을 넣어 섞어요', '계란 하나 올리면 좋아요', '돌솥에 담기도 해요', '전주가 유명해요']),
|
||||
w('불고기', ['달달한 간장 양념이에요', '외국인이 좋아해요', '얇게 썬 고기예요', '버섯이랑 같이 볶아요', '불판에 국물이 자작해요']),
|
||||
w('짜장면', ['중국집에서 시켜요', '이사하는 날 먹어요', '까만 소스예요', '단무지랑 같이 나와요', '입가에 묻기 쉬워요'], ['자장면']),
|
||||
w('삼겹살', ['불판에 구워요', '상추에 싸 먹어요', '기름이 많아요', '층층이 줄이 있어요', '회식 메뉴로 많이 나와요']),
|
||||
w('초밥', ['밥 위에 생선이 올라가요', '회전하는 가게가 있어요', '와사비를 넣어요', '간장에 살짝 찍어요', '한 입에 쏙 들어가요']),
|
||||
w('냉면', ['여름에 시원하게 먹어요', '면을 가위로 잘라요', '물이랑 비빔이 있어요', '고기 먹고 후식으로 먹어요', '식초랑 겨자를 넣어요']),
|
||||
w('떡국', ['설날 아침에 먹어요', '먹으면 나이를 한 살 먹는대요', '하얀 떡을 동그랗게 썰어요', '국물이 뽀얘요', '지단을 올려요']),
|
||||
w('아이스크림', ['차갑고 달아요', '콘이나 컵에 담아요', '빨리 안 먹으면 녹아요', '여름에 많이 먹어요', '맛을 고르는 게 고민돼요']),
|
||||
w('스파게티', ['포크로 돌돌 말아요', '토마토나 크림 소스예요', '이탈리아 음식이에요', '면이 길어요', '면을 벽에 던져서 익었는지 본대요'], ['파스타']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'place',
|
||||
ko: '장소',
|
||||
generic: ['사람들이 많이 가요', '가 본 적 있어요', '주말에 붐벼요', '우리 동네에도 있어요', '가면 기분이 달라져요'],
|
||||
words: [
|
||||
w('학교', ['종이 울려요', '운동장이 있어요', '급식을 먹어요', '친구를 매일 만나요', '시험이 있어요']),
|
||||
w('병원', ['소독약 냄새가 나요', '번호표 받고 기다려요', '아플 때 가요', '하얀 침대가 있어요', '면회 시간이 정해져 있어요']),
|
||||
w('공항', ['큰 가방을 끌고 가요', '여권이 필요해요', '출국이랑 입국이 있어요', '면세점이 있어요', '하늘로 떠나는 곳이에요']),
|
||||
w('도서관', ['조용히 해야 해요', '빌렸다가 돌려줘요', '반납 기한이 있어요', '공부하는 사람이 많아요', '책장이 줄줄이 있어요']),
|
||||
w('영화관', ['불이 꺼지고 어두워요', '팝콘을 사요', '화면이 아주 커요', '휴대폰을 꺼 달라고 해요', '좌석을 미리 골라요'], ['극장']),
|
||||
w('놀이공원', ['줄을 오래 서요', '롤러코스터가 있어요', '머리띠를 사서 써요', '퍼레이드를 해요', '자유이용권을 사요'], ['놀이동산']),
|
||||
w('바다', ['파도가 쳐요', '물이 짜요', '모래사장이 있어요', '여름 휴가로 많이 가요', '갈매기가 날아다녀요']),
|
||||
w('수영장', ['수영모를 써야 해요', '소독약 냄새가 나요', '튜브를 끼고 놀아요', '깊은 곳이랑 얕은 곳이 있어요', '들어가기 전에 샤워해요']),
|
||||
w('은행', ['번호표를 뽑아요', '통장을 만들어요', '창구에서 일을 봐요', '현금인출기가 있어요', '오후 네 시면 문을 닫아요']),
|
||||
w('편의점', ['24시간 열어요', '삼각김밥을 팔아요', '동네마다 있어요', '아르바이트생이 많아요', '1+1 행사를 해요']),
|
||||
w('경찰서', ['신고하러 가요', '순찰차가 서 있어요', '분실물을 찾으러 가기도 해요', '유치장이 있어요', '제복 입은 사람이 많아요'], ['파출소']),
|
||||
w('동물원', ['먹이를 주면 안 돼요', '사육사가 있어요', '우리 안을 구경해요', '소풍으로 많이 가요', '냄새가 좀 나요']),
|
||||
w('찜질방', ['양머리 수건을 써요', '식혜랑 구운 계란을 먹어요', '아주 뜨거운 방이 있어요', '바닥에 누워서 쉬어요', '같은 옷을 입고 다녀요']),
|
||||
w('노래방', ['마이크를 잡아요', '점수가 나와요', '탬버린을 흔들어요', '시간이 추가되면 기뻐요', '방마다 화면이 있어요']),
|
||||
w('캠핑장', ['텐트를 쳐요', '모닥불을 피워요', '밤에 별이 잘 보여요', '고기를 구워 먹어요', '벌레가 많아요']),
|
||||
w('박물관', ['옛날 물건이 많아요', '유리장 안에 있어요', '만지지 말라고 해요', '견학으로 많이 가요', '해설을 들을 수 있어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'sport',
|
||||
ko: '운동',
|
||||
generic: ['몸을 움직여요', '하고 나면 땀이 나요', '친구들이랑 하면 재밌어요', '올림픽에서도 봤어요', '규칙을 알아야 해요'],
|
||||
words: [
|
||||
w('축구', ['공을 발로 차요', '월드컵이 있어요', '골키퍼만 손을 써요', '한 팀에 열한 명이에요', '전반전과 후반전이 있어요']),
|
||||
w('야구', ['방망이를 휘둘러요', '홈런이 나오면 신나요', '글러브를 껴요', '9회까지 해요', '삼진 아웃이 있어요']),
|
||||
w('농구', ['키 큰 사람이 유리해요', '공을 튀기면서 달려요', '골대가 높이 달려 있어요', '3점슛이 있어요', '덩크를 하면 멋있어요']),
|
||||
w('배구', ['네트 너머로 넘겨요', '공이 바닥에 떨어지면 안 돼요', '스파이크를 때려요', '리베로가 있어요', '한 팀에 여섯 명이에요']),
|
||||
w('수영', ['물속에서 해요', '자유형이랑 평영이 있어요', '수경을 써요', '레인을 따라가요', '숨 쉬는 게 어려워요']),
|
||||
w('탁구', ['작고 가벼운 공을 써요', '테이블 위에서 해요', '핑퐁이라고도 해요', '라켓이 작아요', '공이 통통 튀어요']),
|
||||
w('테니스', ['노란 공을 써요', '점수를 러브라고 불러요', '잔디 코트도 있어요', '서브를 세게 넣어요', '라켓 줄이 팽팽해요']),
|
||||
w('볼링', ['무거운 공을 굴려요', '핀을 쓰러뜨려요', '스트라이크가 최고예요', '신발을 빌려 신어요', '손가락 구멍이 세 개예요']),
|
||||
w('골프', ['넓은 잔디에서 해요', '작은 구멍에 넣어요', '적게 칠수록 좋아요', '18홀이 있어요', '채가 여러 개예요']),
|
||||
w('태권도', ['도복을 입어요', '띠 색깔이 바뀌어요', '발차기가 멋있어요', '우리나라 무술이에요', '송판을 깨요']),
|
||||
w('스키', ['눈 위에서 해요', '리프트를 타고 올라가요', '겨울에 해요', '폴을 짚어요', '넘어지면 일어나기 힘들어요']),
|
||||
w('마라톤', ['아주 오래 달려요', '42킬로미터가 넘어요', '중간에 물을 마셔요', '끝까지 가는 게 목표예요', '기록을 재요']),
|
||||
w('줄넘기', ['체육 시간에 해요', '이단뛰기가 있어요', '혼자도 여럿도 할 수 있어요', '발이 걸리면 끝나요', '숫자를 세면서 해요']),
|
||||
w('배드민턴', ['공원에서 많이 해요', '깃털 달린 공을 쳐요', '바람이 불면 힘들어요', '네트를 사이에 두고 쳐요', '라켓이 가벼워요']),
|
||||
w('씨름', ['모래판에서 해요', '샅바를 잡아요', '천하장사가 있어요', '상대를 넘어뜨려요', '명절에 텔레비전에서 해요']),
|
||||
w('스케이트', ['얼음 위에서 타요', '날 달린 신발을 신어요', '빙상장에서 해요', '넘어지기 쉬워요', '빙글빙글 돌기도 해요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'vehicle',
|
||||
ko: '탈것',
|
||||
generic: ['타고 다녀요', '어디 갈 때 써요', '빠른 편이에요', '어릴 때 장난감으로 갖고 놀았어요', '사람을 태워요'],
|
||||
words: [
|
||||
w('자동차', ['바퀴가 네 개예요', '면허가 있어야 해요', '주유소에 들러요', '주차할 곳이 늘 고민이에요', '안전벨트를 매요'], ['승용차']),
|
||||
w('버스', ['정류장에서 기다려요', '번호를 보고 타요', '카드를 찍고 타요', '내릴 때 벨을 눌러요', '손잡이를 잡고 서 있기도 해요']),
|
||||
w('지하철', ['땅속으로 다녀요', '노선마다 색깔이 달라요', '환승을 해요', '출퇴근 시간엔 꽉 차요', '스크린도어가 있어요'], ['전철']),
|
||||
w('기차', ['선로 위를 달려요', '역에서 타요', '창밖 풍경을 보며 가요', '도시 사이를 빠르게 이어 줘요', '칸이 길게 이어져 있어요'], ['열차']),
|
||||
w('비행기', ['날개가 있어요', '구름 위로 가요', '귀가 먹먹해져요', '기내식을 줘요', '창가 자리가 인기예요']),
|
||||
w('유람선', ['물 위를 떠다녀요', '강이나 바다를 구경해요', '갑판에 나가요', '뱃멀미가 날 수 있어요', '밤에 불빛이 예뻐요']),
|
||||
w('자전거', ['페달을 밟아요', '바퀴가 두 개예요', '헬멧을 쓰면 좋아요', '처음엔 보조 바퀴를 달아요', '체인이 빠지면 곤란해요']),
|
||||
w('오토바이', ['헬멧을 꼭 써요', '배달할 때 많이 타요', '두 바퀴인데 엔진이 있어요', '부릉부릉 소리가 커요', '가죽 재킷이랑 어울려요'], ['바이크']),
|
||||
w('택시', ['손을 흔들어서 세워요', '미터기가 돌아가요', '기사님께 목적지를 말해요', '밤늦게 많이 타요', '앱으로 부르기도 해요']),
|
||||
w('헬리콥터', ['프로펠러가 위에 있어요', '제자리에 떠 있을 수 있어요', '옥상에 내려요', '다다다 소리가 나요', '구조할 때 많이 써요'], ['헬기']),
|
||||
w('트럭', ['짐을 많이 실어요', '크고 무거워요', '이사할 때 불러요', '뒤에 짐칸이 있어요', '고속도로에서 많이 봐요']),
|
||||
w('구급차', ['사이렌을 울려요', '아픈 사람을 태워요', '길을 비켜 줘야 해요', '하얀 차에 빨간 줄이 있어요', '병원으로 급히 가요']),
|
||||
w('소방차', ['빨간색이에요', '긴 사다리가 있어요', '물을 뿌려요', '사이렌을 울리며 달려요', '호스가 감겨 있어요']),
|
||||
w('잠수함', ['물속으로 다녀요', '잠망경이 있어요', '군대에서 써요', '창문이 거의 없어요', '물 위로 떠오르기도 해요']),
|
||||
w('로켓', ['우주로 가요', '카운트다운을 해요', '불을 뿜으며 위로 올라가요', '발사대에 세워 둬요', '나로호가 생각나요']),
|
||||
w('킥보드', ['한 발로 밀고 가요', '서서 타요', '전동도 있어요', '공유해서 빌려 타요', '손잡이가 길어요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'thing',
|
||||
ko: '물건',
|
||||
generic: ['집에 하나쯤 있어요', '매일 써요', '잃어버리면 곤란해요', '선물로도 줘요', '가게에서 쉽게 살 수 있어요'],
|
||||
words: [
|
||||
w('우산', ['비 오는 날 꼭 필요해요', '펼치고 접어요', '잃어버리기 쉬워요', '편의점에서 급히 사기도 해요', '바람 불면 뒤집혀요']),
|
||||
w('휴대폰', ['매일 손에 들고 다녀요', '밤마다 충전해요', '알람을 맞춰요', '사진을 찍어요', '화면이 깨지면 속상해요'], ['핸드폰', '스마트폰', '휴대전화']),
|
||||
w('안경', ['코 위에 걸쳐요', '눈이 나쁘면 써요', '김이 서려요', '알이 두 개예요', '닦아도 금방 뿌예져요']),
|
||||
w('시계', ['째깍째깍 소리가 나요', '손목에 차요', '바늘이 돌아가요', '벽에도 걸어요', '건전지가 다 되면 멈춰요']),
|
||||
w('거울', ['나를 비춰 줘요', '화장실에 있어요', '깨지면 위험해요', '왼쪽 오른쪽이 바뀌어 보여요', '마법 이야기에도 나와요']),
|
||||
w('가위', ['종이를 잘라요', '바위 보랑 같이 나와요', '손가락 넣는 구멍이 있어요', '날이 두 개예요', '미술 시간에 써요']),
|
||||
w('연필', ['깎아서 써요', '심이 부러지기도 해요', '시험 볼 때 써요', '노란색이 많아요', '지울 수 있게 써요']),
|
||||
w('지우개', ['틀린 걸 없애 줘요', '쓰면 가루가 나와요', '말랑말랑해요', '쓸수록 작아져요', '필통에 꼭 있어요']),
|
||||
w('칫솔', ['하루 세 번 써요', '치약이랑 짝이에요', '화장실 컵에 꽂아 둬요', '석 달마다 바꾸래요', '솔이 벌어지면 바꿔요']),
|
||||
w('베개', ['잘 때 머리를 대요', '푹신해요', '높이가 맞아야 잘 자요', '수학여행 밤에 던지면서 놀아요', '침대 위에 있어요']),
|
||||
w('냉장고', ['부엌에 있어요', '안이 차가워요', '문 열고 한참 고민해요', '반찬을 넣어 둬요', '자석을 붙여요']),
|
||||
w('텔레비전', ['거실에 있어요', '리모컨으로 켜요', '채널을 돌려요', '드라마를 봐요', '화면이 점점 커져요'], ['티비', 'TV', '텔레비젼']),
|
||||
w('열쇠', ['문을 열어요', '고리에 달아 둬요', '잃어버리면 곤란해요', '자물쇠랑 짝이에요', '요즘은 번호로 많이 바뀌었어요']),
|
||||
w('지갑', ['돈을 넣어요', '카드를 꽂아요', '주머니에 넣고 다녀요', '가죽으로 많이 만들어요', '잃어버리면 정말 곤란해요']),
|
||||
w('장갑', ['겨울에 껴요', '손가락이 다섯 개예요', '한 짝만 잃어버리기 쉬워요', '끼고 눈싸움을 해요', '설거지할 때도 껴요']),
|
||||
w('모자', ['머리 위에 써요', '햇빛을 가려 줘요', '챙이 있어요', '벗으면 머리가 눌려 있어요', '야구장에서 많이 써요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'country',
|
||||
ko: '나라',
|
||||
generic: ['비행기를 타고 가야 해요', '꼭 한번 가 보고 싶어요', '유명한 음식이 있어요', '사람이 많이 살아요', '뉴스에서 자주 봐요'],
|
||||
words: [
|
||||
w('미국', ['자유의 여신상이 있어요', '달러를 써요', '할리우드가 있어요', '땅이 아주 넓어요', '햄버거가 생각나요'], ['아메리카']),
|
||||
w('중국', ['만리장성이 있어요', '인구가 아주 많아요', '빨간색을 좋아한대요', '판다가 살아요', '베이징이 수도예요']),
|
||||
w('일본', ['가까운 섬나라예요', '벚꽃이 유명해요', '초밥이 생각나요', '후지산이 있어요', '온천이 많아요']),
|
||||
w('프랑스', ['에펠탑이 있어요', '바게트 빵이 유명해요', '파리가 수도예요', '패션의 나라예요', '와인이 유명해요']),
|
||||
w('영국', ['홍차를 많이 마셔요', '이층 버스가 있어요', '런던이 수도예요', '여왕이 유명했어요', '시계탑이 있어요']),
|
||||
w('이탈리아', ['파스타가 유명해요', '지도에서 장화처럼 생겼어요', '로마가 수도예요', '콜로세움이 있어요', '피사의 사탑이 있어요']),
|
||||
w('브라질', ['축구를 엄청 잘해요', '삼바 축제가 있어요', '아마존 숲이 있어요', '남미에 있어요', '커피가 많이 나요']),
|
||||
w('호주', ['캥거루가 살아요', '코알라가 있어요', '오페라하우스가 있어요', '여름에 크리스마스를 보내요', '섬 하나가 대륙이에요']),
|
||||
w('인도', ['카레가 유명해요', '타지마할이 있어요', '사람이 아주 많아요', '요가가 시작된 곳이에요', '소를 아낀대요']),
|
||||
w('이집트', ['피라미드가 있어요', '사막이 넓어요', '미라가 생각나요', '나일강이 흘러요', '스핑크스가 있어요']),
|
||||
w('캐나다', ['단풍잎이 국기에 있어요', '메이플 시럽이 유명해요', '겨울이 아주 추워요', '미국 바로 위에 있어요', '나이아가라 폭포가 있어요']),
|
||||
w('러시아', ['땅이 세계에서 제일 넓어요', '아주 추워요', '모스크바가 수도예요', '인형 안에 인형이 들어 있어요', '양파 모양 지붕이 있어요']),
|
||||
w('독일', ['소시지랑 맥주가 유명해요', '자동차를 잘 만들어요', '베를린이 수도예요', '축구를 잘해요', '맥주 축제가 있어요']),
|
||||
w('스페인', ['투우가 유명했어요', '플라멩코 춤이 있어요', '파에야를 먹어요', '마드리드가 수도예요', '축구 팀들이 유명해요']),
|
||||
w('멕시코', ['타코를 먹어요', '챙 넓은 모자가 생각나요', '선인장이 많아요', '매운 음식을 좋아해요', '미국 바로 아래에 있어요']),
|
||||
w('태국', ['코끼리를 아껴요', '똠얌꿍이 유명해요', '방콕이 수도예요', '따뜻한 휴양지가 많아요', '쌀국수 같은 면 요리가 많아요']),
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fairy',
|
||||
ko: '동화 주인공',
|
||||
generic: ['어릴 때 읽었어요', '아주 유명한 이야기예요', '그림책으로 봤어요', '교훈이 있는 이야기예요', '엄마가 읽어 줬어요'],
|
||||
words: [
|
||||
w('신데렐라', ['밤 열두 시가 되면 큰일 나요', '유리 구두를 잃어버려요', '호박이 마차가 돼요', '새엄마랑 언니들이 괴롭혀요', '요정 할머니가 도와줘요']),
|
||||
w('백설공주', ['피부가 아주 하얘요', '독이 든 사과를 먹어요', '일곱 난쟁이랑 살아요', '왕비가 거울에게 물어봐요', '숲으로 도망쳐요']),
|
||||
w('피노키오', ['거짓말을 하면 코가 길어져요', '나무로 만든 인형이에요', '제페토 할아버지가 만들었어요', '고래 뱃속에 들어가요', '진짜 아이가 되고 싶어 해요']),
|
||||
w('피터팬', ['어른이 되지 않아요', '하늘을 날아다녀요', '후크 선장이랑 싸워요', '작은 요정 친구가 있어요', '네버랜드에 살아요']),
|
||||
w('인어공주', ['바닷속에 살아요', '목소리를 잃어요', '다리가 생겨요', '마지막에 물거품이 돼요', '왕자를 구해 줘요']),
|
||||
w('라푼젤', ['머리카락이 엄청 길어요', '높은 탑에 갇혀 있어요', '머리카락을 내려 줘요', '마녀가 키웠어요', '창문으로 밖을 내다봐요']),
|
||||
w('앨리스', ['토끼를 따라가요', '이상한 나라에 가요', '작아졌다 커졌다 해요', '카드 여왕을 만나요', '모자 장수랑 차를 마셔요']),
|
||||
w('빨간모자', ['할머니 댁에 심부름을 가요', '숲속에서 늑대를 만나요', '할머니 귀가 왜 이렇게 크냐고 물어요', '사냥꾼이 구해 줘요', '바구니를 들고 가요'], ['빨간망토', '빨간두건']),
|
||||
w('흥부', ['착한 동생이에요', '제비 다리를 고쳐 줘요', '박을 타니 보물이 나와요', '식구가 아주 많아요', '형한테 쫓겨나요']),
|
||||
w('놀부', ['욕심이 많은 형이에요', '제비 다리를 일부러 부러뜨려요', '박에서 도깨비가 나와요', '동생을 쫓아내요', '나중에 반성해요']),
|
||||
w('심청이', ['아버지 눈을 뜨게 하고 싶어 해요', '바다에 몸을 던져요', '연꽃을 타고 돌아와요', '효녀로 유명해요', '공양미 삼백 석이 나와요'], ['심청']),
|
||||
w('콩쥐', ['밑 빠진 독에 물을 부어야 해요', '두꺼비가 도와줘요', '새엄마가 괴롭혀요', '꽃신을 잃어버려요', '이름이 곡식이랑 비슷한 자매가 있어요']),
|
||||
w('나무꾼', ['산에서 나무를 해요', '사슴을 숨겨 줘요', '날개옷을 감춰요', '하늘로 올라간 가족을 그리워해요', '연못에 도끼를 빠뜨린 이야기도 있어요']),
|
||||
w('별주부', ['용왕님을 위해 육지로 가요', '토끼의 간을 구하러 가요', '바닷속에서 왔어요', '토끼에게 속아요', '등껍질이 있어요'], ['자라']),
|
||||
w('혹부리영감', ['얼굴에 커다란 혹이 있어요', '도깨비들 앞에서 노래해요', '노래 주머니라고 속여요', '욕심쟁이 이웃은 혹을 하나 더 받아요', '산속 빈집에서 밤을 보내요'], ['혹부리']),
|
||||
w('알라딘', ['요술 램프를 문질러요', '소원을 세 가지 들어줘요', '하늘을 나는 양탄자를 타요', '원숭이 친구가 있어요', '사막 나라 이야기예요']),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const topicById = (id: TopicId): LiarTopic => TOPICS.find((t) => t.id === id)!;
|
||||
|
||||
export function wordEntry(topic: TopicId, word: string): LiarWord | undefined {
|
||||
return topicById(topic).words.find((x) => x.word === word);
|
||||
}
|
||||
@@ -24,7 +24,8 @@ export function botProfile(id: string): PublicUser | null {
|
||||
/**
|
||||
* Games that offer computer players. Real-time and drawing games (도블, 할리갈리, 그림 맞히기) don't: a bot there is
|
||||
* either unbeatable or meaningless. 마피아 has talking computers (2026-10-11). 사과 게임 is a race where everyone solves
|
||||
* their own copy of the board, so a computer simply races too at its level's speed (2026-10-12).
|
||||
* their own copy of the board, so a computer simply races too at its level's speed (2026-10-12). 라이어 게임 has
|
||||
* talking computers like 마피아 (2026-10-12).
|
||||
*/
|
||||
export const BOT_GAMES: readonly string[] = [
|
||||
'omok',
|
||||
@@ -55,18 +56,19 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'clue',
|
||||
'connect-four',
|
||||
'uno',
|
||||
'liar',
|
||||
];
|
||||
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */
|
||||
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6 };
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */
|
||||
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6, liar: 5 };
|
||||
|
||||
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
|
||||
|
||||
/**
|
||||
* Games where computers must talk to play at all (마피아 토론): their computers always speak, whatever the room's
|
||||
* Games where computers must talk to play at all (마피아 토론, 라이어 게임 설명·토론): their computers always speak, whatever the room's
|
||||
* "컴퓨터 채팅" setting says. In every other game the computers' small talk is off unless the host turns it on.
|
||||
*/
|
||||
export const BOT_CHAT_REQUIRED: readonly string[] = ['mafia'];
|
||||
export const BOT_CHAT_REQUIRED: readonly string[] = ['mafia', 'liar'];
|
||||
|
||||
export const botChatRequired = (gameId: string): boolean => BOT_CHAT_REQUIRED.includes(gameId);
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
|
||||
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
|
||||
{ id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true },
|
||||
{ id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true },
|
||||
];
|
||||
|
||||
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);
|
||||
|
||||
Reference in New Issue
Block a user