diff --git a/apps/server/src/rooms/liar.room.test.ts b/apps/server/src/rooms/liar.room.test.ts index 7f06f7d..2a6ea25 100644 --- a/apps/server/src/rooms/liar.room.test.ts +++ b/apps/server/src/rooms/liar.room.test.ts @@ -114,4 +114,17 @@ describe('라이어 게임 room flow with computers', () => { expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true); expect(logs).toEqual([]); }); + + test('모든 시간 무제한: 컴퓨터는 알아서 하고, 연결이 끊긴 사람은 유예 시간 뒤 넘겨져 끝까지 가요', () => { + const { room, conn, run, state, logs } = practice(); + const none = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null }; + expect(room.configure('A', { options: { ...(room.config.options as object), ...none } })).toBeNull(); + room.start('A'); + room.disconnect(conn); + run(); + expect(room.game!.finished).toBe(true); + expect(state().options.describeSeconds).toBeNull(); + expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true); + expect(logs).toEqual([]); + }); }); diff --git a/apps/web/src/games/liar/help.test.ts b/apps/web/src/games/liar/help.test.ts index ac64e99..5b1c590 100644 --- a/apps/web/src/games/liar/help.test.ts +++ b/apps/web/src/games/liar/help.test.ts @@ -47,3 +47,10 @@ test('라이어 게임: 설명 차례, 투표, 정답 맞히기', () => { expect(helpNow(view(s, 'D'), 'D', users)).toContain('[정답!]'); expect(helpNow(view(s, 'A'), 'A', users)).toContain(`${users.D!.nickname}님이 라이어였어요`); }); + +test('라이어 게임: 시간 무제한이면 "시간 제한은 없어요" 안내', () => { + const s = tick(game({ describeSeconds: null, discussionSeconds: null })); + const t = helpNow(view(s, 'A'), 'A', users); + expect(t).toContain('시간 제한은 없어요'); + expect(t).not.toContain('시간이 지나면 넘어가요'); +}); diff --git a/apps/web/src/games/liar/help.ts b/apps/web/src/games/liar/help.ts index 8fa4066..682aa2e 100644 --- a/apps/web/src/games/liar/help.ts +++ b/apps/web/src/games/liar/help.ts @@ -35,29 +35,30 @@ export function helpNow(v: LiarView, me: string | null, players: Record p.id === me)?.left) return '게임에서 나갔어요. 남은 사람들이 계속해요.'; const liar = my.role === 'liar'; const mine = liar ? `나는 라이어예요. 제시어는 모르고 주제만 알아요.` : `내 제시어는 위의 [내 제시어] 카드를 꾹 누르면 보여요.`; + const unl = ph.endsAt === null; 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} 시간이 지나면 넘어가요.`; + return `${topic} 내 차례예요! 오른쪽 칸에 한 문장(80자까지)으로 설명하고 [말하기]를 눌러요.\n${tip} ${unl ? '시간 제한은 없어요.' : '시간이 지나면 넘어가요.'}`; } 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}).`; + return `${topic} 자유 토론 시간이에요. [토론 채팅]으로 누가 라이어 같은지 이야기해요. 제시어는 직접 말할 수 없어요.\n${unl ? '토론 시간은 무제한이에요. ' : ''}다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 투표로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).`; case 'vote': { if (!my.voteTargets.length) return `${topic} 동점인 사람끼리 다시 투표하고 있어요. 결과를 기다려 주세요.`; - const now = my.vote ? `지금 ${josa(n(my.vote), ['을', '를'])} 골랐어요. 시간 안에는 바꿀 수 있어요.` : '아직 고르지 않았어요.'; + const now = my.vote ? `지금 ${josa(n(my.vote), ['을', '를'])} 골랐어요. ${unl ? '모두 투표하기 전에는' : '시간 안에는'} 바꿀 수 있어요.` : '아직 고르지 않았어요.'; 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} 들켰어요! 제시어를 맞히면 그래도 라이어가 이겨요. ${how} 기회는 한 번이에요.${unl ? ' 시간 제한은 없어요.' : ''}`; } return `${topic} ${ph.liar ? josa(n(ph.liar), ['이', '가']) : '지목된 사람이'} 라이어였어요! 라이어가 제시어를 맞히는 중이에요. 못 맞히면 시민이 이겨요.`; } diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index 92306fd..a0512f7 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -11,7 +11,7 @@ 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 { haptic, sfx, sounds, tone } from '../../lib/feedback'; import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage'; import { useStickToBottom } from '../../lib/useStickToBottom'; import type { BoardProps, GameUI, OptionsProps } from '../types'; @@ -126,6 +126,12 @@ button.lg-tile { cursor: pointer; } .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; } } +.lg-unl { font-size: 1.6rem; } +.lg-unl small { display: block; font-size: .7rem; font-weight: 800; } +.lg-tile[aria-pressed='true'] { animation: lg-pick .28s ease-out; } +.lg-tile.accused { animation: anim-shake .45s ease both; } +@keyframes lg-pick { 50% { transform: scale(1.07); } } +.lg-card[data-show='true'] { animation: anim-flip .35s ease both; } @keyframes lg-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } } @media (max-width: 1099px) { .lg { height: auto; } @@ -144,14 +150,20 @@ button.lg-tile { cursor: pointer; } .lg-msgs { min-height: 160px; max-height: 300px; } } @media (prefers-reduced-motion: reduce) { - .lg-news, .lg-bar .tr i { animation: none; } + .lg-news, .lg-bar .tr i, .lg-tile[aria-pressed='true'], .lg-tile.accused, .lg-card[data-show='true'] { animation: none; } } `; // ---------------------------------------------------------------- small parts -function Clock({ endsAt }: { endsAt: number | null }) { +function Clock({ endsAt, unlimited }: { endsAt: number | null; unlimited: boolean }) { const now = useServerNow(500); + if (unlimited) + return ( + + ∞무제한 + + ); 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}`; @@ -224,7 +236,7 @@ function eventText(e: PublicEvent, players: Record): string case 'accused': return e.liar ? `${josa(n(e.p), ['은', '는'])} 라이어가 맞아요!` : `${josa(n(e.p), ['은', '는'])} 라이어가 아니었어요`; case 'guess': - return e.text === null ? '라이어가 시간 안에 답하지 못했어요' : `라이어의 답: "${e.text}" — ${e.correct ? '정답!' : '틀렸어요'}`; + return e.text === null ? '라이어가 답하지 못했어요' : `라이어의 답: "${e.text}" — ${e.correct ? '정답!' : '틀렸어요'}`; case 'left': return `${josa(n(e.p), ['이', '가'])} 게임을 나갔어요`; case 'end': @@ -321,8 +333,8 @@ function Players({ v, players, me, pick, pending }: { v: LiarView; players: Reco {id === me ? ' (나)' : ''} {speaking && 말하는 중} - {ph.kind === 'vote' && p.voted && 투표함} - {p.liar === true && 🤥 라이어} + {ph.kind === 'vote' && p.voted && 투표함} + {p.liar === true && 🤥 라이어} {p.left && 나감} ); @@ -371,9 +383,9 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record d.round === r) .map((d) => ( -
  • +
  • {nick(players, d.from)} - {d.text ?? '(시간이 지나 넘어갔어요)'} + {d.text ?? (v.options.describeSeconds === null ? '(자리를 비워 넘어갔어요)' : '(시간이 지나 넘어갔어요)')}
  • ))} {v.phase.kind === 'describe' && v.phase.round === r && v.phase.speaker && ( @@ -524,7 +536,10 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor body = my.canDescribe ? ( <>

    내 차례예요! 한 문장으로 설명해 주세요

    - {my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'} + + {my.role === 'liar' ? '제시어를 모르니 앞사람 말을 잘 듣고 아는 척해요.' : '제시어는 직접 말할 수 없어요. 너무 쉬우면 라이어가 알아채요.'} + {ph.endsAt === null ? ' 시간 제한은 없어요.' : ''} + ) : ( @@ -546,7 +561,7 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor {my.ready ? `기다리는 중 (${ph.readyCount}/${ph.readyNeeded})` : `토론 끝내기 (${ph.readyCount}/${ph.readyNeeded})`} - 모두 누르면 바로 투표로 넘어가요. + {ph.endsAt === null ? '토론 시간이 무제한이에요. ' : ''}모두 누르면 바로 투표로 넘어가요. ); } else if (ph.kind === 'vote') { @@ -567,7 +582,10 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor body = my.canGuess ? ( <>

    들켰어요! 제시어를 맞히면 그래도 이겨요

    - 주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'} + + 주제는 {v.topicKo}이에요. {v.options.guessMode === 'choice' ? '목록에서 하나를 골라요. 기회는 한 번이에요.' : '띄어쓰기는 상관없어요. 기회는 한 번이에요.'} + {ph.endsAt === null ? ' 시간 제한은 없어요.' : ''} + ) : ( @@ -635,6 +653,36 @@ function FinalReveal({ v, players }: { v: LiarView; players: Record tone(660, 70, 'triangle', 0.09), + /** The accused really is the liar. */ + caught: () => [523, 784].forEach((f, i) => tone(f, 140, 'square', 0.07, i * 120)), +}; + +/** Sounds for what anyone did: descriptions, votes being cast, results (the room plays win / lose at the end). */ +function useLiarSounds(v: LiarView, me: string | null): void { + const prev = useRef(v); + useEffect(() => { + const p = prev.current; + prev.current = v; + if (p === v) return; + const last = p.events.at(-1)?.n ?? 0; + const fresh = v.events.filter((e) => e.n > last); + if (fresh.some((e) => e.t === 'end')) return; + const acc = fresh.find((e) => e.t === 'accused'); + if (acc && acc.t === 'accused') return acc.liar ? lgSound.caught() : sfx.bad(); + if (fresh.some((e) => e.t === 'vote')) return sfx.chips(3); + if (fresh.some((e) => e.t === 'left')) return sfx.whoosh(); + const newDesc = v.descriptions.slice(p.descriptions.length); + if (newDesc.some((d) => d.from !== me)) return newDesc.some((d) => d.text === null) ? sfx.tick() : lgSound.said(); + if (v.my?.vote !== p.my?.vote && v.my?.vote) return sfx.select(); + const same = v.phase.kind === p.phase.kind && v.phase.voteRound === p.phase.voteRound; + if (same && (v.phase.votedCount > p.phase.votedCount || v.phase.readyCount > p.phase.readyCount)) sfx.chip(); + }, [v]); // eslint-disable-line react-hooks/exhaustive-deps +} + function LiarBoard({ view: v, me, players, act, pending }: BoardProps) { const ph = v.phase; const my = v.my; @@ -652,6 +700,7 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps) sounds.myTurn(); } }, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps + useLiarSounds(v, me); 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); @@ -667,10 +716,12 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps)
    🤥 라이어 게임 - {phaseTitle(v)} + + {phaseTitle(v)} + {sub} - + {my && }
    @@ -762,7 +813,7 @@ function statusText(v: LiarView, me: string | null, players: Record({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { +function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
    {options.map(([k, l]) => ( @@ -788,7 +839,7 @@ const onOff: [boolean, string][] = [ [true, '켜기'], [false, '끄기'], ]; -const secs = (...v: T[]): [T, string][] => v.map((x) => [x, `${x}초`]); +const secs = (...v: T[]): [T | null, string][] => [...v.map((x): [T, string] => [x, `${x}초`]), [null, '무제한']]; function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); @@ -828,18 +879,21 @@ function Options({ value: o, onChange }: OptionsProps) { {more && ( <> - + set({ describeSeconds })} /> - + set({ discussionSeconds })} /> - + set({ voteSeconds })} /> - + set({ guessSeconds })} /> + {[o.describeSeconds, o.discussionSeconds, o.voteSeconds, o.guessSeconds].includes(null) && ( + 무제한이어도 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 넘어가요(설명 넘김, 표 없음, 답 없음). + )} set({ kidSafeChat })} /> @@ -852,7 +906,7 @@ function Options({ value: o, onChange }: OptionsProps) { 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' ? '정답은 목록에서' : '정답은 직접 적기'); + parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기'); return parts.join(' · '); } @@ -873,6 +927,7 @@ function Rules() {
  • 라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.
  • 점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.
  • 바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.
  • +
  • 시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.
  • 내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.

    diff --git a/docs/games/liar.md b/docs/games/liar.md index 2e29e57..edaf8cc 100644 --- a/docs/games/liar.md +++ b/docs/games/liar.md @@ -14,11 +14,11 @@ | `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 | +| `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 | +| `guessSeconds` | 정답 맞히기 시간 | 20 / 30 / 45 / 60 / 무제한 | 30 | | `kidSafeChat` | 고운 말 필터(욕설·링크·전화번호 막기, 마피아와 같은 필터) | on / off | on | ## 3. 구성물 @@ -97,7 +97,7 @@ interface LiarState { | `ready` | — | 확인 시간·토론 | 아직 안 누름 | | `vote` | `target` | 투표 | 나 말고, 후보(재투표는 동점자) 중 | | `guess` | `text` | 정답 맞히기의 라이어 | 1~20자, `choice`면 주제 단어 | -| `phaseTimeout` | — | 서버(시계) | `endsAt` 이후 | +| `phaseTimeout` | — | 서버(시계) | `endsAt` 이후 (무제한 단계: 아직 안 마친 사람만, 방의 연결 끊김 유예 뒤) | | `leave` | — | 서버(나감) | 아직 안 나감 | ### 8.3 공개/비공개 정보 (view) @@ -115,6 +115,10 @@ interface LiarState { - 시간 초과: 확인 → 첫 설명, 설명 → 넘김, 토론 → 투표, 투표 → 집계, 정답 맞히기 → 틀림. - 나가기(`onLeave`): 그 사람은 이후 차례·투표·"모두 동의"에서 빠진다. 설명 차례였으면 다음 사람. 투표 중이면 그 사람 표와 그 사람이 받은 표를 지우고, 남은 사람이 다 투표했으면 바로 집계. 라이어가 나가면 시민 승리, 시민이 모두 나가면 라이어 승리. +- **시간 무제한**(단계별 옵션 값 `null`): 그 단계는 `endsAt: null`. 설명은 차례인 사람이 말할 때까지, 토론은 모두 [토론 끝내기], 투표는 모두 투표, 정답 맞히기는 라이어가 답할 때까지 기다린다. 제시어 확인(10초)은 그대로. + - 시간 초과 대상(`timeoutPlayers`)은 아직 안 마친 사람들. 연결이 끊긴 채 방의 유예 시간이 지나면 그 사람의 `phaseTimeout`이 넘김(설명 `text: null`, 토론 끝, 표 없음 `passed`, 답 없음 → 시민 승리)으로 처리된다. + - 컴퓨터는 무제한 단계를 기본 시간(설명 30초, 토론 90초, 투표·맞히기 30초)처럼 맞춰 행동한다. + ### 8.6 종료 조건과 결과(GameResult) 6절 표. `reason: 'normal'`, `summary` 예: "라이어 승리! 라이어가 아닌 사람이 지목됐어요. 제시어는 '수박'이었어요." diff --git a/packages/games/src/liar/bot.test.ts b/packages/games/src/liar/bot.test.ts index 0659557..076a09e 100644 --- a/packages/games/src/liar/bot.test.ts +++ b/packages/games/src/liar/bot.test.ts @@ -52,6 +52,18 @@ describe('whole games', () => { }, 60_000); } + test('모든 시간 무제한, 컴퓨터만: 설명·토론 끝내기·투표·맞히기를 해서 모두 끝나요', () => { + const options = opts({ describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null }); + for (const n of [3, 5, 8, 10]) { + const r = liveBotPlayout(liar, liarBot, { players: seats(n, 0), options, seed: seedN(900 + n), isBot }); + expect(r.finished).toBe(true); + expect(r.rejected).toEqual([]); + const st = r.state as LiarState; + expect(st.descriptions.every((d) => d.text !== null)).toBe(true); + expect(r.elapsed).toBeGreaterThan(30_000); + } + }, 60_000); + test('컴퓨터는 토론 때 말하고, 라이어 컴퓨터는 자기를 지목하지 않아요', () => { for (let s = 1; s <= 10; s++) { const r = liveBotPlayout(liar, liarBot, { players: seats(6, 0), seed: seedN(300 + s), isBot }); diff --git a/packages/games/src/liar/bot.ts b/packages/games/src/liar/bot.ts index e471401..54351bf 100644 --- a/packages/games/src/liar/bot.ts +++ b/packages/games/src/liar/bot.ts @@ -130,6 +130,15 @@ function matchAll(m: TopicModel, text: string): Map { // ---------------------------------------------------------------- the bot +/** How a computer paces a 무제한 phase: like the default clock of that phase. */ +const UNLIMITED_PACE_MS: Record, number> = { + reveal: 10_000, + describe: 30_000, + discussion: 90_000, + vote: 30_000, + guess: 30_000, +}; + class LiarBot { readonly v: LiarView; readonly me: PlayerId; @@ -197,8 +206,11 @@ class LiarBot { return this.v.phase.startedAt; } + /** Phase length; 무제한 phases are paced like the default clock (so a computer neither rushes nor stalls). */ private get phaseLen(): number { - return Math.max(1000, (this.v.phase.endsAt ?? this.phaseStart) - this.phaseStart); + const ph = this.v.phase; + if (ph.endsAt === null && ph.kind !== 'ended') return UNLIMITED_PACE_MS[ph.kind]; + return Math.max(1000, (ph.endsAt ?? this.phaseStart) - this.phaseStart); } /** `lo..hi` seconds into the phase (scaled by pace), never later than `cap` of it. */ diff --git a/packages/games/src/liar/index.ts b/packages/games/src/liar/index.ts index 623b5a7..53912be 100644 --- a/packages/games/src/liar/index.ts +++ b/packages/games/src/liar/index.ts @@ -3,6 +3,8 @@ * * 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). + * 무제한 phases (`endsAt` null) end when everyone needed is done; a player away past the room's grace period + * is passed by their own `phaseTimeout` (넘김 / no vote / wrong guess). * 제시어 확인 → 차례대로 한 문장 설명(바퀴 수만큼, 두 번째 바퀴는 거꾸로) → 자유 토론 → 투표(동점이면 동점자끼리 재투표 한 번, * 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과. * @@ -97,6 +99,8 @@ function speakerOf(s: LiarState): PlayerId | 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; +const endsIn = (now: number, sec: number | null) => (sec === null ? null : now + sec * 1000); + /** 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++) { @@ -104,17 +108,17 @@ function nextTurn(s: LiarState, now: number, round: number, turn: number): void 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 }; + s.phase = { kind: 'describe', startedAt: now, endsAt: endsIn(now, s.options.describeSeconds), 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: [] }; + s.phase = { kind: 'discussion', startedAt: now, endsAt: endsIn(now, s.options.discussionSeconds), 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: {} }; + s.phase = { kind: 'vote', startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), round, candidates, votes: {} }; pushEvent(s, now, { t: 'phase', kind: 'vote', round }); } @@ -128,7 +132,48 @@ function voteTargets(s: LiarState, voter: PlayerId): PlayerId[] { /** 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); +/** Has voted (or, 무제한, was passed while away). */ +const hasVoted = (ph: Extract, p: PlayerId) => ph.votes[p] !== undefined || (ph.passed ?? []).includes(p); +const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && hasVoted(s.phase, p.id)); + +/** 무제한 phase: who it still waits for (the speaker, 토론 끝내기, votes, the liar's guess). */ +function awaited(s: LiarState): PlayerId[] { + const ph = s.phase; + if (ph.kind === 'ended' || ph.endsAt !== null) return []; + switch (ph.kind) { + case 'describe': + return [speakerOf(s)!]; + case 'discussion': + case 'reveal': + return present(s) + .filter((p) => !ph.ready.includes(p.id)) + .map((p) => p.id); + case 'vote': + return voters(s) + .filter((p) => !hasVoted(ph, p.id)) + .map((p) => p.id); + case 'guess': + return [s.liar]; + } +} + +/** 무제한: the room moved on for `p` (away past the grace period). */ +function pass(s: LiarState, now: number, p: PlayerId): void { + const ph = s.phase; + switch (ph.kind) { + case 'discussion': + ph.ready.push(p); + if (present(s).every((x) => ph.ready.includes(x.id))) advance(s, now); + return; + case 'vote': + (ph.passed ??= []).push(p); + if (allVoted(s)) resolveVote(s, now); + return; + default: + // describe: the speaker's turn is 넘김; guess: no answer (wrong). + advance(s, now); + } +} function finish(s: LiarState, now: number, winner: 'liar' | 'citizens', reason: WinReason): void { const word = s.word; @@ -176,7 +221,7 @@ function resolveVote(s: LiarState, now: number): void { 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 }; + s.phase = { kind: 'guess', startedAt: now, endsAt: endsIn(now, s.options.guessSeconds) }; pushEvent(s, now, { t: 'phase', kind: 'guess' }); } @@ -273,6 +318,8 @@ function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: num if (s.final || ph.kind === 'ended') return fail('게임이 이미 끝났어요.'); switch (a.type) { case 'phaseTimeout': + // 무제한: only for someone the phase waits on (the room passes a player away past the grace period). + if (ph.endsAt === null) return awaited(s).includes(actor) ? ok : fail('아직 기다리는 중이에요.'); return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok; case 'leave': return p.left ? fail('이미 나갔어요.') : ok; @@ -359,7 +406,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView { 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, + votedCount: ph.kind === 'vote' ? voters(s).filter((p) => hasVoted(ph, p.id)).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')) : [], }, @@ -368,7 +415,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView { players: s.players.map((p) => ({ id: p.id, left: p.left, - voted: ph.kind === 'vote' && ph.votes[p.id] !== undefined, + voted: ph.kind === 'vote' && hasVoted(ph, p.id), liar: known ? p.id === s.liar : null, })), descriptions: s.descriptions.map((d) => ({ ...d })), @@ -392,7 +439,7 @@ function activePlayers(s: LiarState): PlayerId[] { return [s.liar]; case 'vote': return voters(s) - .filter((p) => ph.votes[p.id] === undefined) + .filter((p) => !hasVoted(ph, p.id)) .map((p) => p.id); default: return present(s).map((p) => p.id); @@ -455,7 +502,8 @@ export const liar: Def = { const ph = s.phase; switch (a.type) { case 'phaseTimeout': - advance(s, now); + if (ph.kind !== 'ended' && ph.endsAt === null) pass(s, now, actor); + else advance(s, now); break; case 'leave': leave(s, now, p); @@ -498,9 +546,10 @@ export const liar: Def = { return s.phase.kind === 'ended' ? null : s.phase.endsAt; }, - /** One player drives the phase clock (the deadline is shared by everybody). */ + /** One player drives the phase clock (the deadline is shared by everybody); 무제한: those still awaited (only the away ones time out). */ timeoutPlayers(s) { - return s.phase.kind === 'ended' ? [] : [s.players[0]!.id]; + if (s.phase.kind === 'ended') return []; + return s.phase.endsAt === null ? awaited(s) : [s.players[0]!.id]; }, /** An away driver must not end a phase early. */ @@ -540,7 +589,7 @@ export const liar: Def = { const p = P(s, player); if (!p || s.final || s.phase.kind === 'ended') return []; const out: LiarAction[] = [{ type: 'phaseTimeout' }]; - if (p.left) return out; + if (p.left) return out.filter((a) => validate(s, player, a).ok); const me = myView(s, p); if (me.canChat) out.push({ type: 'chat', text: `m${s.seq}-${player}` }); if (me.canReady) out.push({ type: 'ready' }); diff --git a/packages/games/src/liar/liar.test.ts b/packages/games/src/liar/liar.test.ts index 0517267..cf87876 100644 --- a/packages/games/src/liar/liar.test.ts +++ b/packages/games/src/liar/liar.test.ts @@ -52,7 +52,7 @@ function reject(s: LiarState, actor: PlayerId, a: LiarAction, now?: number): str } 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); + 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); @@ -231,7 +231,7 @@ describe('차례대로 설명 (§5.2)', () => { 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(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 }); @@ -381,6 +381,54 @@ describe('나가기 (§8.5)', () => { }); }); +describe('시간 무제한 (§8.5)', () => { + const U = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null }; + + test('설명·토론·투표·맞히기 모두 무제한: 마감 없이 할 일을 마칠 때까지, 기다리는 사람만 시간 초과 대상', () => { + let s = tick(rig(3, { ...U, rounds: 1 })); + expect(s.phase.kind === 'describe' && s.phase.endsAt).toBeNull(); + expect(liar.deadline!(s)).toBeNull(); + expect(liar.timeoutPlayers!(s)).toEqual(['P0']); + expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.'); + for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'chat', text: `${p} 설명` }, T0 + 3_600_000); + expect(s.phase.kind).toBe('discussion'); + expect(liar.timeoutPlayers!(s)).toEqual(['P0', 'P1', 'P2']); + for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'ready' }); + expect(s.phase.kind).toBe('vote'); + s = votes(s, { P0: 'P2', P1: 'P2' }); + expect(liar.timeoutPlayers!(s)).toEqual(['P2']); + s = act(s, 'P2', { type: 'vote', target: 'P0' }); + expect(s.phase.kind).toBe('guess'); + expect(liar.timeoutPlayers!(s)).toEqual(['P2']); + s = act(s, 'P2', { type: 'guess', text: '수박' }, T0 + 7_200_000); + expect(s.final!.reason).toBe('guessed'); + }); + + test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김: 설명 넘김·토론 끝·표 없음·답 없음', () => { + let s = tick(rig(4, { ...U, rounds: 1 })); + s = act(s, 'P0', liar.onTimeout(s, 'P0')); + expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null }); + for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'chat', text: `${p} 설명` }); + for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'ready' }); + s = act(s, 'P0', liar.onTimeout(s, 'P0')); + expect(s.phase.kind).toBe('vote'); + s = votes(s, { P1: 'P3', P2: 'P3', P3: 'P1' }); + expect(liar.view(s, null).players.find((p) => p.id === 'P0')!.voted).toBe(false); + s = act(s, 'P0', liar.onTimeout(s, 'P0')); + expect(lastEv(s, 'vote')).toMatchObject({ accused: 'P3', votes: { P1: 'P3', P2: 'P3', P3: 'P1' } }); + s = act(s, 'P3', liar.onTimeout(s, 'P3')); + expect(s.final).toMatchObject({ winner: 'citizens', reason: 'caught', guess: null }); + }); + + test('무작위 대국(모두 무제한)도 끝나요', () => { + for (let k = 1; k <= playoutSeeds(40); k++) { + const n = 3 + (k % 8); + const r = randomPlayout(liar, { players: ids(n), options: opts(U), seed: seedN(5000 + k), maxSteps: 3000 }); + expect(r.finished).toBe(true); + } + }); +}); + // ---------------------------------------------------------------- engine checks describe('무작위 대국 (엔진 공통 검사)', () => { diff --git a/packages/games/src/liar/types.ts b/packages/games/src/liar/types.ts index 56b58b2..c8df602 100644 --- a/packages/games/src/liar/types.ts +++ b/packages/games/src/liar/types.ts @@ -5,9 +5,11 @@ import { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics'; export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics'; -const lit = (...vals: T[]) => +const lit = (...vals: T[]) => z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`])); +/** Labels plus 무제한 (null): that phase has no clock (§8.5). */ +const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl }); export const liarOptionsSchema = z.object({ topic: z @@ -18,22 +20,23 @@ export const liarOptionsSchema = z.object({ rounds: lit(1, 2) .default(2) .meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }), - describeSeconds: lit(15, 20, 30, 45, 60) + /** null = 무제한 (each such phase ends when everyone needed is done; away players are passed after the room's grace period). */ + describeSeconds: lit<15 | 20 | 30 | 45 | 60 | null>(15, 20, 30, 45, 60, null) .default(30) - .meta({ title: '한 사람 설명 시간', labels: secLabels(15, 20, 30, 45, 60) }), - discussionSeconds: lit(30, 60, 90, 120, 180) + .meta({ title: '한 사람 설명 시간', labels: secLabelsU('무제한(설명을 보낼 때까지)', 15, 20, 30, 45, 60) }), + discussionSeconds: lit<30 | 60 | 90 | 120 | 180 | null>(30, 60, 90, 120, 180, null) .default(90) - .meta({ title: '자유 토론 시간', labels: secLabels(30, 60, 90, 120, 180) }), - voteSeconds: lit(15, 20, 30, 45) + .meta({ title: '자유 토론 시간', labels: secLabelsU('무제한(모두 토론 끝내기를 누를 때까지)', 30, 60, 90, 120, 180) }), + voteSeconds: lit<15 | 20 | 30 | 45 | null>(15, 20, 30, 45, null) .default(30) - .meta({ title: '투표 시간', labels: secLabels(15, 20, 30, 45) }), + .meta({ title: '투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 15, 20, 30, 45) }), guessMode: z .enum(['text', 'choice']) .default('text') .meta({ title: '라이어의 정답 맞히기', labels: { text: '직접 적기', choice: '주제 단어 목록에서 고르기' } }), - guessSeconds: lit(20, 30, 45, 60) + guessSeconds: lit<20 | 30 | 45 | 60 | null>(20, 30, 45, 60, null) .default(30) - .meta({ title: '정답 맞히기 시간', labels: secLabels(20, 30, 45, 60) }), + .meta({ title: '정답 맞히기 시간', labels: secLabelsU('무제한(라이어가 답할 때까지)', 20, 30, 45, 60) }), kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }), }); export type LiarOptions = z.infer; @@ -54,10 +57,12 @@ export type LiarAction = LiarClientAction | { type: 'phaseTimeout' } | { type: ' 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 } - | { kind: 'guess'; startedAt: number; endsAt: number } + // endsAt null = 무제한: describe/guess wait for the speaker/liar, discussion for everyone's 「투표하자」, vote for every vote. + | { kind: 'describe'; startedAt: number; endsAt: number | null; round: number; turn: number } + | { kind: 'discussion'; startedAt: number; endsAt: number | null; ready: PlayerId[] } + /** `passed`: 무제한 only, voters the room moved on while away (no vote). */ + | { kind: 'vote'; startedAt: number; endsAt: number | null; round: 1 | 2; candidates: PlayerId[]; votes: Record; passed?: PlayerId[] } + | { kind: 'guess'; startedAt: number; endsAt: number | null } | { kind: 'ended' }; export type PhaseKind = Phase['kind'];