From 88db031d0a4e021196c167d0c7dc78f4204ebfdd Mon Sep 17 00:00:00 2001 From: EJClaw Date: Thu, 15 Oct 2026 19:33:32 +0900 Subject: [PATCH] =?UTF-8?q?=EC=83=88=20=EA=B2=8C=EC=9E=84=20=EC=A0=9D?= =?UTF-8?q?=EC=8A=A4=EB=8B=98=ED=8A=B8:=20=EC=88=AB=EC=9E=90=20=EC=B9=B4?= =?UTF-8?q?=EB=93=9C=EB=A5=BC=20=EB=8F=99=EC=8B=9C=EC=97=90=20=EB=AA=B0?= =?UTF-8?q?=EB=9E=98=20=EB=82=B4=EA=B3=A0=20=EC=9E=91=EC=9D=80=20=EC=88=98?= =?UTF-8?q?=EB=B6=80=ED=84=B0=20=EC=A4=84=20=EB=81=9D=EC=97=90=20=EB=B6=99?= =?UTF-8?q?=EC=9D=B4=EA=B8=B0,=20=EC=97=AC=EC=84=AF=20=EB=B2=88=EC=A7=B8?= =?UTF-8?q?=20=EC=B9=B4=EB=93=9C=EB=A9=B4=20=EC=95=9E=EC=9D=98=20=EB=8B=A4?= =?UTF-8?q?=EC=84=AF=20=EC=9E=A5(=EC=86=8C=EB=A8=B8=EB=A6=AC=20=3D=20?= =?UTF-8?q?=EB=B2=8C=EC=A0=90)=EC=9D=84=20=EA=B0=80=EC=A0=B8=EA=B0=80?= =?UTF-8?q?=EB=8A=94=202~10=EB=AA=85=20=EC=B9=B4=EB=93=9C=20=EA=B2=8C?= =?UTF-8?q?=EC=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 엔진 packages/games/src/six-nimmt/(options·rules·types·index·bot): 104장 소머리(합 171), 규칙 1~4, 동시에 몰래 고르기(모두 고르기 전엔 바꾸기 가능, 마지막 사람이 고르면 공개), 작은 카드 줄 고르기·양쪽 끝 같은 차이 자리 고르기에서 멈춤, 라운드 합산·66점(또는 라운드 수) 종료·20라운드 안전장치 - 옵션 전부: 카드 구성(104장/인원×10+4 섞기/펼쳐 골라 가기 프로 2~6명), 양쪽 끝 붙이기, 작은 카드 자동, 30주년판 특별 카드 4종(짝홀·산 오르기·점프하는 소 연쇄·숫자 뒤집기), 끝 점수/라운드 수, 나온 카드 표, 제한 시간 - 시간 초과·나가기: 지금 줄 기준 가장 안전한 카드·소머리 적은 줄, 3번이면 자리 비움(5초), 나간 사람은 바로 자동, 1명 남으면 끝 - 컴퓨터: 카드마다 상대 카드를 흉내 내어 가져갈 소머리 평균(1단계 4번 → 60단계 48번), humanBest 실수, 41단계 이상 숫자 뒤집기·대기 카드 보고 줄 고르기 - 화면 apps/web/src/games/six-nimmt/: 소머리 색 카드, 줄 4개 + 빨간 6번째 칸, 공개 카드 줄과 한 장씩 놓이는 재생(줄 빛남·흔들림·"+🐮" 배너·음매 소리), 손패 미리 보기("2번 줄 3번째"/"⚠ 가져감"/"⬇ 너무 작음"), 뒤집기 토글, 줄 고르기 버튼(추천), 프로 뽑기, 라운드 결과 창, 최종 표, 점수표·나온 카드 표·기록, 휴대폰 320px, 도움말·30초 요약 - 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·카드·패 탭, docs/games/README.md, 설계 문서에 정한 것 기록 - 테스트: 규칙 46개(문서 §10 예시 전부, 무작위 대국 옵션 7종 JSON 왕복·결정성·정보 누출·카드 총수·onTimeout 합법), 컴퓨터 25개(옵션 7종 × 2·5·10명, 60단계 대 1단계), 도움말 2개, 방 통합 4개, E2E six-nimmt·six-nimmt-pro Co-Authored-By: Claude Opus 5.5 --- apps/server/src/rooms/six-nimmt.room.test.ts | 129 +++ apps/web/src/games/help.test.ts | 2 +- apps/web/src/games/registry.ts | 1 + apps/web/src/games/six-nimmt/help.test.ts | 29 + apps/web/src/games/six-nimmt/help.ts | 46 + apps/web/src/games/six-nimmt/index.tsx | 987 ++++++++++++++++++ apps/web/src/games/six-nimmt/quick.tsx | 86 ++ apps/web/src/lib/catalog-ui.ts | 3 +- docs/games/README.md | 1 + docs/games/six-nimmt.md | 43 +- e2e/games.e2e.ts | 157 +++ packages/games/package.json | 1 + packages/games/src/bots/index.ts | 2 + packages/games/src/index.ts | 2 + packages/games/src/six-nimmt/bot.test.ts | 111 ++ packages/games/src/six-nimmt/bot.ts | 126 +++ packages/games/src/six-nimmt/index.ts | 705 +++++++++++++ packages/games/src/six-nimmt/options.ts | 54 + packages/games/src/six-nimmt/rules.ts | 249 +++++ .../games/src/six-nimmt/six-nimmt.test.ts | 584 +++++++++++ packages/games/src/six-nimmt/types.ts | 167 +++ packages/shared/src/bots.ts | 1 + packages/shared/src/catalog.ts | 1 + 23 files changed, 3467 insertions(+), 20 deletions(-) create mode 100644 apps/server/src/rooms/six-nimmt.room.test.ts create mode 100644 apps/web/src/games/six-nimmt/help.test.ts create mode 100644 apps/web/src/games/six-nimmt/help.ts create mode 100644 apps/web/src/games/six-nimmt/index.tsx create mode 100644 apps/web/src/games/six-nimmt/quick.tsx create mode 100644 packages/games/src/six-nimmt/bot.test.ts create mode 100644 packages/games/src/six-nimmt/bot.ts create mode 100644 packages/games/src/six-nimmt/index.ts create mode 100644 packages/games/src/six-nimmt/options.ts create mode 100644 packages/games/src/six-nimmt/rules.ts create mode 100644 packages/games/src/six-nimmt/six-nimmt.test.ts create mode 100644 packages/games/src/six-nimmt/types.ts diff --git a/apps/server/src/rooms/six-nimmt.room.test.ts b/apps/server/src/rooms/six-nimmt.room.test.ts new file mode 100644 index 0000000..1e80d2a --- /dev/null +++ b/apps/server/src/rooms/six-nimmt.room.test.ts @@ -0,0 +1,129 @@ +/** + * 젝스님트 through a real Room (docs/games/six-nimmt.md §10): practice games against computers played to the end from + * the person's own screen, with the simultaneous secret pick, the row choice, the pro draft and timeouts on the clock. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import type { SixNimmtAction, SixNimmtState, SixNimmtView } from '@bg/games/six-nimmt'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import { Room, type Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const db = openDb(':memory:'); + const store = new RoomStore(db); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { db, clock, manager, conn }; +} + +type StateMsg = Extract; +const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as SixNimmtView); + +/** What the person presses, read only from their own screen (the safest-looking card, or the fewest-bulls row). */ +function personMove(v: SixNimmtView, me: string, n: number): SixNimmtAction | null { + if (v.phase === 'draft') return v.draft!.at === me ? { type: 'DRAFT', card: v.draft!.pool[n % v.draft!.pool.length]! } : null; + if (v.phase === 'select') { + if (v.players[me]!.picked || !v.my) return null; + const hand = [...v.my.hand].sort((a, b) => (a.preview?.takes ?? 0) - (b.preview?.takes ?? 0)); + return { type: 'SELECT', card: hand[n % 2 === 0 ? 0 : hand.length - 1]!.n }; + } + const pd = v.pending; + if (v.phase !== 'choose' || !pd || pd.player !== me) return null; + if (pd.kind === 'place') return { type: 'PLACE', row: pd.choices[0]!.row, side: pd.choices[0]!.side }; + const best = v.rows.reduce((b, r, i) => (r.bulls < v.rows[b]!.bulls ? i : b), 0); + return { type: 'TAKE_ROW', row: best }; +} + +describe('젝스님트 room flow', () => { + test.each([ + [1, {}], + [3, { deck: 'pro', endMode: 'rounds', rounds: 2 }], + [4, { placement: 'both', lowCard: 'choose', endMode: 'rounds', rounds: 2 }], + ] as const)('컴퓨터 %i명과 연습 %j: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 카드는 공개 전까지 안 보여요', (nBots, options) => { + const h = harness(); + let room: Room; + if (nBots === 1) room = h.manager.createPractice('A', 'six-nimmt') as Room; + else { + const r = h.manager.create('A', 'six-nimmt', 'private'); + if (typeof r === 'string') throw new Error(r); + room = r; + expect(room.configure('A', { options: { ...GAMES['six-nimmt']!.defaultOptions, ...options } })).toBeNull(); + for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull(); + } + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bots = room.game!.players.filter(isBotId); + expect(bots).toHaveLength(nBots); + let cs = 0; + let seen = 0; + let mine = 0; + let chose = 0; + for (let i = 0; i < 60_000 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const vs = views(a); + for (const v of vs.slice(seen)) { + // A computer's secret pick never reaches my screen before the reveal. + for (const b of bots) expect(JSON.stringify(v)).not.toContain(`six-sel:${b}`); + expect(v.me).toBe('A'); + } + seen = vs.length; + const v = vs.at(-1); + const m = v && personMove(v, 'A', mine); + if (m) { + if (m.type === 'TAKE_ROW' || m.type === 'PLACE') chose++; + room.act('A', ++cs, m); + mine++; + } + } + expect(room.game!.finished).toBe(true); + expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]); + const s = room.game!.state as SixNimmtState; + expect(s.timeouts.A).toBe(0); // every step of the person was a real press + const last = views(a).at(-1)!; + expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort()); + expect(last.result!.ranking[0]!.total).toBe(Math.min(...s.seats.map((p) => s.totals[p]!))); + expect(mine).toBeGreaterThanOrEqual(10); + if (nBots === 1) expect(chose + mine).toBeGreaterThan(10); + const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!; + expect(JSON.parse(row.result_json).practice).toBe(true); + }); + + test('시간 초과: 사람이 아무것도 안 하면 제한 시간마다 자동으로 내고 3번이면 자리 비움', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'six-nimmt') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + for (let i = 0; i < 2000; i++) { + h.clock.advance(500); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + if ((room.game!.state as SixNimmtState).timeouts.A! >= 3) break; + } + const s = room.game!.state as SixNimmtState; + expect(s.timeouts.A).toBeGreaterThanOrEqual(3); + expect(views(a).at(-1)!.players.A!.away).toBe(true); + }); +}); diff --git a/apps/web/src/games/help.test.ts b/apps/web/src/games/help.test.ts index 29e2479..2f275af 100644 --- a/apps/web/src/games/help.test.ts +++ b/apps/web/src/games/help.test.ts @@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti const IDS = Object.keys(GAME_UI); test('모든 게임에 도움말이 있어요', () => { - expect(IDS).toHaveLength(34); + expect(IDS).toHaveLength(35); for (const id of IDS) { const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); expect(src, id).toMatch(/\bquickStart,/); diff --git a/apps/web/src/games/registry.ts b/apps/web/src/games/registry.ts index 36dbfa7..6d8b709 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -36,6 +36,7 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { liar: () => import('./liar'), 'magical-athlete': () => import('./magical-athlete'), blackjack: () => import('./blackjack'), + 'six-nimmt': () => import('./six-nimmt'), }; const cache = new Map(); diff --git a/apps/web/src/games/six-nimmt/help.test.ts b/apps/web/src/games/six-nimmt/help.test.ts new file mode 100644 index 0000000..8afe4a5 --- /dev/null +++ b/apps/web/src/games/six-nimmt/help.test.ts @@ -0,0 +1,29 @@ +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 ID = 'six-nimmt'; +const users = usersOf(['A', 'B', 'C']); +const view = (s: unknown, who: string | null) => GAMES[ID]!.view(s, who) as any; + +test('젝스님트: 고르기 / 낸 뒤 기다리기 / 관전', () => { + let { state } = setupGame(ID, 3); + expect(helpNow(view(state, 'A'), 'A', users)).toContain('[이 카드 내기]'); + state = applyAction(ID, state, 'A', { type: 'SELECT', card: state.hands.A[0] }); + expect(helpNow(view(state, 'A'), 'A', users)).toContain('바꿀 수 있어요'); + expect(helpNow(view(state, null), null, users)).toContain('몰래 골라요'); +}); + +test('젝스님트: 너무 작은 카드면 줄 고르기 안내', () => { + let { state } = setupGame(ID, 3); + state.rows = [[90], [91], [92], [93]]; + state.hands.A = [1, ...state.hands.A.filter((c: number) => c !== 1 && c < 90).slice(0, 9)]; + for (const p of ['B', 'C']) state.hands[p] = state.hands[p].filter((c: number) => c > 1 && c < 90); + state = applyAction(ID, state, 'A', { type: 'SELECT', card: 1 }); + state = applyAction(ID, state, 'B', { type: 'SELECT', card: state.hands.B[0] }); + state = applyAction(ID, state, 'C', { type: 'SELECT', card: state.hands.C[0] }); + expect(state.phase).toBe('choose'); + expect(helpNow(view(state, 'A'), 'A', users)).toContain('통째로 가져가야 해요'); + expect(helpNow(view(state, 'B'), 'B', users)).toContain('고르는 중이에요'); +}); diff --git a/apps/web/src/games/six-nimmt/help.ts b/apps/web/src/games/six-nimmt/help.ts new file mode 100644 index 0000000..fc27964 --- /dev/null +++ b/apps/web/src/games/six-nimmt/help.ts @@ -0,0 +1,46 @@ +/** 젝스님트 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { SixNimmtView } from '@bg/games/six-nimmt'; +import type { PublicUser } from '@bg/shared/lite'; + +export function helpNow(v: SixNimmtView, me: string | null, players: Record): string { + const name = (p: string) => `${players[p]?.nickname ?? '다른 사람'}님`; + const seated = !!me && v.seats.includes(me); + const goal = + v.options.endMode === 'score' + ? `누군가 벌점 ${v.options.endScore}점 이상이 되면 그 라운드 끝에 게임이 끝나요. 벌점이 가장 적은 사람이 이겨요.` + : `${v.options.rounds}라운드를 하고 벌점이 가장 적은 사람이 이겨요.`; + const score = seated ? `지금 내 벌점은 ${v.players[me!]!.total}점${v.players[me!]!.roundBulls ? `, 이번 라운드에 가져간 소머리 ${v.players[me!]!.roundBulls}개` : ''}예요.` : ''; + + if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.'; + if (seated && v.players[me!]!.left) return '나는 그만해서 구경만 할 수 있어요. 남은 카드는 자동으로 나가요.'; + + if (v.phase === 'draft') { + const d = v.draft!; + const head = `${v.round}라운드 카드 골라 가기예요. 펼쳐진 카드에서 차례로 한 장씩 가져가 각자 10장을 만들어요. 남은 4장이 줄의 첫 카드가 돼요.`; + if (seated && d.at === me) return `${head}\n지금 내가 가져갈 차례예요. 카드를 누르면 바로 내 카드가 돼요. 소머리가 적은 카드, 숫자가 고르게 퍼진 카드가 무난해요.\n${score}`; + return `${head}\n지금은 ${name(d.at)}이 고르는 중이에요.\n${goal}`; + } + + const lines: string[] = []; + if (v.phase === 'select') { + lines.push(`${v.round}라운드 ${v.turn}번째 카드예요. 모두 손패에서 한 장을 몰래 골라요. 모두 고르면 한꺼번에 공개되고, 작은 수부터 끝 카드가 가장 가까운 줄에 붙어요.`); + if (!seated) lines.push(goal); + else if (v.my?.selected) lines.push(`나는 ${v.my.selected.card}${v.my.selected.flip ? '(숫자 뒤집기)' : ''}을(를) 냈어요. 다른 사람이 모두 고를 때까지 다른 카드를 눌러 바꿀 수 있어요.`); + else { + lines.push('카드를 누르면 올라와요. 한 번 더 누르거나 [이 카드 내기]를 누르면 내요.'); + lines.push('카드 아래 표시는 지금 줄 모양 그대로일 때 어디에 붙는지예요. "⚠ 가져감"은 여섯 번째가 되어 벌점을 받는 카드, "⬇ 너무 작음"은 줄 하나를 가져와야 하는 카드예요.'); + if (v.options.fanCard === 'flipDigits' && v.players[me!]!.flipLeft) lines.push('[🔄 뒤집기]를 켜고 내면 이번 라운드에 한 번 카드 숫자를 뒤집어 낼 수 있어요(31 → 13).'); + } + } else { + const pd = v.pending!; + if (pd.player === me) { + lines.push( + pd.kind === 'takeRow' + ? `내 카드 ${pd.play.card}이(가) 모든 줄의 끝 카드보다 작아요. 줄 하나를 골라 통째로 가져가야 해요. 소머리가 가장 적은 줄에 "추천"이 붙어 있어요. 내 카드가 그 줄의 새 첫 카드가 돼요.` + : `내 카드 ${pd.play.card}을(를) 놓을 수 있는 자리가 두 곳이에요(차이가 같아요). 반짝이는 자리 중 하나를 눌러요.`, + ); + } else lines.push(`${name(pd.player)}이 ${pd.kind === 'takeRow' ? '가져갈 줄을' : '카드를 놓을 자리를'} 고르는 중이에요. 남은 공개 카드는 그다음에 놓여요.`); + } + if (score) lines.push(score); + return lines.join('\n'); +} diff --git a/apps/web/src/games/six-nimmt/index.tsx b/apps/web/src/games/six-nimmt/index.tsx new file mode 100644 index 0000000..a23ecaf --- /dev/null +++ b/apps/web/src/games/six-nimmt/index.tsx @@ -0,0 +1,987 @@ +/** 젝스님트 화면 (docs/games/six-nimmt.md §9). Penalty points (소머리) are play points of this room only. */ +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import type { LogEntry, Marker, Pending, SixHandCard, SixNimmtOptions, SixNimmtView } from '@bg/games/six-nimmt'; +import { bulls as bullsOfCard, type Card, type Preview, type Step } from '@bg/games/six-nimmt/rules'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar, ConfirmSheet } from '../../components/ui'; +import { TurnTimer } from '../../components/TurnTimer'; +import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; +import { fxMs } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +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, me: string | null, p: string) => (p === me ? '나' : nick(players, p)); +const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches; +const ROW_NAMES = ['1번 줄', '2번 줄', '3번 줄', '4번 줄']; + +/** Sounds on top of the shared palette (site volume applies). */ +const sxSound = { + /** A card put on a row. */ + place: () => { + noise(60, 0.14, 0, 'bandpass', 1400, 0.9); + tone(260, 50, 'triangle', 0.08); + }, + /** "음매": lower and longer the more cows were taken. */ + moo: (n: number) => { + const ms = Math.min(900, 380 + n * 40); + const f = Math.max(110, 230 - n * 8); + tone(f, ms, 'sawtooth', 0.06, 0, { slideTo: f * 0.72 }); + tone(f * 1.5, ms * 0.8, 'sine', 0.05, 30, { slideTo: f * 1.05 }); + }, + /** The fan card / cow moving. */ + hop: () => tone(520, 160, 'sine', 0.08, 0, { slideTo: 980 }), +}; + +// ---------------------------------------------------------------- cards + +const toneOf = (b: number) => (b >= 7 ? 'b7' : b >= 5 ? 'b5' : b >= 3 ? 'b3' : b >= 2 ? 'b2' : 'b1'); +const bullText = (b: number) => (b > 1 ? `🐮${b}` : '🐮'); + +function NumCard({ n, size = 'row', flipped, cls = '', label }: { n: Card; size?: 'row' | 'hand' | 'mini'; flipped?: number; cls?: string; label?: string }) { + const b = bullsOfCard(n); + return ( + + + {bullText(b)} + + + {flipped ?? n} + + {flipped !== undefined && ( + + 원래 {n} + + )} + + ); +} + +function markerLabel(m: Marker | null, row: number): string | null { + if (!m || m.row !== row) return null; + if (m.kind === 'evenOdd') return m.parity === 'even' ? '짝수만' : '홀수만'; + if (m.kind === 'mountain') return `산 오르기(작은 수)${m.dir === 'up' ? ' ▲' : ' ▼'}`; + return null; +} + +function MarkerIcon({ m, row }: { m: Marker | null; row: number }) { + if (!m || m.row !== row || m.kind === 'cow') return null; + const text = m.kind === 'evenOdd' ? (m.parity === 'even' ? '짝' : '홀') : m.dir === 'up' ? '⛰▲' : '⛰▼'; + return ( + + {text} + + ); +} + +// ---------------------------------------------------------------- reveal playback + +interface Playback { + /** Rows to draw (the live rows when nothing is being replayed). */ + rows: Card[][]; + marker: Marker | null; + /** Step being shown (its row glows, takes show a banner). */ + step: Step | null; + /** Cards of the revealed turn still waiting, in order (shown above the rows). */ + waiting: { player: string; card: Card; value: number; flip: boolean }[]; + /** True while the drawing is behind the view. */ + busy: boolean; +} + +/** + * The view already has the whole turn placed; the board replays it one card at a time (0.45 s each, hurried when far + * behind). A board that opens mid-game shows the current rows without replaying. + */ +function usePlayback(v: SixNimmtView): Playback { + const rv = v.reveal; + const [pos, setPos] = useState(() => ({ id: rv?.id ?? 0, shown: rv?.steps.length ?? 0 })); + const live = (): Playback => ({ rows: v.rows.map((r) => r.cards.map((c) => c.n)), marker: v.marker, step: null, waiting: v.queue.map((q) => ({ ...q })), busy: false }); + useEffect(() => { + if (!rv) return; + if (reducedMotion()) { + if (pos.id !== rv.id || pos.shown !== rv.steps.length) setPos({ id: rv.id, shown: rv.steps.length }); + return; + } + if (pos.id !== rv.id) { + setPos({ id: rv.id, shown: -1 }); + sfx.cardFlip(); + return; + } + if (pos.shown >= rv.steps.length) return; + const behind = rv.steps.length - pos.shown; + const t = setTimeout(() => setPos((p) => ({ ...p, shown: p.shown + 1 })), fxMs(pos.shown < 0 ? 650 : behind > 4 ? 220 : 450)); + return () => clearTimeout(t); + }, [rv?.id, rv?.steps.length, pos.id, pos.shown]); // eslint-disable-line react-hooks/exhaustive-deps + // Sound of the step just shown. + useEffect(() => { + if (!rv || pos.id !== rv.id || pos.shown < 0) return; + const st = rv.steps[pos.shown]; + if (!st) return; + if (st.t === 'place') { + if (st.took.length) { + sxSound.moo(st.bulls); + haptic(40); + } else sxSound.place(); + } else if (st.t === 'cow' && st.took.length) sxSound.moo(st.bulls); + else sxSound.hop(); + }, [pos.id, pos.shown]); // eslint-disable-line react-hooks/exhaustive-deps + // A new reveal is drawn from its start even before the effect above has caught up. + const cur = !rv ? pos : pos.id === rv.id ? pos : { id: rv.id, shown: reducedMotion() ? rv.steps.length : -1 }; + if (!rv || cur.shown >= rv.steps.length) return live(); + const placed = new Set(rv.steps.slice(0, Math.max(0, cur.shown + 1)).filter((s) => s.t === 'place').map((s) => (s as { card: Card }).card)); + const waiting = rv.plays.filter((p) => !placed.has(p.card)); + if (cur.shown < 0) return { rows: rv.before.rows, marker: rv.before.marker, step: null, waiting, busy: true }; + const st = rv.steps[cur.shown]!; + return { rows: st.rows, marker: st.marker, step: st, waiting, busy: true }; +} + +// ---------------------------------------------------------------- rows + +function Rows({ v, pb, me, players, act, pending, overlay }: { v: SixNimmtView; pb: Playback; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; overlay?: ReactNode }) { + const pd = v.pending; + const mine = !pb.busy && v.phase === 'choose' && pd && pd.player === me; + const fewest = mine && pd!.kind === 'takeRow' ? recommendRow(v) : -1; + const st = pb.step; + const glowRow = st ? (st.t === 'place' ? st.row : st.t === 'cow' ? st.to : st.to) : -1; + return ( +
+ {pb.rows.map((r, i) => { + const cow = pb.marker?.kind === 'cow' && pb.marker.row === i; + const slots = r.length + (cow ? 1 : 0); + const rb = r.reduce((t, c) => t + bullsOfCard(c), 0); + const ml = markerLabel(pb.marker, i); + const taking = st && st.t === 'place' && st.row === i && st.took.length > 0; + const choicesHere = mine && pd!.kind === 'place' ? pd!.choices.filter((c) => c.row === i) : []; + const placeL = choicesHere.find((c) => c.side === 'L'); + const placeR = choicesHere.find((c) => c.side === 'R'); + return ( +
= 5 ? ' full' : ''}`} aria-label={`${ROW_NAMES[i]}: ${r.join(', ')}${cow ? ', 소' : ''} · 소머리 ${rb}개${ml ? ` · ${ml}` : ''}${slots >= 5 ? ' · 다음 카드가 가져가요' : ''}`}> +
+ {i + 1} + 🐮{rb} + +
+
+ {placeL && ( + + )} + {r.map((c, k) => ( + + ))} + {cow && ( + + + 🐄 + + + )} + {placeR && ( + + )} + {Array.from({ length: Math.max(0, 6 - slots - (placeL ? 1 : 0) - (placeR ? 1 : 0)) }, (_, k) => ( + + {slots + k === 5 ? '6' : ''} + + ))} +
+ {mine && pd!.kind === 'takeRow' && ( + + )} +
+ ); + })} + {st && ((st.t === 'place' && st.took.length > 0) || (st.t === 'cow' && st.took.length > 0)) && ( +
+ {who(players, me, st.player)} +🐮{st.bulls} {st.t === 'cow' ? '(소가 뛰어서 한 줄 더!)' : st.why === 'low' ? '(너무 작은 카드)' : '(6번째 카드)'} +
+ )} + {overlay &&
{overlay}
} +
+ ); +} + +/** Fewest bulls, then the largest end card (the same row the timeout takes). */ +function recommendRow(v: SixNimmtView): number { + let best = 0; + v.rows.forEach((r, i) => { + const b = v.rows[best]!; + if (r.bulls < b.bulls || (r.bulls === b.bulls && r.cards.at(-1)!.n > b.cards.at(-1)!.n)) best = i; + }); + return best; +} + +// ---------------------------------------------------------------- players strip / revealed cards + +function Strip({ v, me, players, active, deadline }: { v: SixNimmtView; me: string | null; players: Record; active: string[]; deadline: number | null }) { + const playing = v.phase !== 'finished'; + return ( +
+ {v.seats.map((p) => { + const pv = v.players[p]!; + const on = playing && active.includes(p); + const state = pv.left ? '나감' : pv.away ? '자리 비움' : v.phase === 'select' ? (pv.picked ? '골랐어요' : '고르는 중') : v.phase === 'choose' && v.pending?.player === p ? '줄 고르는 중' : v.phase === 'draft' && v.draft?.at === p ? '카드 가져가는 중' : ''; + return ( +
+
+ + {who(players, me, p)} + {v.phase === 'select' && pv.picked && ( + + ✔ + + )} +
+
+ {pv.total} + 점 + {pv.roundBulls > 0 && +🐮{pv.roundBulls}} + {v.options.fanCard === 'flipDigits' && pv.flipLeft && 🔄} +
+ {state &&
{state}
} + {on && p === me && deadline && ( + + + + )} +
+ ); + })} +
+ ); +} + +function Revealed({ v, pb, me, players }: { v: SixNimmtView; pb: Playback; me: string | null; players: Record }) { + if (!pb.waiting.length) return null; + const pd = !pb.busy ? v.pending : null; + return ( +
+ 공개된 카드 +
+ {pb.waiting.map((p) => ( +
+ + {who(players, me, p.player)} +
+ ))} +
+
+ ); +} + +// ---------------------------------------------------------------- hand / draft + +function previewText(p: Preview | undefined): string { + if (!p) return ''; + if ('low' in p) return `⬇ 너무 작음`; + if (p.takes > 0) return `⚠ 가져감 🐮${p.takes}`; + return `${p.row + 1}번 줄 ${p.side === 'L' ? '왼쪽' : `${p.pos}번째`}${'tie' in p && p.tie ? '(고름)' : ''}`; +} + +function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean }) { + const my = v.my!; + const [pick, setPick] = useState(null); + const [flip, setFlip] = useState(false); + const sel = my.selected; + useEffect(() => { + setPick(null); + setFlip(false); + }, [v.round, v.turn]); + const open = v.phase === 'select'; + const canFlipNow = v.options.fanCard === 'flipDigits' && v.players[v.me!]!.flipLeft; + const chosen = pick ?? sel?.card ?? null; + const chosenCard = my.hand.find((h) => h.n === chosen); + const useFlip = flip && !!chosenCard?.flipped; + const send = (n: Card, f: boolean) => { + sfx.cardPlay(); + act({ type: 'SELECT', card: n, ...(f ? { flip: true } : {}) }); + setPick(null); + }; + const same = sel && chosen === sel.card && sel.flip === useFlip; + const tap = (h: SixHandCard) => { + if (!open || pending) return; + if (pick === h.n) send(h.n, flip && !!h.flipped); + else { + sfx.select(); + setPick(h.n); + } + }; + return ( +
+ {open && ( +

+ {sel ? `낸 카드: ${sel.card}${sel.flip ? '(뒤집기)' : ''} · 모두 내기 전에는 다른 카드를 눌러 바꿀 수 있어요.` : '카드를 누르면 올라와요. 한 번 더 누르거나 [이 카드 내기]로 내요.'} 카드 아래 표시는 지금 줄 기준이에요. 다른 사람 카드에 따라 달라져요. +

+ )} +
+ {my.hand.map((h) => { + const up = chosen === h.n; + const pv = flip && h.flipped ? h.flipped.preview : h.preview; + return ( + + ); + })} +
+ {open && ( +
+ {canFlipNow && ( + + )} + +
+ )} +
+ ); +} + +function Draft({ v, me, players, act, pending }: { v: SixNimmtView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean }) { + const d = v.draft!; + const mine = d.at === me; + const myCount = me && v.my ? v.my.hand.length : 0; + return ( +
+

{mine ? '내 차례예요. 펼쳐진 카드에서 한 장을 가져가세요' : `${nick(players, d.at)}님이 카드를 고르는 중이에요`}

+

+ 각자 10장이 될 때까지 차례로 한 장씩 가져가요. 남은 4장이 줄의 첫 카드가 돼요.{me && v.seats.includes(me) ? ` 내 카드 ${myCount}/10장.` : ''} +

+
+ {d.pool.map((n) => ( + + ))} +
+ {v.my && v.my.hand.length > 0 && ( +
+ 내 카드 +
+ {v.my.hand.map((h) => ( + + ))} +
+
+ )} +
+ ); +} + +// ---------------------------------------------------------------- round result / final + +function RoundResult({ v, me, players, onClose }: { v: SixNimmtView; me: string | null; players: Record; onClose: () => void }) { + const lr = v.lastRound!; + const end = v.options.endMode === 'score' ? v.options.endScore : null; + const max = Math.max(end ?? 0, ...v.seats.map((p) => v.players[p]!.total), 1); + return ( +
+
+ {lr.round}라운드 결과 + +
+
    + {v.seats.map((p) => { + const total = v.phase === 'finished' ? v.players[p]!.total : v.players[p]!.total; + return ( +
  • + {who(players, me, p)} + + + {end && } + + + +{lr.gained[p] ?? 0} → {total} + +
  • + ); + })} +
+ {end &&

누군가 {end}점 이상이 되면 그 라운드 끝에 게임이 끝나요.

} +
+ ); +} + +function FinalTable({ v, me, players }: { v: SixNimmtView; me: string | null; players: Record }) { + const r = v.result!; + const rounds = Math.max(...v.seats.map((p) => v.roundScores[p]!.length)); + return ( +
+

최종 결과

+

{r.summary}

+
+ + + + + + {Array.from({ length: rounds }, (_, i) => ( + + ))} + + + + + {r.ranking.map((row) => ( + + + + {Array.from({ length: rounds }, (_, i) => ( + + ))} + + + ))} + +
순위이름{i + 1}R벌점
{row.left ? '-' : `${row.rank}등`}{who(players, me, row.player)}{v.roundScores[row.player]![i] ?? ''} + {row.total} +
+
+ {v.bestTake && v.bestTake.bulls > 0 && ( +

+ 가장 크게 가져간 한 번: {who(players, me, v.bestTake.player)} · {v.bestTake.round}라운드에 한 번에 소머리 {v.bestTake.bulls}개! +

+ )} +
+ ); +} + +// ---------------------------------------------------------------- board + +function Board({ view: v, me, players, act, pending, active, deadline }: BoardProps) { + const pb = usePlayback(v); + const [roundShown, setRoundShown] = useState(v.lastRound?.round ?? 0); + const [roundOpen, setRoundOpen] = useState(false); + const prevTurn = useRef(v.turnSeq); + const prevPicked = useRef(0); + const [announce, setAnnounce] = useState(''); + + // Round result window: once the replay of the last turn is done, for 5 seconds (closable). + useEffect(() => { + if (!v.lastRound || v.lastRound.round === roundShown || pb.busy) return; + setRoundShown(v.lastRound.round); + setRoundOpen(true); + const t = setTimeout(() => setRoundOpen(false), 5000); + return () => clearTimeout(t); + }, [v.lastRound?.round, pb.busy]); // eslint-disable-line react-hooks/exhaustive-deps + + // Someone picked a card: a soft tap. + const pickedN = v.seats.filter((p) => v.players[p]!.picked).length; + useEffect(() => { + if (pickedN > prevPicked.current) sfx.chip(); + prevPicked.current = pickedN; + }, [pickedN]); + + useEffect(() => { + if (v.turnSeq === prevTurn.current) return; + prevTurn.current = v.turnSeq; + if (isMyTurn(v, me)) { + haptic(40); + if (document.visibilityState === 'hidden') sounds.myTurn(); + else tone(880, 70, 'triangle', 0.06); + } + }, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps + + // Screen readers: the latest takes. + const lastLog = v.log.at(-1)?.n ?? 0; + const prevLog = useRef(lastLog); + useEffect(() => { + if (lastLog <= prevLog.current) return; + const added = v.log.filter((e) => e.n > prevLog.current); + prevLog.current = lastLog; + const text = added.map((e) => logText(e, me, players)).filter(Boolean).slice(-3).join(' '); + if (text) setAnnounce(text); + }, [lastLog]); // eslint-disable-line react-hooks/exhaustive-deps + + const seated = !!me && v.seats.includes(me) && !v.players[me]!.left; + const pd = v.pending; + return ( +
+ +
+ {v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? `${v.round}라운드 · 카드 골라 가기` : `${v.round}라운드 · ${v.turn}/10번째 카드`} + + {v.options.endMode === 'score' ? `${v.options.endScore}점이 넘으면 끝` : `${v.options.rounds}라운드까지`} + {v.options.fanCard !== 'none' ? ` · ${FAN_KO[v.options.fanCard]}` : ''} + {v.options.placement === 'both' ? ' · 양쪽 끝' : ''} + +
+ + {v.result && } + {v.phase === 'draft' && v.draft ? ( + + ) : ( + <> + + {!pb.busy && v.phase === 'choose' && pd && ( +
+ {pd.player === me + ? pd.kind === 'takeRow' + ? `너무 작은 카드예요(${pd.play.value})! 가져갈 줄을 고르세요` + : `${pd.play.value}을(를) 놓을 자리가 두 곳이에요. 반짝이는 자리를 골라 주세요` + : `${nick(players, pd.player)}님이 ${pd.kind === 'takeRow' ? '가져갈 줄을' : '놓을 자리를'} 고르는 중…`} +
+ )} + setRoundOpen(false)} /> : null} /> + {seated && v.my && v.phase !== 'finished' && } + + )} +

+ {announce} +

+
+ ); +} + +const FAN_KO: Record = { none: '특별 카드 없음', evenOdd: '짝홀', mountain: '산 오르기', jumpingCow: '점프하는 소', flipDigits: '숫자 뒤집기' }; + +function logText(e: LogEntry, me: string | null, players: Record): string { + switch (e.t) { + case 'take': + return `${who(players, me, e.player)} ${ROW_NAMES[e.row]} ${e.cards.length}장 가져감 +🐮${e.bulls}${e.why === 'low' ? '(너무 작은 카드)' : e.why === 'cow' ? '(점프하는 소)' : ''}`; + case 'round': + return `${e.round}라운드 끝`; + case 'flip': + return `${who(players, me, e.player)} 숫자 뒤집기: ${e.card} → ${e.value}`; + case 'timeout': + return `${who(players, me, e.player)} 시간 초과(자동)`; + case 'left': + return `${who(players, me, e.player)} 나감`; + } +} + +// ---------------------------------------------------------------- side panel + +function Tracker({ v, me, players }: { v: SixNimmtView; me: string | null; players: Record }) { + if (!v.seen) return null; + const seen = new Set(v.seen); + const mine = new Set(v.my?.hand.map((h) => h.n) ?? []); + return ( +
+ 나온 카드 표 ({v.seen.length}/{v.deckMax}) +
+ {Array.from({ length: v.deckMax }, (_, i) => i + 1).map((n) => ( + + {n} + + ))} +
+ {v.options.deck === 'all' &&

104장 중 이번 라운드에 안 쓰는 카드가 섞여 있어요.

} + {v.known && ( +
+ {v.seats + .filter((p) => p !== me) + .map((p) => ( +
+ {nick(players, p)}의 남은 카드: {v.known![p]!.join(', ') || '없음'} +
+ ))} +
+ )} +
+ ); +} + +function Side({ view: v, me, players, act }: BoardProps) { + const [ask, setAsk] = useState(false); + const rounds = Math.max(0, ...v.seats.map((p) => v.roundScores[p]!.length)); + const playing = v.phase !== 'finished'; + return ( + <> +
+

점수표(벌점)

+
+ + + + + {Array.from({ length: rounds }, (_, i) => ( + + ))} + {playing && } + + + + + {v.seats.map((p) => ( + + + {Array.from({ length: rounds }, (_, i) => ( + + ))} + {playing && } + + + ))} + +
이름{i + 1}R지금합
{who(players, me, p)}{v.roundScores[p]![i] ?? ''}{v.players[p]!.roundBulls ? `+${v.players[p]!.roundBulls}` : ''} + {v.players[p]!.total} +
+
+
+ + {v.log.length > 0 && ( +
+

기록

+
    + {[...v.log] + .reverse() + .slice(0, 30) + .map((e) => ( +
  • + {logText(e, me, players)} +
  • + ))} +
+
+ )} + {playing && me && v.seats.includes(me) && !v.players[me]!.left && ( + + )} + {ask && ( + act({ type: 'LEAVE' })} + onClose={() => setAsk(false)} + /> + )} + + ); +} + +// ---------------------------------------------------------------- status + +function isMyTurn(v: SixNimmtView, me: string | null): boolean { + if (!me || v.phase === 'finished' || !v.players[me] || v.players[me]!.left) return false; + if (v.phase === 'draft') return v.draft?.at === me; + if (v.phase === 'select') return !v.players[me]!.picked; + return v.pending?.player === me; +} + +function pendingText(pd: Pending): string { + return pd.kind === 'takeRow' ? '가져갈 줄을' : '카드를 놓을 자리를'; +} + +function statusText(v: SixNimmtView, me: string | null, players: Record): string { + if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요'; + if (me && v.players[me]?.left) return '나갔어요. 구경하는 중이에요'; + const seated = !!me && v.seats.includes(me); + if (v.phase === 'draft') return isMyTurn(v, me) ? '내 차례예요. 펼쳐진 카드에서 한 장을 가져가세요' : `${nick(players, v.draft!.at)}님이 카드를 고르는 중이에요`; + if (v.phase === 'select') { + if (!seated) return '모두 낼 카드를 몰래 고르는 중이에요'; + return isMyTurn(v, me) ? '내 차례예요. 낼 카드를 한 장 골라 주세요' : '다른 사람이 고르기를 기다려요'; + } + const pd = v.pending!; + return pd.player === me ? `내 차례예요. ${pendingText(pd)} 골라 주세요` : `${nick(players, pd.player)}님이 ${pendingText(pd)} 고르는 중이에요`; +} + +// ---------------------------------------------------------------- options + +function Seg({ value, options, onChange, label, disabled }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string; disabled?: boolean }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} + +function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) { + return ( +
+ {label} + {children} + {help && {help}} +
+ ); +} + +function Options({ value: o, onChange }: OptionsProps) { + const set = (patch: Partial) => onChange({ ...o, ...patch }); + return ( +
+ + set({ deck })} /> + + + set({ placement, ...(placement === 'both' ? { fanCard: 'none' as const } : {}) })} /> + + + set({ lowCard })} /> + + + set({ fanCard })} /> + + + set({ endMode })} /> + + {o.endMode === 'score' ? ( + + [n, `${n}점`] as [typeof n, string])} onChange={(endScore) => set({ endScore })} /> + + ) : ( + + [n, `${n}라운드`] as [typeof n, string])} onChange={(rounds) => set({ rounds })} /> + + )} + + set({ cardTracker })} /> + + + set({ turnSeconds })} /> + +
+ ); +} + +const FAN_HELP: Record, string> = { + evenOdd: '짝홀 카드가 있는 줄에는 그 면(짝/홀)과 같은 카드만 놓여요. 누가 줄을 가져가면 옮겨 가요.', + mountain: '산 오르기 줄은 끝 카드보다 작은 수를 붙여요(내림차순). 누가 줄을 가져가면 한 줄씩 움직여요.', + jumpingCow: '소가 있는 줄에 카드가 놓이면 소는 끝 카드가 가장 작은 다른 줄로 뛰어가요. 소도 한 칸을 차지해요.', + flipDigits: '라운드에 한 번, 카드 숫자를 뒤집어 낼 수 있어요(31 → 13). 놓인 뒤에는 원래 숫자예요.', +}; + +function optionsSummary(o: SixNimmtOptions): string { + return [ + o.deck === 'all' ? '104장' : o.deck === 'tactics' ? '인원×10+4장' : '펼쳐 골라 가기', + o.placement === 'both' ? '양쪽 끝' : null, + o.lowCard === 'fewest' ? '작은 카드 자동' : null, + o.fanCard !== 'none' ? FAN_KO[o.fanCard] : null, + o.endMode === 'score' ? `${o.endScore}점에 끝` : `${o.rounds}라운드`, + o.cardTracker ? null : '카드 표 없음', + o.turnSeconds === null ? '시간 제한 없음' : `${o.turnSeconds}초`, + ] + .filter(Boolean) + .join(' · '); +} + +// ---------------------------------------------------------------- rules + +function Rules({ options }: { options?: SixNimmtOptions }) { + const o: SixNimmtOptions = { deck: 'all', placement: 'right', lowCard: 'choose', fanCard: 'none', endMode: 'score', endScore: 66, rounds: 3, cardTracker: true, turnSeconds: 30, ...(options ?? {}) }; + return ( +
+

+ 1부터 104까지 숫자 카드로 해요. 카드마다 소머리가 그려져 있고 이것이 벌점이에요(보통 1개, 5로 끝나면 2개, 10의 배수 3개, 11의 배수 5개, 55는 7개). 벌점이 적은 사람이 이겨요. +

+

+ 각자 10장을 받고, 판에는 줄 4개가 한 장씩으로 시작해요. 매번 모두 손패에서 한 장을 몰래 동시에 고르고, 모두 고르면 한꺼번에 공개해요. +

+

+ 공개된 카드는 작은 수부터 한 장씩 줄에 붙어요. 내 카드보다 끝 카드가 작은 줄 중 차이가 가장 작은 줄 끝에 붙어요. 예를 들어 끝 카드가 41, 42일 때 45는 42 다음이에요. +

+

+ 내 카드가 그 줄의 여섯 번째 카드가 되면 앞의 다섯 장을 가져가고(소머리만큼 벌점), 내 카드가 그 줄의 새 첫 카드가 돼요. +

+

+ 내 카드가 모든 줄의 끝 카드보다 작으면 {o.lowCard === 'choose' ? '원하는 줄 하나를 골라 통째로 가져가고' : '소머리가 가장 적은 줄을 자동으로 가져가고'}, 내 카드가 그 줄의 새 첫 카드가 돼요. +

+

+ 10장을 다 내면 라운드가 끝나고 가져간 소머리를 더해요.{' '} + {o.endMode === 'score' ? `누군가 ${o.endScore}점 이상이 되면 그 라운드 끝에 게임이 끝나요(20라운드가 지나도 끝).` : `${o.rounds}라운드를 하고 끝나요.`} 벌점이 같으면 함께 이겨요. +

+ {o.deck !== 'all' && ( +

+ {o.deck === 'pro' ? '프로 변형' : '전술 변형'}: 인원×10+4장(1부터)만 써요. + {o.deck === 'pro' ? ' 모든 카드를 펼쳐 놓고 시작하는 사람부터 차례로 한 장씩 가져가 10장을 만들어요. 남은 4장이 작은 수부터 줄의 첫 카드예요.' : ' 섞어서 나눠요.'} +

+ )} + {o.placement === 'both' && ( +

+ 양쪽 끝: 줄 왼쪽에는 첫 카드보다 작은 카드를 붙일 수 있어요. 오른쪽·왼쪽 중 차이가 가장 작은 자리에 놓이고, 차이가 같은 자리가 둘이면 직접 골라요. +

+ )} + {o.fanCard !== 'none' && ( +

+ {FAN_KO[o.fanCard]}: {FAN_HELP[o.fanCard]} + {o.fanCard === 'jumpingCow' && ' 소가 뛰어간 줄이 여섯 칸이 되면 소를 뛰게 한 사람이 가장 큰 카드만 남기고 그 줄도 가져가요.'} + {o.fanCard === 'flipDigits' && ' 한 자리 수는 0을 붙여 뒤집어요(7 → 70). 100 이상은 뒤집을 수 없어요.'} +

+ )} +

+ {o.cardTracker ? '오른쪽 [나온 카드 표]에서 이번 라운드에 나온 카드를 볼 수 있어요. ' : '나온 카드 표는 꺼져 있어요(원작처럼 기억으로). '} + {o.turnSeconds === null ? '이 방은 시간 제한이 없어요.' : `${o.turnSeconds}초 안에 고르지 않으면 지금 줄 기준으로 가장 안전한 카드가 자동으로 나가요.`} +

+

원작: 볼프강 크라머 「6 nimmt!」(AMIGO). 30주년판 특별 카드 아이디어: Guillaume Lefebvre, Daniela Bustos, Frank Heeren, Martin Profanter. 카드 그림과 규칙 문장은 이 사이트에서 새로 만들었어요.

+
+ ); +} + +// ---------------------------------------------------------------- styles + +const CSS = ` +.sx-wrap { width: 100%; max-width: 980px; display: flex; flex-direction: column; gap: 10px; } +.game-main:has(> .sx-wrap) { justify-content: flex-start; } +.sx-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; flex-wrap: wrap; padding: 8px 14px; } +.sx-strip { display: flex; gap: 6px; overflow-x: auto; padding: 2px; scrollbar-width: thin; } +@media (min-width: 720px) { .sx-strip { flex-wrap: wrap; overflow: visible; } } +.sx-player { position: relative; flex: 0 0 auto; min-width: 96px; max-width: 150px; background: var(--surface); border: 2px solid var(--border); border-radius: 12px; padding: 4px 8px; } +.sx-player.on { border-color: var(--focus); box-shadow: 0 0 0 2px color-mix(in srgb, var(--focus) 35%, transparent); } +.sx-player.me { background: var(--primary-soft); } +.sx-player.gone { opacity: .55; } +.sx-pl-top { display: flex; align-items: center; gap: 4px; min-width: 0; } +.sx-pl-name { font-weight: 700; font-size: .85rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; } +.sx-back { display: inline-flex; width: 18px; height: 24px; border-radius: 4px; background: #2f4f86; color: #fff; font-size: .7rem; align-items: center; justify-content: center; border: 1px solid #1d3461; } +.sx-pl-score { display: flex; align-items: baseline; gap: 3px; font-size: .85rem; } +.sx-pl-score b { font-size: 1.05rem; font-variant-numeric: tabular-nums; } +.sx-plus { color: var(--danger); font-weight: 700; } +.sx-pl-state { font-size: .75rem; color: var(--text-sub); white-space: nowrap; } +.sx-pl-timer { position: absolute; right: 4px; top: 50%; transform: translateY(-50%); } +.sx-player.timed { padding-right: 40px; } + +.sx-rows { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px; background: var(--felt); border-radius: 16px; padding: 8px; } +.sx-row { width: 100%; max-width: 480px; display: grid; grid-template-columns: 30px minmax(0, 1fr); gap: 4px; align-items: center; border-radius: 10px; padding: 2px; transition: background .2s; } +.sx-row.glow { background: rgba(255, 255, 255, .16); } +.sx-row.take { animation: sx-shake .45s ease both; background: rgba(239, 68, 68, .35); } +@keyframes sx-shake { 0%,100% { transform: none; } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } } +.sx-rowhead { display: flex; flex-direction: column; align-items: center; gap: 1px; color: #fff; font-size: .72rem; line-height: 1.1; } +.sx-rowhead b { font-size: 1rem; } +.sx-rowbulls { white-space: nowrap; } +.sx-mark { border-radius: 6px; padding: 1px 3px; font-weight: 900; font-size: .72rem; background: #fff; color: #1c1e21; white-space: nowrap; } +.sx-mark.mountain { background: #d9f99d; } +.sx-slots { display: grid; grid-template-columns: repeat(6, minmax(0, 64px)); gap: 4px; } +.sx-takebtn { grid-column: 2; justify-self: start; min-height: 40px; } +@media (min-width: 720px) { + .sx-row:has(.sx-takebtn) { max-width: 680px; grid-template-columns: 30px minmax(0, 1fr) auto; } + .sx-row .sx-takebtn { grid-column: 3; } +} +.sx-card { position: relative; display: inline-flex; flex-direction: column; align-items: center; justify-content: center; border-radius: 8px; border: 2px solid #3b3f46; color: #1c1e21; background: #fff; font-weight: 900; user-select: none; box-sizing: border-box; } +.sx-card.row { width: 100%; aspect-ratio: 5 / 7; } +.sx-card.hand { width: 100%; aspect-ratio: 5 / 7; } +.sx-card.mini { width: 40px; height: 54px; } +.sx-card.b2 { background: #cfe6ff; } +.sx-card.b3 { background: #fff0a3; } +.sx-card.b5 { background: #ffc98f; } +.sx-card.b7 { background: #ff9d9d; border-color: #9b1c1c; } +.sx-card.cow { background: #f1f5f9; border-style: dashed; } +.sx-card.new { animation: sx-in .35s ease-out both; box-shadow: 0 0 0 3px var(--focus); } +@keyframes sx-in { from { transform: translateY(-14px) scale(1.15); opacity: .3; } } +.sx-bulls { position: absolute; top: 2px; left: 0; right: 0; text-align: center; font-size: .62rem; font-weight: 700; line-height: 1; } +.sx-n { font-size: clamp(.95rem, 4.2vw, 1.5rem); line-height: 1; letter-spacing: -.03em; font-variant-numeric: tabular-nums; } +.sx-card.mini .sx-n { font-size: 1.05rem; } +.sx-card.mini .sx-bulls { font-size: .55rem; } +.sx-orig { position: absolute; bottom: 2px; font-size: .55rem; font-weight: 700; color: #334155; } +.sx-empty { aspect-ratio: 5 / 7; border-radius: 8px; border: 2px dashed rgba(255, 255, 255, .28); display: flex; align-items: center; justify-content: center; color: rgba(255, 255, 255, .5); font-weight: 900; } +.sx-empty.sixth { border-color: rgba(248, 113, 113, .7); background: rgba(248, 113, 113, .16); color: #fecaca; } +.sx-spot { aspect-ratio: 5 / 7; border-radius: 8px; border: 3px solid var(--focus); background: rgba(245, 158, 11, .25); color: #fff; font-weight: 900; font-size: .75rem; cursor: pointer; animation: sx-pulse 1s ease-in-out infinite; padding: 0; } +@keyframes sx-pulse { 50% { background: rgba(245, 158, 11, .55); } } +.sx-banner { border-radius: 12px; padding: 8px 12px; font-weight: 800; text-align: center; background: var(--warning-soft); color: var(--text); } +.sx-banner.mine { background: var(--danger-soft); border: 2px solid var(--danger); } +.sx-banner.take { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); background: var(--danger); color: #fff; font-size: 1.05rem; box-shadow: var(--shadow); white-space: nowrap; animation: sx-pop .3s ease-out both; pointer-events: none; z-index: 2; } +@keyframes sx-pop { from { transform: translate(-50%, -50%) scale(.6); opacity: 0; } } + +.sx-reveal { display: flex; align-items: center; gap: 8px; background: var(--surface); border-radius: 12px; padding: 6px 10px; border: 1px solid var(--border); overflow-x: auto; } +.sx-reveal-label { white-space: nowrap; } +.sx-reveal-cards { display: flex; gap: 6px; flex-wrap: nowrap; } +.sx-rv { display: flex; flex-direction: column; align-items: center; gap: 1px; animation: sx-flip .4s ease-out both; } +.sx-rv.pend .sx-card { box-shadow: 0 0 0 3px var(--danger); } +@keyframes sx-flip { from { transform: rotateY(90deg); } } +.sx-rv-name { font-size: .7rem; max-width: 52px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.sx-hand-wrap { display: flex; flex-direction: column; gap: 6px; } +.sx-hint { margin: 0; } +.sx-hand { display: grid; grid-template-columns: repeat(10, minmax(0, 72px)); gap: 6px; justify-content: center; padding-top: 12px; } +@media (max-width: 720px) { .sx-hand { grid-template-columns: repeat(5, minmax(0, 64px)); } } +.sx-hcard { all: unset; display: flex; flex-direction: column; align-items: center; gap: 2px; cursor: pointer; border-radius: 10px; transition: transform .15s; min-width: 0; } +.sx-hcard:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.sx-hcard:disabled { cursor: default; } +.sx-hcard.up { transform: translateY(-10px); } +.sx-hcard.up .sx-card { box-shadow: 0 0 0 3px var(--primary); } +.sx-hcard.sent .sx-card { outline: 3px dashed var(--success); outline-offset: 1px; } +.sx-pv { font-size: .68rem; line-height: 1.15; text-align: center; color: var(--text-sub); min-height: 2.3em; word-break: keep-all; } +.sx-pv.warn { color: var(--danger); font-weight: 800; } +.sx-hand-actions { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; } +.sx-send { min-width: 220px; flex: 1 1 220px; max-width: 420px; } +.sx-flip[aria-pressed="true"] { background: var(--primary-soft); border-color: var(--primary); } + +.sx-draft { display: flex; flex-direction: column; gap: 8px; padding: 12px; } +.sx-draft h3 { margin: 0; font-size: 1.05rem; } +.sx-pool { display: flex; flex-wrap: wrap; gap: 5px; } +.sx-poolbtn { all: unset; cursor: pointer; border-radius: 8px; } +.sx-poolbtn:focus-visible { outline: 3px solid var(--focus); } +.sx-poolbtn:disabled { cursor: default; opacity: .85; } +.sx-poolbtn:not(:disabled):hover .sx-card { transform: translateY(-3px); box-shadow: 0 0 0 3px var(--primary); } +.sx-mine { display: flex; flex-direction: column; gap: 4px; overflow-x: auto; } + +.sx-overlay { position: absolute; inset: 8px; display: flex; align-items: flex-start; justify-content: center; z-index: 3; pointer-events: none; } +.sx-overlay > * { pointer-events: auto; width: min(100%, 520px); box-shadow: var(--shadow); } +.sx-round { padding: 10px 14px; display: flex; flex-direction: column; gap: 6px; border: 2px solid var(--primary); } +.sx-round-head { display: flex; justify-content: space-between; align-items: center; } +.sx-bars { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; } +.sx-bars li { display: grid; grid-template-columns: minmax(0, 90px) 1fr auto; gap: 8px; align-items: center; font-size: .85rem; } +.sx-bar-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.sx-bar { position: relative; height: 12px; border-radius: 6px; background: var(--border); } +.sx-bar span { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 6px; background: var(--warning); } +.sx-bar i { position: absolute; top: -3px; bottom: -3px; width: 2px; background: var(--danger); } +.sx-bar-num { white-space: nowrap; font-variant-numeric: tabular-nums; } + +.sx-final { padding: 12px; display: flex; flex-direction: column; gap: 8px; } +.sx-final h3, .sx-scores h3, .sx-logbox h3 { margin: 0; font-size: 1rem; } +.sx-table-wrap { overflow-x: auto; } +.sx-table { border-collapse: collapse; width: 100%; font-size: .85rem; font-variant-numeric: tabular-nums; } +.sx-table th, .sx-table td { padding: 3px 6px; border-bottom: 1px solid var(--border); text-align: center; white-space: nowrap; } +.sx-table tr.win td { background: var(--success-soft); } +.sx-td-name { text-align: left !important; max-width: 110px; overflow: hidden; text-overflow: ellipsis; } +.sx-scores, .sx-logbox { padding: 12px; display: flex; flex-direction: column; gap: 6px; } +.sx-log { list-style: none; margin: 0; padding: 0; max-height: 220px; overflow-y: auto; display: flex; flex-direction: column; gap: 3px; font-size: .85rem; } +.sx-log li.take { color: var(--danger); } +.sx-log li.round { font-weight: 800; } +.sx-tracker { padding: 10px 12px; } +.sx-tracker summary { cursor: pointer; font-weight: 700; } +.sx-grid { display: grid; grid-template-columns: repeat(13, minmax(0, 1fr)); gap: 2px; margin: 8px 0; } +.sx-cell { font-size: .68rem; text-align: center; border-radius: 4px; padding: 2px 0; color: #1c1e21; background: #fff; border: 1px solid #c8c8c8; font-variant-numeric: tabular-nums; } +.sx-cell.b2 { background: #cfe6ff; } .sx-cell.b3 { background: #fff0a3; } .sx-cell.b5 { background: #ffc98f; } .sx-cell.b7 { background: #ff9d9d; } +.sx-cell.seen { opacity: .25; text-decoration: line-through; } +.sx-cell.mine { outline: 2px solid var(--primary); font-weight: 900; } +@media (max-width: 400px) { + .sx-rows { padding: 5px; gap: 4px; } + .sx-row { grid-template-columns: 24px minmax(0, 1fr); gap: 2px; } + .sx-slots { gap: 3px; } + .sx-rowhead { font-size: .62rem; } + .sx-card { border-width: 1.5px; border-radius: 6px; } +} +`; + +const ui: GameUI = { + Board, + Side, + statusText, + isMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/six-nimmt/quick.tsx b/apps/web/src/games/six-nimmt/quick.tsx new file mode 100644 index 0000000..587909f --- /dev/null +++ b/apps/web/src/games/six-nimmt/quick.tsx @@ -0,0 +1,86 @@ +/** 젝스님트 30초 규칙 요약 (docs/07 §5). */ +import type { QuickCard } from '../types'; + +const FILL: Record = { 1: '#ffffff', 2: '#cfe6ff', 3: '#fff0a3', 5: '#ffc98f', 7: '#ff9d9d' }; +const bulls = (n: number) => (n === 55 ? 7 : n % 11 === 0 ? 5 : n % 10 === 0 ? 3 : n % 5 === 0 ? 2 : 1); + +function C({ n, x, y, back, hl }: { n?: number; x: number; y: number; back?: boolean; hl?: string }) { + const b = n ? bulls(n) : 1; + return ( + + + {!back && n !== undefined && ( + <> + + {b > 1 ? `🐮${b}` : '🐮'} + + + {n} + + + )} + {back && ( + + ? + + )} + + ); +} + +export const quickStart: QuickCard[] = [ + { + pic: ( + + {['나', '민수', '지호', '서연'].map((t, i) => ( + + + + {t} + + + ))} + + 동시에 1장씩 몰래 → 한꺼번에 공개! + + + ), + alt: '네 사람이 뒷면 카드를 한 장씩 내고 한꺼번에 공개', + title: '동시에 1장 내기', + text: '모두 손패에서 한 장을 몰래 골라요. 모두 고르면 한꺼번에 공개돼요.', + }, + { + pic: ( + + 1줄 + + + 2줄 + + + 41 다음? ✗ + 42 다음 ✓ (차이 3) + 작은 수부터, 끝 카드가 가장 가까운 줄에 + + ), + alt: '45는 끝 카드 41이 아니라 더 가까운 42 다음에 붙음', + title: '가장 가까운 줄 끝에', + text: '공개된 카드는 작은 수부터, 끝 카드가 내 카드보다 작고 가장 가까운 줄에 붙어요. 45는 41이 아니라 42 다음!', + }, + { + pic: ( + + {[12, 14, 15, 21, 26].map((n, i) => ( + + ))} + + 6번째! + 앞의 5장을 가져가요 +🐮6 + 소머리 = 벌점, 적은 사람이 이겨요 + + ), + alt: '여섯 번째 카드 30을 낸 사람이 앞의 다섯 장(소머리 6개)을 가져감', + title: '6번째면 다섯 장을 가져가요', + text: '내 카드가 줄의 6번째가 되면 앞의 5장을 가져가요(소머리 = 벌점). 모든 줄보다 작으면 줄 하나를 골라 가져가요.', + }, +]; diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index 13dc3e4..2f0d013 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -33,6 +33,7 @@ export const GAME_ICON: Record = { liar: '🤥', 'magical-athlete': '🏃', blackjack: '🂡', + 'six-nimmt': '🐮', }; /** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */ @@ -41,6 +42,6 @@ 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', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] }, - { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] }, + { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt'] }, { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 9862aaf..7dcf5e0 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -47,6 +47,7 @@ | `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 | | `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 | | `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 | +| `six-nimmt` | 젝스님트 | 2~10 | 2026-10 새 게임 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/six-nimmt.md b/docs/games/six-nimmt.md index acb469b..ee77449 100644 --- a/docs/games/six-nimmt.md +++ b/docs/games/six-nimmt.md @@ -20,6 +20,9 @@ - 작은 카드로 줄을 고르는 일은 그 카드를 놓을 차례에 바로 한다(뒤 카드는 기다림). 원작 순서 그대로이고, 순서상 고르는 일은 보통 그 차례의 가장 작은 카드에만 생긴다(§5.3). - 숫자 뒤집기에서 한 자리 숫자(1~9)는 "0X"로 보고 X0이 된다(7 → 70). 원작은 31 → 13, 90 → 09 예만 있다. - 66점 모드에서도 20라운드가 지나면 끝낸다(2명 판이 너무 길어지지 않게 하는 안전장치). + - 나간 사람의 차례(고르기·줄 고르기·자리 고르기·뽑아 가기)는 1.2초를 기다리지 않고 그 자리에서 바로 자동으로 처리한다(§8.5 기본값과 같은 수). 고르기만 남은 사람이 모두 "자리 비움"이면 그 순간 마감을 5초로 줄인다. + - 숫자 뒤집기를 쓴 카드도 공개 순서는 뒤집은 수로 정하고, 놓인 뒤에는 원래 숫자가 그 줄의 끝 카드가 된다(그래서 그 뒤 카드는 원래 숫자 기준으로 줄을 찾는다. §10 예: 13(뒤집기 31)이 30 다음에 놓이면 그 줄 끝은 13이라 진짜 31은 다른 줄로 감). + - 게임이 끝난 뒤 화면의 "이번 라운드 소머리"는 0으로 보인다(마지막 라운드 점수는 점수표에 들어감). ## 2. 모드와 옵션 | 옵션 키 | 설명 | 선택지 | 기본값 | @@ -34,6 +37,8 @@ | `cardTracker` | 이번 라운드에 나온 카드 표 보여 주기(프로 변형이면 각자 골라 간 카드도) | `true` / `false`(원작처럼 기억으로) | `true` | | `turnSeconds` | 카드 고르기·줄 고르기·카드 뽑아 가기 제한 시간 | 15 / 20 / 30 / 45 / 60 / 무제한(`null`) | 30 | +구현(2026-10-15): 위 옵션을 모두 방 설정으로 넣었다(나중으로 미룬 옵션 없음). `fanCard`와 `placement = both`를 함께 고르면 옵션 검증(`superRefine`)이 거부하고, 대기실 화면은 `both`를 고르면 특별 카드를 `none`으로 돌려놓고 흐리게 한다. + zod 메타 예(`.meta({ title, labels })`, 09 §2): ```ts @@ -233,6 +238,7 @@ interface SixNimmtState { deadlineAt: number | null; } ``` +- 구현 메모: 위 필드 말고도 `picked`(프로: 이번 라운드에 각자 골라 간 카드), `reveal`(마지막으로 공개된 차례: 공개 카드, 놓기 전 줄 모양, 놓을 때마다의 줄 모양 `steps` — 화면이 이것으로 한 장씩 다시 그린다), `lastRound`, `bestTake`, `clockMs`/`clockExtra`(타이머 고리·라운드 결과 5초), `endReason`이 있다. 고른 카드는 공개될 때까지 손패에 그대로 있다(그래서 불변식에 `selections`를 따로 세지 않는다). - `stateVersion` 1. 덱의 카드 총수 보존 불변식: `hands + rows(숫자만) + taken + queue + selections(공개 전) + aside + draft.pool = deckMax`. ### 8.2 액션 @@ -319,6 +325,7 @@ interface SixNimmtView { - 실수: `humanBest`(`bots/policy.ts`)를 그대로 쓴다. 이 게임 기준 `small` = 소머리 0.5개, `critical` = 없음(꼭 둬야 할 수 개념이 약함). - 1~20단계는 위험 항을 쓰지 않는다(눈앞만 봄). 41단계 이상은 `queue`를 보는 줄 고르기와 숫자 뒤집기 시점 계산(가장 큰 위험을 피할 때 쓰기)을 한다. - 속도: 카드 10장 × `K` 48 × 한 차례 흉내(카드 10장 놓기) = 수천 번 비교라 수 ms 안. 생각 시간은 06 §12대로 사람처럼 1~3초. +- 구현 메모: 위험 항은 "내 카드가 5번째로 줄 끝에 남으면 덤(+0.3)"만 쓴다(6번째 바로 앞에 남기는 손해는 한 차례 흉내 안에 이미 들어 있음). 숫자 뒤집기는 41단계 이상만, 안 뒤집은 가장 좋은 수보다 소머리 2개 이상 아낄 때(라운드 마지막 카드면 조금이라도 나을 때) 쓴다. 5인 판 1라운드 100판에서 60단계 1명의 평균 벌점이 1단계 4명 평균의 85% 미만인지 `six-nimmt/bot.test.ts`가 확인한다(200판 실측 약 10.0 대 14.6). - 테스트(`bots/bots.test.ts`): 2·5·10명, 옵션 조합(기본, `pro`, `both`, 팬 카드 4종)마다 컴퓨터끼리 끝까지 두어 모든 수가 합법이고 멈추지 않는지. 60단계 대 1단계 5인 판 100판 평균 벌점이 뚜렷하게 낮은지. ## 9. UI/UX @@ -345,24 +352,24 @@ interface SixNimmtView { - 소리: 합성음만(사이트 음량). 카드 내기 "톡", 공개 "착", 놓기 "탁", 가져가기 "음매"(소머리 많을수록 낮고 길게), 내 차례가 열릴 때 짧은 알림. ## 10. 테스트 체크리스트 -- [ ] 소머리: 55 → 7, 11·22·…·99 → 5, 10·20·…·100 → 3, 5·15·…·95(55 빼고) → 2, 나머지 → 1. 104장 합 171. -- [ ] 셋업: `all` 4명 → 손패 10장씩, 줄 4장, `aside` 60장, 카드 총수 104. `tactics` 3명 → 1~34만, `aside` 0장. 같은 시드면 같은 분배. -- [ ] `pro` 3명: 1~34를 펼치고 시작 자리부터 돌아가며 30번 고른 뒤 남은 4장이 작은 수부터 줄 시작. 7명 이상은 옵션 검증에서 거부(`playersFor`). -- [ ] §5.4 예시를 그대로: 2차례에 C가 12·14·15·21·26(소머리 6)을 가져가고 1번 줄이 [30 36]. 3차례에 A만 `choose`로 멈추고, A가 2번 줄을 고르면 [3 9]와 4번 줄 [58 61 68 83]. -- [ ] 함정: 끝 카드 41, 42에서 45는 42 다음. 그 줄이 5장이면 가져감. -- [ ] 규칙 4가 아닌 카드(같은 차례의 두 번째 이후)는 `choose`로 멈추지 않는다(기본 규칙). -- [ ] `lowCard = fewest`: 소머리가 같은 두 줄이면 끝 카드가 큰 줄을 자동으로 가져간다. -- [ ] 고르기: 모두 고르기 전에는 다시 `SELECT`로 바꿀 수 있고, 마지막 사람이 고르는 순간 공개된다. 공개 뒤 `SELECT`는 거부. -- [ ] `both`: 끝 40(2번 줄), 첫 카드 46(3번 줄), 낸 카드 43 → `place` 대기, 두 자리 중 하나만 허용. 첫 카드보다 작으면 왼쪽에 붙는다. 5장 줄 왼쪽에 붙이면 5장을 가져간다. -- [ ] `evenOdd`: "홀" 표시 줄(끝 85)에는 짝수가 못 간다(원작 예: 90이 85 다음 대신 52 다음 → 6번째라 가져감). 가져간 뒤 짝홀 카드가 나머지 세 줄(끝 31, 90, 92) 중 끝 카드가 가장 작은 31 줄로 옮겨지고 면은 "홀". -- [ ] `mountain`: 표시 줄은 끝 카드보다 작은 수만, 차이가 같으면 표시 줄. 줄을 가져갈 때마다 한 줄씩, 1번·4번 줄에서 방향이 바뀐다(원작 예: 21이 12 다음 대신 산 오르기 줄의 26 다음(내림차순)으로 → 6번째라 가져감). -- [ ] `jumpingCow`: 숫자 4장 + 소 줄에 놓으면 숫자 4장만 가져가고 소는 끝 카드가 가장 작은 다른 줄로 뛴다(원작 예: 43, 다른 줄 끝 78·104·53 → 53 줄). 뛰어간 줄이 6칸이 되면 같은 사람이 가장 큰 카드 1장을 남기고 4장을 가져가고 소가 또 뛴다. -- [ ] `flipDigits`: 24 + 뒤집기 → 42로 놓을 줄을 정하고 놓인 뒤에는 24, 소머리 1. 13(뒤집기 → 31)과 31(그대로)이 함께 나오면 뒤집은 사람이 먼저. 7 → 70. 100 이상 뒤집기 거부. 라운드에 한 번만. -- [ ] 라운드 끝 점수 합산, 66 이상이면 그 라운드 끝에 종료(도중에 넘어도 라운드는 끝까지). 공동 1등 처리. `endMode = rounds` 3이면 정확히 3라운드. 20라운드 안전장치. -- [ ] 시간 초과: 고르기 = 지금 줄 기준 가져갈 소머리가 가장 적은 카드(같으면 차이 작은 것, 작은 숫자), 줄 고르기 = 가장 적은 소머리 줄, 뽑아 가기 = 소머리 적고 작은 숫자. 모든 상태에서 `onTimeout`이 합법. -- [ ] 연결 끊김·나감: 나간 사람 카드는 `select`가 열리자마자 자동으로 나가 다른 사람을 기다리게 하지 않는다. 결과에서는 맨 뒤. 남은 사람 1명이면 종료. -- [ ] 정보 유출: 공개 전 고른 카드, 남의 손패, `aside`가 다른 사람·관전자 view에 없다(`secretsOf`). `cardTracker = false`면 `seen`·`draft.picked`가 view에 없다. -- [ ] 무작위 대국 1,000판(인원 2~10, 옵션 조합): 예외 없음, 카드 총수 보존, 줄은 언제나 숫자 5장 이하(소 포함 5칸 이하), 직렬화 왕복·결정성. +- [x] 소머리: 55 → 7, 11·22·…·99 → 5, 10·20·…·100 → 3, 5·15·…·95(55 빼고) → 2, 나머지 → 1. 104장 합 171. +- [x] 셋업: `all` 4명 → 손패 10장씩, 줄 4장, `aside` 60장, 카드 총수 104. `tactics` 3명 → 1~34만, `aside` 0장. 같은 시드면 같은 분배. +- [x] `pro` 3명: 1~34를 펼치고 시작 자리부터 돌아가며 30번 고른 뒤 남은 4장이 작은 수부터 줄 시작. 7명 이상은 옵션 검증에서 거부(`playersFor`). +- [x] §5.4 예시를 그대로: 2차례에 C가 12·14·15·21·26(소머리 6)을 가져가고 1번 줄이 [30 36]. 3차례에 A만 `choose`로 멈추고, A가 2번 줄을 고르면 [3 9]와 4번 줄 [58 61 68 83]. +- [x] 함정: 끝 카드 41, 42에서 45는 42 다음. 그 줄이 5장이면 가져감. +- [x] 규칙 4가 아닌 카드(같은 차례의 두 번째 이후)는 `choose`로 멈추지 않는다(기본 규칙). +- [x] `lowCard = fewest`: 소머리가 같은 두 줄이면 끝 카드가 큰 줄을 자동으로 가져간다. +- [x] 고르기: 모두 고르기 전에는 다시 `SELECT`로 바꿀 수 있고, 마지막 사람이 고르는 순간 공개된다. 공개 뒤 `SELECT`는 거부. +- [x] `both`: 끝 40(2번 줄), 첫 카드 46(3번 줄), 낸 카드 43 → `place` 대기, 두 자리 중 하나만 허용. 첫 카드보다 작으면 왼쪽에 붙는다. 5장 줄 왼쪽에 붙이면 5장을 가져간다. +- [x] `evenOdd`: "홀" 표시 줄(끝 85)에는 짝수가 못 간다(원작 예: 90이 85 다음 대신 52 다음 → 6번째라 가져감). 가져간 뒤 짝홀 카드가 나머지 세 줄(끝 31, 90, 92) 중 끝 카드가 가장 작은 31 줄로 옮겨지고 면은 "홀". +- [x] `mountain`: 표시 줄은 끝 카드보다 작은 수만, 차이가 같으면 표시 줄. 줄을 가져갈 때마다 한 줄씩, 1번·4번 줄에서 방향이 바뀐다(원작 예: 21이 12 다음 대신 산 오르기 줄의 26 다음(내림차순)으로 → 6번째라 가져감). +- [x] `jumpingCow`: 숫자 4장 + 소 줄에 놓으면 숫자 4장만 가져가고 소는 끝 카드가 가장 작은 다른 줄로 뛴다(원작 예: 43, 다른 줄 끝 78·104·53 → 53 줄). 뛰어간 줄이 6칸이 되면 같은 사람이 가장 큰 카드 1장을 남기고 4장을 가져가고 소가 또 뛴다. +- [x] `flipDigits`: 24 + 뒤집기 → 42로 놓을 줄을 정하고 놓인 뒤에는 24, 소머리 1. 13(뒤집기 → 31)과 31(그대로)이 함께 나오면 뒤집은 사람이 먼저. 7 → 70. 100 이상 뒤집기 거부. 라운드에 한 번만. +- [x] 라운드 끝 점수 합산, 66 이상이면 그 라운드 끝에 종료(도중에 넘어도 라운드는 끝까지). 공동 1등 처리. `endMode = rounds` 3이면 정확히 3라운드. 20라운드 안전장치. +- [x] 시간 초과: 고르기 = 지금 줄 기준 가져갈 소머리가 가장 적은 카드(같으면 차이 작은 것, 작은 숫자), 줄 고르기 = 가장 적은 소머리 줄, 뽑아 가기 = 소머리 적고 작은 숫자. 모든 상태에서 `onTimeout`이 합법. +- [x] 연결 끊김·나감: 나간 사람 카드는 `select`가 열리자마자 자동으로 나가 다른 사람을 기다리게 하지 않는다. 결과에서는 맨 뒤. 남은 사람 1명이면 종료. +- [x] 정보 유출: 공개 전 고른 카드, 남의 손패, `aside`가 다른 사람·관전자 view에 없다(`secretsOf`). `cardTracker = false`면 `seen`·`draft.picked`가 view에 없다. +- [x] 무작위 대국 1,000판(인원 2~10, 옵션 조합): 예외 없음, 카드 총수 보존, 줄은 언제나 숫자 5장 이하(소 포함 5칸 이하), 직렬화 왕복·결정성. ## 11. 참고 자료 - AMIGO 30주년판 영문 규칙서(2024, 기본 규칙·프로 변형·팬 카드 4종·협력 변형 "버펄로를 이겨라"): https://blog.amigo-spiele.de/content/ap/rule/02401-GB-AmigoRule.pdf diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index b7ceb39..abe989b 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -1191,6 +1191,51 @@ async function magicalStep(p: Page, phone: boolean, st: { picks: number; selects return false; } +async function sixStep(p: Page, phone: boolean, st: { selects: number; taps: number; rows: number; spots: number; drafts: number }): Promise { + const press = (l: Locator) => (phone ? l.tap({ timeout: 1500 }) : l.click({ timeout: 1500 })); + try { + const take = p.locator('.sx-takebtn:not([disabled])'); + if (await take.count()) { + await press(take.first()); + st.rows++; + await p.waitForTimeout(200); + return true; + } + const spot = p.locator('.sx-spot:not([disabled])'); + if (await spot.count()) { + await press(spot.first()); + st.spots++; + return true; + } + const pool = p.locator('.sx-poolbtn:not([disabled])'); + if (await pool.count()) { + await press(pool.nth(st.drafts % (await pool.count()))); + st.drafts++; + return true; + } + const cards = p.locator('.sx-hcard:not([disabled])'); + const n = await cards.count(); + if (n && !(await p.locator('.sx-hcard.sent').count())) { + const card = cards.nth((st.selects * 3) % n); + if (phone && Math.floor(st.selects / 2) % 2 === 0) { + // Phone: tap the same card twice to play it. + await card.tap({ timeout: 1500 }); + await card.tap({ timeout: 1500 }); + st.taps++; + } else { + await press(card); + await press(p.locator('.sx-send')); + } + st.selects++; + await p.locator('.sx-hcard.sent').or(p.locator('.sx-reveal')).first().waitFor({ timeout: 4000 }).catch(() => {}); + return true; + } + } catch { + return false; + } + return false; +} + const PLANS: Record = { blackjack: { // PC host + phone guest. Each hand: bet the minimum, stand (decline insurance), then press 다음 판, until the @@ -3190,6 +3235,118 @@ const PLANS: Record = { console.log(` magical-athlete: ${st.picks} picks, ${st.selects} race picks, ${st.acts} turn choices (${st.second} second options), powers + wild track seen`); }, }, + 'six-nimmt': { + // PC host + phone guest, two rounds by round count. Real secret picks (PC: card + [이 카드 내기]; phone: also a double + // tap), too-low cards take a row through the row buttons, until the game ends. Rules are covered by the engine tests. + lobby: async (host) => { + await host.getByRole('group', { name: '끝나는 조건' }).getByRole('button', { name: '라운드 수' }).click(); + await host.getByRole('group', { name: '라운드 수' }).getByRole('button', { name: '2라운드' }).click(); + await host.getByText('2라운드').first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st = { selects: 0, taps: 0, rows: 0, spots: 0, drafts: 0 }; + const shots = new Set(); + let roundBox = false; + let revealSeen = false; + const over = () => host.getByRole('dialog', { name: '게임 결과' }).count(); + const until = Date.now() + 300_000; + while (Date.now() < until && !(await over())) { + for (const [i, p] of pages.entries()) { + if (!shots.has(`choose${i}`) && (await p.locator('.sx-takebtn:not([disabled])').count())) { + shots.add(`choose${i}`); + await p.screenshot({ path: join(SHOTS, `six-nimmt-choose-${i ? 'phone' : 'pc'}.png`), fullPage: i > 0 }); + } + } + let acted = false; + for (const [i, p] of pages.entries()) { + if (await sixStep(p, i > 0, st)) { + acted = true; + break; + } + } + if (!revealSeen && (await host.locator('.sx-reveal').count())) revealSeen = true; + if (!roundBox && (await host.locator('.sx-round').count())) { + roundBox = true; + await host.screenshot({ path: join(SHOTS, 'six-nimmt-round-pc.png') }); + } + if (!shots.has('mid') && st.selects >= 7) { + shots.add('mid'); + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'six-nimmt-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'six-nimmt-mid-phone.png') }); + await guest.screenshot({ path: join(SHOTS, 'six-nimmt-mid-phone-full.png'), fullPage: true }); + await host.emulateMedia({ colorScheme: 'dark' }); + await guest.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'six-nimmt-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'six-nimmt-mid-phone-dark.png'), fullPage: true }); + await host.emulateMedia({ colorScheme: 'light' }); + await guest.emulateMedia({ colorScheme: 'light' }); + } + if (!shots.has('narrow') && st.selects >= 12) { + shots.add('narrow'); + await guest.setViewportSize({ width: 320, height: 700 }); + await guest.waitForTimeout(300); + await guest.screenshot({ path: join(SHOTS, 'six-nimmt-320-phone.png'), fullPage: true }); + const wide = await guest.evaluate(() => document.documentElement.scrollWidth); + if (wide > 322) throw new Error(`page is ${wide}px wide at 320px`); + await guest.setViewportSize({ width: 390, height: 844 }); + } + if (!acted) await host.waitForTimeout(150); + } + if (!(await over())) throw new Error(`game did not finish (${JSON.stringify(st)})`); + await guest.getByRole('dialog', { name: '게임 결과' }).waitFor(); + await host.waitForTimeout(600); + await host.screenshot({ path: join(SHOTS, 'six-nimmt-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'six-nimmt-result-phone.png') }); + await host.keyboard.press('Escape'); + await host.locator('section[aria-label="최종 결과"]').waitFor(); + await host.screenshot({ path: join(SHOTS, 'six-nimmt-final-pc.png'), fullPage: true }); + const cols = await host.locator('section[aria-label="최종 결과"] thead th').count(); + if (cols !== 5) throw new Error(`expected 2 round columns in the final table, saw ${cols - 3}`); + if (st.selects < 38 || !st.taps || !revealSeen) throw new Error(`too few real steps: ${JSON.stringify(st)} reveal=${revealSeen}`); + console.log(` six-nimmt: ${st.selects} picks (${st.taps} double taps), ${st.rows} row choices, round box ${roundBox ? 'seen' : 'missed'}`); + }, + }, + 'six-nimmt-pro': { + // Variant smoke test: the pro draft (2 players → 1~24 face up, ten picks each) and both-ends placement, one round. + game: 'six-nimmt', + lobby: async (host) => { + await host.getByRole('group', { name: '카드 구성' }).getByRole('button', { name: '펼쳐 골라 가기' }).click(); + await host.getByRole('group', { name: '줄에 붙이는 곳' }).getByRole('button', { name: '양쪽 끝' }).click(); + await host.getByRole('group', { name: '끝나는 조건' }).getByRole('button', { name: '라운드 수' }).click(); + await host.getByRole('group', { name: '라운드 수' }).getByRole('button', { name: '1라운드' }).click(); + await host.getByText('펼쳐 골라 가기').first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st = { selects: 0, taps: 0, rows: 0, spots: 0, drafts: 0 }; + let draftShot = false; + const over = () => host.getByRole('dialog', { name: '게임 결과' }).count(); + const until = Date.now() + 240_000; + while (Date.now() < until && !(await over())) { + let acted = false; + for (const [i, p] of pages.entries()) { + if (await sixStep(p, i > 0, st)) { + acted = true; + break; + } + } + if (!draftShot && st.drafts >= 5) { + draftShot = true; + await host.screenshot({ path: join(SHOTS, 'six-nimmt-pro-draft-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'six-nimmt-pro-draft-phone.png'), fullPage: true }); + } + if (!acted) await host.waitForTimeout(150); + } + if (!(await over())) throw new Error(`game did not finish (${JSON.stringify(st)})`); + await host.waitForTimeout(600); + await host.screenshot({ path: join(SHOTS, 'six-nimmt-pro-result-pc.png') }); + if (st.drafts !== 20 || st.selects < 19) throw new Error(`too few real steps: ${JSON.stringify(st)}`); + console.log(` six-nimmt-pro: ${st.drafts} draft picks, ${st.selects} card picks, ${st.rows} row choices, ${st.spots} spot choices`); + }, + }, }; const games = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(PLANS); diff --git a/packages/games/package.json b/packages/games/package.json index 62f16f9..0318eac 100644 --- a/packages/games/package.json +++ b/packages/games/package.json @@ -12,6 +12,7 @@ "./liar/topics": "./src/liar/topics.ts", "./magical-athlete/racers": "./src/magical-athlete/racers.ts", "./seotda/money": "./src/seotda/money.ts", + "./six-nimmt/rules": "./src/six-nimmt/rules.ts", "./*": "./src/*/index.ts" }, "dependencies": { diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 14d5844..a48ffa4 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -38,6 +38,7 @@ import { unoBot } from '../uno/bot'; import { liarBot } from '../liar/bot'; import { magicalAthleteBot } from '../magical-athlete/bot'; import { blackjackBot } from '../blackjack/bot'; +import { sixNimmtBot } from '../six-nimmt/bot'; export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types'; export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona'; @@ -73,6 +74,7 @@ export const BOT_STRATEGIES: Record = { uno: unoBot, 'magical-athlete': magicalAthleteBot, blackjack: blackjackBot, + 'six-nimmt': sixNimmtBot, }; /** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */ diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index e40af82..f8b827c 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -33,6 +33,7 @@ import { uno } from './uno'; import { liar } from './liar'; import { magicalAthlete } from './magical-athlete'; import { blackjack } from './blackjack'; +import { sixNimmt } from './six-nimmt'; export const GAMES: Record = { [omok.id]: omok, @@ -69,4 +70,5 @@ export const GAMES: Record = { [liar.id]: liar, [magicalAthlete.id]: magicalAthlete, [blackjack.id]: blackjack, + [sixNimmt.id]: sixNimmt, }; diff --git a/packages/games/src/six-nimmt/bot.test.ts b/packages/games/src/six-nimmt/bot.test.ts new file mode 100644 index 0000000..7a19aff --- /dev/null +++ b/packages/games/src/six-nimmt/bot.test.ts @@ -0,0 +1,111 @@ +/** 젝스님트 computer player (docs/games/six-nimmt.md §8.7). */ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, seedN } from '@bg/engine'; +import { decideBotAction } from '../bots'; +import { sixNimmt, type Card, type SixNimmtAction, type SixNimmtOptions, type SixNimmtState } from './index'; +import { samplesFor, sixNimmtBot } from './bot'; + +const rng = (seed = 1) => SeededRng.fromSeed(seedN(seed)); +const opts = (o: Partial = {}) => sixNimmt.optionsSchema.parse(o) as SixNimmtOptions; + +function custom(rows: Card[][], hands: Record, o: Partial = {}): SixNimmtState { + const players = Object.keys(hands); + const s = sixNimmt.setup({ players, options: opts(o), rng: rng(), now: 0 }); + s.rows = rows; + s.marker = null; + s.aside = []; + for (const p of players) s.hands[p] = [...hands[p]!].sort((a, b) => a - b); + s.seen = rows.map((r) => r[0]!); + return s; +} + +const ask = (s: SixNimmtState, me: string, level = 60, seed = 5) => { + const r = rng(seed); + return sixNimmtBot({ me, view: sixNimmt.view(s, me), legal: sixNimmt.legalActions!(s, me), random: () => r.next(), level }); +}; + +describe('sixNimmtBot', () => { + test('여섯 번째가 되는 카드를 피해요', () => { + const s = custom([[10, 11, 12, 13, 14], [40], [60], [80]], { A: [15, 45], B: [90, 91] }); + for (let seed = 1; seed <= 5; seed++) expect(ask(s, 'A', 60, seed)).toEqual({ type: 'SELECT', card: 45 }); + }); + + test('너무 작은 카드면 소머리가 가장 적은 줄을 가져가요', () => { + let s = custom([[50, 55], [61], [70, 77], [90]], { A: [2, 99], B: [98, 97] }); + s = sixNimmt.apply(s, 'A', { type: 'SELECT', card: 2 }, { rng: rng(), now: 1 }).state; + s = sixNimmt.apply(s, 'B', { type: 'SELECT', card: 98 }, { rng: rng(), now: 2 }).state; + expect(s.phase).toBe('choose'); + const a = ask(s, 'A'); + expect(a.type).toBe('TAKE_ROW'); + expect([1, 3]).toContain((a as { row: number }).row); + }); + + test('프로 뽑기는 소머리가 적은 카드', () => { + const s = sixNimmt.setup({ players: ['A', 'B'], options: opts({ deck: 'pro' }), rng: rng(), now: 0 }); + const p = sixNimmt.activePlayers(s)[0]!; + const a = ask(s, p) as Extract; + expect(a.type).toBe('DRAFT'); + expect([55, 11, 22, 10, 20, 5, 15]).not.toContain(a.card); + }); + + test('흉내 횟수: 1단계 4번 → 60단계 48번', () => { + expect(samplesFor(1)).toBe(4); + expect(samplesFor(60)).toBe(48); + expect(samplesFor(30)).toBeGreaterThan(samplesFor(10)); + }); + + const OPTS: Partial[] = [ + { endMode: 'rounds', rounds: 1 }, + { deck: 'pro', endMode: 'rounds', rounds: 1 }, + { placement: 'both', endMode: 'rounds', rounds: 1 }, + { fanCard: 'evenOdd', endMode: 'rounds', rounds: 1 }, + { fanCard: 'mountain', endMode: 'rounds', rounds: 1 }, + { fanCard: 'jumpingCow', endMode: 'rounds', rounds: 1 }, + { fanCard: 'flipDigits', endMode: 'rounds', rounds: 1 }, + ]; + for (const o of OPTS) { + for (const n of [2, 5, 10]) { + if (o.deck === 'pro' && n > 6) continue; + test(`${n}명 ${JSON.stringify(o)}: 컴퓨터끼리 끝까지, 모든 수가 합법`, () => { + const players = Array.from({ length: n }, (_, i) => `bot:${i}:x`); + const r = rng(n * 7); + let s = sixNimmt.setup({ players, options: opts(o), rng: r, now: 0 }); + const ch = rng(n * 13); + let t = 1; + for (let g = 0; g < 5000 && s.phase !== 'finished'; g++) { + const me = sixNimmt.activePlayers(s)[0]!; + const legal = sixNimmt.legalActions!(s, me); + const a = sixNimmtBot({ me, view: sixNimmt.view(s, me), legal, random: () => ch.next(), level: 1 + ((g * 17) % 60) }); + const v = sixNimmt.validate(s, me, a); + expect(v.ok).toBe(true); + s = sixNimmt.apply(s, me, a, { rng: r, now: t++ }).state; + } + expect(s.phase).toBe('finished'); + }); + } + } + + test('60단계가 1단계보다 벌점이 뚜렷하게 적어요(5인 판)', () => { + const games = 100; + let strong = 0; + let weak = 0; + for (let gi = 0; gi < games; gi++) { + const players = Array.from({ length: 5 }, (_, i) => `bot:${i}:x`); + const strongSeat = players[gi % 5]!; + const r = rng(1000 + gi); + const ch = rng(2000 + gi); + let s = sixNimmt.setup({ players, options: opts({ endMode: 'rounds', rounds: 1 }), rng: r, now: 0 }); + let t = 1; + while (s.phase !== 'finished') { + const me = sixNimmt.activePlayers(s)[0]!; + const a = decideBotAction(sixNimmt, s, me, { now: t, random: () => ch.next(), level: me === strongSeat ? 60 : 1 }); + s = sixNimmt.apply(s, me, a as SixNimmtAction, { rng: r, now: t++ }).state; + } + for (const p of players) { + if (p === strongSeat) strong += s.totals[p]!; + else weak += s.totals[p]! / 4; + } + } + expect(strong / games).toBeLessThan((weak / games) * 0.85); + }); +}); diff --git a/packages/games/src/six-nimmt/bot.ts b/packages/games/src/six-nimmt/bot.ts new file mode 100644 index 0000000..9684e05 --- /dev/null +++ b/packages/games/src/six-nimmt/bot.ts @@ -0,0 +1,126 @@ +/** + * 젝스님트 computer player (docs/games/six-nimmt.md §8.7). Reads only its own view: + * - 고르기: for each card (and 숫자 뒤집기 when allowed) it plays the turn out `K` times with random cards for the others + * (from the cards it hasn't seen; the pro draft's known hands when the card table shows them) and keeps the card that + * takes the fewest bulls on average. Above level 20 it also likes leaving its card fifth in a row (someone else takes it). + * - 줄 고르기: the row with the fewest bulls; level 41+ breaks ties by looking at the cards still waiting to be placed. + * - 뽑아 가기(pro): few bulls, spread out over the numbers. + * Level (1~60) sets `K` and how often it slips (`humanBest`). + */ +import type { PlayerId } from '@bg/engine'; +import type { BotStrategy } from '../bots/types'; +import { humanBest, pick, playable } from '../bots/policy'; +import { bulls, bullsOf, placeAt, playOf, simulateTurn, type Board, type Card, type Play } from './rules'; +import type { SixNimmtAction, SixNimmtView } from './types'; + +type Act = SixNimmtAction; +const SCALE = { small: 0.5, critical: Number.POSITIVE_INFINITY }; + +const boardOf = (v: SixNimmtView): Board => ({ rows: v.rows.map((r) => r.cards.map((c) => c.n)), marker: v.marker ? { ...v.marker } : null }); + +/** Simulations per candidate card: 4 at level 1 → 48 at level 60. */ +export const samplesFor = (level: number | undefined): number => (level === undefined ? 32 : Math.round(4 + ((Math.max(1, Math.min(60, level)) - 1) * 44) / 59)); + +/** Cards the bot can't place anywhere it knows of: possible cards in the others' hands. */ +function unknownCards(v: SixNimmtView, me: PlayerId): Card[] { + const out = new Set(Array.from({ length: v.deckMax }, (_, i) => i + 1)); + for (const h of v.my?.hand ?? []) out.delete(h.n); + for (const r of v.rows) for (const c of r.cards) out.delete(c.n); + for (const c of v.seen ?? []) out.delete(c); + for (const c of v.my?.taken ?? []) out.delete(c); + for (const q of v.queue) out.delete(q.card); + if (v.known) for (const [p, cs] of Object.entries(v.known)) if (p !== me) for (const c of cs) out.delete(c); + return [...out]; +} + +function sampleOthers(v: SixNimmtView, me: PlayerId, pool: Card[], random: () => number): Play[] { + const plays: Play[] = []; + const free = [...pool]; + for (const p of v.seats) { + if (p === me) continue; + const known = v.known?.[p]; + let c: Card | undefined; + if (known && known.length) c = pick(known, random); + else if (free.length) c = free.splice(Math.floor(random() * free.length), 1)[0]; + if (c !== undefined) plays.push(playOf(p, c, false)); + } + return plays; +} + +export const sixNimmtBot: BotStrategy = ({ me, view: v, legal, random, level }) => { + const acts = playable(legal); + if (!acts.length) return legal[0]!; + const choose = (score: (a: Act) => number) => humanBest(acts, (a) => score(a) + random() * 1e-4, random, level, SCALE); + const b = boardOf(v); + const lv = level ?? 60; + + if (v.phase === 'draft') { + const mine = v.draft?.picked?.[me] ?? v.my?.hand.map((h) => h.n) ?? []; + return choose((a) => { + if (a.type !== 'DRAFT') return -99; + const crowd = mine.filter((c) => Math.abs(c - a.card) <= 3).length; + return -bulls(a.card) - 0.4 * crowd; + }); + } + + if (v.phase === 'choose' && v.pending) { + const pd = v.pending; + // Cards still waiting after mine (level 41+ looks at them for a tie). + const rest = v.queue.slice(1); + return choose((a) => { + if (a.type !== 'TAKE_ROW' && a.type !== 'PLACE') return -99; + const row = a.row; + const side = a.type === 'PLACE' ? a.side : 'R'; + const res = placeAt(b, pd.play, row, side, a.type === 'TAKE_ROW'); + let score = -bullsOf(res.took); + if (lv > 40 && rest.length) { + const after = simulateTurn(res.board, rest, v.options); + score -= (after.taken[me] ?? 0) * 0.9; + // Mild preference for leaving rows that make the others take cows. + score += 0.05 * Object.entries(after.taken).reduce((t, [p, n]) => (p === me ? t : t + n), 0); + } + return score; + }); + } + + if (v.phase === 'select' && v.my) { + const k = samplesFor(level); + const pool = unknownCards(v, me); + const lastTurn = v.my.hand.length === 1; + const sims = Array.from({ length: k }, () => sampleOthers(v, me, pool, random)); + const scoreOf = (card: Card, flip: boolean) => { + const mine = playOf(me, card, flip); + let total = 0; + let bonus = 0; + for (const others of sims) { + const res = simulateTurn(b, [mine, ...others.filter((o) => o.card !== card)], v.options); + total += res.taken[me] ?? 0; + if (lv > 20) { + const row = res.board.rows.find((r) => r.includes(card)); + if (row && row.length === 5 && row[row.length - 1] === card) bonus += 0.3; + } + } + return -total / k + bonus / k; + }; + const cache = new Map(); + const scored = (a: Act) => { + if (a.type !== 'SELECT') return -99; + const key = `${a.card}:${a.flip ? 1 : 0}`; + if (!cache.has(key)) cache.set(key, scoreOf(a.card, !!a.flip)); + return cache.get(key)!; + }; + // 숫자 뒤집기 only for level 41+, and only when it saves real trouble (or on the last card of the round). + const plain = acts.filter((a) => a.type === 'SELECT' && !a.flip); + let cands = plain.length ? plain : acts; + const flips = acts.filter((a) => a.type === 'SELECT' && a.flip); + if (flips.length && lv > 40) { + const bestPlain = Math.max(...plain.map(scored)); + const good = flips.filter((a) => scored(a) >= bestPlain + (lastTurn ? 0.01 : 2)); + if (good.length) cands = good; + } + return humanBest(cands, (a) => scored(a) + random() * 1e-4, random, level, SCALE); + } + + return pick(acts, random); +}; + diff --git a/packages/games/src/six-nimmt/index.ts b/packages/games/src/six-nimmt/index.ts new file mode 100644 index 0000000..29c3b51 --- /dev/null +++ b/packages/games/src/six-nimmt/index.ts @@ -0,0 +1,705 @@ +/** + * 젝스님트 (docs/games/six-nimmt.md). Everybody secretly picks a card at once; the cards are revealed together and go + * onto four rows from the smallest up. The sixth card of a row takes the five before it (소머리 = 벌점). + * Pure and deterministic; state is JSON. Hidden: hands (except the face-up pro draft), picks before the reveal, and the + * cards not used this round. + */ +import type { ZodType } from 'zod'; +import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine'; +import { playersFor, sixNimmtOptionsSchema, type SixNimmtOptions } from './options'; +import { + HAND, + ROWS, + bulls, + bullsOf, + canFlip, + deckMaxFor, + fewestRow, + flipValue, + placeAt, + playOf, + playOrder, + previewOf, + rowBulls, + spotsFor, + startMarker, + type Board, + type Card, + type Play, + type Side, +} from './rules'; +import { + sixNimmtActionSchema, + type LogEntry, + type SixHandCard, + type SixNimmtAction, + type SixNimmtState, + type SixNimmtView, + type SixRankRow, + type SixResult, +} from './types'; + +export * from './options'; +export * from './rules'; +export * from './types'; + +type S = SixNimmtState; +type A = SixNimmtAction; +type Ev = GameEvent[]; + +const LOG_MAX = 60; +/** Consecutive automatic moves before a player is shown as "자리 비움" (and gets the short clock). */ +export const AWAY_AFTER = 3; +export const AWAY_MS = 5000; +/** Extra time on the first pick of a new round, to read the round result (§8.5). */ +export const ROUND_BREAK_MS = 5000; +/** With `endMode = score` the game still ends after this many rounds (§1 우리가 정한 것). */ +export const ROUND_CAP = 20; + +const isIn = (s: S, p: PlayerId) => !s.left.includes(p); +const inPlayers = (s: S) => s.seats.filter((p) => isIn(s, p)); +const handKey = (p: PlayerId, hand: Card[]) => `six-hand:${p}:${hand.join(',')}`; +const selKey = (s: S, p: PlayerId, card: Card) => `six-sel:${p}:r${s.round}t${s.turn}:${card}`; +const boardOf = (s: S): Board => ({ rows: s.rows, marker: s.marker }); + +type LogInput = LogEntry extends infer T ? (T extends LogEntry ? Omit : never) : never; +function log(s: S, e: LogInput): void { + s.log.push({ n: ++s.logSeq, ...e } as LogEntry); + if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX); +} + +// ---------------------------------------------------------------- turn / clock + +function activeOf(s: S): PlayerId[] { + switch (s.phase) { + case 'draft': + return [s.seats[s.draft!.at]!]; + case 'select': + return inPlayers(s).filter((p) => s.selections[p] === null); + case 'choose': + return [s.pending!.player]; + default: + return []; + } +} + +/** Clock of the current step; `extra` (round break) is added once. */ +function clockMsOf(s: S): number | null { + const act = activeOf(s); + if (!act.length) return null; + if (act.every((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER)) return AWAY_MS; + return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000; +} + +function refreshDeadline(s: S, now: number, extra: number): void { + const ms = clockMsOf(s); + s.clockMs = ms === null ? null : ms + extra; + s.deadlineAt = ms === null ? null : now + ms + extra; +} + +// ---------------------------------------------------------------- rounds + +function startRound(s: S, rng: Rng, ev: Ev): void { + const o = s.options; + const n = s.seats.length; + s.deckMax = deckMaxFor(o.deck, n); + for (const p of s.seats) { + s.taken[p] = []; + s.selections[p] = null; + s.flipLeft[p] = o.fanCard === 'flipDigits'; + s.picked[p] = []; + s.hands[p] = []; + } + s.queue = []; + s.pending = null; + s.turn = 1; + s.aside = []; + const all = Array.from({ length: s.deckMax }, (_, i) => i + 1); + if (o.deck === 'pro') { + s.rows = []; + s.marker = null; + s.seen = []; + s.draft = { pool: all, at: s.startSeat, picked: Object.fromEntries(s.seats.map((p) => [p, []])) }; + s.phase = 'draft'; + s.turnSeq++; + return; + } + const deck = rng.shuffle(all); + // Deal ten each from the round's first player, then four row starters in the order drawn (원작처럼 정렬하지 않음). + for (let k = 0; k < HAND; k++) for (let i = 0; i < n; i++) s.hands[s.seats[(s.startSeat + i) % n]!]!.push(deck.shift()!); + for (const p of s.seats) s.hands[p]!.sort((a, b) => a - b); + s.rows = Array.from({ length: ROWS }, () => [deck.shift()!]); + s.aside = deck.sort((a, b) => a - b); + beginPlay(s, ev); +} + +/** Rows are set: fan card, card table, first pick. */ +function beginPlay(s: S, ev: Ev): void { + s.marker = startMarker(s.options.fanCard, s.rows); + s.seen = s.rows.map((r) => r[0]!); + s.draft = null; + ev.push({ type: 'roundStart', round: s.round, rows: s.rows.map((r) => [...r]), marker: s.marker }); + openSelect(s); +} + +function openSelect(s: S): void { + s.phase = 'select'; + for (const p of s.seats) s.selections[p] = null; + s.pending = null; + s.turnSeq++; +} + +function draftPick(s: S, p: PlayerId, c: Card, ev: Ev): void { + const d = s.draft!; + d.pool = d.pool.filter((x) => x !== c); + d.picked[p]!.push(c); + s.picked[p]!.push(c); + s.hands[p]!.push(c); + s.hands[p]!.sort((a, b) => a - b); + ev.push({ type: 'drafted', player: p, card: c }); + const n = s.seats.length; + // Next seat that still has fewer than ten cards (everyone ends with ten, so this just goes round). + if (s.seats.every((q) => s.hands[q]!.length >= HAND)) { + s.rows = [...d.pool].sort((a, b) => a - b).map((x) => [x]); + return beginPlay(s, ev); + } + let at = d.at; + for (let k = 0; k < n; k++) { + at = (at + 1) % n; + if (s.hands[s.seats[at]!]!.length < HAND) break; + } + d.at = at; + s.turnSeq++; +} + +function endRound(s: S, rng: Rng, ev: Ev): void { + const gained: Record = {}; + for (const p of s.seats) { + gained[p] = bullsOf(s.taken[p]!); + s.totals[p]! += gained[p]!; + s.roundScores[p]!.push(gained[p]!); + } + s.lastRound = { round: s.round, gained }; + log(s, { t: 'round', round: s.round, gained }); + ev.push({ type: 'roundEnd', round: s.round, gained, totals: { ...s.totals } }); + const o = s.options; + if (o.endMode === 'rounds' && s.round >= o.rounds) return finishGame(s, ev, 'rounds'); + if (o.endMode === 'score') { + if (s.seats.some((p) => s.totals[p]! >= o.endScore)) return finishGame(s, ev, 'score'); + if (s.round >= ROUND_CAP) return finishGame(s, ev, 'cap'); + } + s.round++; + s.startSeat = (s.startSeat + 1) % s.seats.length; + s.clockExtra = ROUND_BREAK_MS; + startRound(s, rng, ev); +} + +function finishGame(s: S, ev: Ev, why: NonNullable): void { + if (why === 'resign') { + // Count the cows already taken in the unfinished round. + for (const p of s.seats) { + const b = bullsOf(s.taken[p]!); + s.totals[p]! += b; + s.roundScores[p]!.push(b); + s.taken[p] = []; + } + } + s.phase = 'finished'; + s.endReason = why; + s.pending = null; + s.deadlineAt = null; + s.clockMs = null; + ev.push({ type: 'gameOver' }); +} + +// ---------------------------------------------------------------- reveal and placing + +function reveal(s: S, ev: Ev, rng: Rng): void { + const plays: Play[] = []; + for (const p of s.seats) { + const sel = s.selections[p]; + if (!sel) continue; + s.hands[p] = s.hands[p]!.filter((c) => c !== sel.card); + if (sel.flip) { + s.flipLeft[p] = false; + log(s, { t: 'flip', player: p, card: sel.card, value: flipValue(sel.card) }); + } + plays.push(playOf(p, sel.card, sel.flip)); + } + plays.sort(playOrder); + for (const p of s.seats) s.selections[p] = null; + s.queue = plays; + s.seen.push(...plays.map((x) => x.card)); + s.reveal = { id: ++s.revealSeq, round: s.round, turn: s.turn, plays: plays.map((x) => ({ ...x })), before: { rows: s.rows.map((r) => [...r]), marker: s.marker ? { ...s.marker } : null }, steps: [] }; + ev.push({ type: 'revealed', plays: plays.map((x) => ({ ...x })) }); + resolve(s, ev, rng); +} + +function recordTake(s: S, player: PlayerId, row: number, cards: Card[], why: 'sixth' | 'low' | 'cow', ev: Ev): void { + if (!cards.length) return; + const b = bullsOf(cards); + s.taken[player]!.push(...cards); + log(s, { t: 'take', player, row, cards: [...cards], bulls: b, why }); + ev.push({ type: 'rowTaken', player, row, cards: [...cards], bulls: b, why }); + if (!s.bestTake || b > s.bestTake.bulls) s.bestTake = { player, bulls: b, round: s.round }; +} + +function put(s: S, play: Play, row: number, side: Side, low: boolean, ev: Ev): void { + const res = placeAt(boardOf(s), play, row, side, low); + s.rows = res.board.rows; + s.marker = res.board.marker; + for (const st of res.steps) { + s.reveal!.steps.push(st); + if (st.t === 'place') { + ev.push({ type: 'placed', player: st.player, card: st.card, row: st.row, side: st.side, pos: st.side === 'L' ? 0 : s.rows[st.row]!.length - 1 }); + recordTake(s, st.player, st.row, st.took, st.why ?? 'sixth', ev); + } else if (st.t === 'marker') ev.push({ type: 'markerMoved', marker: st.marker }); + else { + ev.push({ type: 'cowJumped', from: st.from, to: st.to }); + recordTake(s, st.player, st.to, st.took, 'cow', ev); + } + } +} + +/** Places queued cards until one needs a person's choice, then ends the turn when the queue is empty. */ +function resolve(s: S, ev: Ev, rng: Rng): void { + const o = s.options; + while (s.queue.length) { + const play = s.queue[0]!; + const spots = spotsFor(boardOf(s), play.value, o); + if (!spots.length) { + if (o.lowCard === 'fewest') put(s, play, fewestRow(boardOf(s)), 'R', true, ev); + else { + s.pending = { player: play.player, play: { ...play }, kind: 'takeRow', choices: Array.from({ length: ROWS }, (_, row) => ({ row, side: 'R' as Side })) }; + s.phase = 'choose'; + s.turnSeq++; + ev.push({ type: 'choosing', player: play.player, card: play.card }); + return; + } + } else if (spots.length > 1) { + s.pending = { player: play.player, play: { ...play }, kind: 'place', choices: spots.map(({ row, side }) => ({ row, side })) }; + s.phase = 'choose'; + s.turnSeq++; + ev.push({ type: 'choosing', player: play.player, card: play.card }); + return; + } else put(s, play, spots[0]!.row, spots[0]!.side, false, ev); + s.queue.shift(); + } + s.pending = null; + endTurn(s, ev, rng); +} + +/** Pending choice made: place the card and carry on with the queue. */ +function choose(s: S, row: number, side: Side, ev: Ev, rng: Rng): void { + const pd = s.pending!; + s.pending = null; + s.phase = 'select'; + put(s, pd.play, row, side, pd.kind === 'takeRow', ev); + s.queue.shift(); + resolve(s, ev, rng); +} + +function endTurn(s: S, ev: Ev, rng: Rng): void { + if (s.seats.every((p) => s.hands[p]!.length === 0)) return endRound(s, rng, ev); + s.turn++; + openSelect(s); +} + +// ---------------------------------------------------------------- automatic choices (timeout, left players) + +/** Bulls a card would take if played alone now (too low: the fewest-bulls row), then how close it fits. */ +function safeCard(s: S, p: PlayerId): Card { + const b = boardOf(s); + let best: { c: Card; takes: number; diff: number } | null = null; + for (const c of s.hands[p]!) { + const play = playOf(p, c, false); + const pv = previewOf(b, play, s.options); + const spots = spotsFor(b, c, s.options); + const diff = spots.length ? spots[0]!.diff : 999; + if (!best || pv.takes < best.takes || (pv.takes === best.takes && (diff < best.diff || (diff === best.diff && c < best.c)))) best = { c, takes: pv.takes, diff }; + } + return best!.c; +} + +export function defaultAction(s: S, p: PlayerId): Exclude | null { + switch (s.phase) { + case 'draft': { + const pool = [...s.draft!.pool].sort((a, b) => bulls(a) - bulls(b) || a - b); + return { type: 'DRAFT', card: pool[0]! }; + } + case 'select': + return s.hands[p]!.length ? { type: 'SELECT', card: safeCard(s, p) } : null; + case 'choose': { + const pd = s.pending!; + if (pd.kind === 'takeRow') return { type: 'TAKE_ROW', row: fewestRow(boardOf(s)) }; + const scored = pd.choices.map((ch) => { + const full = s.rows[ch.row]!.length >= 5; + const res = placeAt(boardOf(s), pd.play, ch.row, ch.side, false); + return { ch, full, takes: bullsOf(res.took) }; + }); + scored.sort((a, b) => Number(a.full) - Number(b.full) || a.takes - b.takes || (a.ch.side === 'R' ? -1 : 1) - (b.ch.side === 'R' ? -1 : 1)); + return { type: 'PLACE', row: scored[0]!.ch.row, side: scored[0]!.ch.side }; + } + } + return null; +} + +function perform(s: S, p: PlayerId, a: Exclude, ev: Ev, rng: Rng): void { + switch (a.type) { + case 'DRAFT': + return draftPick(s, p, a.card, ev); + case 'SELECT': { + const first = s.selections[p] === null; + s.selections[p] = { card: a.card, flip: !!a.flip }; + if (first) ev.push({ type: 'picked', player: p }); + return; + } + case 'TAKE_ROW': + return choose(s, a.row, 'R', ev, rng); + case 'PLACE': + return choose(s, a.row, a.side, ev, rng); + case 'LEAVE': + s.left.push(p); + log(s, { t: 'left', player: p }); + ev.push({ type: 'left', player: p }); + if (inPlayers(s).length < 2) return finishGame(s, ev, 'resign'); + return; + } +} + +/** Moves the game on wherever it waits on nobody: picks of players who left, and the reveal once all picked. */ +function settle(s: S, ev: Ev, rng: Rng): void { + for (let guard = 0; guard < 2000 && s.phase !== 'finished'; guard++) { + if (s.phase === 'draft') { + const p = s.seats[s.draft!.at]!; + if (isIn(s, p)) return; + perform(s, p, defaultAction(s, p)!, ev, rng); + continue; + } + if (s.phase === 'choose') { + const p = s.pending!.player; + if (isIn(s, p)) return; + perform(s, p, defaultAction(s, p)!, ev, rng); + continue; + } + if (s.phase === 'select') { + for (const p of s.seats) if (!isIn(s, p) && s.selections[p] === null) s.selections[p] = { card: safeCard(s, p), flip: false }; + if (s.seats.every((p) => s.selections[p] !== null)) { + reveal(s, ev, rng); + continue; + } + return; + } + return; + } +} + +// ---------------------------------------------------------------- result + +function rankRows(s: S): SixRankRow[] { + const rows = s.seats.map((p) => ({ player: p, total: s.totals[p]!, left: !isIn(s, p) })); + rows.sort((a, b) => Number(a.left) - Number(b.left) || a.total - b.total); + const out: SixRankRow[] = []; + rows.forEach((r, i) => { + const prev = out[i - 1]; + const tied = prev && (prev.left === r.left && (r.left || prev.total === r.total)); + out.push({ ...r, rank: tied ? prev.rank : i + 1 }); + }); + return out; +} + +function buildResult(s: S): SixResult { + const ranking = rankRows(s); + const winners = ranking.filter((r) => r.rank === 1).map((r) => r.player); + const top = ranking[0]!; + const lastRound = s.roundScores[s.seats[0]!]!.length; + let tail: string; + switch (s.endReason) { + case 'score': + tail = `${s.options.endScore}점을 넘긴 사람이 나와 ${lastRound}라운드에서 끝`; + break; + case 'rounds': + tail = `${lastRound}라운드 끝`; + break; + case 'cap': + tail = `${ROUND_CAP}라운드가 지나 끝`; + break; + default: + tail = '다른 사람이 모두 나가서 끝'; + } + const head = winners.length > 1 ? `공동 1등 ${winners.length}명(벌점 ${top.total}점)` : `1등 벌점 ${top.total}점`; + return { ranking, winners, summary: `${head} · ${tail}`, reason: s.endReason === 'resign' ? 'resign' : 'normal' }; +} + +// ---------------------------------------------------------------- view helpers + +function handView(s: S, p: PlayerId): SixHandCard[] { + const b = boardOf(s); + const flipOk = s.options.fanCard === 'flipDigits' && s.flipLeft[p]; + const rowsReady = s.rows.length === ROWS; + return s.hands[p]!.map((n) => { + const out: SixHandCard = { n, bulls: bulls(n), ...(rowsReady ? { preview: previewOf(b, playOf(p, n, false), s.options) } : {}) }; + if (rowsReady && flipOk && canFlip(n)) out.flipped = { value: flipValue(n), preview: previewOf(b, playOf(p, n, true), s.options) }; + return out; + }); +} + +// ---------------------------------------------------------------- definition + +export function setupSixNimmt(ctx: { players: PlayerId[]; options: SixNimmtOptions; rng: Rng; now: number }): S { + const { players, options, rng, now } = ctx; + const range = playersFor(options); + if (players.length < range.min || players.length > range.max) throw new Error(`six-nimmt: ${range.min}~${range.max}명이 할 수 있어요.`); + const per = (f: () => T) => Object.fromEntries(players.map((p) => [p, f()])); + const s: S = { + options, + seats: [...players], + deckMax: deckMaxFor(options.deck, players.length), + round: 1, + startSeat: rng.int(players.length), + turn: 1, + phase: 'select', + rows: [], + marker: null, + hands: per(() => []), + flipLeft: per(() => false), + aside: [], + draft: null, + selections: per(() => null), + queue: [], + pending: null, + taken: per(() => []), + totals: per(() => 0), + roundScores: per(() => []), + seen: [], + picked: per(() => []), + left: [], + timeouts: per(() => 0), + reveal: null, + revealSeq: 0, + lastRound: null, + bestTake: null, + log: [], + logSeq: 0, + turnSeq: 0, + deadlineAt: null, + clockMs: null, + clockExtra: 0, + endReason: null, + }; + startRound(s, rng, []); + refreshDeadline(s, now, 0); + return s; +} + +export const sixNimmt: GameDefinition = { + id: 'six-nimmt', + nameKo: '젝스님트', + minPlayers: 2, + maxPlayers: 10, + stateVersion: 1, + defaultOptions: sixNimmtOptionsSchema.parse({}), + optionsSchema: sixNimmtOptionsSchema as unknown as ZodType, + actionSchema: sixNimmtActionSchema as unknown as ZodType, + playersFor, + + setup: setupSixNimmt, + + validate(s, actor, a) { + if (!s.seats.includes(actor)) return fail('이 게임의 참가자가 아니에요.'); + if (s.phase === 'finished') return fail('게임이 이미 끝났어요.'); + if (!isIn(s, actor)) return fail('이미 나간 자리예요.'); + if (a.type === 'LEAVE') return ok; + if (a.type === 'TIMEOUT') return activeOf(s).includes(actor) ? ok : fail('지금은 시간 초과를 처리할 수 없어요.'); + switch (a.type) { + case 'DRAFT': + if (s.phase !== 'draft') return fail('지금은 카드를 골라 가져갈 때가 아니에요.'); + if (s.seats[s.draft!.at] !== actor) return fail('지금은 내 차례가 아니에요.'); + return s.draft!.pool.includes(a.card) ? ok : fail('펼쳐진 카드 중에서 골라 주세요.'); + case 'SELECT': { + if (s.phase !== 'select') return fail('이미 모두 냈어요.'); + if (!s.hands[actor]!.includes(a.card)) return fail('손에 없는 카드예요.'); + if (a.flip) { + if (s.options.fanCard !== 'flipDigits') return fail('이 방에서는 숫자 뒤집기를 쓰지 않아요.'); + if (!s.flipLeft[actor]) return fail('숫자 뒤집기는 라운드에 한 번만 쓸 수 있어요.'); + if (!canFlip(a.card)) return fail('100 이상은 뒤집을 수 없어요.'); + } + return ok; + } + case 'TAKE_ROW': + case 'PLACE': { + const pd = s.pending; + if (s.phase !== 'choose' || !pd || pd.player !== actor) return fail('지금은 줄을 고를 차례가 아니에요.'); + if (a.type === 'TAKE_ROW' && pd.kind !== 'takeRow') return fail('카드를 놓을 자리를 골라 주세요.'); + if (a.type === 'PLACE' && pd.kind !== 'place') return fail('가져갈 줄을 골라 주세요.'); + const side = a.type === 'PLACE' ? a.side : 'R'; + return pd.choices.some((c) => c.row === a.row && c.side === side) ? ok : fail('그 줄은 고를 수 없어요.'); + } + } + return fail('알 수 없는 행동이에요.'); + }, + + apply(prev, actor, a, { rng, now }) { + const s = structuredClone(prev); + const ev: Ev = []; + const seq = s.turnSeq; + if (a.type === 'TIMEOUT') { + s.timeouts[actor] = (s.timeouts[actor] ?? 0) + 1; + log(s, { t: 'timeout', player: actor }); + ev.push({ type: 'timeout', player: actor }); + if (s.timeouts[actor] === AWAY_AFTER) ev.push({ type: 'away', player: actor }); + const d = defaultAction(s, actor); + if (d) perform(s, actor, d, ev, rng); + } else { + if (a.type !== 'LEAVE') s.timeouts[actor] = 0; + perform(s, actor, a, ev, rng); + } + settle(s, ev, rng); + if (s.phase === 'finished') { + s.deadlineAt = null; + s.clockMs = null; + } else if (s.turnSeq !== seq || a.type === 'LEAVE') { + refreshDeadline(s, now, s.clockExtra); + s.clockExtra = 0; + } else if (s.phase === 'select' && a.type === 'SELECT') { + // Only "자리 비움" players are still picking: they get the short clock. + const wait = activeOf(s); + if (wait.length && wait.every((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER) && (s.deadlineAt === null || s.deadlineAt > now + AWAY_MS)) { + s.deadlineAt = now + AWAY_MS; + s.clockMs = AWAY_MS; + } + } + return { state: s, events: ev }; + }, + + view(s, viewer) { + const me = viewer !== null && s.seats.includes(viewer) ? viewer : null; + const tracker = s.options.cardTracker; + const players: SixNimmtView['players'] = {}; + for (const p of s.seats) { + players[p] = { + total: s.totals[p]!, + roundBulls: s.phase === 'finished' ? 0 : bullsOf(s.taken[p]!), + takenCount: s.phase === 'finished' ? 0 : s.taken[p]!.length, + picked: s.phase === 'select' && s.selections[p] !== null, + flipLeft: s.flipLeft[p]!, + left: !isIn(s, p), + away: isIn(s, p) && (s.timeouts[p] ?? 0) >= AWAY_AFTER, + }; + } + const d = s.draft; + const sel = me && s.phase === 'select' ? s.selections[me] : null; + const view: SixNimmtView = { + options: s.options, + me, + seats: [...s.seats], + deckMax: s.deckMax, + round: s.round, + turn: s.turn, + phase: s.phase, + startSeat: s.startSeat, + rows: s.rows.map((r) => ({ cards: r.map((n) => ({ n, bulls: bulls(n) })), bulls: rowBulls(r) })), + marker: s.marker ? { ...s.marker } : null, + players, + queue: s.queue.map((x) => ({ ...x })), + pending: s.pending ? structuredClone(s.pending) : null, + draft: d ? { pool: [...d.pool], at: s.seats[d.at]!, ...(tracker ? { picked: structuredClone(d.picked) } : {}) } : null, + roundScores: structuredClone(s.roundScores), + lastRound: s.lastRound ? structuredClone(s.lastRound) : null, + bestTake: s.bestTake ? { ...s.bestTake } : null, + reveal: s.reveal ? structuredClone(s.reveal) : null, + log: s.log.map((e) => structuredClone(e)), + turnSeq: s.turnSeq, + deadlineAt: s.deadlineAt, + clockMs: s.clockMs, + result: s.phase === 'finished' ? buildResult(s) : null, + }; + if (tracker) { + view.seen = [...s.seen].sort((a, b) => a - b); + if (s.options.deck === 'pro' && s.phase !== 'draft') { + const seen = new Set(s.seen); + view.known = Object.fromEntries(s.seats.map((p) => [p, s.picked[p]!.filter((c) => !seen.has(c)).sort((a, b) => a - b)])); + } + } + if (me && s.phase !== 'finished') { + view.my = { + key: handKey(me, s.hands[me]!), + hand: handView(s, me), + selected: sel ? { ...sel, key: selKey(s, me, sel.card) } : null, + taken: [...s.taken[me]!], + }; + } + return view; + }, + + activePlayers: activeOf, + + deadline(s) { + return s.phase === 'finished' ? null : s.deadlineAt; + }, + + onTimeout() { + return { type: 'TIMEOUT' }; + }, + + onLeave(s, player) { + if (s.phase === 'finished' || !s.seats.includes(player) || !isIn(s, player)) return null; + return { type: 'LEAVE' }; + }, + + result(s): GameResult | null { + if (s.phase !== 'finished') return null; + const r = buildResult(s); + const groups = new Map(); + for (const row of r.ranking) groups.set(row.rank, [...(groups.get(row.rank) ?? []), row.player]); + const scores: Record = {}; + for (const row of r.ranking) scores[row.player] = row.total; + return { + ranking: [...groups.entries()].sort((x, y) => x[0] - y[0]).map(([, ps]) => ps), + scores, + scoreText: Object.fromEntries(Object.entries(scores).map(([p, n]) => [p, `벌점 ${n}점`])), + summary: r.summary, + reason: r.reason, + }; + }, + + /** Test helper: every choice the player has now (LEAVE left out). */ + legalActions(s, player) { + if (!isIn(s, player) || !activeOf(s).includes(player)) return []; + switch (s.phase) { + case 'draft': + return s.draft!.pool.map((card) => ({ type: 'DRAFT' as const, card })); + case 'select': { + const out: A[] = []; + const flipOk = s.options.fanCard === 'flipDigits' && s.flipLeft[player]; + for (const card of s.hands[player]!) { + out.push({ type: 'SELECT', card }); + if (flipOk && canFlip(card)) out.push({ type: 'SELECT', card, flip: true }); + } + return out; + } + case 'choose': { + const pd = s.pending!; + return pd.kind === 'takeRow' ? pd.choices.map((c) => ({ type: 'TAKE_ROW' as const, row: c.row })) : pd.choices.map((c) => ({ type: 'PLACE' as const, row: c.row, side: c.side })); + } + } + return []; + }, + + /** Test helper (§8.3): other hands (not in the face-up pro draft), picks before the reveal, the unused cards. */ + secretsOf(s, player) { + const out: string[] = []; + if (s.options.deck !== 'pro' && s.phase !== 'finished') out.push(handKey(player, s.hands[player]!)); + const sel = s.phase === 'select' ? s.selections[player] : null; + if (sel) out.push(selKey(s, player, sel.card)); + if (s.aside.length) out.push(`six-aside:${s.aside.join(',')}`); + return out; + }, +}; + +/** Card total of the round (§8.1 invariant): hands + rows + cow piles + queue + unused + draft pool = deckMax. */ +export function cardCount(s: S): number { + let n = s.rows.reduce((t, r) => t + r.length, 0) + s.queue.length + s.aside.length + (s.draft?.pool.length ?? 0); + for (const p of s.seats) n += s.hands[p]!.length + s.taken[p]!.length; + return n; +} diff --git a/packages/games/src/six-nimmt/options.ts b/packages/games/src/six-nimmt/options.ts new file mode 100644 index 0000000..ab7338f --- /dev/null +++ b/packages/games/src/six-nimmt/options.ts @@ -0,0 +1,54 @@ +/** 젝스님트 options (docs/games/six-nimmt.md §2). The original rules are the defaults; variants are room settings. */ +import { z } from 'zod'; + +const lit = (...vals: T[]) => + z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); + +export const sixNimmtOptionsSchema = z + .object({ + deck: z + .enum(['all', 'tactics', 'pro']) + .default('all') + .meta({ + title: '카드 구성', + labels: { all: '104장 모두(기본)', tactics: '인원×10+4장만 섞어 나누기', pro: '인원×10+4장을 펼쳐 골라 가기(프로, 2~6명)' }, + }), + placement: z + .enum(['right', 'both']) + .default('right') + .meta({ title: '줄에 붙이는 곳', labels: { right: '오른쪽 끝에만(기본)', both: '양쪽 끝(왼쪽은 더 작은 수)' } }), + lowCard: z + .enum(['choose', 'fewest']) + .default('choose') + .meta({ title: '너무 작은 카드를 냈을 때', labels: { choose: '가져갈 줄을 직접 골라요', fewest: '소머리가 가장 적은 줄을 자동으로' } }), + fanCard: z + .enum(['none', 'evenOdd', 'mountain', 'jumpingCow', 'flipDigits']) + .default('none') + .meta({ + title: '특별 카드(30주년판)', + labels: { none: '안 써요', evenOdd: '짝홀', mountain: '산 오르기', jumpingCow: '점프하는 소', flipDigits: '숫자 뒤집기' }, + }), + endMode: z.enum(['score', 'rounds']).default('score').meta({ title: '끝나는 조건', labels: { score: '벌점 점수', rounds: '라운드 수' } }), + endScore: lit(33, 44, 55, 66, 77, 88, 99) + .default(66) + .meta({ title: '끝나는 벌점', labels: { 33: '33점', 44: '44점', 55: '55점', 66: '66점(기본)', 77: '77점', 88: '88점', 99: '99점' } }), + rounds: lit(1, 2, 3, 4, 5, 6) + .default(3) + .meta({ title: '라운드 수', labels: { 1: '1라운드', 2: '2라운드', 3: '3라운드', 4: '4라운드', 5: '5라운드', 6: '6라운드' } }), + cardTracker: z.boolean().default(true).meta({ title: '나온 카드 표', labels: { true: '보여요', false: '기억으로 해요' } }), + /** null = 무제한 (a dropped connection still gets automatic moves after the room's grace time). */ + turnSeconds: lit(15, 20, 30, 45, 60, null) + .default(30) + .meta({ title: '제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 45: '45초', 60: '60초', null: '무제한' } }), + }) + .superRefine((o, ctx) => { + if (o.fanCard !== 'none' && o.placement !== 'right') { + ctx.addIssue({ code: 'custom', path: ['fanCard'], message: '특별 카드는 "오른쪽 끝에만" 붙일 때만 쓸 수 있어요.' }); + } + }); + +export type SixNimmtOptions = z.infer; +export type FanCard = SixNimmtOptions['fanCard']; + +/** Players allowed by the options: the pro draft is 2~6 (원작 "2–6 Players"), everything else 2~10. */ +export const playersFor = (o: Pick): { min: number; max: number } => ({ min: 2, max: o.deck === 'pro' ? 6 : 10 }); diff --git a/packages/games/src/six-nimmt/rules.ts b/packages/games/src/six-nimmt/rules.ts new file mode 100644 index 0000000..f3bb6bd --- /dev/null +++ b/packages/games/src/six-nimmt/rules.ts @@ -0,0 +1,249 @@ +/** + * 젝스님트 pure rules (docs/games/six-nimmt.md §3, §5): bulls, digit flips and where a card goes on the four rows, + * including the 30th-anniversary fan cards. Shared by the engine, the view previews and the computer player. + */ +import type { PlayerId } from '@bg/engine'; +import type { SixNimmtOptions } from './options'; + +export type Card = number; +export type Side = 'L' | 'R'; +export type RowNo = 0 | 1 | 2 | 3; + +export type Marker = + | { kind: 'evenOdd'; row: number; parity: 'even' | 'odd' } + | { kind: 'mountain'; row: number; dir: 'up' | 'down' } + /** The cow stands at the right end of its row (after the last number card). */ + | { kind: 'cow'; row: number }; + +export interface Board { + rows: Card[][]; + marker: Marker | null; +} + +export interface Play { + player: PlayerId; + card: Card; + /** 숫자 뒤집기를 같이 냈나. */ + flip: boolean; + /** Number used for the order and the row (the flipped number when `flip`). */ + value: number; +} + +export interface Spot { + row: number; + side: Side; + diff: number; +} + +/** One thing that happened on the rows, with the rows as they look right after it (the screen replays these). */ +export type Step = + | { + t: 'place'; + player: PlayerId; + card: Card; + value: number; + row: number; + side: Side; + /** Cards taken by this placement (sixth card or a too-low card), else []. */ + took: Card[]; + bulls: number; + why: 'sixth' | 'low' | null; + rows: Card[][]; + marker: Marker | null; + } + | { t: 'marker'; from: number; to: number; rows: Card[][]; marker: Marker | null } + | { t: 'cow'; player: PlayerId; from: number; to: number; took: Card[]; bulls: number; rows: Card[][]; marker: Marker | null }; + +export const ROWS = 4; +/** A row holds at most this many slots (number cards, plus the cow); the next card takes them. */ +export const ROW_MAX = 5; +export const HAND = 10; + +// ---------------------------------------------------------------- cards + +/** 소머리 수 (§3). */ +export const bulls = (n: Card): number => (n === 55 ? 7 : n % 11 === 0 ? 5 : n % 10 === 0 ? 3 : n % 5 === 0 ? 2 : 1); +export const bullsOf = (cards: readonly Card[]): number => cards.reduce((t, c) => t + bulls(c), 0); + +/** 숫자 뒤집기: 31 → 13, 90 → 9, 7 → 70 (a one-digit number reads as "07", 우리 해석). 100 이상은 뒤집을 수 없음. */ +export function flipValue(n: Card): number { + if (n >= 100) throw new Error('100 이상은 뒤집을 수 없어요'); + if (n < 10) return n * 10; + return (n % 10) * 10 + Math.floor(n / 10); +} +export const canFlip = (n: Card): boolean => n <= 99; + +export const playOf = (player: PlayerId, card: Card, flip: boolean): Play => ({ player, card, flip, value: flip ? flipValue(card) : card }); + +/** Reveal order: smaller number first; on a tie the flipped card goes first (§5.5). */ +export const playOrder = (a: Play, b: Play): number => a.value - b.value || Number(b.flip) - Number(a.flip) || a.card - b.card; + +/** Cards used this round: 1..104, or 1..(players × 10 + 4) for the tactics/pro decks. */ +export const deckMaxFor = (deck: SixNimmtOptions['deck'], players: number): number => (deck === 'all' ? 104 : Math.min(104, players * HAND + 4)); + +// ---------------------------------------------------------------- rows + +const end = (r: Card[]): Card => r[r.length - 1]!; +const slots = (b: Board, row: number): number => b.rows[row]!.length + (b.marker?.kind === 'cow' && b.marker.row === row ? 1 : 0); +export const rowBulls = (r: readonly Card[]): number => bullsOf(r); +const cloneBoard = (b: Board): Board => ({ rows: b.rows.map((r) => [...r]), marker: b.marker ? { ...b.marker } : null }); +const snap = (b: Board) => ({ rows: b.rows.map((r) => [...r]), marker: b.marker ? { ...b.marker } : null }); + +/** + * Spots a card of `value` may go to (§5.2, §5.5): the closest one(s). Usually exactly one; two only for a tie with + * `placement = both` (the player picks); none when the card fits nowhere (rule 4: take a row). + */ +export function spotsFor(b: Board, value: number, o: Pick): Spot[] { + const all: (Spot & { mountain: boolean })[] = []; + const m = b.marker; + for (let i = 0; i < b.rows.length; i++) { + const r = b.rows[i]!; + const last = end(r); + if (m?.kind === 'mountain' && m.row === i) { + if (value < last) all.push({ row: i, side: 'R', diff: last - value, mountain: true }); + continue; + } + if (m?.kind === 'evenOdd' && m.row === i && (value % 2 === 0 ? 'even' : 'odd') !== m.parity) continue; + if (value > last) all.push({ row: i, side: 'R', diff: value - last, mountain: false }); + if (o.placement === 'both' && value < r[0]!) all.push({ row: i, side: 'L', diff: r[0]! - value, mountain: false }); + } + if (!all.length) return []; + const min = Math.min(...all.map((s) => s.diff)); + const best = all.filter((s) => s.diff === min); + // Mountain row wins a tie (산 오르기 규칙). + const mt = best.find((s) => s.mountain); + const out = mt ? [mt] : best; + return out.map(({ row, side, diff }) => ({ row, side, diff })); +} + +/** The row a too-low card takes automatically: fewest bulls, then the largest end card (§5.3 `fewest`). */ +export function fewestRow(b: Board): number { + let best = 0; + for (let i = 1; i < b.rows.length; i++) { + const d = rowBulls(b.rows[i]!) - rowBulls(b.rows[best]!); + if (d < 0 || (d === 0 && end(b.rows[i]!) > end(b.rows[best]!))) best = i; + } + return best; +} + +/** Row (other than `except`) with the smallest end card. */ +function smallestEnd(b: Board, except: number): number { + let best = -1; + for (let i = 0; i < b.rows.length; i++) { + if (i === except) continue; + if (best < 0 || end(b.rows[i]!) < end(b.rows[best]!)) best = i; + } + return best; +} + +/** + * Puts `play` at `row`/`side` (or takes the whole row when `low`), then moves the fan card. Mutates a copy of the + * board and returns it with the steps and every card the player took. + */ +export function placeAt(board: Board, play: Play, row: number, side: Side, low: boolean): { board: Board; steps: Step[]; took: Card[] } { + const b = cloneBoard(board); + const steps: Step[] = []; + const took: Card[] = []; + const r = b.rows[row]!; + let here: Card[] = []; + let why: 'sixth' | 'low' | null = null; + if (low) { + here = r; + why = 'low'; + b.rows[row] = [play.card]; + } else if (slots(b, row) >= ROW_MAX) { + here = r; + why = 'sixth'; + b.rows[row] = [play.card]; + } else if (side === 'R') r.push(play.card); + else r.unshift(play.card); + took.push(...here); + steps.push({ t: 'place', player: play.player, card: play.card, value: play.value, row, side, took: [...here], bulls: bullsOf(here), why, ...snap(b) }); + + const m = b.marker; + if (m && here.length && m.kind === 'evenOdd') { + const from = m.row; + const to = smallestEnd(b, from); + b.marker = { kind: 'evenOdd', row: to, parity: end(b.rows[to]!) % 2 === 0 ? 'even' : 'odd' }; + steps.push({ t: 'marker', from, to, ...snap(b) }); + } else if (m && here.length && m.kind === 'mountain') { + const from = m.row; + const to = Math.max(0, Math.min(ROWS - 1, from + (m.dir === 'up' ? -1 : 1))); + const dir = to === 0 ? 'down' : to === ROWS - 1 ? 'up' : m.dir; + b.marker = { kind: 'mountain', row: to, dir }; + steps.push({ t: 'marker', from, to, ...snap(b) }); + } else if (m && m.kind === 'cow' && m.row === row) { + // The cow jumps on to the row with the smallest end card; a row that now has six slots is taken too (keeping its + // largest card), and the cow jumps again. Every take removes four cards, so this stops. + let from = row; + for (let guard = 0; guard < 40; guard++) { + const to = smallestEnd(b, from); + b.marker = { kind: 'cow', row: to }; + const tr = b.rows[to]!; + if (tr.length >= ROW_MAX) { + const keep = Math.max(...tr); + const gone = tr.filter((c) => c !== keep); + b.rows[to] = [keep]; + took.push(...gone); + steps.push({ t: 'cow', player: play.player, from, to, took: gone, bulls: bullsOf(gone), ...snap(b) }); + from = to; + continue; + } + steps.push({ t: 'cow', player: play.player, from, to, took: [], bulls: 0, ...snap(b) }); + break; + } + } + return { board: b, steps, took }; +} + +/** Where a card would go and what it would take if it were played alone on these rows ("지금 기준" preview). */ +export type Preview = { row: number; side: Side; pos: number; takes: number; tie?: true } | { low: true; takes: number; row: number }; + +export function previewOf(b: Board, play: Play, o: Pick): Preview { + const spots = spotsFor(b, play.value, o); + if (!spots.length) { + const row = fewestRow(b); + return { low: true, takes: rowBulls(b.rows[row]!), row }; + } + const s = spots.find((x) => x.side === 'R') ?? spots[0]!; + const after = placeAt(b, play, s.row, s.side, false); + const r = after.board.rows[s.row]!; + return { row: s.row, side: s.side, pos: s.side === 'R' ? r.length : 1, takes: bullsOf(after.took), ...(spots.length > 1 ? { tie: true as const } : {}) }; +} + +/** Sets the fan card for a new round (§4.3). */ +export function startMarker(fan: SixNimmtOptions['fanCard'], rows: Card[][]): Marker | null { + let low = 0; + for (let i = 1; i < rows.length; i++) if (rows[i]![0]! < rows[low]![0]!) low = i; + switch (fan) { + case 'evenOdd': + return { kind: 'evenOdd', row: low, parity: rows[low]![0]! % 2 === 0 ? 'even' : 'odd' }; + case 'mountain': + return { kind: 'mountain', row: ROWS - 1, dir: 'up' }; + case 'jumpingCow': + return { kind: 'cow', row: low }; + default: + return null; + } +} + +/** + * Plays a whole revealed turn with nobody choosing (too-low cards take the fewest-bulls row, `both` ties go right): + * used by the computer's look-ahead. Returns bulls taken per player and the final board. + */ +export function simulateTurn(board: Board, plays: Play[], o: Pick): { board: Board; taken: Record } { + let b = board; + const taken: Record = {}; + for (const p of [...plays].sort(playOrder)) { + const spots = spotsFor(b, p.value, o); + let res; + if (!spots.length) res = placeAt(b, p, fewestRow(b), 'R', true); + else { + const s = spots.find((x) => x.side === 'R') ?? spots[0]!; + res = placeAt(b, p, s.row, s.side, false); + } + b = res.board; + taken[p.player] = (taken[p.player] ?? 0) + bullsOf(res.took); + } + return { board: b, taken }; +} diff --git a/packages/games/src/six-nimmt/six-nimmt.test.ts b/packages/games/src/six-nimmt/six-nimmt.test.ts new file mode 100644 index 0000000..c48bc98 --- /dev/null +++ b/packages/games/src/six-nimmt/six-nimmt.test.ts @@ -0,0 +1,584 @@ +/** 젝스님트 rules (docs/games/six-nimmt.md §10). */ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, checkNoLeak, checkRoundTrip, playoutSeeds, seedN } from '@bg/engine'; +import { + bulls, + cardCount, + flipValue, + placeAt, + playOf, + sixNimmt, + spotsFor, + type Card, + type Marker, + type SixNimmtAction, + type SixNimmtOptions, + type SixNimmtState, +} from './index'; + +const rng = (seed = 1) => SeededRng.fromSeed(seedN(seed)); +const opts = (o: Partial = {}) => sixNimmt.optionsSchema.parse(o) as SixNimmtOptions; +const make = (o: Partial = {}, players = ['A', 'B', 'C', 'D'], seed = 1) => sixNimmt.setup({ players, options: opts(o), rng: rng(seed), now: 0 }); + +/** A select-phase state with exactly these rows and hands (cards not listed are simply out of the round). */ +function custom(rows: Card[][], hands: Record, o: Partial = {}, marker: Marker | null = null): SixNimmtState { + const players = Object.keys(hands); + const s = make(o, players); + s.rows = rows.map((r) => [...r]); + s.marker = marker; + s.aside = []; + s.startSeat = 0; + for (const p of players) s.hands[p] = [...hands[p]!].sort((a, b) => a - b); + s.seen = rows.map((r) => r[0]!); + s.flipLeft = Object.fromEntries(players.map((p) => [p, o.fanCard === 'flipDigits'])); + return s; +} + +let now = 1; +function act(s: SixNimmtState, p: string, a: SixNimmtAction): SixNimmtState { + const v = sixNimmt.validate(s, p, a); + if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`); + return sixNimmt.apply(s, p, a, { rng: rng(now), now: now++ }).state; +} +const reason = (s: SixNimmtState, p: string, a: SixNimmtAction) => { + const v = sixNimmt.validate(s, p, a); + return v.ok ? null : v.reason; +}; +function turn(s: SixNimmtState, picks: Record): SixNimmtState { + for (const [p, c] of Object.entries(picks)) s = act(s, p, Array.isArray(c) ? { type: 'SELECT', card: c[0], flip: c[1] } : { type: 'SELECT', card: c }); + return s; +} + +// ---------------------------------------------------------------- cards + +describe('카드', () => { + test('소머리 수와 합계 171', () => { + expect(bulls(55)).toBe(7); + for (const n of [11, 22, 33, 44, 66, 77, 88, 99]) expect(bulls(n)).toBe(5); + for (const n of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) expect(bulls(n)).toBe(3); + for (const n of [5, 15, 25, 35, 45, 65, 75, 85, 95]) expect(bulls(n)).toBe(2); + expect(bulls(1)).toBe(1); + expect(bulls(104)).toBe(1); + let total = 0; + for (let n = 1; n <= 104; n++) total += bulls(n); + expect(total).toBe(171); + }); + + test('숫자 뒤집기 값', () => { + expect(flipValue(31)).toBe(13); + expect(flipValue(90)).toBe(9); + expect(flipValue(7)).toBe(70); + expect(flipValue(24)).toBe(42); + expect(() => flipValue(100)).toThrow(); + }); +}); + +// ---------------------------------------------------------------- setup + +describe('준비', () => { + test('all 4명: 10장씩, 줄 4장, 안 쓰는 카드 60장, 총 104장', () => { + const s = make(); + for (const p of s.seats) expect(s.hands[p]).toHaveLength(10); + expect(s.rows.map((r) => r.length)).toEqual([1, 1, 1, 1]); + expect(s.aside).toHaveLength(60); + expect(cardCount(s)).toBe(104); + expect(s.phase).toBe('select'); + const all = [...Object.values(s.hands).flat(), ...s.rows.flat(), ...s.aside].sort((a, b) => a - b); + expect(all).toEqual(Array.from({ length: 104 }, (_, i) => i + 1)); + }); + + test('tactics 3명: 1~34만, 안 쓰는 카드 없음', () => { + const s = make({ deck: 'tactics' }, ['A', 'B', 'C']); + expect(s.deckMax).toBe(34); + expect(s.aside).toHaveLength(0); + expect(Math.max(...Object.values(s.hands).flat(), ...s.rows.flat())).toBe(34); + expect(cardCount(s)).toBe(34); + }); + + test('같은 시드면 같은 분배', () => { + expect(JSON.stringify(make({}, ['A', 'B', 'C'], 9))).toBe(JSON.stringify(make({}, ['A', 'B', 'C'], 9))); + expect(JSON.stringify(make({}, ['A', 'B', 'C'], 9).hands)).not.toBe(JSON.stringify(make({}, ['A', 'B', 'C'], 10).hands)); + }); + + test('pro 3명: 1~34를 펼치고 시작 자리부터 돌아가며 30번 고른 뒤 남은 4장이 줄 시작', () => { + let s = make({ deck: 'pro' }, ['A', 'B', 'C']); + expect(s.phase).toBe('draft'); + expect(s.draft!.pool).toEqual(Array.from({ length: 34 }, (_, i) => i + 1)); + const first = s.seats[s.startSeat]!; + expect(sixNimmt.activePlayers(s)).toEqual([first]); + const order: string[] = []; + let picks = 0; + while (s.phase === 'draft') { + const p = sixNimmt.activePlayers(s)[0]!; + order.push(p); + // Take the biggest card each time, so the four smallest are left. + s = act(s, p, { type: 'DRAFT', card: Math.max(...s.draft!.pool) }); + picks++; + } + expect(picks).toBe(30); + expect(order.slice(0, 3)).toEqual([0, 1, 2].map((k) => s.seats[(s.startSeat + k) % 3]!)); + expect(s.rows).toEqual([[1], [2], [3], [4]]); + for (const p of s.seats) expect(s.hands[p]).toHaveLength(10); + expect(s.phase).toBe('select'); + }); + + test('pro는 2~6명, 나머지는 2~10명', () => { + expect(sixNimmt.playersFor!(opts({ deck: 'pro' }))).toEqual({ min: 2, max: 6 }); + expect(sixNimmt.playersFor!(opts({ deck: 'tactics' }))).toEqual({ min: 2, max: 10 }); + expect(() => make({ deck: 'pro' }, ['A', 'B', 'C', 'D', 'E', 'F', 'G'])).toThrow(); + }); + + test('특별 카드는 오른쪽 끝에만 붙일 때만', () => { + expect(sixNimmt.optionsSchema.safeParse({ placement: 'both', fanCard: 'mountain' }).success).toBe(false); + expect(sixNimmt.optionsSchema.safeParse({ placement: 'both' }).success).toBe(true); + expect(sixNimmt.optionsSchema.safeParse({ fanCard: 'flipDigits' }).success).toBe(true); + }); +}); + +// ---------------------------------------------------------------- basic rules + +describe('기본 규칙', () => { + test('§5.4 예시 그대로', () => { + let s = custom([[12], [37], [43], [58]], { A: [14, 21, 3], B: [15, 26, 9], C: [44, 30, 68], D: [61, 36, 83] }); + s = turn(s, { A: 14, B: 15, C: 44, D: 61 }); + expect(s.rows).toEqual([[12, 14, 15], [37], [43, 44], [58, 61]]); + s = turn(s, { A: 21, B: 26, C: 30, D: 36 }); + expect(s.taken.C).toEqual([12, 14, 15, 21, 26]); + expect(s.taken.C!.reduce((t, c) => t + bulls(c), 0)).toBe(6); + expect(s.rows[0]).toEqual([30, 36]); + s = turn(s, { A: 3, B: 9, C: 68, D: 83 }); + expect(s.phase).toBe('choose'); + expect(s.pending!.player).toBe('A'); + expect(s.pending!.kind).toBe('takeRow'); + expect(sixNimmt.activePlayers(s)).toEqual(['A']); + expect(reason(s, 'B', { type: 'TAKE_ROW', row: 1 })).toBe('지금은 줄을 고를 차례가 아니에요.'); + expect(reason(s, 'A', { type: 'SELECT', card: 3 })).toBe('이미 모두 냈어요.'); + // The view shows the other revealed cards waiting. + expect(sixNimmt.view(s, 'B').queue.map((q) => q.card)).toEqual([3, 9, 68, 83]); + // Round ends after the last card: check the rows just before scoring through the reveal record. + s = act(s, 'A', { type: 'TAKE_ROW', row: 1 }); + const last = s.reveal!.steps.at(-1)!; + expect(last.rows).toEqual([[30, 36], [3, 9], [43, 44], [58, 61, 68, 83]]); + expect(s.lastRound!.gained).toEqual({ A: 1, B: 0, C: 6, D: 0 }); + expect(s.totals).toEqual({ A: 1, B: 0, C: 6, D: 0 }); + }); + + test('함정: 끝 카드 41, 42에서 45는 42 다음, 그 줄이 5장이면 가져가요', () => { + expect(spotsFor({ rows: [[41], [42], [10], [90]], marker: null }, 45, { placement: 'right' })).toEqual([{ row: 1, side: 'R', diff: 3 }]); + const res = placeAt({ rows: [[41], [30, 33, 36, 39, 42], [10], [90]], marker: null }, playOf('A', 45, false), 1, 'R', false); + expect(res.took).toEqual([30, 33, 36, 39, 42]); + expect(res.board.rows[1]).toEqual([45]); + }); + + test('규칙 4는 그 차례의 가장 작은 카드만(기본 규칙), 두 번째 카드는 멈추지 않아요', () => { + let s = custom([[50], [60], [70], [80]], { A: [5, 99], B: [6, 98] }); + s = turn(s, { A: 5, B: 6 }); + expect(s.pending!.player).toBe('A'); + s = act(s, 'A', { type: 'TAKE_ROW', row: 0 }); + expect(s.phase).toBe('select'); + expect(s.rows[0]).toEqual([5, 6]); + }); + + test('lowCard = fewest: 소머리가 같으면 끝 카드가 큰 줄을 자동으로', () => { + let s = custom([[51], [52], [53], [54]], { A: [2, 99], B: [98, 97] }, { lowCard: 'fewest' }); + s = turn(s, { A: 2, B: 98 }); + expect(s.phase).toBe('select'); + expect(s.taken.A).toEqual([54]); + expect(s.rows[3]).toEqual([2]); + }); + + test('모두 고르기 전에는 바꿀 수 있고, 마지막 사람이 고르면 공개돼요', () => { + let s = custom([[10], [20], [30], [40]], { A: [11, 21], B: [31, 41] }); + s = act(s, 'A', { type: 'SELECT', card: 11 }); + expect(sixNimmt.view(s, 'B').players.A!.picked).toBe(true); + expect(sixNimmt.view(s, 'A').my!.selected!.card).toBe(11); + s = act(s, 'A', { type: 'SELECT', card: 21 }); + expect(sixNimmt.activePlayers(s)).toEqual(['B']); + s = act(s, 'B', { type: 'SELECT', card: 31 }); + expect(s.rows).toEqual([[10], [20, 21], [30, 31], [40]]); + expect(s.hands.A).toEqual([11]); + expect(reason(s, 'A', { type: 'SELECT', card: 21 })).toBe('손에 없는 카드예요.'); + }); +}); + +// ---------------------------------------------------------------- variants + +describe('양쪽 끝(both)', () => { + test('차이가 같은 두 자리면 고르고, 첫 카드보다 작으면 왼쪽에 붙어요', () => { + let s = custom([[5], [40], [46], [90]], { A: [43, 2, 60], B: [99, 98, 61] }, { placement: 'both' }); + s = turn(s, { A: 43, B: 99 }); + expect(s.phase).toBe('choose'); + expect(s.pending!.kind).toBe('place'); + expect(s.pending!.choices).toEqual([ + { row: 1, side: 'R' }, + { row: 2, side: 'L' }, + ]); + expect(reason(s, 'A', { type: 'PLACE', row: 0, side: 'R' })).toBe('그 줄은 고를 수 없어요.'); + s = act(s, 'A', { type: 'PLACE', row: 2, side: 'L' }); + expect(s.rows[2]).toEqual([43, 46]); + expect(s.rows[3]).toEqual([90, 99]); + s = turn(s, { A: 2, B: 98 }); + expect(s.rows[0]).toEqual([2, 5]); + }); + + test('5장 줄 왼쪽에 붙이면 5장을 가져가요', () => { + const res = placeAt({ rows: [[20, 21, 22, 23, 24], [50], [60], [70]], marker: null }, playOf('A', 18, false), 0, 'L', false); + expect(res.took).toEqual([20, 21, 22, 23, 24]); + expect(res.board.rows[0]).toEqual([18]); + expect(spotsFor({ rows: [[20, 24], [50], [60], [70]], marker: null }, 18, { placement: 'both' })).toEqual([{ row: 0, side: 'L', diff: 2 }]); + }); + + test('모든 줄 사이에 끼면 규칙 4', () => { + expect(spotsFor({ rows: [[10, 30], [40, 60], [70, 80], [90, 100]], marker: null }, 34, { placement: 'both' })).toEqual([{ row: 0, side: 'R', diff: 4 }]); + expect(spotsFor({ rows: [[10, 50], [11, 60], [12, 70], [13, 80]], marker: null }, 20, { placement: 'both' })).toEqual([]); + }); +}); + +describe('짝홀', () => { + test('홀 줄(끝 85)에는 짝수가 못 가요: 90은 52 다음 → 6번째라 가져가고, 짝홀 카드는 끝 31 줄로(홀)', () => { + const marker: Marker = { kind: 'evenOdd', row: 0, parity: 'odd' }; + const rows = [[85], [40, 44, 47, 50, 52], [31], [92]]; + expect(spotsFor({ rows, marker }, 90, { placement: 'right' })).toEqual([{ row: 1, side: 'R', diff: 38 }]); + const res = placeAt({ rows, marker }, playOf('A', 90, false), 1, 'R', false); + expect(res.took).toEqual([40, 44, 47, 50, 52]); + expect(res.board.marker).toEqual({ kind: 'evenOdd', row: 2, parity: 'odd' }); + expect(res.steps.map((x) => x.t)).toEqual(['place', 'marker']); + }); + + test('처음에는 첫 카드가 가장 작은 줄, 그 카드의 홀짝', () => { + const s = make({ fanCard: 'evenOdd' }); + const low = s.rows.reduce((b, r, i) => (r[0]! < s.rows[b]![0]! ? i : b), 0); + expect(s.marker).toEqual({ kind: 'evenOdd', row: low, parity: s.rows[low]![0]! % 2 ? 'odd' : 'even' }); + }); +}); + +describe('산 오르기', () => { + test('21은 12 다음 대신 산 오르기 줄 26 다음(내림차순) → 6번째라 가져가고 화살표 방향으로 한 줄', () => { + const marker: Marker = { kind: 'mountain', row: 3, dir: 'up' }; + const rows = [[12], [60], [70], [40, 35, 30, 28, 26]]; + expect(spotsFor({ rows, marker }, 21, { placement: 'right' })).toEqual([{ row: 3, side: 'R', diff: 5 }]); + const res = placeAt({ rows, marker }, playOf('A', 21, false), 3, 'R', false); + expect(res.took).toEqual([40, 35, 30, 28, 26]); + expect(res.board.marker).toEqual({ kind: 'mountain', row: 2, dir: 'up' }); + }); + + test('차이가 같으면 산 오르기 줄, 1번 줄에 닿으면 방향이 바뀌어요', () => { + const marker: Marker = { kind: 'mountain', row: 1, dir: 'up' }; + expect(spotsFor({ rows: [[17], [23], [60], [70]], marker }, 20, { placement: 'right' })).toEqual([{ row: 1, side: 'R', diff: 3 }]); + const res = placeAt({ rows: [[17], [23], [60], [70]], marker }, playOf('A', 1, false), 0, 'R', true); + expect(res.board.marker).toEqual({ kind: 'mountain', row: 0, dir: 'down' }); + const back = placeAt(res.board, playOf('A', 2, false), 2, 'R', true); + expect(back.board.marker).toEqual({ kind: 'mountain', row: 1, dir: 'down' }); + }); +}); + +describe('점프하는 소', () => { + test('숫자 4장 + 소 줄에 놓으면 4장만 가져가고 소는 끝 카드가 가장 작은 다른 줄(53)로', () => { + const marker: Marker = { kind: 'cow', row: 0 }; + const rows = [[30, 33, 36, 40], [78], [104], [50, 53]]; + expect(spotsFor({ rows, marker }, 43, { placement: 'right' })).toEqual([{ row: 0, side: 'R', diff: 3 }]); + const res = placeAt({ rows, marker }, playOf('A', 43, false), 0, 'R', false); + expect(res.took).toEqual([30, 33, 36, 40]); + expect(res.board.rows[0]).toEqual([43]); + expect(res.board.marker).toEqual({ kind: 'cow', row: 3 }); + }); + + test('뛰어간 줄이 6칸이면 같은 사람이 가장 큰 카드만 남기고 4장을 가져가고, 소가 또 뛰어요', () => { + const marker: Marker = { kind: 'cow', row: 0 }; + const rows = [[60], [78], [104], [41, 42, 44, 45, 53]]; + const res = placeAt({ rows, marker }, playOf('A', 61, false), 0, 'R', false); + expect(res.board.rows[0]).toEqual([60, 61]); + expect(res.board.rows[3]).toEqual([53]); + expect(res.took).toEqual([41, 42, 44, 45]); + // From row 3 the cow jumps to the smallest end among 61, 78, 104. + expect(res.board.marker).toEqual({ kind: 'cow', row: 0 }); + expect(res.steps.map((x) => x.t)).toEqual(['place', 'cow', 'cow']); + }); + + test('규칙 4로 소가 있는 줄을 가져가도 소는 뛰어요', () => { + const res = placeAt({ rows: [[60], [78], [90], [99]], marker: { kind: 'cow', row: 2 } }, playOf('A', 5, false), 2, 'R', true); + expect(res.took).toEqual([90]); + expect(res.board.rows[2]).toEqual([5]); + expect(res.board.marker).toEqual({ kind: 'cow', row: 0 }); + }); +}); + +describe('숫자 뒤집기', () => { + test('24 + 뒤집기 → 42로 줄을 정하고, 놓인 뒤에는 24(소머리 1)', () => { + let s = custom([[10], [40], [60], [80]], { A: [24, 1], B: [99, 98] }, { fanCard: 'flipDigits' }); + expect(sixNimmt.view(s, 'A').my!.hand.find((h) => h.n === 24)!.flipped).toEqual({ value: 42, preview: { row: 1, side: 'R', pos: 2, takes: 0 } }); + s = turn(s, { A: [24, true], B: 99 }); + expect(s.rows[1]).toEqual([40, 24]); + expect(s.flipLeft.A).toBe(false); + expect(reason(s, 'A', { type: 'SELECT', card: 1, flip: true })).toBe('숫자 뒤집기는 라운드에 한 번만 쓸 수 있어요.'); + }); + + test('13(뒤집어 31)과 31이 같이 나오면 뒤집은 사람이 먼저', () => { + let s = custom([[10], [20], [30], [90]], { A: [13, 2], B: [31, 3] }, { fanCard: 'flipDigits' }); + s = turn(s, { B: 31, A: [13, true] }); + expect(s.reveal!.plays.map((p) => p.player)).toEqual(['A', 'B']); + // 13 goes after 30 as "31"; back to 13 there, so the real 31 then goes after 20. + expect(s.rows[2]).toEqual([30, 13]); + expect(s.rows[1]).toEqual([20, 31]); + }); + + test('7은 70, 100 이상은 거부, 방에서 안 쓰면 거부', () => { + let s = custom([[10], [65], [75], [90]], { A: [7, 100], B: [99, 98] }, { fanCard: 'flipDigits' }); + expect(reason(s, 'A', { type: 'SELECT', card: 100, flip: true })).toBe('100 이상은 뒤집을 수 없어요.'); + s = turn(s, { A: [7, true], B: 99 }); + expect(s.rows[1]).toEqual([65, 7]); + const plain = custom([[10], [20], [30], [40]], { A: [7, 8], B: [99, 98] }); + expect(reason(plain, 'A', { type: 'SELECT', card: 7, flip: true })).toBe('이 방에서는 숫자 뒤집기를 쓰지 않아요.'); + }); + + test('다음 라운드에 새로 받아요', () => { + let s = make({ fanCard: 'flipDigits' }, ['A', 'B']); + s = act(s, 'A', { type: 'SELECT', card: s.hands.A!.find((c) => c < 100)!, flip: true }); + expect(s.flipLeft.A).toBe(true); // used at the reveal + while (s.round === 1 && s.phase !== 'finished') s = act(s, sixNimmt.activePlayers(s)[0]!, { type: 'TIMEOUT' }); + expect(s.round).toBe(2); + expect(s.flipLeft.A).toBe(true); + }); +}); + +// ---------------------------------------------------------------- scoring / end + +function playRound(s: SixNimmtState): SixNimmtState { + const r = s.round; + while (s.round === r && s.phase !== 'finished') s = act(s, sixNimmt.activePlayers(s)[0]!, { type: 'TIMEOUT' }); + return s; +} + +describe('점수와 끝', () => { + test('라운드 끝에 합산, 66 이상이면 그 라운드 끝에 종료, 공동 1등', () => { + let s = custom([[12], [37], [43], [58]], { A: [14, 21, 3], B: [15, 26, 9], C: [44, 30, 68], D: [61, 36, 83] }); + s.totals = { A: 69, B: 40, C: 34, D: 55 }; + s = turn(s, { A: 14, B: 15, C: 44, D: 61 }); + s = turn(s, { A: 21, B: 26, C: 30, D: 36 }); + s = turn(s, { A: 3, B: 9, C: 68, D: 83 }); + s = act(s, 'A', { type: 'TAKE_ROW', row: 1 }); + expect(s.phase).toBe('finished'); + expect(s.totals).toEqual({ A: 70, B: 40, C: 40, D: 55 }); + const r = sixNimmt.result(s)!; + expect(r.ranking).toEqual([['B', 'C'], ['D'], ['A']]); + expect(r.scoreText!.B).toBe('벌점 40점'); + expect(r.summary).toBe('공동 1등 2명(벌점 40점) · 66점을 넘긴 사람이 나와 1라운드에서 끝'); + }); + + test('도중에 66을 넘어도 그 라운드는 끝까지 해요', () => { + let s = make({}, ['A', 'B']); + s.totals.A = 90; + s = act(s, 'A', { type: 'TIMEOUT' }); + expect(s.phase).not.toBe('finished'); + s = playRound(s); + expect(s.phase).toBe('finished'); + expect(s.roundScores.A).toHaveLength(1); + }); + + test('endMode = rounds 3이면 정확히 3라운드', () => { + let s = make({ endMode: 'rounds', rounds: 3, endScore: 33 }, ['A', 'B', 'C']); + for (let i = 0; i < 3; i++) { + expect(s.phase).not.toBe('finished'); + s = playRound(s); + } + expect(s.phase).toBe('finished'); + expect(s.roundScores.A).toHaveLength(3); + expect(sixNimmt.result(s)!.summary).toContain('3라운드 끝'); + }); + + test('20라운드 안전장치', () => { + let s = make({ endScore: 99 }, ['A', 'B']); + s.round = 20; + s = playRound(s); + if (s.seats.every((p) => s.totals[p]! < 99)) { + expect(s.phase).toBe('finished'); + expect(sixNimmt.result(s)!.summary).toContain('20라운드가 지나 끝'); + } + }); + + test('새 라운드 첫 고르기는 5초 더', () => { + let s = custom([[10], [20], [30], [40]], { A: [50], B: [60] }, { turnSeconds: 15 }); + const t = 5_000_000; + s = sixNimmt.apply(s, 'A', { type: 'SELECT', card: 50 }, { rng: rng(3), now: t }).state; + s = sixNimmt.apply(s, 'B', { type: 'SELECT', card: 60 }, { rng: rng(3), now: t }).state; + expect(s.round).toBe(2); + expect(s.deadlineAt).toBe(t + 20_000); + s = sixNimmt.apply(s, 'A', { type: 'SELECT', card: s.hands.A![9]! }, { rng: rng(3), now: t + 1 }).state; + s = sixNimmt.apply(s, 'B', { type: 'SELECT', card: s.hands.B![9]! }, { rng: rng(3), now: t + 2 }).state; + expect(s.phase).toBe('select'); + expect(s.deadlineAt).toBe(t + 2 + 15_000); + }); +}); + +// ---------------------------------------------------------------- timeouts / leaving + +describe('시간 초과와 나가기', () => { + test('고르기 시간 초과 = 지금 줄 기준 가져갈 소머리가 가장 적은 카드(같으면 차이 작은 것)', () => { + let s = custom([[10, 11, 12, 13, 14], [40], [60], [80]], { A: [15, 45, 3], B: [99, 98, 97] }); + s = act(s, 'A', { type: 'TIMEOUT' }); + expect(s.selections.A).toEqual({ card: 45, flip: false }); + expect(s.timeouts.A).toBe(1); + }); + + test('줄 고르기 시간 초과 = 가장 적은 소머리 줄, 뽑아 가기 = 소머리 적고 작은 숫자', () => { + let s = custom([[50, 51], [55], [60, 61], [70]], { A: [2, 99], B: [98, 97] }); + s = turn(s, { A: 2, B: 98 }); + s = act(s, 'A', { type: 'TIMEOUT' }); + expect(s.taken.A).toEqual([70]); + let d = make({ deck: 'pro' }, ['A', 'B']); + const p = sixNimmt.activePlayers(d)[0]!; + d = act(d, p, { type: 'TIMEOUT' }); + expect(d.hands[p]).toEqual([1]); + }); + + test('3번 연속 시간 초과면 자리 비움(마감 5초)', () => { + let s = make({}, ['A', 'B']); + for (let g = 0; g < 100 && s.timeouts.A! < 3; g++) { + const p = sixNimmt.activePlayers(s).includes('A') ? 'A' : 'B'; + s = act(s, p, p === 'A' ? { type: 'TIMEOUT' } : s.phase === 'choose' ? { type: 'TAKE_ROW', row: 0 } : { type: 'SELECT', card: s.hands.B![0]! }); + } + expect(s.timeouts.A).toBe(3); + expect(sixNimmt.view(s, 'B').players.A!.away).toBe(true); + let c = custom([[10], [20], [30], [40]], { A: [50, 51], B: [60, 61] }); + c.timeouts.A = 3; + c = sixNimmt.apply(c, 'B', { type: 'SELECT', card: 60 }, { rng: rng(), now: 1000 }).state; + expect(c.deadlineAt).toBe(6000); + while (s.phase !== 'select') s = act(s, sixNimmt.activePlayers(s)[0]!, { type: 'TIMEOUT' }); + s = act(s, 'A', { type: 'SELECT', card: s.hands.A![0]! }); + expect(s.timeouts.A).toBe(0); + }); + + test('나간 사람 카드는 고르기가 열리자마자 자동으로, 결과는 맨 뒤, 남은 사람 1명이면 끝', () => { + let s = make({}, ['A', 'B', 'C']); + s = act(s, 'C', { type: 'LEAVE' }); + expect(s.selections.C).not.toBeNull(); + expect(sixNimmt.activePlayers(s).sort()).toEqual(['A', 'B']); + s = turn(s, { A: s.hands.A![0]!, B: s.hands.B![0]! }); + while (s.phase === 'choose') s = act(s, s.pending!.player, { type: 'TIMEOUT' }); + expect(s.hands.C).toHaveLength(9); + expect(s.selections.C).not.toBeNull(); + s = act(s, 'B', { type: 'LEAVE' }); + expect(s.phase).toBe('finished'); + const r = sixNimmt.result(s)!; + expect(r.ranking).toEqual([['A'], ['B', 'C']]); + expect(r.reason).toBe('resign'); + }); +}); + +// ---------------------------------------------------------------- hidden information + +describe('정보', () => { + test('공개 전 고른 카드·남의 손패·안 쓰는 카드가 남의 화면에 없어요', () => { + let s = make({}, ['A', 'B', 'C']); + s = act(s, 'A', { type: 'SELECT', card: s.hands.A![4]! }); + const vb = sixNimmt.view(s, 'B'); + const vn = sixNimmt.view(s, null); + for (const v of [vb, vn]) { + expect(JSON.stringify(v)).not.toContain('six-hand:A'); + expect(JSON.stringify(v)).not.toContain('six-sel:A'); + expect(v.players.A!.picked).toBe(true); + } + expect(JSON.stringify(sixNimmt.view(s, 'A'))).toContain('six-sel:A'); + expect(vn.my).toBeUndefined(); + expect(vb.my!.hand.map((h) => h.n)).toEqual(s.hands.B!); + checkNoLeak(sixNimmt, s, 'B', s.seats); + }); + + test('나온 카드 표를 끄면 seen·draft.picked가 없어요', () => { + const on = make({ deck: 'pro' }, ['A', 'B']); + expect(sixNimmt.view(on, 'A').draft!.picked).toBeDefined(); + expect(sixNimmt.view(on, 'A').seen).toBeDefined(); + const off = make({ deck: 'pro', cardTracker: false }, ['A', 'B']); + expect(sixNimmt.view(off, 'A').draft!.picked).toBeUndefined(); + expect(sixNimmt.view(off, 'A').seen).toBeUndefined(); + expect(sixNimmt.view(make({ cardTracker: false }), 'A').seen).toBeUndefined(); + }); + + test('pro + 표: 각자 아직 안 낸 카드가 보여요', () => { + let s = make({ deck: 'pro' }, ['A', 'B']); + while (s.phase === 'draft') s = act(s, sixNimmt.activePlayers(s)[0]!, { type: 'TIMEOUT' }); + const v = sixNimmt.view(s, 'A'); + expect(v.known!.B).toEqual(s.hands.B!); + }); +}); + +// ---------------------------------------------------------------- random playouts + +const OPTS: Partial[] = [ + {}, + { deck: 'pro', lowCard: 'fewest' }, + { deck: 'tactics', placement: 'both' }, + { fanCard: 'evenOdd', endMode: 'rounds', rounds: 2 }, + { fanCard: 'mountain', endScore: 33 }, + { fanCard: 'jumpingCow', deck: 'tactics' }, + { fanCard: 'flipDigits', cardTracker: false, turnSeconds: null }, +]; + +function invariant(s: SixNimmtState) { + if (s.phase === 'finished') return; + if (cardCount(s) !== s.deckMax) throw new Error(`card count ${cardCount(s)} != ${s.deckMax}`); + if (s.phase !== 'draft') { + for (let i = 0; i < s.rows.length; i++) { + const slotsUsed = s.rows[i]!.length + (s.marker?.kind === 'cow' && s.marker.row === i ? 1 : 0); + if (s.rows[i]!.length < 1 || slotsUsed > 5) throw new Error(`row ${i} has ${slotsUsed} slots`); + } + const n = s.hands[s.seats[0]!]!.length; + if (s.seats.some((p) => s.hands[p]!.length !== n)) throw new Error('hands of different sizes'); + } +} + +describe('무작위 대국', () => { + const seeds = playoutSeeds(1000); + const per = Math.max(2, Math.ceil(seeds / OPTS.length)); + for (const [oi, o] of OPTS.entries()) { + test(`옵션 ${JSON.stringify(o)}`, () => { + for (let i = 1; i <= per; i++) { + const max = o.deck === 'pro' ? 6 : 10; + const n = 2 + ((i + oi) % (max - 1)); + const players = Array.from({ length: n }, (_, k) => `P${k}`); + const seed = seedN(i * 31 + oi); + const r1 = playout(players, opts(o), seed); + if (i === 1) expect(playout(players, opts(o), seed)).toBe(r1); // determinism + } + }); + } +}); + +/** Random legal actions plus timeouts and the odd leave; checks invariants, JSON, leaks and onTimeout. Returns the final state JSON. */ +function playout(players: string[], o: SixNimmtOptions, seed: ReturnType): string { + const rr = SeededRng.fromSeed(seed); + const ch = SeededRng.fromSeed([seed[3], seed[2], seed[1], seed[0] ^ 0x9e3779b9]); + let t = 1_700_000_000_000; + let s = sixNimmt.setup({ players, options: o, rng: rr, now: t }); + for (let step = 0; step < 20_000; step++) { + checkRoundTrip(s); + invariant(s); + if (step % 7 === 0) for (const p of players) checkNoLeak(sixNimmt, s, p, players); + if (sixNimmt.result(s)) { + const res = sixNimmt.result(s)!; + expect(res.ranking.flat().sort()).toEqual([...players].sort()); + return JSON.stringify(s); + } + const actives = sixNimmt.activePlayers(s); + if (!actives.length) throw new Error('nobody to act'); + const actor = actives[ch.int(actives.length)]!; + const timeoutA = sixNimmt.onTimeout(s, actor); + if (!sixNimmt.validate(s, actor, timeoutA).ok) throw new Error('onTimeout not legal'); + let a: SixNimmtAction; + const r = ch.next(); + if (r < 0.002 && players.length > 2) a = { type: 'LEAVE' }; + else if (r < 0.1) a = timeoutA; + else { + const legal = sixNimmt.legalActions!(s, actor); + a = legal[ch.int(legal.length)]!; + } + const v = sixNimmt.validate(s, actor, a); + if (!v.ok) throw new Error(`rejected ${JSON.stringify(a)}: ${v.reason}`); + t += 1000; + const t0 = performance.now(); + s = sixNimmt.apply(s, actor, a, { rng: rr, now: t }).state; + const ms = performance.now() - t0; + if (ms > 20) throw new Error(`apply took ${ms.toFixed(1)}ms`); + } + throw new Error('game did not finish'); +} diff --git a/packages/games/src/six-nimmt/types.ts b/packages/games/src/six-nimmt/types.ts new file mode 100644 index 0000000..e5bb651 --- /dev/null +++ b/packages/games/src/six-nimmt/types.ts @@ -0,0 +1,167 @@ +/** 젝스님트 state, actions and view (docs/games/six-nimmt.md §8). */ +import { z } from 'zod'; +import type { GameResult, PlayerId } from '@bg/engine'; +import type { SixNimmtOptions } from './options'; +import type { Card, Marker, Play, Preview, Side, Step } from './rules'; + +const card = z.number().int().min(1).max(104); + +export const sixNimmtActionSchema = z.discriminatedUnion('type', [ + z.object({ type: z.literal('DRAFT'), card }), + z.object({ type: z.literal('SELECT'), card, flip: z.boolean().optional() }), + z.object({ type: z.literal('TAKE_ROW'), row: z.number().int().min(0).max(3) }), + z.object({ type: z.literal('PLACE'), row: z.number().int().min(0).max(3), side: z.enum(['L', 'R']) }), + z.object({ type: z.literal('LEAVE') }), +]); +export type SixNimmtClientAction = z.infer; +/** Client actions plus the system-only timer action (docs/09 §2). */ +export type SixNimmtAction = SixNimmtClientAction | { type: 'TIMEOUT' }; + +/** The game waits on one person's choice (§8.1). */ +export interface Pending { + player: PlayerId; + play: Play; + /** takeRow: rule 4 (too low) / place: two equally close spots with `placement = both`. */ + kind: 'takeRow' | 'place'; + choices: { row: number; side: Side }[]; +} + +/** One revealed turn as the screen replays it: the cards in order and every step on the rows so far. */ +export interface Reveal { + /** Unique per revealed turn. */ + id: number; + round: number; + turn: number; + plays: Play[]; + /** Rows before the first card was placed. */ + before: { rows: Card[][]; marker: Marker | null }; + steps: Step[]; +} + +export type LogEntry = + | { n: number; t: 'take'; player: PlayerId; row: number; cards: Card[]; bulls: number; why: 'sixth' | 'low' | 'cow' } + | { n: number; t: 'round'; round: number; gained: Record } + | { n: number; t: 'flip'; player: PlayerId; card: Card; value: number } + | { n: number; t: 'timeout'; player: PlayerId } + | { n: number; t: 'left'; player: PlayerId }; + +export interface SixNimmtState { + options: SixNimmtOptions; + seats: PlayerId[]; + deckMax: number; + round: number; + startSeat: number; + /** 1..10 within the round. */ + turn: number; + phase: 'draft' | 'select' | 'choose' | 'finished'; + rows: Card[][]; + marker: Marker | null; + /** Secret, sorted. */ + hands: Record; + flipLeft: Record; + /** `all`: cards not used this round (secret). */ + aside: Card[]; + /** `pro`: face-up cards to pick from; `at` = seat index picking now. */ + draft: { pool: Card[]; at: number; picked: Record } | null; + /** Secret picks before the reveal (the card stays in the hand until then). */ + selections: Record; + /** Revealed and not placed yet, in order. */ + queue: Play[]; + pending: Pending | null; + /** This round's cow pile (public). */ + taken: Record; + /** Totals of the rounds played so far. */ + totals: Record; + roundScores: Record; + /** Cards revealed this round (row starters included), for the card table. */ + seen: Card[]; + /** `pro`: every card each player picked this round (public in the original too). */ + picked: Record; + left: PlayerId[]; + timeouts: Record; + reveal: Reveal | null; + revealSeq: number; + lastRound: { round: number; gained: Record } | null; + /** The biggest single take of the game (result screen). */ + bestTake: { player: PlayerId; bulls: number; round: number } | null; + log: LogEntry[]; + logSeq: number; + turnSeq: number; + deadlineAt: number | null; + /** Ms the current clock was set to (timer ring). */ + clockMs: number | null; + /** Added once to the next clock (round break). */ + clockExtra: number; + endReason: 'score' | 'rounds' | 'cap' | 'resign' | null; +} + +export interface SixPlayerView { + total: number; + roundBulls: number; + takenCount: number; + picked: boolean; + flipLeft: boolean; + left: boolean; + away: boolean; +} + +export interface SixHandCard { + n: Card; + bulls: number; + /** Absent while the pro draft is still going (no rows yet). */ + preview?: Preview; + /** Preview with 숫자 뒤집기 (only when it can be used on this card). */ + flipped?: { value: number; preview: Preview }; +} + +export interface SixRankRow { + rank: number; + player: PlayerId; + total: number; + left: boolean; +} + +export interface SixResult { + ranking: SixRankRow[]; + winners: PlayerId[]; + summary: string; + reason: GameResult['reason']; +} + +export interface SixNimmtView { + options: SixNimmtOptions; + me: PlayerId | null; + seats: PlayerId[]; + deckMax: number; + round: number; + turn: number; + phase: SixNimmtState['phase']; + startSeat: number; + rows: { cards: { n: Card; bulls: number }[]; bulls: number }[]; + marker: Marker | null; + players: Record; + queue: Play[]; + pending: Pending | null; + draft: { pool: Card[]; at: PlayerId; picked?: Record } | null; + /** cardTracker only. */ + seen?: Card[]; + /** cardTracker + pro: cards each player picked and has not played yet. */ + known?: Record; + roundScores: Record; + lastRound: SixNimmtState['lastRound']; + bestTake: SixNimmtState['bestTake']; + reveal: Reveal | null; + log: LogEntry[]; + turnSeq: number; + deadlineAt: number | null; + /** Ms the current clock was set to (for the timer ring). */ + clockMs: number | null; + my?: { + /** Leak-check key (docs/09 §7): only the owner's view has it. */ + key: string; + hand: SixHandCard[]; + selected: { card: Card; flip: boolean; key: string } | null; + taken: Card[]; + }; + result: SixResult | null; +} diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index 134d6f7..6959d07 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -59,6 +59,7 @@ export const BOT_GAMES: readonly string[] = [ 'liar', 'magical-athlete', 'blackjack', + 'six-nimmt', ]; /** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */ diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index b95f2ac..17f4845 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -45,6 +45,7 @@ export const CATALOG: CatalogEntry[] = [ { id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true }, { id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true }, { id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true }, + { id: 'six-nimmt', nameKo: '젝스님트', minPlayers: 2, maxPlayers: 10, minutes: '20~45', level: '쉬움', blurb: '숫자 카드를 동시에 내고 작은 수부터 줄에 붙여요. 여섯 번째 카드면 소머리 벌점! · 10명까지', available: true }, ]; export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);