새 게임 티츄: 4인 2:2 팀전(원작, 1,000점) 기본 + 4인 개인전·3인(더미)·6인 3:3 변형, 그랜드/스몰 티츄, 끼어드는 폭탄, 참새 소원, 파티 모드
- 엔진 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>
This commit is contained in:
@@ -38,6 +38,7 @@ import { unoBot } from '../uno/bot';
|
||||
import { liarBot } from '../liar/bot';
|
||||
import { magicalAthleteBot } from '../magical-athlete/bot';
|
||||
import { blackjackBot } from '../blackjack/bot';
|
||||
import { tichuBot } from '../tichu/bot';
|
||||
|
||||
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
@@ -73,6 +74,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
uno: unoBot,
|
||||
'magical-athlete': magicalAthleteBot,
|
||||
blackjack: blackjackBot,
|
||||
tichu: tichuBot,
|
||||
};
|
||||
|
||||
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */
|
||||
|
||||
@@ -33,6 +33,7 @@ import { uno } from './uno';
|
||||
import { liar } from './liar';
|
||||
import { magicalAthlete } from './magical-athlete';
|
||||
import { blackjack } from './blackjack';
|
||||
import { tichu } from './tichu';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -69,4 +70,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[liar.id]: liar,
|
||||
[magicalAthlete.id]: magicalAthlete,
|
||||
[blackjack.id]: blackjack,
|
||||
[tichu.id]: tichu,
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@ import { GAMES } from './index';
|
||||
|
||||
/** Games without a score (win/lose only, or survival) leave `scoreText` out. */
|
||||
const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker', 'clue', 'connect-four']);
|
||||
/** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). */
|
||||
const SCORED_OPTIONS: Record<string, object> = { 'one-card': { mode: 'uno-style' } };
|
||||
/** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). 티츄: a 300-point game so random play ends in time. */
|
||||
const SCORED_OPTIONS: Record<string, object> = { 'one-card': { mode: 'uno-style' }, tichu: { targetScore: 300 } };
|
||||
|
||||
describe('final score text', () => {
|
||||
for (const def of Object.values(GAMES)) {
|
||||
|
||||
110
packages/games/src/tichu/bot.test.ts
Normal file
110
packages/games/src/tichu/bot.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
/** 티츄 computer player (docs/games/tichu.md §8.7). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { decideBotAction } from '../bots';
|
||||
import { tichuBot, handCost } from './bot';
|
||||
import { classify, tichu, type TichuAction, type TichuOptions, type TichuState, type TichuView } from './index';
|
||||
|
||||
const isBot = (p: string) => p.startsWith('bot:');
|
||||
const bots = (n: number) => Array.from({ length: n }, (_, i) => `bot:${i + 1}:x`);
|
||||
const C = (ids: string) => ids.split(' ');
|
||||
|
||||
function make(opts: Partial<TichuOptions>, players: string[], seed = 1): TichuState {
|
||||
return tichu.setup({ players, options: tichu.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
}
|
||||
function rigPlay(s: TichuState, hands: string[][], current: number, plays: { seat: number; cards: string[] }[] = [], wish: number | null = null): TichuState {
|
||||
s.hands = hands;
|
||||
s.pending = s.seats.map(() => []);
|
||||
s.won = s.seats.map(() => []);
|
||||
s.phase = { kind: 'playing' };
|
||||
s.out = [];
|
||||
s.played = s.seats.map(() => true);
|
||||
s.calls = s.seats.map(() => 'none');
|
||||
s.wish = wish;
|
||||
s.current = current;
|
||||
s.trick = { leader: plays[0]?.seat ?? current, plays: [], passed: [], closingAt: null, waived: [] };
|
||||
for (const p of plays) s.trick.plays.push({ seat: p.seat, cards: p.cards, combo: classify(p.cards, s.trick.plays.at(-1)?.combo ?? null)!, outOfTurn: false });
|
||||
return s;
|
||||
}
|
||||
const decide = (s: TichuState, p: string, level = 60): TichuAction => {
|
||||
const view = tichu.view(s, p) as TichuView;
|
||||
return tichuBot({ me: p, view, legal: tichu.legalActions(s, p), random: () => 0.5, level });
|
||||
};
|
||||
|
||||
describe('컴퓨터끼리 끝까지', () => {
|
||||
const cases: [string, Partial<TichuOptions>, number][] = [
|
||||
['team', {}, 4],
|
||||
['individual', { mode: 'individual', targetScore: 500 }, 4],
|
||||
['threechu', { mode: 'threechu', threechuHands: 3 }, 3],
|
||||
['tientsin', { mode: 'tientsin', targetScore: 500 }, 6],
|
||||
['penalty + party', { wishRule: 'penalty', party: true, targetScore: 500 }, 4],
|
||||
];
|
||||
test.each(cases)('%s', (_n, opts, n) => {
|
||||
for (const level of [1, 60]) {
|
||||
const r = botPlayout(tichu, { players: bots(n), options: tichu.optionsSchema.parse(opts), seed: seedN(level + n), isBot, maxSteps: 30_000, level });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
expect(r.maxBotMs).toBeLessThan(250);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('penalty 모드에서도 컴퓨터는 소원을 지켜요(위반 라운드 없음)', () => {
|
||||
let penalties = 0;
|
||||
for (let k = 1; k <= 4; k++) {
|
||||
const players = bots(4);
|
||||
const options = tichu.optionsSchema.parse({ wishRule: 'penalty', targetScore: 500 });
|
||||
const rng = SeededRng.fromSeed(seedN(k));
|
||||
let s = tichu.setup({ players, options, rng, now: 0 });
|
||||
let now = 0;
|
||||
for (let i = 0; i < 20_000 && !tichu.result(s); i++) {
|
||||
const who = tichu.activePlayers(s)[0]!;
|
||||
now += 700;
|
||||
const a = (decideBotAction(tichu, s, who, { now, random: () => 0.3, level: 60 }) as TichuAction | null) ?? tichu.onTimeout(s, who);
|
||||
s = tichu.apply(s, who, a, { rng, now }).state;
|
||||
}
|
||||
penalties += s.rounds.filter((r) => r.kind === 'penalty').length;
|
||||
}
|
||||
expect(penalties).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('판단', () => {
|
||||
test('짝꿍이 맨 위면 대개 패스, 상대가 맨 위면 조합을 깨지 않고 이김', () => {
|
||||
const P = ['A', 'B', 'C', 'D'];
|
||||
let s = make({ grandTichu: false }, P);
|
||||
// D (seat 3) to play; partner B (seat 1) holds the trick with a 9.
|
||||
s = rigPlay(s, [C('s2 s3'), C('j4 s4'), C('j6 j7'), C('j10 b11 t3 t4 t5')], 3, [{ seat: 1, cards: ['j9'] }]);
|
||||
expect(decide(s, 'D').type).toBe('pass');
|
||||
// The opponent (A, seat 0) holds it: beat with the loose 10 or J, not by breaking anything.
|
||||
s = rigPlay(s, [C('s2 s3'), C('j4 s4'), C('j6 j7'), C('j10 b11 t3 t4 t5')], 3, [{ seat: 0, cards: ['j9'] }]);
|
||||
const a = decide(s, 'D');
|
||||
expect(a.type).toBe('play');
|
||||
expect((a as { cardIds: string[] }).cardIds.length).toBe(1);
|
||||
});
|
||||
|
||||
test('선이면 가장 약한 조합부터(긴 조합 우선)', () => {
|
||||
const P = ['A', 'B', 'C', 'D'];
|
||||
let s = make({ grandTichu: false }, P);
|
||||
s = rigPlay(s, [C('j2 s3 b4 t5 j6 s13 b13 j14'), C('j4 s4'), C('j6 j7'), C('j10 b11')], 0);
|
||||
const a = decide(s, 'A') as { type: string; cardIds: string[] };
|
||||
expect(a.type).toBe('play');
|
||||
expect(a.cardIds).toEqual(C('j2 s3 b4 t5 j6'));
|
||||
});
|
||||
|
||||
test('손패 나누기: 스트레이트·연속 페어·풀하우스를 한 번으로 셈', () => {
|
||||
expect(handCost(C('j2 s3 b4 t5 j6'))).toBe(1);
|
||||
expect(handCost(C('j5 s5 j6 s6 j7 s7'))).toBe(1);
|
||||
expect(handCost(C('j9 s9 b9 j3 s3'))).toBe(1);
|
||||
expect(handCost(C('j2 s9 b13'))).toBe(3);
|
||||
});
|
||||
|
||||
test('센 8장이면 그랜드 티츄, 약하면 안 함', () => {
|
||||
const P = ['A', 'B', 'C', 'D'];
|
||||
const s = make({}, P);
|
||||
s.hands[0] = C('DR PH j14 s14 b14 t13 j13 s12');
|
||||
expect(decide(s, 'A')).toEqual({ type: 'grand', call: true });
|
||||
s.hands[0] = C('j2 s3 b4 t6 j7 s8 b9 t11');
|
||||
expect(decide(s, 'A')).toEqual({ type: 'grand', call: false });
|
||||
});
|
||||
});
|
||||
267
packages/games/src/tichu/bot.ts
Normal file
267
packages/games/src/tichu/bot.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 티츄 computer player (docs/games/tichu.md §8.7). Uses only its own view and the legal actions: it splits its hand
|
||||
* into as few combinations as it can (rank counts, straights, pair runs, full houses, the phoenix as a joker), leads
|
||||
* the weakest part of that plan, beats opponents without breaking it, leaves partners' tricks alone, keeps bombs and
|
||||
* the dragon for opponents close to going out, and calls tichu only with enough high cards for the weak ones.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { humanBest, pick } from '../bots/policy';
|
||||
import {
|
||||
DOG,
|
||||
DR,
|
||||
MJ,
|
||||
PH,
|
||||
cardPoints,
|
||||
classify,
|
||||
includesWish,
|
||||
isBomb,
|
||||
isNumber,
|
||||
mustFulfillWish,
|
||||
rankOf,
|
||||
type Combo,
|
||||
type MySeatView,
|
||||
type PlayAction,
|
||||
type TichuAction,
|
||||
type TichuView,
|
||||
} from './types';
|
||||
|
||||
const SCALE = { small: 4, critical: 900 };
|
||||
|
||||
function counts(hand: readonly string[]): number[] {
|
||||
const c = Array.from({ length: 15 }, () => 0);
|
||||
for (const id of hand) if (isNumber(id) || id === MJ) c[rankOf(id)]!++;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Plays needed for these rank counts without straights (pairs, runs of pairs, triples, full houses, bombs). */
|
||||
function groupCost(c: number[], ph: boolean, extra: number): number {
|
||||
let singles = c[1]!;
|
||||
let pairs = 0;
|
||||
let triples = 0;
|
||||
let bombs = 0;
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const k = c[r]!;
|
||||
if (k === 1) singles++;
|
||||
else if (k === 2) pairs++;
|
||||
else if (k === 3) triples++;
|
||||
else if (k === 4) bombs++;
|
||||
}
|
||||
// Runs of consecutive pairs play as one.
|
||||
let run = 0;
|
||||
for (let r = 2; r <= 15; r++) {
|
||||
if (r <= 14 && c[r] === 2) run++;
|
||||
else {
|
||||
if (run >= 2) pairs -= run - 1;
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
const fh = Math.min(triples, pairs);
|
||||
let total = singles + pairs + triples + bombs - fh + extra;
|
||||
if (ph && singles > 0) total -= 1; // the phoenix pairs a loose card
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Fewest plays to empty the hand (one straight considered on top of the groups). */
|
||||
export function handCost(hand: readonly string[]): number {
|
||||
const c = counts(hand);
|
||||
const ph = hand.includes(PH);
|
||||
const extra = (hand.includes(DR) ? 1 : 0) + (hand.includes(DOG) ? 0.5 : 0) + (ph && !c.some((k, r) => r > 0 && k === 1) ? 1 : 0);
|
||||
let best = groupCost(c, ph, extra);
|
||||
for (let lo = 1; lo <= 10; lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
let gaps = 0;
|
||||
for (let r = lo; r <= hi; r++) if (c[r] === 0) gaps++;
|
||||
if (gaps > (ph ? 1 : 0)) break;
|
||||
const d = [...c];
|
||||
for (let r = lo; r <= hi; r++) if (d[r]! > 0) d[r]!--;
|
||||
const usesPh = gaps === 1;
|
||||
best = Math.min(best, 1 + groupCost(d, ph && !usesPh, extra - (usesPh && extra > 0 && !c.some((k, r) => r > 0 && k === 1) ? 1 : 0)));
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** High cards that win the lead back: dragon, aces, bombs, the phoenix (half). */
|
||||
function controls(hand: readonly string[]): number {
|
||||
const c = counts(hand);
|
||||
let n = 0;
|
||||
if (hand.includes(DR)) n += 1;
|
||||
if (hand.includes(PH)) n += 0.5;
|
||||
if (c[14]! > 0) n += 1;
|
||||
if (c[13]! >= 2) n += 0.5;
|
||||
for (let r = 2; r <= 14; r++) if (c[r] === 4) n += 1.5;
|
||||
return n;
|
||||
}
|
||||
|
||||
function grandScore(hand: readonly string[]): number {
|
||||
const c = counts(hand);
|
||||
let v = 0;
|
||||
if (hand.includes(DR)) v += 3;
|
||||
if (hand.includes(PH)) v += 3;
|
||||
v += c[14]! * 2 + c[13]!;
|
||||
for (let r = 2; r <= 14; r++) if (c[r] === 4) v += 4;
|
||||
return v;
|
||||
}
|
||||
|
||||
const without = (hand: readonly string[], cards: readonly string[]) => hand.filter((c) => !cards.includes(c));
|
||||
|
||||
export const tichuBot: BotStrategy<TichuView, TichuAction> = ({ view, legal, random, level }) => {
|
||||
const of = <T extends TichuAction['type']>(t: T) => legal.filter((a): a is Extract<TichuAction, { type: T }> => a.type === t);
|
||||
const lvl = level ?? 60;
|
||||
const sloppy = (1 - Math.min(lvl, 60) / 60) * 2; // 0 (best) .. ~2 (level 1)
|
||||
const my = view.my;
|
||||
const seatOf = (s: number) => view.seats[s]!;
|
||||
const myTeam = my ? seatOf(my.seat).team : 0;
|
||||
const partnerSeats = view.seats.filter((x) => x.team === myTeam && x.seat !== my?.seat).map((x) => x.seat);
|
||||
const partnerCalled = partnerSeats.some((x) => seatOf(x).call !== 'none');
|
||||
|
||||
if (of('ready').length) return of('ready')[0]!;
|
||||
|
||||
// Grand tichu on the first 8 cards.
|
||||
// (Calls are built here: `legal` lists them only now and then.)
|
||||
const grands = of('grand');
|
||||
if (grands.length) {
|
||||
const need = 9 - (random() < sloppy * 0.2 ? 2 : 0);
|
||||
if (my?.canGrand && !partnerCalled && grandScore(my.hand) >= need) return { type: 'grand', call: true };
|
||||
return grands.find((a) => !a.call) ?? grands[0]!;
|
||||
}
|
||||
|
||||
// Dragon gift: an opponent who did not call, with the most cards.
|
||||
const gifts = of('dragonTo');
|
||||
if (gifts.length) {
|
||||
const score = (a: (typeof gifts)[number]) => {
|
||||
const x = seatOf(a.to);
|
||||
return x.cards + (x.call === 'none' ? 20 : 0) + (x.place === null ? 10 : 0);
|
||||
};
|
||||
return [...gifts].sort((a, b) => score(b) - score(a))[0]!;
|
||||
}
|
||||
|
||||
// Exchange: build my own (partner gets a high card, opponents loose low cards and the dog).
|
||||
const exchanges = of('exchange');
|
||||
if (exchanges.length) {
|
||||
const target = exchanges[0]!;
|
||||
const hand: MySeatView | null = target.seat !== undefined && view.dummy?.seat === target.seat ? view.dummy : my;
|
||||
if (hand) {
|
||||
const built = buildExchange(view, hand, partnerCalled);
|
||||
if (built) return { type: 'exchange', ...(target.seat !== undefined ? { seat: target.seat } : {}), give: built };
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
// Small tichu: before my first card, with enough control for the weak combinations.
|
||||
if (my?.canTichu && view.phase === 'playing' && !partnerCalled && view.seats.every((x) => x.place === null)) {
|
||||
const cost = handCost(my.hand);
|
||||
const ctl = controls(my.hand);
|
||||
const jitter = (random() - 0.5) * sloppy * 2;
|
||||
if (ctl + jitter >= cost - ctl - 1) return { type: 'tichu', ...(view.dummy ? { seat: my.seat } : {}) };
|
||||
}
|
||||
|
||||
// Collecting (everyone passed): bomb only an opponent's valuable trick or a caller about to go out.
|
||||
if (view.trick?.closingAt !== null && view.trick?.closingAt !== undefined) {
|
||||
const bombs = of('play');
|
||||
const top = view.trick.plays[view.trick.plays.length - 1];
|
||||
if (bombs.length && top && seatOf(top.seat).team !== myTeam) {
|
||||
const pts = cardPoints(view.trick.plays.flatMap((p) => p.cards));
|
||||
const danger = view.seats.some((x) => x.team !== myTeam && x.call !== 'none' && x.cards > 0 && x.cards <= 3);
|
||||
if (pts >= 25 || danger) return bombs[0]!;
|
||||
}
|
||||
return of('noBomb')[0] ?? legal[0]!;
|
||||
}
|
||||
|
||||
// Which hand am I playing (the threechu dealer also plays the dummy)?
|
||||
const forDummy = !!view.dummy && view.current === view.dummy.seat;
|
||||
const mineNow = (a: { seat?: number }) => (forDummy ? a.seat === view.dummy!.seat : a.seat === undefined || a.seat === my?.seat);
|
||||
const plays = of('play').filter(mineNow);
|
||||
const passes = of('pass').filter(mineNow);
|
||||
if (!plays.length) return passes[0] ?? pick(legal, random);
|
||||
const me: MySeatView | null = forDummy ? view.dummy : my;
|
||||
if (!me) return pick(plays, random);
|
||||
const hand = me.hand;
|
||||
const top = view.trick?.plays[view.trick.plays.length - 1] ?? null;
|
||||
const leading = !top;
|
||||
const topCombo: Combo | null = top?.combo ?? null;
|
||||
const topIsPartner = !!top && seatOf(top.seat).team === myTeam;
|
||||
const oppDanger = view.seats.some((x) => x.team !== myTeam && x.cards > 0 && x.cards <= (x.call !== 'none' ? 4 : 2));
|
||||
// wishRule = penalty: the screen does not stop me, so keep the duty myself (the dummy is free).
|
||||
const duty = !me.dummy && view.wish !== null && mustFulfillWish(hand, topCombo, view.wish, leading) ? view.wish : null;
|
||||
let options: TichuAction[] = duty !== null ? plays.filter((a) => includesWish(a.cardIds, duty)) : [...plays, ...passes];
|
||||
if (!options.length) options = [...plays, ...passes];
|
||||
const baseCost = handCost(hand);
|
||||
const missingHigh = [14, 13, 12, 11, 10].find((r) => !hand.some((c) => rankOf(c) === r)) ?? null;
|
||||
|
||||
const score = (a: TichuAction): number => {
|
||||
if (a.type === 'pass') {
|
||||
let v = -baseCost * 10 - 3;
|
||||
if (topIsPartner) v += 25;
|
||||
if (oppDanger && !topIsPartner) v -= 15;
|
||||
return v;
|
||||
}
|
||||
if (a.type !== 'play') return -1e6;
|
||||
const cards = a.cardIds;
|
||||
const rest = without(hand, cards);
|
||||
if (rest.length === 0) return 1000;
|
||||
const combo = classify(cards, topCombo)!;
|
||||
let v = -handCost(rest) * 10;
|
||||
const urgent = oppDanger && !topIsPartner;
|
||||
if (isBomb(combo)) v -= urgent ? 2 : leading ? 30 : 40;
|
||||
if (cards.includes(DR)) v -= urgent ? 0 : 14;
|
||||
if (cards.length === 1 && cards[0] === PH) v -= urgent ? 2 : 10;
|
||||
else if (cards.includes(PH)) v -= 4;
|
||||
if (cards.includes(DOG)) {
|
||||
const partnerLow = partnerSeats.some((x) => seatOf(x).cards > 0 && (seatOf(x).call !== 'none' || seatOf(x).cards <= 3));
|
||||
v += partnerLow ? 30 : -6;
|
||||
}
|
||||
// Weak first; when leading prefer shedding many cards at once.
|
||||
v -= Math.min(combo.value, 20) * (leading ? 0.6 : 0.4);
|
||||
if (leading) v += cards.length * 0.8;
|
||||
if (topIsPartner) v -= 30;
|
||||
// The wish: call a high rank I don't hold (not when my partner called: it could break their bomb).
|
||||
if (a.wish !== undefined) v += a.wish === (partnerCalled ? null : missingHigh) ? 0.5 : 0;
|
||||
// Pick up points.
|
||||
if (!leading && top) v += cardPoints(view.trick!.plays.flatMap((p) => p.cards)) * 0.15;
|
||||
return v;
|
||||
};
|
||||
const choice = humanBest(options, score, random, lvl, SCALE);
|
||||
return choice as TichuAction;
|
||||
};
|
||||
|
||||
/** Exchange plan: partner the best (dragon/phoenix/ace if they called), opponents the dog and loose low cards. */
|
||||
function buildExchange(view: TichuView, me: MySeatView, partnerCalled: boolean): { to: number; cardId: string }[] | null {
|
||||
const targets = me.exchangeTargets;
|
||||
if (!targets.length) return null;
|
||||
const myTeam = view.seats[me.seat]!.team;
|
||||
const hand = [...me.hand];
|
||||
const c = counts(hand);
|
||||
const used = new Set<string>();
|
||||
const take = (pred: (id: string) => boolean, order: string[]) => {
|
||||
const id = order.find((x) => !used.has(x) && pred(x));
|
||||
if (id) used.add(id);
|
||||
return id;
|
||||
};
|
||||
const asc = hand.filter(isNumber).sort((a, b) => rankOf(a) - rankOf(b));
|
||||
const desc = [...asc].reverse();
|
||||
const loose = (id: string) => c[rankOf(id)] === 1 && ![5, 10, 13].includes(rankOf(id));
|
||||
const out: { to: number; cardId: string }[] = [];
|
||||
const partnersFirst = [...targets].sort((a, b) => Number(view.seats[b.seat]!.team === myTeam) - Number(view.seats[a.seat]!.team === myTeam));
|
||||
let dogGiven = false;
|
||||
for (const t of partnersFirst) {
|
||||
const partner = view.seats[t.seat]!.team === myTeam;
|
||||
let id: string | undefined;
|
||||
if (partner) {
|
||||
if (partnerCalled) id = take((x) => x === DR || x === PH, [DR, PH]) ?? take((x) => rankOf(x) === 14, desc);
|
||||
id ??= take((x) => c[rankOf(x)] === 1, desc) ?? take(() => true, desc);
|
||||
} else {
|
||||
if (!dogGiven && hand.includes(DOG)) {
|
||||
id = take((x) => x === DOG, [DOG]);
|
||||
dogGiven = !!id;
|
||||
}
|
||||
id ??= take(loose, asc) ?? take((x) => ![5, 10, 13].includes(rankOf(x)), asc) ?? take(() => true, asc);
|
||||
}
|
||||
id ??= take(() => true, hand);
|
||||
if (!id) return null;
|
||||
out.push({ to: t.seat, cardId: id });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type { PlayAction };
|
||||
417
packages/games/src/tichu/combo.ts
Normal file
417
packages/games/src/tichu/combo.ts
Normal file
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* 티츄 combinations (docs/games/tichu.md §5.1~§5.5, §8.1): card ids, classify / beats / wish duty, card points and
|
||||
* the combination finder. Pure and dependency-free so the screen can import it for the live "풀하우스(9) · 낼 수 있어요"
|
||||
* label (`@bg/games/tichu/combo`).
|
||||
*
|
||||
* Card ids: number cards `<suit><rank>` (suit j 옥 · s 칼 · b 탑 · t 별, rank 2..14; 탑 is `b`, not `p`, so ids never equal test player ids like `p2`), specials MJ 참새 · DOG 개 · PH 봉황 · DR 용.
|
||||
*/
|
||||
|
||||
export type Rank = number;
|
||||
export type ComboType = 'single' | 'pair' | 'pairSeq' | 'triple' | 'fullHouse' | 'straight' | 'bomb4' | 'bombSF' | 'dog';
|
||||
|
||||
export interface Combo {
|
||||
type: ComboType;
|
||||
/** Number of cards. */
|
||||
length: number;
|
||||
/** Strength (§5.4): single phoenix x.5, dragon 100; otherwise the compared rank. */
|
||||
value: number;
|
||||
/** Rank the phoenix stands for (null for a single phoenix or without one). */
|
||||
phoenixAs: Rank | null;
|
||||
}
|
||||
|
||||
export const MJ = 'MJ';
|
||||
export const DOG = 'DOG';
|
||||
export const PH = 'PH';
|
||||
export const DR = 'DR';
|
||||
export const SPECIALS = [MJ, DOG, PH, DR] as const;
|
||||
export const SUITS = ['j', 's', 'b', 't'] as const;
|
||||
export type Suit = (typeof SUITS)[number];
|
||||
export const SUIT_KO: Record<Suit, string> = { j: '옥', s: '칼', b: '탑', t: '별' };
|
||||
export const DRAGON_VALUE = 100;
|
||||
|
||||
/** 56 cards in a fixed order: suits j, s, b, t × ranks 2..14, then MJ, DOG, PH, DR. */
|
||||
export const FULL_DECK: readonly string[] = [...SUITS.flatMap((s) => Array.from({ length: 13 }, (_, i) => `${s}${i + 2}`)), MJ, DOG, PH, DR];
|
||||
|
||||
export const isSpecial = (id: string): boolean => id === MJ || id === DOG || id === PH || id === DR;
|
||||
/** A real number card (2..A, with a suit). */
|
||||
export const isNumber = (id: string): boolean => !isSpecial(id);
|
||||
export const suitOf = (id: string): Suit | null => (isNumber(id) ? (id[0] as Suit) : null);
|
||||
/** 1 for the mahjong, 2..14 for number cards, 0 for the others. */
|
||||
export const rankOf = (id: string): number => (id === MJ ? 1 : isNumber(id) ? Number(id.slice(1)) : 0);
|
||||
|
||||
const SUIT_IDX: Record<string, number> = { j: 0, s: 1, b: 2, t: 3 };
|
||||
/** Sort key: 개, 참새, 2..A (suit order j s b t), 봉황, 용. */
|
||||
export function cardKey(id: string): number {
|
||||
if (id === DOG) return 0;
|
||||
if (id === MJ) return 1;
|
||||
if (id === PH) return 1000;
|
||||
if (id === DR) return 1001;
|
||||
return rankOf(id) * 10 + (SUIT_IDX[id[0]!] ?? 0);
|
||||
}
|
||||
export const sortCards = (ids: readonly string[]): string[] => [...ids].sort((a, b) => cardKey(a) - cardKey(b));
|
||||
|
||||
export const rankName = (r: number): string => (r === 1 ? '1' : r === 11 ? 'J' : r === 12 ? 'Q' : r === 13 ? 'K' : r === 14 ? 'A' : String(r));
|
||||
export function cardName(id: string): string {
|
||||
if (id === MJ) return '참새';
|
||||
if (id === DOG) return '개';
|
||||
if (id === PH) return '봉황';
|
||||
if (id === DR) return '용';
|
||||
return `${SUIT_KO[id[0] as Suit]} ${rankName(rankOf(id))}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- points
|
||||
|
||||
/** Card points (§3): 5 → 5, 10·K → 10, 용 +25, 봉황 −25. The party effect `negative` flips every sign (§7). */
|
||||
export function cardPoints(cards: readonly string[], effect: string | null = null): number {
|
||||
let p = 0;
|
||||
for (const c of cards) {
|
||||
if (c === DR) p += 25;
|
||||
else if (c === PH) p -= 25;
|
||||
else if (isNumber(c)) {
|
||||
const r = rankOf(c);
|
||||
if (r === 5) p += 5;
|
||||
else if (r === 10 || r === 13) p += 10;
|
||||
}
|
||||
}
|
||||
return effect === 'negative' ? 0 - p : p;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- classify
|
||||
|
||||
interface Item {
|
||||
rank: number;
|
||||
suit: string | null;
|
||||
}
|
||||
|
||||
const isBombType = (t: ComboType) => t === 'bomb4' || t === 'bombSF';
|
||||
export const isBomb = (c: Combo | null | undefined): boolean => !!c && isBombType(c.type);
|
||||
|
||||
/** Combination of plain items (no phoenix, no dog/dragon); a virtual phoenix card has `suit: null`. */
|
||||
function classifyPlain(items: Item[]): Omit<Combo, 'phoenixAs'> | null {
|
||||
const n = items.length;
|
||||
if (n === 0) return null;
|
||||
const ranks = items.map((i) => i.rank).sort((a, b) => a - b);
|
||||
const counts = new Map<number, number>();
|
||||
for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);
|
||||
const distinct = [...counts.keys()].sort((a, b) => a - b);
|
||||
const lo = ranks[0]!;
|
||||
const hi = ranks[n - 1]!;
|
||||
if (n === 1) return { type: 'single', length: 1, value: lo };
|
||||
if (distinct.length === 1) {
|
||||
if (lo < 2) return null;
|
||||
if (n === 2) return { type: 'pair', length: 2, value: lo };
|
||||
if (n === 3) return { type: 'triple', length: 3, value: lo };
|
||||
// Four of a kind is only a bomb with four real cards (no phoenix).
|
||||
if (n === 4 && items.every((i) => i.suit !== null)) return { type: 'bomb4', length: 4, value: lo };
|
||||
return null;
|
||||
}
|
||||
if (n === 5 && distinct.length === 2 && lo >= 2) {
|
||||
const a = distinct[0]!;
|
||||
const b = distinct[1]!;
|
||||
if (counts.get(a) === 3 && counts.get(b) === 2) return { type: 'fullHouse', length: 5, value: a };
|
||||
if (counts.get(b) === 3 && counts.get(a) === 2) return { type: 'fullHouse', length: 5, value: b };
|
||||
}
|
||||
if (n >= 5 && distinct.length === n && hi - lo === n - 1) {
|
||||
const suit = items[0]!.suit;
|
||||
if (suit !== null && items.every((i) => i.suit === suit)) return { type: 'bombSF', length: n, value: hi };
|
||||
return { type: 'straight', length: n, value: hi };
|
||||
}
|
||||
if (n >= 4 && n % 2 === 0 && lo >= 2 && distinct.length === n / 2 && distinct.every((r) => counts.get(r) === 2) && hi - lo === n / 2 - 1) {
|
||||
return { type: 'pairSeq', length: n, value: hi };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The combination these cards make (§5.1), or null. A phoenix takes the strongest reading; if `prevTop` is given and
|
||||
* some reading beats it, the strongest of those (§8.1). A single phoenix is the previous single + 0.5 (1.5 when
|
||||
* leading or on the mahjong).
|
||||
*/
|
||||
export function classify(cards: readonly string[], prevTop: Combo | null = null): Combo | null {
|
||||
const n = cards.length;
|
||||
if (n === 0 || new Set(cards).size !== n) return null;
|
||||
if (n === 1) {
|
||||
const c = cards[0]!;
|
||||
if (c === DOG) return { type: 'dog', length: 1, value: 0, phoenixAs: null };
|
||||
if (c === DR) return { type: 'single', length: 1, value: DRAGON_VALUE, phoenixAs: null };
|
||||
if (c === PH) {
|
||||
const v = prevTop && prevTop.type === 'single' && prevTop.value < DRAGON_VALUE ? Math.max(prevTop.value, 1) + 0.5 : 1.5;
|
||||
return { type: 'single', length: 1, value: v, phoenixAs: null };
|
||||
}
|
||||
return { type: 'single', length: 1, value: rankOf(c), phoenixAs: null };
|
||||
}
|
||||
if (cards.includes(DOG) || cards.includes(DR)) return null;
|
||||
const hasPh = cards.includes(PH);
|
||||
const real: Item[] = cards.filter((c) => c !== PH).map((c) => ({ rank: rankOf(c), suit: suitOf(c) }));
|
||||
if (!hasPh) {
|
||||
const c = classifyPlain(real);
|
||||
return c ? { ...c, phoenixAs: null } : null;
|
||||
}
|
||||
let best: Combo | null = null;
|
||||
let bestBeats = false;
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const c = classifyPlain([...real, { rank: r, suit: null }]);
|
||||
if (!c || isBombType(c.type)) continue;
|
||||
const combo: Combo = { ...c, phoenixAs: r };
|
||||
const b = prevTop ? beats(combo, prevTop) : false;
|
||||
if (!best || (b && !bestBeats) || (b === bestBeats && combo.value > best.value)) {
|
||||
best = combo;
|
||||
bestBeats = b;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Whether `c` may go on `top` (§5.2, §5.4, §5.5). `top` null = leading (anything but the dog's rules is fine). */
|
||||
export function beats(c: Combo, top: Combo | null): boolean {
|
||||
if (!top) return true;
|
||||
if (top.type === 'dog' || c.type === 'dog') return false;
|
||||
if (isBomb(c)) {
|
||||
if (!isBomb(top)) return true;
|
||||
return c.length > top.length || (c.length === top.length && c.value > top.value);
|
||||
}
|
||||
if (isBomb(top)) return false;
|
||||
if (c.type !== top.type || c.length !== top.length) return false;
|
||||
if (c.type === 'single' && top.value >= DRAGON_VALUE) return false;
|
||||
return c.value > top.value;
|
||||
}
|
||||
|
||||
export const includesWish = (cards: readonly string[], wish: Rank | null): boolean => wish !== null && cards.some((c) => isNumber(c) && rankOf(c) === wish);
|
||||
|
||||
// ---------------------------------------------------------------- names
|
||||
|
||||
export function comboName(c: Combo, cards?: readonly string[]): string {
|
||||
const v = c.value;
|
||||
switch (c.type) {
|
||||
case 'dog':
|
||||
return '개';
|
||||
case 'single':
|
||||
if (v >= DRAGON_VALUE) return '용';
|
||||
if (v === 1 && (!cards || cards[0] === MJ)) return '참새';
|
||||
if (!Number.isInteger(v) || (cards && cards[0] === PH)) return '봉황';
|
||||
return `싱글 ${rankName(v)}`;
|
||||
case 'pair':
|
||||
return `${rankName(v)} 페어`;
|
||||
case 'triple':
|
||||
return `${rankName(v)} 트리플`;
|
||||
case 'fullHouse':
|
||||
return `풀하우스(${rankName(v)})`;
|
||||
case 'pairSeq':
|
||||
return `연속 페어 ${rankName(v - c.length / 2 + 1)}~${rankName(v)}`;
|
||||
case 'straight':
|
||||
return `스트레이트 ${c.length}장(${rankName(v - c.length + 1)}~${rankName(v)})`;
|
||||
case 'bomb4':
|
||||
return `폭탄(${rankName(v)} 넉 장)`;
|
||||
case 'bombSF':
|
||||
return `폭탄(스트레이트 플러시 ${c.length}장 ${rankName(v - c.length + 1)}~${rankName(v)})`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Short kind name for "앞 조합(페어)과 모양이 달라요". */
|
||||
export function comboKind(c: Combo): string {
|
||||
switch (c.type) {
|
||||
case 'single':
|
||||
return '싱글';
|
||||
case 'pair':
|
||||
return '페어';
|
||||
case 'triple':
|
||||
return '트리플';
|
||||
case 'fullHouse':
|
||||
return '풀하우스';
|
||||
case 'pairSeq':
|
||||
return `연속 페어 ${c.length / 2}쌍`;
|
||||
case 'straight':
|
||||
return `스트레이트 ${c.length}장`;
|
||||
case 'dog':
|
||||
return '개';
|
||||
default:
|
||||
return '폭탄';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- finder
|
||||
|
||||
export interface Found {
|
||||
cards: string[];
|
||||
combo: Combo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Representative combinations in `hand` that may go on `top` (all bombs; one of each kind × length × value × phoenix ×
|
||||
* wish card, §8.7). Leading (`top` null) includes the dog. Card choice: lowest card id first; a straight that would
|
||||
* accidentally be one suit swaps in another suit when it can.
|
||||
*/
|
||||
export function findCombos(hand: readonly string[], top: Combo | null, wish: Rank | null = null): Found[] {
|
||||
const sorted = sortCards(hand);
|
||||
const byRank = new Map<number, string[]>();
|
||||
for (const c of sorted) {
|
||||
if (!isNumber(c) && c !== MJ) continue;
|
||||
const r = rankOf(c);
|
||||
byRank.set(r, [...(byRank.get(r) ?? []), c]);
|
||||
}
|
||||
const cnt = (r: number) => byRank.get(r)?.length ?? 0;
|
||||
const ph = hand.includes(PH);
|
||||
const cand: string[][] = [];
|
||||
/** Only kinds that could follow `top` (bombs always). */
|
||||
const want = (t: ComboType) => !top || top.type === t;
|
||||
const add = (cards: string[]) => cand.push(cards);
|
||||
// A wish card of rank r first when the wish is r (lowest id otherwise; all cards of a rank are equal otherwise).
|
||||
const pickRank = (r: number, k: number): string[] => (byRank.get(r) ?? []).slice(0, k);
|
||||
|
||||
// Singles.
|
||||
if (want('single')) {
|
||||
for (const [r] of byRank) add(pickRank(r, 1));
|
||||
if (ph) add([PH]);
|
||||
if (hand.includes(DR)) add([DR]);
|
||||
}
|
||||
if (!top && hand.includes(DOG)) add([DOG]);
|
||||
// Pairs, triples.
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const k = cnt(r);
|
||||
if (want('pair')) {
|
||||
if (k >= 2) add(pickRank(r, 2));
|
||||
if (k >= 1 && ph) add([...pickRank(r, 1), PH]);
|
||||
}
|
||||
if (want('triple')) {
|
||||
if (k >= 3) add(pickRank(r, 3));
|
||||
if (k === 2 && ph) add([...pickRank(r, 2), PH]);
|
||||
}
|
||||
}
|
||||
// Full houses: per triple rank, the lowest pair, the lowest phoenix pair, and a wish pair.
|
||||
if (want('fullHouse')) {
|
||||
for (let t = 2; t <= 14; t++) {
|
||||
const tk = cnt(t);
|
||||
const triples: { cards: string[]; usesPh: boolean }[] = [];
|
||||
if (tk >= 3) triples.push({ cards: pickRank(t, 3), usesPh: false });
|
||||
if (tk === 2 && ph) triples.push({ cards: [...pickRank(t, 2), PH], usesPh: true });
|
||||
for (const tr of triples) {
|
||||
const pairs: string[][] = [];
|
||||
const realPair = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].find((p) => p !== t && cnt(p) >= 2);
|
||||
if (realPair !== undefined) pairs.push(pickRank(realPair, 2));
|
||||
if (!tr.usesPh && ph) {
|
||||
const single = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].find((p) => p !== t && cnt(p) >= 1);
|
||||
if (single !== undefined) pairs.push([...pickRank(single, 1), PH]);
|
||||
}
|
||||
if (wish !== null && wish !== t) {
|
||||
if (cnt(wish) >= 2) pairs.push(pickRank(wish, 2));
|
||||
if (!tr.usesPh && ph && cnt(wish) >= 1) pairs.push([...pickRank(wish, 1), PH]);
|
||||
}
|
||||
for (const p of pairs) add([...tr.cards, ...p]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pair sequences (one missing card may be the phoenix).
|
||||
for (let lo = 2; lo <= 13 && want('pairSeq'); lo++) {
|
||||
let usesPh = false;
|
||||
const cards: string[] = [];
|
||||
for (let hi = lo; hi <= 14; hi++) {
|
||||
const k = cnt(hi);
|
||||
if (k >= 2) cards.push(...pickRank(hi, 2));
|
||||
else if (k === 1 && ph && !usesPh) {
|
||||
usesPh = true;
|
||||
cards.push(...pickRank(hi, 1), PH);
|
||||
} else break;
|
||||
if (hi > lo) add([...cards]);
|
||||
}
|
||||
}
|
||||
// Straights (≥ 5, the mahjong as 1; the phoenix fills one gap, or stands in for one rank).
|
||||
for (let lo = 1; lo <= 10 && want('straight'); lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
if (top && hi - lo + 1 !== top.length) continue;
|
||||
const missing: number[] = [];
|
||||
for (let r = lo; r <= hi; r++) if (cnt(r) === 0) missing.push(r);
|
||||
if (missing.length > 1) break;
|
||||
const variants: number[][] = []; // ranks the phoenix replaces (empty = none)
|
||||
if (missing.length === 1) {
|
||||
if (!ph || missing[0] === 1) continue;
|
||||
variants.push([missing[0]!]);
|
||||
} else {
|
||||
variants.push([]);
|
||||
if (ph) {
|
||||
variants.push([hi]);
|
||||
if (wish !== null && wish >= lo && wish <= hi && wish !== hi && wish !== 1) variants.push([wish]);
|
||||
}
|
||||
}
|
||||
for (const v of variants) {
|
||||
const cards: string[] = [];
|
||||
for (let r = lo; r <= hi; r++) cards.push(v.includes(r) ? PH : pickRank(r, 1)[0]!);
|
||||
const real = cards.filter((c) => isNumber(c));
|
||||
if (real.length === cards.length && real.every((c) => c[0] === real[0]![0])) {
|
||||
// Accidentally a straight flush: swap one card for another suit if there is one (the bomb is listed below).
|
||||
let swapped = false;
|
||||
for (let i = 0; i < cards.length && !swapped; i++) {
|
||||
const alt = (byRank.get(rankOf(cards[i]!)) ?? []).find((c) => c[0] !== cards[i]![0]);
|
||||
if (alt) {
|
||||
cards[i] = alt;
|
||||
swapped = true;
|
||||
}
|
||||
}
|
||||
if (!swapped) continue;
|
||||
}
|
||||
add(cards);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Bombs: four of a kind and every straight flush.
|
||||
for (let r = 2; r <= 14; r++) if (cnt(r) === 4) add(pickRank(r, 4));
|
||||
for (const s of SUITS) {
|
||||
const have = new Set(sorted.filter((c) => c[0] === s && isNumber(c)).map(rankOf));
|
||||
for (let lo = 2; lo <= 10; lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
let ok = true;
|
||||
for (let r = lo; r <= hi && ok; r++) ok = have.has(r);
|
||||
if (!ok) break;
|
||||
add(Array.from({ length: hi - lo + 1 }, (_, i) => `${s}${lo + i}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const out: Found[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const cards of cand) {
|
||||
const combo = classify(cards, top);
|
||||
if (!combo) continue;
|
||||
if (top && !beats(combo, top)) continue;
|
||||
const key = isBomb(combo)
|
||||
? `B|${sortCards(cards).join(',')}`
|
||||
: `${combo.type}|${combo.length}|${combo.value}|${cards.includes(PH)}|${includesWish(cards, wish)}|${cards.length === 1 ? cards[0] : ''}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({ cards: sortCards(cards), combo });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bombs in a hand (four of a kind, every straight flush), weakest first. */
|
||||
export function findBombs(hand: readonly string[]): Found[] {
|
||||
const out: Found[] = [];
|
||||
const nums = hand.filter(isNumber);
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const four = SUITS.map((x) => `${x}${r}`);
|
||||
if (four.every((c) => nums.includes(c))) out.push({ cards: four, combo: { type: 'bomb4', length: 4, value: r, phoenixAs: null } });
|
||||
}
|
||||
for (const x of SUITS) {
|
||||
const have = new Set(nums.filter((c) => c[0] === x).map(rankOf));
|
||||
for (let lo = 2; lo <= 10; lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
if (!have.has(hi) || ![...Array(hi - lo).keys()].every((k) => have.has(lo + k))) break;
|
||||
out.push({ cards: Array.from({ length: hi - lo + 1 }, (_, i) => `${x}${lo + i}`), combo: { type: 'bombSF', length: hi - lo + 1, value: hi, phoenixAs: null } });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.combo.length - b.combo.length || a.combo.value - b.combo.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* The mahjong wish duty (§5.3): on my own turn, holding a real card of the wished rank and able to play it in a legal
|
||||
* combination (phoenix and bombs included), I must. Leading, a single of that rank always works.
|
||||
*/
|
||||
export function mustFulfillWish(hand: readonly string[], top: Combo | null, wish: Rank | null, leading: boolean): boolean {
|
||||
if (wish === null || !includesWish(hand, wish)) return false;
|
||||
if (leading) return true;
|
||||
return findCombos(hand, top, wish).some((f) => includesWish(f.cards, wish));
|
||||
}
|
||||
|
||||
/** Weakest first: non-bombs before bombs, then value, then more cards first. */
|
||||
export const weakestFirst = (a: Found, b: Found): number =>
|
||||
Number(isBomb(a.combo)) - Number(isBomb(b.combo)) || a.combo.value - b.combo.value || b.cards.length - a.cards.length;
|
||||
1326
packages/games/src/tichu/index.ts
Normal file
1326
packages/games/src/tichu/index.ts
Normal file
File diff suppressed because it is too large
Load Diff
878
packages/games/src/tichu/tichu.test.ts
Normal file
878
packages/games/src/tichu/tichu.test.ts
Normal file
@@ -0,0 +1,878 @@
|
||||
/** 티츄 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);
|
||||
});
|
||||
});
|
||||
325
packages/games/src/tichu/types.ts
Normal file
325
packages/games/src/tichu/types.ts
Normal file
@@ -0,0 +1,325 @@
|
||||
/** 티츄 options, actions, state and view types (docs/games/tichu.md §2, §8). */
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import type { Combo, Rank } from './combo';
|
||||
|
||||
export * from './combo';
|
||||
|
||||
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
export const tichuOptionsSchema = z.object({
|
||||
mode: z
|
||||
.enum(['team', 'individual', 'threechu', 'tientsin'])
|
||||
.default('team')
|
||||
.meta({
|
||||
title: '게임 방식',
|
||||
labels: { team: '4인 팀전(2:2)', individual: '4인 개인전(짝꿍이 바뀜)', threechu: '3인(딜러 + 더미)', tientsin: '6인 팀전(3:3)' },
|
||||
}),
|
||||
targetScore: lit<300 | 500 | 1000 | 1500>(300, 500, 1000, 1500)
|
||||
.default(1000)
|
||||
.meta({ title: '목표 점수(3인은 판 수로 끝)', labels: { 300: '300점', 500: '500점', 1000: '1,000점', 1500: '1,500점' } }),
|
||||
threechuHands: lit<3 | 6 | 9 | 12>(3, 6, 9, 12)
|
||||
.default(6)
|
||||
.meta({ title: '3인 판 수', labels: { 3: '3판', 6: '6판', 9: '9판', 12: '12판' } }),
|
||||
grandTichu: z.boolean().default(true).meta({ title: '그랜드 티츄(첫 8장 보고 ±200)' }),
|
||||
direction: z
|
||||
.enum(['right', 'left'])
|
||||
.default('right')
|
||||
.meta({ title: '차례 방향', labels: { right: '오른쪽(반시계, 원작)', left: '왼쪽(시계)' } }),
|
||||
bombTiming: z
|
||||
.enum(['anytime', 'ownTurn'])
|
||||
.default('anytime')
|
||||
.meta({ title: '폭탄 내는 때', labels: { anytime: '아무 때나 끼어들기(원작)', ownTurn: '자기 차례에만' } }),
|
||||
bombWindowSeconds: lit<1 | 2 | 3>(1, 2, 3)
|
||||
.default(2)
|
||||
.meta({ title: '트릭 끝 폭탄 기다리기', labels: { 1: '1초', 2: '2초', 3: '3초' } }),
|
||||
wishRule: z
|
||||
.enum(['enforce', 'penalty'])
|
||||
.default('enforce')
|
||||
.meta({ title: '참새 소원을 어기면', labels: { enforce: '화면이 막아 줌(원작)', penalty: '막지 않고 어기면 상대 원투(대회식)' } }),
|
||||
trickHistory: z
|
||||
.enum(['last', 'all'])
|
||||
.default('last')
|
||||
.meta({ title: '지난 카드 보기', labels: { last: '직전 트릭만', all: '이번 라운드 전부(초보 도움)' } }),
|
||||
party: z.boolean().default(false).meta({ title: '파티 모드(라운드마다 효과 하나, 팀전·개인전)' }),
|
||||
/** null = 무제한: no clock for turns, the grand choice and the dragon gift (away players keep the short one). */
|
||||
turnSeconds: lit<20 | 30 | 45 | 60 | null>(20, 30, 45, 60, null)
|
||||
.default(30)
|
||||
.meta({ title: '한 턴 제한 시간', labels: { 20: '20초', 30: '30초', 45: '45초', 60: '60초', null: '무제한' } }),
|
||||
exchangeSeconds: lit<30 | 45 | 60 | null>(30, 45, 60, null)
|
||||
.default(45)
|
||||
.meta({ title: '카드 교환 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', null: '무제한' } }),
|
||||
});
|
||||
export type TichuOptions = z.infer<typeof tichuOptionsSchema>;
|
||||
export type TichuMode = TichuOptions['mode'];
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
const cardId = z.string().max(4);
|
||||
const seat = z.number().int().min(0).max(5);
|
||||
|
||||
export const tichuActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('grand'), call: z.boolean() }),
|
||||
z.object({ type: z.literal('tichu'), seat: seat.optional() }),
|
||||
z.object({ type: z.literal('exchange'), seat: seat.optional(), give: z.array(z.object({ to: seat, cardId })).min(1).max(3) }),
|
||||
z.object({
|
||||
type: z.literal('play'),
|
||||
cardIds: z.array(cardId).min(1).max(14),
|
||||
seat: seat.optional(),
|
||||
wish: z.number().int().min(2).max(14).nullable().optional(),
|
||||
dogTo: seat.optional(),
|
||||
}),
|
||||
z.object({ type: z.literal('pass'), seat: seat.optional() }),
|
||||
z.object({ type: z.literal('noBomb') }),
|
||||
z.object({ type: z.literal('dragonTo'), to: seat }),
|
||||
z.object({ type: z.literal('ready') }),
|
||||
]);
|
||||
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
|
||||
export type TichuAction = z.infer<typeof tichuActionSchema> | { type: 'timeout' } | { type: 'leave' };
|
||||
export type PlayAction = Extract<TichuAction, { type: 'play' }>;
|
||||
export type ExchangeAction = Extract<TichuAction, { type: 'exchange' }>;
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
export type Seat = number;
|
||||
export type Call = 'none' | 'tichu' | 'grand';
|
||||
export type Effect = 'double' | 'negative' | 'rotate' | 'plain';
|
||||
export const EFFECTS: readonly Effect[] = ['double', 'negative', 'rotate', 'plain'];
|
||||
|
||||
export interface Play {
|
||||
seat: Seat;
|
||||
cards: string[];
|
||||
combo: Combo;
|
||||
outOfTurn: boolean;
|
||||
}
|
||||
|
||||
export type Phase =
|
||||
| { kind: 'grand'; decided: boolean[] }
|
||||
| { kind: 'exchange'; give: ({ to: Seat; card: string }[] | null)[] }
|
||||
| { kind: 'playing' }
|
||||
/** `final`: the round is already over (3rd out with the dragon on top); score after the gift. */
|
||||
| { kind: 'dragonGift'; by: Seat; final: boolean }
|
||||
| { kind: 'roundEnd'; ready: boolean[] }
|
||||
| { kind: 'finished' };
|
||||
|
||||
export interface Trick {
|
||||
leader: Seat;
|
||||
plays: Play[];
|
||||
/** Seats that passed since the top play. */
|
||||
passed: Seat[];
|
||||
/** "카드 모으는 중" deadline (everyone passed; bombs may still come, §8.5). */
|
||||
closingAt: number | null;
|
||||
/** Seats that pressed "폭탄 없음" in this closing window. */
|
||||
waived: Seat[];
|
||||
}
|
||||
|
||||
export type RoundKind = 'double' | 'triple' | 'last' | 'penalty';
|
||||
|
||||
export interface CallResult {
|
||||
seat: Seat;
|
||||
player: PlayerId;
|
||||
call: 'tichu' | 'grand';
|
||||
success: boolean;
|
||||
points: number;
|
||||
}
|
||||
|
||||
export interface RoundResult {
|
||||
round: number;
|
||||
kind: RoundKind;
|
||||
out: Seat[];
|
||||
/** Seat that was left with cards (`last`), else null. */
|
||||
lastSeat: Seat | null;
|
||||
/** Owner of each seat this round (null for the threechu dummy). */
|
||||
seatOwners: (PlayerId | null)[];
|
||||
teams: PlayerId[][];
|
||||
/** Per team (0 for a 원투 / 트리플 빅토리 / penalty). */
|
||||
cardPoints: number[];
|
||||
bonus: number[];
|
||||
callPoints: number[];
|
||||
calls: CallResult[];
|
||||
/** Points the last seat's hand gave the other team, and points of its tricks moved to the winner. */
|
||||
handover: { hand: number; won: number } | null;
|
||||
effect: Effect | null;
|
||||
penalty: { seat: Seat } | null;
|
||||
total: number[];
|
||||
/** Score standing after this round (same shape as `scores`). */
|
||||
scoresAfter: number[];
|
||||
}
|
||||
|
||||
export type LogEntry =
|
||||
| { seq: number; t: 'play'; seat: Seat; cards: string[]; label: string; bomb: boolean; outOfTurn: boolean }
|
||||
| { seq: number; t: 'pass'; seat: Seat }
|
||||
| { seq: number; t: 'dog'; seat: Seat; to: Seat }
|
||||
| { seq: number; t: 'trick'; seat: Seat; points: number }
|
||||
| { seq: number; t: 'dragon'; seat: Seat; to: Seat; points: number }
|
||||
| { seq: number; t: 'wish'; seat: Seat; rank: Rank }
|
||||
| { seq: number; t: 'wishDone'; rank: Rank }
|
||||
| { seq: number; t: 'call'; seat: Seat; call: 'tichu' | 'grand' }
|
||||
| { seq: number; t: 'out'; seat: Seat; place: number }
|
||||
| { seq: number; t: 'exchanged'; rotated: boolean }
|
||||
| { seq: number; t: 'round'; round: number; kind: RoundKind; total: number[] }
|
||||
| { seq: number; t: 'deal'; round: number; effect: Effect | null }
|
||||
| { seq: number; t: 'penalty'; seat: Seat; rank: Rank }
|
||||
| { seq: number; t: 'timeout'; p: PlayerId }
|
||||
| { seq: number; t: 'left'; p: PlayerId };
|
||||
|
||||
export interface TichuFinal {
|
||||
ranking: PlayerId[][];
|
||||
scores: Record<PlayerId, number>;
|
||||
scoreText: Record<PlayerId, string>;
|
||||
summary: string;
|
||||
reason: 'normal' | 'abandoned';
|
||||
}
|
||||
|
||||
export interface SeatInfo {
|
||||
owner: PlayerId;
|
||||
/** threechu: the dummy hand, played by `owner` (this round's dealer). */
|
||||
dummy: boolean;
|
||||
}
|
||||
|
||||
export interface TichuState {
|
||||
options: TichuOptions;
|
||||
players: PlayerId[];
|
||||
round: number;
|
||||
seats: SeatInfo[];
|
||||
/** Seat numbers in turn order (clockwise seats; `right` = counter-clockwise). */
|
||||
order: Seat[];
|
||||
team: number[];
|
||||
/** threechu: index (in `players`) of this round's dealer; tientsin: seat that starts the deal. */
|
||||
dealer: number | null;
|
||||
effect: Effect | null;
|
||||
hands: string[][];
|
||||
/** grand phase: the cards not dealt yet (secret). */
|
||||
pending: string[][];
|
||||
received: { from: Seat; card: string }[][];
|
||||
calls: Call[];
|
||||
played: boolean[];
|
||||
wish: Rank | null;
|
||||
trick: Trick;
|
||||
lastTrick: { winner: Seat; plays: Play[]; points: number } | null;
|
||||
playedCards: string[];
|
||||
won: string[][];
|
||||
out: Seat[];
|
||||
current: Seat;
|
||||
phase: Phase;
|
||||
/** team / tientsin: per team; individual / threechu: per player (`players` order). */
|
||||
scores: number[];
|
||||
rounds: RoundResult[];
|
||||
/** tientsin: who finished first last round (starts the next deal). */
|
||||
lastFirst: Seat | null;
|
||||
turnStartedAt: number;
|
||||
turnNo: number;
|
||||
seq: number;
|
||||
timeoutsInRow: Record<PlayerId, number>;
|
||||
away: Record<PlayerId, boolean>;
|
||||
left: Record<PlayerId, boolean>;
|
||||
log: LogEntry[];
|
||||
final: TichuFinal | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export interface SeatView {
|
||||
seat: Seat;
|
||||
owner: PlayerId;
|
||||
dummy: boolean;
|
||||
team: number;
|
||||
cards: number;
|
||||
call: Call;
|
||||
/** Finish place this round (1-based). */
|
||||
place: number | null;
|
||||
passed: boolean;
|
||||
isTurn: boolean;
|
||||
/** grand: decided; exchange: sent; roundEnd: ready (owner). */
|
||||
done: boolean;
|
||||
away: boolean;
|
||||
left: boolean;
|
||||
/** threechu dummy hand once it is open (after the exchange). */
|
||||
openHand: string[] | null;
|
||||
/** trickHistory = all: card points this seat has won so far. */
|
||||
wonPoints: number | null;
|
||||
}
|
||||
|
||||
export interface PlayView {
|
||||
seat: Seat;
|
||||
cards: string[];
|
||||
combo: Combo;
|
||||
label: string;
|
||||
outOfTurn: boolean;
|
||||
}
|
||||
|
||||
export interface Suggestion {
|
||||
cards: string[];
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface MySeatView {
|
||||
seat: Seat;
|
||||
dummy: boolean;
|
||||
hand: string[];
|
||||
/** Normal turn: may play now. */
|
||||
canPlay: boolean;
|
||||
canPass: boolean;
|
||||
leading: boolean;
|
||||
/** enforce: the wished rank I must include now; always null in `penalty`. */
|
||||
mustWish: Rank | null;
|
||||
canTichu: boolean;
|
||||
canGrand: boolean;
|
||||
/** grand phase: still has to choose. */
|
||||
grandPending: boolean;
|
||||
bombs: string[][];
|
||||
canBombNow: boolean;
|
||||
canNoBomb: boolean;
|
||||
suggestions: Suggestion[];
|
||||
exchangeTargets: { seat: Seat; label: string }[];
|
||||
/** My chosen exchange (null before sending). */
|
||||
exchangeSent: { to: Seat; cardId: string }[] | null;
|
||||
exchangeSuggest: { to: Seat; cardId: string }[];
|
||||
received: { from: Seat; cardId: string }[];
|
||||
dragonTargets: Seat[];
|
||||
/** tientsin: partners the dog may go to. */
|
||||
dogTargets: Seat[];
|
||||
}
|
||||
|
||||
export interface TichuView {
|
||||
options: TichuOptions;
|
||||
me: PlayerId | null;
|
||||
mode: TichuMode;
|
||||
round: number;
|
||||
phase: Phase['kind'];
|
||||
seats: SeatView[];
|
||||
order: Seat[];
|
||||
/** My own (non-dummy) seat. */
|
||||
mySeat: Seat | null;
|
||||
dealer: PlayerId | null;
|
||||
effect: Effect | null;
|
||||
current: Seat | null;
|
||||
trick: { leader: Seat; plays: PlayView[]; passed: Seat[]; closingAt: number | null; waived: Seat[] } | null;
|
||||
wish: Rank | null;
|
||||
lastTrick: { winner: Seat; plays: PlayView[]; points: number } | null;
|
||||
/** trickHistory = all: every card played this round. */
|
||||
playedCards: string[] | null;
|
||||
/** trickHistory = all: card points won per team so far. */
|
||||
teamWon: number[] | null;
|
||||
scores: number[];
|
||||
/** Who each entry of `scores` belongs to. */
|
||||
scoreOwners: PlayerId[][];
|
||||
/** The latest round in full (round-end screen). */
|
||||
lastRound: RoundResult | null;
|
||||
/** Every round in short (score table). */
|
||||
history: { round: number; kind: RoundKind; total: number[]; effect: Effect | null; /** Change of `scores` (same shape) */ gains: number[] }[];
|
||||
dragonBy: Seat | null;
|
||||
ready: Record<PlayerId, boolean> | null;
|
||||
my: MySeatView | null;
|
||||
/** threechu dealer: the dummy hand I play. */
|
||||
dummy: MySeatView | null;
|
||||
turnStartedAt: number;
|
||||
deadlineTotalMs: number;
|
||||
bombWindowMs: number;
|
||||
turnNo: number;
|
||||
log: LogEntry[];
|
||||
result: TichuFinal | null;
|
||||
}
|
||||
Reference in New Issue
Block a user