도둑잡기(old-maid): 규칙·화면·컴퓨터 상대·테스트·문서·E2E
- 규칙 모듈 packages/games/src/old-maid: 2~8명, 트럼프 52장 + 조커 1장을 첫 사람(무작위)부터 한 장씩 나누고 같은 숫자 짝은 자동으로 버림. 차례에는 다음 자리(왼쪽)의 카드 있는 사람 손패에서 자리(index)로 한 장 뽑기(from 함께 보내 대상이 바뀌면 거절), 짝이 없으면 내 손패 무작위 자리에 숨김. 다 턴 순서대로 순위, 마지막 조커를 든 사람이 도둑(꼴찌). 결과 scoreText 에 "🃏 도둑"/"다 털었어요"/"나감" 표시. - 내 손패 섞기: 남은 사람 누구나 언제든, 차례마다 3번까지, 시계는 그대로. 남에게 보이는 자리는 실제 손패 순서이고, view 에는 남의 손패 장수만(뽑은 카드는 뽑은 사람에게만). - 시간 초과는 무작위 한 장 뽑기(3번 연속이면 5초), 카드를 든 채 나가면 그 카드를 섞어 다음 자리부터 한 장씩 나눠 주고 짝을 버림, 나간 사람은 맨 아래. 둘만 남았을 때 나가면 도둑 없이 끝. - 컴퓨터 상대(BOT_GAMES): 단계와 관계없이 무작위로 뽑고 가끔(15%) 자기 손패를 먼저 섞음. - 화면 apps/web/src/games/old-maid: 뽑힐 사람의 뒷면 카드를 펼쳐 고르기(tapConfirm 이면 두 번 눌러 확인, PC 한 번, 키보드 방향키+Enter), 섞으면 흔들림, 지난 뽑기·버린 짝, 내 손패(조커 표시)와 [🔀 섞기], 조커를 넘기면 알림. 30초 요약, 지금 할 수 있는 것, 규칙. - 등록(GAMES, 카탈로그, BOT_GAMES·전략, 화면 레지스트리, 아이콘·카드 탭), 도움말 테스트 게임 수 27, 문서 docs/games/old-maid.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,6 +29,7 @@ import { quoridorBot } from '../quoridor/bot';
|
||||
import { lasVegasBot } from '../las-vegas/bot';
|
||||
import { cockroachPokerBot } from '../cockroach-poker/bot';
|
||||
import { ninetyNineBot } from '../ninety-nine/bot';
|
||||
import { oldMaidBot } from '../old-maid/bot';
|
||||
import { mafiaBot } from '../mafia/bot';
|
||||
import { appleBot } from '../apple/bot';
|
||||
import { clueBot } from '../clue/bot';
|
||||
@@ -64,6 +65,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
'ninety-nine': ninetyNineBot,
|
||||
clue: clueBot,
|
||||
'connect-four': connectFourBot,
|
||||
'old-maid': oldMaidBot,
|
||||
};
|
||||
|
||||
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */
|
||||
|
||||
@@ -22,6 +22,7 @@ import { quoridor } from './quoridor';
|
||||
import { lasVegas } from './las-vegas';
|
||||
import { cockroachPoker } from './cockroach-poker';
|
||||
import { ninetyNine } from './ninety-nine';
|
||||
import { oldMaid } from './old-maid';
|
||||
import { dobble } from './dobble';
|
||||
import { catchmind } from './catchmind';
|
||||
import { mafia } from './mafia';
|
||||
@@ -53,6 +54,7 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[lasVegas.id]: lasVegas,
|
||||
[cockroachPoker.id]: cockroachPoker,
|
||||
[ninetyNine.id]: ninetyNine,
|
||||
[oldMaid.id]: oldMaid,
|
||||
[dobble.id]: dobble,
|
||||
[catchmind.id]: catchmind,
|
||||
[mafia.id]: mafia,
|
||||
|
||||
46
packages/games/src/old-maid/bot.test.ts
Normal file
46
packages/games/src/old-maid/bot.test.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { oldMaid as game, type OldMaidState } from './index';
|
||||
import { SHUFFLE_CHANCE } from './bot';
|
||||
|
||||
const setup = (players: string[], seed = 1): OldMaidState =>
|
||||
game.setup({ players, options: game.defaultOptions, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
const decide = (s: OldMaidState, p: string, r: number) => decideBotAction(game, s, p, { now: 0, random: () => r }) as Record<string, unknown>;
|
||||
|
||||
describe('old-maid bot', () => {
|
||||
test('draws a card from the neighbour it must draw from, at any spot', () => {
|
||||
const s = setup(['bot:1:x', 'B', 'C']);
|
||||
s.turn = 'bot:1:x';
|
||||
const from = 'B';
|
||||
const n = s.hands.B!.length;
|
||||
const spots = new Set<number>();
|
||||
for (const r of [0.2, 0.4, 0.6, 0.8, 0.99]) {
|
||||
const a = decide(s, 'bot:1:x', r);
|
||||
expect(a).toMatchObject({ type: 'draw', from });
|
||||
spots.add(a.index as number);
|
||||
}
|
||||
expect(spots.size).toBeGreaterThan(2);
|
||||
expect(Math.max(...spots)).toBeLessThan(n);
|
||||
});
|
||||
|
||||
test('now and then shuffles its own hand first, but only once a turn', () => {
|
||||
let s = setup(['bot:1:x', 'B', 'C']);
|
||||
s.turn = 'bot:1:x';
|
||||
expect(decide(s, 'bot:1:x', SHUFFLE_CHANCE / 2)).toEqual({ type: 'shuffle' });
|
||||
s = game.apply(s, 'bot:1:x', { type: 'shuffle' }, { rng: SeededRng.fromSeed([1, 2, 3, 4]), now: 1 }).state;
|
||||
expect(decide(s, 'bot:1:x', SHUFFLE_CHANCE / 2).type).toBe('draw');
|
||||
});
|
||||
|
||||
for (const n of [2, 5, 8]) {
|
||||
test(`bots finish a game: ${n} players`, () => {
|
||||
const players = ['h', ...Array.from({ length: n - 1 }, (_, i) => `bot:${i + 1}`)];
|
||||
for (let seed = 1; seed <= 3; seed++) {
|
||||
const r = botPlayout(game as never, { players, seed: seedN(seed), isBot: (p) => p.startsWith('bot:') });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
18
packages/games/src/old-maid/bot.ts
Normal file
18
packages/games/src/old-maid/bot.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 도둑잡기 computer player. There is nothing to read from face-down cards, so every level plays the same way: a random
|
||||
* card from the neighbour's fan, and now and then (like a person fidgeting) a shuffle of its own hand first. The
|
||||
* human-like thinking time comes from the room's bot driver. Uses only the view and the legal actions.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { pick, playable } from '../bots/policy';
|
||||
import { SHUFFLES_PER_TURN, type OldMaidAction, type OldMaidView } from './types';
|
||||
|
||||
/** Chance to shuffle its own hand before drawing (at most once a turn). */
|
||||
export const SHUFFLE_CHANCE = 0.15;
|
||||
|
||||
export const oldMaidBot: BotStrategy<OldMaidView, OldMaidAction> = ({ view, legal, random }) => {
|
||||
const draws = legal.filter((a) => a.type === 'draw');
|
||||
const fresh = (view.my?.shufflesLeft ?? 0) === SHUFFLES_PER_TURN;
|
||||
if (fresh && legal.some((a) => a.type === 'shuffle') && random() < SHUFFLE_CHANCE) return { type: 'shuffle' };
|
||||
return draws.length ? pick(draws, random) : pick(playable(legal), random);
|
||||
};
|
||||
398
packages/games/src/old-maid/index.ts
Normal file
398
packages/games/src/old-maid/index.ts
Normal file
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* 도둑잡기 (docs/games/old-maid.md).
|
||||
*
|
||||
* Secret-id design: card ids ("7H", "X1" = joker) only appear in a view when the viewer may know that card: their own
|
||||
* hand, thrown-away pairs (public), the card they just drew themselves, and every hand once the game is over. Other hands
|
||||
* are sent as counts only; a drawer picks a position, never a card.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { fail, isJoker, ok, rankOf, standardDeck, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
|
||||
import {
|
||||
JOKER,
|
||||
LOG_KEEP,
|
||||
SHUFFLES_PER_TURN,
|
||||
oldMaidActionSchema,
|
||||
oldMaidOptionsSchema,
|
||||
type DrawAction,
|
||||
type LogEntry,
|
||||
type OldMaidAction,
|
||||
type OldMaidOptions,
|
||||
type OldMaidState,
|
||||
type OldMaidView,
|
||||
type SeatStatus,
|
||||
} from './types';
|
||||
|
||||
export * from './types';
|
||||
|
||||
const AWAY_AFTER = 3;
|
||||
const AWAY_MS = 5000;
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
const finished = (s: OldMaidState) => s.final !== null;
|
||||
const isOut = (s: OldMaidState, p: PlayerId) => s.out.some((g) => g.includes(p));
|
||||
|
||||
/** Still in the game: holds cards and has not left. */
|
||||
export const inPlay = (s: OldMaidState, p: PlayerId): boolean => !s.left.includes(p) && !isOut(s, p) && (s.hands[p]?.length ?? 0) > 0;
|
||||
|
||||
/** Next player still in the game after `p` in seat order (not `p` itself), or null. */
|
||||
function nextInPlay(s: OldMaidState, p: PlayerId): PlayerId | null {
|
||||
const i = s.order.indexOf(p);
|
||||
for (let k = 1; k < s.order.length; k++) {
|
||||
const q = s.order[(i + k) % s.order.length]!;
|
||||
if (inPlay(s, q)) return q;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whom `p` draws from: the next player still holding cards (the one on the left). */
|
||||
export const targetOf = (s: OldMaidState, p: PlayerId): PlayerId | null => nextInPlay(s, p);
|
||||
|
||||
const playing = (s: OldMaidState) => s.order.filter((p) => inPlay(s, p));
|
||||
|
||||
function waiting(s: OldMaidState): PlayerId[] {
|
||||
return finished(s) || !s.turn ? [] : [s.turn];
|
||||
}
|
||||
|
||||
function turnMs(s: OldMaidState): number {
|
||||
return s.turn && s.away[s.turn] ? AWAY_MS : s.options.turnSeconds * 1000;
|
||||
}
|
||||
|
||||
function pushLog(s: OldMaidState, e: LogEntry): void {
|
||||
s.log.push(e);
|
||||
s.logCount += 1;
|
||||
if (s.log.length > LOG_KEEP) s.log.splice(0, s.log.length - LOG_KEEP);
|
||||
}
|
||||
|
||||
/** Throws away every pair in `p`'s hand (first two of a rank, in hand order); returns the pairs. */
|
||||
export function discardPairs(s: OldMaidState, p: PlayerId): [string, string][] {
|
||||
const hand = s.hands[p]!;
|
||||
const pairs: [string, string][] = [];
|
||||
const open = new Map<string, number>();
|
||||
const keep: string[] = [];
|
||||
for (const c of hand) {
|
||||
if (isJoker(c)) {
|
||||
keep.push(c);
|
||||
continue;
|
||||
}
|
||||
const r = rankOf(c);
|
||||
const at = open.get(r);
|
||||
if (at === undefined) {
|
||||
open.set(r, keep.length);
|
||||
keep.push(c);
|
||||
} else {
|
||||
pairs.push([keep[at]!, c]);
|
||||
keep[at] = '';
|
||||
open.delete(r);
|
||||
}
|
||||
}
|
||||
s.hands[p] = keep.filter((c) => c !== '');
|
||||
for (const [a, b] of pairs) s.discards[p]!.push(a, b);
|
||||
return pairs;
|
||||
}
|
||||
|
||||
/** Players in `who` (in that order) that just emptied their hand go out together as one finishing group. */
|
||||
function markOut(s: OldMaidState, who: PlayerId[], events: GameEvent[]): void {
|
||||
const fresh = who.filter((p) => !isOut(s, p) && !s.left.includes(p) && s.hands[p]!.length === 0);
|
||||
if (!fresh.length) return;
|
||||
const place = s.out.reduce((n, g) => n + g.length, 0) + 1;
|
||||
s.out.push(fresh);
|
||||
for (const p of fresh) {
|
||||
pushLog(s, { t: 'out', player: p, place });
|
||||
events.push({ type: 'out', player: p, place });
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends the game when at most one player still holds cards. Returns true when it ended. */
|
||||
function checkEnd(s: OldMaidState, byLeave: boolean, events: GameEvent[]): boolean {
|
||||
const rest = playing(s);
|
||||
if (rest.length > 1) return false;
|
||||
const holder = rest[0] ?? null;
|
||||
const thief = byLeave ? null : holder;
|
||||
const ranking: PlayerId[][] = s.out.map((g) => [...g]);
|
||||
if (holder) ranking.push([holder]);
|
||||
if (s.left.length) ranking.push([...s.left]);
|
||||
const summary = thief
|
||||
? '조커를 끝까지 들고 있던 꼴찌가 🃏 도둑이에요! 나머지는 손패를 먼저 다 턴 순서대로 순위가 정해졌어요'
|
||||
: '한 사람이 게임을 나가서 끝났어요. 손패를 먼저 다 턴 순서대로 순위가 정해졌어요';
|
||||
s.final = { thief, reason: byLeave ? 'left' : 'normal', ranking, summary };
|
||||
s.turn = null;
|
||||
events.push({ type: 'gameEnded', thief, reason: byLeave ? 'left' : 'normal' });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Turn goes to the next player in play after `p` (or stays with `p`'s next seat when `p` is gone). */
|
||||
function nextTurn(s: OldMaidState, p: PlayerId): void {
|
||||
s.turn = nextInPlay(s, p);
|
||||
s.turnNo += 1;
|
||||
s.shufflesThisTurn = Object.fromEntries(s.order.map((q) => [q, 0]));
|
||||
}
|
||||
|
||||
function validateDraw(s: OldMaidState, actor: PlayerId, a: DrawAction): Validation {
|
||||
if (s.turn !== actor) return fail('지금은 내 차례가 아니에요.');
|
||||
const from = targetOf(s, actor);
|
||||
if (!from || a.from !== from) return fail('지금은 그 사람의 카드를 뽑을 수 없어요. 화면이 바뀌었는지 확인해 주세요.');
|
||||
if (!Number.isInteger(a.index) || a.index < 0 || a.index >= s.hands[from]!.length) return fail('없는 자리의 카드예요.');
|
||||
return ok;
|
||||
}
|
||||
|
||||
function canShuffle(s: OldMaidState, p: PlayerId): boolean {
|
||||
return !finished(s) && inPlay(s, p) && s.hands[p]!.length >= 2 && (s.shufflesThisTurn[p] ?? 0) < SHUFFLES_PER_TURN;
|
||||
}
|
||||
|
||||
function applyDraw(s: OldMaidState, actor: PlayerId, a: DrawAction, rng: Rng, events: GameEvent[], auto: boolean): void {
|
||||
const from = a.from;
|
||||
const card = s.hands[from]!.splice(a.index, 1)[0]!;
|
||||
const hand = s.hands[actor]!;
|
||||
const mate = isJoker(card) ? -1 : hand.findIndex((c) => !isJoker(c) && rankOf(c) === rankOf(card));
|
||||
let pair: [string, string] | null = null;
|
||||
if (mate >= 0) {
|
||||
pair = [hand[mate]!, card];
|
||||
hand.splice(mate, 1);
|
||||
s.discards[actor]!.push(...pair);
|
||||
} else {
|
||||
// Slipped in at a random spot, so the player it came from can't tell where it is (matters with 2 players).
|
||||
hand.splice(rng.int(hand.length + 1), 0, card);
|
||||
}
|
||||
s.lastDraw = { no: s.turnNo, drawer: actor, from, index: a.index, card, pair, auto };
|
||||
pushLog(s, { t: 'draw', no: s.turnNo, drawer: actor, from, index: a.index, pair, auto });
|
||||
events.push({ type: 'draw', drawer: actor, from, index: a.index, ...(pair ? { pair } : {}), auto });
|
||||
// The one drawn from emptied first, then the drawer (if the pair was their last card).
|
||||
markOut(s, [from], events);
|
||||
markOut(s, [actor], events);
|
||||
if (!checkEnd(s, false, events)) nextTurn(s, actor);
|
||||
}
|
||||
|
||||
/** A player with cards leaves: their cards are shuffled and dealt one by one to the others still in play, from the next seat. */
|
||||
function applyLeave(s: OldMaidState, actor: PlayerId, rng: Rng, events: GameEvent[]): void {
|
||||
const cards = rng.shuffle([...s.hands[actor]!]);
|
||||
s.hands[actor] = [];
|
||||
s.left.push(actor);
|
||||
const wasTurn = s.turn === actor;
|
||||
const receivers = playing(s);
|
||||
const start = receivers.length ? Math.max(0, receivers.indexOf(nextInPlay(s, actor) ?? receivers[0]!)) : 0;
|
||||
const counts = new Map<PlayerId, number>();
|
||||
if (receivers.length) {
|
||||
cards.forEach((c, i) => {
|
||||
const to = receivers[(start + i) % receivers.length]!;
|
||||
const hand = s.hands[to]!;
|
||||
hand.splice(rng.int(hand.length + 1), 0, c);
|
||||
counts.set(to, (counts.get(to) ?? 0) + 1);
|
||||
});
|
||||
}
|
||||
const pairs: [string, string][] = [];
|
||||
for (const p of receivers) if (counts.has(p)) pairs.push(...discardPairs(s, p));
|
||||
pushLog(s, { t: 'left', player: actor, gave: [...counts].map(([to, count]) => ({ to, count })), pairs });
|
||||
events.push({ type: 'left', player: actor });
|
||||
markOut(s, receivers, events);
|
||||
if (checkEnd(s, true, events)) return;
|
||||
if (wasTurn || !s.turn || !inPlay(s, s.turn)) nextTurn(s, wasTurn || !s.turn ? actor : s.turn);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definition
|
||||
|
||||
export const oldMaid: GameDefinition<OldMaidState, OldMaidAction, OldMaidView, OldMaidOptions> = {
|
||||
id: 'old-maid',
|
||||
nameKo: '도둑잡기',
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
stateVersion: 1,
|
||||
defaultOptions: oldMaidOptionsSchema.parse({}),
|
||||
optionsSchema: oldMaidOptionsSchema as unknown as z.ZodType<OldMaidOptions>,
|
||||
actionSchema: oldMaidActionSchema as unknown as z.ZodType<OldMaidAction>,
|
||||
|
||||
setup({ players, options, rng, now }) {
|
||||
if (players.length < 2 || players.length > 8) throw new Error(`old-maid: ${players.length} players not allowed`);
|
||||
const deck = rng.shuffle(standardDeck(1));
|
||||
const per = <T>(f: (p: PlayerId) => T) => Object.fromEntries(players.map((p) => [p, f(p)])) as Record<PlayerId, T>;
|
||||
const first = players[rng.int(players.length)]!;
|
||||
const fi = players.indexOf(first);
|
||||
const hands = per<string[]>(() => []);
|
||||
// Dealt one at a time from the first player, so the first players get the extra card.
|
||||
deck.forEach((c, i) => hands[players[(fi + i) % players.length]!]!.push(c));
|
||||
const s: OldMaidState = {
|
||||
options,
|
||||
order: [...players],
|
||||
hands,
|
||||
discards: per(() => []),
|
||||
out: [],
|
||||
left: [],
|
||||
turn: first,
|
||||
turnNo: 1,
|
||||
shuffles: per(() => 0),
|
||||
shufflesThisTurn: per(() => 0),
|
||||
lastDraw: null,
|
||||
log: [],
|
||||
logCount: 0,
|
||||
timeoutsInRow: per(() => 0),
|
||||
away: per(() => false),
|
||||
turnStartedAt: now,
|
||||
seq: 0,
|
||||
final: null,
|
||||
};
|
||||
for (const p of players) discardPairs(s, p);
|
||||
// Rare: someone threw away their whole hand right away (they go out together, in seat order).
|
||||
const events: GameEvent[] = [];
|
||||
markOut(s, players, events);
|
||||
if (!checkEnd(s, false, events) && !inPlay(s, first)) s.turn = nextInPlay(s, first);
|
||||
return s;
|
||||
},
|
||||
|
||||
validate(s, actor, a) {
|
||||
if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
|
||||
if (finished(s)) return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'leave':
|
||||
return ok;
|
||||
case 'timeout':
|
||||
return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
|
||||
case 'shuffle':
|
||||
if (!inPlay(s, actor)) return fail('손에 카드가 없어요.');
|
||||
if (s.hands[actor]!.length < 2) return fail('카드가 2장 이상일 때 섞을 수 있어요.');
|
||||
return canShuffle(s, actor) ? ok : fail(`손패는 한 차례에 ${SHUFFLES_PER_TURN}번까지 섞을 수 있어요.`);
|
||||
case 'draw':
|
||||
return validateDraw(s, actor, a);
|
||||
default:
|
||||
return fail('알 수 없는 행동이에요.');
|
||||
}
|
||||
},
|
||||
|
||||
apply(prev, actor, a, { rng, now }) {
|
||||
const s = structuredClone(prev);
|
||||
const events: GameEvent[] = [];
|
||||
s.seq += 1;
|
||||
switch (a.type) {
|
||||
case 'shuffle':
|
||||
s.hands[actor] = rng.shuffle(s.hands[actor]!);
|
||||
s.shuffles[actor] = (s.shuffles[actor] ?? 0) + 1;
|
||||
s.shufflesThisTurn[actor] = (s.shufflesThisTurn[actor] ?? 0) + 1;
|
||||
pushLog(s, { t: 'shuffle', player: actor });
|
||||
events.push({ type: 'shuffle', player: actor });
|
||||
// Shuffling does not restart the turn clock.
|
||||
return { state: s, events };
|
||||
case 'leave':
|
||||
events.push({ type: 'left', player: actor });
|
||||
// Someone already out keeps their place; nothing changes.
|
||||
if (inPlay(s, actor)) applyLeave(s, actor, rng, events);
|
||||
break;
|
||||
case 'timeout': {
|
||||
const from = targetOf(s, actor)!;
|
||||
const concrete: DrawAction = { type: 'draw', from, index: rng.int(s.hands[from]!.length) };
|
||||
const v = validateDraw(s, actor, concrete);
|
||||
if (!v.ok) throw new Error(`old-maid: auto draw rejected: ${v.reason}`);
|
||||
s.timeoutsInRow[actor] = (s.timeoutsInRow[actor] ?? 0) + 1;
|
||||
events.push({ type: 'timeout', player: actor });
|
||||
if (s.timeoutsInRow[actor]! >= AWAY_AFTER && !s.away[actor]) {
|
||||
s.away[actor] = true;
|
||||
events.push({ type: 'away', player: actor });
|
||||
}
|
||||
applyDraw(s, actor, concrete, rng, events, true);
|
||||
break;
|
||||
}
|
||||
case 'draw':
|
||||
s.timeoutsInRow[actor] = 0;
|
||||
s.away[actor] = false;
|
||||
applyDraw(s, actor, a, rng, events, false);
|
||||
break;
|
||||
}
|
||||
s.turnStartedAt = now;
|
||||
return { state: s, events };
|
||||
},
|
||||
|
||||
view(s, viewer) {
|
||||
const me = viewer && s.order.includes(viewer) ? viewer : null;
|
||||
const over = finished(s);
|
||||
const per = <T>(f: (p: PlayerId) => T) => Object.fromEntries(s.order.map((p) => [p, f(p)])) as Record<PlayerId, T>;
|
||||
const places: Record<PlayerId, number> = {};
|
||||
let place = 1;
|
||||
for (const g of s.out) {
|
||||
for (const p of g) places[p] = place;
|
||||
place += g.length;
|
||||
}
|
||||
const target = s.turn ? targetOf(s, s.turn) : null;
|
||||
const ld = s.lastDraw;
|
||||
let my: OldMaidView['my'] = null;
|
||||
if (me && !over) {
|
||||
const drawing = s.turn === me && !!target;
|
||||
my = {
|
||||
canDraw: drawing,
|
||||
from: drawing ? target : null,
|
||||
count: drawing ? s.hands[target!]!.length : 0,
|
||||
canShuffle: canShuffle(s, me),
|
||||
shufflesLeft: inPlay(s, me) ? SHUFFLES_PER_TURN - (s.shufflesThisTurn[me] ?? 0) : 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
options: s.options,
|
||||
me,
|
||||
order: s.order,
|
||||
phase: over ? 'finished' : 'playing',
|
||||
turn: s.turn,
|
||||
target,
|
||||
turnNo: s.turnNo,
|
||||
handCounts: per((p) => s.hands[p]!.length),
|
||||
pairCounts: per((p) => s.discards[p]!.length / 2),
|
||||
status: per<SeatStatus>((p) => (s.left.includes(p) ? 'left' : isOut(s, p) ? 'out' : 'playing')),
|
||||
places,
|
||||
shuffles: { ...s.shuffles },
|
||||
myHand: me ? [...s.hands[me]!] : null,
|
||||
lastDraw: ld ? { ...ld, card: ld.pair || over || ld.drawer === me ? ld.card : null } : null,
|
||||
my,
|
||||
log: s.log.map((e) => structuredClone(e)),
|
||||
logCount: s.logCount,
|
||||
away: { ...s.away },
|
||||
turnStartedAt: s.turnStartedAt,
|
||||
turnMs: turnMs(s),
|
||||
seq: s.seq,
|
||||
final: s.final,
|
||||
revealed: over ? per((p) => [...s.hands[p]!]) : null,
|
||||
};
|
||||
},
|
||||
|
||||
activePlayers: waiting,
|
||||
|
||||
deadline(s) {
|
||||
return finished(s) || !s.turn ? null : s.turnStartedAt + turnMs(s);
|
||||
},
|
||||
|
||||
timeoutPlayers: waiting,
|
||||
|
||||
onTimeout() {
|
||||
return { type: 'timeout' };
|
||||
},
|
||||
|
||||
/** Leaving with cards hands them out to the others (§8.5); someone already out just keeps their place. */
|
||||
onLeave(s, player) {
|
||||
if (!s.order.includes(player) || finished(s) || !inPlay(s, player)) return null;
|
||||
return { type: 'leave' };
|
||||
},
|
||||
|
||||
result(s): GameResult | null {
|
||||
const f = s.final;
|
||||
if (!f) return null;
|
||||
// The result screen has no names in the summary: the thief is marked next to their name instead.
|
||||
const scoreText: Record<PlayerId, string> = {};
|
||||
for (const p of f.ranking.flat()) {
|
||||
scoreText[p] = p === f.thief ? '🃏 도둑' : s.left.includes(p) ? '나감' : isOut(s, p) ? '다 털었어요' : `카드 ${s.hands[p]!.length}장 남음`;
|
||||
}
|
||||
return { ranking: f.ranking, scoreText, summary: f.summary, reason: f.reason === 'left' ? 'resign' : 'normal' };
|
||||
},
|
||||
|
||||
legalActions(s, p) {
|
||||
if (finished(s) || s.turn !== p) return [];
|
||||
const from = targetOf(s, p);
|
||||
if (!from) return [];
|
||||
const out: OldMaidAction[] = s.hands[from]!.map((_, index) => ({ type: 'draw', from, index }));
|
||||
if (canShuffle(s, p)) out.push({ type: 'shuffle' });
|
||||
return out;
|
||||
},
|
||||
|
||||
/** `player`'s hand. */
|
||||
secretsOf(s, player) {
|
||||
if (finished(s)) return [];
|
||||
return [...(s.hands[player] ?? [])];
|
||||
},
|
||||
};
|
||||
|
||||
/** Whether `p` holds the joker (tests / summaries only — never sent to other players). */
|
||||
export const holdsJoker = (s: OldMaidState, p: PlayerId): boolean => s.hands[p]?.includes(JOKER) ?? false;
|
||||
432
packages/games/src/old-maid/old-maid.test.ts
Normal file
432
packages/games/src/old-maid/old-maid.test.ts
Normal file
@@ -0,0 +1,432 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, isJoker, playoutSeeds, randomPlayout, rankOf, seedN, standardDeck, type GameEvent } from '@bg/engine';
|
||||
import { JOKER, SHUFFLES_PER_TURN, holdsJoker, inPlay, oldMaid as game, targetOf, type OldMaidAction, type OldMaidOptions, type OldMaidState } from './index';
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
let clock = 1_000;
|
||||
const rng = (n = 7) => SeededRng.fromSeed([n, n, n, n]);
|
||||
|
||||
function setup(players = ['A', 'B', 'C'], seed = 1, opts: Partial<OldMaidOptions> = {}): OldMaidState {
|
||||
return game.setup({ players, options: game.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
}
|
||||
|
||||
/** A game in progress with exactly these hands (no pairs inside a hand), `turn` to draw. Unlisted cards count as thrown away. */
|
||||
function rigged(hands: Record<string, string[]>, turn?: string): OldMaidState {
|
||||
const players = Object.keys(hands);
|
||||
const s = setup(players);
|
||||
const used = new Set(Object.values(hands).flat());
|
||||
const rest = standardDeck(1).filter((c) => !used.has(c));
|
||||
for (const p of players) {
|
||||
s.hands[p] = [...hands[p]!];
|
||||
s.discards[p] = [];
|
||||
}
|
||||
s.discards[players[0]!] = rest;
|
||||
s.out = [];
|
||||
s.left = [];
|
||||
s.turn = turn ?? players[0]!;
|
||||
s.turnNo = 1;
|
||||
s.log = [];
|
||||
s.lastDraw = null;
|
||||
return s;
|
||||
}
|
||||
|
||||
/** A different (but reproducible) RNG per call, so repeated timeouts don't keep picking the same spot. */
|
||||
let calls = 0;
|
||||
function actE(s: OldMaidState, p: string, a: OldMaidAction, r = rng(++calls)): { state: OldMaidState; events: GameEvent[] } {
|
||||
const v = game.validate(s, p, a);
|
||||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||||
return game.apply(s, p, a, { rng: r, now: (clock += 1000) });
|
||||
}
|
||||
const act = (s: OldMaidState, p: string, a: OldMaidAction, r?: SeededRng) => actE(s, p, a, r).state;
|
||||
const reject = (s: OldMaidState, p: string, a: OldMaidAction) => {
|
||||
const v = game.validate(s, p, a);
|
||||
return v.ok ? null : v.reason;
|
||||
};
|
||||
const draw = (s: OldMaidState, p: string, index: number) => act(s, p, { type: 'draw', from: targetOf(s, p)!, index });
|
||||
const sorted = (xs: string[]) => [...xs].sort();
|
||||
|
||||
/** Every card exists exactly once across hands and discards; no hand holds a pair. */
|
||||
/** `pairs`: also check that discards come in same-rank pairs (off for rigged states, whose unused cards are dumped there). */
|
||||
function checkInvariants(st: unknown, pairs = true): void {
|
||||
const s = st as OldMaidState;
|
||||
const all = [...Object.values(s.hands).flat(), ...Object.values(s.discards).flat()];
|
||||
if (all.length !== 53) throw new Error(`card count ${all.length}`);
|
||||
if (new Set(all).size !== 53) throw new Error('duplicate card');
|
||||
if (!Object.values(s.hands).flat().includes(JOKER)) throw new Error('joker thrown away');
|
||||
for (const [p, h] of Object.entries(s.hands)) {
|
||||
const ranks = h.filter((c) => !isJoker(c)).map(rankOf);
|
||||
if (new Set(ranks).size !== ranks.length) throw new Error(`${p} keeps a pair`);
|
||||
}
|
||||
if (pairs) {
|
||||
for (const d of Object.values(s.discards)) for (let i = 0; i < d.length; i += 2) if (rankOf(d[i]!) !== rankOf(d[i + 1]!)) throw new Error(`bad pair ${d[i]} ${d[i + 1]}`);
|
||||
}
|
||||
if (!s.final && s.turn && !inPlay(s, s.turn)) throw new Error(`turn on ${s.turn} who is not in play`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- setup
|
||||
|
||||
describe('준비 (§4)', () => {
|
||||
test.each([2, 3, 4, 5, 6, 7, 8])('%i명: 53장을 고르게 나누고 짝을 모두 버림, 조커는 한 사람에게', (n) => {
|
||||
const players = Array.from({ length: n }, (_, i) => `P${i}`);
|
||||
for (let seed = 1; seed <= 5; seed++) {
|
||||
const s = setup(players, seed);
|
||||
checkInvariants(s);
|
||||
const dealt = players.map((p) => s.hands[p]!.length + s.discards[p]!.length);
|
||||
expect(Math.max(...dealt) - Math.min(...dealt)).toBeLessThanOrEqual(1);
|
||||
expect(dealt.reduce((a, b) => a + b, 0)).toBe(53);
|
||||
for (const p of players) expect(s.discards[p]!.length % 2).toBe(0);
|
||||
expect(players.filter((p) => holdsJoker(s, p))).toHaveLength(1);
|
||||
expect(s.turn && players.includes(s.turn)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('첫 사람이 한 장 더 받음(나누기 시작)', () => {
|
||||
const s = setup(['A', 'B', 'C', 'D'], 3);
|
||||
const first = s.turn!;
|
||||
const dealt = (p: string) => s.hands[p]!.length + s.discards[p]!.length;
|
||||
expect(dealt(first)).toBe(14);
|
||||
});
|
||||
|
||||
test('처음부터 손패가 0장이면 바로 빠지고 차례는 다음 사람에게', () => {
|
||||
// Same pairs dealt to A only: emulate by rigging a fresh state and replaying the setup steps.
|
||||
let found = false;
|
||||
for (let seed = 1; seed <= 4000 && !found; seed++) {
|
||||
const s = setup(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], seed);
|
||||
if (s.out.length) {
|
||||
found = true;
|
||||
checkInvariants(s);
|
||||
for (const p of s.out[0]!) expect(s.hands[p]).toEqual([]);
|
||||
expect(inPlay(s, s.turn!)).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(found).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- draws
|
||||
|
||||
describe('뽑기와 짝 버리기 (§5)', () => {
|
||||
test('왼쪽(다음) 사람의 고른 자리 카드를 뽑고, 짝이 생기면 바로 둘 다 버림', () => {
|
||||
let s = rigged({ A: ['7H', 'KS'], B: ['9C', '7D', X()], C: ['KD', '9S'] });
|
||||
expect(targetOf(s, 'A')).toBe('B');
|
||||
s = draw(s, 'A', 1);
|
||||
expect(s.hands.A).toEqual(['KS']);
|
||||
expect(s.discards.A!.slice(-2)).toEqual(['7H', '7D']);
|
||||
expect(s.hands.B).toEqual(['9C', JOKER]);
|
||||
expect(s.lastDraw).toMatchObject({ drawer: 'A', from: 'B', index: 1, card: '7D', pair: ['7H', '7D'] });
|
||||
expect(s.turn).toBe('B');
|
||||
expect(targetOf(s, 'B')).toBe('C');
|
||||
});
|
||||
|
||||
test('짝이 없으면 뽑은 카드는 내 손패 아무 자리에 숨겨짐', () => {
|
||||
const seen = new Set<number>();
|
||||
for (let n = 1; n <= 40; n++) {
|
||||
const s0 = rigged({ A: ['2H', '3H', '4H', '5H'], B: ['9C', X()], C: ['KD'] });
|
||||
const s = act(s0, 'A', { type: 'draw', from: 'B', index: 0 }, rng(n));
|
||||
expect(sorted(s.hands.A!)).toEqual(sorted(['2H', '3H', '4H', '5H', '9C']));
|
||||
seen.add(s.hands.A!.indexOf('9C'));
|
||||
}
|
||||
expect(seen.size).toBeGreaterThan(2);
|
||||
});
|
||||
|
||||
test('검증: 내 차례만, 지금 왼쪽 사람에게서만, 있는 자리만', () => {
|
||||
const s = rigged({ A: ['7H'], B: ['9C', X()], C: ['9S', '7D'] });
|
||||
expect(reject(s, 'B', { type: 'draw', from: 'C', index: 0 })).toContain('내 차례가 아니에요');
|
||||
expect(reject(s, 'A', { type: 'draw', from: 'C', index: 0 })).toContain('그 사람의 카드를 뽑을 수 없어요');
|
||||
expect(reject(s, 'A', { type: 'draw', from: 'B', index: 2 })).toContain('없는 자리');
|
||||
expect(reject(s, 'A', { type: 'draw', from: 'B', index: -1 })).toContain('없는 자리');
|
||||
expect(reject(s, 'Z', { type: 'draw', from: 'B', index: 0 })).toContain('플레이어가 아니에요');
|
||||
expect(reject(s, 'A', { type: 'draw', from: 'B', index: 1 })).toBeNull();
|
||||
});
|
||||
|
||||
test('손패를 다 턴 사람은 빠지고, 빠진 사람은 건너뜀', () => {
|
||||
// A draws B's last card (B goes out first), pairs it, and is out too (2nd).
|
||||
let s = rigged({ A: ['7H'], B: ['7D'], C: ['9C', X()], D: ['9S'] });
|
||||
s = draw(s, 'A', 0);
|
||||
expect(s.out).toEqual([['B'], ['A']]);
|
||||
expect(s.turn).toBe('C');
|
||||
expect(targetOf(s, 'C')).toBe('D');
|
||||
s = draw(s, 'C', 0); // C: 9C+9S pair → C holds joker, D out
|
||||
expect(s.out).toEqual([['B'], ['A'], ['D']]);
|
||||
expect(s.final).not.toBeNull();
|
||||
expect(s.final!.thief).toBe('C');
|
||||
});
|
||||
|
||||
test('끝: 조커를 든 사람이 도둑(꼴찌), 순위는 먼저 턴 순서, 결과 문구', () => {
|
||||
let s = rigged({ A: ['QH', X()], B: ['QS', '5D'], C: ['5C'] });
|
||||
s = draw(s, 'A', 0); // A: QH+QS → A [X1], B [5D]
|
||||
expect(s.turn).toBe('B');
|
||||
s = draw(s, 'B', 0); // B draws 5C from C → pair; B and C out (C first)
|
||||
expect(s.out).toEqual([['C'], ['B']]);
|
||||
const r = game.result(s)!;
|
||||
expect(r.ranking).toEqual([['C'], ['B'], ['A']]);
|
||||
expect(r.reason).toBe('normal');
|
||||
expect(r.summary).toContain('도둑');
|
||||
expect(r.scoreText).toEqual({ C: '다 털었어요', B: '다 털었어요', A: '🃏 도둑' });
|
||||
expect(game.activePlayers(s)).toEqual([]);
|
||||
expect(game.deadline!(s)).toBeNull();
|
||||
const v = game.view(s, 'B');
|
||||
expect(v.revealed!.A).toEqual([JOKER]);
|
||||
expect(v.places).toEqual({ C: 1, B: 2 });
|
||||
expect(reject(s, 'A', { type: 'shuffle' })).toContain('이미 끝났어요');
|
||||
});
|
||||
|
||||
test('2명: 조커를 주고받다 끝남', () => {
|
||||
let s = rigged({ A: ['3H', X()], B: ['3S'] }, 'B');
|
||||
s = draw(s, 'B', s.hands.A!.indexOf(JOKER)); // B takes the joker
|
||||
expect(s.turn).toBe('A');
|
||||
expect(s.hands.B!.length).toBe(2);
|
||||
s = draw(s, 'A', s.hands.B!.indexOf('3S')); // A pairs 3H+3S: A out, B thief
|
||||
expect(game.result(s)!.ranking).toEqual([['A'], ['B']]);
|
||||
expect(s.final!.thief).toBe('B');
|
||||
});
|
||||
});
|
||||
|
||||
function X(): string {
|
||||
return JOKER;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- shuffle
|
||||
|
||||
describe('내 손패 섞기', () => {
|
||||
test('언제든(내 차례가 아니어도) 2장 이상이면 섞을 수 있고, 차례마다 3번까지, 시계는 그대로', () => {
|
||||
let s = rigged({ A: ['2H', '3H'], B: ['4H', '5H', '6H', '7H', '8H', X()], C: ['9C'] });
|
||||
const startedAt = s.turnStartedAt;
|
||||
for (let i = 0; i < SHUFFLES_PER_TURN; i++) s = act(s, 'B', { type: 'shuffle' }, rng(i + 1));
|
||||
expect(sorted(s.hands.B!)).toEqual(sorted(['4H', '5H', '6H', '7H', '8H', JOKER]));
|
||||
expect(s.shuffles.B).toBe(3);
|
||||
expect(s.turnStartedAt).toBe(startedAt);
|
||||
expect(reject(s, 'B', { type: 'shuffle' })).toContain('3번까지');
|
||||
expect(reject(s, 'C', { type: 'shuffle' })).toContain('2장 이상');
|
||||
expect(game.view(s, 'B').my!.shufflesLeft).toBe(0);
|
||||
s = draw(s, 'A', 0);
|
||||
expect(game.view(s, 'B').my!.shufflesLeft).toBe(3);
|
||||
expect(reject(s, 'B', { type: 'shuffle' })).toBeNull();
|
||||
expect(s.log.filter((e) => e.t === 'shuffle')).toHaveLength(3);
|
||||
});
|
||||
|
||||
test('남이 보는 자리 = 실제 손패 순서: 섞은 뒤 같은 자리를 뽑으면 섞인 순서의 카드', () => {
|
||||
let s = rigged({ A: ['2H'], B: ['4H', '5H', '6H', '7H', X()], C: ['9C'] });
|
||||
s = act(s, 'B', { type: 'shuffle' }, rng(3));
|
||||
const at2 = s.hands.B![2]!;
|
||||
s = draw(s, 'A', 2);
|
||||
expect(s.lastDraw!.card).toBe(at2);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- timeout / leave
|
||||
|
||||
describe('시간 초과·나가기 (§8.5)', () => {
|
||||
test('시간 초과 → 무작위 한 장 뽑기; 3번 연속이면 자리 비움(5초), 직접 뽑으면 해제', () => {
|
||||
let s = rigged({ A: ['2H', '3H', '4H', '5H'], B: ['6H', '7H', '8H', '9H', X()], C: ['2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S'] });
|
||||
expect(game.onTimeout(s, 'A')).toEqual({ type: 'timeout' });
|
||||
expect(reject(s, 'B', { type: 'timeout' })).toContain('시간 초과 대상이 아니에요');
|
||||
let ev = actE(s, 'A', { type: 'timeout' });
|
||||
s = ev.state;
|
||||
expect(s.lastDraw).toMatchObject({ drawer: 'A', from: 'B', auto: true });
|
||||
expect(ev.events.some((e) => e.type === 'timeout')).toBe(true);
|
||||
expect(s.timeoutsInRow.A).toBe(1);
|
||||
// Everybody times out until A has done it 3 times in a row.
|
||||
while ((s.timeoutsInRow.A ?? 0) < 3 && !s.final) s = act(s, s.turn!, { type: 'timeout' });
|
||||
if (!s.final) {
|
||||
expect(s.away.A).toBe(true);
|
||||
while (!s.final && s.turn !== 'A') s = act(s, s.turn!, { type: 'timeout' });
|
||||
if (!s.final) {
|
||||
expect(game.deadline!(s)).toBe(s.turnStartedAt + 5000);
|
||||
s = draw(s, 'A', 0);
|
||||
expect(s.away.A).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('모두 시간 초과만 해도 끝나고, 모든 상태에서 onTimeout이 합법', () => {
|
||||
for (const n of [2, 5, 8]) {
|
||||
let s = setup(Array.from({ length: n }, (_, i) => `P${i}`), n);
|
||||
let steps = 0;
|
||||
while (!s.final && steps < 5000) {
|
||||
const p = game.timeoutPlayers!(s)[0]!;
|
||||
expect(reject(s, p, game.onTimeout(s, p))).toBeNull();
|
||||
s = act(s, p, game.onTimeout(s, p));
|
||||
checkInvariants(s);
|
||||
steps++;
|
||||
}
|
||||
expect(s.final?.thief).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
test('카드를 든 사람이 나가면 그 카드를 남은 사람들에게 다음 자리부터 한 장씩 나눠 주고 짝을 버림', () => {
|
||||
let s = rigged({ A: ['2H', '3H'], B: ['4H', '5H', '6H', X()], C: ['4S', '7S'], D: ['5S', '8S'] }, 'B');
|
||||
expect(game.onLeave!(s, 'B')).toEqual({ type: 'leave' });
|
||||
const { state, events } = actE(s, 'B', { type: 'leave' });
|
||||
s = state;
|
||||
checkInvariants(s, false);
|
||||
expect(s.left).toEqual(['B']);
|
||||
expect(s.hands.B).toEqual([]);
|
||||
// 4 cards → C, D, A, C (from the next seat). C/D may pair 4s / 5s.
|
||||
const e = s.log.find((x) => x.t === 'left')!;
|
||||
expect(e.t === 'left' && e.gave).toEqual([
|
||||
{ to: 'C', count: 2 },
|
||||
{ to: 'D', count: 1 },
|
||||
{ to: 'A', count: 1 },
|
||||
]);
|
||||
expect(s.turn).toBe('C');
|
||||
expect(targetOf(s, 'A')).toBe('C');
|
||||
expect(events.some((x) => x.type === 'left')).toBe(true);
|
||||
expect(game.view(s, 'A').status.B).toBe('left');
|
||||
});
|
||||
|
||||
test('2명 중 한 사람이 나가면 남은 사람이 위, 나간 사람이 아래, 도둑 없음(resign)', () => {
|
||||
let s = rigged({ A: ['2H', X()], B: ['3S', '4S'] });
|
||||
s = act(s, 'B', { type: 'leave' });
|
||||
const r = game.result(s)!;
|
||||
expect(r.ranking).toEqual([['A'], ['B']]);
|
||||
expect(r.reason).toBe('resign');
|
||||
expect(s.final!.thief).toBeNull();
|
||||
expect(r.scoreText!.B).toBe('나감');
|
||||
expect(r.summary).toContain('나가서');
|
||||
});
|
||||
|
||||
test('이미 다 턴 사람이 나가면 아무 일도 없음(onLeave null)', () => {
|
||||
let s = rigged({ A: ['7H'], B: ['7D'], C: ['9C', X()], D: ['9S'] });
|
||||
s = draw(s, 'A', 0);
|
||||
expect(game.onLeave!(s, 'B')).toBeNull();
|
||||
expect(game.onLeave!(s, 'C')).toEqual({ type: 'leave' });
|
||||
});
|
||||
|
||||
test('3명 이상에서 나가면 남은 사람끼리 계속, 결과에는 나간 사람이 맨 아래', () => {
|
||||
// Every card but the joker still has its partner somewhere, like in a real game.
|
||||
let s = rigged({ A: ['2H', '3H'], B: ['4H', X(), '3S'], C: ['2S', '4S'] });
|
||||
s = act(s, 'C', { type: 'leave' });
|
||||
checkInvariants(s, false);
|
||||
expect(s.final).toBeNull();
|
||||
while (!s.final) s = act(s, s.turn!, { type: 'timeout' });
|
||||
const r = game.result(s)!;
|
||||
expect(r.ranking.at(-1)).toEqual(['C']);
|
||||
expect(r.ranking.flat().sort()).toEqual(['A', 'B', 'C']);
|
||||
expect(s.final!.thief).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- privacy
|
||||
|
||||
describe('비공개 정보 (§8.3)', () => {
|
||||
test('남의 손패는 장수만; 뽑은 카드는 뽑은 사람만(짝이 나면 모두), 관전자는 손패 없음', () => {
|
||||
let s = rigged({ A: ['2H', '3H'], B: ['9C', '4D', X()], C: ['5S', '6S'] });
|
||||
const vA = game.view(s, 'A');
|
||||
expect(vA.myHand).toEqual(['2H', '3H']);
|
||||
expect(vA.handCounts).toEqual({ A: 2, B: 3, C: 2 });
|
||||
expect(JSON.stringify(vA)).not.toContain('"9C"');
|
||||
expect(JSON.stringify(game.view(s, null))).not.toContain('"2H"');
|
||||
expect(game.view(s, null).myHand).toBeNull();
|
||||
expect(vA.my).toMatchObject({ canDraw: true, from: 'B', count: 3 });
|
||||
expect(game.view(s, 'C').my).toMatchObject({ canDraw: false, from: null, count: 0 });
|
||||
s = draw(s, 'A', 0); // 9C, no pair
|
||||
expect(game.view(s, 'A').lastDraw!.card).toBe('9C');
|
||||
expect(game.view(s, 'B').lastDraw!.card).toBeNull();
|
||||
expect(game.view(s, 'C').lastDraw!.card).toBeNull();
|
||||
expect(game.view(s, null).lastDraw!.card).toBeNull();
|
||||
expect(JSON.stringify(game.view(s, 'C'))).not.toContain('"9C"');
|
||||
s = act(s, 'B', { type: 'draw', from: 'C', index: 1 }); // 6S, no pair for B
|
||||
s = act(s, 'C', { type: 'draw', from: 'A', index: s.hands.A!.indexOf('9C') }); // C has 5S → no pair
|
||||
expect(game.view(s, 'B').lastDraw!.card).toBeNull();
|
||||
});
|
||||
|
||||
test('무작위 진행 중 모든 view와 이벤트에 남의 손패가 없음', () => {
|
||||
for (let seed = 1; seed <= 6; seed++) {
|
||||
const players = Array.from({ length: 2 + (seed % 7) }, (_, i) => `P${i}`);
|
||||
let s = setup(players, seed);
|
||||
const chooser = SeededRng.fromSeed(seedN(seed + 99));
|
||||
for (let step = 0; step < 3000 && !s.final; step++) {
|
||||
const actor = s.turn!;
|
||||
const legal = game.legalActions!(s, actor);
|
||||
const out = actE(s, actor, legal[chooser.int(legal.length)]!, rng(step));
|
||||
for (const e of out.events) {
|
||||
const ej = JSON.stringify(e);
|
||||
for (const p of players) for (const c of out.state.hands[p]!) if (ej.includes(JSON.stringify(c))) throw new Error(`event ${e.type} leaks ${c}`);
|
||||
}
|
||||
s = out.state;
|
||||
}
|
||||
expect(s.final).not.toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- schema
|
||||
|
||||
describe('옵션·스키마', () => {
|
||||
test('모든 옵션에 한국어 메타; 기본값', () => {
|
||||
const shape = (game.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
|
||||
for (const [k, v] of Object.entries(shape)) expect(v.meta()?.title, k).toBeTruthy();
|
||||
expect(game.defaultOptions).toEqual({ turnSeconds: 20 });
|
||||
expect(game.optionsSchema.safeParse({ turnSeconds: 15 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test('클라이언트 행동만 스키마에 있음', () => {
|
||||
expect(game.actionSchema.safeParse({ type: 'draw', from: 'B', index: 3 }).success).toBe(true);
|
||||
expect(game.actionSchema.safeParse({ type: 'draw', from: 'B', index: 1.5 }).success).toBe(false);
|
||||
expect(game.actionSchema.safeParse({ type: 'shuffle' }).success).toBe(true);
|
||||
expect(game.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false);
|
||||
expect(game.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- properties
|
||||
|
||||
describe('무작위 대국 (docs/09 §7)', () => {
|
||||
const SEEDS = playoutSeeds(300);
|
||||
test(`engine randomPlayout, seeds 1–${SEEDS}, 2~8명: 끝남, 카드 보존, 유출 없음, onTimeout 합법, 결정성`, () => {
|
||||
for (let i = 1; i <= SEEDS; i++) {
|
||||
const players = Array.from({ length: 2 + (i % 7) }, (_, k) => `P${k}`);
|
||||
const invariant = (st: unknown) => {
|
||||
checkInvariants(st);
|
||||
const s = st as OldMaidState;
|
||||
for (const p of game.timeoutPlayers!(s)) if (reject(s, p, game.onTimeout(s, p))) throw new Error('onTimeout illegal');
|
||||
};
|
||||
const r = randomPlayout(game, { players, seed: seedN(i), maxSteps: 3000, invariant, maxApplyMs: 50 });
|
||||
expect(r.finished).toBe(true);
|
||||
const s = r.finalState as OldMaidState;
|
||||
const res = game.result(s)!;
|
||||
expect(res.ranking.flat().sort()).toEqual([...players].sort());
|
||||
expect(res.ranking.at(-1)).toEqual([s.final!.thief!]);
|
||||
expect(holdsJoker(s, s.final!.thief!)).toBe(true);
|
||||
if (i % 10 === 1) {
|
||||
const b = randomPlayout(game, { players, seed: seedN(i), maxSteps: 3000, maxApplyMs: 50 });
|
||||
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(r.finalState));
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('같은 시드 + 같은 행동 기록 = 같은 결과(나가기 섞음)', () => {
|
||||
for (let i = 1; i <= 20; i++) {
|
||||
const players = Array.from({ length: 3 + (i % 6) }, (_, k) => `P${k}`);
|
||||
const r = SeededRng.fromSeed(seedN(i));
|
||||
const chooser = SeededRng.fromSeed(seedN(i + 5000));
|
||||
let s = game.setup({ players, options: game.defaultOptions, rng: r, now: 0 });
|
||||
const log: { actor: string; action: OldMaidAction }[] = [];
|
||||
for (let step = 0; step < 3000 && !s.final; step++) {
|
||||
let actor = s.turn!;
|
||||
let a: OldMaidAction;
|
||||
const roll = chooser.int(40);
|
||||
if (roll === 0) {
|
||||
const leaver = players.find((p) => game.onLeave!(s, p));
|
||||
actor = leaver!;
|
||||
a = { type: 'leave' };
|
||||
} else if (roll < 5) a = game.onTimeout(s, actor);
|
||||
else {
|
||||
const legal = game.legalActions!(s, actor);
|
||||
a = legal[chooser.int(legal.length)]!;
|
||||
}
|
||||
expect(reject(s, actor, a)).toBeNull();
|
||||
s = game.apply(s, actor, a, { rng: r, now: step * 1000 }).state;
|
||||
log.push({ actor, action: a });
|
||||
checkInvariants(s);
|
||||
}
|
||||
expect(s.final).not.toBeNull();
|
||||
const r2 = SeededRng.fromSeed(seedN(i));
|
||||
let t = game.setup({ players, options: game.defaultOptions, rng: r2, now: 0 });
|
||||
log.forEach(({ actor, action }, k) => (t = game.apply(t, actor, action, { rng: r2, now: k * 1000 }).state));
|
||||
expect(JSON.stringify(t)).toBe(JSON.stringify(s));
|
||||
}
|
||||
});
|
||||
});
|
||||
128
packages/games/src/old-maid/types.ts
Normal file
128
packages/games/src/old-maid/types.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
/** 도둑잡기 options, actions, state and view types (docs/games/old-maid.md §2, §8). */
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
|
||||
/** Trump 52 + one joker ("X1"). */
|
||||
export const DECK_SIZE = 53;
|
||||
export const JOKER = 'X1';
|
||||
/** Shuffles of one's own hand per player per turn (keeps the log and the traffic small). */
|
||||
export const SHUFFLES_PER_TURN = 3;
|
||||
/** Public log entries kept in the state. */
|
||||
export const LOG_KEEP = 30;
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
export const oldMaidOptionsSchema = z.object({
|
||||
turnSeconds: z
|
||||
.union([z.literal(10), z.literal(20), z.literal(30), z.literal(60)])
|
||||
.default(20)
|
||||
.meta({ title: '한 번 뽑는 제한 시간', labels: { 10: '10초', 20: '20초', 30: '30초', 60: '60초' } }),
|
||||
});
|
||||
export type OldMaidOptions = z.infer<typeof oldMaidOptionsSchema>;
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
export const oldMaidActionSchema = z.discriminatedUnion('type', [
|
||||
/** Draw the card at `index` (0 = leftmost as the owner holds it) from `from`'s face-down hand. */
|
||||
z.object({ type: z.literal('draw'), from: z.string().max(64), index: z.number().int().min(0).max(DECK_SIZE) }),
|
||||
/** Shuffle my own hand (anyone still holding 2+ cards, any time). */
|
||||
z.object({ type: z.literal('shuffle') }),
|
||||
]);
|
||||
export type OldMaidClientAction = z.infer<typeof oldMaidActionSchema>;
|
||||
/** Client actions plus system-only actions (timer / leaving), which are not in the schema. */
|
||||
export type OldMaidAction = OldMaidClientAction | { type: 'timeout' } | { type: 'leave' };
|
||||
export type DrawAction = Extract<OldMaidClientAction, { type: 'draw' }>;
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
export type LogEntry =
|
||||
/** A draw. `pair` = the two cards thrown away right after it (public), null when the drawn card stayed hidden. */
|
||||
| { t: 'draw'; no: number; drawer: PlayerId; from: PlayerId; index: number; pair: [string, string] | null; auto: boolean }
|
||||
| { t: 'out'; player: PlayerId; place: number }
|
||||
| { t: 'shuffle'; player: PlayerId }
|
||||
/** Someone left with cards: their cards were dealt face down to `to` (counts only), pairs thrown away. */
|
||||
| { t: 'left'; player: PlayerId; gave: { to: PlayerId; count: number }[]; pairs: [string, string][] };
|
||||
|
||||
export interface LastDraw {
|
||||
no: number;
|
||||
drawer: PlayerId;
|
||||
from: PlayerId;
|
||||
index: number;
|
||||
/** The drawn card. Secret (only in the drawer's view) unless it made a pair. */
|
||||
card: string;
|
||||
pair: [string, string] | null;
|
||||
auto: boolean;
|
||||
}
|
||||
|
||||
export interface OldMaidFinal {
|
||||
/** Who was left holding the joker; null when the game ended because players left. */
|
||||
thief: PlayerId | null;
|
||||
reason: 'normal' | 'left';
|
||||
ranking: PlayerId[][];
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface OldMaidState {
|
||||
options: OldMaidOptions;
|
||||
order: PlayerId[];
|
||||
/** Hands in the order the owner holds them (left to right). Others pick by position. */
|
||||
hands: Record<PlayerId, string[]>;
|
||||
/** Pairs each player threw away, in order (public). */
|
||||
discards: Record<PlayerId, string[]>;
|
||||
/** Players who emptied their hand, in finishing groups (same group = same moment). */
|
||||
out: PlayerId[][];
|
||||
/** Players who left the game while still holding cards. */
|
||||
left: PlayerId[];
|
||||
/** Whose turn it is (draws from `targetOf(turn)`); null once finished. */
|
||||
turn: PlayerId | null;
|
||||
turnNo: number;
|
||||
shuffles: Record<PlayerId, number>;
|
||||
/** Shuffles per player during the current turn (reset every turn). */
|
||||
shufflesThisTurn: Record<PlayerId, number>;
|
||||
lastDraw: LastDraw | null;
|
||||
log: LogEntry[];
|
||||
/** Log entries ever written (the log keeps only the last LOG_KEEP). */
|
||||
logCount: number;
|
||||
timeoutsInRow: Record<PlayerId, number>;
|
||||
away: Record<PlayerId, boolean>;
|
||||
turnStartedAt: number;
|
||||
seq: number;
|
||||
final: OldMaidFinal | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export type SeatStatus = 'playing' | 'out' | 'left';
|
||||
|
||||
export interface OldMaidView {
|
||||
options: OldMaidOptions;
|
||||
me: PlayerId | null;
|
||||
order: PlayerId[];
|
||||
phase: 'playing' | 'finished';
|
||||
turn: PlayerId | null;
|
||||
/** The player the turn player draws from. */
|
||||
target: PlayerId | null;
|
||||
turnNo: number;
|
||||
handCounts: Record<PlayerId, number>;
|
||||
pairCounts: Record<PlayerId, number>;
|
||||
status: Record<PlayerId, SeatStatus>;
|
||||
/** Finishing place (1 = first out) for players who emptied their hand. */
|
||||
places: Record<PlayerId, number>;
|
||||
shuffles: Record<PlayerId, number>;
|
||||
/** My hand in my order (null for spectators). */
|
||||
myHand: string[] | null;
|
||||
/** The last draw; `card` only for the drawer (or once it made a pair). */
|
||||
lastDraw: (Omit<LastDraw, 'card'> & { card: string | null }) | null;
|
||||
/** What I can do now (null for spectators and finished games). */
|
||||
my: { canDraw: boolean; from: PlayerId | null; count: number; canShuffle: boolean; shufflesLeft: number } | null;
|
||||
log: LogEntry[];
|
||||
/** Log entries ever written: the screen tells new entries from old ones with it. */
|
||||
logCount: number;
|
||||
away: Record<PlayerId, boolean>;
|
||||
turnStartedAt: number;
|
||||
turnMs: number;
|
||||
seq: number;
|
||||
final: OldMaidFinal | null;
|
||||
/** After the game: what everyone still held (only the joker with the thief, or leftovers when someone left). */
|
||||
revealed: Record<PlayerId, string[]> | null;
|
||||
}
|
||||
@@ -49,6 +49,7 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'las-vegas',
|
||||
'cockroach-poker',
|
||||
'ninety-nine',
|
||||
'old-maid',
|
||||
'mafia',
|
||||
'apple',
|
||||
'clue',
|
||||
|
||||
@@ -34,6 +34,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'las-vegas', nameKo: '라스베가스', minPlayers: 2, maxPlayers: 5, minutes: '20~30', level: '쉬움', blurb: '주사위를 같은 숫자 카지노에 몽땅! 개수가 같으면 둘 다 꽝 · 놀이용 지폐', available: true },
|
||||
{ id: 'cockroach-poker', nameKo: '바퀴벌레 포커', minPlayers: 2, maxPlayers: 6, minutes: '15~20', level: '쉬움', blurb: '벌레 카드를 건네며 "이건 쥐야!" 진짜일까 거짓말일까?', available: true },
|
||||
{ id: 'ninety-nine', nameKo: '구십구', minPlayers: 2, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '카드를 내며 숫자를 더해요. 99를 넘기면 탈락!', available: true },
|
||||
{ id: 'old-maid', nameKo: '도둑잡기', minPlayers: 2, maxPlayers: 8, minutes: '5~10', level: '쉬움', blurb: '옆 사람 카드를 한 장씩 뽑아 짝을 버려요. 마지막에 조커를 든 사람이 도둑!', available: true },
|
||||
{ id: 'dobble', nameKo: '도블', minPlayers: 2, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '어느 두 카드에나 딱 하나 있는 같은 그림을 누구보다 빨리 콕!', available: true },
|
||||
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true },
|
||||
{ id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true },
|
||||
|
||||
Reference in New Issue
Block a user