From c9f81804cf6ab8785a6160a0e3363774448d877b Mon Sep 17 00:00:00 2001 From: EJClaw Date: Mon, 12 Oct 2026 22:27:42 +0900 Subject: [PATCH] =?UTF-8?q?=ED=81=B4=EB=A3=A8:=20=EA=B7=9C=EC=B9=99=C2=B7?= =?UTF-8?q?=EC=BB=B4=ED=93=A8=ED=84=B0=20=EC=83=81=EB=8C=80=C2=B7=ED=99=94?= =?UTF-8?q?=EB=A9=B4=C2=B7=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 규칙 모듈 packages/games/src/clue: 3~6명, 용의자 6·흉기 6·방 9, 봉투 3장, 나머지는 같은 장수로 나누고 남는 카드는 공개(원작). 9개 방 + 복도를 거리 표로 단순화한 저택(비밀 통로 부엌↔서재, 온실↔라운지), 주사위 2개 합만큼 이동해 닿는 방에 들어가거나 먼 방 쪽으로 걸어가기, 빠른 이동 옵션. 추리 시 용의자 말·흉기 이동과 불려 온 사람의 제자리 추리, 다음 사람부터 반증(반증자가 직접 고름, 보여 준 카드는 두 사람만), 고발(틀리면 탈락하되 반증은 계속, 모두 틀리면 무승부). 카드 id(card-*)와 추리 이름을 나눠 view 누출 검사가 의미 있게, 이벤트에는 카드 없음. 시간 초과는 차례를 통째로 자동 진행, 반증은 첫 카드 자동, 나가면 카드 공개. - 컴퓨터 상대(bot.ts): 소거 노트(내 카드·공개·받은 카드 → 못 보여 준 사람·손패 수 → "셋 중 하나" 제약·틀린 고발), 단계가 높을수록 깊게, 확실할 때만 고발, 모르는 카드로 추리, 모르는 방으로 이동. - 화면 apps/web/src/games/clue: 저택 지도(말·흉기·거리·통로), 주사위·방 고르기, 추리/고발 칩, 반증 카드 고르기, 내 카드·공개 카드, 추리 노트(localStorage, 방 코드+게임 번호), 추리 기록. - 등록(GAMES, 카탈로그, BOT_GAMES, BOT_STRATEGIES, 화면 레지스트리, 아이콘·분류), 문서 docs/games/clue.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지). Co-Authored-By: Claude Opus 5.5 --- apps/web/src/games/clue/help.test.ts | 66 ++ apps/web/src/games/clue/help.ts | 74 ++ apps/web/src/games/clue/index.tsx | 977 ++++++++++++++++++++++++ apps/web/src/games/clue/quick.tsx | 88 +++ apps/web/src/games/registry.ts | 1 + apps/web/src/lib/catalog-ui.ts | 3 +- docs/games/README.md | 1 + docs/games/clue.md | 165 ++++ e2e/games.e2e.ts | 150 ++++ packages/games/package.json | 1 + packages/games/src/bots/index.ts | 2 + packages/games/src/clue/board.ts | 130 ++++ packages/games/src/clue/bot.test.ts | 202 +++++ packages/games/src/clue/bot.ts | 194 +++++ packages/games/src/clue/clue.test.ts | 438 +++++++++++ packages/games/src/clue/index.ts | 506 ++++++++++++ packages/games/src/clue/types.ts | 169 ++++ packages/games/src/index.ts | 2 + packages/games/src/result-score.test.ts | 2 +- packages/shared/src/bots.ts | 1 + packages/shared/src/catalog.ts | 1 + 21 files changed, 3171 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/games/clue/help.test.ts create mode 100644 apps/web/src/games/clue/help.ts create mode 100644 apps/web/src/games/clue/index.tsx create mode 100644 apps/web/src/games/clue/quick.tsx create mode 100644 docs/games/clue.md create mode 100644 packages/games/src/clue/board.ts create mode 100644 packages/games/src/clue/bot.test.ts create mode 100644 packages/games/src/clue/bot.ts create mode 100644 packages/games/src/clue/clue.test.ts create mode 100644 packages/games/src/clue/index.ts create mode 100644 packages/games/src/clue/types.ts diff --git a/apps/web/src/games/clue/help.test.ts b/apps/web/src/games/clue/help.test.ts new file mode 100644 index 0000000..fa1fb4a --- /dev/null +++ b/apps/web/src/games/clue/help.test.ts @@ -0,0 +1,66 @@ +import { expect, test } from 'bun:test'; +import { applyAction, setupGame, usersOf } from '../help-kit.test-util'; +import { GAMES } from '@bg/games'; +import { helpNow } from './help'; + +const ids = ['A', 'B', 'C']; +const users = usersOf(ids); +const view = (s: unknown, who: string | null) => GAMES.clue!.view(s, who) as any; +const nickOf = (id: string) => users[id]!.nickname; + +/** A fresh game with the current player standing in the library, ready to suggest. */ +function inLibrary() { + const { state } = setupGame('clue', 3); + const cur = state.current as string; + const s = structuredClone(state); + s.pos[s.suspectOf[cur]] = { at: 'library' }; + s.phase = { kind: 'suggest', room: 'library' }; + return { s, cur }; +} + +test('클루: 주사위 차례 / 기다리기 / 관전', () => { + const { state } = setupGame('clue', 3); + const cur = state.current as string; + const other = ids.find((p) => p !== cur)!; + expect(helpNow(view(state, cur), cur, users)).toContain('[🎲 주사위 굴리기]'); + expect(helpNow(view(state, other), other, users)).toContain(`${nickOf(cur)}님이 이동하는 중이에요`); + expect(helpNow(view(state, null), null, users)).toContain(`${nickOf(cur)}님 차례예요`); + const rolled = applyAction('clue', state, cur, { type: 'roll' }); + expect(helpNow(view(rolled, cur), cur, users)).toContain('주사위 합은'); +}); + +test('클루: 추리 → 몰래 보여 주기 (보여 주는 사람 / 추리한 사람 / 다른 사람)', () => { + const { s, cur } = inLibrary(); + expect(helpNow(view(s, cur), cur, users)).toContain('[추리하기]'); + // Ask about cards the next player surely holds: one of their own. + const order = s.seats as string[]; + const next = order[(order.indexOf(cur) + 1) % 3]!; + const third = order.find((p) => p !== cur && p !== next)!; + const theirs: string[] = s.hands[next].map((c: string) => c.slice(5)); + const suspect = theirs.find((x) => ['scarlet', 'mustard', 'white', 'green', 'peacock', 'plum'].includes(x)) ?? 'plum'; + const weapon = theirs.find((x) => ['candlestick', 'dagger', 'pipe', 'revolver', 'rope', 'wrench'].includes(x)) ?? 'rope'; + const t = applyAction('clue', s, cur, { type: 'suggest', suspect, weapon }); + if (t.phase.kind === 'refute') { + const r = t.phase.refuter as string; + expect(helpNow(view(t, r), r, users)).toContain('한 장을 보여 줘야 해요'); + expect(helpNow(view(t, cur), cur, users)).toContain('나에게 보여 줄 카드를 고르는 중'); + const watcher = [next, third].find((p) => p !== r)!; + expect(helpNow(view(t, watcher), watcher, users)).toContain('두 사람만 알아요'); + const done = applyAction('clue', t, r, { type: 'show', card: t.hands[r].find((c: string) => [suspect, weapon, 'library'].includes(c.slice(5))) }); + expect(helpNow(view(done, cur), cur, users)).toContain('보여 준 카드는 정답이 아니에요'); + } else { + expect(helpNow(view(t, cur), cur, users)).toContain('아무도 카드를 보여 주지 못했어요'); + } +}); + +test('클루: 고발이 틀려 탈락 / 게임 끝', () => { + const { state } = setupGame('clue', 3); + const cur = state.current as string; + const sol = state.solution; + const wrong = { type: 'accuse', suspect: sol.suspect === 'plum' ? 'green' : 'plum', weapon: sol.weapon, room: sol.room }; + const s = applyAction('clue', state, cur, wrong); + expect(helpNow(view(s, cur), cur, users)).toContain('고발이 틀려서 탈락했어요'); + const next = s.current as string; + const end = applyAction('clue', s, next, { type: 'accuse', ...sol }); + expect(helpNow(view(end, cur), cur, users)).toContain('게임이 끝났어요'); +}); diff --git a/apps/web/src/games/clue/help.ts b/apps/web/src/games/clue/help.ts new file mode 100644 index 0000000..fa63311 --- /dev/null +++ b/apps/web/src/games/clue/help.ts @@ -0,0 +1,74 @@ +/** 클루 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { ClueView } from '@bg/games/clue'; +import { PASSAGES, ROOM_KO, SUSPECT_KO, WEAPON_KO, roomAt } from '@bg/games/clue/board'; +import type { PublicUser } from '@bg/shared/lite'; + +const triple = (x: { suspect: keyof typeof SUSPECT_KO; weapon: keyof typeof WEAPON_KO; room: keyof typeof ROOM_KO }) => + `${SUSPECT_KO[x.suspect]} · ${WEAPON_KO[x.weapon]} · ${ROOM_KO[x.room]}`; + +/** "서재로" / "식당으로" / "홀로": the particle after the last word. */ +const ro = (word: string) => { + const c = word.charCodeAt(word.length - 1); + const jong = c >= 0xac00 && c <= 0xd7a3 ? (c - 0xac00) % 28 : 0; + return `${word}${jong === 0 || jong === 8 ? '로' : '으로'}`; +}; + +export function helpNow(v: ClueView, me: string | null, players: Record): string { + const name = (id: string) => `${players[id]?.nickname ?? '다른 사람'}님`; + const goal = '범인·흉기·장소 카드 한 장씩이 사건 봉투에 숨어 있어요. 추리로 남의 카드를 하나씩 알아내 봉투 속 정답을 맞히면 이겨요.'; + const ph = v.phase; + if (ph.kind === 'finished') return `게임이 끝났어요. ${v.final?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.'; + + const seated = !!me && v.seats.includes(me) && !v.left[me]; + const last = v.suggestions[v.suggestions.length - 1]; + const cur = name(v.current); + + if (ph.kind === 'refute' && last) { + if (ph.refuter === me) + return `${name(last.by)}이 ${ro(triple(last))} 추리했어요. 그중 내 카드가 있어서 한 장을 보여 줘야 해요.\n파란 테두리 카드 중 하나를 누르면 ${name(last.by)}에게만 보여져요. 여러 장이면 원하는 카드를 골라요(이미 보여 준 카드를 또 보여 주면 새 정보를 덜 줘요).`; + if (last.by === me) return `${name(ph.refuter)}이 나에게 보여 줄 카드를 고르는 중이에요. 보여 준 카드는 추리 노트에 자동으로 ✗ 표시돼요.`; + return `${name(ph.refuter)}이 ${name(last.by)}에게 카드를 몰래 보여 주는 중이에요. 어떤 카드인지는 두 사람만 알아요.\n${name(ph.refuter)}이 ${triple(last)} 중 적어도 한 장은 가졌다는 것을 기억해 두세요.`; + } + + if (!seated) return `${cur} 차례예요. ${goal}`; + if (v.out[me!]) + return `고발이 틀려서 탈락했어요. 더 움직이거나 추리할 수는 없지만, 다른 사람이 추리하면 가진 카드는 계속 보여 줘야 해요.\n지금은 ${cur} 차례예요.`; + + if (v.current !== me) { + const doing: Record = { + move: '이동하는 중이에요', + moveTo: '갈 방을 고르는 중이에요', + suggest: '추리할 범인과 흉기를 고르는 중이에요', + afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요', + }; + return `${cur}이 ${doing[ph.kind] ?? '차례를 진행하는 중이에요'}. 기다려 주세요.\n누가 무엇을 추리했고 누가 카드를 보여 주지 못했는지 기록을 보며 추리 노트를 정리해 보세요.`; + } + + const pos = v.pos[v.suspectOf[me!]!]; + const here = roomAt(pos); + switch (ph.kind) { + case 'move': { + if (v.options.movement === 'free') return `내 차례예요. 지도에서 갈 방을 누르고 [들어가기]를 눌러요. 들어간 방에서 추리할 수 있어요.\n확신이 서면 [⚖️ 고발하기…]로 정답을 말해요. 틀리면 탈락이에요.`; + const pass = here ? PASSAGES[here] : undefined; + const extra = [ + pass ? `여기는 모서리 방이라 [🕳️ 비밀 통로]로 ${ROOM_KO[pass]}에 바로 갈 수도 있어요.` : '', + here && v.movedIn[me!] ? `다른 사람의 추리로 ${ROOM_KO[here]}에 불려 왔으니 [여기서 추리하기]로 움직이지 않고 추리할 수도 있어요.` : '', + ] + .filter(Boolean) + .join(' '); + return `내 차례예요. [🎲 주사위 굴리기]를 눌러 나온 합만큼 복도를 걸어 방에 들어가요. ${extra}\n확신이 서면 [⚖️ 고발하기…]로 정답을 말해요. 틀리면 탈락이에요.`; + } + case 'moveTo': { + const sum = v.dice ? v.dice[0] + v.dice[1] : 0; + return `주사위 합은 ${sum}이에요. 지도에서 초록 방(${sum}칸 안)을 누르고 [들어가기]를 눌러요.\n점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요. 다음 차례에 이어서 가요.`; + } + case 'suggest': + return `${ROOM_KO[ph.room]}에 들어왔어요. 범인과 흉기를 하나씩 고르고 [추리하기]를 눌러요. 장소는 지금 있는 ${ROOM_KO[ph.room]}이에요.\n다음 사람부터 차례로 셋 중 가진 카드 한 장을 나에게만 보여 줘요. ✗ 표시된 카드는 이미 정답이 아닌 카드예요.`; + case 'afterSuggest': + return last?.refuter + ? `${name(last.refuter)}이 보여 준 카드는 정답이 아니에요(노트에 자동 표시). [차례 끝내기]를 누르거나, 확신이 서면 [⚖️ 고발하기…]를 눌러요.` + : '아무도 카드를 보여 주지 못했어요! 내 카드가 아니라면 셋 중에 정답이 있을 수 있어요. [차례 끝내기] 또는 [⚖️ 고발하기…]를 눌러요.'; + default: + return `내 차례예요. ${goal}`; + } +} diff --git a/apps/web/src/games/clue/index.tsx b/apps/web/src/games/clue/index.tsx new file mode 100644 index 0000000..fec2a03 --- /dev/null +++ b/apps/web/src/games/clue/index.tsx @@ -0,0 +1,977 @@ +/** 클루 화면 (docs/games/clue.md §9). */ +import { useEffect, useMemo, useRef, useState } from 'react'; +import type { ClueOptions, ClueView, SuggestionView } from '@bg/games/clue'; +import { + PASSAGES, + ROOMS, + ROOM_KO, + SUSPECTS, + SUSPECT_KO, + WEAPONS, + WEAPON_KO, + ITEM_KO, + categoryOf, + distTo, + itemOf, + roomAt, + type Item, + type Pos, + type Room, + type Suspect, + type Weapon, +} from '@bg/games/clue/board'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar } from '../../components/ui'; +import { TurnTimer } from '../../components/TurnTimer'; +import { haptic, sounds } from '../../lib/feedback'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +export const SUSPECT_COLOR: Record = { + scarlet: '#dc2626', + mustard: '#ca8a04', + white: '#f5f5f4', + green: '#15803d', + peacock: '#2563eb', + plum: '#7e22ce', +}; +const SUSPECT_SHORT: Record = { scarlet: '스', mustard: '머', white: '화', green: '그', peacock: '피', plum: '플' }; +export const WEAPON_ICON: Record = { candlestick: '🕯️', dagger: '🗡️', pipe: '🔩', revolver: '🔫', rope: '🪢', wrench: '🔧' }; +export const ROOM_ICON: Record = { kitchen: '🍳', ballroom: '💃', conservatory: '🌿', dining: '🍽️', billiard: '🎱', library: '📚', lounge: '🛋️', hall: '🚪', study: '🖋️' }; +const CAT_KO = { suspect: '용의자', weapon: '흉기', room: '장소' } as const; +const iconOf = (x: Item) => (categoryOf(x) === 'suspect' ? '' : categoryOf(x) === 'weapon' ? WEAPON_ICON[x as Weapon] : ROOM_ICON[x as Room]); +const AREA: Record = { kitchen: 'k', ballroom: 'b', conservatory: 'c', dining: 'd', billiard: 'bi', library: 'li', lounge: 'lo', hall: 'h', study: 's' }; +const DICE = ['', '⚀', '⚁', '⚂', '⚃', '⚄', '⚅']; + +const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; +const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; +const triple = (x: { suspect: Suspect; weapon: Weapon; room: Room }) => `${SUSPECT_KO[x.suspect]} · ${WEAPON_KO[x.weapon]} · ${ROOM_KO[x.room]}`; +/** "식당으로" / "서재로" / "홀로" (ㄹ 받침도 "로"). */ +const ro = (word: string) => { + const c = word.charCodeAt(word.length - 1); + const jong = c >= 0xac00 && c <= 0xd7a3 ? (c - 0xac00) % 28 : 0; + return `${word}${jong === 0 || jong === 8 ? '로' : '으로'}`; +}; +const lastOf = (xs: readonly T[]): T | undefined => xs[xs.length - 1]; + +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; +} + +/** 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); + +/** Where a token in the corridor is, in words. */ +function hallwayText(p: Pos): string { + if ('at' in p) return p.at.startsWith('start-') ? '출발점' : ROOM_KO[p.at as Room]; + let best: Room = 'hall'; + for (const r of ROOMS) if (distTo(p, r) < distTo(p, best)) best = r; + return `${ROOM_KO[best]}까지 ${distTo(p, best)}칸`; +} + +/** Cards whose place the viewer knows (not in the case file): own, face up, shown to me. */ +function knownCards(v: ClueView): Map { + const out = new Map(); + for (const c of v.myHand ?? []) out.set(itemOf(c), '내 카드'); + for (const c of v.publicCards) if (!out.has(itemOf(c))) out.set(itemOf(c), '공개 카드'); + return out; +} + +const CSS = ` +.cl-board { 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); } +.cl-room { position: relative; display: flex; flex-direction: column; align-items: stretch; gap: 3px; text-align: left; border-radius: 10px; padding: 6px 7px; + background: var(--surface); color: var(--text); border: 2px solid var(--border); font: inherit; min-width: 0; } +button.cl-room { cursor: pointer; } +button.cl-room:disabled { cursor: default; } +.cl-room.reach { border-color: var(--success); background: color-mix(in srgb, var(--success-soft) 70%, var(--surface)); } +.cl-room.far { border-style: dashed; border-color: var(--primary); } +.cl-room.sel { outline: 4px solid var(--focus); outline-offset: 1px; } +.cl-room.here { box-shadow: inset 0 0 0 2px var(--primary); } +.cl-room:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.cl-rname { font-weight: 800; font-size: .92rem; line-height: 1.15; display: flex; gap: 4px; align-items: center; min-width: 0; } +.cl-rname span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cl-room.reach .cl-rname, .cl-room.far .cl-rname { padding-right: 36px; } +.cl-pass { position: absolute; right: 4px; bottom: 3px; font-size: .7rem; color: var(--text-sub); font-weight: 700; } +.cl-dist { position: absolute; right: 5px; top: 4px; font-size: .75rem; font-weight: 800; border-radius: 999px; padding: 0 6px; background: var(--surface-2); } +.cl-room.reach .cl-dist { background: var(--success); color: #fff; } +.cl-things { display: flex; flex-wrap: wrap; gap: 3px; align-items: center; min-height: 22px; } +.cl-weap { font-size: 1rem; line-height: 1; } +.cl-tok { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 50%; font-size: .72rem; font-weight: 900; + color: #fff; border: 2px solid rgba(0,0,0,.35); flex: none; } +.cl-tok.light { color: #1c1917; } +.cl-tok.me { box-shadow: 0 0 0 3px var(--focus); } +.cl-mid { grid-area: m; background: color-mix(in srgb, var(--surface-2) 85%, var(--wood)); color: var(--text); border-radius: 10px; padding: 6px 8px; display: flex; + flex-direction: column; gap: 4px; font-size: .8rem; min-width: 0; } +.cl-mid ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 3px; } +.cl-mid li { display: flex; gap: 5px; align-items: center; min-width: 0; } +.cl-mid li span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cl-env { font-weight: 800; display: flex; gap: 4px; align-items: center; } +.cl-panel { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 10px; } +.cl-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.cl-chip { min-height: 44px; border-radius: 12px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font: inherit; font-weight: 700; + padding: 4px 10px; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; } +.cl-chip[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); } +.cl-chip.known { opacity: .55; } +.cl-chip.known::after { content: '✗'; color: var(--danger); font-weight: 900; } +.cl-chip:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.cl-btns { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; } +.cl-btns .btn { min-height: 52px; } +.cl-dice { font-size: 2.6rem; line-height: 1; display: flex; gap: 6px; align-items: center; } +.cl-dice b { font-size: 1.2rem; margin-left: 6px; } +.cl-cards { display: flex; flex-wrap: wrap; gap: 6px; } +.cl-card { display: inline-flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; width: 74px; min-height: 86px; border-radius: 10px; + background: linear-gradient(160deg, #fffaf0, #f1e6cf); color: #2b2118; border: 2px solid #b79c6b; padding: 4px; text-align: center; font-weight: 800; font-size: .8rem; + box-shadow: 0 2px 0 rgba(0,0,0,.25); } +.cl-card .ic { font-size: 1.5rem; line-height: 1.1; } +.cl-card .cat { font-size: .65rem; font-weight: 700; opacity: .7; } +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; } +@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; } +.cl-note h4 { margin: 0 0 4px; font-size: .9rem; } +.cl-note ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } +.cl-note li { display: flex; align-items: center; gap: 6px; min-height: 34px; font-size: .9rem; } +.cl-note li .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cl-note li .why { font-size: .72rem; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 7.5em; } +.cl-note li.auto .nm { text-decoration: line-through; color: var(--text-sub); } +.cl-mark { width: 34px; height: 30px; border-radius: 8px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font-weight: 900; cursor: pointer; flex: none; font-size: 1rem; } +.cl-mark.x { color: var(--danger); } +.cl-mark.o { color: var(--success); border-color: var(--success); } +.cl-mark.q { color: var(--warning); } +.cl-mark:disabled { cursor: default; opacity: .8; } +.cl-mark:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.cl-badge { display: inline-block; border-radius: 999px; padding: 1px 8px; font-weight: 800; font-size: .75rem; background: var(--surface-2); color: var(--text); white-space: nowrap; } +.cl-badge.turn { background: var(--focus); color: #1c1e21; } +.cl-badge.out { background: var(--danger-soft); color: var(--danger); } +.cl-badge.ok { background: var(--success-soft); color: var(--success); } +.cl-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 5px; max-height: 280px; overflow: auto; font-size: .86rem; } +.cl-log li { line-height: 1.35; } +.cl-shown { font-weight: 800; color: var(--primary); } +@media (max-width: 719px) { + .cl-top { grid-template-columns: minmax(0, 1fr); } + .cl-board { max-height: none; overflow: visible; } + .cl-map { gap: 4px; padding: 5px; grid-template-rows: repeat(4, minmax(76px, auto)); } + .cl-room { padding: 4px 5px; } + .cl-rname { font-size: .8rem; } + .cl-tok { width: 21px; height: 21px; font-size: .66rem; } + .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; } } +`; + +// ---------------------------------------------------------------- small pieces + +function Token({ x, me }: { x: Suspect; me?: boolean }) { + return ( + + {SUSPECT_SHORT[x]} + + ); +} + +function Card({ id, onClick, can, fresh, label }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string }) { + const x = itemOf(id); + const cat = categoryOf(x); + const body = ( + <> + + {cat === 'suspect' ? : iconOf(x)} + + {ITEM_KO[x]} + {CAT_KO[cat]} + + ); + const aria = label ?? `${CAT_KO[cat]} 카드 ${ITEM_KO[x]}`; + if (onClick) + return ( + + ); + return ( + + {body} + + ); +} + +// ---------------------------------------------------------------- board + +function ClueBoard({ view: v, me, players, act, pending }: BoardProps) { + const amPlayer = !!me && v.seats.includes(me); + const myTurn = amPlayer && v.current === me && !v.out[me!] && v.phase.kind !== 'refute' && v.phase.kind !== 'finished'; + const [sel, setSel] = useState(null); + const [announce, setAnnounce] = useState(''); + const prevTurn = useRef(`${v.current}|${v.turnNo}`); + const prevSg = useRef(JSON.stringify(lastOf(v.suggestions) ?? null)); + + useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]); + + useEffect(() => { + const key = `${v.current}|${v.turnNo}`; + if (key !== prevTurn.current && v.phase.kind !== 'finished') { + if (v.current === me) { + haptic(40); + sounds.myTurn(); + setAnnounce('내 차례예요.'); + } else setAnnounce(`${nick(players, v.current)}님 차례예요.`); + } + prevTurn.current = key; + }, [v.current, v.turnNo]); // eslint-disable-line react-hooks/exhaustive-deps + + // Read out suggestions and their answers. + const last = lastOf(v.suggestions); + const sgKey = JSON.stringify(last ?? null); + useEffect(() => { + if (sgKey === prevSg.current) return; + prevSg.current = sgKey; + if (!last) return; + const who = last.by === me ? '내가' : `${nick(players, last.by)}님이`; + const head = `${who} ${ro(triple(last))} 추리했어요.`; + if (v.phase.kind === 'refute' && v.phase.refuter === me) { + haptic([30, 40, 30]); + sounds.myTurn(); + setAnnounce(`${head} 보여 줄 카드를 골라 주세요.`); + } else if (last.refuter) setAnnounce(`${head} ${nick(players, last.refuter)}님이 카드를 보여 줬어요.${last.shown && last.by === me ? ` 보여 준 카드는 ${ITEM_KO[itemOf(last.shown)]}예요.` : ''}`); + else if (v.phase.kind === 'afterSuggest' || last.passed.length) setAnnounce(`${head} 아무도 카드를 보여 주지 못했어요.`); + }, [sgKey]); // eslint-disable-line react-hooks/exhaustive-deps + + return ( +
+ +
+ + +
+ {amPlayer && } + {amPlayer && } +

+ {announce} +

+
+ ); +} + +function Mansion({ view: v, me, myTurn, sel, setSel }: { view: ClueView; me: string | null; myTurn: boolean; sel: Room | null; setSel: (r: Room | null) => void }) { + const mySuspect = me ? v.suspectOf[me] : undefined; + const myPos = mySuspect ? v.pos[mySuspect] : null; + const here = myPos ? roomAt(myPos) : null; + const ph = v.phase.kind; + const free = v.options.movement === 'free'; + const picking = myTurn && ((ph === 'move' && free) || ph === 'moveTo'); + const sum = v.dice ? v.dice[0] + v.dice[1] : 0; + const owner = (x: Suspect) => v.seats.find((p) => v.suspectOf[p] === x); + const inRoom = (r: Room) => SUSPECTS.filter((x) => roomAt(v.pos[x]) === r); + const hall = SUSPECTS.filter((x) => !roomAt(v.pos[x])); + return ( +
+ {ROOMS.map((r) => { + const toks = inRoom(r); + const weaps = WEAPONS.filter((w) => v.weaponAt[w] === r); + const d = v.distances?.[r]; + 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 label = [ + ROOM_KO[r], + r === here ? '내가 있는 방' : '', + can ? (free ? '갈 수 있어요' : reach ? `${d}칸, 들어갈 수 있어요` : `${d}칸, 이번에는 못 닿아요(걸어가기)`) : '', + toks.length ? `말: ${toks.map((x) => SUSPECT_KO[x]).join(', ')}` : '', + weaps.length ? `흉기: ${weaps.map((w) => WEAPON_KO[w]).join(', ')}` : '', + pass ? `비밀 통로로 ${ROOM_KO[pass]}와 이어져요` : '', + ] + .filter(Boolean) + .join(', '); + const inner = ( + <> + + {ROOM_ICON[r]} + {ROOM_KO[r]} + + {can && !free && d !== undefined && {d}칸} + + {toks.map((x) => ( + + ))} + {weaps.map((w) => ( + + {WEAPON_ICON[w]} + + ))} + + {pass && ( + + ↗ {ROOM_KO[pass]} + + )} + + ); + return can ? ( + + ) : ( +
+ {inner} +
+ ); + })} +
+ + 📁 사건 봉투 + + {hall.length > 0 ? ( +
    + {hall.map((x) => { + const p = owner(x); + return ( +
  • + + {hallwayText(v.pos[x])} +
  • + ); + })} +
+ ) : ( + 복도에 아무도 없어요 + )} +
+
+ ); +} + +function ChipRow({ label, items, value, onPick, known }: { label: string; items: readonly T[]; value: T | null; onPick: (x: T) => void; known: Map }) { + return ( +
+ {label} +
+ {items.map((x) => ( + + ))} +
+
+ ); +} + +function AccusePanel({ act, pending, onCancel, known }: { act: (a: unknown) => void; pending: boolean; onCancel: () => void; known: Map }) { + const [s, setS] = useState(null); + const [w, setW] = useState(null); + const [r, setR] = useState(null); + const [sure, setSure] = useState(false); + const done = s && w && r; + return ( +
e.key === 'Escape' && onCancel()}> + 고발하기: 봉투 속 정답을 말해요 + 맞히면 바로 이기고, 틀리면 탈락해요(카드 보여 주기는 계속해요). 한 사람에 한 번만 할 수 있어요. + (setS(x), setSure(false))} known={known} /> + (setW(x), setSure(false))} known={known} /> + (setR(x), setSure(false))} known={known} /> +
+ + {!sure ? ( + + ) : ( + + )} +
+
+ ); +} + +function SuggestPanel({ room, act, pending, known, onAccuse }: { room: Room; act: (a: unknown) => void; pending: boolean; known: Map; onAccuse: () => void }) { + const [s, setS] = useState(null); + const [w, setW] = useState(null); + return ( +
+ + {ROOM_ICON[room]} {ROOM_KO[room]}에서 추리해요 + + 범인과 흉기를 하나씩 고르면, 다음 사람부터 차례로 그중 가진 카드를 나에게만 보여 줘요. 고른 용의자 말과 흉기는 이 방으로 옮겨져요. + + +
+ +
+
+ + +
+
+ ); +} + +function LastResult({ view: v, me, players }: { view: ClueView; me: string | null; players: Record }) { + const last = lastOf(v.suggestions); + if (!last || last.turnNo !== v.turnNo) return null; + const by = last.by === me ? '내' : `${nick(players, last.by)}님의`; + return ( +
+ + {by} 추리: {triple(last)} + {last.passed.length > 0 && · 못 보여 준 사람: {last.passed.map((p) => (p === me ? '나' : nick(players, p))).join(', ')}} + + {last.refuter ? ( + last.shown ? ( +
+ + + {last.refuter === me ? `내가 ${nick(players, last.by)}님에게 보여 준 카드` : `${nick(players, last.refuter)}님이 보여 준 카드`} +
+ {last.by === me ? '추리 노트에 자동으로 표시했어요.' : '다른 사람은 어떤 카드인지 몰라요.'} +
+
+ ) : ( + + {nick(players, last.refuter)}님이 {last.by === me ? '나' : `${nick(players, last.by)}님`}에게 카드 한 장을 몰래 보여 줬어요. + + ) + ) : ( + v.phase.kind !== 'refute' && 아무도 카드를 보여 주지 못했어요! + )} +
+ ); +} + +function ActionPanel({ + view: v, + me, + players, + act, + pending, + myTurn, + sel, + setSel, +}: { + view: ClueView; + me: string | null; + players: Record; + act: (a: unknown) => void; + pending: boolean; + myTurn: boolean; + sel: Room | null; + setSel: (r: Room | null) => void; +}) { + const [accusing, setAccusing] = useState(false); + const known = useMemo(() => { + const k = knownCards(v); + for (const sg of v.suggestions) if (sg.by === me && sg.shown && sg.refuter) k.set(itemOf(sg.shown), `${nick(players, sg.refuter)}님 카드`); + return k; + }, [v, me, players]); + useEffect(() => setAccusing(false), [v.turnNo, v.phase.kind]); + const ph = v.phase; + + if (ph.kind === 'finished') { + return ( +
+ 게임이 끝났어요 + {v.final?.summary} + {v.solution && ( +
+ {[v.solution.suspect, v.solution.weapon, v.solution.room].map((x) => ( + + ))} +
+ )} +
+ ); + } + + if (ph.kind === 'refute') { + const sg = lastOf(v.suggestions)!; + if (ph.refuter === me) { + return ( +
+ + {nick(players, sg.by)}님이 {ro(triple(sg))} 추리했어요 + + 내 카드 중 하나를 골라 {nick(players, sg.by)}님에게만 보여 줘요. 다른 사람은 내가 보여 줬다는 것만 알아요. 20초 안에 안 고르면 자동으로 보여 줘요. +
+ {(ph.canShow ?? []).map((c) => ( + !pending && act({ type: 'show', card: c })} label={`${ITEM_KO[itemOf(c)]} 카드 보여 주기`} /> + ))} +
+
+ ); + } + return ( +
+ + + {nick(players, ph.refuter)}님이 {sg.by === me ? '나' : `${nick(players, sg.by)}님`}에게 보여 줄 카드를 고르는 중이에요 + +
+ ); + } + + if (!myTurn) { + const doing: Record = { + move: '이동하는 중이에요', + moveTo: `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`, + suggest: '추리할 카드를 고르는 중이에요', + afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요', + }; + return ( +
+ + + {nick(players, v.current)}님이 {doing[ph.kind]} + + {me && v.seats.includes(me) && v.out[me] && 나는 고발이 틀려 탈락했어요. 다른 사람이 추리하면 카드 보여 주기는 계속해요.} + 누가 무엇을 추리했고 누가 카드를 보여 줬는지 오른쪽 기록에서 볼 수 있어요. +
+ ); + } + + if (accusing) return setAccusing(false)} known={known} />; + + const myPos = v.pos[v.suspectOf[me!]!]; + const here = roomAt(myPos); + const accuseBtn = ( + + ); + + if (ph.kind === 'suggest') return setAccusing(true)} />; + + if (ph.kind === 'afterSuggest') { + return ( +
+ +
+ + {accuseBtn} +
+
+ ); + } + + const free = v.options.movement === 'free'; + if (ph.kind === 'move' && !free) { + const pass = here ? PASSAGES[here] : undefined; + return ( +
+ 내 차례예요. {here ? `지금 ${ROOM_KO[here]}에 있어요.` : `지금 복도(${hallwayText(myPos)})에 있어요.`} +
+ + {pass && ( + + )} + {here && v.movedIn[me!] && ( + + )} + {accuseBtn} +
+ {here && v.movedIn[me!] && 다른 사람의 추리로 이 방에 불려 왔어요. 움직이지 않고 여기서 추리할 수 있어요.} +
+ ); + } + + // Choosing where to go: free move, or after the dice. + const sum = v.dice ? v.dice[0] + v.dice[1] : 0; + const d = sel && v.distances ? v.distances[sel] : null; + const enter = sel && (free || (d !== null && d <= sum)); + return ( +
+ {v.dice && ( +
+ {DICE[v.dice[0]]} + {DICE[v.dice[1]]} + = {sum}칸 +
+ )} + 지도에서 갈 방을 눌러 주세요. + + {free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`} + +
+ {sel && enter && ( + + )} + {sel && !enter && d !== null && ( + + )} + {!sel && ( + + )} + {free && here && v.movedIn[me!] && ( + + )} + {sel && ( + + )} + {accuseBtn} +
+
+ ); +} + +function MyCards({ view: v, me }: { view: ClueView; me: string }) { + const mine = v.myHand ?? []; + return ( +
+
+ + 내 카드 {mine.length}장 · {SUSPECT_KO[v.suspectOf[me]!]} 말 + + 내 카드는 봉투에 없어요 +
+
+ {mine.map((c) => ( + + ))} +
+ {v.publicCards.length > 0 && ( + <> + 모두에게 공개된 카드 {v.publicCards.length}장 +
+ {v.publicCards.map((c) => ( + + ))} +
+ + )} +
+ ); +} + +// ---------------------------------------------------------------- notebook (kept on this device) + +type Mark = '' | 'x' | 'q' | 'o'; +const NEXT: Record = { '': 'x', x: 'q', q: 'o', o: '' }; +const MARK_TEXT: Record = { '': '', x: '✗', q: '?', o: '✓' }; +const MARK_KO: Record = { '': '표시 없음', x: '아님(✗)', q: '모름(?)', o: '정답 같음(✓)' }; + +/** localStorage key: room code + game number (docs §9). Replays and other pages keep notes in memory only. */ +function noteKey(gameNo: number): string | null { + const m = typeof location !== 'undefined' ? /\/r\/(\d{6})/.exec(location.pathname) : null; + return m ? `bg:clue:note:${m[1]}:${gameNo}` : null; +} + +function Notebook({ view: v, me, players }: { view: ClueView; me: string; players: Record }) { + const key = noteKey(v.gameNo); + const [marks, setMarks] = useState>(() => { + try { + return key ? (JSON.parse(localStorage.getItem(key) ?? '{}') as Record) : {}; + } catch { + return {}; + } + }); + const auto = useMemo(() => { + const k = knownCards(v); + for (const sg of v.suggestions) if (sg.by === me && sg.shown && sg.refuter && !k.has(itemOf(sg.shown))) k.set(itemOf(sg.shown), `${nick(players, sg.refuter)}님이 보여 줌`); + return k; + }, [v, me, players]); + const set = (x: Item) => { + const next = { ...marks, [x]: NEXT[marks[x] ?? ''] }; + setMarks(next); + try { + if (key) localStorage.setItem(key, JSON.stringify(next)); + } catch {} + }; + const group = (title: string, items: readonly Item[]) => ( +
+

{title}

+
    + {items.map((x) => { + const why = auto.get(x); + const m: Mark = why ? 'x' : (marks[x] ?? ''); + return ( +
  • + + + {categoryOf(x) !== 'suspect' && {iconOf(x)} } + {ITEM_KO[x]} + + {why && {why}} +
  • + ); + })} +
+
+ ); + return ( +
+ 🗒️ 추리 노트 + 내 카드·공개 카드·나에게 보여 준 카드는 자동으로 ✗예요. 나머지는 눌러서 ✗ → ? → ✓ 로 바꿔요. 이 기기에만 저장돼요. +
+ {group('범인', SUSPECTS)} + {group('흉기', WEAPONS)} + {group('장소', ROOMS)} +
+
+ ); +} + +// ---------------------------------------------------------------- side + +type LogLine = { turn: number; order: number; text: string; shown?: string; mine?: boolean }; + +function logLines(v: ClueView, me: string | null, players: Record): LogLine[] { + const who = (p: string) => (p === me ? '나' : `${nick(players, p)}님`); + const subj = (p: string) => (p === me ? '내가' : `${nick(players, p)}님이`); + const out: LogLine[] = []; + v.suggestions.forEach((sg: SuggestionView, i) => { + const answer = sg.refuter ? `${subj(sg.refuter)} 카드를 보여 줌` : v.phase.kind === 'refute' && i === v.suggestions.length - 1 ? '답을 기다리는 중' : '아무도 못 보여 줌'; + const passed = sg.passed.length ? ` (못 보여 준 사람: ${sg.passed.map(who).join(', ')})` : ''; + out.push({ turn: sg.turnNo, order: i, text: `🔍 ${who(sg.by)}: ${triple(sg)} → ${answer}${passed}`, shown: sg.shown ?? undefined, mine: sg.by === me || sg.refuter === me }); + }); + v.accusations.forEach((a, i) => out.push({ turn: a.turnNo, order: 1000 + i, text: `⚖️ ${who(a.by)} 고발: ${triple(a)} → ${a.correct ? '맞았어요!' : '틀려서 탈락'}` })); + return out.sort((a, b) => a.turn - b.turn || a.order - b.order); +} + +function ClueSide({ view: v, me, players, deadline }: BoardProps) { + const running = v.phase.kind !== 'finished'; + const lines = logLines(v, me, players); + const wait = waitingOn(v); + return ( + <> + +
+
+ {running ? (v.phase.kind === 'refute' ? `${nick(players, wait)}님이 카드 고르는 중` : `${nick(players, v.current)}님 차례`) : '게임 끝'} + {running && } +
+ {optionsSummary(v.options)} +
    + {v.seats.map((p) => { + const x = v.suspectOf[p]!; + return ( +
  1. + + + {nick(players, p)} + {p === me && (나)} + + + + 카드 {v.handCounts[p]}장 + + {running && wait === p && {v.phase.kind === 'refute' ? '보여 주는 중' : '차례'}} + {v.final?.winner === p && 승리} + {v.left[p] ? 나감 : v.out[p] && 고발 실패} +
  2. + ); + })} +
+
+ {v.hands && v.solution && ( +
+ 정답: {triple(v.solution)} + {v.seats.map((p) => ( + + {nick(players, p)}: {v.hands![p]!.map((c) => ITEM_KO[itemOf(c)]).join(', ') || '없음'} + + ))} +
+ )} +
+ 추리 기록 ({lines.length}) + {lines.length === 0 ? ( +

+ 아직 추리가 없어요. +

+ ) : ( +
    + {[...lines].reverse().map((l, i) => ( +
  1. + {l.text} + {l.shown && [{ITEM_KO[itemOf(l.shown)]}]} +
  2. + ))} +
+ )} +
+ + ); +} + +// ---------------------------------------------------------------- status + +function isMyTurn(v: ClueView, me: string | null): boolean { + if (!me || !v.seats.includes(me) || v.phase.kind === 'finished' || v.left[me]) return false; + if (v.phase.kind === 'refute') return v.phase.refuter === me; + return v.current === me && !v.out[me]; +} + +function statusText(v: ClueView, me: string | null, players: Record): string { + if (v.phase.kind === 'finished') return v.final?.summary ?? '게임이 끝났어요'; + if (isMyTurn(v, me)) { + switch (v.phase.kind) { + case 'move': + return v.options.movement === 'free' ? '내 차례예요. 갈 방을 골라 주세요' : '내 차례예요. 주사위를 굴려 주세요'; + case 'moveTo': + return '내 차례예요. 들어갈 방을 골라 주세요'; + case 'suggest': + return '내 차례예요. 범인과 흉기를 골라 추리해 주세요'; + case 'afterSuggest': + return '내 차례예요. 고발하거나 차례를 끝내 주세요'; + case 'refute': + return `내 차례예요. ${nick(players, lastOf(v.suggestions)?.by ?? v.current)}님에게 보여 줄 카드를 골라 주세요`; + } + } + const out = me && v.seats.includes(me) && v.out[me] ? '탈락 · ' : ''; + if (v.phase.kind === 'refute') return `${out}${nick(players, v.phase.refuter)}님이 보여 줄 카드를 고르는 중이에요`; + return `${out}${nick(players, v.current)}님 차례예요`; +} + +// ---------------------------------------------------------------- options + +function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} + +function Options({ value: o, onChange }: OptionsProps) { + const set = (patch: Partial) => onChange({ ...o, ...patch }); + return ( +
+
+ 이동 방식 + set({ movement })} + /> +
+
+ 차례 제한 시간 + set({ turnSeconds })} + /> +
+
+ ); +} + +function optionsSummary(o: ClueOptions): string { + return [o.movement === 'free' ? '빠른 이동' : '주사위 이동', `차례 ${o.turnSeconds}초`].join(' · '); +} + +function Rules({ options }: { options?: ClueOptions }) { + const free = options?.movement === 'free'; + return ( +
+

+ 저택에서 살인 사건이 일어났어요. 누가(범인), 무엇으로(흉기), 어디서(장소) 했는지 맞히는 추리 게임이에요. 3~6명이 할 수 있어요. +

+

+ 준비: 용의자 6장, 흉기 6장, 방 9장 중 종류마다 한 장씩 몰래 뽑아 사건 봉투에 넣어요. 이것이 정답이에요. 남은 18장은 모두에게 똑같이 나눠 주고, + 똑같이 나누고 남는 카드(4명이면 2장, 5명이면 3장)는 모두에게 공개해요. 내 손에 있는 카드는 봉투에 없다는 뜻이에요. 각자 용의자 말 하나를 맡고, 스칼렛을 맡은 사람이 먼저 해요. +

+

+ 이동:{' '} + {free + ? '이 방은 "빠른 이동"이라 주사위 없이 아무 방이나 바로 들어가요(지금 있는 방 빼고).' + : '주사위 2개를 굴려 나온 합만큼 복도를 걸어요. 지도에 칸 수가 나오고, 닿는 방(초록)에 바로 들어가요. 먼 방(점선)을 고르면 그쪽으로 걸어가다 차례가 끝나요. 모서리 방(부엌↔서재, 온실↔라운지)은 비밀 통로로 주사위 없이 바로 건너가요. 방금 있던 방에 다시 들어갈 수는 없어요.'} +

+

+ 추리: 방에 들어가면 "○○가, △△로, 이 방에서"라고 추리해요. 장소는 지금 있는 방이에요. 말한 용의자 말과 흉기가 그 방으로 옮겨져요. 그러면 내 다음 사람부터 차례로, 셋 중 하나라도 가진 + 사람이 그중 한 장을 나에게만 보여 줘요(여러 장이면 보여 주는 사람이 골라요). 한 사람이 보여 주면 거기서 멈추고, 다른 사람들은 누가 보여 줬는지만 알아요. 다른 사람의 추리로 내 말이 어떤 방에 + 불려 갔다면, 다음 내 차례에 움직이지 않고 그 방에서 추리할 수 있어요. +

+

+ 고발: 확신이 서면 내 차례 아무 때나 "범인·흉기·장소"를 말해 고발해요(장소는 어느 방이든 돼요). 한 사람에 한 번뿐이에요. 셋 다 맞으면 이기고, 틀리면 탈락해요. 탈락해도 다른 사람이 추리하면 + 카드는 계속 보여 줘야 해요. 모두 틀리면 아무도 못 이겨요. +

+

+ 추리 노트: 화면 아래 노트에 내 카드, 공개 카드, 나에게 보여 준 카드가 자동으로 ✗ 표시돼요. 나머지는 직접 눌러 ✗·?·✓를 적어 두세요(이 기기에만 저장돼요). +

+

+ 차례 시간이 지나면 가까운 방으로 움직이고 추리 없이 차례가 넘어가요. 카드를 보여 줄 때는 20초 안에 고르지 않으면 맞는 카드가 자동으로 보여져요. 게임 중에 나간 사람의 카드는 모두에게 공개돼요. +

+
+ ); +} + +const ui: GameUI = { + Board: ClueBoard, + Side: ClueSide, + statusText, + isMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/clue/quick.tsx b/apps/web/src/games/clue/quick.tsx new file mode 100644 index 0000000..eb7c579 --- /dev/null +++ b/apps/web/src/games/clue/quick.tsx @@ -0,0 +1,88 @@ +/** 클루 30초 규칙 요약 (docs/07 §5). */ +import type { QuickCard } from '../types'; + +function Mini({ label, icon, hidden, tone }: { label: string; icon: string; hidden?: boolean; tone?: 'shown' | 'out' }) { + return ( + + ); +} + +const row = { display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center' } as const; + +export const quickStart: QuickCard[] = [ + { + pic: ( +
+ + 📁 + +
+
+
+ ), + alt: '사건 봉투 아래에 뒤집힌 카드 세 장(범인, 흉기, 장소)이 있어요', + title: '봉투 속 세 장을 맞혀요', + text: '범인·흉기·장소 카드가 한 장씩 사건 봉투에 숨어 있어요. 나머지 카드는 모두 나눠 가져요. 내 카드는 정답이 아니에요.', + }, + { + pic: ( +
+
+
🖋️
+ 서재 +
+ 스 +
+
+ + 🎲 + + “플럼 교수가, 밧줄로, 서재에서!” +
+ ), + alt: '주사위를 굴려 서재에 들어간 빨간 말과 추리하는 말풍선이 있어요', + title: '방에 들어가 추리해요', + text: '주사위로 복도를 걸어 방에 들어가면, 그 방에서 "범인·흉기·이 방"을 말해 추리해요. 모서리 방은 비밀 통로로 건너가요.', + }, + { + pic: ( +
+ + + ➜ + + + + ⚖️ + +
+ ), + alt: '다른 사람이 몰래 보여 준 밧줄 카드에 노트에서 ✗ 표시를 하고, 저울(고발)이 있어요', + title: '지우고, 고발해요', + text: '다음 사람부터 셋 중 가진 카드 한 장을 나에게만 보여 줘요. 노트에서 지워 가다 확신이 서면 고발! 틀리면 탈락이에요.', + }, +]; diff --git a/apps/web/src/games/registry.ts b/apps/web/src/games/registry.ts index a52416e..14212f0 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -29,6 +29,7 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { catchmind: () => import('./catchmind'), mafia: () => import('./mafia'), apple: () => import('./apple'), + clue: () => import('./clue'), }; const cache = new Map(); diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index 41fe419..0af0131 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -26,6 +26,7 @@ export const GAME_ICON: Record = { catchmind: '🖍️', mafia: '🌙', apple: '🍎', + clue: '🔎', }; /** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */ @@ -33,7 +34,7 @@ export const UPCOMING: string[] = []; /** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ - { key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] }, + { key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'clue'] }, { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'mahjong', 'rummikub', 'davinci-code'] }, { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'apple'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 93a10a3..92fbc76 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -40,6 +40,7 @@ | `catchmind` | 그림 맞히기 | 2~10 | M8 | | `mafia` | 마피아 | 4~12 | M8 | | `apple` | 사과 게임(합 10 만들기, 같은 판 경주) | 1~8 | M9 | +| `clue` | 클루 | 3~6 | M9 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/clue.md b/docs/games/clue.md new file mode 100644 index 0000000..4b0fdae --- /dev/null +++ b/docs/games/clue.md @@ -0,0 +1,165 @@ +# 클루 (`clue`) + +> 마일스톤: M9 · 인원: 최소 3 ~ 최대 6명 · 예상 시간: 약 30~50분(빠른 이동 20~30분) · 난이도: 보통 + +## 1. 개요 +- 저택에서 일어난 살인 사건의 범인·흉기·장소를 '추리(질문)'와 소거법으로 알아내는 추리 보드게임. 1943년 영국의 앤서니 프랫이 고안, 1949년 워딩턴스 출시(영국 이름 Cluedo, 미국 이름 Clue). +- 인원 근거: 원작 3~6인. **2인은 넣지 않았다.** 노트 파일의 "판에 따라 2~6명"은 일부 판의 이야기인데, 공식 2인 변형 규칙의 출처를 확인하지 못했다. 2명이면 반증하는 사람이 늘 상대 한 명뿐이라 "누가 보여 줬는지"라는 정보가 사라지고 거의 카드 맞히기가 된다. 확인되면 옵션으로 추가한다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `movement` | 이동 방식 | `dice` 주사위 2개로 복도 이동(원작처럼) / `free` 빠르게(아무 방이나 바로) | `dice` | +| `turnSeconds` | 차례 제한 시간(이동·추리·고발) | 30 / 45 / 60 / 90초 | 60 | + +카드 보여 주기(반증)는 옵션 없이 20초. `free`는 노트 파일의 "이동을 줄이는 옵션이 있으면 좋다"를 반영한 하우스 룰이다. + +## 3. 구성물 +- 카드 21장: 용의자 6(스칼렛·머스터드 대령·화이트 부인·그린 목사·피콕 부인·플럼 교수), 흉기 6(촛대·단검·납 파이프·권총·밧줄·스패너), 방 9(부엌·무도회장·온실·식당·당구장·도서실·라운지·홀·서재). +- 용의자 말 6개(색: 빨강·노랑·흰색·초록·파랑·보라), 흉기 6개(지도 위 아이콘), 주사위 2개. +- 그림·지도는 직접 만든 이모지·CSS. 원작 판 그림은 쓰지 않는다(12절). + +## 4. 준비(셋업) +1. 첫 사람을 RNG로 뽑고, 그 사람부터 시계 방향으로 스칼렛·머스터드·화이트·그린·피콕·플럼을 맡는다(원작: 스칼렛이 먼저, 원작 판에서의 시계 방향 순서). 사람이 맡지 않은 용의자 말도 지도에 있고, 추리로 불려 다닌다. +2. 종류마다 한 장씩 RNG로 뽑아 **사건 봉투**에 넣는다. +3. 남은 18장을 섞어 모두에게 **같은 장수**를 나눠 준다. 똑같이 나누고 남는 카드는 **모두에게 공개**한다(원작 규칙). + +| 인원 | 각자 | 공개 | +|---|---|---| +| 3 | 6 | 0 | +| 4 | 4 | 2 | +| 5 | 3 | 3 | +| 6 | 3 | 0 | + +4. 말은 모두 자기 출발점(복도), 흉기 6개는 서로 다른 방 6곳에 RNG로 놓는다. + +## 5. 진행 규칙 +### 5.1 차례 +내 차례 순서: ① 이동 → ② (방에 들어갔으면) 추리 → ③ 반증 → ④ 차례 끝내기. **고발**은 내 차례 동안(카드를 기다리는 중 빼고) 언제든 할 수 있다. + +### 5.2 저택(단순화한 지도) +원작은 칸 단위 판이지만 화면에 그대로 옮기면 너무 크다. 그래서 9개 방 + 복도를 **방 사이 거리 표**로 바꿨다. +- 화면 배치(3열 × 4행): 위 `부엌 · 무도회장 · 온실`, 왼쪽 `식당`(2칸 높이), 오른쪽 `당구장 · 도서실`, 아래 `라운지 · 홀 · 서재`, 가운데는 복도와 사건 봉투. +- 복도 거리(칸): 부엌–무도회장 7, 무도회장–온실 4, 온실–당구장 7, 당구장–도서실 4, 도서실–서재 7, 서재–홀 4, 홀–라운지 8, 라운지–식당 4, 식당–부엌 6, 식당–무도회장 7, 무도회장–당구장 6, 식당–홀 6, 홀–도서실 7. 출발점: 스칼렛(라운지 7·홀 7), 머스터드(라운지 6·식당 7), 화이트(부엌 8·무도회장 6), 그린(무도회장 6·온실 8), 피콕(온실 7·당구장 6), 플럼(도서실 6·서재 8). 나머지 거리는 이 길들의 최단 거리(`board.ts`의 `DIST`). +- **비밀 통로**(원작 그대로 2쌍): 부엌↔서재, 온실↔라운지. 모서리 방에서 차례를 시작하면 주사위 없이 건너가 바로 추리한다. + +### 5.3 이동 (`dice`) +- 방이나 복도에서 시작: [주사위 굴리기] → 두 눈의 합만큼 걷는다. 합 이하 거리의 방(지금 있는 방 제외)에 **들어간다**(원작처럼 남는 걸음은 버린다). +- 더 먼 방을 고르면 그쪽으로 합만큼 **걸어가 복도에 멈추고** 차례가 끝난다. 다음 차례 거리는 그 자리에서 다시 잰다(지나온 방 쪽으로 되돌아가도 됨). 방 문 앞을 지나쳐도 들어간 것이 아니다. +- 지금 있는 방에 다시 들어갈 수 없다(원작: 같은 차례에 같은 방에 다시 들어갈 수 없음 → 머물러 추리할 수 없음). +- **불려 온 경우**(원작): 다른 사람의 추리로 내 말이 어떤 방으로 옮겨졌다면, 다음 내 차례에 움직이지 않고 그 방에서 추리할 수 있다([여기서 추리하기]). 그 차례가 끝나면 권리는 사라진다. +- 막힌 문·말이 길을 막는 규칙은 거리 표에서는 뺐다. + +### 5.4 이동 (`free`) +주사위 없이 지금 있는 방이 아닌 아무 방에나 들어간다(불려 온 경우엔 머물러 추리도 가능). + +### 5.5 추리(suggestion) +- 지금 들어간 방 + 용의자 1 + 흉기 1. 추리를 건너뛰고 차례를 끝낼 수도 있다(원작도 선택). +- 말한 용의자 말과 흉기를 그 방으로 옮긴다(원작). 그 말을 맡은 사람에게 5.3의 "불려 온 경우" 권리가 생긴다. +- 반증: 추리한 사람의 **다음 사람부터 시계 방향**으로 묻는다. 셋 중 한 장도 없는 사람은 서버가 바로 "못 보여 줌"으로 처리하고(공개 정보), 처음으로 가진 사람이 **반드시 한 장**을 골라 추리한 사람에게만 보여 준다(여러 장이면 보여 주는 사람이 고름). 거기서 멈춘다. 고발이 틀려 탈락한 사람도 반증은 계속한다(원작). 나간 사람은 건너뛴다(카드가 공개되어 있으므로). +- 한 장뿐이어도 보여 주는 사람이 직접 누른다(한 장/여러 장이 반응 속도로 드러나지 않게). +- 다른 사람들은 "누가 보여 줬다"와 "누가 못 보여 줬다"만 안다. + +### 5.6 고발(accusation) +- 범인·흉기·장소(장소는 아무 방)를 말한다. 한 사람에 한 번. +- 맞으면 바로 승리. 틀리면 **탈락**: 더 이상 차례가 없지만 반증은 계속한다(원작). 고발 내용과 맞음/틀림은 모두에게 공개(원작에서도 소리 내어 말함). +- **원작과 다른 점**: 원작은 틀린 사람이 봉투를 몰래 본다. 온라인에서는 탈락한 사람이 채팅으로 정답을 흘릴 수 있어 **보여 주지 않는다**. + +## 6. 승패와 점수 계산 +- 고발을 맞힌 사람 1위, 나머지 모두 2위(공동). 점수 없음(`scoreText` 없음). +- 모두 고발이 틀리면 아무도 못 이기고 모두 공동 순위(무승부). +- 남은 한 사람만 방에 있으면(다른 사람이 모두 나감) 그 사람이 이긴다(`resign`). + +## 7. 지역 룰 / 하우스 룰 +- `free` 빠른 이동(5.4). +- 일부러 뺀 것: 막힌 문, 칸 단위 이동, 2인 변형, 틀린 고발자의 봉투 확인(5.6), "탐정 수첩" 서버 저장(화면 노트는 기기에만 저장). + +## 8. 엔진 설계 +### 8.1 상태(State) +```ts +interface ClueState { + options; seats; gameNo; + suspectOf: Record; + solution: { suspect; weapon; room }; // 비밀 + hands: Record; // 카드 id 'card-' + publicCards: string[]; // 남는 카드 + 나간 사람 카드 + pos: Record; // { at: 방|출발점 } | { from, to, moved } (복도) + weaponAt: Record; + current; phase; dice; + movedIn: Record; // 추리로 불려 옴 + out; left; // 고발 실패 / 나감 + suggestions: { by; suspect; weapon; room; passed[]; refuter; shown /*비밀*/; auto; turnNo }[]; + accusations: { by; suspect; weapon; room; correct; turnNo }[]; + turnNo; idle; idleTurn; deadlineAt; seq; final; +} +``` +단계(phase): `move` → (`moveTo`) → `suggest` → `refute` → `afterSuggest` → 다음 사람 `move`. `finished`. + +### 8.2 액션 +| type | payload | 누가 / 언제 | 검증 조건 | +|---|---|---|---| +| `roll` | – | 차례인 사람, `move`, 주사위 모드 | | +| `passage` | – | `move`, 주사위 모드 | 비밀 통로가 있는 방에 있음 | +| `stay` | – | `move` | 방에 있고 `movedIn` | +| `go` | `room` | 주사위: `moveTo` / 빠른: `move` | 지금 방이 아님, 주사위면 거리 ≤ 합 | +| `walk` | `room` | `moveTo` | 거리 > 합 | +| `suggest` | `suspect, weapon` | `suggest` | | +| `show` | `card` | `refute`의 반증자 | 추리한 세 장 중 내 손의 카드 | +| `accuse` | `suspect, weapon, room` | 차례인 사람(탈락 아님), `refute` 아닐 때 | | +| `end` | – | `suggest`(추리 건너뛰기), `afterSuggest` | | +| `timeout` / `leave` | – | 서버 | | + +### 8.3 공개/비공개 정보 (view) +- 카드 id(`card-rope`)와 추리에서 말하는 이름(`rope`)을 나눠, 카드 id는 볼 수 있는 사람의 view에만 나온다: 내 손패(`myHand`), 공개 카드, 내가 보여 준/받은 카드(`suggestions[].shown`은 추리한 사람·반증자에게만), 게임 끝난 뒤 전부. +- 반증 중 `canShow`(보여 줄 수 있는 카드)는 반증자 view에만. 봉투(`solution`)·모든 손패(`hands`)는 끝난 뒤에만. +- 이벤트에는 카드 id가 전혀 없다(`refuted`는 누가→누구에게만). +- `secretsOf(p)`: p가 아직 아무에게도 보여 주지 않은 손패 + 봉투 3장(끝나면 없음). 테스트는 여기에 더해 "보는 사람마다 알아도 되는 카드 집합" 밖의 카드 id가 view에 없는지 수백 판 검사한다. + +### 8.4 랜덤 요소 +첫 사람, 봉투 3장, 나머지 섞기, 흉기 위치, 주사위. 모두 `ctx.rng`. + +### 8.5 타이머·시간 초과·연결 끊김 +- 차례 `turnSeconds`, 반증 20초. 내 차례를 3번 연속 시간 초과로 넘기면 그 사람 차례는 10초. +- 내 차례 시간 초과: 차례 하나를 통째로 자동 진행 — 주사위를 굴려 가장 가까운 닿는 방에 들어가고(없으면 가장 가까운 방 쪽으로 걸음), 추리 없이 끝낸다. 빠른 이동이면 가장 가까운 방. +- 반증 시간 초과: 맞는 카드 중 첫 장(용의자→흉기→방 순)을 보여 준다. +- 아직 고발하지 않은 사람이 모두 3번 연속 시간 초과 상태면 아무도 못 이기고 끝난다(`timeout`). 혼자 남은 자리 비운 사람 때문에 판이 끝나지 않는 것을 막는다. +- 나가기: 그 사람 카드는 모두에게 공개, 반증 중이었으면 다음 사람에게 묻기, 차례였으면 다음 사람. + +### 8.6 종료 조건과 결과 +맞는 고발 / 모두 탈락 / 한 사람만 남음 / 모두 자리 비움. 요약에 정답을 쓴다("고발이 맞았어요! 정답은 플럼 교수 · 밧줄 · 서재였어요."). + +### 8.7 컴퓨터 상대 (`bot.ts`) +자기 view만으로 카드마다 "가질 수 있는 사람(+봉투)" 집합을 줄여 가는 소거 노트. +- 1~20(쉬움): 단순 소거 — 내 카드, 공개 카드, 나에게 보여 준 카드, "한 종류에서 봉투에 있을 수 있는 카드가 하나뿐이면 그것". +- 21~40(보통): + "못 보여 준 사람은 그 세 장이 없다", 손패 장수(다 찾은 사람은 다른 카드를 안 가짐 / 가능한 카드 수 = 손패 수면 전부 그 사람 것). +- 41~60(어려움, 기본): + "그 사람이 셋 중 하나는 가졌다" 제약(둘이 지워지면 남은 하나), 남의 틀린 고발(둘이 봉투로 확정이면 나머지는 아님). +- 고발: 봉투가 확실할 때만. 쉬움은 남은 정답 후보가 2개면 가끔(35%) 찍는다. +- 추리: 아직 모르는 카드를 우선(종류가 풀렸으면 내 카드/봉투 카드로 그 자리를 막음). 이동: 모르는 방 쪽으로(닿으면 들어가고, 아니면 가장 가까운 모르는 방으로 걸어감, 비밀 통로 활용). +- 반증: 그 사람에게 이미 보여 준 카드를 먼저(새 정보를 안 줌). +- 모든 깊이에서 추론이 건전한지(진짜 주인을 지우지 않는지) 실제 대국으로 테스트한다. 같은 조건 강한 컴퓨터(60)는 약한 컴퓨터(5) 둘을 상대로 3인전 대부분을 이긴다. + +## 9. UI/UX +- PC: 왼쪽 저택 지도(3×4 칸, 가운데 복도·사건 봉투), 오른쪽 행동 패널, 아래 내 카드·공개 카드, 추리 노트. 오른쪽 사이드: 참가자(맡은 말, 카드 수, 차례/보여 주는 중/고발 실패/나감), 추리 기록(누가 무엇을 추리했고 누가 보여 줬는지, 내가 보거나 보여 준 카드는 [카드 이름]으로). +- 휴대폰(320px~): 지도·패널·카드·노트가 한 줄로 쌓인다. +- 이동: 주사위를 굴리면 지도 방에 칸 수가 나오고 닿는 방은 초록, 먼 방은 점선. 방을 누르고 [들어가기]/[걸어가기]로 확정. 방 칸에는 말(색 원+첫 글자)·흉기 아이콘·비밀 통로 표시. +- 추리·고발: 용의자/흉기(/장소) 칩을 고르고 버튼. 내가 아는(정답 아닌) 카드는 칩에 ✗로 흐리게. 고발은 두 번 눌러 확정("정말 고발해요 (틀리면 탈락)"). +- 반증: 반증자에게만 보여 줄 카드 버튼이 뜬다. 추리한 사람에게는 받은 카드가 크게 보인다. +- 추리 노트: 21장 목록, 내 카드·공개 카드·나에게 보여 준 카드는 자동 ✗(누가 보여 줬는지 함께), 나머지는 눌러서 ✗ → ? → ✓. `localStorage` 키 `bg:clue:note:<방 코드>:<게임 번호>` — 기기에만 저장. +- 키보드: 모든 방·칩·카드·노트가 버튼. 스크린리더: 방마다 "식당, 5칸, 들어갈 수 있어요, 말: …, 흉기: …", 추리·반증 결과를 aria-live로 읽음. 다크 모드는 공통 색 변수. + +## 10. 테스트 체크리스트 +- [x] 인원별 손패/공개 장수, 봉투가 손패·공개 카드와 겹치지 않음, 스칼렛 선, 흉기 6곳 (`clue.test.ts`) +- [x] 거리 대칭, 걸어간 만큼 정확히 가까워짐, 비밀 통로, 같은 방 재입장 금지, 빠른 이동 +- [x] 추리로 말·흉기 이동과 불려 온 권리, 반증 순서·못 보여 준 사람 기록, 반증자만 고름, 보여 준 카드는 두 사람만, 이벤트에 카드 없음 +- [x] 고발 맞음/틀림, 틀린 사람의 반증 의무, 모두 틀림 → 무승부 +- [x] 시간 초과(차례 통째로, 반증 자동), 자리 비움 단축·종료, 나가기(카드 공개, 반증 이어 가기, 혼자 남으면 승리) +- [x] 무작위 수백 판: 보존, 보는 사람마다 허용 카드 밖 누출 없음, onTimeout 유효, 엔진 randomPlayout(secretsOf), 결정성 +- [x] 컴퓨터: 깊이별 추론, 확실할 때만 고발, 추론 건전성, 강약 차이, 사람이 시간만 넘겨도 끝남 (`bot.test.ts`) +- [x] 도움말(`help.test.ts`), E2E(PC 1 + 휴대폰 2, 주사위·통로·추리·반증·비밀 유지·고발까지) + +## 11. 참고 자료 +- Hasbro Clue/Cluedo 공식 설명서(추리·반증 순서, 불려 온 말, 틀린 고발자의 반증 의무, 남는 카드 공개) +- 내부 노트: `groups/grp_discord_joke-app/notes/new-game-descriptions-20261012.md` 64절 + +## 12. 메모 (상표·법적 주의 등) +'Clue/Cluedo'와 인물 이름은 해즈브로 상표. 사이트 방침(README 5절)대로 이름은 쓰되 지도·카드 그림은 직접 만든 이모지/CSS로 새로 그렸다. 저택 배치는 원작처럼 방 9개가 가운데를 둘러싼 형태지만 칸·문 위치는 쓰지 않았다. diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index 918b22b..e22ebd8 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -904,6 +904,96 @@ async function mafiaShots(pages: Page[], name: string) { await phone.emulateMedia({ colorScheme: 'light' }); } +/** + * 클루: one UI step for whoever must act on `p` — show a card (refute panel), roll / take the passage, pick a room on the + * map and enter it (or walk towards a far one), suggest (suspect + weapon chips), end the turn; once `accuseAfter` + * suggestions were made, accuse a guess (two-step confirm) so the game ends (right → win, all wrong → nobody wins). + */ +async function clueStep(p: Page, st: Record, accuseAfter: number): Promise { + const status = await p.locator('.turn-status').innerText().catch(() => ''); + if (!status.includes('내 차례예요')) return null; + const refute = p.getByRole('group', { name: '카드 보여 주기' }); + if (await refute.count()) { + if (!st[`shot-refute-${tag(p)}`]) { + st[`shot-refute-${tag(p)}`] = 1; + await p.screenshot({ path: join(SHOTS, `clue-refute-${tag(p)}.png`), fullPage: tag(p) === 'phone' }); + } + await refute.locator('button.cl-card').first().click({ timeout: 2000 }); + st.show = (st.show ?? 0) + 1; + return 'show'; + } + const btn = (name: RegExp) => p.locator('.cl-panel').getByRole('button', { name }); + const accuse = async () => { + await btn(/고발하기…/).first().click({ timeout: 2000 }); + const panel = p.getByRole('group', { name: '고발하기' }); + for (const g of ['범인', '흉기', '장소']) await panel.getByRole('group', { name: g }).locator('button:not(.known)').first().click(); + await panel.getByRole('button', { name: / 고발$/ }).click(); + await panel.getByRole('button', { name: '정말 고발해요 (틀리면 탈락)' }).click({ timeout: 2000 }); + st.accuse = (st.accuse ?? 0) + 1; + return 'accuse'; + }; + const roll = btn(/주사위 굴리기/); + if (await roll.count()) { + if ((st.suggest ?? 0) >= accuseAfter) return accuse(); + const pass = btn(/비밀 통로로/); + if ((await pass.count()) && (st.passage ?? 0) === 0) { + await pass.click(); + st.passage = 1; + return 'passage'; + } + if (tag(p) === 'pc' && !st.keyboard) { + // Keyboard: focus the roll button and press Enter. + await roll.focus(); + await p.keyboard.press('Enter'); + st.keyboard = 1; + } else await roll.click({ timeout: 2000 }); + st.roll = (st.roll ?? 0) + 1; + return 'roll'; + } + const rooms = p.locator('.cl-map button.cl-room'); + if (await rooms.count()) { + if (!st[`shot-move-${tag(p)}`]) { + st[`shot-move-${tag(p)}`] = 1; + await p.screenshot({ path: join(SHOTS, `clue-move-${tag(p)}.png`), fullPage: tag(p) === 'phone' }); + } + const reach = p.locator('.cl-map button.cl-room.reach'); + if (await reach.count()) { + await reach.nth((st.roll ?? 0) % (await reach.count())).click(); + await btn(/들어가기$/).click({ timeout: 2000 }); + st.enter = (st.enter ?? 0) + 1; + return 'enter'; + } + await rooms.first().click(); + await btn(/쪽으로 걸어가기/).click({ timeout: 2000 }); + st.walk = (st.walk ?? 0) + 1; + return 'walk'; + } + const sug = p.getByRole('group', { name: '추리하기' }); + if (await sug.count()) { + if ((st.suggest ?? 0) >= accuseAfter) return accuse(); + const n = st.suggest ?? 0; + for (const g of ['범인', '흉기']) { + const opts = sug.getByRole('group', { name: g }).locator('button:not(.known)'); + await opts.nth(n % (await opts.count())).click(); + } + await sug.getByRole('button', { name: /^추리하기:/ }).click({ timeout: 2000 }); + st.suggest = n + 1; + return 'suggest'; + } + const end = btn(/^차례 끝내기$/); + if (await end.count()) { + if (!st[`shot-after-${tag(p)}`]) { + st[`shot-after-${tag(p)}`] = 1; + await p.screenshot({ path: join(SHOTS, `clue-after-${tag(p)}.png`), fullPage: tag(p) === 'phone' }); + } + if ((st.suggest ?? 0) >= accuseAfter) return accuse(); + await end.click(); + st.end = (st.end ?? 0) + 1; + return 'end'; + } + return null; +} + const PLANS: Record = { rummikub: { // PC host + phone guest, first meld "없음" so hint plays happen early; 10 real turns through the UI. @@ -2203,6 +2293,66 @@ const PLANS: Record = { const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText(); if (!/사과 \d+개/.test(text)) throw new Error(`no apple scores in the result: ${text.replace(/\n/g, ' ')}`); console.log(` apple: ${st.pc} mouse + ${st.key} keyboard clears on PC, ${st.phone}+ touch clears on the phone, ${st.miss} miss; final PC ${await appleScore(host)} / phone ${await appleScore(guest)}`); + }, + }, + clue: { + // PC host + 2 phones, dice movement, 30-second turns. Real turns through the UI: roll (PC once by keyboard), a secret + // passage, rooms picked on the map, suggestions from the chips, cards shown from the refute panel. Only the suggester + // and the refuter see the shown card. After 8 suggestions everybody accuses a guess, so the game ends. + players: 3, + lobby: async (host) => { + await host.getByRole('group', { name: '차례 제한 시간' }).getByRole('button', { name: '30초' }).click(); + await host.getByText(/주사위 이동 · 차례 30초/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page, Page]; + const st: Record = {}; + let actions = 0; + let shot = false; + let privacy = false; + const over = () => host.getByRole('dialog', { name: '게임 결과' }).count(); + const until = Date.now() + 300_000; + while (Date.now() < until && !(await over())) { + let acted = false; + for (const p of pages) { + const did = await clueStep(p, st, 8).catch(() => null); + if (did) { + acted = true; + actions++; + await p.waitForTimeout(250); + break; + } + } + if (!privacy && (st.show ?? 0) >= 1) { + // The first shown card: exactly two pages (suggester, refuter) show it in the log. + privacy = true; + await host.waitForTimeout(400); + const seen = await Promise.all(pages.map((p) => p.locator('.cl-log .cl-shown').count())); + if (seen.filter((n) => n > 0).length !== 2) throw new Error(`shown card visible on ${seen.join('/')} pages`); + } + if (!shot && (st.suggest ?? 0) >= 3) { + shot = true; + await host.waitForTimeout(500); + await host.screenshot({ path: join(SHOTS, 'clue-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'clue-mid-phone.png') }); + await guest.screenshot({ path: join(SHOTS, 'clue-mid-phone-full.png'), fullPage: true }); + await host.emulateMedia({ colorScheme: 'dark' }); + await guest.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(400); + await host.screenshot({ path: join(SHOTS, 'clue-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'clue-mid-phone-dark.png'), fullPage: true }); + await host.emulateMedia({ colorScheme: 'light' }); + await guest.emulateMedia({ colorScheme: 'light' }); + } + if (!acted) await host.waitForTimeout(150); + } + if (!(await over())) throw new Error(`game did not finish (${actions} UI actions: ${JSON.stringify(st)})`); + for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor(); + await host.waitForTimeout(600); + await host.screenshot({ path: join(SHOTS, 'clue-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'clue-result-phone.png') }); + if ((st.suggest ?? 0) < 8 || !st.roll || !st.enter || !st.accuse || !privacy) throw new Error(`too few real turns: ${JSON.stringify(st)}`); + console.log(` clue: finished after ${actions} UI actions ${JSON.stringify(Object.fromEntries(Object.entries(st).filter(([k]) => !k.startsWith('shot'))))}`); }, }, }; diff --git a/packages/games/package.json b/packages/games/package.json index 6bf874a..c2e4e21 100644 --- a/packages/games/package.json +++ b/packages/games/package.json @@ -7,6 +7,7 @@ ".": "./src/index.ts", "./rummikub/rules": "./src/rummikub/rules.ts", "./marble/board": "./src/marble/board.ts", + "./clue/board": "./src/clue/board.ts", "./bots/luck": "./src/bots/luck.ts", "./*": "./src/*/index.ts" }, diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 131c8b6..13b77e1 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -31,6 +31,7 @@ import { cockroachPokerBot } from '../cockroach-poker/bot'; import { ninetyNineBot } from '../ninety-nine/bot'; import { mafiaBot } from '../mafia/bot'; import { appleBot } from '../apple/bot'; +import { clueBot } from '../clue/bot'; export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types'; export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona'; @@ -60,6 +61,7 @@ export const BOT_STRATEGIES: Record = { 'las-vegas': lasVegasBot, 'cockroach-poker': cockroachPokerBot, 'ninety-nine': ninetyNineBot, + clue: clueBot, }; /** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */ diff --git a/packages/games/src/clue/board.ts b/packages/games/src/clue/board.ts new file mode 100644 index 0000000..f50bbed --- /dev/null +++ b/packages/games/src/clue/board.ts @@ -0,0 +1,130 @@ +/** + * 클루 cards and the simplified mansion map (docs/games/clue.md §3, §5.2). Pure data + distance helpers, no zod, so the + * screen can import it cheaply. + */ +// ---------------------------------------------------------------- cards + +/** Suspects in the official turn order (스칼렛 first, then clockwise round the board). */ +export const SUSPECTS = ['scarlet', 'mustard', 'white', 'green', 'peacock', 'plum'] as const; +export const WEAPONS = ['candlestick', 'dagger', 'pipe', 'revolver', 'rope', 'wrench'] as const; +export const ROOMS = ['kitchen', 'ballroom', 'conservatory', 'dining', 'billiard', 'library', 'lounge', 'hall', 'study'] as const; +export type Suspect = (typeof SUSPECTS)[number]; +export type Weapon = (typeof WEAPONS)[number]; +export type Room = (typeof ROOMS)[number]; +export type Item = Suspect | Weapon | Room; +export type Category = 'suspect' | 'weapon' | 'room'; +export const ITEMS: readonly Item[] = [...SUSPECTS, ...WEAPONS, ...ROOMS]; +export const CATEGORY_ITEMS: Record = { suspect: SUSPECTS, weapon: WEAPONS, room: ROOMS }; + +export const SUSPECT_KO: Record = { + scarlet: '스칼렛', + mustard: '머스터드 대령', + white: '화이트 부인', + green: '그린 목사', + peacock: '피콕 부인', + plum: '플럼 교수', +}; +export const WEAPON_KO: Record = { + candlestick: '촛대', + dagger: '단검', + pipe: '납 파이프', + revolver: '권총', + rope: '밧줄', + wrench: '스패너', +}; +export const ROOM_KO: Record = { + kitchen: '부엌', + ballroom: '무도회장', + conservatory: '온실', + dining: '식당', + billiard: '당구장', + library: '도서실', + lounge: '라운지', + hall: '홀', + study: '서재', +}; +export const ITEM_KO: Record = { ...SUSPECT_KO, ...WEAPON_KO, ...ROOM_KO }; + +export const categoryOf = (x: Item): Category => + (SUSPECTS as readonly string[]).includes(x) ? 'suspect' : (WEAPONS as readonly string[]).includes(x) ? 'weapon' : 'room'; +export const isItem = (x: unknown): x is Item => typeof x === 'string' && (ITEMS as readonly string[]).includes(x); + +/** + * Card ids ('card-rope') differ from the item names said aloud in suggestions ('rope'), so a card id only ever appears + * in a view where the viewer may know who holds it: own hand, a card shown to / by the viewer, public cards, and + * everything after the game. The leak tests look for these ids. + */ +export const cardId = (x: Item): string => `card-${x}`; +export const itemOf = (id: string): Item => id.slice(5) as Item; + +// ---------------------------------------------------------------- mansion (simplified map, docs §5.2) + +/** Start squares in the hallway, one per suspect (near the same rooms as on the original board). */ +export type StartNode = `start-${Suspect}`; +export type MapNode = Room | StartNode; +export const startOf = (x: Suspect): StartNode => `start-${x}`; + +/** Corridor steps between neighbouring places; every other distance is the shortest path over these. */ +export const CORRIDORS: readonly (readonly [MapNode, MapNode, number])[] = [ + ['kitchen', 'ballroom', 7], + ['ballroom', 'conservatory', 4], + ['conservatory', 'billiard', 7], + ['billiard', 'library', 4], + ['library', 'study', 7], + ['study', 'hall', 4], + ['hall', 'lounge', 8], + ['lounge', 'dining', 4], + ['dining', 'kitchen', 6], + ['dining', 'ballroom', 7], + ['ballroom', 'billiard', 6], + ['dining', 'hall', 6], + ['hall', 'library', 7], + ['start-scarlet', 'lounge', 7], + ['start-scarlet', 'hall', 7], + ['start-mustard', 'lounge', 6], + ['start-mustard', 'dining', 7], + ['start-white', 'kitchen', 8], + ['start-white', 'ballroom', 6], + ['start-green', 'ballroom', 6], + ['start-green', 'conservatory', 8], + ['start-peacock', 'conservatory', 7], + ['start-peacock', 'billiard', 6], + ['start-plum', 'library', 6], + ['start-plum', 'study', 8], +]; + +/** Official secret passages between opposite corner rooms. */ +export const PASSAGES: Partial> = { kitchen: 'study', study: 'kitchen', conservatory: 'lounge', lounge: 'conservatory' }; + +const NODES: MapNode[] = [...ROOMS, ...SUSPECTS.map(startOf)]; + +/** All-pairs shortest corridor distance (Floyd–Warshall over `CORRIDORS`). */ +export const DIST: Record> = (() => { + const d = Object.fromEntries(NODES.map((a) => [a, Object.fromEntries(NODES.map((b) => [b, a === b ? 0 : Infinity]))])) as Record>; + for (const [a, b, n] of CORRIDORS) d[a][b] = d[b][a] = Math.min(d[a][b], n); + for (const k of NODES) for (const i of NODES) for (const j of NODES) if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j]; + return d; +})(); + +/** Where a suspect token is: standing on a place (room or start square), or out in a corridor between two places. */ +export type Pos = { at: MapNode } | { from: MapNode; to: Room; moved: number }; + +/** Corridor steps from `p` to `room` (0 = already in it). */ +export function distTo(p: Pos, room: Room): number { + if ('at' in p) return DIST[p.at][room]; + const len = DIST[p.from][p.to]; + return Math.min(p.moved + DIST[p.from][room], len - p.moved + DIST[p.to][room]); +} + +/** Position after walking `steps` (< distance) along a shortest way from `p` towards `room`. */ +export function walkToward(p: Pos, room: Room, steps: number): Pos { + if ('at' in p) return { from: p.at, to: room, moved: steps }; + const len = DIST[p.from][p.to]; + const back = p.moved + DIST[p.from][room]; + const ahead = len - p.moved + DIST[p.to][room]; + // Ending exactly on a place's door keeps the token in the corridor (moved 0 or = length): passing a room is not entering it. + if (ahead <= back) return steps <= len - p.moved ? { from: p.from, to: p.to, moved: p.moved + steps } : { from: p.to as MapNode, to: room, moved: steps - (len - p.moved) }; + return steps <= p.moved ? { from: p.from, to: p.to, moved: p.moved - steps } : { from: p.from, to: room, moved: steps - p.moved }; +} + +export const roomAt = (p: Pos): Room | null => ('at' in p && (ROOMS as readonly string[]).includes(p.at) ? (p.at as Room) : null); diff --git a/packages/games/src/clue/bot.test.ts b/packages/games/src/clue/bot.test.ts new file mode 100644 index 0000000..3e0c2ff --- /dev/null +++ b/packages/games/src/clue/bot.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, seedN } from '@bg/engine'; +import { decideBotAction } from '../bots/index'; +import { botPlayout } from '../bots/playout'; +import { ITEMS, SUSPECTS, cardId, clue, type ClueAction, type ClueOptions, type ClueState, type Item, type Room } from './index'; +import { deduce, solved, type Owner } from './bot'; + +/** A game with A to move and hands / case file as written. */ +function rigged(hands: Record, solution = { suspect: 'plum', weapon: 'rope', room: 'study' } as ClueState['solution'], opts: Partial = {}): ClueState { + const players = Object.keys(hands); + const s = clue.setup({ players, options: clue.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(1)), now: 0 }); + s.solution = solution; + s.hands = Object.fromEntries(players.map((p) => [p, hands[p]!.map(cardId)])); + const used = new Set([...Object.values(hands).flat(), solution.suspect, solution.weapon, solution.room]); + s.publicCards = ITEMS.filter((x) => !used.has(x)).map(cardId); + s.current = players[0]!; + s.suspectOf = Object.fromEntries(players.map((p, i) => [p, SUSPECTS[i]!])); + return s; +} +const apply = (s: ClueState, p: string, a: ClueAction) => { + const v = clue.validate(s, p, a); + if (!v.ok) throw new Error(v.reason); + return clue.apply(s, p, a, { rng: SeededRng.fromSeed(seedN(9)), now: 1 }).state; +}; +const decide = (s: ClueState, p: string, seed = 1, level?: number) => { + const r = SeededRng.fromSeed(seedN(seed)); + return decideBotAction(clue, s, p, { now: 1, random: () => r.next(), level }) as ClueAction; +}; +const owners = (n: ReturnType, x: Item) => [...n[x]].sort(); + +// 3 players, 6 cards each, nothing face up. Case file: plum / rope / study. +const HANDS: Record = { + A: ['scarlet', 'mustard', 'candlestick', 'kitchen', 'ballroom', 'conservatory'], + B: ['white', 'dagger', 'pipe', 'dining', 'billiard', 'library'], + C: ['green', 'peacock', 'revolver', 'wrench', 'lounge', 'hall'], +}; + +describe('clue bot notes', () => { + test('own cards, cards shown to me, the last unknown of a kind', () => { + let s = rigged(HANDS); + // A asks green / rope / kitchen in the kitchen: B passes, C shows green. + s.pos.scarlet = { at: 'kitchen' }; + s.phase = { kind: 'suggest', room: 'kitchen' }; + s = apply(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' }); + s = apply(s, 'C', { type: 'show', card: cardId('green') }); + const n = deduce(clue.view(s, 'A'), 'A', 1); + expect(owners(n, 'scarlet')).toEqual(['A']); + expect(owners(n, 'green')).toEqual(['C']); + expect(owners(n, 'white')).toEqual(['B', 'C', 'env']); + // Depth 1 ignores who passed; depth 2 knows B has none of the three. + expect(owners(n, 'rope')).toEqual(['B', 'C', 'env']); + expect(owners(deduce(clue.view(s, 'A'), 'A', 2), 'rope')).toEqual(['C', 'env']); + }); + + test('depth 3: "one of these three" with the other two ruled out pins the card', () => { + let s = rigged(HANDS); + // B asks plum / dagger / hall and C shows one of them (hall); A only sees that C answered. + s.current = 'B'; + s.pos.white = { at: 'hall' }; + s.phase = { kind: 'suggest', room: 'hall' }; + s = apply(s, 'B', { type: 'suggest', suspect: 'plum', weapon: 'dagger' }); + expect(s.phase).toEqual({ kind: 'refute', refuter: 'C' }); + s = apply(s, 'C', { type: 'show', card: cardId('hall') }); + // A learns elsewhere that B holds the dagger and that plum is not C's (C passed on plum). + s.suggestions.push({ by: 'A', suspect: 'plum', weapon: 'dagger', room: 'kitchen', passed: [], refuter: 'B', shown: cardId('dagger'), auto: false, turnNo: 3 }); + s.suggestions.push({ by: 'A', suspect: 'plum', weapon: 'candlestick', room: 'kitchen', passed: ['B', 'C'], refuter: null, shown: null, auto: false, turnNo: 4 }); + const v = clue.view(s, 'A'); + expect(owners(deduce(v, 'A', 2), 'hall')).toEqual(['B', 'C', 'env']); + expect(owners(deduce(v, 'A', 3), 'hall')).toEqual(['C']); + // Nobody had plum: it is in the envelope. + expect(owners(deduce(v, 'A', 2), 'plum')).toEqual(['env']); + }); + + test('stays sound: the true owner is never ruled out, at any depth, through whole bot games', () => { + for (let g = 0; g < 12; g++) { + const n = 3 + (g % 4); + const players = Array.from({ length: n }, (_, i) => `bot:${i}:x`); + const rng = SeededRng.fromSeed(seedN(300 + g)); + const ch = SeededRng.fromSeed(seedN(400 + g)); + let s = clue.setup({ players, options: clue.defaultOptions, rng, now: 0 }); + for (let step = 0; step < 4000 && !clue.result(s); step++) { + const p = clue.activePlayers(s)[0]!; + if (step % 5 === 0) { + for (const depth of [1, 2, 3] as const) { + const notes = deduce(clue.view(s, p), p, depth); + for (const x of ITEMS) { + const card = cardId(x); + const truth: Owner | null = s.publicCards.includes(card) + ? null + : x === s.solution.suspect || x === s.solution.weapon || x === s.solution.room + ? 'env' + : players.find((q) => s.hands[q]!.includes(card))!; + if (truth !== null && !notes[x].has(truth)) throw new Error(`depth ${depth}: ${x} ruled out for ${truth}`); + } + } + } + const a = decideBotAction(clue, s, p, { now: step, random: () => ch.next(), level: [5, 30, 55][g % 3] }); + s = clue.apply(s, p, a as ClueAction, { rng, now: step }).state; + } + expect(clue.result(s)).not.toBeNull(); + } + }); +}); + +describe('clue bot play', () => { + test('accuses as soon as the case is certain, never before (default strength)', () => { + const s = rigged(HANDS); + // A has seen every card except plum / rope / study. + const shownTo = (by: string, refuter: string, x: Item, room: Room) => + ({ by, suspect: 'scarlet', weapon: 'candlestick', room, passed: [], refuter, shown: cardId(x), auto: false, turnNo: 1 }) as ClueState['suggestions'][number]; + const others: Item[] = [...HANDS.B!, ...HANDS.C!]; + s.suggestions = others.map((x) => shownTo('A', HANDS.B!.includes(x) ? 'B' : 'C', x, 'kitchen')); + expect(solved(deduce(clue.view(s, 'A'), 'A'))).toEqual({ suspect: 'plum', weapon: 'rope', room: 'study' }); + expect(decide(s, 'A')).toEqual({ type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'study' }); + // One card short: no accusation. + s.suggestions.pop(); + expect(decide(s, 'A').type).not.toBe('accuse'); + }); + + test('suggests cards it knows nothing about; heads for unknown rooms', () => { + const s = rigged(HANDS); + s.pos.scarlet = { at: 'kitchen' }; + s.phase = { kind: 'suggest', room: 'kitchen' }; + for (let seed = 1; seed <= 8; seed++) { + const a = decide(s, 'A', seed) as Extract; + expect(a.type).toBe('suggest'); + expect(HANDS.A).not.toContain(a.suspect); + expect(HANDS.A).not.toContain(a.weapon); + } + // Quick mode: goes to a room it has not ruled out (not one of its own three). + const f = rigged(HANDS, undefined, { movement: 'free' }); + for (let seed = 1; seed <= 8; seed++) { + const a = decide(f, 'A', seed) as Extract; + expect(a.type).toBe('go'); + expect(HANDS.A).not.toContain(a.room); + } + // In the kitchen (own card) a corner passage to the unknown study is taken. + const k = rigged(HANDS); + k.pos.scarlet = { at: 'kitchen' }; + expect(decide(k, 'A')).toEqual({ type: 'passage' }); + }); + + test('shows the asker a card they have already seen from it', () => { + let s = rigged(HANDS); + s.suggestions.push({ by: 'A', suspect: 'white', weapon: 'rope', room: 'kitchen', passed: [], refuter: 'B', shown: cardId('library'), auto: false, turnNo: 0 }); + s.pos.scarlet = { at: 'library' }; + s.phase = { kind: 'suggest', room: 'library' }; + s = apply(s, 'A', { type: 'suggest', suspect: 'white', weapon: 'dagger' }); + expect(s.phase).toEqual({ kind: 'refute', refuter: 'B' }); + for (let seed = 1; seed <= 5; seed++) expect(decide(s, 'B', seed)).toEqual({ type: 'show', card: cardId('library') }); + }); + + test('bots-only games end with a correct accusation; the strongest never accuses wrongly', () => { + for (const movement of ['dice', 'free'] as const) { + for (let g = 0; g < 6; g++) { + const n = 3 + (g % 4); + const players = Array.from({ length: n }, (_, i) => `bot:${i}:x`); + const rng = SeededRng.fromSeed(seedN(700 + g)); + const ch = SeededRng.fromSeed(seedN(800 + g)); + let s = clue.setup({ players, options: clue.optionsSchema.parse({ movement }), rng, now: 0 }); + let steps = 0; + for (; steps < 6000 && !clue.result(s); steps++) { + const p = clue.activePlayers(s)[0]!; + s = clue.apply(s, p, decideBotAction(clue, s, p, { now: steps, random: () => ch.next(), level: 60 }) as ClueAction, { rng, now: steps }).state; + } + const r = clue.result(s)!; + expect(r).not.toBeNull(); + expect(s.accusations.every((a) => a.correct)).toBe(true); + expect(r.ranking[0]).toHaveLength(1); + } + } + }); + + test('a strong computer beats two weak ones more often than its share', () => { + let wins = 0; + const G = 24; + for (let g = 0; g < G; g++) { + const players = ['bot:0:x', 'bot:1:x', 'bot:2:x']; + const strong = players[g % 3]!; + const rng = SeededRng.fromSeed(seedN(900 + g)); + const ch = SeededRng.fromSeed(seedN(950 + g)); + let s = clue.setup({ players, options: clue.defaultOptions, rng, now: 0 }); + for (let steps = 0; steps < 6000 && !clue.result(s); steps++) { + const p = clue.activePlayers(s)[0]!; + const a = decideBotAction(clue, s, p, { now: steps, random: () => ch.next(), level: p === strong ? 60 : 5 }); + s = clue.apply(s, p, a as ClueAction, { rng, now: steps }).state; + } + if (clue.result(s)?.ranking[0]?.[0] === strong && clue.result(s)!.ranking[0]!.length === 1) wins++; + } + expect(wins).toBeGreaterThan(G / 2); + }); + + test('with a person who only times out and with every level, games finish', () => { + for (const level of [1, 30, 60]) { + for (let seed = 1; seed <= 3; seed++) { + const r = botPlayout(clue as never, { players: ['human', 'bot:1:x', 'bot:2:x', 'bot:3:x'], seed: seedN(seed * 11 + level), isBot: (p) => p.startsWith('bot:'), maxSteps: 20_000, level }); + expect(r.finished).toBe(true); + expect(r.botTimeouts).toBe(0); + } + } + }); +}); diff --git a/packages/games/src/clue/bot.ts b/packages/games/src/clue/bot.ts new file mode 100644 index 0000000..01feb66 --- /dev/null +++ b/packages/games/src/clue/bot.ts @@ -0,0 +1,194 @@ +/** + * 클루 computer player: a detective's notebook kept from its own view only — own cards, public cards, cards shown to + * it, who could not answer a suggestion, "someone showed one of these three" and wrong accusations. Higher levels use + * more of it (docs/games/clue.md §8.7): + * 1~20 단순 소거: own / public / shown cards, and "the last unknown card of a kind is in the envelope". + * 21~40 + who could not answer, and hand sizes (a full hand owns nothing else). + * 41~60 + "one of these three" constraints and wrong accusations. + * It accuses only when the case file is certain (the weakest sometimes gambles on one of two answers), suggests the + * cards it knows least about, and heads for rooms it has not ruled out. + */ +import type { PlayerId } from '@bg/engine'; +import type { BotStrategy } from '../bots/types'; +import { best, pick, randomPolicy } from '../bots/policy'; +import { + CATEGORY_ITEMS, + ITEMS, + PASSAGES, + ROOMS, + SUSPECTS, + WEAPONS, + categoryOf, + itemOf, + roomAt, + type Category, + type ClueAction, + type ClueView, + type Item, + type Room, + type Suspect, + type Weapon, +} from './index'; + +/** Who may hold a card: a player or the case file. */ +export type Owner = PlayerId | 'env'; +export type Notes = Record>; +export type Depth = 1 | 2 | 3; + +export const depthFor = (level: number | undefined): Depth => (level === undefined || level > 40 ? 3 : level > 20 ? 2 : 1); + +/** + * Possible owners of every card that is not face up (public cards get an empty set). Sound: the true owner always + * stays in the set, whatever the depth. + */ +export function deduce(v: ClueView, me: PlayerId, depth: Depth = 3): Notes { + const holders = v.seats.filter((p) => !v.left[p]); + const pub = new Set(v.publicCards.map(itemOf)); + const mine = new Set((v.myHand ?? []).map(itemOf)); + const notes = {} as Notes; + for (const x of ITEMS) notes[x] = pub.has(x) ? new Set() : mine.has(x) ? new Set([me]) : new Set([...holders.filter((p) => p !== me), 'env']); + const constraints: { p: PlayerId; items: Item[] }[] = []; + const notAll: Item[][] = []; + for (const sg of v.suggestions) { + const three: Item[] = [sg.suspect, sg.weapon, sg.room]; + if (sg.shown) { + if (sg.by === me && sg.refuter) notes[itemOf(sg.shown)] = new Set([sg.refuter]); + } else if (sg.refuter && sg.refuter !== me) constraints.push({ p: sg.refuter, items: three }); + if (depth >= 2) for (const p of sg.passed) for (const x of three) notes[x].delete(p); + } + for (const a of v.accusations) if (!a.correct) notAll.push([a.suspect, a.weapon, a.room]); + const assigned = (x: Item) => (notes[x].size === 1 ? [...notes[x]][0]! : null); + for (let round = 0; round < 30; round++) { + const before = ITEMS.map((x) => notes[x].size).join(); + // A kind's card in the envelope rules the others out; the last one that can be there is there. + for (const cat of ['suspect', 'weapon', 'room'] as Category[]) { + const items = CATEGORY_ITEMS[cat]; + const inEnv = items.filter((x) => assigned(x) === 'env'); + if (inEnv.length) for (const x of items) if (x !== inEnv[0]) notes[x].delete('env'); + const can = items.filter((x) => notes[x].has('env')); + if (can.length === 1) notes[can[0]!] = new Set(['env']); + } + if (depth >= 2) { + for (const p of holders) { + if (p === me) continue; + const has = ITEMS.filter((x) => assigned(x) === p); + const could = ITEMS.filter((x) => notes[x].has(p)); + const size = v.handCounts[p] ?? 0; + if (has.length >= size) { + for (const x of could) if (assigned(x) !== p) notes[x].delete(p); + } else if (could.length === size) { + for (const x of could) notes[x] = new Set([p]); + } + } + } + if (depth >= 3) { + for (const c of constraints) { + if (c.items.some((x) => assigned(x) === c.p)) continue; + const left = c.items.filter((x) => notes[x].has(c.p)); + if (left.length === 1) notes[left[0]!] = new Set([c.p]); + } + for (const three of notAll) { + const inEnv = three.filter((x) => assigned(x) === 'env'); + if (inEnv.length === 2) for (const x of three) if (!inEnv.includes(x)) notes[x].delete('env'); + } + } + // A card with no owner left means the notes contradict themselves (cannot happen with sound rules); stop here. + if (ITEMS.some((x) => !pub.has(x) && notes[x].size === 0)) break; + if (ITEMS.map((x) => notes[x].size).join() === before) break; + } + return notes; +} + +/** Cards of a kind that may still be in the envelope. */ +export const envCandidates = (notes: Notes, items: readonly T[]): T[] => items.filter((x) => notes[x].has('env')); + +/** The case file if the notes pin it down. */ +export function solved(notes: Notes): { suspect: Suspect; weapon: Weapon; room: Room } | null { + const s = envCandidates(notes, SUSPECTS); + const w = envCandidates(notes, WEAPONS); + const r = envCandidates(notes, ROOMS); + return s.length === 1 && w.length === 1 && r.length === 1 ? { suspect: s[0]!, weapon: w[0]!, room: r[0]! } : null; +} + +/** How useful a card is to name in a suggestion: unknown cards first, then ones nobody can show (mine / the envelope). */ +function askValue(notes: Notes, x: Item, me: PlayerId): number { + const o = notes[x]; + if (o.size > 1) return 10 + o.size + (o.has('env') ? 2 : 0); + if (o.has('env') || o.has(me)) return 4; + return 0; +} + +/** Is a room worth suggesting in? Unknown rooms most, then rooms whose card nobody else can show. */ +const roomValue = (notes: Notes, r: Room, me: PlayerId) => askValue(notes, r, me); + +function accuseIfReady(notes: Notes, level: number | undefined, random: () => number): ClueAction | null { + const sol = solved(notes); + if (sol) return { type: 'accuse', ...sol }; + // 쉬움 computers sometimes trust a hunch when only two answers are left. + if (level !== undefined && level <= 20) { + const s = envCandidates(notes, SUSPECTS); + const w = envCandidates(notes, WEAPONS); + const r = envCandidates(notes, ROOMS); + if (s.length * w.length * r.length === 2 && random() < 0.35) return { type: 'accuse', suspect: pick(s, random), weapon: pick(w, random), room: pick(r, random) }; + } + return null; +} + +/** Chance to ignore the notes for one choice (a person's lapse). */ +const slipChance = (level: number | undefined) => (level === undefined ? 0 : Math.max(0, 0.3 - level * 0.005)); + +export const clueBot: BotStrategy = (input) => { + const { me, view: v, legal, random, level } = input; + const ph = v.phase; + if (ph.kind === 'refute') { + // Show a card this suggester has already seen from me if possible (gives nothing new away), otherwise one I've shown before. + const cards = ph.canShow ?? []; + if (!cards.length) return randomPolicy(input); + const asker = v.suggestions[v.suggestions.length - 1]!.by; + const shownTo = (c: string, who?: PlayerId) => v.suggestions.filter((x) => x.refuter === me && x.shown === c && (!who || x.by === who)).length; + const card = best(cards, (c) => shownTo(c, asker) * 10 + shownTo(c) + (categoryOf(itemOf(c)) === 'room' ? 0.5 : 0), random); + return { type: 'show', card }; + } + const notes = deduce(v, me, depthFor(level)); + const slip = random() < slipChance(level); + const accuse = ph.kind === 'moveTo' ? null : accuseIfReady(notes, level, random); + if (accuse) return accuse; + const pos = v.pos[v.suspectOf[me]!]; + const here = roomAt(pos); + const value = (r: Room) => (slip ? random() * 10 : roomValue(notes, r, me)); + switch (ph.kind) { + case 'move': { + if (here && v.movedIn[me] && value(here) >= 10) return { type: 'stay' }; + if (v.options.movement === 'free') { + const rooms = ROOMS.filter((r) => r !== here); + return { type: 'go', room: best(rooms, value, random) }; + } + const through = here ? PASSAGES[here] : undefined; + if (through && value(through) >= 10) return { type: 'passage' }; + return { type: 'roll' }; + } + case 'moveTo': { + const d = v.distances!; + const sum = v.dice ? v.dice[0] + v.dice[1] : 0; + const rooms = ROOMS.filter((r) => r !== here); + const reach = rooms.filter((r) => d[r] <= sum); + const top = Math.max(...rooms.map(value)); + const goodReach = reach.filter((r) => value(r) >= Math.min(top, 10)); + if (goodReach.length) return { type: 'go', room: best(goodReach, (r) => value(r) - d[r] * 0.01, random) }; + // Nothing worth it in reach: head for the nearest room worth visiting (or step into any room if none is far). + const worth = rooms.filter((r) => value(r) >= Math.min(top, 10)); + const target = best(worth, (r) => -d[r], random); + if (d[target] > sum) return { type: 'walk', room: target }; + return reach.length ? { type: 'go', room: best(reach, value, random) } : { type: 'walk', room: target }; + } + case 'suggest': { + const ask = (xs: readonly Item[]) => best(xs, (x) => (slip ? random() : askValue(notes, x, me)), random); + return { type: 'suggest', suspect: ask(SUSPECTS) as Suspect, weapon: ask(WEAPONS) as Weapon }; + } + case 'afterSuggest': + return { type: 'end' }; + default: + break; + } + return legal.length ? randomPolicy(input) : { type: 'end' }; +}; diff --git a/packages/games/src/clue/clue.test.ts b/packages/games/src/clue/clue.test.ts new file mode 100644 index 0000000..7e77c1e --- /dev/null +++ b/packages/games/src/clue/clue.test.ts @@ -0,0 +1,438 @@ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent } from '@bg/engine'; +import { + DIST, + ITEMS, + PASSAGES, + ROOMS, + SUSPECTS, + WEAPONS, + cardId, + clue, + distTo, + walkToward, + type ClueAction, + type ClueOptions, + type ClueState, + type Item, + type Pos, + type Room, +} from './index'; + +const P3 = ['A', 'B', 'C']; +let clock = 1_700_000_000_000; + +function make(players = P3, opts: Partial = {}, seed = 1): ClueState { + return clue.setup({ players, options: clue.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: clock }); +} + +/** A game with A to move, every token at its start, and hands / case file as written. */ +function rigged(hands: Record, solution = { suspect: 'plum', weapon: 'rope', room: 'study' } as ClueState['solution'], opts: Partial = {}): ClueState { + const players = Object.keys(hands); + const s = make(players, opts); + s.solution = solution; + s.hands = Object.fromEntries(players.map((p) => [p, hands[p]!.map(cardId)])); + const used = new Set([...Object.values(hands).flat(), solution.suspect, solution.weapon, solution.room]); + s.publicCards = ITEMS.filter((x) => !used.has(x)).map(cardId); + s.current = players[0]!; + s.suspectOf = Object.fromEntries(players.map((p, i) => [p, SUSPECTS[i]!])); + return s; +} + +function act(s: ClueState, actor: string, a: ClueAction, seed = 7): { state: ClueState; events: GameEvent[] } { + const v = clue.validate(s, actor, a); + if (!v.ok) throw new Error(`rejected ${JSON.stringify(a)} by ${actor}: ${v.reason}`); + clock += 1000; + return clue.apply(s, actor, a, { rng: SeededRng.fromSeed(seedN(seed)), now: clock }); +} +const go = (s: ClueState, actor: string, a: ClueAction) => act(s, actor, a).state; +const reason = (s: ClueState, actor: string, a: ClueAction) => { + const v = clue.validate(s, actor, a); + return v.ok ? 'ok' : v.reason; +}; +/** Puts `actor` straight into `room`, ready to suggest. */ +function inRoom(s: ClueState, actor: string, room: Room): ClueState { + const t = structuredClone(s); + t.pos[t.suspectOf[actor]!] = { at: room }; + t.current = actor; + t.phase = { kind: 'suggest', room }; + return t; +} + +describe('setup', () => { + test.each([ + [3, 6, 0], + [4, 4, 2], + [5, 3, 3], + [6, 3, 0], + ])('%i players: %i cards each, %i face up, case file out of the deal', (n, each, open) => { + for (let seed = 1; seed <= 20; seed++) { + const players = ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n); + const s = make(players, {}, seed); + for (const p of players) expect(s.hands[p]).toHaveLength(each); + expect(s.publicCards).toHaveLength(open); + const all = [...Object.values(s.hands).flat(), ...s.publicCards, cardId(s.solution.suspect), cardId(s.solution.weapon), cardId(s.solution.room)]; + expect(new Set(all).size).toBe(21); + expect(SUSPECTS).toContain(s.solution.suspect); + expect(WEAPONS).toContain(s.solution.weapon); + expect(ROOMS).toContain(s.solution.room); + // The first player is 스칼렛; the suspects follow clockwise. + expect(s.suspectOf[s.current]).toBe('scarlet'); + const i = players.indexOf(s.current); + expect(s.suspectOf[players[(i + 1) % n]!]).toBe('mustard'); + expect(new Set(Object.values(s.weaponAt)).size).toBe(6); + for (const x of SUSPECTS) expect(s.pos[x]).toEqual({ at: `start-${x}` }); + } + }); + + test('2 or 7 players are refused', () => { + expect(() => make(['A', 'B'])).toThrow(); + expect(() => make(['A', 'B', 'C', 'D', 'E', 'F', 'G'])).toThrow(); + }); +}); + +describe('mansion', () => { + test('distances are symmetric, rooms 4~16 steps apart, passages join opposite corners', () => { + for (const a of ROOMS) + for (const b of ROOMS) { + expect(DIST[a][b]).toBe(DIST[b][a]); + if (a !== b) expect(DIST[a][b]).toBeGreaterThanOrEqual(4); + expect(DIST[a][b]).toBeLessThan(20); + } + expect(PASSAGES.kitchen).toBe('study'); + expect(PASSAGES.lounge).toBe('conservatory'); + expect(DIST.kitchen.study).toBeGreaterThan(12); // the passage is the only quick way + }); + + test('walking k steps towards a room brings it exactly k steps closer', () => { + const r = SeededRng.fromSeed(seedN(3)); + for (let i = 0; i < 2000; i++) { + let p: Pos = { at: i % 2 ? ROOMS[r.int(9)]! : `start-${SUSPECTS[r.int(6)]!}` }; + for (let hop = 0; hop < 4; hop++) { + const target = ROOMS[r.int(9)]!; + const d = distTo(p, target); + if (d <= 2) break; + const k = 1 + r.int(d - 1); + const q = walkToward(p, target, k); + expect(distTo(q, target)).toBe(d - k); + p = q; + } + } + }); +}); + +describe('moving', () => { + test('roll → enter a room in reach (not the one I left) or walk towards a far one', () => { + let s = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] }); + expect(reason(s, 'A', { type: 'go', room: 'lounge' })).toBe('먼저 주사위를 굴려 주세요.'); + expect(reason(s, 'A', { type: 'passage' })).toBe('여기에는 비밀 통로가 없어요.'); + expect(reason(s, 'B', { type: 'roll' })).toBe('지금은 내 차례가 아니에요.'); + s = go(s, 'A', { type: 'roll' }); + expect(s.phase.kind).toBe('moveTo'); + const sum = s.dice![0] + s.dice![1]; + const pos = s.pos.scarlet; + for (const room of ROOMS) { + const d = distTo(pos, room); + expect(reason(s, 'A', { type: 'go', room })).toBe(d <= sum ? 'ok' : `${{ kitchen: '부엌', ballroom: '무도회장', conservatory: '온실', dining: '식당', billiard: '당구장', library: '도서실', lounge: '라운지', hall: '홀', study: '서재' }[room]}까지 ${d}칸이라 이번에는 닿지 않아요.`); + expect(reason(s, 'A', { type: 'walk', room })).toBe(d > sum ? 'ok' : '닿는 방이에요. 바로 들어가 주세요.'); + } + // Walking ends the turn in the corridor. + const far = ROOMS.find((r) => distTo(pos, r) > sum)!; + const w = go(s, 'A', { type: 'walk', room: far }); + expect(w.current).toBe('B'); + expect('at' in w.pos.scarlet).toBe(false); + expect(distTo(w.pos.scarlet, far)).toBe(distTo(pos, far) - sum); + }); + + test('secret passage from a corner room; no re-entering the room I am in', () => { + let s = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] }); + s.pos.scarlet = { at: 'kitchen' }; + s = go(s, 'A', { type: 'passage' }); + expect(s.phase).toEqual({ kind: 'suggest', room: 'study' }); + expect(s.pos.scarlet).toEqual({ at: 'study' }); + let t = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] }); + t.pos.scarlet = { at: 'hall' }; + t = go(t, 'A', { type: 'roll' }); + expect(reason(t, 'A', { type: 'go', room: 'hall' })).toBe('방금 있던 방에는 다시 들어갈 수 없어요. 다른 방을 골라 주세요.'); + }); + + test('quick mode: go anywhere at once, no dice', () => { + let s = rigged({ A: ['scarlet'], B: ['mustard'], C: ['white'] }, undefined, { movement: 'free' }); + expect(reason(s, 'A', { type: 'roll' })).toBe('이 방은 주사위 없이 바로 이동해요.'); + s = go(s, 'A', { type: 'go', room: 'study' }); + expect(s.phase).toEqual({ kind: 'suggest', room: 'study' }); + expect(clue.view(s, 'A').distances).toBeNull(); + }); +}); + +describe('suggestions', () => { + // Solution plum / rope / study. B holds green+dagger, C holds candlestick+library. + const hands = { A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] } as Record; + + test('the named suspect and weapon come into the room; the next player with a card must show one', () => { + let s = inRoom(rigged(hands), 'A', 'library'); + const r = act(s, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' }); + s = r.state; + expect(s.pos.mustard).toEqual({ at: 'library' }); + expect(s.weaponAt.rope).toBe('library'); + expect(s.movedIn.B).toBe(true); // B plays 머스터드 + // B has none of mustard / rope / library → passes; C has two → C chooses. + expect(s.phase).toEqual({ kind: 'refute', refuter: 'C' }); + expect(s.suggestions[0]!.passed).toEqual(['B']); + expect(clue.activePlayers(s)).toEqual(['C']); + expect(clue.view(s, 'C').phase).toEqual({ kind: 'refute', refuter: 'C', canShow: [cardId('mustard'), cardId('library')] }); + expect(clue.view(s, 'A').phase).toEqual({ kind: 'refute', refuter: 'C' }); + expect(reason(s, 'C', { type: 'show', card: cardId('candlestick') })).toBe('추리에 나온 카드 중 내가 가진 카드를 골라 주세요.'); + expect(reason(s, 'A', { type: 'end' })).toBe('다른 사람이 카드를 보여 주는 중이에요.'); + const shown = act(s, 'C', { type: 'show', card: cardId('library') }); + s = shown.state; + expect(s.phase.kind).toBe('afterSuggest'); + expect(s.current).toBe('A'); + // Only A and C see which card; events never carry it. + expect(clue.view(s, 'A').suggestions[0]!.shown).toBe(cardId('library')); + expect(clue.view(s, 'C').suggestions[0]!.shown).toBe(cardId('library')); + expect(clue.view(s, 'B').suggestions[0]!.shown).toBeUndefined(); + expect(clue.view(s, null).suggestions[0]!.shown).toBeUndefined(); + expect(clue.view(s, 'B').suggestions[0]!.refuter).toBe('C'); + for (const e of [...r.events, ...shown.events]) expect(JSON.stringify(e)).not.toContain('card-'); + s = go(s, 'A', { type: 'end' }); + expect(s.current).toBe('B'); + }); + + test('moved in by a suggestion: may suggest there on the next turn without moving', () => { + let s = inRoom(rigged(hands), 'A', 'library'); + expect(reason(s, 'A', { type: 'end' })).toBe('ok'); + s = go(s, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' }); + s = go(s, 'C', { type: 'show', card: cardId('mustard') }); + s = go(s, 'A', { type: 'end' }); + expect(s.current).toBe('B'); + expect(clue.legalActions!(s, 'B')).toContainEqual({ type: 'stay' }); + s = go(s, 'B', { type: 'stay' }); + expect(s.phase).toEqual({ kind: 'suggest', room: 'library' }); + s = go(s, 'B', { type: 'end' }); + // The right expires after that turn. + expect(s.movedIn.B).toBe(false); + }); + + test('nobody can answer: everyone passes, the suggester decides', () => { + let s = inRoom(rigged(hands), 'A', 'study'); + s = go(s, 'A', { type: 'suggest', suspect: 'plum', weapon: 'rope' }); + expect(s.phase.kind).toBe('afterSuggest'); + expect(s.suggestions[0]).toMatchObject({ passed: ['B', 'C'], refuter: null, shown: null }); + }); + + test('my own cards in a suggestion do not stop the others from being asked', () => { + let s = inRoom(rigged(hands), 'A', 'kitchen'); + s = go(s, 'A', { type: 'suggest', suspect: 'scarlet', weapon: 'wrench' }); + expect(s.suggestions[0]!.passed).toEqual(['B', 'C']); + }); +}); + +describe('accusations', () => { + const hands = { A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] } as Record; + + test('right: wins at once, anywhere on my turn', () => { + const s = rigged(hands); + const r = act(s, 'A', { type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'study' }); + const res = clue.result(r.state)!; + expect(res.ranking).toEqual([['A'], ['B', 'C']]); + expect(res.summary).toContain('플럼 교수 · 밧줄 · 서재'); + expect(res.scoreText).toBeUndefined(); + expect(clue.view(r.state, 'B').solution).toEqual({ suspect: 'plum', weapon: 'rope', room: 'study' }); + }); + + test('wrong: out of turns but still shows cards; all wrong → nobody wins', () => { + let s = rigged(hands); + s = go(s, 'A', { type: 'accuse', suspect: 'green', weapon: 'rope', room: 'study' }); + expect(s.out.A).toBe(true); + expect(s.current).toBe('B'); + expect(clue.view(s, 'B').solution).toBeNull(); + // B suggests cards only A holds (C passes): A is out but must still show one. + s = inRoom(s, 'B', 'kitchen'); + s = go(s, 'B', { type: 'suggest', suspect: 'plum', weapon: 'wrench' }); + expect(s.phase).toEqual({ kind: 'refute', refuter: 'A' }); + expect(s.suggestions[0]!.passed).toEqual(['C']); + expect(clue.legalActions!(s, 'A')).toEqual([ + { type: 'show', card: cardId('wrench') }, + { type: 'show', card: cardId('kitchen') }, + ]); + s = go(s, 'A', { type: 'show', card: cardId('kitchen') }); + expect(reason(s, 'A', { type: 'roll' })).toBe('고발이 틀려서 이제 카드 보여 주기만 할 수 있어요.'); + s = go(s, 'B', { type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'hall' }); + expect(s.current).toBe('C'); // A is skipped + s = go(s, 'C', { type: 'accuse', suspect: 'plum', weapon: 'dagger', room: 'study' }); + const res = clue.result(s)!; + expect(res.ranking).toEqual([['A', 'B', 'C']]); + expect(res.summary).toContain('아무도 못 이겼어요'); + }); +}); + +describe('timer and leaving', () => { + const hands = { A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] } as Record; + + test('one timeout plays the whole turn (roll, nearest room, no suggestion)', () => { + const s = rigged(hands); + const t = go(s, 'A', { type: 'timeout' }); + expect(t.current).toBe('B'); + expect(t.suggestions).toHaveLength(0); + expect(t.idle.A).toBe(1); + expect(t.deadlineAt).toBe(clock + 60_000); + }); + + test('refute timeout shows the first matching card; refute clock is 20 s', () => { + let s = inRoom(rigged(hands), 'A', 'library'); + s = go(s, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' }); + expect(s.deadlineAt).toBe(clock + 20_000); + s = go(s, 'C', { type: 'timeout' }); + expect(s.suggestions[0]).toMatchObject({ refuter: 'C', shown: cardId('mustard'), auto: true }); + expect(s.idle.C).toBe(0); + }); + + test('three missed turns shorten the clock; when everyone left in the game is away it ends', () => { + let s = rigged(hands); + s.out.B = true; + s.out.C = true; + for (let i = 0; i < 2; i++) s = go(s, 'A', { type: 'timeout' }); + expect(s.current).toBe('A'); + expect(s.phase.kind).toBe('move'); + s = go(s, 'A', { type: 'timeout' }); + expect(clue.result(s)!.reason).toBe('timeout'); + let t = rigged(hands); + for (let i = 0; i < 9; i++) t = go(t, t.current, { type: 'timeout' }); + expect(clue.result(t)!.reason).toBe('timeout'); + // A and B are away, C still plays: the game goes on, A's and B's turns get the short clock. + let u = rigged(hands); + for (let i = 0; i < 3; i++) { + u = go(u, 'A', { type: 'timeout' }); + u = go(u, 'B', { type: 'timeout' }); + u = go(u, 'C', { type: 'roll' }); + u = go(u, 'C', clue.legalActions!(u, 'C').find((a) => a.type === 'walk' || a.type === 'go')!); + if (u.phase.kind === 'suggest') u = go(u, 'C', { type: 'end' }); + } + expect(u.phase.kind).toBe('move'); + 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' }); + expect(s.phase).toEqual({ kind: 'refute', refuter: 'B' }); + s = go(s, 'B', { type: 'leave' }); + expect(s.publicCards).toEqual(expect.arrayContaining([cardId('green'), cardId('dagger'), cardId('hall')])); + expect(s.phase).toEqual({ kind: 'refute', refuter: 'C' }); + s = go(s, 'C', { type: 'show', card: cardId('library') }); + s = go(s, 'A', { type: 'end' }); + expect(s.current).toBe('C'); + s = go(s, 'C', { type: 'leave' }); + const res = clue.result(s)!; + expect(res.ranking[0]).toEqual(['A']); + expect(res.reason).toBe('resign'); + }); +}); + +// ---------------------------------------------------------------- random games + +/** Random but varied: pick an action type first (accusations rarely), then one of that type. */ +function variedPick(legal: ClueAction[], r: SeededRng): ClueAction { + const types = [...new Set(legal.map((a) => a.type))]; + const weighted = types.flatMap((t) => (t === 'accuse' ? (r.int(12) === 0 ? [t] : []) : [t, t])); + const t = weighted.length ? weighted[r.int(weighted.length)]! : types[r.int(types.length)]!; + const xs = legal.filter((a) => a.type === t); + return xs[r.int(xs.length)]!; +} + +/** What `viewer` may know: own hand, face-up cards, cards shown to or by them (everything once the game is over). */ +function allowedCards(s: ClueState, viewer: string | null): Set { + if (s.phase.kind === 'finished') return new Set(ITEMS.map(cardId)); + const out = new Set(s.publicCards); + if (viewer) { + for (const c of s.hands[viewer] ?? []) out.add(c); + for (const sg of s.suggestions) if (sg.shown && (sg.by === viewer || sg.refuter === viewer)) out.add(sg.shown); + } + return out; +} + +function checkViews(s: ClueState) { + for (const viewer of [...s.seats, null]) { + const json = JSON.stringify(clue.view(s, viewer)); + const ok = allowedCards(s, viewer); + for (const x of ITEMS) if (!ok.has(cardId(x)) && json.includes(`"${cardId(x)}"`)) throw new Error(`view of ${viewer} leaks ${cardId(x)}`); + if (s.phase.kind !== 'finished' && json.includes('"solution":{')) throw new Error('case file leaks'); + } +} + +function conserved(s: ClueState) { + const all = [...Object.values(s.hands).flat(), ...s.publicCards.filter((c) => !Object.values(s.hands).flat().includes(c)), cardId(s.solution.suspect), cardId(s.solution.weapon), cardId(s.solution.room)]; + if (new Set(all).size !== 21 || all.length !== 21) throw new Error(`cards not conserved: ${all.length}`); +} + +describe('random games', () => { + const N = playoutSeeds(300); + test(`${N} varied games: legal, conserved, no leaks in views or events, onTimeout always valid`, () => { + let finished = 0; + let refutes = 0; + for (let g = 0; g < N; g++) { + const n = 3 + (g % 4); + const players = ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n); + const opts = clue.optionsSchema.parse({ movement: g % 3 === 2 ? 'free' : 'dice' }); + const rng = SeededRng.fromSeed(seedN(1000 + g)); + const ch = SeededRng.fromSeed(seedN(5000 + g)); + let s = clue.setup({ players, options: opts, rng, now: 0 }); + for (let step = 0; step < 3000 && !clue.result(s); step++) { + checkViews(s); + conserved(s); + const actor = clue.activePlayers(s)[0]!; + expect(clue.validate(s, actor, clue.onTimeout(s, actor)).ok).toBe(true); + const r = ch.int(25); + let a: ClueAction; + if (r === 0) a = clue.onTimeout(s, actor); + else if (r === 1 && step > 30) a = { type: 'leave' }; + else a = variedPick(clue.legalActions!(s, actor), ch); + const v = clue.validate(s, actor, a); + if (!v.ok) throw new Error(`legal action rejected: ${v.reason} ${JSON.stringify(a)}`); + if (s.phase.kind === 'refute') refutes++; + const out = clue.apply(s, actor, a, { rng, now: step * 1000 }); + const hidden = new Set(ITEMS.map(cardId)); + if (out.state.phase.kind !== 'finished') for (const e of out.events) for (const c of hidden) if (JSON.stringify(e).includes(`"${c}"`)) throw new Error(`event leaks ${c}`); + s = out.state; + } + checkViews(s); + if (clue.result(s)) finished++; + } + expect(finished).toBe(N); + expect(refutes).toBeGreaterThan(N); + }); + + 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 }); + expect(r.finished).toBe(true); + } + }); + + test('deterministic for the same seed and actions', () => { + const run = () => { + const rng = SeededRng.fromSeed(seedN(42)); + const ch = SeededRng.fromSeed(seedN(43)); + let s = clue.setup({ players: P3, options: clue.defaultOptions, rng, now: 0 }); + for (let i = 0; i < 200 && !clue.result(s); i++) { + const actor = clue.activePlayers(s)[0]!; + s = clue.apply(s, actor, variedPick(clue.legalActions!(s, actor), ch), { rng, now: i }).state; + } + return JSON.stringify(s); + }; + expect(run()).toBe(run()); + }); + + test('secretsOf: unshown hand cards and the case file; nothing after the end', () => { + let s = inRoom(rigged({ A: ['scarlet', 'wrench', 'kitchen'], B: ['green', 'dagger', 'hall'], C: ['candlestick', 'library', 'mustard'] }), 'A', 'hall'); + expect(clue.secretsOf!(s, 'B')).toEqual([cardId('green'), cardId('dagger'), cardId('hall'), cardId('plum'), cardId('rope'), cardId('study')]); + s = go(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' }); + s = go(s, 'B', { type: 'show', card: cardId('green') }); + expect(clue.secretsOf!(s, 'B')).not.toContain(cardId('green')); + s = go(s, 'A', { type: 'accuse', suspect: 'plum', weapon: 'rope', room: 'study' }); + expect(clue.secretsOf!(s, 'B')).toEqual([]); + }); +}); diff --git a/packages/games/src/clue/index.ts b/packages/games/src/clue/index.ts new file mode 100644 index 0000000..ab73c93 --- /dev/null +++ b/packages/games/src/clue/index.ts @@ -0,0 +1,506 @@ +/** + * 클루 (docs/games/clue.md). + * + * Secret-id design: cards are 'card-' while suggestions and accusations name items ('rope'), so a card id only + * appears in a view where the viewer may know that card's place (own hand, a card shown to or by the viewer, public + * cards, everything after the game). The case file (사건 봉투) stays out of every view until the game ends. + */ +import { fail, nextSeat, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Validation } from '@bg/engine'; +import { + ITEMS, + PASSAGES, + ROOMS, + ROOM_KO, + SUSPECTS, + SUSPECT_KO, + WEAPONS, + WEAPON_KO, + cardId, + clueActionSchema, + clueOptionsSchema, + distTo, + roomAt, + startOf, + walkToward, + type ClueAction, + type ClueClientAction, + type ClueFinal, + type ClueOptions, + type ClueState, + type ClueView, + type PhaseView, + type Pos, + type Room, + type Suggestion, + type Suspect, + type Weapon, +} from './types'; +import type { z } from 'zod'; + +export * from './types'; + +export const MIN_PLAYERS = 3; +export const MAX_PLAYERS = 6; +const REFUTE_MS = 20_000; +const IDLE_MS = 10_000; +const IDLE_TURNS = 3; + +// ---------------------------------------------------------------- helpers + +const per = (players: PlayerId[], f: (p: PlayerId) => T) => Object.fromEntries(players.map((p) => [p, f(p)])) as Record; +const diceSum = (s: ClueState) => (s.dice ? s.dice[0] + s.dice[1] : 0); +const ownTurnPhase = (s: ClueState) => s.phase.kind === 'move' || s.phase.kind === 'moveTo' || s.phase.kind === 'suggest' || s.phase.kind === 'afterSuggest'; +/** Still takes turns. */ +const playing = (s: ClueState, p: PlayerId) => !s.out[p] && !s.left[p]; + +export const tripleKo = (x: { suspect: Suspect; weapon: Weapon; room: Room }) => `${SUSPECT_KO[x.suspect]} · ${WEAPON_KO[x.weapon]} · ${ROOM_KO[x.room]}`; + +/** The suggester's matching cards in `p`'s hand. */ +export function matchingCards(s: ClueState, p: PlayerId, sg: Pick): string[] { + const want = new Set([cardId(sg.suspect), cardId(sg.weapon), cardId(sg.room)]); + return ITEMS.map(cardId).filter((c) => want.has(c) && (s.hands[p] ?? []).includes(c)); +} + +function refreshDeadline(s: ClueState, now: number): void { + if (s.phase.kind === 'finished') { + s.deadlineAt = null; + return; + } + if (s.phase.kind === 'refute') { + s.deadlineAt = now + REFUTE_MS; + return; + } + s.deadlineAt = now + ((s.idle[s.current] ?? 0) >= IDLE_TURNS ? IDLE_MS : s.options.turnSeconds * 1000); +} + +function finish(s: ClueState, winner: PlayerId | null, reason: ClueFinal['reason'], events: GameEvent[]): void { + const answer = tripleKo(s.solution); + // "…서재였어요" / "…식당이었어요" + const last = answer.charCodeAt(answer.length - 1); + const was = last >= 0xac00 && last <= 0xd7a3 && (last - 0xac00) % 28 !== 0 ? '이었어요' : '였어요'; + const ranking = winner ? [[winner], s.seats.filter((p) => p !== winner)] : [[...s.seats]]; + let summary: string; + if (winner && reason === 'resign') summary = `다른 사람이 모두 나가서 게임이 끝났어요. 정답은 ${answer}${was}.`; + else if (winner) summary = `고발이 맞았어요! 정답은 ${answer}${was}. (추리 ${s.suggestions.filter((x) => x.by === winner).length}번)`; + else if (reason === 'timeout') summary = `남은 사람이 모두 자리를 비워 아무도 못 맞히고 끝났어요. 정답은 ${answer}${was}.`; + else summary = `모두 고발이 틀려서 아무도 못 이겼어요. 정답은 ${answer}${was}.`; + s.final = { winner, ranking, summary, reason }; + s.phase = { kind: 'finished' }; + s.dice = null; + events.push({ type: 'gameEnded', winner }); +} + +/** Ends the game when nobody is left to play (or only one person is still in the room). Returns true when finished. */ +function checkFinish(s: ClueState, events: GameEvent[]): boolean { + if (s.phase.kind === 'finished') return true; + const present = s.seats.filter((p) => !s.left[p]); + if (present.length === 1 && s.seats.length > 1 && !s.out[present[0]!]) { + finish(s, present[0]!, 'resign', events); + return true; + } + const active = s.seats.filter((p) => playing(s, p)); + if (active.length === 0) { + finish(s, null, 'normal', events); + return true; + } + return false; +} + +function endTurn(s: ClueState, events: GameEvent[]): void { + s.movedIn[s.current] = false; + s.dice = null; + if (checkFinish(s, events)) return; + const active = s.seats.filter((p) => playing(s, p)); + // Everybody still in the game let the clock run out three turns in a row: nobody is playing any more. + if (active.every((p) => (s.idle[p] ?? 0) >= IDLE_TURNS)) { + finish(s, null, 'timeout', events); + return; + } + const i = s.seats.indexOf(s.current); + s.current = s.seats[nextSeat(i, s.seats.length, (j) => !playing(s, s.seats[j]!))]!; + s.turnNo += 1; + s.phase = { kind: 'move' }; + events.push({ type: 'turn', player: s.current }); +} + +/** Asks the players after the suggester in turn, starting after `after`; stops at the first one holding a card. */ +function continueRefute(s: ClueState, after: PlayerId, events: GameEvent[]): void { + const sg = s.suggestions[s.suggestions.length - 1]!; + const n = s.seats.length; + const from = s.seats.indexOf(after); + for (let k = 1; k < n; k++) { + const p = s.seats[(from + k) % n]!; + if (p === sg.by) break; + if (s.left[p]) continue; + if (matchingCards(s, p, sg).length) { + s.phase = { kind: 'refute', refuter: p }; + events.push({ type: 'refuting', player: p }); + return; + } + sg.passed.push(p); + events.push({ type: 'passed', player: p }); + } + s.phase = { kind: 'afterSuggest' }; + events.push({ type: 'noRefute', by: sg.by }); +} + +function moveToken(s: ClueState, who: Suspect, room: Room): boolean { + if (roomAt(s.pos[who]) === room) return false; + s.pos[who] = { at: room }; + return true; +} + +function enter(s: ClueState, actor: PlayerId, room: Room, how: string, events: GameEvent[]): void { + s.pos[s.suspectOf[actor]!] = { at: room }; + s.phase = { kind: 'suggest', room }; + events.push({ type: 'entered', player: actor, room, how }); +} + +// ---------------------------------------------------------------- automatic actions (timer) + +/** Nearest room from `p` other than `except` (ties: map order). */ +function nearestRoom(p: Pos, except: Room | null): Room { + let best: Room = ROOMS.find((r) => r !== except)!; + for (const r of ROOMS) if (r !== except && distTo(p, r) < distTo(p, best)) best = r; + return best; +} + +/** The concrete action a timeout stands for (docs §8.5): move on to the nearest room without suggesting, show the first matching card. */ +export function autoAction(s: ClueState, player: PlayerId): ClueClientAction { + const ph = s.phase; + const pos = s.pos[s.suspectOf[player]!]; + switch (ph.kind) { + case 'move': + return s.options.movement === 'dice' ? { type: 'roll' } : { type: 'go', room: nearestRoom(pos, roomAt(pos)) }; + case 'moveTo': { + const here = roomAt(pos); + const reach = ROOMS.filter((r) => r !== here && distTo(pos, r) <= diceSum(s)); + if (reach.length) return { type: 'go', room: reach.reduce((a, b) => (distTo(pos, b) < distTo(pos, a) ? b : a)) }; + return { type: 'walk', room: nearestRoom(pos, here) }; + } + case 'suggest': + case 'afterSuggest': + return { type: 'end' }; + case 'refute': + return { type: 'show', card: matchingCards(s, player, s.suggestions[s.suggestions.length - 1]!)[0]! }; + case 'finished': + throw new Error('clue: no auto action after the game'); + } +} + +// ---------------------------------------------------------------- validate / apply + +function validateClient(s: ClueState, actor: PlayerId, a: ClueClientAction): Validation { + const ph = s.phase; + if (a.type === 'show') { + if (ph.kind !== 'refute') return fail('지금은 카드를 보여 줄 때가 아니에요.'); + if (ph.refuter !== actor) return fail('지금은 내가 카드를 보여 줄 차례가 아니에요.'); + if (!matchingCards(s, actor, s.suggestions[s.suggestions.length - 1]!).includes(a.card)) return fail('추리에 나온 카드 중 내가 가진 카드를 골라 주세요.'); + return ok; + } + if (s.out[actor]) return fail('고발이 틀려서 이제 카드 보여 주기만 할 수 있어요.'); + if (s.current !== actor) return fail('지금은 내 차례가 아니에요.'); + if (ph.kind === 'refute') return fail('다른 사람이 카드를 보여 주는 중이에요.'); + const pos = s.pos[s.suspectOf[actor]!]; + const here = roomAt(pos); + const dice = s.options.movement === 'dice'; + switch (a.type) { + case 'roll': + if (ph.kind !== 'move') return fail('지금은 주사위를 굴릴 때가 아니에요.'); + return dice ? ok : fail('이 방은 주사위 없이 바로 이동해요.'); + case 'passage': { + if (ph.kind !== 'move') return fail('비밀 통로는 차례를 시작할 때만 쓸 수 있어요.'); + if (!dice) return fail('이 방은 아무 방이나 바로 갈 수 있어요.'); + return here && PASSAGES[here] ? ok : fail('여기에는 비밀 통로가 없어요.'); + } + case 'stay': + if (ph.kind !== 'move') return fail('지금은 고를 수 없어요.'); + if (!here || !s.movedIn[actor]) return fail('다른 사람의 추리로 방에 불려 왔을 때만 그 자리에서 추리할 수 있어요.'); + return ok; + case 'go': { + if (a.room === here) return fail('방금 있던 방에는 다시 들어갈 수 없어요. 다른 방을 골라 주세요.'); + if (!dice) return ph.kind === 'move' ? ok : fail('지금은 이동할 때가 아니에요.'); + if (ph.kind !== 'moveTo') return fail(ph.kind === 'move' ? '먼저 주사위를 굴려 주세요.' : '지금은 이동할 때가 아니에요.'); + const d = distTo(pos, a.room); + return d <= diceSum(s) ? ok : fail(`${ROOM_KO[a.room]}까지 ${d}칸이라 이번에는 닿지 않아요.`); + } + case 'walk': { + if (!dice || ph.kind !== 'moveTo') return fail('지금은 복도를 걸어갈 때가 아니에요.'); + if (a.room === here) return fail('지금 있는 방이에요.'); + return distTo(pos, a.room) > diceSum(s) ? ok : fail('닿는 방이에요. 바로 들어가 주세요.'); + } + case 'suggest': + return ph.kind === 'suggest' ? ok : fail('방에 들어갔을 때만 추리할 수 있어요.'); + case 'accuse': + return ownTurnPhase(s) ? ok : fail('지금은 고발할 수 없어요.'); + case 'end': + return ph.kind === 'suggest' || ph.kind === 'afterSuggest' ? ok : fail('먼저 이동해 주세요.'); + } +} + +function applyClient(s: ClueState, actor: PlayerId, a: ClueClientAction, events: GameEvent[], rng: { int(n: number): number }, auto: boolean): void { + const me = s.suspectOf[actor]!; + switch (a.type) { + case 'roll': + s.dice = [rng.int(6) + 1, rng.int(6) + 1]; + s.phase = { kind: 'moveTo' }; + events.push({ type: 'rolled', player: actor, dice: s.dice }); + break; + case 'passage': + enter(s, actor, PASSAGES[roomAt(s.pos[me])!]!, 'passage', events); + break; + case 'stay': + enter(s, actor, roomAt(s.pos[me])!, 'stay', events); + break; + case 'go': + enter(s, actor, a.room, 'go', events); + break; + case 'walk': + s.pos[me] = walkToward(s.pos[me], a.room, diceSum(s)); + events.push({ type: 'walked', player: actor, toward: a.room }); + endTurn(s, events); + break; + case 'suggest': { + const room = (s.phase as Extract).room; + // The named suspect's token and the weapon are brought into the room (official rule). + if (moveToken(s, a.suspect, room)) { + const owner = s.seats.find((p) => s.suspectOf[p] === a.suspect); + if (owner && owner !== actor) s.movedIn[owner] = true; + } + s.weaponAt[a.weapon] = room; + s.suggestions.push({ by: actor, suspect: a.suspect, weapon: a.weapon, room, passed: [], refuter: null, shown: null, auto: false, turnNo: s.turnNo }); + events.push({ type: 'suggested', by: actor, suspect: a.suspect, weapon: a.weapon, room }); + continueRefute(s, actor, events); + break; + } + case 'show': { + const sg = s.suggestions[s.suggestions.length - 1]!; + sg.refuter = actor; + sg.shown = a.card; + sg.auto = auto; + s.phase = { kind: 'afterSuggest' }; + // Public: who showed a card to whom, never which one. + events.push({ type: 'refuted', by: actor, to: sg.by }); + break; + } + case 'accuse': { + const sol = s.solution; + const correct = a.suspect === sol.suspect && a.weapon === sol.weapon && a.room === sol.room; + s.accusations.push({ by: actor, suspect: a.suspect, weapon: a.weapon, room: a.room, correct, turnNo: s.turnNo }); + events.push({ type: 'accused', by: actor, suspect: a.suspect, weapon: a.weapon, room: a.room, correct }); + if (correct) finish(s, actor, 'normal', events); + else { + s.out[actor] = true; + endTurn(s, events); + } + break; + } + case 'end': + endTurn(s, events); + break; + } +} + +function applyLeave(s: ClueState, actor: PlayerId, events: GameEvent[]): void { + s.left[actor] = true; + events.push({ type: 'left', player: actor }); + // Their cards go face up so the case stays solvable. + for (const c of s.hands[actor] ?? []) if (!s.publicCards.includes(c)) s.publicCards.push(c); + const ph = s.phase; + if (checkFinish(s, events)) return; + if (ph.kind === 'refute' && ph.refuter === actor) { + continueRefute(s, actor, events); + return; + } + if (s.current === actor) endTurn(s, events); +} + +// ---------------------------------------------------------------- definition + +export const clue: GameDefinition = { + id: 'clue', + nameKo: '클루', + minPlayers: MIN_PLAYERS, + maxPlayers: MAX_PLAYERS, + stateVersion: 1, + defaultOptions: clueOptionsSchema.parse({}), + optionsSchema: clueOptionsSchema as unknown as z.ZodType, + actionSchema: clueActionSchema as unknown as z.ZodType, + + setup({ players, options, rng, now, gameNo }) { + if (players.length < MIN_PLAYERS || players.length > MAX_PLAYERS) throw new Error(`clue: ${players.length} players not allowed`); + const n = players.length; + // Scarlet moves first (official); the first player is drawn and the suspects follow clockwise from them. + const first = rng.int(n); + const suspectOf = per(players, (p) => SUSPECTS[(players.indexOf(p) - first + n) % n]!); + const solution = { suspect: SUSPECTS[rng.int(6)]!, weapon: WEAPONS[rng.int(6)]!, room: ROOMS[rng.int(9)]! }; + const rest = rng.shuffle(ITEMS.filter((x) => x !== solution.suspect && x !== solution.weapon && x !== solution.room).map(cardId)); + // Everyone gets the same number of cards; the leftovers lie face up for all (official rule). + const each = Math.floor(rest.length / n); + const hands = per(players, (p) => rest.slice(players.indexOf(p) * each, (players.indexOf(p) + 1) * each)); + const publicCards = rest.slice(n * each); + const roomsForWeapons = rng.shuffle([...ROOMS]); + const s: ClueState = { + options, + seats: [...players], + gameNo: gameNo ?? 1, + suspectOf, + solution, + hands, + publicCards, + pos: Object.fromEntries(SUSPECTS.map((x) => [x, { at: startOf(x) }])) as Record, + weaponAt: Object.fromEntries(WEAPONS.map((w, i) => [w, roomsForWeapons[i]!])) as Record, + current: players[first]!, + phase: { kind: 'move' }, + dice: null, + movedIn: per(players, () => false), + out: per(players, () => false), + left: per(players, () => false), + suggestions: [], + accusations: [], + turnNo: 0, + idle: per(players, () => 0), + idleTurn: per(players, () => -1), + deadlineAt: null, + seq: 0, + final: null, + }; + refreshDeadline(s, now); + return s; + }, + + validate(s, actor, a) { + if (!s.seats.includes(actor)) return fail('이 게임의 플레이어가 아니에요.'); + if (s.phase.kind === 'finished') return fail('게임이 이미 끝났어요.'); + if (a.type === 'leave') return s.left[actor] ? fail('이미 나간 플레이어예요.') : ok; + if (s.left[actor]) return fail('이미 나간 플레이어예요.'); + if (a.type === 'timeout') return activeOf(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.'); + return validateClient(s, actor, a); + }, + + apply(prev, actor, a, { rng, now }) { + const s = structuredClone(prev); + const events: GameEvent[] = []; + if (a.type === 'leave') applyLeave(s, actor, events); + else if (a.type === 'timeout') { + events.push({ type: 'timeout', player: actor }); + if (s.phase.kind !== 'refute' && s.idleTurn[actor] !== s.turnNo) { + s.idleTurn[actor] = s.turnNo; + s.idle[actor] = (s.idle[actor] ?? 0) + 1; + } + // One timeout plays out the rest of the step: on the player's own turn, the whole turn (move, no suggestion). + const turn = s.turnNo; + do { + const concrete = autoAction(s, actor); + const v = validateClient(s, actor, concrete); + if (!v.ok) throw new Error(`clue: auto action rejected: ${v.reason}`); + applyClient(s, actor, concrete, events, rng, true); + } while (s.turnNo === turn && s.current === actor && ownTurnPhase(s)); + } else { + s.idle[actor] = 0; + applyClient(s, actor, a, events, rng, false); + } + s.seq += 1; + refreshDeadline(s, now); + return { state: s, events }; + }, + + view(s, viewer) { + const me = viewer && s.seats.includes(viewer) ? viewer : null; + const over = s.phase.kind === 'finished'; + const ph = s.phase; + let phase: PhaseView; + if (ph.kind === 'refute') { + phase = { kind: 'refute', refuter: ph.refuter }; + if (me === ph.refuter) phase.canShow = matchingCards(s, me, s.suggestions[s.suggestions.length - 1]!); + } else phase = { ...ph }; + const mover = s.pos[s.suspectOf[s.current]!]; + const distances = + s.options.movement === 'dice' && (ph.kind === 'move' || ph.kind === 'moveTo') + ? (Object.fromEntries(ROOMS.map((r) => [r, distTo(mover, r)])) as Record) + : null; + return { + options: s.options, + me, + seats: s.seats, + gameNo: s.gameNo, + suspectOf: s.suspectOf, + current: s.current, + phase, + dice: s.dice, + pos: s.pos, + weaponAt: s.weaponAt, + distances, + myHand: me ? [...s.hands[me]!] : null, + handCounts: per(s.seats, (p) => s.hands[p]!.length), + publicCards: [...s.publicCards], + movedIn: s.movedIn, + out: s.out, + left: s.left, + suggestions: s.suggestions.map(({ shown, ...rest }) => (shown && (over || me === rest.by || me === rest.refuter) ? { ...rest, shown } : rest)), + accusations: s.accusations, + turnNo: s.turnNo, + idle: s.idle, + deadlineAt: s.deadlineAt, + solution: over ? s.solution : null, + hands: over ? s.hands : null, + final: s.final, + }; + }, + + activePlayers: activeOf, + + deadline(s) { + return s.phase.kind === 'finished' ? null : s.deadlineAt; + }, + + onTimeout() { + return { type: 'timeout' }; + }, + + onLeave(s, player) { + if (!s.seats.includes(player) || s.left[player] || s.phase.kind === 'finished') return null; + return { type: 'leave' }; + }, + + result(s): GameResult | null { + if (!s.final) return null; + return { ranking: s.final.ranking, summary: s.final.summary, reason: s.final.reason }; + }, + + legalActions(s, p) { + if (!activeOf(s).includes(p)) return []; + const ph = s.phase; + if (ph.kind === 'refute') return matchingCards(s, p, s.suggestions[s.suggestions.length - 1]!).map((card) => ({ type: 'show', card })); + const all: ClueAction[] = []; + const pos = s.pos[s.suspectOf[p]!]; + const here = roomAt(pos); + if (ph.kind === 'move') { + if (s.options.movement === 'dice') all.push({ type: 'roll' }); + else for (const room of ROOMS) if (room !== here) all.push({ type: 'go', room }); + if (s.options.movement === 'dice' && here && PASSAGES[here]) all.push({ type: 'passage' }); + if (here && s.movedIn[p]) all.push({ type: 'stay' }); + } else if (ph.kind === 'moveTo') { + for (const room of ROOMS) if (room !== here) all.push(distTo(pos, room) <= diceSum(s) ? { type: 'go', room } : { type: 'walk', room }); + } else if (ph.kind === 'suggest') { + for (const suspect of SUSPECTS) for (const weapon of WEAPONS) all.push({ type: 'suggest', suspect, weapon }); + all.push({ type: 'end' }); + } else if (ph.kind === 'afterSuggest') all.push({ type: 'end' }); + for (const suspect of SUSPECTS) for (const weapon of WEAPONS) for (const room of ROOMS) all.push({ type: 'accuse', suspect, weapon, room }); + return all; + }, + + /** Card ids nobody else may see yet: `player`'s cards never shown to anyone, and the case file. */ + secretsOf(s, player) { + if (s.phase.kind === 'finished') return []; + const shown = new Set(s.suggestions.map((x) => x.shown).filter(Boolean)); + const own = s.left[player] ? [] : (s.hands[player] ?? []).filter((c) => !shown.has(c)); + return [...own, cardId(s.solution.suspect), cardId(s.solution.weapon), cardId(s.solution.room)]; + }, +}; + +function activeOf(s: ClueState): PlayerId[] { + if (s.phase.kind === 'finished') return []; + if (s.phase.kind === 'refute') return [s.phase.refuter]; + return [s.current]; +} diff --git a/packages/games/src/clue/types.ts b/packages/games/src/clue/types.ts new file mode 100644 index 0000000..43f4f21 --- /dev/null +++ b/packages/games/src/clue/types.ts @@ -0,0 +1,169 @@ +/** 클루 options, actions, state and view types (docs/games/clue.md §2, §8); cards and the map live in board.ts. */ +import { z } from 'zod'; +import type { PlayerId } from '@bg/engine'; +import { ROOMS, SUSPECTS, WEAPONS, type Pos, type Room, type Suspect, type Weapon } from './board'; + +export * from './board'; + +// ---------------------------------------------------------------- options + +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({ + movement: z + .enum(['dice', 'free']) + .default('dice') + .meta({ title: '이동 방식', labels: { dice: '주사위 2개로 복도 이동(원작처럼)', free: '빠르게(아무 방이나 바로 이동)' } }), + turnSeconds: lit(30, 45, 60, 90) + .default(60) + .meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초' } }), +}); +export type ClueOptions = z.infer; + +// ---------------------------------------------------------------- actions + +const suspectSchema = z.enum(SUSPECTS); +const weaponSchema = z.enum(WEAPONS); +const roomSchema = z.enum(ROOMS); +export const clueActionSchema = z.discriminatedUnion('type', [ + z.object({ type: z.literal('roll') }), + z.object({ type: z.literal('passage') }), + z.object({ type: z.literal('stay') }), + z.object({ type: z.literal('go'), room: roomSchema }), + z.object({ type: z.literal('walk'), room: roomSchema }), + z.object({ type: z.literal('suggest'), suspect: suspectSchema, weapon: weaponSchema }), + z.object({ type: z.literal('show'), card: z.string().max(32) }), + z.object({ type: z.literal('accuse'), suspect: suspectSchema, weapon: weaponSchema, room: roomSchema }), + z.object({ type: z.literal('end') }), +]); +export type ClueClientAction = z.infer; +/** Client actions plus system-only actions (timer / leaving), which are not in the schema. */ +export type ClueAction = ClueClientAction | { type: 'timeout' } | { type: 'leave' }; + +// ---------------------------------------------------------------- state + +export type CluePhase = + /** Start of the turn: roll (or go anywhere in the quick mode), take a secret passage, stay after being moved in, or accuse. */ + | { kind: 'move' } + /** Dice rolled: enter a room within reach or walk towards one. */ + | { kind: 'moveTo' } + /** In a room: suggest a suspect + weapon there (or skip), or accuse. */ + | { kind: 'suggest'; room: Room } + /** `refuter` must show the suggester one of the matching cards. */ + | { kind: 'refute'; refuter: PlayerId } + /** Suggestion answered: accuse or end the turn. */ + | { kind: 'afterSuggest' } + | { kind: 'finished' }; +export type PhaseKind = CluePhase['kind']; + +export interface Suggestion { + by: PlayerId; + suspect: Suspect; + weapon: Weapon; + room: Room; + /** Players asked in turn who had none of the three cards. */ + passed: PlayerId[]; + refuter: PlayerId | null; + /** The card shown (secret: only `by` and `refuter` see it). */ + shown: string | null; + /** The card was picked by the timer. */ + auto: boolean; + turnNo: number; +} + +export interface Accusation { + by: PlayerId; + suspect: Suspect; + weapon: Weapon; + room: Room; + correct: boolean; + turnNo: number; +} + +export interface ClueFinal { + winner: PlayerId | null; + ranking: PlayerId[][]; + summary: string; + reason: 'normal' | 'resign' | 'timeout'; +} + +export interface ClueState { + options: ClueOptions; + seats: PlayerId[]; + gameNo: number; + /** The suspect each player plays (their token on the map). */ + suspectOf: Record; + /** The case file (사건 봉투): item names. Secret until the end. */ + solution: { suspect: Suspect; weapon: Weapon; room: Room }; + /** Card ids per player. */ + hands: Record; + /** Face-up cards: the deal's leftovers, plus the hands of players who left. */ + publicCards: string[]; + pos: Record; + weaponAt: Record; + current: PlayerId; + phase: CluePhase; + dice: [number, number] | null; + /** Token moved into a room by someone's suggestion since the player's last turn (may suggest there without moving). */ + movedIn: Record; + /** Made a wrong accusation: no more turns, but still shows cards. */ + out: Record; + left: Record; + suggestions: Suggestion[]; + accusations: Accusation[]; + turnNo: number; + /** Consecutive own turns ended by the timer; at 3 the clock drops to 10 s. */ + idle: Record; + idleTurn: Record; + deadlineAt: number | null; + seq: number; + final: ClueFinal | null; +} + +// ---------------------------------------------------------------- view + +export interface SuggestionView extends Omit { + /** Present only for the suggester and the refuter. */ + shown?: string; +} + +export type PhaseView = + | { kind: 'move' } + | { kind: 'moveTo' } + | { kind: 'suggest'; room: Room } + /** `canShow`: the refuter's matching cards (only in the refuter's own view). */ + | { kind: 'refute'; refuter: PlayerId; canShow?: string[] } + | { kind: 'afterSuggest' } + | { kind: 'finished' }; + +export interface ClueView { + options: ClueOptions; + me: PlayerId | null; + seats: PlayerId[]; + gameNo: number; + suspectOf: Record; + current: PlayerId; + phase: PhaseView; + dice: [number, number] | null; + pos: Record; + weaponAt: Record; + /** Dice mode, the mover's move steps: corridor steps from the current player's token to every room. */ + distances: Record | null; + /** My cards (card ids); null for spectators. */ + myHand: string[] | null; + handCounts: Record; + publicCards: string[]; + movedIn: Record; + out: Record; + left: Record; + suggestions: SuggestionView[]; + accusations: Accusation[]; + turnNo: number; + idle: Record; + deadlineAt: number | null; + /** After the game: the case file and every hand. */ + solution: ClueState['solution'] | null; + hands: Record | null; + final: ClueFinal | null; +} diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index 4ff6841..d66adcf 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -26,6 +26,7 @@ import { dobble } from './dobble'; import { catchmind } from './catchmind'; import { mafia } from './mafia'; import { apple } from './apple'; +import { clue } from './clue'; export const GAMES: Record = { [omok.id]: omok, @@ -55,4 +56,5 @@ export const GAMES: Record = { [catchmind.id]: catchmind, [mafia.id]: mafia, [apple.id]: apple, + [clue.id]: clue, }; diff --git a/packages/games/src/result-score.test.ts b/packages/games/src/result-score.test.ts index 6b44519..f7fb5ea 100644 --- a/packages/games/src/result-score.test.ts +++ b/packages/games/src/result-score.test.ts @@ -4,7 +4,7 @@ import { randomPlayout, seedN } from '@bg/engine'; import { GAMES } from './index'; /** Games without a score (win/lose only, or survival) leave `scoreText` out. */ -const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker']); +const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker', 'clue']); /** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). */ const SCORED_OPTIONS: Record = { 'one-card': { mode: 'uno-style' } }; diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index 0624f40..466dff4 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -51,6 +51,7 @@ export const BOT_GAMES: readonly string[] = [ 'ninety-nine', 'mafia', 'apple', + 'clue', ]; /** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */ diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index fb90d8e..01d0a6e 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -38,6 +38,7 @@ export const CATALOG: CatalogEntry[] = [ { id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true }, { id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true }, { id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true }, + { id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true }, ]; export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);