Merge branch 'wip/game-tichu' into codex/owner/grp_discord_joke-app
# Conflicts: # apps/web/src/games/help.test.ts # apps/web/src/games/registry.ts # apps/web/src/lib/catalog-ui.ts # docs/games/README.md # e2e/games.e2e.ts # packages/games/package.json # packages/games/src/bots/index.ts # packages/games/src/index.ts # packages/shared/src/bots.ts # packages/shared/src/catalog.ts
This commit is contained in:
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(37);
|
||||
expect(IDS).toHaveLength(38);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
@@ -39,6 +39,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
'six-nimmt': () => import('./six-nimmt'),
|
||||
gemblo: () => import('./gemblo'),
|
||||
'hot-streak': () => import('./hot-streak'),
|
||||
tichu: () => import('./tichu'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
132
apps/web/src/games/tichu/cards.tsx
Normal file
132
apps/web/src/games/tichu/cards.tsx
Normal file
@@ -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<string, string> = { j: 'C', s: 'S', b: 'D', t: 'H' };
|
||||
const RANK_MAP: Record<number, string> = { 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<string, { name: string; corner: string; bg: string; ink: string }> = {
|
||||
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 (
|
||||
<g>
|
||||
<ellipse cx="54" cy="82" rx="24" ry="19" fill={ink} opacity="0.85" />
|
||||
<circle cx="72" cy="64" r="12" fill={ink} />
|
||||
<path d="M83 63 L95 66 L83 69 Z" fill="#f59e0b" />
|
||||
<circle cx="75" cy="61" r="2.5" fill="#fff" />
|
||||
<path d="M34 78 L18 70 L30 88 Z" fill={ink} opacity="0.7" />
|
||||
<path d="M50 100 L46 112 M60 100 L62 112" stroke={ink} strokeWidth="3" strokeLinecap="round" />
|
||||
</g>
|
||||
);
|
||||
case 'DOG':
|
||||
// A friendly dog face.
|
||||
return (
|
||||
<g>
|
||||
<ellipse cx="50" cy="80" rx="24" ry="22" fill="#a8a29e" />
|
||||
<ellipse cx="30" cy="66" rx="9" ry="17" fill={ink} transform="rotate(20 30 66)" />
|
||||
<ellipse cx="70" cy="66" rx="9" ry="17" fill={ink} transform="rotate(-20 70 66)" />
|
||||
<circle cx="42" cy="76" r="3.5" fill="#1c1917" />
|
||||
<circle cx="58" cy="76" r="3.5" fill="#1c1917" />
|
||||
<ellipse cx="50" cy="88" rx="6" ry="4.5" fill="#1c1917" />
|
||||
<path d="M44 95 Q50 100 56 95" stroke="#1c1917" strokeWidth="2.5" fill="none" strokeLinecap="round" />
|
||||
</g>
|
||||
);
|
||||
case 'PH':
|
||||
// A bird of flame: three feathers and a crest.
|
||||
return (
|
||||
<g>
|
||||
<path d="M50 112 C30 100 24 78 34 60 C38 74 44 80 50 82 C56 80 62 74 66 60 C76 78 70 100 50 112 Z" fill="#f97316" />
|
||||
<path d="M50 104 C40 96 38 84 42 74 C46 82 50 86 50 86 C50 86 54 82 58 74 C62 84 60 96 50 104 Z" fill="#fde047" />
|
||||
<circle cx="50" cy="56" r="9" fill={ink} />
|
||||
<path d="M50 47 C46 38 52 32 56 30 C54 36 58 40 54 47 Z" fill="#ef4444" />
|
||||
<path d="M58 56 L66 58 L58 60 Z" fill="#fbbf24" />
|
||||
</g>
|
||||
);
|
||||
default:
|
||||
// A winding dragon with a pearl.
|
||||
return (
|
||||
<g>
|
||||
<path d="M22 108 C22 86 46 92 46 74 C46 58 24 62 28 46 C32 36 46 36 54 42" stroke={ink} strokeWidth="11" fill="none" strokeLinecap="round" />
|
||||
<path d="M22 108 C22 86 46 92 46 74 C46 58 24 62 28 46 C32 36 46 36 54 42" stroke="#fbbf24" strokeWidth="3" strokeDasharray="4 6" fill="none" />
|
||||
<circle cx="60" cy="44" r="10" fill={ink} />
|
||||
<circle cx="63" cy="41" r="2.5" fill="#fff" />
|
||||
<path d="M66 36 L76 28 M60 34 L64 24" stroke={ink} strokeWidth="3" strokeLinecap="round" />
|
||||
<circle cx="76" cy="84" r="9" fill="#fbbf24" stroke="#d97706" strokeWidth="2" />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function SpecialCard({ id }: { id: string }) {
|
||||
const s = SPECIAL[id]!;
|
||||
return (
|
||||
<span className="tc-sp" aria-hidden style={{ display: 'inline-flex' }}>
|
||||
<svg viewBox="0 0 100 140" width={64} height={90} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="138" rx="9" fill={s.bg} stroke={s.ink} strokeWidth="3" />
|
||||
<SpecialPicture id={id} ink={s.ink} />
|
||||
<text x="9" y="31" fontSize={s.corner.length > 1 ? 22 : 30} fontWeight="800" fill={s.ink} fontFamily="Pretendard Variable, sans-serif">
|
||||
{s.corner}
|
||||
</text>
|
||||
<text x="50" y="132" fontSize="17" fontWeight="800" fill={s.ink} textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{s.name}
|
||||
</text>
|
||||
</svg>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 <SpecialCard id={id} />;
|
||||
return <PlayingCard card={id ? stdId(id) : null} size="md" fourColor />;
|
||||
}
|
||||
|
||||
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 (
|
||||
<button type="button" className={cls} onClick={onClick} aria-pressed={!!selected} aria-label={aria} data-card={id} style={style}>
|
||||
<CardFace id={id} />
|
||||
{badge && <span className="tc-badge-on">{badge}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={cls} role="img" aria-label={aria} data-card={id} style={style}>
|
||||
<CardFace id={id} />
|
||||
{badge && <span className="tc-badge-on">{badge}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
21
apps/web/src/games/tichu/help.test.ts
Normal file
21
apps/web/src/games/tichu/help.test.ts
Normal file
@@ -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('기다려 주세요');
|
||||
});
|
||||
81
apps/web/src/games/tichu/help.ts
Normal file
81
apps/web/src/games/tichu/help.ts
Normal file
@@ -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<number, string> = { 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, PublicUser>): 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;
|
||||
}
|
||||
1382
apps/web/src/games/tichu/index.tsx
Normal file
1382
apps/web/src/games/tichu/index.tsx
Normal file
File diff suppressed because it is too large
Load Diff
61
apps/web/src/games/tichu/quick.tsx
Normal file
61
apps/web/src/games/tichu/quick.tsx
Normal file
@@ -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 (
|
||||
<g transform={`translate(${x} ${y})`}>
|
||||
<rect width={34} height={48} rx={5} fill={bg} stroke="#9ca3af" strokeWidth={1.5} />
|
||||
<text x={17} y={31} textAnchor="middle" fontSize={label.length > 1 ? 13 : 18} fontWeight={900} fill={color}>
|
||||
{label}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 130" width={250} height={130} aria-hidden>
|
||||
<circle cx={125} cy={65} r={34} fill="#15803d" />
|
||||
<text x={125} y={18} textAnchor="middle" fontSize={14} fontWeight={800} fill="#2563eb">짝꿍</text>
|
||||
<text x={125} y={124} textAnchor="middle" fontSize={14} fontWeight={800} fill="#2563eb">나</text>
|
||||
<text x={40} y={70} textAnchor="middle" fontSize={14} fontWeight={800} fill="#dc2626">상대</text>
|
||||
<text x={210} y={70} textAnchor="middle" fontSize={14} fontWeight={800} fill="#dc2626">상대</text>
|
||||
<path d="M125 28 V102" stroke="#2563eb" strokeWidth={3} strokeDasharray="5 4" />
|
||||
</svg>
|
||||
),
|
||||
alt: '네 사람이 둘러앉고 마주 앉은 나와 짝꿍이 한 팀',
|
||||
title: '마주 앉은 짝꿍과 한 팀',
|
||||
text: '4명이 2:2로 해요. 손패를 먼저 털고 트릭에서 5·10·K·용 점수 카드를 모아 목표 점수에 먼저 닿는 팀이 이겨요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<Card x={10} y={20} label="8" />
|
||||
<Card x={30} y={20} label="8" color="#dc2626" />
|
||||
<text x={100} y={52} fontSize={26} fontWeight={900} fill="#374151">→</text>
|
||||
<Card x={140} y={20} label="J" color="#2563eb" />
|
||||
<Card x={160} y={20} label="J" color="#15803d" />
|
||||
<text x={45} y={100} textAnchor="middle" fontSize={13} fontWeight={800} fill="#374151">8 페어</text>
|
||||
<text x={175} y={100} textAnchor="middle" fontSize={13} fontWeight={800} fill="#15803d">더 센 페어</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '8 페어 위에 J 페어를 내는 모습',
|
||||
title: '같은 모양으로 더 세게',
|
||||
text: '싱글·페어·트리플·풀하우스·스트레이트·연속 페어 중 앞과 같은 모양·같은 장수로 더 센 것을 내거나 패스해요. 폭탄은 언제든 이겨요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<Card x={12} y={14} label="참새" color="#a16207" bg="#fef9c3" />
|
||||
<Card x={72} y={14} label="개" color="#57534e" bg="#f5f5f4" />
|
||||
<Card x={132} y={14} label="봉황" color="#c2410c" bg="#ffedd5" />
|
||||
<Card x={192} y={14} label="용" color="#15803d" bg="#dcfce7" />
|
||||
<text x={125} y={92} textAnchor="middle" fontSize={15} fontWeight={900} fill="#dc2626">티츄! = 1등에 +100</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '특수 카드 참새, 개, 봉황, 용과 티츄 선언',
|
||||
title: '특수 카드와 티츄!',
|
||||
text: '참새는 소원을 부르고, 개는 선을 짝꿍에게, 봉황은 아무 숫자, 용은 가장 센 싱글이에요. 첫 카드 전 [티츄!]로 1등에 걸 수 있어요.',
|
||||
},
|
||||
];
|
||||
@@ -36,6 +36,7 @@ export const GAME_ICON: Record<string, string> = {
|
||||
'six-nimmt': '🐮',
|
||||
gemblo: '💠',
|
||||
'hot-streak': '🏁',
|
||||
tichu: '🐉',
|
||||
};
|
||||
|
||||
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
|
||||
@@ -44,6 +45,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', 'gemblo'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt', 'tichu'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'hot-streak'] },
|
||||
];
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
| `six-nimmt` | 젝스님트 | 2~10 | 2026-10 새 게임 |
|
||||
| `gemblo` | 젬블로 | 2~6 | 2026-10 새 게임 |
|
||||
| `hot-streak` | 핫스트릭 | 2~10 | 2026-10 새 게임 |
|
||||
| `tichu` | 티츄 | 4 (변형 3·6) | 2026-10 새 게임 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
@@ -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장이 들어가지 않아 높이로 탭 영역을 확보했다.
|
||||
|
||||
121
e2e/games.e2e.ts
121
e2e/games.e2e.ts
@@ -1234,6 +1234,71 @@ async function sixStep(p: Page, phone: boolean, st: { selects: number; taps: num
|
||||
return false;
|
||||
}
|
||||
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<string, number>): Promise<string | null> {
|
||||
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<string, Plan> = {
|
||||
@@ -3561,6 +3626,62 @@ const PLANS: Record<string, Plan> = {
|
||||
await host.screenshot({ path: join(SHOTS, 'hot-streak-final-pc.png'), fullPage: true });
|
||||
if (st.drafts !== 6 || st.doubles !== 2 || st.puts !== 2 || st.flips < 3 || !st.hurried || !st.payout) throw new Error(`too few real steps: ${JSON.stringify(st)}`);
|
||||
console.log(` hot-streak: ${st.drafts} tickets (${st.risky} risky), ${st.doubles} doubles, ${st.puts} secret puts, ${st.flips}+ cards flipped on the clock, 빨리 보기, payout`);
|
||||
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<string, number> = {};
|
||||
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'))))}`);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"./six-nimmt/rules": "./src/six-nimmt/rules.ts",
|
||||
"./gemblo/board": "./src/gemblo/board.ts",
|
||||
"./hot-streak/cards": "./src/hot-streak/cards.ts",
|
||||
"./tichu/combo": "./src/tichu/combo.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -41,6 +41,7 @@ import { blackjackBot } from '../blackjack/bot';
|
||||
import { sixNimmtBot } from '../six-nimmt/bot';
|
||||
import { gembloBot } from '../gemblo/bot';
|
||||
import { hotStreakBot } from '../hot-streak/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';
|
||||
@@ -79,6 +80,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
'six-nimmt': sixNimmtBot,
|
||||
gemblo: gembloBot,
|
||||
'hot-streak': hotStreakBot,
|
||||
tichu: tichuBot,
|
||||
};
|
||||
|
||||
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */
|
||||
|
||||
@@ -36,6 +36,7 @@ import { blackjack } from './blackjack';
|
||||
import { sixNimmt } from './six-nimmt';
|
||||
import { gemblo } from './gemblo';
|
||||
import { hotStreak } from './hot-streak';
|
||||
import { tichu } from './tichu';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -75,4 +76,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[sixNimmt.id]: sixNimmt,
|
||||
[gemblo.id]: gemblo,
|
||||
[hotStreak.id]: hotStreak,
|
||||
[tichu.id]: tichu,
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@ import { GAMES } from './index';
|
||||
|
||||
/** Games without a score (win/lose only, or survival) leave `scoreText` out. */
|
||||
const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker', 'clue', 'connect-four']);
|
||||
/** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). */
|
||||
const SCORED_OPTIONS: Record<string, object> = { 'one-card': { mode: 'uno-style' } };
|
||||
/** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). 티츄: a 300-point game so random play ends in time. */
|
||||
const SCORED_OPTIONS: Record<string, object> = { 'one-card': { mode: 'uno-style' }, tichu: { targetScore: 300 } };
|
||||
|
||||
describe('final score text', () => {
|
||||
for (const def of Object.values(GAMES)) {
|
||||
|
||||
110
packages/games/src/tichu/bot.test.ts
Normal file
110
packages/games/src/tichu/bot.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
/** 티츄 computer player (docs/games/tichu.md §8.7). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { decideBotAction } from '../bots';
|
||||
import { tichuBot, handCost } from './bot';
|
||||
import { classify, tichu, type TichuAction, type TichuOptions, type TichuState, type TichuView } from './index';
|
||||
|
||||
const isBot = (p: string) => p.startsWith('bot:');
|
||||
const bots = (n: number) => Array.from({ length: n }, (_, i) => `bot:${i + 1}:x`);
|
||||
const C = (ids: string) => ids.split(' ');
|
||||
|
||||
function make(opts: Partial<TichuOptions>, players: string[], seed = 1): TichuState {
|
||||
return tichu.setup({ players, options: tichu.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
}
|
||||
function rigPlay(s: TichuState, hands: string[][], current: number, plays: { seat: number; cards: string[] }[] = [], wish: number | null = null): TichuState {
|
||||
s.hands = hands;
|
||||
s.pending = s.seats.map(() => []);
|
||||
s.won = s.seats.map(() => []);
|
||||
s.phase = { kind: 'playing' };
|
||||
s.out = [];
|
||||
s.played = s.seats.map(() => true);
|
||||
s.calls = s.seats.map(() => 'none');
|
||||
s.wish = wish;
|
||||
s.current = current;
|
||||
s.trick = { leader: plays[0]?.seat ?? current, plays: [], passed: [], closingAt: null, waived: [] };
|
||||
for (const p of plays) s.trick.plays.push({ seat: p.seat, cards: p.cards, combo: classify(p.cards, s.trick.plays.at(-1)?.combo ?? null)!, outOfTurn: false });
|
||||
return s;
|
||||
}
|
||||
const decide = (s: TichuState, p: string, level = 60): TichuAction => {
|
||||
const view = tichu.view(s, p) as TichuView;
|
||||
return tichuBot({ me: p, view, legal: tichu.legalActions(s, p), random: () => 0.5, level });
|
||||
};
|
||||
|
||||
describe('컴퓨터끼리 끝까지', () => {
|
||||
const cases: [string, Partial<TichuOptions>, number][] = [
|
||||
['team', {}, 4],
|
||||
['individual', { mode: 'individual', targetScore: 500 }, 4],
|
||||
['threechu', { mode: 'threechu', threechuHands: 3 }, 3],
|
||||
['tientsin', { mode: 'tientsin', targetScore: 500 }, 6],
|
||||
['penalty + party', { wishRule: 'penalty', party: true, targetScore: 500 }, 4],
|
||||
];
|
||||
test.each(cases)('%s', (_n, opts, n) => {
|
||||
for (const level of [1, 60]) {
|
||||
const r = botPlayout(tichu, { players: bots(n), options: tichu.optionsSchema.parse(opts), seed: seedN(level + n), isBot, maxSteps: 30_000, level });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
expect(r.maxBotMs).toBeLessThan(250);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('penalty 모드에서도 컴퓨터는 소원을 지켜요(위반 라운드 없음)', () => {
|
||||
let penalties = 0;
|
||||
for (let k = 1; k <= 4; k++) {
|
||||
const players = bots(4);
|
||||
const options = tichu.optionsSchema.parse({ wishRule: 'penalty', targetScore: 500 });
|
||||
const rng = SeededRng.fromSeed(seedN(k));
|
||||
let s = tichu.setup({ players, options, rng, now: 0 });
|
||||
let now = 0;
|
||||
for (let i = 0; i < 20_000 && !tichu.result(s); i++) {
|
||||
const who = tichu.activePlayers(s)[0]!;
|
||||
now += 700;
|
||||
const a = (decideBotAction(tichu, s, who, { now, random: () => 0.3, level: 60 }) as TichuAction | null) ?? tichu.onTimeout(s, who);
|
||||
s = tichu.apply(s, who, a, { rng, now }).state;
|
||||
}
|
||||
penalties += s.rounds.filter((r) => r.kind === 'penalty').length;
|
||||
}
|
||||
expect(penalties).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('판단', () => {
|
||||
test('짝꿍이 맨 위면 대개 패스, 상대가 맨 위면 조합을 깨지 않고 이김', () => {
|
||||
const P = ['A', 'B', 'C', 'D'];
|
||||
let s = make({ grandTichu: false }, P);
|
||||
// D (seat 3) to play; partner B (seat 1) holds the trick with a 9.
|
||||
s = rigPlay(s, [C('s2 s3'), C('j4 s4'), C('j6 j7'), C('j10 b11 t3 t4 t5')], 3, [{ seat: 1, cards: ['j9'] }]);
|
||||
expect(decide(s, 'D').type).toBe('pass');
|
||||
// The opponent (A, seat 0) holds it: beat with the loose 10 or J, not by breaking anything.
|
||||
s = rigPlay(s, [C('s2 s3'), C('j4 s4'), C('j6 j7'), C('j10 b11 t3 t4 t5')], 3, [{ seat: 0, cards: ['j9'] }]);
|
||||
const a = decide(s, 'D');
|
||||
expect(a.type).toBe('play');
|
||||
expect((a as { cardIds: string[] }).cardIds.length).toBe(1);
|
||||
});
|
||||
|
||||
test('선이면 가장 약한 조합부터(긴 조합 우선)', () => {
|
||||
const P = ['A', 'B', 'C', 'D'];
|
||||
let s = make({ grandTichu: false }, P);
|
||||
s = rigPlay(s, [C('j2 s3 b4 t5 j6 s13 b13 j14'), C('j4 s4'), C('j6 j7'), C('j10 b11')], 0);
|
||||
const a = decide(s, 'A') as { type: string; cardIds: string[] };
|
||||
expect(a.type).toBe('play');
|
||||
expect(a.cardIds).toEqual(C('j2 s3 b4 t5 j6'));
|
||||
});
|
||||
|
||||
test('손패 나누기: 스트레이트·연속 페어·풀하우스를 한 번으로 셈', () => {
|
||||
expect(handCost(C('j2 s3 b4 t5 j6'))).toBe(1);
|
||||
expect(handCost(C('j5 s5 j6 s6 j7 s7'))).toBe(1);
|
||||
expect(handCost(C('j9 s9 b9 j3 s3'))).toBe(1);
|
||||
expect(handCost(C('j2 s9 b13'))).toBe(3);
|
||||
});
|
||||
|
||||
test('센 8장이면 그랜드 티츄, 약하면 안 함', () => {
|
||||
const P = ['A', 'B', 'C', 'D'];
|
||||
const s = make({}, P);
|
||||
s.hands[0] = C('DR PH j14 s14 b14 t13 j13 s12');
|
||||
expect(decide(s, 'A')).toEqual({ type: 'grand', call: true });
|
||||
s.hands[0] = C('j2 s3 b4 t6 j7 s8 b9 t11');
|
||||
expect(decide(s, 'A')).toEqual({ type: 'grand', call: false });
|
||||
});
|
||||
});
|
||||
267
packages/games/src/tichu/bot.ts
Normal file
267
packages/games/src/tichu/bot.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 티츄 computer player (docs/games/tichu.md §8.7). Uses only its own view and the legal actions: it splits its hand
|
||||
* into as few combinations as it can (rank counts, straights, pair runs, full houses, the phoenix as a joker), leads
|
||||
* the weakest part of that plan, beats opponents without breaking it, leaves partners' tricks alone, keeps bombs and
|
||||
* the dragon for opponents close to going out, and calls tichu only with enough high cards for the weak ones.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { humanBest, pick } from '../bots/policy';
|
||||
import {
|
||||
DOG,
|
||||
DR,
|
||||
MJ,
|
||||
PH,
|
||||
cardPoints,
|
||||
classify,
|
||||
includesWish,
|
||||
isBomb,
|
||||
isNumber,
|
||||
mustFulfillWish,
|
||||
rankOf,
|
||||
type Combo,
|
||||
type MySeatView,
|
||||
type PlayAction,
|
||||
type TichuAction,
|
||||
type TichuView,
|
||||
} from './types';
|
||||
|
||||
const SCALE = { small: 4, critical: 900 };
|
||||
|
||||
function counts(hand: readonly string[]): number[] {
|
||||
const c = Array.from({ length: 15 }, () => 0);
|
||||
for (const id of hand) if (isNumber(id) || id === MJ) c[rankOf(id)]!++;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Plays needed for these rank counts without straights (pairs, runs of pairs, triples, full houses, bombs). */
|
||||
function groupCost(c: number[], ph: boolean, extra: number): number {
|
||||
let singles = c[1]!;
|
||||
let pairs = 0;
|
||||
let triples = 0;
|
||||
let bombs = 0;
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const k = c[r]!;
|
||||
if (k === 1) singles++;
|
||||
else if (k === 2) pairs++;
|
||||
else if (k === 3) triples++;
|
||||
else if (k === 4) bombs++;
|
||||
}
|
||||
// Runs of consecutive pairs play as one.
|
||||
let run = 0;
|
||||
for (let r = 2; r <= 15; r++) {
|
||||
if (r <= 14 && c[r] === 2) run++;
|
||||
else {
|
||||
if (run >= 2) pairs -= run - 1;
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
const fh = Math.min(triples, pairs);
|
||||
let total = singles + pairs + triples + bombs - fh + extra;
|
||||
if (ph && singles > 0) total -= 1; // the phoenix pairs a loose card
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Fewest plays to empty the hand (one straight considered on top of the groups). */
|
||||
export function handCost(hand: readonly string[]): number {
|
||||
const c = counts(hand);
|
||||
const ph = hand.includes(PH);
|
||||
const extra = (hand.includes(DR) ? 1 : 0) + (hand.includes(DOG) ? 0.5 : 0) + (ph && !c.some((k, r) => r > 0 && k === 1) ? 1 : 0);
|
||||
let best = groupCost(c, ph, extra);
|
||||
for (let lo = 1; lo <= 10; lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
let gaps = 0;
|
||||
for (let r = lo; r <= hi; r++) if (c[r] === 0) gaps++;
|
||||
if (gaps > (ph ? 1 : 0)) break;
|
||||
const d = [...c];
|
||||
for (let r = lo; r <= hi; r++) if (d[r]! > 0) d[r]!--;
|
||||
const usesPh = gaps === 1;
|
||||
best = Math.min(best, 1 + groupCost(d, ph && !usesPh, extra - (usesPh && extra > 0 && !c.some((k, r) => r > 0 && k === 1) ? 1 : 0)));
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** High cards that win the lead back: dragon, aces, bombs, the phoenix (half). */
|
||||
function controls(hand: readonly string[]): number {
|
||||
const c = counts(hand);
|
||||
let n = 0;
|
||||
if (hand.includes(DR)) n += 1;
|
||||
if (hand.includes(PH)) n += 0.5;
|
||||
if (c[14]! > 0) n += 1;
|
||||
if (c[13]! >= 2) n += 0.5;
|
||||
for (let r = 2; r <= 14; r++) if (c[r] === 4) n += 1.5;
|
||||
return n;
|
||||
}
|
||||
|
||||
function grandScore(hand: readonly string[]): number {
|
||||
const c = counts(hand);
|
||||
let v = 0;
|
||||
if (hand.includes(DR)) v += 3;
|
||||
if (hand.includes(PH)) v += 3;
|
||||
v += c[14]! * 2 + c[13]!;
|
||||
for (let r = 2; r <= 14; r++) if (c[r] === 4) v += 4;
|
||||
return v;
|
||||
}
|
||||
|
||||
const without = (hand: readonly string[], cards: readonly string[]) => hand.filter((c) => !cards.includes(c));
|
||||
|
||||
export const tichuBot: BotStrategy<TichuView, TichuAction> = ({ view, legal, random, level }) => {
|
||||
const of = <T extends TichuAction['type']>(t: T) => legal.filter((a): a is Extract<TichuAction, { type: T }> => a.type === t);
|
||||
const lvl = level ?? 60;
|
||||
const sloppy = (1 - Math.min(lvl, 60) / 60) * 2; // 0 (best) .. ~2 (level 1)
|
||||
const my = view.my;
|
||||
const seatOf = (s: number) => view.seats[s]!;
|
||||
const myTeam = my ? seatOf(my.seat).team : 0;
|
||||
const partnerSeats = view.seats.filter((x) => x.team === myTeam && x.seat !== my?.seat).map((x) => x.seat);
|
||||
const partnerCalled = partnerSeats.some((x) => seatOf(x).call !== 'none');
|
||||
|
||||
if (of('ready').length) return of('ready')[0]!;
|
||||
|
||||
// Grand tichu on the first 8 cards.
|
||||
// (Calls are built here: `legal` lists them only now and then.)
|
||||
const grands = of('grand');
|
||||
if (grands.length) {
|
||||
const need = 9 - (random() < sloppy * 0.2 ? 2 : 0);
|
||||
if (my?.canGrand && !partnerCalled && grandScore(my.hand) >= need) return { type: 'grand', call: true };
|
||||
return grands.find((a) => !a.call) ?? grands[0]!;
|
||||
}
|
||||
|
||||
// Dragon gift: an opponent who did not call, with the most cards.
|
||||
const gifts = of('dragonTo');
|
||||
if (gifts.length) {
|
||||
const score = (a: (typeof gifts)[number]) => {
|
||||
const x = seatOf(a.to);
|
||||
return x.cards + (x.call === 'none' ? 20 : 0) + (x.place === null ? 10 : 0);
|
||||
};
|
||||
return [...gifts].sort((a, b) => score(b) - score(a))[0]!;
|
||||
}
|
||||
|
||||
// Exchange: build my own (partner gets a high card, opponents loose low cards and the dog).
|
||||
const exchanges = of('exchange');
|
||||
if (exchanges.length) {
|
||||
const target = exchanges[0]!;
|
||||
const hand: MySeatView | null = target.seat !== undefined && view.dummy?.seat === target.seat ? view.dummy : my;
|
||||
if (hand) {
|
||||
const built = buildExchange(view, hand, partnerCalled);
|
||||
if (built) return { type: 'exchange', ...(target.seat !== undefined ? { seat: target.seat } : {}), give: built };
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
// Small tichu: before my first card, with enough control for the weak combinations.
|
||||
if (my?.canTichu && view.phase === 'playing' && !partnerCalled && view.seats.every((x) => x.place === null)) {
|
||||
const cost = handCost(my.hand);
|
||||
const ctl = controls(my.hand);
|
||||
const jitter = (random() - 0.5) * sloppy * 2;
|
||||
if (ctl + jitter >= cost - ctl - 1) return { type: 'tichu', ...(view.dummy ? { seat: my.seat } : {}) };
|
||||
}
|
||||
|
||||
// Collecting (everyone passed): bomb only an opponent's valuable trick or a caller about to go out.
|
||||
if (view.trick?.closingAt !== null && view.trick?.closingAt !== undefined) {
|
||||
const bombs = of('play');
|
||||
const top = view.trick.plays[view.trick.plays.length - 1];
|
||||
if (bombs.length && top && seatOf(top.seat).team !== myTeam) {
|
||||
const pts = cardPoints(view.trick.plays.flatMap((p) => p.cards));
|
||||
const danger = view.seats.some((x) => x.team !== myTeam && x.call !== 'none' && x.cards > 0 && x.cards <= 3);
|
||||
if (pts >= 25 || danger) return bombs[0]!;
|
||||
}
|
||||
return of('noBomb')[0] ?? legal[0]!;
|
||||
}
|
||||
|
||||
// Which hand am I playing (the threechu dealer also plays the dummy)?
|
||||
const forDummy = !!view.dummy && view.current === view.dummy.seat;
|
||||
const mineNow = (a: { seat?: number }) => (forDummy ? a.seat === view.dummy!.seat : a.seat === undefined || a.seat === my?.seat);
|
||||
const plays = of('play').filter(mineNow);
|
||||
const passes = of('pass').filter(mineNow);
|
||||
if (!plays.length) return passes[0] ?? pick(legal, random);
|
||||
const me: MySeatView | null = forDummy ? view.dummy : my;
|
||||
if (!me) return pick(plays, random);
|
||||
const hand = me.hand;
|
||||
const top = view.trick?.plays[view.trick.plays.length - 1] ?? null;
|
||||
const leading = !top;
|
||||
const topCombo: Combo | null = top?.combo ?? null;
|
||||
const topIsPartner = !!top && seatOf(top.seat).team === myTeam;
|
||||
const oppDanger = view.seats.some((x) => x.team !== myTeam && x.cards > 0 && x.cards <= (x.call !== 'none' ? 4 : 2));
|
||||
// wishRule = penalty: the screen does not stop me, so keep the duty myself (the dummy is free).
|
||||
const duty = !me.dummy && view.wish !== null && mustFulfillWish(hand, topCombo, view.wish, leading) ? view.wish : null;
|
||||
let options: TichuAction[] = duty !== null ? plays.filter((a) => includesWish(a.cardIds, duty)) : [...plays, ...passes];
|
||||
if (!options.length) options = [...plays, ...passes];
|
||||
const baseCost = handCost(hand);
|
||||
const missingHigh = [14, 13, 12, 11, 10].find((r) => !hand.some((c) => rankOf(c) === r)) ?? null;
|
||||
|
||||
const score = (a: TichuAction): number => {
|
||||
if (a.type === 'pass') {
|
||||
let v = -baseCost * 10 - 3;
|
||||
if (topIsPartner) v += 25;
|
||||
if (oppDanger && !topIsPartner) v -= 15;
|
||||
return v;
|
||||
}
|
||||
if (a.type !== 'play') return -1e6;
|
||||
const cards = a.cardIds;
|
||||
const rest = without(hand, cards);
|
||||
if (rest.length === 0) return 1000;
|
||||
const combo = classify(cards, topCombo)!;
|
||||
let v = -handCost(rest) * 10;
|
||||
const urgent = oppDanger && !topIsPartner;
|
||||
if (isBomb(combo)) v -= urgent ? 2 : leading ? 30 : 40;
|
||||
if (cards.includes(DR)) v -= urgent ? 0 : 14;
|
||||
if (cards.length === 1 && cards[0] === PH) v -= urgent ? 2 : 10;
|
||||
else if (cards.includes(PH)) v -= 4;
|
||||
if (cards.includes(DOG)) {
|
||||
const partnerLow = partnerSeats.some((x) => seatOf(x).cards > 0 && (seatOf(x).call !== 'none' || seatOf(x).cards <= 3));
|
||||
v += partnerLow ? 30 : -6;
|
||||
}
|
||||
// Weak first; when leading prefer shedding many cards at once.
|
||||
v -= Math.min(combo.value, 20) * (leading ? 0.6 : 0.4);
|
||||
if (leading) v += cards.length * 0.8;
|
||||
if (topIsPartner) v -= 30;
|
||||
// The wish: call a high rank I don't hold (not when my partner called: it could break their bomb).
|
||||
if (a.wish !== undefined) v += a.wish === (partnerCalled ? null : missingHigh) ? 0.5 : 0;
|
||||
// Pick up points.
|
||||
if (!leading && top) v += cardPoints(view.trick!.plays.flatMap((p) => p.cards)) * 0.15;
|
||||
return v;
|
||||
};
|
||||
const choice = humanBest(options, score, random, lvl, SCALE);
|
||||
return choice as TichuAction;
|
||||
};
|
||||
|
||||
/** Exchange plan: partner the best (dragon/phoenix/ace if they called), opponents the dog and loose low cards. */
|
||||
function buildExchange(view: TichuView, me: MySeatView, partnerCalled: boolean): { to: number; cardId: string }[] | null {
|
||||
const targets = me.exchangeTargets;
|
||||
if (!targets.length) return null;
|
||||
const myTeam = view.seats[me.seat]!.team;
|
||||
const hand = [...me.hand];
|
||||
const c = counts(hand);
|
||||
const used = new Set<string>();
|
||||
const take = (pred: (id: string) => boolean, order: string[]) => {
|
||||
const id = order.find((x) => !used.has(x) && pred(x));
|
||||
if (id) used.add(id);
|
||||
return id;
|
||||
};
|
||||
const asc = hand.filter(isNumber).sort((a, b) => rankOf(a) - rankOf(b));
|
||||
const desc = [...asc].reverse();
|
||||
const loose = (id: string) => c[rankOf(id)] === 1 && ![5, 10, 13].includes(rankOf(id));
|
||||
const out: { to: number; cardId: string }[] = [];
|
||||
const partnersFirst = [...targets].sort((a, b) => Number(view.seats[b.seat]!.team === myTeam) - Number(view.seats[a.seat]!.team === myTeam));
|
||||
let dogGiven = false;
|
||||
for (const t of partnersFirst) {
|
||||
const partner = view.seats[t.seat]!.team === myTeam;
|
||||
let id: string | undefined;
|
||||
if (partner) {
|
||||
if (partnerCalled) id = take((x) => x === DR || x === PH, [DR, PH]) ?? take((x) => rankOf(x) === 14, desc);
|
||||
id ??= take((x) => c[rankOf(x)] === 1, desc) ?? take(() => true, desc);
|
||||
} else {
|
||||
if (!dogGiven && hand.includes(DOG)) {
|
||||
id = take((x) => x === DOG, [DOG]);
|
||||
dogGiven = !!id;
|
||||
}
|
||||
id ??= take(loose, asc) ?? take((x) => ![5, 10, 13].includes(rankOf(x)), asc) ?? take(() => true, asc);
|
||||
}
|
||||
id ??= take(() => true, hand);
|
||||
if (!id) return null;
|
||||
out.push({ to: t.seat, cardId: id });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type { PlayAction };
|
||||
417
packages/games/src/tichu/combo.ts
Normal file
417
packages/games/src/tichu/combo.ts
Normal file
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* 티츄 combinations (docs/games/tichu.md §5.1~§5.5, §8.1): card ids, classify / beats / wish duty, card points and
|
||||
* the combination finder. Pure and dependency-free so the screen can import it for the live "풀하우스(9) · 낼 수 있어요"
|
||||
* label (`@bg/games/tichu/combo`).
|
||||
*
|
||||
* Card ids: number cards `<suit><rank>` (suit j 옥 · s 칼 · b 탑 · t 별, rank 2..14; 탑 is `b`, not `p`, so ids never equal test player ids like `p2`), specials MJ 참새 · DOG 개 · PH 봉황 · DR 용.
|
||||
*/
|
||||
|
||||
export type Rank = number;
|
||||
export type ComboType = 'single' | 'pair' | 'pairSeq' | 'triple' | 'fullHouse' | 'straight' | 'bomb4' | 'bombSF' | 'dog';
|
||||
|
||||
export interface Combo {
|
||||
type: ComboType;
|
||||
/** Number of cards. */
|
||||
length: number;
|
||||
/** Strength (§5.4): single phoenix x.5, dragon 100; otherwise the compared rank. */
|
||||
value: number;
|
||||
/** Rank the phoenix stands for (null for a single phoenix or without one). */
|
||||
phoenixAs: Rank | null;
|
||||
}
|
||||
|
||||
export const MJ = 'MJ';
|
||||
export const DOG = 'DOG';
|
||||
export const PH = 'PH';
|
||||
export const DR = 'DR';
|
||||
export const SPECIALS = [MJ, DOG, PH, DR] as const;
|
||||
export const SUITS = ['j', 's', 'b', 't'] as const;
|
||||
export type Suit = (typeof SUITS)[number];
|
||||
export const SUIT_KO: Record<Suit, string> = { j: '옥', s: '칼', b: '탑', t: '별' };
|
||||
export const DRAGON_VALUE = 100;
|
||||
|
||||
/** 56 cards in a fixed order: suits j, s, b, t × ranks 2..14, then MJ, DOG, PH, DR. */
|
||||
export const FULL_DECK: readonly string[] = [...SUITS.flatMap((s) => Array.from({ length: 13 }, (_, i) => `${s}${i + 2}`)), MJ, DOG, PH, DR];
|
||||
|
||||
export const isSpecial = (id: string): boolean => id === MJ || id === DOG || id === PH || id === DR;
|
||||
/** A real number card (2..A, with a suit). */
|
||||
export const isNumber = (id: string): boolean => !isSpecial(id);
|
||||
export const suitOf = (id: string): Suit | null => (isNumber(id) ? (id[0] as Suit) : null);
|
||||
/** 1 for the mahjong, 2..14 for number cards, 0 for the others. */
|
||||
export const rankOf = (id: string): number => (id === MJ ? 1 : isNumber(id) ? Number(id.slice(1)) : 0);
|
||||
|
||||
const SUIT_IDX: Record<string, number> = { j: 0, s: 1, b: 2, t: 3 };
|
||||
/** Sort key: 개, 참새, 2..A (suit order j s b t), 봉황, 용. */
|
||||
export function cardKey(id: string): number {
|
||||
if (id === DOG) return 0;
|
||||
if (id === MJ) return 1;
|
||||
if (id === PH) return 1000;
|
||||
if (id === DR) return 1001;
|
||||
return rankOf(id) * 10 + (SUIT_IDX[id[0]!] ?? 0);
|
||||
}
|
||||
export const sortCards = (ids: readonly string[]): string[] => [...ids].sort((a, b) => cardKey(a) - cardKey(b));
|
||||
|
||||
export const rankName = (r: number): string => (r === 1 ? '1' : r === 11 ? 'J' : r === 12 ? 'Q' : r === 13 ? 'K' : r === 14 ? 'A' : String(r));
|
||||
export function cardName(id: string): string {
|
||||
if (id === MJ) return '참새';
|
||||
if (id === DOG) return '개';
|
||||
if (id === PH) return '봉황';
|
||||
if (id === DR) return '용';
|
||||
return `${SUIT_KO[id[0] as Suit]} ${rankName(rankOf(id))}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- points
|
||||
|
||||
/** Card points (§3): 5 → 5, 10·K → 10, 용 +25, 봉황 −25. The party effect `negative` flips every sign (§7). */
|
||||
export function cardPoints(cards: readonly string[], effect: string | null = null): number {
|
||||
let p = 0;
|
||||
for (const c of cards) {
|
||||
if (c === DR) p += 25;
|
||||
else if (c === PH) p -= 25;
|
||||
else if (isNumber(c)) {
|
||||
const r = rankOf(c);
|
||||
if (r === 5) p += 5;
|
||||
else if (r === 10 || r === 13) p += 10;
|
||||
}
|
||||
}
|
||||
return effect === 'negative' ? 0 - p : p;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- classify
|
||||
|
||||
interface Item {
|
||||
rank: number;
|
||||
suit: string | null;
|
||||
}
|
||||
|
||||
const isBombType = (t: ComboType) => t === 'bomb4' || t === 'bombSF';
|
||||
export const isBomb = (c: Combo | null | undefined): boolean => !!c && isBombType(c.type);
|
||||
|
||||
/** Combination of plain items (no phoenix, no dog/dragon); a virtual phoenix card has `suit: null`. */
|
||||
function classifyPlain(items: Item[]): Omit<Combo, 'phoenixAs'> | null {
|
||||
const n = items.length;
|
||||
if (n === 0) return null;
|
||||
const ranks = items.map((i) => i.rank).sort((a, b) => a - b);
|
||||
const counts = new Map<number, number>();
|
||||
for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);
|
||||
const distinct = [...counts.keys()].sort((a, b) => a - b);
|
||||
const lo = ranks[0]!;
|
||||
const hi = ranks[n - 1]!;
|
||||
if (n === 1) return { type: 'single', length: 1, value: lo };
|
||||
if (distinct.length === 1) {
|
||||
if (lo < 2) return null;
|
||||
if (n === 2) return { type: 'pair', length: 2, value: lo };
|
||||
if (n === 3) return { type: 'triple', length: 3, value: lo };
|
||||
// Four of a kind is only a bomb with four real cards (no phoenix).
|
||||
if (n === 4 && items.every((i) => i.suit !== null)) return { type: 'bomb4', length: 4, value: lo };
|
||||
return null;
|
||||
}
|
||||
if (n === 5 && distinct.length === 2 && lo >= 2) {
|
||||
const a = distinct[0]!;
|
||||
const b = distinct[1]!;
|
||||
if (counts.get(a) === 3 && counts.get(b) === 2) return { type: 'fullHouse', length: 5, value: a };
|
||||
if (counts.get(b) === 3 && counts.get(a) === 2) return { type: 'fullHouse', length: 5, value: b };
|
||||
}
|
||||
if (n >= 5 && distinct.length === n && hi - lo === n - 1) {
|
||||
const suit = items[0]!.suit;
|
||||
if (suit !== null && items.every((i) => i.suit === suit)) return { type: 'bombSF', length: n, value: hi };
|
||||
return { type: 'straight', length: n, value: hi };
|
||||
}
|
||||
if (n >= 4 && n % 2 === 0 && lo >= 2 && distinct.length === n / 2 && distinct.every((r) => counts.get(r) === 2) && hi - lo === n / 2 - 1) {
|
||||
return { type: 'pairSeq', length: n, value: hi };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The combination these cards make (§5.1), or null. A phoenix takes the strongest reading; if `prevTop` is given and
|
||||
* some reading beats it, the strongest of those (§8.1). A single phoenix is the previous single + 0.5 (1.5 when
|
||||
* leading or on the mahjong).
|
||||
*/
|
||||
export function classify(cards: readonly string[], prevTop: Combo | null = null): Combo | null {
|
||||
const n = cards.length;
|
||||
if (n === 0 || new Set(cards).size !== n) return null;
|
||||
if (n === 1) {
|
||||
const c = cards[0]!;
|
||||
if (c === DOG) return { type: 'dog', length: 1, value: 0, phoenixAs: null };
|
||||
if (c === DR) return { type: 'single', length: 1, value: DRAGON_VALUE, phoenixAs: null };
|
||||
if (c === PH) {
|
||||
const v = prevTop && prevTop.type === 'single' && prevTop.value < DRAGON_VALUE ? Math.max(prevTop.value, 1) + 0.5 : 1.5;
|
||||
return { type: 'single', length: 1, value: v, phoenixAs: null };
|
||||
}
|
||||
return { type: 'single', length: 1, value: rankOf(c), phoenixAs: null };
|
||||
}
|
||||
if (cards.includes(DOG) || cards.includes(DR)) return null;
|
||||
const hasPh = cards.includes(PH);
|
||||
const real: Item[] = cards.filter((c) => c !== PH).map((c) => ({ rank: rankOf(c), suit: suitOf(c) }));
|
||||
if (!hasPh) {
|
||||
const c = classifyPlain(real);
|
||||
return c ? { ...c, phoenixAs: null } : null;
|
||||
}
|
||||
let best: Combo | null = null;
|
||||
let bestBeats = false;
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const c = classifyPlain([...real, { rank: r, suit: null }]);
|
||||
if (!c || isBombType(c.type)) continue;
|
||||
const combo: Combo = { ...c, phoenixAs: r };
|
||||
const b = prevTop ? beats(combo, prevTop) : false;
|
||||
if (!best || (b && !bestBeats) || (b === bestBeats && combo.value > best.value)) {
|
||||
best = combo;
|
||||
bestBeats = b;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Whether `c` may go on `top` (§5.2, §5.4, §5.5). `top` null = leading (anything but the dog's rules is fine). */
|
||||
export function beats(c: Combo, top: Combo | null): boolean {
|
||||
if (!top) return true;
|
||||
if (top.type === 'dog' || c.type === 'dog') return false;
|
||||
if (isBomb(c)) {
|
||||
if (!isBomb(top)) return true;
|
||||
return c.length > top.length || (c.length === top.length && c.value > top.value);
|
||||
}
|
||||
if (isBomb(top)) return false;
|
||||
if (c.type !== top.type || c.length !== top.length) return false;
|
||||
if (c.type === 'single' && top.value >= DRAGON_VALUE) return false;
|
||||
return c.value > top.value;
|
||||
}
|
||||
|
||||
export const includesWish = (cards: readonly string[], wish: Rank | null): boolean => wish !== null && cards.some((c) => isNumber(c) && rankOf(c) === wish);
|
||||
|
||||
// ---------------------------------------------------------------- names
|
||||
|
||||
export function comboName(c: Combo, cards?: readonly string[]): string {
|
||||
const v = c.value;
|
||||
switch (c.type) {
|
||||
case 'dog':
|
||||
return '개';
|
||||
case 'single':
|
||||
if (v >= DRAGON_VALUE) return '용';
|
||||
if (v === 1 && (!cards || cards[0] === MJ)) return '참새';
|
||||
if (!Number.isInteger(v) || (cards && cards[0] === PH)) return '봉황';
|
||||
return `싱글 ${rankName(v)}`;
|
||||
case 'pair':
|
||||
return `${rankName(v)} 페어`;
|
||||
case 'triple':
|
||||
return `${rankName(v)} 트리플`;
|
||||
case 'fullHouse':
|
||||
return `풀하우스(${rankName(v)})`;
|
||||
case 'pairSeq':
|
||||
return `연속 페어 ${rankName(v - c.length / 2 + 1)}~${rankName(v)}`;
|
||||
case 'straight':
|
||||
return `스트레이트 ${c.length}장(${rankName(v - c.length + 1)}~${rankName(v)})`;
|
||||
case 'bomb4':
|
||||
return `폭탄(${rankName(v)} 넉 장)`;
|
||||
case 'bombSF':
|
||||
return `폭탄(스트레이트 플러시 ${c.length}장 ${rankName(v - c.length + 1)}~${rankName(v)})`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Short kind name for "앞 조합(페어)과 모양이 달라요". */
|
||||
export function comboKind(c: Combo): string {
|
||||
switch (c.type) {
|
||||
case 'single':
|
||||
return '싱글';
|
||||
case 'pair':
|
||||
return '페어';
|
||||
case 'triple':
|
||||
return '트리플';
|
||||
case 'fullHouse':
|
||||
return '풀하우스';
|
||||
case 'pairSeq':
|
||||
return `연속 페어 ${c.length / 2}쌍`;
|
||||
case 'straight':
|
||||
return `스트레이트 ${c.length}장`;
|
||||
case 'dog':
|
||||
return '개';
|
||||
default:
|
||||
return '폭탄';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- finder
|
||||
|
||||
export interface Found {
|
||||
cards: string[];
|
||||
combo: Combo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Representative combinations in `hand` that may go on `top` (all bombs; one of each kind × length × value × phoenix ×
|
||||
* wish card, §8.7). Leading (`top` null) includes the dog. Card choice: lowest card id first; a straight that would
|
||||
* accidentally be one suit swaps in another suit when it can.
|
||||
*/
|
||||
export function findCombos(hand: readonly string[], top: Combo | null, wish: Rank | null = null): Found[] {
|
||||
const sorted = sortCards(hand);
|
||||
const byRank = new Map<number, string[]>();
|
||||
for (const c of sorted) {
|
||||
if (!isNumber(c) && c !== MJ) continue;
|
||||
const r = rankOf(c);
|
||||
byRank.set(r, [...(byRank.get(r) ?? []), c]);
|
||||
}
|
||||
const cnt = (r: number) => byRank.get(r)?.length ?? 0;
|
||||
const ph = hand.includes(PH);
|
||||
const cand: string[][] = [];
|
||||
/** Only kinds that could follow `top` (bombs always). */
|
||||
const want = (t: ComboType) => !top || top.type === t;
|
||||
const add = (cards: string[]) => cand.push(cards);
|
||||
// A wish card of rank r first when the wish is r (lowest id otherwise; all cards of a rank are equal otherwise).
|
||||
const pickRank = (r: number, k: number): string[] => (byRank.get(r) ?? []).slice(0, k);
|
||||
|
||||
// Singles.
|
||||
if (want('single')) {
|
||||
for (const [r] of byRank) add(pickRank(r, 1));
|
||||
if (ph) add([PH]);
|
||||
if (hand.includes(DR)) add([DR]);
|
||||
}
|
||||
if (!top && hand.includes(DOG)) add([DOG]);
|
||||
// Pairs, triples.
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const k = cnt(r);
|
||||
if (want('pair')) {
|
||||
if (k >= 2) add(pickRank(r, 2));
|
||||
if (k >= 1 && ph) add([...pickRank(r, 1), PH]);
|
||||
}
|
||||
if (want('triple')) {
|
||||
if (k >= 3) add(pickRank(r, 3));
|
||||
if (k === 2 && ph) add([...pickRank(r, 2), PH]);
|
||||
}
|
||||
}
|
||||
// Full houses: per triple rank, the lowest pair, the lowest phoenix pair, and a wish pair.
|
||||
if (want('fullHouse')) {
|
||||
for (let t = 2; t <= 14; t++) {
|
||||
const tk = cnt(t);
|
||||
const triples: { cards: string[]; usesPh: boolean }[] = [];
|
||||
if (tk >= 3) triples.push({ cards: pickRank(t, 3), usesPh: false });
|
||||
if (tk === 2 && ph) triples.push({ cards: [...pickRank(t, 2), PH], usesPh: true });
|
||||
for (const tr of triples) {
|
||||
const pairs: string[][] = [];
|
||||
const realPair = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].find((p) => p !== t && cnt(p) >= 2);
|
||||
if (realPair !== undefined) pairs.push(pickRank(realPair, 2));
|
||||
if (!tr.usesPh && ph) {
|
||||
const single = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].find((p) => p !== t && cnt(p) >= 1);
|
||||
if (single !== undefined) pairs.push([...pickRank(single, 1), PH]);
|
||||
}
|
||||
if (wish !== null && wish !== t) {
|
||||
if (cnt(wish) >= 2) pairs.push(pickRank(wish, 2));
|
||||
if (!tr.usesPh && ph && cnt(wish) >= 1) pairs.push([...pickRank(wish, 1), PH]);
|
||||
}
|
||||
for (const p of pairs) add([...tr.cards, ...p]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pair sequences (one missing card may be the phoenix).
|
||||
for (let lo = 2; lo <= 13 && want('pairSeq'); lo++) {
|
||||
let usesPh = false;
|
||||
const cards: string[] = [];
|
||||
for (let hi = lo; hi <= 14; hi++) {
|
||||
const k = cnt(hi);
|
||||
if (k >= 2) cards.push(...pickRank(hi, 2));
|
||||
else if (k === 1 && ph && !usesPh) {
|
||||
usesPh = true;
|
||||
cards.push(...pickRank(hi, 1), PH);
|
||||
} else break;
|
||||
if (hi > lo) add([...cards]);
|
||||
}
|
||||
}
|
||||
// Straights (≥ 5, the mahjong as 1; the phoenix fills one gap, or stands in for one rank).
|
||||
for (let lo = 1; lo <= 10 && want('straight'); lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
if (top && hi - lo + 1 !== top.length) continue;
|
||||
const missing: number[] = [];
|
||||
for (let r = lo; r <= hi; r++) if (cnt(r) === 0) missing.push(r);
|
||||
if (missing.length > 1) break;
|
||||
const variants: number[][] = []; // ranks the phoenix replaces (empty = none)
|
||||
if (missing.length === 1) {
|
||||
if (!ph || missing[0] === 1) continue;
|
||||
variants.push([missing[0]!]);
|
||||
} else {
|
||||
variants.push([]);
|
||||
if (ph) {
|
||||
variants.push([hi]);
|
||||
if (wish !== null && wish >= lo && wish <= hi && wish !== hi && wish !== 1) variants.push([wish]);
|
||||
}
|
||||
}
|
||||
for (const v of variants) {
|
||||
const cards: string[] = [];
|
||||
for (let r = lo; r <= hi; r++) cards.push(v.includes(r) ? PH : pickRank(r, 1)[0]!);
|
||||
const real = cards.filter((c) => isNumber(c));
|
||||
if (real.length === cards.length && real.every((c) => c[0] === real[0]![0])) {
|
||||
// Accidentally a straight flush: swap one card for another suit if there is one (the bomb is listed below).
|
||||
let swapped = false;
|
||||
for (let i = 0; i < cards.length && !swapped; i++) {
|
||||
const alt = (byRank.get(rankOf(cards[i]!)) ?? []).find((c) => c[0] !== cards[i]![0]);
|
||||
if (alt) {
|
||||
cards[i] = alt;
|
||||
swapped = true;
|
||||
}
|
||||
}
|
||||
if (!swapped) continue;
|
||||
}
|
||||
add(cards);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Bombs: four of a kind and every straight flush.
|
||||
for (let r = 2; r <= 14; r++) if (cnt(r) === 4) add(pickRank(r, 4));
|
||||
for (const s of SUITS) {
|
||||
const have = new Set(sorted.filter((c) => c[0] === s && isNumber(c)).map(rankOf));
|
||||
for (let lo = 2; lo <= 10; lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
let ok = true;
|
||||
for (let r = lo; r <= hi && ok; r++) ok = have.has(r);
|
||||
if (!ok) break;
|
||||
add(Array.from({ length: hi - lo + 1 }, (_, i) => `${s}${lo + i}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const out: Found[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const cards of cand) {
|
||||
const combo = classify(cards, top);
|
||||
if (!combo) continue;
|
||||
if (top && !beats(combo, top)) continue;
|
||||
const key = isBomb(combo)
|
||||
? `B|${sortCards(cards).join(',')}`
|
||||
: `${combo.type}|${combo.length}|${combo.value}|${cards.includes(PH)}|${includesWish(cards, wish)}|${cards.length === 1 ? cards[0] : ''}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({ cards: sortCards(cards), combo });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bombs in a hand (four of a kind, every straight flush), weakest first. */
|
||||
export function findBombs(hand: readonly string[]): Found[] {
|
||||
const out: Found[] = [];
|
||||
const nums = hand.filter(isNumber);
|
||||
for (let r = 2; r <= 14; r++) {
|
||||
const four = SUITS.map((x) => `${x}${r}`);
|
||||
if (four.every((c) => nums.includes(c))) out.push({ cards: four, combo: { type: 'bomb4', length: 4, value: r, phoenixAs: null } });
|
||||
}
|
||||
for (const x of SUITS) {
|
||||
const have = new Set(nums.filter((c) => c[0] === x).map(rankOf));
|
||||
for (let lo = 2; lo <= 10; lo++) {
|
||||
for (let hi = lo + 4; hi <= 14; hi++) {
|
||||
if (!have.has(hi) || ![...Array(hi - lo).keys()].every((k) => have.has(lo + k))) break;
|
||||
out.push({ cards: Array.from({ length: hi - lo + 1 }, (_, i) => `${x}${lo + i}`), combo: { type: 'bombSF', length: hi - lo + 1, value: hi, phoenixAs: null } });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.combo.length - b.combo.length || a.combo.value - b.combo.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* The mahjong wish duty (§5.3): on my own turn, holding a real card of the wished rank and able to play it in a legal
|
||||
* combination (phoenix and bombs included), I must. Leading, a single of that rank always works.
|
||||
*/
|
||||
export function mustFulfillWish(hand: readonly string[], top: Combo | null, wish: Rank | null, leading: boolean): boolean {
|
||||
if (wish === null || !includesWish(hand, wish)) return false;
|
||||
if (leading) return true;
|
||||
return findCombos(hand, top, wish).some((f) => includesWish(f.cards, wish));
|
||||
}
|
||||
|
||||
/** Weakest first: non-bombs before bombs, then value, then more cards first. */
|
||||
export const weakestFirst = (a: Found, b: Found): number =>
|
||||
Number(isBomb(a.combo)) - Number(isBomb(b.combo)) || a.combo.value - b.combo.value || b.cards.length - a.cards.length;
|
||||
1326
packages/games/src/tichu/index.ts
Normal file
1326
packages/games/src/tichu/index.ts
Normal file
File diff suppressed because it is too large
Load Diff
878
packages/games/src/tichu/tichu.test.ts
Normal file
878
packages/games/src/tichu/tichu.test.ts
Normal file
@@ -0,0 +1,878 @@
|
||||
/** 티츄 rules (docs/games/tichu.md §10). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN, type AnyGameDefinition } from '@bg/engine';
|
||||
import {
|
||||
DOG,
|
||||
DR,
|
||||
FULL_DECK,
|
||||
MJ,
|
||||
PH,
|
||||
allCards,
|
||||
beats,
|
||||
cardPoints,
|
||||
classify,
|
||||
findCombos,
|
||||
mustFulfillWish,
|
||||
scoreRound,
|
||||
tichu,
|
||||
type Combo,
|
||||
type TichuAction,
|
||||
type TichuOptions,
|
||||
type TichuState,
|
||||
type TichuView,
|
||||
} from './index';
|
||||
|
||||
const P4 = ['A', 'B', 'C', 'D'];
|
||||
const P3 = ['A', 'B', 'C'];
|
||||
const P6 = ['A', 'B', 'C', 'D', 'E', 'F'];
|
||||
let clock = 1_000_000;
|
||||
|
||||
function make(opts: Partial<TichuOptions> = {}, players = P4, seed = 1): TichuState {
|
||||
const options = tichu.optionsSchema.parse(opts);
|
||||
return tichu.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
}
|
||||
|
||||
/** Seats hands (by seat), starts a trick on `current` (optionally with plays on the table) in phase playing. */
|
||||
function rig(
|
||||
s: TichuState,
|
||||
r: { hands: string[][]; current?: number; plays?: { seat: number; cards: string[] }[]; wish?: number | null; won?: string[][] },
|
||||
): TichuState {
|
||||
s.hands = r.hands.map((h) => [...h]);
|
||||
s.pending = s.seats.map(() => []);
|
||||
s.won = r.won ?? s.seats.map(() => []);
|
||||
s.phase = { kind: 'playing' };
|
||||
s.out = [];
|
||||
s.played = s.seats.map(() => false);
|
||||
s.calls = s.seats.map(() => 'none');
|
||||
s.wish = r.wish ?? null;
|
||||
s.current = r.current ?? 0;
|
||||
s.trick = { leader: r.plays?.[0]?.seat ?? s.current, plays: [], passed: [], closingAt: null, waived: [] };
|
||||
let top: Combo | null = null;
|
||||
for (const p of r.plays ?? []) {
|
||||
const combo: Combo = classify(p.cards, top)!;
|
||||
s.trick.plays.push({ seat: p.seat, cards: p.cards, combo, outOfTurn: false });
|
||||
top = combo;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
const act = (s: TichuState, p: string, a: TichuAction, now = (clock += 1000)): TichuState => {
|
||||
const v = tichu.validate(s, p, a);
|
||||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||||
return tichu.apply(s, p, a, { rng: SeededRng.fromSeed([3, 3, 3, 3]), now }).state;
|
||||
};
|
||||
const reject = (s: TichuState, p: string, a: TichuAction): string | null => {
|
||||
const v = tichu.validate(s, p, a);
|
||||
return v.ok ? null : v.reason;
|
||||
};
|
||||
const play = (s: TichuState, p: string, cardIds: string[], extra: Partial<Extract<TichuAction, { type: 'play' }>> = {}) => act(s, p, { type: 'play', cardIds, ...extra });
|
||||
const pass = (s: TichuState, p: string) => act(s, p, { type: 'pass' });
|
||||
const view = (s: TichuState, p: string | null) => tichu.view(s, p) as TichuView;
|
||||
const C = (ids: string) => ids.split(' ');
|
||||
const cl = (ids: string, top: Combo | null = null) => classify(C(ids), top);
|
||||
|
||||
/** A legal hand filler: cards not used elsewhere (low, no specials), `n` of them. */
|
||||
function filler(used: string[], n: number): string[] {
|
||||
return FULL_DECK.filter((c) => !used.includes(c) && c !== MJ && c !== DOG && c !== PH && c !== DR).slice(0, n);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- deck / deal
|
||||
|
||||
describe('덱과 배분', () => {
|
||||
test('56장, 카드 점수 합 100, 8장 → 6장, 각자 14장, 같은 시드면 같은 배분', () => {
|
||||
expect(FULL_DECK).toHaveLength(56);
|
||||
expect(new Set(FULL_DECK).size).toBe(56);
|
||||
expect(cardPoints(FULL_DECK)).toBe(100);
|
||||
expect(cardPoints(FULL_DECK, 'negative')).toBe(-100);
|
||||
const s = make();
|
||||
expect(s.phase.kind).toBe('grand');
|
||||
expect(s.hands.map((h) => h.length)).toEqual([8, 8, 8, 8]);
|
||||
expect(s.pending.map((h) => h.length)).toEqual([6, 6, 6, 6]);
|
||||
expect(new Set(allCards(s)).size).toBe(56);
|
||||
expect(JSON.stringify(make())).toBe(JSON.stringify(s));
|
||||
let t = s;
|
||||
for (const p of P4) t = act(t, p, { type: 'grand', call: false });
|
||||
expect(t.phase.kind).toBe('exchange');
|
||||
expect(t.hands.map((h) => h.length)).toEqual([14, 14, 14, 14]);
|
||||
});
|
||||
|
||||
test('그랜드 티츄 끄기: 14장을 한 번에 받고 바로 교환', () => {
|
||||
const s = make({ grandTichu: false });
|
||||
expect(s.phase.kind).toBe('exchange');
|
||||
expect(s.hands.map((h) => h.length)).toEqual([14, 14, 14, 14]);
|
||||
expect(reject(s, 'A', { type: 'grand', call: true })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- combos
|
||||
|
||||
describe('조합 판정 (§5.1)', () => {
|
||||
test('모양', () => {
|
||||
expect(cl('j5 s5 j6 s6')?.type).toBe('pairSeq');
|
||||
expect(cl('j5 s5 j7 s7')).toBeNull();
|
||||
expect(cl('MJ j2 s3 b4 t5')).toMatchObject({ type: 'straight', value: 5, length: 5 });
|
||||
expect(cl('j12 s13 b14 t2 j3')).toBeNull();
|
||||
expect(cl('j4 s5 b6 t7')).toBeNull();
|
||||
expect(cl('j3 s3 b3 t3 PH')).toBeNull();
|
||||
expect(cl('j9 s9 b9 PH')).toBeNull();
|
||||
expect(cl('j9 s9 b9 t9')?.type).toBe('bomb4');
|
||||
expect(cl('MJ j2')).toBeNull();
|
||||
expect(cl('DOG j2')).toBeNull();
|
||||
expect(cl('DR PH')).toBeNull();
|
||||
const fh6 = cl('j6 s6 b6 j2 s2')!;
|
||||
const fh5 = cl('j5 s5 b5 j14 s14')!;
|
||||
expect(fh6).toMatchObject({ type: 'fullHouse', value: 6 });
|
||||
expect(beats(fh6, fh5)).toBe(true);
|
||||
expect(beats(fh5, fh6)).toBe(false);
|
||||
});
|
||||
|
||||
test('봉황 해석: 가장 센 것, 앞 조합을 이기는 해석이 있으면 그것', () => {
|
||||
expect(cl('j7 s7 j9 s9 PH')).toMatchObject({ type: 'fullHouse', value: 9, phoenixAs: 9 });
|
||||
expect(cl('j3 s4 b5 t6 PH')).toMatchObject({ type: 'straight', value: 7 });
|
||||
expect(cl('j10 s11 b12 t13 PH')).toMatchObject({ type: 'straight', value: 14 });
|
||||
const top = cl('j4 s5 b6 t7 j8')!;
|
||||
const mine = cl('s5 b6 t7 s8 PH', top)!;
|
||||
expect(mine).toMatchObject({ type: 'straight', value: 9 });
|
||||
expect(beats(mine, top)).toBe(true);
|
||||
expect(cl('j9 PH')).toMatchObject({ type: 'pair', value: 9 });
|
||||
expect(cl('j11 s11 j12 s12 PH j13')).toMatchObject({ type: 'pairSeq', value: 13, length: 6 });
|
||||
});
|
||||
|
||||
test('싱글 봉황: 앞 싱글 + 0.5, 선 1.5, 용 위는 안 됨', () => {
|
||||
const eight = cl('j8')!;
|
||||
const ph = classify([PH], eight)!;
|
||||
expect(ph.value).toBe(8.5);
|
||||
expect(beats(ph, eight)).toBe(true);
|
||||
expect(beats(cl('s9')!, ph)).toBe(true);
|
||||
expect(beats(cl('s8')!, ph)).toBe(false);
|
||||
expect(classify([PH])!.value).toBe(1.5);
|
||||
expect(beats(cl('j2')!, classify([PH])!)).toBe(true);
|
||||
expect(classify([PH], classify([MJ]))!.value).toBe(1.5);
|
||||
const aceP = classify([PH], cl('j14'))!;
|
||||
expect(aceP.value).toBe(14.5);
|
||||
expect(beats(classify([DR])!, aceP)).toBe(true);
|
||||
expect(beats(classify([PH], classify([DR]))!, classify([DR])!)).toBe(false);
|
||||
});
|
||||
|
||||
test('장수가 같아야 비교', () => {
|
||||
const six = cl('j3 s4 b5 t6 j7 s8')!;
|
||||
expect(beats(cl('j4 s5 b6 t7 j8')!, six)).toBe(false);
|
||||
expect(beats(cl('j4 s5 b6 t7 j8 s9 b10')!, six)).toBe(false);
|
||||
expect(beats(cl('j4 s5 b6 t7 j8 s9')!, six)).toBe(true);
|
||||
const two = cl('j5 s5 j6 s6')!;
|
||||
expect(beats(cl('j7 s7 j8 s8 j9 s9')!, two)).toBe(false);
|
||||
expect(beats(cl('j7 s7 j8 s8')!, two)).toBe(true);
|
||||
});
|
||||
|
||||
test('폭탄 순서: 8888 < AAAA < 5장 SF(9~K) < 6장 SF(2~7); 같은 무늬 5장은 늘 폭탄', () => {
|
||||
const b8 = cl('j8 s8 b8 t8')!;
|
||||
const bA = cl('j14 s14 b14 t14')!;
|
||||
const sf5 = cl('j9 j10 j11 j12 j13')!;
|
||||
const sf6 = cl('s2 s3 s4 s5 s6 s7')!;
|
||||
expect(sf5.type).toBe('bombSF');
|
||||
expect(beats(bA, b8)).toBe(true);
|
||||
expect(beats(sf5, bA)).toBe(true);
|
||||
expect(beats(sf6, sf5)).toBe(true);
|
||||
expect(beats(b8, bA)).toBe(false);
|
||||
expect(beats(b8, cl('DR')!)).toBe(true);
|
||||
expect(cl('s3 s4 s5 s6 s7')!.type).toBe('bombSF');
|
||||
expect(cl('s3 s4 s5 s6 s7 t8')).toMatchObject({ type: 'straight', length: 6 });
|
||||
// On a 5-card straight the one-suit run goes on as a bomb, not as a straight.
|
||||
const st = cl('j2 s3 b4 t5 j6')!;
|
||||
expect(cl('s3 s4 s5 s6 s7', st)!.type).toBe('bombSF');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- tricks
|
||||
|
||||
describe('트릭 (§5.2)', () => {
|
||||
test('따라 내기·패스·트릭 끝(카드 모으는 중 → 모으기)', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('j8 s9'), C('j10 s2'), C('j11 s3'), C('j12 s4')], current: 0 });
|
||||
expect(reject(s, 'A', { type: 'pass' })).toContain('패스할 수 없어요');
|
||||
s = play(s, 'A', ['j8']);
|
||||
expect(s.current).toBe(3); // right = counter-clockwise: 0 → 3
|
||||
expect(reject(s, 'D', { type: 'play', cardIds: ['s4'] })).toBe('더 센 조합만 낼 수 있어요.');
|
||||
expect(reject(s, 'C', { type: 'play', cardIds: ['j11'] })).toBe('지금은 내 차례가 아니에요.');
|
||||
s = play(s, 'D', ['j12']);
|
||||
s = pass(s, 'C');
|
||||
s = pass(s, 'B');
|
||||
s = pass(s, 'A');
|
||||
expect(s.trick.closingAt).not.toBeNull();
|
||||
expect(tichu.activePlayers(s).sort()).toEqual(P4);
|
||||
for (const p of P4) s = act(s, p, { type: 'noBomb' });
|
||||
expect(s.won[3]).toEqual(['j8', 'j12']);
|
||||
expect(s.current).toBe(3);
|
||||
expect(s.trick.plays).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('카드 모으는 시간이 끝나면 시간 초과로 모아요(자리 비움에는 안 셈)', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('j8 s9'), C('j10 s2'), C('j11 s3'), C('j12 s4')], current: 0 });
|
||||
s = play(s, 'A', ['j8']);
|
||||
s = pass(s, 'D');
|
||||
s = pass(s, 'C');
|
||||
s = pass(s, 'B', );
|
||||
expect(tichu.deadline!(s)).toBe(s.trick.closingAt);
|
||||
s = act(s, 'C', { type: 'timeout' });
|
||||
expect(s.won[0]).toEqual(['j8']);
|
||||
expect(s.timeoutsInRow.C).toBe(0);
|
||||
});
|
||||
|
||||
test('나간 사람은 패스 판정에서 빠지고, 맨 위 낸 사람이 나갔으면 다음 사람이 선', () => {
|
||||
let s = make({ grandTichu: false, bombTiming: 'ownTurn' });
|
||||
s = rig(s, { hands: [C('j14'), C('j10 s2'), C('j11 s3'), C('j12 s4')], current: 0 });
|
||||
s = play(s, 'A', ['j14']);
|
||||
expect(s.out).toEqual([0]);
|
||||
s = pass(s, 'D');
|
||||
s = pass(s, 'C');
|
||||
s = pass(s, 'B');
|
||||
expect(s.won[0]).toEqual(['j14']);
|
||||
expect(s.current).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('끼어드는 폭탄 (§5.5)', () => {
|
||||
const setup = (o: Partial<TichuOptions> = {}) => {
|
||||
const s = make({ grandTichu: false, ...o });
|
||||
return rig(s, { hands: [C('j8 s3'), C('j9 s9 b9 t9 j2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||||
};
|
||||
test('차례가 아니어도 바닥 위에 폭탄, 다음 차례는 폭탄 낸 사람 다음', () => {
|
||||
let s = setup();
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBe('폭탄은 바닥에 카드가 있을 때만 끼어들 수 있어요.');
|
||||
s = play(s, 'A', ['j8']);
|
||||
expect(s.current).toBe(3);
|
||||
s = play(s, 'B', C('j9 s9 b9 t9'));
|
||||
expect(s.trick.plays.at(-1)!.outOfTurn).toBe(true);
|
||||
expect(s.current).toBe(0); // after seat 1 (right) is seat 0
|
||||
});
|
||||
test('내 조합 위에 내 폭탄, 카드 모으는 중 폭탄, 모은 뒤 거부', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('j8 j9 s9 b9 t9 s3'), C('j10 s2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||||
s = play(s, 'A', ['j8']);
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBeNull();
|
||||
s = pass(s, 'D');
|
||||
s = pass(s, 'C');
|
||||
s = pass(s, 'B');
|
||||
expect(s.trick.closingAt).not.toBeNull();
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: ['s3'] })).toBe('카드 모으는 중에는 폭탄만 낼 수 있어요.');
|
||||
const withBomb = s;
|
||||
s = play(withBomb, 'A', C('j9 s9 b9 t9'));
|
||||
expect(s.trick.closingAt).toBeNull();
|
||||
expect(s.current).toBe(3);
|
||||
// Collected instead: no bomb on an empty table.
|
||||
let t = withBomb;
|
||||
for (const p of P4) t = act(t, p, { type: 'noBomb' });
|
||||
expect(t.trick.plays).toHaveLength(0);
|
||||
expect(reject(t, 'D', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBeTruthy();
|
||||
expect(reject(t, 'A', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBeNull(); // A leads: a bomb as lead is fine
|
||||
});
|
||||
test('개 직후 끼어들기 거부, ownTurn이면 차례 밖 폭탄 거부', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('DOG s3'), C('j9 s9 b9 t9 j2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||||
s = play(s, 'A', [DOG]);
|
||||
expect(s.current).toBe(2);
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toBe('폭탄은 바닥에 카드가 있을 때만 끼어들 수 있어요.');
|
||||
let o = setup({ bombTiming: 'ownTurn' });
|
||||
o = play(o, 'A', ['j8']);
|
||||
expect(reject(o, 'B', { type: 'play', cardIds: C('j9 s9 b9 t9') })).toContain('자기 차례에만');
|
||||
});
|
||||
test('카드 모으는 중 activePlayers는 폭탄이 있든 없든 카드가 남은 모두', () => {
|
||||
const run = (bomb: boolean) => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('j8 s3'), bomb ? C('j9 s9 b9 t9 j2') : C('j9 s10 b11 t12 j2'), C('j11 s4'), C('j12 s5')], current: 0 });
|
||||
s = play(s, 'A', ['j8']);
|
||||
for (const p of ['D', 'C', 'B']) s = pass(s, p);
|
||||
return [...tichu.activePlayers(s)].sort();
|
||||
};
|
||||
expect(run(true)).toEqual(run(false));
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- wish
|
||||
|
||||
describe('참새 소원 (§5.3)', () => {
|
||||
test('참새 + 소원 8 → 8을 가진 다음 사람은 8 싱글만(9·패스 거부)', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('MJ s3'), C('j9 s2'), C('j7 s4'), C('j8 s9')], current: 0 });
|
||||
s = play(s, 'A', [MJ], { wish: 8 });
|
||||
expect(s.wish).toBe(8);
|
||||
expect(reject(s, 'D', { type: 'play', cardIds: ['s9'] })).toContain('소원 8');
|
||||
expect(reject(s, 'D', { type: 'pass' })).toContain('소원 8');
|
||||
expect(view(s, 'D').my!.mustWish).toBe(8);
|
||||
s = play(s, 'D', ['j8']);
|
||||
expect(s.wish).toBeNull();
|
||||
});
|
||||
test('8이 없고 봉황만 있으면 의무 없음', () => {
|
||||
expect(mustFulfillWish(C('PH s9'), cl('j3'), 8, false)).toBe(false);
|
||||
});
|
||||
test('바닥 7 7, 손 8 봉황 → 8 봉황(8 페어)을 내야 함', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('s3'), C('j8 PH j13 s13'), C('s4'), C('s5')], current: 1, plays: [{ seat: 2, cards: C('j7 s7') }], wish: 8 });
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: C('j13 s13') })).toContain('소원 8');
|
||||
expect(reject(s, 'B', { type: 'pass' })).toContain('소원 8');
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: C('j8 PH') })).toBeNull();
|
||||
});
|
||||
test('바닥 용, 손 8888 → 폭탄만 허용', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('s3'), C('j8 s8 b8 t8 j2'), C('s4'), C('s5')], current: 1, plays: [{ seat: 2, cards: [DR] }], wish: 8 });
|
||||
expect(reject(s, 'B', { type: 'pass' })).toContain('소원 8');
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: C('j8 s8 b8 t8') })).toBeNull();
|
||||
});
|
||||
test('선이 8을 가지면 8 포함 조합만(개 거부)', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('DOG j8 s3'), C('s4'), C('s5'), C('s6')], current: 0, wish: 8 });
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: [DOG] })).toContain('소원 8');
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: ['s3'] })).toContain('소원 8');
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: ['j8'] })).toBeNull();
|
||||
});
|
||||
test('끼어드는 폭탄은 의무 없음, 8이 끼어든 폭탄으로 나와도 소원이 풀림, 소원은 트릭을 넘어 유지', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('MJ j8 s3'), C('j9 s9 b9 t9 j2'), C('j3 j4 j5 j6 j7 b8'), C('s5 s12')], current: 0 });
|
||||
s = play(s, 'A', [MJ], { wish: 8 });
|
||||
// D has no 8: free. Then B bombs out of turn without an 8 (no duty for an interrupting bomb).
|
||||
s = play(s, 'D', ['s5']);
|
||||
s = play(s, 'B', C('j9 s9 b9 t9'));
|
||||
expect(s.wish).toBe(8);
|
||||
for (const p of ['A', 'D', 'C']) s = pass(s, p === 'A' ? 'A' : p);
|
||||
expect(s.trick.closingAt).not.toBeNull();
|
||||
// C bombs with a straight flush that holds a real 8? No: j3..j7 + b8 is mixed. Pass the window.
|
||||
for (const p of P4) s = act(s, p, { type: 'noBomb' });
|
||||
expect(s.wish).toBe(8); // survives the trick
|
||||
// A straight flush containing 8 ends the wish even out of turn.
|
||||
let t = make({ grandTichu: false });
|
||||
t = rig(t, { hands: [C('s3 s4'), C('j9 s2'), C('j4 j5 j6 j7 j8 b11'), C('s5 s12')], current: 0, wish: 8 });
|
||||
t = play(t, 'A', ['s3']);
|
||||
t = play(t, 'C', C('j4 j5 j6 j7 j8'));
|
||||
expect(t.wish).toBeNull();
|
||||
});
|
||||
test('스트레이트 안의 참새도 소원을 걸어요', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('MJ j2 s3 b4 t5 s9'), C('s6'), C('s7'), C('s8')], current: 0 });
|
||||
s = play(s, 'A', C('MJ j2 s3 b4 t5'), { wish: 11 });
|
||||
expect(s.wish).toBe(11);
|
||||
expect(reject(s, 'D', { type: 'play', cardIds: ['s8'], wish: 3 })).toContain('참새');
|
||||
});
|
||||
});
|
||||
|
||||
describe('소원 위반 패널티 (wishRule = penalty)', () => {
|
||||
test('의무를 어긴 패스 → 즉시 라운드 끝, 상대 팀 200 + 상대 선언 성공, 위반 팀 선언 실패', () => {
|
||||
let s = make({ grandTichu: false, wishRule: 'penalty' });
|
||||
s = rig(s, { hands: [C('MJ s3'), C('j8 s9'), C('j7 s4'), C('j9 s2')], current: 0 });
|
||||
s.calls = ['tichu', 'none', 'none', 'tichu'];
|
||||
s = play(s, 'A', [MJ], { wish: 8 });
|
||||
s = play(s, 'D', ['j9']);
|
||||
s = pass(s, 'C');
|
||||
expect(view(s, 'B').my!.mustWish).toBeNull(); // the screen does not tell in penalty mode
|
||||
s = pass(s, 'B'); // B holds an 8 that beats 9? no: 8 < 9, so B is free here
|
||||
expect(s.phase.kind).toBe('playing');
|
||||
let t = make({ grandTichu: false, wishRule: 'penalty' });
|
||||
t = rig(t, { hands: [C('MJ s3'), C('j8 s9'), C('j7 s4'), C('j6 s2')], current: 0 });
|
||||
t.calls = ['tichu', 'none', 'none', 'tichu'];
|
||||
t = play(t, 'A', [MJ], { wish: 8 });
|
||||
t = play(t, 'D', ['j6']);
|
||||
t = pass(t, 'C');
|
||||
t = pass(t, 'B'); // B could play the 8: penalty for team B (seats 1·3)
|
||||
const r = t.rounds.at(-1)!;
|
||||
expect(r.kind).toBe('penalty');
|
||||
expect(r.bonus).toEqual([200, 0]);
|
||||
expect(r.cardPoints).toEqual([0, 0]);
|
||||
expect(r.callPoints).toEqual([100, -100]);
|
||||
expect(t.scores).toEqual([300, -100]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- dog / dragon
|
||||
|
||||
describe('개와 용 (§5.3)', () => {
|
||||
test('개: 선만, 짝꿍이 선, 짝꿍이 나갔으면 짝꿍 다음 카드 남은 사람', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('DOG s3'), C('s6'), C('s7'), C('s8')], current: 0 });
|
||||
s = play(s, 'A', [DOG]);
|
||||
expect(s.current).toBe(2);
|
||||
expect(s.won[0]).toEqual([DOG]);
|
||||
let t = make({ grandTichu: false });
|
||||
t = rig(t, { hands: [C('s9'), C('s6'), C('s7'), C('DOG s8')], current: 0 });
|
||||
t = play(t, 'A', ['s9']);
|
||||
expect(reject(t, 'D', { type: 'play', cardIds: [DOG] })).toContain('새 트릭');
|
||||
let u = make({ grandTichu: false });
|
||||
u = rig(u, { hands: [C('DOG s3'), C('s6 s10'), [], C('s8')], current: 0 });
|
||||
u.out = [2];
|
||||
u = play(u, 'A', [DOG]);
|
||||
// partner seat 2 is out; next after 2 in turn order (right: 2 → 1)
|
||||
expect(u.current).toBe(1);
|
||||
});
|
||||
test('tientsin: 개는 dogTo 필수', () => {
|
||||
let s = make({ grandTichu: false, mode: 'tientsin' }, P6);
|
||||
s = rig(s, { hands: [C('DOG s3'), C('s4'), C('s5'), C('s6'), C('s7'), C('s8')], current: 0 });
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: [DOG] })).toContain('짝꿍을 골라');
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: [DOG], dogTo: 1 })).toContain('짝꿍에게만');
|
||||
s = play(s, 'A', [DOG], { dogTo: 4 });
|
||||
expect(s.current).toBe(4);
|
||||
});
|
||||
test('용으로 이기면 상대에게 줌(같은 팀 거부, 나간 상대 허용), 폭탄에 지면 폭탄 낸 사람이 가져감', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('DR s3'), [], C('s7'), C('s8 s9')], current: 0 });
|
||||
s.out = [1];
|
||||
s = play(s, 'A', [DR]);
|
||||
s = pass(s, 'D');
|
||||
s = pass(s, 'C');
|
||||
for (const p of ['A', 'C', 'D']) s = act(s, p, { type: 'noBomb' });
|
||||
expect(s.phase.kind).toBe('dragonGift');
|
||||
expect(reject(s, 'A', { type: 'dragonTo', to: 2 })).toContain('상대 팀');
|
||||
s = act(s, 'A', { type: 'dragonTo', to: 1 });
|
||||
expect(s.won[1]).toEqual([DR]);
|
||||
expect(s.current).toBe(0);
|
||||
let t = make({ grandTichu: false });
|
||||
t = rig(t, { hands: [C('DR s3'), C('j9 s9 b9 t9 s2'), C('s7'), C('s8')], current: 0 });
|
||||
t = play(t, 'A', [DR]);
|
||||
t = play(t, 'B', C('j9 s9 b9 t9'));
|
||||
for (const p of ['A', 'D', 'C']) t = pass(t, p);
|
||||
for (const p of P4) t = act(t, p, { type: 'noBomb' });
|
||||
expect(t.won[1]!.sort()).toEqual([DR, 'j9', 's9', 'b9', 't9'].sort());
|
||||
});
|
||||
test('3등이 용으로 나가 라운드가 끝날 때도 용 주기 후 계산', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('DR'), [], [], C('s7 s4')], current: 0 });
|
||||
s.out = [1, 2];
|
||||
s = play(s, 'A', [DR]);
|
||||
expect(s.phase).toMatchObject({ kind: 'dragonGift', final: true });
|
||||
s = act(s, 'A', { type: 'dragonTo', to: 3 });
|
||||
expect(s.phase.kind).toBe('roundEnd');
|
||||
expect(s.rounds).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- calls / exchange
|
||||
|
||||
describe('티츄 선언 (§5.6)', () => {
|
||||
test('첫 카드 전 허용, 낸 뒤 거부, 그랜드 한 사람은 스몰 거부, 누가 나간 뒤 거부', () => {
|
||||
let s = make();
|
||||
expect(reject(s, 'A', { type: 'tichu' })).toContain('14장');
|
||||
s = act(s, 'A', { type: 'grand', call: true });
|
||||
for (const p of ['B', 'C', 'D']) s = act(s, p, { type: 'grand', call: false });
|
||||
expect(s.calls[0]).toBe('grand');
|
||||
expect(reject(s, 'A', { type: 'tichu' })).toContain('그랜드');
|
||||
s = act(s, 'B', { type: 'tichu' });
|
||||
expect(reject(s, 'B', { type: 'tichu' })).toContain('이미');
|
||||
let t = make({ grandTichu: false });
|
||||
t = rig(t, { hands: [C('s3 s4'), C('s6 s9'), C('s7'), C('s8')], current: 0 });
|
||||
t = play(t, 'A', ['s3']);
|
||||
expect(reject(t, 'A', { type: 'tichu' })).toContain('이미 카드를 내서');
|
||||
expect(reject(t, 'D', { type: 'tichu' })).toBeNull();
|
||||
t = play(t, 'D', ['s8']);
|
||||
expect(t.out).toEqual([3]);
|
||||
expect(reject(t, 'C', { type: 'tichu' })).toContain('다 털어서');
|
||||
});
|
||||
test('교환 중 선언 뒤 다른 사람이 교환을 다시 보낼 수 있음', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
const give = (seat: number, k = 0) => [1, 2, 3].map((d) => ({ to: (seat + d) % 4, cardId: s.hands[seat]![d - 1 + k]! }));
|
||||
s = act(s, 'A', { type: 'exchange', give: give(0) });
|
||||
s = act(s, 'B', { type: 'tichu' });
|
||||
s = act(s, 'A', { type: 'exchange', give: give(0, 3) });
|
||||
expect(s.phase.kind).toBe('exchange');
|
||||
expect((s.phase as { give: unknown[] }).give[0]).toHaveLength(3);
|
||||
});
|
||||
test('그랜드는 끄면 거부, threechu 딜러 거부', () => {
|
||||
const s = make({ mode: 'threechu' }, P3);
|
||||
const dealer = s.players[s.dealer!]!;
|
||||
expect(reject(s, dealer, { type: 'grand', call: true })).toBeTruthy();
|
||||
const other = P3.find((p) => p !== dealer)!;
|
||||
expect(reject(s, other, { type: 'grand', call: true })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('카드 교환 (§5.7)', () => {
|
||||
test('같은 사람에게 2장 거부, 손에 없는 카드 거부, 모두 보내야 옮김, 받은 카드는 받은 사람 view에만', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
const h = s.hands.map((x) => [...x]);
|
||||
expect(reject(s, 'A', { type: 'exchange', give: [{ to: 1, cardId: h[0]![0]! }, { to: 1, cardId: h[0]![1]! }, { to: 2, cardId: h[0]![2]! }] })).toContain('한 사람에게');
|
||||
expect(reject(s, 'A', { type: 'exchange', give: [{ to: 1, cardId: h[1]![0]! }, { to: 2, cardId: h[0]![1]! }, { to: 3, cardId: h[0]![2]! }] })).toContain('손에 없는');
|
||||
const gives = [0, 1, 2, 3].map((seat) => [1, 2, 3].map((d) => ({ to: (seat + d) % 4, cardId: h[seat]![d - 1]! })));
|
||||
for (let i = 0; i < 3; i++) s = act(s, P4[i]!, { type: 'exchange', give: gives[i]! });
|
||||
expect(s.phase.kind).toBe('exchange');
|
||||
expect(s.hands[1]).toEqual(h[1]!);
|
||||
s = act(s, 'D', { type: 'exchange', give: gives[3]! });
|
||||
expect(s.phase.kind).toBe('playing');
|
||||
expect(s.hands.every((x) => x.length === 14)).toBe(true);
|
||||
const got = gives[0]![1]!.cardId; // A → C (partner)
|
||||
expect(s.hands[2]).toContain(got);
|
||||
expect(view(s, 'C').my!.received.some((r) => r.cardId === got && r.from === 0)).toBe(true);
|
||||
for (const p of ['A', 'B', 'D']) expect(JSON.stringify(view(s, p))).not.toContain(`"${got}"`);
|
||||
expect(s.hands[s.current]).toContain(MJ);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- scoring
|
||||
|
||||
describe('점수 (§6)', () => {
|
||||
test('예 1: 스몰 티츄 1등, 꼴찌 손패는 상대 팀, 딴 카드는 1등에게 → 170 : 30', () => {
|
||||
// Seats: 0 지수(A팀), 1 민호(B), 2 서연(A), 3 하늘(B). Out 0, 1, 2; 하늘 keeps K·5 (15) and won a 10.
|
||||
const s = make({ grandTichu: false });
|
||||
rig(s, { hands: [[], [], [], C('j13 j5')], won: [C('s5 s10 s13 b13'), C('b5 t5 b10 DR PH j10'), C('t13 s14'), C('t10')] });
|
||||
s.out = [0, 1, 2];
|
||||
s.calls = ['tichu', 'none', 'none', 'none'];
|
||||
const r = scoreRound(s, 'last', null);
|
||||
expect(r.cardPoints).toEqual([70, 30]);
|
||||
expect(r.total).toEqual([170, 30]);
|
||||
expect(r.handover).toEqual({ hand: 15, won: 10 });
|
||||
});
|
||||
test('예 2: 그랜드 실패 + 원투 → 200 : −200', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('s3'), C('s6 s9'), C('s7'), C('s8 s10')], current: 0 });
|
||||
s.calls = ['none', 'grand', 'none', 'none'];
|
||||
s.out = [2];
|
||||
s.hands[2] = [];
|
||||
s = play(s, 'A', ['s3']);
|
||||
expect(s.rounds.at(-1)!.kind).toBe('double');
|
||||
expect(s.rounds.at(-1)!.total).toEqual([200, -200]);
|
||||
});
|
||||
test('예 3: 짝꿍이 1등이어도 선언한 본인이 아니면 실패(−100)', () => {
|
||||
const s = make({ grandTichu: false });
|
||||
rig(s, { hands: [[], [], [], C('s3')], won: [[], [], FULL_DECK.filter((c) => c !== 's3'), []] });
|
||||
s.out = [2, 1, 0];
|
||||
s.calls = ['tichu', 'none', 'none', 'none'];
|
||||
const r = scoreRound(s, 'last', null);
|
||||
expect(r.callPoints).toEqual([-100, 0]);
|
||||
});
|
||||
test('봉황만 딴 팀은 −25', () => {
|
||||
const t = make({ grandTichu: false });
|
||||
rig(t, { hands: [[], [], C('s3'), []], won: [[PH], FULL_DECK.filter((c) => c !== PH && c !== 's3'), [], []] });
|
||||
t.out = [1, 3, 0];
|
||||
expect(scoreRound(t, 'last', null).cardPoints).toEqual([-25, 125]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('게임 끝 (§6)', () => {
|
||||
test('한 팀 1000 이상이면 끝, 동점이면 한 라운드 더', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
s.out = [2];
|
||||
s.scores = [900, 500];
|
||||
s = play(s, 'A', ['s3']);
|
||||
expect(s.phase.kind).toBe('finished');
|
||||
expect(s.final!.ranking).toEqual([
|
||||
['A', 'C'],
|
||||
['B', 'D'],
|
||||
]);
|
||||
expect(s.final!.scoreText.A).toBe('1,100점');
|
||||
let t = make({ grandTichu: false });
|
||||
t = rig(t, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
t.out = [2];
|
||||
t.scores = [800, 1000];
|
||||
t = play(t, 'A', ['s3']);
|
||||
expect(t.scores).toEqual([1000, 1000]);
|
||||
expect(t.phase.kind).toBe('roundEnd');
|
||||
for (const p of P4) t = act(t, p, { type: 'ready' });
|
||||
expect(t.round).toBe(2);
|
||||
});
|
||||
test('둘 다 넘으면 높은 팀이 이겨요', () => {
|
||||
let t = make({ grandTichu: false });
|
||||
t = rig(t, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
t.out = [2];
|
||||
t.scores = [1000, 1300];
|
||||
t = play(t, 'A', ['s3']);
|
||||
expect(t.final!.ranking[0]).toEqual(['B', 'D']);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- modes
|
||||
|
||||
describe('다른 모드 (§5.9)', () => {
|
||||
test('individual: 짝꿍 3가지 순환, 팀 점수가 두 사람 개인 점수에 같게', () => {
|
||||
let s = make({ mode: 'individual', grandTichu: false });
|
||||
const pairs: string[][] = [];
|
||||
for (let r = 0; r < 4; r++) {
|
||||
pairs.push([`${s.seats[0]!.owner}${s.seats[2]!.owner}`, `${s.seats[1]!.owner}${s.seats[3]!.owner}`]);
|
||||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
s.out = [2];
|
||||
const before = [...s.scores];
|
||||
s = play(s, s.seats[0]!.owner, ['s3']);
|
||||
const r1 = s.rounds.at(-1)!;
|
||||
r1.teams.forEach((team, t) => {
|
||||
for (const p of team) expect(s.scores[P4.indexOf(p)]! - before[P4.indexOf(p)]!).toBe(r1.total[t]!);
|
||||
});
|
||||
for (const p of P4) s = act(s, p, { type: 'ready' });
|
||||
}
|
||||
expect(pairs.slice(0, 3)).toEqual([
|
||||
['AC', 'BD'],
|
||||
['AB', 'CD'],
|
||||
['AD', 'BC'],
|
||||
]);
|
||||
expect(pairs[3]).toEqual(pairs[0]);
|
||||
});
|
||||
|
||||
test('threechu: 2장 교환(딜러↔더미 없음), 교환 뒤 더미 공개, 더미 소원 의무 없음, 딜러 순환, 정해진 판 수 뒤 끝', () => {
|
||||
let s = make({ mode: 'threechu', grandTichu: false, threechuHands: 3 }, P3);
|
||||
const dealer = s.players[s.dealer!]!;
|
||||
expect(s.seats[0]!.owner).toBe(dealer);
|
||||
expect(s.seats[2]).toEqual({ owner: dealer, dummy: true });
|
||||
const opp = P3.filter((p) => p !== dealer);
|
||||
expect(view(s, opp[0]!).seats[2]!.openHand).toBeNull();
|
||||
expect(view(s, dealer).dummy!.hand).toHaveLength(14);
|
||||
// Dealer exchanges for both seats; each gives to its two opponents only.
|
||||
const giveFor = (seat: number) => [1, 3].map((d, i) => ({ to: (seat + d) % 4, cardId: s.hands[seat]![i]! }));
|
||||
expect(reject(s, dealer, { type: 'exchange', give: [{ to: 2, cardId: s.hands[0]![0]! }, { to: 1, cardId: s.hands[0]![1]! }] })).toContain('한 사람에게');
|
||||
s = act(s, dealer, { type: 'exchange', give: giveFor(0) });
|
||||
s = act(s, dealer, { type: 'exchange', seat: 2, give: giveFor(2) });
|
||||
for (const p of opp) s = act(s, p, { type: 'exchange', give: giveFor(s.seats.findIndex((x) => x.owner === p && !x.dummy)) });
|
||||
expect(s.phase.kind).toBe('playing');
|
||||
expect(view(s, opp[0]!).seats[2]!.openHand).toHaveLength(14);
|
||||
// The dummy is free of the wish.
|
||||
s = rig(s, { hands: [C('s3'), C('s4'), C('j8 s9'), C('s5')], current: 2, plays: [{ seat: 1, cards: ['s4'] }], wish: 8 });
|
||||
expect(reject(s, dealer, { type: 'play', seat: 2, cardIds: ['s9'] })).toBeNull();
|
||||
expect(reject(s, dealer, { type: 'pass', seat: 2 })).toBeNull();
|
||||
// Dealer rotates and the game ends after 3 hands.
|
||||
const dealers = [s.dealer];
|
||||
for (let r = 0; r < 3; r++) {
|
||||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
s.out = [2];
|
||||
s = play(s, s.seats[0]!.owner, ['s3']);
|
||||
if (s.phase.kind === 'finished') break;
|
||||
for (const p of P3) s = act(s, p, { type: 'ready' });
|
||||
dealers.push(s.dealer);
|
||||
}
|
||||
expect(new Set(dealers).size).toBe(3);
|
||||
expect(s.phase.kind).toBe('finished');
|
||||
expect(s.final!.ranking.flat().sort()).toEqual(P3);
|
||||
});
|
||||
|
||||
test('tientsin: 10·10·9·9·9·9 배분, 6장 뒤 그랜드, 짝꿍 2명과 교환, 트리플 빅토리 300, 5등 딴 카드 → 1등', () => {
|
||||
let s = make({ mode: 'tientsin' }, P6);
|
||||
expect(s.hands.map((h) => h.length)).toEqual([6, 6, 6, 6, 6, 6]);
|
||||
for (const p of P6) s = act(s, p, { type: 'grand', call: false });
|
||||
expect(s.hands.map((h) => h.length).sort((a, b) => a - b)).toEqual([9, 9, 9, 9, 10, 10]);
|
||||
const starter = s.dealer!;
|
||||
const second = s.order[(s.order.indexOf(starter) + 1) % 6]!;
|
||||
expect(s.hands[starter]).toHaveLength(10);
|
||||
expect(s.hands[second]).toHaveLength(10);
|
||||
expect(view(s, 'A').my!.exchangeTargets.map((t) => t.seat)).toEqual([2, 4]);
|
||||
// Triple victory.
|
||||
let t = make({ mode: 'tientsin', grandTichu: false }, P6);
|
||||
t = rig(t, { hands: [C('s3'), C('s4'), [], C('s5'), [], C('s6')], current: 0 });
|
||||
t.out = [2, 4];
|
||||
t = play(t, 'A', ['s3']);
|
||||
expect(t.rounds.at(-1)!).toMatchObject({ kind: 'triple', bonus: [300, 0], cardPoints: [0, 0] });
|
||||
// Last one gives hand + tricks to the other team, the 5th's tricks go to the first.
|
||||
const u = make({ mode: 'tientsin', grandTichu: false }, P6);
|
||||
rig(u, { hands: [[], [], [], [], [], C('j5')], won: [[], ['j10'], [], [], ['s13'], ['t13']] });
|
||||
u.out = [1, 0, 2, 3, 4];
|
||||
const r = scoreRound(u, 'last', null);
|
||||
// team1 (seats 1,3,5): seat1 10 + seat4's K (5th, team 0) → seat1 → +10 = 20; last seat5 (team1) gives 5 + 10 to team 0.
|
||||
expect(r.cardPoints).toEqual([15, 20]);
|
||||
});
|
||||
|
||||
test('party: 두 배 판, 점수 뒤집기 합 −100, 손패 돌리기 후 선언은 사람에게 남음, 같은 효과 연속 없음', () => {
|
||||
let s = make({ party: true, grandTichu: false, targetScore: 1500 });
|
||||
const effects = [s.effect];
|
||||
for (let r = 0; r < 12; r++) {
|
||||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
s.out = [2];
|
||||
s = play(s, 'A', ['s3']);
|
||||
if (s.phase.kind !== 'roundEnd') break;
|
||||
for (const p of P4) s = act(s, p, { type: 'ready' });
|
||||
effects.push(s.effect);
|
||||
}
|
||||
for (let i = 1; i < effects.length; i++) expect(effects[i]).not.toBe(effects[i - 1]);
|
||||
const d = make({ party: true, grandTichu: false });
|
||||
d.effect = 'double';
|
||||
rig(d, { hands: [[], [], [], C('s3')], won: [FULL_DECK.filter((c) => c !== 's3'), [], [], []] });
|
||||
d.out = [0, 1, 2];
|
||||
expect(scoreRound(d, 'last', null).total).toEqual([200, 0]);
|
||||
const n = make({ party: true, grandTichu: false });
|
||||
n.effect = 'negative';
|
||||
rig(n, { hands: [[], [], [], C('s3')], won: [FULL_DECK.filter((c) => c !== 's3'), [], [], []] });
|
||||
n.out = [0, 1, 2];
|
||||
const rn = scoreRound(n, 'last', null);
|
||||
expect(rn.cardPoints[0]! + rn.cardPoints[1]!).toBe(-100);
|
||||
// Rotate: hands move on after the exchange, calls stay.
|
||||
let rot = make({ party: true, grandTichu: false });
|
||||
rot.effect = 'rotate';
|
||||
rot = act(rot, 'B', { type: 'tichu' });
|
||||
const after = rot.hands.map((h) => [...h]);
|
||||
const give = (seat: number) => [1, 2, 3].map((dd) => ({ to: (seat + dd) % 4, cardId: rot.hands[seat]![dd - 1]! }));
|
||||
const gives = [0, 1, 2, 3].map(give);
|
||||
for (let i = 0; i < 4; i++) rot = act(rot, P4[i]!, { type: 'exchange', give: gives[i]! });
|
||||
expect(rot.calls[1]).toBe('tichu');
|
||||
// seat 0's exchanged hand went to the next seat in turn order (right: 0 → 3)
|
||||
const seat0 = after[0]!.filter((c) => !gives[0]!.some((g) => g.cardId === c));
|
||||
for (const c of seat0) expect(rot.hands[3]).toContain(c);
|
||||
expect(reject(rot, 'B', { type: 'tichu' })).toContain('이미');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- automatic moves
|
||||
|
||||
describe('시간 초과 (§8.5)', () => {
|
||||
test('선 = 가장 약한 싱글, 따라 내기 = 패스, 의무가 있으면 가장 약한 의무 조합', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('s9 j3 DR'), C('s4 s10'), C('s7'), C('j8 s12')], current: 0 });
|
||||
s = act(s, 'A', { type: 'timeout' });
|
||||
expect(s.trick.plays[0]!.cards).toEqual(['j3']);
|
||||
s = act(s, 'D', { type: 'timeout' });
|
||||
expect(s.trick.passed).toEqual([3]);
|
||||
let w = make({ grandTichu: false });
|
||||
w = rig(w, { hands: [C('s3'), C('s4'), C('s7'), C('j8 s8 s12')], current: 3, plays: [{ seat: 0, cards: C('j5 s5') }], wish: 8 });
|
||||
w = act(w, 'D', { type: 'timeout' });
|
||||
expect(w.trick.plays.at(-1)!.cards).toEqual(['j8', 's8']);
|
||||
});
|
||||
test('교환 시간 초과: 상대에게 약한 낱장, 짝꿍에게 가장 센 숫자', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s.hands[0] = C('j2 s3 j5 j9 s9 j13 s14 DOG MJ PH DR b4 t7 b12');
|
||||
s = act(s, 'A', { type: 'timeout' });
|
||||
const g = (s.phase as { give: ({ to: number; card: string }[] | null)[] }).give[0]!;
|
||||
expect(g.find((x) => x.to === 2)!.card).toBe('s14');
|
||||
expect(g.find((x) => x.to === 1)!.card).toBe('j2');
|
||||
expect(g.find((x) => x.to === 3)!.card).toBe('s3');
|
||||
});
|
||||
test('모든 상태에서 onTimeout이 합법', () => {
|
||||
for (const mode of ['team', 'threechu', 'tientsin'] as const) {
|
||||
const players = mode === 'threechu' ? P3 : mode === 'tientsin' ? P6 : P4;
|
||||
let s = make({ mode, targetScore: 300, threechuHands: 3 }, players, 5);
|
||||
for (let i = 0; i < 1500 && !tichu.result(s); i++) {
|
||||
const who = tichu.timeoutPlayers!(s);
|
||||
expect(who.length).toBeGreaterThan(0);
|
||||
const p = who[i % who.length]!;
|
||||
s = act(s, p, tichu.onTimeout(s, p));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('거부되는 행동', () => {
|
||||
test('차례가 아닌 play, 끝난 라운드의 행동은 거부되고 상태가 바뀌지 않음', () => {
|
||||
let s = make({ grandTichu: false });
|
||||
s = rig(s, { hands: [C('s3'), C('s6'), [], C('s7')], current: 0 });
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: ['s6'] })).toBeTruthy();
|
||||
s.out = [2];
|
||||
const before = JSON.stringify(s);
|
||||
expect(reject(s, 'B', { type: 'play', cardIds: ['s6'] })).toBeTruthy();
|
||||
expect(JSON.stringify(s)).toBe(before);
|
||||
s = play(s, 'A', ['s3']);
|
||||
expect(s.phase.kind).toBe('roundEnd');
|
||||
expect(reject(s, 'D', { type: 'play', cardIds: ['s7'] })).toBeTruthy();
|
||||
expect(reject(s, 'D', { type: 'pass' })).toBeTruthy();
|
||||
s = act(s, 'A', { type: 'ready' });
|
||||
expect(reject(s, 'A', { type: 'ready' })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- random play
|
||||
|
||||
/** Random play with fewer wild calls (a uniform pick calls grand tichu every other time and never ends). */
|
||||
const tamed: AnyGameDefinition = {
|
||||
...(tichu as AnyGameDefinition),
|
||||
legalActions(s: TichuState, p: string) {
|
||||
const all = tichu.legalActions(s, p);
|
||||
const rare = (a: TichuAction) => (a.type === 'grand' && a.call) || a.type === 'tichu';
|
||||
const keep = all.filter((a) => !rare(a) || s.seq % 9 === 0);
|
||||
return keep.length ? keep : all;
|
||||
},
|
||||
};
|
||||
|
||||
const CONFIGS: [string, Partial<TichuOptions>, string[]][] = [
|
||||
['team', { targetScore: 300 }, P4],
|
||||
['individual', { mode: 'individual', targetScore: 300 }, P4],
|
||||
['threechu', { mode: 'threechu', threechuHands: 3 }, P3],
|
||||
['tientsin', { mode: 'tientsin', targetScore: 300 }, P6],
|
||||
['variants', { targetScore: 300, wishRule: 'penalty', party: true, bombTiming: 'ownTurn', grandTichu: false, direction: 'left', trickHistory: 'all', turnSeconds: null, exchangeSeconds: null }, P4],
|
||||
['party-left', { targetScore: 500, party: true, direction: 'left', bombWindowSeconds: 1 }, P4],
|
||||
];
|
||||
|
||||
function invariants(s: TichuState, seen: { rounds: number }): void {
|
||||
const all = allCards(s);
|
||||
if (all.length !== 56 || new Set(all).size !== 56) throw new Error(`cards: ${all.length}`);
|
||||
for (const rr of s.rounds.slice(seen.rounds)) {
|
||||
if (rr.kind === 'last' && rr.cardPoints[0]! + rr.cardPoints[1]! !== (rr.effect === 'negative' ? -100 : 100)) throw new Error(`round points ${rr.cardPoints}`);
|
||||
}
|
||||
seen.rounds = s.rounds.length;
|
||||
}
|
||||
|
||||
/** Random legal play without the per-step view checks (those run in the next test); every 100th step is leak-checked. */
|
||||
function fastPlayout(players: string[], options: TichuOptions, seed: number, maxSteps = 8000) {
|
||||
const rng = SeededRng.fromSeed(seedN(seed));
|
||||
const chooser = SeededRng.fromSeed(seedN(seed + 7777));
|
||||
let now = 1_700_000_000_000;
|
||||
let s = tichu.setup({ players, options, rng, now });
|
||||
const seen = { rounds: 0 };
|
||||
const trace: string[] = [];
|
||||
for (let step = 0; step < maxSteps; step++) {
|
||||
invariants(s, seen);
|
||||
if (step % 100 === 0) for (const p of players) checkNoLeak(tichu as AnyGameDefinition, s, p, players);
|
||||
if (tichu.result(s)) return { finished: true, s, trace: trace.join('|'), steps: step };
|
||||
const actives = tichu.activePlayers(s);
|
||||
const actor = actives[chooser.int(actives.length)]!;
|
||||
const legal = (tamed.legalActions!(s, actor) as TichuAction[]) ?? [];
|
||||
const a = legal.length ? legal[chooser.int(legal.length)]! : tichu.onTimeout(s, actor);
|
||||
const v = tichu.validate(s, actor, a);
|
||||
if (!v.ok) throw new Error(`seed ${seed}: rejected ${JSON.stringify(a)}: ${v.reason}`);
|
||||
// Now and then the clock runs out instead (timeouts are legal everywhere).
|
||||
const act2 = chooser.int(20) === 0 && tichu.validate(s, actor, { type: 'timeout' }).ok ? ({ type: 'timeout' } as TichuAction) : a;
|
||||
now += 500 + chooser.int(1500);
|
||||
s = tichu.apply(s, actor, act2, { rng, now }).state;
|
||||
trace.push(JSON.stringify(act2));
|
||||
}
|
||||
return { finished: false, s, trace: trace.join('|'), steps: maxSteps };
|
||||
}
|
||||
|
||||
const SEEDS = playoutSeeds(1000);
|
||||
|
||||
describe(`무작위 대국 (§10, ${SEEDS}판)`, () => {
|
||||
test('끝까지, 카드 56장 보존, 라운드 점수 합 100(뒤집기면 −100), 결과에 모두, 직렬화 왕복, 결정적', () => {
|
||||
let finished = 0;
|
||||
for (let i = 1; i <= SEEDS; i++) {
|
||||
const [, opts, players] = CONFIGS[i % CONFIGS.length]!;
|
||||
const options = tichu.optionsSchema.parse(opts);
|
||||
const a = fastPlayout(players, options, i);
|
||||
if (a.finished) {
|
||||
finished++;
|
||||
expect(tichu.result(a.s)!.ranking.flat().sort()).toEqual([...players].sort());
|
||||
}
|
||||
expect(JSON.parse(JSON.stringify(a.s))).toEqual(a.s);
|
||||
if (i % 50 === 0) {
|
||||
const b = fastPlayout(players, options, i);
|
||||
expect(b.trace).toBe(a.trace);
|
||||
expect(JSON.stringify(b.s)).toBe(JSON.stringify(a.s));
|
||||
}
|
||||
}
|
||||
expect(finished).toBeGreaterThanOrEqual(Math.floor(SEEDS * 0.9));
|
||||
}, 120_000);
|
||||
|
||||
test.each(CONFIGS)('%s: 엔진 무작위 대국(매 단계 정보 유출·왕복 검사)', (_name, opts, players) => {
|
||||
const options = tichu.optionsSchema.parse(opts);
|
||||
const seen = { rounds: 0 };
|
||||
// Six viewers make the per-step checks slow: a shorter stretch there.
|
||||
const maxSteps = players.length === 6 ? 500 : 2500;
|
||||
const r = randomPlayout(tamed, { players, options, seed: seedN(900 + players.length), maxSteps, maxApplyMs: 30, invariant: (st) => invariants(st as TichuState, seen) });
|
||||
expect(r.steps).toBeGreaterThan(50);
|
||||
}, 60_000);
|
||||
|
||||
test('결정성: 같은 시드·같은 행동이면 같은 결과', () => {
|
||||
const run = () => randomPlayout(tamed, { players: P4, options: tichu.optionsSchema.parse({ targetScore: 300 }), seed: seedN(42), maxSteps: 3000 }).finalState;
|
||||
expect(JSON.stringify(run())).toBe(JSON.stringify(run()));
|
||||
});
|
||||
|
||||
test('관전자와 다른 사람에게 남의 손패·남은 6장·더미(교환 전)가 보이지 않아요', () => {
|
||||
let s = make({ mode: 'threechu' }, P3);
|
||||
for (const p of P3) checkNoLeak(tichu as AnyGameDefinition, s, p, P3);
|
||||
const dealer = s.players[s.dealer!]!;
|
||||
const other = P3.find((p) => p !== dealer)!;
|
||||
const json = JSON.stringify(view(s, other));
|
||||
for (const c of s.hands[2]!) expect(json).not.toContain(`"${c}"`);
|
||||
for (const c of s.pending.flat()) expect(JSON.stringify(view(s, dealer))).not.toContain(`"${c}"`);
|
||||
s = act(s, other, { type: 'grand', call: false });
|
||||
expect(view(s, other).seats.find((x) => x.owner === dealer && !x.dummy)!.done).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('legalActions (§8.7)', () => {
|
||||
test('조합 대표 하나씩, 폭탄은 모두, 소원 포함/미포함 둘 다', () => {
|
||||
const hand = C('j8 s8 b8 t8 j9 s9 PH j3 j4 j5 j6 j7');
|
||||
const found = findCombos(hand, null, 8);
|
||||
const bombs = found.filter((f) => f.combo.type === 'bomb4' || f.combo.type === 'bombSF');
|
||||
expect(bombs.map((b) => b.cards.join(' ')).sort()).toEqual(['j3 j4 j5 j6 j7', 'j3 j4 j5 j6 j7 j8', 'j4 j5 j6 j7 j8', 'j8 s8 b8 t8', 'j3 j4 j5 j6 j7 j8 j9', 'j4 j5 j6 j7 j8 j9', 'j5 j6 j7 j8 j9'].sort());
|
||||
const st8 = found.filter((f) => f.combo.type === 'straight' && f.combo.length === 6 && f.combo.value === 9);
|
||||
expect(st8.some((f) => f.cards.some((c) => c.endsWith('8') && c !== PH))).toBe(true);
|
||||
expect(st8.some((f) => f.cards.every((c) => !/^.8$/.test(c)))).toBe(true);
|
||||
});
|
||||
});
|
||||
325
packages/games/src/tichu/types.ts
Normal file
325
packages/games/src/tichu/types.ts
Normal file
@@ -0,0 +1,325 @@
|
||||
/** 티츄 options, actions, state and view types (docs/games/tichu.md §2, §8). */
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import type { Combo, Rank } from './combo';
|
||||
|
||||
export * from './combo';
|
||||
|
||||
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
export const tichuOptionsSchema = z.object({
|
||||
mode: z
|
||||
.enum(['team', 'individual', 'threechu', 'tientsin'])
|
||||
.default('team')
|
||||
.meta({
|
||||
title: '게임 방식',
|
||||
labels: { team: '4인 팀전(2:2)', individual: '4인 개인전(짝꿍이 바뀜)', threechu: '3인(딜러 + 더미)', tientsin: '6인 팀전(3:3)' },
|
||||
}),
|
||||
targetScore: lit<300 | 500 | 1000 | 1500>(300, 500, 1000, 1500)
|
||||
.default(1000)
|
||||
.meta({ title: '목표 점수(3인은 판 수로 끝)', labels: { 300: '300점', 500: '500점', 1000: '1,000점', 1500: '1,500점' } }),
|
||||
threechuHands: lit<3 | 6 | 9 | 12>(3, 6, 9, 12)
|
||||
.default(6)
|
||||
.meta({ title: '3인 판 수', labels: { 3: '3판', 6: '6판', 9: '9판', 12: '12판' } }),
|
||||
grandTichu: z.boolean().default(true).meta({ title: '그랜드 티츄(첫 8장 보고 ±200)' }),
|
||||
direction: z
|
||||
.enum(['right', 'left'])
|
||||
.default('right')
|
||||
.meta({ title: '차례 방향', labels: { right: '오른쪽(반시계, 원작)', left: '왼쪽(시계)' } }),
|
||||
bombTiming: z
|
||||
.enum(['anytime', 'ownTurn'])
|
||||
.default('anytime')
|
||||
.meta({ title: '폭탄 내는 때', labels: { anytime: '아무 때나 끼어들기(원작)', ownTurn: '자기 차례에만' } }),
|
||||
bombWindowSeconds: lit<1 | 2 | 3>(1, 2, 3)
|
||||
.default(2)
|
||||
.meta({ title: '트릭 끝 폭탄 기다리기', labels: { 1: '1초', 2: '2초', 3: '3초' } }),
|
||||
wishRule: z
|
||||
.enum(['enforce', 'penalty'])
|
||||
.default('enforce')
|
||||
.meta({ title: '참새 소원을 어기면', labels: { enforce: '화면이 막아 줌(원작)', penalty: '막지 않고 어기면 상대 원투(대회식)' } }),
|
||||
trickHistory: z
|
||||
.enum(['last', 'all'])
|
||||
.default('last')
|
||||
.meta({ title: '지난 카드 보기', labels: { last: '직전 트릭만', all: '이번 라운드 전부(초보 도움)' } }),
|
||||
party: z.boolean().default(false).meta({ title: '파티 모드(라운드마다 효과 하나, 팀전·개인전)' }),
|
||||
/** null = 무제한: no clock for turns, the grand choice and the dragon gift (away players keep the short one). */
|
||||
turnSeconds: lit<20 | 30 | 45 | 60 | null>(20, 30, 45, 60, null)
|
||||
.default(30)
|
||||
.meta({ title: '한 턴 제한 시간', labels: { 20: '20초', 30: '30초', 45: '45초', 60: '60초', null: '무제한' } }),
|
||||
exchangeSeconds: lit<30 | 45 | 60 | null>(30, 45, 60, null)
|
||||
.default(45)
|
||||
.meta({ title: '카드 교환 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', null: '무제한' } }),
|
||||
});
|
||||
export type TichuOptions = z.infer<typeof tichuOptionsSchema>;
|
||||
export type TichuMode = TichuOptions['mode'];
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
const cardId = z.string().max(4);
|
||||
const seat = z.number().int().min(0).max(5);
|
||||
|
||||
export const tichuActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('grand'), call: z.boolean() }),
|
||||
z.object({ type: z.literal('tichu'), seat: seat.optional() }),
|
||||
z.object({ type: z.literal('exchange'), seat: seat.optional(), give: z.array(z.object({ to: seat, cardId })).min(1).max(3) }),
|
||||
z.object({
|
||||
type: z.literal('play'),
|
||||
cardIds: z.array(cardId).min(1).max(14),
|
||||
seat: seat.optional(),
|
||||
wish: z.number().int().min(2).max(14).nullable().optional(),
|
||||
dogTo: seat.optional(),
|
||||
}),
|
||||
z.object({ type: z.literal('pass'), seat: seat.optional() }),
|
||||
z.object({ type: z.literal('noBomb') }),
|
||||
z.object({ type: z.literal('dragonTo'), to: seat }),
|
||||
z.object({ type: z.literal('ready') }),
|
||||
]);
|
||||
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
|
||||
export type TichuAction = z.infer<typeof tichuActionSchema> | { type: 'timeout' } | { type: 'leave' };
|
||||
export type PlayAction = Extract<TichuAction, { type: 'play' }>;
|
||||
export type ExchangeAction = Extract<TichuAction, { type: 'exchange' }>;
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
export type Seat = number;
|
||||
export type Call = 'none' | 'tichu' | 'grand';
|
||||
export type Effect = 'double' | 'negative' | 'rotate' | 'plain';
|
||||
export const EFFECTS: readonly Effect[] = ['double', 'negative', 'rotate', 'plain'];
|
||||
|
||||
export interface Play {
|
||||
seat: Seat;
|
||||
cards: string[];
|
||||
combo: Combo;
|
||||
outOfTurn: boolean;
|
||||
}
|
||||
|
||||
export type Phase =
|
||||
| { kind: 'grand'; decided: boolean[] }
|
||||
| { kind: 'exchange'; give: ({ to: Seat; card: string }[] | null)[] }
|
||||
| { kind: 'playing' }
|
||||
/** `final`: the round is already over (3rd out with the dragon on top); score after the gift. */
|
||||
| { kind: 'dragonGift'; by: Seat; final: boolean }
|
||||
| { kind: 'roundEnd'; ready: boolean[] }
|
||||
| { kind: 'finished' };
|
||||
|
||||
export interface Trick {
|
||||
leader: Seat;
|
||||
plays: Play[];
|
||||
/** Seats that passed since the top play. */
|
||||
passed: Seat[];
|
||||
/** "카드 모으는 중" deadline (everyone passed; bombs may still come, §8.5). */
|
||||
closingAt: number | null;
|
||||
/** Seats that pressed "폭탄 없음" in this closing window. */
|
||||
waived: Seat[];
|
||||
}
|
||||
|
||||
export type RoundKind = 'double' | 'triple' | 'last' | 'penalty';
|
||||
|
||||
export interface CallResult {
|
||||
seat: Seat;
|
||||
player: PlayerId;
|
||||
call: 'tichu' | 'grand';
|
||||
success: boolean;
|
||||
points: number;
|
||||
}
|
||||
|
||||
export interface RoundResult {
|
||||
round: number;
|
||||
kind: RoundKind;
|
||||
out: Seat[];
|
||||
/** Seat that was left with cards (`last`), else null. */
|
||||
lastSeat: Seat | null;
|
||||
/** Owner of each seat this round (null for the threechu dummy). */
|
||||
seatOwners: (PlayerId | null)[];
|
||||
teams: PlayerId[][];
|
||||
/** Per team (0 for a 원투 / 트리플 빅토리 / penalty). */
|
||||
cardPoints: number[];
|
||||
bonus: number[];
|
||||
callPoints: number[];
|
||||
calls: CallResult[];
|
||||
/** Points the last seat's hand gave the other team, and points of its tricks moved to the winner. */
|
||||
handover: { hand: number; won: number } | null;
|
||||
effect: Effect | null;
|
||||
penalty: { seat: Seat } | null;
|
||||
total: number[];
|
||||
/** Score standing after this round (same shape as `scores`). */
|
||||
scoresAfter: number[];
|
||||
}
|
||||
|
||||
export type LogEntry =
|
||||
| { seq: number; t: 'play'; seat: Seat; cards: string[]; label: string; bomb: boolean; outOfTurn: boolean }
|
||||
| { seq: number; t: 'pass'; seat: Seat }
|
||||
| { seq: number; t: 'dog'; seat: Seat; to: Seat }
|
||||
| { seq: number; t: 'trick'; seat: Seat; points: number }
|
||||
| { seq: number; t: 'dragon'; seat: Seat; to: Seat; points: number }
|
||||
| { seq: number; t: 'wish'; seat: Seat; rank: Rank }
|
||||
| { seq: number; t: 'wishDone'; rank: Rank }
|
||||
| { seq: number; t: 'call'; seat: Seat; call: 'tichu' | 'grand' }
|
||||
| { seq: number; t: 'out'; seat: Seat; place: number }
|
||||
| { seq: number; t: 'exchanged'; rotated: boolean }
|
||||
| { seq: number; t: 'round'; round: number; kind: RoundKind; total: number[] }
|
||||
| { seq: number; t: 'deal'; round: number; effect: Effect | null }
|
||||
| { seq: number; t: 'penalty'; seat: Seat; rank: Rank }
|
||||
| { seq: number; t: 'timeout'; p: PlayerId }
|
||||
| { seq: number; t: 'left'; p: PlayerId };
|
||||
|
||||
export interface TichuFinal {
|
||||
ranking: PlayerId[][];
|
||||
scores: Record<PlayerId, number>;
|
||||
scoreText: Record<PlayerId, string>;
|
||||
summary: string;
|
||||
reason: 'normal' | 'abandoned';
|
||||
}
|
||||
|
||||
export interface SeatInfo {
|
||||
owner: PlayerId;
|
||||
/** threechu: the dummy hand, played by `owner` (this round's dealer). */
|
||||
dummy: boolean;
|
||||
}
|
||||
|
||||
export interface TichuState {
|
||||
options: TichuOptions;
|
||||
players: PlayerId[];
|
||||
round: number;
|
||||
seats: SeatInfo[];
|
||||
/** Seat numbers in turn order (clockwise seats; `right` = counter-clockwise). */
|
||||
order: Seat[];
|
||||
team: number[];
|
||||
/** threechu: index (in `players`) of this round's dealer; tientsin: seat that starts the deal. */
|
||||
dealer: number | null;
|
||||
effect: Effect | null;
|
||||
hands: string[][];
|
||||
/** grand phase: the cards not dealt yet (secret). */
|
||||
pending: string[][];
|
||||
received: { from: Seat; card: string }[][];
|
||||
calls: Call[];
|
||||
played: boolean[];
|
||||
wish: Rank | null;
|
||||
trick: Trick;
|
||||
lastTrick: { winner: Seat; plays: Play[]; points: number } | null;
|
||||
playedCards: string[];
|
||||
won: string[][];
|
||||
out: Seat[];
|
||||
current: Seat;
|
||||
phase: Phase;
|
||||
/** team / tientsin: per team; individual / threechu: per player (`players` order). */
|
||||
scores: number[];
|
||||
rounds: RoundResult[];
|
||||
/** tientsin: who finished first last round (starts the next deal). */
|
||||
lastFirst: Seat | null;
|
||||
turnStartedAt: number;
|
||||
turnNo: number;
|
||||
seq: number;
|
||||
timeoutsInRow: Record<PlayerId, number>;
|
||||
away: Record<PlayerId, boolean>;
|
||||
left: Record<PlayerId, boolean>;
|
||||
log: LogEntry[];
|
||||
final: TichuFinal | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export interface SeatView {
|
||||
seat: Seat;
|
||||
owner: PlayerId;
|
||||
dummy: boolean;
|
||||
team: number;
|
||||
cards: number;
|
||||
call: Call;
|
||||
/** Finish place this round (1-based). */
|
||||
place: number | null;
|
||||
passed: boolean;
|
||||
isTurn: boolean;
|
||||
/** grand: decided; exchange: sent; roundEnd: ready (owner). */
|
||||
done: boolean;
|
||||
away: boolean;
|
||||
left: boolean;
|
||||
/** threechu dummy hand once it is open (after the exchange). */
|
||||
openHand: string[] | null;
|
||||
/** trickHistory = all: card points this seat has won so far. */
|
||||
wonPoints: number | null;
|
||||
}
|
||||
|
||||
export interface PlayView {
|
||||
seat: Seat;
|
||||
cards: string[];
|
||||
combo: Combo;
|
||||
label: string;
|
||||
outOfTurn: boolean;
|
||||
}
|
||||
|
||||
export interface Suggestion {
|
||||
cards: string[];
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface MySeatView {
|
||||
seat: Seat;
|
||||
dummy: boolean;
|
||||
hand: string[];
|
||||
/** Normal turn: may play now. */
|
||||
canPlay: boolean;
|
||||
canPass: boolean;
|
||||
leading: boolean;
|
||||
/** enforce: the wished rank I must include now; always null in `penalty`. */
|
||||
mustWish: Rank | null;
|
||||
canTichu: boolean;
|
||||
canGrand: boolean;
|
||||
/** grand phase: still has to choose. */
|
||||
grandPending: boolean;
|
||||
bombs: string[][];
|
||||
canBombNow: boolean;
|
||||
canNoBomb: boolean;
|
||||
suggestions: Suggestion[];
|
||||
exchangeTargets: { seat: Seat; label: string }[];
|
||||
/** My chosen exchange (null before sending). */
|
||||
exchangeSent: { to: Seat; cardId: string }[] | null;
|
||||
exchangeSuggest: { to: Seat; cardId: string }[];
|
||||
received: { from: Seat; cardId: string }[];
|
||||
dragonTargets: Seat[];
|
||||
/** tientsin: partners the dog may go to. */
|
||||
dogTargets: Seat[];
|
||||
}
|
||||
|
||||
export interface TichuView {
|
||||
options: TichuOptions;
|
||||
me: PlayerId | null;
|
||||
mode: TichuMode;
|
||||
round: number;
|
||||
phase: Phase['kind'];
|
||||
seats: SeatView[];
|
||||
order: Seat[];
|
||||
/** My own (non-dummy) seat. */
|
||||
mySeat: Seat | null;
|
||||
dealer: PlayerId | null;
|
||||
effect: Effect | null;
|
||||
current: Seat | null;
|
||||
trick: { leader: Seat; plays: PlayView[]; passed: Seat[]; closingAt: number | null; waived: Seat[] } | null;
|
||||
wish: Rank | null;
|
||||
lastTrick: { winner: Seat; plays: PlayView[]; points: number } | null;
|
||||
/** trickHistory = all: every card played this round. */
|
||||
playedCards: string[] | null;
|
||||
/** trickHistory = all: card points won per team so far. */
|
||||
teamWon: number[] | null;
|
||||
scores: number[];
|
||||
/** Who each entry of `scores` belongs to. */
|
||||
scoreOwners: PlayerId[][];
|
||||
/** The latest round in full (round-end screen). */
|
||||
lastRound: RoundResult | null;
|
||||
/** Every round in short (score table). */
|
||||
history: { round: number; kind: RoundKind; total: number[]; effect: Effect | null; /** Change of `scores` (same shape) */ gains: number[] }[];
|
||||
dragonBy: Seat | null;
|
||||
ready: Record<PlayerId, boolean> | null;
|
||||
my: MySeatView | null;
|
||||
/** threechu dealer: the dummy hand I play. */
|
||||
dummy: MySeatView | null;
|
||||
turnStartedAt: number;
|
||||
deadlineTotalMs: number;
|
||||
bombWindowMs: number;
|
||||
turnNo: number;
|
||||
log: LogEntry[];
|
||||
result: TichuFinal | null;
|
||||
}
|
||||
@@ -62,6 +62,7 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'six-nimmt',
|
||||
'gemblo',
|
||||
'hot-streak',
|
||||
'tichu',
|
||||
];
|
||||
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */
|
||||
|
||||
@@ -48,6 +48,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'six-nimmt', nameKo: '젝스님트', minPlayers: 2, maxPlayers: 10, minutes: '20~45', level: '쉬움', blurb: '숫자 카드를 동시에 내고 작은 수부터 줄에 붙여요. 여섯 번째 카드면 소머리 벌점! · 10명까지', available: true },
|
||||
{ id: 'gemblo', nameKo: '젬블로', minPlayers: 2, maxPlayers: 6, minutes: '20~30', level: '쉬움', blurb: '육각 보석 블록을 꼭짓점 선으로 이어 놓는 땅따먹기! 같은 색끼리는 닿으면 안 돼요 · 2~6명', available: true },
|
||||
{ id: 'hot-streak', nameKo: '핫스트릭', minPlayers: 2, maxPlayers: 10, minutes: '15~25', level: '쉬움', blurb: '마스코트 넷의 엉망진창 달리기에 티켓으로 걸어요! 비밀 카드 한 장 몰래 넣고 소리 지르며 구경 · 놀이용 돈', 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);
|
||||
|
||||
Reference in New Issue
Block a user