새 게임 라이어 게임: 규칙 엔진·말하는 컴퓨터·화면·도움말·문서·E2E
- packages/games/src/liar: 주제 10개 제시어 은행, 설명(두 번째 바퀴 거꾸로)·자유 토론·투표(동점 재투표 한 번, 또 동점이면 라이어 승리)·라이어 정답 맞히기(띄어쓰기·다른 표기 무시), 바보 모드 - 컴퓨터: 마피아처럼 live 전략, 레벨 1~60을 LiveBotInput.level 로 받음(서버 BotDriver 가 넘김), BOT_CHAT_REQUIRED 에 추가 - 웹: 꾹 누르는 제시어 카드, 설명 기록·토론 채팅·투표 화면, 30초 요약, [?] 도움말 - 문서 docs/games/liar.md, 등록(GAMES·CATALOG·BOT_GAMES·registry·아이콘), 서버 방 테스트, E2E(거절 알림이 저절로 사라지는지 확인 포함) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,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'] },
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user