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

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

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

View File

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

View File

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

View File

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