Files
joke-app/packages/games/src/bang/bang.test.ts
EJClaw ac37a6a6d8 카드 게임 시간 무제한(우노·뱅!·달무티·고스톱·도둑잡기·포커·바퀴벌레 포커·99), 공통 카드 움직임(card-fx), 우노·달무티·도둑잡기·포커 소리·애니메이션
- 무제한(null): 차례 시계·타임아웃 없음, 자리 비움만 짧은 시계, 연결 끊김은 방 유예 뒤 자동 행동 그대로
- 포커는 리바이 고르는 시간도 무제한 가능, 고스톱은 고·스톱 선택 시간도 무제한 가능, 뱅!은 반응 시간·캐릭터 고르기도
- card-fx: 날아가는 카드·칩(ghost), 제자리 날아오기, 배너, view 변화 감지 훅(처음 렌더·다시 보기는 건너뜀)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:04:11 +09:00

1393 lines
68 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent, type PlayerId, type RngState } from '@bg/engine';
import {
CARDS,
CHARACTER_LIFE,
allCards,
bang,
cardById,
distance,
type BangAction,
type BangOptions,
type BangState,
type CardKind,
type CharacterId,
type Role,
type TurnPhase,
} from './index';
// ---------------------------------------------------------------- helpers
let clock = 1_000_000;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
interface PSpec {
id: string;
role: Role;
ch: CharacterId;
life?: number;
hand?: string[];
inPlay?: string[];
alive?: boolean;
}
/** Card picker for one rigged game: `c('bang')` = any unused 뱅!, `c('missed', '10C')` = that exact card. */
function pool() {
const used = new Set<string>();
return (kind: CardKind, code?: string): string => {
const card = CARDS.find((x) => x.kind === kind && !used.has(x.id) && (!code || `${x.rank}${x.suit}` === code));
if (!card) throw new Error(`no unused ${kind} ${code ?? ''}`);
used.add(card.id);
return card.id;
};
}
/**
* Builds a state directly: players in seat order, the current player in the play phase (unless `phase`),
* `deckTop` = cards drawn next (first element first); every other card goes under them.
*/
function rig(o: { players: PSpec[]; turn?: string; phase?: TurnPhase; deckTop?: string[]; discard?: string[]; options?: Partial<BangOptions> }): BangState {
const options = bang.optionsSchema.parse(o.options ?? {});
const players = o.players.map((p, i) => {
const maxLife = CHARACTER_LIFE[p.ch] + (p.role === 'sheriff' ? 1 : 0);
return {
id: p.id,
seat: i,
role: p.role,
character: p.ch,
characterOffer: null,
maxLife,
life: p.life ?? maxLife,
alive: p.alive ?? true,
hand: p.hand ?? [],
inPlay: p.inPlay ?? [],
timeoutsInRow: 0,
away: false,
};
});
const placed = new Set([...players.flatMap((p) => [...p.hand, ...p.inPlay]), ...(o.deckTop ?? []), ...(o.discard ?? [])]);
const rest = CARDS.map((c) => c.id).filter((id) => !placed.has(id));
const turn = o.turn ?? players[0]!.id;
return {
options,
players,
deck: [...rest, ...[...(o.deckTop ?? [])].reverse()],
discard: o.discard ?? [],
turn: { player: turn, phase: o.phase ?? 'play', bangsPlayed: 0, deadline: clock + 60_000, pausedAt: null, dynamiteChecked: false, jailChecked: false },
reactions: [],
lastCheck: null,
winner: null,
deathOrder: players.filter((p) => !p.alive).map((p) => p.id),
round: 1,
seq: 0,
log: [],
final: null,
};
}
function actE(s: BangState, p: string, a: BangAction): { state: BangState; events: GameEvent[] } {
const v = bang.validate(s, p, a);
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return bang.apply(s, p, a, { rng: rng(), now: (clock += 1000) });
}
const act = (s: BangState, p: string, a: BangAction) => actE(s, p, a).state;
const reject = (s: BangState, p: string, a: BangAction): string | null => {
const v = bang.validate(s, p, a);
return v.ok ? null : v.reason;
};
const pl = (s: BangState, id: string) => s.players.find((p) => p.id === id)!;
const play = (s: BangState, p: string, cardId: string, extra: Partial<Extract<BangAction, { type: 'play' }>> = {}) => act(s, p, { type: 'play', cardId, ...extra });
const kinds = (ids: string[]) => ids.map((id) => cardById(id).kind);
const conserve = (s: BangState) => {
const all = allCards(s);
expect(all.length).toBe(80);
expect(new Set(all).size).toBe(80);
};
/** Four players A (sheriff) B C D around the table with plain characters. */
const basic = (over: Partial<Record<string, Partial<PSpec>>> = {}): PSpec[] =>
(
[
{ id: 'A', role: 'sheriff', ch: 'sid' },
{ id: 'B', role: 'outlaw', ch: 'bart' },
{ id: 'C', role: 'renegade', ch: 'pedro' },
{ id: 'D', role: 'outlaw', ch: 'willy' },
] as PSpec[]
).map((p) => ({ ...p, ...(over[p.id] ?? {}) }));
// ---------------------------------------------------------------- deck and setup
const TABLE: Record<CardKind, string> = {
bang: 'AS 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD 2C 3C 4C 5C 6C 7C 8C 9C QH KH AH',
missed: '10C JC QC KC AC 2S 3S 4S 5S 6S 7S 8S',
beer: '6H 7H 8H 9H 10H JH',
panic: 'JH QH AH 8D',
catBalou: 'KH 9D 10D JD',
duel: 'QD JS 8C',
generalStore: '9C QS',
indians: 'KD AD',
stagecoach: '9S 9S',
gatling: '10H',
saloon: '5H',
wellsFargo: '3H',
barrel: 'QS KS',
mustang: '8H 9H',
scope: 'AS',
jail: 'JS 10S 4H',
dynamite: '2H',
volcanic: '10S 10C',
schofield: 'JC QC KS',
remington: 'KC',
carabine: 'AC',
winchester: '8S',
};
describe('덱과 셋업 (§3, §4)', () => {
test('80장: 종류별 장수와 무늬·숫자가 3.3 표와 정확히 같다; 갈색 63 + 파랑 17', () => {
expect(CARDS).toHaveLength(80);
expect(new Set(CARDS.map((c) => c.id)).size).toBe(80);
for (const [kind, codes] of Object.entries(TABLE)) {
const got = CARDS.filter((c) => c.kind === kind).map((c) => `${c.rank}${c.suit}`);
expect(got.sort(), kind).toEqual(codes.split(' ').sort());
}
const blue = ['barrel', 'mustang', 'scope', 'jail', 'dynamite', 'volcanic', 'schofield', 'remington', 'carabine', 'winchester'];
expect(CARDS.filter((c) => blue.includes(c.kind))).toHaveLength(17);
expect(CARDS.filter((c) => !blue.includes(c.kind))).toHaveLength(63);
});
test.each([
[4, { sheriff: 1, deputy: 0, outlaw: 2, renegade: 1 }, false],
[5, { sheriff: 1, deputy: 1, outlaw: 2, renegade: 1 }, false],
[6, { sheriff: 1, deputy: 1, outlaw: 3, renegade: 1 }, false],
[7, { sheriff: 1, deputy: 2, outlaw: 3, renegade: 1 }, false],
[7, { sheriff: 1, deputy: 1, outlaw: 4, renegade: 1 }, true],
] as const)('%i명 역할 분배, 보안관 생명 +1, 시작 손패 = 생명 (deputyCount7=%p)', (n, roles, dc7) => {
for (let seed = 1; seed <= 20; seed++) {
const players = Array.from({ length: n }, (_, k) => `P${k}`);
const s = bang.setup({ players, options: bang.optionsSchema.parse({ deputyCount7: dc7 }), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
const count = { sheriff: 0, deputy: 0, outlaw: 0, renegade: 0 };
for (const p of s.players) count[p.role]++;
expect(count).toEqual(roles);
expect(new Set(s.players.map((p) => p.character)).size).toBe(n);
for (const p of s.players) {
expect(p.maxLife).toBe(CHARACTER_LIFE[p.character] + (p.role === 'sheriff' ? 1 : 0));
expect(p.life).toBe(p.maxLife);
// The sheriff starts and has already drawn (automatically, unless Jesse/Pedro choose or Kit keeps).
const drawn = s.log.filter((e) => e.t === 'draw' && e.p === p.id).reduce((a, e) => a + (e.t === 'draw' ? e.n : 0), 0);
const pedro = s.log.filter((e) => (e.t === 'pedro' || e.t === 'take' || e.t === 'blackJack') && e.p === p.id).length;
expect(p.hand.length - drawn - pedro).toBe(p.life);
}
expect(s.turn.player).toBe(s.players.find((p) => p.role === 'sheriff')!.id);
expect(s.round).toBe(1);
conserve(s);
}
});
test('좌석은 RNG로 섞이고 같은 시드면 같은 결과', () => {
const players = ['A', 'B', 'C', 'D', 'E'];
const a = bang.setup({ players, options: bang.defaultOptions, rng: SeededRng.fromSeed(seedN(3)), now: 0 });
const b = bang.setup({ players, options: bang.defaultOptions, rng: SeededRng.fromSeed(seedN(3)), now: 0 });
expect(JSON.stringify(a)).toBe(JSON.stringify(b));
const orders = new Set<string>();
for (let i = 1; i <= 20; i++) orders.add(bang.setup({ players, options: bang.defaultOptions, rng: SeededRng.fromSeed(seedN(i)), now: 0 }).players.map((p) => p.id).join(''));
expect(orders.size).toBeGreaterThan(5);
expect(() => bang.setup({ players: ['A', 'B', 'C'], options: bang.defaultOptions, rng: rng(), now: 0 })).toThrow();
expect(() => bang.setup({ players: 'ABCDEFGH'.split(''), options: bang.defaultOptions, rng: rng(), now: 0 })).toThrow();
});
test('choose2: 2장 중 1장 고르기, 남의 후보는 비공개, 시간 초과 시 첫 후보', () => {
const players = ['A', 'B', 'C', 'D'];
let s = bang.setup({ players, options: bang.optionsSchema.parse({ characterDraft: 'choose2' }), rng: SeededRng.fromSeed(seedN(9)), now: 0 });
expect(s.turn.phase).toBe('draft');
expect(s.reactions.filter((r) => r.kind === 'choose2')).toHaveLength(4);
expect(bang.activePlayers(s).sort()).toEqual(players);
const offerA = pl(s, 'A').characterOffer!;
const vB = JSON.stringify(bang.view(s, 'B'));
for (const c of offerA) expect(vB).not.toContain(`"${c}"`);
const vA = bang.view(s, 'A');
expect(vA.my!.prompt).toEqual({ kind: 'choose2', options: offerA });
expect(reject(s, 'A', { type: 'pickCharacter', character: pl(s, 'B').characterOffer![0]! })).toBe('받은 캐릭터 중에서 골라 주세요.');
s = act(s, 'A', { type: 'pickCharacter', character: offerA[1]! });
expect(pl(s, 'A').character).toBe(offerA[1]!);
for (const p of ['B', 'C']) s = act(s, p, { type: 'pickCharacter', character: pl(s, p).characterOffer![0]! });
const offerD = pl(s, 'D').characterOffer!;
s = act(s, 'D', { type: 'timeout' });
expect(pl(s, 'D').character).toBe(offerD[0]!);
expect(s.turn.phase).not.toBe('draft');
for (const p of s.players) if (p.id !== s.turn.player) expect(p.hand).toHaveLength(p.life);
conserve(s);
});
});
// ---------------------------------------------------------------- distance
describe('거리와 사거리 (§5.1)', () => {
test('5인 A-B-C-D-E: A→C 2, 머스탱 3, 조준경 2; B 사망 후 1; 레밍턴이면 사격 가능, 스코필드면 불가', () => {
const c = pool();
const ps: PSpec[] = [
{ id: 'A', role: 'sheriff', ch: 'bart', hand: [c('bang')] },
{ id: 'B', role: 'deputy', ch: 'kit' },
{ id: 'C', role: 'outlaw', ch: 'suzy' },
{ id: 'D', role: 'outlaw', ch: 'vulture' },
{ id: 'E', role: 'renegade', ch: 'willy' },
];
const s = rig({ players: ps });
expect(distance(s, 'A', 'C')).toBe(2);
expect(distance(s, 'A', 'D')).toBe(2);
expect(distance(s, 'A', 'E')).toBe(1);
pl(s, 'C').inPlay = [c('mustang')];
expect(distance(s, 'A', 'C')).toBe(3);
pl(s, 'A').inPlay = [c('scope')];
expect(distance(s, 'A', 'C')).toBe(2);
pl(s, 'A').inPlay = [c('schofield')];
const bangId = pl(s, 'A').hand[0]!;
expect(reject(s, 'A', { type: 'play', cardId: bangId, target: 'C' })).toBe('사거리가 닿지 않아요(거리 3, 사거리 2).');
pl(s, 'A').inPlay = [c('remington')];
expect(reject(s, 'A', { type: 'play', cardId: bangId, target: 'C' })).toBeNull();
pl(s, 'C').inPlay = [];
pl(s, 'B').alive = false;
expect(distance(s, 'A', 'C')).toBe(1);
});
test('머스탱 + 폴 리그레트 = +2, 조준경 + 로즈 둘란 = −2, 최소 1', () => {
const c = pool();
const s = rig({
players: [
{ id: 'A', role: 'sheriff', ch: 'rose', inPlay: [c('scope')] },
{ id: 'B', role: 'deputy', ch: 'kit' },
{ id: 'C', role: 'outlaw', ch: 'paul', inPlay: [c('mustang')] },
{ id: 'D', role: 'outlaw', ch: 'suzy' },
{ id: 'E', role: 'renegade', ch: 'willy' },
{ id: 'F', role: 'outlaw', ch: 'bart' },
{ id: 'G', role: 'deputy', ch: 'sid' },
],
});
// Seats A→C = 2, +2 (mustang + Paul) −2 (scope + Rose) = 2.
expect(distance(s, 'A', 'C')).toBe(2);
expect(distance(s, 'B', 'C')).toBe(3);
expect(distance(s, 'C', 'A')).toBe(2);
// A→B: 1 − 2 → minimum 1.
expect(distance(s, 'A', 'B')).toBe(1);
expect(distance(s, 'A', 'D')).toBe(1);
expect(distance(s, 'A', 'E')).toBe(1);
// Distance is the shorter way round.
expect(distance(s, 'B', 'F')).toBe(3);
expect(distance(s, 'E', 'B')).toBe(3);
});
test('view: 거리와 사거리 안 여부를 미리 계산해 준다', () => {
const c = pool();
const s = rig({ players: basic({ A: { hand: [c('bang')] }, C: { inPlay: [c('mustang')] } }) });
const v = bang.view(s, 'A');
const by = Object.fromEntries(v.players.map((p) => [p.id, p]));
expect(by.B!.distance).toBe(1);
expect(by.B!.inRange).toBe(true);
expect(by.C!.distance).toBe(3);
expect(by.C!.inRange).toBe(false);
expect(by.A!.distance).toBeNull();
const opt = v.my!.plays[0]!;
expect(opt.ok).toBe(true);
expect(opt.targets!.map((t) => [t.id, t.ok])).toEqual([
['B', true],
['C', false],
['D', true],
]);
expect(opt.targets![1]!.reason).toBe('사거리가 닿지 않아요(거리 3, 사거리 1).');
});
});
// ---------------------------------------------------------------- bang! limits and responses
describe('뱅!과 빗나감! (§5.2, §5.4)', () => {
test('뱅! 턴당 1회: 두 번째 거부; 볼캐닉·윌리 더 키드는 허용', () => {
const c = pool();
const b1 = c('bang');
const b2 = c('bang');
let s = rig({ players: basic({ A: { hand: [b1, b2] } }) });
s = play(s, 'A', b1, { target: 'B' });
expect(s.reactions).toHaveLength(1);
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').life).toBe(3);
expect(reject(s, 'A', { type: 'play', cardId: b2, target: 'B' })).toBe('이번 턴에는 뱅!을 이미 썼어요.');
expect(bang.view(s, 'A').my!.plays.find((o) => o.cardId === b2)!.reason).toBe('이번 턴에는 뱅!을 이미 썼어요.');
// Volcanic
pl(s, 'A').inPlay = [c('volcanic')];
expect(reject(s, 'A', { type: 'play', cardId: b2, target: 'B' })).toBeNull();
// Willy the Kid
const w1 = c('bang');
const w2 = c('bang');
let t = rig({ players: basic({ D: { hand: [w1, w2] } }), turn: 'D' });
t = play(t, 'D', w1, { target: 'A' });
t = act(t, 'A', { type: 'takeHit' });
t = play(t, 'D', w2, { target: 'A' });
t = act(t, 'A', { type: 'takeHit' });
expect(pl(t, 'A').life).toBe(3);
});
test('빗나감!은 내 차례에 낼 수 없고, 맞을 때 1장으로 막는다; 맞기 / 시간 초과(autoDefend)', () => {
const c = pool();
const m = c('missed');
const b = c('bang');
const b2 = c('bang');
let s = rig({ players: basic({ A: { hand: [b, b2, c('missed')] }, B: { hand: [m] } }), options: { autoDefend: true } });
expect(reject(s, 'A', { type: 'play', cardId: pl(s, 'A').hand[2]!, target: 'B' })).toBe('빗나감!은 공격을 받았을 때만 낼 수 있어요.');
s = play(s, 'A', b, { target: 'B' });
expect(bang.view(s, 'B').my!.prompt).toMatchObject({ kind: 'bang', source: 'A', needed: 1, options: [m] });
expect(reject(s, 'A', { type: 'endPlay' })).toBe('지금은 턴을 마칠 수 없어요.');
s = act(s, 'B', { type: 'timeout' });
expect(pl(s, 'B').life).toBe(4);
expect(pl(s, 'B').hand).toEqual([]);
expect(s.discard).toContain(m);
expect(s.log.some((e) => e.t === 'missed' && e.p === 'B')).toBe(true);
// autoDefend off: timeout = take the hit.
let t = rig({ players: basic({ A: { hand: [b2] }, B: { hand: [c('missed')] } }), options: { autoDefend: false } });
t = play(t, 'A', b2, { target: 'B' });
t = act(t, 'B', { type: 'timeout' });
expect(pl(t, 'B').life).toBe(3);
});
test('캘러미티 자넷: 빗나감!을 뱅!으로(1회 제한 포함), 뱅!을 빗나감!으로; 결투·인디언!에도', () => {
const c = pool();
const m1 = c('missed');
const b1 = c('bang');
let s = rig({ players: basic({ A: { ch: 'calamity', hand: [m1, b1] }, B: { hand: [c('bang')] } }) });
expect(reject(s, 'A', { type: 'play', cardId: m1, target: 'B' })).toBe('빗나감!은 공격을 받았을 때만 낼 수 있어요.');
expect(reject(s, 'B', { type: 'play', cardId: m1, as: 'bang', target: 'A' })).toBe('지금은 카드를 낼 수 없어요.');
const opt = bang.view(s, 'A').my!.plays.find((o) => o.cardId === m1)!;
expect(opt.as).toBe('bang');
s = play(s, 'A', m1, { as: 'bang', target: 'B' });
expect(s.turn.bangsPlayed).toBe(1);
// B answers with... a 뱅! is not a 빗나감! for B.
expect(reject(s, 'B', { type: 'respond', cardIds: [pl(s, 'B').hand[0]!] })).toBe('빗나감!만 낼 수 있어요.');
s = act(s, 'B', { type: 'takeHit' });
expect(reject(s, 'A', { type: 'play', cardId: b1, target: 'B' })).toBe('이번 턴에는 뱅!을 이미 썼어요.');
// Calamity answers a 뱅! with a 뱅!, and Indians with a 빗나감!.
const bb = c('bang');
const mm = c('missed');
const ind = c('indians');
let t = rig({ players: basic({ B: { ch: 'calamity', hand: [bb, mm] }, A: { hand: [c('bang'), ind] } }) });
t = play(t, 'A', pl(t, 'A').hand[0]!, { target: 'B' });
t = act(t, 'B', { type: 'respond', cardIds: [bb] });
expect(pl(t, 'B').life).toBe(4);
t = play(t, 'A', ind);
t = act(t, 'B', { type: 'respond', cardIds: [mm] });
expect(pl(t, 'B').life).toBe(4);
expect(t.log.some((e) => e.t === 'respond' && e.p === 'B' && e.why === 'indians')).toBe(true);
});
test('슬랩 더 킬러: 빗나감! 1장 제출 거부, 술통 성공 1 + 빗나감! 1로 회피; 슬랩의 개틀링은 1장', () => {
const c = pool();
const b = c('bang');
const m1 = c('missed');
const m2 = c('missed');
let s = rig({ players: basic({ A: { ch: 'slab', hand: [b] }, B: { hand: [m1] } }) });
s = play(s, 'A', b, { target: 'B' });
expect(bang.view(s, 'B').my!.prompt).toMatchObject({ kind: 'bang', needed: 2 });
expect(reject(s, 'B', { type: 'respond', cardIds: [m1] })).toBe('빗나감! 2장을 한꺼번에 내야 막을 수 있어요.');
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').life).toBe(3);
// Barrel ♥ success + one 빗나감!.
const b2 = c('bang');
let t = rig({ players: basic({ A: { ch: 'slab', hand: [b2] }, B: { hand: [m2], inPlay: [c('barrel')] } }), deckTop: [c('beer', '6H')] });
t = play(t, 'A', b2, { target: 'B' });
expect(t.lastCheck).toMatchObject({ player: 'B', purpose: 'barrel', success: true });
expect(t.reactions[0]).toMatchObject({ kind: 'bang', needed: 1 });
t = act(t, 'B', { type: 'respond', cardIds: [m2] });
expect(pl(t, 'B').life).toBe(4);
expect(t.reactions).toEqual([]);
// Slab's gatling: one 빗나감! is enough.
const g = c('gatling');
const m3 = c('missed');
let u = rig({ players: basic({ A: { ch: 'slab', hand: [g] }, B: { hand: [m3] } }) });
u = play(u, 'A', g);
expect(u.reactions.find((r) => r.kind === 'bang' && r.target === 'B')).toMatchObject({ needed: 1, via: 'gatling' });
u = act(u, 'B', { type: 'respond', cardIds: [m3] });
expect(pl(u, 'B').life).toBe(4);
});
test('술통: ♥ 판정이면 회피, 아니면 반응 대기; autoBarrel 끄면 useBarrel로 직접', () => {
const c = pool();
const b = c('bang');
let s = rig({ players: basic({ A: { hand: [b] }, B: { inPlay: [c('barrel')] } }), deckTop: [c('missed', '2S')] });
s = play(s, 'A', b, { target: 'B' });
expect(s.lastCheck).toMatchObject({ purpose: 'barrel', success: false });
expect(s.reactions).toHaveLength(1);
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').life).toBe(3);
// Manual barrel.
const b2 = c('bang');
let t = rig({ players: basic({ A: { hand: [b2] }, B: { inPlay: [c('barrel')] } }), deckTop: [c('beer', '7H')], options: { autoBarrel: false } });
t = play(t, 'A', b2, { target: 'B' });
expect(t.lastCheck).toBeNull();
expect(bang.view(t, 'B').my!.prompt).toMatchObject({ kind: 'bang', canBarrel: true });
t = act(t, 'B', { type: 'useBarrel' });
expect(t.reactions).toEqual([]);
expect(pl(t, 'B').life).toBe(4);
expect(reject(t, 'B', { type: 'useBarrel' })).toBe('뱅!을 받았을 때만 술통 판정을 해요.');
});
test('주르도네 + 술통: 판정 2회(각 1장 공개); 럭키 듀크는 2장 공개 후 좋은 카드', () => {
const c = pool();
const b = c('bang');
// Real barrel fails (♠), Jourdonnais succeeds (♥).
let s = rig({ players: basic({ A: { hand: [b] }, B: { ch: 'jourdonnais', inPlay: [c('barrel')] } }), deckTop: [c('missed', '3S'), c('beer', '8H')] });
s = play(s, 'A', b, { target: 'B' });
const checks = s.log.filter((e) => e.t === 'check');
expect(checks.map((e) => (e.t === 'check' ? [e.purpose, e.cards.length, e.success] : null))).toEqual([
['barrel', 1, false],
['jourdonnais', 1, true],
]);
expect(s.reactions).toEqual([]);
expect(pl(s, 'B').life).toBe(4);
// Lucky Duke with a barrel: ♠ and ♥ revealed, the ♥ counts.
const b2 = c('bang');
let t = rig({ players: basic({ A: { hand: [b2] }, B: { ch: 'lucky', inPlay: [c('barrel')] } }), deckTop: [c('missed', '4S'), c('beer', '9H')] });
t = play(t, 'A', b2, { target: 'B' });
expect(t.lastCheck).toMatchObject({ purpose: 'barrel', success: true });
expect(t.lastCheck!.cards).toHaveLength(2);
expect(t.reactions).toEqual([]);
expect(t.discard.slice(-2).map((id) => cardById(id).suit)).toEqual(['S', 'H']);
});
});
// ---------------------------------------------------------------- turn start checks
describe('다이너마이트와 감옥 (§5.2)', () => {
test('다이너마이트: ♠2~♠9 폭발(3 피해); ♠10·♥는 다음 생존자로; 다이너마이트 → 감옥 순서', () => {
for (const [code, kind, boom] of [
['2S', 'missed', true],
['9S', 'stagecoach', true],
['8S', 'missed', true],
['10S', 'volcanic', false],
['6H', 'beer', false],
['AS', 'bang', false],
] as const) {
const c = pool();
const dyn = c('dynamite');
const jail = c('jail');
const s0 = rig({
players: basic({ B: { ch: 'willy', inPlay: [dyn, jail], hand: [] } }),
turn: 'A',
deckTop: [c(kind, code), c('beer', '7H')],
});
// Ending A's turn starts B's turn.
const s = act(s0, 'A', { type: 'endPlay' });
const b = pl(s, 'B');
const checks = s.log.filter((e) => e.t === 'check').map((e) => (e.t === 'check' ? e.purpose : ''));
expect(checks).toEqual(['dynamite', 'jail']);
if (boom) {
expect(b.life).toBe(1);
expect(s.discard).toContain(dyn);
expect(pl(s, 'C').inPlay).not.toContain(dyn);
} else {
expect(b.life).toBe(4);
expect(pl(s, 'C').inPlay).toContain(dyn);
}
// ♥7 → escaped from jail, normal turn (drew 2).
expect(b.inPlay).not.toContain(jail);
expect(s.turn.player).toBe('B');
expect(s.turn.phase).toBe('play');
expect(b.hand.length).toBe(2);
conserve(s);
}
});
test('다이너마이트 폭발로 무법자가 죽으면 처치 보상 없음; 죽은 사람 턴은 넘어간다', () => {
const c = pool();
const dyn = c('dynamite');
const s0 = rig({ players: basic({ B: { inPlay: [dyn], life: 2, ch: 'suzy' } }), turn: 'A', deckTop: [c('missed', '5S')] });
const s = act(s0, 'A', { type: 'endPlay' });
expect(pl(s, 'B').alive).toBe(false);
expect(s.log.some((e) => e.t === 'reward')).toBe(false);
expect(s.log.find((e) => e.t === 'dead')).toMatchObject({ p: 'B', role: 'outlaw', by: null });
expect(s.turn.player).toBe('C');
});
test('감옥: 보안관 대상 거부; ♥ 탈출 시 정상 턴; 실패하면 1단계 포함 턴 전체를 건너뜀', () => {
const c = pool();
const j = c('jail');
let s = rig({ players: basic({ B: { hand: [j] } }), turn: 'B' });
expect(reject(s, 'B', { type: 'play', cardId: j, target: 'A' })).toBe('보안관은 감옥에 넣을 수 없어요.');
expect(reject(s, 'B', { type: 'play', cardId: j, target: 'B' })).toBe('자기 자신은 감옥에 넣을 수 없어요.');
s = play(s, 'B', j, { target: 'C' });
expect(pl(s, 'C').inPlay).toContain(j);
const j2 = c('jail');
pl(s, 'B').hand.push(j2);
expect(reject(s, 'B', { type: 'play', cardId: j2, target: 'C' })).toBe('이미 감옥에 있는 사람이에요.');
// C's turn: a ♠ → stays in jail, the whole turn is skipped (no cards drawn).
s.deck.push(c('missed', '6S'));
const handBefore = pl(s, 'C').hand.length;
s = act(s, 'B', { type: 'endPlay' });
expect(s.log.find((e) => e.t === 'jail')).toMatchObject({ p: 'C', escaped: false });
expect(pl(s, 'C').hand.length).toBe(handBefore);
expect(pl(s, 'C').inPlay).not.toContain(j);
expect(s.turn.player).toBe('D');
// Escape on ♥.
const j3 = c('jail');
let t = rig({ players: basic({ C: { inPlay: [j3] } }), turn: 'B', deckTop: [c('beer', '8H')] });
t = act(t, 'B', { type: 'endPlay' });
expect(t.turn.player).toBe('C');
expect(t.turn.phase).toBe('draw'); // Pedro Ramirez may choose where to draw from
expect(pl(t, 'C').inPlay).toEqual([]);
});
});
// ---------------------------------------------------------------- life, beer, death
describe('맥주·살롱·빈사 (§5.3, §5.4)', () => {
test('맥주: 생명 가득이면 거부; 2명 남으면 거부; 살롱은 2명에서도 회복', () => {
const c = pool();
const beer = c('beer');
let s = rig({ players: basic({ A: { hand: [beer] } }) });
expect(reject(s, 'A', { type: 'play', cardId: beer })).toBe('생명이 가득 차서 맥주를 쓸 수 없어요.');
pl(s, 'A').life = 3;
s = play(s, 'A', beer);
expect(pl(s, 'A').life).toBe(4);
const b2 = c('beer');
const sal = c('saloon');
let t = rig({ players: basic({ A: { hand: [b2, sal], life: 2 }, B: { alive: false }, C: { alive: false }, D: { life: 1 } }) });
expect(reject(t, 'A', { type: 'play', cardId: b2 })).toBe('두 명만 남으면 맥주는 효과가 없어요.');
t = play(t, 'A', sal);
expect([pl(t, 'A').life, pl(t, 'D').life]).toEqual([3, 2]);
// House rule: beer at full health is allowed (no effect).
const b3 = c('beer');
const u = rig({ players: basic({ A: { hand: [b3] } }), options: { beerAtFullHealth: true } });
expect(reject(u, 'A', { type: 'play', cardId: b3 })).toBeNull();
});
test('빈사: 생명 −1이면 맥주 2장 필요; 1장 제출 거부; 2장으로 생존', () => {
const c = pool();
const dyn = c('dynamite');
const beers = [c('beer'), c('beer')];
const s0 = rig({ players: basic({ B: { inPlay: [dyn], life: 2, hand: beers, ch: 'suzy' } }), turn: 'A', deckTop: [c('missed', '7S')] });
let s = act(s0, 'A', { type: 'endPlay' });
expect(pl(s, 'B').life).toBe(-1);
expect(bang.view(s, 'B').my!.prompt).toMatchObject({ kind: 'dying', needed: 2, beers, beerAllowed: true });
expect(reject(s, 'B', { type: 'respond', cardIds: [beers[0]!] })).toBe('맥주 2장이 필요해요.');
s = act(s, 'B', { type: 'respond', cardIds: beers });
expect(pl(s, 'B').life).toBe(1);
expect(pl(s, 'B').alive).toBe(true);
// B's turn continues (start → draw → play).
expect(s.turn.player).toBe('B');
expect(s.turn.phase).toBe('play');
});
test('2명 남았을 때 빈사에서 맥주를 쓸 수 없어 바로 제거', () => {
const c = pool();
const b = c('bang');
const s0 = rig({ players: basic({ A: { hand: [b] }, B: { alive: false }, C: { life: 1, hand: [c('beer')] }, D: { alive: false } }), turn: 'A' });
let s = play(s0, 'A', b, { target: 'C' });
s = act(s, 'C', { type: 'takeHit' });
expect(pl(s, 'C').alive).toBe(false);
expect(s.winner).toBe('law');
});
test('빈사 시간 초과: 맥주로 살 수 있으면 자동 사용, 아니면 포기', () => {
const c = pool();
const b = c('bang');
const beer = c('beer');
let s = rig({ players: basic({ A: { hand: [b] }, B: { life: 1, hand: [beer] } }) });
s = play(s, 'A', b, { target: 'B' });
s = act(s, 'B', { type: 'takeHit' });
expect(s.reactions[0]).toMatchObject({ kind: 'dying', player: 'B' });
s = act(s, 'B', { type: 'timeout' });
expect(pl(s, 'B')).toMatchObject({ alive: true, life: 1 });
// giveUp → eliminated, killer A (sheriff kills an outlaw → 3 cards).
const b2 = c('bang');
let t = rig({ players: basic({ A: { hand: [b2] }, B: { life: 1, hand: [c('beer')] } }) });
t = play(t, 'A', b2, { target: 'B' });
t = act(t, 'B', { type: 'takeHit' });
t = act(t, 'B', { type: 'giveUp' });
expect(pl(t, 'B').alive).toBe(false);
expect(t.log.find((e) => e.t === 'reward')).toMatchObject({ p: 'A', n: 3 });
});
});
// ---------------------------------------------------------------- duel, indians, gatling, store
describe('결투·인디언!·개틀링·잡화점 (§5.4)', () => {
test('결투 왕복: A→B, B 뱅! → A 뱅! → B 포기 → B 1 손실(처치자 A); A가 먼저 포기하면 A 손실(처치자 B)', () => {
const c = pool();
const duel = c('duel');
const a1 = c('bang');
const b1 = c('bang');
let s = rig({ players: basic({ A: { hand: [duel, a1] }, B: { hand: [b1], life: 1, ch: 'suzy' }, C: { ch: 'kit' } }) });
s = play(s, 'A', duel, { target: 'B' });
expect(s.reactions[0]).toMatchObject({ kind: 'duel', actor: 'B', other: 'A' });
expect(reject(s, 'A', { type: 'respond', cardIds: [a1] })).toBe('지금은 낼 수 있는 반응이 없어요.');
s = act(s, 'B', { type: 'respond', cardIds: [b1] });
// Suzy: her last card went into the duel → she draws one at once.
expect(pl(s, 'B').hand).toHaveLength(1);
expect(s.reactions[0]).toMatchObject({ kind: 'duel', actor: 'A', other: 'B' });
s = act(s, 'A', { type: 'respond', cardIds: [a1] });
expect(s.turn.bangsPlayed).toBe(0); // duel bangs do not count
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').alive).toBe(false);
expect(s.log.find((e) => e.t === 'dead')).toMatchObject({ p: 'B', by: 'A' });
expect(s.log.find((e) => e.t === 'reward')).toMatchObject({ p: 'A' });
// A gives up first.
const d2 = c('duel');
let t = rig({ players: basic({ A: { hand: [d2], life: 1 }, B: { hand: [c('bang')] }, C: { role: 'deputy' } }), turn: 'A' });
t = play(t, 'A', d2, { target: 'B' });
t = act(t, 'B', { type: 'respond', cardIds: [pl(t, 'B').hand[0]!] });
t = act(t, 'A', { type: 'takeHit' });
expect(t.log.find((e) => e.t === 'hit')).toMatchObject({ p: 'A', by: 'B' });
expect(t.winner).toBe('outlaws');
});
test('인디언!: 3명이 서로 다른 순서로 응답, 도착 순서대로 처리, 모두 끝나기 전 play 거부', () => {
const c = pool();
const ind = c('indians');
const bang1 = c('bang');
const other = c('bang');
let s = rig({ players: basic({ A: { hand: [ind, other] }, B: { hand: [] }, C: { hand: [bang1] }, D: { hand: [c('missed')] } }) });
s = play(s, 'A', ind);
expect(s.reactions.map((r) => r.kind)).toEqual(['indians', 'indians', 'indians']);
expect(bang.activePlayers(s).sort()).toEqual(['B', 'C', 'D']);
expect(reject(s, 'A', { type: 'play', cardId: other, target: 'B' })).toBe('다른 사람의 반응을 기다리고 있어요.');
s = act(s, 'D', { type: 'takeHit' });
expect(reject(s, 'D', { type: 'takeHit' })).toBe('지금은 맞을 공격이 없어요.');
s = act(s, 'C', { type: 'respond', cardIds: [bang1] });
s = act(s, 'B', { type: 'timeout' });
const hits = s.log.filter((e) => e.t === 'hit').map((e) => (e.t === 'hit' ? e.p : ''));
expect(hits).toEqual(['D', 'B']);
expect([pl(s, 'B').life, pl(s, 'C').life, pl(s, 'D').life]).toEqual([3, 4, 3]);
expect(s.reactions).toEqual([]);
expect(reject(s, 'A', { type: 'play', cardId: other, target: 'B' })).toBeNull();
});
test('개틀링: 다른 모두에게 뱅!(거리 무관, 턴 제한에 포함 안 됨), 각자 빗나감!/술통 가능', () => {
const c = pool();
const g = c('gatling');
const b = c('bang');
const mC = c('missed');
let s = rig({
players: basic({ A: { hand: [g, b] }, B: { inPlay: [c('barrel')] }, C: { hand: [mC], inPlay: [c('mustang')] } }),
deckTop: [c('beer', '9H')],
});
s = play(s, 'A', g);
// B's barrel (♥) saved him at once; C and D must answer.
expect(s.reactions.map((r) => (r.kind === 'bang' ? r.target : ''))).toEqual(['C', 'D']);
s = act(s, 'C', { type: 'respond', cardIds: [mC] });
s = act(s, 'D', { type: 'takeHit' });
expect([pl(s, 'B').life, pl(s, 'C').life, pl(s, 'D').life]).toEqual([4, 4, 3]);
expect(s.turn.bangsPlayed).toBe(0);
expect(reject(s, 'A', { type: 'play', cardId: b, target: 'B' })).toBeNull();
});
test('잡화점: 생존자 수만큼 공개, 낸 사람부터 시계 방향, 시간 초과 시 첫 장, 마지막 장은 자동', () => {
const c = pool();
const gs = c('generalStore');
const top = [c('bang'), c('beer'), c('missed'), c('panic')];
let s = rig({ players: basic({ C: { hand: [gs] }, B: { alive: false } }), turn: 'C', deckTop: [...top, c('duel')] });
s = play(s, 'C', gs);
const r = s.reactions[0]!;
expect(r.kind).toBe('store');
if (r.kind !== 'store') return;
expect(r.revealed).toEqual(top.slice(0, 3));
expect(r.picker).toBe('C');
expect(bang.view(s, 'A').reactions[0]!.revealed!.map((x) => x.id)).toEqual(top.slice(0, 3));
expect(reject(s, 'D', { type: 'storePick', cardId: top[0]! })).toBe('지금은 잡화점 카드를 고를 차례가 아니에요.');
s = act(s, 'C', { type: 'storePick', cardId: top[1]! });
expect(s.reactions[0]).toMatchObject({ picker: 'D' });
s = act(s, 'D', { type: 'timeout' });
// A gets the last card without choosing.
expect(s.reactions).toEqual([]);
expect(pl(s, 'C').hand).toEqual([top[1]!]);
expect(pl(s, 'D').hand).toEqual([top[0]!]);
expect(pl(s, 'A').hand).toEqual([top[2]!]);
conserve(s);
});
});
// ---------------------------------------------------------------- other brown and blue cards
describe('나머지 카드 (§5.3)', () => {
test('역마차 2장, 웰스 파고 3장', () => {
const c = pool();
const st = c('stagecoach');
const wf = c('wellsFargo');
let s = rig({ players: basic({ A: { hand: [st, wf] } }) });
s = play(s, 'A', st);
expect(pl(s, 'A').hand).toHaveLength(3);
s = play(s, 'A', wf);
expect(pl(s, 'A').hand).toHaveLength(5);
});
test('패닉!: 거리 1 이내만, 손패 무작위 1장 또는 장착 카드 지정; 가져간 카드는 두 사람에게만 보임', () => {
const c = pool();
const pn = c('panic');
const pn2 = c('panic');
const bHand = c('beer');
const mus = c('barrel');
let s = rig({ players: basic({ A: { hand: [pn, pn2] }, B: { hand: [bHand], inPlay: [mus] }, C: { hand: [c('bang')] } }) });
expect(reject(s, 'A', { type: 'play', cardId: pn, target: 'C', targetCard: 'hand' })).toBe('패닉!은 거리 1인 사람에게만 쓸 수 있어요(거리 2).');
expect(reject(s, 'A', { type: 'play', cardId: pn, target: 'B' })).toBe('가져올 카드를 골라 주세요.');
expect(reject(s, 'A', { type: 'play', cardId: pn, target: 'A', targetCard: 'hand' })).toBe('자기 자신에게는 쓸 수 없어요.');
const opt = bang.view(s, 'A').my!.plays.find((o) => o.cardId === pn)!;
expect(opt.targets!.find((t) => t.id === 'B')!.cards).toEqual(['hand', mus]);
s = play(s, 'A', pn, { target: 'B', targetCard: mus });
expect(pl(s, 'A').hand).toContain(mus);
expect(pl(s, 'B').inPlay).toEqual([]);
s = play(s, 'A', pn2, { target: 'B', targetCard: 'hand' });
expect(pl(s, 'A').hand).toContain(bHand);
const entry = s.log.filter((e) => e.t === 'take').pop()!;
expect(entry).toMatchObject({ how: 'panic', vis: ['A', 'B'] });
const seen = (v: string) => JSON.stringify(bang.view(s, v).log.filter((e) => e.t === 'take').pop());
expect(seen('A')).toContain('"beer"');
expect(seen('B')).toContain('"beer"');
expect(seen('C')).not.toContain('"beer"');
expect(JSON.stringify(bang.view(s, null).log.filter((e) => e.t === 'take').pop())).not.toContain('"beer"');
});
test('캣 벌루: 거리 무관, 손패 무작위 1장(공개 버림) 또는 장착 카드; 하우스 룰로 자기 다이너마이트 제거', () => {
const c = pool();
const cb = c('catBalou');
const cHand = c('missed');
let s = rig({ players: basic({ A: { hand: [cb] }, C: { hand: [cHand] } }) });
s = play(s, 'A', cb, { target: 'C', targetCard: 'hand' });
expect(pl(s, 'C').hand).toEqual([]);
expect(s.discard).toContain(cHand);
expect(s.log.filter((e) => e.t === 'discarded').pop()).toMatchObject({ p: 'C', by: 'A', fromHand: true });
const cb2 = c('catBalou');
const dyn = c('dynamite');
const t = rig({ players: basic({ A: { hand: [cb2], inPlay: [dyn] } }) });
expect(reject(t, 'A', { type: 'play', cardId: cb2, target: 'A', targetCard: dyn })).toBe('자기 자신에게는 쓸 수 없어요.');
const u = rig({ players: basic({ A: { hand: [cb2], inPlay: [dyn] } }), options: { selfTargetCatBalou: true } });
expect(reject(u, 'A', { type: 'play', cardId: cb2, target: 'A', targetCard: 'hand' })).toBe('내 손패에는 쓸 수 없어요.');
const u2 = play(u, 'A', cb2, { target: 'A', targetCard: dyn });
expect(pl(u2, 'A').inPlay).toEqual([]);
});
test('파란 카드: 같은 이름은 1장, 무기는 1개(새 무기를 내면 기존 무기 버림), 다이너마이트는 내 앞에', () => {
const c = pool();
const sch = c('schofield');
const sch2 = c('schofield');
const win = c('winchester');
const mus = c('mustang');
const mus2 = c('mustang');
const dyn = c('dynamite');
let s = rig({ players: basic({ A: { hand: [sch, sch2, win, mus, mus2, dyn] } }) });
s = play(s, 'A', sch);
expect(reject(s, 'A', { type: 'play', cardId: sch2 })).toBe('같은 카드를 이미 앞에 놓았어요.');
s = play(s, 'A', win);
expect(pl(s, 'A').inPlay).toEqual([win]);
expect(s.discard).toContain(sch);
expect(bang.view(s, 'A').my!.range).toBe(5);
s = play(s, 'A', mus);
expect(reject(s, 'A', { type: 'play', cardId: mus2 })).toBe('같은 카드를 이미 앞에 놓았어요.');
s = play(s, 'A', dyn);
expect(pl(s, 'A').inPlay).toEqual([win, mus, dyn]);
});
});
// ---------------------------------------------------------------- death rewards, vulture, win
describe('처치 보상·벌칙·벌처 샘·승리 (§5.6, §6)', () => {
test('무법자 처치 시 처치자가 3장(처치자가 무법자여도)', () => {
const c = pool();
const b = c('bang');
let s = rig({ players: basic({ B: { hand: [b] }, C: { role: 'outlaw', life: 1 }, D: { role: 'renegade' } }), turn: 'B' });
s = play(s, 'B', b, { target: 'C' });
s = act(s, 'C', { type: 'takeHit' });
expect(pl(s, 'C').alive).toBe(false);
expect(pl(s, 'B').hand).toHaveLength(3);
expect(bang.view(s, 'D').players.find((p) => p.id === 'C')!.role).toBe('outlaw');
});
test('보안관이 부관을 처치하면 손패·장착 전부 버림; 벌처 샘은 죽은 사람 카드를 전부 손패로 (동시에)', () => {
const c = pool();
const b = c('bang');
const keep = [c('beer'), c('missed')];
const sheriffGear = [c('barrel'), c('scope')];
const depHand = [c('panic'), c('duel')];
const depGear = [c('mustang')];
let s = rig({
players: [
// The scope makes up for the deputy's mustang.
{ id: 'A', role: 'sheriff', ch: 'bart', hand: [b, ...keep], inPlay: sheriffGear },
{ id: 'B', role: 'deputy', ch: 'kit', life: 1, hand: depHand, inPlay: depGear },
{ id: 'C', role: 'outlaw', ch: 'vulture' },
{ id: 'D', role: 'outlaw', ch: 'pedro' },
{ id: 'E', role: 'renegade', ch: 'rose' },
],
});
s = play(s, 'A', b, { target: 'B' });
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').alive).toBe(false);
expect(s.log.some((e) => e.t === 'penalty' && e.p === 'A')).toBe(true);
expect(pl(s, 'A').hand).toEqual([]);
expect(pl(s, 'A').inPlay).toEqual([]);
for (const id of [...keep, ...sheriffGear]) expect(s.discard).toContain(id);
expect(pl(s, 'C').hand.sort()).toEqual([...depHand, ...depGear].sort());
conserve(s);
});
test('승리: 보안관·부관·배신자 생존 중 보안관 사망 → 무법자 승리(이미 죽은 무법자도)', () => {
const c = pool();
const b = c('bang');
let s = rig({
players: [
{ id: 'A', role: 'sheriff', ch: 'bart', life: 1 },
{ id: 'B', role: 'deputy', ch: 'kit' },
{ id: 'C', role: 'renegade', ch: 'suzy', hand: [b] },
{ id: 'D', role: 'outlaw', ch: 'pedro', alive: false },
{ id: 'E', role: 'outlaw', ch: 'rose', alive: false },
],
turn: 'C',
});
s = play(s, 'C', b, { target: 'A' });
s = act(s, 'A', { type: 'takeHit' });
expect(s.winner).toBe('outlaws');
const r = bang.result(s)!;
expect(r.ranking[0]!.sort()).toEqual(['D', 'E']);
expect(r.scores).toEqual({ A: 0, B: 0, C: 0, D: 1, E: 1 });
expect(r.summary).toContain('무법자 승리');
expect(r.ranking.flat().sort()).toEqual(['A', 'B', 'C', 'D', 'E']);
});
test('배신자 1대1에서 보안관 처치 → 배신자 승리; 무법자·배신자 모두 쓰러지면 보안관 팀 승리', () => {
const c = pool();
const b = c('bang');
let s = rig({ players: basic({ A: { life: 1 }, B: { alive: false }, C: { hand: [b] }, D: { alive: false } }), turn: 'C' });
s = play(s, 'C', b, { target: 'A' });
s = act(s, 'A', { type: 'takeHit' });
expect(s.winner).toBe('renegade');
expect(bang.result(s)!.ranking[0]).toEqual(['C']);
expect(bang.result(s)!.summary).toContain('배신자 승리');
// Law: the last outlaw falls.
const b2 = c('bang');
let t = rig({ players: basic({ A: { hand: [b2] }, B: { life: 1 }, C: { alive: false }, D: { alive: false } }) });
t = play(t, 'A', b2, { target: 'B' });
t = act(t, 'B', { type: 'takeHit' });
expect(t.winner).toBe('law');
expect(bang.result(t)!.ranking[0]).toEqual(['A']);
// After the end every role is visible and actions are refused.
expect(bang.view(t, null).players.every((p) => p.role !== null)).toBe(true);
expect(reject(t, 'A', { type: 'endPlay' })).toBe('게임이 이미 끝났어요.');
});
});
// ---------------------------------------------------------------- characters
describe('캐릭터 능력 (§3.2)', () => {
test('바트 캐시디: 잃은 생명만큼 1장씩', () => {
const c = pool();
const b = c('bang');
let s = rig({ players: basic({ A: { hand: [b] }, B: { ch: 'bart', hand: [] } }) });
s = play(s, 'A', b, { target: 'B' });
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').hand).toHaveLength(1);
expect(s.log.some((e) => e.t === 'draw' && e.p === 'B' && e.why === 'bart')).toBe(true);
});
test('블랙 잭: 두 번째 카드를 공개하고 ♥/♦면 1장 더', () => {
for (const [second, extra] of [
[['bang', 'QH'], true],
[['bang', '2D'], true],
[['missed', '2S'], false],
] as const) {
const c = pool();
let s = rig({ players: basic({ B: { ch: 'blackJack' } }), deckTop: [c('beer'), c(second[0], second[1]), c('panic')] });
s = act(s, 'A', { type: 'endPlay' });
expect(s.log.find((e) => e.t === 'blackJack')).toMatchObject({ p: 'B', extra });
expect(pl(s, 'B').hand).toHaveLength(extra ? 3 : 2);
}
});
test('엘 그링고: 뱅!으로 1 피해 시 공격자 손패 무작위 1장; 공격자 손패 0이면 없음; 다이너마이트 피해에는 없음', () => {
const c = pool();
const b = c('bang');
const aCard = c('beer');
let s = rig({ players: basic({ A: { hand: [b, aCard] }, B: { ch: 'elGringo', hand: [] } }) });
s = play(s, 'A', b, { target: 'B' });
s = act(s, 'B', { type: 'takeHit' });
expect(pl(s, 'B').hand).toEqual([aCard]);
expect(pl(s, 'A').hand).toEqual([]);
const b2 = c('bang');
let t = rig({ players: basic({ A: { hand: [b2] }, B: { ch: 'elGringo', hand: [] } }) });
t = play(t, 'A', b2, { target: 'B' });
t = act(t, 'B', { type: 'takeHit' });
expect(pl(t, 'B').hand).toEqual([]);
// Dynamite: El Gringo (sheriff, 4 life) loses 3 and takes nothing.
const dyn = c('dynamite');
const u0 = rig({ players: basic({ A: { ch: 'elGringo', inPlay: [dyn] }, D: { hand: [c('missed')] } }), turn: 'D', deckTop: [c('missed', '2S')] });
const u = act(u0, 'D', { type: 'endPlay' });
expect(pl(u, 'A').life).toBe(1);
expect(pl(u, 'D').hand).toHaveLength(1);
expect(u.log.some((e) => e.t === 'take')).toBe(false);
});
test('제시 존스: 첫 장을 다른 사람 손패에서 무작위로(손패 있는 사람만)', () => {
const c = pool();
const cCard = c('beer');
let s = rig({ players: basic({ B: { ch: 'jesse' }, C: { hand: [cCard] }, D: { hand: [] } }) });
s = act(s, 'A', { type: 'endPlay' });
expect(s.turn).toMatchObject({ player: 'B', phase: 'draw' });
expect(bang.view(s, 'B').my!.prompt).toEqual({ kind: 'draw', jesseTargets: ['C'], pedro: null });
expect(reject(s, 'B', { type: 'draw', jesseFrom: 'D' })).toBe('손패가 있는 다른 사람을 골라 주세요.');
expect(reject(s, 'B', { type: 'draw', pedroDiscard: true })).toBe('페드로 라미레스만 버린 카드 더미에서 받을 수 있어요.');
s = act(s, 'B', { type: 'draw', jesseFrom: 'C' });
expect(pl(s, 'B').hand).toHaveLength(2);
expect(pl(s, 'B').hand).toContain(cCard);
expect(pl(s, 'C').hand).toEqual([]);
expect(s.turn.phase).toBe('play');
});
test('킷 칼슨: 3장 보고 2장, 나머지는 덱 맨 위; 후보는 본인만 보임; 시간 초과 = 위 2장', () => {
const c = pool();
const top = [c('bang'), c('beer'), c('missed')];
let s = rig({ players: basic({ B: { ch: 'kit' } }), deckTop: top });
s = act(s, 'A', { type: 'endPlay' });
expect(s.reactions[0]).toMatchObject({ kind: 'kitKeep', player: 'B', options: top });
expect(JSON.stringify(bang.view(s, 'C'))).not.toContain(`"${top[0]}"`);
expect(bang.view(s, 'B').my!.prompt).toMatchObject({ kind: 'kitKeep' });
s = act(s, 'B', { type: 'kitKeep', keep: [top[0]!, top[2]!] });
expect(pl(s, 'B').hand.sort()).toEqual([top[0]!, top[2]!].sort());
expect(s.deck[s.deck.length - 1]).toBe(top[1]!);
let t = rig({ players: basic({ B: { ch: 'kit' } }), deckTop: top });
t = act(t, 'A', { type: 'endPlay' });
t = act(t, 'B', { type: 'timeout' });
expect(pl(t, 'B').hand).toEqual([top[0]!, top[1]!]);
});
test('페드로 라미레스: 첫 장을 버림 더미 맨 위에서', () => {
const c = pool();
const top = c('beer');
let s = rig({ players: basic({ B: { ch: 'pedro' } }), discard: [c('bang'), top] });
s = act(s, 'A', { type: 'endPlay' });
expect(bang.view(s, 'B').my!.prompt).toMatchObject({ kind: 'draw', pedro: { kind: 'beer' } });
s = act(s, 'B', { type: 'draw', pedroDiscard: true });
expect(pl(s, 'B').hand).toContain(top);
expect(pl(s, 'B').hand).toHaveLength(2);
// Timeout → normal draw.
let t = rig({ players: basic({ B: { ch: 'pedro' } }), discard: [c('missed')] });
t = act(t, 'A', { type: 'endPlay' });
t = act(t, 'B', { type: 'timeout' });
expect(t.turn.phase).toBe('play');
expect(pl(t, 'B').hand).toHaveLength(2);
});
test('럭키 듀크: 감옥 판정에서 2장 공개 후 ♥로 탈출', () => {
const c = pool();
const j = c('jail');
let s = rig({ players: basic({ B: { ch: 'lucky', inPlay: [j] } }), deckTop: [c('missed', '2S'), c('beer', '10H')] });
s = act(s, 'A', { type: 'endPlay' });
expect(s.lastCheck).toMatchObject({ player: 'B', purpose: 'jail', success: true });
expect(s.lastCheck!.cards).toHaveLength(2);
expect(s.turn).toMatchObject({ player: 'B', phase: 'play' });
});
test('시드 케첨: 손패 2장으로 1 회복(자기 턴·반응 중·빈사), 최대 생명 초과 불가', () => {
const c = pool();
const h = [c('mustang'), c('scope'), c('barrel'), c('volcanic'), c('jail'), c('dynamite')];
let s = rig({ players: basic({ A: { ch: 'sid', life: 3, hand: h } }) });
expect(reject(s, 'A', { type: 'sidHeal', cardIds: [h[0]!, h[0]!] })).toBe('같은 카드를 두 번 고를 수 없어요.');
s = act(s, 'A', { type: 'sidHeal', cardIds: [h[0]!, h[1]!] });
s = act(s, 'A', { type: 'sidHeal', cardIds: [h[2]!, h[3]!] });
expect(pl(s, 'A').life).toBe(5);
expect(reject(s, 'A', { type: 'sidHeal', cardIds: [h[4]!, h[5]!] })).toBe('생명이 이미 가득 찼어요.');
expect(reject(s, 'B', { type: 'sidHeal', cardIds: [h[2]!, h[3]!] })).toBe('시드 케첨만 쓸 수 있는 능력이에요.');
// Dying at 0 with 2 cards and no beer: heals back to 1.
const b = c('bang');
const two: [string, string] = [c('schofield'), c('remington')];
let t = rig({ players: basic({ A: { hand: [b] }, B: { ch: 'sid', life: 1, hand: two } }) });
t = play(t, 'A', b, { target: 'B' });
expect(reject(t, 'C', { type: 'sidHeal', cardIds: two })).not.toBeNull();
t = act(t, 'B', { type: 'takeHit' });
expect(t.reactions[0]).toMatchObject({ kind: 'dying', player: 'B' });
t = act(t, 'B', { type: 'sidHeal', cardIds: two });
expect(pl(t, 'B')).toMatchObject({ alive: true, life: 1 });
expect(t.reactions).toEqual([]);
// Not on someone else's turn without a reaction.
const u = rig({ players: basic({ B: { ch: 'sid', life: 2, hand: [c('carabine'), c('winchester')] } }) });
expect(reject(u, 'B', { type: 'sidHeal', cardIds: pl(u, 'B').hand as [string, string] })).toBe('지금은 능력을 쓸 수 없어요.');
});
test('수지 라파예트: 손패가 0장이 되는 순간 1장', () => {
const c = pool();
const st = c('stagecoach');
let s = rig({ players: basic({ A: { ch: 'suzy', hand: [st] } }) });
s = play(s, 'A', st);
expect(pl(s, 'A').hand).toHaveLength(3);
expect(s.log.some((e) => e.t === 'draw' && e.why === 'suzy')).toBe(true);
});
test('폴 리그레트·로즈 둘란: 거리 ±1 (머스탱·조준경 없이)', () => {
const s = rig({ players: basic({ C: { ch: 'paul' }, A: { ch: 'rose' } }) });
expect(distance(s, 'B', 'C')).toBe(2);
expect(distance(s, 'A', 'C')).toBe(2);
expect(distance(s, 'A', 'B')).toBe(1);
expect(distance(s, 'D', 'C')).toBe(2);
});
});
// ---------------------------------------------------------------- timeouts, away, leaving
describe('시간 초과·자리 비움·나가기 (§8.5)', () => {
test('턴 중 무응답 → endPlay → 손패 초과분 자동 버림', () => {
const c = pool();
const hand = [c('mustang'), c('scope'), c('barrel'), c('volcanic'), c('jail'), c('winchester')];
let s = rig({ players: basic({ A: { hand, life: 3 } }) });
expect(bang.deadline!(s)).toBe(s.turn.deadline);
expect(bang.timeoutPlayers!(s)).toEqual(['A']);
s = act(s, 'A', { type: 'timeout' });
expect(pl(s, 'A').hand).toHaveLength(3);
expect(s.log.some((e) => e.t === 'limit' && e.p === 'A' && e.cards.length === 3)).toBe(true);
expect(s.turn.player).toBe('B');
});
test('버리기 단계: 정확한 장수만, 시간 초과 시 무작위', () => {
const c = pool();
const hand = [c('mustang'), c('scope'), c('barrel'), c('volcanic'), c('jail')];
let s = rig({ players: basic({ A: { hand, life: 4 } }) });
s = act(s, 'A', { type: 'endPlay' });
expect(s.turn.phase).toBe('discard');
expect(bang.view(s, 'A').my!.prompt).toEqual({ kind: 'discard', count: 1 });
expect(reject(s, 'A', { type: 'discard', cardIds: hand.slice(0, 2) })).toBe('카드 1장을 골라 버려 주세요.');
s = act(s, 'A', { type: 'discard', cardIds: [hand[0]!] });
expect(s.turn.player).toBe('B');
});
test('반응 중에는 턴 시계가 멈춘다; 늦게 열린 반응은 먼저 끝나지 않는다', () => {
const c = pool();
const g = c('gatling');
let s = rig({ players: basic({ A: { hand: [g] }, B: { life: 1, hand: [c('beer')] } }) });
const before = s.turn.deadline!;
s = play(s, 'A', g);
const paused = clock;
s = act(s, 'B', { type: 'takeHit' });
// B's dying window opened later than C's and D's bang windows.
expect(bang.timeoutPlayers!(s).sort()).toEqual(['C', 'D']);
s = act(s, 'C', { type: 'takeHit' });
s = act(s, 'D', { type: 'takeHit' });
expect(bang.timeoutPlayers!(s)).toEqual(['B']);
s = act(s, 'B', { type: 'respond', cardIds: pl(s, 'B').hand.filter((id) => cardById(id).kind === 'beer') });
expect(s.reactions).toEqual([]);
expect(s.turn.deadline).toBe(before + (clock - paused));
});
test('3번 연속 시간 초과 → 자리 비움(5초 제한), 직접 행동하면 복귀', () => {
const c = pool();
let s = rig({ players: basic({ A: { hand: [c('bang')] } }) });
for (let k = 0; k < 3; k++) {
const p = s.turn.player;
s = act(s, p, { type: 'timeout' });
}
// A, B, C each timed out once; nobody is away yet.
expect(s.players.some((p) => p.away)).toBe(false);
const d = rig({ players: basic({ A: { hand: [c('bang')] } }) });
pl(d, 'A').timeoutsInRow = 2;
let x = act(d, 'A', { type: 'timeout' });
expect(pl(x, 'A').away).toBe(true);
// Next time it is A's turn the limit is 5 s.
for (const p of ['B', 'C', 'D']) x = act(x, p, { type: 'timeout' });
expect(x.turn.player).toBe('A');
expect(x.turn.deadline! - clock).toBe(5000);
x = act(x, 'A', { type: 'endPlay' });
expect(pl(x, 'A').away).toBe(false);
});
test('나가기: 그 사람은 쓰러진 것으로(역할 공개, 처치자 없음), 차례면 다음 사람; 보안관이 나가면 무법자 승리', () => {
const c = pool();
let s = rig({ players: basic({ B: { hand: [c('beer')] } }), turn: 'B' });
expect(bang.onLeave!(s, 'B')).toEqual({ type: 'leave' });
s = act(s, 'B', { type: 'leave' });
expect(pl(s, 'B').alive).toBe(false);
expect(s.log.find((e) => e.t === 'dead')).toMatchObject({ p: 'B', by: null, left: true });
expect(s.turn.player).toBe('C');
expect(bang.onLeave!(s, 'B')).toBeNull();
s = act(s, 'A', { type: 'leave' });
expect(s.winner).toBe('outlaws');
expect(bang.onLeave!(s, 'C')).toBeNull();
});
test('나가기: 반응 대기 중인 사람이 나가면 그 반응은 정리된다', () => {
const c = pool();
const ind = c('indians');
let s = rig({ players: basic({ A: { hand: [ind] } }) });
s = play(s, 'A', ind);
s = act(s, 'C', { type: 'leave' });
expect(s.reactions.map((r) => (r.kind === 'indians' ? r.target : ''))).toEqual(['B', 'D']);
});
test('무제한 (turnSeconds·reactionSeconds null): 시계 없음, 연결이 끊긴 사람은 여전히 자동 처리, 자리 비움은 5초', () => {
const shape = (bang.optionsSchema as unknown as { shape: Record<string, { meta(): { labels?: Record<string, string> } | undefined }> }).shape;
expect(shape.turnSeconds!.meta()?.labels?.null).toBe('무제한');
expect(shape.reactionSeconds!.meta()?.labels?.null).toBe('무제한');
expect(bang.optionsSchema.safeParse({ turnSeconds: null, reactionSeconds: null }).success).toBe(true);
expect(bang.defaultOptions).toMatchObject({ turnSeconds: 60, reactionSeconds: 15 });
const options = { turnSeconds: null, reactionSeconds: null };
const c = pool();
const ind = c('indians');
const bg = c('bang');
let s = rig({ players: basic({ A: { hand: [ind, bg, c('mustang'), c('scope'), c('barrel'), c('jail'), c('volcanic'), c('beer'), c('beer')] }, C: { hand: [c('bang')] } }), options });
s.turn.deadline = null;
expect(bang.deadline!(s)).toBeNull();
expect(bang.timeoutPlayers!(s)).toEqual(['A']);
expect(bang.view(s, 'A')).toMatchObject({ turnDeadline: null, deadlineTotalMs: 5000, reactionTotalMs: 5000 });
// 인디언: every reaction is unclocked, so every responder is listed (the room's disconnect grace times each one out).
s = play(s, 'A', ind);
expect(s.reactions.map((r) => r.deadline)).toEqual([null, null, null]);
expect(bang.deadline!(s)).toBeNull();
expect(bang.timeoutPlayers!(s).sort()).toEqual(['B', 'C', 'D']);
expect(bang.view(s, 'B').reactions.every((r) => r.deadline === null)).toBe(true);
expect(JSON.parse(JSON.stringify(s))).toEqual(s);
s = act(s, 'C', { type: 'timeout' });
expect(s.log.some((e) => e.t === 'respond' && e.p === 'C' && e.why === 'indians')).toBe(true);
s = act(s, 'B', { type: 'timeout' });
expect(pl(s, 'B').life).toBe(pl(s, 'B').maxLife - 1);
s = act(s, 'D', { type: 'takeHit' });
// The turn clock stays off after the reactions (pause arithmetic skips null).
expect(s.reactions).toEqual([]);
expect(s.turn).toMatchObject({ deadline: null, pausedAt: null });
// 뱅! at an away player: only that reaction has a clock (5 s), so only they are timed.
pl(s, 'B').away = true;
s = play(s, 'A', bg, { target: 'B' });
expect(s.reactions[0]!.deadline).toBe(clock + 5000);
expect(bang.deadline!(s)).toBe(clock + 5000);
expect(bang.timeoutPlayers!(s)).toEqual(['B']);
s = act(s, 'B', { type: 'timeout' });
// Hand over the limit → discard phase, still unclocked; a timeout discards at random.
s = act(s, 'A', { type: 'endPlay' });
expect(s.turn).toMatchObject({ phase: 'discard', deadline: null });
s = act(s, 'A', { type: 'timeout' });
expect(s.turn.player).toBe('B');
// B is away → the short clock on its own turn; C (not away) gets no clock.
expect(s.turn.deadline! - clock).toBe(5000);
expect(bang.deadline!(s)).toBe(s.turn.deadline);
s = act(s, 'B', { type: 'timeout' });
expect(s.turn.player).toBe('C');
expect(s.turn.deadline).toBeNull();
});
test('무제한: choose2 캐릭터 고르기도 시계 없음, 시간 초과(연결 끊김) 시 첫 번째 카드', () => {
const players = ['A', 'B', 'C', 'D'];
let s = bang.setup({ players, options: bang.optionsSchema.parse({ characterDraft: 'choose2', turnSeconds: null }), rng: SeededRng.fromSeed(seedN(5)), now: 0 });
expect(s.reactions.every((r) => r.kind === 'choose2' && r.deadline === null)).toBe(true);
expect(bang.deadline!(s)).toBeNull();
expect(bang.timeoutPlayers!(s).sort()).toEqual(players);
const offer = pl(s, 'B').characterOffer!;
s = act(s, 'B', { type: 'timeout' });
expect(pl(s, 'B').character).toBe(offer[0]!);
for (const p of ['A', 'C', 'D']) s = act(s, p, { type: 'timeout' });
expect(s.turn.phase).not.toBe('draft');
expect(s.turn.deadline).toBeNull();
// Timed draft keeps its 30 s clock.
const t = bang.setup({ players, options: bang.optionsSchema.parse({ characterDraft: 'choose2' }), rng: SeededRng.fromSeed(seedN(5)), now: 0 });
expect(bang.deadline!(t)).toBe(30_000);
});
test('onTimeout은 모든 상태에서 합법 행동', () => {
for (let seed = 1; seed <= 40; seed++) {
const players = ['A', 'B', 'C', 'D', 'E'];
let s = bang.setup({ players, options: bang.optionsSchema.parse({ characterDraft: seed % 2 ? 'choose2' : 'random' }), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
const r = SeededRng.fromSeed(seedN(seed + 1000));
for (let step = 0; step < 400 && !s.winner; step++) {
for (const p of bang.timeoutPlayers!(s)) expect(bang.validate(s, p, bang.onTimeout(s, p)).ok).toBe(true);
const p = bang.timeoutPlayers!(s)[0]!;
s = bang.apply(s, p, bang.onTimeout(s, p), { rng: r, now: (clock += 1000) }).state;
}
}
});
});
// ---------------------------------------------------------------- schema, views, leaks
describe('스키마·화면 정보 (§8.3)', () => {
test('옵션에 한국어 메타; 시스템 행동은 스키마에 없음', () => {
const shape = (bang.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(bang.actionSchema.safeParse({ type: 'timeout' }).success).toBe(false);
expect(bang.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
expect(bang.actionSchema.safeParse({ type: 'play', cardId: 'c1', target: 'B' }).success).toBe(true);
expect(bang.actionSchema.safeParse({ type: 'kitKeep', keep: ['c1'] }).success).toBe(false);
expect(bang.defaultOptions).toMatchObject({ characterDraft: 'random', turnSeconds: 60, reactionSeconds: 15, autoDefend: true, autoBarrel: true });
});
test('남의 차례·손에 없는 카드는 거부되고 상태는 그대로', () => {
const c = pool();
const b = c('bang');
const s = rig({ players: basic({ A: { hand: [b] }, B: { hand: [c('bang')] } }) });
const json = JSON.stringify(s);
expect(reject(s, 'B', { type: 'play', cardId: pl(s, 'B').hand[0]!, target: 'A' })).toBe('지금은 카드를 낼 수 없어요.');
expect(reject(s, 'A', { type: 'play', cardId: pl(s, 'B').hand[0]!, target: 'B' })).toBe('손에 없는 카드예요.');
expect(reject(s, 'X', { type: 'endPlay' })).toBe('이 게임의 플레이어가 아니에요.');
expect(reject(s, 'A', { type: 'play', cardId: b })).toBe('대상을 골라 주세요.');
expect(JSON.stringify(s)).toBe(json);
});
test('view: 보안관·나·죽은 사람만 역할 공개, 남 손패는 장수만, 덱은 장수만', () => {
const s = bang.setup({ players: ['A', 'B', 'C', 'D', 'E', 'F', 'G'], options: bang.defaultOptions, rng: SeededRng.fromSeed(seedN(5)), now: 0 });
for (const viewer of [...s.players.map((p) => p.id), null]) {
const v = bang.view(s, viewer);
for (const p of v.players) {
const real = pl(s, p.id);
expect(p.role).toBe(real.role === 'sheriff' || p.id === viewer ? real.role : null);
expect(p.handCount).toBe(real.hand.length);
}
expect(v.deckCount).toBe(s.deck.length);
expect(JSON.stringify(v)).not.toContain('"deck"');
}
});
});
// ---------------------------------------------------------------- properties
const TOKEN = /"[^"\\]*"/g;
/** Every JSON string token of a view is compared with the other players' secret ids; roles of hidden living players never show. */
function checkLeaks(s: BangState, viewers: (PlayerId | null)[]): void {
const owners = new Map<string, PlayerId[]>();
for (const p of s.players)
for (const secret of bang.secretsOf!(s, p.id)) {
const k = `"${secret}"`;
const list = owners.get(k);
if (list) list.push(p.id);
else owners.set(k, [p.id]);
}
for (const viewer of viewers) {
const v = bang.view(s, viewer);
for (const tok of JSON.stringify(v).match(TOKEN) ?? []) {
const of = owners.get(tok);
if (of && of.some((o) => o !== viewer)) throw new Error(`leak ${tok} of ${of.join(',')} to ${viewer}`);
}
for (const p of v.players) {
const real = pl(s, p.id);
if (p.role && !s.winner && real.alive && real.role !== 'sheriff' && p.id !== viewer) throw new Error(`role of ${p.id} leaked to ${viewer}`);
}
}
}
function invariants(s: BangState): void {
const all = allCards(s);
if (all.length !== 80 || new Set(all).size !== 80) throw new Error(`cards not conserved: ${all.length}`);
for (const p of s.players) {
if (p.life > p.maxLife) throw new Error(`${p.id} life above max`);
if (p.alive && p.life < 1 && !s.reactions.some((r) => r.kind === 'dying' && r.player === p.id)) throw new Error(`${p.id} alive at ${p.life} without dying window`);
if (!p.alive && (p.hand.length || p.inPlay.length)) throw new Error(`dead ${p.id} holds cards`);
if (p.inPlay.filter((id) => cardById(id).kind in { volcanic: 1, schofield: 1, remington: 1, carabine: 1, winchester: 1 }).length > 1) throw new Error('two weapons');
const names = p.inPlay.map((id) => cardById(id).kind);
if (new Set(names).size !== names.length) throw new Error('duplicate blue card');
}
if (s.deathOrder.length !== s.players.filter((p) => !p.alive).length) throw new Error('death order out of sync');
if (!s.winner) {
if (!pl(s, s.turn.player).alive && s.reactions.length === 0) throw new Error('dead current player');
if (bang.activePlayers(s).length === 0) throw new Error('nobody to act');
}
}
interface FastReport {
steps: number;
finished: boolean;
trace: string;
final: BangState;
}
/** Same chooser/action selection as `randomPlayout`, with cheaper scheduled checks so 1,000 games stay fast. */
function fastPlayout(players: PlayerId[], options: BangOptions, seed: RngState, maxSteps: number): FastReport {
const r = SeededRng.fromSeed(seed);
const chooser = SeededRng.fromSeed([seed[3], seed[2], seed[1], seed[0] ^ 0x9e3779b9]);
let now = 1_700_000_000_000;
let s = bang.setup({ players, options, rng: r, now });
const trace: string[] = [];
for (let step = 0; step < maxSteps; step++) {
invariants(s);
if (step % 10 === 0) checkLeaks(s, [null, players[(step / 10) % players.length]!]);
if (step % 50 === 0 && JSON.stringify(JSON.parse(JSON.stringify(s))) !== JSON.stringify(s)) throw new Error('not JSON round-trippable');
for (const p of bang.timeoutPlayers!(s)) {
const v = bang.validate(s, p, bang.onTimeout(s, p));
if (!v.ok) throw new Error(`onTimeout rejected for ${p}: ${v.reason}`);
}
if (bang.result(s)) {
checkLeaks(s, [...players, null]);
return { steps: step, finished: true, trace: trace.join(';'), final: s };
}
const actives = bang.activePlayers(s);
const actor = actives[chooser.int(actives.length)]!;
const legal = bang.legalActions!(s, actor);
// Now and then let the timer act instead (auto defence, auto discard, …).
const action = legal.length > 0 && chooser.int(8) > 0 ? legal[chooser.int(legal.length)]! : bang.onTimeout(s, actor);
const v = bang.validate(s, actor, action);
if (!v.ok) throw new Error(`generated action rejected: ${v.reason} ${JSON.stringify(action)}`);
now += 1000;
const out = bang.apply(s, actor, action, { rng: r, now });
if (step % 10 === 5) {
const hidden = new Set([...out.state.deck, ...out.state.players.flatMap((p) => p.hand)].map((id) => `"${id}"`));
for (const tok of JSON.stringify(out.events).match(TOKEN) ?? []) if (hidden.has(tok)) throw new Error(`event leaks ${tok}`);
}
s = out.state;
trace.push(`${actor}:${JSON.stringify(action)}`);
}
return { steps: maxSteps, finished: false, trace: trace.join(';'), final: s };
}
const PRESETS: Partial<BangOptions>[] = [
{},
{ characterDraft: 'choose2', autoBarrel: false },
{ autoDefend: false, drawBeforeDeath: true },
{ beerAtFullHealth: true, selfTargetCatBalou: true, deputyCount7: true },
{ characterDraft: 'choose2', autoBarrel: false, autoDefend: false, reactionSeconds: 8 },
{ characterDraft: 'choose2', turnSeconds: null, reactionSeconds: null },
];
const SEEDS = playoutSeeds(1000);
describe(`무작위 대국 (시드 ${SEEDS}개, 4~7명)`, () => {
test(`${SEEDS} games finish; cards conserved, life in bounds, no leaks, onTimeout always legal, deterministic`, () => {
let finished = 0;
const wins = { law: 0, outlaws: 0, renegade: 0 };
for (let i = 1; i <= SEEDS; i++) {
const n = 4 + (i % 4);
const players = Array.from({ length: n }, (_, k) => `P${k}`);
const options = bang.optionsSchema.parse(PRESETS[i % PRESETS.length]!);
const a = fastPlayout(players, options, seedN(i), 5000);
if (!a.finished) throw new Error(`seed ${i} (${n} players) did not finish in 5,000 steps`);
finished++;
wins[a.final.winner!]++;
const res = bang.result(a.final)!;
expect(res.ranking.flat().sort()).toEqual([...players].sort());
if (i % 25 === 0) {
const b = fastPlayout(players, options, seedN(i), 5000);
expect(b.trace).toBe(a.trace);
expect(JSON.stringify(b.final)).toBe(JSON.stringify(a.final));
}
}
expect(finished).toBe(SEEDS);
// Every team wins sometimes.
expect(wins.law).toBeGreaterThan(0);
expect(wins.outlaws).toBeGreaterThan(0);
expect(wins.renegade).toBeGreaterThan(0);
}, 60_000);
test.each([
[4, {}],
[5, { characterDraft: 'choose2' }],
[6, { autoBarrel: false }],
[7, { drawBeforeDeath: true }],
[5, { turnSeconds: null, reactionSeconds: null, characterDraft: 'choose2' }],
] as const)('randomPlayout with the engine per-step leak / round-trip checks: %i players', (n, opts) => {
const players = Array.from({ length: n }, (_, k) => `P${k}`);
const options = bang.optionsSchema.parse(opts);
for (let i = 1; i <= playoutSeeds(3); i++) {
const a = randomPlayout(bang, { players, options, seed: seedN(2000 + i), maxSteps: 5000, invariant: (st) => invariants(st as BangState), maxApplyMs: 30 });
expect(a.finished).toBe(true);
if (i === 1) {
const b = randomPlayout(bang, { players, options, seed: seedN(2000 + i), maxSteps: 5000, maxApplyMs: 30 });
expect(JSON.stringify(b.trace)).toBe(JSON.stringify(a.trace));
}
}
}, 60_000);
test('같은 시드 + 같은 행동 기록을 다시 적용하면 같은 최종 상태', () => {
const players = ['A', 'B', 'C', 'D', 'E', 'F'];
const options = bang.optionsSchema.parse({ characterDraft: 'choose2' });
const rep = randomPlayout(bang, { players, options, seed: seedN(77), maxSteps: 5000, maxApplyMs: 30 });
const replayRng = SeededRng.fromSeed(seedN(77));
let now = 1_700_000_000_000;
let s = bang.setup({ players, options, rng: replayRng, now });
for (const { actor, action } of rep.trace) s = bang.apply(s, actor, action as BangAction, { rng: replayRng, now: (now += 1000) }).state;
expect(JSON.stringify(s)).toBe(JSON.stringify(rep.finalState));
});
});