Files
joke-app/packages/games/src/seotda/hands.ts
EJClaw 5dd8e6ea07 M3: 섯다·포커 규칙과 화면, 카드 게임 E2E
- 섯다(packages/games/seotda): 2장·3장 섯다, 1장씩/한 번에 나눠 주기, 족보(광땡·땡·알리…망통),
  땡잡이·암행어사·구사/멍텅구리구사 재경기, 동점 재경기·나눔, 리바이·탈락, 사이드 팟. 규칙 테스트 54개
- 포커(packages/games/poker): 홀덤·오마하·7포커(초이스·보스)·7포커 하이로우(동시 선언)·바둑이(아침·점심·저녁)·
  5카드 드로우·인디언 포커(이마 카드, 동점 이월, 다이 벌칙). 한국식/노리밋/팟리밋, 블라인드·앤티,
  리바이·레벨 상승·최후 1인. 규칙 테스트 52개 + 족보 판정 24개, 무작위 1,000판(칩 보존·비공개 카드 유출 없음)
- 웹: 섯다·포커 화면(테이블 좌석, 공용 카드, 사이드 팟, 한국식 버튼/레이즈 슬라이더, 초이스·교환·선언,
  체크 가능할 때 포기 확인, 리바이 안내), 섯다 결과 화면에서 가져간 칩 표시
- 엔진 betting.buildPots: 라운드 진행 중에는 아직 콜할 수 있는 플레이어도 각 팟 자격자로 표시
- 서버 테스트: 크래시 흉내 후 소켓 종료로 다시 걸린 타이머가 닫힌 DB를 건드리던 누수 수정
- E2E: 3인(PC + 휴대폰 2) 섯다·7포커 한 판, 6개 게임 모두 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 03:48:56 +09:00

198 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 섯다 족보와 쇼다운 판정 (docs/games/seotda.md §6.1–6.3). Pure functions, table-tested.
*
* Card ids are the shared HWATU ids from SEOTDA_DECK (packages/engine/src/cards.ts):
* month m (1..10) → special card id (m-1)*4, plain card id (m-1)*4+1.
*/
export type SpecialKind = 'ttaengjabi' | 'amhaeng' | 'gusa' | 'mungGusa';
export interface HandRules {
gwangTtaeng: 'all' | 'only38';
ttaengjabi: 'off' | 'strict' | 'loose';
amhaeng: boolean;
gusa: boolean;
mungGusa: 'off' | 'upTo8' | 'upTo9' | 'upToJang';
}
export interface HandEval {
/** Comparison value of the normal hand (special hands keep their normal value). */
value: number;
/** Display name: the special name when a special is active, otherwise the normal name. */
name: string;
/** The normal name ("3끗", "알리", …). */
baseName: string;
special: SpecialKind | null;
}
export const monthOf = (id: number): number => Math.floor(id / 4) + 1;
/** Slot 0 of each month: 광 for 1·3·8월, 열끗 for the others. */
export const isSpecialCard = (id: number): boolean => id % 4 === 0;
export const isGwang = (id: number): boolean => isSpecialCard(id) && [1, 3, 8].includes(monthOf(id));
/** 열끗 of a month (4·7·9월 matter for special hands). */
export const isYeol = (id: number, month: number): boolean => isSpecialCard(id) && monthOf(id) === month;
export const SPECIAL_NAME: Record<SpecialKind, string> = {
ttaengjabi: '땡잡이',
amhaeng: '암행어사',
gusa: '구사',
mungGusa: '멍텅구리구사',
};
const PAIRS: [number, number, number, string][] = [
[1, 2, 806, '알리'],
[1, 4, 805, '독사'],
[1, 9, 804, '구삥'],
[1, 10, 803, '장삥'],
[4, 10, 802, '장사'],
[4, 6, 801, '세륙'],
];
function normal(a: number, b: number, rules: HandRules): { value: number; name: string } {
const ma = monthOf(a);
const mb = monthOf(b);
if (isGwang(a) && isGwang(b)) {
const set = new Set([ma, mb]);
if (set.has(3) && set.has(8)) return { value: 1000, name: '38광땡' };
if (rules.gwangTtaeng === 'all') {
if (set.has(1) && set.has(8)) return { value: 990, name: '18광땡' };
if (set.has(1) && set.has(3)) return { value: 980, name: '13광땡' };
}
}
if (ma === mb) {
if (ma === 10) return { value: 910, name: '장땡' };
if (ma === 1) return { value: 901, name: '삥땡' };
return { value: 900 + ma, name: `${ma}땡` };
}
const lo = Math.min(ma, mb);
const hi = Math.max(ma, mb);
for (const [x, y, v, n] of PAIRS) if (lo === x && hi === y) return { value: v, name: n };
const k = (ma + mb) % 10;
if (k === 9) return { value: 9, name: '갑오' };
if (k === 0) return { value: 0, name: '망통' };
return { value: k, name: `${k}끗` };
}
function specialOf(a: number, b: number, rules: HandRules): SpecialKind | null {
const months = new Set([monthOf(a), monthOf(b)]);
const has = (m: number) => months.has(m);
const yeol = (m: number) => isYeol(a, m) || isYeol(b, m);
if (has(3) && has(7)) {
if (rules.ttaengjabi === 'loose') return 'ttaengjabi';
if (rules.ttaengjabi === 'strict' && isGwang(a) !== isGwang(b) && (isGwang(a) ? monthOf(a) : monthOf(b)) === 3 && yeol(7)) return 'ttaengjabi';
}
if (rules.amhaeng && has(4) && has(7) && yeol(4) && yeol(7)) return 'amhaeng';
if (rules.gusa && has(4) && has(9)) {
if (rules.mungGusa !== 'off' && yeol(4) && yeol(9)) return 'mungGusa';
return 'gusa';
}
return null;
}
/** 족보 of two cards (order-independent). */
export function evalSeotda(a: number, b: number, rules: HandRules): HandEval {
const n = normal(a, b, rules);
const special = specialOf(a, b, rules);
return { value: n.value, baseName: n.name, name: special ? SPECIAL_NAME[special] : n.name, special };
}
/** 구사 재경기 기준값 (§6.2): the best other normal hand must be ≤ this. */
export function gusaThreshold(special: SpecialKind | null, rules: HandRules): number | null {
if (special === 'gusa') return 806;
if (special === 'mungGusa') return rules.mungGusa === 'upTo9' ? 909 : rules.mungGusa === 'upToJang' ? 910 : 908;
return null;
}
export type Resolution =
| { type: 'win'; winners: string[]; reason: 'normal' | 'ttaengjabi' | 'amhaeng' }
| { type: 'split'; winners: string[] }
| { type: 'rematch'; reason: 'gusa' | 'mungGusa' | 'tie'; participants: string[] };
/**
* Showdown judgement for one pot (§6.3). `players` are the pot's eligible contenders in
* seat order from the dealer (선) — split winners keep that order for odd chips.
*/
export function resolve(players: { id: string; hand: HandEval }[], tieRule: 'rematch' | 'split', rules: HandRules): Resolution {
const vmax = Math.max(...players.map((p) => p.hand.value));
const holders = (k: SpecialKind) => players.filter((p) => p.hand.special === k).map((p) => p.id);
let W: string[];
let reason: 'normal' | 'ttaengjabi' | 'amhaeng' = 'normal';
if (holders('ttaengjabi').length > 0 && vmax >= 901 && vmax <= 909) {
W = holders('ttaengjabi');
reason = 'ttaengjabi';
} else if (holders('amhaeng').length > 0 && (vmax === 980 || vmax === 990)) {
W = holders('amhaeng');
reason = 'amhaeng';
} else {
W = players.filter((p) => p.hand.value === vmax).map((p) => p.id);
}
// 구사 재경기: a 구사 holder who does not already win, with every other hand ≤ its threshold.
let gusa: 'gusa' | 'mungGusa' | null = null;
for (const h of players) {
if (h.hand.special !== 'gusa' && h.hand.special !== 'mungGusa') continue;
if (W.includes(h.id)) continue;
const t = gusaThreshold(h.hand.special, rules);
const best = Math.max(...players.filter((q) => q.id !== h.id).map((q) => q.hand.value));
if (t !== null && best <= t) gusa = gusa === 'mungGusa' ? gusa : h.hand.special;
}
if (gusa) return { type: 'rematch', reason: gusa, participants: players.map((p) => p.id) };
if (W.length === 1) return { type: 'win', winners: W, reason };
return tieRule === 'rematch' ? { type: 'rematch', reason: 'tie', participants: W } : { type: 'split', winners: W };
}
/** The three 2-card combinations of a 3-card hand. */
export function combos(hand: number[]): [number, number][] {
const out: [number, number][] = [];
for (let i = 0; i < hand.length; i++) for (let j = i + 1; j < hand.length; j++) out.push([hand[i]!, hand[j]!]);
return out;
}
/** Auto choice (§8.5): highest normal value, then a special combo, then the smaller id sum. */
export function bestChoice(hand: number[], rules: HandRules): [number, number] {
let best: [number, number] | null = null;
let bestEval: HandEval | null = null;
for (const c of combos(hand)) {
const e = evalSeotda(c[0], c[1], rules);
if (!best || !bestEval) {
best = c;
bestEval = e;
continue;
}
const better =
e.value > bestEval.value ||
(e.value === bestEval.value && !!e.special && !bestEval.special) ||
(e.value === bestEval.value && !!e.special === !!bestEval.special && c[0] + c[1] < best[0] + best[1]);
if (better) {
best = c;
bestEval = e;
}
}
return [Math.min(...best!), Math.max(...best!)] as [number, number];
}
/** Rough strength for beginner hints (§9). */
export function strengthOf(e: HandEval): 'high' | 'mid' | 'low' {
if (e.value >= 801) return 'high';
if (e.value >= 5 || e.special === 'gusa' || e.special === 'mungGusa' || e.special === 'ttaengjabi' || e.special === 'amhaeng') return 'mid';
return 'low';
}
/** Beginner sentence for my current hand (hints option). */
export function hintText(e: HandEval, rules: HandRules): string {
const lvl = { high: '아주 센 패예요.', mid: '중간 정도 패예요.', low: '약한 패예요.' }[strengthOf(e)];
switch (e.special) {
case 'ttaengjabi':
return '땡잡이예요. 상대 최고 패가 1땡~9땡이면 이겨요. 아니면 망통이에요.';
case 'amhaeng':
return '암행어사예요. 상대 최고 패가 13광땡이나 18광땡이면 이겨요. 아니면 1끗이에요.';
case 'gusa':
return '구사예요. 상대가 알리 이하면 재경기예요. 아니면 3끗이에요.';
case 'mungGusa': {
const upTo = rules.mungGusa === 'upTo9' ? '9땡' : rules.mungGusa === 'upToJang' ? '장땡' : '8땡';
return `멍텅구리구사예요. 상대가 ${upTo} 이하면 재경기예요. 아니면 3끗이에요.`;
}
default:
return `지금 패는 ${e.name}이에요. ${lvl}`;
}
}