새 게임 젝스님트: 숫자 카드를 동시에 몰래 내고 작은 수부터 줄 끝에 붙이기, 여섯 번째 카드면 앞의 다섯 장(소머리 = 벌점)을 가져가는 2~10명 카드 게임

- 엔진 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 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 19:33:32 +09:00
parent 8620c82ca8
commit 88db031d0a
23 changed files with 3467 additions and 20 deletions

View File

@@ -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": {

View File

@@ -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<string, BotStrategy> = {
uno: unoBot,
'magical-athlete': magicalAthleteBot,
blackjack: blackjackBot,
'six-nimmt': sixNimmtBot,
};
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */

View File

@@ -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<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -69,4 +70,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[liar.id]: liar,
[magicalAthlete.id]: magicalAthlete,
[blackjack.id]: blackjack,
[sixNimmt.id]: sixNimmt,
};

View File

@@ -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<SixNimmtOptions> = {}) => sixNimmt.optionsSchema.parse(o) as SixNimmtOptions;
function custom(rows: Card[][], hands: Record<string, Card[]>, o: Partial<SixNimmtOptions> = {}): 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<SixNimmtAction, { type: 'DRAFT' }>;
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<SixNimmtOptions>[] = [
{ 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);
});
});

View File

@@ -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<Card>(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<SixNimmtView, Act> = ({ 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<string, number>();
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);
};

View File

@@ -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<T, 'n'> : 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<PlayerId, number> = {};
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<S['endReason']>): 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<A, { type: 'TIMEOUT' | 'LEAVE' }> | 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<A, { type: 'TIMEOUT' }>, 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 = <T>(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<S, A, SixNimmtView, SixNimmtOptions> = {
id: 'six-nimmt',
nameKo: '젝스님트',
minPlayers: 2,
maxPlayers: 10,
stateVersion: 1,
defaultOptions: sixNimmtOptionsSchema.parse({}),
optionsSchema: sixNimmtOptionsSchema as unknown as ZodType<SixNimmtOptions>,
actionSchema: sixNimmtActionSchema as unknown as ZodType<A>,
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<number, PlayerId[]>();
for (const row of r.ranking) groups.set(row.rank, [...(groups.get(row.rank) ?? []), row.player]);
const scores: Record<PlayerId, number> = {};
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;
}

View File

@@ -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 = <T extends number | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
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<typeof sixNimmtOptionsSchema>;
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<SixNimmtOptions, 'deck'>): { min: number; max: number } => ({ min: 2, max: o.deck === 'pro' ? 6 : 10 });

View File

@@ -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<SixNimmtOptions, 'placement'>): 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<SixNimmtOptions, 'placement'>): 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<SixNimmtOptions, 'placement'>): { board: Board; taken: Record<PlayerId, number> } {
let b = board;
const taken: Record<PlayerId, number> = {};
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 };
}

View File

@@ -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<SixNimmtOptions> = {}) => sixNimmt.optionsSchema.parse(o) as SixNimmtOptions;
const make = (o: Partial<SixNimmtOptions> = {}, 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<string, Card[]>, o: Partial<SixNimmtOptions> = {}, 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<string, Card | [Card, boolean]>): 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<SixNimmtOptions>[] = [
{},
{ 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<typeof seedN>): 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');
}

View File

@@ -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<typeof sixNimmtActionSchema>;
/** 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<PlayerId, number> }
| { 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<PlayerId, Card[]>;
flipLeft: Record<PlayerId, boolean>;
/** `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<PlayerId, Card[]> } | null;
/** Secret picks before the reveal (the card stays in the hand until then). */
selections: Record<PlayerId, { card: Card; flip: boolean } | null>;
/** Revealed and not placed yet, in order. */
queue: Play[];
pending: Pending | null;
/** This round's cow pile (public). */
taken: Record<PlayerId, Card[]>;
/** Totals of the rounds played so far. */
totals: Record<PlayerId, number>;
roundScores: Record<PlayerId, number[]>;
/** 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<PlayerId, Card[]>;
left: PlayerId[];
timeouts: Record<PlayerId, number>;
reveal: Reveal | null;
revealSeq: number;
lastRound: { round: number; gained: Record<PlayerId, number> } | 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<PlayerId, SixPlayerView>;
queue: Play[];
pending: Pending | null;
draft: { pool: Card[]; at: PlayerId; picked?: Record<PlayerId, Card[]> } | null;
/** cardTracker only. */
seen?: Card[];
/** cardTracker + pro: cards each player picked and has not played yet. */
known?: Record<PlayerId, Card[]>;
roundScores: Record<PlayerId, number[]>;
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;
}

View File

@@ -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명). */

View File

@@ -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);