Files
joke-app/packages/games/src/tichu/index.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

1327 lines
54 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.
/** 티츄 (docs/games/tichu.md). Pure and deterministic; state is JSON. */
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
import {
DOG,
DR,
EFFECTS,
FULL_DECK,
MJ,
PH,
beats,
cardPoints,
classify,
comboKind,
comboName,
findBombs,
findCombos,
includesWish,
isBomb,
isNumber,
mustFulfillWish,
rankName,
rankOf,
sortCards,
tichuActionSchema,
tichuOptionsSchema,
weakestFirst,
type CallResult,
type Combo,
type Effect,
type ExchangeAction,
type Found,
type LogEntry,
type MySeatView,
type Play,
type PlayAction,
type PlayView,
type RoundKind,
type RoundResult,
type Seat,
type SeatInfo,
type Suggestion,
type TichuAction,
type TichuFinal,
type TichuOptions,
type TichuState,
type TichuView,
} from './types';
export * from './types';
const GRAND_MS = 15_000;
const DRAGON_MS = 15_000;
const ROUND_END_MS = 10_000;
const AWAY_MS = 5000;
const AWAY_AFTER = 3;
/** Automatic moves wait this long after a turn starts, so people can still drop a bomb (§8.5). */
const MIN_TURN_MS = 1200;
const LOG_MAX = 60;
const LOG_VIEW = 24;
const SUGGEST_MAX = 8;
type Def = GameDefinition<TichuState, TichuAction, TichuView, TichuOptions> & {
legalActions(s: TichuState, p: PlayerId): TichuAction[];
secretsOf(s: TichuState, p: PlayerId): string[];
};
interface Ctx {
rng: Rng;
now: number;
events: GameEvent[];
}
// ---------------------------------------------------------------- small helpers
const clone = (s: TichuState): TichuState => structuredClone(s);
export const seatCount = (o: Pick<TichuOptions, 'mode'>): number => (o.mode === 'tientsin' ? 6 : 4);
export const playerCount = (o: Pick<TichuOptions, 'mode'>): number => (o.mode === 'tientsin' ? 6 : o.mode === 'threechu' ? 3 : 4);
const fourSeats = (s: TichuState) => s.seats.length === 4;
function log(s: TichuState, e: Record<string, unknown> & { t: LogEntry['t'] }): void {
s.log.push({ seq: s.seq, ...e } as LogEntry);
if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX);
}
const hasCards = (s: TichuState, seat: Seat) => s.hands[seat]!.length > 0;
const seatsWithCards = (s: TichuState): Seat[] => s.order.filter((x) => hasCards(s, x));
const ownerOf = (s: TichuState, seat: Seat): PlayerId => s.seats[seat]!.owner;
/** Seats `p` plays (own seat first; the threechu dealer also plays the dummy). */
export const seatsOf = (s: TichuState, p: PlayerId): Seat[] => {
const own = s.seats.findIndex((x) => x.owner === p && !x.dummy);
const dummy = s.seats.findIndex((x) => x.owner === p && x.dummy);
return [own, dummy].filter((x) => x >= 0);
};
const mainSeat = (s: TichuState, p: PlayerId): Seat | null => seatsOf(s, p)[0] ?? null;
const ownsSeat = (s: TichuState, p: PlayerId, seat: Seat) => seat >= 0 && seat < s.seats.length && s.seats[seat]!.owner === p;
/** Next seat after `from` in turn order that still has cards (`from` itself if nobody else). */
function nextWithCards(s: TichuState, from: Seat): Seat {
const n = s.order.length;
const i0 = s.order.indexOf(from);
for (let k = 1; k <= n; k++) {
const x = s.order[(i0 + k) % n]!;
if (hasCards(s, x)) return x;
}
return from;
}
const partners = (s: TichuState, seat: Seat): Seat[] => s.order.filter((x) => x !== seat && s.team[x] === s.team[seat]);
const opponents = (s: TichuState, seat: Seat): Seat[] => s.order.filter((x) => s.team[x] !== s.team[seat]);
/** Exchange targets (§4.5, §5.9) with names: seats clockwise, so seat+1 sits on my left on the screen. */
export function exchangeTargets(s: Pick<TichuState, 'options' | 'seats'>, seat: Seat): { seat: Seat; label: string }[] {
const n = s.seats.length;
const at = (k: number) => (seat + k) % n;
if (s.options.mode === 'tientsin') {
return [
{ seat: at(2), label: '왼쪽 짝꿍' },
{ seat: at(4), label: '오른쪽 짝꿍' },
];
}
if (s.options.mode === 'threechu') {
return [
{ seat: at(1), label: '왼쪽 상대' },
{ seat: at(3), label: '오른쪽 상대' },
];
}
return [
{ seat: at(1), label: '왼쪽 상대' },
{ seat: at(2), label: '짝꿍' },
{ seat: at(3), label: '오른쪽 상대' },
];
}
const topPlay = (s: TichuState): Play | null => s.trick.plays[s.trick.plays.length - 1] ?? null;
const trickCards = (s: TichuState): string[] => s.trick.plays.flatMap((p) => p.cards);
const leadingNow = (s: TichuState) => s.trick.plays.length === 0;
function newTurn(s: TichuState, seat: Seat): void {
s.current = seat;
s.turnNo += 1;
}
function startTrick(s: TichuState, leader: Seat, ctx: Ctx): void {
s.trick = { leader, plays: [], passed: [], closingAt: null, waived: [] };
ctx.events.push({ type: 'trickStart', seat: leader });
newTurn(s, leader);
}
const fmt = (n: number): string => {
const sign = n < 0 ? '−' : '';
return sign + String(Math.abs(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
// ---------------------------------------------------------------- rounds
/** individual: partners per round (§5.9) as [[a, b], [c, d]] player indexes. */
const PAIRINGS = [
[
[0, 2],
[1, 3],
],
[
[0, 1],
[2, 3],
],
[
[0, 3],
[1, 2],
],
];
function seatingFor(s: TichuState): SeatInfo[] {
const P = s.players;
switch (s.options.mode) {
case 'individual': {
const [[a, b], [c, d]] = PAIRINGS[(s.round - 1) % 3]! as [[number, number], [number, number]];
return [P[a]!, P[c]!, P[b]!, P[d]!].map((owner) => ({ owner, dummy: false }));
}
case 'threechu': {
const d = s.dealer!;
const step = s.options.direction === 'left' ? 1 : 2;
const next = P[(d + step) % 3]!;
const other = P[(d + 3 - step) % 3]!;
// Turn order dealer → next → dummy → other in either direction.
const dealer = P[d]!;
const ring = s.options.direction === 'left' ? [dealer, next, dealer, other] : [dealer, other, dealer, next];
return ring.map((owner, i) => ({ owner, dummy: i === 2 }));
}
default:
return P.map((owner) => ({ owner, dummy: false }));
}
}
function startRound(s: TichuState, ctx: Ctx): void {
s.round += 1;
if (s.options.mode === 'threechu' && s.round > 1) {
const step = s.options.direction === 'left' ? 1 : 2;
s.dealer = (s.dealer! + step) % 3;
}
if (s.options.mode === 'tientsin' && s.lastFirst !== null) s.dealer = s.lastFirst;
s.seats = seatingFor(s);
const n = s.seats.length;
const clockwise = Array.from({ length: n }, (_, i) => i);
s.order = s.options.direction === 'left' ? clockwise : [0, ...clockwise.slice(1).reverse()];
s.team = s.seats.map((_, i) => i % 2);
if (s.options.party && (s.options.mode === 'team' || s.options.mode === 'individual')) {
const pool = EFFECTS.filter((e) => e !== s.effect);
s.effect = pool[ctx.rng.int(pool.length)]!;
} else s.effect = null;
const deck = ctx.rng.shuffle(FULL_DECK);
s.hands = s.seats.map(() => []);
s.pending = s.seats.map(() => []);
const tientsin = s.options.mode === 'tientsin';
const first = tientsin ? 6 : 8;
// tientsin: the first two in turn order from the deal starter get 10 cards, the others 9 (§5.9).
const dealOrder = tientsin ? Array.from({ length: n }, (_, k) => s.order[(s.order.indexOf(s.dealer ?? 0) + k) % n]!) : s.order;
let at = 0;
dealOrder.forEach((seat, k) => {
const size = tientsin ? (k < 2 ? 10 : 9) : 14;
const cards = deck.slice(at, at + size);
at += size;
s.hands[seat] = sortCards(cards.slice(0, first));
s.pending[seat] = cards.slice(first);
});
s.received = s.seats.map(() => []);
s.calls = s.seats.map(() => 'none');
s.played = s.seats.map(() => false);
s.wish = null;
s.trick = { leader: 0, plays: [], passed: [], closingAt: null, waived: [] };
s.lastTrick = null;
s.playedCards = [];
s.won = s.seats.map(() => []);
s.out = [];
s.current = s.order[0]!;
// Card ids repeat every round: old plays leave the log so a view never names a card that is in a hand again.
s.log = s.log.filter((e) => e.t !== 'play');
log(s, { t: 'deal', round: s.round, effect: s.effect });
ctx.events.push({ type: 'deal', round: s.round, effect: s.effect });
if (s.options.grandTichu) {
// The threechu dealer (and the dummy) may not call a grand tichu (§5.9).
s.phase = { kind: 'grand', decided: s.seats.map((x) => s.options.mode === 'threechu' && x.owner === s.players[s.dealer!]) };
} else dealRest(s);
s.turnNo += 1;
}
function dealRest(s: TichuState): void {
s.hands = s.hands.map((h, i) => sortCards([...h, ...s.pending[i]!]));
s.pending = s.seats.map(() => []);
s.phase = { kind: 'exchange', give: s.seats.map(() => null) };
}
function doExchange(s: TichuState, ctx: Ctx): void {
if (s.phase.kind !== 'exchange') throw new Error('not exchanging');
const give = s.phase.give;
const incoming: { from: Seat; card: string }[][] = s.seats.map(() => []);
give.forEach((g, from) => {
for (const x of g!) {
s.hands[from] = s.hands[from]!.filter((c) => c !== x.card);
incoming[x.to]!.push({ from, card: x.card });
}
});
incoming.forEach((inc, seat) => {
s.hands[seat] = sortCards([...s.hands[seat]!, ...inc.map((x) => x.card)]);
});
s.received = incoming;
const rotated = s.effect === 'rotate';
if (rotated) {
// §7 손패 돌리기: every hand moves on to the next seat in turn order; calls stay with the people.
const next = s.hands.map(() => [] as string[]);
s.order.forEach((seat, i) => {
next[s.order[(i + 1) % s.order.length]!] = s.hands[seat]!;
});
s.hands = next;
s.received = s.seats.map(() => []);
}
log(s, { t: 'exchanged', rotated });
ctx.events.push({ type: 'exchanged', rotated });
const leader = s.hands.findIndex((h) => h.includes(MJ));
s.phase = { kind: 'playing' };
startTrick(s, leader, ctx);
}
/** How the round ends right now, or null (§5.8, §5.9). */
function roundOver(s: TichuState): RoundKind | null {
if (fourSeats(s) && s.out.length >= 2 && s.team[s.out[0]!] === s.team[s.out[1]!]) return 'double';
if (!fourSeats(s) && s.out.length >= 3 && s.out.slice(0, 3).every((x) => s.team[x] === s.team[s.out[0]!])) return 'triple';
if (seatsWithCards(s).length <= 1) return 'last';
return null;
}
const teamsOf = (s: TichuState): PlayerId[][] =>
[0, 1].map((t) => [...new Set(s.seats.filter((x, i) => s.team[i] === t && !x.dummy).map((x) => x.owner))]);
/** Score the round (§6, §7) and add it to the standings. */
export function scoreRound(s: TichuState, kind: RoundKind, penaltySeat: Seat | null): RoundResult {
const n = s.seats.length;
const cardPts = [0, 0];
const bonus = [0, 0];
const callPts = [0, 0];
const calls: CallResult[] = [];
let lastSeat: Seat | null = null;
let handover: RoundResult['handover'] = null;
const vt = penaltySeat === null ? null : s.team[penaltySeat]!;
s.calls.forEach((c, seat) => {
if (c === 'none') return;
const success = vt !== null ? s.team[seat] !== vt : s.out[0] === seat;
const points = (c === 'grand' ? 200 : 100) * (success ? 1 : -1);
callPts[s.team[seat]!]! += points;
calls.push({ seat, player: ownerOf(s, seat), call: c, success, points });
});
// The penalty counts as the other team's instant win: 200 (tientsin: 300, as it has no 원투).
if (kind === 'penalty') bonus[1 - vt!] = n === 6 ? 300 : 200;
else if (kind === 'double') bonus[s.team[s.out[0]!]!] = 200;
else if (kind === 'triple') bonus[s.team[s.out[0]!]!] = 300;
else {
const won = s.won.map((w) => [...w]);
const extra = [0, 0];
lastSeat = seatsWithCards(s)[0] ?? null;
if (lastSeat !== null) {
const opp = 1 - s.team[lastSeat]!;
const handPts = cardPoints(s.hands[lastSeat]!, s.effect);
extra[opp]! += handPts;
const first = s.out[0]!;
if (n === 4) {
handover = { hand: handPts, won: cardPoints(won[lastSeat]!, s.effect) };
won[first]!.push(...won[lastSeat]!);
won[lastSeat] = [];
} else {
// tientsin: the last one's tricks go to the other team too, the 5th one's tricks to the first (§5.9).
const lastWon = cardPoints(won[lastSeat]!, s.effect);
extra[opp]! += lastWon;
won[lastSeat] = [];
const fifth = s.out[4];
handover = { hand: handPts, won: lastWon };
if (fifth !== undefined) {
won[first]!.push(...won[fifth]!);
won[fifth] = [];
}
}
}
won.forEach((w, seat) => {
cardPts[s.team[seat]!]! += cardPoints(w, s.effect);
});
cardPts[0]! += extra[0]!;
cardPts[1]! += extra[1]!;
}
const mult = s.effect === 'double' ? 2 : 1;
const total = [0, 1].map((t) => (bonus[t]! + cardPts[t]! + callPts[t]!) * mult);
if (s.options.mode === 'team' || s.options.mode === 'tientsin') {
s.scores[0]! += total[0]!;
s.scores[1]! += total[1]!;
} else {
s.players.forEach((p, i) => {
const seat = mainSeat(s, p)!;
s.scores[i]! += total[s.team[seat]!]!;
});
}
const r: RoundResult = {
round: s.round,
kind,
out: [...s.out],
lastSeat,
seatOwners: s.seats.map((x) => (x.dummy ? null : x.owner)),
teams: teamsOf(s),
cardPoints: cardPts,
bonus,
callPoints: callPts,
calls,
handover,
effect: s.effect,
penalty: penaltySeat === null ? null : { seat: penaltySeat },
total,
scoresAfter: [...s.scores],
};
return r;
}
function endRound(s: TichuState, kind: RoundKind, ctx: Ctx, penaltySeat: Seat | null = null): void {
// 'last': the table's trick went to its winner already. Otherwise (원투 / penalty) its cards don't count; they go to
// the top seat's pile so every card stays accounted for.
const top = topPlay(s);
if (kind !== 'last' && top) s.won[top.seat]!.push(...trickCards(s));
s.trick = { ...s.trick, plays: [], passed: [], closingAt: null, waived: [] };
const r = scoreRound(s, kind, penaltySeat);
s.rounds.push(r);
if (s.options.mode === 'tientsin' && s.out.length) s.lastFirst = s.out[0]!;
log(s, { t: 'round', round: s.round, kind, total: r.total });
ctx.events.push({ type: 'roundEnd', round: s.round, kind, total: r.total });
if (gameOver(s)) {
finish(s, 'normal', ctx);
return;
}
s.phase = { kind: 'roundEnd', ready: s.players.map(() => false) };
s.turnNo += 1;
}
function gameOver(s: TichuState): boolean {
if (s.options.mode === 'threechu') return s.round >= s.options.threechuHands;
const max = Math.max(...s.scores);
if (max < s.options.targetScore) return false;
return s.scores.filter((x) => x === max).length === 1;
}
/** Final ranking (§8.6). Teams share a place; individual / threechu rank people (ties share). */
export function finalOf(s: TichuState, reason: 'normal' | 'abandoned'): TichuFinal {
const scores: Record<PlayerId, number> = {};
let ranking: PlayerId[][];
let summary: string;
const doubles = (t: number) => s.rounds.filter((r) => (r.kind === 'double' || r.kind === 'triple') && r.bonus[t]! > 0).length;
if (s.options.mode === 'team' || s.options.mode === 'tientsin') {
const teams = [0, 1].map((t) => s.players.filter((_, i) => i % 2 === t));
teams.forEach((ps, t) => ps.forEach((p) => (scores[p] = s.scores[t]!)));
const w = s.scores[0]! >= s.scores[1]! ? 0 : 1;
const tie = s.scores[0] === s.scores[1];
ranking = tie ? [s.players.slice()] : [teams[w]!, teams[1 - w]!];
const big = s.options.mode === 'tientsin' ? '트리플 빅토리' : '원투';
const extra = doubles(w) > 0 ? ` (${big} ${doubles(w)}번)` : '';
summary = tie
? `두 팀이 ${fmt(s.scores[0]!)}점으로 비겼어요.`
: `${w === 0 ? 'A' : 'B'}팀이 ${fmt(s.scores[w]!)} 대 ${fmt(s.scores[1 - w]!)}으로 이겼어요!${extra}`;
} else {
s.players.forEach((p, i) => (scores[p] = s.scores[i]!));
const sorted = [...s.players].sort((a, b) => scores[b]! - scores[a]! || s.players.indexOf(a) - s.players.indexOf(b));
ranking = [];
for (const p of sorted) {
const last = ranking[ranking.length - 1];
if (last && scores[last[0]!] === scores[p]) last.push(p);
else ranking.push([p]);
}
const top = ranking[0]!;
summary = top.length > 1 ? `${top.length}명이 ${fmt(scores[top[0]!]!)}점으로 공동 1등이에요!` : `${fmt(scores[top[0]!]!)}점을 모은 사람이 1등이에요!`;
if (s.options.mode === 'threechu') summary = `${s.round}판을 마쳤어요. ${summary}`;
}
if (reason === 'abandoned') summary = `모두 나가서 게임을 멈췄어요. ${summary}`;
return {
ranking,
scores,
scoreText: Object.fromEntries(Object.entries(scores).map(([p, v]) => [p, `${fmt(v)}점`])),
summary,
reason,
};
}
function finish(s: TichuState, reason: 'normal' | 'abandoned', ctx: Ctx): void {
s.final = finalOf(s, reason);
s.phase = { kind: 'finished' };
ctx.events.push({ type: 'gameEnd', ranking: s.final.ranking });
}
// ---------------------------------------------------------------- playing
/** Duty check for a normal turn (§5.3): the wished rank I must include now, or null. Dummy hands are free. */
function wishDuty(s: TichuState, seat: Seat, found?: Found[]): number | null {
if (s.seats[seat]!.dummy || s.wish === null) return null;
const hand = s.hands[seat]!;
if (!includesWish(hand, s.wish)) return null;
const top = topPlay(s);
if (!top) return s.wish;
const list = found ?? findCombos(hand, top.combo, s.wish);
return list.some((f) => includesWish(f.cards, s.wish)) ? s.wish : null;
}
const isNormalTurn = (s: TichuState, seat: Seat) => s.phase.kind === 'playing' && s.current === seat && s.trick.closingAt === null;
function playCards(s: TichuState, seat: Seat, a: PlayAction, ctx: Ctx): void {
const top = topPlay(s);
const outOfTurn = !isNormalTurn(s, seat);
const ids = a.cardIds;
const combo = classify(ids, top?.combo ?? null)!;
// wishRule = penalty: breaking the duty ends the round at once (§7).
if (!outOfTurn && s.options.wishRule === 'penalty') {
const duty = wishDuty(s, seat);
if (duty !== null && !includesWish(ids, duty)) {
penalize(s, seat, ctx);
return;
}
}
s.hands[seat] = s.hands[seat]!.filter((c) => !ids.includes(c));
s.played[seat] = true;
const play: Play = { seat, cards: sortCards(ids), combo, outOfTurn };
s.playedCards.push(...ids);
if (combo.type === 'dog') {
s.won[seat]!.push(DOG);
s.lastTrick = { winner: seat, plays: [play], points: 0 };
markOut(s, seat, ctx);
const kind = roundOver(s);
// Lead goes to the partner (tientsin: the chosen one); if out, the next seat with cards after them.
const target = a.dogTo ?? partners(s, seat)[0]!;
log(s, { t: 'dog', seat, to: target });
ctx.events.push({ type: 'dog', seat, to: target });
if (kind) {
endRound(s, kind, ctx);
return;
}
startTrick(s, hasCards(s, target) ? target : nextWithCards(s, target), ctx);
return;
}
s.trick.plays.push(play);
s.trick.passed = [];
s.trick.closingAt = null;
s.trick.waived = [];
const label = comboName(combo, play.cards);
log(s, { t: 'play', seat, cards: play.cards, label, bomb: isBomb(combo), outOfTurn });
ctx.events.push({ type: isBomb(combo) ? 'bomb' : 'played', seat, cards: play.cards, label, outOfTurn });
if (s.wish !== null && includesWish(ids, s.wish)) {
log(s, { t: 'wishDone', rank: s.wish });
s.wish = null;
}
if (ids.includes(MJ)) {
s.wish = a.wish ?? null;
if (s.wish !== null) {
log(s, { t: 'wish', seat, rank: s.wish });
ctx.events.push({ type: 'wish', seat, rank: s.wish });
}
}
markOut(s, seat, ctx);
const kind = roundOver(s);
if (kind) {
if (kind === 'last' && combo.type === 'single' && ids[0] === DR) {
s.phase = { kind: 'dragonGift', by: seat, final: true };
s.turnNo += 1;
return;
}
if (kind === 'last') collect(s, seat, ctx);
endRound(s, kind, ctx);
return;
}
newTurn(s, nextWithCards(s, seat));
}
function markOut(s: TichuState, seat: Seat, ctx: Ctx): void {
if (hasCards(s, seat) || s.out.includes(seat)) return;
s.out.push(seat);
log(s, { t: 'out', seat, place: s.out.length });
ctx.events.push({ type: 'out', seat, place: s.out.length });
}
function penalize(s: TichuState, seat: Seat, ctx: Ctx): void {
log(s, { t: 'penalty', seat, rank: s.wish! });
ctx.events.push({ type: 'penalty', seat, rank: s.wish });
endRound(s, 'penalty', ctx, seat);
}
/** The trick's cards go to `winner` (§5.2). */
function collect(s: TichuState, winner: Seat, ctx: Ctx): void {
const cards = trickCards(s);
s.won[winner]!.push(...cards);
const points = cardPoints(cards, s.effect);
s.lastTrick = { winner, plays: s.trick.plays, points };
log(s, { t: 'trick', seat: winner, points });
ctx.events.push({ type: 'trick', seat: winner, points });
}
function pass(s: TichuState, seat: Seat, ctx: Ctx): void {
if (s.options.wishRule === 'penalty' && wishDuty(s, seat) !== null) {
penalize(s, seat, ctx);
return;
}
s.trick.passed.push(seat);
log(s, { t: 'pass', seat });
ctx.events.push({ type: 'pass', seat });
const top = topPlay(s)!;
const waiting = seatsWithCards(s).filter((x) => x !== top.seat && !s.trick.passed.includes(x));
if (waiting.length > 0) {
newTurn(s, nextWithCards(s, seat));
return;
}
if (s.options.bombTiming === 'ownTurn') {
closeTrick(s, ctx);
return;
}
// Everyone passed: "카드 모으는 중" — bombs may still come for a moment (§5.2, §8.5).
s.trick.closingAt = ctx.now + s.options.bombWindowSeconds * 1000;
s.trick.waived = [];
s.turnNo += 1;
ctx.events.push({ type: 'closing', seat: top.seat });
}
function closeTrick(s: TichuState, ctx: Ctx): void {
const top = topPlay(s)!;
s.trick.closingAt = null;
if (top.combo.type === 'single' && top.cards[0] === DR) {
s.phase = { kind: 'dragonGift', by: top.seat, final: false };
s.turnNo += 1;
return;
}
collect(s, top.seat, ctx);
startTrick(s, hasCards(s, top.seat) ? top.seat : nextWithCards(s, top.seat), ctx);
}
function giveDragon(s: TichuState, to: Seat, ctx: Ctx): void {
if (s.phase.kind !== 'dragonGift') throw new Error('no dragon gift');
const { by, final } = s.phase;
const cards = trickCards(s);
s.won[to]!.push(...cards);
const points = cardPoints(cards, s.effect);
s.lastTrick = { winner: to, plays: s.trick.plays, points };
log(s, { t: 'dragon', seat: by, to, points });
ctx.events.push({ type: 'dragon', seat: by, to, points });
s.phase = { kind: 'playing' };
if (final) {
endRound(s, 'last', ctx);
return;
}
startTrick(s, hasCards(s, by) ? by : nextWithCards(s, by), ctx);
}
/** Dragon gift by rule (§8.5): the opponent with most cards (out ones last), first in turn order on ties. */
export function autoDragonTarget(s: TichuState, by: Seat): Seat {
const opp = opponents(s, by);
const i0 = s.order.indexOf(by);
const dist = (x: Seat) => (s.order.indexOf(x) - i0 + s.order.length) % s.order.length;
return [...opp].sort((a, b) => s.hands[b]!.length - s.hands[a]!.length || dist(a) - dist(b))[0]!;
}
// ---------------------------------------------------------------- choices (legal, auto, view)
interface TurnInfo {
/** Every representative play on the table now (no wish filter). */
found: Found[];
/** Wished rank I must include (any wish rule), or null. */
duty: number | null;
/** Legal plays (enforce: duty applied), weakest first. */
plays: Found[];
}
/** One look at a normal turn for `seat`: what can be played and whether the wish binds. */
function turnInfo(s: TichuState, seat: Seat): TurnInfo {
const top = topPlay(s);
const found = findCombos(s.hands[seat]!, top?.combo ?? null, s.wish);
const duty = wishDuty(s, seat, found);
const enforced = s.options.wishRule === 'enforce' ? duty : null;
const plays = found.filter((f) => enforced === null || includesWish(f.cards, enforced)).sort(weakestFirst);
return { found, duty, plays };
}
/** Bombs `seat` may drop now out of turn (§5.5), weakest first. */
function outOfTurnBombs(s: TichuState, seat: Seat): Found[] {
if (s.options.bombTiming !== 'anytime' || s.phase.kind !== 'playing' || !hasCards(s, seat)) return [];
if (isNormalTurn(s, seat)) return [];
const top = topPlay(s);
if (!top || s.trick.waived.includes(seat)) return [];
return findBombs(s.hands[seat]!).filter((f) => beats(f.combo, top.combo));
}
const canTichu = (s: TichuState, seat: Seat): boolean =>
(s.phase.kind === 'exchange' || s.phase.kind === 'playing' || s.phase.kind === 'dragonGift') && !s.played[seat] && s.calls[seat] === 'none' && s.out.length === 0;
function canGrand(s: TichuState, seat: Seat): boolean {
return s.phase.kind === 'grand' && !s.phase.decided[seat] && !s.seats[seat]!.dummy && !(s.options.mode === 'threechu' && s.seats[seat]!.owner === s.players[s.dealer!]);
}
/** §8.5 exchange timeout: weakest loose number cards to opponents, the strongest number card to partners. */
export function autoExchange(s: TichuState, seat: Seat): { to: Seat; cardId: string }[] {
const hand = sortCards(s.hands[seat]!);
const nums = hand.filter(isNumber);
const count = (r: number) => nums.filter((c) => rankOf(c) === r).length;
const avoid = (c: string) => [5, 10, 13].includes(rankOf(c)) || count(rankOf(c)) >= 2;
const used = new Set<string>();
const take = (list: string[]) => {
const c = list.find((x) => !used.has(x));
if (c) used.add(c);
return c;
};
const specialsLow = [DOG, MJ, PH, DR].filter((c) => hand.includes(c));
const weakPool = () => [...nums.filter((c) => !avoid(c)), ...nums, ...specialsLow];
const strongPool = () => [...[...nums].reverse(), ...[...specialsLow].reverse()];
return exchangeTargets(s, seat).map((t) => {
const partner = s.team[t.seat] === s.team[seat];
const cardId = (partner ? take(strongPool()) : take(weakPool())) ?? take(hand)!;
return { to: t.seat, cardId };
});
}
/** §8.5 normal-turn timeout move (never a tichu; a bomb only when the wish leaves nothing else). */
function autoMove(s: TichuState, seat: Seat): TichuAction {
const top = topPlay(s);
const hand = s.hands[seat]!;
const duty = wishDuty(s, seat);
const withSeat = <T extends object>(a: T) => (seatsOf(s, ownerOf(s, seat)).length > 1 ? { ...a, seat } : a);
if (duty !== null) {
const f = findCombos(hand, top?.combo ?? null, duty)
.filter((x) => includesWish(x.cards, duty))
.sort(weakestFirst)[0]!;
return withSeat({ type: 'play', cardIds: f.cards, ...(f.cards.includes(MJ) ? { wish: null } : {}) }) as TichuAction;
}
if (top) return withSeat({ type: 'pass' }) as TichuAction;
const order = [MJ, ...sortCards(hand.filter(isNumber)), PH, DR, DOG];
const card = order.find((c) => hand.includes(c))!;
const a: PlayAction = { type: 'play', cardIds: [card] };
if (card === MJ) a.wish = null;
if (card === DOG && s.options.mode === 'tientsin') a.dogTo = dogTargets(s, seat)[0] ?? partners(s, seat)[0]!;
return withSeat(a) as TichuAction;
}
/** tientsin: partners with cards the dog may go to (both out: the first partner, then onwards). */
function dogTargets(s: TichuState, seat: Seat): Seat[] {
const ps = partners(s, seat);
const live = ps.filter((x) => hasCards(s, x));
return live.length ? live : ps.slice(0, 1);
}
function suggestionsFor(s: TichuState, info: TurnInfo): Suggestion[] {
const plays = info.plays.filter((f) => !isBomb(f.combo));
const leading = leadingNow(s);
const picked: Found[] = [];
if (leading) {
// One of each kind first (weakest), then fill with the next weakest.
const kinds = new Set<string>();
for (const f of plays) {
if (kinds.has(f.combo.type)) continue;
kinds.add(f.combo.type);
picked.push(f);
}
}
for (const f of plays) if (picked.length < SUGGEST_MAX && !picked.includes(f)) picked.push(f);
return picked.slice(0, SUGGEST_MAX).map((f) => ({ cards: f.cards, label: comboName(f.combo, f.cards) }));
}
// ---------------------------------------------------------------- validation
function resolveSeat(s: TichuState, actor: PlayerId, seat: number | undefined, preferCurrent: boolean): Seat | null {
if (seat !== undefined) return ownsSeat(s, actor, seat) ? seat : null;
if (preferCurrent && s.phase.kind === 'playing' && s.trick.closingAt === null && ownsSeat(s, actor, s.current)) return s.current;
return mainSeat(s, actor);
}
function validatePlay(s: TichuState, actor: PlayerId, a: PlayAction): Validation {
if (s.phase.kind !== 'playing') return fail('지금은 카드를 낼 수 없어요.');
const seat = resolveSeat(s, actor, a.seat, true);
if (seat === null) return fail('내 자리가 아니에요.');
const ids = a.cardIds;
if (new Set(ids).size !== ids.length) return fail('같은 카드를 두 번 고를 수 없어요.');
const hand = s.hands[seat]!;
if (ids.some((c) => !hand.includes(c))) return fail('손에 없는 카드예요.');
const top = topPlay(s);
const combo = classify(ids, top?.combo ?? null);
if (!combo) return fail('낼 수 없는 모양이에요.');
if (ids.includes(MJ)) {
if (a.wish !== undefined && a.wish !== null && (a.wish < 2 || a.wish > 14)) return fail('소원은 2~A 중에서 골라 주세요.');
} else if (a.wish !== undefined && a.wish !== null) return fail('소원은 참새를 낼 때만 부를 수 있어요.');
if (isNormalTurn(s, seat)) {
if (combo.type === 'dog' && top) return fail('개는 새 트릭을 시작할 때만 낼 수 있어요.');
if (top && ids.length === 1 && ids[0] === PH && top.combo.type === 'single' && top.combo.value >= 100) return fail('봉황은 용 위에 낼 수 없어요.');
if (top && !beats(combo, top.combo)) {
if (!isBomb(combo) && (combo.type !== top.combo.type || combo.length !== top.combo.length)) return fail('앞 조합과 같은 모양·같은 장수로 내야 해요.');
return fail('더 센 조합만 낼 수 있어요.');
}
if (s.options.wishRule === 'enforce') {
const duty = wishDuty(s, seat);
if (duty !== null && !includesWish(ids, duty)) return fail(`소원 ${rankName(duty)}을(를) 넣어서 내야 해요.`);
}
if (combo.type === 'dog') {
if (s.options.mode === 'tientsin') {
const targets = dogTargets(s, seat);
if (a.dogTo === undefined) return fail('개로 선을 넘길 짝꿍을 골라 주세요.');
if (!targets.includes(a.dogTo)) return fail('개는 짝꿍에게만 넘길 수 있어요.');
} else if (a.dogTo !== undefined) return fail('개는 짝꿍에게 자동으로 넘어가요.');
} else if (a.dogTo !== undefined) return fail('개를 낼 때만 넘길 사람을 골라요.');
return ok;
}
// Out of turn: only a bomb (§5.5).
if (!isBomb(combo)) return s.trick.closingAt !== null ? fail('카드 모으는 중에는 폭탄만 낼 수 있어요.') : fail('지금은 내 차례가 아니에요.');
if (s.options.bombTiming !== 'anytime') return fail('이 방에서는 폭탄도 자기 차례에만 낼 수 있어요.');
if (!top) return fail('폭탄은 바닥에 카드가 있을 때만 끼어들 수 있어요.');
if (s.trick.waived.includes(seat)) return fail('이번에는 이미 "폭탄 없음"을 눌렀어요.');
if (!beats(combo, top.combo)) return fail('바닥 폭탄보다 센 폭탄만 낼 수 있어요.');
return ok;
}
function validateExchange(s: TichuState, actor: PlayerId, a: ExchangeAction): Validation {
if (s.phase.kind !== 'exchange') return fail('지금은 카드를 교환할 때가 아니에요.');
const seat = resolveSeat(s, actor, a.seat, false);
if (seat === null) return fail('내 자리가 아니에요.');
const targets = exchangeTargets(s, seat).map((t) => t.seat);
const to = a.give.map((g) => g.to);
if (to.length !== targets.length || new Set(to).size !== to.length || !to.every((x) => targets.includes(x))) return fail('한 사람에게 한 장씩 골라 주세요.');
const cards = a.give.map((g) => g.cardId);
if (new Set(cards).size !== cards.length) return fail('서로 다른 카드를 골라 주세요.');
if (cards.some((c) => !s.hands[seat]!.includes(c))) return fail('손에 없는 카드예요.');
return ok;
}
// ---------------------------------------------------------------- waiting / clocks
function waiting(s: TichuState): PlayerId[] {
const ph = s.phase;
const uniq = (seats: Seat[]) => [...new Set(seats.map((x) => ownerOf(s, x)))];
switch (ph.kind) {
case 'grand':
return uniq(s.order.filter((x) => !ph.decided[x]));
case 'exchange':
return uniq(s.order.filter((x) => ph.give[x] === null));
case 'playing':
// Collecting: everyone with cards (so nobody can tell who holds a bomb, §8.3).
if (s.trick.closingAt !== null) return uniq(seatsWithCards(s));
return [ownerOf(s, s.current)];
case 'dragonGift':
return [ownerOf(s, ph.by)];
case 'roundEnd':
return s.players.filter((_, i) => !ph.ready[i]);
case 'finished':
return [];
}
}
function deadlineMs(s: TichuState): number | null {
const ph = s.phase;
if (ph.kind === 'finished') return null;
if (ph.kind === 'playing' && s.trick.closingAt !== null) return s.options.bombWindowSeconds * 1000;
const w = waiting(s);
if (w.length > 0 && w.every((p) => s.away[p])) return AWAY_MS;
const t = s.options.turnSeconds;
switch (ph.kind) {
case 'grand':
return t === null ? null : GRAND_MS;
case 'exchange':
return s.options.exchangeSeconds === null ? null : s.options.exchangeSeconds * 1000;
case 'playing':
return t === null ? null : t * 1000;
case 'dragonGift':
return t === null ? null : DRAGON_MS;
case 'roundEnd':
return ROUND_END_MS;
}
}
function timeoutMove(s: TichuState, p: PlayerId, ctx: Ctx): void {
const ph = s.phase;
switch (ph.kind) {
case 'grand':
for (const seat of seatsOf(s, p)) if (!ph.decided[seat]) decideGrand(s, seat, false, ctx);
return;
case 'exchange':
for (const seat of seatsOf(s, p)) {
if (s.phase.kind !== 'exchange' || s.phase.give[seat] !== null) continue;
sendExchange(s, seat, autoExchange(s, seat), ctx);
}
return;
case 'playing': {
if (s.trick.closingAt !== null) {
closeTrick(s, ctx);
return;
}
const a = autoMove(s, s.current);
if (a.type === 'play') playCards(s, s.current, a, ctx);
else pass(s, s.current, ctx);
return;
}
case 'dragonGift':
giveDragon(s, autoDragonTarget(s, ph.by), ctx);
return;
case 'roundEnd':
setReady(s, p, ctx);
return;
}
}
function decideGrand(s: TichuState, seat: Seat, call: boolean, ctx: Ctx): void {
if (s.phase.kind !== 'grand') throw new Error('not grand');
s.phase.decided[seat] = true;
if (call) {
s.calls[seat] = 'grand';
log(s, { t: 'call', seat, call: 'grand' });
ctx.events.push({ type: 'call', seat, call: 'grand' });
}
if (s.phase.decided.every(Boolean)) {
dealRest(s);
s.turnNo += 1;
ctx.events.push({ type: 'dealRest' });
}
}
function sendExchange(s: TichuState, seat: Seat, give: { to: Seat; cardId: string }[], ctx: Ctx): void {
if (s.phase.kind !== 'exchange') throw new Error('not exchanging');
s.phase.give[seat] = give.map((g) => ({ to: g.to, card: g.cardId }));
ctx.events.push({ type: 'exchangeSent', seat });
if (s.phase.give.every((g) => g !== null)) doExchange(s, ctx);
}
function setReady(s: TichuState, p: PlayerId, ctx: Ctx): void {
if (s.phase.kind !== 'roundEnd') throw new Error('not roundEnd');
s.phase.ready[s.players.indexOf(p)] = true;
if (s.phase.ready.every(Boolean)) startRound(s, ctx);
}
// ---------------------------------------------------------------- view
function playView(p: Play): PlayView {
return { seat: p.seat, cards: p.cards, combo: p.combo, label: comboName(p.combo, p.cards), outOfTurn: p.outOfTurn };
}
function mySeatView(s: TichuState, seat: Seat): MySeatView {
const ph = s.phase;
const hand = sortCards(s.hands[seat]!);
const normal = isNormalTurn(s, seat);
const top = topPlay(s);
const info = normal ? turnInfo(s, seat) : null;
const bombs = findBombs(hand);
const anytime = s.options.bombTiming === 'anytime' && ph.kind === 'playing' && !normal && !!top && !s.trick.waived.includes(seat);
const canBombNow = info ? info.plays.some((f) => isBomb(f.combo)) : anytime && bombs.some((b) => beats(b.combo, top!.combo));
const closing = ph.kind === 'playing' && s.trick.closingAt !== null;
const sent = ph.kind === 'exchange' ? ph.give[seat] : null;
const enforce = s.options.wishRule === 'enforce';
return {
seat,
dummy: s.seats[seat]!.dummy,
hand,
canPlay: normal,
canPass: normal && !!top && !(enforce && info!.duty !== null),
leading: normal && !top,
mustWish: info && enforce ? info.duty : null,
canTichu: canTichu(s, seat),
canGrand: canGrand(s, seat),
grandPending: ph.kind === 'grand' && !ph.decided[seat],
bombs: bombs.map((b) => b.cards),
canBombNow,
canNoBomb: closing && hasCards(s, seat) && !s.trick.waived.includes(seat),
suggestions: info ? suggestionsFor(s, info) : [],
exchangeTargets: ph.kind === 'exchange' ? exchangeTargets(s, seat) : [],
exchangeSent: sent ? sent.map((g) => ({ to: g.to, cardId: g.card })) : null,
exchangeSuggest: ph.kind === 'exchange' ? autoExchange(s, seat) : [],
received: s.received[seat]!.filter((r) => hand.includes(r.card)).map((r) => ({ from: r.from, cardId: r.card })),
dragonTargets: ph.kind === 'dragonGift' && ph.by === seat ? opponents(s, seat) : [],
dogTargets: s.options.mode === 'tientsin' && normal && !top && hand.includes(DOG) ? dogTargets(s, seat) : [],
};
}
// ---------------------------------------------------------------- definition
export const tichu: Def = {
id: 'tichu',
nameKo: '티츄',
minPlayers: 3,
maxPlayers: 6,
stateVersion: 1,
defaultOptions: tichuOptionsSchema.parse({}),
optionsSchema: tichuOptionsSchema as unknown as Def['optionsSchema'],
actionSchema: tichuActionSchema as unknown as Def['actionSchema'],
playersFor(o) {
const n = playerCount(o);
return { min: n, max: n };
},
playerCountError(o, count) {
const n = playerCount(o);
return count === n ? null : `${o.mode === 'threechu' ? '3인 티츄' : o.mode === 'tientsin' ? '6인 티츄' : '티츄'}는 ${n}명이 해요.`;
},
setup({ players, options, rng, now }) {
const n = playerCount(options);
if (players.length !== n) throw new Error(`tichu: ${options.mode} needs ${n} players, got ${players.length}`);
const individual = options.mode === 'individual' || options.mode === 'threechu';
const s: TichuState = {
options,
players: [...players],
round: 0,
seats: [],
order: [],
team: [],
dealer: options.mode === 'threechu' ? rng.int(3) : options.mode === 'tientsin' ? rng.int(6) : null,
effect: null,
hands: [],
pending: [],
received: [],
calls: [],
played: [],
wish: null,
trick: { leader: 0, plays: [], passed: [], closingAt: null, waived: [] },
lastTrick: null,
playedCards: [],
won: [],
out: [],
current: 0,
phase: { kind: 'playing' },
scores: individual ? players.map(() => 0) : [0, 0],
rounds: [],
lastFirst: null,
turnStartedAt: now,
turnNo: 0,
seq: 0,
timeoutsInRow: Object.fromEntries(players.map((p) => [p, 0])),
away: Object.fromEntries(players.map((p) => [p, false])),
left: Object.fromEntries(players.map((p) => [p, false])),
log: [],
final: null,
};
startRound(s, { rng, now, events: [] });
return s;
},
validate(s, actor, a) {
if (!s.players.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase.kind === 'finished') return fail('게임이 이미 끝났어요.');
const ph = s.phase;
switch (a.type) {
case 'leave':
return s.left[actor] ? fail('이미 나간 플레이어예요.') : ok;
case 'timeout':
return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
case 'grand': {
if (ph.kind !== 'grand') return fail('지금은 그랜드 티츄를 고를 때가 아니에요.');
const seat = mainSeat(s, actor);
if (seat === null || ph.decided[seat]) return fail('이미 골랐어요.');
if (a.call && !canGrand(s, seat)) return fail('딜러는 그랜드 티츄를 부를 수 없어요.');
return ok;
}
case 'tichu': {
const seat = resolveSeat(s, actor, a.seat, false);
if (seat === null) return fail('내 자리가 아니에요.');
if (s.phase.kind === 'grand') return fail('14장을 다 받은 뒤에 티츄를 부를 수 있어요.');
if (s.calls[seat] === 'grand') return fail('이미 그랜드 티츄를 불렀어요.');
if (s.calls[seat] === 'tichu') return fail('이미 티츄를 불렀어요.');
if (s.out.length > 0) return fail('누가 이미 손패를 다 털어서 티츄를 부를 수 없어요.');
if (s.played[seat]) return fail('이미 카드를 내서 티츄를 부를 수 없어요.');
if (!canTichu(s, seat)) return fail('지금은 티츄를 부를 수 없어요.');
return ok;
}
case 'exchange':
return validateExchange(s, actor, a);
case 'play':
return validatePlay(s, actor, a);
case 'pass': {
if (ph.kind !== 'playing') return fail('지금은 패스할 수 없어요.');
const seat = resolveSeat(s, actor, a.seat, true);
if (seat === null || !isNormalTurn(s, seat)) return fail('지금은 내 차례가 아니에요.');
if (leadingNow(s)) return fail('새 트릭을 시작할 때는 패스할 수 없어요.');
if (s.options.wishRule === 'enforce') {
const duty = wishDuty(s, seat);
if (duty !== null) return fail(`소원 ${rankName(duty)}을(를) 낼 수 있어서 패스할 수 없어요.`);
}
return ok;
}
case 'noBomb': {
if (ph.kind !== 'playing' || s.trick.closingAt === null) return fail('지금은 카드를 모으는 중이 아니에요.');
const mine = seatsOf(s, actor).filter((x) => hasCards(s, x) && !s.trick.waived.includes(x));
return mine.length ? ok : fail('이미 눌렀어요.');
}
case 'dragonTo':
if (ph.kind !== 'dragonGift' || ownerOf(s, ph.by) !== actor) return fail('지금은 용 트릭을 줄 때가 아니에요.');
return opponents(s, ph.by).includes(a.to) ? ok : fail('용 트릭은 상대 팀에게만 줄 수 있어요.');
case 'ready':
if (ph.kind !== 'roundEnd') return fail('지금은 다음 라운드를 기다리는 중이 아니에요.');
return ph.ready[s.players.indexOf(actor)] ? fail('이미 눌렀어요.') : ok;
}
},
apply(prev, actor, a, { rng, now }) {
const s = clone(prev);
const ctx: Ctx = { rng, now, events: [] };
const before = `${s.turnNo}|${s.phase.kind}`;
s.seq += 1;
const closing = s.phase.kind === 'playing' && s.trick.closingAt !== null;
if (a.type !== 'timeout' && a.type !== 'leave') {
s.timeoutsInRow[actor] = 0;
s.away[actor] = !!s.left[actor];
}
switch (a.type) {
case 'grand':
decideGrand(s, mainSeat(s, actor)!, a.call, ctx);
break;
case 'tichu': {
const seat = resolveSeat(s, actor, a.seat, false)!;
s.calls[seat] = 'tichu';
log(s, { t: 'call', seat, call: 'tichu' });
ctx.events.push({ type: 'call', seat, call: 'tichu' });
break;
}
case 'exchange':
sendExchange(s, resolveSeat(s, actor, a.seat, false)!, a.give, ctx);
break;
case 'play':
playCards(s, resolveSeat(s, actor, a.seat, true)!, a, ctx);
break;
case 'pass':
pass(s, resolveSeat(s, actor, a.seat, true)!, ctx);
break;
case 'noBomb': {
for (const x of seatsOf(s, actor)) if (hasCards(s, x) && !s.trick.waived.includes(x)) s.trick.waived.push(x);
if (seatsWithCards(s).every((x) => s.trick.waived.includes(x))) closeTrick(s, ctx);
break;
}
case 'dragonTo':
giveDragon(s, a.to, ctx);
break;
case 'ready':
setReady(s, actor, ctx);
break;
case 'leave':
s.left[actor] = true;
s.away[actor] = true;
ctx.events.push({ type: 'left', player: actor });
log(s, { t: 'left', p: actor });
if (s.players.every((p) => s.left[p])) finish(s, 'abandoned', ctx);
break;
case 'timeout': {
// The bomb window running out is nobody's fault (no away count).
if (!closing) {
s.timeoutsInRow[actor] = (s.timeoutsInRow[actor] ?? 0) + 1;
if (s.timeoutsInRow[actor]! >= AWAY_AFTER && !s.away[actor]) {
s.away[actor] = true;
ctx.events.push({ type: 'away', player: actor });
}
ctx.events.push({ type: 'timeout', player: actor });
log(s, { t: 'timeout', p: actor });
}
timeoutMove(s, actor, ctx);
break;
}
}
if (`${s.turnNo}|${s.phase.kind}` !== before) s.turnStartedAt = now;
return { state: s, events: ctx.events };
},
view(s, viewer) {
const me = viewer && s.players.includes(viewer) ? viewer : null;
const ph = s.phase;
const w = waiting(s);
const playing = ph.kind === 'playing';
const closing = playing && s.trick.closingAt !== null;
const exchanged = ph.kind === 'playing' || ph.kind === 'dragonGift' || ph.kind === 'roundEnd' || ph.kind === 'finished';
const all = s.options.trickHistory === 'all';
const mine = me ? seatsOf(s, me) : [];
const own = me ? mainSeat(s, me) : null;
const dummySeat = mine.find((x) => s.seats[x]!.dummy) ?? null;
const individual = s.options.mode === 'individual' || s.options.mode === 'threechu';
return {
options: s.options,
me,
mode: s.options.mode,
round: s.round,
phase: ph.kind,
seats: s.seats.map((x, seat) => ({
seat,
owner: x.owner,
dummy: x.dummy,
team: s.team[seat]!,
cards: s.hands[seat]!.length,
call: s.calls[seat]!,
place: s.out.includes(seat) ? s.out.indexOf(seat) + 1 : null,
passed: playing && s.trick.passed.includes(seat),
isTurn:
ph.kind === 'grand'
? !ph.decided[seat]
: ph.kind === 'exchange'
? ph.give[seat] === null
: ph.kind === 'playing'
? closing
? hasCards(s, seat)
: s.current === seat
: ph.kind === 'dragonGift'
? ph.by === seat
: false,
done:
ph.kind === 'grand'
? !!ph.decided[seat]
: ph.kind === 'exchange'
? ph.give[seat] !== null
: ph.kind === 'roundEnd'
? !!ph.ready[s.players.indexOf(x.owner)]
: false,
away: !!s.away[x.owner],
left: !!s.left[x.owner],
openHand: x.dummy && exchanged && ph.kind !== 'roundEnd' && ph.kind !== 'finished' ? sortCards(s.hands[seat]!) : null,
wonPoints: all ? cardPoints(s.won[seat]!, s.effect) : null,
})),
order: [...s.order],
mySeat: own,
dealer: s.options.mode === 'threechu' ? s.players[s.dealer!]! : null,
effect: s.effect,
current: playing && !closing ? s.current : null,
trick: playing || ph.kind === 'dragonGift' ? { leader: s.trick.leader, plays: s.trick.plays.map(playView), passed: [...s.trick.passed], closingAt: s.trick.closingAt, waived: [...s.trick.waived] } : null,
wish: s.wish,
lastTrick: s.lastTrick ? { winner: s.lastTrick.winner, plays: s.lastTrick.plays.map(playView), points: s.lastTrick.points } : null,
playedCards: all ? sortCards(s.playedCards) : null,
teamWon: all ? [0, 1].map((t) => s.won.reduce((acc, wn, seat) => acc + (s.team[seat] === t ? cardPoints(wn, s.effect) : 0), 0)) : null,
scores: [...s.scores],
scoreOwners: individual ? s.players.map((p) => [p]) : [0, 1].map((t) => s.players.filter((_, i) => i % 2 === t)),
lastRound: s.rounds[s.rounds.length - 1] ?? null,
history: s.rounds.map((r, i) => ({ round: r.round, kind: r.kind, total: r.total, effect: r.effect, gains: r.scoresAfter.map((x, k) => x - (s.rounds[i - 1]?.scoresAfter[k] ?? 0)) })),
dragonBy: ph.kind === 'dragonGift' ? ph.by : null,
ready: ph.kind === 'roundEnd' ? Object.fromEntries(s.players.map((p, i) => [p, !!ph.ready[i]])) : null,
my: own !== null && ph.kind !== 'finished' ? mySeatView(s, own) : null,
dummy: dummySeat !== null && ph.kind !== 'finished' ? mySeatView(s, dummySeat) : null,
turnStartedAt: s.turnStartedAt,
deadlineTotalMs: deadlineMs(s) ?? 0,
bombWindowMs: s.options.bombWindowSeconds * 1000,
turnNo: s.turnNo,
log: s.log.slice(-LOG_VIEW),
result: s.final,
};
},
activePlayers: waiting,
deadline(s) {
if (s.phase.kind === 'playing' && s.trick.closingAt !== null) return s.trick.closingAt;
const ms = deadlineMs(s);
return ms === null ? null : s.turnStartedAt + ms;
},
timeoutPlayers: waiting,
timeoutNotBefore(s) {
if (s.phase.kind !== 'playing') return null;
if (s.trick.closingAt !== null) return s.trick.closingAt;
return s.turnStartedAt + MIN_TURN_MS;
},
onTimeout() {
return { type: 'timeout' };
},
onLeave(s, player) {
if (!s.players.includes(player) || s.left[player] || s.phase.kind === 'finished') return null;
return { type: 'leave' };
},
result(s): GameResult | null {
if (!s.final) return null;
return { ranking: s.final.ranking, scores: s.final.scores, scoreText: s.final.scoreText, summary: s.final.summary, reason: s.final.reason };
},
legalActions(s, p) {
if (!s.players.includes(p) || s.phase.kind === 'finished') return [];
const mine = seatsOf(s, p);
// The threechu dealer plays two hands: always name the seat.
const seatArg = (seat: Seat) => (mine.length > 1 ? { seat } : {});
// A tichu call is offered next to whatever the game waits on this player for (never on its own, so a computer
// is not asked to act just because it still may call).
// Calls are listed only with a hand that could make them (validate accepts any call): uniformly random play would
// otherwise call on every other hand and never reach the target score.
const calls: TichuAction[] = mine.filter((seat) => canTichu(s, seat) && callStrength(s.hands[seat]!) >= 7).map((seat) => ({ type: 'tichu', ...seatArg(seat) }));
const withCalls = (acts: TichuAction[]): TichuAction[] => (acts.length ? [...calls, ...acts] : []);
return withCalls(tichuMoves(s, p, mine, seatArg));
},
/** Cards only this player may see: own hands still in play, the undealt cards, the dummy before it opens. */
secretsOf(s, player) {
const out: string[] = [];
const exchanged = s.phase.kind !== 'grand' && s.phase.kind !== 'exchange';
for (const seat of seatsOf(s, player)) {
if (s.seats[seat]!.dummy && exchanged) continue;
out.push(...s.hands[seat]!, ...(s.pending[seat] ?? []));
}
return out;
},
};
/** Rough hand strength for listing calls: dragon 3, phoenix 3, ace 2, king 1, four of a kind 4. */
function callStrength(hand: readonly string[]): number {
let v = (hand.includes(DR) ? 3 : 0) + (hand.includes(PH) ? 3 : 0);
for (let r = 13; r <= 14; r++) v += hand.filter((c) => isNumber(c) && rankOf(c) === r).length * (r === 14 ? 2 : 1);
for (let r = 2; r <= 14; r++) if (hand.filter((c) => isNumber(c) && rankOf(c) === r).length === 4) v += 4;
return v;
}
/** Moves other than a tichu call (`legalActions`). */
function tichuMoves(s: TichuState, p: PlayerId, mine: Seat[], seatArg: (seat: Seat) => { seat?: Seat }): TichuAction[] {
const ph = s.phase;
const out: TichuAction[] = [];
switch (ph.kind) {
case 'grand': {
const seat = mainSeat(s, p)!;
if (ph.decided[seat]) return [];
out.push({ type: 'grand', call: false });
if (canGrand(s, seat) && callStrength(s.hands[seat]!) >= 6) out.push({ type: 'grand', call: true });
return out;
}
case 'exchange':
for (const seat of mine) {
if (ph.give[seat] !== null) continue;
const auto = autoExchange(s, seat);
// The suggested exchange and a few reassignments of the same cards.
const cards = auto.map((g) => g.cardId);
const tos = auto.map((g) => g.to);
const perms = cards.length === 3 ? [[0, 1, 2], [2, 1, 0], [1, 0, 2], [0, 2, 1]] : [[0, 1], [1, 0]];
for (const pm of perms) out.push({ type: 'exchange', ...seatArg(seat), give: tos.map((to, i) => ({ to, cardId: cards[pm[i]!]! })) });
// One with the two highest cards to the first targets (more variety for random play).
const hand = sortCards(s.hands[seat]!);
out.push({ type: 'exchange', ...seatArg(seat), give: tos.map((to, i) => ({ to, cardId: hand[hand.length - 1 - i]! })) });
}
return out;
case 'playing': {
if (s.trick.closingAt !== null) {
const live = mine.filter((x) => hasCards(s, x) && !s.trick.waived.includes(x));
if (live.length) out.push({ type: 'noBomb' });
for (const seat of live) for (const b of outOfTurnBombs(s, seat)) out.push({ type: 'play', cardIds: b.cards, ...seatArg(seat) });
return out;
}
for (const seat of mine) {
if (isNormalTurn(s, seat)) {
const info = turnInfo(s, seat);
const plays = info.plays;
const missing = [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2].filter((r) => !s.hands[seat]!.some((c) => rankOf(c) === r));
for (const f of plays) {
const base: PlayAction = { type: 'play', cardIds: f.cards, ...seatArg(seat) };
if (f.cards.includes(MJ)) {
out.push({ ...base, wish: null });
for (const r of missing.slice(0, 3)) out.push({ ...base, wish: r });
} else if (f.combo.type === 'dog' && s.options.mode === 'tientsin') {
for (const t of dogTargets(s, seat)) out.push({ ...base, dogTo: t });
} else out.push(base);
}
if (!leadingNow(s) && !(s.options.wishRule === 'enforce' && info.duty !== null)) out.push({ type: 'pass', ...seatArg(seat) });
} else for (const b of outOfTurnBombs(s, seat)) out.push({ type: 'play', cardIds: b.cards, ...seatArg(seat) });
}
return out;
}
case 'dragonGift':
if (ownerOf(s, ph.by) !== p) return out;
for (const to of opponents(s, ph.by)) out.push({ type: 'dragonTo', to });
return out;
case 'roundEnd':
return ph.ready[s.players.indexOf(p)] ? [] : [{ type: 'ready' }];
case 'finished':
return [];
}
}
/** Every card of the deck exactly once across hands, pending, table and won piles (test invariant). */
export const allCards = (s: TichuState): string[] => [...s.hands.flat(), ...s.pending.flat(), ...s.trick.plays.flatMap((p) => p.cards), ...s.won.flat()];
export { comboKind, comboName };