diff --git a/apps/web/src/games/help.test.ts b/apps/web/src/games/help.test.ts index 29e2479..2f275af 100644 --- a/apps/web/src/games/help.test.ts +++ b/apps/web/src/games/help.test.ts @@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti const IDS = Object.keys(GAME_UI); test('모든 게임에 도움말이 있어요', () => { - expect(IDS).toHaveLength(34); + expect(IDS).toHaveLength(35); for (const id of IDS) { const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); expect(src, id).toMatch(/\bquickStart,/); diff --git a/apps/web/src/games/registry.ts b/apps/web/src/games/registry.ts index 36dbfa7..441fe35 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -36,6 +36,7 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { liar: () => import('./liar'), 'magical-athlete': () => import('./magical-athlete'), blackjack: () => import('./blackjack'), + tichu: () => import('./tichu'), }; const cache = new Map(); diff --git a/apps/web/src/games/tichu/cards.tsx b/apps/web/src/games/tichu/cards.tsx new file mode 100644 index 0000000..189bcd0 --- /dev/null +++ b/apps/web/src/games/tichu/cards.tsx @@ -0,0 +1,132 @@ +/** + * 티츄 card art (docs/games/tichu.md §3, §12): the 52 number cards reuse the shared PlayingCard (4-colour suits: + * 옥 green ♣ · 칼 black ♠ · 탑 blue ◆ · 별 red ♥ — the names are the original's, the shapes are the site's), the four + * special cards are our own simple SVG drawings. Size comes from the parent (`--cw` CSS variable, see `.tc-c`). + */ +import type { CSSProperties } from 'react'; +import { PlayingCard } from '../../components/cards/PlayingCard'; +import { cardName } from '@bg/games/tichu/combo'; + +const SUIT_MAP: Record = { j: 'C', s: 'S', b: 'D', t: 'H' }; +const RANK_MAP: Record = { 10: 'T', 11: 'J', 12: 'Q', 13: 'K', 14: 'A' }; + +/** PlayingCard id ("TD", "AS") of a number card. */ +export const stdId = (id: string): string => { + const r = Number(id.slice(1)); + return `${RANK_MAP[r] ?? String(r)}${SUIT_MAP[id[0]!] ?? 'S'}`; +}; + +const SPECIAL: Record = { + MJ: { name: '참새', corner: '1', bg: '#fef9c3', ink: '#a16207' }, + DOG: { name: '개', corner: '개', bg: '#f5f5f4', ink: '#57534e' }, + PH: { name: '봉황', corner: '봉', bg: '#ffedd5', ink: '#c2410c' }, + DR: { name: '용', corner: '용', bg: '#dcfce7', ink: '#15803d' }, +}; + +function SpecialPicture({ id, ink }: { id: string; ink: string }) { + switch (id) { + case 'MJ': + // A small round sparrow. + return ( + + + + + + + + + ); + case 'DOG': + // A friendly dog face. + return ( + + + + + + + + + + ); + case 'PH': + // A bird of flame: three feathers and a crest. + return ( + + + + + + + + ); + default: + // A winding dragon with a pearl. + return ( + + + + + + + + + ); + } +} + +export function SpecialCard({ id }: { id: string }) { + const s = SPECIAL[id]!; + return ( + + + + + 1 ? 22 : 30} fontWeight="800" fill={s.ink} fontFamily="Pretendard Variable, sans-serif"> + {s.corner} + + + {s.name} + + + + ); +} + +/** One card face (or back with `id` null). Sized by the surrounding `.tc-c` box. */ +export function CardFace({ id }: { id: string | null }) { + if (id && SPECIAL[id]) return ; + return ; +} + +export interface TCardProps { + id: string; + selected?: boolean; + dimmed?: boolean; + highlight?: boolean; + badge?: string; + onClick?: () => void; + label?: string; + style?: CSSProperties; +} + +/** A tappable (or still) card of the 티츄 deck. */ +export function TCard({ id, selected, dimmed, highlight, badge, onClick, label, style }: TCardProps) { + const cls = `tc-c${selected ? ' sel' : ''}${dimmed ? ' dim' : ''}${highlight ? ' hi' : ''}`; + const aria = label ?? cardName(id); + if (onClick) { + return ( + + ); + } + return ( + + + {badge && {badge}} + + ); +} diff --git a/apps/web/src/games/tichu/help.test.ts b/apps/web/src/games/tichu/help.test.ts new file mode 100644 index 0000000..8f7f379 --- /dev/null +++ b/apps/web/src/games/tichu/help.test.ts @@ -0,0 +1,21 @@ +import { expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import { applyAction, setupGame, usersOf } from '../help-kit.test-util'; +import { helpNow } from './help'; + +const ids = ['A', 'B', 'C', 'D']; +const users = usersOf(ids); +const view = (s: unknown, who: string | null) => GAMES.tichu!.view(s, who) as any; + +test('티츄: 그랜드 → 교환 → 첫 트릭', () => { + let { state: s } = setupGame('tichu', 4); + expect(helpNow(view(s, 'A'), 'A', users)).toContain('그랜드 티츄'); + expect(helpNow(view(s, null), null, users)).toContain('준비 중'); + for (const p of ids) s = applyAction('tichu', s, p, { type: 'grand', call: false }); + expect(helpNow(view(s, 'A'), 'A', users)).toContain('[보내기]'); + for (const p of ids) s = applyAction('tichu', s, p, { type: 'exchange', give: view(s, p).my.exchangeSuggest }); + const lead = s.seats[s.current].owner as string; + expect(helpNow(view(s, lead), lead, users)).toContain('새 트릭을 시작해요'); + const other = ids.find((p) => p !== lead)!; + expect(helpNow(view(s, other), other, users)).toContain('기다려 주세요'); +}); diff --git a/apps/web/src/games/tichu/help.ts b/apps/web/src/games/tichu/help.ts new file mode 100644 index 0000000..bff5d48 --- /dev/null +++ b/apps/web/src/games/tichu/help.ts @@ -0,0 +1,81 @@ +/** 티츄 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { TichuView } from '@bg/games/tichu'; +import type { PublicUser } from '@bg/shared/lite'; + +const RANK: Record = { 11: 'J', 12: 'Q', 13: 'K', 14: 'A' }; +const rk = (r: number) => RANK[r] ?? String(r); +const subj = (n: string) => (n === '나' ? '내가' : `${n}이`); + +export function helpNow(v: TichuView, me: string | null, players: Record): string { + const name = (seat: number) => { + const s = v.seats[seat]; + if (!s) return '다른 사람'; + const n = players[s.owner]?.nickname ?? '다른 사람'; + return s.dummy ? `더미(${n}님)` : s.owner === me ? '나' : `${n}님`; + }; + const goal = '마주 앉은 짝꿍과 한 팀이에요. 앞 조합보다 센 같은 모양·같은 장수를 내며 손패를 먼저 털고, 점수 카드(5·10·K·용)를 모아요.'; + const my = v.my; + if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.'; + + if (v.phase === 'grand') { + if (!my) return `${v.round}라운드 준비 중이에요. 모두 첫 카드를 보고 그랜드 티츄를 할지 고르고 있어요.\n${goal}`; + if (my.grandPending) { + const lines = ['첫 카드만 보고 그랜드 티츄를 할지 골라요. 이번 라운드에 내가 1등으로 나가면 +200, 못 하면 −200이에요.']; + lines.push(my.canGrand ? '자신 없으면 [안 함]을 눌러요. 그다음 나머지 카드를 받아요.' : '딜러는 그랜드 티츄를 할 수 없어요. [안 함]을 눌러요.'); + return lines.join('\n'); + } + return '골랐어요. 다른 사람이 고르기를 기다리는 중이에요. 모두 고르면 나머지 카드를 받아요.'; + } + + if (v.phase === 'exchange') { + if (!my) return '모두 카드를 한 장씩 건넬 사람을 고르고 있어요. 다 고르면 한꺼번에 옮겨져요.'; + const lines: string[] = []; + if (my.exchangeSent === null || (v.dummy && v.dummy.exchangeSent === null)) { + const who = my.exchangeTargets.map((t) => t.label).join('·'); + lines.push(`${who}에게 카드를 한 장씩 줘요. 카드를 누르고 칸을 누르거나 [추천대로 채우기]를 누른 뒤 [보내기]를 눌러요.`); + lines.push('짝꿍에게는 좋은 카드, 상대에게는 약한 카드를 주는 게 보통이에요.'); + } else lines.push('보냈어요. 모두 보내기 전에는 [다시 고르기]로 바꿀 수 있어요.'); + if (my.canTichu) lines.push('손패가 좋으면 [티츄!]로 1등에 걸 수 있어요(+100 / −100). 첫 카드를 내기 전까지 언제든 돼요.'); + return lines.join('\n'); + } + + if (v.phase === 'roundEnd') { + const r = v.lastRound; + const head = r ? `${r.round}라운드가 끝났어요. 이번 라운드 A팀 ${r.total[0]}점, B팀 ${r.total[1]}점이에요.` : '라운드가 끝났어요.'; + return `${head}\n${me && v.ready && !v.ready[me] ? '[다음 라운드]를 누르면 새 카드를 받아요.' : '다른 사람이 준비하기를 기다리는 중이에요.'}`; + } + + if (v.phase === 'dragonGift') { + const mine = (my?.dragonTargets.length ?? 0) > 0 || (v.dummy?.dragonTargets.length ?? 0) > 0; + if (mine) return '용으로 트릭을 이겼어요! 용 트릭은 상대 팀 한 명에게 줘야 해요. 버튼 중 하나를 눌러요(보통 카드가 많은 상대에게 줘요).'; + return `${subj(v.dragonBy !== null ? name(v.dragonBy) : '다른 사람')} 용으로 트릭을 이겨서, 그 트릭을 줄 상대를 고르고 있어요.`; + } + + // playing + const top = v.trick?.plays[v.trick.plays.length - 1] ?? null; + const wish = v.wish !== null ? `\n참새 소원(${rk(v.wish)})이 걸려 있어요. 그 숫자를 가진 사람은 낼 수 있으면 꼭 넣어서 내야 해요.` : ''; + if (v.trick?.closingAt) { + const can = my?.canNoBomb || v.dummy?.canNoBomb; + return `모두 패스해서 카드를 모으는 중이에요. 이때도 폭탄을 낼 수 있어요.${can ? '\n폭탄이 없으면 [폭탄 없음]을 눌러요. 누르지 않아도 곧 모아요.' : ''}`; + } + const ctl = [my, v.dummy].find((h) => h && h.canPlay) ?? null; + if (ctl) { + const lines: string[] = []; + if (ctl.leading) lines.push(`내 차례예요${ctl.dummy ? '(더미 손패)' : ''}. 새 트릭을 시작해요. 아무 조합이나 낼 수 있어요(패스는 안 돼요).`); + else lines.push(`내 차례예요${ctl.dummy ? '(더미 손패)' : ''}. 바닥 맨 위는 ${top!.label}. 같은 모양·같은 장수로 더 센 조합을 내거나 [패스]를 눌러요.`); + lines.push('카드를 눌러 고르면 위에 조합 이름과 낼 수 있는지가 나와요. [추천] 칩을 누르면 한 번에 골라져요.'); + if (ctl.mustWish !== null) lines.push(`소원 카드(${rk(ctl.mustWish)})를 넣어서 낼 수 있으니 꼭 넣어야 해요.`); + if (ctl.canTichu) lines.push('아직 카드를 안 냈으니 [티츄!]로 1등에 걸 수 있어요.'); + if (ctl.bombs.length) lines.push('[💣 폭탄]으로 무엇이든 이길 수 있어요.'); + return lines.join('\n') + (ctl.mustWish === null ? wish : ''); + } + const cur = v.current !== null ? name(v.current) : '다른 사람'; + const table = top ? `바닥 맨 위: ${top.label}.` : `${subj(cur)} 새 트릭을 시작해요.`; + if (!my) return `${cur} 차례예요. ${table}\n${goal}${wish}`; + const seat = v.mySeat !== null ? v.seats[v.mySeat] : null; + if (seat?.place) return `${seat.place}등으로 손패를 다 털었어요! 짝꿍과 남은 사람을 지켜봐요.`; + const lines = [`${cur} 차례예요. 기다려 주세요. ${table}`]; + if (my.canBombNow) lines.push('폭탄이 있어서 차례가 아니어도 [💣 폭탄]으로 끼어들 수 있어요.'); + if (my.canTichu) lines.push('아직 카드를 안 냈으니 [티츄!]를 누를 수 있어요.'); + return lines.join('\n') + wish; +} diff --git a/apps/web/src/games/tichu/index.tsx b/apps/web/src/games/tichu/index.tsx new file mode 100644 index 0000000..672fbb1 --- /dev/null +++ b/apps/web/src/games/tichu/index.tsx @@ -0,0 +1,1382 @@ +/** 티츄 화면 (docs/games/tichu.md §9). */ +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import type { LogEntry, MySeatView, PlayView, RoundResult, SeatView, TichuOptions, TichuView } from '@bg/games/tichu'; +import { MJ, DOG, beats, cardName, classify, comboKind, comboName, includesWish, isBomb, isNumber, rankName, rankOf, sortCards, SUIT_KO, SUITS } from '@bg/games/tichu/combo'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar, Sheet } from '../../components/ui'; +import { TurnTimer, useServerNow } from '../../components/TurnTimer'; +import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard'; +import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; +import { bump, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx'; +import { fxAnim } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { CardFace, TCard } from './cards'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +type Players = Record; +const TIP_KEY = 'tc-tip-hidden'; +const SORT_KEY = 'tc-sort'; + +const nick = (players: Players, id: string) => players[id]?.nickname ?? '알 수 없음'; +const userOf = (players: Players, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; +const short = (s: string, n = 6) => (s.length > n ? `${s.slice(0, n)}…` : s); +const fmt = (n: number) => (n < 0 ? '−' : '') + String(Math.abs(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ','); +const signed = (n: number) => (n > 0 ? `+${fmt(n)}` : fmt(n)); +const teamName = (t: number) => (t === 0 ? 'A팀' : 'B팀'); +const TEAM_COLOR = ['#2563eb', '#dc2626']; + +/** "호랑이" / "나" / "더미(호랑이)" for a seat. */ +function seatName(v: TichuView, players: Players, seat: number, me: string | null): string { + const s = v.seats[seat]; + if (!s) return '?'; + if (s.dummy) return `더미(${nick(players, s.owner)})`; + return s.owner === me ? '나' : nick(players, s.owner); +} +const seatSubject = (v: TichuView, players: Players, seat: number, me: string | null) => { + const n = seatName(v, players, seat, me); + return n === '나' ? '내가' : `${n}님이`; +}; + +/** Where each seat sits on my screen (§9): me bottom, partner top, opponents left / right (seats are clockwise). */ +function positions(v: TichuView): Record { + const n = v.seats.length; + const base = v.mySeat ?? 0; + const out: Record = {}; + for (let k = 0; k < n; k++) { + const seat = (base + k) % n; + out[seat] = k === 0 ? 'bottom' : n === 4 ? (k === 1 ? 'left' : k === 2 ? 'top' : 'right') : 'row'; + } + return out; +} + +// ---------------------------------------------------------------- sounds + +const tcSfx = { + play: (n: number) => { + for (let i = 0; i < Math.min(n, 5); i++) noise(60, 0.15, i * 45, 'bandpass', 1500 + i * 150, 0.9); + tone(230, 60, 'sine', 0.09, Math.min(n - 1, 4) * 45); + }, + knock: () => { + tone(190, 70, 'sine', 0.13); + noise(35, 0.06, 0, 'lowpass', 700); + }, + bomb: () => { + noise(260, 0.3, 0, 'lowpass', 220); + tone(70, 420, 'sawtooth', 0.09, 0, { slideTo: 40 }); + }, + gong: (big: boolean) => { + tone(big ? 196 : 262, big ? 1400 : 900, 'sine', 0.2); + tone(big ? 294 : 392, big ? 1100 : 700, 'sine', 0.07, 20); + }, + dragon: () => { + tone(330, 140, 'triangle', 0.08); + tone(494, 180, 'triangle', 0.08, 120); + noise(220, 0.08, 60, 'bandpass', 800, 0.6); + }, +}; + +function shake(el: Element | null): void { + if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return; + fxAnim( + (el as HTMLElement).animate( + [{ transform: 'translateX(0)' }, { transform: 'translateX(-6px)' }, { transform: 'translateX(5px)' }, { transform: 'translateX(-3px)' }, { transform: 'translateX(0)' }], + { duration: 380, easing: 'ease-out', composite: 'add' }, + ), + ); +} + +// ---------------------------------------------------------------- styles + +const CSS = ` +.tc { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 10px; align-self: center; } +.tc-tip { display: flex; align-items: center; gap: 8px; background: var(--primary-soft); color: var(--text); border-radius: 12px; padding: 6px 6px 6px 12px; font-weight: 700; font-size: .92rem; } +.tc-tip span { flex: 1; min-width: 0; } +.tc-tip button { min-width: 40px; min-height: 40px; border: 0; border-radius: 10px; background: transparent; color: var(--text); font-size: 1.1rem; cursor: pointer; } +.tc-effect { border-radius: 12px; padding: 6px 12px; font-weight: 800; text-align: center; background: linear-gradient(90deg, #7c3aed, #db2777); color: #fff; } +.tc-ring { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 2.4fr) minmax(0, 1fr); grid-template-areas: ". top ." "left table right"; gap: 8px; align-items: center; } +.tc-ring.six { grid-template-columns: 1fr; grid-template-areas: "row" "table"; } +.tc-pos-top { grid-area: top; justify-self: center; } .tc-pos-left { grid-area: left; } .tc-pos-right { grid-area: right; } +.tc-row { grid-area: row; display: flex; gap: 6px; flex-wrap: wrap; justify-content: center; } +.tc-tablewrap { grid-area: table; min-width: 0; } +.tc-seat { position: relative; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px; border: 3px solid transparent; box-shadow: var(--shadow); + display: flex; flex-direction: column; gap: 2px; font-size: .86rem; min-width: 0; border-left: 6px solid var(--tc-team); } +.tc-seat.turn { border-color: var(--focus); border-left-color: var(--tc-team); } +.tc-seat.anim-glow { animation: anim-glow 1.4s ease-in-out infinite; } +.tc-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; } +.tc-seat .meta { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; min-height: 22px; } +.tc-count { display: inline-flex; align-items: center; gap: 3px; font-weight: 800; font-variant-numeric: tabular-nums; } +.tc-count i { display: inline-block; width: 11px; height: 15px; border-radius: 3px; background: #1e3a8a; border: 1.5px solid #93c5fd; } +.tc-badge { display: inline-block; border-radius: 999px; padding: 0 7px; font-weight: 800; font-size: .74rem; line-height: 1.6; white-space: nowrap; } +.tc-badge.t { background: #fde68a; color: #78350f; } .tc-badge.gt { background: #f59e0b; color: #fff; } +.tc-badge.place { background: var(--success); color: #fff; } .tc-badge.gray { background: var(--surface-2); color: var(--text); } +.tc-bubble { position: absolute; top: -10px; right: -4px; background: #fff; color: #1f2937; border: 2px solid #9ca3af; border-radius: 10px; padding: 0 6px; font-weight: 800; font-size: .74rem; } +.tc-table { position: relative; border-radius: 22px; background: radial-gradient(ellipse at center, rgba(255,255,255,.12), rgba(255,255,255,0) 65%), var(--felt); + border: 8px solid var(--wood); box-shadow: var(--shadow); padding: 12px; min-height: 190px; color: #fff; display: flex; flex-direction: column; gap: 8px; align-items: center; justify-content: center; } +.tc-table.closing { box-shadow: 0 0 0 4px #f59e0b, var(--shadow); } +.tc-now { font-size: 1.25rem; font-weight: 900; text-shadow: 0 1px 3px rgba(0,0,0,.5); text-align: center; line-height: 1.3; } +.tc-now small { display: block; font-size: .9rem; font-weight: 700; opacity: .92; } +.tc-wish { position: absolute; top: 8px; left: 8px; background: #fbbf24; color: #78350f; border-radius: 12px; padding: 2px 10px; font-weight: 900; font-size: 1.05rem; box-shadow: 0 2px 4px rgba(0,0,0,.3); } +.tc-dir { position: absolute; top: 8px; right: 10px; font-size: .78rem; opacity: .85; font-weight: 700; } +.tc-pile { display: flex; align-items: flex-end; gap: 12px; justify-content: center; flex-wrap: wrap; } +.tc-set { display: flex; --cw: 56px; } +.tc-set.prev { --cw: 34px; opacity: .78; } +.tc-set > .tc-c + .tc-c { margin-left: calc(var(--cw) * -0.42); } +.tc-set.many > .tc-c + .tc-c { margin-left: calc(var(--cw) * -0.62); } +.tc-c { position: relative; flex: none; width: var(--cw, 56px); padding: 0; border: 0; background: none; border-radius: 8px; transition: transform .12s ease, opacity .12s ease; color: inherit; font: inherit; } +.tc-c > span, .tc-c svg { width: 100% !important; height: auto !important; display: block; transform: none !important; } +button.tc-c { cursor: pointer; } +.tc-c.sel { transform: translateY(-10px); } +.tc-c.sel svg rect:first-of-type { stroke: #2563eb; stroke-width: 6; } +.tc-c.dim { opacity: .45; } +.tc-c.hi::after { content: ''; position: absolute; inset: -3px; border: 3px solid #f59e0b; border-radius: 10px; pointer-events: none; } +.tc-c:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } +.tc-badge-on { position: absolute; left: 50%; top: -8px; transform: translateX(-50%); background: var(--warning); color: #fff; font-size: .66rem; font-weight: 800; border-radius: 999px; padding: 0 5px; white-space: nowrap; } +.tc-hand-wrap { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } +.tc-hand { display: flex; flex-wrap: wrap; gap: 4px; padding-top: 10px; --cw: 58px; } +.tc-live { min-height: 1.5em; font-weight: 800; } +.tc-live.ok { color: var(--success); } .tc-live.no { color: var(--danger); } +.tc-chips { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 2px; } +.tc-chip { flex: none; min-height: 40px; border-radius: 999px; border: 2px solid var(--border); background: var(--surface-2); color: var(--text); font-weight: 800; padding: 0 12px; cursor: pointer; white-space: nowrap; } +.tc-chip[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); } +.tc-actions { display: flex; gap: 6px; flex-wrap: wrap; } +.tc-actions .btn { flex: 1 1 0; min-height: 52px; font-size: 1.05rem; min-width: 64px; } +.tc-panel { background: var(--surface); color: var(--text); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 8px; } +.tc-panel.hot { border: 3px solid var(--warning); } +.tc-panel h3 { margin: 0; font-size: 1.05rem; } +.tc-slots { display: grid; grid-template-columns: repeat(var(--n, 3), minmax(0, 1fr)); gap: 6px; } +.tc-slot { min-height: 104px; border: 2px dashed var(--border); border-radius: 12px; background: var(--surface-2); color: var(--text); display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 4px; cursor: pointer; font: inherit; --cw: 50px; } +.tc-slot.full { border-style: solid; border-color: var(--primary); } +.tc-slot b { font-size: .8rem; } +.tc-big { display: flex; gap: 8px; flex-wrap: wrap; } +.tc-big .btn { flex: 1 1 140px; min-height: 56px; } +.tc-mini { display: flex; flex-wrap: wrap; gap: 2px; --cw: 28px; } +.tc-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 220px; overflow: auto; } +.tc-tbl { border-collapse: collapse; width: 100%; } +.tc-tbl td, .tc-tbl th { padding: 3px 6px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: middle; } +.tc-bar { height: 8px; border-radius: 999px; background: var(--surface-2); overflow: hidden; } +.tc-bar i { display: block; height: 100%; } +.tc-wishgrid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; } +.tc-wishgrid .btn { min-height: 48px; } +@media (prefers-reduced-motion: reduce) { .tc *, .tc-seat { animation: none !important; transition: none !important; } } +@media (max-width: 719px) { + .tc { gap: 8px; } + .tc-ring { grid-template-columns: 1fr; grid-template-areas: "row" "table"; } + .tc-ring .tc-pos-top, .tc-ring .tc-pos-left, .tc-ring .tc-pos-right { display: none; } + .tc-ring .tc-row { display: grid; grid-template-columns: repeat(var(--others, 3), minmax(0, 1fr)); gap: 4px; } + .tc-row .tc-seat { padding: 3px 5px; font-size: .78rem; border-left-width: 4px; } + .tc-table { border-width: 5px; padding: 8px; min-height: 140px; } + .tc-now { font-size: 1.05rem; } + .tc-set { --cw: 44px; } + .tc-set.prev { --cw: 26px; } + .tc-hand { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 3px; --cw: auto; } + .tc-hand .tc-c { width: auto; } + .tc-hand-wrap { padding: 8px; } + .tc-actions { position: sticky; bottom: 0; background: var(--surface); padding: 4px 0 2px; z-index: 2; } + .tc-actions .btn { min-height: 48px; font-size: .98rem; min-width: 56px; padding: 0 6px; } +} +@media (min-width: 720px) { .tc-ring .tc-row.mobile-only { display: none; } } +`; + +// ---------------------------------------------------------------- seats + +function seatAria(v: TichuView, s: SeatView, players: Players, me: string | null): string { + const parts = [`${teamName(s.team)} ${seatName(v, players, s.seat, me)}`, `카드 ${s.cards}장`]; + if (s.call === 'grand') parts.push('그랜드 티츄 선언'); + if (s.call === 'tichu') parts.push('티츄 선언'); + if (s.place) parts.push(`${s.place}등으로 나감`); + if (s.passed) parts.push('패스'); + if (s.isTurn && v.phase === 'playing') parts.push(v.trick?.closingAt ? '카드 모으는 중' : '차례'); + if (s.left) parts.push('나감'); + else if (s.away) parts.push('자리 비움'); + return parts.join(', '); +} + +function SeatChip({ v, s, players, me, deadline, compact }: { v: TichuView; s: SeatView; players: Players; me: string | null; deadline: number | null; compact?: boolean }) { + const u = userOf(players, s.owner); + const turn = s.isTurn && v.phase === 'playing' && !v.trick?.closingAt; + const name = s.dummy ? `더미` : s.owner === me ? '나' : u.nickname; + const status = + v.phase === 'grand' ? (s.done ? '골랐어요' : '고르는 중') : v.phase === 'exchange' ? (s.done ? '보냈어요' : '고르는 중') : v.phase === 'roundEnd' && !s.dummy ? (s.done ? '준비 ✓' : '') : ''; + return ( +
+ {s.passed && ( + + 패스 + + )} +
+ {!compact && } + {compact ? short(name) : name} + {turn && } +
+
+ + + {s.cards} + + {s.call === 'tichu' && T} + {s.call === 'grand' && GT} + {s.place && {s.place}등} + {status && {status}} + {s.left ? 나감 : s.away && 자리 비움} + {s.wonPoints !== null && !compact && {s.wonPoints}점} +
+
+ ); +} + +// ---------------------------------------------------------------- table + +function PlaySet({ p, prev }: { p: Pick; prev?: boolean }) { + return ( + 6 ? ' many' : ''}`} aria-hidden> + {p.cards.map((c) => ( + + ))} + + ); +} + +function ClosingBar({ v }: { v: TichuView }) { + const now = useServerNow(100); + const at = v.trick?.closingAt ?? null; + if (!at) return null; + const left = Math.max(0, at - now); + return ( +
+ 💣 폭탄? 카드 모으는 중… {Math.ceil(left / 1000)}초 +
+ ); +} + +function TableArea({ v, players, me, act, pending }: { v: TichuView; players: Players; me: string | null; act: (a: unknown) => void; pending: boolean }) { + const t = v.trick; + const top = t?.plays[t.plays.length - 1] ?? null; + const prev = t ? t.plays.slice(0, -1).slice(-3) : []; + const dirText = v.options.direction === 'right' ? '차례 ↺ 오른쪽으로' : '차례 ↻ 왼쪽으로'; + const myNoBomb = (v.my?.canNoBomb || v.dummy?.canNoBomb) ?? false; + return ( +
+ {v.wish !== null && ( + + 소원 {rankName(v.wish)} + + )} + + {dirText} + + {v.phase === 'dragonGift' && v.dragonBy !== null ? ( + + ) : top ? ( + <> +
+ {top.label} + + {seatSubject(v, players, top.seat, me)} {top.outOfTurn ? '끼어들어 ' : ''}냈어요{isBomb(top.combo) ? ' 💥' : ''} + +
+
+ {prev.length > 0 && ( + p.label).join(', ')}`}> + {prev.map((p, i) => ( + + ))} + + )} + + + +
+ + {myNoBomb && ( + + )} + + ) : ( +
+ {v.current !== null ? `${seatSubject(v, players, v.current, me)} 새 트릭을 시작해요` : '잠시만요'} + {v.lastTrick ? `직전 트릭: ${seatSubject(v, players, v.lastTrick.winner, me)} ${v.lastTrick.points}점을 가져갔어요` : '참새를 가진 사람이 먼저 시작해요'} +
+ )} +
+ ); +} + +function DragonGift({ v, players, me, act, pending }: { v: TichuView; players: Players; me: string | null; act: (a: unknown) => void; pending: boolean }) { + const mine = v.my?.dragonTargets.length ? v.my : v.dummy?.dragonTargets.length ? v.dummy : null; + if (!mine) { + return ( +
+ 🐉 용으로 트릭을 이겼어요 + {seatSubject(v, players, v.dragonBy!, me)} 트릭을 줄 상대를 고르고 있어요 +
+ ); + } + return ( +
+
+ 🐉 용 트릭을 상대 한 명에게 줘요 + 용 25점을 포함한 이 트릭 전체가 그 사람 것이 돼요 +
+
+ {mine.dragonTargets.map((seat) => ( + + ))} +
+
+ ); +} + +// ---------------------------------------------------------------- my hand + +type SortMode = 'rank' | 'combo'; + +function sortedHand(hand: string[], mode: SortMode): string[] { + const h = sortCards(hand); + if (mode === 'rank') return h; + const count = (c: string) => (isNumber(c) ? h.filter((x) => isNumber(x) && rankOf(x) === rankOf(c)).length : 0); + return [...h].sort((a, b) => count(b) - count(a) || h.indexOf(a) - h.indexOf(b)); +} + +/** "풀하우스(9) · 낼 수 있어요" and whether [내기] may send it. */ +function liveCheck(v: TichuView, ctl: MySeatView, sel: string[]): { text: string; ok: boolean } { + if (sel.length === 0) return { text: ctl.canPlay ? (ctl.leading ? '낼 카드를 골라요 · 아무 조합이나 낼 수 있어요' : '더 센 같은 모양을 고르거나 패스해요') : '', ok: false }; + const top = v.trick?.plays[v.trick.plays.length - 1]?.combo ?? null; + const combo = classify(sel, top); + if (!combo) return { text: '낼 수 없는 모양이에요', ok: false }; + const name = comboName(combo, sel); + if (ctl.canPlay) { + if (combo.type === 'dog' && top) return { text: `${name} · 개는 새 트릭을 시작할 때만 내요`, ok: false }; + if (top && !beats(combo, top)) { + if (!isBomb(combo) && (combo.type !== top.type || combo.length !== top.length)) return { text: `${name} · 앞 조합(${comboKind(top)})과 모양이 달라요`, ok: false }; + return { text: `${name} · 앞 조합보다 약해요`, ok: false }; + } + if (ctl.mustWish !== null && !includesWish(sel, ctl.mustWish)) return { text: `${name} · 소원 카드(${rankName(ctl.mustWish)})를 꼭 넣어야 해요`, ok: false }; + return { text: `${name} · 낼 수 있어요`, ok: true }; + } + if (isBomb(combo) && ctl.canBombNow && (!top || beats(combo, top))) return { text: `${name} · 지금 끼어들 수 있어요`, ok: true }; + return { text: `${name} · 지금은 내 차례가 아니에요`, ok: false }; +} + +function HandPanel({ v, players, me, act, pending }: { v: TichuView; players: Players; me: string | null; act: (a: unknown) => void; pending: boolean }) { + const dealer = !!v.dummy; + const turnOnDummy = dealer && v.current === v.dummy!.seat; + const [tab, setTab] = useState<'mine' | 'dummy'>(turnOnDummy ? 'dummy' : 'mine'); + useEffect(() => { + if (dealer && v.current !== null) setTab(v.current === v.dummy!.seat ? 'dummy' : 'mine'); + }, [v.turnNo]); // eslint-disable-line react-hooks/exhaustive-deps + const ctl = (tab === 'dummy' && v.dummy) || v.my!; + const [sel, setSel] = useState([]); + const [sort, setSort] = useState(() => { + try { + return localStorage.getItem(SORT_KEY) === 'combo' ? 'combo' : 'rank'; + } catch { + return 'rank'; + } + }); + const [sheet, setSheet] = useState(null); + const handKey = ctl.hand.join(','); + useEffect(() => setSel((s) => s.filter((c) => ctl.hand.includes(c))), [handKey, tab]); // eslint-disable-line react-hooks/exhaustive-deps + const live = liveCheck(v, ctl, sel); + const top = v.trick?.plays[v.trick.plays.length - 1]?.combo ?? null; + const usable = useMemo(() => { + if (!ctl.canPlay || ctl.leading) return null; + return new Set([...ctl.suggestions.flatMap((x) => x.cards), ...(ctl.canBombNow ? ctl.bombs.flat() : [])]); + }, [ctl]); + const seatArg = dealer ? { seat: ctl.seat } : {}; + const toggle = (c: string) => { + sfx.select(); + setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c])); + }; + const send = (cards: string[], extra: Record = {}) => { + act({ type: 'play', cardIds: cards, ...seatArg, ...extra }); + setSel([]); + setSheet(null); + }; + const playNow = () => { + if (!live.ok) return; + if (sel.includes(MJ)) return setSheet('wish'); + if (sel.length === 1 && sel[0] === DOG && ctl.dogTargets.length) return setSheet('dog'); + send(sel); + }; + const legalBombs = ctl.bombs.filter((b) => { + const c = classify(b, top); + return !!c && (!top || beats(c, top)); + }); + const receivedFrom = new Map(ctl.received.map((r) => [r.cardId, r.from])); + const hand = sortedHand(ctl.hand, sort); + const title = tab === 'dummy' ? `더미 손패 ${ctl.hand.length}장` : `내 카드 ${ctl.hand.length}장`; + const myTurn = ctl.canPlay; + return ( +
+
+ {title} +
+ {dealer && ( +
+ + +
+ )} + +
+
+
+ {hand.map((c) => { + const from = receivedFrom.get(c); + return ( + toggle(c)} + label={`${cardName(c)}${from !== undefined ? `, ${seatName(v, players, from, me)}에게 받음` : ''}`} + /> + ); + })} + {ctl.hand.length === 0 && 손패를 다 털었어요! 남은 사람을 지켜봐요.} +
+ {ctl.mustWish !== null && 소원 카드({rankName(ctl.mustWish)})를 꼭 넣어야 해요} +
+ {live.text} +
+ {myTurn && ctl.suggestions.length > 0 && ( +
+ + 추천 + + {ctl.suggestions.map((sg) => ( + + ))} +
+ )} +
+ + {myTurn && ( + + )} + {ctl.canTichu && ( + + )} + {ctl.bombs.length > 0 && ( + + )} +
+ {sheet === 'wish' && ( + setSheet(null)} label="참새 소원 고르기"> +

소원을 불러요

+

부른 숫자를 가진 사람은 낼 수 있으면 그 숫자를 꼭 내야 해요.

+
+ {[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].map((r) => ( + + ))} +
+ +
+ )} + {sheet === 'dog' && ( + setSheet(null)} label="개로 선을 넘길 짝꿍"> +

누구에게 선을 넘길까요?

+
+ {ctl.dogTargets.map((seat) => ( + + ))} +
+
+ )} + {sheet === 'bomb' && ( + setSheet(null)} label="폭탄 고르기"> +

💣 폭탄 내기

+
+ {legalBombs.map((b) => ( + + ))} +
+
+ )} +
+ ); +} + +// ---------------------------------------------------------------- grand / exchange / round end + +function GrandPanel({ v, act, pending }: { v: TichuView; act: (a: unknown) => void; pending: boolean }) { + const my = v.my; + const done = v.seats.filter((s) => s.done).length; + const n = v.mode === 'tientsin' ? 6 : 8; + return ( +
+

+ 첫 {n}장 · 그랜드 티츄? ({done}/{v.seats.length}) +

+ 나머지 카드를 받기 전에 "이번 라운드 1등으로 나간다"에 크게 걸 수 있어요. 성공 +200, 실패 −200. + {my && ( +
+ {my.hand.map((c) => ( + + ))} +
+ )} + {my?.grandPending ? ( +
+ {my.canGrand && ( + + )} + +
+ ) : ( + {v.mode === 'threechu' && v.dealer === v.me ? '딜러는 그랜드 티츄를 할 수 없어요. ' : ''}다른 사람이 고르기를 기다리는 중이에요… + )} +
+ ); +} + +function ExchangeFor({ v, players, me, ctl, act, pending, seatArg }: { v: TichuView; players: Players; me: string | null; ctl: MySeatView; act: (a: unknown) => void; pending: boolean; seatArg: object }) { + const [editing, setEditing] = useState(ctl.exchangeSent === null); + const [slots, setSlots] = useState>(() => Object.fromEntries((ctl.exchangeSent ?? []).map((g) => [g.to, g.cardId]))); + const [picked, setPicked] = useState(null); + useEffect(() => { + if (ctl.exchangeSent === null) setEditing(true); + }, [ctl.exchangeSent === null]); // eslint-disable-line react-hooks/exhaustive-deps + const used = new Set(Object.values(slots)); + const full = ctl.exchangeTargets.every((t) => slots[t.seat]); + const tapSlot = (seat: number) => { + if (!editing) return; + if (picked) { + const next = Object.fromEntries(Object.entries(slots).filter(([, c]) => c !== picked)); + setSlots({ ...next, [seat]: picked }); + setPicked(null); + sfx.select(); + } else if (slots[seat]) { + const next = { ...slots }; + delete next[seat]; + setSlots(next); + } + }; + const fill = () => { + setSlots(Object.fromEntries(ctl.exchangeSuggest.map((g) => [g.to, g.cardId]))); + setPicked(null); + }; + const sendIt = () => { + act({ type: 'exchange', ...seatArg, give: ctl.exchangeTargets.map((t) => ({ to: t.seat, cardId: slots[t.seat]! })) }); + setEditing(false); + }; + return ( +
+
+ {ctl.exchangeTargets.map((t) => ( + + ))} +
+
+ {ctl.hand.map((c) => ( + setPicked(picked === c ? null : c) : undefined} /> + ))} +
+ {editing ? ( +
+ + +
+ ) : ( +
+ + 보냈어요 · 모두 보낼 때까지 바꿀 수 있어요 + + +
+ )} +
+ ); +} + +function ExchangePanel({ v, players, me, act, pending }: { v: TichuView; players: Players; me: string | null; act: (a: unknown) => void; pending: boolean }) { + const done = v.seats.filter((s) => s.done).length; + const my = v.my; + return ( +
+

+ 카드 교환 ({done}/{v.seats.length}) +

+ 카드를 누르고 칸을 눌러 한 사람에게 한 장씩 놓아요. 짝꿍에게는 좋은 카드, 상대에게는 약한 카드를 주는 게 보통이에요. + {my && } + {v.dummy && ( + <> + 더미 손패에서 건넬 카드 + + + )} + {my?.canTichu && ( + + )} + {!my && 모두 카드를 고르고 있어요.} +
+ ); +} + +function RoundTable({ v, r, players, me }: { v: TichuView; r: RoundResult; players: Players; me: string | null }) { + const name = (seat: number) => (r.seatOwners[seat] === null ? '더미' : r.seatOwners[seat] === me ? '나' : nick(players, r.seatOwners[seat]!)); + const kindText = r.kind === 'double' ? '원투!' : r.kind === 'triple' ? '트리플 빅토리!' : r.kind === 'penalty' ? '소원 위반 → 상대 원투' : ''; + return ( +
+ + 나간 순서: {r.out.map((seat, i) => `${i + 1}. ${name(seat)}`).join(' · ')} + {r.lastSeat !== null ? ` · 꼴찌 ${name(r.lastSeat)}` : ''} + + {kindText && {kindText}} + {r.handover && ( + + 꼴찌 손패 {r.handover.hand}점 → 상대 팀, 꼴찌가 딴 카드 {r.handover.won}점 → {v.seats.length === 6 ? '상대 팀' : '1등'} + + )} + {r.effect && r.effect !== 'plain' && 파티 효과: {EFFECT_KO[r.effect]}} + + + + + + + + + + + + {[0, 1].map((t) => ( + + + + + + + + ))} + +
팀카드보너스티츄합계
+ {teamName(t)} {r.teams[t]!.map((p) => (p === me ? '나' : nick(players, p))).join('·')} + {r.cardPoints[t]}{r.bonus[t]}{r.callPoints[t]} + {signed(r.total[t]!)} +
+ {r.calls.length > 0 && ( + + {r.calls.map((c) => `${name(c.seat)} ${c.call === 'grand' ? '그랜드 티츄' : '티츄'} ${c.success ? '성공' : '실패'}(${signed(c.points)})`).join(' · ')} + + )} +
+ ); +} + +function RoundEndPanel({ v, players, me, act, pending }: { v: TichuView; players: Players; me: string | null; act: (a: unknown) => void; pending: boolean }) { + const r = v.lastRound; + if (!r) return null; + const ready = me ? v.ready?.[me] : true; + const n = v.ready ? Object.values(v.ready).filter(Boolean).length : 0; + return ( +
+

{r.round}라운드 결과

+ + + {me && v.ready && ( + + )} +
+ ); +} + +function Standings({ v, players, me }: { v: TichuView; players: Players; me: string | null }) { + const target = v.mode === 'threechu' ? null : v.options.targetScore; + const max = Math.max(target ?? 1, ...v.scores.map((x) => Math.abs(x)), 1); + return ( +
+ {v.scores.map((sc, i) => { + const owners = v.scoreOwners[i]!; + const team = v.scoreOwners.length === 2; + const label = team ? `${teamName(i)} ${owners.map((p) => (p === me ? '나' : short(nick(players, p)))).join('·')}` : owners[0] === me ? '나' : nick(players, owners[0]!); + return ( +
+
+ {label} + {fmt(sc)}점 +
+
+ +
+
+ ); + })} + {target ? `목표 ${fmt(target)}점` : `${v.options.threechuHands}판 중 ${v.round}판째`} +
+ ); +} + +// ---------------------------------------------------------------- log + +const EFFECT_KO: Record = { + double: '두 배 판 — 이번 라운드 점수가 모두 2배', + negative: '점수 뒤집기 — 카드 점수 부호가 반대(5 → −5, 용 −25, 봉황 +25)', + rotate: '손패 돌리기 — 교환이 끝나면 손패가 통째로 다음 사람에게', + plain: '평범한 판 — 효과 없음', +}; + +function logText(e: LogEntry, v: TichuView, players: Players, me: string | null): string { + const n = (seat: number) => seatName(v, players, seat, me); + switch (e.t) { + case 'play': + return `${n(e.seat)}: ${e.label}${e.outOfTurn ? ' (끼어들기)' : ''}`; + case 'pass': + return `${n(e.seat)}: 패스`; + case 'dog': + return `${n(e.seat)}: 개 → ${n(e.to)}에게 선`; + case 'trick': + return `${seatSubject(v, players, e.seat, me)} 트릭을 가져갔어요 (${e.points}점)`; + case 'dragon': + return `🐉 ${seatSubject(v, players, e.seat, me)} 용 트릭(${e.points}점)을 ${n(e.to)}에게 줬어요`; + case 'wish': + return `${n(e.seat)}의 참새 소원: ${rankName(e.rank)}`; + case 'wishDone': + return `소원 카드(${rankName(e.rank)})가 나와서 소원이 풀렸어요`; + case 'call': + return `${n(e.seat)}: ${e.call === 'grand' ? '그랜드 티츄!' : '티츄!'}`; + case 'out': + return `${seatSubject(v, players, e.seat, me)} ${e.place}등으로 나갔어요`; + case 'exchanged': + return e.rotated ? '카드 교환 끝 · 손패가 다음 사람에게 넘어갔어요' : '카드 교환이 끝났어요'; + case 'round': + return `${e.round}라운드 끝: A팀 ${signed(e.total[0]!)} · B팀 ${signed(e.total[1]!)}${e.kind === 'double' ? ' (원투)' : e.kind === 'triple' ? ' (트리플 빅토리)' : ''}`; + case 'deal': + return `${e.round}라운드를 시작해요${e.effect ? ` · 파티 효과: ${EFFECT_KO[e.effect]!.split(' — ')[0]}` : ''}`; + case 'penalty': + return `${seatSubject(v, players, e.seat, me)} 소원(${rankName(e.rank)})을 어겼어요 → 상대 팀 원투`; + case 'timeout': + return `${nick(players, e.p)}님 시간이 다 되어 자동으로 진행했어요`; + case 'left': + return `${nick(players, e.p)}님이 나갔어요. 자동으로 진행해요`; + } +} + +// ---------------------------------------------------------------- board + +function Tip() { + const [hidden, setHidden] = useState(() => { + try { + return localStorage.getItem(TIP_KEY) === '1'; + } catch { + return false; + } + }); + if (hidden) return null; + return ( +
+ 💡 같은 모양·같은 장수로 더 세게! 폭탄은 언제든 끼어들 수 있어요 + +
+ ); +} + +function useTichuFx(v: TichuView, me: string | null, players: Players, showBanner: ReturnType[1]) { + const seatFx = (seat: number) => seatEl(`seat-${seat}`) ?? (v.seats[seat]?.owner === me ? fxEl('tc-hand') : null); + useNewEntries( + v.log, + (e) => `${e.seq}-${e.t}-${'seat' in e ? e.seat : ''}`, + (fresh) => { + for (const e of fresh) { + switch (e.t) { + case 'play': + if (e.bomb) { + tcSfx.bomb(); + shake(fxEl('tc-center')); + haptic([40, 30, 80]); + } else tcSfx.play(e.cards.length); + break; + case 'pass': + tcSfx.knock(); + break; + case 'call': + tcSfx.gong(e.call === 'grand'); + showBanner(e.call === 'grand' ? '그랜드 티츄!' : '티츄!', e.call === 'grand' ? 'red' : 'gold', seatName(v, players, e.seat, me)); + bump(seatFx(e.seat)); + break; + case 'out': + if (e.place === 1) sfx.good(); + bump(seatFx(e.seat)); + break; + case 'trick': + flyGhost(fxEl('tc-center'), seatFx(e.seat), { count: 3, gap: 60, ms: 420 }); + sfx.whoosh(); + break; + case 'dragon': + flyGhost(fxEl('tc-center'), seatFx(e.to), { count: 4, gap: 60, ms: 520 }); + tcSfx.dragon(); + break; + case 'dog': + sfx.pop(); + break; + case 'round': + if (e.kind === 'double' || e.kind === 'triple') { + showBanner(e.kind === 'double' ? '원투!' : '트리플 빅토리!', 'gold'); + sfx.fanfare(); + } + break; + case 'deal': + sfx.shuffle(); + if (e.effect) showBanner('파티 효과', 'blue', EFFECT_KO[e.effect]!.split(' — ')[0]); + break; + case 'penalty': + sfx.alarm(); + showBanner('소원 위반!', 'red', '상대 팀 원투로 처리해요'); + break; + case 'exchanged': + sfx.deal(3, 90); + break; + default: + break; + } + } + }, + ); +} + +function TichuBoard({ view: v, me, players, act, pending, deadline }: BoardProps) { + const [banner, showBanner] = useBanner(); + const mine = isMyTurn(v, me); + const prevMine = useRef(false); + useTichuFx(v, me, players, showBanner); + useEffect(() => { + if (mine && !prevMine.current) { + haptic(40); + sounds.myTurn(); + } + prevMine.current = mine; + }, [mine]); + const pos = positions(v); + const base = v.mySeat ?? 0; + // Left, partner (top), right — the order around the table from my seat. + const others = v.seats.filter((s) => pos[s.seat] !== 'bottom').sort((a, b) => ((a.seat - base + v.seats.length) % v.seats.length) - ((b.seat - base + v.seats.length) % v.seats.length)); + const four = v.seats.length === 4; + const playingish = v.phase === 'playing' || v.phase === 'dragonGift'; + return ( +
+ + + {v.effect && v.phase !== 'finished' &&
🎉 파티 효과 · {EFFECT_KO[v.effect]}
} +
+ {four && + others.map((s) => ( +
+ +
+ ))} +
+ {others.map((s) => ( + + ))} +
+
+ {playingish && } + {v.phase === 'grand' && } + {v.phase === 'exchange' && } + {v.phase === 'roundEnd' && } + {v.phase === 'finished' && v.result && ( +
+

게임이 끝났어요

+ {v.result.summary} + {v.lastRound && } + +
+ )} +
+
+ {v.mySeat !== null && v.seats[v.mySeat] && (playingish || v.phase === 'roundEnd') && ( +
+
+ +
+
+ )} + {playingish && v.my && } + {playingish && v.seats.some((s) => s.dummy && s.openHand) && !v.dummy && ( +
+ 더미 손패(모두 공개) +
+ {v.seats.find((s) => s.dummy)!.openHand!.map((c) => ( + + ))} +
+
+ )} + {banner} +
+ ); +} + +// ---------------------------------------------------------------- side + +function PlayedTable({ cards }: { cards: string[] }) { + const has = new Set(cards); + return ( + + + {SUITS.map((s) => ( + + + + + ))} + + + + + +
{SUIT_KO[s]} + {Array.from({ length: 13 }, (_, i) => i + 2).map((r) => ( + + {rankName(r)} + + ))} +
특수 + {['MJ', 'DOG', 'PH', 'DR'].map((c) => ( + + {cardName(c)} + + ))} +
+ ); +} + +function TichuSide({ view: v, me, players, deadline }: BoardProps) { + const phaseKo = { grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase]; + const [showLast, setShowLast] = useState(false); + return ( + <> + +
+
+ + 티츄 · {v.round}라운드 · {phaseKo} + + {v.phase !== 'finished' && } +
+ {optionsSummary(v.options)} + +
+ {v.history.length > 0 && ( +
+ 라운드 기록 + + + + + {v.scoreOwners.map((o, i) => ( + + ))} + + + + {v.history.map((h) => ( + + + {v.scoreOwners.length === 2 ? ( + h.total.map((t, i) => ) + ) : ( + h.gains.map((g, i) => ) + )} + + ))} + +
R + {v.scoreOwners.length === 2 ? teamName(i) : o[0] === me ? '나' : short(nick(players, o[0]!), 4)} +
+ {h.round} + {h.kind === 'double' ? ' 원투' : h.kind === 'triple' ? ' 3연' : h.kind === 'penalty' ? ' 위반' : ''} + {signed(t)}{signed(g)}
+
+ )} + {v.lastTrick && ( +
+ + {showLast && ( +
+ + {seatSubject(v, players, v.lastTrick.winner, me)} {v.lastTrick.points}점을 가져갔어요 + + {v.lastTrick.plays.map((p, i) => ( +
+ + {short(seatName(v, players, p.seat, me))} + + + {p.cards.map((c) => ( + + ))} + +
+ ))} +
+ )} +
+ )} + {v.playedCards && ( +
+ 나온 카드 (흐린 것이 나온 카드) + + {v.teamWon && ( + + 지금까지 딴 점수 · A팀 {v.teamWon[0]}점 · B팀 {v.teamWon[1]}점 + + )} +
+ )} + {v.log.length > 0 && ( +
+ 기록 +
    + {[...v.log].reverse().map((e, i) => ( +
  1. + {logText(e, v, players, me)} +
  2. + ))} +
+
+ )} + + ); +} + +// ---------------------------------------------------------------- status + +function isMyTurn(v: TichuView, me: string | null): boolean { + if (!me || v.me !== me) return false; + const hands = [v.my, v.dummy].filter((x): x is MySeatView => !!x); + switch (v.phase) { + case 'grand': + return !!v.my?.grandPending; + case 'exchange': + return hands.some((h) => h.exchangeSent === null); + case 'playing': + return hands.some((h) => h.canPlay || h.canNoBomb); + case 'dragonGift': + return hands.some((h) => h.dragonTargets.length > 0); + case 'roundEnd': + return !!v.ready && !v.ready[me]; + default: + return false; + } +} + +function statusText(v: TichuView, me: string | null, players: Players): string { + switch (v.phase) { + case 'finished': + return v.result?.summary ?? '게임이 끝났어요'; + case 'grand': + return v.my?.grandPending ? '내 차례예요 · 그랜드 티츄를 할지 골라요' : '그랜드 티츄 고르기를 기다려요'; + case 'exchange': + return isMyTurn(v, me) ? '내 차례예요 · 건넬 카드를 골라요' : '카드 교환을 기다려요'; + case 'dragonGift': + return isMyTurn(v, me) ? '내 차례예요 · 용 트릭을 줄 상대를 골라요' : '용 트릭을 줄 상대를 고르는 중이에요'; + case 'roundEnd': + return isMyTurn(v, me) ? `${v.round}라운드 결과 · [다음 라운드]를 눌러요` : `${v.round}라운드 결과`; + case 'playing': { + if (v.trick?.closingAt) return '카드 모으는 중 · 폭탄?'; + const cur = v.current; + if (cur === null) return '잠시만 기다려 주세요'; + const mineSeat = [v.my, v.dummy].find((h) => h?.seat === cur); + if (mineSeat) return `내 차례예요${mineSeat.dummy ? ' (더미)' : ''}${mineSeat.leading ? ' · 새 트릭을 시작해요' : ''}`; + return `${seatName(v, players, cur, me)}${v.seats[cur]?.dummy ? '' : '님'} 차례예요`; + } + } +} + +// ---------------------------------------------------------------- options + +function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} + +function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) { + return ( +
+ {label} + {children} + {help && {help}} +
+ ); +} + +const onOff: [boolean, string][] = [ + [true, '켜기'], + [false, '끄기'], +]; + +const MODE_HELP: Record = { + team: '4명, 마주 앉은 사람과 한 팀(원작).', + individual: '4명, 라운드마다 짝꿍이 바뀌고 점수는 각자 받아요. 친구끼리 재미용이에요.', + threechu: '3명. 딜러가 공개된 더미 손패와 한 팀이 되어 두 손을 쳐요. 정해진 판 수로 끝나요.', + tientsin: '6명, 3:3 팀전. 10·10·9·9·9·9장, 원투 대신 트리플 빅토리(300).', +}; + +function Options({ value: o, onChange }: OptionsProps) { + const [more, setMore] = useState(false); + const set = (patch: Partial) => onChange({ ...o, ...patch }); + return ( +
+ + set({ mode })} /> + + {o.mode === 'threechu' ? ( + + set({ threechuHands })} /> + + ) : ( + + set({ targetScore })} /> + + )} + + set({ grandTichu })} /> + + + set({ turnSeconds })} /> + + + {more && ( + <> + + set({ direction })} /> + + + set({ bombTiming })} /> + + {o.bombTiming === 'anytime' && ( + + set({ bombWindowSeconds })} /> + + )} + + set({ wishRule })} /> + + + set({ trickHistory })} /> + + + set({ party })} /> + + + set({ exchangeSeconds })} /> + + + )} +
+ ); +} + +function optionsSummary(o: TichuOptions): string { + const mode = { team: '4인 팀전', individual: '4인 개인전', threechu: '3인', tientsin: '6인 팀전' }[o.mode]; + const parts = [mode, o.mode === 'threechu' ? `${o.threechuHands}판` : `${fmt(o.targetScore)}점`]; + if (!o.grandTichu) parts.push('그랜드 없음'); + if (o.direction === 'left') parts.push('왼쪽 차례'); + if (o.bombTiming === 'ownTurn') parts.push('폭탄은 자기 차례에만'); + if (o.wishRule === 'penalty') parts.push('소원 위반 패널티'); + if (o.trickHistory === 'all') parts.push('나온 카드 보기'); + if (o.party && (o.mode === 'team' || o.mode === 'individual')) parts.push('파티 모드'); + parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`); + return parts.join(' · '); +} + +// ---------------------------------------------------------------- rules + +function Ex({ ids }: { ids: string }) { + return ( + + {ids.split(' ').map((c) => ( + + + + ))} + + ); +} + +function Rules({ options }: { options?: TichuOptions }) { + const o = options; + const rows: [string, string, string][] = [ + ['싱글', '카드 1장', 'b7'], + ['페어', '같은 숫자 2장', 'j8 s8'], + ['연속 페어', '이어지는 페어 2쌍 이상', 'j5 s5 j6 s6'], + ['트리플', '같은 숫자 3장', 'j9 s9 b9'], + ['풀하우스', '트리플 + 페어 (트리플 숫자로 비교)', 'j6 s6 b6 j2 s2'], + ['스트레이트', '이어지는 5장 이상 (무늬 상관없음)', 'j4 s5 b6 t7 j8'], + ['폭탄', '같은 숫자 4장, 또는 같은 무늬로 이어지는 5장 이상', 's9 j9 b9 t9'], + ]; + return ( +
+

+ 마주 앉은 사람과 한 팀이에요. 앞사람보다 센 같은 모양·같은 장수를 내면서 손패를 먼저 털고, 트릭에서 점수 카드(5 = 5점, 10·K = 10점, 용 +25, 봉황 −25)를 모아요. + 한 라운드의 카드 점수는 모두 합해 100점이에요. 목표 점수에 먼저 닿는 팀이 이겨요. +

+ + + {rows.map(([n, d, ex]) => ( + + + + + + ))} + +
{n}{d} + +
+

+ 트릭을 시작하는 사람은 아무 조합이나 내요. 다음 사람부터 같은 종류·같은 장수로 더 센 조합을 내거나 패스해요. 패스해도 차례가 다시 오면 낼 수 있어요. 맨 위 조합을 낸 사람 말고 모두 패스하면 그 사람이 + 트릭을 가져가고 새로 시작해요. 폭탄은 무엇이든 이기고{o?.bombTiming === 'ownTurn' ? ', 이 방에서는 자기 차례에만 낼 수 있어요.' : ', 차례가 아니어도 끼어들 수 있어요. 모두 패스해도 잠깐("카드 모으는 중") 기다리니 그사이에도 낼 수 있어요.'} +

+ + + + + + + + + + + + + + + + + + + +
+ 참새(1) 가진 사람이 첫 트릭을 시작해요. 낼 때 숫자 하나를 소원으로 부를 수 있어요. 그 숫자를 가진 사람은 낼 수 있으면 꼭 넣어서 내야 해요 + {o?.wishRule === 'penalty' ? '(이 방은 화면이 막지 않고, 어기면 상대 팀 원투로 처리해요).' : '(화면이 알려 주고 막아 줘요).'} +
+ 개 트릭을 시작할 때만 낼 수 있고, 선을 짝꿍에게 넘겨요. +
+ 봉황 아무 숫자 1장을 대신해요(폭탄에는 못 써요). 혼자 내면 앞 싱글보다 0.5 높아요. 용 위에는 못 내요. −25점. +
+ 용 가장 센 싱글(폭탄만 이겨요). 용으로 트릭을 이기면 그 트릭을 상대 한 명에게 줘야 해요. +25점. +
+

+ 티츄 선언: 첫 카드를 내기 전에 [티츄!]를 누르면 "1등으로 나간다"에 걸어요(성공 +100, 실패 −100). + {o?.grandTichu === false ? '' : ' 첫 8장만 보고 하는 그랜드 티츄는 ±200이에요.'} 짝꿍이 1등이어도 선언한 본인이 아니면 실패예요. +

+

+ 14장을 받으면 카드 교환: 왼쪽 상대·짝꿍·오른쪽 상대에게 1장씩 줘요. 같은 팀 두 사람이 1·2등으로 나가면 원투(200점, 카드 점수 없음). 그 밖에는 3명이 나가면 끝나고, + 꼴찌는 남은 손패를 상대 팀에, 딴 카드를 1등에게 줘요. +

+ {o?.mode === 'individual' &&

개인전: 라운드마다 짝꿍이 바뀌고, 그 라운드 팀 점수를 두 사람이 각자 똑같이 받아요.

} + {o?.mode === 'threechu' &&

3인: 딜러가 맞은편 더미와 한 팀이 되어 두 손을 쳐요. 교환은 상대에게만 2장, 교환 뒤 더미 손패는 모두에게 보여요. 더미는 소원을 지키지 않아도 돼요.

} + {o?.mode === 'tientsin' && ( +

6인: 3:3 팀전, 짝꿍 둘에게 1장씩 교환해요. 앞 두 사람 10장, 나머지 9장(원작에 장수가 없어 이 사이트가 정한 방식). 원투 대신 트리플 빅토리 300점. 꼴찌는 손패와 딴 카드를 모두 상대 팀에, 5등은 딴 카드를 1등에게 줘요.

+ )} + {o?.party &&

파티 모드(공식 아님): 라운드마다 두 배 판·점수 뒤집기·손패 돌리기·평범한 판 중 하나가 나와요. 같은 효과가 두 번 이어지지 않아요.

} +

짝꿍끼리 채팅으로 손패를 알려 주면 안 돼요. "카드 모으는 중" 기다리는 시간과 지난 카드 보기, 파티 모드 효과는 이 사이트가 정한 방식이에요(공식 아님). 점수는 이 방 안에서만 쓰는 표시용이에요.

+

{PLAYING_CARD_CREDIT} 참새·개·봉황·용 그림은 이 사이트가 직접 그렸어요.

+
+ ); +} + +const ui: GameUI = { + Board: TichuBoard, + Side: TichuSide, + statusText, + isMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/tichu/quick.tsx b/apps/web/src/games/tichu/quick.tsx new file mode 100644 index 0000000..83a1d46 --- /dev/null +++ b/apps/web/src/games/tichu/quick.tsx @@ -0,0 +1,61 @@ +/** 티츄 30초 규칙 요약 (docs/07 §5). */ +import type { QuickCard } from '../types'; + +function Card({ x, y, label, color = '#111827', bg = '#fffef9' }: { x: number; y: number; label: string; color?: string; bg?: string }) { + return ( + + + 1 ? 13 : 18} fontWeight={900} fill={color}> + {label} + + + ); +} + +export const quickStart: QuickCard[] = [ + { + pic: ( + + + 짝꿍 + 나 + 상대 + 상대 + + + ), + alt: '네 사람이 둘러앉고 마주 앉은 나와 짝꿍이 한 팀', + title: '마주 앉은 짝꿍과 한 팀', + text: '4명이 2:2로 해요. 손패를 먼저 털고 트릭에서 5·10·K·용 점수 카드를 모아 목표 점수에 먼저 닿는 팀이 이겨요.', + }, + { + pic: ( + + + + → + + + 8 페어 + 더 센 페어 + + ), + alt: '8 페어 위에 J 페어를 내는 모습', + title: '같은 모양으로 더 세게', + text: '싱글·페어·트리플·풀하우스·스트레이트·연속 페어 중 앞과 같은 모양·같은 장수로 더 센 것을 내거나 패스해요. 폭탄은 언제든 이겨요.', + }, + { + pic: ( + + + + + + 티츄! = 1등에 +100 + + ), + alt: '특수 카드 참새, 개, 봉황, 용과 티츄 선언', + title: '특수 카드와 티츄!', + text: '참새는 소원을 부르고, 개는 선을 짝꿍에게, 봉황은 아무 숫자, 용은 가장 센 싱글이에요. 첫 카드 전 [티츄!]로 1등에 걸 수 있어요.', + }, +]; diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index 13dc3e4..57ad20e 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -33,6 +33,7 @@ export const GAME_ICON: Record = { liar: '🤥', 'magical-athlete': '🏃', blackjack: '🂡', + tichu: '🐉', }; /** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */ @@ -41,6 +42,6 @@ export const UPCOMING: string[] = []; /** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] }, - { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] }, + { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'tichu'] }, { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 9862aaf..50adc89 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -47,6 +47,7 @@ | `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 | | `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 | | `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 | +| `tichu` | 티츄 | 4 (변형 3·6) | 2026-10 새 게임 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/tichu.md b/docs/games/tichu.md index b725729..1d47d4a 100644 --- a/docs/games/tichu.md +++ b/docs/games/tichu.md @@ -27,7 +27,8 @@ | `exchangeSeconds` | 카드 교환 제한 시간 | 30 / 45 / 60 / 무제한(`null`) | 45 | 사이트 | - 인원(`playersFor`): `team`·`individual` 4명, `threechu` 3명, `tientsin` 6명. 컴퓨터로 빈자리를 채울 수 있다. -- 구현 순서 제안: 1단계 = `team` + `targetScore`·`grandTichu`·`direction`·`bombTiming`·`bombWindowSeconds`·`trickHistory`·시간 옵션, `wishRule=enforce`. 2단계 = `individual`, `threechu`, `tientsin`, `wishRule=penalty`, `party`. 2단계 옵션은 구현 전까지 스키마에 넣지 않는다. +- 구현(2026-10-15): 표의 옵션을 모두 구현했다(나중으로 미룬 것 없음). `party`는 `team`·`individual`에서만 효과가 있고 다른 모드에서는 무시한다. +- 구현 순서 제안(참고): 1단계 = `team` + `targetScore`·`grandTichu`·`direction`·`bombTiming`·`bombWindowSeconds`·`trickHistory`·시간 옵션, `wishRule=enforce`. 2단계 = `individual`, `threechu`, `tientsin`, `wishRule=penalty`, `party`. 2단계 옵션은 구현 전까지 스키마에 넣지 않는다. ## 3. 구성물 - 56장. @@ -45,7 +46,7 @@ | 나머지 | 0점 | - 한 라운드 카드 점수 합은 언제나 100점이다(5×4 + 10×4 + 10×4 + 25 − 25). -- 엔진 카드 ID: 숫자 카드 `<무늬><숫자>`(무늬 `j`옥·`s`칼·`p`탑·`t`별, 숫자 2~14, J=11, Q=12, K=13, A=14). 예: `j2`, `t10`, `s14`. 특수 카드 `MJ`(참새), `DOG`(개), `PH`(봉황), `DR`(용). +- 엔진 카드 ID: 숫자 카드 `<무늬><숫자>`(무늬 `j`옥·`s`칼·`b`탑·`t`별 — 탑을 `p`로 하면 `p2` 같은 테스트 플레이어 id와 겹쳐 정보 유출 검사가 헛걸려서 `b`(파랑)로 정함, 숫자 2~14, J=11, Q=12, K=13, A=14). 예: `j2`, `t10`, `s14`. 특수 카드 `MJ`(참새), `DOG`(개), `PH`(봉황), `DR`(용). ## 4. 준비(셋업) 기본(`team`) 기준. 다른 모드의 차이는 §5.9. @@ -462,3 +463,17 @@ interface TichuFinal { - 6인전 손패 장수는 원작 룰북에 없다. 공개된 플레이 후기(9장, 2명 10장)를 따랐고, 규칙 화면에 "원작에 장수가 없어 이 사이트가 정한 방식"이라고 적는다. - 파티 모드 효과와 `trickHistory`, `bombWindowSeconds`는 이 사이트가 정한 것이다. 규칙 화면에 "공식 아님" 표시를 붙인다. - 돈, 칩을 쓰지 않는다. 점수는 방 안 결과 표시용이다. + +## 13. 구현 메모 (2026-10-15) +- 규칙 모듈 `packages/games/src/tichu/`: `combo.ts`(판정·조합 찾기, 화면도 `@bg/games/tichu/combo`로 같이 씀), `index.ts`(상태 기계), `bot.ts`. +- 정한 것(문서에 없거나 애매했던 부분) + - 자리는 시계 방향 번호, 화면에서 내 왼쪽 = 자리+1. 교환 칸 이름(왼쪽 상대·짝꿍·오른쪽 상대)은 화면 자리 기준이라 `direction`과 상관없이 같다. 차례 방향은 바닥 화살표로 보여 준다. + - 3인: 딜러 자리 0, 더미는 맞은편 자리 2. 딜러는 차례 방향으로 다음 사람에게 넘어간다. 딜러와 더미 자리는 그랜드 단계를 자동으로 "안 함" 처리한다. 딜러의 행동에는 `seat`를 늘 붙인다. + - 6인 소원 위반 패널티: 원투가 없으므로 상대 팀 300점(트리플 빅토리와 같게). + - 그랜드·스몰 티츄와 용 주기의 마감은 `turnSeconds`를 따르고(무제한이면 없음), 교환은 `exchangeSeconds`, 라운드 결과는 10초. + - "카드 모으는 중"에 [폭탄 없음]을 누른 자리는 그 창이 끝날 때까지 폭탄을 낼 수 없다(누르면 확정). 이 창의 시간 초과는 자리 비움 횟수에 넣지 않는다. + - 모두 방을 나가면 게임을 `abandoned`로 끝낸다. + - 결과 요약은 이름 대신 "A팀(0·2번 자리)/B팀"으로 쓴다(규칙 모듈은 닉네임을 모름). + - 카드 ID가 라운드마다 다시 쓰이므로 새 라운드를 시작할 때 기록에서 지난 라운드의 `play` 줄을 지운다(정보 유출 방지). + - `legalActions`(테스트·컴퓨터용)는 그랜드·스몰 티츄를 "해 볼 만한 손패"(용3·봉황3·A2·K1·폭탄4 합이 6/7 이상)일 때만, 그리고 다른 할 일과 함께만 넣는다. 무작위 대국이 절반 확률로 선언해 점수가 끝없이 내려가는 것을 막기 위해서다. `validate`는 언제든 받는다. 컴퓨터는 선언을 스스로 만든다. + - 휴대폰 320px에서 손패는 7장씩 두 줄(카드 폭 약 38px, 높이 53px). 44px 너비는 320px에 7장이 들어가지 않아 높이로 탭 영역을 확보했다. diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index b7ceb39..508b501 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -1191,6 +1191,73 @@ async function magicalStep(p: Page, phone: boolean, st: { picks: number; selects return false; } + +/** + * 티츄: one UI step for `p` — grand tichu "안 함", the exchange (추천대로 채우기 → 보내기), dragon gift, "폭탄 없음", + * "다음 라운드", or on its turn: tap a card (phone, leading) / a suggestion chip / the keyboard (PC host) and "내기" + * (wish sheet → 소원 없음), passing now and then. Returns what it did, or null. + */ +async function tichuStep(p: Page, isHost: boolean, st: Record): Promise { + const on = async (l: Locator) => (await l.count()) > 0 && (await l.first().isEnabled().catch(() => false)); + const press = async (l: Locator, key: string) => { + await l.first().click({ timeout: 1500 }); + st[key] = (st[key] ?? 0) + 1; + return key; + }; + const btn = (name: string | RegExp) => p.getByRole('button', { name, exact: typeof name === 'string' }); + if (await on(btn('안 함'))) return press(btn('안 함'), 'grand'); + if (await on(btn('추천대로 채우기'))) { + await btn('추천대로 채우기').first().click(); + if (!st[`xshot-${tag(p)}`]) { + st[`xshot-${tag(p)}`] = 1; + await p.screenshot({ path: join(SHOTS, `tichu-exchange-${tag(p)}.png`), fullPage: tag(p) === 'phone' }); + } + return press(btn('보내기'), 'exchange'); + } + if (await on(btn(/에게 주기/))) return press(btn(/에게 주기/), 'dragon'); + if (await on(btn('다음 라운드'))) return press(btn('다음 라운드'), 'ready'); + if (await on(btn('소원 없음'))) return press(btn('소원 없음'), 'wish'); + if (await on(btn('폭탄 없음'))) return press(btn('폭탄 없음'), 'noBomb'); + const play = btn('내기'); + if (!(await play.count())) return null; + const status = (await p.locator('.turn-status').innerText().catch(() => '')).trim(); + if (!status.includes('내 차례예요')) return null; + const pass = btn('패스'); + const leading = status.includes('새 트릭'); + if (!leading && (await on(pass)) && (st.turns ?? 0) % 3 === 2) { + st.turns = (st.turns ?? 0) + 1; + return press(pass, 'pass'); + } + if (leading && tag(p) === 'phone' && !st.tapped) { + // Tap the lowest card: the live label names it and says it can go. + await p.locator('.tc-hand button.tc-c').first().click(); + const live = (await p.locator('.tc-live').innerText()).trim(); + if (live.includes('낼 수 있어요')) { + st.tapped = 1; + if (!st.liveshot) { + st.liveshot = 1; + await p.screenshot({ path: join(SHOTS, 'tichu-pick-phone.png') }); + } + } else await p.locator('.tc-hand button.tc-c').first().click(); + } + if (!(await on(play))) { + const chip = p.locator('.tc-chips button.tc-chip').first(); + if (await chip.count()) { + if (isHost) { + await chip.focus(); + await p.keyboard.press('Enter'); + st.keys = (st.keys ?? 0) + 1; + } else await chip.click(); + } + } + if (await on(play)) { + st.turns = (st.turns ?? 0) + 1; + return press(play, 'play'); + } + if (await on(pass)) return press(pass, 'pass'); + return null; +} + const PLANS: Record = { blackjack: { // PC host + phone guest. Each hand: bet the minimum, stand (decline insurance), then press 다음 판, until the @@ -3190,6 +3257,64 @@ const PLANS: Record = { console.log(` magical-athlete: ${st.picks} picks, ${st.selects} race picks, ${st.acts} turn choices (${st.second} second options), powers + wild track seen`); }, }, + tichu: { + // PC host + 3 phone guests, 4인 팀전 to 300 points with 45-second turns: real grand / exchange / plays (card taps, + // suggestion chips, keyboard on PC) through the UI until round 1 is scored and round 2 is being played. + players: 4, + lobby: async (host) => { + await host.getByRole('group', { name: '목표 점수' }).getByRole('button', { name: '300', exact: true }).click(); + await host.getByRole('group', { name: '한 턴 제한 시간' }).getByRole('button', { name: '45초' }).click(); + await host.getByText(/300점/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st: Record = {}; + let midShot = false; + let roundShot = false; + const until = Date.now() + 360_000; + const over = () => host.getByRole('dialog', { name: '게임 결과' }).count(); + while (Date.now() < until && !(await over())) { + let acted = false; + for (const [i, p] of pages.entries()) { + if (await tichuStep(p, i === 0, st).catch(() => null)) { + acted = true; + await p.waitForTimeout(150); + break; + } + } + if (!midShot && (st.play ?? 0) >= 8 && (await host.locator('.tc-set').count())) { + midShot = true; + await host.waitForTimeout(400); + await host.screenshot({ path: join(SHOTS, 'tichu-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'tichu-mid-phone.png') }); + await guest.screenshot({ path: join(SHOTS, 'tichu-mid-phone-full.png'), fullPage: true }); + await guest.setViewportSize({ width: 320, height: 720 }); + await guest.waitForTimeout(300); + await guest.screenshot({ path: join(SHOTS, 'tichu-mid-phone-320.png'), fullPage: true }); + const overflow = await guest.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + if (overflow > 1) throw new Error(`320px: page is ${overflow}px too wide`); + await guest.setViewportSize({ width: 390, height: 844 }); + for (const p of [host, guest]) await p.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'tichu-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'tichu-mid-phone-dark.png') }); + for (const p of [host, guest]) await p.emulateMedia({ colorScheme: 'light' }); + } + if (!roundShot && (await host.getByRole('heading', { name: /라운드 결과/ }).count())) { + roundShot = true; + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'tichu-round-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'tichu-round-phone.png'), fullPage: true }); + } + if (roundShot && (st.ready ?? 0) >= 4 && (st.exchange ?? 0) >= 8 && (await host.locator('.tc-hand-wrap').count())) break; + if (!acted) await host.waitForTimeout(150); + } + if (!roundShot && !(await over())) throw new Error(`round 1 did not finish (${JSON.stringify(st)})`); + if ((st.play ?? 0) < 10 || !st.exchange || !st.grand || !st.tapped || !st.keys) throw new Error(`too few real steps: ${JSON.stringify(st)}`); + await host.screenshot({ path: join(SHOTS, 'tichu-round2-pc.png') }); + console.log(` tichu: ${JSON.stringify(Object.fromEntries(Object.entries(st).filter(([k]) => !k.includes('shot'))))}`); + }, + }, }; const games = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(PLANS); diff --git a/packages/games/package.json b/packages/games/package.json index 62f16f9..79478dd 100644 --- a/packages/games/package.json +++ b/packages/games/package.json @@ -12,6 +12,7 @@ "./liar/topics": "./src/liar/topics.ts", "./magical-athlete/racers": "./src/magical-athlete/racers.ts", "./seotda/money": "./src/seotda/money.ts", + "./tichu/combo": "./src/tichu/combo.ts", "./*": "./src/*/index.ts" }, "dependencies": { diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 14d5844..6046c8c 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -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 = { uno: unoBot, 'magical-athlete': magicalAthleteBot, blackjack: blackjackBot, + tichu: tichuBot, }; /** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */ diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index e40af82..803af9d 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -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 = { [omok.id]: omok, @@ -69,4 +70,5 @@ export const GAMES: Record = { [liar.id]: liar, [magicalAthlete.id]: magicalAthlete, [blackjack.id]: blackjack, + [tichu.id]: tichu, }; diff --git a/packages/games/src/result-score.test.ts b/packages/games/src/result-score.test.ts index 15725e7..ae8e253 100644 --- a/packages/games/src/result-score.test.ts +++ b/packages/games/src/result-score.test.ts @@ -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 = { '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 = { 'one-card': { mode: 'uno-style' }, tichu: { targetScore: 300 } }; describe('final score text', () => { for (const def of Object.values(GAMES)) { diff --git a/packages/games/src/tichu/bot.test.ts b/packages/games/src/tichu/bot.test.ts new file mode 100644 index 0000000..acf625f --- /dev/null +++ b/packages/games/src/tichu/bot.test.ts @@ -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, 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, 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 }); + }); +}); diff --git a/packages/games/src/tichu/bot.ts b/packages/games/src/tichu/bot.ts new file mode 100644 index 0000000..0b0ce61 --- /dev/null +++ b/packages/games/src/tichu/bot.ts @@ -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 = ({ view, legal, random, level }) => { + const of = (t: T) => legal.filter((a): a is Extract => 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(); + 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 }; diff --git a/packages/games/src/tichu/combo.ts b/packages/games/src/tichu/combo.ts new file mode 100644 index 0000000..da8fc5d --- /dev/null +++ b/packages/games/src/tichu/combo.ts @@ -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 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 = { 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 = { 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 | 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(); + 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(); + 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(); + 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; diff --git a/packages/games/src/tichu/index.ts b/packages/games/src/tichu/index.ts new file mode 100644 index 0000000..1dc999d --- /dev/null +++ b/packages/games/src/tichu/index.ts @@ -0,0 +1,1326 @@ +/** 티츄 (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 & { + 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): number => (o.mode === 'tientsin' ? 6 : 4); +export const playerCount = (o: Pick): number => (o.mode === 'tientsin' ? 6 : o.mode === 'threechu' ? 3 : 4); +const fourSeats = (s: TichuState) => s.seats.length === 4; + +function log(s: TichuState, e: Record & { 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, 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 = {}; + 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(); + 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 = (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(); + 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 }; diff --git a/packages/games/src/tichu/tichu.test.ts b/packages/games/src/tichu/tichu.test.ts new file mode 100644 index 0000000..a06738e --- /dev/null +++ b/packages/games/src/tichu/tichu.test.ts @@ -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 = {}, 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> = {}) => 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 = {}) => { + 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, 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); + }); +}); diff --git a/packages/games/src/tichu/types.ts b/packages/games/src/tichu/types.ts new file mode 100644 index 0000000..e2b763a --- /dev/null +++ b/packages/games/src/tichu/types.ts @@ -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 = (...vals: T[]) => + z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); + +// ---------------------------------------------------------------- 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; +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 | { type: 'timeout' } | { type: 'leave' }; +export type PlayAction = Extract; +export type ExchangeAction = Extract; + +// ---------------------------------------------------------------- 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; + scoreText: Record; + 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; + away: Record; + left: Record; + 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 | 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; +} diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index 134d6f7..2139fbe 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -59,6 +59,7 @@ export const BOT_GAMES: readonly string[] = [ 'liar', 'magical-athlete', 'blackjack', + 'tichu', ]; /** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */ diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index b95f2ac..8c03c4d 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -45,6 +45,7 @@ export const CATALOG: CatalogEntry[] = [ { id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true }, { id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true }, { id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true }, + { id: 'tichu', nameKo: '티츄', minPlayers: 3, maxPlayers: 6, minutes: '30~60', level: '보통', blurb: '마주 앉은 짝꿍과 한 팀! 더 센 조합으로 손패를 먼저 털고 점수 카드 모으기 · 폭탄·티츄 선언 · 3인·6인 변형', available: true }, ]; export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);