From cf7523f862bdff3fcd9f12e802a193d9174dda0f Mon Sep 17 00:00:00 2001 From: EJClaw Date: Mon, 12 Oct 2026 22:24:26 +0900 Subject: [PATCH] =?UTF-8?q?=EB=8F=84=EB=91=91=EC=9E=A1=EA=B8=B0(old-maid):?= =?UTF-8?q?=20=EA=B7=9C=EC=B9=99=C2=B7=ED=99=94=EB=A9=B4=C2=B7=EC=BB=B4?= =?UTF-8?q?=ED=93=A8=ED=84=B0=20=EC=83=81=EB=8C=80=C2=B7=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=C2=B7=EB=AC=B8=EC=84=9C=C2=B7E2E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 규칙 모듈 packages/games/src/old-maid: 2~8명, 트럼프 52장 + 조커 1장을 첫 사람(무작위)부터 한 장씩 나누고 같은 숫자 짝은 자동으로 버림. 차례에는 다음 자리(왼쪽)의 카드 있는 사람 손패에서 자리(index)로 한 장 뽑기(from 함께 보내 대상이 바뀌면 거절), 짝이 없으면 내 손패 무작위 자리에 숨김. 다 턴 순서대로 순위, 마지막 조커를 든 사람이 도둑(꼴찌). 결과 scoreText 에 "🃏 도둑"/"다 털었어요"/"나감" 표시. - 내 손패 섞기: 남은 사람 누구나 언제든, 차례마다 3번까지, 시계는 그대로. 남에게 보이는 자리는 실제 손패 순서이고, view 에는 남의 손패 장수만(뽑은 카드는 뽑은 사람에게만). - 시간 초과는 무작위 한 장 뽑기(3번 연속이면 5초), 카드를 든 채 나가면 그 카드를 섞어 다음 자리부터 한 장씩 나눠 주고 짝을 버림, 나간 사람은 맨 아래. 둘만 남았을 때 나가면 도둑 없이 끝. - 컴퓨터 상대(BOT_GAMES): 단계와 관계없이 무작위로 뽑고 가끔(15%) 자기 손패를 먼저 섞음. - 화면 apps/web/src/games/old-maid: 뽑힐 사람의 뒷면 카드를 펼쳐 고르기(tapConfirm 이면 두 번 눌러 확인, PC 한 번, 키보드 방향키+Enter), 섞으면 흔들림, 지난 뽑기·버린 짝, 내 손패(조커 표시)와 [🔀 섞기], 조커를 넘기면 알림. 30초 요약, 지금 할 수 있는 것, 규칙. - 등록(GAMES, 카탈로그, BOT_GAMES·전략, 화면 레지스트리, 아이콘·카드 탭), 도움말 테스트 게임 수 27, 문서 docs/games/old-maid.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지). Co-Authored-By: Claude Opus 5.5 --- apps/web/src/games/old-maid/help.test.ts | 48 ++ apps/web/src/games/old-maid/help.ts | 42 ++ apps/web/src/games/old-maid/index.tsx | 653 +++++++++++++++++++ apps/web/src/games/old-maid/quick.tsx | 51 ++ apps/web/src/games/registry.ts | 1 + apps/web/src/lib/catalog-ui.ts | 4 + docs/games/README.md | 1 + docs/games/old-maid.md | 116 ++++ e2e/games.e2e.ts | 101 +++ packages/games/src/bots/index.ts | 2 + packages/games/src/index.ts | 2 + packages/games/src/old-maid/bot.test.ts | 46 ++ packages/games/src/old-maid/bot.ts | 18 + packages/games/src/old-maid/index.ts | 398 +++++++++++ packages/games/src/old-maid/old-maid.test.ts | 432 ++++++++++++ packages/games/src/old-maid/types.ts | 128 ++++ packages/shared/src/bots.ts | 1 + packages/shared/src/catalog.ts | 1 + 18 files changed, 2045 insertions(+) create mode 100644 apps/web/src/games/old-maid/help.test.ts create mode 100644 apps/web/src/games/old-maid/help.ts create mode 100644 apps/web/src/games/old-maid/index.tsx create mode 100644 apps/web/src/games/old-maid/quick.tsx create mode 100644 docs/games/old-maid.md create mode 100644 packages/games/src/old-maid/bot.test.ts create mode 100644 packages/games/src/old-maid/bot.ts create mode 100644 packages/games/src/old-maid/index.ts create mode 100644 packages/games/src/old-maid/old-maid.test.ts create mode 100644 packages/games/src/old-maid/types.ts diff --git a/apps/web/src/games/old-maid/help.test.ts b/apps/web/src/games/old-maid/help.test.ts new file mode 100644 index 0000000..922efe8 --- /dev/null +++ b/apps/web/src/games/old-maid/help.test.ts @@ -0,0 +1,48 @@ +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['old-maid']!.view(s, who) as any; +const nickOf = (id: string) => users[id]!.nickname; + +/** Rigged 3-player game: A draws from B, B from C, C from A. Unlisted cards count as thrown away. */ +function rigged(hands: Record, turn = 'A') { + const { state } = setupGame('old-maid', 3); + for (const p of ids) { + state.hands[p] = hands[p]; + state.discards[p] = []; + } + state.out = []; + state.turn = turn; + return state; +} + +test('도둑잡기: 내 차례 / 뽑히는 사람 / 기다림 / 관전', () => { + const s = rigged({ A: ['2H', '3H'], B: ['2S', 'X1'], C: ['3S', '4H', '4S'] }); + const a = helpNow(view(s, 'A'), 'A', users); + expect(a).toContain(`내 차례예요. ${nickOf('B')}님의 뒷면 카드 2장`); + expect(a).toContain('도둑'); + const b = helpNow(view(s, 'B'), 'B', users); + expect(b).toContain(`${nickOf('A')}님이 내 카드를 고르는 중`); + expect(b).toContain('조커가 내 손에 있어요! [🔀 섞기]'); + expect(helpNow(view(s, 'C'), 'C', users)).toContain('기다려 주세요'); + expect(helpNow(view(s, null), null, users)).toContain(`${nickOf('A')}님이 ${nickOf('B')}님의 카드를 고르는 중`); +}); + +test('도둑잡기: 다 털고 구경, 게임 끝(도둑)', () => { + let s = rigged({ A: ['2H', '3H'], B: ['2S', 'X1'], C: ['3S'] }); + s = applyAction('old-maid', s, 'A', { type: 'draw', from: 'B', index: 0 }); // 2H·2S 짝 → A [3H], B [X1] + s = applyAction('old-maid', s, 'B', { type: 'draw', from: 'C', index: 0 }); // B [X1, 3S], C 다 털어서 1등 + expect(helpNow(view(s, 'C'), 'C', users)).toContain('1등이에요'); + expect(s.turn).toBe('A'); + s = applyAction('old-maid', s, 'A', { type: 'draw', from: 'B', index: s.hands.B.indexOf('3S') }); // A 2등, B 도둑 + expect(s.final.thief).toBe('B'); + expect(helpNow(view(s, 'B'), 'B', users)).toContain('내가 조커를 끝까지 들고 있어서 도둑'); + const a = helpNow(view(s, 'A'), 'A', users); + expect(a).toContain(`${nickOf('B')}님이 조커를 끝까지`); + expect(a).toContain('나는 2등으로'); + expect(helpNow(view(s, null), null, users)).toContain('게임이 끝났어요'); +}); diff --git a/apps/web/src/games/old-maid/help.ts b/apps/web/src/games/old-maid/help.ts new file mode 100644 index 0000000..5d3e656 --- /dev/null +++ b/apps/web/src/games/old-maid/help.ts @@ -0,0 +1,42 @@ +/** 도둑잡기 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { OldMaidView } from '@bg/games/old-maid'; +import type { PublicUser } from '@bg/shared/lite'; + +const JOKER = 'X1'; + +export function helpNow(v: OldMaidView, me: string | null, players: Record): string { + const mine = me && v.order.includes(me) ? me : null; + const name = (id: string) => `${players[id]?.nickname ?? '다른 사람'}님`; + const goal = '같은 숫자 두 장은 저절로 짝으로 버려져요. 손패를 먼저 다 털면 이기고, 마지막에 조커를 든 사람이 도둑(꼴찌)이에요.'; + + if (v.phase === 'finished') { + const f = v.final; + if (!f) return '게임이 끝났어요.'; + const thief = f.thief ? (f.thief === mine ? '내가 조커를 끝까지 들고 있어서 도둑이 됐어요.' : `${name(f.thief)}이 조커를 끝까지 들고 있어서 도둑이에요.`) : '한 사람이 나가서 도둑 없이 끝났어요.'; + const place = mine && v.places[mine] ? `나는 ${v.places[mine]}등으로 손패를 다 털었어요!` : null; + return ['게임이 끝났어요.', thief, place].filter(Boolean).join('\n'); + } + + const lines: string[] = []; + const turn = v.turn!; + const target = v.target; + const hand = mine ? (v.myHand ?? []) : []; + if (mine && v.status[mine] === 'out') { + lines.push(`나는 손패를 다 털어서 ${v.places[mine]}등이에요! 끝날 때까지 구경해요.`); + lines.push(`지금은 ${name(turn)}이 ${target ? `${name(target)}의` : ''} 카드를 고르는 중이에요.`); + return lines.join('\n'); + } + if (mine && v.status[mine] === 'left') return '게임을 나가서 구경만 할 수 있어요.'; + if (turn === mine && target) { + lines.push(`내 차례예요. ${name(target)}의 뒷면 카드 ${v.handCounts[target]}장 중 한 장을 골라 뽑아요.`); + lines.push('카드를 누르면 골라지고, 한 번 더 누르면 뽑아요(PC는 한 번 누르면 바로 뽑아요). 짝이 생기면 저절로 버려져요.'); + } else if (target === mine) { + lines.push(`${name(turn)}이 내 카드를 고르는 중이에요.`); + lines.push(hand.includes(JOKER) ? '조커가 내 손에 있어요! [🔀 섞기]로 순서를 바꿔 조커를 숨겨 보세요.' : '[🔀 섞기]로 내 손패 순서를 바꿀 수 있어요.'); + } else { + lines.push(`${name(turn)}이 ${target ? `${name(target)}의 카드를` : '카드를'} 고르는 중이에요.${mine ? ' 기다려 주세요.' : ''}`); + if (mine && hand.includes(JOKER)) lines.push('조커가 내 손에 있어요. 내 카드를 뽑을 사람이 가져가길 기다려요.'); + } + lines.push(goal); + return lines.join('\n'); +} diff --git a/apps/web/src/games/old-maid/index.tsx b/apps/web/src/games/old-maid/index.tsx new file mode 100644 index 0000000..681ecfc --- /dev/null +++ b/apps/web/src/games/old-maid/index.tsx @@ -0,0 +1,653 @@ +/** 도둑잡기 화면 (docs/games/old-maid.md §9). Cards are the shared trump card SVGs. */ +import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; +import type { LogEntry, OldMaidOptions, OldMaidView } from '@bg/games/old-maid'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar } from '../../components/ui'; +import { TurnTimer } from '../../components/TurnTimer'; +import { PlayingCard, cardAria } from '../../components/cards/PlayingCard'; +import { haptic, sounds } from '../../lib/feedback'; +import { toast } from '../../store/toast'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod. +const JOKER = 'X1'; +const SHUFFLES_PER_TURN = 3; + +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 who = (players: Record, id: string, me: string | null) => (id === me ? '나' : `${nick(players, id)}님`); + +/** "♥7", "조커". */ +function cardName(c: string): string { + if (c.startsWith('X')) return '조커'; + const r = c[0]!; + return `${{ S: '♠', H: '♥', D: '◆', C: '♣' }[c[1]!] ?? ''}${r === 'T' ? '10' : r}`; +} + +function logText(e: LogEntry, players: Record, me: string | null): string { + switch (e.t) { + case 'draw': { + const base = `${who(players, e.drawer, me)}${e.drawer === me ? '는' : '이'} ${who(players, e.from, me)}의 ${e.index + 1}번째 카드를 뽑았어요`; + const pair = e.pair ? ` → ${cardName(e.pair[0])}·${cardName(e.pair[1])} 짝을 버렸어요` : ''; + return `${base}${pair}${e.auto ? ' (시간 초과)' : ''}`; + } + case 'out': + return `${who(players, e.player, me)}${e.player === me ? '는' : '이'} 손패를 다 털었어요! ${e.place}등`; + case 'shuffle': + return `${who(players, e.player, me)}${e.player === me ? '는' : '이'} 손패를 섞었어요`; + case 'left': + return `${nick(players, e.player)}님이 나가서 카드를 ${e.gave.map((g) => `${who(players, g.to, me)}에게 ${g.count}장`).join(', ') || '아무에게도 안'} 나눠 줬어요${e.pairs.length ? ` (짝 ${e.pairs.length}쌍 버림)` : ''}`; + } +} + +// ---------------------------------------------------------------- styles + +const CSS = ` +.om-board { width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; } +.om-seats { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 10px; } +.om-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 8px 10px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 5px; min-width: 0; } +.om-seat.turn { border-color: var(--focus); } +.om-seat.target { border-color: var(--primary); border-style: dashed; } +.om-seat.done { opacity: .72; } +.om-seat.thief { border-color: var(--danger); opacity: 1; } +.om-head { display: flex; align-items: center; gap: 7px; min-height: 30px; min-width: 0; } +.om-name { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; } +.om-badges { display: flex; gap: 4px; flex-wrap: wrap; min-height: 22px; } +.om-badge { display: inline-block; border-radius: 999px; padding: 1px 8px; font-weight: 800; font-size: .78rem; background: var(--surface-2); color: var(--text); white-space: nowrap; } +.om-badge.turn { background: var(--focus); color: #1c1e21; } +.om-badge.target { background: var(--primary-soft); color: var(--text); } +.om-badge.win { background: var(--success-soft); color: var(--success); } +.om-badge.lose { background: var(--danger-soft); color: var(--danger); } +.om-meta { font-size: .85rem; color: var(--text-sub); display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.om-mini { display: inline-flex; align-items: center; } +.om-mini i { width: 12px; height: 17px; border-radius: 3px; background: #1e3a8a; border: 1.5px solid #fff; box-shadow: 0 0 0 1px #1e3a8a; margin-left: -6px; display: inline-block; } +.om-mini i:first-child { margin-left: 0; } +.om-bubble { position: absolute; right: 8px; top: -12px; background: var(--text); color: var(--surface); border-radius: 12px; padding: 2px 10px; font-weight: 800; font-size: .8rem; box-shadow: var(--shadow); animation: om-pop .25s ease-out; z-index: 2; } +.om-table { background: var(--felt); color: #fff; border-radius: var(--radius-lg); padding: 12px; display: flex; flex-direction: column; gap: 10px; align-items: center; min-height: 200px; } +.om-table .small { color: #fff; opacity: .92; } +.om-title { font-weight: 900; font-size: 1.05rem; text-align: center; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: center; } +.om-title .arrow { opacity: .85; } +.om-fan { --cw: 60px; display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; padding: 14px 4px 4px; max-width: 760px; } +.om-fan.many { --cw: 50px; gap: 5px; } +.om-fan.shake { animation: om-shake .5s ease-in-out; } +.om-back { position: relative; flex: none; width: var(--cw); height: calc(var(--cw) * 1.4); padding: 0; border: 0; background: none; border-radius: 9px; cursor: default; transition: transform .12s ease; } +button.om-back { cursor: pointer; } +button.om-back:hover:not(:disabled) { transform: translateY(-5px); } +.om-back[aria-pressed='true'] { transform: translateY(-12px); box-shadow: 0 0 0 4px #fde047; z-index: 2; } +.om-back:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; z-index: 3; } +.om-back:disabled { cursor: default; } +.om-back .om-no { position: absolute; left: 50%; bottom: 4px; transform: translateX(-50%); background: rgba(0,0,0,.55); color: #fff; font-size: .7rem; font-weight: 800; border-radius: 6px; padding: 0 4px; pointer-events: none; } +.om-face { display: block; width: 100%; height: 100%; } +.om-face svg, .om-face > span { width: 100% !important; height: 100% !important; display: block; } +.om-last { display: flex; align-items: center; gap: 10px; background: rgba(0,0,0,.22); border-radius: 12px; padding: 8px 10px; width: 100%; flex-wrap: wrap; justify-content: center; } +.om-last .cards { display: flex; gap: 4px; } +.om-last .cards .om-card { --cw: 40px; } +.om-card { position: relative; flex: none; width: var(--cw); height: calc(var(--cw) * 1.4); display: inline-block; } +.om-pile { display: flex; flex-wrap: wrap; gap: 4px 10px; justify-content: center; align-items: center; font-size: .85rem; } +.om-pile .pair { display: inline-flex; gap: 2px; } +.om-pile .om-card { --cw: 28px; } +.om-me { position: relative; background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; border: 3px solid var(--primary); display: flex; flex-direction: column; gap: 8px; } +.om-me.turn { border-color: var(--focus); } +.om-me.target { border-style: dashed; } +.om-me .om-bubble { right: auto; left: 16px; top: -14px; } +.om-hand { --cw: 64px; display: flex; flex-wrap: wrap; gap: 6px; } +.om-hand.many { --cw: 52px; } +.om-hand .om-card.joker { box-shadow: 0 0 0 3px var(--danger); border-radius: 9px; } +.om-hand .om-card.fresh { animation: om-pop .45s ease-out; box-shadow: 0 0 0 3px #f59e0b; border-radius: 9px; } +.om-mine { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: space-between; } +.om-shuffle { min-height: 44px; } +.om-note { font-size: .85rem; color: var(--text-sub); } +.om-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; font-size: .88rem; } +@keyframes om-pop { 0% { transform: scale(.6); opacity: 0; } 100% { transform: none; opacity: 1; } } +@keyframes om-shake { 0%, 100% { transform: none; } 20% { transform: translateX(-8px) rotate(-1deg); } 40% { transform: translateX(8px) rotate(1deg); } 60% { transform: translateX(-6px); } 80% { transform: translateX(6px); } } +@media (max-width: 719px) { + .om-board { max-height: none; overflow: visible; } + .om-seats { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } + .om-seat { padding: 6px 8px; } + .om-fan { --cw: 46px; gap: 5px; } + .om-fan.many { --cw: 44px; gap: 4px; } + .om-hand { --cw: 50px; gap: 5px; } + .om-hand.many { --cw: 44px; gap: 4px; } + .om-table { min-height: 0; padding: 10px 8px; } +} +@media (prefers-reduced-motion: reduce) { + .om-fan.shake, .om-bubble, .om-hand .om-card.fresh { animation: none; } + .om-back, .om-back[aria-pressed='true'] { transition: none; } +} +`; + +// ---------------------------------------------------------------- pieces + +function Card({ card, className }: { card: string | null; className?: string }) { + return ( + + + + + + ); +} + +function MiniBacks({ n }: { n: number }) { + return ( + + {Array.from({ length: Math.min(n, 8) }, (_, i) => ( + + ))} + + ); +} + +function seatLabel(v: OldMaidView, id: string, me: string | null, players: Record): string { + const st = v.status[id]; + const parts = [`${nick(players, id)}님${id === me ? '(나)' : ''}`]; + if (st === 'out') parts.push(`다 털었어요, ${v.places[id]}등`); + else if (st === 'left') parts.push('나갔어요'); + else parts.push(`카드 ${v.handCounts[id]}장`); + parts.push(`버린 짝 ${v.pairCounts[id]}쌍`); + if (v.turn === id) parts.push('뽑는 차례'); + if (v.target === id) parts.push('카드를 뽑히는 중'); + if (v.final?.thief === id) parts.push('도둑'); + if (v.away[id]) parts.push('자리 비움'); + return parts.join(', '); +} + +function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaidView; me: string | null; players: Record; deadline: number | null; bubble: string | null }) { + const u = userOf(players, id); + const st = v.status[id]; + const thief = v.final?.thief === id; + const cls = ['om-seat', v.turn === id ? 'turn' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' '); + return ( +
+ {bubble && ( + + {bubble} + + )} +
+ + {u.nickname} + {v.turn === id && } +
+
+ {v.turn === id && 뽑는 중} + {v.target === id && {v.turn === me ? '여기서 뽑아요' : '뽑히는 중'}} + {st === 'out' && 🎉 {v.places[id]}등} + {st === 'left' && 나감} + {thief && 🃏 도둑} + {v.away[id] && 자리 비움} +
+
+ {st === 'playing' || thief ? ( + <> + + {v.handCounts[id]}장 + + ) : ( + {st === 'out' ? '다 털었어요' : '나갔어요'} + )} + · 짝 {v.pairCounts[id]} +
+
+ ); +} + +/** The face-down hand of the player being drawn from. Interactive only for the drawer. */ +function Fan({ v, me, players, act, pending, tapConfirm, shake }: { v: OldMaidView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; shake: boolean }) { + const target = v.target!; + const mine = !!v.my?.canDraw && v.my.from === target; + const count = mine ? v.my!.count : (v.handCounts[target] ?? 0); + const [sel, setSel] = useState(null); + // A new turn, or the owner shuffled / the fan changed: start over. + useEffect(() => setSel(null), [v.turnNo, target, count, v.shuffles[target]]); + const draw = (index: number) => { + if (pending) return; + act({ type: 'draw', from: target, index }); + setSel(null); + }; + const tap = (i: number) => { + if (!mine) return; + if (sel === i || !tapConfirm) draw(i); + else setSel(i); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + setSel(null); + return; + } + if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; + const btns = Array.from(e.currentTarget.querySelectorAll('button.om-back')); + const i = btns.indexOf(document.activeElement as HTMLButtonElement); + if (i < 0) return; + e.preventDefault(); + btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus(); + }; + const owner = who(players, target, me); + return ( +
12 ? ' many' : ''}${shake ? ' shake' : ''}`} + role="group" + aria-label={mine ? `${owner}의 뒤집힌 카드 ${count}장. 좌우 방향키로 고르고 Enter로 뽑아요` : `${owner}의 뒤집힌 카드 ${count}장`} + onKeyDown={onKey} + > + {Array.from({ length: count }, (_, i) => + mine ? ( + + ) : ( + + + + + + ), + )} +
+ ); +} + +function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; players: Record }) { + const d = v.lastDraw; + if (!d) return null; + const mineDraw = d.drawer === me; + const text = `${who(players, d.drawer, me)}${mineDraw ? '는' : '이'} ${who(players, d.from, me)}의 ${d.index + 1}번째 카드를 뽑았어요${d.auto ? '(시간 초과)' : ''}`; + let tail: string; + if (d.pair) tail = `${cardName(d.pair[0])}·${cardName(d.pair[1])} 짝을 버렸어요`; + else if (mineDraw && d.card) tail = d.card === JOKER ? '앗, 조커를 뽑았어요!' : `뽑은 카드 ${cardName(d.card)} · 짝이 없어서 손에 넣었어요`; + else tail = '짝이 없어서 손에 넣었어요'; + return ( +
+ {(d.pair || (mineDraw && d.card)) && ( + + {d.pair ? d.pair.map((c) => ) : } + + )} + + {text} +
+ {tail} +
+
+ ); +} + +function Pile({ v }: { v: OldMaidView }) { + const pairs = v.log.flatMap((e) => (e.t === 'draw' && e.pair ? [e.pair] : e.t === 'left' ? e.pairs : [])).slice(-6); + const total = Object.values(v.pairCounts).reduce((a, b) => a + b, 0); + return ( +
`${cardName(p[0])}·${cardName(p[1])}`).join(', ')}` : ''}`} role="group"> + 버린 짝 {total}쌍 / 26쌍 + {pairs.map((p, i) => ( + + + + + ))} +
+ ); +} + +function Table(props: { v: OldMaidView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; shake: boolean }) { + const { v, me, players } = props; + if (v.phase === 'finished') { + const f = v.final!; + return ( +
+ 게임이 끝났어요 + {f.thief ? ( + <> + + 🃏 도둑: {who(players, f.thief, me)} + + ) : ( + 한 사람이 나가서 도둑 없이 끝났어요. + )} + + {f.summary} + + +
+ ); + } + const drawer = v.turn!; + const target = v.target; + return ( +
+
+ {who(players, drawer, me)} + + ← + + {target ? `${who(players, target, me)}의 카드 ${v.handCounts[target]}장` : ''} +
+ {target && } + {v.my?.canDraw ? ( + + {props.tapConfirm ? '뽑을 카드를 눌러 고르고, 한 번 더 누르면 뽑아요.' : '뽑을 카드를 누르면 바로 뽑아요.'} 숫자는 왼쪽부터의 자리예요. + + ) : ( + + {target === me ? `${who(players, drawer, me)}이 내 카드를 고르는 중이에요. 아래 [🔀 섞기]로 순서를 바꿀 수 있어요.` : `${who(players, drawer, me)}이 고르는 중이에요.`} + + )} + + +
+ ); +} + +function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; me: string; players: Record; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) { + const hand = v.myHand ?? []; + const st = v.status[me]; + const cls = ['om-me', v.turn === me ? 'turn' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' '); + return ( +
+ {bubble && ( + + {bubble} + + )} +
+ + {nick(players, me)} (나) + {v.away[me] && 자리 비움} + {st === 'out' && 🎉 {v.places[me]}등} + {v.final?.thief === me && 🃏 도둑} + {v.turn === me && } +
+
+ + 내 손패 {hand.length}장 · 버린 짝 {v.pairCounts[me]}쌍 + + {v.phase === 'playing' && st === 'playing' && ( + + )} +
+ {hand.length > 0 ? ( +
12 ? ' many' : ''}`} role="list" aria-label={`내 손패, 왼쪽부터: ${hand.map(cardAria).join(', ')}`}> + {hand.map((c) => ( + + + + ))} +
+ ) : ( + {st === 'out' ? '손패를 다 털었어요! 끝날 때까지 구경해요.' : '손에 카드가 없어요.'} + )} + {st === 'playing' && v.phase === 'playing' && ( + 다른 사람에게는 이 순서 그대로 뒷면으로 보여요. 조커를 어디에 둘지 섞어서 숨겨 보세요. + )} +
+ ); +} + +// ---------------------------------------------------------------- board + +function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm }: BoardProps) { + const amPlayer = !!me && v.order.includes(me); + const [announce, setAnnounce] = useState(''); + const [bubbles, setBubbles] = useState>({}); + const [shake, setShake] = useState(false); + const [fresh, setFresh] = useState(null); + const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn }); + + useEffect(() => { + const p = prev.current; + // New public log entries since last time (the log keeps only the last 30). + const n = Math.max(0, Math.min(v.log.length, v.logCount - p.logCount)); + const added = n ? v.log.slice(-n) : []; + const msgs: string[] = []; + const bub: Record = {}; + let shook = false; + for (const e of added) { + msgs.push(logText(e, players, me)); + if (e.t === 'shuffle') { + bub[e.player] = '🔀 섞었어요'; + if (e.player === v.target) shook = true; + } else if (e.t === 'draw' && e.pair) bub[e.drawer] = '짝!'; + else if (e.t === 'out') bub[e.player] = '🎉 다 털었어요'; + } + const hand = v.myHand ?? []; + const ld = v.lastDraw; + if (amPlayer && ld && added.some((e) => e.t === 'draw')) { + if (ld.drawer === me && ld.card === JOKER) { + toast('앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.'); + haptic([40, 30, 40]); + } else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) { + toast('조커를 넘겼어요! 😆'); + haptic(40); + } + setFresh(ld.drawer === me && !ld.pair ? ld.card : null); + } + if (amPlayer && v.turn === me && p.turn !== me && v.phase === 'playing') { + sounds.myTurn(); + haptic(40); + msgs.push('내 차례예요.'); + } + if (msgs.length) setAnnounce(msgs.join(' ')); + if (Object.keys(bub).length) { + setBubbles((b) => ({ ...b, ...bub })); + setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), 2500); + } + prev.current = { logCount: v.logCount, hand, turn: v.turn }; + if (shook) { + setShake(true); + const t = setTimeout(() => setShake(false), 550); + return () => clearTimeout(t); + } + return undefined; + }, [v.seq]); // eslint-disable-line react-hooks/exhaustive-deps + + const seats = amPlayer ? v.order.slice(v.order.indexOf(me!) + 1).concat(v.order.slice(0, v.order.indexOf(me!))) : v.order; + return ( +
+ +
+ {seats.map((p) => ( + + ))} +
+ + {amPlayer && } +

+ {announce} +

+ + ); +} + +// ---------------------------------------------------------------- side + +function OldMaidSide({ view: v, me, players, deadline }: BoardProps) { + const running = v.phase === 'playing'; + const log = v.log.filter((e) => e.t !== 'shuffle').slice(-8).reverse(); + return ( + <> + +
+
+ {running ? `${nick(players, v.turn!)}님 차례` : '게임 끝'} + {running && } +
+ {optionsSummary(v.options)} +
    + {v.order.map((p) => ( +
  1. + + + {nick(players, p)} + {v.turn === p ? ' · 차례' : ''} + {v.final?.thief === p ? ' · 🃏 도둑' : ''} + + + {v.status[p] === 'out' ? `${v.places[p]}등` : v.status[p] === 'left' ? '나감' : `${v.handCounts[p]}장`} + +
  2. + ))} +
+
+ {v.final && ( +
+ 결과 + {v.final.thief ? `🃏 도둑은 ${who(players, v.final.thief, me)}${v.final.thief === me ? '예요' : '이에요'}.` : '한 사람이 나가서 끝났어요.'} +
    + {v.final.ranking.map((g, i) => ( +
  1. + {v.final!.ranking.slice(0, i).reduce((n, x) => n + x.length, 1)}등 {g.map((p) => `${nick(players, p)}${p === v.final!.thief ? ' (도둑)' : v.status[p] === 'left' ? ' (나감)' : ''}`).join(', ')} +
  2. + ))} +
+
+ )} + {log.length > 0 && ( +
+ 최근 기록 +
    + {log.map((e, i) => ( +
  1. {logText(e, players, me)}
  2. + ))} +
+
+ )} +
+ 도움말 +
    +
  • 내 차례에는 다음 사람(왼쪽)의 뒷면 카드 중 한 장을 뽑아요.
  • +
  • 같은 숫자 두 장은 저절로 짝으로 버려져요(무늬는 상관없어요).
  • +
  • 손패를 먼저 다 털수록 높은 등수예요.
  • +
  • 마지막까지 조커를 든 사람이 도둑(꼴찌)이에요.
  • +
  • [🔀 섞기]로 내 손패 순서를 섞을 수 있어요(차례마다 3번까지).
  • +
+
+ + ); +} + +// ---------------------------------------------------------------- status + +function isMyTurn(v: OldMaidView, me: string | null): boolean { + return !!me && v.phase === 'playing' && v.turn === me; +} + +function statusText(v: OldMaidView, me: string | null, players: Record): string { + if (v.phase === 'finished') return v.final?.summary ?? '게임이 끝났어요'; + const t = v.turn!; + const target = v.target; + if (isMyTurn(v, me)) return `내 차례예요. ${target ? `${nick(players, target)}님 카드에서 한 장 뽑아요` : '기다려 주세요'}`; + if (target && target === me) return `${nick(players, t)}님이 내 카드를 고르는 중이에요`; + return `${nick(players, t)}님이 ${target ? `${nick(players, target)}님 카드를 ` : ''}고르는 중이에요`; +} + +// ---------------------------------------------------------------- options + +function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} + +function Field({ label, children }: { label: string; children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + +function Options({ value: o, onChange }: OptionsProps) { + return ( +
+ + onChange({ ...o, turnSeconds })} + /> + +
+ ); +} + +function optionsSummary(o: OldMaidOptions): string { + return `트럼프 52장 + 조커 1장 · 제한 ${o.turnSeconds}초`; +} + +function Rules({ options }: { options?: OldMaidOptions }) { + const row: CSSProperties = { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }; + return ( +
+

+ 옆 사람 손패에서 한 장씩 몰래 뽑아 같은 숫자 짝을 버리다가, 마지막에 조커를 들고 있는 사람이 도둑(꼴찌)이 되는 카드놀이예요. 2~8명이 할 수 있어요. +

+
+ + + → 짝! 버려요 · + + 짝 없음 +
+

+ 준비: 트럼프 52장에 조커 1장을 넣은 53장을 섞어 모두에게 한 장씩 고르게 나눠요(한 장 차이는 괜찮아요). 먼저 나누어 받는 사람은 무작위로 정하고, 그 사람이 먼저 뽑아요. 나눈 뒤 각자 손에서 같은 숫자 두 장을 짝으로 모두 + 버려요(무늬는 상관없어요). 이건 저절로 돼요. +

+

+ 뽑기: 내 차례에는 다음 사람(왼쪽)이 뒷면으로 내민 카드 중 한 장을 골라 뽑아요. 뽑은 카드로 짝이 생기면 바로 버리고, 짝이 없으면 내 손에 넣어요(내 손패 아무 자리에 섞여 들어가요). 그다음 차례는 내가 뽑아 온 사람이에요. +

+

+ 섞기: 언제든 [🔀 섞기]로 내 손패 순서를 섞을 수 있어요(차례마다 {SHUFFLES_PER_TURN}번까지). 다른 사람에게는 내 손패가 순서 그대로 뒷면으로 보이니, 조커를 숨길 때 써 보세요. +

+

+ 끝: 손패를 다 턴 사람은 빠지고, 먼저 턴 순서대로 1등, 2등…이에요. 짝이 다 버려지면 조커 한 장만 남고, 그걸 든 사람이 도둑이에요. +

+

+ {options?.turnSeconds ?? 20}초 안에 고르지 않으면 무작위로 한 장을 뽑아요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 카드를 든 채 게임을 나가면 그 사람 카드는 섞어서 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고(짝이 + 생기면 버려요), 나간 사람은 맨 아래 등수가 돼요. 둘만 남았을 때 한 사람이 나가면 도둑 없이 끝나요. +

+
+ ); +} + +const ui: GameUI = { + Board: OldMaidBoard, + Side: OldMaidSide, + statusText, + isMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/old-maid/quick.tsx b/apps/web/src/games/old-maid/quick.tsx new file mode 100644 index 0000000..b914f1b --- /dev/null +++ b/apps/web/src/games/old-maid/quick.tsx @@ -0,0 +1,51 @@ +/** 도둑잡기 30초 규칙 요약 (docs/07 §5). */ +import { PlayingCard } from '../../components/cards/PlayingCard'; +import type { QuickCard } from '../types'; + +const row = { display: 'flex', alignItems: 'center', gap: 8 } as const; +const label = { fontSize: 13, fontWeight: 800, color: '#374151', textAlign: 'center' } as const; + +export const quickStart: QuickCard[] = [ + { + pic: ( +
+
+ + +
+ → + 짝! 버려요 +
+ ), + alt: '하트 7과 스페이드 7이 짝이 되어 버려져요', + 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 9d500b3..44bebec 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -26,6 +26,7 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { 'cockroach-poker': () => import('./cockroach-poker'), 'ninety-nine': () => import('./ninety-nine'), 'connect-four': () => import('./connect-four'), + 'old-maid': () => import('./old-maid'), dobble: () => import('./dobble'), catchmind: () => import('./catchmind'), mafia: () => import('./mafia'), diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index afca556..3cc4c11 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -22,6 +22,7 @@ export const GAME_ICON: Record = { 'las-vegas': '⚅', 'cockroach-poker': '🐞', 'ninety-nine': '💯', + 'old-maid': '🤡', dobble: '👀', catchmind: '🖍️', mafia: '🌙', @@ -39,4 +40,7 @@ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] }, { 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'] }, + { key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] }, + { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] }, + { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 5a63cd0..de747e7 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -42,6 +42,7 @@ | `apple` | 사과 게임(합 10 만들기, 같은 판 경주) | 1~8 | M9 | | `clue` | 클루 | 3~6 | M9 | | `connect-four` | 커넥트 포(사목) | 2 | M9 | +| `old-maid` | 도둑잡기 | 2~8 | M9 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/old-maid.md b/docs/games/old-maid.md new file mode 100644 index 0000000..219df51 --- /dev/null +++ b/docs/games/old-maid.md @@ -0,0 +1,116 @@ +# 도둑잡기 (`old-maid`) + +> 마일스톤: M9 · 인원: 최소 2 ~ 최대 8명 · 예상 시간: 약 5~10분 · 난이도: 쉬움 + +## 1. 개요 +- 트럼프 52장에 조커 1장을 넣어 나누고, 옆 사람 손패에서 한 장씩 몰래 뽑아 같은 숫자 짝을 버리다가 마지막에 조커를 든 사람이 지는(도둑) 가족 카드놀이. 집에서 한 번쯤 해 본 놀이라 설명이 거의 필요 없다. +- 비슷한 놀이: 영국의 올드 메이드(1882년 기록, 퀸 한 장을 빼는 방식), 독일의 블랙 피터, 일본의 바바누키. 우리 사이트는 한국에서 흔한 "조커 한 장" 방식만 쓴다. +- 인원 근거: 2명부터 가능하고, 53장을 나누면 8명일 때 한 사람 6~7장이라 그 이상은 짝 버리기 뒤 손패가 너무 적다. 2~8명. +- 실력 요소가 거의 없는 운 게임이라, 사람 사이의 재미(조커 넘기기, 섞기 "손장난", 채팅)가 중심이다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `turnSeconds` | 한 번 뽑는 제한 시간 | 10 / 20 / 30 / 60초 | 20초 | + +일부러 넣지 않은 것: 짝 직접 버리기(항상 자동), 퀸 빼기(올드 메이드) 방식, 상대가 고르는 카드를 실시간으로 보여 주는 표시, "한 장 살짝 올려 보이기" 손장난. 규칙을 단순하게 두려고 뺐다. 손장난은 [섞기] 하나로 대신한다. + +## 3. 구성물 +- 트럼프 52장(♠♥◆♣ × 2~10·J·Q·K·A) + 조커 1장 = 53장. 카드 id는 엔진 공통 형식(`7H`, `TD`, 조커 `X1`). +- 짝은 숫자(랭크)만 본다. 무늬·색은 상관없다. 조커는 짝이 없다. + +## 4. 준비(셋업) +1. 53장을 시드 RNG로 섞는다. +2. 첫 사람을 무작위로 정하고, 그 사람부터 자리 순서대로 한 장씩 나눈다(53장이라 앞자리 몇 명이 한 장 더 받는다). +3. 모두 손에서 같은 숫자 두 장을 짝으로 버린다(자동). 같은 숫자가 세 장이면 두 장만 버리고 한 장은 남는다. 버린 짝은 공개 정보다. +4. 이때 손패가 0장이 된 사람은 바로 빠지고(같은 순간이라 공동 순위), 첫 사람이 빠졌으면 다음 자리부터 시작한다. 드물게 이것만으로 한 사람만 남으면 그 자리에서 끝난다. + +## 5. 진행 규칙 +- 차례인 사람은 **다음 자리(왼쪽)에서 아직 카드가 있는 사람**의 손패에서 뒷면 카드 한 장을 고른다. 뽑는 사람에게 보이는 것은 그 사람 카드의 **장수와 자리(왼쪽부터 몇 번째)** 뿐이다. 자리는 그 사람이 실제로 들고 있는 순서 그대로다. +- 뽑은 카드와 같은 숫자가 내 손에 있으면 두 장을 바로 버린다(자동, 공개). 없으면 뽑은 카드를 내 손패 **무작위 자리**에 넣는다(2명일 때 뺏긴 사람이 그 카드 자리를 알 수 없게). +- 손패가 0장이 된 사람은 빠진다(먼저 턴 순서대로 1등, 2등…). 한 번에 두 사람이 빠지면(뽑힌 사람이 마지막 카드를 뺏기고 뽑은 사람도 그 짝으로 다 털 때) 뽑힌 사람이 먼저다. +- 다음 차례는 내가 뽑은 사람(그 사람이 빠졌으면 그다음 자리에서 카드가 있는 사람)이다. 즉 A가 B에게서, B가 C에게서 … 뽑으며 돈다. +- **섞기**: 게임에 남아 카드가 2장 이상인 사람은 언제든(내 차례가 아니어도) 내 손패 순서를 섞을 수 있다. 섞기는 서버 시드 RNG로 하고, 한 사람이 한 차례 동안 3번까지 할 수 있다(연타 방지). 섞어도 차례 시계는 그대로다. + +### 5.1 예시(3명 A·B·C) +A [♥2, ♥3], B [♠2, 조커], C [♠3]. A 차례: B의 첫 카드(♠2)를 뽑아 ♥2와 짝 → 버림. B [조커]. B 차례: C의 ♠3을 뽑았지만 짝이 없어 손에 넣음 → C는 0장이라 1등. 다음은 A(C가 빠짐) 차례: B의 두 장 중 ♠3을 뽑아 ♥3과 짝 → A 2등. B는 조커만 들고 도둑. + +## 6. 승패와 점수 계산 +- 짝이 모두 버려지면 조커 한 장만 남고, 그 사람이 **도둑(꼴찌)** 이다. +- 순위: 손패를 먼저 다 턴 순서대로 위, 도둑이 그 아래, 게임 중에 나간 사람이 맨 아래(같은 그룹 공동). +- 점수는 없다. 결과 화면의 점수 칸(`scoreText`)에 도둑은 "🃏 도둑", 다 턴 사람은 "다 털었어요", 나간 사람은 "나감"으로 적어 **누가 도둑인지** 이름 옆에 보인다(엔진 문구에는 닉네임을 넣을 수 없어서). `summary`는 "조커를 끝까지 들고 있던 꼴찌가 🃏 도둑이에요! …". + +## 7. 지역 룰 / 하우스 룰 (옵션으로 켜고 끄기) +- 없음. 원작 변형(퀸 빼기, 짝 직접 버리기, 뽑는 방향 바꾸기)은 규칙을 단순하게 두려고 넣지 않았다. + +## 8. 엔진 설계 +### 8.1 상태(State) +```ts +interface OldMaidState { + options: { turnSeconds: 10 | 20 | 30 | 60 }; + order: PlayerId[]; + hands: Record; // 들고 있는 순서 그대로(왼쪽부터) + discards: Record; // 버린 짝(공개) + out: PlayerId[][]; // 다 턴 순서(같은 순간은 한 그룹) + left: PlayerId[]; // 카드를 든 채 나간 사람 + turn: PlayerId | null; turnNo: number; + shuffles / shufflesThisTurn: Record; + lastDraw: { no, drawer, from, index, card, pair, auto } | null; + log: LogEntry[]; logCount: number; // 공개 기록(최근 30개) + timeoutsInRow, away, turnStartedAt, seq, final; +} +``` +### 8.2 액션 +| type | payload | 누가 / 언제 | 검증 조건 | +|---|---|---|---| +| `draw` | `from`, `index` | 차례인 사람 | `from`이 지금 뽑을 사람(다음 자리의 카드 있는 사람)과 같고, `0 ≤ index < 그 사람 장수`. `from`을 함께 보내 그사이 누가 나가 대상이 바뀌면 거절된다 | +| `shuffle` | 없음 | 남아 있는 사람 누구나, 언제든 | 카드 2장 이상, 이번 차례에 3번 미만 | +| `timeout` | (시스템) | 차례인 사람 | 무작위 자리 한 장 뽑기 | +| `leave` | (시스템) | 카드를 든 사람 | 8.5 참고 | + +### 8.3 공개/비공개 정보 (view) +- 내 손패만 카드 id로, 다른 사람은 **장수만**(`handCounts`). 관전자는 아무 손패도 받지 않는다. +- 뽑기 기록(`log`, `lastDraw`)은 누가 누구의 몇 번째 카드를 뽑았는지와 버린 짝만 공개. 짝이 안 난 카드는 **뽑은 사람의 view에만** `lastDraw.card`로 들어간다. 뺏긴 사람은 자기 손패가 바뀐 것으로 알 수 있다(화면이 "조커를 넘겼어요!"를 알려 준다). +- 조커가 누구에게 있는지는 끝날 때까지 어디에도 없다. 끝나면 `revealed`로 남은 손패(도둑의 조커)를 공개한다. +- 이벤트(`draw`, `shuffle`, `out`, `left`, `timeout`, `gameEnded`)에도 손에 남은 카드 id는 넣지 않는다(테스트로 확인). +- `secretsOf` = 그 사람 손패. 엔진 공통 유출 검사를 매 상태 통과한다. + +### 8.4 랜덤 요소 (시드 RNG 사용 지점) +- 덱 섞기, 첫 사람, 뽑은 카드를 넣을 자리, 섞기, 시간 초과 때 뽑을 자리, 나간 사람 카드 섞기와 넣을 자리. 모두 `ctx.rng`. + +### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동 +- 차례마다 `turnSeconds`. 넘기면 지금 뽑을 사람의 **무작위 자리 한 장**을 뽑는다(자동 짝 버리기 포함). 3번 연속이면 "자리 비움"으로 제한 시간 5초, 직접 뽑으면 풀린다. +- 섞기는 차례 시계를 다시 시작하지 않는다. +- **나가기(공정 처리)**: 카드를 든 사람이 나가면 그 카드를 섞어, 남아 있는 사람들에게 **나간 사람의 다음 자리부터 한 장씩 돌아가며** 나눠 준다(각자 손패 무작위 자리에). 받은 사람은 짝을 자동으로 버리고, 그걸로 0장이 되면 빠진다. 조커가 있었다면 누구에게 갈지 무작위라 특정 사람만 손해 보지 않는다. 나간 사람은 맨 아래 순위. 그 결과 카드 든 사람이 한 명 이하가 되면 **도둑 없이** 끝난다(`reason: resign`, 남은 사람이 나간 사람보다 위). 나간 사람이 차례였으면 다음 자리로 넘어간다. +- 이미 다 턴 사람이 나가면 아무 변화도 없다(`onLeave` = null, 순위 유지). + +### 8.6 종료 조건과 결과(GameResult) +- 카드를 든 사람이 1명 이하가 되는 순간 끝. `ranking` = 다 턴 그룹들 + [도둑] + [나간 사람들]. `scoreText`는 6절. `reason`은 보통 `normal`, 나가서 끝나면 `resign`. + +## 9. UI/UX +- 위: 다른 사람 자리 카드(내 다음 자리부터, 즉 내가 뽑을 사람이 맨 앞). 장수(작은 뒷면 묶음), 버린 짝 수, "뽑는 중"/"뽑히는 중"/"🎉 N등"/"🃏 도둑" 배지, 섞으면 "🔀 섞었어요" 말풍선. +- 가운데 초록 테이블: "A ← B의 카드 N장"과 뽑힐 사람의 뒷면 카드를 펼쳐 보여 준다(자리 번호 표시, 많으면 작게 여러 줄). 내 차례면 카드가 버튼이 된다. 터치 기기에서 "두 번 눌러 확인"(설정 `tapConfirm`)이 켜져 있으면 첫 탭은 고르기(카드가 위로), 두 번째 탭에 뽑는다. PC 마우스는 한 번에 뽑는다. 키보드는 좌우 방향키로 고르고 Enter. 뽑힐 사람이 섞으면 펼친 카드가 흔들리고 고른 것이 풀린다. +- 지난 뽑기: 누가 누구의 몇 번째를 뽑았는지, 짝이 나면 두 장을 앞면으로. 내가 뽑은 카드는 나에게만 앞면으로("뽑은 카드 ♠9 · 짝이 없어서 손에 넣었어요", "앗, 조커를 뽑았어요!"). 최근 버린 짝 6쌍. +- 아래 내 자리: 내 손패(앞면, 실제 순서), 조커는 빨간 테두리, 방금 들어온 카드는 반짝. [🔀 섞기 (남은 횟수/3)] 버튼. "다른 사람에게는 이 순서 그대로 뒷면으로 보여요" 안내. 조커를 넘기면 "조커를 넘겼어요! 😆" 알림. +- 오른쪽(휴대폰은 아래): 차례·타이머, 참가자(장수/등수), 최근 기록, 결과(등수와 도둑), 도움말. +- 휴대폰 320px~: 자리 카드 2열, 카드 폭 44~50px(터치 44px 이상). 다크 모드는 공통 색 변수, 화면 읽기 프로그램용 aria-label과 aria-live 안내. +- 컴퓨터 상대: 단계와 관계없이 무작위로 한 장 뽑고, 가끔(15%, 차례마다 한 번까지) 자기 손패를 먼저 섞는다. 생각 시간은 방의 공통 "사람 같은 지연". + +## 10. 테스트 체크리스트 +- [x] 2~8명 셋업: 53장 고르게, 짝 모두 버림, 조커 한 사람, 첫 사람이 한 장 더 +- [x] 처음부터 0장인 사람은 바로 빠지고 차례 넘김 +- [x] 고른 자리 카드 뽑기, 짝 자동 버리기, 짝 없으면 무작위 자리, 다음 차례, 빠진 사람 건너뛰기 +- [x] 한 번에 두 사람 빠짐(뽑힌 사람 먼저), 도둑·순위·`scoreText`·요약 +- [x] 검증: 차례, 대상(`from`), 자리 범위 +- [x] 섞기: 차례 아니어도 가능, 차례마다 3번, 시계 유지, 섞은 뒤 같은 자리를 뽑으면 섞인 순서의 카드 +- [x] 시간 초과 무작위 뽑기, 자리 비움(5초), 모두 시간 초과만 해도 끝 +- [x] 나가기: 다음 자리부터 나눠 주기·짝 버리기·차례 넘김, 2명이면 도둑 없이 끝, 다 턴 사람은 null +- [x] view/이벤트 유출 없음(뽑은 카드는 뽑은 사람만), 엔진 randomPlayout(2~8명) + 결정성, 같은 기록 재생 +- [x] 컴퓨터: 무작위 자리, 가끔 섞기(차례마다 한 번), 2·5·8명 끝까지, 방 연습 게임 끝까지 +- [x] 웹 도움말(차례/뽑히는 사람/구경/끝), E2E(PC + 휴대폰 2명, 끝까지) + +## 11. 참고 자료 +- 위키백과 "Old maid (card game)", 한국어 "도둑잡기" 항목. 기획 메모 `notes/new-game-descriptions-20261012.md` 15절. + +## 12. 메모 (상표·법적 주의 등) +- 민속 놀이라 상표 문제가 없다. 카드 그림은 사이트 공통 SVG 트럼프 카드(`apps/web/src/components/cards/PlayingCard.tsx`)를 쓴다. diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index fd6a37a..e0d9282 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -646,6 +646,56 @@ async function ninetyNineStep(p: Page, stats: Record): Promise): Promise { + const status = (await p.locator('.turn-status').innerText().catch(() => '')).trim(); + if (!status.includes('내 차례예요')) return false; + const cards = p.locator('.om-fan button.om-back'); + const n = await cards.count(); + if (!n) return false; + const draws = stats.draws ?? 0; + const card = cards.nth((draws * 7) % n); + if (tag(p) === 'phone') { + await card.tap(); + if ((await card.getAttribute('aria-pressed')) === 'true') { + if (!stats[`shot-pick-${tag(p)}`]) { + stats[`shot-pick-${tag(p)}`] = 1; + await p.screenshot({ path: join(SHOTS, 'old-maid-pick-phone.png'), fullPage: true }); + } + await card.tap(); + stats.confirm = (stats.confirm ?? 0) + 1; + } + } else if ((stats.pc = (stats.pc ?? 0) + 1) % 3 === 2 && n > 1) { + await cards.first().focus(); + await p.keyboard.press('ArrowRight'); + await p.keyboard.press('Enter'); + stats.keyboard = (stats.keyboard ?? 0) + 1; + } else { + await card.click(); + stats.click = (stats.click ?? 0) + 1; + } + stats.draws = draws + 1; + await p.waitForFunction((s) => document.querySelector('.turn-status')?.textContent?.trim() !== s, status, { timeout: 5000 }).catch(() => {}); + return true; +} + +/** 도둑잡기: a player whose cards are being picked from shuffles them (button), a few times per game. */ +async function oldMaidShuffle(p: Page, stats: Record): Promise { + if ((stats.shuffle ?? 0) >= 4) return false; + const status = (await p.locator('.turn-status').innerText().catch(() => '')).trim(); + if (!status.includes('내 카드를 고르는 중')) return false; + const btn = p.getByRole('button', { name: /^🔀 섞기/ }); + if (!(await btn.isEnabled().catch(() => false))) return false; + const before = await p.locator('.om-hand').getAttribute('aria-label'); + await btn.click(); + await p.waitForFunction((b) => document.querySelector('.om-hand')?.getAttribute('aria-label') !== b || !document.querySelector('.om-hand'), before, { timeout: 3000 }).catch(() => {}); + stats.shuffle = (stats.shuffle ?? 0) + 1; + return true; +} + /** * 도블: one real tap on `p`'s own screen. Reads the pictures of the two compared cards from the DOM (data-art), taps the shared one * (or, when `wrong`, a picture of my card that is not on the other). PC: focus + Enter, phone: tap. Returns the judgement shown. @@ -2071,6 +2121,57 @@ const PLANS: Record = { console.log(` ninety-nine: finished after ${turns} UI turns ${JSON.stringify(stats)}, ${outs} eliminations in the log`); }, }, + 'old-maid': { + // PC host + 2 phones, real draws through the UI until only the joker is left: PC clicks (sometimes keyboard), phones tap + // twice (pick, then draw). Whoever is being drawn from sometimes shuffles their hand. Screens: mid-game (light/dark), result. + players: 3, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page, Page]; + const stats: Record = {}; + let shot = false; + const until = Date.now() + 300_000; + const over = () => host.getByRole('dialog', { name: '게임 결과' }).count(); + while (Date.now() < until && !(await over())) { + let acted = false; + for (const p of pages) if (await oldMaidShuffle(p, stats)) acted = true; + for (const p of pages) { + if (await oldMaidStep(p, stats)) { + acted = true; + break; + } + } + if (!shot && (stats.draws ?? 0) >= 6) { + shot = true; + await host.waitForTimeout(500); + await host.screenshot({ path: join(SHOTS, 'old-maid-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'old-maid-mid-phone.png') }); + await guest.screenshot({ path: join(SHOTS, 'old-maid-mid-phone-full.png'), fullPage: true }); + // Narrowest supported phone. + await guest.setViewportSize({ width: 320, height: 700 }); + await guest.waitForTimeout(300); + await guest.screenshot({ path: join(SHOTS, 'old-maid-mid-phone-320.png'), fullPage: true }); + await guest.setViewportSize({ width: 390, height: 844 }); + await host.emulateMedia({ colorScheme: 'dark' }); + await guest.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(400); + await host.screenshot({ path: join(SHOTS, 'old-maid-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'old-maid-mid-phone-dark.png'), fullPage: true }); + await host.emulateMedia({ colorScheme: 'light' }); + await guest.emulateMedia({ colorScheme: 'light' }); + } + if (!acted) await host.waitForTimeout(120); + } + if (!(await over())) throw new Error(`game did not finish (${JSON.stringify(stats)})`); + for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor(); + const dialog = host.getByRole('dialog', { name: '게임 결과' }); + await dialog.getByText('🃏 도둑').first().waitFor({ timeout: 3000 }); + await host.waitForTimeout(600); + await host.screenshot({ path: join(SHOTS, 'old-maid-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'old-maid-result-phone.png') }); + if ((stats.draws ?? 0) < 6 || !stats.confirm || !stats.click || !stats.keyboard) throw new Error(`too few real turns: ${JSON.stringify(stats)}`); + console.log(` old-maid: finished after ${JSON.stringify(Object.fromEntries(Object.entries(stats).filter(([k]) => !k.startsWith('shot'))))}`); + }, + }, dobble: { // PC host + phone guest, 탑 쌓기 with the 55-card deck and a 1-second lock. Both players find the shared picture of their own card and the centre // card on their own screen (PC: keyboard focus + Enter, phone: tap), one deliberate wrong tap (shake + lock), until the draw pile runs out. diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 79e99e4..1d09466 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -29,6 +29,7 @@ import { quoridorBot } from '../quoridor/bot'; import { lasVegasBot } from '../las-vegas/bot'; import { cockroachPokerBot } from '../cockroach-poker/bot'; import { ninetyNineBot } from '../ninety-nine/bot'; +import { oldMaidBot } from '../old-maid/bot'; import { mafiaBot } from '../mafia/bot'; import { appleBot } from '../apple/bot'; import { clueBot } from '../clue/bot'; @@ -64,6 +65,7 @@ export const BOT_STRATEGIES: Record = { 'ninety-nine': ninetyNineBot, clue: clueBot, 'connect-four': connectFourBot, + 'old-maid': oldMaidBot, }; /** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */ diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index 0441497..5ed8d4f 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -22,6 +22,7 @@ import { quoridor } from './quoridor'; import { lasVegas } from './las-vegas'; import { cockroachPoker } from './cockroach-poker'; import { ninetyNine } from './ninety-nine'; +import { oldMaid } from './old-maid'; import { dobble } from './dobble'; import { catchmind } from './catchmind'; import { mafia } from './mafia'; @@ -53,6 +54,7 @@ export const GAMES: Record = { [lasVegas.id]: lasVegas, [cockroachPoker.id]: cockroachPoker, [ninetyNine.id]: ninetyNine, + [oldMaid.id]: oldMaid, [dobble.id]: dobble, [catchmind.id]: catchmind, [mafia.id]: mafia, diff --git a/packages/games/src/old-maid/bot.test.ts b/packages/games/src/old-maid/bot.test.ts new file mode 100644 index 0000000..3db0a63 --- /dev/null +++ b/packages/games/src/old-maid/bot.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, seedN } from '@bg/engine'; +import { decideBotAction } from '../bots/index'; +import { botPlayout } from '../bots/playout'; +import { oldMaid as game, type OldMaidState } from './index'; +import { SHUFFLE_CHANCE } from './bot'; + +const setup = (players: string[], seed = 1): OldMaidState => + game.setup({ players, options: game.defaultOptions, rng: SeededRng.fromSeed(seedN(seed)), now: 0 }); +const decide = (s: OldMaidState, p: string, r: number) => decideBotAction(game, s, p, { now: 0, random: () => r }) as Record; + +describe('old-maid bot', () => { + test('draws a card from the neighbour it must draw from, at any spot', () => { + const s = setup(['bot:1:x', 'B', 'C']); + s.turn = 'bot:1:x'; + const from = 'B'; + const n = s.hands.B!.length; + const spots = new Set(); + for (const r of [0.2, 0.4, 0.6, 0.8, 0.99]) { + const a = decide(s, 'bot:1:x', r); + expect(a).toMatchObject({ type: 'draw', from }); + spots.add(a.index as number); + } + expect(spots.size).toBeGreaterThan(2); + expect(Math.max(...spots)).toBeLessThan(n); + }); + + test('now and then shuffles its own hand first, but only once a turn', () => { + let s = setup(['bot:1:x', 'B', 'C']); + s.turn = 'bot:1:x'; + expect(decide(s, 'bot:1:x', SHUFFLE_CHANCE / 2)).toEqual({ type: 'shuffle' }); + s = game.apply(s, 'bot:1:x', { type: 'shuffle' }, { rng: SeededRng.fromSeed([1, 2, 3, 4]), now: 1 }).state; + expect(decide(s, 'bot:1:x', SHUFFLE_CHANCE / 2).type).toBe('draw'); + }); + + for (const n of [2, 5, 8]) { + test(`bots finish a game: ${n} players`, () => { + const players = ['h', ...Array.from({ length: n - 1 }, (_, i) => `bot:${i + 1}`)]; + for (let seed = 1; seed <= 3; seed++) { + const r = botPlayout(game as never, { players, seed: seedN(seed), isBot: (p) => p.startsWith('bot:') }); + expect(r.finished).toBe(true); + expect(r.botTimeouts).toBe(0); + } + }); + } +}); diff --git a/packages/games/src/old-maid/bot.ts b/packages/games/src/old-maid/bot.ts new file mode 100644 index 0000000..d9eb0ae --- /dev/null +++ b/packages/games/src/old-maid/bot.ts @@ -0,0 +1,18 @@ +/** + * 도둑잡기 computer player. There is nothing to read from face-down cards, so every level plays the same way: a random + * card from the neighbour's fan, and now and then (like a person fidgeting) a shuffle of its own hand first. The + * human-like thinking time comes from the room's bot driver. Uses only the view and the legal actions. + */ +import type { BotStrategy } from '../bots/types'; +import { pick, playable } from '../bots/policy'; +import { SHUFFLES_PER_TURN, type OldMaidAction, type OldMaidView } from './types'; + +/** Chance to shuffle its own hand before drawing (at most once a turn). */ +export const SHUFFLE_CHANCE = 0.15; + +export const oldMaidBot: BotStrategy = ({ view, legal, random }) => { + const draws = legal.filter((a) => a.type === 'draw'); + const fresh = (view.my?.shufflesLeft ?? 0) === SHUFFLES_PER_TURN; + if (fresh && legal.some((a) => a.type === 'shuffle') && random() < SHUFFLE_CHANCE) return { type: 'shuffle' }; + return draws.length ? pick(draws, random) : pick(playable(legal), random); +}; diff --git a/packages/games/src/old-maid/index.ts b/packages/games/src/old-maid/index.ts new file mode 100644 index 0000000..95f848b --- /dev/null +++ b/packages/games/src/old-maid/index.ts @@ -0,0 +1,398 @@ +/** + * 도둑잡기 (docs/games/old-maid.md). + * + * Secret-id design: card ids ("7H", "X1" = joker) only appear in a view when the viewer may know that card: their own + * hand, thrown-away pairs (public), the card they just drew themselves, and every hand once the game is over. Other hands + * are sent as counts only; a drawer picks a position, never a card. + */ +import { z } from 'zod'; +import { fail, isJoker, ok, rankOf, standardDeck, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine'; +import { + JOKER, + LOG_KEEP, + SHUFFLES_PER_TURN, + oldMaidActionSchema, + oldMaidOptionsSchema, + type DrawAction, + type LogEntry, + type OldMaidAction, + type OldMaidOptions, + type OldMaidState, + type OldMaidView, + type SeatStatus, +} from './types'; + +export * from './types'; + +const AWAY_AFTER = 3; +const AWAY_MS = 5000; + +// ---------------------------------------------------------------- helpers + +const finished = (s: OldMaidState) => s.final !== null; +const isOut = (s: OldMaidState, p: PlayerId) => s.out.some((g) => g.includes(p)); + +/** Still in the game: holds cards and has not left. */ +export const inPlay = (s: OldMaidState, p: PlayerId): boolean => !s.left.includes(p) && !isOut(s, p) && (s.hands[p]?.length ?? 0) > 0; + +/** Next player still in the game after `p` in seat order (not `p` itself), or null. */ +function nextInPlay(s: OldMaidState, p: PlayerId): PlayerId | null { + const i = s.order.indexOf(p); + for (let k = 1; k < s.order.length; k++) { + const q = s.order[(i + k) % s.order.length]!; + if (inPlay(s, q)) return q; + } + return null; +} + +/** Whom `p` draws from: the next player still holding cards (the one on the left). */ +export const targetOf = (s: OldMaidState, p: PlayerId): PlayerId | null => nextInPlay(s, p); + +const playing = (s: OldMaidState) => s.order.filter((p) => inPlay(s, p)); + +function waiting(s: OldMaidState): PlayerId[] { + return finished(s) || !s.turn ? [] : [s.turn]; +} + +function turnMs(s: OldMaidState): number { + return s.turn && s.away[s.turn] ? AWAY_MS : s.options.turnSeconds * 1000; +} + +function pushLog(s: OldMaidState, e: LogEntry): void { + s.log.push(e); + s.logCount += 1; + if (s.log.length > LOG_KEEP) s.log.splice(0, s.log.length - LOG_KEEP); +} + +/** Throws away every pair in `p`'s hand (first two of a rank, in hand order); returns the pairs. */ +export function discardPairs(s: OldMaidState, p: PlayerId): [string, string][] { + const hand = s.hands[p]!; + const pairs: [string, string][] = []; + const open = new Map(); + const keep: string[] = []; + for (const c of hand) { + if (isJoker(c)) { + keep.push(c); + continue; + } + const r = rankOf(c); + const at = open.get(r); + if (at === undefined) { + open.set(r, keep.length); + keep.push(c); + } else { + pairs.push([keep[at]!, c]); + keep[at] = ''; + open.delete(r); + } + } + s.hands[p] = keep.filter((c) => c !== ''); + for (const [a, b] of pairs) s.discards[p]!.push(a, b); + return pairs; +} + +/** Players in `who` (in that order) that just emptied their hand go out together as one finishing group. */ +function markOut(s: OldMaidState, who: PlayerId[], events: GameEvent[]): void { + const fresh = who.filter((p) => !isOut(s, p) && !s.left.includes(p) && s.hands[p]!.length === 0); + if (!fresh.length) return; + const place = s.out.reduce((n, g) => n + g.length, 0) + 1; + s.out.push(fresh); + for (const p of fresh) { + pushLog(s, { t: 'out', player: p, place }); + events.push({ type: 'out', player: p, place }); + } +} + +/** Ends the game when at most one player still holds cards. Returns true when it ended. */ +function checkEnd(s: OldMaidState, byLeave: boolean, events: GameEvent[]): boolean { + const rest = playing(s); + if (rest.length > 1) return false; + const holder = rest[0] ?? null; + const thief = byLeave ? null : holder; + const ranking: PlayerId[][] = s.out.map((g) => [...g]); + if (holder) ranking.push([holder]); + if (s.left.length) ranking.push([...s.left]); + const summary = thief + ? '조커를 끝까지 들고 있던 꼴찌가 🃏 도둑이에요! 나머지는 손패를 먼저 다 턴 순서대로 순위가 정해졌어요' + : '한 사람이 게임을 나가서 끝났어요. 손패를 먼저 다 턴 순서대로 순위가 정해졌어요'; + s.final = { thief, reason: byLeave ? 'left' : 'normal', ranking, summary }; + s.turn = null; + events.push({ type: 'gameEnded', thief, reason: byLeave ? 'left' : 'normal' }); + return true; +} + +/** Turn goes to the next player in play after `p` (or stays with `p`'s next seat when `p` is gone). */ +function nextTurn(s: OldMaidState, p: PlayerId): void { + s.turn = nextInPlay(s, p); + s.turnNo += 1; + s.shufflesThisTurn = Object.fromEntries(s.order.map((q) => [q, 0])); +} + +function validateDraw(s: OldMaidState, actor: PlayerId, a: DrawAction): Validation { + if (s.turn !== actor) return fail('지금은 내 차례가 아니에요.'); + const from = targetOf(s, actor); + if (!from || a.from !== from) return fail('지금은 그 사람의 카드를 뽑을 수 없어요. 화면이 바뀌었는지 확인해 주세요.'); + if (!Number.isInteger(a.index) || a.index < 0 || a.index >= s.hands[from]!.length) return fail('없는 자리의 카드예요.'); + return ok; +} + +function canShuffle(s: OldMaidState, p: PlayerId): boolean { + return !finished(s) && inPlay(s, p) && s.hands[p]!.length >= 2 && (s.shufflesThisTurn[p] ?? 0) < SHUFFLES_PER_TURN; +} + +function applyDraw(s: OldMaidState, actor: PlayerId, a: DrawAction, rng: Rng, events: GameEvent[], auto: boolean): void { + const from = a.from; + const card = s.hands[from]!.splice(a.index, 1)[0]!; + const hand = s.hands[actor]!; + const mate = isJoker(card) ? -1 : hand.findIndex((c) => !isJoker(c) && rankOf(c) === rankOf(card)); + let pair: [string, string] | null = null; + if (mate >= 0) { + pair = [hand[mate]!, card]; + hand.splice(mate, 1); + s.discards[actor]!.push(...pair); + } else { + // Slipped in at a random spot, so the player it came from can't tell where it is (matters with 2 players). + hand.splice(rng.int(hand.length + 1), 0, card); + } + s.lastDraw = { no: s.turnNo, drawer: actor, from, index: a.index, card, pair, auto }; + pushLog(s, { t: 'draw', no: s.turnNo, drawer: actor, from, index: a.index, pair, auto }); + events.push({ type: 'draw', drawer: actor, from, index: a.index, ...(pair ? { pair } : {}), auto }); + // The one drawn from emptied first, then the drawer (if the pair was their last card). + markOut(s, [from], events); + markOut(s, [actor], events); + if (!checkEnd(s, false, events)) nextTurn(s, actor); +} + +/** A player with cards leaves: their cards are shuffled and dealt one by one to the others still in play, from the next seat. */ +function applyLeave(s: OldMaidState, actor: PlayerId, rng: Rng, events: GameEvent[]): void { + const cards = rng.shuffle([...s.hands[actor]!]); + s.hands[actor] = []; + s.left.push(actor); + const wasTurn = s.turn === actor; + const receivers = playing(s); + const start = receivers.length ? Math.max(0, receivers.indexOf(nextInPlay(s, actor) ?? receivers[0]!)) : 0; + const counts = new Map(); + if (receivers.length) { + cards.forEach((c, i) => { + const to = receivers[(start + i) % receivers.length]!; + const hand = s.hands[to]!; + hand.splice(rng.int(hand.length + 1), 0, c); + counts.set(to, (counts.get(to) ?? 0) + 1); + }); + } + const pairs: [string, string][] = []; + for (const p of receivers) if (counts.has(p)) pairs.push(...discardPairs(s, p)); + pushLog(s, { t: 'left', player: actor, gave: [...counts].map(([to, count]) => ({ to, count })), pairs }); + events.push({ type: 'left', player: actor }); + markOut(s, receivers, events); + if (checkEnd(s, true, events)) return; + if (wasTurn || !s.turn || !inPlay(s, s.turn)) nextTurn(s, wasTurn || !s.turn ? actor : s.turn); +} + +// ---------------------------------------------------------------- definition + +export const oldMaid: GameDefinition = { + id: 'old-maid', + nameKo: '도둑잡기', + minPlayers: 2, + maxPlayers: 8, + stateVersion: 1, + defaultOptions: oldMaidOptionsSchema.parse({}), + optionsSchema: oldMaidOptionsSchema as unknown as z.ZodType, + actionSchema: oldMaidActionSchema as unknown as z.ZodType, + + setup({ players, options, rng, now }) { + if (players.length < 2 || players.length > 8) throw new Error(`old-maid: ${players.length} players not allowed`); + const deck = rng.shuffle(standardDeck(1)); + const per = (f: (p: PlayerId) => T) => Object.fromEntries(players.map((p) => [p, f(p)])) as Record; + const first = players[rng.int(players.length)]!; + const fi = players.indexOf(first); + const hands = per(() => []); + // Dealt one at a time from the first player, so the first players get the extra card. + deck.forEach((c, i) => hands[players[(fi + i) % players.length]!]!.push(c)); + const s: OldMaidState = { + options, + order: [...players], + hands, + discards: per(() => []), + out: [], + left: [], + turn: first, + turnNo: 1, + shuffles: per(() => 0), + shufflesThisTurn: per(() => 0), + lastDraw: null, + log: [], + logCount: 0, + timeoutsInRow: per(() => 0), + away: per(() => false), + turnStartedAt: now, + seq: 0, + final: null, + }; + for (const p of players) discardPairs(s, p); + // Rare: someone threw away their whole hand right away (they go out together, in seat order). + const events: GameEvent[] = []; + markOut(s, players, events); + if (!checkEnd(s, false, events) && !inPlay(s, first)) s.turn = nextInPlay(s, first); + return s; + }, + + validate(s, actor, a) { + if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.'); + if (finished(s)) return fail('게임이 이미 끝났어요.'); + switch (a.type) { + case 'leave': + return ok; + case 'timeout': + return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.'); + case 'shuffle': + if (!inPlay(s, actor)) return fail('손에 카드가 없어요.'); + if (s.hands[actor]!.length < 2) return fail('카드가 2장 이상일 때 섞을 수 있어요.'); + return canShuffle(s, actor) ? ok : fail(`손패는 한 차례에 ${SHUFFLES_PER_TURN}번까지 섞을 수 있어요.`); + case 'draw': + return validateDraw(s, actor, a); + default: + return fail('알 수 없는 행동이에요.'); + } + }, + + apply(prev, actor, a, { rng, now }) { + const s = structuredClone(prev); + const events: GameEvent[] = []; + s.seq += 1; + switch (a.type) { + case 'shuffle': + s.hands[actor] = rng.shuffle(s.hands[actor]!); + s.shuffles[actor] = (s.shuffles[actor] ?? 0) + 1; + s.shufflesThisTurn[actor] = (s.shufflesThisTurn[actor] ?? 0) + 1; + pushLog(s, { t: 'shuffle', player: actor }); + events.push({ type: 'shuffle', player: actor }); + // Shuffling does not restart the turn clock. + return { state: s, events }; + case 'leave': + events.push({ type: 'left', player: actor }); + // Someone already out keeps their place; nothing changes. + if (inPlay(s, actor)) applyLeave(s, actor, rng, events); + break; + case 'timeout': { + const from = targetOf(s, actor)!; + const concrete: DrawAction = { type: 'draw', from, index: rng.int(s.hands[from]!.length) }; + const v = validateDraw(s, actor, concrete); + if (!v.ok) throw new Error(`old-maid: auto draw rejected: ${v.reason}`); + s.timeoutsInRow[actor] = (s.timeoutsInRow[actor] ?? 0) + 1; + events.push({ type: 'timeout', player: actor }); + if (s.timeoutsInRow[actor]! >= AWAY_AFTER && !s.away[actor]) { + s.away[actor] = true; + events.push({ type: 'away', player: actor }); + } + applyDraw(s, actor, concrete, rng, events, true); + break; + } + case 'draw': + s.timeoutsInRow[actor] = 0; + s.away[actor] = false; + applyDraw(s, actor, a, rng, events, false); + break; + } + s.turnStartedAt = now; + return { state: s, events }; + }, + + view(s, viewer) { + const me = viewer && s.order.includes(viewer) ? viewer : null; + const over = finished(s); + const per = (f: (p: PlayerId) => T) => Object.fromEntries(s.order.map((p) => [p, f(p)])) as Record; + const places: Record = {}; + let place = 1; + for (const g of s.out) { + for (const p of g) places[p] = place; + place += g.length; + } + const target = s.turn ? targetOf(s, s.turn) : null; + const ld = s.lastDraw; + let my: OldMaidView['my'] = null; + if (me && !over) { + const drawing = s.turn === me && !!target; + my = { + canDraw: drawing, + from: drawing ? target : null, + count: drawing ? s.hands[target!]!.length : 0, + canShuffle: canShuffle(s, me), + shufflesLeft: inPlay(s, me) ? SHUFFLES_PER_TURN - (s.shufflesThisTurn[me] ?? 0) : 0, + }; + } + return { + options: s.options, + me, + order: s.order, + phase: over ? 'finished' : 'playing', + turn: s.turn, + target, + turnNo: s.turnNo, + handCounts: per((p) => s.hands[p]!.length), + pairCounts: per((p) => s.discards[p]!.length / 2), + status: per((p) => (s.left.includes(p) ? 'left' : isOut(s, p) ? 'out' : 'playing')), + places, + shuffles: { ...s.shuffles }, + myHand: me ? [...s.hands[me]!] : null, + lastDraw: ld ? { ...ld, card: ld.pair || over || ld.drawer === me ? ld.card : null } : null, + my, + log: s.log.map((e) => structuredClone(e)), + logCount: s.logCount, + away: { ...s.away }, + turnStartedAt: s.turnStartedAt, + turnMs: turnMs(s), + seq: s.seq, + final: s.final, + revealed: over ? per((p) => [...s.hands[p]!]) : null, + }; + }, + + activePlayers: waiting, + + deadline(s) { + return finished(s) || !s.turn ? null : s.turnStartedAt + turnMs(s); + }, + + timeoutPlayers: waiting, + + onTimeout() { + return { type: 'timeout' }; + }, + + /** Leaving with cards hands them out to the others (§8.5); someone already out just keeps their place. */ + onLeave(s, player) { + if (!s.order.includes(player) || finished(s) || !inPlay(s, player)) return null; + return { type: 'leave' }; + }, + + result(s): GameResult | null { + const f = s.final; + if (!f) return null; + // The result screen has no names in the summary: the thief is marked next to their name instead. + const scoreText: Record = {}; + for (const p of f.ranking.flat()) { + scoreText[p] = p === f.thief ? '🃏 도둑' : s.left.includes(p) ? '나감' : isOut(s, p) ? '다 털었어요' : `카드 ${s.hands[p]!.length}장 남음`; + } + return { ranking: f.ranking, scoreText, summary: f.summary, reason: f.reason === 'left' ? 'resign' : 'normal' }; + }, + + legalActions(s, p) { + if (finished(s) || s.turn !== p) return []; + const from = targetOf(s, p); + if (!from) return []; + const out: OldMaidAction[] = s.hands[from]!.map((_, index) => ({ type: 'draw', from, index })); + if (canShuffle(s, p)) out.push({ type: 'shuffle' }); + return out; + }, + + /** `player`'s hand. */ + secretsOf(s, player) { + if (finished(s)) return []; + return [...(s.hands[player] ?? [])]; + }, +}; + +/** Whether `p` holds the joker (tests / summaries only — never sent to other players). */ +export const holdsJoker = (s: OldMaidState, p: PlayerId): boolean => s.hands[p]?.includes(JOKER) ?? false; diff --git a/packages/games/src/old-maid/old-maid.test.ts b/packages/games/src/old-maid/old-maid.test.ts new file mode 100644 index 0000000..234d2dc --- /dev/null +++ b/packages/games/src/old-maid/old-maid.test.ts @@ -0,0 +1,432 @@ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, isJoker, playoutSeeds, randomPlayout, rankOf, seedN, standardDeck, type GameEvent } from '@bg/engine'; +import { JOKER, SHUFFLES_PER_TURN, holdsJoker, inPlay, oldMaid as game, targetOf, type OldMaidAction, type OldMaidOptions, type OldMaidState } from './index'; + +// ---------------------------------------------------------------- helpers + +let clock = 1_000; +const rng = (n = 7) => SeededRng.fromSeed([n, n, n, n]); + +function setup(players = ['A', 'B', 'C'], seed = 1, opts: Partial = {}): OldMaidState { + return game.setup({ players, options: game.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: 0 }); +} + +/** A game in progress with exactly these hands (no pairs inside a hand), `turn` to draw. Unlisted cards count as thrown away. */ +function rigged(hands: Record, turn?: string): OldMaidState { + const players = Object.keys(hands); + const s = setup(players); + const used = new Set(Object.values(hands).flat()); + const rest = standardDeck(1).filter((c) => !used.has(c)); + for (const p of players) { + s.hands[p] = [...hands[p]!]; + s.discards[p] = []; + } + s.discards[players[0]!] = rest; + s.out = []; + s.left = []; + s.turn = turn ?? players[0]!; + s.turnNo = 1; + s.log = []; + s.lastDraw = null; + return s; +} + +/** A different (but reproducible) RNG per call, so repeated timeouts don't keep picking the same spot. */ +let calls = 0; +function actE(s: OldMaidState, p: string, a: OldMaidAction, r = rng(++calls)): { state: OldMaidState; events: GameEvent[] } { + const v = game.validate(s, p, a); + if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`); + return game.apply(s, p, a, { rng: r, now: (clock += 1000) }); +} +const act = (s: OldMaidState, p: string, a: OldMaidAction, r?: SeededRng) => actE(s, p, a, r).state; +const reject = (s: OldMaidState, p: string, a: OldMaidAction) => { + const v = game.validate(s, p, a); + return v.ok ? null : v.reason; +}; +const draw = (s: OldMaidState, p: string, index: number) => act(s, p, { type: 'draw', from: targetOf(s, p)!, index }); +const sorted = (xs: string[]) => [...xs].sort(); + +/** Every card exists exactly once across hands and discards; no hand holds a pair. */ +/** `pairs`: also check that discards come in same-rank pairs (off for rigged states, whose unused cards are dumped there). */ +function checkInvariants(st: unknown, pairs = true): void { + const s = st as OldMaidState; + const all = [...Object.values(s.hands).flat(), ...Object.values(s.discards).flat()]; + if (all.length !== 53) throw new Error(`card count ${all.length}`); + if (new Set(all).size !== 53) throw new Error('duplicate card'); + if (!Object.values(s.hands).flat().includes(JOKER)) throw new Error('joker thrown away'); + for (const [p, h] of Object.entries(s.hands)) { + const ranks = h.filter((c) => !isJoker(c)).map(rankOf); + if (new Set(ranks).size !== ranks.length) throw new Error(`${p} keeps a pair`); + } + if (pairs) { + for (const d of Object.values(s.discards)) for (let i = 0; i < d.length; i += 2) if (rankOf(d[i]!) !== rankOf(d[i + 1]!)) throw new Error(`bad pair ${d[i]} ${d[i + 1]}`); + } + if (!s.final && s.turn && !inPlay(s, s.turn)) throw new Error(`turn on ${s.turn} who is not in play`); +} + +// ---------------------------------------------------------------- setup + +describe('준비 (§4)', () => { + test.each([2, 3, 4, 5, 6, 7, 8])('%i명: 53장을 고르게 나누고 짝을 모두 버림, 조커는 한 사람에게', (n) => { + const players = Array.from({ length: n }, (_, i) => `P${i}`); + for (let seed = 1; seed <= 5; seed++) { + const s = setup(players, seed); + checkInvariants(s); + const dealt = players.map((p) => s.hands[p]!.length + s.discards[p]!.length); + expect(Math.max(...dealt) - Math.min(...dealt)).toBeLessThanOrEqual(1); + expect(dealt.reduce((a, b) => a + b, 0)).toBe(53); + for (const p of players) expect(s.discards[p]!.length % 2).toBe(0); + expect(players.filter((p) => holdsJoker(s, p))).toHaveLength(1); + expect(s.turn && players.includes(s.turn)).toBe(true); + } + }); + + test('첫 사람이 한 장 더 받음(나누기 시작)', () => { + const s = setup(['A', 'B', 'C', 'D'], 3); + const first = s.turn!; + const dealt = (p: string) => s.hands[p]!.length + s.discards[p]!.length; + expect(dealt(first)).toBe(14); + }); + + test('처음부터 손패가 0장이면 바로 빠지고 차례는 다음 사람에게', () => { + // Same pairs dealt to A only: emulate by rigging a fresh state and replaying the setup steps. + let found = false; + for (let seed = 1; seed <= 4000 && !found; seed++) { + const s = setup(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], seed); + if (s.out.length) { + found = true; + checkInvariants(s); + for (const p of s.out[0]!) expect(s.hands[p]).toEqual([]); + expect(inPlay(s, s.turn!)).toBe(true); + } + } + expect(found).toBe(true); + }); +}); + +// ---------------------------------------------------------------- draws + +describe('뽑기와 짝 버리기 (§5)', () => { + test('왼쪽(다음) 사람의 고른 자리 카드를 뽑고, 짝이 생기면 바로 둘 다 버림', () => { + let s = rigged({ A: ['7H', 'KS'], B: ['9C', '7D', X()], C: ['KD', '9S'] }); + expect(targetOf(s, 'A')).toBe('B'); + s = draw(s, 'A', 1); + expect(s.hands.A).toEqual(['KS']); + expect(s.discards.A!.slice(-2)).toEqual(['7H', '7D']); + expect(s.hands.B).toEqual(['9C', JOKER]); + expect(s.lastDraw).toMatchObject({ drawer: 'A', from: 'B', index: 1, card: '7D', pair: ['7H', '7D'] }); + expect(s.turn).toBe('B'); + expect(targetOf(s, 'B')).toBe('C'); + }); + + test('짝이 없으면 뽑은 카드는 내 손패 아무 자리에 숨겨짐', () => { + const seen = new Set(); + for (let n = 1; n <= 40; n++) { + const s0 = rigged({ A: ['2H', '3H', '4H', '5H'], B: ['9C', X()], C: ['KD'] }); + const s = act(s0, 'A', { type: 'draw', from: 'B', index: 0 }, rng(n)); + expect(sorted(s.hands.A!)).toEqual(sorted(['2H', '3H', '4H', '5H', '9C'])); + seen.add(s.hands.A!.indexOf('9C')); + } + expect(seen.size).toBeGreaterThan(2); + }); + + test('검증: 내 차례만, 지금 왼쪽 사람에게서만, 있는 자리만', () => { + const s = rigged({ A: ['7H'], B: ['9C', X()], C: ['9S', '7D'] }); + expect(reject(s, 'B', { type: 'draw', from: 'C', index: 0 })).toContain('내 차례가 아니에요'); + expect(reject(s, 'A', { type: 'draw', from: 'C', index: 0 })).toContain('그 사람의 카드를 뽑을 수 없어요'); + expect(reject(s, 'A', { type: 'draw', from: 'B', index: 2 })).toContain('없는 자리'); + expect(reject(s, 'A', { type: 'draw', from: 'B', index: -1 })).toContain('없는 자리'); + expect(reject(s, 'Z', { type: 'draw', from: 'B', index: 0 })).toContain('플레이어가 아니에요'); + expect(reject(s, 'A', { type: 'draw', from: 'B', index: 1 })).toBeNull(); + }); + + test('손패를 다 턴 사람은 빠지고, 빠진 사람은 건너뜀', () => { + // A draws B's last card (B goes out first), pairs it, and is out too (2nd). + let s = rigged({ A: ['7H'], B: ['7D'], C: ['9C', X()], D: ['9S'] }); + s = draw(s, 'A', 0); + expect(s.out).toEqual([['B'], ['A']]); + expect(s.turn).toBe('C'); + expect(targetOf(s, 'C')).toBe('D'); + s = draw(s, 'C', 0); // C: 9C+9S pair → C holds joker, D out + expect(s.out).toEqual([['B'], ['A'], ['D']]); + expect(s.final).not.toBeNull(); + expect(s.final!.thief).toBe('C'); + }); + + test('끝: 조커를 든 사람이 도둑(꼴찌), 순위는 먼저 턴 순서, 결과 문구', () => { + let s = rigged({ A: ['QH', X()], B: ['QS', '5D'], C: ['5C'] }); + s = draw(s, 'A', 0); // A: QH+QS → A [X1], B [5D] + expect(s.turn).toBe('B'); + s = draw(s, 'B', 0); // B draws 5C from C → pair; B and C out (C first) + expect(s.out).toEqual([['C'], ['B']]); + const r = game.result(s)!; + expect(r.ranking).toEqual([['C'], ['B'], ['A']]); + expect(r.reason).toBe('normal'); + expect(r.summary).toContain('도둑'); + expect(r.scoreText).toEqual({ C: '다 털었어요', B: '다 털었어요', A: '🃏 도둑' }); + expect(game.activePlayers(s)).toEqual([]); + expect(game.deadline!(s)).toBeNull(); + const v = game.view(s, 'B'); + expect(v.revealed!.A).toEqual([JOKER]); + expect(v.places).toEqual({ C: 1, B: 2 }); + expect(reject(s, 'A', { type: 'shuffle' })).toContain('이미 끝났어요'); + }); + + test('2명: 조커를 주고받다 끝남', () => { + let s = rigged({ A: ['3H', X()], B: ['3S'] }, 'B'); + s = draw(s, 'B', s.hands.A!.indexOf(JOKER)); // B takes the joker + expect(s.turn).toBe('A'); + expect(s.hands.B!.length).toBe(2); + s = draw(s, 'A', s.hands.B!.indexOf('3S')); // A pairs 3H+3S: A out, B thief + expect(game.result(s)!.ranking).toEqual([['A'], ['B']]); + expect(s.final!.thief).toBe('B'); + }); +}); + +function X(): string { + return JOKER; +} + +// ---------------------------------------------------------------- shuffle + +describe('내 손패 섞기', () => { + test('언제든(내 차례가 아니어도) 2장 이상이면 섞을 수 있고, 차례마다 3번까지, 시계는 그대로', () => { + let s = rigged({ A: ['2H', '3H'], B: ['4H', '5H', '6H', '7H', '8H', X()], C: ['9C'] }); + const startedAt = s.turnStartedAt; + for (let i = 0; i < SHUFFLES_PER_TURN; i++) s = act(s, 'B', { type: 'shuffle' }, rng(i + 1)); + expect(sorted(s.hands.B!)).toEqual(sorted(['4H', '5H', '6H', '7H', '8H', JOKER])); + expect(s.shuffles.B).toBe(3); + expect(s.turnStartedAt).toBe(startedAt); + expect(reject(s, 'B', { type: 'shuffle' })).toContain('3번까지'); + expect(reject(s, 'C', { type: 'shuffle' })).toContain('2장 이상'); + expect(game.view(s, 'B').my!.shufflesLeft).toBe(0); + s = draw(s, 'A', 0); + expect(game.view(s, 'B').my!.shufflesLeft).toBe(3); + expect(reject(s, 'B', { type: 'shuffle' })).toBeNull(); + expect(s.log.filter((e) => e.t === 'shuffle')).toHaveLength(3); + }); + + test('남이 보는 자리 = 실제 손패 순서: 섞은 뒤 같은 자리를 뽑으면 섞인 순서의 카드', () => { + let s = rigged({ A: ['2H'], B: ['4H', '5H', '6H', '7H', X()], C: ['9C'] }); + s = act(s, 'B', { type: 'shuffle' }, rng(3)); + const at2 = s.hands.B![2]!; + s = draw(s, 'A', 2); + expect(s.lastDraw!.card).toBe(at2); + }); +}); + +// ---------------------------------------------------------------- timeout / leave + +describe('시간 초과·나가기 (§8.5)', () => { + test('시간 초과 → 무작위 한 장 뽑기; 3번 연속이면 자리 비움(5초), 직접 뽑으면 해제', () => { + let s = rigged({ A: ['2H', '3H', '4H', '5H'], B: ['6H', '7H', '8H', '9H', X()], C: ['2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S'] }); + expect(game.onTimeout(s, 'A')).toEqual({ type: 'timeout' }); + expect(reject(s, 'B', { type: 'timeout' })).toContain('시간 초과 대상이 아니에요'); + let ev = actE(s, 'A', { type: 'timeout' }); + s = ev.state; + expect(s.lastDraw).toMatchObject({ drawer: 'A', from: 'B', auto: true }); + expect(ev.events.some((e) => e.type === 'timeout')).toBe(true); + expect(s.timeoutsInRow.A).toBe(1); + // Everybody times out until A has done it 3 times in a row. + while ((s.timeoutsInRow.A ?? 0) < 3 && !s.final) s = act(s, s.turn!, { type: 'timeout' }); + if (!s.final) { + expect(s.away.A).toBe(true); + while (!s.final && s.turn !== 'A') s = act(s, s.turn!, { type: 'timeout' }); + if (!s.final) { + expect(game.deadline!(s)).toBe(s.turnStartedAt + 5000); + s = draw(s, 'A', 0); + expect(s.away.A).toBe(false); + } + } + }); + + test('모두 시간 초과만 해도 끝나고, 모든 상태에서 onTimeout이 합법', () => { + for (const n of [2, 5, 8]) { + let s = setup(Array.from({ length: n }, (_, i) => `P${i}`), n); + let steps = 0; + while (!s.final && steps < 5000) { + const p = game.timeoutPlayers!(s)[0]!; + expect(reject(s, p, game.onTimeout(s, p))).toBeNull(); + s = act(s, p, game.onTimeout(s, p)); + checkInvariants(s); + steps++; + } + expect(s.final?.thief).toBeTruthy(); + } + }); + + test('카드를 든 사람이 나가면 그 카드를 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고 짝을 버림', () => { + let s = rigged({ A: ['2H', '3H'], B: ['4H', '5H', '6H', X()], C: ['4S', '7S'], D: ['5S', '8S'] }, 'B'); + expect(game.onLeave!(s, 'B')).toEqual({ type: 'leave' }); + const { state, events } = actE(s, 'B', { type: 'leave' }); + s = state; + checkInvariants(s, false); + expect(s.left).toEqual(['B']); + expect(s.hands.B).toEqual([]); + // 4 cards → C, D, A, C (from the next seat). C/D may pair 4s / 5s. + const e = s.log.find((x) => x.t === 'left')!; + expect(e.t === 'left' && e.gave).toEqual([ + { to: 'C', count: 2 }, + { to: 'D', count: 1 }, + { to: 'A', count: 1 }, + ]); + expect(s.turn).toBe('C'); + expect(targetOf(s, 'A')).toBe('C'); + expect(events.some((x) => x.type === 'left')).toBe(true); + expect(game.view(s, 'A').status.B).toBe('left'); + }); + + test('2명 중 한 사람이 나가면 남은 사람이 위, 나간 사람이 아래, 도둑 없음(resign)', () => { + let s = rigged({ A: ['2H', X()], B: ['3S', '4S'] }); + s = act(s, 'B', { type: 'leave' }); + const r = game.result(s)!; + expect(r.ranking).toEqual([['A'], ['B']]); + expect(r.reason).toBe('resign'); + expect(s.final!.thief).toBeNull(); + expect(r.scoreText!.B).toBe('나감'); + expect(r.summary).toContain('나가서'); + }); + + test('이미 다 턴 사람이 나가면 아무 일도 없음(onLeave null)', () => { + let s = rigged({ A: ['7H'], B: ['7D'], C: ['9C', X()], D: ['9S'] }); + s = draw(s, 'A', 0); + expect(game.onLeave!(s, 'B')).toBeNull(); + expect(game.onLeave!(s, 'C')).toEqual({ type: 'leave' }); + }); + + test('3명 이상에서 나가면 남은 사람끼리 계속, 결과에는 나간 사람이 맨 아래', () => { + // Every card but the joker still has its partner somewhere, like in a real game. + let s = rigged({ A: ['2H', '3H'], B: ['4H', X(), '3S'], C: ['2S', '4S'] }); + s = act(s, 'C', { type: 'leave' }); + checkInvariants(s, false); + expect(s.final).toBeNull(); + while (!s.final) s = act(s, s.turn!, { type: 'timeout' }); + const r = game.result(s)!; + expect(r.ranking.at(-1)).toEqual(['C']); + expect(r.ranking.flat().sort()).toEqual(['A', 'B', 'C']); + expect(s.final!.thief).not.toBeNull(); + }); +}); + +// ---------------------------------------------------------------- privacy + +describe('비공개 정보 (§8.3)', () => { + test('남의 손패는 장수만; 뽑은 카드는 뽑은 사람만(짝이 나면 모두), 관전자는 손패 없음', () => { + let s = rigged({ A: ['2H', '3H'], B: ['9C', '4D', X()], C: ['5S', '6S'] }); + const vA = game.view(s, 'A'); + expect(vA.myHand).toEqual(['2H', '3H']); + expect(vA.handCounts).toEqual({ A: 2, B: 3, C: 2 }); + expect(JSON.stringify(vA)).not.toContain('"9C"'); + expect(JSON.stringify(game.view(s, null))).not.toContain('"2H"'); + expect(game.view(s, null).myHand).toBeNull(); + expect(vA.my).toMatchObject({ canDraw: true, from: 'B', count: 3 }); + expect(game.view(s, 'C').my).toMatchObject({ canDraw: false, from: null, count: 0 }); + s = draw(s, 'A', 0); // 9C, no pair + expect(game.view(s, 'A').lastDraw!.card).toBe('9C'); + expect(game.view(s, 'B').lastDraw!.card).toBeNull(); + expect(game.view(s, 'C').lastDraw!.card).toBeNull(); + expect(game.view(s, null).lastDraw!.card).toBeNull(); + expect(JSON.stringify(game.view(s, 'C'))).not.toContain('"9C"'); + s = act(s, 'B', { type: 'draw', from: 'C', index: 1 }); // 6S, no pair for B + s = act(s, 'C', { type: 'draw', from: 'A', index: s.hands.A!.indexOf('9C') }); // C has 5S → no pair + expect(game.view(s, 'B').lastDraw!.card).toBeNull(); + }); + + test('무작위 진행 중 모든 view와 이벤트에 남의 손패가 없음', () => { + for (let seed = 1; seed <= 6; seed++) { + const players = Array.from({ length: 2 + (seed % 7) }, (_, i) => `P${i}`); + let s = setup(players, seed); + const chooser = SeededRng.fromSeed(seedN(seed + 99)); + for (let step = 0; step < 3000 && !s.final; step++) { + const actor = s.turn!; + const legal = game.legalActions!(s, actor); + const out = actE(s, actor, legal[chooser.int(legal.length)]!, rng(step)); + for (const e of out.events) { + const ej = JSON.stringify(e); + for (const p of players) for (const c of out.state.hands[p]!) if (ej.includes(JSON.stringify(c))) throw new Error(`event ${e.type} leaks ${c}`); + } + s = out.state; + } + expect(s.final).not.toBeNull(); + } + }); +}); + +// ---------------------------------------------------------------- schema + +describe('옵션·스키마', () => { + test('모든 옵션에 한국어 메타; 기본값', () => { + const shape = (game.optionsSchema as unknown as { shape: Record }).shape; + for (const [k, v] of Object.entries(shape)) expect(v.meta()?.title, k).toBeTruthy(); + expect(game.defaultOptions).toEqual({ turnSeconds: 20 }); + expect(game.optionsSchema.safeParse({ turnSeconds: 15 }).success).toBe(false); + }); + + test('클라이언트 행동만 스키마에 있음', () => { + expect(game.actionSchema.safeParse({ type: 'draw', from: 'B', index: 3 }).success).toBe(true); + expect(game.actionSchema.safeParse({ type: 'draw', from: 'B', index: 1.5 }).success).toBe(false); + expect(game.actionSchema.safeParse({ type: 'shuffle' }).success).toBe(true); + expect(game.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false); + expect(game.actionSchema.safeParse({ type: 'leave' }).success).toBe(false); + }); +}); + +// ---------------------------------------------------------------- properties + +describe('무작위 대국 (docs/09 §7)', () => { + const SEEDS = playoutSeeds(300); + test(`engine randomPlayout, seeds 1–${SEEDS}, 2~8명: 끝남, 카드 보존, 유출 없음, onTimeout 합법, 결정성`, () => { + for (let i = 1; i <= SEEDS; i++) { + const players = Array.from({ length: 2 + (i % 7) }, (_, k) => `P${k}`); + const invariant = (st: unknown) => { + checkInvariants(st); + const s = st as OldMaidState; + for (const p of game.timeoutPlayers!(s)) if (reject(s, p, game.onTimeout(s, p))) throw new Error('onTimeout illegal'); + }; + const r = randomPlayout(game, { players, seed: seedN(i), maxSteps: 3000, invariant, maxApplyMs: 50 }); + expect(r.finished).toBe(true); + const s = r.finalState as OldMaidState; + const res = game.result(s)!; + expect(res.ranking.flat().sort()).toEqual([...players].sort()); + expect(res.ranking.at(-1)).toEqual([s.final!.thief!]); + expect(holdsJoker(s, s.final!.thief!)).toBe(true); + if (i % 10 === 1) { + const b = randomPlayout(game, { players, seed: seedN(i), maxSteps: 3000, maxApplyMs: 50 }); + expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(r.finalState)); + } + } + }, 60_000); + + test('같은 시드 + 같은 행동 기록 = 같은 결과(나가기 섞음)', () => { + for (let i = 1; i <= 20; i++) { + const players = Array.from({ length: 3 + (i % 6) }, (_, k) => `P${k}`); + const r = SeededRng.fromSeed(seedN(i)); + const chooser = SeededRng.fromSeed(seedN(i + 5000)); + let s = game.setup({ players, options: game.defaultOptions, rng: r, now: 0 }); + const log: { actor: string; action: OldMaidAction }[] = []; + for (let step = 0; step < 3000 && !s.final; step++) { + let actor = s.turn!; + let a: OldMaidAction; + const roll = chooser.int(40); + if (roll === 0) { + const leaver = players.find((p) => game.onLeave!(s, p)); + actor = leaver!; + a = { type: 'leave' }; + } else if (roll < 5) a = game.onTimeout(s, actor); + else { + const legal = game.legalActions!(s, actor); + a = legal[chooser.int(legal.length)]!; + } + expect(reject(s, actor, a)).toBeNull(); + s = game.apply(s, actor, a, { rng: r, now: step * 1000 }).state; + log.push({ actor, action: a }); + checkInvariants(s); + } + expect(s.final).not.toBeNull(); + const r2 = SeededRng.fromSeed(seedN(i)); + let t = game.setup({ players, options: game.defaultOptions, rng: r2, now: 0 }); + log.forEach(({ actor, action }, k) => (t = game.apply(t, actor, action, { rng: r2, now: k * 1000 }).state)); + expect(JSON.stringify(t)).toBe(JSON.stringify(s)); + } + }); +}); diff --git a/packages/games/src/old-maid/types.ts b/packages/games/src/old-maid/types.ts new file mode 100644 index 0000000..45d4728 --- /dev/null +++ b/packages/games/src/old-maid/types.ts @@ -0,0 +1,128 @@ +/** 도둑잡기 options, actions, state and view types (docs/games/old-maid.md §2, §8). */ +import { z } from 'zod'; +import type { PlayerId } from '@bg/engine'; + +/** Trump 52 + one joker ("X1"). */ +export const DECK_SIZE = 53; +export const JOKER = 'X1'; +/** Shuffles of one's own hand per player per turn (keeps the log and the traffic small). */ +export const SHUFFLES_PER_TURN = 3; +/** Public log entries kept in the state. */ +export const LOG_KEEP = 30; + +// ---------------------------------------------------------------- options + +export const oldMaidOptionsSchema = z.object({ + turnSeconds: z + .union([z.literal(10), z.literal(20), z.literal(30), z.literal(60)]) + .default(20) + .meta({ title: '한 번 뽑는 제한 시간', labels: { 10: '10초', 20: '20초', 30: '30초', 60: '60초' } }), +}); +export type OldMaidOptions = z.infer; + +// ---------------------------------------------------------------- actions + +export const oldMaidActionSchema = z.discriminatedUnion('type', [ + /** Draw the card at `index` (0 = leftmost as the owner holds it) from `from`'s face-down hand. */ + z.object({ type: z.literal('draw'), from: z.string().max(64), index: z.number().int().min(0).max(DECK_SIZE) }), + /** Shuffle my own hand (anyone still holding 2+ cards, any time). */ + z.object({ type: z.literal('shuffle') }), +]); +export type OldMaidClientAction = z.infer; +/** Client actions plus system-only actions (timer / leaving), which are not in the schema. */ +export type OldMaidAction = OldMaidClientAction | { type: 'timeout' } | { type: 'leave' }; +export type DrawAction = Extract; + +// ---------------------------------------------------------------- state + +export type LogEntry = + /** A draw. `pair` = the two cards thrown away right after it (public), null when the drawn card stayed hidden. */ + | { t: 'draw'; no: number; drawer: PlayerId; from: PlayerId; index: number; pair: [string, string] | null; auto: boolean } + | { t: 'out'; player: PlayerId; place: number } + | { t: 'shuffle'; player: PlayerId } + /** Someone left with cards: their cards were dealt face down to `to` (counts only), pairs thrown away. */ + | { t: 'left'; player: PlayerId; gave: { to: PlayerId; count: number }[]; pairs: [string, string][] }; + +export interface LastDraw { + no: number; + drawer: PlayerId; + from: PlayerId; + index: number; + /** The drawn card. Secret (only in the drawer's view) unless it made a pair. */ + card: string; + pair: [string, string] | null; + auto: boolean; +} + +export interface OldMaidFinal { + /** Who was left holding the joker; null when the game ended because players left. */ + thief: PlayerId | null; + reason: 'normal' | 'left'; + ranking: PlayerId[][]; + summary: string; +} + +export interface OldMaidState { + options: OldMaidOptions; + order: PlayerId[]; + /** Hands in the order the owner holds them (left to right). Others pick by position. */ + hands: Record; + /** Pairs each player threw away, in order (public). */ + discards: Record; + /** Players who emptied their hand, in finishing groups (same group = same moment). */ + out: PlayerId[][]; + /** Players who left the game while still holding cards. */ + left: PlayerId[]; + /** Whose turn it is (draws from `targetOf(turn)`); null once finished. */ + turn: PlayerId | null; + turnNo: number; + shuffles: Record; + /** Shuffles per player during the current turn (reset every turn). */ + shufflesThisTurn: Record; + lastDraw: LastDraw | null; + log: LogEntry[]; + /** Log entries ever written (the log keeps only the last LOG_KEEP). */ + logCount: number; + timeoutsInRow: Record; + away: Record; + turnStartedAt: number; + seq: number; + final: OldMaidFinal | null; +} + +// ---------------------------------------------------------------- view + +export type SeatStatus = 'playing' | 'out' | 'left'; + +export interface OldMaidView { + options: OldMaidOptions; + me: PlayerId | null; + order: PlayerId[]; + phase: 'playing' | 'finished'; + turn: PlayerId | null; + /** The player the turn player draws from. */ + target: PlayerId | null; + turnNo: number; + handCounts: Record; + pairCounts: Record; + status: Record; + /** Finishing place (1 = first out) for players who emptied their hand. */ + places: Record; + shuffles: Record; + /** My hand in my order (null for spectators). */ + myHand: string[] | null; + /** The last draw; `card` only for the drawer (or once it made a pair). */ + lastDraw: (Omit & { card: string | null }) | null; + /** What I can do now (null for spectators and finished games). */ + my: { canDraw: boolean; from: PlayerId | null; count: number; canShuffle: boolean; shufflesLeft: number } | null; + log: LogEntry[]; + /** Log entries ever written: the screen tells new entries from old ones with it. */ + logCount: number; + away: Record; + turnStartedAt: number; + turnMs: number; + seq: number; + final: OldMaidFinal | null; + /** After the game: what everyone still held (only the joker with the thief, or leftovers when someone left). */ + revealed: Record | null; +} diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index 296d260..37bf86f 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -49,6 +49,7 @@ export const BOT_GAMES: readonly string[] = [ 'las-vegas', 'cockroach-poker', 'ninety-nine', + 'old-maid', 'mafia', 'apple', 'clue', diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index 1fc2618..9b978f0 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -34,6 +34,7 @@ export const CATALOG: CatalogEntry[] = [ { id: 'las-vegas', nameKo: '라스베가스', minPlayers: 2, maxPlayers: 5, minutes: '20~30', level: '쉬움', blurb: '주사위를 같은 숫자 카지노에 몽땅! 개수가 같으면 둘 다 꽝 · 놀이용 지폐', available: true }, { id: 'cockroach-poker', nameKo: '바퀴벌레 포커', minPlayers: 2, maxPlayers: 6, minutes: '15~20', level: '쉬움', blurb: '벌레 카드를 건네며 "이건 쥐야!" 진짜일까 거짓말일까?', available: true }, { id: 'ninety-nine', nameKo: '구십구', minPlayers: 2, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '카드를 내며 숫자를 더해요. 99를 넘기면 탈락!', available: true }, + { id: 'old-maid', nameKo: '도둑잡기', minPlayers: 2, maxPlayers: 8, minutes: '5~10', level: '쉬움', blurb: '옆 사람 카드를 한 장씩 뽑아 짝을 버려요. 마지막에 조커를 든 사람이 도둑!', available: true }, { id: 'dobble', nameKo: '도블', minPlayers: 2, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '어느 두 카드에나 딱 하나 있는 같은 그림을 누구보다 빨리 콕!', available: true }, { 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 },