diff --git a/apps/server/src/rooms/mafia.room.test.ts b/apps/server/src/rooms/mafia.room.test.ts index d77bc74..d0a7406 100644 --- a/apps/server/src/rooms/mafia.room.test.ts +++ b/apps/server/src/rooms/mafia.room.test.ts @@ -7,7 +7,7 @@ import { openDb } from '../db'; import { Room, type Conn, type RoomConfig } from './room'; import { RoomStore } from './store'; -function harness(players: string[]) { +function harness(players: string[], options: Record = {}) { const db = openDb(':memory:'); const store = new RoomStore(db); let now = 1_000_000; @@ -16,7 +16,7 @@ function harness(players: string[]) { const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now }; const config: RoomConfig = { gameId: 'mafia', - options: { ...games.mafia.defaultOptions, firstPhase: 'night' }, + options: { ...games.mafia.defaultOptions, firstPhase: 'night', ...options }, maxPlayers: players.length, visibility: 'private', allowSpectators: true, @@ -67,4 +67,23 @@ describe('마피아 room flow', () => { expect(state().phase.kind).toBe('discussion'); expect(state().day).toBe(2); }); + + test('밤 시간 무제한: 타이머 없이 모두 밤 마치기를 누를 때까지, 연결이 끊긴 사람은 유예 시간 뒤 넘김', () => { + const { room, clock, conns, state } = harness(['A', 'B', 'C', 'D'], { nightSeconds: null }); + expect(room.start('A')).toBeNull(); + clock.advance(8_000); + room.onTimer(); + expect(state().phase.kind).toBe('night'); + expect(room.effectiveDeadline()).toBeNull(); + let cs = 10; + for (const p of ['A', 'B', 'C']) room.act(p, ++cs, { type: 'readyEarly' }); + clock.advance(3_600_000); + room.onTimer(); + expect(state().phase.kind).toBe('night'); + room.disconnect(conns.D!); + expect(room.effectiveDeadline()).toBe(clock.now() + 60_000); + clock.advance(60_000); + room.onTimer(); + expect(state().phase.kind).toBe('discussion'); + }); }); diff --git a/apps/web/src/games/clue/index.tsx b/apps/web/src/games/clue/index.tsx index da642fe..5e63534 100644 --- a/apps/web/src/games/clue/index.tsx +++ b/apps/web/src/games/clue/index.tsx @@ -280,7 +280,7 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps) const a = v.accusations[v.accusations.length - 1]!; const who = a.by === me ? '내' : `${nick(players, a.by)}님의`; if (a.correct) { - sfx.fanfare(); + // The game ends here: the room plays win / lose. setBanner({ key: `a${v.accusations.length}`, kind: 'ok', text: `⚖️ ${who} 고발이 맞았어요!` }); } else { sfx.bad(); diff --git a/apps/web/src/games/mafia/help.test.ts b/apps/web/src/games/mafia/help.test.ts index 12ad7fb..033582b 100644 --- a/apps/web/src/games/mafia/help.test.ts +++ b/apps/web/src/games/mafia/help.test.ts @@ -55,3 +55,16 @@ test('마피아: 지목 투표 → 찬반 투표, 탈락한 사람', () => { const dead = { ...confirm, players: g.state.players.map((p: any) => (p.id === g.doctor ? { ...p, alive: false, diedDay: 1, diedBy: 'mafia' } : p)) }; expect(helpNow(view(dead, g.doctor), g.doctor, users)).toContain('[죽은 사람] 채팅'); }); + +test('마피아: 시간 무제한이면 [밤 마치기]·[반론 마치기]·모두 투표 안내', () => { + const g = game(); + const night = { kind: 'night', startedAt: T, endsAt: null, ready: [], mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null }; + const s = { ...g.state, day: 2, phase: night }; + const c = helpNow(view(s, g.citizen), g.citizen, users); + expect(c).toContain('[밤 마치기]'); + expect(c).toContain('(0/7)'); + const def = { ...g.state, day: 2, phase: { kind: 'defense', startedAt: T, endsAt: null, accused: g.citizen } }; + expect(helpNow(view(def, g.citizen), g.citizen, users)).toContain('[반론 마치기]를 눌러요'); + const vote = { ...g.state, day: 2, phase: { kind: 'vote', startedAt: T, endsAt: null, votes: {} } }; + expect(helpNow(view(vote, g.police), g.police, users)).toContain('모두 투표(기권 포함)하면 바로 결과가 나와요(0/7)'); +}); diff --git a/apps/web/src/games/mafia/help.ts b/apps/web/src/games/mafia/help.ts index a7a9ae3..e0e8ae8 100644 --- a/apps/web/src/games/mafia/help.ts +++ b/apps/web/src/games/mafia/help.ts @@ -50,6 +50,8 @@ export function helpNow(v: MafiaView, me: string | null, players: Record, string> }; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; + +/** Game sounds on top of the shared palette (site volume applies). */ +const mfSound = { + /** Night falls: a low falling hum. */ + night: () => { + tone(392, 520, 'sine', 0.1, 0, { slideTo: 196 }); + tone(294, 620, 'sine', 0.06, 180, { slideTo: 147 }); + }, + /** Morning: a small rising chime. */ + morning: () => [523, 659, 784].forEach((f, i) => tone(f, 160, 'triangle', 0.09, i * 110)), + /** Judge's gavel (executed). */ + gavel: () => { + noise(70, 0.35, 0, 'lowpass', 500); + tone(120, 160, 'square', 0.08); + noise(60, 0.25, 220, 'lowpass', 500); + }, + /** Someone was taken in the night. */ + death: () => { + tone(220, 380, 'sawtooth', 0.06, 0, { slideTo: 110 }); + tone(233, 380, 'sawtooth', 0.04, 40, { slideTo: 116 }); + }, +}; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const isNight = (v: MafiaView) => v.phase.kind === 'night' || v.phase.kind === 'roleReveal'; @@ -135,6 +157,11 @@ button.mf-tile { cursor: pointer; } .mf-log { list-style: none; margin: 6px 0 0; padding: 0; display: grid; gap: 3px; max-height: 320px; overflow: auto; } .mf-rules td, .mf-rules th { padding: 4px 6px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--border); } @keyframes mf-pop { from { transform: scale(.96); opacity: 0; } to { transform: none; opacity: 1; } } +.mf-unl { font-size: 1.6rem; } +.mf-unl small { display: block; font-size: .7rem; font-weight: 800; } +.mf-tile[aria-pressed='true'] { animation: mf-pick .28s ease-out; } +@keyframes mf-pick { 50% { transform: scale(1.07); } } +.mf-rolecard[data-show='true'] { animation: anim-flip .35s ease both; } @keyframes mf-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } } @media (max-width: 1099px) { .mf { height: auto; } @@ -154,14 +181,20 @@ button.mf-tile { cursor: pointer; } } @media (prefers-reduced-motion: reduce) { .mf-banner { transition: none; } - .mf-news, .mf-bar .tr i { animation: none; } + .mf-news, .mf-bar .tr i, .mf-tile[aria-pressed='true'], .mf-rolecard[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}`; @@ -537,7 +570,7 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco body = ( <>

{ph.kind === 'greeting' ? '인사 시간이에요. 오늘은 투표가 없어요.' : '토론 시간이에요. 마피아가 누구일까요?'}

- {ph.kind === 'discussion' && v.options.timeAdjust && ( + {ph.kind === 'discussion' && v.options.timeAdjust && ph.endsAt !== null && (
)} - {ph.kind === 'discussion' && !my.canAdjust && v.options.timeAdjust && 시간 바꾸기는 하루에 한 번만 할 수 있어요.} + {ph.kind === 'discussion' && !my.canAdjust && v.options.timeAdjust && ph.endsAt !== null && 시간 바꾸기는 하루에 한 번만 할 수 있어요.}
- 살아 있는 사람이 모두 누르면 바로 다음으로 넘어가요. + {ph.endsAt === null ? '토론 시간이 무제한이에요. ' : ''}살아 있는 사람이 모두 누르면 바로 다음으로 넘어가요. ); } else if (ph.kind === 'vote') { body = ( <>

마피아로 의심되는 사람을 골라 주세요

- 초록 테두리 사람을 누르면 지목해요. 시간 안에는 바꿀 수 있어요. - {my.vote === null ? '아직 고르지 않았어요 (안 고르면 기권)' : my.vote === 'abstain' ? '기권했어요' : `${n(my.vote)}을 지목했어요`} + + {ph.endsAt === null ? '초록 테두리 사람을 누르면 지목해요. 모두 투표하면 바로 결과가 나와요. ' : '초록 테두리 사람을 누르면 지목해요. 시간 안에는 바꿀 수 있어요.'} + {ph.endsAt === null && } + + {my.vote === null ? `아직 고르지 않았어요${ph.endsAt === null ? '' : ' (안 고르면 기권)'}` : my.vote === 'abstain' ? '기권했어요' : `${n(my.vote)}을 지목했어요`}
+
+ )} + {ph.endsAt === null && 시간 제한이 없어요. {ph.accused === me ? '다 말했으면 [반론 마치기]를 눌러요.' : '지목된 사람이 [반론 마치기]를 누르면 찬반 투표로 넘어가요.'}} + + ); } else if (ph.kind === 'confirm') { body = my.canConfirm ? ( <> @@ -583,7 +631,16 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco 반대 (살리기) - {my.ballot ? `${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 시간 안에는 바꿀 수 있어요.` : '고르지 않으면 집계에서 빠져요.'} + + {ph.endsAt === null + ? my.ballot + ? `${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 모두 고르면 바로 결과가 나와요. ` + : '모두 고르면 바로 결과가 나와요. ' + : my.ballot + ? `${my.ballot === 'yes' ? '찬성' : '반대'}했어요. 시간 안에는 바꿀 수 있어요.` + : '고르지 않으면 집계에서 빠져요.'} + {ph.endsAt === null && } + ) : (

다른 사람들이 찬반 투표를 하고 있어요.

@@ -595,7 +652,7 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco

{nv.prompt}

{nv.action && nv.targets.length > 0 && ( <> - 초록 테두리 사람을 누르면 골라요. 밤이 끝날 때 고른 사람으로 정해져요. + 초록 테두리 사람을 누르면 골라요. 밤이 끝날 때 고른 사람으로 정해져요.{ph.endsAt === null ? ' 고른 다음 [밤 마치기]를 눌러요.' : ''} {nv.choice ? `고른 사람: ${n(nv.choice)}${nv.pickedBy && nv.pickedBy !== me ? ` (${n(nv.pickedBy)}이 골랐어요)` : ''}` : '아직 고르지 않았어요'} {nv.action === 'mafiaTarget' && nv.choice && (
@@ -607,6 +664,16 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco )} {!nv.action && 밤이 지나면 아침 발표가 있어요.} + {ph.endsAt === null && ( + <> +
+ +
+ 밤 시간이 무제한이에요. 살아 있는 사람이 모두 누르면 아침이 와요. + + )} ); } @@ -629,6 +696,17 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco ); } +/** "(3/5)": how many are done in this phase; bumps when it changes (someone else pressed / voted). */ +function Count({ v }: { v: MafiaView }) { + const { readyCount: c, readyNeeded: n } = v.phase; + if (!n) return null; + return ( + + ({c}/{n}) + + ); +} + function FinalReveal({ v, players }: { v: MafiaView; players: Record }) { const f = v.final!; return ( @@ -670,6 +748,39 @@ function FinalReveal({ v, players }: { v: MafiaView; players: Record { + 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); + let played = false; + const play = (f: () => void) => { + if (played) return; + played = true; + f(); + }; + // The most telling announcement wins (one sound per update); the room plays win / lose at the end. + if (fresh.some((e) => e.t === 'end')) return; + for (const e of fresh) { + if (e.t === 'death') play(e.by === 'mafia' ? mfSound.death : e.by === 'vote' ? mfSound.gavel : sfx.whoosh); + else if (e.t === 'confirm' && e.outcome !== 'executed') play(sfx.good); + else if (e.t === 'healed' || e.t === 'soldier') play(sfx.good); + } + if (fresh.some((e) => e.t === 'vote')) play(() => sfx.chips(3)); + if (fresh.some((e) => e.t === 'adjust')) play(sfx.tick); + if (fresh.length) return; + // Same phase: my own pick (vote, ballot, night target incl. a mafia mate's) or someone else being done. + const my = v.my; + const pm = p.my; + if (my && pm && (my.vote !== pm.vote || my.ballot !== pm.ballot || my.night?.choice !== pm.night?.choice)) return play(sfx.select); + if (v.phase.readyCount > p.phase.readyCount && v.phase.kind === p.phase.kind) play(sfx.chip); + }, [v]); +} + function MafiaBoard({ view: v, me, players, act, pending }: BoardProps) { const ph = v.phase; const my = v.my; @@ -682,11 +793,13 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps act({ type: 'vote', target: id }) }; @@ -711,10 +824,12 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps {time === 'night' ? '🌙' : time === 'end' ? '🏁' : '☀️'} {v.day}일차 - {PHASE_KO[ph.kind]} + + {PHASE_KO[ph.kind]} + {sub} - + {my && } @@ -824,7 +939,7 @@ function statusText(v: MafiaView, 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]) => ( @@ -851,6 +966,8 @@ const onOff: [boolean, string][] = [ [false, '끄기'], ]; const secs = (...v: T[]): [T, string][] => v.map((x) => [x, `${x}초`]); +/** Seconds plus 무제한 (null). */ +const secsU = (...v: T[]): [T | null, string][] => [...secs(...v), [null, '무제한']]; const EXTRA_KO: Record = { soldier: '군인', politician: '정치인', medium: '영매', lovers: '연인(2명)' }; function Options({ value: o, onChange }: OptionsProps) { @@ -893,7 +1010,8 @@ function Options({ value: o, onChange }: OptionsProps) { /> - set({ nightSeconds })} /> + set({ nightSeconds })} /> + {o.nightSeconds === null && 살아 있는 사람이 모두 [밤 마치기]를 누르면 아침이 와요(직업과 상관없이 모두 눌러요).} ) { {more && ( <> - set({ discussionPerAlive })} /> + set({ discussionPerAlive })} /> - - set({ discussionMin })} /> + {o.discussionPerAlive === null ? ( + 토론 시간이 무제한이에요. 살아 있는 사람이 모두 [토론 끝내기]를 누르면 투표로 넘어가요(최소·최대·±15초는 쓰지 않아요). + ) : ( + <> + + set({ discussionMin })} /> + + + set({ discussionMax })} /> + + + )} + + set({ voteSeconds })} /> - - set({ discussionMax })} /> + + set({ defenseSeconds })} /> - - set({ voteSeconds })} /> - - - set({ defenseSeconds })} /> - - - set({ confirmSeconds })} /> - - - set({ timeAdjust })} /> + + set({ confirmSeconds })} /> + {o.discussionPerAlive !== null && ( + + set({ timeAdjust })} /> + + )} set({ openVote })} /> @@ -975,7 +1101,8 @@ function optionsSummary(o: MafiaOptions): string { const extras = (Object.keys(EXTRA_KO) as (keyof MafiaOptions['extraRoles'])[]).filter((k) => o.extraRoles[k]).map((k) => EXTRA_KO[k]); const parts = [o.mafiaCount === 'auto' ? '마피아 자동' : `마피아 ${o.mafiaCount}명`]; if (extras.length) parts.push(`추가: ${extras.join('·')}`); - parts.push(o.firstPhase === 'day' ? '낮부터' : '밤부터', `밤 ${o.nightSeconds}초`, `투표 ${o.voteSeconds}초`); + parts.push(o.firstPhase === 'day' ? '낮부터' : '밤부터', o.nightSeconds === null ? '밤 무제한' : `밤 ${o.nightSeconds}초`, o.voteSeconds === null ? '투표 무제한' : `투표 ${o.voteSeconds}초`); + if (o.discussionPerAlive === null) parts.push('토론 무제한'); parts.push(o.deathReveal === 'none' ? '탈락자 비공개' : o.deathReveal === 'team' ? '탈락 시 마피아 여부 공개' : '탈락 시 직업 공개'); return parts.join(' · '); } @@ -996,6 +1123,10 @@ function Rules() {

밤에는 낮 채팅이 잠겨요. 마피아는 마피아 채팅으로, 연인은 연인 채팅으로 몰래 이야기해요. 탈락한 사람은 죽은 사람 채팅에서만 이야기할 수 있어요(영매는 밤에 함께해요).

+

+ 시간 무제한: 단계마다 시간을 무제한으로 할 수 있어요. 그러면 토론은 모두 [토론 끝내기], 투표는 모두 투표, 반론은 지목된 사람이 [반론 마치기], 밤은 모두 [밤 마치기]를 누를 때 + 넘어가요. 연결이 끊긴 채 돌아오지 않는 사람은 잠시 뒤 기권·마침으로 처리돼요. +

{ROLE_ORDER.map((r) => ( diff --git a/docs/games/mafia.md b/docs/games/mafia.md index 198975c..9ccfa01 100644 --- a/docs/games/mafia.md +++ b/docs/games/mafia.md @@ -16,13 +16,13 @@ | `mafiaCount` | 마피아 수 | `auto` / 1~4 | `auto`(4장 표) | | `extraRoles` | 추가 직업(시민 자리를 대체) | `soldier`, `politician`, `medium`, `lovers` 다중 선택 | 없음 | | `firstPhase` | 시작 페이즈 | `day`(투표 없는 인사 낮) / `night` | `day` | -| `discussionPerAlive` | 토론 시간 = 생존자 수 × 이 값 | 10 / 15 / 20 | 15 | +| `discussionPerAlive` | 토론 시간 = 생존자 수 × 이 값 | 10 / 15 / 20 / 무제한 | 15 | | `discussionMin` / `discussionMax` | 토론 시간 하한/상한 | 30~300 | 60 / 180 | | `timeAdjust` | 낮마다 생존자 1인 1회 시간 연장/단축(±15초) | on / off | on | -| `voteSeconds` | 지목 투표 시간 | 10~60 | 20 | -| `defenseSeconds` | 최후의 반론 시간 | 10~60 | 20 | -| `confirmSeconds` | 찬반 투표 시간 | 5~30 | 10 | -| `nightSeconds` | 밤 시간 | 15~90 | 30 | +| `voteSeconds` | 지목 투표 시간 | 10~60 / 무제한 | 20 | +| `defenseSeconds` | 최후의 반론 시간 | 10~60 / 무제한 | 20 | +| `confirmSeconds` | 찬반 투표 시간 | 5~30 / 무제한 | 10 | +| `nightSeconds` | 밤 시간 | 15~90 / 무제한 | 30 | | `deathReveal` | 사망 시 공개 정보 | `none` / `team`(마피아 여부) / `role`(직업) | `team` | | `openVote` | 지목 투표에서 누가 누구를 찍었는지 공개 | on / off | on | | `doctorSelfHeal` | 의사 자기 치료 허용 | on / off | on | @@ -183,7 +183,7 @@ interface MafiaState { | `heal` | `{ target }` | 살아 있는 의사, night | 대상 생존, 자기면 `doctorSelfHeal`, 연속이면 `doctorRepeat` | | `mediumPeek` | `{ target }` | 살아 있는 영매, night | 대상 사망자 | | `phaseTimeout` | `{}` | 서버 내부(타이머) | `now >= phase.endsAt` | -| `readyEarly` | `{}` | 생존자, discussion | 생존자 전원이 누르면 토론 즉시 종료(선택 기능) | +| `readyEarly` | `{}` | 생존자, discussion (무제한 night: 생존자 「밤 마치기」, 무제한 defense: 피고 「반론 마치기」) | 생존자 전원이 누르면 토론 즉시 종료(선택 기능) | 페이즈 전환은 서버 타이머가 `phaseTimeout`을 apply하는 방식으로 일관되게 처리한다(재생 가능). @@ -205,6 +205,12 @@ interface MafiaState { - 연결 끊김: 진행은 멈추지 않는다. 같은 플레이어가 연속 2번의 낮 동안 접속하지 않으면 "자리 비움 탈락" 처리(사망과 동일, `deathReveal` 적용). 이후 승리 판정. - 재접속 시 현재 view 전체(허용된 채팅 기록 포함) 재전송. +- **시간 무제한**(단계별 옵션 값 `null`, `discussionPerAlive: null`이면 토론 무제한·최소/최대/±15초 안 씀): 그 단계는 `endsAt: null`이고 마감 대신 "모두 마침"으로 넘어간다. + - 토론: 생존자 전원 `readyEarly`. 지목 투표: 생존자 전원이 투표(기권 포함)하면 즉시 집계. 최후의 반론: 피고의 `readyEarly`. 찬반 투표: 피고를 뺀 생존자 전원이 찬반. 밤: 생존자 전원이 `readyEarly`(직업과 상관없이 모두 눌러서 누가 밤 행동을 하는지 드러나지 않음). + - 시간 초과 대상(`timeoutPlayers`)은 아직 안 마친 사람들. 연결이 끊긴 채 방의 유예 시간이 지나면 그 사람의 `phaseTimeout`이 "넘김"(투표 기권, 찬반 미투표, 토론·밤 마침, 피고면 반론 끝)으로 처리된다. 자리 비움(`idleDays`) 규칙은 그대로. + - 직업 확인·인사 시간은 고정 시간 그대로. + - 컴퓨터는 무제한 단계를 기본 시간(토론 90초, 투표·반론 20초, 찬반 10초, 밤 30초)처럼 맞춰 행동하고 버튼을 누른다. + ### 8.6 종료 조건과 결과(GameResult) ```ts interface MafiaResult { diff --git a/packages/games/src/mafia/bot.test.ts b/packages/games/src/mafia/bot.test.ts index b8b45eb..ecf3fd7 100644 --- a/packages/games/src/mafia/bot.test.ts +++ b/packages/games/src/mafia/bot.test.ts @@ -64,6 +64,17 @@ describe('whole games', () => { }, 60_000); } + test('every phase 무제한, computers only: they press 토론 끝내기·밤 마치기·반론 마치기 and vote, so every game ends', () => { + const options = opts({ discussionPerAlive: null, voteSeconds: null, defenseSeconds: null, confirmSeconds: null, nightSeconds: null }); + for (const n of [4, 6, 9, 12]) { + const r = liveBotPlayout(mafia, mafiaBot, { players: seats(n, 0), options, seed: seedN(700 + n), isBot }); + expect(r.finished).toBe(true); + expect(r.rejected).toEqual([]); + // Paced like the default clocks: neither instant nor endless. + expect(r.elapsed).toBeGreaterThan(60_000); + } + }, 60_000); + test('a mafia computer never points at its own team in the day chat', () => { for (let s = 1; s <= 12; s++) { const r = liveBotPlayout(mafia, mafiaBot, { players: seats(8, 0), seed: seedN(500 + s), isBot }); @@ -118,7 +129,7 @@ describe('timing and answers', () => { const rng = SeededRng.fromSeed(seedN(10)); let now = 0; while (st.phase.kind !== kind) { - now = st.phase.kind === 'ended' ? now : st.phase.endsAt; + now = st.phase.kind === 'ended' ? now : st.phase.endsAt!; st = mafia.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now }).state; } return { st, now, rng, players }; @@ -131,7 +142,7 @@ describe('timing and answers', () => { const quick = firstAction(st, bot, { smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!; const slow = firstAction(st, bot, { smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!; expect(quick.at).toBeLessThan(slow.at); - expect(slow.at).toBeLessThan(st.options.voteSeconds * 1000); + expect(slow.at).toBeLessThan(st.options.voteSeconds! * 1000); }); test('asked "컴퓨터 3 직업 뭐야?", computer 3 answers within seconds — and a mafia says it is a citizen', () => { diff --git a/packages/games/src/mafia/bot.ts b/packages/games/src/mafia/bot.ts index 3ff17c8..8ad9f56 100644 --- a/packages/games/src/mafia/bot.ts +++ b/packages/games/src/mafia/bot.ts @@ -148,6 +148,17 @@ interface Mention { tail: string; } +/** How a computer paces a 무제한 phase: like the default clock of that phase. */ +const UNLIMITED_PACE_MS: Record, number> = { + roleReveal: 8_000, + greeting: 60_000, + discussion: 90_000, + vote: 20_000, + defense: 20_000, + confirm: 10_000, + night: 30_000, +}; + class Reader { readonly v: MafiaView; readonly me: PlayerId; @@ -305,8 +316,11 @@ class MafiaBot { 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); } /** A moment inside the phase: `lo..hi` seconds after it started (scaled by pace), never later than `cap` of it. */ @@ -512,6 +526,8 @@ class MafiaBot { if (k === 'defense' && v.phase.accused === this.me) { out.push({ key: key('def1'), due: this.inPhase(1.5, 4, 'def1'), make: () => this.say('day', this.defenseLine(true)) }); if (this.smart || this.h('def2', v.day) < 0.5) out.push({ key: key('def2'), due: this.inPhase(7, 12, 'def2', 0.75), make: () => this.say('day', this.defenseLine(false)) }); + // 무제한: 반론 마치기 after the last line. + if (this.my.canReady) out.push({ key: key('defEnd'), due: this.inPhase(13, 17, 'defEnd', 0.95), make: () => ({ type: 'readyEarly' }) }); } if (k === 'confirm' && this.my.canConfirm && this.my.ballot === null) { @@ -530,6 +546,8 @@ class MafiaBot { } if (k === 'night') out.push(...this.night(key)); + // 무제한 night: 밤 마치기 after the night action (its latest time is earlier for the same pace). + if (k === 'night' && this.my.canReady) out.push({ key: key('nready'), due: this.inPhase(18, 24, 'nready', 0.95), make: () => ({ type: 'readyEarly' }) }); return out; } diff --git a/packages/games/src/mafia/index.ts b/packages/games/src/mafia/index.ts index 8dcfe58..9b2f504 100644 --- a/packages/games/src/mafia/index.ts +++ b/packages/games/src/mafia/index.ts @@ -3,7 +3,9 @@ * * The server runs the phases: every phase has `endsAt`; the room timer applies the system-only * `phaseTimeout` there (one "driver" player, `timeoutNotBefore` keeps away players from firing it - * early). Chat lives in the state and the view filters it by channel permission (§5.6, §8.3). + * early). 무제한 phases (`endsAt` null) end when everyone needed is done instead; a player away past the + * room's grace period is passed by their own `phaseTimeout`. Chat lives in the state and the view filters + * it by channel permission (§5.6, §8.3). */ import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine'; import { @@ -126,13 +128,73 @@ const alive = (s: MafiaState) => s.players.filter((p) => p.alive); const isAlive = (s: MafiaState, id: PlayerId | null) => !!id && !!P(s, id)?.alive; type NightPhase = Extract; -function discussionMs(s: MafiaState): number { +/** Discussion length; null = 무제한. */ +function discussionMs(s: MafiaState): number | null { const o = s.options; + if (o.discussionPerAlive === null) return null; const lo = o.discussionMin; const hi = Math.max(o.discussionMin, o.discussionMax); return Math.min(hi, Math.max(lo, alive(s).length * o.discussionPerAlive)) * 1000; } +const ends = (now: number, ms: number | null) => (ms === null ? null : now + ms); +const endsIn = (now: number, sec: number | null) => (sec === null ? null : now + sec * 1000); + +/** 무제한 phase: the living players it still waits for (votes, ballots, 토론 끝내기 / 밤 마치기, the accused's 반론 마치기). */ +function awaited(s: MafiaState): PlayerId[] { + const ph = s.phase; + if (ph.kind === 'ended' || ph.endsAt !== null) return []; + const live = alive(s).map((p) => p.id); + switch (ph.kind) { + case 'greeting': + case 'discussion': + return live.filter((p) => !ph.ready.includes(p)); + case 'night': + return live.filter((p) => !(ph.ready ?? []).includes(p)); + case 'vote': + return live.filter((p) => ph.votes[p] === undefined); + case 'defense': + return isAlive(s, ph.accused) ? [ph.accused] : []; + case 'confirm': + return live.filter((p) => p !== ph.accused && ph.ballots[p] === undefined && !(ph.passed ?? []).includes(p)); + default: + return []; + } +} + +/** 무제한: the phase ends once nobody is awaited. */ +function settle(s: MafiaState, now: number, rng: Rng): void { + const ph = s.phase; + if (s.winner || ph.kind === 'ended' || ph.endsAt !== null || ph.kind === 'roleReveal') return; + if (awaited(s).length === 0) advance(s, now, rng); +} + +/** 무제한: the room moved on for `p` (away past the grace period): no vote / no ballot / done. */ +function pass(s: MafiaState, now: number, rng: Rng, p: PlayerId): void { + const ph = s.phase; + switch (ph.kind) { + case 'greeting': + case 'discussion': + if (!ph.ready.includes(p)) ph.ready.push(p); + break; + case 'night': + (ph.ready ??= []).push(p); + break; + case 'vote': + ph.votes[p] = 'abstain'; + break; + case 'defense': + advance(s, now, rng); + return; + case 'confirm': + (ph.passed ??= []).push(p); + break; + default: + break; + } + settle(s, now, rng); +} + function pushEvent(s: MafiaState, now: number, e: DistributiveOmit, day = s.day): void { s.events.push({ ...e, n: s.events.length + 1, at: now, day } as PublicEvent); } @@ -144,13 +206,14 @@ function startPhase(s: MafiaState, now: number, kind: 'greeting' | 'discussion' s.phase = { kind, startedAt: now, endsAt: now + GREETING_MS, ready: [] }; break; case 'discussion': - s.phase = { kind, startedAt: now, endsAt: now + discussionMs(s), adjustedBy: [], ready: [] }; + s.phase = { kind, startedAt: now, endsAt: ends(now, discussionMs(s)), adjustedBy: [], ready: [] }; break; case 'vote': - s.phase = { kind, startedAt: now, endsAt: now + s.options.voteSeconds * 1000, votes: {} }; + s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), votes: {} }; break; case 'night': - s.phase = { kind, startedAt: now, endsAt: now + s.options.nightSeconds * 1000, mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null }; + s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.nightSeconds), mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null }; + if (s.phase.endsAt === null) s.phase.ready = []; break; } pushEvent(s, now, { t: 'phase', kind }); @@ -318,7 +381,7 @@ function advance(s: MafiaState, now: number, rng: Rng): void { case 'vote': { const accused = resolveVote(s, now); if (accused) { - s.phase = { kind: 'defense', startedAt: now, endsAt: now + s.options.defenseSeconds * 1000, accused }; + s.phase = { kind: 'defense', startedAt: now, endsAt: endsIn(now, s.options.defenseSeconds), accused }; pushEvent(s, now, { t: 'phase', kind: 'defense' }); return; } @@ -326,7 +389,7 @@ function advance(s: MafiaState, now: number, rng: Rng): void { return; } case 'defense': - s.phase = { kind: 'confirm', startedAt: now, endsAt: now + s.options.confirmSeconds * 1000, accused: ph.accused, ballots: {} }; + s.phase = { kind: 'confirm', startedAt: now, endsAt: endsIn(now, s.options.confirmSeconds), accused: ph.accused, ballots: {} }; pushEvent(s, now, { t: 'phase', kind: 'confirm' }); return; case 'confirm': @@ -450,6 +513,8 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n if (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.alive ? ok : fail('이미 탈락했어요.'); @@ -470,9 +535,12 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n case 'adjustTime': if (ph.kind !== 'discussion') return fail('토론 시간에만 시간을 바꿀 수 있어요.'); if (!s.options.timeAdjust) return fail('이 방은 토론 시간을 바꿀 수 없어요.'); + if (ph.endsAt === null) return fail('이 방은 토론 시간이 무제한이에요.'); if (ph.adjustedBy.includes(actor)) return fail('시간 바꾸기는 하루에 한 번만 할 수 있어요.'); return a.delta === 15 || a.delta === -15 ? ok : fail('15초씩만 바꿀 수 있어요.'); case 'readyEarly': + if (ph.kind === 'night' && ph.endsAt === null) return (ph.ready ?? []).includes(actor) ? fail('이미 밤 마치기를 눌렀어요.') : ok; + if (ph.kind === 'defense' && ph.endsAt === null) return ph.accused === actor ? ok : fail('지목된 사람만 반론을 마칠 수 있어요.'); if (ph.kind !== 'discussion' && ph.kind !== 'greeting') return fail('지금은 토론 시간이 아니에요.'); return ph.ready.includes(actor) ? fail('이미 토론 끝내기를 눌렀어요.') : ok; case 'vote': @@ -534,6 +602,8 @@ function myView(s: MafiaState, me: PlayerState): MyView { const ph = s.phase; const mates = me.role === 'mafia' || me.role === 'lover' ? s.players.filter((p) => p.role === me.role && p.id !== me.id).map((p) => p.id) : []; const day = ph.kind === 'greeting' || ph.kind === 'discussion'; + const nightReady = ph.kind === 'night' && ph.endsAt === null ? (ph.ready ?? []) : null; + const defenseEnd = ph.kind === 'defense' && ph.endsAt === null && ph.accused === me.id; return { role: me.role, team: teamOf(me.role), @@ -543,15 +613,24 @@ function myView(s: MafiaState, me: PlayerState): MyView { voteTargets: ph.kind === 'vote' && me.alive ? alive(s).filter((p) => p.id !== me.id).map((p) => p.id) : [], ballot: ph.kind === 'confirm' && me.alive ? (ph.ballots[me.id] ?? null) : null, canConfirm: ph.kind === 'confirm' && me.alive && ph.accused !== me.id, - canAdjust: ph.kind === 'discussion' && me.alive && s.options.timeAdjust && !ph.adjustedBy.includes(me.id), - canReady: day && me.alive && !ph.ready.includes(me.id), - ready: day && ph.ready.includes(me.id), + canAdjust: ph.kind === 'discussion' && ph.endsAt !== null && me.alive && s.options.timeAdjust && !ph.adjustedBy.includes(me.id), + canReady: me.alive && ((day && !ph.ready.includes(me.id)) || (nightReady !== null && !nightReady.includes(me.id)) || defenseEnd), + ready: (day && ph.ready.includes(me.id)) || (nightReady?.includes(me.id) ?? false), night: ph.kind === 'night' && me.alive ? nightView(s, me) : null, results: s.privateResults.filter((r) => r.to === me.id), idleWarning: me.alive && !s.winner && me.idleDays >= AWAY_DAYS - 1 && !me.activeToday, }; } +/** Ready / done counts for the phase banner (무제한 vote, ballots and night too). */ +function doneCounts(s: MafiaState, day: boolean): { readyCount: number; readyNeeded: number } { + const ph = s.phase; + if (day && (ph.kind === 'greeting' || ph.kind === 'discussion')) return { readyCount: ph.ready.length, readyNeeded: alive(s).length }; + if (ph.kind === 'ended' || ph.endsAt !== null || (ph.kind !== 'vote' && ph.kind !== 'confirm' && ph.kind !== 'night')) return { readyCount: 0, readyNeeded: 0 }; + const need = ph.kind === 'confirm' ? alive(s).filter((p) => p.id !== ph.accused).length : alive(s).length; + return { readyCount: need - awaited(s).length, readyNeeded: need }; +} + function view(s: MafiaState, viewer: PlayerId | null): MafiaView { const me = viewer ? (P(s, viewer) ?? null) : null; const ph = s.phase; @@ -573,8 +652,7 @@ function view(s: MafiaState, viewer: PlayerId | null): MafiaView { endsAt: ph.kind === 'ended' ? null : ph.endsAt, accused: ph.kind === 'defense' || ph.kind === 'confirm' ? ph.accused : null, adjustedBy: ph.kind === 'discussion' ? [...ph.adjustedBy] : [], - readyCount: day ? ph.ready.length : 0, - readyNeeded: day ? alive(s).length : 0, + ...doneCounts(s, day), }, players: s.players.map((p) => { const known = roleKnown(s, p, me); @@ -661,7 +739,8 @@ export const mafia: Def = { if (a.type !== 'phaseTimeout' && a.type !== 'leave') p.activeToday = true; switch (a.type) { case 'phaseTimeout': - advance(s, now, rng); + if (ph.kind !== 'ended' && ph.endsAt === null) pass(s, now, rng, actor); + else advance(s, now, rng); break; case 'leave': leave(s, now, rng, p); @@ -676,10 +755,19 @@ export const mafia: Def = { case 'adjustTime': if (ph.kind !== 'discussion') throw new Error('mafia: adjustTime outside discussion'); ph.adjustedBy.push(actor); + if (ph.endsAt === null) throw new Error('mafia: adjustTime in a 무제한 discussion'); ph.endsAt = a.delta > 0 ? ph.endsAt + ADJUST_MS : Math.max(ph.endsAt - ADJUST_MS, Math.min(ph.endsAt, now + ADJUST_FLOOR_MS)); pushEvent(s, now, { t: 'adjust', p: actor, delta: a.delta }); break; case 'readyEarly': + if (ph.kind === 'defense') { + advance(s, now, rng); + break; + } + if (ph.kind === 'night') { + (ph.ready ??= []).push(actor); + break; + } if (ph.kind !== 'discussion' && ph.kind !== 'greeting') throw new Error('mafia: readyEarly outside discussion'); ph.ready.push(actor); if (alive(s).every((x) => ph.ready.includes(x.id))) advance(s, now, rng); @@ -704,6 +792,7 @@ export const mafia: Def = { ph[a.type] = a.target; break; } + if (a.type !== 'chat') settle(s, now, rng); // Only public announcements become events (chat and night choices stay in the filtered view). const events: GameEvent[] = s.events.slice(before).map((e) => ({ ...e, type: e.t })); return { state: s, events }; @@ -717,9 +806,10 @@ export const mafia: 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. */ @@ -756,7 +846,7 @@ export const mafia: Def = { if (!p || s.winner || s.phase.kind === 'ended') return []; const out: MafiaAction[] = [{ type: 'phaseTimeout' }]; for (const ch of CHANNELS) if (!writeBlock(s, p, ch)) out.push({ type: 'chat', channel: ch, text: `m${s.seq}-${player}-${ch}` }); - if (!p.alive) return out; + if (!p.alive) return out.filter((a) => validate(s, player, a).ok); const ph = s.phase; const me = myView(s, p); if (me.canReady) out.push({ type: 'readyEarly' }); @@ -781,4 +871,4 @@ export const mafia: Def = { }, }; -export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs }; +export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs, awaited }; diff --git a/packages/games/src/mafia/mafia.test.ts b/packages/games/src/mafia/mafia.test.ts index 1bbacfd..49655fb 100644 --- a/packages/games/src/mafia/mafia.test.ts +++ b/packages/games/src/mafia/mafia.test.ts @@ -46,7 +46,7 @@ function reject(s: MafiaState, actor: PlayerId, a: MafiaAction, now?: number): s /** The phase clock runs out. */ function tick(s: MafiaState): MafiaState { 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!); } /** Ticks until `kind` (stops early if the game ends). */ function until(s: MafiaState, kind: MafiaState['phase']['kind']): MafiaState { @@ -135,13 +135,13 @@ describe('직업 배분 (§4)', () => { test('토론 시간 = clamp(생존자 × 값, 최소, 최대)', () => { const s = until(busy(until(rig(['mafia', 'police', 'doctor', 'citizen', 'citizen']), 'night')), 'discussion'); - expect(s.phase.kind === 'discussion' && s.phase.endsAt - s.phase.startedAt).toBe(75_000); // 5 × 15 + expect(s.phase.kind === 'discussion' && s.phase.endsAt! - s.phase.startedAt).toBe(75_000); // 5 × 15 let t = until(rig(['mafia', 'police', 'doctor', 'citizen'], { discussionPerAlive: 10, discussionMin: 60 }), 'night'); t = tick(t); - expect(t.phase.kind === 'discussion' && t.phase.endsAt - t.phase.startedAt).toBe(60_000); + expect(t.phase.kind === 'discussion' && t.phase.endsAt! - t.phase.startedAt).toBe(60_000); let u = until(rig(['mafia', 'mafia', 'mafia', 'police', 'doctor', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen'], { discussionPerAlive: 20, discussionMax: 120 }), 'night'); u = tick(u); - expect(u.phase.kind === 'discussion' && u.phase.endsAt - u.phase.startedAt).toBe(120_000); + expect(u.phase.kind === 'discussion' && u.phase.endsAt! - u.phase.startedAt).toBe(120_000); }); }); @@ -610,17 +610,17 @@ describe('시간 조절·자리 비움·나가기 (§5.2, §8.5)', () => { test('timeAdjust: 1인 1일 1회, -15초로 5초 미만 내려가지 않음', () => { let s = day2(); const ph0 = s.phase as Extract; - const end0 = ph0.endsAt; + const end0 = ph0.endsAt!; s = act(s, 'P1', { type: 'adjustTime', delta: 15 }); expect((s.phase as typeof ph0).endsAt).toBe(end0 + 15_000); expect(reject(s, 'P1', { type: 'adjustTime', delta: -15 })).toBe('시간 바꾸기는 하루에 한 번만 할 수 있어요.'); expect(lastEv(s, 'adjust')).toMatchObject({ p: 'P1', delta: 15 }); // 끝나기 8초 전에 -15 → 5초 남김 - s = act(s, 'P2', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt - 8_000); + s = act(s, 'P2', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt! - 8_000); const now = end0 + 15_000 - 8_000; expect((s.phase as typeof ph0).endsAt).toBe(now + 5_000); // 이미 5초 미만이면 그대로 - s = act(s, 'P3', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt - 3_000); + s = act(s, 'P3', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt! - 3_000); expect((s.phase as typeof ph0).endsAt).toBe(now + 5_000); expect(mafia.view(s, null).phase.adjustedBy).toEqual(['P1', 'P2', 'P3']); // 다음 날에는 다시 가능 @@ -691,6 +691,93 @@ describe('시간 조절·자리 비움·나가기 (§5.2, §8.5)', () => { }); }); +describe('시간 무제한 (§8.5)', () => { + const U = { discussionPerAlive: null, voteSeconds: null, defenseSeconds: null, confirmSeconds: null, nightSeconds: null }; + const roles: Role[] = ['mafia', 'police', 'doctor', 'citizen', 'citizen']; + const live = (s: MafiaState) => s.players.filter((p) => p.alive).map((p) => p.id); + + test('모든 단계 무제한: 마감 없이 모두 마칠 때까지 기다리고, 기다리는 사람만 시간 초과 대상', () => { + // Role reveal and greeting keep their fixed clocks. + let s = until(busy(rig(roles, U)), 'night'); + expect(s.phase.kind === 'night' && s.phase.endsAt).toBeNull(); + expect(mafia.deadline!(s)).toBeNull(); + expect(mafia.timeoutNotBefore!(s)).toBeNull(); + expect(mafia.timeoutPlayers!(s)).toEqual(live(s)); + s = act(s, 'P0', { type: 'mafiaTarget', target: 'P3' }); + for (const p of ['P0', 'P1', 'P2', 'P3']) s = act(s, p, { type: 'readyEarly' }); + expect(reject(s, 'P0', { type: 'readyEarly' })).toBe('이미 밤 마치기를 눌렀어요.'); + expect(s.phase.kind).toBe('night'); + expect(mafia.view(s, 'P1').phase).toMatchObject({ readyCount: 4, readyNeeded: 5 }); + expect(mafia.timeoutPlayers!(s)).toEqual(['P4']); + expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.'); + s = act(s, 'P4', { type: 'readyEarly' }, T0 + 3_600_000); + expect(s.phase.kind).toBe('discussion'); + expect(pl(s, 'P3').alive).toBe(false); + // Discussion: no ±15초; everybody alive presses 토론 끝내기. + const v = mafia.view(s, 'P1'); + expect(v.phase.endsAt).toBeNull(); + expect(v.my!.canAdjust).toBe(false); + expect(reject(s, 'P1', { type: 'adjustTime', delta: 15 })).toBe('이 방은 토론 시간이 무제한이에요.'); + for (const p of live(s)) s = act(s, p, { type: 'readyEarly' }); + expect(s.phase.kind).toBe('vote'); + // Vote: ends when every living player voted (abstain counts). + s = act(s, 'P1', { type: 'vote', target: 'P0' }); + s = act(s, 'P2', { type: 'vote', target: 'P0' }); + s = act(s, 'P0', { type: 'vote', target: 'P1' }); + expect(mafia.view(s, null).phase).toMatchObject({ readyCount: 3, readyNeeded: 4 }); + s = act(s, 'P4', { type: 'vote', target: 'abstain' }); + expect(s.phase.kind === 'defense' && s.phase.accused).toBe('P0'); + // Defense: only the accused ends it. + expect(reject(s, 'P1', { type: 'readyEarly' })).toBe('지목된 사람만 반론을 마칠 수 있어요.'); + expect(mafia.view(s, 'P0').my!.canReady).toBe(true); + expect(mafia.timeoutPlayers!(s)).toEqual(['P0']); + s = act(s, 'P0', { type: 'readyEarly' }); + expect(s.phase.kind).toBe('confirm'); + // Confirm: every voter but the accused. + s = act(s, 'P1', { type: 'confirm', choice: 'yes' }); + s = act(s, 'P2', { type: 'confirm', choice: 'yes' }); + expect(s.phase.kind).toBe('confirm'); + s = act(s, 'P4', { type: 'confirm', choice: 'no' }); + expect(s.winner).toBe('town'); + }); + + test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김(기권·투표 없음·마침), 토론 시간만 무제한도 가능', () => { + let s = until(busy(rig(roles, { voteSeconds: null, confirmSeconds: null })), 'vote'); + for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'vote', target: 'P0' }); + s = act(s, 'P0', { type: 'vote', target: 'P1' }); + expect(mafia.timeoutPlayers!(s)).toEqual(['P4']); + s = act(s, 'P4', mafia.onTimeout(s, 'P4')); + expect(lastEv(s, 'vote')!.votes!.P4).toBe('abstain'); + // Defense keeps its 20 s clock (driver P0), then a 무제한 confirm. + expect(s.phase.kind === 'defense' && s.phase.endsAt! - s.phase.startedAt).toBe(20_000); + s = tick(s); + expect(s.phase.kind).toBe('confirm'); + s = act(s, 'P1', { type: 'confirm', choice: 'no' }); + s = act(s, 'P2', { type: 'confirm', choice: 'no' }); + s = act(s, 'P3', mafia.onTimeout(s, 'P3')); + expect(s.phase.kind).toBe('confirm'); + s = act(s, 'P4', mafia.onTimeout(s, 'P4')); + expect(lastEv(s, 'confirm')).toMatchObject({ yes: 0, no: 2, outcome: 'spared' }); + expect(s.phase.kind).toBe('night'); + expect(s.phase.kind === 'night' && s.phase.endsAt! - s.phase.startedAt).toBe(30_000); + // Only the discussion without a clock. + let d = until(busy(until(rig(roles, { discussionPerAlive: null }), 'night')), 'discussion'); + expect(d.phase.kind === 'discussion' && d.phase.endsAt).toBeNull(); + for (const p of live(d).slice(1)) d = act(d, p, { type: 'readyEarly' }); + d = act(d, 'P0', mafia.onTimeout(d, 'P0')); + expect(d.phase.kind === 'vote' && d.phase.endsAt! - d.phase.startedAt).toBe(20_000); + }); + + test('무작위 대국(모든 단계 무제한)도 끝나고, 시간 초과 행동은 기다리는 사람에게 항상 합법', () => { + for (let i = 1; i <= 120; i++) { + const n = 4 + (i % 9); + const options = { ...presetFor(i, n), ...U } as MafiaOptions; + const a = fastPlayout(ids(n), options, seedN(9000 + i), 6000); + if (!a.finished) throw new Error(`seed ${i} (${n} players) did not finish`); + } + }, 60_000); +}); + describe('스키마', () => { test('옵션에 한국어 메타, 기본값', () => { const shape = (mafia.optionsSchema as unknown as { shape: Record }).shape; @@ -783,7 +870,12 @@ function fastPlayout(players: PlayerId[], options: MafiaOptions, seed: RngState, const pool = pick < 2 ? players : mafia.activePlayers(s); actor = pool[chooser.int(pool.length)]!; const legal = mafia.legalActions!(s, actor); - action = legal.length ? legal[chooser.int(legal.length)]! : mafia.onTimeout(s, actor); + if (legal.length) action = legal[chooser.int(legal.length)]!; + else { + // Nothing to do (무제한: not awaited): the room's timeout for someone the phase waits on instead. + actor = mafia.timeoutPlayers!(s)[0] ?? actor; + action = mafia.onTimeout(s, actor); + } } const v = mafia.validate(s, actor, action); if (!v.ok) throw new Error(`generated action rejected: ${v.reason} ${JSON.stringify(action)}`); @@ -858,8 +950,8 @@ describe(`무작위 대국 (시드 ${SEEDS}개, 4~12명)`, () => { while (!s.winner) { for (const p of [...s.players.map((x) => x.id)]) expect(mafia.validate(s, p, mafia.onTimeout(s, p)).ok).toBe(true); const ph = s.phase as Exclude; - expect(mafia.validate(s, 'P0', mafia.onTimeout(s, 'P0'), { now: ph.endsAt }).ok).toBe(true); - s = mafia.apply(s, 'P0', mafia.onTimeout(s, 'P0'), { rng: r, now: ph.endsAt }).state; + expect(mafia.validate(s, 'P0', mafia.onTimeout(s, 'P0'), { now: ph.endsAt! }).ok).toBe(true); + s = mafia.apply(s, 'P0', mafia.onTimeout(s, 'P0'), { rng: r, now: ph.endsAt! }).state; } // Only timeouts: nobody acts, so away eliminations end the game. expect(s.final!.cause === 'disconnect' || s.final!.cause === 'night').toBe(true); diff --git a/packages/games/src/mafia/types.ts b/packages/games/src/mafia/types.ts index 28d7d24..a4dbfa5 100644 --- a/packages/games/src/mafia/types.ts +++ b/packages/games/src/mafia/types.ts @@ -2,9 +2,11 @@ import { z } from 'zod'; import type { PlayerId } from '@bg/engine'; -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 and ends when everyone needed is done (§8.5). */ +const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl }); export const ROLES = ['mafia', 'police', 'doctor', 'citizen', 'soldier', 'politician', 'medium', 'lover'] as const; export type Role = (typeof ROLES)[number]; @@ -34,9 +36,10 @@ export const mafiaOptionsSchema = z.object({ .enum(['day', 'night']) .default('day') .meta({ title: '시작 페이즈', labels: { day: '인사하는 낮부터(투표 없음)', night: '밤부터' } }), - discussionPerAlive: lit(10, 15, 20) + /** null = 무제한 토론: ends when every living player pressed 토론 끝내기 (min/max and ±15초 do not apply). */ + discussionPerAlive: lit<10 | 15 | 20 | null>(10, 15, 20, null) .default(15) - .meta({ title: '토론 시간(살아 있는 사람 1명당)', labels: secLabels(10, 15, 20) }), + .meta({ title: '토론 시간(살아 있는 사람 1명당)', labels: secLabelsU('무제한(모두 토론 끝내기를 누를 때까지)', 10, 15, 20) }), discussionMin: lit(30, 45, 60, 90, 120) .default(60) .meta({ title: '토론 시간 최소', labels: secLabels(30, 45, 60, 90, 120) }), @@ -44,18 +47,18 @@ export const mafiaOptionsSchema = z.object({ .default(180) .meta({ title: '토론 시간 최대', labels: secLabels(60, 120, 180, 240, 300) }), timeAdjust: z.boolean().default(true).meta({ title: '하루 한 번 토론 시간 늘리기·줄이기(±15초)' }), - voteSeconds: lit(10, 15, 20, 30, 45, 60) + voteSeconds: lit<10 | 15 | 20 | 30 | 45 | 60 | null>(10, 15, 20, 30, 45, 60, null) .default(20) - .meta({ title: '지목 투표 시간', labels: secLabels(10, 15, 20, 30, 45, 60) }), - defenseSeconds: lit(10, 15, 20, 30, 45, 60) + .meta({ title: '지목 투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 10, 15, 20, 30, 45, 60) }), + defenseSeconds: lit<10 | 15 | 20 | 30 | 45 | 60 | null>(10, 15, 20, 30, 45, 60, null) .default(20) - .meta({ title: '최후의 반론 시간', labels: secLabels(10, 15, 20, 30, 45, 60) }), - confirmSeconds: lit(5, 10, 15, 20, 30) + .meta({ title: '최후의 반론 시간', labels: secLabelsU('무제한(지목된 사람이 반론 마치기를 누를 때까지)', 10, 15, 20, 30, 45, 60) }), + confirmSeconds: lit<5 | 10 | 15 | 20 | 30 | null>(5, 10, 15, 20, 30, null) .default(10) - .meta({ title: '찬반 투표 시간', labels: secLabels(5, 10, 15, 20, 30) }), - nightSeconds: lit(15, 20, 30, 45, 60, 90) + .meta({ title: '찬반 투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 5, 10, 15, 20, 30) }), + nightSeconds: lit<15 | 20 | 30 | 45 | 60 | 90 | null>(15, 20, 30, 45, 60, 90, null) .default(30) - .meta({ title: '밤 시간', labels: secLabels(15, 20, 30, 45, 60, 90) }), + .meta({ title: '밤 시간', labels: secLabelsU('무제한(모두 밤 마치기를 누를 때까지)', 15, 20, 30, 45, 60, 90) }), deathReveal: z .enum(['none', 'team', 'role']) .default('team') @@ -113,14 +116,18 @@ export interface PlayerState { export type Phase = | { kind: 'roleReveal'; startedAt: number; endsAt: number } | { kind: 'greeting'; startedAt: number; endsAt: number; ready: PlayerId[] } - | { kind: 'discussion'; startedAt: number; endsAt: number; adjustedBy: PlayerId[]; ready: PlayerId[] } - | { kind: 'vote'; startedAt: number; endsAt: number; votes: Record } - | { kind: 'defense'; startedAt: number; endsAt: number; accused: PlayerId } - | { kind: 'confirm'; startedAt: number; endsAt: number; accused: PlayerId; ballots: Record } + // endsAt null = 무제한 (that phase's seconds option is null): it ends when everyone needed is done (§8.5). + | { kind: 'discussion'; startedAt: number; endsAt: number | null; adjustedBy: PlayerId[]; ready: PlayerId[] } + | { kind: 'vote'; startedAt: number; endsAt: number | null; votes: Record } + | { kind: 'defense'; startedAt: number; endsAt: number | null; accused: PlayerId } + /** `passed`: 무제한 only, voters the room moved on while away (no ballot). */ + | { kind: 'confirm'; startedAt: number; endsAt: number | null; accused: PlayerId; ballots: Record; passed?: PlayerId[] } | { kind: 'night'; startedAt: number; - endsAt: number; + endsAt: number | null; + /** 무제한 only: who pressed 밤 마치기 (everybody alive must, so it shows nothing about roles). */ + ready?: PlayerId[]; mafiaTarget: PlayerId | null; mafiaPickedBy: PlayerId | null; investigate: PlayerId | null; @@ -270,6 +277,7 @@ export interface MafiaView { accused: PlayerId | null; /** Discussion: who used ±15초 today (public). */ adjustedBy: PlayerId[]; + /** Greeting/discussion: 토론 끝내기; 무제한 vote/confirm/night: how many are done. */ readyCount: number; readyNeeded: number; };