Files
joke-app/packages/games/src/tichu/combo.ts
EJClaw 4f69f19bf9 새 게임 티츄: 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>
2026-10-15 23:31:37 +09:00

418 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 티츄 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;