- 엔진 packages/games/src/tichu/: combo.ts(조합 판정·봉황 가장 센 해석·폭탄 비교·소원 의무·조합 찾기, 화면도 @bg/games/tichu/combo로 같이 씀), index.ts(그랜드 → 교환 → 플레이 → 용 주기 → 라운드 결과 상태 기계), bot.ts
- 옵션 전부: mode(team/individual/threechu/tientsin), targetScore, threechuHands, grandTichu, direction, bombTiming + bombWindowSeconds("카드 모으는 중" 폭탄 창, 폭탄 유무와 상관없이 같은 대기), wishRule(enforce/penalty), trickHistory(last/all), party(두 배·점수 뒤집기·손패 돌리기·평범, 연속 없음), turnSeconds, exchangeSeconds
- 비공개: 남의 손패·남은 6장·교환 전 더미. 카드 ID가 라운드마다 다시 쓰여 새 라운드에 지난 play 기록을 지움. 탑 무늬 ID는 b(p2 같은 플레이어 id와 겹침 방지)
- 컴퓨터: 손패 나누기 비용으로 가장 약한 조합부터, 짝꿍 트릭은 패스, 폭탄·용은 상대가 곧 나갈 때, 티츄/그랜드 판단, 교환(짝꿍 좋은 카드·상대 개와 약한 낱장), 패널티 모드에서도 소원 지킴, 레벨 1~60
- 화면 apps/web/src/games/tichu/: 52장은 PlayingCard(4색), 참새·개·봉황·용은 직접 그린 SVG. PC 십자 배치·휴대폰 칩 줄, 손패 7장×2줄(320px), 고른 카드 실시간 "풀하우스(9) · 낼 수 있어요", 추천 조합 칩, 소원 시트, 폭탄 목록, 교환 칸 3개(추천대로 채우기·다시 고르기), 용 주기, 라운드 결과 표, 점수판·라운드 기록·직전 트릭·나온 카드 표, 소리·흔들림·배너, 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·카드·패 탭, docs/games/README.md, result-score 테스트에 300점 옵션, e2e/games.e2e.ts(PC + 휴대폰 3대, 1라운드 끝 → 2라운드)
- 문서 docs/games/tichu.md에 구현 메모(정한 것) 추가
- 검증: tichu 64개, web games 224개, server 240개, bots·result-score 161개, 타입 검사·웹 빌드, E2E_PORT=4603 bun e2e/games.e2e.ts tichu 통과
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
879 lines
42 KiB
TypeScript
879 lines
42 KiB
TypeScript
/** 티츄 rules (docs/games/tichu.md §10). */
|
||
import { describe, expect, test } from 'bun:test';
|
||
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN, type AnyGameDefinition } from '@bg/engine';
|
||
import {
|
||
DOG,
|
||
DR,
|
||
FULL_DECK,
|
||
MJ,
|
||
PH,
|
||
allCards,
|
||
beats,
|
||
cardPoints,
|
||
classify,
|
||
findCombos,
|
||
mustFulfillWish,
|
||
scoreRound,
|
||
tichu,
|
||
type Combo,
|
||
type TichuAction,
|
||
type TichuOptions,
|
||
type TichuState,
|
||
type TichuView,
|
||
} from './index';
|
||
|
||
const P4 = ['A', 'B', 'C', 'D'];
|
||
const P3 = ['A', 'B', 'C'];
|
||
const P6 = ['A', 'B', 'C', 'D', 'E', 'F'];
|
||
let clock = 1_000_000;
|
||
|
||
function make(opts: Partial<TichuOptions> = {}, players = P4, seed = 1): TichuState {
|
||
const options = tichu.optionsSchema.parse(opts);
|
||
return tichu.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||
}
|
||
|
||
/** Seats hands (by seat), starts a trick on `current` (optionally with plays on the table) in phase playing. */
|
||
function rig(
|
||
s: TichuState,
|
||
r: { hands: string[][]; current?: number; plays?: { seat: number; cards: string[] }[]; wish?: number | null; won?: string[][] },
|
||
): TichuState {
|
||
s.hands = r.hands.map((h) => [...h]);
|
||
s.pending = s.seats.map(() => []);
|
||
s.won = r.won ?? s.seats.map(() => []);
|
||
s.phase = { kind: 'playing' };
|
||
s.out = [];
|
||
s.played = s.seats.map(() => false);
|
||
s.calls = s.seats.map(() => 'none');
|
||
s.wish = r.wish ?? null;
|
||
s.current = r.current ?? 0;
|
||
s.trick = { leader: r.plays?.[0]?.seat ?? s.current, plays: [], passed: [], closingAt: null, waived: [] };
|
||
let top: Combo | null = null;
|
||
for (const p of r.plays ?? []) {
|
||
const combo: Combo = classify(p.cards, top)!;
|
||
s.trick.plays.push({ seat: p.seat, cards: p.cards, combo, outOfTurn: false });
|
||
top = combo;
|
||
}
|
||
return s;
|
||
}
|
||
|
||
const act = (s: TichuState, p: string, a: TichuAction, now = (clock += 1000)): TichuState => {
|
||
const v = tichu.validate(s, p, a);
|
||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||
return tichu.apply(s, p, a, { rng: SeededRng.fromSeed([3, 3, 3, 3]), now }).state;
|
||
};
|
||
const reject = (s: TichuState, p: string, a: TichuAction): string | null => {
|
||
const v = tichu.validate(s, p, a);
|
||
return v.ok ? null : v.reason;
|
||
};
|
||
const play = (s: TichuState, p: string, cardIds: string[], extra: Partial<Extract<TichuAction, { type: 'play' }>> = {}) => act(s, p, { type: 'play', cardIds, ...extra });
|
||
const pass = (s: TichuState, p: string) => act(s, p, { type: 'pass' });
|
||
const view = (s: TichuState, p: string | null) => tichu.view(s, p) as TichuView;
|
||
const C = (ids: string) => ids.split(' ');
|
||
const cl = (ids: string, top: Combo | null = null) => classify(C(ids), top);
|
||
|
||
/** A legal hand filler: cards not used elsewhere (low, no specials), `n` of them. */
|
||
function filler(used: string[], n: number): string[] {
|
||
return FULL_DECK.filter((c) => !used.includes(c) && c !== MJ && c !== DOG && c !== PH && c !== DR).slice(0, n);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- deck / deal
|
||
|
||
describe('덱과 배분', () => {
|
||
test('56장, 카드 점수 합 100, 8장 → 6장, 각자 14장, 같은 시드면 같은 배분', () => {
|
||
expect(FULL_DECK).toHaveLength(56);
|
||
expect(new Set(FULL_DECK).size).toBe(56);
|
||
expect(cardPoints(FULL_DECK)).toBe(100);
|
||
expect(cardPoints(FULL_DECK, 'negative')).toBe(-100);
|
||
const s = make();
|
||
expect(s.phase.kind).toBe('grand');
|
||
expect(s.hands.map((h) => h.length)).toEqual([8, 8, 8, 8]);
|
||
expect(s.pending.map((h) => h.length)).toEqual([6, 6, 6, 6]);
|
||
expect(new Set(allCards(s)).size).toBe(56);
|
||
expect(JSON.stringify(make())).toBe(JSON.stringify(s));
|
||
let t = s;
|
||
for (const p of P4) t = act(t, p, { type: 'grand', call: false });
|
||
expect(t.phase.kind).toBe('exchange');
|
||
expect(t.hands.map((h) => h.length)).toEqual([14, 14, 14, 14]);
|
||
});
|
||
|
||
test('그랜드 티츄 끄기: 14장을 한 번에 받고 바로 교환', () => {
|
||
const s = make({ grandTichu: false });
|
||
expect(s.phase.kind).toBe('exchange');
|
||
expect(s.hands.map((h) => h.length)).toEqual([14, 14, 14, 14]);
|
||
expect(reject(s, 'A', { type: 'grand', call: true })).toBeTruthy();
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- combos
|
||
|
||
describe('조합 판정 (§5.1)', () => {
|
||
test('모양', () => {
|
||
expect(cl('j5 s5 j6 s6')?.type).toBe('pairSeq');
|
||
expect(cl('j5 s5 j7 s7')).toBeNull();
|
||
expect(cl('MJ j2 s3 b4 t5')).toMatchObject({ type: 'straight', value: 5, length: 5 });
|
||
expect(cl('j12 s13 b14 t2 j3')).toBeNull();
|
||
expect(cl('j4 s5 b6 t7')).toBeNull();
|
||
expect(cl('j3 s3 b3 t3 PH')).toBeNull();
|
||
expect(cl('j9 s9 b9 PH')).toBeNull();
|
||
expect(cl('j9 s9 b9 t9')?.type).toBe('bomb4');
|
||
expect(cl('MJ j2')).toBeNull();
|
||
expect(cl('DOG j2')).toBeNull();
|
||
expect(cl('DR PH')).toBeNull();
|
||
const fh6 = cl('j6 s6 b6 j2 s2')!;
|
||
const fh5 = cl('j5 s5 b5 j14 s14')!;
|
||
expect(fh6).toMatchObject({ type: 'fullHouse', value: 6 });
|
||
expect(beats(fh6, fh5)).toBe(true);
|
||
expect(beats(fh5, fh6)).toBe(false);
|
||
});
|
||
|
||
test('봉황 해석: 가장 센 것, 앞 조합을 이기는 해석이 있으면 그것', () => {
|
||
expect(cl('j7 s7 j9 s9 PH')).toMatchObject({ type: 'fullHouse', value: 9, phoenixAs: 9 });
|
||
expect(cl('j3 s4 b5 t6 PH')).toMatchObject({ type: 'straight', value: 7 });
|
||
expect(cl('j10 s11 b12 t13 PH')).toMatchObject({ type: 'straight', value: 14 });
|
||
const top = cl('j4 s5 b6 t7 j8')!;
|
||
const mine = cl('s5 b6 t7 s8 PH', top)!;
|
||
expect(mine).toMatchObject({ type: 'straight', value: 9 });
|
||
expect(beats(mine, top)).toBe(true);
|
||
expect(cl('j9 PH')).toMatchObject({ type: 'pair', value: 9 });
|
||
expect(cl('j11 s11 j12 s12 PH j13')).toMatchObject({ type: 'pairSeq', value: 13, length: 6 });
|
||
});
|
||
|
||
test('싱글 봉황: 앞 싱글 + 0.5, 선 1.5, 용 위는 안 됨', () => {
|
||
const eight = cl('j8')!;
|
||
const ph = classify([PH], eight)!;
|
||
expect(ph.value).toBe(8.5);
|
||
expect(beats(ph, eight)).toBe(true);
|
||
expect(beats(cl('s9')!, ph)).toBe(true);
|
||
expect(beats(cl('s8')!, ph)).toBe(false);
|
||
expect(classify([PH])!.value).toBe(1.5);
|
||
expect(beats(cl('j2')!, classify([PH])!)).toBe(true);
|
||
expect(classify([PH], classify([MJ]))!.value).toBe(1.5);
|
||
const aceP = classify([PH], cl('j14'))!;
|
||
expect(aceP.value).toBe(14.5);
|
||
expect(beats(classify([DR])!, aceP)).toBe(true);
|
||
expect(beats(classify([PH], classify([DR]))!, classify([DR])!)).toBe(false);
|
||
});
|
||
|
||
test('장수가 같아야 비교', () => {
|
||
const six = cl('j3 s4 b5 t6 j7 s8')!;
|
||
expect(beats(cl('j4 s5 b6 t7 j8')!, six)).toBe(false);
|
||
expect(beats(cl('j4 s5 b6 t7 j8 s9 b10')!, six)).toBe(false);
|
||
expect(beats(cl('j4 s5 b6 t7 j8 s9')!, six)).toBe(true);
|
||
const two = cl('j5 s5 j6 s6')!;
|
||
expect(beats(cl('j7 s7 j8 s8 j9 s9')!, two)).toBe(false);
|
||
expect(beats(cl('j7 s7 j8 s8')!, two)).toBe(true);
|
||
});
|
||
|
||
test('폭탄 순서: 8888 < AAAA < 5장 SF(9~K) < 6장 SF(2~7); 같은 무늬 5장은 늘 폭탄', () => {
|
||
const b8 = cl('j8 s8 b8 t8')!;
|
||
const bA = cl('j14 s14 b14 t14')!;
|
||
const sf5 = cl('j9 j10 j11 j12 j13')!;
|
||
const sf6 = cl('s2 s3 s4 s5 s6 s7')!;
|
||
expect(sf5.type).toBe('bombSF');
|
||
expect(beats(bA, b8)).toBe(true);
|
||
expect(beats(sf5, bA)).toBe(true);
|
||
expect(beats(sf6, sf5)).toBe(true);
|
||
expect(beats(b8, bA)).toBe(false);
|
||
expect(beats(b8, cl('DR')!)).toBe(true);
|
||
expect(cl('s3 s4 s5 s6 s7')!.type).toBe('bombSF');
|
||
expect(cl('s3 s4 s5 s6 s7 t8')).toMatchObject({ type: 'straight', length: 6 });
|
||
// On a 5-card straight the one-suit run goes on as a bomb, not as a straight.
|
||
const st = cl('j2 s3 b4 t5 j6')!;
|
||
expect(cl('s3 s4 s5 s6 s7', st)!.type).toBe('bombSF');
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- tricks
|
||
|
||
describe('트릭 (§5.2)', () => {
|
||
test('따라 내기·패스·트릭 끝(카드 모으는 중 → 모으기)', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('j8 s9'), C('j10 s2'), C('j11 s3'), C('j12 s4')], current: 0 });
|
||
expect(reject(s, 'A', { type: 'pass' })).toContain('패스할 수 없어요');
|
||
s = play(s, 'A', ['j8']);
|
||
expect(s.current).toBe(3); // right = counter-clockwise: 0 → 3
|
||
expect(reject(s, 'D', { type: 'play', cardIds: ['s4'] })).toBe('더 센 조합만 낼 수 있어요.');
|
||
expect(reject(s, 'C', { type: 'play', cardIds: ['j11'] })).toBe('지금은 내 차례가 아니에요.');
|
||
s = play(s, 'D', ['j12']);
|
||
s = pass(s, 'C');
|
||
s = pass(s, 'B');
|
||
s = pass(s, 'A');
|
||
expect(s.trick.closingAt).not.toBeNull();
|
||
expect(tichu.activePlayers(s).sort()).toEqual(P4);
|
||
for (const p of P4) s = act(s, p, { type: 'noBomb' });
|
||
expect(s.won[3]).toEqual(['j8', 'j12']);
|
||
expect(s.current).toBe(3);
|
||
expect(s.trick.plays).toHaveLength(0);
|
||
});
|
||
|
||
test('카드 모으는 시간이 끝나면 시간 초과로 모아요(자리 비움에는 안 셈)', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('j8 s9'), C('j10 s2'), C('j11 s3'), C('j12 s4')], current: 0 });
|
||
s = play(s, 'A', ['j8']);
|
||
s = pass(s, 'D');
|
||
s = pass(s, 'C');
|
||
s = pass(s, 'B', );
|
||
expect(tichu.deadline!(s)).toBe(s.trick.closingAt);
|
||
s = act(s, 'C', { type: 'timeout' });
|
||
expect(s.won[0]).toEqual(['j8']);
|
||
expect(s.timeoutsInRow.C).toBe(0);
|
||
});
|
||
|
||
test('나간 사람은 패스 판정에서 빠지고, 맨 위 낸 사람이 나갔으면 다음 사람이 선', () => {
|
||
let s = make({ grandTichu: false, bombTiming: 'ownTurn' });
|
||
s = rig(s, { hands: [C('j14'), C('j10 s2'), C('j11 s3'), C('j12 s4')], current: 0 });
|
||
s = play(s, 'A', ['j14']);
|
||
expect(s.out).toEqual([0]);
|
||
s = pass(s, 'D');
|
||
s = pass(s, 'C');
|
||
s = pass(s, 'B');
|
||
expect(s.won[0]).toEqual(['j14']);
|
||
expect(s.current).toBe(3);
|
||
});
|
||
});
|
||
|
||
describe('끼어드는 폭탄 (§5.5)', () => {
|
||
const setup = (o: Partial<TichuOptions> = {}) => {
|
||
const s = make({ grandTichu: false, ...o });
|
||
return rig(s, { hands: [C('j8 s3'), C('j9 s9 b9 t9 j2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||
};
|
||
test('차례가 아니어도 바닥 위에 폭탄, 다음 차례는 폭탄 낸 사람 다음', () => {
|
||
let s = setup();
|
||
expect(reject(s, 'B', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBe('폭탄은 바닥에 카드가 있을 때만 끼어들 수 있어요.');
|
||
s = play(s, 'A', ['j8']);
|
||
expect(s.current).toBe(3);
|
||
s = play(s, 'B', C('j9 s9 b9 t9'));
|
||
expect(s.trick.plays.at(-1)!.outOfTurn).toBe(true);
|
||
expect(s.current).toBe(0); // after seat 1 (right) is seat 0
|
||
});
|
||
test('내 조합 위에 내 폭탄, 카드 모으는 중 폭탄, 모은 뒤 거부', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('j8 j9 s9 b9 t9 s3'), C('j10 s2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||
s = play(s, 'A', ['j8']);
|
||
expect(reject(s, 'A', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBeNull();
|
||
s = pass(s, 'D');
|
||
s = pass(s, 'C');
|
||
s = pass(s, 'B');
|
||
expect(s.trick.closingAt).not.toBeNull();
|
||
expect(reject(s, 'A', { type: 'play', cardIds: ['s3'] })).toBe('카드 모으는 중에는 폭탄만 낼 수 있어요.');
|
||
const withBomb = s;
|
||
s = play(withBomb, 'A', C('j9 s9 b9 t9'));
|
||
expect(s.trick.closingAt).toBeNull();
|
||
expect(s.current).toBe(3);
|
||
// Collected instead: no bomb on an empty table.
|
||
let t = withBomb;
|
||
for (const p of P4) t = act(t, p, { type: 'noBomb' });
|
||
expect(t.trick.plays).toHaveLength(0);
|
||
expect(reject(t, 'D', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBeTruthy();
|
||
expect(reject(t, 'A', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBeNull(); // A leads: a bomb as lead is fine
|
||
});
|
||
test('개 직후 끼어들기 거부, ownTurn이면 차례 밖 폭탄 거부', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('DOG s3'), C('j9 s9 b9 t9 j2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||
s = play(s, 'A', [DOG]);
|
||
expect(s.current).toBe(2);
|
||
expect(reject(s, 'B', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBe('폭탄은 바닥에 카드가 있을 때만 끼어들 수 있어요.');
|
||
let o = setup({ bombTiming: 'ownTurn' });
|
||
o = play(o, 'A', ['j8']);
|
||
expect(reject(o, 'B', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toContain('자기 차례에만');
|
||
});
|
||
test('카드 모으는 중 activePlayers는 폭탄이 있든 없든 카드가 남은 모두', () => {
|
||
const run = (bomb: boolean) => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('j8 s3'), bomb ? C('j9 s9 b9 t9 j2') : C('j9 s10 b11 t12 j2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||
s = play(s, 'A', ['j8']);
|
||
for (const p of ['D', 'C', 'B']) s = pass(s, p);
|
||
return [...tichu.activePlayers(s)].sort();
|
||
};
|
||
expect(run(true)).toEqual(run(false));
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- wish
|
||
|
||
describe('참새 소원 (§5.3)', () => {
|
||
test('참새 + 소원 8 → 8을 가진 다음 사람은 8 싱글만(9·패스 거부)', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('MJ s3'), C('j9 s2'), C('j7 s4'), C('j8 s9')], current: 0 });
|
||
s = play(s, 'A', [MJ], { wish: 8 });
|
||
expect(s.wish).toBe(8);
|
||
expect(reject(s, 'D', { type: 'play', cardIds: ['s9'] })).toContain('소원 8');
|
||
expect(reject(s, 'D', { type: 'pass' })).toContain('소원 8');
|
||
expect(view(s, 'D').my!.mustWish).toBe(8);
|
||
s = play(s, 'D', ['j8']);
|
||
expect(s.wish).toBeNull();
|
||
});
|
||
test('8이 없고 봉황만 있으면 의무 없음', () => {
|
||
expect(mustFulfillWish(C('PH s9'), cl('j3'), 8, false)).toBe(false);
|
||
});
|
||
test('바닥 7 7, 손 8 봉황 → 8 봉황(8 페어)을 내야 함', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('s3'), C('j8 PH j13 s13'), C('s4'), C('s5')], current: 1, plays: [{ seat: 2, cards: C('j7 s7') }], wish: 8 });
|
||
expect(reject(s, 'B', { type: 'play', cardIds: C('j13 s13') })).toContain('소원 8');
|
||
expect(reject(s, 'B', { type: 'pass' })).toContain('소원 8');
|
||
expect(reject(s, 'B', { type: 'play', cardIds: C('j8 PH') })).toBeNull();
|
||
});
|
||
test('바닥 용, 손 8888 → 폭탄만 허용', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('s3'), C('j8 s8 b8 t8 j2'), C('s4'), C('s5')], current: 1, plays: [{ seat: 2, cards: [DR] }], wish: 8 });
|
||
expect(reject(s, 'B', { type: 'pass' })).toContain('소원 8');
|
||
expect(reject(s, 'B', { type: 'play', cardIds: C('j8 s8 b8 t8') })).toBeNull();
|
||
});
|
||
test('선이 8을 가지면 8 포함 조합만(개 거부)', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('DOG j8 s3'), C('s4'), C('s5'), C('s6')], current: 0, wish: 8 });
|
||
expect(reject(s, 'A', { type: 'play', cardIds: [DOG] })).toContain('소원 8');
|
||
expect(reject(s, 'A', { type: 'play', cardIds: ['s3'] })).toContain('소원 8');
|
||
expect(reject(s, 'A', { type: 'play', cardIds: ['j8'] })).toBeNull();
|
||
});
|
||
test('끼어드는 폭탄은 의무 없음, 8이 끼어든 폭탄으로 나와도 소원이 풀림, 소원은 트릭을 넘어 유지', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('MJ j8 s3'), C('j9 s9 b9 t9 j2'), C('j3 j4 j5 j6 j7 b8'), C('s5 s12')], current: 0 });
|
||
s = play(s, 'A', [MJ], { wish: 8 });
|
||
// D has no 8: free. Then B bombs out of turn without an 8 (no duty for an interrupting bomb).
|
||
s = play(s, 'D', ['s5']);
|
||
s = play(s, 'B', C('j9 s9 b9 t9'));
|
||
expect(s.wish).toBe(8);
|
||
for (const p of ['A', 'D', 'C']) s = pass(s, p === 'A' ? 'A' : p);
|
||
expect(s.trick.closingAt).not.toBeNull();
|
||
// C bombs with a straight flush that holds a real 8? No: j3..j7 + b8 is mixed. Pass the window.
|
||
for (const p of P4) s = act(s, p, { type: 'noBomb' });
|
||
expect(s.wish).toBe(8); // survives the trick
|
||
// A straight flush containing 8 ends the wish even out of turn.
|
||
let t = make({ grandTichu: false });
|
||
t = rig(t, { hands: [C('s3 s4'), C('j9 s2'), C('j4 j5 j6 j7 j8 b11'), C('s5 s12')], current: 0, wish: 8 });
|
||
t = play(t, 'A', ['s3']);
|
||
t = play(t, 'C', C('j4 j5 j6 j7 j8'));
|
||
expect(t.wish).toBeNull();
|
||
});
|
||
test('스트레이트 안의 참새도 소원을 걸어요', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('MJ j2 s3 b4 t5 s9'), C('s6'), C('s7'), C('s8')], current: 0 });
|
||
s = play(s, 'A', C('MJ j2 s3 b4 t5'), { wish: 11 });
|
||
expect(s.wish).toBe(11);
|
||
expect(reject(s, 'D', { type: 'play', cardIds: ['s8'], wish: 3 })).toContain('참새');
|
||
});
|
||
});
|
||
|
||
describe('소원 위반 패널티 (wishRule = penalty)', () => {
|
||
test('의무를 어긴 패스 → 즉시 라운드 끝, 상대 팀 200 + 상대 선언 성공, 위반 팀 선언 실패', () => {
|
||
let s = make({ grandTichu: false, wishRule: 'penalty' });
|
||
s = rig(s, { hands: [C('MJ s3'), C('j8 s9'), C('j7 s4'), C('j9 s2')], current: 0 });
|
||
s.calls = ['tichu', 'none', 'none', 'tichu'];
|
||
s = play(s, 'A', [MJ], { wish: 8 });
|
||
s = play(s, 'D', ['j9']);
|
||
s = pass(s, 'C');
|
||
expect(view(s, 'B').my!.mustWish).toBeNull(); // the screen does not tell in penalty mode
|
||
s = pass(s, 'B'); // B holds an 8 that beats 9? no: 8 < 9, so B is free here
|
||
expect(s.phase.kind).toBe('playing');
|
||
let t = make({ grandTichu: false, wishRule: 'penalty' });
|
||
t = rig(t, { hands: [C('MJ s3'), C('j8 s9'), C('j7 s4'), C('j6 s2')], current: 0 });
|
||
t.calls = ['tichu', 'none', 'none', 'tichu'];
|
||
t = play(t, 'A', [MJ], { wish: 8 });
|
||
t = play(t, 'D', ['j6']);
|
||
t = pass(t, 'C');
|
||
t = pass(t, 'B'); // B could play the 8: penalty for team B (seats 1·3)
|
||
const r = t.rounds.at(-1)!;
|
||
expect(r.kind).toBe('penalty');
|
||
expect(r.bonus).toEqual([200, 0]);
|
||
expect(r.cardPoints).toEqual([0, 0]);
|
||
expect(r.callPoints).toEqual([100, -100]);
|
||
expect(t.scores).toEqual([300, -100]);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- dog / dragon
|
||
|
||
describe('개와 용 (§5.3)', () => {
|
||
test('개: 선만, 짝꿍이 선, 짝꿍이 나갔으면 짝꿍 다음 카드 남은 사람', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('DOG s3'), C('s6'), C('s7'), C('s8')], current: 0 });
|
||
s = play(s, 'A', [DOG]);
|
||
expect(s.current).toBe(2);
|
||
expect(s.won[0]).toEqual([DOG]);
|
||
let t = make({ grandTichu: false });
|
||
t = rig(t, { hands: [C('s9'), C('s6'), C('s7'), C('DOG s8')], current: 0 });
|
||
t = play(t, 'A', ['s9']);
|
||
expect(reject(t, 'D', { type: 'play', cardIds: [DOG] })).toContain('새 트릭');
|
||
let u = make({ grandTichu: false });
|
||
u = rig(u, { hands: [C('DOG s3'), C('s6 s10'), [], C('s8')], current: 0 });
|
||
u.out = [2];
|
||
u = play(u, 'A', [DOG]);
|
||
// partner seat 2 is out; next after 2 in turn order (right: 2 → 1)
|
||
expect(u.current).toBe(1);
|
||
});
|
||
test('tientsin: 개는 dogTo 필수', () => {
|
||
let s = make({ grandTichu: false, mode: 'tientsin' }, P6);
|
||
s = rig(s, { hands: [C('DOG s3'), C('s4'), C('s5'), C('s6'), C('s7'), C('s8')], current: 0 });
|
||
expect(reject(s, 'A', { type: 'play', cardIds: [DOG] })).toContain('짝꿍을 골라');
|
||
expect(reject(s, 'A', { type: 'play', cardIds: [DOG], dogTo: 1 })).toContain('짝꿍에게만');
|
||
s = play(s, 'A', [DOG], { dogTo: 4 });
|
||
expect(s.current).toBe(4);
|
||
});
|
||
test('용으로 이기면 상대에게 줌(같은 팀 거부, 나간 상대 허용), 폭탄에 지면 폭탄 낸 사람이 가져감', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('DR s3'), [], C('s7'), C('s8 s9')], current: 0 });
|
||
s.out = [1];
|
||
s = play(s, 'A', [DR]);
|
||
s = pass(s, 'D');
|
||
s = pass(s, 'C');
|
||
for (const p of ['A', 'C', 'D']) s = act(s, p, { type: 'noBomb' });
|
||
expect(s.phase.kind).toBe('dragonGift');
|
||
expect(reject(s, 'A', { type: 'dragonTo', to: 2 })).toContain('상대 팀');
|
||
s = act(s, 'A', { type: 'dragonTo', to: 1 });
|
||
expect(s.won[1]).toEqual([DR]);
|
||
expect(s.current).toBe(0);
|
||
let t = make({ grandTichu: false });
|
||
t = rig(t, { hands: [C('DR s3'), C('j9 s9 b9 t9 s2'), C('s7'), C('s8')], current: 0 });
|
||
t = play(t, 'A', [DR]);
|
||
t = play(t, 'B', C('j9 s9 b9 t9'));
|
||
for (const p of ['A', 'D', 'C']) t = pass(t, p);
|
||
for (const p of P4) t = act(t, p, { type: 'noBomb' });
|
||
expect(t.won[1]!.sort()).toEqual([DR, 'j9', 's9', 'b9', 't9'].sort());
|
||
});
|
||
test('3등이 용으로 나가 라운드가 끝날 때도 용 주기 후 계산', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('DR'), [], [], C('s7 s4')], current: 0 });
|
||
s.out = [1, 2];
|
||
s = play(s, 'A', [DR]);
|
||
expect(s.phase).toMatchObject({ kind: 'dragonGift', final: true });
|
||
s = act(s, 'A', { type: 'dragonTo', to: 3 });
|
||
expect(s.phase.kind).toBe('roundEnd');
|
||
expect(s.rounds).toHaveLength(1);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- calls / exchange
|
||
|
||
describe('티츄 선언 (§5.6)', () => {
|
||
test('첫 카드 전 허용, 낸 뒤 거부, 그랜드 한 사람은 스몰 거부, 누가 나간 뒤 거부', () => {
|
||
let s = make();
|
||
expect(reject(s, 'A', { type: 'tichu' })).toContain('14장');
|
||
s = act(s, 'A', { type: 'grand', call: true });
|
||
for (const p of ['B', 'C', 'D']) s = act(s, p, { type: 'grand', call: false });
|
||
expect(s.calls[0]).toBe('grand');
|
||
expect(reject(s, 'A', { type: 'tichu' })).toContain('그랜드');
|
||
s = act(s, 'B', { type: 'tichu' });
|
||
expect(reject(s, 'B', { type: 'tichu' })).toContain('이미');
|
||
let t = make({ grandTichu: false });
|
||
t = rig(t, { hands: [C('s3 s4'), C('s6 s9'), C('s7'), C('s8')], current: 0 });
|
||
t = play(t, 'A', ['s3']);
|
||
expect(reject(t, 'A', { type: 'tichu' })).toContain('이미 카드를 내서');
|
||
expect(reject(t, 'D', { type: 'tichu' })).toBeNull();
|
||
t = play(t, 'D', ['s8']);
|
||
expect(t.out).toEqual([3]);
|
||
expect(reject(t, 'C', { type: 'tichu' })).toContain('다 털어서');
|
||
});
|
||
test('교환 중 선언 뒤 다른 사람이 교환을 다시 보낼 수 있음', () => {
|
||
let s = make({ grandTichu: false });
|
||
const give = (seat: number, k = 0) => [1, 2, 3].map((d) => ({ to: (seat + d) % 4, cardId: s.hands[seat]![d - 1 + k]! }));
|
||
s = act(s, 'A', { type: 'exchange', give: give(0) });
|
||
s = act(s, 'B', { type: 'tichu' });
|
||
s = act(s, 'A', { type: 'exchange', give: give(0, 3) });
|
||
expect(s.phase.kind).toBe('exchange');
|
||
expect((s.phase as { give: unknown[] }).give[0]).toHaveLength(3);
|
||
});
|
||
test('그랜드는 끄면 거부, threechu 딜러 거부', () => {
|
||
const s = make({ mode: 'threechu' }, P3);
|
||
const dealer = s.players[s.dealer!]!;
|
||
expect(reject(s, dealer, { type: 'grand', call: true })).toBeTruthy();
|
||
const other = P3.find((p) => p !== dealer)!;
|
||
expect(reject(s, other, { type: 'grand', call: true })).toBeNull();
|
||
});
|
||
});
|
||
|
||
describe('카드 교환 (§5.7)', () => {
|
||
test('같은 사람에게 2장 거부, 손에 없는 카드 거부, 모두 보내야 옮김, 받은 카드는 받은 사람 view에만', () => {
|
||
let s = make({ grandTichu: false });
|
||
const h = s.hands.map((x) => [...x]);
|
||
expect(reject(s, 'A', { type: 'exchange', give: [{ to: 1, cardId: h[0]![0]! }, { to: 1, cardId: h[0]![1]! }, { to: 2, cardId: h[0]![2]! }] })).toContain('한 사람에게');
|
||
expect(reject(s, 'A', { type: 'exchange', give: [{ to: 1, cardId: h[1]![0]! }, { to: 2, cardId: h[0]![1]! }, { to: 3, cardId: h[0]![2]! }] })).toContain('손에 없는');
|
||
const gives = [0, 1, 2, 3].map((seat) => [1, 2, 3].map((d) => ({ to: (seat + d) % 4, cardId: h[seat]![d - 1]! })));
|
||
for (let i = 0; i < 3; i++) s = act(s, P4[i]!, { type: 'exchange', give: gives[i]! });
|
||
expect(s.phase.kind).toBe('exchange');
|
||
expect(s.hands[1]).toEqual(h[1]!);
|
||
s = act(s, 'D', { type: 'exchange', give: gives[3]! });
|
||
expect(s.phase.kind).toBe('playing');
|
||
expect(s.hands.every((x) => x.length === 14)).toBe(true);
|
||
const got = gives[0]![1]!.cardId; // A → C (partner)
|
||
expect(s.hands[2]).toContain(got);
|
||
expect(view(s, 'C').my!.received.some((r) => r.cardId === got && r.from === 0)).toBe(true);
|
||
for (const p of ['A', 'B', 'D']) expect(JSON.stringify(view(s, p))).not.toContain(`"${got}"`);
|
||
expect(s.hands[s.current]).toContain(MJ);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- scoring
|
||
|
||
describe('점수 (§6)', () => {
|
||
test('예 1: 스몰 티츄 1등, 꼴찌 손패는 상대 팀, 딴 카드는 1등에게 → 170 : 30', () => {
|
||
// Seats: 0 지수(A팀), 1 민호(B), 2 서연(A), 3 하늘(B). Out 0, 1, 2; 하늘 keeps K·5 (15) and won a 10.
|
||
const s = make({ grandTichu: false });
|
||
rig(s, { hands: [[], [], [], C('j13 j5')], won: [C('s5 s10 s13 b13'), C('b5 t5 b10 DR PH j10'), C('t13 s14'), C('t10')] });
|
||
s.out = [0, 1, 2];
|
||
s.calls = ['tichu', 'none', 'none', 'none'];
|
||
const r = scoreRound(s, 'last', null);
|
||
expect(r.cardPoints).toEqual([70, 30]);
|
||
expect(r.total).toEqual([170, 30]);
|
||
expect(r.handover).toEqual({ hand: 15, won: 10 });
|
||
});
|
||
test('예 2: 그랜드 실패 + 원투 → 200 : −200', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('s3'), C('s6 s9'), C('s7'), C('s8 s10')], current: 0 });
|
||
s.calls = ['none', 'grand', 'none', 'none'];
|
||
s.out = [2];
|
||
s.hands[2] = [];
|
||
s = play(s, 'A', ['s3']);
|
||
expect(s.rounds.at(-1)!.kind).toBe('double');
|
||
expect(s.rounds.at(-1)!.total).toEqual([200, -200]);
|
||
});
|
||
test('예 3: 짝꿍이 1등이어도 선언한 본인이 아니면 실패(−100)', () => {
|
||
const s = make({ grandTichu: false });
|
||
rig(s, { hands: [[], [], [], C('s3')], won: [[], [], FULL_DECK.filter((c) => c !== 's3'), []] });
|
||
s.out = [2, 1, 0];
|
||
s.calls = ['tichu', 'none', 'none', 'none'];
|
||
const r = scoreRound(s, 'last', null);
|
||
expect(r.callPoints).toEqual([-100, 0]);
|
||
});
|
||
test('봉황만 딴 팀은 −25', () => {
|
||
const t = make({ grandTichu: false });
|
||
rig(t, { hands: [[], [], C('s3'), []], won: [[PH], FULL_DECK.filter((c) => c !== PH && c !== 's3'), [], []] });
|
||
t.out = [1, 3, 0];
|
||
expect(scoreRound(t, 'last', null).cardPoints).toEqual([-25, 125]);
|
||
});
|
||
});
|
||
|
||
describe('게임 끝 (§6)', () => {
|
||
test('한 팀 1000 이상이면 끝, 동점이면 한 라운드 더', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
s.out = [2];
|
||
s.scores = [900, 500];
|
||
s = play(s, 'A', ['s3']);
|
||
expect(s.phase.kind).toBe('finished');
|
||
expect(s.final!.ranking).toEqual([
|
||
['A', 'C'],
|
||
['B', 'D'],
|
||
]);
|
||
expect(s.final!.scoreText.A).toBe('1,100점');
|
||
let t = make({ grandTichu: false });
|
||
t = rig(t, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
t.out = [2];
|
||
t.scores = [800, 1000];
|
||
t = play(t, 'A', ['s3']);
|
||
expect(t.scores).toEqual([1000, 1000]);
|
||
expect(t.phase.kind).toBe('roundEnd');
|
||
for (const p of P4) t = act(t, p, { type: 'ready' });
|
||
expect(t.round).toBe(2);
|
||
});
|
||
test('둘 다 넘으면 높은 팀이 이겨요', () => {
|
||
let t = make({ grandTichu: false });
|
||
t = rig(t, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
t.out = [2];
|
||
t.scores = [1000, 1300];
|
||
t = play(t, 'A', ['s3']);
|
||
expect(t.final!.ranking[0]).toEqual(['B', 'D']);
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- modes
|
||
|
||
describe('다른 모드 (§5.9)', () => {
|
||
test('individual: 짝꿍 3가지 순환, 팀 점수가 두 사람 개인 점수에 같게', () => {
|
||
let s = make({ mode: 'individual', grandTichu: false });
|
||
const pairs: string[][] = [];
|
||
for (let r = 0; r < 4; r++) {
|
||
pairs.push([`${s.seats[0]!.owner}${s.seats[2]!.owner}`, `${s.seats[1]!.owner}${s.seats[3]!.owner}`]);
|
||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
s.out = [2];
|
||
const before = [...s.scores];
|
||
s = play(s, s.seats[0]!.owner, ['s3']);
|
||
const r1 = s.rounds.at(-1)!;
|
||
r1.teams.forEach((team, t) => {
|
||
for (const p of team) expect(s.scores[P4.indexOf(p)]! - before[P4.indexOf(p)]!).toBe(r1.total[t]!);
|
||
});
|
||
for (const p of P4) s = act(s, p, { type: 'ready' });
|
||
}
|
||
expect(pairs.slice(0, 3)).toEqual([
|
||
['AC', 'BD'],
|
||
['AB', 'CD'],
|
||
['AD', 'BC'],
|
||
]);
|
||
expect(pairs[3]).toEqual(pairs[0]);
|
||
});
|
||
|
||
test('threechu: 2장 교환(딜러↔더미 없음), 교환 뒤 더미 공개, 더미 소원 의무 없음, 딜러 순환, 정해진 판 수 뒤 끝', () => {
|
||
let s = make({ mode: 'threechu', grandTichu: false, threechuHands: 3 }, P3);
|
||
const dealer = s.players[s.dealer!]!;
|
||
expect(s.seats[0]!.owner).toBe(dealer);
|
||
expect(s.seats[2]).toEqual({ owner: dealer, dummy: true });
|
||
const opp = P3.filter((p) => p !== dealer);
|
||
expect(view(s, opp[0]!).seats[2]!.openHand).toBeNull();
|
||
expect(view(s, dealer).dummy!.hand).toHaveLength(14);
|
||
// Dealer exchanges for both seats; each gives to its two opponents only.
|
||
const giveFor = (seat: number) => [1, 3].map((d, i) => ({ to: (seat + d) % 4, cardId: s.hands[seat]![i]! }));
|
||
expect(reject(s, dealer, { type: 'exchange', give: [{ to: 2, cardId: s.hands[0]![0]! }, { to: 1, cardId: s.hands[0]![1]! }] })).toContain('한 사람에게');
|
||
s = act(s, dealer, { type: 'exchange', give: giveFor(0) });
|
||
s = act(s, dealer, { type: 'exchange', seat: 2, give: giveFor(2) });
|
||
for (const p of opp) s = act(s, p, { type: 'exchange', give: giveFor(s.seats.findIndex((x) => x.owner === p && !x.dummy)) });
|
||
expect(s.phase.kind).toBe('playing');
|
||
expect(view(s, opp[0]!).seats[2]!.openHand).toHaveLength(14);
|
||
// The dummy is free of the wish.
|
||
s = rig(s, { hands: [C('s3'), C('s4'), C('j8 s9'), C('s5')], current: 2, plays: [{ seat: 1, cards: ['s4'] }], wish: 8 });
|
||
expect(reject(s, dealer, { type: 'play', seat: 2, cardIds: ['s9'] })).toBeNull();
|
||
expect(reject(s, dealer, { type: 'pass', seat: 2 })).toBeNull();
|
||
// Dealer rotates and the game ends after 3 hands.
|
||
const dealers = [s.dealer];
|
||
for (let r = 0; r < 3; r++) {
|
||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
s.out = [2];
|
||
s = play(s, s.seats[0]!.owner, ['s3']);
|
||
if (s.phase.kind === 'finished') break;
|
||
for (const p of P3) s = act(s, p, { type: 'ready' });
|
||
dealers.push(s.dealer);
|
||
}
|
||
expect(new Set(dealers).size).toBe(3);
|
||
expect(s.phase.kind).toBe('finished');
|
||
expect(s.final!.ranking.flat().sort()).toEqual(P3);
|
||
});
|
||
|
||
test('tientsin: 10·10·9·9·9·9 배분, 6장 뒤 그랜드, 짝꿍 2명과 교환, 트리플 빅토리 300, 5등 딴 카드 → 1등', () => {
|
||
let s = make({ mode: 'tientsin' }, P6);
|
||
expect(s.hands.map((h) => h.length)).toEqual([6, 6, 6, 6, 6, 6]);
|
||
for (const p of P6) s = act(s, p, { type: 'grand', call: false });
|
||
expect(s.hands.map((h) => h.length).sort((a, b) => a - b)).toEqual([9, 9, 9, 9, 10, 10]);
|
||
const starter = s.dealer!;
|
||
const second = s.order[(s.order.indexOf(starter) + 1) % 6]!;
|
||
expect(s.hands[starter]).toHaveLength(10);
|
||
expect(s.hands[second]).toHaveLength(10);
|
||
expect(view(s, 'A').my!.exchangeTargets.map((t) => t.seat)).toEqual([2, 4]);
|
||
// Triple victory.
|
||
let t = make({ mode: 'tientsin', grandTichu: false }, P6);
|
||
t = rig(t, { hands: [C('s3'), C('s4'), [], C('s5'), [], C('s6')], current: 0 });
|
||
t.out = [2, 4];
|
||
t = play(t, 'A', ['s3']);
|
||
expect(t.rounds.at(-1)!).toMatchObject({ kind: 'triple', bonus: [300, 0], cardPoints: [0, 0] });
|
||
// Last one gives hand + tricks to the other team, the 5th's tricks go to the first.
|
||
const u = make({ mode: 'tientsin', grandTichu: false }, P6);
|
||
rig(u, { hands: [[], [], [], [], [], C('j5')], won: [[], ['j10'], [], [], ['s13'], ['t13']] });
|
||
u.out = [1, 0, 2, 3, 4];
|
||
const r = scoreRound(u, 'last', null);
|
||
// team1 (seats 1,3,5): seat1 10 + seat4's K (5th, team 0) → seat1 → +10 = 20; last seat5 (team1) gives 5 + 10 to team 0.
|
||
expect(r.cardPoints).toEqual([15, 20]);
|
||
});
|
||
|
||
test('party: 두 배 판, 점수 뒤집기 합 −100, 손패 돌리기 후 선언은 사람에게 남음, 같은 효과 연속 없음', () => {
|
||
let s = make({ party: true, grandTichu: false, targetScore: 1500 });
|
||
const effects = [s.effect];
|
||
for (let r = 0; r < 12; r++) {
|
||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
s.out = [2];
|
||
s = play(s, 'A', ['s3']);
|
||
if (s.phase.kind !== 'roundEnd') break;
|
||
for (const p of P4) s = act(s, p, { type: 'ready' });
|
||
effects.push(s.effect);
|
||
}
|
||
for (let i = 1; i < effects.length; i++) expect(effects[i]).not.toBe(effects[i - 1]);
|
||
const d = make({ party: true, grandTichu: false });
|
||
d.effect = 'double';
|
||
rig(d, { hands: [[], [], [], C('s3')], won: [FULL_DECK.filter((c) => c !== 's3'), [], [], []] });
|
||
d.out = [0, 1, 2];
|
||
expect(scoreRound(d, 'last', null).total).toEqual([200, 0]);
|
||
const n = make({ party: true, grandTichu: false });
|
||
n.effect = 'negative';
|
||
rig(n, { hands: [[], [], [], C('s3')], won: [FULL_DECK.filter((c) => c !== 's3'), [], [], []] });
|
||
n.out = [0, 1, 2];
|
||
const rn = scoreRound(n, 'last', null);
|
||
expect(rn.cardPoints[0]! + rn.cardPoints[1]!).toBe(-100);
|
||
// Rotate: hands move on after the exchange, calls stay.
|
||
let rot = make({ party: true, grandTichu: false });
|
||
rot.effect = 'rotate';
|
||
rot = act(rot, 'B', { type: 'tichu' });
|
||
const after = rot.hands.map((h) => [...h]);
|
||
const give = (seat: number) => [1, 2, 3].map((dd) => ({ to: (seat + dd) % 4, cardId: rot.hands[seat]![dd - 1]! }));
|
||
const gives = [0, 1, 2, 3].map(give);
|
||
for (let i = 0; i < 4; i++) rot = act(rot, P4[i]!, { type: 'exchange', give: gives[i]! });
|
||
expect(rot.calls[1]).toBe('tichu');
|
||
// seat 0's exchanged hand went to the next seat in turn order (right: 0 → 3)
|
||
const seat0 = after[0]!.filter((c) => !gives[0]!.some((g) => g.cardId === c));
|
||
for (const c of seat0) expect(rot.hands[3]).toContain(c);
|
||
expect(reject(rot, 'B', { type: 'tichu' })).toContain('이미');
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- automatic moves
|
||
|
||
describe('시간 초과 (§8.5)', () => {
|
||
test('선 = 가장 약한 싱글, 따라 내기 = 패스, 의무가 있으면 가장 약한 의무 조합', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('s9 j3 DR'), C('s4 s10'), C('s7'), C('j8 s12')], current: 0 });
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
expect(s.trick.plays[0]!.cards).toEqual(['j3']);
|
||
s = act(s, 'D', { type: 'timeout' });
|
||
expect(s.trick.passed).toEqual([3]);
|
||
let w = make({ grandTichu: false });
|
||
w = rig(w, { hands: [C('s3'), C('s4'), C('s7'), C('j8 s8 s12')], current: 3, plays: [{ seat: 0, cards: C('j5 s5') }], wish: 8 });
|
||
w = act(w, 'D', { type: 'timeout' });
|
||
expect(w.trick.plays.at(-1)!.cards).toEqual(['j8', 's8']);
|
||
});
|
||
test('교환 시간 초과: 상대에게 약한 낱장, 짝꿍에게 가장 센 숫자', () => {
|
||
let s = make({ grandTichu: false });
|
||
s.hands[0] = C('j2 s3 j5 j9 s9 j13 s14 DOG MJ PH DR b4 t7 b12');
|
||
s = act(s, 'A', { type: 'timeout' });
|
||
const g = (s.phase as { give: ({ to: number; card: string }[] | null)[] }).give[0]!;
|
||
expect(g.find((x) => x.to === 2)!.card).toBe('s14');
|
||
expect(g.find((x) => x.to === 1)!.card).toBe('j2');
|
||
expect(g.find((x) => x.to === 3)!.card).toBe('s3');
|
||
});
|
||
test('모든 상태에서 onTimeout이 합법', () => {
|
||
for (const mode of ['team', 'threechu', 'tientsin'] as const) {
|
||
const players = mode === 'threechu' ? P3 : mode === 'tientsin' ? P6 : P4;
|
||
let s = make({ mode, targetScore: 300, threechuHands: 3 }, players, 5);
|
||
for (let i = 0; i < 1500 && !tichu.result(s); i++) {
|
||
const who = tichu.timeoutPlayers!(s);
|
||
expect(who.length).toBeGreaterThan(0);
|
||
const p = who[i % who.length]!;
|
||
s = act(s, p, tichu.onTimeout(s, p));
|
||
}
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('거부되는 행동', () => {
|
||
test('차례가 아닌 play, 끝난 라운드의 행동은 거부되고 상태가 바뀌지 않음', () => {
|
||
let s = make({ grandTichu: false });
|
||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||
expect(reject(s, 'B', { type: 'play', cardIds: ['s6'] })).toBeTruthy();
|
||
s.out = [2];
|
||
const before = JSON.stringify(s);
|
||
expect(reject(s, 'B', { type: 'play', cardIds: ['s6'] })).toBeTruthy();
|
||
expect(JSON.stringify(s)).toBe(before);
|
||
s = play(s, 'A', ['s3']);
|
||
expect(s.phase.kind).toBe('roundEnd');
|
||
expect(reject(s, 'D', { type: 'play', cardIds: ['s7'] })).toBeTruthy();
|
||
expect(reject(s, 'D', { type: 'pass' })).toBeTruthy();
|
||
s = act(s, 'A', { type: 'ready' });
|
||
expect(reject(s, 'A', { type: 'ready' })).toBeTruthy();
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------- random play
|
||
|
||
/** Random play with fewer wild calls (a uniform pick calls grand tichu every other time and never ends). */
|
||
const tamed: AnyGameDefinition = {
|
||
...(tichu as AnyGameDefinition),
|
||
legalActions(s: TichuState, p: string) {
|
||
const all = tichu.legalActions(s, p);
|
||
const rare = (a: TichuAction) => (a.type === 'grand' && a.call) || a.type === 'tichu';
|
||
const keep = all.filter((a) => !rare(a) || s.seq % 9 === 0);
|
||
return keep.length ? keep : all;
|
||
},
|
||
};
|
||
|
||
const CONFIGS: [string, Partial<TichuOptions>, string[]][] = [
|
||
['team', { targetScore: 300 }, P4],
|
||
['individual', { mode: 'individual', targetScore: 300 }, P4],
|
||
['threechu', { mode: 'threechu', threechuHands: 3 }, P3],
|
||
['tientsin', { mode: 'tientsin', targetScore: 300 }, P6],
|
||
['variants', { targetScore: 300, wishRule: 'penalty', party: true, bombTiming: 'ownTurn', grandTichu: false, direction: 'left', trickHistory: 'all', turnSeconds: null, exchangeSeconds: null }, P4],
|
||
['party-left', { targetScore: 500, party: true, direction: 'left', bombWindowSeconds: 1 }, P4],
|
||
];
|
||
|
||
function invariants(s: TichuState, seen: { rounds: number }): void {
|
||
const all = allCards(s);
|
||
if (all.length !== 56 || new Set(all).size !== 56) throw new Error(`cards: ${all.length}`);
|
||
for (const rr of s.rounds.slice(seen.rounds)) {
|
||
if (rr.kind === 'last' && rr.cardPoints[0]! + rr.cardPoints[1]! !== (rr.effect === 'negative' ? -100 : 100)) throw new Error(`round points ${rr.cardPoints}`);
|
||
}
|
||
seen.rounds = s.rounds.length;
|
||
}
|
||
|
||
/** Random legal play without the per-step view checks (those run in the next test); every 100th step is leak-checked. */
|
||
function fastPlayout(players: string[], options: TichuOptions, seed: number, maxSteps = 8000) {
|
||
const rng = SeededRng.fromSeed(seedN(seed));
|
||
const chooser = SeededRng.fromSeed(seedN(seed + 7777));
|
||
let now = 1_700_000_000_000;
|
||
let s = tichu.setup({ players, options, rng, now });
|
||
const seen = { rounds: 0 };
|
||
const trace: string[] = [];
|
||
for (let step = 0; step < maxSteps; step++) {
|
||
invariants(s, seen);
|
||
if (step % 100 === 0) for (const p of players) checkNoLeak(tichu as AnyGameDefinition, s, p, players);
|
||
if (tichu.result(s)) return { finished: true, s, trace: trace.join('|'), steps: step };
|
||
const actives = tichu.activePlayers(s);
|
||
const actor = actives[chooser.int(actives.length)]!;
|
||
const legal = (tamed.legalActions!(s, actor) as TichuAction[]) ?? [];
|
||
const a = legal.length ? legal[chooser.int(legal.length)]! : tichu.onTimeout(s, actor);
|
||
const v = tichu.validate(s, actor, a);
|
||
if (!v.ok) throw new Error(`seed ${seed}: rejected ${JSON.stringify(a)}: ${v.reason}`);
|
||
// Now and then the clock runs out instead (timeouts are legal everywhere).
|
||
const act2 = chooser.int(20) === 0 && tichu.validate(s, actor, { type: 'timeout' }).ok ? ({ type: 'timeout' } as TichuAction) : a;
|
||
now += 500 + chooser.int(1500);
|
||
s = tichu.apply(s, actor, act2, { rng, now }).state;
|
||
trace.push(JSON.stringify(act2));
|
||
}
|
||
return { finished: false, s, trace: trace.join('|'), steps: maxSteps };
|
||
}
|
||
|
||
const SEEDS = playoutSeeds(1000);
|
||
|
||
describe(`무작위 대국 (§10, ${SEEDS}판)`, () => {
|
||
test('끝까지, 카드 56장 보존, 라운드 점수 합 100(뒤집기면 −100), 결과에 모두, 직렬화 왕복, 결정적', () => {
|
||
let finished = 0;
|
||
for (let i = 1; i <= SEEDS; i++) {
|
||
const [, opts, players] = CONFIGS[i % CONFIGS.length]!;
|
||
const options = tichu.optionsSchema.parse(opts);
|
||
const a = fastPlayout(players, options, i);
|
||
if (a.finished) {
|
||
finished++;
|
||
expect(tichu.result(a.s)!.ranking.flat().sort()).toEqual([...players].sort());
|
||
}
|
||
expect(JSON.parse(JSON.stringify(a.s))).toEqual(a.s);
|
||
if (i % 50 === 0) {
|
||
const b = fastPlayout(players, options, i);
|
||
expect(b.trace).toBe(a.trace);
|
||
expect(JSON.stringify(b.s)).toBe(JSON.stringify(a.s));
|
||
}
|
||
}
|
||
expect(finished).toBeGreaterThanOrEqual(Math.floor(SEEDS * 0.9));
|
||
}, 120_000);
|
||
|
||
test.each(CONFIGS)('%s: 엔진 무작위 대국(매 단계 정보 유출·왕복 검사)', (_name, opts, players) => {
|
||
const options = tichu.optionsSchema.parse(opts);
|
||
const seen = { rounds: 0 };
|
||
// Six viewers make the per-step checks slow: a shorter stretch there.
|
||
const maxSteps = players.length === 6 ? 500 : 2500;
|
||
const r = randomPlayout(tamed, { players, options, seed: seedN(900 + players.length), maxSteps, maxApplyMs: 30, invariant: (st) => invariants(st as TichuState, seen) });
|
||
expect(r.steps).toBeGreaterThan(50);
|
||
}, 60_000);
|
||
|
||
test('결정성: 같은 시드·같은 행동이면 같은 결과', () => {
|
||
const run = () => randomPlayout(tamed, { players: P4, options: tichu.optionsSchema.parse({ targetScore: 300 }), seed: seedN(42), maxSteps: 3000 }).finalState;
|
||
expect(JSON.stringify(run())).toBe(JSON.stringify(run()));
|
||
});
|
||
|
||
test('관전자와 다른 사람에게 남의 손패·남은 6장·더미(교환 전)가 보이지 않아요', () => {
|
||
let s = make({ mode: 'threechu' }, P3);
|
||
for (const p of P3) checkNoLeak(tichu as AnyGameDefinition, s, p, P3);
|
||
const dealer = s.players[s.dealer!]!;
|
||
const other = P3.find((p) => p !== dealer)!;
|
||
const json = JSON.stringify(view(s, other));
|
||
for (const c of s.hands[2]!) expect(json).not.toContain(`"${c}"`);
|
||
for (const c of s.pending.flat()) expect(JSON.stringify(view(s, dealer))).not.toContain(`"${c}"`);
|
||
s = act(s, other, { type: 'grand', call: false });
|
||
expect(view(s, other).seats.find((x) => x.owner === dealer && !x.dummy)!.done).toBe(true);
|
||
});
|
||
});
|
||
|
||
describe('legalActions (§8.7)', () => {
|
||
test('조합 대표 하나씩, 폭탄은 모두, 소원 포함/미포함 둘 다', () => {
|
||
const hand = C('j8 s8 b8 t8 j9 s9 PH j3 j4 j5 j6 j7');
|
||
const found = findCombos(hand, null, 8);
|
||
const bombs = found.filter((f) => f.combo.type === 'bomb4' || f.combo.type === 'bombSF');
|
||
expect(bombs.map((b) => b.cards.join(' ')).sort()).toEqual(['j3 j4 j5 j6 j7', 'j3 j4 j5 j6 j7 j8', 'j4 j5 j6 j7 j8', 'j8 s8 b8 t8', 'j3 j4 j5 j6 j7 j8 j9', 'j4 j5 j6 j7 j8 j9', 'j5 j6 j7 j8 j9'].sort());
|
||
const st8 = found.filter((f) => f.combo.type === 'straight' && f.combo.length === 6 && f.combo.value === 9);
|
||
expect(st8.some((f) => f.cards.some((c) => c.endsWith('8') && c !== PH))).toBe(true);
|
||
expect(st8.some((f) => f.cards.every((c) => !/^.8$/.test(c)))).toBe(true);
|
||
});
|
||
});
|