From b8966db2a68a535ec1b1d7c4914c6fd69e9d08ce Mon Sep 17 00:00:00 2001 From: EJClaw Date: Tue, 13 Oct 2026 13:01:42 +0900 Subject: [PATCH] =?UTF-8?q?=EA=B7=B8=EB=A6=BC=20=EB=A7=9E=ED=9E=88?= =?UTF-8?q?=EA=B8=B0=C2=B7=ED=81=B4=EB=A3=A8:=20=EA=B7=B8=EB=A6=AC?= =?UTF-8?q?=EA=B8=B0=C2=B7=EC=B0=A8=EB=A1=80=20=EC=8B=9C=EA=B0=84=20?= =?UTF-8?q?=EB=AC=B4=EC=A0=9C=ED=95=9C(=EC=B6=9C=EC=A0=9C=EC=9E=90=20?= =?UTF-8?q?=EC=A0=95=EB=8B=B5=20=EA=B3=B5=EA=B0=9C=EB=A1=9C=20=EB=84=98?= =?UTF-8?q?=EA=B8=B0=EA=B8=B0),=20=EC=86=8C=EB=A6=AC=C2=B7=EC=9B=80?= =?UTF-8?q?=EC=A7=81=EC=9E=84,=20=ED=95=A0=EB=A6=AC=EA=B0=88=EB=A6=AC?= =?UTF-8?q?=C2=B7=EC=82=AC=EA=B3=BC=20=EA=B2=8C=EC=9E=84=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EC=97=90=20=EB=AC=B4=EC=A0=9C=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/rooms/catchmind.room.test.ts | 23 ++- apps/web/src/games/catchmind/help.test.ts | 10 ++ apps/web/src/games/catchmind/help.ts | 2 +- apps/web/src/games/catchmind/index.tsx | 127 ++++++++++++-- apps/web/src/games/clue/index.tsx | 159 +++++++++++++++--- docs/games/apple.md | 11 +- docs/games/catchmind.md | 3 +- docs/games/clue.md | 3 +- docs/games/halli-galli.md | 4 +- .../games/src/catchmind/catchmind.test.ts | 60 +++++-- packages/games/src/catchmind/index.ts | 33 +++- packages/games/src/catchmind/types.ts | 18 +- packages/games/src/clue/clue.test.ts | 30 +++- packages/games/src/clue/index.ts | 7 +- packages/games/src/clue/types.ts | 7 +- 15 files changed, 413 insertions(+), 84 deletions(-) diff --git a/apps/server/src/rooms/catchmind.room.test.ts b/apps/server/src/rooms/catchmind.room.test.ts index 9b8234b..3500747 100644 --- a/apps/server/src/rooms/catchmind.room.test.ts +++ b/apps/server/src/rooms/catchmind.room.test.ts @@ -10,7 +10,7 @@ import { RoomStore } from './store'; type Msgs = ServerMessage[]; type StateMsg = Extract; -function harness(players: string[]) { +function harness(players: string[], options: Record = {}) { const db = openDb(':memory:'); const store = new RoomStore(db); let now = 1_000_000; @@ -19,7 +19,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: 'catchmind', - options: games.catchmind.defaultOptions, + options: { ...games.catchmind.defaultOptions, ...options }, maxPlayers: players.length, visibility: 'private', allowSpectators: true, @@ -170,12 +170,29 @@ describe('그림 맞히기 room flow', () => { expect(state().away).toEqual([d]); }); + test('그리기 무제한: 연결된 출제자는 타이머 없음, 연결이 끊기면 10초 뒤 턴 종료', () => { + const { room, clock, conns, state, act } = harness(['A', 'B'], { drawSeconds: null, hints: 'basic' }); + const d = state().turn.drawer; + act(d, { type: 'chooseWord', index: 0 }); + expect(state().turn.endsAt).toBeNull(); + expect(room.effectiveDeadline()).toBeNull(); + clock.advance(600_000); + expect(state().turn.phase).toBe('drawing'); + room.disconnect(conns[d]!); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(clock.now() + 10_000); + clock.advance(10_000); + room.onTimer(); + room.clearTimer(); + expect(state().turn.endReason).toBe('drawerAway'); + }); + test('연결된 출제자는 힌트·시간 만료 때만 tick(10초 지나도 끝나지 않음)', () => { const { room, clock, state, act } = harness(['A', 'B']); const d = state().turn.drawer; act(d, { type: 'chooseWord', index: 0 }); const t0 = state().turn.startedAt; - const ends = state().turn.endsAt; + const ends = state().turn.endsAt!; expect(room.effectiveDeadline()).toBe(t0 + (ends - t0) / 2); clock.advance(20_000); room.onTimer(); diff --git a/apps/web/src/games/catchmind/help.test.ts b/apps/web/src/games/catchmind/help.test.ts index 0cd2d60..b4206d6 100644 --- a/apps/web/src/games/catchmind/help.test.ts +++ b/apps/web/src/games/catchmind/help.test.ts @@ -57,3 +57,13 @@ test('그림 맞히기: 공개 / 끝', () => { s.final = { ranking: [], turns: [], summary: '호랑이님 우승!' }; expect(helpNow(view(s, null), null, users)).toContain('호랑이님 우승!'); }); + +test('그림 맞히기: 그리기 무제한이면 출제자에게 정답 공개 안내', async () => { + const { setupGame, usersOf } = await import('../help-kit.test-util'); + const { GAMES } = await import('@bg/games'); + const users = usersOf(['A', 'B', 'C']); + const { state } = setupGame('catchmind', 3, { drawSeconds: null, wordChoice: false }); + const d: string = state.turn.drawer; + const t = helpNow(GAMES.catchmind!.view(state, d) as never, d, users); + expect(t).toContain('[정답 공개하고 넘기기]'); +}); diff --git a/apps/web/src/games/catchmind/help.ts b/apps/web/src/games/catchmind/help.ts index 1a7f729..8d99bc4 100644 --- a/apps/web/src/games/catchmind/help.ts +++ b/apps/web/src/games/catchmind/help.ts @@ -32,7 +32,7 @@ export function helpNow(v: CatchmindView, me: string | null, players: Record, id: string) => players[id]?.nickname ?? '나간 사람'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '나간 사람', avatar: null, kind: 'guest' }; +/** Game sounds on top of the shared palette (site volume applies). */ +const cmSound = { + /** Pencil touching the paper (drawer's own strokes only). */ + scribble: () => noise(50, 0.05, 0, 'highpass', 4500), + /** A hint letter turned over. */ + hint: () => { + tone(880, 70, 'triangle', 0.1); + tone(1320, 110, 'triangle', 0.08, 60); + }, + /** Somebody else got it. */ + otherCorrect: () => tone(1175, 120, 'triangle', 0.1), + /** "아까워요!" (only the sender sees it). */ + close: () => tone(700, 90, 'triangle', 0.1, 0, { slideTo: 600 }), + /** The drawer's reaction button (heard by the guessers). */ + react: () => tone(990, 60, 'sine', 0.08), +}; + const CSS = ` .cm { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 8px; align-self: center; } .cm-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: space-between; font-weight: 700; } @@ -139,6 +156,12 @@ const CSS = ` .cm-form { display: flex; gap: 6px; } .cm-form .input { flex: 1; min-height: 48px; font-size: 1.05rem; } .cm-close { color: var(--warning); font-weight: 900; font-size: .95rem; animation: cm-shake .4s ease; } +.cm-over { animation: fade .25s ease both; } +.cm-over .word { animation: cm-word .5s cubic-bezier(.3,1.6,.5,1) both; animation-delay: .1s; } +.cm-hint .ch.flip { animation: anim-flip .42s ease both; } +.cm-strip .p .sc, .cm-score strong { display: inline-block; } +.cm-unl { font-weight: 800; color: var(--text-sub); font-size: .92rem; } +@keyframes cm-word { from { transform: scale(.3) rotate(-6deg); opacity: 0; } } .cm-away { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; background: var(--warning-soft); color: var(--text); border-radius: 12px; padding: 8px 12px; } @keyframes cm-pop { 0% { transform: translate(-50%, -50%) scale(.5); opacity: 0; } 70% { transform: translate(-50%, -50%) scale(1.08); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } } @keyframes cm-shake { 0%,100% { transform: none; } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } } @@ -156,7 +179,7 @@ const CSS = ` .cm-hint .ch { min-width: 34px; height: 40px; font-size: 1.35rem; } } @media (prefers-reduced-motion: reduce) { - .cm-pop, .cm-close { animation: none; } + .cm-pop, .cm-close, .cm-over, .cm-over .word, .cm-hint .ch.flip { animation: none; } .cm-bar i { transition: none; } } `; @@ -507,6 +530,7 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a sender.begin(t.c, t.w, ex, x, y); drawing.apply({ k: 'b', s: sender.stroke, c: t.c, w: t.w, e: ex }); drawing.addPoint(x, y); + cmSound.scribble(); }; const onMove = (e: React.PointerEvent) => { if (active.current !== e.pointerId) return; @@ -606,6 +630,7 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a ))} + {v.options.drawSeconds === null && } {!wide && 그리는 동안에는 채팅 대신 반응 버튼만 쓸 수 있어요.} )} @@ -613,6 +638,29 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a ); } +/** 무제한 drawings: the drawer may open the answer (press twice). */ +function GiveUp({ act }: { act: (a: unknown) => void }) { + const [ask, setAsk] = useState(false); + useEffect(() => { + if (!ask) return; + const t = setTimeout(() => setAsk(false), 3000); + return () => clearTimeout(t); + }, [ask]); + return ( + + ); +} + const END_TEXT: Record = { time: '시간이 다 됐어요', allSolved: '모두 맞혔어요!', @@ -620,6 +668,7 @@ const END_TEXT: Record = { report: '글자를 썼다는 신고로 끝났어요(출제자 0점)', drawerAway: '출제자의 연결이 끊겼어요', drawerLeft: '출제자가 나갔어요', + giveUp: '출제자가 정답을 공개했어요', }; function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string | null; act: (a: unknown) => void; players: Record; onSave: () => void }) { @@ -663,7 +712,12 @@ function OverlayMain({ v, act, players, onSave }: { v: CatchmindView; act: (a: u

그릴 단어를 골라 주세요

{v.choices.map((c, i) => ( -
@@ -807,7 +875,7 @@ function ScoreList({ v, me, players }: { v: CatchmindView; me: string | null; pl ✓ 맞힘 )} - + {v.scores[id] ?? 0}점 @@ -917,7 +985,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st {v.chat.map((m) => { const { cls, body } = chatLine(m, me, players, v.drawer); return ( -
  • +
  • {body}
  • ); @@ -983,8 +1051,40 @@ function AwayBanner({ v, me, act }: { v: CatchmindView; me: string | null; act: ); } +/** Sounds for what happens on the table (my own "정답!" is played by the overlay). */ +function useTableSounds(v: CatchmindView, me: string | null): void { + const prev = useRef(v); + useEffect(() => { + const p = prev.current; + prev.current = v; + if (p === v) return; + const turnChanged = p.turnNo !== v.turnNo; + if (turnChanged && v.phase === 'choosing') { + if (v.drawer === me) { + sounds.myTurn(); + sfx.deal(v.choices?.length ?? 1); + } else sfx.whoosh(); + } + if (v.phase === 'drawing' && (p.phase !== 'drawing' || turnChanged)) sfx.whoosh(); + if (!turnChanged && v.phase === 'drawing' && v.hintStage > p.hintStage) cmSound.hint(); + // New chat lines: someone else got it, the drawer reacted, my "아까워요". + const seen = p.chat.at(-1)?.id ?? 0; + const fresh = v.chat.filter((m) => m.id > seen); + if (fresh.some((m) => m.kind === 'correct' && m.from !== me)) cmSound.otherCorrect(); + if (v.role !== 'drawer' && fresh.some((m) => m.kind === 'reaction')) cmSound.react(); + if (fresh.some((m) => m.kind === 'close' && m.from === me)) cmSound.close(); + if (!turnChanged && p.phase === 'drawing' && v.phase === 'reveal') { + if (v.endReason === 'report') sfx.alarm(); + else if (v.endReason === 'allSolved') sfx.fanfare(); + else if (v.solvers.length === 0) sfx.bad(); + else sfx.cardFlip(); + } + }, [v]); // eslint-disable-line react-hooks/exhaustive-deps +} + function CatchmindBoard({ view: v, me, players, act, pending }: BoardProps) { const wide = useWide(); + useTableSounds(v, me); return (
    @@ -1068,7 +1168,7 @@ function statusText(v: CatchmindView, 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]) => ( @@ -1137,9 +1237,11 @@ function Options({ value: o, onChange }: OptionsProps) { [80, '80초'], [100, '100초'], [120, '120초'], + [null, '무제한'], ]} onChange={(drawSeconds) => set({ drawSeconds })} /> + {o.drawSeconds === null && 맞힐 때까지 그려요. 아무도 못 맞히면 출제자가 [정답 공개하고 넘기기]로 넘겨요. 힌트는 80초 기준으로 나와요.} ) { function optionsSummary(o: CatchmindOptions): string { const hint = o.hints === 'full' ? '힌트 많이' : o.hints === 'basic' ? '글자 수 힌트' : '힌트 없음'; const diff = o.difficulty === 'easy' ? '쉬운 단어' : o.difficulty === 'normal' ? '보통 단어' : ''; - return [o.guessMode === 'multi' ? '여러 명 맞히기' : '첫 정답자만', `${o.rounds}라운드`, `${o.drawSeconds}초`, hint, diff, o.customOnly ? '추가 단어만' : ''].filter(Boolean).join(' · '); + return [o.guessMode === 'multi' ? '여러 명 맞히기' : '첫 정답자만', `${o.rounds}라운드`, o.drawSeconds === null ? '그리기 무제한' : `${o.drawSeconds}초`, hint, diff, o.customOnly ? '추가 단어만' : ''].filter(Boolean).join(' · '); } // ---------------------------------------------------------------- rules @@ -1223,7 +1325,7 @@ function Rules({ options }: { options?: CatchmindOptions }) {

    한 사람(출제자)이 제시어를 그림으로 그리고, 나머지는 그림을 보며 채팅으로 정답을 맞혀요. 차례대로 돌아가며 모두 한 번씩 그리면 1라운드예요 - {o ? `(이 방은 ${o.rounds}라운드, 그리기 ${o.drawSeconds}초)` : ''}. + {o ? `(이 방은 ${o.rounds}라운드, 그리기 ${o.drawSeconds === null ? '시간 무제한' : `${o.drawSeconds}초`})` : ''}.

    출제자는 단어 3개 중 하나를 10초 안에 골라요. 그리는 동안에는 글자를 쓰면 안 되고, 채팅 대신 "거의 다 왔어요" 같은 반응 버튼만 쓸 수 있어요. 글자를 쓰면 맞히는 사람들이 신고할 수 있어요. @@ -1234,7 +1336,10 @@ function Rules({ options }: { options?: CatchmindOptions }) { : '먼저 맞힐수록 점수가 커요: 10점, 8점, 6점, 그다음부터 4점. 출제자는 맞힌 사람 1명마다 2점(최대 12점)을 받아요.'}{' '} 띄어쓰기·문장부호는 무시하고, "사과요"처럼 끝에 붙인 말도 정답으로 봐요. 거의 맞히면 나에게만 "아까워요!"가 떠요.

    -

    시간이 지나면 힌트가 나와요: 처음엔 글자 수, 절반이 지나면 초성, 3/4이 지나면 한 글자. 점수가 같으면 많이 맞힌 사람이 앞서요.

    +

    + 시간이 지나면 힌트가 나와요: 처음엔 글자 수, 절반이 지나면 초성, 3/4이 지나면 한 글자.{' '} + {o?.drawSeconds === null ? '그리기 시간이 무제한이면 40초에 초성, 60초에 한 글자가 나오고, 아무도 못 맞히면 출제자가 정답을 공개하고 넘길 수 있어요. ' : ''}점수가 같으면 많이 맞힌 사람이 앞서요. +

    ); } diff --git a/apps/web/src/games/clue/index.tsx b/apps/web/src/games/clue/index.tsx index fec2a03..da642fe 100644 --- a/apps/web/src/games/clue/index.tsx +++ b/apps/web/src/games/clue/index.tsx @@ -1,5 +1,5 @@ /** 클루 화면 (docs/games/clue.md §9). */ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import type { ClueOptions, ClueView, SuggestionView } from '@bg/games/clue'; import { PASSAGES, @@ -23,7 +23,7 @@ import { import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; -import { haptic, sounds } from '../../lib/feedback'; +import { haptic, sfx, sounds, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -55,12 +55,29 @@ const ro = (word: string) => { }; const lastOf = (xs: readonly T[]): T | undefined => xs[xs.length - 1]; +/** Clock length for the timer ring (무제한 has no deadline, so the ring only shows for away players' grace). */ function totalMsOf(v: ClueView): number { if (v.phase.kind === 'refute') return 20_000; if ((v.idle[v.current] ?? 0) >= 3) return 10_000; - return v.options.turnSeconds * 1000; + return (v.options.turnSeconds ?? 60) * 1000; } +/** Game sounds on top of the shared palette (site volume applies). */ +const clSound = { + /** "그건 바로…!" a suggestion is made: a low questioning motif. */ + suggest: () => [330, 392, 466].forEach((f, i) => tone(f, 150, 'triangle', 0.1, i * 110)), + /** Nobody could show a card: a suspenseful low "dun-dun". */ + noneShown: () => { + tone(196, 260, 'sawtooth', 0.05); + tone(185, 420, 'sawtooth', 0.05, 280); + }, + /** Walking a few squares in the hallway. */ + steps: (n: number) => { + for (let i = 0; i < Math.min(4, n); i++) tone(i % 2 ? 520 : 440, 45, 'triangle', 0.09, i * 120); + }, +}; +const posKey = (p: Pos) => JSON.stringify(p); + /** The player the game waits on (refuter while a card is being chosen). */ const waitingOn = (v: ClueView): string => (v.phase.kind === 'refute' ? v.phase.refuter : v.current); @@ -81,7 +98,7 @@ function knownCards(v: ClueView): Map { } const CSS = ` -.cl-board { width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; } +.cl-board { position: relative; width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; } .cl-top { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 12px; align-items: start; } .cl-map { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-rows: repeat(4, minmax(84px, auto)); grid-template-areas: "k b c" "d m bi" "d m li" "lo h s"; gap: 6px; background: var(--wood); padding: 8px; border-radius: var(--radius-lg); box-shadow: var(--shadow); } @@ -133,7 +150,15 @@ button.cl-room:disabled { cursor: default; } button.cl-card { cursor: pointer; font: inherit; font-weight: 800; font-size: .8rem; } button.cl-card:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); } -.cl-card.new { animation: cl-pop .6s ease-out; } +.cl-card.new { animation: cl-pop .6s ease-out; animation-delay: var(--anim-delay, 0ms); animation-fill-mode: both; } +.cl-dice span { display: inline-block; } +.cl-room.landed { animation: cl-land .7s ease-out; } +.cl-banner { position: absolute; left: 50%; top: 30%; translate: -50% 0; z-index: 8; pointer-events: none; border-radius: 18px; padding: 12px 22px; font-weight: 900; font-size: 1.35rem; + background: var(--surface); box-shadow: 0 10px 30px rgba(0,0,0,.35); text-align: center; white-space: nowrap; max-width: 92vw; overflow: hidden; text-overflow: ellipsis; } +.cl-banner.ok { border: 4px solid var(--success); color: var(--success); } +.cl-banner.bad { border: 4px solid var(--danger); color: var(--danger); } +.cl-banner.info { border: 4px solid var(--primary); color: var(--text); } +@keyframes cl-land { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--focus) 80%, transparent); } 100% { box-shadow: 0 0 0 12px transparent; } } @keyframes cl-pop { 0% { transform: scale(.6) rotate(-8deg); opacity: .2; } 100% { transform: none; opacity: 1; } } .cl-sec { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .cl-note { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; } @@ -166,20 +191,20 @@ button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); } .cl-note { grid-template-columns: minmax(0, 1fr); } .cl-card { width: 66px; min-height: 78px; } } -@media (prefers-reduced-motion: reduce) { .cl-card.new { animation: none; } } +@media (prefers-reduced-motion: reduce) { .cl-card.new, .cl-room.landed { animation: none; } } `; // ---------------------------------------------------------------- small pieces -function Token({ x, me }: { x: Suspect; me?: boolean }) { +function Token({ x, me, pop }: { x: Suspect; me?: boolean; pop?: boolean }) { return ( - + {SUSPECT_SHORT[x]} ); } -function Card({ id, onClick, can, fresh, label }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string }) { +function Card({ id, onClick, can, fresh, label, delay }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string; delay?: number }) { const x = itemOf(id); const cat = categoryOf(x); const body = ( @@ -199,7 +224,7 @@ function Card({ id, onClick, can, fresh, label }: { id: string; onClick?: () => ); return ( - + {body} ); @@ -214,9 +239,67 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps) const [announce, setAnnounce] = useState(''); const prevTurn = useRef(`${v.current}|${v.turnNo}`); const prevSg = useRef(JSON.stringify(lastOf(v.suggestions) ?? null)); + const prevView = useRef(v); + const [banner, setBanner] = useState<{ key: string; kind: 'ok' | 'bad' | 'info'; text: string } | null>(null); + const [landed, setLanded] = useState<{ room: Room; key: number } | null>(null); useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]); + // Sounds and highlights for what anyone just did: dice, moves, passages, suggestions, answers, accusations. + useEffect(() => { + const p = prevView.current; + prevView.current = v; + if (p === v) return; + if (v.dice && (!p.dice || p.turnNo !== v.turnNo || p.dice[0] !== v.dice[0] || p.dice[1] !== v.dice[1])) sfx.dice(); + const mover = v.suspectOf[v.current]; + let moved = false; + for (const x of SUSPECTS) { + if (posKey(v.pos[x]) === posKey(p.pos[x])) continue; + moved = true; + const r = roomAt(v.pos[x]); + if (r && x === mover) setLanded({ room: r, key: Date.now() }); + } + const sgNew = v.suggestions.length > p.suggestions.length; + if (moved && !sgNew && mover) { + const from = roomAt(p.pos[mover]); + const to = roomAt(v.pos[mover]); + if (from && to && PASSAGES[from] === to && !v.dice) sfx.whoosh(); + else if (to) sfx.piece(); + else clSound.steps(v.dice ? v.dice[0] + v.dice[1] : 3); + } + if (sgNew) clSound.suggest(); + const lastNow = lastOf(v.suggestions); + const lastPrev = lastOf(p.suggestions); + if (lastNow && !sgNew && lastPrev && v.suggestions.length === p.suggestions.length && !lastPrev.refuter && lastNow.refuter) { + if (lastNow.shown && (lastNow.by === me || lastNow.refuter === me)) sfx.cardFlip(); + else sfx.cardDeal(); + } + if (lastNow && p.phase.kind === 'refute' && v.phase.kind !== 'refute' && !lastNow.refuter) clSound.noneShown(); + if (lastNow && sgNew && v.phase.kind === 'afterSuggest' && !lastNow.refuter) clSound.noneShown(); + if (v.accusations.length > p.accusations.length) { + const a = v.accusations[v.accusations.length - 1]!; + const who = a.by === me ? '내' : `${nick(players, a.by)}님의`; + if (a.correct) { + sfx.fanfare(); + setBanner({ key: `a${v.accusations.length}`, kind: 'ok', text: `⚖️ ${who} 고발이 맞았어요!` }); + } else { + sfx.bad(); + setBanner({ key: `a${v.accusations.length}`, kind: 'bad', text: `⚖️ ${who} 고발이 틀렸어요 · 탈락` }); + } + } + }, [v]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (!banner) return; + const t = setTimeout(() => setBanner(null), 1700); + return () => clearTimeout(t); + }, [banner]); + useEffect(() => { + if (!landed) return; + const t = setTimeout(() => setLanded(null), 800); + return () => clearTimeout(t); + }, [landed]); + useEffect(() => { const key = `${v.current}|${v.turnNo}`; if (key !== prevTurn.current && v.phase.kind !== 'finished') { @@ -250,11 +333,16 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps)
    - +
    {amPlayer && } {amPlayer && } + {banner && ( +
    + {banner.text} +
    + )}

    {announce}

    @@ -262,7 +350,21 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps) ); } -function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: string | null; myTurn: boolean; sel: Room | null; setSel: (r: Room | null) => void }) { +function Mansion({ + view: v, + me, + myTurn, + sel, + setSel, + landed, +}: { + view: ClueView; + me: string | null; + myTurn: boolean; + sel: Room | null; + setSel: (r: Room | null) => void; + landed: Room | null; +}) { const mySuspect = me ? v.suspectOf[me] : undefined; const myPos = mySuspect ? v.pos[mySuspect] : null; const here = myPos ? roomAt(myPos) : null; @@ -282,7 +384,7 @@ function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: str const can = picking && r !== here; const reach = can && (free || (d !== undefined && d <= sum)); const pass = PASSAGES[r]; - const cls = ['cl-room', can ? (reach ? 'reach' : 'far') : '', sel === r ? 'sel' : '', r === here ? 'here' : ''].filter(Boolean).join(' '); + const cls = ['cl-room', can ? (reach ? 'reach' : 'far') : '', sel === r ? 'sel' : '', r === here ? 'here' : '', landed === r ? 'landed' : ''].filter(Boolean).join(' '); const label = [ ROOM_KO[r], r === here ? '내가 있는 방' : '', @@ -302,10 +404,10 @@ function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: str {can && !free && d !== undefined && {d}칸} {toks.map((x) => ( - + ))} {weaps.map((w) => ( - + {WEAPON_ICON[w]} ))} @@ -337,7 +439,7 @@ function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: str const p = owner(x); return (
  • - + {hallwayText(v.pos[x])}
  • ); @@ -500,8 +602,8 @@ function ActionPanel({ {v.final?.summary} {v.solution && (
    - {[v.solution.suspect, v.solution.weapon, v.solution.room].map((x) => ( - + {[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => ( + ))}
    )} @@ -517,7 +619,7 @@ function ActionPanel({ {nick(players, sg.by)}님이 {ro(triple(sg))} 추리했어요 - 내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요. 20초 안에 안 고르면 자동으로 보여 줘요. + 내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요.{v.options.turnSeconds === null ? '' : ' 20초 안에 안 고르면 자동으로 보여 줘요.'}
    {(ph.canShow ?? []).map((c) => ( !pending && act({ type: 'show', card: c })} label={`${ITEM_KO[itemOf(c)]} 카드 보여 주기`} /> @@ -616,8 +718,12 @@ function ActionPanel({
    {v.dice && (
    - {DICE[v.dice[0]]} - {DICE[v.dice[1]]} + + {DICE[v.dice[0]]} + + + {DICE[v.dice[1]]} + = {sum}칸
    )} @@ -876,7 +982,7 @@ function statusText(v: ClueView, 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]) => ( @@ -914,16 +1020,18 @@ function Options({ value: o, onChange }: OptionsProps) { [45, '45초'], [60, '60초'], [90, '90초'], + [null, '무제한'], ]} onChange={(turnSeconds) => set({ turnSeconds })} /> + {o.turnSeconds === null && 차례와 카드 보여 주기에 시간 제한이 없어요. 연결이 끊긴 채 돌아오지 않는 사람만 자동으로 넘겨요.}
    ); } function optionsSummary(o: ClueOptions): string { - return [o.movement === 'free' ? '빠른 이동' : '주사위 이동', `차례 ${o.turnSeconds}초`].join(' · '); + return [o.movement === 'free' ? '빠른 이동' : '주사위 이동', o.turnSeconds === null ? '차례 시간 무제한' : `차례 ${o.turnSeconds}초`].join(' · '); } function Rules({ options }: { options?: ClueOptions }) { @@ -956,7 +1064,10 @@ function Rules({ options }: { options?: ClueOptions }) { 추리 노트: 화면 아래 노트에 내 카드, 공개 카드, 나에게 보여 준 카드가 자동으로 ✗ 표시돼요. 나머지는 직접 눌러 ✗·?·✓를 적어 두세요(이 기기에만 저장돼요).

    - 차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요. 게임 중에 나간 사람의 카드는 모두에게 공개돼요. + {options?.turnSeconds === null + ? '이 방은 차례 시간이 무제한이에요. 연결이 끊긴 채 돌아오지 않으면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요(카드 보여 주기는 맞는 카드가 자동으로).' + : '차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요.'}{' '} + 게임 중에 나간 사람의 카드는 모두에게 공개돼요.

    ); diff --git a/docs/games/apple.md b/docs/games/apple.md index 06c849f..fbef189 100644 --- a/docs/games/apple.md +++ b/docs/games/apple.md @@ -10,7 +10,7 @@ ## 2. 모드와 옵션 | 옵션 키 | 설명 | 선택지 | 기본값 | |---|---|---|---| -| `timeLimitSec` | 제한 시간 | 60(1분) / 120(2분) / 180(3분) | 120 (원작) | +| `timeLimitSec` | 제한 시간 | 60(1분) / 120(2분) / 180(3분) / 무제한 | 120 (원작) | - 판 크기는 원작의 17×10으로 **고정**한다(단순하게). 휴대폰에서는 판을 돌려서 보여 주므로 작은 판 옵션은 넣지 않았다. @@ -43,17 +43,17 @@ ### 8.1 상태(State) ```ts interface AppleState { - options: { timeLimitSec: 60 | 120 | 180 }; + options: { timeLimitSec: 60 | 120 | 180 | null }; // null = 무제한 order: PlayerId[]; initial: string; // 170자 '1'..'9' (행 우선), 공용 시작 판 boards: Record; // 각자 판, 지운 칸은 '0' score: Record; clears: Record; // 지운 횟수 - status: Record; + status: Record; // done = 무제한에서 「여기까지」 recent: Record; // 최근 고르기 서버 시각(속도 제한) phase: 'countdown' | 'playing' | 'ended'; countdownEndsAt: number; - endsAt: number; // countdownEndsAt + timeLimitSec + endsAt: number | null; // countdownEndsAt + timeLimitSec (무제한이면 null) final: AppleFinal | null; } ``` @@ -63,6 +63,7 @@ interface AppleState { | type | payload | 누가 / 언제 | 검증 조건 | |---|---|---|---| | `select` | `r0, c0, r1, c1` (행 0~9, 열 0~16, 정수) | 게임 중인 사람, 카운트다운 끝 ~ 마감 전 | 나가지 않음, 막히지 않음, 1초에 5번 이하, 안에 사과 1개 이상, 합 = 10 | +| `stop` | — | 「여기까지」, 무제한 방에서 게임 중인 사람 | 시작 뒤, 아직 `playing` | | `tick` | — | 서버 타이머 전용(스키마에 없음) | — | | `leave` | — | 서버(나가기) 전용 | 아직 게임 중 | @@ -78,7 +79,7 @@ interface AppleState { - `setup`의 판 생성만(`ctx.rng`). 모두 같은 판이라 운의 차이가 없다. 컴퓨터 운(셔플 여러 번 중 고르기)도 적용하지 않는다(턴 게임 전략에만 적용, `luckApplies`). ### 8.5 타이머·시간 초과·연결 끊김 -- `deadline`: 카운트다운 중 `countdownEndsAt`, 진행 중 `endsAt`(서버 시계). 마감 `tick`으로 끝난다. 마감 뒤 도착한 `select`는 `시간이 다 됐어요.`로 거절. +- `deadline`: 카운트다운 중 `countdownEndsAt`, 진행 중 `endsAt`(서버 시계). 마감 `tick`으로 끝난다. 마감 뒤 도착한 `select`는 `시간이 다 됐어요.`로 거절. 무제한이면 진행 중 마감이 없고, 모두 막히거나 「여기까지」(`stop`)를 누르면 끝난다. 연결이 끊긴 채 방의 유예 시간이 지난 사람은 `tick`으로 `done` 처리된다. - `timeoutPlayers`: 게임 중인 모두(막힌 사람 포함). - `timeoutNotBefore` = `deadline`: 연결이 끊긴 사람도 **일찍 시간 초과되지 않는다**(할 행동이 없음). 그 사람 점수는 그대로 남고 마감 때 순위에 들어간다. - 나가기: `leave` → 상태 `left`, 더는 못 고름. 여러 명으로 시작했는데 남은 사람이 1명이면 그 사람이 이긴 것으로 바로 끝, 아무도 안 남으면 끝. diff --git a/docs/games/catchmind.md b/docs/games/catchmind.md index 52f05d7..2929942 100644 --- a/docs/games/catchmind.md +++ b/docs/games/catchmind.md @@ -12,7 +12,7 @@ |---|---|---|---| | `guessMode` | 맞히기 방식 | `multi`(여러 명이 맞힐 때까지) / `firstOnly`(첫 정답자가 나오면 즉시 종료, 원조 캐치마인드식) | `multi` | | `rounds` | 라운드 수(1라운드 = 모두 1번씩 출제) | 1 / 2 / 3 | 2 | -| `drawSeconds` | 그리기 제한 시간 | 60 / 80 / 100 / 120 | 80 | +| `drawSeconds` | 그리기 제한 시간 | 60 / 80 / 100 / 120 / 무제한 | 80 | | `wordChoice` | 출제자가 3개 중 고르기 | on / off(무작위 1개) | on | | `categories` | 사용할 단어 분야 | 3.2 분야 다중 선택 | 전체 | | `difficulty` | 단어 난이도 | `easy` / `normal` / `mixed` | `mixed` | @@ -63,6 +63,7 @@ ### 5.2 그리기 종료 조건 - 시간 만료. +- `drawSeconds` 무제한(null): 마감이 없다. 출제자가 `giveUp`(「정답 공개하고 넘기기」, 두 번 눌러 확인)으로 끝낼 수 있다(`endReason: giveUp`, 출제자 점수는 평소처럼 맞힌 사람 수로). 힌트(`full`)와 속도 보너스는 80초 기준(40초 초성, 60초 한 글자). 연결이 끊긴 출제자는 평소처럼 10초 뒤 `drawerAway`. - `multi`: 출제자를 제외한 접속 중인 전원이 맞힘. - `firstOnly`: 첫 정답자가 나오는 즉시. - 출제자 연결 끊김 10초 경과(출제자 0점, 정답 공개). diff --git a/docs/games/clue.md b/docs/games/clue.md index 4b0fdae..6b11d98 100644 --- a/docs/games/clue.md +++ b/docs/games/clue.md @@ -10,7 +10,7 @@ | 옵션 키 | 설명 | 선택지 | 기본값 | |---|---|---|---| | `movement` | 이동 방식 | `dice` 주사위 2개로 복도 이동(원작처럼) / `free` 빠르게(아무 방이나 바로) | `dice` | -| `turnSeconds` | 차례 제한 시간(이동·추리·고발) | 30 / 45 / 60 / 90초 | 60 | +| `turnSeconds` | 차례 제한 시간(이동·추리·고발) | 30 / 45 / 60 / 90초 / 무제한 | 60 | 카드 보여 주기(반증)는 옵션 없이 20초. `free`는 노트 파일의 "이동을 줄이는 옵션이 있으면 좋다"를 반영한 하우스 룰이다. @@ -120,6 +120,7 @@ interface ClueState { ### 8.5 타이머·시간 초과·연결 끊김 - 차례 `turnSeconds`, 반증 20초. 내 차례를 3번 연속 시간 초과로 넘기면 그 사람 차례는 10초. +- `turnSeconds` 무제한(null): 차례와 반증 모두 마감이 없다. 연결이 끊긴 채 방의 유예 시간이 지난 사람만 아래처럼 자동 진행되고, 그렇게 3번 넘긴 사람은 무제한 방에서도 10초 차례가 된다. - 내 차례 시간 초과: 차례 하나를 통째로 자동 진행 — 주사위를 굴려 가장 가까운 닿는 방에 들어가고(없으면 가장 가까운 방 쪽으로 걸음), 추리 없이 끝낸다. 빠른 이동이면 가장 가까운 방. - 반증 시간 초과: 맞는 카드 중 첫 장(용의자→흉기→방 순)을 보여 준다. - 아직 고발하지 않은 사람이 모두 3번 연속 시간 초과 상태면 아무도 못 이기고 끝난다(`timeout`). 혼자 남은 자리 비운 사람 때문에 판이 끝나지 않는 것을 막는다. diff --git a/docs/games/halli-galli.md b/docs/games/halli-galli.md index 76e0d2c..74dea47 100644 --- a/docs/games/halli-galli.md +++ b/docs/games/halli-galli.md @@ -12,7 +12,7 @@ |---|---|---|---| | `endMode` | 종료 방식 | `lastStanding`(한 명이 모든 카드를 가질 때까지, 국내 통상 규칙) / `official`(2명 남으면 다음 종 판정으로 종료, 원작 규칙) | `lastStanding` | | `timeLimitMin` | 전체 제한 시간(분). 만료 시 카드 많은 사람 승 | 5 / 10 / 15 / 없음 | 10 | -| `flipSeconds` | 자기 차례에 뒤집기 제한 시간(초과 시 자동 뒤집기) | 2 / 3 / 5 / 8 | 3 | +| `flipSeconds` | 자기 차례에 뒤집기 제한 시간(초과 시 자동 뒤집기) | 2 / 3 / 5 / 8 / 무제한 | 3 | | `autoFlip` | 모든 뒤집기를 서버가 일정 간격으로 자동 진행 | on / off | off | | `flipGuardMs` | 뒤집기 직후 다음 뒤집기를 받지 않는 시간(지연 공정성) | 400 / 600 / 1000 | 600 | | `wrongRingLockoutMs` | 틀린 종 후 그 사람의 종 잠금 시간 | 0 / 1000 / 2000 | 1000 | @@ -55,7 +55,7 @@ ### 5.1 뒤집기 - 차례인 플레이어는 자기 덱 맨 위 카드를 뒤집어 자기 공개 더미 위에 놓는다. 그 다음 시계 방향으로 다음 "참가 중" 플레이어 차례. - 각 플레이어의 공개 더미 **맨 위 카드만** 셈에 들어간다. -- `flipSeconds` 안에 뒤집지 않으면 서버가 자동으로 뒤집는다. +- `flipSeconds` 안에 뒤집지 않으면 서버가 자동으로 뒤집는다. `무제한`(null)이면 차례 플레이어가 뒤집을 때까지 기다린다(연결이 끊긴 사람만 방의 유예 시간 뒤 자동 뒤집기). `autoFlip`과 함께면 3초(어린이 모드 8초) 간격으로 서버가 뒤집는다. - 뒤집은 직후 `flipGuardMs` 동안은 다음 사람의 뒤집기를 받지 않는다(예약해 두었다가 시간이 지나면 처리). 지연이 큰 사람도 같은 화면을 보고 종을 칠 시간을 보장하기 위함. ### 5.2 종 치기 diff --git a/packages/games/src/catchmind/catchmind.test.ts b/packages/games/src/catchmind/catchmind.test.ts index af4ecd6..06e02c5 100644 --- a/packages/games/src/catchmind/catchmind.test.ts +++ b/packages/games/src/catchmind/catchmind.test.ts @@ -202,7 +202,7 @@ describe('점수(§6)', () => { test('multi: 아무도 못 맞히면 출제자 0점, 시간 만료로 공개', () => { let s = drawWith(make(3), '기린'); const d = s.turn.drawer; - s = act(s, d, { type: 'tick' }, s.turn.endsAt); + s = act(s, d, { type: 'tick' }, s.turn.endsAt!); expect(s.turn.phase).toBe('reveal'); expect(s.turn.endReason).toBe('time'); expect(s.scores[d]).toBe(0); @@ -224,11 +224,42 @@ describe('점수(§6)', () => { test('speedBonus: 남은 시간 비율 × 5점 추가', () => { let s = drawWith(make(3, { speedBonus: true }), '기린', T0); const g = guessers(s)[0]!; - const dur = s.turn.endsAt - s.turn.startedAt; + const dur = s.turn.endsAt! - s.turn.startedAt; s = act(s, g, guess('기린'), T0 + dur / 2); expect(s.scores[g]).toBe(10 + 3); // round(2.5) }); + test('그리기 무제한: 마감 없음(힌트는 80초 기준), 출제자 정답 공개로 넘기기, 시간 제한 방에서는 거절', () => { + let s = drawWith(make(3, { drawSeconds: null, speedBonus: true }), '아이스크림', T0); + const d = s.turn.drawer; + const [a, b] = guessers(s) as [string, string]; + expect(s.turn.endsAt).toBeNull(); + expect(view(s, a).phaseMs).toBeNull(); + // Hints still come, at 40 s and 60 s (the 80 s reference); after them nothing is due. + expect(cm.deadline!(s)).toBe(T0 + 40_000); + s = act(s, d, { type: 'tick' }, T0 + 40_000); + expect(s.turn.hintStage).toBe(1); + s = act(s, d, { type: 'tick' }, T0 + 60_000); + expect(s.turn.hintStage).toBe(2); + expect(cm.deadline!(s)).toBeNull(); + // A guess long after "80 s" is still taken (speed bonus 0 by then). + s = act(s, a, guess('아이스크림'), T0 + 600_000); + expect(s.scores[a]).toBe(10); + expect(reason(s, a, { type: 'giveUp' })).toBe('출제자만 정답을 공개할 수 있어요.'); + s = act(s, d, { type: 'giveUp' }, T0 + 601_000); + expect(s.turn.phase).toBe('reveal'); + expect(s.turn.endReason).toBe('giveUp'); + expect(s.scores[d]).toBe(2); // one solver in multi mode + expect(view(s, b).word).toBe('아이스크림'); + const timed = drawWith(make(3), '기린'); + expect(reason(timed, timed.turn.drawer, { type: 'giveUp' })).toBe('제한 시간이 있는 방에서는 시간이 끝날 때까지 그려요.'); + // An away drawer is still timed out by the room (nothing else due → drawerAway). + let w = drawWith(make(3, { drawSeconds: null, hints: 'basic' }), '기린', T0); + expect(cm.deadline!(w)).toBeNull(); + w = act(w, w.turn.drawer, { type: 'tick' }, T0 + 30_000); + expect(w.turn.endReason).toBe('drawerAway'); + }); + test('신고 과반 → 즉시 종료, 출제자 0점(맞힌 사람 점수 유지)', () => { let s = drawWith(make(5), '기린'); const d = s.turn.drawer; @@ -367,16 +398,16 @@ describe('진행(§5.1, §5.2, §8.5)', () => { expect(s.turn.phase).toBe('drawing'); expect(s.turn.word!.word).toBe(c0); expect(s.away).toEqual([]); - s = act(s, first, { type: 'tick' }, s.turn.endsAt); + s = act(s, first, { type: 'tick' }, s.turn.endsAt!); expect(s.turn.phase).toBe('reveal'); expect(cm.deadline!(s)).toBe(s.turn.startedAt + REVEAL_MS); - s = act(s, first, { type: 'tick' }, s.turn.endsAt); + s = act(s, first, { type: 'tick' }, s.turn.endsAt!); expect(s.turn.drawer).not.toBe(first); expect(s.turn.no).toBe(2); const second = s.turn.drawer; s = act(s, second, { type: 'chooseWord', index: 2 }, s.turn.startedAt + 1000); - s = act(s, second, { type: 'tick' }, s.turn.endsAt); - s = act(s, second, { type: 'tick' }, s.turn.endsAt); + s = act(s, second, { type: 'tick' }, s.turn.endsAt!); + s = act(s, second, { type: 'tick' }, s.turn.endsAt!); expect(s.finished).toBe(true); const r = cm.result(s)!; expect(r.ranking.flat().sort()).toEqual(['p1', 'p2']); @@ -410,15 +441,15 @@ describe('진행(§5.1, §5.2, §8.5)', () => { // Skipped while away: the next drawers are the others. const seen: string[] = []; for (let i = 0; i < 2; i++) { - s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt); + s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!); seen.push(s.turn.drawer); s = act(s, s.turn.drawer, { type: 'chooseWord', index: 0 }, s.turn.startedAt + 100); - s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt); + s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!); } expect(seen).not.toContain(d); // "돌아왔어요" clears the mark. expect(reason(s, d, { type: 'back' })).toBeNull(); - s = act(s, d, { type: 'back' }, s.turn.endsAt - 1); + s = act(s, d, { type: 'back' }, s.turn.endsAt! - 1); expect(s.away).toEqual([]); expect(reason(s, d, { type: 'back' })).not.toBeNull(); }); @@ -431,7 +462,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => { expect(s.turn.phase).toBe('reveal'); expect(s.turn.endReason).toBe('drawerLeft'); expect(cm.onLeave!(s, d)).toBeNull(); - s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt); + s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!); expect(s.turn.drawer).not.toBe(d); const other = s.order.find((p) => p !== d && p !== s.turn.drawer)!; s = act(s, other, { type: 'leave' }, s.turn.startedAt + 100); @@ -454,7 +485,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => { let s = drawWith(make(4, { guessMode: 'firstOnly', answererDraws: true }), '기린'); const g = guessers(s)[2]!; s = act(s, g, guess('기린'), T0 + 2000); - s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt); + s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!); expect(s.turn.drawer).toBe(g); }); @@ -466,7 +497,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => { s.turnsPlayed = s.totalTurns - 1; s.round = s.options.rounds; s.turn.drawer = s.order.at(-1)!; - const r = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt); + const r = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!); expect(r.finished).toBe(true); expect(cm.result(r)!.ranking.map((g) => [...g].sort())).toEqual([['p2'], ['p1', 'p3'], ['p4']]); expect(r.final!.ranking.map((x) => x.rank)).toEqual([1, 2, 2, 4]); @@ -540,7 +571,8 @@ function fastPlayout(players: PlayerId[], options: CatchmindOptions, seed: RngSt invariants(s, poolSize); if (cm.result(s)) return { state: s, trace, steps: step }; // Timer: the drawer's tick when due (as the room would), otherwise a random actor. - const due = cm.deadline!(s)!; + // 무제한 drawing without hints has no deadline: only the random "away drawer" ticks below. + const due = cm.deadline!(s) ?? Infinity; let p: PlayerId; let a: CatchmindAction; if (now >= due || pick.int(12) === 0) { @@ -603,7 +635,7 @@ describe('무작위 대국(§10, docs/09 §7)', () => { const options = opts({ guessMode: pk.int(3) === 0 ? 'firstOnly' : 'multi', rounds: (1 + pk.int(3)) as 1 | 2 | 3, - drawSeconds: ([60, 80, 100, 120] as const)[pk.int(4)]!, + drawSeconds: ([60, 80, 100, 120, null] as const)[pk.int(5)]!, wordChoice: pk.int(4) !== 0, hints: (['none', 'basic', 'full'] as const)[pk.int(3)]!, letterReport: pk.int(3) !== 0, diff --git a/packages/games/src/catchmind/index.ts b/packages/games/src/catchmind/index.ts index 54bb780..224ad9d 100644 --- a/packages/games/src/catchmind/index.ts +++ b/packages/games/src/catchmind/index.ts @@ -118,11 +118,16 @@ export function reportsNeeded(s: S): number { return Math.floor(voters / 2) + 1; } +/** 무제한 drawings time their hints and the speed bonus as if they had the default 80 seconds. */ +export const UNLIMITED_REF_MS = 80_000; +/** The drawing's length for hints / speed bonus (무제한: the 80 s reference). */ +const drawLen = (t: Turn) => (t.endsAt === null ? UNLIMITED_REF_MS : t.endsAt - t.startedAt); + /** Next hint time while drawing (`hints: full` only): 50% → initials, 75% → one letter (skipped for ≤ 2 letters). */ export function nextHintAt(s: S): number | null { const t = s.turn; if (s.finished || t.phase !== 'drawing' || s.options.hints !== 'full' || !t.word) return null; - const dur = t.endsAt - t.startedAt; + const dur = drawLen(t); if (t.hintStage === 0) return t.startedAt + Math.round(dur * 0.5); if (t.hintStage === 1 && letters(t.word.word) > 2) return t.startedAt + Math.round(dur * 0.75); return null; @@ -178,7 +183,7 @@ function beginDrawing(s: S, index: number, ctx: Ctx): void { t.choices = []; t.phase = 'drawing'; t.startedAt = ctx.now; - t.endsAt = ctx.now + s.options.drawSeconds * 1000; + t.endsAt = s.options.drawSeconds === null ? null : ctx.now + s.options.drawSeconds * 1000; t.hintStage = 0; ctx.events.push({ type: 'drawing', no: t.no, drawer: t.drawer }); } @@ -297,7 +302,7 @@ function guess(s: S, p: PlayerId, raw: string, ctx: Ctx): void { if (j === 'correct') { const k = t.solvers.length + 1; let points = s.options.guessMode === 'multi' ? Math.max(10 - 2 * (k - 1), 4) : 10; - if (s.options.speedBonus) points += Math.round((5 * Math.max(0, t.endsAt - ctx.now)) / Math.max(1, t.endsAt - t.startedAt)); + if (s.options.speedBonus) points += Math.round((5 * Math.max(0, t.startedAt + drawLen(t) - ctx.now)) / Math.max(1, drawLen(t))); t.solvers.push({ id: p, at: ctx.now, points }); s.scores[p] = (s.scores[p] ?? 0) + points; s.correctCounts[p] = (s.correctCounts[p] ?? 0) + 1; @@ -318,7 +323,7 @@ function tick(s: S, ctx: Ctx): void { const t = s.turn; if (t.phase === 'choosing') { // Only a disconnected drawer is timed out before the 10 s are up (room grace hook): skip them next time. - if (ctx.now < t.endsAt) markAway(s, t.drawer); + if (ctx.now < t.endsAt!) markAway(s, t.drawer); beginDrawing(s, 0, ctx); return; } @@ -328,7 +333,7 @@ function tick(s: S, ctx: Ctx): void { advanceHint(s, ctx); hinted = true; } - if (ctx.now >= t.endsAt) return endDrawing(s, 'time', ctx); + if (t.endsAt !== null && ctx.now >= t.endsAt) return endDrawing(s, 'time', ctx); if (hinted) return; // Nothing was due: the drawer has been disconnected for DRAWER_AWAY_MS (§5.2) → 0 points, answer revealed. markAway(s, t.drawer); @@ -499,7 +504,7 @@ function buildView(s: S, viewer: PlayerId | null, withCanvas: boolean): Catchmin drawer: t.drawer, startedAt: t.startedAt, endsAt: t.endsAt, - phaseMs: t.endsAt - t.startedAt, + phaseMs: t.endsAt === null ? null : t.endsAt - t.startedAt, choices: isDrawer && t.phase === 'choosing' && !s.finished ? t.choices.map((w) => ({ word: w.word, category: w.category, difficulty: w.difficulty })) : null, word: knows && t.word ? t.word.word : null, category: knows && t.word ? t.word.category : null, @@ -613,7 +618,7 @@ export const catchmind: GameDefinition = const len = [...cleanText(a.text)].length; if (len < 1) return fail('내용을 입력해 주세요.'); if (len > GUESS_MAX) return fail(`${GUESS_MAX}자까지 쓸 수 있어요.`); - if (now !== undefined && now >= t.endsAt) return fail('시간이 다 됐어요.'); + if (now !== undefined && t.endsAt !== null && now >= t.endsAt) return fail('시간이 다 됐어요.'); if (!rateOk(s.msgTimes[actor], GUESS_MSGS_PER_SEC, now)) return fail('조금 천천히 보내 주세요.'); return ok; } @@ -632,6 +637,11 @@ export const catchmind: GameDefinition = return ok; case 'back': return s.away.includes(actor) ? ok : fail('이미 게임에 참여하고 있어요.'); + case 'giveUp': + if (actor !== t.drawer) return fail('출제자만 정답을 공개할 수 있어요.'); + if (t.phase !== 'drawing') return fail('그리는 동안에만 정답을 공개할 수 있어요.'); + if (s.options.drawSeconds !== null) return fail('제한 시간이 있는 방에서는 시간이 끝날 때까지 그려요.'); + return ok; case 'report': if (!s.options.letterReport) return fail('이 방은 신고를 쓰지 않아요.'); if (t.phase !== 'drawing') return fail('그리는 동안에만 신고할 수 있어요.'); @@ -670,6 +680,9 @@ export const catchmind: GameDefinition = case 'back': ctx.events.push({ type: 'back', player: actor }); break; + case 'giveUp': + endDrawing(s, 'giveUp', ctx); + break; case 'report': s.turn.reports.push(actor); ctx.events.push({ type: 'report', count: s.turn.reports.length, need: reportsNeeded(s) }); @@ -702,7 +715,9 @@ export const catchmind: GameDefinition = deadline(s) { if (s.finished) return null; const h = nextHintAt(s); - return h === null ? s.turn.endsAt : Math.min(h, s.turn.endsAt); + const e = s.turn.endsAt; + if (h === null) return e; + return e === null ? h : Math.min(h, e); }, /** The drawer's clock drives every server tick (choosing, hints, time up, reveal). */ @@ -768,7 +783,7 @@ export const catchmind: GameDefinition = out.push({ type: 'draw', op: { k: 'e', s: t.lastStroke } }); } if (t.live > 0) out.push({ type: 'draw', op: { k: 'u' } }, { type: 'draw', op: { k: 'x' } }); - out.push({ type: 'reaction', code: 'almost' }); + out.push({ type: 'reaction', code: 'almost' }, { type: 'giveUp' }); } else { out.push({ type: 'guess', text: t.word!.word }, { type: 'guess', text: '모르겠어요' }, { type: 'guess', text: `${t.word!.word} 맞나` }, { type: 'report' }); } diff --git a/packages/games/src/catchmind/types.ts b/packages/games/src/catchmind/types.ts index 4447754..6fa177c 100644 --- a/packages/games/src/catchmind/types.ts +++ b/packages/games/src/catchmind/types.ts @@ -53,9 +53,10 @@ export const catchmindOptionsSchema = z.object({ rounds: lit<1 | 2 | 3>(1, 2, 3) .default(2) .meta({ title: '라운드 수(모두 한 번씩 그리면 1라운드)', labels: { 1: '1라운드', 2: '2라운드', 3: '3라운드' } }), - drawSeconds: lit<60 | 80 | 100 | 120>(60, 80, 100, 120) + /** null = 무제한: the drawing goes on until it is solved (or the drawer opens the answer with `giveUp`). */ + drawSeconds: lit<60 | 80 | 100 | 120 | null>(60, 80, 100, 120, null) .default(80) - .meta({ title: '그리기 제한 시간', labels: { 60: '60초', 80: '80초', 100: '100초', 120: '120초' } }), + .meta({ title: '그리기 제한 시간', labels: { 60: '60초', 80: '80초', 100: '100초', 120: '120초', null: '무제한(맞히거나 출제자가 넘길 때까지)' } }), wordChoice: z.boolean().default(true).meta({ title: '출제자가 단어 3개 중 고르기(끄면 무작위 1개)' }), categories: z .object(Object.fromEntries(CATEGORIES.map((c) => [c, z.boolean().default(true).meta({ title: CATEGORY_KO[c] })])) as Record>) @@ -104,6 +105,8 @@ export const catchmindActionSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('report') }), /** "돌아왔어요": clears the away mark (players marked away are skipped as drawer). */ z.object({ type: z.literal('back') }), + /** 무제한 only: the drawer opens the answer and ends the drawing (drawer points as usual for those who got it). */ + z.object({ type: z.literal('giveUp') }), ]); /** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */ export type CatchmindAction = z.infer | { type: 'tick' } | { type: 'leave' }; @@ -130,7 +133,7 @@ export interface Solver { points: number; } -export type TurnEndReason = 'time' | 'allSolved' | 'first' | 'report' | 'drawerAway' | 'drawerLeft'; +export type TurnEndReason = 'time' | 'allSolved' | 'first' | 'report' | 'drawerAway' | 'drawerLeft' | 'giveUp'; export interface Turn { /** 1-based turn counter (also the canvas key). */ @@ -140,7 +143,8 @@ export interface Turn { choices: WordEntry[]; word: WordEntry | null; startedAt: number; - endsAt: number; + /** null only while drawing with no time limit (무제한). */ + endsAt: number | null; /** 0 letter count, 1 initial consonants, 2 one letter (§5.4). */ hintStage: 0 | 1 | 2; revealIndex: number | null; @@ -243,9 +247,9 @@ export interface CatchmindView { phase: Turn['phase'] | 'ended'; drawer: PlayerId; startedAt: number; - endsAt: number; - /** Length of the current phase (ms), for timer rings. */ - phaseMs: number; + endsAt: number | null; + /** Length of the current phase (ms), for timer rings; null = 무제한. */ + phaseMs: number | null; /** Drawer only, while choosing. */ choices: ChoiceView[] | null; /** Drawer, solvers and (after the turn) everyone. */ diff --git a/packages/games/src/clue/clue.test.ts b/packages/games/src/clue/clue.test.ts index 7e77c1e..6e3191d 100644 --- a/packages/games/src/clue/clue.test.ts +++ b/packages/games/src/clue/clue.test.ts @@ -314,6 +314,29 @@ describe('timer and leaving', () => { expect(u.deadlineAt).toBe(clock + 10_000); }); + test('turnSeconds 무제한: no clock on turns or refuting; an away player (room grace) is still moved on and then gets the short clock', () => { + let s = rigged(hands, undefined, { turnSeconds: null }); + // setup's own deadline was computed before rigging; a fresh turn shows the unlimited clock. + s = go(s, 'A', { type: 'timeout' }); + expect(s.current).toBe('B'); + expect(s.deadlineAt).toBeNull(); + expect(clue.deadline!(s)).toBeNull(); + let r = inRoom(rigged(hands, undefined, { turnSeconds: null }), 'A', 'library'); + r = go(r, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' }); + expect(r.phase.kind).toBe('refute'); + expect(r.deadlineAt).toBeNull(); + let u = rigged(hands, undefined, { turnSeconds: null }); + u.out.C = true; + for (let i = 0; i < 3; i++) { + u = go(u, 'A', { type: 'timeout' }); + u = go(u, 'B', { type: 'roll' }); + u = go(u, 'B', clue.legalActions!(u, 'B').find((a) => a.type === 'walk' || a.type === 'go')!); + if (u.phase.kind === 'suggest') u = go(u, 'B', { type: 'end' }); + } + expect(u.current).toBe('A'); + expect(u.deadlineAt).toBe(clock + 10_000); + }); + test('leaving: cards go face up, the answer chain and turns go on, the last one in the room wins', () => { let s = inRoom(rigged(hands), 'A', 'library'); s = go(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' }); @@ -407,7 +430,12 @@ describe('random games', () => { test('engine random playouts (secretsOf leak check, JSON round trip)', () => { for (let i = 0; i < playoutSeeds(60); i++) { const n = 3 + (i % 4); - const r = randomPlayout(clue, { players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n), seed: seedN(i + 1), maxApplyMs: 50 }); + const r = randomPlayout(clue, { + players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n), + seed: seedN(i + 1), + maxApplyMs: 50, + ...(i % 4 === 3 ? { options: clue.optionsSchema.parse({ turnSeconds: null }) } : {}), + }); expect(r.finished).toBe(true); } }); diff --git a/packages/games/src/clue/index.ts b/packages/games/src/clue/index.ts index ab73c93..ec3b4ea 100644 --- a/packages/games/src/clue/index.ts +++ b/packages/games/src/clue/index.ts @@ -66,11 +66,14 @@ function refreshDeadline(s: ClueState, now: number): void { s.deadlineAt = null; return; } + const unlimited = s.options.turnSeconds === null; if (s.phase.kind === 'refute') { - s.deadlineAt = now + REFUTE_MS; + s.deadlineAt = unlimited ? null : now + REFUTE_MS; return; } - s.deadlineAt = now + ((s.idle[s.current] ?? 0) >= IDLE_TURNS ? IDLE_MS : s.options.turnSeconds * 1000); + // Someone who let the clock run out three turns in a row gets a short clock (무제한 too: only away players time out there). + if ((s.idle[s.current] ?? 0) >= IDLE_TURNS) s.deadlineAt = now + IDLE_MS; + else s.deadlineAt = unlimited ? null : now + s.options.turnSeconds! * 1000; } function finish(s: ClueState, winner: PlayerId | null, reason: ClueFinal['reason'], events: GameEvent[]): void { diff --git a/packages/games/src/clue/types.ts b/packages/games/src/clue/types.ts index 43f4f21..09f9b5a 100644 --- a/packages/games/src/clue/types.ts +++ b/packages/games/src/clue/types.ts @@ -7,7 +7,7 @@ export * from './board'; // ---------------------------------------------------------------- options -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[]]); export const clueOptionsSchema = z.object({ @@ -15,9 +15,10 @@ export const clueOptionsSchema = z.object({ .enum(['dice', 'free']) .default('dice') .meta({ title: '이동 방식', labels: { dice: '주사위 2개로 복도 이동(원작처럼)', free: '빠르게(아무 방이나 바로 이동)' } }), - turnSeconds: lit(30, 45, 60, 90) + /** null = 무제한: no clock on turns or on showing a card (only players away past the room's grace period are moved on). */ + turnSeconds: lit<30 | 45 | 60 | 90 | null>(30, 45, 60, 90, null) .default(60) - .meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초' } }), + .meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초', null: '무제한' } }), }); export type ClueOptions = z.infer;