병합: wt2/seotda
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* Hwatu card drawn in SVG (our own simple artwork, no commercial hwatu images — docs/games/seotda.md §12).
|
||||
* Large month number + kind badge so the card is readable without knowing the pictures.
|
||||
* Hwatu card: the real 48-card hwatu artwork from Wikimedia Commons "SVG Hwatu" (Marcus Richert after Louie Mantia Jr.,
|
||||
* CC BY-SA 4.0 — ./hwatu/ATTRIBUTION.txt, docs/games/seotda.md "화투 그림"), bundled from our own origin (no external
|
||||
* URLs). A small month badge stays on top so beginners can read the card at a glance;
|
||||
* 쌍피 / bonus cards get their value tag (고스톱). The back and the bonus cards are drawn here.
|
||||
*/
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
export interface HwatuInfo {
|
||||
id: number;
|
||||
@@ -13,172 +15,180 @@ export interface HwatuInfo {
|
||||
piValue?: number;
|
||||
}
|
||||
|
||||
const MONTH_COLOR = ['#6b7280', '#15803d', '#be185d', '#db2777', '#1f2937', '#7c3aed', '#dc2626', '#b91c1c', '#111827', '#ca8a04', '#c2410c', '#7c2d12', '#1e40af'];
|
||||
const MONTH_NAME = ['보너스', '송학', '매조', '벚꽃', '흑싸리', '난초', '모란', '홍싸리', '공산', '국화', '단풍', '오동', '비'];
|
||||
const KIND_BADGE: Record<HwatuInfo['kind'], string> = { gwang: '光', yeol: '열', tti: '띠', pi: '피', ssangpi: '쌍피', bonus: '+' };
|
||||
const TTI_COLOR = { hong: '#dc2626', cheong: '#2563eb', cho: '#15803d', plain: '#dc2626' };
|
||||
const TTI_TEXT = { hong: '홍단', cheong: '청단', cho: '', plain: '' };
|
||||
/** Attribution of the card artwork (CC BY-SA 4.0 asks for it); shown in the rules of the games that use these cards. */
|
||||
export const HWATU_CREDIT =
|
||||
'화투 그림: Marcus Richert(Louie Mantia, Jr.의 Hanafuda 그림 바탕), Spenĉjo — Wikimedia Commons "SVG Hwatu", CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). 크기만 줄여 썼어요.';
|
||||
|
||||
/** A small motif per month (flowers/plants), drawn with basic shapes. */
|
||||
function Motif({ month, color }: { month: number; color: string }): ReactNode {
|
||||
const c = color;
|
||||
switch (month) {
|
||||
case 1: // 송학: pine
|
||||
return <path d="M50 52 L28 92 H72 Z M50 72 L22 116 H78 Z" fill={c} opacity="0.85" />;
|
||||
case 2: // 매조: plum blossoms
|
||||
case 3: // 벚꽃
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
{[[34, 70], [62, 62], [50, 92], [70, 100], [30, 108]].map(([x, y], i) => (
|
||||
<circle key={i} cx={x} cy={y} r="10" />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
case 4: // 흑싸리
|
||||
case 7: // 홍싸리
|
||||
return (
|
||||
<g stroke={c} strokeWidth="5" strokeLinecap="round" opacity="0.85">
|
||||
{[30, 45, 60, 75].map((x, i) => (
|
||||
<line key={i} x1={x} y1="52" x2={x - 6} y2={100 + (i % 2) * 14} />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
case 5: // 난초: iris leaves
|
||||
return (
|
||||
<g fill="none" stroke={c} strokeWidth="5" opacity="0.85">
|
||||
<path d="M40 120 Q34 80 44 52" />
|
||||
<path d="M55 120 Q62 84 52 54" />
|
||||
<path d="M70 120 Q76 92 68 64" />
|
||||
</g>
|
||||
);
|
||||
case 6: // 모란: peony
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
<circle cx="50" cy="86" r="22" />
|
||||
<circle cx="50" cy="86" r="10" fill="#fde68a" />
|
||||
</g>
|
||||
);
|
||||
case 8: // 공산: hill
|
||||
return <path d="M8 120 Q50 52 92 120 Z" fill={c} opacity="0.85" />;
|
||||
case 9: // 국화
|
||||
return (
|
||||
<g fill={c} opacity="0.9">
|
||||
{Array.from({ length: 10 }, (_, i) => {
|
||||
const a = (i / 10) * Math.PI * 2;
|
||||
return <ellipse key={i} cx={50 + Math.cos(a) * 14} cy={88 + Math.sin(a) * 14} rx="8" ry="4" transform={`rotate(${(a * 180) / Math.PI} ${50 + Math.cos(a) * 14} ${88 + Math.sin(a) * 14})`} />;
|
||||
})}
|
||||
<circle cx="50" cy="88" r="7" fill="#78350f" />
|
||||
</g>
|
||||
);
|
||||
case 10: // 단풍: maple
|
||||
return <path d="M50 58 L58 78 L78 74 L64 90 L74 108 L50 98 L26 108 L36 90 L22 74 L42 78 Z" fill={c} opacity="0.9" />;
|
||||
case 11: // 오동
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
<ellipse cx="38" cy="82" rx="16" ry="22" />
|
||||
<ellipse cx="64" cy="94" rx="16" ry="22" />
|
||||
</g>
|
||||
);
|
||||
case 12: // 비: rain lines + umbrella
|
||||
return (
|
||||
<g stroke={c} strokeWidth="3" opacity="0.85">
|
||||
{[20, 35, 50, 65, 80].map((x) => (
|
||||
<line key={x} x1={x} y1="54" x2={x - 8} y2="118" />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
default:
|
||||
return <text x="50" y="98" fontSize="36" textAnchor="middle" fill={c}>★</text>;
|
||||
}
|
||||
export type HwatuSize = 'sm' | 'md' | 'lg' | 'xl';
|
||||
const WIDTH: Record<HwatuSize, number> = { sm: 40, md: 60, lg: 84, xl: 108 };
|
||||
/** Height / width of the artwork (103.2 × 168.2). */
|
||||
export const HWATU_RATIO = 1.63;
|
||||
|
||||
/**
|
||||
* URL of a card face (ids 0..47). Vite turns this pattern into hashed /assets/ files (cached for good, also by the
|
||||
* service worker); in tests it is just a file URL.
|
||||
*/
|
||||
export const hwatuSrc = (id: number): string => new URL(`./hwatu/${id}.svg`, import.meta.url).href;
|
||||
|
||||
/** Card back: deep red lacquer with a thin gold frame, like a real hwatu back. */
|
||||
export function HwatuBack({ w, h }: { w: number; h: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 163" width={w} height={h} aria-hidden style={{ display: 'block' }}>
|
||||
<defs>
|
||||
<linearGradient id="hwb-g" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor="#c8102e" />
|
||||
<stop offset="1" stopColor="#8a0b1f" />
|
||||
</linearGradient>
|
||||
<pattern id="hwb-p" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
|
||||
<rect width="10" height="10" fill="none" />
|
||||
<path d="M0 5h10M5 0v10" stroke="#ffffff" strokeOpacity="0.07" strokeWidth="1.2" />
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="url(#hwb-g)" stroke="#4a0510" strokeWidth="2" />
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="url(#hwb-p)" />
|
||||
<rect x="8" y="8" width="84" height="147" rx="4" fill="none" stroke="#f6c453" strokeOpacity="0.55" strokeWidth="1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export type HwatuSize = 'sm' | 'md' | 'lg';
|
||||
const WIDTH: Record<HwatuSize, number> = { sm: 40, md: 60, lg: 84 };
|
||||
function BonusFace({ w, h, value }: { w: number; h: number; value: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 163" width={w} height={h} aria-hidden style={{ display: 'block' }}>
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="#e3262b" />
|
||||
<rect x="7" y="7" width="86" height="149" rx="5" fill="#fffaf0" />
|
||||
<circle cx="50" cy="70" r="27" fill="#f6c453" stroke="#b45309" strokeWidth="3" />
|
||||
<text x="50" y="81" fontSize="30" fontWeight="900" fill="#7c2d12" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{value}
|
||||
</text>
|
||||
<text x="50" y="128" fontSize="20" fontWeight="900" fill="#b91c1c" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
보너스
|
||||
</text>
|
||||
<text x="50" y="148" fontSize="15" fontWeight="800" fill="#7c2d12" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{value}피
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function HwatuCard({
|
||||
card,
|
||||
size = 'md',
|
||||
width,
|
||||
selected,
|
||||
dimmed,
|
||||
highlight,
|
||||
showMonth = true,
|
||||
onClick,
|
||||
className,
|
||||
style,
|
||||
}: {
|
||||
card: HwatuInfo | null;
|
||||
size?: HwatuSize;
|
||||
/** Exact width in px (overrides `size`). */
|
||||
width?: number;
|
||||
selected?: boolean;
|
||||
dimmed?: boolean;
|
||||
highlight?: boolean;
|
||||
/** Small month number badge (on by default). */
|
||||
showMonth?: boolean;
|
||||
onClick?: () => void;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}) {
|
||||
const w = WIDTH[size];
|
||||
const h = Math.round(w * 1.6);
|
||||
const w = width ?? WIDTH[size];
|
||||
const h = Math.round(w * HWATU_RATIO);
|
||||
const Tag = onClick ? 'button' : 'span';
|
||||
const radius = Math.max(3, Math.round(w * 0.07));
|
||||
const s: CSSProperties = {
|
||||
position: 'relative',
|
||||
width: w,
|
||||
height: h,
|
||||
flex: 'none',
|
||||
display: 'inline-block',
|
||||
padding: 0,
|
||||
border: 0,
|
||||
borderRadius: radius,
|
||||
background: 'none',
|
||||
cursor: onClick ? 'pointer' : 'default',
|
||||
opacity: dimmed ? 0.45 : 1,
|
||||
transform: selected ? `translateY(${-Math.round(w * 0.2)}px)` : undefined,
|
||||
transition: 'transform 0.12s ease',
|
||||
filter: highlight ? 'drop-shadow(0 0 6px #f59e0b)' : 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))',
|
||||
boxShadow: selected ? '0 0 0 3px #2563eb' : undefined,
|
||||
filter: highlight ? 'drop-shadow(0 0 6px #f59e0b)' : 'drop-shadow(0 1px 2px rgba(0,0,0,0.35))',
|
||||
verticalAlign: 'bottom',
|
||||
...style,
|
||||
};
|
||||
if (!card) {
|
||||
return (
|
||||
<Tag style={s} onClick={onClick} aria-label="뒤집힌 화투">
|
||||
<svg viewBox="0 0 100 160" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="158" rx="8" fill="#991b1b" stroke="#450a0a" strokeWidth="3" />
|
||||
<rect x="10" y="10" width="80" height="140" rx="5" fill="#b91c1c" />
|
||||
</svg>
|
||||
<Tag style={s} onClick={onClick} aria-label="뒤집힌 화투" className={className}>
|
||||
<HwatuBack w={w} h={h} />
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
const color = MONTH_COLOR[card.month] ?? '#374151';
|
||||
const badge = Math.max(12, Math.round(w * 0.24));
|
||||
// 고스톱 passes 쌍피 as kind 'pi' with piValue 2.
|
||||
const tag = card.kind === 'ssangpi' || (card.kind === 'pi' && (card.piValue ?? 1) >= 2) ? '쌍피' : null;
|
||||
return (
|
||||
<Tag style={s} onClick={onClick} aria-label={card.name} aria-pressed={onClick ? !!selected : undefined} title={card.name}>
|
||||
<svg viewBox="0 0 100 160" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="158" rx="8" fill="#fffaf0" stroke={selected ? '#2563eb' : '#1f2937'} strokeWidth={selected ? 6 : 3} />
|
||||
{card.kind === 'bonus' ? (
|
||||
<text x="50" y="102" fontSize="34" fontWeight="900" fill="#b45309" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{card.piValue ?? 2}피
|
||||
</text>
|
||||
) : (
|
||||
<Motif month={card.month} color={color} />
|
||||
)}
|
||||
{card.kind === 'tti' && (
|
||||
<g>
|
||||
<rect x="58" y="30" width="18" height="90" rx="3" fill={TTI_COLOR[card.tti ?? 'plain']} />
|
||||
{TTI_TEXT[card.tti ?? 'plain'] && (
|
||||
<text x="67" y="62" fontSize="13" fontWeight="800" fill="#fff" textAnchor="middle" style={{ writingMode: 'vertical-rl' } as CSSProperties}>
|
||||
{TTI_TEXT[card.tti ?? 'plain']}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
{(card.kind === 'gwang' || card.kind === 'yeol') && (
|
||||
<g>
|
||||
<circle cx="78" cy="120" r="15" fill={card.kind === 'gwang' ? '#dc2626' : '#a16207'} />
|
||||
<text x="78" y="127" fontSize={card.kind === 'gwang' ? 20 : 16} fontWeight="800" fill="#fff" textAnchor="middle">
|
||||
{card.kind === 'gwang' ? '光' : '열'}
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
{/* Month number: large and always readable */}
|
||||
<rect x="6" y="6" width="38" height="38" rx="8" fill={color} />
|
||||
<text x="25" y="35" fontSize="28" fontWeight="900" fill="#fff" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{card.month || '+'}
|
||||
</text>
|
||||
<text x="50" y="154" fontSize="13" fontWeight="700" fill="#374151" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{MONTH_NAME[card.month]} · {card.kind === 'bonus' ? `${card.piValue ?? 2}피` : card.kind === 'tti' ? (TTI_TEXT[card.tti ?? 'plain'] || '띠') : KIND_BADGE[card.kind] === '光' ? '광' : KIND_BADGE[card.kind] === '열' ? '열끗' : KIND_BADGE[card.kind]}
|
||||
</text>
|
||||
</svg>
|
||||
<Tag
|
||||
style={s}
|
||||
onClick={onClick}
|
||||
aria-label={card.name}
|
||||
aria-pressed={onClick ? !!selected : undefined}
|
||||
title={card.name}
|
||||
className={className}
|
||||
>
|
||||
{card.kind === 'bonus' || card.id >= 48 ? (
|
||||
<BonusFace w={w} h={h} value={card.piValue ?? 2} />
|
||||
) : (
|
||||
<img src={hwatuSrc(card.id)} alt="" draggable={false} width={w} height={h} decoding="async" style={{ display: 'block', width: w, height: h, borderRadius: radius }} />
|
||||
)}
|
||||
{showMonth && card.month > 0 && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: Math.round(w * 0.05),
|
||||
right: Math.round(w * 0.05),
|
||||
minWidth: badge,
|
||||
height: badge,
|
||||
padding: '0 2px',
|
||||
borderRadius: badge,
|
||||
background: 'rgba(17,24,39,0.82)',
|
||||
color: '#fff',
|
||||
fontSize: Math.max(9, Math.round(badge * 0.66)),
|
||||
fontWeight: 800,
|
||||
lineHeight: `${badge}px`,
|
||||
textAlign: 'center',
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{card.month}
|
||||
</span>
|
||||
)}
|
||||
{tag && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: '50%',
|
||||
bottom: Math.round(w * 0.06),
|
||||
transform: 'translateX(-50%)',
|
||||
padding: '0 4px',
|
||||
borderRadius: 4,
|
||||
background: '#f6c453',
|
||||
color: '#7c2d12',
|
||||
fontSize: Math.max(9, Math.round(w * 0.2)),
|
||||
fontWeight: 900,
|
||||
lineHeight: 1.25,
|
||||
whiteSpace: 'nowrap',
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
)}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
1
apps/web/src/components/cards/hwatu/0.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
apps/web/src/components/cards/hwatu/1.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
apps/web/src/components/cards/hwatu/10.svg
Normal file
|
After Width: | Height: | Size: 51 KiB |
1
apps/web/src/components/cards/hwatu/11.svg
Normal file
|
After Width: | Height: | Size: 56 KiB |
1
apps/web/src/components/cards/hwatu/12.svg
Normal file
|
After Width: | Height: | Size: 34 KiB |
1
apps/web/src/components/cards/hwatu/13.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/14.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
apps/web/src/components/cards/hwatu/15.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/16.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
apps/web/src/components/cards/hwatu/17.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
1
apps/web/src/components/cards/hwatu/18.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/19.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
apps/web/src/components/cards/hwatu/2.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
apps/web/src/components/cards/hwatu/20.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
apps/web/src/components/cards/hwatu/21.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/22.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
apps/web/src/components/cards/hwatu/23.svg
Normal file
|
After Width: | Height: | Size: 23 KiB |
1
apps/web/src/components/cards/hwatu/24.svg
Normal file
|
After Width: | Height: | Size: 54 KiB |
1
apps/web/src/components/cards/hwatu/25.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/26.svg
Normal file
|
After Width: | Height: | Size: 24 KiB |
1
apps/web/src/components/cards/hwatu/27.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
apps/web/src/components/cards/hwatu/28.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m3.3 3.15c-.17 10.85 1.3 101.25 1.3 101.25l94.7 9.5 1.25-110.75c-32.28.58-64.87-1.85-97.25 0zm46.45 19c18.68-.54 33.23 16.56 33.23 31.59 0 21.84-16.42 34.31-33.38 34.31-14.18 0-32.68-12.1-32.68-32.42 0-16.47 11.61-32.87 32.83-33.48z" fill="#ef1d1e"/><path d="m48.05 21.45c-8.53.4-15.92 3.75-22.15 10.05-6.6 6.67-9.78 14.78-9.55 24.35.37 11.97 5.65 21.23 15.85 27.8 6.37 4.07 13.38 5.7 21.05 4.9 9.1-.97 16.6-4.95 22.5-11.95 5.73-6.77 8.32-14.82 7.75-24.15-.5-8.27-3.9-15.47-10.2-21.6-6.9-6.7-15.32-9.83-25.25-9.4zm.92 1.21c6.93-.28 13.46 1.72 19.58 5.99 6.2 4.33 10.35 10.15 12.45 17.45 2.8 9.93 1.22 19.15-4.75 27.65-2.9 4.13-6.42 7.37-10.55 9.7-3.97 2.23-8.35 3.55-13.15 3.95-8.4.3-15.68-1.82-21.85-6.35-5.63-4.17-9.48-9.43-11.55-15.8-2.87-9.07-2.08-17.63 2.35-25.7h.05l.05-.05c4.57-8.23 11.33-13.5 20.3-15.8 2.4-.6 4.76-.95 7.07-1.04zm-8.22 70.09c-2.53.27-4.43.43-5.7.5-.6 0-1.35.08-2.25.25-.97.17-1.7.28-2.2.35-.17.03-1.22.23-3.15.6-2.37.57-3.83.93-4.4 1.1l-6.5 2.25c-.8.27-1.9.72-3.3 1.35-1.5.67-2.62 1.13-3.35 1.4-2.03.73-3.97 1.77-5.8 3.1l-.82 59.4 95.11 1.07-.89-52.96c-1-.87-2.92-2.22-5.75-4.05-2.03-1.33-4.47-2.8-7.3-4.4-1.93-1.1-4.67-2.38-8.2-3.85-3.03-1.1-5.3-1.93-6.8-2.5-2.13-.77-5.77-1.65-10.9-2.65-.43-.07-2.75-.28-6.95-.65l-2.75-.2c-.47 0-1.13-.03-2-.1l-3.1.05c-1.33-.07-2.33-.08-3-.05z"/><g transform="translate(479.2 -235.55)"><path transform="translate(-848.6,2.2)" d="m399.45 353.05c-4.87 0-9.02 1.72-12.45 5.15-3.4 3.43-5.1 7.58-5.1 12.45s1.7 9.02 5.1 12.45c3.43 3.43 7.58 5.15 12.45 5.15s9.02-1.72 12.45-5.15 5.15-7.58 5.15-12.45-1.72-9.02-5.15-12.45-7.58-5.15-12.45-5.15z" fill="#ef1d1e"/><path transform="translate(-848.6,2.2)" d="m397.62 356.15c-.52.06-.91.55-1.17 1.45-.3 1-.3 2.55 0 4.65.03.93.05 1.82.05 2.65-.03.97-.1 1.85-.2 2.65-.73.23-1.38.47-1.95.7-2.07.83-3.1 1.65-3.1 2.45v.25l.15.4h.4c.03 0 1.67-.4 4.9-1.2-.27.9-.85 1.93-1.75 3.1-.83 1.1-1.58 1.97-2.25 2.6-.7.67-1.15 1.12-1.35 1.35-.13.2-.52.55-1.15 1.05-.6.47-1.18.82-1.75 1.05-.6.23-.9.48-.9.75 0 .17.13.35.4.55.27.17.6.25 1 .25.97 0 2.25-.8 3.85-2.4 1.6-1.63 2.65-2.78 3.15-3.45s1.1-1.62 1.8-2.85c.67-1.23 1.15-2.1 1.45-2.6v-.05c.06 0 .11-.02.15-.05-.04.04-.09.07-.15.1.07 1.03.13 2 .2 2.9l-.35 5.5c0 1.33.38 2.27 1.15 2.8.73.5 2.27.78 4.6.85 2.3.13 4.07-.32 5.3-1.35 1.33-1.07 1.93-2.18 1.8-3.35-.07-1.13-.35-1.95-.85-2.45s-.92-.82-1.25-.95c-.4-.07-.78.48-1.15 1.65-.43 1.13-.92 1.82-1.45 2.05-.57.2-1.37.4-2.4.6-1.07.3-1.73.45-2 .45-1 0-1.52-1.07-1.55-3.2.07-2.1.1-3.2.1-3.3 0-.97-.02-1.55-.05-1.75-.13-.3-.37-.6-.7-.9 2.83-1 4.25-1.88 4.25-2.65 0-.53-.2-.87-.6-1-.17-.1-.58-.15-1.25-.15-.6 0-1.22.15-1.85.45-1.1.47-1.9.8-2.4 1-.07-.33-.1-.77-.1-1.3 0-.83.08-1.77.25-2.8 0-.2.02-.42.05-.65.17-1.3.25-2.32.25-3.05s-.02-1.23-.05-1.5c-.23-.87-.67-1.3-1.3-1.3-.08-.01-.16-.01-.23 0zm5.73 1.75c-.6.47-1.38 1.22-2.35 2.25-.97 1.03-1.45 1.9-1.45 2.6 0 .67.02 1.02.05 1.05.07.07.1.12.1.15.13.1.23.15.3.15.33 0 1.27-.55 2.8-1.65 1.63-1.2 2.45-2.05 2.45-2.55 0-.43-.2-.87-.6-1.3-.4-.47-.83-.7-1.3-.7zm-12.5 4.6c-.3 0-.55.18-.75.55-.13.33-.2.65-.2.95 0 .83.17 1.45.5 1.85.3.3.77.48 1.4.55.2.03.43.05.7.05.2-.03.43-.08.7-.15.1-.03.22-.1.35-.2.83-.33 1.25-.75 1.25-1.25 0-.43-.15-.72-.45-.85-.17-.07-.62-.17-1.35-.3-.6-.07-1.02-.3-1.25-.7-.27-.33-.57-.5-.9-.5z" fill="#fff"/><path transform="translate(-848.6,2.2)" d="m399.45 353.05c-4.87 0-9.02 1.72-12.45 5.15-3.4 3.43-5.1 7.58-5.1 12.45s1.7 9.02 5.1 12.45c3.43 3.43 7.58 5.15 12.45 5.15s9.02-1.72 12.45-5.15 5.15-7.58 5.15-12.45-1.72-9.02-5.15-12.45-7.58-5.15-12.45-5.15z" fill="none" stroke="#000"/></g><g transform="translate(-447.2 -373.75)"><path transform="translate(160.15,84.1)" d="m292.05 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m300.35 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
1
apps/web/src/components/cards/hwatu/29.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/3.svg
Normal file
|
After Width: | Height: | Size: 10 KiB |
1
apps/web/src/components/cards/hwatu/30.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m41.15 88.75c-1.6.07-3.2.22-4.8.45-3.07.4-5.35.75-6.85 1.05-3.43.7-5.65 1.18-6.65 1.45-1.5.4-3.72 1.13-6.65 2.2-3.9 1.43-6.35 2.42-7.35 2.95-1.63.7-2.83 1.27-3.6 1.7l-1.7 67.5c.46.42 97.25 0 97.25 0l-3.7-59.55c-1.87-1.67-3.3-2.87-4.3-3.6-1.07-.77-2.7-1.82-4.9-3.15-2.3-1.3-4.32-2.38-6.05-3.25-1.27-.6-3.47-1.5-6.6-2.7-1.9-.73-3.6-1.3-5.1-1.7-2.2-.47-3.85-.83-4.95-1.1-2.73-.6-4.8-.98-6.2-1.15l-3.75-.55c-2.5-.23-4-.37-4.5-.4-2.17.1-3.78.07-4.85-.1-.87-.1-2.45-.12-4.75-.05z"/><g transform="translate(-555.75,-373.75)"><path transform="translate(160.15,84.1)" d="m400.6 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m408.9 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
1
apps/web/src/components/cards/hwatu/31.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m46.2 81.65c-1.8 0-3.35.07-4.65.2-3.77.33-6.58.62-8.45.85-2.53.27-4.38.53-5.55.8-2.33.5-4.7 1.1-7.1 1.8-2.57.7-4.72 1.4-6.45 2.1-.37.17-2.32 1.1-5.85 2.8-1.93 1.07-3.32 1.97-4.15 2.7l-.6 73.15h97.25l-1.55-67.2c-1.27-1.1-2.14-1.82-2.6-2.15-.1-.07-.2-.11-.3-.18-.36-.28-.5-.48-.9-.77-.53-.4-2.22-1.48-5.05-3.25-1.93-1.2-4.27-2.4-7-3.6-1.33-.6-3.58-1.47-6.75-2.6-1.97-.77-3.3-1.23-4-1.4-2.77-.6-4.85-1.08-6.25-1.45-.4-.13-1.02-.22-1.85-.25-.87-.03-1.48-.1-1.85-.2-.8-.23-1.77-.42-2.9-.55-1.27-.13-2.23-.25-2.9-.35-2.13-.27-4.12-.4-5.95-.4-2.07-.03-3.6-.05-4.6-.05z"/><g transform="translate(-773.5,-373.75)"><path transform="translate(160.15,84.1)" d="m618.35 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m626.65 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
apps/web/src/components/cards/hwatu/32.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
apps/web/src/components/cards/hwatu/33.svg
Normal file
|
After Width: | Height: | Size: 37 KiB |
1
apps/web/src/components/cards/hwatu/34.svg
Normal file
|
After Width: | Height: | Size: 35 KiB |
1
apps/web/src/components/cards/hwatu/35.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1
apps/web/src/components/cards/hwatu/36.svg
Normal file
|
After Width: | Height: | Size: 56 KiB |
1
apps/web/src/components/cards/hwatu/37.svg
Normal file
|
After Width: | Height: | Size: 32 KiB |
1
apps/web/src/components/cards/hwatu/38.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/39.svg
Normal file
|
After Width: | Height: | Size: 30 KiB |
1
apps/web/src/components/cards/hwatu/4.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1
apps/web/src/components/cards/hwatu/40.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1
apps/web/src/components/cards/hwatu/41.svg
Normal file
|
After Width: | Height: | Size: 15 KiB |
1
apps/web/src/components/cards/hwatu/42.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/43.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
apps/web/src/components/cards/hwatu/44.svg
Normal file
|
After Width: | Height: | Size: 54 KiB |
1
apps/web/src/components/cards/hwatu/45.svg
Normal file
|
After Width: | Height: | Size: 40 KiB |
1
apps/web/src/components/cards/hwatu/46.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/47.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
1
apps/web/src/components/cards/hwatu/5.svg
Normal file
|
After Width: | Height: | Size: 30 KiB |
1
apps/web/src/components/cards/hwatu/6.svg
Normal file
|
After Width: | Height: | Size: 32 KiB |
1
apps/web/src/components/cards/hwatu/7.svg
Normal file
|
After Width: | Height: | Size: 25 KiB |
1
apps/web/src/components/cards/hwatu/8.svg
Normal file
|
After Width: | Height: | Size: 65 KiB |
1
apps/web/src/components/cards/hwatu/9.svg
Normal file
|
After Width: | Height: | Size: 55 KiB |
14
apps/web/src/components/cards/hwatu/ATTRIBUTION.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
화투 그림 출처 (Hwatu card artwork)
|
||||
|
||||
0.svg ~ 47.svg (화투 48장, 파일 이름 = 게임 엔진의 카드 id = (월-1)*4 + 칸)
|
||||
|
||||
- 원본: Wikimedia Commons "Category:SVG Hwatu"
|
||||
https://commons.wikimedia.org/wiki/Category:SVG_Hwatu
|
||||
(File:Hwatu January Hikari.svg ~ File:Hwatu December Kasu.svg, 2026-10-13 받음)
|
||||
- 만든 사람: Marcus Richert (Louie Mantia, Jr.의 Hanafuda 그림을 바탕으로 한국 화투처럼 다시 칠하고 일부 선을 고침),
|
||||
카드별 파일 분리: Spenĉjo
|
||||
- 라이선스: CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/)
|
||||
- 바꾼 점: 좌표를 소수 둘째 자리로 반올림하고 공백·주석을 지워 파일 크기를 줄였다. 그림 내용은 바꾸지 않았다.
|
||||
이 파일들(변형본)도 CC BY-SA 4.0 으로 배포한다.
|
||||
|
||||
원본 파일 → 이 폴더 파일 대응은 docs/games/seotda.md "화투 그림" 절에 있다.
|
||||
724
apps/web/src/games/seotda/board.tsx
Normal file
@@ -0,0 +1,724 @@
|
||||
/**
|
||||
* 섯다 판 화면 (docs/games/seotda.md §9), 한게임 섯다처럼: 초록 테이블 둘레에 자리, 가운데 판돈, 아래쪽 내 자리에 큰 패와
|
||||
* 족보 이름, 그 밑에 숫자 키가 붙은 베팅 버튼. 돈은 이 방 안에서만 쓰는 놀이용 원(§12).
|
||||
* Sound and motion follow view changes (anyone's bet, deal, reveal, payout), so other players' moves play too.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import type { BetLogEntry, BetType, CardSlot, PotOutcome, SeotdaCardView, SeotdaSeatView, SeotdaView } from '@bg/games/seotda';
|
||||
import { formatWon, formatWonDelta, formatWonShort } from '@bg/games/seotda/money';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { HwatuCard } from '../../components/cards/HwatuCard';
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { usePhone } from '../../lib/media';
|
||||
import type { BoardProps } from '../types';
|
||||
|
||||
export const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
|
||||
/** Number keys like 한게임 섯다 (콜 7, 다이 8, 삥 4, 체크 5, 따당 1, 하프 0); 쿼터 2 and 풀 9 are ours. */
|
||||
export const BET_KEY: Record<BetType, string> = { call: '7', die: '8', ping: '4', check: '5', ddadang: '1', half: '0', quarter: '2', full: '9' };
|
||||
export const BET_HELP: Record<BetType, string> = {
|
||||
check: '걸지 않고 다음 사람에게 넘겨요',
|
||||
ping: '기본금만큼 걸어요',
|
||||
call: '앞사람이 건 만큼 맞춰요',
|
||||
ddadang: '앞사람이 건 돈의 두 배를 걸어요',
|
||||
quarter: '맞춘 뒤 판돈의 4분의 1을 더 걸어요',
|
||||
half: '맞춘 뒤 판돈의 절반을 더 걸어요',
|
||||
full: '맞춘 뒤 판돈만큼 더 걸어요',
|
||||
die: '이번 판을 포기해요',
|
||||
};
|
||||
const BET_COLOR: Record<BetType, string> = {
|
||||
call: '#2563eb',
|
||||
die: '#b91c1c',
|
||||
half: '#ea580c',
|
||||
ping: '#0f766e',
|
||||
check: '#15803d',
|
||||
ddadang: '#7c3aed',
|
||||
quarter: '#0e7490',
|
||||
full: '#be123c',
|
||||
};
|
||||
const REASON_KO: Record<PotOutcome['reason'], string> = {
|
||||
normal: '',
|
||||
ttaengjabi: '땡잡이',
|
||||
amhaeng: '암행어사',
|
||||
gusa: '구사 재경기',
|
||||
mungGusa: '멍텅구리구사 재경기',
|
||||
tie: '같은 족보',
|
||||
limit: '재경기 횟수 초과로 나눔',
|
||||
fold: '모두 다이',
|
||||
};
|
||||
export const REMATCH_KO = { gusa: '구사', mungGusa: '멍텅구리구사', tie: '같은 족보' } as const;
|
||||
|
||||
export const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
export const userOf = (players: Record<string, PublicUser>, id: string): PublicUser =>
|
||||
players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
export const isCard = (c: CardSlot): c is SeotdaCardView => !('hidden' in c);
|
||||
|
||||
export function totalMsOf(v: SeotdaView): number {
|
||||
const o = v.options;
|
||||
if (v.phase === 'rebuy' || v.handPhase === 'rejoin') return o.decisionSeconds * 1000;
|
||||
if (v.handPhase === 'handEnd') return 5000;
|
||||
if (o.turnSeconds === null) return 0;
|
||||
if (v.handPhase === 'choose') return (o.turnSeconds + 10) * 1000;
|
||||
const turn = v.seats.find((s) => s.id === v.toAct);
|
||||
return turn?.away ? 5000 : o.turnSeconds * 1000;
|
||||
}
|
||||
|
||||
/** Big banner over the table after a showdown (or none). */
|
||||
function bannerOf(v: SeotdaView): string | null {
|
||||
const pots = v.showdown?.pots ?? [];
|
||||
if (pots.some((p) => p.reason === 'ttaengjabi')) return '땡잡이!';
|
||||
if (pots.some((p) => p.reason === 'amhaeng')) return '암행어사 출두!';
|
||||
if (pots.some((p) => p.type === 'rematch' && p.reason === 'gusa')) return '구사 재경기';
|
||||
if (pots.some((p) => p.type === 'rematch' && p.reason === 'mungGusa')) return '멍텅구리구사 재경기';
|
||||
if (pots.some((p) => p.type === 'rematch')) return '같은 족보 재경기';
|
||||
const win = pots.find((p) => p.type === 'win');
|
||||
const name = win ? v.showdown!.hands.find((h) => h.id === win.winners[0])?.name : null;
|
||||
if (name && /광땡|장땡/.test(name)) return `${name}!`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Hand names worth a gold badge (땡 and up). */
|
||||
const isBig = (name: string) => /광땡|땡$|장땡/.test(name) && name !== '땡잡이';
|
||||
|
||||
const CSS = `
|
||||
.sd-wrap { width: 100%; max-width: 1060px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
|
||||
.sd-table { position: relative; width: 100%; aspect-ratio: 16 / 9.4; min-height: 470px; border-radius: 44px; border: 12px solid #5b3a1e;
|
||||
background: radial-gradient(ellipse at 50% 45%, #2f8a5c 0%, #1d6a44 55%, #134b30 100%); box-shadow: inset 0 0 0 3px rgba(255,255,255,.08), inset 0 0 60px rgba(0,0,0,.35), 0 8px 24px rgba(0,0,0,.3); }
|
||||
.sd-table::before { content: ''; position: absolute; inset: 14px; border-radius: 30px; border: 2px dashed rgba(255,255,255,.12); pointer-events: none; }
|
||||
.sd-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -50%); width: 156px; z-index: 2;
|
||||
background: rgba(10, 22, 16, .78); color: #f8fafc; border-radius: 12px; padding: 6px 8px; display: flex; flex-direction: column; gap: 3px;
|
||||
border: 2px solid rgba(255,255,255,.12); box-shadow: 0 3px 10px rgba(0,0,0,.35); font-size: .82rem; transition: border-color .2s, opacity .2s; }
|
||||
.sd-seat.turn { border-color: #fbbf24; box-shadow: 0 0 0 3px rgba(251,191,36,.35), 0 3px 10px rgba(0,0,0,.35); }
|
||||
.sd-seat.out { opacity: .55; }
|
||||
.sd-seat.win { border-color: #fde047; box-shadow: 0 0 0 3px rgba(253,224,71,.5), 0 0 22px rgba(253,224,71,.45); }
|
||||
.sd-seat .nm { font-weight: 800; flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sd-money { font-variant-numeric: tabular-nums; font-weight: 800; color: #fde68a; white-space: nowrap; }
|
||||
.sd-cards { display: flex; justify-content: center; min-height: 52px; align-items: flex-end; }
|
||||
.sd-tag { display: inline-block; border-radius: 999px; padding: 0 7px; font-weight: 800; font-size: .74rem; line-height: 1.5; white-space: nowrap; }
|
||||
.sd-act { position: absolute; top: -14px; right: -8px; z-index: 3; border-radius: 10px; padding: 1px 9px; font-weight: 900; font-size: .85rem; color: #fff;
|
||||
box-shadow: 0 2px 6px rgba(0,0,0,.35); pointer-events: none; }
|
||||
.sd-hand { text-align: center; font-weight: 900; font-size: .92rem; border-radius: 8px; padding: 1px 4px; background: rgba(255,255,255,.12); color: #fff; }
|
||||
.sd-hand.big { background: linear-gradient(180deg, #fde047, #f59e0b); color: #422006; }
|
||||
.sd-delta { text-align: center; font-weight: 900; font-variant-numeric: tabular-nums; }
|
||||
.sd-delta.plus { color: #86efac; } .sd-delta.minus { color: #fca5a5; }
|
||||
.sd-center { position: absolute; left: 50%; top: 46%; transform: translate(-50%, -50%); text-align: center; color: #fff; z-index: 1; min-width: 220px; }
|
||||
.sd-pot-label { display: inline-block; font-size: .9rem; font-weight: 800; letter-spacing: .1em; background: rgba(0,0,0,.35); border-radius: 999px; padding: 1px 12px; }
|
||||
.sd-pot { font-size: 2.3rem; font-weight: 900; font-variant-numeric: tabular-nums; color: #fde68a; text-shadow: 0 2px 6px rgba(0,0,0,.55); line-height: 1.15; }
|
||||
.sd-pile { position: relative; height: 34px; width: 120px; margin: 0 auto 2px; }
|
||||
.sd-pile i { position: absolute; bottom: 0; width: 26px; height: 26px; border-radius: 50%; background: radial-gradient(circle at 35% 35%, #fff7c2, #f5b301 55%, #b45309);
|
||||
border: 2px solid #92400e; box-shadow: 0 2px 3px rgba(0,0,0,.4); }
|
||||
.sd-info { font-size: .82rem; opacity: .92; margin-top: 2px; }
|
||||
.sd-banner { position: absolute; left: 0; right: 0; top: 30%; text-align: center; z-index: 6; font-size: 3rem; font-weight: 900; color: #fde047;
|
||||
-webkit-text-stroke: 2px #7c2d12; text-shadow: 0 4px 12px rgba(0,0,0,.6); white-space: nowrap; }
|
||||
.sd-fly { position: absolute; left: var(--sx); top: var(--sy); width: 22px; height: 22px; margin: -11px 0 0 -11px; border-radius: 50%; z-index: 7; pointer-events: none;
|
||||
background: radial-gradient(circle at 35% 35%, #fff7c2, #f5b301 55%, #b45309); border: 2px solid #92400e;
|
||||
animation: sd-fly .55s cubic-bezier(.3,.7,.4,1) both; animation-delay: var(--d, 0ms); }
|
||||
@keyframes sd-fly { from { transform: translate(0, 0) scale(.9); opacity: 1; } 85% { opacity: 1; } to { transform: translate(var(--dx), var(--dy)) scale(.7); opacity: 0; } }
|
||||
.sd-me { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); z-index: 2; display: flex; align-items: flex-end; gap: 14px;
|
||||
background: rgba(10, 22, 16, .72); border: 2px solid rgba(255,255,255,.14); border-radius: 16px; padding: 8px 14px; color: #fff; max-width: 96%; }
|
||||
.sd-me.turn { border-color: #fbbf24; box-shadow: 0 0 0 3px rgba(251,191,36,.35); }
|
||||
.sd-me.win { border-color: #fde047; box-shadow: 0 0 0 3px rgba(253,224,71,.5), 0 0 22px rgba(253,224,71,.45); }
|
||||
.sd-me .mine { display: flex; gap: 6px; align-items: flex-end; }
|
||||
.sd-me .meta { display: flex; flex-direction: column; gap: 3px; min-width: 150px; }
|
||||
.sd-myhand { font-size: 1.45rem; font-weight: 900; color: #fde047; text-shadow: 0 2px 4px rgba(0,0,0,.5); line-height: 1.15; }
|
||||
.sd-bar { display: flex; gap: 12px; align-items: stretch; justify-content: center; flex-wrap: wrap; }
|
||||
.sd-bets { display: grid; grid-template-columns: repeat(3, minmax(92px, 1fr)); gap: 8px; flex: 1; max-width: 560px; }
|
||||
.sd-bet { position: relative; min-height: 58px; border: 0; border-radius: 12px; color: #fff; font-weight: 900; font-size: 1.15rem; cursor: pointer;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.1; box-shadow: inset 0 -3px 0 rgba(0,0,0,.25), 0 2px 4px rgba(0,0,0,.2); }
|
||||
.sd-bet small { font-size: .78rem; font-weight: 700; opacity: .95; font-variant-numeric: tabular-nums; }
|
||||
.sd-bet kbd { position: absolute; top: 4px; left: 6px; font: 700 .7rem/1 inherit; opacity: .8; background: rgba(0,0,0,.25); border-radius: 4px; padding: 2px 4px; }
|
||||
.sd-bet:disabled { filter: grayscale(.85) brightness(.85); opacity: .45; cursor: default; box-shadow: none; }
|
||||
.sd-bet:not(:disabled):hover { filter: brightness(1.1); }
|
||||
.sd-bet:not(:disabled):active { transform: translateY(1px); }
|
||||
.sd-help { margin: 0; text-align: center; min-height: 1.4em; }
|
||||
@media (max-width: 719px) {
|
||||
.sd-table { aspect-ratio: auto; min-height: 0; border-width: 7px; border-radius: 22px; padding: 10px 8px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.sd-table::before { inset: 6px; border-radius: 16px; }
|
||||
.sd-others { display: grid; grid-template-columns: repeat(var(--cols, 2), minmax(0, 1fr)); gap: 6px; }
|
||||
.sd-seat { position: relative; left: auto; top: auto; transform: none; width: auto; padding: 5px 6px; font-size: .76rem; }
|
||||
.sd-cards { min-height: 40px; }
|
||||
.sd-act { top: -9px; right: auto; left: -4px; font-size: .74rem; padding: 0 7px; }
|
||||
.sd-center { position: relative; left: auto; top: auto; transform: none; min-width: 0; padding: 2px 0; }
|
||||
.sd-pot { font-size: 1.8rem; }
|
||||
.sd-pile { height: 26px; }
|
||||
.sd-pile i { width: 20px; height: 20px; }
|
||||
.sd-banner { position: fixed; top: 38%; font-size: 2.2rem; }
|
||||
.sd-me { position: relative; left: auto; bottom: auto; transform: none; max-width: none; justify-content: center; gap: 10px; padding: 8px; }
|
||||
.sd-me .meta { min-width: 0; flex: 1; }
|
||||
.sd-myhand { font-size: 1.15rem; }
|
||||
.sd-bets { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; max-width: none; }
|
||||
.sd-bet { min-height: 56px; font-size: 1.05rem; }
|
||||
.sd-bet kbd { display: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- table positions
|
||||
|
||||
/** Seats other than mine around the table: from my left, over the top, to my right (PC). */
|
||||
function seatPos(rel: number, others: number): { x: number; y: number } {
|
||||
const t = rel / (others + 1);
|
||||
const ang = ((150 + t * 240) * Math.PI) / 180;
|
||||
return { x: 50 + 41 * Math.cos(ang), y: 49 + 36 * Math.sin(ang) };
|
||||
}
|
||||
|
||||
/** Pile of coins in the middle; more coins for a bigger 판돈 (up to 9). */
|
||||
function Pile({ pot, base }: { pot: number; base: number }) {
|
||||
const n = pot <= 0 ? 0 : Math.min(9, 1 + Math.floor(Math.log2(Math.max(1, pot / Math.max(1, base)))));
|
||||
return (
|
||||
<div className="sd-pile" aria-hidden>
|
||||
{Array.from({ length: n }, (_, i) => (
|
||||
<i key={i} style={{ left: 47 + ((i % 3) - 1) * 22 + (i > 2 ? 6 : 0), bottom: Math.floor(i / 3) * 6 }} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- seats
|
||||
|
||||
function SeatCards({ seat, view: v, width }: { seat: SeotdaSeatView; view: SeotdaView; width: number }) {
|
||||
if (!seat.cards.length) return <div className="sd-cards" />;
|
||||
const tag = `${v.handNo}-${v.rematchNo}`;
|
||||
return (
|
||||
<div className="sd-cards">
|
||||
{seat.cards.map((c, i) =>
|
||||
isCard(c) ? (
|
||||
<HwatuCard key={c.key} card={c} width={width} className="anim-flip" style={{ marginLeft: i ? -Math.round(width * 0.3) : 0, ['--anim-delay' as string]: `${i * 90}ms` }} />
|
||||
) : (
|
||||
<HwatuCard key={`b${tag}-${i}`} card={null} width={width} className="anim-deal" style={{ marginLeft: i ? -Math.round(width * 0.3) : 0, ['--anim-delay' as string]: `${i * 80}ms` }} />
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActBubble({ seat }: { seat: SeotdaSeatView }) {
|
||||
const a = seat.folded ? { type: 'die' as BetType, amount: 0 } : seat.lastAction;
|
||||
if (!a) return null;
|
||||
return (
|
||||
<span key={`${a.type}-${a.amount}`} className="sd-act anim-pop" style={{ background: BET_COLOR[a.type] }}>
|
||||
{BET_KO[a.type]}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface SeatProps {
|
||||
seat: SeotdaSeatView;
|
||||
view: SeotdaView;
|
||||
players: Record<string, PublicUser>;
|
||||
me: string | null;
|
||||
deadline: number | null;
|
||||
pos: { x: number; y: number } | null;
|
||||
cardW: number;
|
||||
winner: boolean;
|
||||
setRef: (id: string, el: HTMLElement | null) => void;
|
||||
}
|
||||
|
||||
function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) {
|
||||
const u = userOf(players, seat.id);
|
||||
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
|
||||
const tags: [string, string][] = [];
|
||||
if (seat.left) tags.push(['나감', '#b91c1c']);
|
||||
else if (seat.away) tags.push(['자리 비움', '#b45309']);
|
||||
if (seat.status === 'eliminated') tags.push(['탈락', '#475569']);
|
||||
if (seat.status === 'busted') tags.push(['다시 받는 중', '#b45309']);
|
||||
if (seat.allIn) tags.push(['올인', '#1d4ed8']);
|
||||
if (seat.chosen === true) tags.push(['고름', '#15803d']);
|
||||
if (seat.chosen === false) tags.push(['고르는 중', '#475569']);
|
||||
const timed = seat.isTurn || seat.chosen === false;
|
||||
const style = pos ? ({ '--x': `${pos.x}%`, '--y': `${pos.y}%` } as CSSProperties) : undefined;
|
||||
return (
|
||||
<div
|
||||
ref={(el) => setRef(seat.id, el)}
|
||||
className={`sd-seat${seat.isTurn ? ' turn' : ''}${out ? ' out' : ''}${winner ? ' win' : ''}`}
|
||||
style={style}
|
||||
aria-label={`${u.nickname}, 보유 ${formatWon(seat.stack)}${seat.isDealer ? ', 선' : ''}${seat.folded ? ', 다이' : ''}${tags.length ? `, ${tags.map((t) => t[0]).join(', ')}` : ''}`}
|
||||
>
|
||||
<ActBubble seat={seat} />
|
||||
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={22} />
|
||||
<span className="nm">
|
||||
{u.nickname}
|
||||
{seat.id === me && ' (나)'}
|
||||
</span>
|
||||
{seat.isDealer && (
|
||||
<span className="sd-tag" style={{ background: '#facc15', color: '#422006' }} title="선(먼저 받고 먼저 거는 사람)">
|
||||
선
|
||||
</span>
|
||||
)}
|
||||
{timed && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine={seat.id === me} size={26} />}
|
||||
</div>
|
||||
<div className="row" style={{ justifyContent: 'space-between', gap: 4, flexWrap: 'nowrap' }}>
|
||||
<span className="sd-money" title="보유 금액">
|
||||
{formatWonShort(seat.stack)}원
|
||||
</span>
|
||||
{seat.matchBet > 0 && (
|
||||
<span className="small" style={{ opacity: 0.85, whiteSpace: 'nowrap' }} title="이번 판에 건 돈">
|
||||
건 돈 {formatWonShort(seat.matchBet)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<SeatCards seat={seat} view={v} width={cardW} />
|
||||
{seat.handName && <div className={`sd-hand${isBig(seat.handName) ? ' big' : ''} anim-pop`}>{seat.handName}</div>}
|
||||
{seat.handDelta !== null && seat.handDelta !== 0 && (
|
||||
<div className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</div>
|
||||
)}
|
||||
{tags.length > 0 && (
|
||||
<div className="row" style={{ gap: 3 }}>
|
||||
{tags.map(([t, c]) => (
|
||||
<span key={t} className="sd-tag" style={{ background: c, color: '#fff' }}>
|
||||
{t}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** My place at the bottom of the table: big cards, 족보 name, money. */
|
||||
function MySeat({ seat, view: v, players, deadline, winner, setRef, phone }: { seat: SeotdaSeatView; view: SeotdaView; players: Record<string, PublicUser>; deadline: number | null; winner: boolean; setRef: SeatProps['setRef']; phone: boolean }) {
|
||||
const u = userOf(players, seat.id);
|
||||
const cards = seat.cards;
|
||||
const w = phone ? (cards.length > 2 ? 62 : 74) : cards.length > 2 ? 78 : 92;
|
||||
const tag = `${v.handNo}-${v.rematchNo}`;
|
||||
const h = v.myHand;
|
||||
return (
|
||||
<div ref={(el) => setRef(seat.id, el)} className={`sd-me${seat.isTurn ? ' turn' : ''}${winner ? ' win' : ''}`} aria-label={`내 자리, 보유 ${formatWon(seat.stack)}`}>
|
||||
<ActBubble seat={seat} />
|
||||
<div className="mine" aria-label="내 패">
|
||||
{cards.length === 0 && <span className="small" style={{ opacity: 0.8, alignSelf: 'center' }}>{seat.inHand ? '패를 기다리는 중' : '이번 판은 쉬어요'}</span>}
|
||||
{cards.map((c, i) =>
|
||||
isCard(c) ? (
|
||||
<HwatuCard
|
||||
key={c.key}
|
||||
card={c}
|
||||
width={w}
|
||||
className="anim-deal"
|
||||
highlight={!!v.myChosen?.includes(c.id)}
|
||||
dimmed={(!!v.myChosen && !v.myChosen.includes(c.id)) || seat.folded}
|
||||
style={{ ['--anim-delay' as string]: `${i * 110}ms`, ['--from-y' as string]: '-180px' }}
|
||||
/>
|
||||
) : (
|
||||
<HwatuCard key={`m${tag}-${i}`} card={null} width={w} />
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<div className="meta">
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={22} />
|
||||
<strong style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.nickname} (나)</strong>
|
||||
{seat.isDealer && (
|
||||
<span className="sd-tag" style={{ background: '#facc15', color: '#422006' }}>
|
||||
선
|
||||
</span>
|
||||
)}
|
||||
{(seat.isTurn || seat.chosen === false) && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine size={30} />}
|
||||
</div>
|
||||
<span className="sd-money" style={{ fontSize: '1.05rem' }}>
|
||||
{formatWon(seat.stack)}
|
||||
</span>
|
||||
{h && seat.inHand && !seat.folded && !seat.handName && (
|
||||
<span className="sd-myhand" aria-live="polite">
|
||||
{h.name}
|
||||
</span>
|
||||
)}
|
||||
{h && seat.inHand && !seat.folded && !seat.handName && v.options.hints && <span className="small" style={{ opacity: 0.9 }}>{h.hint}</span>}
|
||||
{seat.folded && <span className="small" style={{ opacity: 0.9 }}>다이했어요. 내 패는 나만 볼 수 있어요.</span>}
|
||||
{seat.handName && <div className={`sd-myhand anim-pop`}>{seat.handName}</div>}
|
||||
{seat.handDelta !== null && seat.handDelta !== 0 && (
|
||||
<div className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`} style={{ textAlign: 'left', fontSize: '1.1rem' }}>
|
||||
{formatWonDelta(seat.handDelta)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Center({ view: v, potRef }: { view: SeotdaView; potRef: (el: HTMLElement | null) => void }) {
|
||||
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
|
||||
// On the result screen the paid pots are no longer in v.pot (only a carried rematch pot is).
|
||||
const paid =
|
||||
v.handPhase === 'handEnd' ? (v.foldWin?.amount ?? (v.showdown?.pots ?? []).filter((p) => p.type !== 'rematch').reduce((a, p) => a + p.amount, 0)) : 0;
|
||||
const shown = v.pot + paid;
|
||||
const [bump, setBump] = useState(0);
|
||||
const last = useRef(v.pot);
|
||||
useEffect(() => {
|
||||
if (v.pot > last.current) setBump((b) => b + 1);
|
||||
last.current = v.pot;
|
||||
}, [v.pot]);
|
||||
return (
|
||||
<div className="sd-center" ref={potRef}>
|
||||
{v.rematchNo > 0 && v.rematchReason && (
|
||||
<div className="sd-tag" style={{ background: '#fde047', color: '#422006', fontSize: '.9rem', padding: '1px 12px', marginBottom: 4 }}>
|
||||
재경기 {v.rematchNo}회차 · {REMATCH_KO[v.rematchReason]}
|
||||
</div>
|
||||
)}
|
||||
<Pile pot={shown} base={v.baseUnit} />
|
||||
<div className="sd-pot-label">판돈</div>
|
||||
<div key={bump} className={`sd-pot${bump ? ' anim-bump' : ''}`} aria-live="polite" aria-label={`판돈 ${formatWon(shown)}`}>
|
||||
{formatWon(shown)}
|
||||
</div>
|
||||
{v.pots.length > 1 && v.handPhase === 'betting' && (
|
||||
<div className="small" style={{ opacity: 0.9 }}>
|
||||
{v.pots.map((p, i) => (
|
||||
<div key={i}>
|
||||
{i === v.pots.length - 1 ? '메인' : `사이드 ${i + 1}`} {formatWonShort(p.amount)}원
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="sd-info">
|
||||
{v.phase === 'finished' ? '게임 끝' : `${Math.max(1, v.handNo)}${limit}판`} · 기본금 {formatWon(v.baseUnit)}
|
||||
{v.handPhase === 'betting' && v.currentBet > 0 ? ` · 콜 ${formatWonShort(v.currentBet)}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- effects (sound + motion from view changes)
|
||||
|
||||
interface Fly {
|
||||
id: number;
|
||||
sx: number;
|
||||
sy: number;
|
||||
dx: number;
|
||||
dy: number;
|
||||
d: number;
|
||||
}
|
||||
|
||||
function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefObject<HTMLDivElement | null>, seatEls: React.MutableRefObject<Map<string, HTMLElement>>, potEl: React.MutableRefObject<HTMLElement | null>) {
|
||||
const [flies, setFlies] = useState<Fly[]>([]);
|
||||
const [banner, setBanner] = useState<{ text: string; key: number } | null>(null);
|
||||
const seen = useRef<{ match: string; log: number; cards: number; phase: string | null } | null>(null);
|
||||
const flyId = useRef(0);
|
||||
|
||||
const center = (el: HTMLElement | null | undefined) => {
|
||||
const t = tableRef.current?.getBoundingClientRect();
|
||||
const r = el?.getBoundingClientRect();
|
||||
if (!t || !r) return null;
|
||||
return { x: r.left + r.width / 2 - t.left, y: r.top + r.height / 2 - t.top };
|
||||
};
|
||||
const launch = (from: string | 'pot', to: string | 'pot', n: number) => {
|
||||
const a = center(from === 'pot' ? potEl.current : seatEls.current.get(from));
|
||||
const b = center(to === 'pot' ? potEl.current : seatEls.current.get(to));
|
||||
if (!a || !b) return;
|
||||
const add: Fly[] = Array.from({ length: n }, (_, i) => ({ id: ++flyId.current, sx: a.x + (i % 2 ? 6 : -6), sy: a.y, dx: b.x - a.x, dy: b.y - a.y, d: i * 70 }));
|
||||
setFlies((f) => [...f, ...add]);
|
||||
const ids = new Set(add.map((x) => x.id));
|
||||
setTimeout(() => setFlies((f) => f.filter((x) => !ids.has(x.id))), 700 + n * 70);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const match = `${v.handNo}-${v.rematchNo}`;
|
||||
const cards = v.seats.reduce((a, s) => a + s.cards.length, 0);
|
||||
const prev = seen.current;
|
||||
seen.current = { match, log: v.betLog.length, cards, phase: v.handPhase };
|
||||
if (!prev) return; // first render: nothing to replay
|
||||
const sameMatch = prev.match === match;
|
||||
// Deal: a new (re)match or more cards on the table.
|
||||
if (!sameMatch || cards > prev.cards) {
|
||||
if (!sameMatch) sfx.shuffle();
|
||||
const dealt = sameMatch ? cards - prev.cards : cards;
|
||||
if (v.handPhase === 'betting' || v.handPhase === 'choose') sfx.deal(Math.min(6, Math.max(1, dealt)), 60);
|
||||
}
|
||||
// Bets since last time (anyone's): coins fly from the seat to the 판돈.
|
||||
const fresh: BetLogEntry[] = sameMatch ? v.betLog.slice(prev.log) : v.betLog;
|
||||
fresh.forEach((e, i) => {
|
||||
setTimeout(() => {
|
||||
if (e.t === 'die') sfx.whoosh();
|
||||
else if (e.amount <= 0) sfx.tick();
|
||||
else {
|
||||
const n = e.t === 'ping' || e.t === 'call' ? 2 : e.t === 'full' ? 5 : e.t === 'quarter' ? 3 : 4;
|
||||
sfx.chips(n);
|
||||
launch(e.p, 'pot', n);
|
||||
}
|
||||
}, i * 220);
|
||||
});
|
||||
// Result: reveal, payout, banner.
|
||||
if (v.handPhase === 'handEnd' && prev.phase !== 'handEnd') {
|
||||
if (v.showdown) sfx.cardFlip();
|
||||
const winners = new Set<string>();
|
||||
if (v.foldWin) winners.add(v.foldWin.winner);
|
||||
for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w);
|
||||
const b = bannerOf(v);
|
||||
setTimeout(() => {
|
||||
for (const w of winners) launch('pot', w, 5);
|
||||
if (winners.size) sfx.collect();
|
||||
if (b) {
|
||||
setBanner({ text: b, key: Date.now() });
|
||||
if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare();
|
||||
else sfx.pop();
|
||||
}
|
||||
if (me && winners.has(me)) {
|
||||
sounds.win();
|
||||
haptic([40, 30, 80]);
|
||||
} else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose();
|
||||
}, v.showdown ? 450 : 150);
|
||||
}
|
||||
}); // every render: cheap comparisons against the refs
|
||||
|
||||
useEffect(() => {
|
||||
if (!banner) return undefined;
|
||||
const t = setTimeout(() => setBanner(null), 1700);
|
||||
return () => clearTimeout(t);
|
||||
}, [banner]);
|
||||
|
||||
return { flies, banner };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- bet bar
|
||||
|
||||
function BetBar({ view: v, me, act, pending, players }: { view: SeotdaView; me: string; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
const seat = v.seats.find((s) => s.id === me)!;
|
||||
const myTurn = v.toAct === me && v.handPhase === 'betting';
|
||||
const legal = new Map(v.legal.map((l) => [l.type, l]));
|
||||
const [hover, setHover] = useState<BetType | null>(null);
|
||||
const types: BetType[] = ['call', 'die', 'half', 'ping', 'check', 'ddadang'];
|
||||
if (v.options.quarter) types.push('quarter');
|
||||
if (v.options.maxRaise === 'full') types.push('full');
|
||||
const press = (t: BetType) => {
|
||||
if (!myTurn || pending || !legal.has(t)) return;
|
||||
sfx.click();
|
||||
act({ type: t });
|
||||
};
|
||||
// Number keys (PC), like 한게임 섯다. Ignored while typing in the chat.
|
||||
const pressRef = useRef(press);
|
||||
pressRef.current = press;
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
const el = e.target as HTMLElement | null;
|
||||
if (el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable)) return;
|
||||
const t = (Object.keys(BET_KEY) as BetType[]).find((k) => BET_KEY[k] === e.key);
|
||||
if (t) {
|
||||
pressRef.current(t);
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, []);
|
||||
const hoverBet = hover ? legal.get(hover) : undefined;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<div className="sd-bar">
|
||||
<div className="sd-bets" role="group" aria-label="베팅">
|
||||
{types.map((t) => {
|
||||
const l = legal.get(t);
|
||||
const enabled = myTurn && !!l && !pending;
|
||||
return (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className={`sd-bet${enabled && t !== 'die' ? ' anim-pop' : ''}`}
|
||||
style={{ background: BET_COLOR[t] }}
|
||||
disabled={!enabled}
|
||||
title={`${BET_HELP[t]} (숫자 ${BET_KEY[t]})`}
|
||||
aria-keyshortcuts={BET_KEY[t]}
|
||||
onMouseEnter={() => setHover(t)}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
onFocus={() => setHover(t)}
|
||||
onBlur={() => setHover(null)}
|
||||
onClick={() => press(t)}
|
||||
>
|
||||
<kbd aria-hidden>{BET_KEY[t]}</kbd>
|
||||
<span>{BET_KO[t]}</span>
|
||||
<small>{l ? (l.amount > 0 ? `${formatWonShort(l.amount)}원${l.allIn ? ' 올인' : ''}` : t === 'die' ? '포기' : '0원') : ' '}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<p className="small muted sd-help">
|
||||
{myTurn
|
||||
? hoverBet
|
||||
? `${BET_KO[hover!]}: ${BET_HELP[hover!]}. 걸고 나면 내 돈 ${formatWon(seat.stack - hoverBet.amount)}, 판돈 ${formatWon(v.pot + hoverBet.amount)}`
|
||||
: v.forcedHalf
|
||||
? `베팅 규칙 ${v.options.betRule}: 첫 베팅은 하프 또는 다이만 할 수 있어요.`
|
||||
: '내 차례예요. 버튼이나 숫자 키로 걸어요.'
|
||||
: v.toAct
|
||||
? `${nick(players, v.toAct)}님 차례예요.`
|
||||
: ' '}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 3장 섯다 choice and result
|
||||
|
||||
function ChooseBox({ view: v, me, act, pending }: { view: SeotdaView; me: string; act: (a: unknown) => void; pending: boolean }) {
|
||||
const seat = v.seats.find((s) => s.id === me)!;
|
||||
const [pick, setPick] = useState<number[]>([]);
|
||||
useEffect(() => setPick([]), [v.handNo, v.rematchNo]);
|
||||
const cards = seat.cards.filter(isCard);
|
||||
const preview = pick.length === 2 ? v.myCombos?.find((c) => c.cardIds.includes(pick[0]!) && c.cardIds.includes(pick[1]!)) : null;
|
||||
const toggle = (id: number) => setPick((p) => (p.includes(id) ? p.filter((x) => x !== id) : p.length >= 2 ? [p[1]!, id] : [...p, id]));
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 8, padding: 12 }}>
|
||||
<p style={{ margin: 0, textAlign: 'center' }}>
|
||||
<strong>쓸 패 2장을 골라 주세요.</strong> 남는 1장은 아무에게도 보이지 않아요.
|
||||
</p>
|
||||
<div className="row" style={{ justifyContent: 'center', gap: 10 }}>
|
||||
{cards.map((c) => (
|
||||
<HwatuCard key={c.key} card={c} size="lg" selected={pick.includes(c.id)} onClick={() => toggle(c.id)} />
|
||||
))}
|
||||
</div>
|
||||
{v.options.hints && v.myCombos && (
|
||||
<div className="row" style={{ justifyContent: 'center', gap: 6 }}>
|
||||
{v.myCombos.map((c) => (
|
||||
<button key={c.cardIds.join()} type="button" className={`btn btn-sm ${c.best ? 'btn-soft' : 'btn-ghost'}`} onClick={() => setPick([...c.cardIds])}>
|
||||
{c.name}
|
||||
{c.best ? ' (추천)' : ''}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<button type="button" className="btn btn-primary" disabled={pick.length !== 2 || pending} onClick={() => act({ type: 'choose', cardIds: [pick[0], pick[1]] })}>
|
||||
{preview ? `${preview.name}(으)로 정하기` : '두 장을 고르세요'}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function resultLine(v: SeotdaView, players: Record<string, PublicUser>): string {
|
||||
if (v.foldWin) return `${nick(players, v.foldWin.winner)}님이 판돈 ${formatWon(v.foldWin.amount)}을 가져갔어요(모두 다이).`;
|
||||
if (!v.showdown) return '';
|
||||
return v.showdown.pots
|
||||
.map((p) => {
|
||||
const who = p.winners.map((id) => nick(players, id)).join('·');
|
||||
const name = v.showdown!.hands.find((h) => h.id === p.winners[0])?.name ?? '';
|
||||
if (p.type === 'rematch') return `${REASON_KO[p.reason]}: ${who}님이 다시 겨뤄요(판돈 ${formatWon(p.amount)} 그대로)`;
|
||||
if (p.type === 'split') return `${who}님이 ${formatWon(p.amount)}을 나눠 가졌어요${p.reason === 'limit' ? '(재경기 횟수 초과)' : ''}`;
|
||||
return `${who}님이 ${name}${p.reason === 'normal' ? '' : ' 발동'}(으)로 ${formatWon(p.amount)}을 가져갔어요`;
|
||||
})
|
||||
.join(' / ');
|
||||
}
|
||||
|
||||
function ResultPanel({ view: v, players }: { view: SeotdaView; players: Record<string, PublicUser> }) {
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }} aria-live="polite">
|
||||
<strong>{v.next === 'rematch' ? '재경기가 정해졌어요' : '이번 판 결과'}</strong>
|
||||
{v.foldWin && (
|
||||
<span>
|
||||
{nick(players, v.foldWin.winner)}님이 판돈 {formatWon(v.foldWin.amount)}을 가져갔어요. 모두 다이해서 패는 공개하지 않아요.
|
||||
</span>
|
||||
)}
|
||||
{v.showdown?.pots.map((p, i) => {
|
||||
const who = p.winners.map((id) => nick(players, id)).join(' · ');
|
||||
const name = v.showdown!.hands.find((h) => h.id === p.winners[0])?.name;
|
||||
const label = v.showdown!.pots.length > 1 ? `${i === v.showdown!.pots.length - 1 ? '메인' : '사이드'} ${formatWon(p.amount)}: ` : `판돈 ${formatWon(p.amount)}: `;
|
||||
return (
|
||||
<span key={i}>
|
||||
{label}
|
||||
{p.type === 'win' && (
|
||||
<>
|
||||
<strong>{who}</strong> 승리 ({name}
|
||||
{p.reason === 'ttaengjabi' || p.reason === 'amhaeng' ? ' 발동' : ''})
|
||||
</>
|
||||
)}
|
||||
{p.type === 'split' && (
|
||||
<>
|
||||
<strong>{who}</strong> 나눠 가짐{p.reason === 'limit' ? ' (재경기 횟수 초과)' : ' (같은 족보)'}
|
||||
</>
|
||||
)}
|
||||
{p.type === 'rematch' && (
|
||||
<>
|
||||
<strong>{REASON_KO[p.reason]}</strong>: {who}님이 다시 겨뤄요. 판돈은 그대로 남아요.
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: BoardProps<SeotdaView>) {
|
||||
const phone = usePhone();
|
||||
const n = v.seats.length;
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
const mySeat = myIdx >= 0 ? v.seats[myIdx]! : null;
|
||||
const base = Math.max(0, myIdx);
|
||||
const others = v.seats.map((s, i) => ({ s, rel: (i - base + n) % n })).filter((x) => x.s.id !== mySeat?.id).sort((a, b) => a.rel - b.rel);
|
||||
const tableRef = useRef<HTMLDivElement | null>(null);
|
||||
const seatEls = useRef(new Map<string, HTMLElement>());
|
||||
const potEl = useRef<HTMLElement | null>(null);
|
||||
const setRef = (id: string, el: HTMLElement | null) => {
|
||||
if (el) seatEls.current.set(id, el);
|
||||
else seatEls.current.delete(id);
|
||||
};
|
||||
const { flies, banner } = useTableEffects(v, me, tableRef, seatEls, potEl);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevToAct = useRef(v.toAct);
|
||||
useLayoutEffect(() => {
|
||||
if (v.toAct && v.toAct !== prevToAct.current) {
|
||||
if (v.toAct === me) {
|
||||
haptic(40);
|
||||
sounds.myTurn();
|
||||
setAnnounce('내 차례예요.');
|
||||
} else setAnnounce(`${nick(players, v.toAct)}님 차례예요.`);
|
||||
}
|
||||
prevToAct.current = v.toAct;
|
||||
}, [v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const winners = new Set<string>();
|
||||
if (v.handPhase === 'handEnd') {
|
||||
if (v.foldWin) winners.add(v.foldWin.winner);
|
||||
for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w);
|
||||
}
|
||||
const cardW = phone ? (v.options.cardMode === 'three' ? 24 : 28) : v.options.cardMode === 'three' ? 38 : 46;
|
||||
const cols = phone ? (others.length > 4 ? 3 : 2) : 0;
|
||||
const othersEls: ReactNode = others.map(({ s, rel }) => (
|
||||
<Seat
|
||||
key={s.id}
|
||||
seat={s}
|
||||
view={v}
|
||||
players={players}
|
||||
me={me}
|
||||
deadline={deadline}
|
||||
pos={phone ? null : seatPos(mySeat ? rel : rel + 1, mySeat ? n - 1 : n)}
|
||||
cardW={cardW}
|
||||
winner={winners.has(s.id)}
|
||||
setRef={setRef}
|
||||
/>
|
||||
));
|
||||
return (
|
||||
<div className="sd-wrap">
|
||||
<style>{CSS}</style>
|
||||
<div className="sd-table" ref={tableRef} role="region" aria-label="섯다 테이블">
|
||||
{phone ? (
|
||||
<div className="sd-others" style={{ '--cols': cols } as CSSProperties}>
|
||||
{othersEls}
|
||||
</div>
|
||||
) : (
|
||||
othersEls
|
||||
)}
|
||||
<Center view={v} potRef={(el) => (potEl.current = el)} />
|
||||
{mySeat && <MySeat seat={mySeat} view={v} players={players} deadline={deadline} winner={winners.has(mySeat.id)} setRef={setRef} phone={phone} />}
|
||||
{flies.map((f) => (
|
||||
<span key={f.id} className="sd-fly" aria-hidden style={{ '--sx': `${f.sx}px`, '--sy': `${f.sy}px`, '--dx': `${f.dx}px`, '--dy': `${f.dy}px`, '--d': `${f.d}ms` } as CSSProperties} />
|
||||
))}
|
||||
{banner && (
|
||||
<div key={banner.key} className="sd-banner anim-banner" aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{mySeat && v.handPhase === 'choose' && mySeat.chosen === false && <ChooseBox view={v} me={mySeat.id} act={act} pending={pending} />}
|
||||
{mySeat && v.handPhase === 'choose' && mySeat.chosen === true && <p className="small muted sd-help">골랐어요. 다른 사람이 고르기를 기다리는 중이에요.</p>}
|
||||
{mySeat && mySeat.inHand && v.handPhase === 'betting' && !mySeat.folded && <BetBar view={v} me={mySeat.id} act={act} pending={pending} players={players} />}
|
||||
{v.handPhase === 'handEnd' && <ResultPanel view={v} players={players} />}
|
||||
{mySeat && v.handPhase === 'handEnd' && mySeat.status === 'playing' && !mySeat.left && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={mySeat.ready || pending} onClick={() => act({ type: 'ready' })}>
|
||||
{mySeat.ready ? '다른 사람을 기다리는 중…' : v.next === 'rematch' ? '재경기 시작' : '다음 판으로'}
|
||||
</button>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,8 +7,8 @@ const users = usersOf(['A', 'B', 'C']);
|
||||
const view = (s: unknown, who: string | null) => GAMES.seotda!.view(s, who) as any;
|
||||
const nickOf = (id: string) => users[id]!.nickname;
|
||||
|
||||
test('섯다: 내 차례(버튼·족보) / 상대 차례 / 관전', () => {
|
||||
const { state } = setupGame('seotda', 3);
|
||||
test('섯다: 내 차례(버튼·족보) / 상대 차례 / 관전 (1장씩 받는 방)', () => {
|
||||
const { state } = setupGame('seotda', 3, { dealMode: 'twoRounds' });
|
||||
const turn = view(state, null).toAct as string;
|
||||
const other = ['A', 'B', 'C'].find((id) => id !== turn)!;
|
||||
|
||||
@@ -27,7 +27,7 @@ test('섯다: 내 차례(버튼·족보) / 상대 차례 / 관전', () => {
|
||||
|
||||
const spec = helpNow(view(state, null), null, users);
|
||||
expect(spec).toContain(`${nickOf(turn)}님 차례예요`);
|
||||
expect(spec).toContain('모인 칩');
|
||||
expect(spec).toContain('판돈은 3만원');
|
||||
expect(spec).not.toContain('내 족보');
|
||||
expect(spec).not.toContain('월 한 장');
|
||||
|
||||
@@ -37,11 +37,25 @@ test('섯다: 내 차례(버튼·족보) / 상대 차례 / 관전', () => {
|
||||
const t = helpNow(view(s2, next), next, users);
|
||||
expect(t).toContain('[콜]');
|
||||
expect(t).toContain('[따당]');
|
||||
expect(t).toContain('[콜]은 그만큼(10 칩) 맞추는');
|
||||
expect(t).toContain('[콜]은 그만큼(1만원) 맞추는');
|
||||
expect(t).toContain('숫자 키(콜 7');
|
||||
});
|
||||
|
||||
test('섯다: 한게임 기본(2장 한 번에), 베팅 규칙 111 안내', () => {
|
||||
const { state } = setupGame('seotda', 3);
|
||||
const turn = view(state, null).toAct as string;
|
||||
const t = helpNow(view(state, turn), turn, users);
|
||||
expect(t).toContain('2장을 받고 한 번만 베팅해요');
|
||||
expect(t).toContain('지금 내 족보:');
|
||||
const forced = setupGame('seotda', 3, { betRule: '111' }).state;
|
||||
const p = view(forced, null).toAct as string;
|
||||
const f = helpNow(view(forced, p), p, users);
|
||||
expect(f).toContain('누를 수 있는 버튼: [다이] [하프]');
|
||||
expect(f).toContain('베팅 규칙 111');
|
||||
});
|
||||
|
||||
test('섯다: 2장째를 받으면 지금 내 족보와 마지막 베팅, 족보 숨기기 옵션', () => {
|
||||
let { state } = setupGame('seotda', 2);
|
||||
let { state } = setupGame('seotda', 2, { dealMode: 'twoRounds' });
|
||||
for (let i = 0; i < 2; i++) state = applyAction('seotda', state, view(state, null).toAct, { type: 'check' });
|
||||
const v = view(state, null);
|
||||
expect(v.street).toBe(1);
|
||||
@@ -51,7 +65,7 @@ test('섯다: 2장째를 받으면 지금 내 족보와 마지막 베팅, 족보
|
||||
|
||||
const off = setupGame('seotda', 2, { hints: false }).state;
|
||||
const p = view(off, null).toAct as string;
|
||||
expect(helpNow(view(off, p), p, users)).toContain("'족보표'를 보고");
|
||||
expect(helpNow(view(off, p), p, users)).toContain("'족보 도우미'를 보고");
|
||||
});
|
||||
|
||||
test('섯다: 3장 섯다 고르기 단계', () => {
|
||||
@@ -61,7 +75,7 @@ test('섯다: 3장 섯다 고르기 단계', () => {
|
||||
const t = helpNow(view(state, 'A'), 'A', users);
|
||||
expect(t).toContain('2장을 눌러 고르면');
|
||||
expect(t).toContain('정하기');
|
||||
expect(t).toContain('[추천 조합]');
|
||||
expect(t).toContain('(추천)]이 가장 센 조합');
|
||||
expect(helpNow(view(state, null), null, users)).toContain('몰래 고르는 중');
|
||||
|
||||
const v = view(state, 'A');
|
||||
@@ -81,7 +95,7 @@ test('섯다: 모두 다이 → 판 결과와 [다음 판으로], 다이한 사
|
||||
expect(t).toContain('[다음 판으로]');
|
||||
});
|
||||
|
||||
test('섯다: 칩 다시 받기 / 구사 재경기 참가 / 재경기 표시', () => {
|
||||
test('섯다: 시작 금액 다시 받기 / 구사 재경기 참가 / 재경기 표시', () => {
|
||||
const { state } = setupGame('seotda', 3);
|
||||
const rebuy = structuredClone(state);
|
||||
rebuy.phase = 'rebuy';
|
||||
@@ -90,15 +104,16 @@ test('섯다: 칩 다시 받기 / 구사 재경기 참가 / 재경기 표시', (
|
||||
rebuy.seats.find((s: any) => s.id === 'B').status = 'busted';
|
||||
rebuy.seats.find((s: any) => s.id === 'B').stack = 0;
|
||||
const b = helpNow(view(rebuy, 'B'), 'B', users);
|
||||
expect(b).toContain('[칩 다시 받기]');
|
||||
expect(b).toContain('[다시 받기]');
|
||||
expect(b).toContain('100만원');
|
||||
expect(b).toContain('[그만하기]');
|
||||
expect(helpNow(view(rebuy, 'A'), 'A', users)).toContain('고양이님이 칩을 다시 받을지');
|
||||
expect(helpNow(view(rebuy, 'A'), 'A', users)).toContain('고양이님이 시작 금액을 다시 받을지');
|
||||
|
||||
const rejoin = structuredClone(state);
|
||||
rejoin.hand.phase = 'rejoin';
|
||||
rejoin.hand.rejoinPending = ['C'];
|
||||
rejoin.hand.rejoinCost = 50;
|
||||
expect(helpNow(view(rejoin, 'C'), 'C', users)).toContain('[50 칩 내고 참가]');
|
||||
rejoin.hand.rejoinCost = 15_000;
|
||||
expect(helpNow(view(rejoin, 'C'), 'C', users)).toContain('[1만 5,000원 내고 참가]');
|
||||
expect(helpNow(view(rejoin, 'A'), 'A', users)).toContain('다시 들어올지');
|
||||
|
||||
const re = structuredClone(state);
|
||||
@@ -112,6 +127,6 @@ test('섯다: 게임 끝', () => {
|
||||
const end = structuredClone(state);
|
||||
end.phase = 'finished';
|
||||
end.hand = null;
|
||||
end.final = { ranking: [['A'], ['B']], scores: { A: 10, B: -10 }, summary: '20판 끝. 1위 +10칩' };
|
||||
end.final = { ranking: [['A'], ['B']], scores: { A: 10_000, B: -10_000 }, summary: '20판 끝. 1위 +1만원' };
|
||||
expect(helpNow(view(end, 'A'), 'A', users)).toContain('게임이 끝났어요. 20판 끝');
|
||||
});
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
/** 섯다 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view (never other players' cards). */
|
||||
import type { BetType, SeotdaSeatView, SeotdaView } from '@bg/games/seotda';
|
||||
import { formatWon } from '@bg/games/seotda/money';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
/** Same order and labels as the bet buttons in index.tsx. */
|
||||
const BET_ORDER: BetType[] = ['die', 'check', 'ping', 'call', 'ddadang', 'quarter', 'half', 'full'];
|
||||
/** Same order, labels and number keys as the bet buttons in board.tsx (한게임 섯다 배치). */
|
||||
const BET_ORDER: BetType[] = ['call', 'die', 'half', 'ping', 'check', 'ddadang', 'quarter', 'full'];
|
||||
const BET_KEY: Record<BetType, string> = { call: '7', die: '8', ping: '4', check: '5', ddadang: '1', half: '0', quarter: '2', full: '9' };
|
||||
const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
|
||||
const RAISES: BetType[] = ['ping', 'ddadang', 'quarter', 'half', 'full'];
|
||||
const STRENGTH_KO = { high: '센 패', mid: '중간 패', low: '약한 패' } as const;
|
||||
const REMATCH_KO = { gusa: '구사', mungGusa: '멍텅구리구사', tie: '같은 족보(동점)' } as const;
|
||||
const REASON_KO = { gusa: '구사', mungGusa: '멍텅구리구사', tie: '동점' } as const;
|
||||
|
||||
const chips = (n: number) => `${Math.max(0, Math.round(n)).toLocaleString('ko-KR')} 칩`;
|
||||
const won = (n: number) => formatWon(Math.max(0, n));
|
||||
|
||||
function who(players: Record<string, PublicUser>, id: string): string {
|
||||
return `${players[id]?.nickname ?? '다른 사람'}님`;
|
||||
@@ -32,27 +34,27 @@ function roundText(v: SeotdaView): string {
|
||||
/** My current hand as the view gives it (hints option on). */
|
||||
function handLine(v: SeotdaView, seat: SeotdaSeatView): string {
|
||||
const h = v.myHand;
|
||||
if (!h) return seat.cards.length > 0 ? "이 방은 족보 이름을 따로 보여 주지 않아요. '족보표'를 보고 내 패를 맞춰 보세요." : '';
|
||||
if (!h) return seat.cards.length > 0 ? "이 방은 족보 이름을 따로 보여 주지 않아요. '족보 도우미'를 보고 내 패를 맞춰 보세요." : '';
|
||||
if (h.special) return h.hint;
|
||||
if (h.value === null) return `지금은 ${h.name}만 받았어요. ${h.hint}`;
|
||||
return `지금 내 족보: ${h.name}${h.strength ? `(${STRENGTH_KO[h.strength]})` : ''}. 족보표에 '내 패'로 표시돼요.`;
|
||||
return `지금 내 족보: ${h.name}${h.strength ? `(${STRENGTH_KO[h.strength]})` : ''}. 족보 도우미에 '내 패'로 표시돼요.`;
|
||||
}
|
||||
|
||||
function rematchLine(v: SeotdaView): string {
|
||||
if (v.rematchNo === 0 || !v.rematchReason) return '';
|
||||
return `재경기 ${v.rematchNo}회차(${REMATCH_KO[v.rematchReason]})예요. 모인 칩은 그대로 두고, 학교(기본 칩)는 다시 내지 않아요.`;
|
||||
return `재경기 ${v.rematchNo}회차(${REMATCH_KO[v.rematchReason]})예요. 판돈은 그대로 두고, 기본금은 다시 내지 않아요.`;
|
||||
}
|
||||
|
||||
function resultLine(v: SeotdaView, players: Record<string, PublicUser>): string {
|
||||
if (v.foldWin) return `모두 다이해서 ${who(players, v.foldWin.winner)}이 ${chips(v.foldWin.amount)}을 가져갔어요. 이때는 패를 공개하지 않아요.`;
|
||||
if (v.foldWin) return `모두 다이해서 ${who(players, v.foldWin.winner)}이 판돈 ${won(v.foldWin.amount)}을 가져갔어요. 이때는 패를 공개하지 않아요.`;
|
||||
if (!v.showdown) return '이번 판이 끝났어요.';
|
||||
return v.showdown.pots
|
||||
.map((p) => {
|
||||
const names = p.winners.map((id) => players[id]?.nickname ?? '다른 사람').join('·') + '님';
|
||||
const name = v.showdown!.hands.find((h) => h.id === p.winners[0])?.name ?? '';
|
||||
if (p.type === 'rematch') return `${REASON_KO[p.reason as keyof typeof REASON_KO] ?? '동점'} 재경기: ${names}이 다시 겨뤄요. 모인 칩은 그대로 남아요.`;
|
||||
if (p.type === 'split') return `${names}이 ${chips(p.amount)}을 나눠 가졌어요.`;
|
||||
return `${names}이 ${name ? `${name}(으)로 ` : ''}${chips(p.amount)}을 가져갔어요.`;
|
||||
if (p.type === 'rematch') return `${REASON_KO[p.reason as keyof typeof REASON_KO] ?? '동점'} 재경기: ${names}이 다시 겨뤄요. 판돈은 그대로 남아요.`;
|
||||
if (p.type === 'split') return `${names}이 ${won(p.amount)}을 나눠 가졌어요.`;
|
||||
return `${names}이 ${name ? `${name}(으)로 ` : ''}${won(p.amount)}을 가져갔어요.`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
@@ -73,10 +75,10 @@ function waitingLine(v: SeotdaView, players: Record<string, PublicUser>): string
|
||||
function watching(v: SeotdaView, players: Record<string, PublicUser>, prefix = ''): string {
|
||||
if (v.phase === 'rebuy') {
|
||||
const ids = v.rebuy?.pending ?? [];
|
||||
const names = ids.length ? ids.map((id) => players[id]?.nickname ?? '다른 사람').join('·') + '님이' : '칩을 모두 잃은 사람이';
|
||||
return `${prefix}${names} 칩을 다시 받을지 고르는 중이에요.`;
|
||||
const names = ids.length ? ids.map((id) => players[id]?.nickname ?? '다른 사람').join('·') + '님이' : '원을 모두 잃은 사람이';
|
||||
return `${prefix}${names} 시작 금액을 다시 받을지 고르는 중이에요.`;
|
||||
}
|
||||
return [prefix + waitingLine(v, players), v.handPhase === 'betting' ? `모인 칩은 ${chips(v.pot)}이에요.` : '', rematchLine(v)].filter(Boolean).join('\n');
|
||||
return [prefix + waitingLine(v, players), v.handPhase === 'betting' ? `판돈은 ${won(v.pot)}이에요.` : '', rematchLine(v)].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
function myBetting(v: SeotdaView, seat: SeotdaSeatView): string {
|
||||
@@ -85,13 +87,14 @@ function myBetting(v: SeotdaView, seat: SeotdaSeatView): string {
|
||||
const lines = [`내 차례예요. ${roundText(v)}`];
|
||||
const hand = handLine(v, seat);
|
||||
if (hand) lines.push(hand);
|
||||
lines.push(`누를 수 있는 버튼: ${buttons.map((t) => `[${BET_KO[t]}]`).join(' ')}. 버튼 아래 적힌 만큼 칩이 바로 나가요.`);
|
||||
lines.push(`누를 수 있는 버튼: ${buttons.map((t) => `[${BET_KO[t]}]`).join(' ')}. 버튼 아래 적힌 금액이 바로 판돈에 들어가요. PC에서는 버튼 왼쪽 위 숫자 키(${buttons.map((t) => `${BET_KO[t]} ${BET_KEY[t]}`).join(', ')})로도 걸 수 있어요.`);
|
||||
const tips: string[] = [];
|
||||
if (v.forcedHalf) tips.push(`이 방은 베팅 규칙 ${v.options.betRule}이라 첫 베팅에서 앞쪽 사람은 [하프]나 [다이]만 할 수 있어요.`);
|
||||
const call = legal.get('call');
|
||||
if (call) tips.push(`앞사람이 칩을 걸었어요. [콜]은 그만큼(${chips(call.amount)}) 맞추는 거예요.`);
|
||||
else if (legal.has('ping')) tips.push(`[체크]는 칩을 걸지 않고 넘기고, [삥]은 학교(기본 칩)만큼 ${chips(v.baseUnit)}을 걸어요.`);
|
||||
if (call) tips.push(`앞사람이 걸었어요. [콜]은 그만큼(${won(call.amount)}) 맞추는 거예요.`);
|
||||
else if (legal.has('ping')) tips.push(`[체크]는 걸지 않고 넘기고, [삥]은 기본금만큼 ${won(v.baseUnit)}을 걸어요.`);
|
||||
if (!buttons.some((t) => RAISES.includes(t)) && seat.lastAction) tips.push('이번 라운드에 이미 한 번 해서 더 올릴 수는 없어요(올리기는 한 라운드에 한 번).');
|
||||
if (v.legal.some((l) => l.allIn)) tips.push('칩이 모자라면 가진 칩을 다 내는 올인이 돼요.');
|
||||
if (v.legal.some((l) => l.allIn)) tips.push('가진 금액이 모자라면 가진 만큼 다 내는 올인이 돼요.');
|
||||
tips.push('패가 약하면 [다이]로 이번 판을 포기할 수 있어요.');
|
||||
lines.push(tips.join(' '));
|
||||
return lines.join('\n');
|
||||
@@ -108,7 +111,7 @@ export function helpNow(v: SeotdaView, me: string | null, players: Record<string
|
||||
if (!v.rebuy?.mine) return watching(v, players) + ' 잠시 기다려 주세요.';
|
||||
const left = v.rebuy.left !== null ? `(남은 횟수 ${v.rebuy.left}번)` : '';
|
||||
return [
|
||||
`칩을 모두 잃었어요. [칩 다시 받기]를 누르면 놀이용 칩 ${chips(v.options.startingChips)}을 다시 받고 계속해요${left}.`,
|
||||
`가진 원을 모두 잃었어요. [다시 받기]를 누르면 놀이용 시작 금액 ${won(v.options.startingChips)}을 다시 받고 계속해요${left}.`,
|
||||
'[그만하기]를 누르면 탈락하고 구경만 해요. 다시 받은 만큼 최종 점수에서 빠져요.',
|
||||
'시간 안에 고르지 않으면 그만하는 것으로 처리돼요.',
|
||||
].join('\n');
|
||||
@@ -122,27 +125,27 @@ export function helpNow(v: SeotdaView, me: string | null, players: Record<string
|
||||
if (seat.folded) return `이번 판은 다이했어요. 다음 판을 기다려 주세요. 내 패는 나만 볼 수 있어요.\n${waitingLine(v, players)}`;
|
||||
if (v.toAct === me) return [re, myBetting(v, seat)].filter(Boolean).join('\n');
|
||||
const hand = handLine(v, seat);
|
||||
if (seat.allIn) return ['올인했어요(가진 칩을 다 걸었어요). 더 걸지 않고 결과를 기다리면 돼요.', hand, re].filter(Boolean).join('\n');
|
||||
if (seat.allIn) return ['올인했어요(가진 금액을 다 걸었어요). 더 걸지 않고 결과를 기다리면 돼요.', hand, re].filter(Boolean).join('\n');
|
||||
return [`${waitingLine(v, players)} 내 차례가 올 때까지 기다려 주세요.`, hand, re].filter(Boolean).join('\n');
|
||||
}
|
||||
case 'choose': {
|
||||
if (seat.chosen === null) return seat.folded ? '이번 판은 다이했어요. 다음 판을 기다려 주세요.' : [notIn, watching(v, players)].join('\n');
|
||||
if (seat.chosen) {
|
||||
const name = v.myHand ? `(${v.myHand.name})` : '';
|
||||
return `쓸 카드 2장을 골랐어요${name}. 다른 사람이 다 고를 때까지 기다려 주세요. 다 고르면 마지막 베팅을 해요.`;
|
||||
return `쓸 패 2장을 골랐어요${name}. 다른 사람이 다 고를 때까지 기다려 주세요. 다 고르면 마지막 베팅을 해요.`;
|
||||
}
|
||||
const lines = ["3장 중 쓸 카드 2장을 눌러 고르면 아래 버튼이 '○○(으)로 정하기'로 바뀌어요. 그 버튼을 눌러 정해 주세요. 남는 1장은 아무에게도 보이지 않아요."];
|
||||
const lines = ["3장 중 쓸 패 2장을 눌러 고르면 아래 버튼이 '○○(으)로 정하기'로 바뀌어요. 그 버튼을 눌러 정해 주세요. 남는 1장은 아무에게도 보이지 않아요."];
|
||||
const best = v.options.hints ? v.myCombos?.find((c) => c.best) : undefined;
|
||||
if (best) lines.push(`[추천 조합]을 누르면 가장 센 조합(${best.name})이 골라져요.`);
|
||||
if (best) lines.push(`조합 버튼을 누르면 그 2장이 골라져요. [${best.name} (추천)]이 가장 센 조합이에요.`);
|
||||
lines.push('모두 동시에 몰래 고르고, 시간이 지나면 가장 센 조합으로 저절로 골라져요.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
case 'rejoin': {
|
||||
if (!v.rejoin?.mine) return `${waitingLine(v, players)} 잠시 기다려 주세요.`;
|
||||
const cost = chips(v.rejoin.cost);
|
||||
const cost = won(v.rejoin.cost);
|
||||
return [
|
||||
`구사 재경기가 열려요. 다이했던 나도 모인 칩에 ${cost}을 더 내면 다시 들어갈 수 있어요.`,
|
||||
v.rejoin.canAfford ? `[${cost} 내고 참가] 또는 [참가 안 함]을 눌러 주세요.` : '칩이 모자라서 참가할 수 없어요. [참가 안 함]을 눌러 주세요.',
|
||||
`구사 재경기가 열려요. 다이했던 나도 판돈에 ${cost}을 더 내면 다시 들어갈 수 있어요.`,
|
||||
v.rejoin.canAfford ? `[${cost} 내고 참가] 또는 [참가 안 함]을 눌러 주세요.` : '보유 금액이 모자라서 참가할 수 없어요. [참가 안 함]을 눌러 주세요.',
|
||||
'시간이 지나면 참가하지 않는 것으로 처리돼요.',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
@@ -1,57 +1,20 @@
|
||||
/** 섯다 화면 (docs/games/seotda.md §9). Chips are room-only play points. */
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type {
|
||||
BetType,
|
||||
CardSlot,
|
||||
PotOutcome,
|
||||
SeotdaCardView,
|
||||
SeotdaOptions,
|
||||
SeotdaSeatView,
|
||||
SeotdaView,
|
||||
SpecialKind,
|
||||
} from '@bg/games/seotda';
|
||||
/**
|
||||
* 섯다 (docs/games/seotda.md §9): 한게임 섯다처럼 원과 판돈으로. 판 화면은 board.tsx, 여기는 옆 패널·설정·규칙.
|
||||
* 원은 이 방 안에서만 쓰는 놀이용 숫자다(§12): 진짜 돈과 바꿀 수 없고 방이 끝나면 사라진다.
|
||||
*/
|
||||
import { useState } from 'react';
|
||||
import type { SeotdaOptions, SeotdaView, SpecialKind } from '@bg/games/seotda';
|
||||
import { formatWon, formatWonDelta, formatWonShort } from '@bg/games/seotda/money';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
||||
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { HWATU_CREDIT, HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { BET_KO, SeotdaBoard, nick, resultLine, totalMsOf, userOf } from './board';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const BET_ORDER: BetType[] = ['die', 'check', 'ping', 'call', 'ddadang', 'quarter', 'half', 'full'];
|
||||
const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
|
||||
const BET_HELP: Record<BetType, string> = {
|
||||
check: '칩을 걸지 않고 넘겨요',
|
||||
ping: '기본 칩만큼 걸어요',
|
||||
call: '앞사람만큼 맞춰요',
|
||||
ddadang: '앞사람이 건 만큼의 두 배',
|
||||
quarter: '모인 칩의 4분의 1만큼 더',
|
||||
half: '모인 칩의 절반만큼 더',
|
||||
full: '모인 칩만큼 더',
|
||||
die: '이번 판을 포기해요',
|
||||
};
|
||||
const STRENGTH_COLOR = { high: 'var(--success)', mid: 'var(--warning)', low: 'var(--text-sub)' } as const;
|
||||
const STRENGTH_KO = { high: '센 패', mid: '중간 패', low: '약한 패' } as const;
|
||||
const REMATCH_KO = { gusa: '구사', mungGusa: '멍텅구리구사', tie: '동점' } as const;
|
||||
const REASON_KO: Record<PotOutcome['reason'], string> = {
|
||||
normal: '',
|
||||
ttaengjabi: '땡잡이',
|
||||
amhaeng: '암행어사',
|
||||
gusa: '구사 재경기',
|
||||
mungGusa: '멍텅구리구사 재경기',
|
||||
tie: '동점',
|
||||
limit: '재경기 횟수 초과로 나눔',
|
||||
fold: '모두 다이',
|
||||
};
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser =>
|
||||
players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const isCard = (c: CardSlot): c is SeotdaCardView => !('hidden' in c);
|
||||
|
||||
/** Illustration card for the rules / 족보표 (no rule code needed on the client). */
|
||||
/** Illustration card for the 족보표 (no rule code needed on the client). */
|
||||
function illus(month: number, special: boolean): HwatuInfo {
|
||||
const gwang = [1, 3, 8].includes(month);
|
||||
const kind: HwatuInfo['kind'] = special ? (gwang ? 'gwang' : 'yeol') : month === 8 ? 'pi' : 'tti';
|
||||
@@ -64,388 +27,17 @@ function illus(month: number, special: boolean): HwatuInfo {
|
||||
};
|
||||
}
|
||||
|
||||
function totalMsOf(v: SeotdaView): number {
|
||||
const o = v.options;
|
||||
if (v.phase === 'rebuy' || v.handPhase === 'rejoin') return o.decisionSeconds * 1000;
|
||||
if (v.handPhase === 'choose') return (o.turnSeconds + 10) * 1000;
|
||||
if (v.handPhase === 'handEnd') return 4000;
|
||||
const turn = v.seats.find((s) => s.id === v.toAct);
|
||||
return turn?.away ? 5000 : o.turnSeconds * 1000;
|
||||
}
|
||||
const PLAY_MONEY_NOTICE = '여기 나오는 원과 판돈은 이 방 안에서만 쓰는 놀이용 숫자예요. 진짜 돈과는 아무 상관이 없고, 바꾸거나 주고받을 수 없으며 방이 끝나면 사라져요.';
|
||||
|
||||
function specialFlash(v: SeotdaView): string | null {
|
||||
const pots = v.showdown?.pots ?? [];
|
||||
if (pots.some((p) => p.reason === 'ttaengjabi')) return '땡잡이!';
|
||||
if (pots.some((p) => p.reason === 'amhaeng')) return '암행어사 출두!';
|
||||
if (pots.some((p) => p.type === 'rematch' && p.reason === 'gusa')) return '구사 재경기';
|
||||
if (pots.some((p) => p.type === 'rematch' && p.reason === 'mungGusa')) return '멍텅구리구사 재경기';
|
||||
if (pots.some((p) => p.type === 'rematch')) return '동점 재경기';
|
||||
return null;
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.sd-table { position: relative; width: 100%; aspect-ratio: 16 / 11; border-radius: 180px; border: 10px solid var(--wood);
|
||||
background: radial-gradient(ellipse at center, rgba(255,255,255,0.12) 0%, rgba(255,255,255,0) 60%), var(--felt); box-shadow: var(--shadow); }
|
||||
.sd-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -50%); width: var(--seat-w, 168px); z-index: 1;
|
||||
background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.25);
|
||||
border: 3px solid transparent; display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; transition: border-color .2s; }
|
||||
.sd-seat.turn { border-color: var(--focus); }
|
||||
.sd-seat.me { border-color: var(--primary); }
|
||||
.sd-seat.me.turn { border-color: var(--focus); }
|
||||
.sd-seat.out { opacity: 0.6; }
|
||||
.sd-center { position: absolute; left: 50%; top: 47%; transform: translate(-50%, -50%); text-align: center; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,.5); max-width: 46%; }
|
||||
.sd-flash { position: absolute; left: 50%; top: 30%; transform: translate(-50%, -50%); z-index: 3; font-size: 2.6rem; font-weight: 900; color: #fde047;
|
||||
text-shadow: 0 3px 8px rgba(0,0,0,.6); animation: sd-pop .35s ease-out; pointer-events: none; white-space: nowrap; }
|
||||
@keyframes sd-pop { from { transform: translate(-50%, -50%) scale(.5); opacity: 0 } to { transform: translate(-50%, -50%) scale(1); opacity: 1 } }
|
||||
.sd-actions { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
|
||||
.sd-actions .btn { min-height: 64px; flex-direction: column; gap: 0; padding: 0 8px; line-height: 1.15; }
|
||||
.sd-actions .btn small { font-weight: 600; font-size: .85rem; opacity: .9; }
|
||||
.sd-mine { display: flex; gap: 14px; align-items: flex-end; flex-wrap: wrap; justify-content: center; }
|
||||
.sd-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .78rem; }
|
||||
@media (max-width: 719px) {
|
||||
.sd-table { aspect-ratio: auto; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 10px; border-radius: 20px; border-width: 6px; }
|
||||
.sd-seat { position: static; transform: none; width: auto; }
|
||||
.sd-center { position: static; transform: none; grid-column: 1 / -1; order: -1; max-width: none; padding: 8px 0; }
|
||||
.sd-flash { position: fixed; top: 40%; }
|
||||
.sd-actions { grid-template-columns: repeat(2, 1fr); }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function SeatBox({ seat, view: v, players, me, deadline, x, y }: { seat: SeotdaSeatView; view: SeotdaView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: number }) {
|
||||
const u = userOf(players, seat.id);
|
||||
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
|
||||
const badges: [string, string][] = [];
|
||||
if (seat.left) badges.push(['나감', 'var(--danger)']);
|
||||
else if (seat.away) badges.push(['자리 비움', 'var(--warning)']);
|
||||
if (seat.status === 'eliminated') badges.push(['탈락', 'var(--text-sub)']);
|
||||
if (seat.status === 'busted') badges.push(['리바이 대기', 'var(--warning)']);
|
||||
if (seat.folded) badges.push(['다이', 'var(--danger)']);
|
||||
if (seat.allIn) badges.push(['올인', 'var(--primary)']);
|
||||
if (seat.chosen === true) badges.push(['고름', 'var(--success)']);
|
||||
if (seat.chosen === false) badges.push(['고르는 중', 'var(--text-sub)']);
|
||||
const timed = seat.isTurn || seat.chosen === false;
|
||||
return (
|
||||
<div
|
||||
className={`sd-seat${seat.isTurn ? ' turn' : ''}${seat.id === me ? ' me' : ''}${out ? ' out' : ''}`}
|
||||
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
|
||||
aria-label={`${u.nickname} ${formatChips(seat.stack)}${seat.isDealer ? ', 선' : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
||||
>
|
||||
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={22} />
|
||||
<strong style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{u.nickname}
|
||||
{seat.id === me && <span className="muted"> (나)</span>}
|
||||
</strong>
|
||||
{seat.isDealer && (
|
||||
<span className="sd-badge" style={{ background: '#facc15', color: '#422006' }} title="선(먼저 하는 사람)">
|
||||
선
|
||||
</span>
|
||||
)}
|
||||
{timed && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine={seat.id === me} size={28} />}
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap', alignItems: 'flex-start' }}>
|
||||
<div className="stack" style={{ gap: 2, flex: 1, minWidth: 0 }}>
|
||||
<Chips n={seat.stack} strong />
|
||||
{((seat.lastAction && !seat.folded) || seat.roundBet > 0) && (
|
||||
<span className="small" style={{ whiteSpace: 'nowrap' }} title="마지막 행동 · 이번 라운드에 건 칩">
|
||||
{seat.lastAction && !seat.folded && <span className="muted">{BET_KO[seat.lastAction.type]} </span>}
|
||||
{seat.roundBet > 0 && `+${seat.roundBet.toLocaleString('ko-KR')}`}
|
||||
</span>
|
||||
)}
|
||||
<div className="row" style={{ gap: 3 }}>
|
||||
{badges.map(([t, c]) => (
|
||||
<span key={t} className="sd-badge" style={{ background: c, color: '#fff' }}>
|
||||
{t}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{seat.cards.length > 0 && (
|
||||
<div style={{ display: 'flex', flex: 'none' }}>
|
||||
{seat.cards.map((c, i) => (
|
||||
<HwatuCard key={isCard(c) ? c.key : `h${i}`} card={isCard(c) ? c : null} size="sm" style={i > 0 ? { marginLeft: -14 } : undefined} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{seat.handName && <strong style={{ color: 'var(--primary)', textAlign: 'center' }}>{seat.handName}</strong>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CenterInfo({ view: v, players }: { view: SeotdaView; players: Record<string, PublicUser> }) {
|
||||
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
|
||||
// On the result screen the paid-out pots are no longer in v.pot (only a carried rematch pot is).
|
||||
const paid = v.handPhase === 'handEnd' ? (v.foldWin?.amount ?? (v.showdown?.pots ?? []).filter((p) => p.type !== 'rematch').reduce((a, p) => a + p.amount, 0)) : 0;
|
||||
return (
|
||||
<div className="sd-center">
|
||||
{v.rematchNo > 0 && v.rematchReason && (
|
||||
<div className="sd-badge" style={{ background: '#fde047', color: '#422006', fontSize: '1rem', padding: '2px 12px', marginBottom: 6 }}>
|
||||
재경기 {v.rematchNo}회차 · {REMATCH_KO[v.rematchReason]}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
|
||||
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite">
|
||||
{formatChips(v.pot + paid)}
|
||||
</div>
|
||||
{v.pots.length > 1 && (
|
||||
<div className="small" style={{ opacity: 0.9 }}>
|
||||
{v.pots.map((p, i) => (
|
||||
<div key={i}>
|
||||
{i === v.pots.length - 1 ? '메인' : `사이드 ${i + 1}`}: {formatChips(p.amount)} ({p.eligible.map((id) => nick(players, id)).join('·')})
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="small" style={{ opacity: 0.85, marginTop: 4 }}>
|
||||
{v.phase === 'finished' ? '게임 끝' : `${Math.max(1, v.handNo)}${limit}판`} · 학교 {formatChips(v.baseUnit)}
|
||||
{v.currentBet > 0 && v.handPhase === 'betting' ? ` · 이번 라운드 ${formatChips(v.currentBet)}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeotdaBoard({ view: v, me, players, act, pending, deadline }: BoardProps<SeotdaView>) {
|
||||
const n = v.seats.length;
|
||||
const myIdx = Math.max(0, v.seats.findIndex((s) => s.id === me));
|
||||
const [flash, setFlash] = useState<string | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevToAct = useRef(v.toAct);
|
||||
const showKey = `${v.handNo}-${v.rematchNo}-${v.handPhase}`;
|
||||
|
||||
useEffect(() => {
|
||||
const f = v.handPhase === 'handEnd' ? specialFlash(v) : null;
|
||||
if (f) {
|
||||
setFlash(f);
|
||||
const t = setTimeout(() => setFlash(null), 1400);
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
return undefined;
|
||||
}, [showKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (v.toAct && v.toAct !== prevToAct.current) {
|
||||
if (v.toAct === me) {
|
||||
haptic(40);
|
||||
sounds.myTurn();
|
||||
setAnnounce('내 차례예요.');
|
||||
} else setAnnounce(`${nick(players, v.toAct)}님 차례예요.`);
|
||||
}
|
||||
prevToAct.current = v.toAct;
|
||||
}, [v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (v.handPhase !== 'handEnd') return;
|
||||
if (v.foldWin) setAnnounce(`${nick(players, v.foldWin.winner)}님이 ${formatChips(v.foldWin.amount)}을 가져갔어요.`);
|
||||
else if (v.showdown) setAnnounce(resultLine(v, players));
|
||||
const won = v.foldWin?.winner === me || v.showdown?.pots.some((p) => p.type !== 'rematch' && p.winners.includes(me ?? ''));
|
||||
if (me && won) sounds.win();
|
||||
}, [showKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 12 }}>
|
||||
<style>{CSS}</style>
|
||||
<div className="sd-table" role="region" aria-label="섯다 테이블" style={{ '--seat-w': v.options.cardMode === 'three' ? '196px' : n > 6 ? '150px' : '172px' } as React.CSSProperties}>
|
||||
{v.seats.map((s, i) => {
|
||||
const rel = (i - myIdx + n) % n;
|
||||
const ang = Math.PI / 2 + (rel * 2 * Math.PI) / n;
|
||||
return <SeatBox key={s.id} seat={s} view={v} players={players} me={me} deadline={deadline} x={50 + 40 * Math.cos(ang)} y={50 + 38 * Math.sin(ang)} />;
|
||||
})}
|
||||
<CenterInfo view={v} players={players} />
|
||||
{flash && <div className="sd-flash">{flash}</div>}
|
||||
</div>
|
||||
<MyArea view={v} me={me} players={players} act={act} pending={pending} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function resultLine(v: SeotdaView, players: Record<string, PublicUser>): string {
|
||||
if (v.foldWin) return `${nick(players, v.foldWin.winner)}님이 ${formatChips(v.foldWin.amount)}을 가져갔어요(모두 다이).`;
|
||||
if (!v.showdown) return '';
|
||||
return v.showdown.pots
|
||||
.map((p) => {
|
||||
const who = p.winners.map((id) => nick(players, id)).join('·');
|
||||
const name = v.showdown!.hands.find((h) => h.id === p.winners[0])?.name ?? '';
|
||||
if (p.type === 'rematch') return `${REASON_KO[p.reason]}: ${who}님이 다시 겨뤄요(${formatChips(p.amount)})`;
|
||||
if (p.type === 'split') return `${who}님이 ${formatChips(p.amount)}을 나눠 가졌어요${p.reason === 'limit' ? '(재경기 횟수 초과)' : ''}`;
|
||||
return `${who}님이 ${name}${p.reason === 'normal' ? '' : ' 발동'}(으)로 ${formatChips(p.amount)}을 가져갔어요`;
|
||||
})
|
||||
.join(' / ');
|
||||
}
|
||||
|
||||
/** My cards, hand name, 3장 choice and the action buttons. */
|
||||
function MyArea({ view: v, me, players, act, pending }: { view: SeotdaView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
const [pick, setPick] = useState<number[]>([]);
|
||||
const [hover, setHover] = useState<BetType | null>(null);
|
||||
useEffect(() => setPick([]), [v.handNo, v.rematchNo, v.handPhase]);
|
||||
if (!me || !seat) return v.handPhase === 'handEnd' ? <ResultPanel view={v} players={players} /> : null;
|
||||
const myCards = seat.cards.filter(isCard);
|
||||
const choosing = v.handPhase === 'choose' && seat.chosen === false;
|
||||
const preview = choosing && pick.length === 2 ? v.myCombos?.find((c) => c.cardIds.includes(pick[0]!) && c.cardIds.includes(pick[1]!)) : null;
|
||||
const myTurn = v.toAct === me && v.handPhase === 'betting';
|
||||
const legal = new Map(v.legal.map((l) => [l.type, l]));
|
||||
const hoverBet = hover ? legal.get(hover) : undefined;
|
||||
const toggle = (id: number) => setPick((p) => (p.includes(id) ? p.filter((x) => x !== id) : p.length >= 2 ? [p[1]!, id] : [...p, id]));
|
||||
const showHand = myCards.length > 0 && seat.inHand;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 10 }}>
|
||||
{showHand && (
|
||||
<div className="card stack" style={{ gap: 10, padding: 12 }}>
|
||||
<div className="sd-mine">
|
||||
{myCards.map((c) => {
|
||||
const chosen = v.myChosen?.includes(c.id);
|
||||
return (
|
||||
<HwatuCard
|
||||
key={c.key}
|
||||
card={c}
|
||||
size="lg"
|
||||
selected={choosing && pick.includes(c.id)}
|
||||
highlight={!!chosen}
|
||||
dimmed={!!v.myChosen && !chosen}
|
||||
onClick={choosing ? () => toggle(c.id) : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{v.myHand && (
|
||||
<div className="stack" style={{ gap: 2, minWidth: 160, maxWidth: 320 }}>
|
||||
<span style={{ fontSize: '1.5rem', fontWeight: 900, color: v.myHand.strength ? STRENGTH_COLOR[v.myHand.strength] : undefined }}>
|
||||
지금: {v.myHand.name}
|
||||
{v.myHand.strength && <span className="small" style={{ marginLeft: 6 }}>({STRENGTH_KO[v.myHand.strength]})</span>}
|
||||
</span>
|
||||
<span className="small muted">{v.myHand.hint}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{seat.folded && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>이번 판은 다이했어요. 내 패는 나만 볼 수 있어요.</p>}
|
||||
{choosing && (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
<p style={{ margin: 0, textAlign: 'center' }}>
|
||||
<strong>쓸 카드 2장을 골라 주세요.</strong> 남는 1장은 아무에게도 보이지 않아요.
|
||||
{preview && (
|
||||
<>
|
||||
{' '}
|
||||
고른 조합: <strong>{preview.name}</strong>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="row" style={{ justifyContent: 'center' }}>
|
||||
{v.options.hints && v.myCombos && (
|
||||
<button type="button" className="btn btn-secondary" onClick={() => setPick([...v.myCombos!.find((c) => c.best)!.cardIds])}>
|
||||
추천 조합
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={pick.length !== 2 || pending}
|
||||
onClick={() => act({ type: 'choose', cardIds: [pick[0], pick[1]] })}
|
||||
>
|
||||
{preview ? `${preview.name}(으)로 정하기` : '두 장을 고르세요'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{v.handPhase === 'choose' && seat.chosen === true && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>골랐어요. 다른 사람을 기다리는 중이에요.</p>}
|
||||
</div>
|
||||
)}
|
||||
{seat.inHand && v.handPhase === 'betting' && !seat.folded && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<div className="sd-actions" role="group" aria-label="베팅">
|
||||
{BET_ORDER.filter((t) => t !== 'full' || v.options.maxRaise === 'full').map((t) => {
|
||||
const l = legal.get(t);
|
||||
const enabled = myTurn && !!l && !pending;
|
||||
const cls = t === 'die' ? 'btn-danger' : t === 'check' || t === 'call' ? 'btn-primary' : 'btn-soft';
|
||||
return (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className={`btn ${cls}`}
|
||||
disabled={!enabled}
|
||||
title={BET_HELP[t]}
|
||||
onMouseEnter={() => setHover(t)}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
onFocus={() => setHover(t)}
|
||||
onBlur={() => setHover(null)}
|
||||
onClick={() => act({ type: t })}
|
||||
>
|
||||
<span>{BET_KO[t]}</span>
|
||||
<small>{l && l.amount > 0 ? `${formatChips(l.amount)}${l.allIn ? ' 올인' : ''}` : t === 'die' ? '포기' : l ? '0 칩' : '-'}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="small muted" style={{ margin: 0, minHeight: '1.4em', textAlign: 'center' }}>
|
||||
{myTurn
|
||||
? hoverBet
|
||||
? `${BET_KO[hover!]}: ${BET_HELP[hover!]}. 내고 나면 내 칩 ${formatChips(seat.stack - hoverBet.amount)}, 모인 칩 ${formatChips(v.pot + hoverBet.amount)}`
|
||||
: '내 차례예요. 버튼에 적힌 칩이 바로 나가요.'
|
||||
: v.toAct
|
||||
? `${nick(players, v.toAct)}님 차례예요.`
|
||||
: ''}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{v.handPhase === 'handEnd' && <ResultPanel view={v} players={players} />}
|
||||
{v.handPhase === 'handEnd' && seat.status === 'playing' && !seat.left && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={seat.ready || pending} onClick={() => act({ type: 'ready' })}>
|
||||
{seat.ready ? '다른 사람을 기다리는 중…' : v.next === 'rematch' ? '재경기 시작' : '다음 판으로'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultPanel({ view: v, players }: { view: SeotdaView; players: Record<string, PublicUser> }) {
|
||||
return (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }} aria-live="polite">
|
||||
<strong>{v.next === 'rematch' ? '재경기가 결정됐어요' : '이번 판 결과'}</strong>
|
||||
{v.foldWin && (
|
||||
<span>
|
||||
{nick(players, v.foldWin.winner)}님이 {formatChips(v.foldWin.amount)}을 가져갔어요. 모두 다이해서 패는 공개하지 않아요.
|
||||
</span>
|
||||
)}
|
||||
{v.showdown?.pots.map((p, i) => {
|
||||
const who = p.winners.map((id) => nick(players, id)).join(' · ');
|
||||
const name = v.showdown!.hands.find((h) => h.id === p.winners[0])?.name;
|
||||
return (
|
||||
<span key={i}>
|
||||
{v.showdown!.pots.length > 1 ? `${i === v.showdown!.pots.length - 1 ? '메인' : '사이드'} ${formatChips(p.amount)}: ` : `${formatChips(p.amount)}: `}
|
||||
{p.type === 'win' && (
|
||||
<>
|
||||
<strong>{who}</strong> 승리 ({name}
|
||||
{p.reason === 'ttaengjabi' || p.reason === 'amhaeng' ? ' 발동' : ''})
|
||||
</>
|
||||
)}
|
||||
{p.type === 'split' && (
|
||||
<>
|
||||
<strong>{who}</strong> 나눠 가짐{p.reason === 'limit' ? ' (재경기 횟수 초과)' : ' (같은 족보)'}
|
||||
</>
|
||||
)}
|
||||
{p.type === 'rematch' && (
|
||||
<>
|
||||
<strong>{REASON_KO[p.reason]}</strong> — {who}님이 다시 겨뤄요. 칩은 그대로 남아요.
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
// ---------------------------------------------------------------- 족보 도우미
|
||||
|
||||
interface JokboRow {
|
||||
name: string;
|
||||
cards: [number, boolean][];
|
||||
note: string;
|
||||
match: (value: number | null, special: SpecialKind | null) => boolean;
|
||||
/** 특수 족보 (numbered "특" like the 한게임 족보 list). */
|
||||
special?: boolean;
|
||||
}
|
||||
|
||||
function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
@@ -458,7 +50,7 @@ function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
{ name: '13광땡', cards: [[1, true], [3, true]], note: '', match: v(980) } as JokboRow,
|
||||
]
|
||||
: []),
|
||||
{ name: '장땡(10땡)', cards: [[10, true], [10, false]], note: '같은 월 두 장 중 최고', match: v(910) },
|
||||
{ name: '장땡(10땡)', cards: [[10, true], [10, false]], note: '같은 달 두 장 중 최고', match: v(910) },
|
||||
{ name: '9땡 ~ 삥땡(1땡)', cards: [[9, true], [9, false]], note: '숫자가 클수록 셈', match: v(901, 909) },
|
||||
{ name: '알리', cards: [[1, true], [2, false]], note: '1 + 2', match: v(806) },
|
||||
{ name: '독사', cards: [[1, true], [4, false]], note: '1 + 4', match: v(805) },
|
||||
@@ -466,7 +58,7 @@ function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
{ name: '장삥', cards: [[1, true], [10, false]], note: '1 + 10', match: v(803) },
|
||||
{ name: '장사', cards: [[4, false], [10, false]], note: '4 + 10', match: v(802) },
|
||||
{ name: '세륙', cards: [[4, false], [6, false]], note: '4 + 6', match: v(801) },
|
||||
{ name: '갑오(9끗)', cards: [[2, false], [7, false]], note: '두 월을 더한 일의 자리 9', match: v(9) },
|
||||
{ name: '갑오(9끗)', cards: [[2, false], [7, false]], note: '두 달을 더한 일의 자리 9', match: v(9) },
|
||||
{ name: '8끗 ~ 1끗', cards: [[3, false], [5, false]], note: '일의 자리가 클수록 셈', match: v(1, 8) },
|
||||
{ name: '망통(0끗)', cards: [[2, false], [8, false]], note: '가장 약한 패', match: v(0) },
|
||||
];
|
||||
@@ -474,16 +66,17 @@ function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
if (o.ttaengjabi !== 'off')
|
||||
rows.push({
|
||||
name: '땡잡이',
|
||||
special: true,
|
||||
cards: [[3, true], [7, true]],
|
||||
note: `${o.ttaengjabi === 'strict' ? '3월 광 + 7월 열끗' : '3월 + 7월 아무 패'}. 상대 최고가 1~9땡이면 이김, 아니면 망통`,
|
||||
note: `${o.ttaengjabi === 'strict' ? '3월 광 + 7월 열끗' : '3월 + 7월'}. 상대 최고가 1~9땡이면 이김, 아니면 망통`,
|
||||
match: sp('ttaengjabi'),
|
||||
});
|
||||
if (o.amhaeng) rows.push({ name: '암행어사', cards: [[4, true], [7, true]], note: '4·7월 열끗. 13·18광땡을 잡음, 아니면 1끗', match: sp('amhaeng') });
|
||||
if (o.amhaeng) rows.push({ name: '암행어사', special: true, cards: [[4, true], [7, true]], note: '4·7월 열끗. 13·18광땡을 잡음, 아니면 1끗', match: sp('amhaeng') });
|
||||
if (o.gusa) {
|
||||
rows.push({ name: '구사', cards: [[4, false], [9, true]], note: '4 + 9. 상대가 알리 이하면 재경기, 아니면 3끗', match: sp('gusa') });
|
||||
rows.push({ name: '구사', special: true, cards: [[4, false], [9, true]], note: '4 + 9. 상대가 알리 이하면 재경기, 아니면 3끗', match: sp('gusa') });
|
||||
if (o.mungGusa !== 'off') {
|
||||
const upTo = o.mungGusa === 'upTo9' ? '9땡' : o.mungGusa === 'upToJang' ? '장땡' : '8땡';
|
||||
rows.push({ name: '멍텅구리구사', cards: [[4, true], [9, true]], note: `4·9월 열끗. 상대가 ${upTo} 이하면 재경기`, match: sp('mungGusa') });
|
||||
rows.push({ name: '멍텅구리구사', special: true, cards: [[4, true], [9, true]], note: `4·9월 열끗. 상대가 ${upTo} 이하면 재경기`, match: sp('mungGusa') });
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
@@ -492,20 +85,29 @@ function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
function JokboTable({ options, mine }: { options: SeotdaOptions; mine?: SeotdaView['myHand'] }) {
|
||||
const rows = jokboRows(options);
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.9rem' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem' }}>
|
||||
<tbody>
|
||||
{rows.map((r) => {
|
||||
{rows.map((r, i) => {
|
||||
const hit = !!mine && options.hints && r.match(mine.value, mine.special);
|
||||
return (
|
||||
<tr key={r.name} style={{ background: hit ? 'var(--warning-soft)' : undefined, borderBottom: '1px solid var(--border)' }} aria-current={hit ? 'true' : undefined}>
|
||||
<td style={{ padding: '4px 2px', whiteSpace: 'nowrap' }}>
|
||||
{r.cards.map(([m, sp], i) => (
|
||||
<HwatuCard key={i} card={illus(m, sp)} size="sm" style={{ marginRight: 2 }} />
|
||||
<tr
|
||||
key={r.name}
|
||||
style={{ background: hit ? 'color-mix(in srgb, #7c3aed 22%, transparent)' : undefined, borderBottom: '1px solid var(--border)' }}
|
||||
aria-current={hit ? 'true' : undefined}
|
||||
>
|
||||
<td style={{ padding: '3px 4px', fontWeight: 800, color: 'var(--text-sub)', width: 28, textAlign: 'right', whiteSpace: 'nowrap' }}>{r.special ? '특' : i + 1}</td>
|
||||
<td style={{ padding: '3px 2px', whiteSpace: 'nowrap' }}>
|
||||
{r.cards.map(([m, sp], j) => (
|
||||
<HwatuCard key={j} card={illus(m, sp)} width={30} showMonth={false} style={{ marginRight: 2 }} />
|
||||
))}
|
||||
</td>
|
||||
<td style={{ padding: '4px 6px' }}>
|
||||
<td style={{ padding: '3px 6px' }}>
|
||||
<strong>{r.name}</strong>
|
||||
{hit && <span className="sd-badge" style={{ background: 'var(--warning)', color: '#fff', marginLeft: 4 }}>내 패</span>}
|
||||
{hit && (
|
||||
<span className="sd-tag" style={{ background: '#7c3aed', color: '#fff', marginLeft: 4, borderRadius: 999, padding: '0 7px', fontSize: '.74rem', fontWeight: 800 }}>
|
||||
내 패
|
||||
</span>
|
||||
)}
|
||||
{r.note && <div className="small muted">{r.note}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -516,13 +118,17 @@ function JokboTable({ options, mine }: { options: SeotdaOptions; mine?: SeotdaVi
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side panel
|
||||
|
||||
function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps<SeotdaView>) {
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
const ranked = [...v.seats].sort((a, b) => b.stack - a.stack);
|
||||
const log = v.betLog;
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<PlayChipNotice />
|
||||
<p className="small" style={{ background: 'var(--surface-2)', borderRadius: 10, padding: '8px 12px', margin: 0 }}>
|
||||
{PLAY_MONEY_NOTICE}
|
||||
</p>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>
|
||||
@@ -532,9 +138,10 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine={isMyTurn(v, me)} size={36} />}
|
||||
</div>
|
||||
<span className="small muted">
|
||||
학교 {formatChips(v.baseUnit)} · {v.options.cardMode === 'three' ? '3장 섯다' : '2장 섯다'} · {v.options.maxRaise === 'full' ? '풀까지' : '하프까지'}
|
||||
기본금 {formatWon(v.baseUnit)} · {v.options.cardMode === 'three' ? '3장 섯다' : '2장 섯다'} · {v.options.deck}장 ·{' '}
|
||||
{v.options.betRule === 'free' ? '일반 베팅' : `베팅 규칙 ${v.options.betRule}`}
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }} aria-label="보유 금액 순위">
|
||||
{ranked.map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'eliminated' ? 0.55 : 1 }}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
@@ -544,7 +151,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{s.rebuys > 0 ? ` · 리바이 ${s.rebuys}` : ''}
|
||||
{s.status === 'eliminated' ? ' · 탈락' : s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
<Chips n={s.stack} />
|
||||
<span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 800, whiteSpace: 'nowrap' }}>{formatWon(s.stack)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@@ -555,16 +162,27 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{v.result.ranking.map((g, i) => (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')}
|
||||
{v.options.endCondition === 'hands' || v.handsPlayed >= 300
|
||||
? ` (${(v.result!.scores[g[0]!] ?? 0) >= 0 ? '+' : ''}${(v.result!.scores[g[0]!] ?? 0).toLocaleString('ko-KR')} 칩)`
|
||||
: ''}
|
||||
{v.options.endCondition === 'hands' || v.handsPlayed >= 300 ? ` (${formatWonDelta(v.result!.scores[g[0]!] ?? 0)})` : ''}
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">점수 = 마지막 칩 − 시작 칩 × 리바이 횟수</span>
|
||||
<span className="small muted">점수 = 마지막 보유 금액 − 시작 금액 × 다시 받은 횟수</span>
|
||||
</div>
|
||||
)}
|
||||
{log.length > 0 && v.handPhase && v.handPhase !== 'handEnd' && (
|
||||
<details className="card" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>이번 판 베팅</summary>
|
||||
<ol style={{ listStyle: 'none', margin: '6px 0 0', padding: 0, display: 'grid', gap: 2, maxHeight: 160, overflow: 'auto' }}>
|
||||
{log.map((e, i) => (
|
||||
<li key={i} className="small">
|
||||
{nick(players, e.p)} <strong>{BET_KO[e.t]}</strong>
|
||||
{e.amount > 0 ? ` ${formatWonShort(e.amount)}원` : ''}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보표</summary>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보 도우미</summary>
|
||||
<JokboTable options={v.options} mine={v.myHand} />
|
||||
</details>
|
||||
{v.history.length > 0 && (
|
||||
@@ -577,8 +195,8 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{r.handNo}판{r.rematchNo ? `(재${r.rematchNo})` : ''}
|
||||
</span>{' '}
|
||||
{r.how === 'rematch'
|
||||
? `재경기로 넘어감 ${formatChips(r.amount)}`
|
||||
: `${r.winners.map((id) => nick(players, id)).join('·')} ${formatChips(r.amount)}${r.name ? ` · ${r.name}` : ''}${r.how !== 'normal' ? ` · ${REASON_KO[r.how]}` : ''}`}
|
||||
? `재경기로 넘어감 ${formatWon(r.amount)}`
|
||||
: `${r.winners.map((id) => nick(players, id)).join('·')} ${formatWon(r.amount)}${r.name ? ` · ${r.name}` : ''}${r.how === 'fold' ? ' · 모두 다이' : r.how === 'ttaengjabi' ? ' · 땡잡이' : r.how === 'amhaeng' ? ' · 암행어사' : r.how === 'limit' ? ' · 나눔' : r.how === 'tie' ? ' · 같은 족보 나눔' : ''}`}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@@ -587,12 +205,10 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{v.rejoin?.mine && (
|
||||
<Sheet onClose={() => {}} label="재경기 참가">
|
||||
<h2>구사 재경기에 다시 들어갈까요?</h2>
|
||||
<p className="muted">
|
||||
{formatChips(v.rejoin.cost)}을 모인 칩에 더 내면 재경기에 참가할 수 있어요. 시간이 지나면 참가하지 않아요.
|
||||
</p>
|
||||
<p className="muted">판돈에 {formatWon(v.rejoin.cost)}을 더 내면 재경기에 참가할 수 있어요. 시간이 지나면 참가하지 않아요.</p>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending || !v.rejoin.canAfford} onClick={() => act({ type: 'rejoin', accept: true })}>
|
||||
{v.rejoin.canAfford ? `${formatChips(v.rejoin.cost)} 내고 참가` : '칩이 모자라요'}
|
||||
{v.rejoin.canAfford ? `${formatWon(v.rejoin.cost)} 내고 참가` : '보유 금액이 모자라요'}
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'rejoin', accept: false })}>
|
||||
참가 안 함
|
||||
@@ -601,14 +217,14 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</Sheet>
|
||||
)}
|
||||
{v.rebuy?.mine && !confirmQuit && (
|
||||
<Sheet onClose={() => {}} label="칩 다시 받기">
|
||||
<h2>칩을 모두 잃었어요</h2>
|
||||
<Sheet onClose={() => {}} label="시작 금액 다시 받기">
|
||||
<h2>가진 원을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.rebuy.left !== null ? ` (남은 횟수 ${v.rebuy.left}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
|
||||
놀이용 시작 금액 {formatWon(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.rebuy.left !== null ? ` (남은 횟수 ${v.rebuy.left}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
|
||||
</p>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'rebuy', accept: true })}>
|
||||
칩 다시 받기
|
||||
다시 받기
|
||||
</button>
|
||||
<button className="btn btn-danger" style={{ flex: 1 }} disabled={pending} onClick={() => setConfirmQuit(true)}>
|
||||
그만하기
|
||||
@@ -643,13 +259,13 @@ function isMyTurn(v: SeotdaView, me: string | null): boolean {
|
||||
|
||||
function statusText(v: SeotdaView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'rebuy') return v.rebuy?.mine ? '칩을 다시 받을지 골라 주세요' : '칩을 다시 받을지 기다리는 중이에요';
|
||||
if (v.phase === 'rebuy') return v.rebuy?.mine ? '시작 금액을 다시 받을지 골라 주세요' : '시작 금액을 다시 받을지 기다리는 중이에요';
|
||||
switch (v.handPhase) {
|
||||
case 'betting':
|
||||
if (v.toAct === me) return v.myHand && v.options.hints ? `내 차례예요 · 지금: ${v.myHand.name}` : '내 차례예요. 베팅해 주세요';
|
||||
return v.toAct ? `${nick(players, v.toAct)}님 차례예요` : '카드를 나눠 주는 중이에요';
|
||||
if (v.toAct === me) return v.myHand && v.options.hints ? `내 차례예요 · 내 패: ${v.myHand.name}` : '내 차례예요. 베팅해 주세요';
|
||||
return v.toAct ? `${nick(players, v.toAct)}님 차례예요` : '패를 나눠 주는 중이에요';
|
||||
case 'choose':
|
||||
return isMyTurn(v, me) ? '쓸 카드 2장을 골라 주세요' : '다른 사람이 카드를 고르는 중이에요';
|
||||
return isMyTurn(v, me) ? '쓸 패 2장을 골라 주세요' : '다른 사람이 패를 고르는 중이에요';
|
||||
case 'rejoin':
|
||||
return v.rejoin?.mine ? '구사 재경기에 참가할지 골라 주세요' : '다이한 사람이 재경기 참가를 고르는 중이에요';
|
||||
case 'handEnd':
|
||||
@@ -661,7 +277,7 @@ function statusText(v: SeotdaView, me: string | null, players: Record<string, Pu
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
||||
function Seg<T extends string | number | null>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
||||
return (
|
||||
<div className="segmented">
|
||||
{options.map(([k, l]) => (
|
||||
@@ -688,43 +304,63 @@ function Options({ value: o, onChange }: OptionsProps<SeotdaOptions>) {
|
||||
const tooBig = o.baseUnit * 20 > o.startingChips;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<Field label="카드 수">
|
||||
<Seg value={o.cardMode} options={[['two', '2장 섯다'], ['three', '3장 섯다(최대 6명)']]} onChange={(cardMode) => set({ cardMode })} />
|
||||
<Field label="게임 방식">
|
||||
<Seg value={o.cardMode} options={[['two', '2장 섯다'], ['three', o.deck === 40 ? '3장 섯다' : '3장 섯다(최대 6명)']]} onChange={(cardMode) => set({ cardMode })} />
|
||||
</Field>
|
||||
{o.cardMode === 'two' && (
|
||||
<Field label="카드 나눠 주기">
|
||||
<Seg value={o.dealMode} options={[['twoRounds', '1장씩 두 번(베팅 2번)'], ['oneRound', '2장 한 번에(베팅 1번)']]} onChange={(dealMode) => set({ dealMode })} />
|
||||
<Field label="패 받기">
|
||||
<Seg value={o.dealMode} options={[['oneRound', '2장 한 번에(베팅 1번)'], ['twoRounds', '1장씩 두 번(베팅 2번)']]} onChange={(dealMode) => set({ dealMode })} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="시작 칩">
|
||||
<Seg value={o.startingChips} options={[[500, '500'], [1000, '1,000'], [2000, '2,000'], [5000, '5,000']]} onChange={(startingChips) => set({ startingChips })} />
|
||||
<Field label="화투 장수">
|
||||
<Seg value={o.deck} options={[[20, '20장(1~10월 2장씩)'], [40, '40장(1~10월 4장씩)']]} onChange={(deck) => set({ deck })} />
|
||||
</Field>
|
||||
<Field label="학교(기본 칩) = 삥">
|
||||
<Seg value={o.baseUnit} options={[[2, '2칩'], [10, '10칩'], [20, '20칩'], [50, '50칩']]} onChange={(baseUnit) => set({ baseUnit })} />
|
||||
{tooBig && <span className="field-error">학교는 시작 칩의 20분의 1 이하로 골라 주세요.</span>}
|
||||
<Field label="시작 금액">
|
||||
<Seg value={o.startingChips} options={[[500_000, '50만원'], [1_000_000, '100만원'], [2_000_000, '200만원'], [5_000_000, '500만원']]} onChange={(startingChips) => set({ startingChips })} />
|
||||
</Field>
|
||||
<Field label="기본금(판마다 내는 돈, 삥)">
|
||||
<Seg value={o.baseUnit} options={[[2_000, '2천원'], [10_000, '1만원'], [20_000, '2만원'], [50_000, '5만원']]} onChange={(baseUnit) => set({ baseUnit })} />
|
||||
{tooBig && <span className="field-error">기본금은 시작 금액의 20분의 1 이하로 골라 주세요.</span>}
|
||||
</Field>
|
||||
<Field label="베팅 규칙">
|
||||
<Seg
|
||||
value={o.betRule}
|
||||
options={[
|
||||
['free', '일반'],
|
||||
['111', '111'],
|
||||
['222', '222'],
|
||||
['333', '333'],
|
||||
['444', '444'],
|
||||
]}
|
||||
onChange={(betRule) => set({ betRule })}
|
||||
/>
|
||||
<span className="small muted">
|
||||
{o.betRule === 'free' ? '모두 마음대로 걸어요.' : `선부터 ${o.betRule[0]}명은 첫 베팅에서 하프나 다이만 할 수 있고, 그 뒤는 마음대로예요.`}
|
||||
</span>
|
||||
</Field>
|
||||
<Field label="끝내는 방식">
|
||||
<Seg value={o.endCondition} options={[['hands', '정해진 판 수'], ['lastStanding', '최후의 1인']]} onChange={(endCondition) => set({ endCondition })} />
|
||||
{o.endCondition === 'hands' && (
|
||||
<Seg value={o.handLimit} options={[[10, '10판'], [20, '20판'], [30, '30판'], [50, '50판']]} onChange={(handLimit) => set({ handLimit })} />
|
||||
)}
|
||||
{o.endCondition === 'hands' && <Seg value={o.handLimit} options={[[10, '10판'], [20, '20판'], [30, '30판'], [50, '50판']]} onChange={(handLimit) => set({ handLimit })} />}
|
||||
</Field>
|
||||
<Field label="행동 제한 시간">
|
||||
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||
</button>
|
||||
{more && (
|
||||
<>
|
||||
<Field label="최대 레이즈">
|
||||
<Seg value={o.maxRaise} options={[['half', '하프까지'], ['full', '풀까지']]} onChange={(maxRaise) => set({ maxRaise })} />
|
||||
<Field label="최대 베팅">
|
||||
<Seg value={o.maxRaise} options={[['half', '하프까지'], ['full', '풀(판돈만큼)까지']]} onChange={(maxRaise) => set({ maxRaise })} />
|
||||
</Field>
|
||||
<Field label="칩 다시 받기(리바이)">
|
||||
<Seg value={o.rebuy} options={[['off', '안 함(탈락)'], ['limited', '횟수 제한'], ['unlimited', '무제한']]} onChange={(rebuy) => set({ rebuy })} />
|
||||
<Field label="쿼터 버튼">
|
||||
<Seg value={o.quarter ? 'on' : 'off'} options={[['off', '안 씀'], ['on', '씀']]} onChange={(k) => set({ quarter: k === 'on' })} />
|
||||
</Field>
|
||||
<Field label="원을 다 잃으면(리바이)">
|
||||
<Seg value={o.rebuy} options={[['off', '탈락'], ['limited', '횟수 제한'], ['unlimited', '무제한']]} onChange={(rebuy) => set({ rebuy })} />
|
||||
{o.rebuy === 'limited' && <Seg value={o.rebuyLimit} options={[[1, '1번'], [2, '2번'], [3, '3번']]} onChange={(rebuyLimit) => set({ rebuyLimit })} />}
|
||||
</Field>
|
||||
<Field label="학교 올리기">
|
||||
<Field label="기본금 올리기">
|
||||
<Seg value={o.schoolUpEvery} options={[[0, '안 올림'], [5, '5판마다 2배'], [10, '10판마다 2배'], [15, '15판마다 2배']]} onChange={(schoolUpEvery) => set({ schoolUpEvery })} />
|
||||
</Field>
|
||||
<Field label="다음 판의 선">
|
||||
@@ -734,7 +370,7 @@ function Options({ value: o, onChange }: OptionsProps<SeotdaOptions>) {
|
||||
<Seg value={o.gwangTtaeng} options={[['all', '38·18·13광땡'], ['only38', '38광땡만']]} onChange={(gwangTtaeng) => set({ gwangTtaeng })} />
|
||||
</Field>
|
||||
<Field label="땡잡이(3·7)">
|
||||
<Seg value={o.ttaengjabi} options={[['strict', '3월 광 + 7월 열끗'], ['loose', '3월 + 7월 아무 패'], ['off', '없음']]} onChange={(ttaengjabi) => set({ ttaengjabi })} />
|
||||
<Seg value={o.ttaengjabi} options={[['loose', '3월 + 7월 아무 패'], ['strict', '3월 광 + 7월 열끗만'], ['off', '없음']]} onChange={(ttaengjabi) => set({ ttaengjabi })} />
|
||||
</Field>
|
||||
<Field label="특수패">
|
||||
<Seg value={o.amhaeng ? 'on' : 'off'} options={[['on', '암행어사 켜기'], ['off', '암행어사 끄기']]} onChange={(k) => set({ amhaeng: k === 'on' })} />
|
||||
@@ -743,10 +379,10 @@ function Options({ value: o, onChange }: OptionsProps<SeotdaOptions>) {
|
||||
{o.gusa && (
|
||||
<>
|
||||
<Field label="멍텅구리구사 재경기 범위">
|
||||
<Seg value={o.mungGusa} options={[['upTo8', '8땡까지'], ['upTo9', '9땡까지'], ['upToJang', '장땡까지'], ['off', '일반 구사로']]} onChange={(mungGusa) => set({ mungGusa })} />
|
||||
<Seg value={o.mungGusa} options={[['upTo9', '9땡까지'], ['upTo8', '8땡까지'], ['upToJang', '장땡까지'], ['off', '일반 구사로']]} onChange={(mungGusa) => set({ mungGusa })} />
|
||||
</Field>
|
||||
<Field label="구사 재경기 때 다이한 사람">
|
||||
<Seg value={o.rejoinCost} options={[['none', '참가 불가'], ['half', '모인 칩 절반 내고 참가'], ['full', '모인 칩만큼 내고 참가']]} onChange={(rejoinCost) => set({ rejoinCost })} />
|
||||
<Seg value={o.rejoinCost} options={[['none', '참가 불가'], ['half', '판돈 절반 내고 참가'], ['full', '판돈만큼 내고 참가']]} onChange={(rejoinCost) => set({ rejoinCost })} />
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
@@ -759,7 +395,7 @@ function Options({ value: o, onChange }: OptionsProps<SeotdaOptions>) {
|
||||
<Field label="재참가·리바이 답 시간">
|
||||
<Seg value={o.decisionSeconds} options={[[10, '10초'], [15, '15초'], [30, '30초']]} onChange={(decisionSeconds) => set({ decisionSeconds })} />
|
||||
</Field>
|
||||
<Field label="도움 표시">
|
||||
<Field label="족보 도우미">
|
||||
<Seg value={o.hints ? 'on' : 'off'} options={[['on', '내 족보 이름 보여 주기'], ['off', '보여 주지 않기']]} onChange={(k) => set({ hints: k === 'on' })} />
|
||||
</Field>
|
||||
</>
|
||||
@@ -770,11 +406,13 @@ function Options({ value: o, onChange }: OptionsProps<SeotdaOptions>) {
|
||||
|
||||
function optionsSummary(o: SeotdaOptions): string {
|
||||
return [
|
||||
o.cardMode === 'three' ? '3장 섯다' : o.dealMode === 'twoRounds' ? '2장 섯다(1장씩 두 번)' : '2장 섯다(한 번에)',
|
||||
`시작 ${o.startingChips.toLocaleString('ko-KR')}칩`,
|
||||
`학교 ${o.baseUnit}칩`,
|
||||
o.cardMode === 'three' ? '3장 섯다' : o.dealMode === 'twoRounds' ? '2장 섯다(1장씩)' : '2장 섯다',
|
||||
`${o.deck}장`,
|
||||
`시작 ${formatWon(o.startingChips)}`,
|
||||
`기본금 ${formatWon(o.baseUnit)}`,
|
||||
o.betRule === 'free' ? '일반 베팅' : `베팅 ${o.betRule}`,
|
||||
o.endCondition === 'hands' ? `${o.handLimit}판` : '최후의 1인',
|
||||
`${o.turnSeconds}초`,
|
||||
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
@@ -783,39 +421,47 @@ function Rules({ options }: { options?: SeotdaOptions }) {
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
화투 20장(1~10월 각 2장)으로 하는 족보 대결이에요. 각자 받은 <strong>2장의 조합(족보)</strong>이 가장 센 사람이 모인 칩을 가져가요. 칩은 이 방에서만 쓰는 놀이용 점수예요.
|
||||
화투 {o?.deck ?? 20}장({o?.deck === 40 ? '1~10월 4장씩' : '1~10월 2장씩'})으로 하는 족보 대결이에요. 각자 받은 <strong>2장의 조합(족보)</strong>이 가장 센 사람이 가운데{' '}
|
||||
<strong>판돈</strong>을 모두 가져가요. {PLAY_MONEY_NOTICE}
|
||||
</p>
|
||||
<p>
|
||||
<strong>진행</strong>: 판마다 모두 <strong>학교(기본 칩)</strong>를 내요. 선부터 카드를 받고 차례로 베팅해요.
|
||||
<strong>진행</strong>: 판마다 모두 <strong>기본금</strong>을 판돈에 내요. 선부터 패를 받고 차례로 베팅해요.
|
||||
{o?.cardMode === 'three'
|
||||
? ' 3장 섯다는 2장을 받고 베팅 → 1장을 더 받아 3장 중 쓸 2장을 동시에 몰래 고르고 → 마지막 베팅 후 공개해요. 버린 1장은 끝까지 아무도 못 봐요.'
|
||||
: o?.dealMode === 'oneRound'
|
||||
? ' 2장을 한 번에 받고 한 번 베팅한 뒤 공개해요.'
|
||||
: ' 1장 받고 베팅, 1장 더 받고 베팅한 뒤 남은 사람끼리 패를 공개해요.'}{' '}
|
||||
모두 다이하고 한 명만 남으면 그 사람이 패를 보여 주지 않고 가져가요.
|
||||
? ' 3장 섯다는 2장을 받고 베팅 → 1장을 더 받아 3장 중 쓸 2장을 몰래 고르고 → 마지막 베팅 후 공개해요. 버린 1장은 끝까지 아무도 못 봐요.'
|
||||
: o?.dealMode === 'twoRounds'
|
||||
? ' 1장 받고 베팅, 1장 더 받고 베팅한 뒤 남은 사람끼리 패를 공개해요.'
|
||||
: ' 2장을 한 번에 받고 한 번 베팅한 뒤 남은 사람끼리 패를 공개해요.'}{' '}
|
||||
모두 다이하고 한 명만 남으면 그 사람이 패를 보여 주지 않고 판돈을 가져가요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>베팅</strong>: 체크(안 걸고 넘김), 삥(기본 칩만큼), 콜(앞사람만큼), 따당(앞사람이 건 만큼의 두 배), 쿼터·하프{o?.maxRaise === 'full' ? '·풀' : ''}(모인 칩의 4분의 1·절반
|
||||
{o?.maxRaise === 'full' ? '·전부' : ''}만큼 더), 다이(포기). 한 라운드에 올리기는 한 번뿐이고, 체크나 콜을 한 뒤에는 같은 라운드에서 올릴 수 없어요. 칩이 모자라면 가진 만큼 내고 올인해요.
|
||||
<strong>베팅</strong>(괄호는 숫자 키): 콜(7) 앞사람만큼, 다이(8) 포기, 삥(4) 기본금만큼, 체크(5) 안 걸고 넘김, 따당(1) 앞사람이 건 돈의 두 배, 하프(0) 맞춘 뒤 판돈의 절반을 더
|
||||
{o?.quarter ? ', 쿼터(2) 판돈의 4분의 1을 더' : ''}
|
||||
{o?.maxRaise === 'full' ? ', 풀(9) 판돈만큼 더' : ''}. 한 라운드에 올리기는 한 번뿐이고, 체크나 콜을 한 뒤에는 같은 라운드에서 올릴 수 없어요. 가진 금액이 모자라면 가진 만큼 내고 올인해요.
|
||||
{o && o.betRule !== 'free' ? ` 이 방은 베팅 규칙 ${o.betRule}: 선부터 ${o.betRule[0]}명은 첫 베팅에서 하프나 다이만 할 수 있어요.` : ''}
|
||||
</p>
|
||||
<p>
|
||||
<strong>끗</strong>: 두 장의 월을 더한 값의 일의 자리예요. 7 + 8 = 15 → 5끗, 9 + 10 = 19 → 9끗(갑오), 2 + 8 = 10 → 0끗(망통).
|
||||
<strong>끗</strong>: 두 장의 달을 더한 값의 일의 자리예요. 7 + 8 = 15 → 5끗, 9 + 10 = 19 → 9끗(갑오), 2 + 8 = 10 → 0끗(망통).
|
||||
</p>
|
||||
<JokboTable options={o ?? ({ gwangTtaeng: 'all', ttaengjabi: 'strict', amhaeng: true, gusa: true, mungGusa: 'upTo8', hints: false } as SeotdaOptions)} />
|
||||
<JokboTable options={o ?? ({ gwangTtaeng: 'all', ttaengjabi: 'loose', amhaeng: true, gusa: true, mungGusa: 'upTo9', hints: false } as SeotdaOptions)} />
|
||||
<p>
|
||||
<strong>재경기</strong>: 구사나 같은 족보{o?.tieRule === 'split' ? '(이 방은 동점이면 나눠 가져요)' : ''}로 재경기가 되면 모인 칩은 그대로 두고 남은 사람끼리 새로 카드를 받아요. 학교는 다시 내지 않아요.
|
||||
{o && o.rejoinCost !== 'none' ? ` 구사 재경기 때 다이한 사람은 모인 칩의 ${o.rejoinCost === 'half' ? '절반' : '전부'}만큼 내고 다시 들어올 수 있어요.` : ''} 한 판에서 재경기가{' '}
|
||||
<strong>재경기</strong>: 구사나 같은 족보{o?.tieRule === 'split' ? '(이 방은 같은 족보면 나눠 가져요)' : ''}로 재경기가 되면 판돈은 그대로 두고 남은 사람끼리 새로 패를 받아요. 기본금은 다시 내지 않아요.
|
||||
{o && o.rejoinCost !== 'none' ? ` 구사 재경기 때 다이한 사람은 판돈의 ${o.rejoinCost === 'half' ? '절반' : '전부'}만큼 내고 다시 들어올 수 있어요.` : ''} 한 판에서 재경기가{' '}
|
||||
{o?.maxRematches ?? 3}번을 넘으면 나눠 가져요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>선</strong>: 선은 카드를 먼저 받고 먼저 베팅해요. {o?.dealerRule === 'rotate' ? '판마다 다음 사람에게 넘어가요.' : '이긴 사람이 다음 판의 선이 돼요.'}
|
||||
<strong>선</strong>: 선은 패를 먼저 받고 먼저 베팅해요. {o?.dealerRule === 'rotate' ? '판마다 다음 사람에게 넘어가요.' : '이긴 사람이 다음 판의 선이 돼요.'}
|
||||
</p>
|
||||
<p>
|
||||
<strong>칩이 떨어지면</strong>:{' '}
|
||||
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '칩을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
|
||||
{o?.endCondition === 'lastStanding' ? '칩을 가진 사람이 한 명 남으면 끝나요.' : `정해진 판 수가 끝나면 (마지막 칩 − 시작 칩 × 다시 받은 횟수)로 순위를 정해요.`}
|
||||
<strong>원을 모두 잃으면</strong>:{' '}
|
||||
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '시작 금액을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
|
||||
{o?.endCondition === 'lastStanding' ? '원이 남은 사람이 한 명이 되면 끝나요.' : '정해진 판 수가 끝나면 (마지막 보유 금액 − 시작 금액 × 다시 받은 횟수)로 순위를 정해요.'}
|
||||
</p>
|
||||
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 다이로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 5초로 줄어요.</p>
|
||||
<p>
|
||||
{o?.turnSeconds === null
|
||||
? '이 방은 행동 시간이 무제한이에요.'
|
||||
: "시간 안에 고르지 않으면 앞사람이 건 금액이 없을 때는 체크, 있을 때는 다이로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 5초로 줄어요."}
|
||||
</p>
|
||||
<p className="small muted">{HWATU_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ const btn = (bg: string): CSSProperties => ({
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minWidth: 74,
|
||||
minWidth: 0,
|
||||
height: 40,
|
||||
borderRadius: 10,
|
||||
background: bg,
|
||||
@@ -47,11 +47,13 @@ const btn = (bg: string): CSSProperties => ({
|
||||
|
||||
function Buttons() {
|
||||
return (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, width: 170 }} aria-hidden>
|
||||
<span style={btn('#dc2626')}>다이</span>
|
||||
<span style={btn('#2563eb')}>체크</span>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, width: 240 }} aria-hidden>
|
||||
<span style={btn('#2563eb')}>콜</span>
|
||||
<span style={btn('#7c3aed')}>하프</span>
|
||||
<span style={btn('#b91c1c')}>다이</span>
|
||||
<span style={btn('#ea580c')}>하프</span>
|
||||
<span style={btn('#0f766e')}>삥</span>
|
||||
<span style={btn('#15803d')}>체크</span>
|
||||
<span style={btn('#7c3aed')}>따당</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -67,13 +69,13 @@ export const quickStart: QuickCard[] = [
|
||||
),
|
||||
alt: '3월 광과 8월 광 화투 두 장이 놓여 있고 38광땡이라고 적혀 있어요',
|
||||
title: '2장 조합이 센 사람이 이겨요',
|
||||
text: '화투 2장의 조합(족보)을 겨뤄요. 가장 센 족보를 가진 사람이 가운데 모인 칩을 모두 가져가요.',
|
||||
text: '화투 2장의 조합(족보)을 겨뤄요. 가장 센 족보를 가진 사람이 가운데 판돈을 모두 가져가요. 원은 이 방에서만 쓰는 놀이용 숫자예요.',
|
||||
},
|
||||
{
|
||||
pic: <Buttons />,
|
||||
alt: '다이, 체크, 콜, 하프라고 적힌 버튼 네 개가 있어요',
|
||||
title: '차례가 오면 칩을 걸어요',
|
||||
text: '[체크]·[콜]·[하프] 같은 버튼으로 칩을 걸고, 패가 약하면 [다이]로 이번 판을 포기해요. 다른 사람이 다 다이하면 내가 가져가요.',
|
||||
alt: '콜, 다이, 하프, 삥, 체크, 따당이라고 적힌 버튼 여섯 개가 있어요',
|
||||
title: '차례가 오면 걸어요',
|
||||
text: '[체크]·[삥]·[콜]·[하프]·[따당] 버튼(PC는 숫자 키도)으로 걸고, 패가 약하면 [다이]로 이번 판을 포기해요. 다른 사람이 다 다이하면 내가 가져가요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
@@ -87,6 +89,6 @@ export const quickStart: QuickCard[] = [
|
||||
),
|
||||
alt: '장땡, 알리, 8끗 순서로 화투 두 장씩 놓여 있고 사이에 큰 쪽 표시가 있어요',
|
||||
title: '땡 > 알리 > 끗 순서예요',
|
||||
text: "광땡 > 땡(같은 달 2장) > 알리·독사 등 > 끗(두 달을 더한 일의 자리) 순으로 세요. 화면의 '족보표'를 보면 쉬워요.",
|
||||
text: "광땡 > 땡(같은 달 2장) > 알리·독사 등 > 끗(두 달을 더한 일의 자리) 순으로 세요. 화면의 '족보 도우미'를 보면 쉬워요.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
/**
|
||||
* Guard (docs/04 §6, reviewer request): betting-game UI text must never look like real money.
|
||||
* Scans the betting games' screens and shared chip/card components for currency-like wording.
|
||||
*
|
||||
* Exception (2026-10-13, user request "한게임 섯다처럼 원과 판돈으로"): 섯다 shows its room-only play money in "원" and
|
||||
* calls the pot "판돈", like 한게임 섯다. Only those two are allowed there; currency symbols, 현금·머니·골드, "돈을/돈이/돈은"
|
||||
* and transaction words (충전·환전·결제 …) stay forbidden in 섯다 too.
|
||||
*/
|
||||
import { expect, test } from 'bun:test';
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const ROOTS = ['games/poker', 'games/seotda', 'games/gostop', 'games/marble', 'games/las-vegas', 'components/cards'].map((p) => join(import.meta.dir, p));
|
||||
const SEOTDA = join(import.meta.dir, 'games/seotda');
|
||||
const FORBIDDEN: [RegExp, string][] = [
|
||||
[/₩|\$\s?\d|\d\s?\$/, '통화 기호'],
|
||||
[/\d[\d,]*\s*(만\s*)?원(?![가-힣])/, '"원" 단위'],
|
||||
@@ -30,10 +35,25 @@ function visibleText(src: string): string {
|
||||
test('no currency-like wording in betting game UI', () => {
|
||||
const problems: string[] = [];
|
||||
for (const f of ROOTS.flatMap(files)) {
|
||||
const seotda = f.startsWith(SEOTDA);
|
||||
const text = visibleText(readFileSync(f, 'utf8'));
|
||||
text.split('\n').forEach((line, i) => {
|
||||
for (const [re, why] of FORBIDDEN) if (re.test(line)) problems.push(`${f.split('/src/')[1]}:${i + 1} ${why}: ${line.trim().slice(0, 80)}`);
|
||||
// 섯다: "판돈" is the game's word for the pot; the other 돈 words are still checked.
|
||||
const checked = seotda ? line.replace(/판돈/g, '') : line;
|
||||
for (const [re, why] of FORBIDDEN) {
|
||||
if (seotda && why === '"원" 단위') continue;
|
||||
if (re.test(checked)) problems.push(`${f.split('/src/')[1]}:${i + 1} ${why}: ${line.trim().slice(0, 80)}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
test('섯다 exception is narrow: 원 and 판돈 only', () => {
|
||||
const lines = ['판돈 1만원', '판돈은 그대로', '10만원 충전', '₩1000', '게임머니', '돈을 걸어요', '현금'];
|
||||
const bad = lines.filter((line) => {
|
||||
const checked = line.replace(/판돈/g, '');
|
||||
return FORBIDDEN.some(([re, why]) => why !== '"원" 단위' && re.test(checked));
|
||||
});
|
||||
expect(bad).toEqual(['10만원 충전', '₩1000', '게임머니', '돈을 걸어요', '현금']);
|
||||
});
|
||||
|
||||
@@ -1,44 +1,52 @@
|
||||
# 섯다 (`seotda`)
|
||||
|
||||
> 마일스톤: M3 · 인원: 최소 2 ~ 최대 10명 (3장 섯다는 최대 6명) · 예상 시간: 약 15~25분 (20판 기준) · 난이도: 쉬움~보통
|
||||
> 마일스톤: M3 · 인원: 최소 2 ~ 최대 10명 (20장 3장 섯다는 최대 6명) · 예상 시간: 약 15~25분 (20판 기준) · 난이도: 쉬움~보통
|
||||
>
|
||||
> 2026-10-13 다시 만듦: 한게임 섯다의 화면·흐름·용어를 본떴다(초록 테이블, 가운데 판돈, 숫자 키 베팅 버튼, 원 단위, 2장 한 번에 받기 기본, 20/40장, 베팅 규칙 111~444, 실제 화투 그림, 남은 패를 전부 따져 보는 컴퓨터).
|
||||
|
||||
## 1. 개요
|
||||
|
||||
- 화투 20장(1~10월 각 2장)으로 각자 2장의 조합(족보)을 겨루는 한국 전통 베팅 카드 게임이다. 명절·모임에서 고스톱과 함께 가장 널리 알려진 화투 놀이이고, "광땡", "장땡", "땡잡이", "구사" 같은 용어는 일상어처럼 쓰인다.
|
||||
- 칩은 방 안에서만 쓰는 가상 칩이다. 돈·유료 재화·환전·양도·방 간 이월이 없다(12장).
|
||||
- 인원 근거: 전통 규칙에 고정된 인원 상한은 없고, 덱 20장이 물리적 상한을 정한다. 2장 섯다는 1인 2장이므로 최대 10명, 3장 섯다는 1인 3장이므로 최대 6명(18장). 최소 2명. 실제로는 4~6명이 가장 흔하다.
|
||||
- 금액은 한게임 섯다처럼 **원**으로, 가운데 모인 돈은 **판돈**, 판마다 내는 돈은 **기본금**이라 부른다. 이 원은 방 안에서만 쓰는 놀이용 숫자다. 진짜 돈·유료 재화·환전·양도·방 간 이월이 없다(12장). 엔진 안의 이름(`startingChips`, `baseUnit`, `stack`)은 예전 칩 시절 이름을 그대로 쓴다.
|
||||
- 인원 근거: 전통 규칙에 고정된 인원 상한은 없고, 덱 장수가 물리적 상한을 정한다. 2장 섯다는 1인 2장이므로 최대 10명, 20장 3장 섯다는 1인 3장이므로 최대 6명(18장), 40장이면 3장 섯다도 10명. 최소 2명. 실제로는 4~6명이 가장 흔하다.
|
||||
- 베팅 방식(삥/콜/따당/하프/체크/다이)과 사이드 팟·리바이는 포커 문서(`poker`)의 한국식 판돈 베팅 공용 모듈을 그대로 쓴다. 이 문서에도 필요한 정의를 모두 다시 적는다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `cardMode` | 2장 섯다 / 3장 섯다(3장 받아 2장 선택) | `two` / `three` | `two` |
|
||||
| `dealMode` | 2장 섯다 분배 방식 | `twoRounds`(1장 받고 베팅, 1장 더 받고 베팅) / `oneRound`(2장 한 번에 받고 베팅 1회) | `twoRounds` |
|
||||
| `startingChips` | 시작 칩 | 500 / 1000 / 2000 / 5000 | 1000 |
|
||||
| `baseUnit` | 기본 단위 = 학교(참가비, 앤티) = 삥 금액 | 2 / 10 / 20 / 50 | 10 |
|
||||
| `maxRaise` | 허용하는 최대 레이즈 | `half`(하프까지) / `full`(풀까지) | `half` |
|
||||
| `cardMode` | 게임 방식: 2장 섯다 / 3장 섯다(3장 받아 2장 선택) | `two` / `three` | `two` |
|
||||
| `dealMode` | 2장 섯다 패 받기 | `oneRound`(2장 한 번에 받고 베팅 1회, 한게임 2장 섯다) / `twoRounds`(1장 받고 베팅, 1장 더 받고 베팅) | `oneRound` |
|
||||
| `deck` | 화투 장수 | `20`(1~10월 광·열끗과 띠, 8월은 기러기) / `40`(1~10월 4장 모두, 피 포함) | `20` |
|
||||
| `startingChips` | 시작 금액(원) | 50만 / 100만 / 200만 / 500만 | 100만원 |
|
||||
| `baseUnit` | 기본금 = 판마다 모두 내는 돈 = 삥 금액(원) | 2,000 / 1만 / 2만 / 5만 | 1만원 |
|
||||
| `betRule` | 베팅 규칙 | `free`(일반) / `111`·`222`·`333`·`444`(선부터 1~4명은 첫 베팅에서 하프·다이만) | `free` |
|
||||
| `maxRaise` | 허용하는 최대 베팅 | `half`(하프까지) / `full`(풀까지) | `half` |
|
||||
| `quarter` | 쿼터 버튼(한게임에는 없음) | 켬 / 끔 | 끔 |
|
||||
| `endCondition` | 게임 종료 방식 | `hands`(정해진 판 수) / `lastStanding`(최후 1인) | `hands` |
|
||||
| `handLimit` | `hands`일 때 총 판 수(재경기는 판 수에 포함하지 않음) | 10 / 20 / 30 / 50 | 20 |
|
||||
| `schoolUpEvery` | N판마다 학교 금액 2배(0=안 올림) | 0 / 5 / 10 / 15 | 0 |
|
||||
| `rebuy` | 리바이(칩 다시 받기) | `off` / `limited` / `unlimited` | `unlimited` |
|
||||
| `schoolUpEvery` | N판마다 기본금 2배(0=안 올림) | 0 / 5 / 10 / 15 | 0 |
|
||||
| `rebuy` | 리바이(원을 다 잃으면 시작 금액 다시 받기) | `off` / `limited` / `unlimited` | `unlimited` |
|
||||
| `rebuyLimit` | `limited`일 때 1인당 횟수 | 1 / 2 / 3 | 1 |
|
||||
| `turnSeconds` | 행동 제한 시간(초) | 15 / 20 / 30 / 60 | 20 |
|
||||
| `turnSeconds` | 행동 제한 시간(초) | 15 / 20 / 30 / 60 / `null`(무제한) | 20 |
|
||||
| `dealerRule` | 다음 판의 선 | `winner`(직전 판 승자) / `rotate`(시계 방향) | `winner` |
|
||||
| `gwangTtaeng` | 광땡 종류 | `all`(38·18·13광땡) / `only38`(38광땡만) | `all` |
|
||||
| `ttaengjabi` | 땡잡이(3·7) | `off` / `strict`(3월 광 + 7월 열끗) / `loose`(3월 아무 패 + 7월 아무 패) | `strict` |
|
||||
| `ttaengjabi` | 땡잡이(3·7) | `off` / `strict`(3월 광 + 7월 열끗) / `loose`(3월 + 7월 아무 패, 한게임) | `loose` |
|
||||
| `amhaeng` | 암행어사(4월 열끗 + 7월 열끗) | 켬 / 끔 | 켬 |
|
||||
| `gusa` | 구사 재경기(4·9, "49파토") | 켬 / 끔 | 켬 |
|
||||
| `mungGusa` | 멍텅구리구사(4월 열끗 + 9월 열끗) 재경기 범위 | `off`(일반 구사로 취급) / `upTo8`(8땡 이하 재경기) / `upTo9`(9땡 이하) / `upToJang`(장땡 이하) | `upTo8` |
|
||||
| `mungGusa` | 멍텅구리구사(4월 열끗 + 9월 열끗) 재경기 범위 | `off`(일반 구사로 취급) / `upTo8`(8땡 이하 재경기) / `upTo9`(9땡 이하, 한게임) / `upToJang`(장땡 이하) | `upTo9` |
|
||||
| `tieRule` | 같은 족보 동점 처리 | `rematch`(동점자끼리 재경기) / `split`(나눠 가짐) | `rematch` |
|
||||
| `rejoinCost` | 구사 재경기 때 다이한 사람의 재참가 | `none`(불가) / `half`(현재 판돈의 절반을 내고 참가) / `full`(현재 판돈만큼 내고 참가) | `none` |
|
||||
| `hints` | 내 족보 이름 표시, 족보표 강조 | 켬 / 끔 | 켬 |
|
||||
| `hints` | 족보 도우미: 내 족보 이름 표시, 족보표에서 내 패 강조 | 켬 / 끔 | 켬 |
|
||||
|
||||
옵션 검증: `cardMode=three`이면 참가자 6명 이하, `dealMode`는 무시(3장 섯다 고유 흐름). `baseUnit × 20 ≤ startingChips`. `gusa=off`이면 `mungGusa`도 무시(4·9는 모두 3끗).
|
||||
- 2026-10-13 전에 만든 방(상태 버전 1, 칩 단위)은 버전 2로 옮길 때 금액을 모두 1000배 해서 원으로 바꾸고(시작 1,000칩 → 100만원), 진행 중인 게임의 규칙은 그대로 둔다(쿼터 켬, 20장, 일반 베팅). 저장된 옛 옵션 값(500칩 등)은 스키마에서 기본값으로 바뀐다(`.catch`).
|
||||
- 한게임 섯다 기준으로 바꾼 기본값: `dealMode` 1장씩 → 2장 한 번에, `ttaengjabi` 엄격 → 3·7 아무 패, `mungGusa` 8땡 → 9땡까지, 쿼터 버튼 기본 끔. 한게임의 땡값·딜러비·등급·무료 충전 같은 머니 제도는 넣지 않는다(12장).
|
||||
|
||||
옵션 검증: `cardMode=three`이고 20장이면 참가자 6명 이하, `dealMode`는 무시(3장 섯다 고유 흐름). `baseUnit × 20 ≤ startingChips`. `betRule`은 매 (재)경기 첫 베팅 라운드의 처음 N번 행동에만 걸린다(시간 초과로 체크가 안 되면 다이). `gusa=off`이면 `mungGusa`도 무시(4·9는 모두 3끗).
|
||||
|
||||
## 3. 구성물
|
||||
|
||||
화투 20장. 각 월의 "특수 패" 1장 + "일반 패" 1장:
|
||||
화투 20장(기본). 각 월의 "특수 패" 1장 + "일반 패" 1장. `deck=40`이면 1~10월의 피 2장씩도 넣어 40장(피는 숫자로만 쓰인다):
|
||||
|
||||
| 월 | 꽃(그림 소재) | 특수 패 | 일반 패 |
|
||||
|---|---|---|---|
|
||||
@@ -54,21 +62,23 @@
|
||||
| 10 | 단풍(사슴) | 열끗 | 띠 |
|
||||
|
||||
- 규칙상 의미가 있는 특수 패는 1·3·8월 광, 4·7·9월 열끗뿐이다. 나머지 열끗·띠·일반 패는 숫자(월)로만 쓰인다.
|
||||
- 가상 칩, 선 표시, 판돈 영역.
|
||||
- 카드 그림은 직접 그린 단순 SVG(9장, 12장 참고).
|
||||
- 놀이용 원, 선 표시, 판돈 영역.
|
||||
- 카드 그림은 Wikimedia Commons의 화투 SVG(CC BY-SA 4.0, 9.1 "화투 그림")를 쓴다.
|
||||
|
||||
## 4. 준비(셋업)
|
||||
|
||||
1. 참가자를 좌석에 앉히고 좌석 순서를 `rng`로 섞는다.
|
||||
2. 모든 플레이어 칩 = `startingChips`.
|
||||
2. 모든 플레이어 보유 금액 = `startingChips`.
|
||||
3. 첫 판의 선을 `rng`로 고른다.
|
||||
4. 첫 판을 시작한다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
|
||||
### 5.1 한 판의 흐름 (2장 섯다, `dealMode=twoRounds`)
|
||||
### 5.1 한 판의 흐름 (2장 섯다)
|
||||
|
||||
1. 학교: 칩이 있는 참가자 전원이 `baseUnit`을 판돈에 낸다(칩이 모자라면 전부 내고 올인).
|
||||
기본(`dealMode=oneRound`, 한게임 2장 섯다): 기본금 → 2장을 한 번에 나눠 줌 → 베팅 1회 → 쇼다운. 아래는 `dealMode=twoRounds`(1장씩)의 흐름이다.
|
||||
|
||||
1. 기본금: 원이 있는 참가자 전원이 `baseUnit`을 판돈에 낸다(모자라면 전부 내고 올인).
|
||||
2. 기리(패 떼기): 실제 섞기는 서버 `rng`가 한다. 화면에서는 선의 오른쪽 사람이 패를 떼는 짧은 연출만 보여 준다(규칙 영향 없음).
|
||||
3. 선부터 시계 방향으로 1장씩(비공개) 나눠 준다.
|
||||
4. 1차 베팅(선부터 시계 방향, 5.4).
|
||||
@@ -76,13 +86,13 @@
|
||||
6. 2차 베팅(선이 다이했으면 선 다음 좌석의 남은 사람부터).
|
||||
7. 2명 이상 남으면 쇼다운: 남은 사람의 패를 동시에 공개하고 6장 규칙으로 판정.
|
||||
8. 도중에 1명만 남으면 그 사람이 판돈을 가져가고 패는 공개하지 않는다.
|
||||
9. 판 종료 결과를 4초간 보여 준 뒤 다음 판(리바이·탈락·종료 확인 포함).
|
||||
9. 판 종료 결과를 5초간 보여 준 뒤 다음 판(리바이·탈락·종료 확인 포함).
|
||||
|
||||
`dealMode=oneRound`: 3~6 대신 2장을 한 번에 나눠 주고 베팅 1회 후 쇼다운.
|
||||
`dealMode=oneRound`(기본): 3~6 대신 2장을 한 번에 나눠 주고 베팅 1회 후 쇼다운.
|
||||
|
||||
### 5.2 3장 섯다 (`cardMode=three`)
|
||||
|
||||
1. 학교 → 2장씩 나눠 줌(비공개) → 1차 베팅.
|
||||
1. 기본금 → 2장씩 나눠 줌(비공개) → 1차 베팅.
|
||||
2. 남은 사람에게 1장 더(비공개, 손에 3장).
|
||||
3. 선택 단계(동시 진행): 각자 3장 중 2장을 고른다. 고르지 않은 1장은 뒷면으로 버리며 끝까지 아무에게도 공개하지 않는다.
|
||||
4. 2차 베팅 → 쇼다운(고른 2장으로 판정).
|
||||
@@ -96,7 +106,7 @@
|
||||
|
||||
### 5.4 베팅 (한국식 판돈 베팅, 포커 문서 5.2와 동일한 공용 모듈)
|
||||
|
||||
용어: `pot` = 현재 판돈 전체(학교 포함), `currentBet` = 이번 라운드 최고 베팅액, `toCall` = `currentBet - 내 이번 라운드 베팅액`, `opened` = 이번 라운드에 누군가 칩을 걸었는가.
|
||||
용어: `pot` = 현재 판돈 전체(기본금 포함), `currentBet` = 이번 라운드 최고 베팅액, `toCall` = `currentBet - 내 이번 라운드 베팅액`, `opened` = 이번 라운드에 누군가 걸었는가.
|
||||
|
||||
| 행동 | 조건 | 낼 금액 |
|
||||
|---|---|---|
|
||||
@@ -109,38 +119,41 @@
|
||||
| 풀 | 레이즈 가능, `maxRaise=full` | `toCall + (pot + toCall)` |
|
||||
| 다이 | 자기 차례 언제나 | 0, 이번 판 포기(낸 돈은 판돈에 남음) |
|
||||
|
||||
- 쿼터는 `quarter` 옵션을 켠 방에서만 쓸 수 있다(한게임 섯다에는 없다).
|
||||
- 베팅 규칙(`betRule`) 111·222·333·444: (재)경기의 첫 베팅 라운드에서 처음 1·2·3·4번의 행동은 하프(하프를 못 하면 남은 올리기, 그것도 없으면 체크·콜) 또는 다이만 할 수 있다. 그 뒤는 자유.
|
||||
- 버튼과 숫자 키(PC): 콜 7, 다이 8, 삥 4, 체크 5, 따당 1, 하프 0(한게임과 같다), 쿼터 2, 풀 9.
|
||||
- 레이즈 가능 조건: (1) 이번 라운드에서 아직 체크·콜·삥·레이즈를 하지 않았다(한 라운드에 1인 1회, 체크·콜 후 레이즈 금지), (2) 낼 금액이 `toCall`보다 크다. `toCall`을 뺀 추가분이 `baseUnit`보다 작으면 `baseUnit`으로 올린다.
|
||||
- 첫 행동자가 체크하면 다음 사람도 체크/삥/쿼터/하프(/풀)/다이 중 고를 수 있다. 전원 체크하면 다음 단계로 넘어간다.
|
||||
- 라운드 종료: 다이·올인하지 않은 모든 사람이 이번 라운드에 한 번 이상 행동했고 모두 `currentBet`을 맞췄을 때.
|
||||
- 올인: 낼 금액이 스택 이상이면 전부 내고 올인. `toCall`보다 적게 올인하면 사이드 팟이 생긴다. 올인한 사람은 더 행동하지 않고 남은 카드는 받는다.
|
||||
- 사이드 팟 계산은 포커 문서 5.5와 같다: 올인 금액 레벨별로 팟을 나누고, 각 팟의 자격자는 그 레벨까지 낸 다이하지 않은 사람. 아무도 맞추지 못한 초과분은 돌려준다.
|
||||
|
||||
예(3명, 학교 10, 기본 단위 10): 학교 후 판돈 30. 선 A 삥 10(판돈 40) → B 하프: 콜 10 + (50의 절반 25) = 35(판돈 75) → C 따당: `toCall=35` → 70(판돈 145) → A는 이미 삥을 했으므로 콜 60 또는 다이 → A 콜(판돈 205) → B 콜 35(판돈 240). 세 사람 모두 70을 맞춰 종료. 검산: 30 + 70 × 3 = 240.
|
||||
예(3명, 기본금 10 — 단위를 줄여 적음, 실제 방은 1만원 같은 원 단위): 기본금 후 판돈 30. 선 A 삥 10(판돈 40) → B 하프: 콜 10 + (50의 절반 25) = 35(판돈 75) → C 따당: `toCall=35` → 70(판돈 145) → A는 이미 삥을 했으므로 콜 60 또는 다이 → A 콜(판돈 205) → B 콜 35(판돈 240). 세 사람 모두 70을 맞춰 종료. 검산: 30 + 70 × 3 = 240.
|
||||
|
||||
### 5.5 재경기(구사·동점)
|
||||
|
||||
재경기가 결정되면(6.3) 그 판의 판돈은 그대로 두고 새 판을 진행한다.
|
||||
1. 참가자:
|
||||
- 구사 재경기: 쇼다운에 남아 있던 사람 전원(구사를 든 사람 포함). `rejoinCost`가 `none`이 아니면 그 판에서 다이한 사람(탈락자 제외)에게 재참가 여부를 묻는다(동시 진행, 15초, 시간 초과는 불참). 재참가하면 `half`=현재 판돈의 절반(내림), `full`=현재 판돈만큼을 판돈에 낸다. 칩이 모자라면 재참가할 수 없다.
|
||||
- 구사 재경기: 쇼다운에 남아 있던 사람 전원(구사를 든 사람 포함). `rejoinCost`가 `none`이 아니면 그 판에서 다이한 사람(탈락자 제외)에게 재참가 여부를 묻는다(동시 진행, 15초, 시간 초과는 불참). 재참가하면 `half`=현재 판돈의 절반(내림), `full`=현재 판돈만큼을 판돈에 낸다. 보유 금액이 모자라면 재참가할 수 없다.
|
||||
- 동점 재경기(`tieRule=rematch`): 동점으로 최고패를 가진 사람만. 진 사람은 빠진다.
|
||||
2. 덱 20장을 새로 섞고, 학교는 다시 내지 않는다. 카드 분배·베팅·쇼다운은 5.1/5.2와 같다(새 베팅은 기존 판돈 위에 더해진다).
|
||||
2. 덱 20장을 새로 섞고, 기본금는 다시 내지 않는다. 카드 분배·베팅·쇼다운은 5.1/5.2와 같다(새 베팅은 기존 판돈 위에 더해진다).
|
||||
3. 이전 판에서 올인한 사람은 계속 올인 상태로 카드만 받는다.
|
||||
4. 사이드 팟이 있었던 경우: 각 팟을 그 팟의 자격자끼리 따로 판정한다. 재경기가 필요 없는 팟(자격자끼리 승자가 하나로 정해진 팟)은 재경기 전에 바로 지급하고, 재경기가 필요한 팟만 남긴다. 재경기 참가자는 남은 팟들의 재경기 참가자 합집합이며, 재경기 후 각 남은 팟을 다시 그 팟 자격자(재참가자 포함)끼리 판정한다.
|
||||
5. 같은 판에서 재경기가 연속 3번 일어나면 4번째 재경기 대신 그 팟을 재경기 참가자끼리 균등 분할한다(무한 반복 방지).
|
||||
6. 재경기는 `handLimit`의 판 수에 포함하지 않는다(원래 판의 연장).
|
||||
|
||||
### 5.6 칩이 떨어졌을 때
|
||||
### 5.6 원이 떨어졌을 때
|
||||
|
||||
- 판(재경기 포함)이 완전히 끝난 뒤 칩 0인 사람은 `busted`.
|
||||
- 판(재경기 포함)이 완전히 끝난 뒤 보유 금액이 0인 사람은 `busted`.
|
||||
- `rebuy=off`: 탈락(관전 화면, 결과 순위에는 남음).
|
||||
- `rebuy=limited/unlimited`: "칩 다시 받기 / 그만하기"(15초, 시간 초과는 그만하기). 받으면 `startingChips`로 채움. `hands` 방식에서 마지막 판 직후에는 묻지 않는다.
|
||||
- 칩이 학교 금액보다 적으면 가진 만큼 내고 올인 상태로 참가한다.
|
||||
- `rebuy=limited/unlimited`: "다시 받기 / 그만하기"(15초, 시간 초과는 그만하기). 받으면 `startingChips`로 채움. `hands` 방식에서 마지막 판 직후에는 묻지 않는다.
|
||||
- 보유 금액이 기본금보다 적으면 가진 만큼 내고 올인 상태로 참가한다.
|
||||
|
||||
### 5.7 학교 상승과 자리 비움
|
||||
### 5.7 기본금 상승과 자리 비움
|
||||
|
||||
- `schoolUpEvery = N > 0`이면 N판마다 `baseUnit` 2배(상한 `startingChips / 5`).
|
||||
- 연속 2번 시간 초과하면 `away` 표시, 이후 그 사람의 제한 시간 5초. 직접 행동하면 해제.
|
||||
- 방을 나간 사람(`left`)은 매 판 학교를 낸 뒤 자동 다이. 칩이 0이 되면 탈락.
|
||||
- 방을 나간 사람(`left`)은 매 판 기본금를 낸 뒤 자동 다이. 보유 금액이 0이 되면 탈락.
|
||||
|
||||
## 6. 승패와 점수 계산
|
||||
|
||||
@@ -195,7 +208,7 @@
|
||||
- 아니면 W = `v(p) = Vmax`인 사람들.
|
||||
4. 구사 재경기 검사(`gusa` 켬): 구사 또는 멍텅구리구사를 든 사람 h 중 W에 속하지 않은 사람이 있고, `max{ v(q) : q ∈ S, q ≠ h }`가 h의 기준값 이하이면 → 구사 재경기(5.5). 기준값: 구사 806, 멍텅구리구사는 `mungGusa`에 따라 908/909/910(`off`면 일반 구사로 보아 806).
|
||||
5. 재경기가 아니고 W가 1명이면 그 사람이 승리.
|
||||
6. W가 2명 이상이면 `tieRule`: `rematch`면 W끼리 재경기, `split`이면 균등 분할(나머지 칩은 선에서 시계 방향으로 가장 가까운 승자부터 1칩씩).
|
||||
6. W가 2명 이상이면 `tieRule`: `rematch`면 W끼리 재경기, `split`이면 균등 분할(나머지 원은 선에서 시계 방향으로 가장 가까운 승자부터 1원씩).
|
||||
|
||||
이 판정은 팟마다 그 팟의 자격자(S ∩ 자격자)로 따로 수행한다(5.5의 4).
|
||||
|
||||
@@ -218,26 +231,29 @@
|
||||
|
||||
### 6.5 판돈 지급
|
||||
|
||||
- 승자(들)가 해당 팟을 가져간다. 다이한 사람·패배자의 낸 칩은 돌려주지 않는다.
|
||||
- 승자(들)가 해당 팟을 가져간다. 다이한 사람·패배자의 낸 돈은 돌려주지 않는다.
|
||||
- 사이드 팟은 자격자가 적은 팟부터 판정해 지급하고 마지막에 메인 팟.
|
||||
|
||||
### 6.6 게임 종료와 점수
|
||||
|
||||
- `endCondition=hands`: `handLimit`판(재경기 제외)이 끝나면 종료. 점수 = `최종 칩 - startingChips × 리바이 횟수`. 점수 높은 순 순위, 같으면 공동 순위.
|
||||
- `endCondition=lastStanding`: 칩을 가진 사람이 1명 남으면 종료(리바이 결정 대기 중이면 대기). 순위 = 늦게 탈락한 순, 같은 판 동시 탈락은 그 판 시작 칩이 많은 쪽이 위. 300판 도달 시 `hands` 방식 점수로 강제 종료.
|
||||
- 접속 중이고 칩이 있는 사람이 1명 이하가 되면 즉시 종료.
|
||||
- `endCondition=hands`: `handLimit`판(재경기 제외)이 끝나면 종료. 점수 = `최종 보유 금액 - startingChips × 리바이 횟수`. 점수 높은 순 순위, 같으면 공동 순위.
|
||||
- `endCondition=lastStanding`: 원이 남은 사람이 1명이면 종료(리바이 결정 대기 중이면 대기). 순위 = 늦게 탈락한 순, 같은 판 동시 탈락은 그 판 시작 금액이 많은 쪽이 위. 300판 도달 시 `hands` 방식 점수로 강제 종료.
|
||||
- 접속 중이고 원이 남은 사람이 1명 이하가 되면 즉시 종료.
|
||||
|
||||
## 7. 지역 룰 / 하우스 룰 (옵션으로 켜고 끄기)
|
||||
|
||||
| 하우스 룰 | 옵션 | 기본 |
|
||||
|---|---|---|
|
||||
| 1장씩 2번 받기 / 2장 한 번에 | `dealMode` | 1장씩 2번 |
|
||||
| 2장 한 번에 / 1장씩 2번 받기 | `dealMode` | 2장 한 번에 |
|
||||
| 3장 받아 2장 고르기 | `cardMode=three` | 2장 |
|
||||
| 광땡 종류(38만 / 38·18·13) | `gwangTtaeng` | 모두 |
|
||||
| 땡잡이 엄격(3광+7열끗) / 느슨(3·7 아무 패) / 없음 | `ttaengjabi` | 엄격 |
|
||||
| 땡잡이 느슨(3·7 아무 패) / 엄격(3광+7열끗) / 없음 | `ttaengjabi` | 느슨 |
|
||||
| 암행어사 | `amhaeng` | 켬 |
|
||||
| 구사 재경기("49파토") | `gusa` | 켬 |
|
||||
| 멍텅구리구사 범위(8땡/9땡/장땡까지) | `mungGusa` | 8땡까지 |
|
||||
| 멍텅구리구사 범위(8땡/9땡/장땡까지) | `mungGusa` | 9땡까지 |
|
||||
| 화투 20장 / 40장 | `deck` | 20장 |
|
||||
| 베팅 규칙 111~444 | `betRule` | 일반 |
|
||||
| 쿼터 버튼 | `quarter` | 끔 |
|
||||
| 동점 재경기 / 나눔 | `tieRule` | 재경기 |
|
||||
| 구사 재경기 때 다이한 사람 재참가 비용 | `rejoinCost` | 재참가 불가 |
|
||||
| 선 = 이긴 사람 / 회전 | `dealerRule` | 이긴 사람 |
|
||||
@@ -347,7 +363,7 @@ interface SeotdaState {
|
||||
options: SeotdaOptions;
|
||||
rng: RngState;
|
||||
seats: SeatState[];
|
||||
baseUnit: number; // 학교 상승 반영
|
||||
baseUnit: number; // 기본금 상승 반영
|
||||
hand: SeotdaHand | null;
|
||||
handsPlayed: number;
|
||||
lastWinner: PlayerId | null;
|
||||
@@ -378,7 +394,7 @@ interface SeotdaState {
|
||||
| `rebuy` | `{ accept: boolean }` | `phase=rebuy`, 대상자 | 남은 리바이 횟수 > 0 |
|
||||
| `leave` | - | 서버가 퇴장 시 주입 | - |
|
||||
|
||||
거부 사유 예: "지금은 내 차례가 아니에요", "누가 이미 걸어서 체크할 수 없어요", "이번 라운드에는 더 올릴 수 없어요(콜 또는 다이)", "칩이 모자라 재참가할 수 없어요", "카드 두 장을 골라 주세요".
|
||||
거부 사유 예: "지금은 내 차례가 아니에요", "누가 이미 걸어서 체크할 수 없어요", "이번 라운드에는 더 올릴 수 없어요(콜 또는 다이)", "보유 금액이 모자라 재참가할 수 없어요", "카드 두 장을 골라 주세요".
|
||||
|
||||
### 8.3 공개/비공개 정보 (view)
|
||||
|
||||
@@ -401,11 +417,11 @@ interface SeotdaState {
|
||||
|
||||
1. `setup`: 좌석 섞기, 첫 선.
|
||||
2. 매 판·매 재경기 시작: 20장 Fisher-Yates 섞기. 분배는 덱 위에서 순서대로.
|
||||
- 판정, 분할 나머지 칩, 자동 선택은 결정적(난수 없음). 같은 시드 + 같은 액션 열 → 같은 결과.
|
||||
- 판정, 분할 나머지 원, 자동 선택은 결정적(난수 없음). 같은 시드 + 같은 액션 열 → 같은 결과.
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||
|
||||
`deadline`: 베팅 `turnSeconds`(자리 비움 5초), 3장 선택 `turnSeconds + 10`초(동시), 재참가 15초, `handEnd` 4초, 리바이 15초.
|
||||
`deadline`: 베팅 `turnSeconds`(자리 비움 5초), 3장 선택 `turnSeconds + 10`초(동시), 재참가 15초, `handEnd` 5초, 리바이 15초. `turnSeconds=null`(무제한)이면 베팅·3장 선택에는 마감이 없다(자리 비움도 생기지 않음). 재참가·리바이·판 결과 화면은 그대로 시간이 흐른다.
|
||||
|
||||
| 단계 | `onTimeout` 자동 행동 |
|
||||
|---|---|
|
||||
@@ -426,12 +442,12 @@ interface SeotdaResult /* extends GameResult */ {
|
||||
ranking: {
|
||||
playerId: PlayerId;
|
||||
rank: number; // 공동 순위 허용
|
||||
score: number; // hands: 최종 칩 - startingChips × rebuys / lastStanding: 생존 순서(1위=N)
|
||||
score: number; // hands: 최종 보유 금액 - startingChips × rebuys / lastStanding: 생존 순서(1위=N)
|
||||
finalChips: number;
|
||||
rebuys: number;
|
||||
eliminatedAtHand: number | null;
|
||||
}[];
|
||||
summary: string; // 예: "20판 종료. 1위 영희(+860칩), 최고 족보 38광땡"
|
||||
summary: string; // 예: "20판 종료. 1위 영희(+86만원), 최고 족보 38광땡"
|
||||
stats: {
|
||||
handsPlayed: number;
|
||||
rematches: number;
|
||||
@@ -441,30 +457,64 @@ interface SeotdaResult /* extends GameResult */ {
|
||||
}
|
||||
```
|
||||
|
||||
### 8.7 컴퓨터 플레이어 (`bot.ts`, `odds.ts`)
|
||||
|
||||
자기 화면(view)에 보이는 것만 쓴다: 내 패, 방의 덱(20/40장), 각자 든 장 수, 이번 (재)경기의 공개 베팅 기록(`betLog`).
|
||||
|
||||
1. **상대 패 범위**: 베팅 하나하나가 그 사람의 패를 좁힌다. 하프·따당·풀은 센 패 쪽(손에 쥘 수 있는 모든 2장 조합을 "무작위 상대에게 이길 몫" 순으로 줄 세운 백분위로 0.55~0.68 근처), 삥·쿼터는 그보다 약하게, 콜은 "뭔가 있음", 체크는 맨 위를 조금 깎는다(함정 체크). 뻥카(블러프)도 있으니 약한 패도 0.22 이상의 무게를 남긴다. 1장만 들고 한 베팅(1장씩 받는 방의 첫 라운드)은 덜 믿는다. 베팅 규칙 111~444로 억지로 한 하프는 정보가 없다.
|
||||
2. **승률(판돈 몫) 계산**: 남은 카드에서 나올 수 있는 모든 경우(내가 아직 받을 카드 포함, 3장 섯다는 상대의 3장 중 최고 2장)를 범위 무게를 곱해 더한다. 판정은 실제 쇼다운과 같다(땡잡이·암행어사·구사 재경기·동점). 이기면 1, 나누거나 재경기면 1/참가자 수, 지면 0. 맞대결과 대부분의 3명 판은 경우의 수가 3만 개 이하라 **전부 센다**(예: 20장 2장 섯다 맞대결 153가지, 1장 들었을 때 19×153가지). 그보다 크면(4명 이상, 40장 다인원) 같은 방법으로 무작위 3,000판을 뽑아 센다. 한 번 판단에 수 ms(테스트 기준 최대 수십 ms), CPU만 쓴다 — 경우의 수가 작아 GPU가 필요 없다.
|
||||
3. **결정**: 버튼마다 기댓값(원)을 낸다. 다이 0, 체크 = 판돈 × 내 몫, 콜 = 판돈(+뒤에 따라올 사람) × 내 몫 − 콜 금액, 올리기 = 모두 접을 확률 × 판돈 + 아니면 (센 쪽만 남은 상대에 대한 몫) × 커진 판돈 − 건 금액. 접을 확률은 베팅 크기와 그 사람이 이미 보여 준 세기(올렸으면 잘 안 접음)로 정한다. 카드가 더 올 때는 받을 카드마다 "좋으면 계속, 나쁘면 그때 다이"로 한 수 앞을 본다. 레벨(1~60)에 따라 `humanBest`가 가끔 덜 좋은 수를 고른다. 드물게 뻥카(약한 패로 하프), 아주 센 패는 가끔 체크·콜로 기다린다.
|
||||
4. **바보 같은 다이 막기**: 체크가 공짜면 다이하지 않는다. 카드가 더 올 때 콜이 손익분기보다 조금 나쁜 정도면 따라간다(1장만 들었고 올리기가 한 번이면 콜 금액의 80%까지, 올리기가 이어지면 35%까지). 예전 봇은 1장 패를 고정값(0.35~0.5)으로 보고 "콜 금액 비율 + 0.12"와 비교해, 1장만 받은 상태에서 하프 한 번에 절반쯤 다이했다(2026-10-13 사용자 신고, `bot.test.ts`에 20장 × 2~4명 회귀 테스트).
|
||||
5. 3장 섯다 고르기는 세 조합 각각의 판돈 몫을 같은 방법으로 비교해 고른다(예: 구사보다 세륙). 구사 재참가는 (판돈 + 비용)/참가자 수 > 비용이고 비용이 가진 돈의 1/3 이하일 때.
|
||||
|
||||
## 9. UI/UX
|
||||
|
||||
화면 배치(모바일 세로):
|
||||
- 위: 상대 플레이어 원형 배치(닉네임, 스택, 이번 라운드 베팅, 카드 뒷면 장수, "다이"/"올인"/"자리 비움" 뱃지, 선 표시).
|
||||
- 가운데: 판돈 큰 숫자, 재경기 중이면 "재경기 2회차 - 구사" 띠 배너.
|
||||
- 아래: 내 카드 2~3장을 크게(카드 높이 최소 120px), 그 위에 내 족보 이름 큰 글씨(`hints`), 맨 아래 행동 버튼.
|
||||
- PC: 오른쪽에 족보표 상시 표시, 판 기록.
|
||||
한게임 섯다 화면을 본떴다(`apps/web/src/games/seotda/board.tsx`).
|
||||
|
||||
화면 배치:
|
||||
- PC: 나무 테두리의 초록 테이블. 다른 사람 자리는 내 왼쪽 아래에서 위를 돌아 오른쪽 아래까지 둥글게, 내 자리는 테이블 아래 가운데에 크게(패 2~3장, 족보 이름 금색 큰 글씨, 보유 금액). 가운데에 동전 더미와 **판돈** 큰 숫자, 그 밑에 판 수·기본금·현재 콜 금액. 재경기면 "재경기 2회차 · 구사" 띠.
|
||||
- 자리 상자: 아바타, 닉네임, 선 표시, 남은 시간 고리, 보유 금액(만 단위로 줄임), 이번 판에 건 돈, 카드 뒷면, 마지막 행동 말풍선(콜·하프·다이 … 색 구분), 쇼다운 뒤 족보 이름(땡 이상은 금색)과 딴/잃은 금액(+1만 5,000원 / -1만원), 이긴 자리는 금빛 테두리.
|
||||
- 휴대폰: 테이블이 세로로 바뀐다. 위에 다른 사람 자리 2~3열, 가운데 판돈, 아래 내 자리. 버튼은 3열.
|
||||
- 아래: 베팅 버튼 3×2(콜·다이·하프 / 삥·체크·따당, 쿼터·풀을 켜면 한 줄 더). 버튼마다 낼 금액과 숫자 키(PC)를 적는다. 못 누르는 버튼은 흐리게 두고 자리를 바꾸지 않는다(오조작 방지). 마우스를 올리면 "걸고 나면 내 돈 … 판돈 …"을 미리 보여 준다.
|
||||
- 옆 패널: 놀이용 원 안내, 판 정보·시간, 보유 금액 순위, 이번 판 베팅 기록, **족보 도우미**(번호가 작을수록 센 족보, 내 패 줄을 보라색으로 강조, 켜진 특수패만), 판 기록.
|
||||
|
||||
소리와 움직임(내 행동이든 상대·컴퓨터 행동이든 화면 변화에 반응, 한 변화에 한 번만):
|
||||
- 새 판·재경기: 섞는 소리, 카드가 위에서 날아와 놓임(`anim-deal`), 장수만큼 카드 소리.
|
||||
- 베팅: 건 사람 자리에서 판돈으로 동전이 날아가고(`sd-fly`) 칩 소리(베팅이 클수록 동전·소리가 많음), 판돈 숫자가 튐(`anim-bump`). 체크는 짧은 딸깍, 다이는 휙 소리.
|
||||
- 쇼다운: 남은 사람 패가 뒤집힘(`anim-flip`)과 뒤집는 소리, 족보 이름이 튀어나옴. 이어서 판돈에서 이긴 사람 자리로 동전이 날아가고 모으는 소리. 내가 이기면 승리음과 진동, 쇼다운에서 지면 진 소리.
|
||||
- 큰 글자(`anim-banner`): 땡잡이!, 암행어사 출두!, 구사 재경기, 멍텅구리구사 재경기, 같은 족보 재경기, 38광땡!·장땡! 같은 큰 승리. 특수패·광땡·장땡은 팡파르.
|
||||
- 내 차례: 차례 소리와 짧은 진동.
|
||||
|
||||
조작:
|
||||
- 버튼(높이 56px 이상): `다이` `체크` `삥` `콜 (+60)` `따당 (+140)` `쿼터` `하프 (+75)` `풀`. 가능한 버튼만 색 강조, 불가능한 버튼은 흐리게(위치 고정으로 오조작 방지). 금액은 서버 `legalActions` 값.
|
||||
- 3장 섯다 선택: 카드 3장을 누르면 2장이 위로 올라오고, 고른 조합의 족보 이름을 미리 보여 준다. "추천 조합" 버튼(`hints`).
|
||||
- 쇼다운: 남은 사람 패가 동시에 뒤집히고 족보 이름 표시, 특수패 발동 시 "땡잡이!" "암행어사 출두!" 큰 글자 연출(1초), 재경기 시 "구사 재경기" 연출.
|
||||
- 족보표 버튼: 6.1 표를 그림 카드와 함께 표시, 내 현재 족보 줄 강조, 특수패는 켜진 옵션만 표시.
|
||||
- 3장 섯다 선택: 카드 3장을 누르면 2장이 올라오고, 세 조합 버튼(가장 센 조합에 "추천")으로도 고를 수 있다. 고른 조합 이름이 "○○(으)로 정하기" 버튼에 보인다.
|
||||
|
||||
카드 그림(자체 제작 SVG):
|
||||
- 화투 고유 이미지(시판 화투 인쇄 디자인, 특정 게임사 화투 그림)를 복제하지 않는다. 직접 그린 단순 SVG를 쓴다.
|
||||
- 구성: 세로 2:3 카드, 왼쪽 위에 큰 월 숫자(1~10, 고대비), 월별 배경색과 단순화한 식물 아이콘(소나무, 매화, 벚꽃, 등나무, 창포, 모란, 싸리, 억새와 달, 국화, 단풍), 특수 패 표시:
|
||||
- 광: 빨간 원 안에 "광" 글자.
|
||||
- 열끗: 동물 실루엣(꾀꼬리, 두견새, 다리, 나비, 멧돼지, 술잔, 사슴) + 작은 "열" 뱃지. 4·7·9월 열끗은 특수패 재료이므로 뱃지를 더 눈에 띄게.
|
||||
- 일반 패: 띠(가로 리본) 또는 잎 무늬.
|
||||
- 색만으로 구분하지 않고 글자(월 숫자, "광", "열")를 반드시 함께 넣는다. 큰 글씨 모드에서는 월 숫자만 크게 보이는 단순 카드로 전환.
|
||||
### 9.1 화투 그림
|
||||
|
||||
실제 화투 모양을 쓰기로 했다(2026-10-13 사용자 요청 "진짜 화투 이미지"). 처음 계획(직접 그린 단순 SVG)은 버렸다.
|
||||
- 출처: Wikimedia Commons "Category:SVG Hwatu" https://commons.wikimedia.org/wiki/Category:SVG_Hwatu — Marcus Richert가 Louie Mantia, Jr.의 Hanafuda SVG를 바탕으로 한국 화투처럼 다시 칠한 그림(File:Hwatu overview.svg)을 Spenĉjo가 카드별 파일로 나눈 것.
|
||||
- 라이선스: CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). 48장 모두 Commons API로 라이선스를 확인했다(2026-10-13).
|
||||
- 바꾼 점: 좌표 반올림·공백 제거로 크기만 줄였다(그림은 그대로, 원본과 렌더링 비교에서 장마다 평균 픽셀 차이 1.3/255 이하). 변형본도 CC BY-SA 4.0. 출처·라이선스 파일: `apps/web/src/components/cards/hwatu/ATTRIBUTION.txt`. 규칙 화면에도 출처 한 줄을 보인다.
|
||||
- 빌드: `HwatuCard`가 `new URL(`./hwatu/${id}.svg`, import.meta.url)`로 불러 Vite가 해시 붙은 `/assets/` 파일로 내보낸다(외부 URL 없음, 오래 캐시). 카드 오른쪽 위 작은 월 숫자 뱃지는 초보자용으로 우리가 덧붙인다. 카드 뒷면·보너스 패(고스톱)는 직접 그린다.
|
||||
- 고스톱(`gostop`)도 같은 `HwatuCard`를 쓰므로 같은 그림이 나온다(쌍피에는 "쌍피" 꼬리표).
|
||||
- 파일 대응(파일 이름 = 엔진 카드 id = (월−1)×4 + 칸, Commons 파일 "Hwatu <월> <종류>.svg"):
|
||||
|
||||
| 월 | 칸 0 | 칸 1 | 칸 2 | 칸 3 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | `0` January Hikari | `1` January Tanzaku | `2` January Kasu 1 | `3` January Kasu 2 |
|
||||
| 2 | `4` February Tane | `5` February Tanzaku | `6` February Kasu 1 | `7` February Kasu 2 |
|
||||
| 3 | `8` March Hikari | `9` March Tanzaku | `10` March Kasu 1 | `11` March Kasu 2 |
|
||||
| 4 | `12` April Tane | `13` April Tanzaku | `14` April Kasu 1 | `15` April Kasu 2 |
|
||||
| 5 | `16` May Tane | `17` May Tanzaku | `18` May Kasu 1 | `19` May Kasu 2 |
|
||||
| 6 | `20` June Tane | `21` June Tanzaku | `22` June Kasu 1 | `23` June Kasu 2 |
|
||||
| 7 | `24` July Tane | `25` July Tanzaku | `26` July Kasu 1 | `27` July Kasu 2 |
|
||||
| 8 | `28` August Hikari | `29` August Tane | `30` August Kasu 1 | `31` August Kasu 2 |
|
||||
| 9 | `32` September Tane | `33` September Tanzaku | `34` September Kasu 1 | `35` September Kasu 2 |
|
||||
| 10 | `36` October Tane | `37` October Tanzaku | `38` October Kasu 1 | `39` October Kasu 2 |
|
||||
| 11 | `40` November Hikari | `41` November Kasu 2 | `42` November Kasu 1 | `43` November Kasu 3 |
|
||||
| 12 | `44` December Hikari | `45` December Tane | `46` December Tanzaku | `47` December Kasu |
|
||||
|
||||
초보자 도움:
|
||||
- "규칙 보기": 진행 순서, 끗 계산법, 족보표, 특수패 설명, 베팅 용어(학교·삥·따당·하프·다이).
|
||||
- "규칙 보기": 진행 순서, 끗 계산법, 족보표, 특수패 설명, 베팅 용어(기본금·삥·콜·따당·하프·체크·다이, 숫자 키).
|
||||
- 첫 판 말풍선 튜토리얼. 내 차례 진동/소리, 남은 시간 게이지.
|
||||
- 힌트: "지금 패는 5끗이에요. 중간 정도 패예요." 같은 쉬운 문장(강도 3단계: 높음/중간/낮음 색).
|
||||
|
||||
@@ -475,11 +525,11 @@ interface SeotdaResult /* extends GameResult */ {
|
||||
- [ ] 6.4 예시 1~12가 모두 기대 결과와 일치.
|
||||
- [ ] 땡잡이 `strict`: 3월 띠 + 7월 열끗은 일반 망통이며 9땡을 잡지 못함. `loose`면 잡음.
|
||||
- [ ] `loose` 땡잡이 2명 + 5땡 → 땡잡이 두 사람 동점 처리(`tieRule`).
|
||||
- [ ] 구사 재경기: 판돈 유지, 학교 재징수 없음, 참가자는 쇼다운 생존자만(`rejoinCost=none`).
|
||||
- [ ] 구사 재경기 `rejoinCost=half`: 다이한 사람이 판돈 절반(내림)을 내고 참가, 칩이 모자라면 거부, 시간 초과 시 불참.
|
||||
- [ ] 동점 재경기 3연속 후 4번째에는 균등 분할, 나머지 칩은 선에서 가까운 승자.
|
||||
- [ ] 구사 재경기: 판돈 유지, 기본금 재징수 없음, 참가자는 쇼다운 생존자만(`rejoinCost=none`).
|
||||
- [ ] 구사 재경기 `rejoinCost=half`: 다이한 사람이 판돈 절반(내림)을 내고 참가, 보유 금액이 모자라면 거부, 시간 초과 시 불참.
|
||||
- [ ] 동점 재경기 3연속 후 4번째에는 균등 분할, 나머지 원은 선에서 가까운 승자.
|
||||
- [ ] 사이드 팟 + 재경기: A 올인(메인만), 메인에서 A·B 동점, 사이드(B·C)에서 B 단독 승 → 사이드는 즉시 B에게, 메인만 A·B 재경기.
|
||||
- [ ] 베팅: 5.4 예시(학교 30 → 삥 → 하프 35 → 따당 70 → 콜 → 콜) 최종 판돈 240.
|
||||
- [ ] 베팅: 5.4 예시(기본금 30 → 삥 → 하프 35 → 따당 70 → 콜 → 콜) 최종 판돈 240.
|
||||
- [ ] 체크·콜 후 같은 라운드 레이즈 거부, `maxRaise=half`에서 `full` 거부.
|
||||
- [ ] 2차 베팅 첫 행동자: 선이 1차에서 다이했으면 선 다음 좌석의 남은 사람.
|
||||
- [ ] `dealMode=oneRound`: 베팅 1회 후 바로 쇼다운.
|
||||
@@ -489,15 +539,22 @@ interface SeotdaResult /* extends GameResult */ {
|
||||
- [ ] 연결 끊김 상태로 선 차례 → 마감 후 자동 체크/다이, 재접속 후 정상 행동.
|
||||
- [ ] 비밀 누출: 매 단계 모든 시청자(플레이어·관전자) `view`와 이벤트 JSON에 남의 비공개 카드의 월·종류·id가 없음(무작위 시드 1,000판 속성 테스트).
|
||||
- [ ] 다이로 끝난 판: 승자 패도 공개되지 않음.
|
||||
- [ ] 리바이·탈락·점수: `hands` 점수 = 칩 - 시작 칩 × 리바이, `lastStanding` 동시 탈락 순위.
|
||||
- [ ] 칩 보존 불변식: `Σ스택 + Σ팟 + Σ이번 라운드 기여 = 초기 칩 합 + 리바이 합` (재경기 중에도).
|
||||
- [ ] 리바이·탈락·점수: `hands` 점수 = 보유 금액 - 시작 금액 × 리바이, `lastStanding` 동시 탈락 순위.
|
||||
- [ ] 금액 보존 불변식: `Σ스택 + Σ팟 + Σ이번 라운드 기여 = 초기 금액 합 + 리바이 합` (재경기 중에도).
|
||||
- [ ] 재현성: 같은 시드 + 같은 액션 열 → 같은 상태 해시.
|
||||
- [x] 한게임 방식 기본값: 2장 한 번에·베팅 1번, 원 단위(기본금 1만원 × 3명 = 판돈 3만원), 쿼터 없음.
|
||||
- [x] 베팅 규칙 222: 선과 다음 사람은 하프·다이만, 그 뒤 자유. 111에서 선 시간 초과 → 다이.
|
||||
- [x] 40장: 40장 모두 쓰고, 3장 섯다 10명까지. 시간 무제한: 베팅·고르기 마감 없음.
|
||||
- [x] v1(칩) → v2(원) 옮기기: 금액 × 1000, 진행 중 규칙 유지.
|
||||
- [x] 컴퓨터: 맞대결 승률이 직접 센 값과 같음(153가지), 1장 상태 하프에 다이하지 않음(20장 × 2~4명), 비싼 연속 올리기에는 약한 1장이 다이, 하프를 맞은 8끗은 체크를 본 8끗보다 승률이 낮음, 땡잡이는 상대가 세게 걸수록 승률이 오름.
|
||||
|
||||
## 11. 참고 자료
|
||||
|
||||
- 나무위키 "섯다": https://namu.wiki/w/섯다 (20장 구성, 족보 순서, 땡잡이 = 3월 광 + 7월 열끗, 암행어사 = 4월 열끗 + 7월 열끗로 13·18광땡만 잡음, 구사는 상대 최고패가 알리 이하일 때 판돈을 둔 채 재경기, 멍텅구리구사는 8땡까지 재경기·광땡은 불가·지역에 따라 장땡 차이, 다이한 사람이 구사 재경기에 참가하려면 판돈만큼 지불, 같은 족보는 판돈을 둔 채 재대결, 3장 섯다, 베팅 용어 정의)
|
||||
- 한게임 포커 7포커 베팅 방법(공용 한국식 베팅 용어 정의): https://poker.hangame.com/gameguide/poker7/game_7poker2_1.html
|
||||
- 포커 문서 `docs/games/poker.md` 5.2(한국식 베팅), 5.5(사이드 팟), 5.6(리바이).
|
||||
- 한게임 섯다 게임방법(공식 안내, 2026-10-13 확인): https://gostop.hangame.com/gameGuide/gssudda/guide_gssudda01_01.html — 20장/40장, 3장 섯다는 2장 받고 베팅 → 1장 더 받고 베팅, 2장 섯다는 2장을 모두 받고 베팅, 족보·특수 족보(땡잡이 = 3월 + 7월로 9땡 이하를 잡음, 암행어사 = 열자리 4·7로 13·18광땡을 잡고 아니면 1끗, 구사는 알리 이하와 재경기, 멍텅구리 구사는 9땡 이하와 재경기), 베팅 버튼과 숫자 키(콜 7, 삥 4, 다이 8, 체크 5, 따당 1, 하프 0), 베팅룰 일반/111/222/333/444, 게임 화면(나의 패와 족보, 베팅 버튼, 족보도우미, 판돈).
|
||||
- 화투 그림: Wikimedia Commons "Category:SVG Hwatu"(9.1).
|
||||
|
||||
출처 간 차이와 이 문서의 선택:
|
||||
- 멍텅구리구사 범위: "8땡까지"가 기본 서술이고 지역에 따라 장땡까지 무승부로 보기도 한다 → `mungGusa` 옵션, 기본 8땡.
|
||||
@@ -506,10 +563,10 @@ interface SeotdaResult /* extends GameResult */ {
|
||||
|
||||
## 12. 메모 (상표·법적 주의 등)
|
||||
|
||||
- 가상 칩만 사용한다. 방 전용이며 돈·유료 재화·광고 보상과 연결하지 않는다. 칩 거래·선물·누적 랭킹을 만들지 않는다. 결과 화면에 원(₩) 같은 화폐 표현을 쓰지 않는다.
|
||||
- 놀이용 원만 사용한다. 방 전용이며 진짜 돈·유료 재화·광고 보상과 연결하지 않는다. 거래·선물·누적 랭킹을 만들지 않는다. 2026-10-13 사용자 요청으로 한게임 섯다처럼 "원"과 "판돈"이라는 말만 쓰기로 했다(`no-money-wording.test.ts`에서 섯다만 이 두 낱말 예외). ₩ 같은 화폐 기호, 현금·머니·골드, 충전·환전·결제·구매 같은 거래 낱말은 섯다에서도 쓰지 않는다. 옆 패널과 규칙에 "이 방 안에서만 쓰는 놀이용 숫자, 진짜 돈과는 상관없음"을 늘 보인다.
|
||||
- 법적 검토 필요(사용자 확인):
|
||||
- 형법 제246조(도박): 재물을 걸지 않는 구조라 해당하지 않도록 설계했지만, 외부 정산을 부추기는 기능은 넣지 않는다.
|
||||
- 게임산업진흥법 등급분류: 공개 배포하는 게임물은 원칙적으로 등급분류 대상이고, 비영리 예외는 청소년이용불가 기준에 해당하는 내용을 포함하면 적용되지 않는다. 섯다·고스톱·포커 같은 웹보드 게임은 통상 청소년이용불가로 분류되므로 서비스 전 확인이 필요하다.
|
||||
- 어린이 사용자가 있으므로 섯다는 기본 목록과 분리하거나(예: "어른용" 탭) 방장 확인 문구를 두는 방안을 검토한다.
|
||||
- 화투 그림: 화투(하나후다) 전통 도안 자체는 오래된 디자인이지만, 시판 화투나 다른 게임의 그림은 각 제작사의 저작물일 수 있다. 이미지를 가져오지 말고 9장의 지침대로 직접 단순화한 SVG를 그린다.
|
||||
- 명칭: "섯다"는 일반 놀이 이름이라 상표 문제가 적다. 특정 서비스 이름(예: "한게임 섯다", "피망 섯다")은 쓰지 않는다. 표시 이름 후보: "섯다"(기본), 어린이 노출을 줄이고 싶다면 "화투 족보 대결".
|
||||
- 화투 그림: 시판 화투나 다른 게임(한게임 포함)의 그림은 각 제작사의 저작물이라 가져오지 않는다. 대신 자유 라이선스(CC BY-SA 4.0)로 공개된 Wikimedia Commons 그림을 출처 표시와 함께 쓴다(9.1). 바꾼 그림을 다시 내보낼 때도 같은 라이선스로 둔다.
|
||||
- 명칭: "섯다"는 일반 놀이 이름이라 상표 문제가 적다. 특정 서비스 이름(예: "한게임 섯다", "피망 섯다")은 화면에 쓰지 않는다(화면·흐름·용어만 본뜸, 문서에는 참고 출처로만 적음). 표시 이름 후보: "섯다"(기본), 어린이 노출을 줄이고 싶다면 "화투 족보 대결".
|
||||
|
||||
@@ -1494,15 +1494,29 @@ const PLANS: Record<string, Plan> = {
|
||||
},
|
||||
},
|
||||
seotda: {
|
||||
// 3 players, default 2장 섯다 (1장씩 두 번): everyone checks both betting rounds → showdown.
|
||||
// A tie (or 구사) starts a 재경기 with the same pot, so keep checking until the hand result shows up.
|
||||
// 3 players, default 2장 섯다 (2장 한 번에, 베팅 1번): whoever acts first bets 하프 (coins fly to the 판돈),
|
||||
// the others call → showdown. A tie (or 구사) starts a 재경기 with the same 판돈, so keep calling/checking
|
||||
// until the hand result shows up. Screenshots: mid-hand PC/phone (light + dark) and the result.
|
||||
players: 3,
|
||||
drive: async (pages) => {
|
||||
await pressActions(pages, /^(체크|콜)/, 6);
|
||||
await pressActions(pages, /^하프/, 1);
|
||||
await pages[0]!.waitForTimeout(700);
|
||||
for (const p of pages.slice(0, 2)) {
|
||||
const tag = (p.viewportSize()?.width ?? 0) < 600 ? 'phone' : 'pc';
|
||||
await p.screenshot({ path: join(SHOTS, `seotda-mid-${tag}.png`), fullPage: tag === 'phone' });
|
||||
await p.emulateMedia({ colorScheme: 'dark' });
|
||||
await p.waitForTimeout(150);
|
||||
await p.screenshot({ path: join(SHOTS, `seotda-mid-${tag}-dark.png`), fullPage: tag === 'phone' });
|
||||
await p.emulateMedia({ colorScheme: 'light' });
|
||||
}
|
||||
await pressActions(pages, /^(체크|콜)/, 2);
|
||||
for (let extra = 0; extra < 30 && !(await pages[0]!.getByText('이번 판 결과').count()); extra++) {
|
||||
await pressActions(pages, /^(체크|콜)/, 1).catch(() => {});
|
||||
}
|
||||
await finishHand(pages);
|
||||
await pages[0]!.waitForTimeout(600);
|
||||
await pages[0]!.screenshot({ path: join(SHOTS, 'seotda-result-pc.png') });
|
||||
await pages[1]!.screenshot({ path: join(SHOTS, 'seotda-result-phone.png'), fullPage: true });
|
||||
},
|
||||
},
|
||||
poker: {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"./bots/luck": "./src/bots/luck.ts",
|
||||
"./liar/topics": "./src/liar/topics.ts",
|
||||
"./magical-athlete/racers": "./src/magical-athlete/racers.ts",
|
||||
"./seotda/money": "./src/seotda/money.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -2,7 +2,10 @@ import { describe, expect, test } from 'bun:test';
|
||||
import { SEOTDA_DECK, SeededRng, seedN } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { rulesOfView, situation } from './bot';
|
||||
import { evalSeotda, type HandRules } from './hands';
|
||||
import { seotda, type SeotdaAction, type SeotdaOptions, type SeotdaState } from './index';
|
||||
import { odds, shareOf } from './odds';
|
||||
|
||||
/** Special card of a month (1·3·8 광, others 열끗) and the plain card. */
|
||||
const S = (m: number) => (m - 1) * 4;
|
||||
@@ -25,25 +28,121 @@ function rig(s: SeotdaState, cards: Record<string, number[]>, next: number[] = [
|
||||
return s;
|
||||
}
|
||||
const act = (s: SeotdaState, p: string, a: SeotdaAction) => seotda.apply(s, p, a, { rng: SeededRng.fromSeed([7, 7, 7, 7]), now: (clock += 1000) }).state;
|
||||
const decide = (s: SeotdaState, p: string, r = 0.1) => decideBotAction(seotda, s, p, { now: clock, random: () => r }) as SeotdaAction;
|
||||
const decide = (s: SeotdaState, p: string, r = 0.9) => decideBotAction(seotda, s, p, { now: clock, random: () => r }) as SeotdaAction;
|
||||
const RULES: HandRules = { gwangTtaeng: 'all', ttaengjabi: 'loose', amhaeng: true, gusa: true, mungGusa: 'upTo9' };
|
||||
|
||||
describe('승률 계산 (odds): 남은 카드를 전부 따져 봄', () => {
|
||||
test('맞대결은 정확히 전부 셈: 직접 센 값과 같음', () => {
|
||||
for (const mine of [
|
||||
[S(10), P(10)], // 장땡
|
||||
[S(3), P(7)], // 땡잡이
|
||||
[P(4), P(9)], // 구사
|
||||
[S(4), S(7)], // 암행어사
|
||||
[P(2), P(3)], // 5끗
|
||||
]) {
|
||||
const o = odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine, finalSize: 2, opponents: [() => 1] });
|
||||
expect(o.exact).toBe(true);
|
||||
// Brute force with the pure 족보 functions.
|
||||
const rest = SEOTDA_DECK.filter((c) => !mine.includes(c));
|
||||
let sum = 0;
|
||||
let n = 0;
|
||||
for (let i = 0; i < rest.length; i++)
|
||||
for (let j = i + 1; j < rest.length; j++) {
|
||||
sum += shareOf([evalSeotda(mine[0]!, mine[1]!, RULES), evalSeotda(rest[i]!, rest[j]!, RULES)], RULES);
|
||||
n++;
|
||||
}
|
||||
expect(n).toBe(153);
|
||||
expect(o.equity).toBeCloseTo(sum / n, 12);
|
||||
}
|
||||
});
|
||||
|
||||
test('38광땡은 언제나 이김, 망통은 거의 짐', () => {
|
||||
expect(odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine: [S(3), S(8)], finalSize: 2, opponents: [() => 1, () => 1] }).equity).toBe(1);
|
||||
expect(odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine: [P(2), P(8)], finalSize: 2, opponents: [() => 1] }).equity).toBeLessThan(0.05);
|
||||
});
|
||||
|
||||
test('1장만 들고 있으면 둘째 장 19가지를 모두 따져 봄', () => {
|
||||
const o = odds({ rules: RULES, tieRule: 'rematch', deck: SEOTDA_DECK, mine: [S(1)], finalSize: 2, opponents: [() => 1] });
|
||||
expect(o.exact).toBe(true);
|
||||
expect(o.perDraw).toHaveLength(19);
|
||||
expect(o.perDraw.find((d) => d.card === S(8))!.equity).toBeGreaterThan(0.95); // 18광땡
|
||||
expect(o.perDraw.reduce((a, d) => a + d.weight, 0)).toBeCloseTo(1, 9);
|
||||
});
|
||||
|
||||
test('사람이 많아 전부 셀 수 없으면 무작위로 많이 뽑아 셈: 정확한 값과 가까움', () => {
|
||||
const base = { rules: RULES, tieRule: 'rematch' as const, deck: SEOTDA_DECK, mine: [P(2), P(7)], finalSize: 2 as const };
|
||||
const exact = odds({ ...base, opponents: [() => 1, () => 1] });
|
||||
expect(exact.exact).toBe(true);
|
||||
const sampled = odds({ ...base, opponents: [() => 1, () => 1], samples: 3000 });
|
||||
expect(sampled.exact).toBe(false);
|
||||
expect(Math.abs(sampled.equity - exact.equity)).toBeLessThan(0.03);
|
||||
});
|
||||
});
|
||||
|
||||
describe('seotda bot', () => {
|
||||
test('raises a 38광땡', () => {
|
||||
const s = rig(make({ dealMode: 'oneRound' }), { A: [S(3), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] });
|
||||
expect(['half', 'quarter', 'full']).toContain(decide(s, 'A').type);
|
||||
const s = rig(make(), { A: [S(3), S(8)], B: [P(5), P(6)], C: [P(2), P(7)] });
|
||||
expect(['half', 'ping']).toContain(decide(s, 'A').type);
|
||||
});
|
||||
|
||||
test('dies with 망통 facing a half bet, calls it with 장땡', () => {
|
||||
let s = rig(make({ dealMode: 'oneRound' }), { A: [S(3), S(8)], B: [P(2), P(8)], C: [S(10), P(10)] });
|
||||
test('dies with 망통 facing a half bet, calls or raises it with 장땡', () => {
|
||||
let s = rig(make(), { A: [S(3), S(8)], B: [P(2), P(8)], C: [S(10), P(10)] });
|
||||
s = act(s, 'A', { type: 'half' });
|
||||
expect(decide(s, 'B', 0.9).type).toBe('die');
|
||||
expect(decide(s, 'B').type).toBe('die');
|
||||
s = act(s, 'B', { type: 'die' });
|
||||
expect(['call', 'ddadang', 'quarter', 'half']).toContain(decide(s, 'C', 0.9).type);
|
||||
expect(['call', 'ddadang', 'half']).toContain(decide(s, 'C').type);
|
||||
});
|
||||
|
||||
test('checks a weak hand when betting is free (never dies for nothing)', () => {
|
||||
const s = rig(make({ dealMode: 'oneRound' }), { A: [P(2), P(3)], B: [P(5), P(6)], C: [P(2), P(7)] });
|
||||
expect(decide(s, 'A', 0.9).type).toBe('check');
|
||||
const s = rig(make(), { A: [P(2), P(3)], B: [P(5), P(6)], C: [P(2), P(7)] });
|
||||
for (const r of [0.05, 0.5, 0.95]) expect(decide(s, 'A', r).type).not.toBe('die');
|
||||
});
|
||||
|
||||
test('2장 섯다 1장씩: 1장만 받은 상태에서 하프 한 번에 다이하지 않음 (예전 버그)', () => {
|
||||
// 예전 봇은 1장 패를 고정값(0.35)으로 보고 "콜 값 비율 + 0.12"와 비교해, 하프만 나와도 절반쯤 다이했다.
|
||||
const dies: string[] = [];
|
||||
for (const players of [['A', 'B'], ['A', 'B', 'C'], ['A', 'B', 'C', 'D']])
|
||||
for (const first of SEOTDA_DECK) {
|
||||
let s = make({ dealMode: 'twoRounds' }, players);
|
||||
const rest = SEOTDA_DECK.filter((c) => c !== first);
|
||||
s.hand!.cards = Object.fromEntries(players.map((p, i) => [p, p === 'B' ? [first] : [rest[i]!]]));
|
||||
s = act(s, 'A', { type: 'half' });
|
||||
expect(seotda.view(s, 'B').seats.find((x) => x.id === 'B')!.cards).toHaveLength(1);
|
||||
for (const r of [0.1, 0.5, 0.9]) if (decide(s, 'B', r).type === 'die') dies.push(`${players.length}명 ${first}번 ${r}`);
|
||||
}
|
||||
expect(dies).toEqual([]);
|
||||
});
|
||||
|
||||
test('1장 단계라도 하프·따당이 이어져 값이 아주 비싸면 약한 카드는 다이할 수 있음', () => {
|
||||
let s = make({ dealMode: 'twoRounds' }, ['A', 'B', 'C', 'D']);
|
||||
s.hand!.cards = { A: [S(1)], B: [S(8)], C: [S(10)], D: [P(2)] };
|
||||
s = act(s, 'A', { type: 'half' });
|
||||
s = act(s, 'B', { type: 'ddadang' });
|
||||
s = act(s, 'C', { type: 'ddadang' });
|
||||
expect(decide(s, 'D').type).toBe('die');
|
||||
});
|
||||
|
||||
test('상대 베팅으로 상대 패를 좁혀 봄: 하프를 맞은 8끗은 체크를 본 8끗보다 승률이 낮음', () => {
|
||||
const base = rig(make(), { A: [P(5), P(6)], B: [P(3), P(5)], C: [P(2), P(7)] });
|
||||
const checked = act(base, 'A', { type: 'check' });
|
||||
const halved = act(base, 'A', { type: 'half' });
|
||||
const eqCheck = situation(seotda.view(checked, 'B'), 'B', () => 0.5).equity;
|
||||
const eqHalf = situation(seotda.view(halved, 'B'), 'B', () => 0.5).equity;
|
||||
expect(eqHalf).toBeLessThan(eqCheck - 0.05);
|
||||
});
|
||||
|
||||
test('땡잡이는 상대가 세게 걸수록(땡일 가능성이 클수록) 오히려 승률이 오름', () => {
|
||||
const base = rig(make(), { A: [P(5), P(6)], B: [S(3), P(7)], C: [P(2), P(8)] });
|
||||
const checked = act(base, 'A', { type: 'check' });
|
||||
const halved = act(base, 'A', { type: 'half' });
|
||||
const v = seotda.view(halved, 'B');
|
||||
expect(rulesOfView(v.options).ttaengjabi).toBe('loose');
|
||||
expect(situation(v, 'B', () => 0.5).equity).toBeGreaterThan(situation(seotda.view(checked, 'B'), 'B', () => 0.5).equity);
|
||||
});
|
||||
|
||||
test('베팅 규칙 111: 하프·다이만 남으면 센 패는 하프', () => {
|
||||
const s = rig(make({ betRule: '111' }), { A: [S(10), P(10)], B: [P(5), P(6)], C: [P(2), P(7)] });
|
||||
expect(decide(s, 'A').type).toBe('half');
|
||||
});
|
||||
|
||||
test('3장 섯다: keeps the best pair of its three cards', () => {
|
||||
@@ -52,19 +151,21 @@ describe('seotda bot', () => {
|
||||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||||
expect(s.hand!.phase).toBe('choose');
|
||||
const a = decide(s, 'A') as Extract<SeotdaAction, { type: 'choose' }>;
|
||||
expect([...a.cardIds].sort((x, y) => x - y)).toEqual([P(4), P(6)]); // 세륙 over 구사·5끗
|
||||
expect([...a.cardIds].sort((x, y) => x - y)).toEqual([P(4), P(6)]); // 세륙 over 구사·3끗
|
||||
});
|
||||
|
||||
test.each([
|
||||
['2장 섯다', {}],
|
||||
['2장 섯다(한 번에)', {}],
|
||||
['2장 섯다(1장씩)', { dealMode: 'twoRounds' }],
|
||||
['3장 섯다', { cardMode: 'three' }],
|
||||
] as const)('%s: 1 human + 3 bots finish without bot timeouts', (_, options) => {
|
||||
['40장', { deck: 40 }],
|
||||
] as const)('%s: 1 human + 3 bots finish without bot timeouts, fast', (_, options) => {
|
||||
const opts = seotda.optionsSchema.parse(options);
|
||||
for (let s = 1; s <= 2; s++) {
|
||||
const r = botPlayout(seotda, { players: ['human', 'bot:1', 'bot:2', 'bot:3'], options: opts, seed: seedN(s), isBot: (p) => p.startsWith('bot:') });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
expect(r.maxBotMs).toBeLessThan(100);
|
||||
expect(r.maxBotMs).toBeLessThan(150);
|
||||
}
|
||||
});
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
/**
|
||||
* 섯다 computer player: a cautious beginner that bets by the strength of its own cards.
|
||||
* Strong 족보 raise, middling ones call cheap bets, weak ones check or die; an occasional small bluff.
|
||||
* Uses only its own view (own cards, pot, legal bet amounts) and the pure 족보 helpers.
|
||||
* 섯다 computer player (docs/games/seotda.md §8.7). It thinks like a careful player, using only its own screen:
|
||||
*
|
||||
* 1. Ranges: every bet it saw narrows what that opponent may hold — a 하프·따당 usually means a strong hand (but people
|
||||
* bluff, so weak hands keep some weight), a call means "something", a check caps the very top a little. Forced bets of
|
||||
* 베팅 규칙 111~444 say nothing.
|
||||
* 2. Odds: `odds` enumerates every way the unseen cards can fall (the cards still to come included — with one card in
|
||||
* hand it also counts all its own second cards) and adds up its share of the pot, special hands included.
|
||||
* 3. Decision: each legal bet gets an expected value from that share, the pot, the price and how likely the others are to
|
||||
* fold; the level (`humanBest`) adds the human-like slips. A small bluff now and then, a trap with a monster now and
|
||||
* then. It never dies when checking is free, and with a card still to come it keeps cheap hands (the old bug: it died
|
||||
* after one card because a fixed "one card = weak" guess was compared with the price).
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { pick, typeOf } from '../bots/policy';
|
||||
import { evalSeotda, isGwang, monthOf, type HandRules } from './hands';
|
||||
import type { SeotdaAction, SeotdaView } from './index';
|
||||
import { humanBest, pick, typeOf } from '../bots/policy';
|
||||
import type { HandRules } from './hands';
|
||||
import { deckOf, type BetType, type SeotdaAction, type SeotdaView } from './index';
|
||||
import { cardsKey, odds, strengthPercentile, type Odds, type RangeWeight } from './odds';
|
||||
|
||||
type Bet = SeotdaView['legal'][number];
|
||||
|
||||
const rulesOf = (o: SeotdaView['options']): HandRules => ({
|
||||
export const rulesOfView = (o: SeotdaView['options']): HandRules => ({
|
||||
gwangTtaeng: o.gwangTtaeng,
|
||||
ttaengjabi: o.ttaengjabi,
|
||||
amhaeng: o.amhaeng,
|
||||
@@ -18,95 +27,233 @@ const rulesOf = (o: SeotdaView['options']): HandRules => ({
|
||||
mungGusa: o.gusa ? o.mungGusa : 'off',
|
||||
});
|
||||
|
||||
/** Rough winning chance (0..1) of a 2-card hand; specials count for what they can do. */
|
||||
export function pairStrength(a: number, b: number, rules: HandRules): number {
|
||||
const e = evalSeotda(a, b, rules);
|
||||
let s: number;
|
||||
if (e.value >= 980) s = 0.96 + (e.value - 980) / 500; // 광땡
|
||||
else if (e.value >= 901) s = 0.8 + (e.value - 900) * 0.015; // 땡
|
||||
else if (e.value >= 801) s = 0.6 + (e.value - 801) * 0.025; // 알리 … 세륙
|
||||
else s = 0.12 + e.value * 0.045; // 망통 0.12 … 갑오 0.53
|
||||
if (e.special === 'ttaengjabi' || e.special === 'gusa') s = Math.max(s, 0.4);
|
||||
if (e.special === 'mungGusa') s = Math.max(s, 0.5);
|
||||
if (e.special === 'amhaeng') s = Math.max(s, 0.3);
|
||||
return s;
|
||||
const RAISES: BetType[] = ['ping', 'quarter', 'half', 'ddadang', 'full'];
|
||||
/** How strong a raise of this size usually is (percentile the range centres on). */
|
||||
const RAISE_T: Partial<Record<BetType, number>> = { ping: 0.35, quarter: 0.45, half: 0.55, ddadang: 0.6, full: 0.68 };
|
||||
const sigmoid = (x: number) => 1 / (1 + Math.exp(-x));
|
||||
|
||||
const myCardsOf = (v: SeotdaView, me: string): number[] =>
|
||||
(v.seats.find((s) => s.id === me)?.cards ?? []).flatMap((c) => ('id' in c ? [c.id] : []));
|
||||
|
||||
const finalSizeOf = (v: SeotdaView): 2 | 3 => (v.options.cardMode === 'three' ? 3 : 2);
|
||||
|
||||
/** Opponents still in the hand, each with a range built from the public bets of this (re)match. */
|
||||
export function rangesOf(v: SeotdaView, me: string): { id: string; weight: RangeWeight }[] {
|
||||
const rules = rulesOfView(v.options);
|
||||
const deck = deckOf(v.options);
|
||||
const finalSize = finalSizeOf(v);
|
||||
const forced = v.options.betRule === 'free' ? 0 : Number(v.options.betRule[0]);
|
||||
const live = v.seats.filter((s) => s.id !== me && s.inHand && !s.folded);
|
||||
// Which log entries were forced (the first `forced` actions of the first round).
|
||||
let firstRound = 0;
|
||||
const entries = v.betLog.map((e) => {
|
||||
const isForced = e.street === 0 && firstRound++ < forced;
|
||||
return { ...e, forced: isForced };
|
||||
});
|
||||
// Cards held when the bet was made: 2장 섯다 1장씩 → 1 card on street 0; 3장 섯다 → 2 of 3 on street 0.
|
||||
const partialStreet0 = v.options.cardMode === 'three' || v.options.dealMode === 'twoRounds';
|
||||
return live.map((s) => {
|
||||
const mine = entries.filter((e) => e.p === s.id && !e.forced);
|
||||
if (!mine.length) return { id: s.id, weight: () => 1 };
|
||||
const memo = new Map<number, number>();
|
||||
const weight: RangeWeight = (cards) => {
|
||||
const key = cardsKey(cards);
|
||||
const hit = memo.get(key);
|
||||
if (hit !== undefined) return hit;
|
||||
const p = strengthPercentile(cards, rules, deck, finalSize);
|
||||
let w = 1;
|
||||
let raises = 0;
|
||||
for (const e of mine) {
|
||||
// A bet made with fewer cards tells less about the final hand.
|
||||
const blur = partialStreet0 && e.street === 0 ? 0.5 : 1;
|
||||
if (RAISES.includes(e.t)) {
|
||||
const t = (RAISE_T[e.t] ?? 0.5) + 0.05 * raises;
|
||||
raises++;
|
||||
const bluff = 0.22 + (1 - blur) * 0.4;
|
||||
w *= bluff + (1 - bluff) * sigmoid((p - t) / 0.09);
|
||||
} else if (e.t === 'call') {
|
||||
const bluff = 0.45 + (1 - blur) * 0.3;
|
||||
w *= bluff + (1 - bluff) * sigmoid((p - 0.25) / 0.1);
|
||||
} else if (e.t === 'check') {
|
||||
// Strong hands check now and then to trap: cap the top a little.
|
||||
w *= 1 - 0.3 * blur * sigmoid((p - 0.85) / 0.05);
|
||||
}
|
||||
}
|
||||
memo.set(key, w);
|
||||
return w;
|
||||
};
|
||||
return { id: s.id, weight };
|
||||
});
|
||||
}
|
||||
|
||||
/** Strength from the cards I hold right now (1 card in 2장 섯다's first round, 2 of 3 before choosing). */
|
||||
function strength(cards: number[], rules: HandRules, threeMode: boolean): number {
|
||||
if (cards.length === 1) {
|
||||
const c = cards[0]!;
|
||||
const m = monthOf(c);
|
||||
// 광 and 10월 lead to the big hands; 1·4 to 알리/독사/세륙 and friends.
|
||||
return isGwang(c) || m === 10 ? 0.5 : m === 1 || m === 4 ? 0.45 : 0.35;
|
||||
export interface Situation {
|
||||
equity: number;
|
||||
/** One card still to come: my equity for each card I may get. */
|
||||
perDraw: Odds['perDraw'];
|
||||
/** Cards still to come for me (or the 3장 섯다 third card). */
|
||||
drawing: boolean;
|
||||
exact: boolean;
|
||||
}
|
||||
|
||||
export function situation(v: SeotdaView, me: string, random: () => number): Situation {
|
||||
const finalSize = finalSizeOf(v);
|
||||
const all = myCardsOf(v, me);
|
||||
// 3장 섯다 after the secret choice: my hand is the chosen pair, the thrown card is out of play.
|
||||
const chosen = v.myChosen;
|
||||
const mine = chosen ? [...chosen] : all;
|
||||
const ranges = rangesOf(v, me);
|
||||
const o = odds({
|
||||
rules: rulesOfView(v.options),
|
||||
tieRule: v.options.tieRule,
|
||||
deck: deckOf(v.options),
|
||||
mine,
|
||||
dead: chosen ? all.filter((c) => !chosen.includes(c)) : [],
|
||||
finalSize: chosen ? 2 : finalSize,
|
||||
oppSize: finalSize,
|
||||
opponents: ranges.map((r) => r.weight),
|
||||
random,
|
||||
});
|
||||
return { equity: o.equity, perDraw: o.perDraw, drawing: mine.length < (chosen ? 2 : finalSize), exact: o.exact };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the rest of the hand is worth to me once the pot is `pot`, before I put in more: with a card still to come I look
|
||||
* at every card I may get — a good one plays on (and may face a 하프 of about half the pot), a bad one dies there and
|
||||
* loses nothing more. `scale` < 1 when only the stronger part of the others' range is still in.
|
||||
*/
|
||||
function continuation(sit: Situation, pot: number, scale = 1): number {
|
||||
const play = (e: number) => {
|
||||
const bet = 0.5 * pot;
|
||||
// Half the time nobody bets on the last round; otherwise I call a 하프 only when it pays.
|
||||
return 0.5 * e * pot + 0.5 * Math.max(0, e * (pot + 2 * bet) - bet);
|
||||
};
|
||||
if (!sit.drawing || !sit.perDraw.length) return Math.min(1, sit.equity * scale) * pot;
|
||||
let v = 0;
|
||||
for (const d of sit.perDraw) v += d.weight * play(Math.min(1, d.equity * scale));
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Expected value (in 원) of each legal bet, from my share of the pot and the others' likely answers. */
|
||||
export function betValues(v: SeotdaView, me: string, sit: Situation): Map<BetType, number> {
|
||||
const pot = Math.max(1, v.pot);
|
||||
const others = v.seats.filter((s) => s.id !== me && s.inHand && !s.folded);
|
||||
const canAct = others.filter((s) => !s.allIn);
|
||||
// Players who still have to answer this round's bet (no action yet on this street).
|
||||
const yetToAct = canAct.filter((s) => !s.lastAction).length;
|
||||
const out = new Map<BetType, number>();
|
||||
for (const b of v.legal) {
|
||||
switch (b.type) {
|
||||
case 'die':
|
||||
out.set('die', 0);
|
||||
break;
|
||||
case 'check':
|
||||
// Free: whatever my share of the pot is (tiny edge so it always beats dying).
|
||||
out.set('check', continuation(sit, pot) + 0.001 * pot);
|
||||
break;
|
||||
case 'call': {
|
||||
const extra = yetToAct * 0.5 * b.amount; // later players calling too
|
||||
out.set('call', continuation(sit, pot + b.amount + extra) - b.amount);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
// A raise of b.amount: each opponent who can act folds with some chance — more often to bigger bets, much less
|
||||
// often when it has raised this hand itself (it showed strength) or already called.
|
||||
const size = b.amount / (pot + b.amount);
|
||||
const foldOf = (id: string) => {
|
||||
const acts = v.betLog.filter((e) => e.p === id).map((e) => e.t);
|
||||
const showed = acts.some((t) => RAISES.includes(t) && t !== 'ping') ? 0.35 : acts.includes('call') || acts.includes('ping') ? 0.7 : 1;
|
||||
return Math.min(0.6, Math.max(0.03, (0.1 + 0.8 * size) * showed));
|
||||
};
|
||||
const folds = canAct.map((s) => foldOf(s.id));
|
||||
const allFold = folds.length ? folds.reduce((a, f) => a * f, 1) : 0;
|
||||
const meanFold = folds.length ? folds.reduce((a, f) => a + f, 0) / folds.length : 0;
|
||||
// Those who call are the stronger part of their range: my share against them drops.
|
||||
const scale = 0.85 - 0.05 * Math.min(3, Math.max(0, canAct.length - 1));
|
||||
const callers = Math.max(1, canAct.length * (1 - meanFold));
|
||||
const called = continuation(sit, pot + b.amount + callers * b.amount * 0.8, scale) - b.amount;
|
||||
out.set(b.type, allFold * pot + (1 - allFold) * called);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let s = 0;
|
||||
for (let i = 0; i < cards.length; i++) for (let j = i + 1; j < cards.length; j++) s = Math.max(s, pairStrength(cards[i]!, cards[j]!, rules));
|
||||
// 3장 섯다 first round: a third card is still coming.
|
||||
return threeMode && cards.length === 2 ? Math.min(1, s + 0.06) : s;
|
||||
return out;
|
||||
}
|
||||
|
||||
export const seotdaBot: BotStrategy<SeotdaView, SeotdaAction> = ({ me, view, legal, random }) => {
|
||||
const rules = rulesOf(view.options);
|
||||
const mine = view.seats.find((x) => x.id === me);
|
||||
const cards = (mine?.cards ?? []).flatMap((c) => ('id' in c ? [c.id] : []));
|
||||
export const seotdaBot: BotStrategy<SeotdaView, SeotdaAction> = ({ me, view: v, legal, random, level }) => {
|
||||
const rules = rulesOfView(v.options);
|
||||
const mine = v.seats.find((x) => x.id === me);
|
||||
const first = legal[0]!;
|
||||
|
||||
switch (typeOf(first)) {
|
||||
case 'ready':
|
||||
return first;
|
||||
case 'rebuy':
|
||||
// Keep playing: take the chips while rebuys remain.
|
||||
return { type: 'rebuy', accept: true };
|
||||
case 'rejoin': {
|
||||
// Pay into a 구사 rematch only when it is cheap compared to the pot.
|
||||
const cheap = !!view.rejoin && view.rejoin.cost <= Math.min(view.pot / 3, (mine?.stack ?? 0) / 5);
|
||||
return legal.find((a) => a.type === 'rejoin' && a.accept === cheap) ?? first;
|
||||
// 구사 재경기: pay in when my even share of the bigger pot is worth the price.
|
||||
const r = v.rejoin;
|
||||
if (!r || !r.canAfford) return legal.find((a) => a.type === 'rejoin' && !a.accept) ?? first;
|
||||
const k = (v.seats.filter((s) => s.inHand && !s.folded).length || 2) + 1;
|
||||
const join = (v.pot + r.cost) / k - r.cost > 0 && r.cost <= (mine?.stack ?? 0) / 3;
|
||||
return legal.find((a) => a.type === 'rejoin' && a.accept === join) ?? first;
|
||||
}
|
||||
case 'choose': {
|
||||
// 3장 섯다: keep the pair with the best chance (specials such as 땡잡이 included).
|
||||
// 3장 섯다: keep the pair with the best share of the pot against what the others may hold (specials included).
|
||||
const chooses = legal.filter((a): a is Extract<SeotdaAction, { type: 'choose' }> => a.type === 'choose');
|
||||
let top = chooses[0]!;
|
||||
for (const c of chooses) if (pairStrength(c.cardIds[0], c.cardIds[1], rules) > pairStrength(top.cardIds[0], top.cardIds[1], rules)) top = c;
|
||||
return top;
|
||||
const all = myCardsOf(v, me);
|
||||
const pairScore = (c: Extract<SeotdaAction, { type: 'choose' }>) => pairEquity(v, me, c.cardIds, all, random);
|
||||
return humanBest(chooses, pairScore, random, level, { small: 0.02, critical: 2 });
|
||||
}
|
||||
}
|
||||
|
||||
// Betting.
|
||||
const s = strength(cards, rules, view.options.cardMode === 'three');
|
||||
const bets = view.legal;
|
||||
const by = (t: string) => bets.find((b) => b.type === t);
|
||||
const act = (b: Bet | undefined) => (b ? (legal.find((a) => a.type === b.type) ?? null) : null);
|
||||
const stack = mine?.stack ?? 0;
|
||||
const call = by('call');
|
||||
const toCall = call?.amount ?? 0;
|
||||
const pot = Math.max(view.pot, 1);
|
||||
// Raises that keep chips behind unless the hand is a monster.
|
||||
const raises = bets.filter((b) => ['ping', 'ddadang', 'quarter', 'half', 'full'].includes(b.type) && (!b.allIn || s >= 0.85));
|
||||
const raise = (big: boolean) => {
|
||||
const order = big ? ['half', 'full', 'ddadang', 'quarter', 'ping'] : ['ping', 'quarter', 'ddadang', 'half'];
|
||||
for (const t of order) {
|
||||
const b = raises.find((r) => r.type === t);
|
||||
if (b) return act(b);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
if (!call) {
|
||||
// Free to check (or open the betting).
|
||||
if (s >= 0.75) return raise(true) ?? act(by('check'))!;
|
||||
if ((s >= 0.5 && random() < 0.5) || random() < 0.08) return raise(false) ?? act(by('check'))!;
|
||||
return act(by('check')) ?? act(by('die'))!;
|
||||
const sit = situation(v, me, random);
|
||||
const values = betValues(v, me, sit);
|
||||
const has = (t: BetType) => values.has(t);
|
||||
const potNow = Math.max(1, v.pot);
|
||||
// With a card still to come nothing is settled yet: stay in unless the price is clearly wrong (the 1장 다이 bug: the old
|
||||
// bot died to a single 하프 after one card). How much worse than break-even a call may be, as a share of its price:
|
||||
// generous against one raise (it was made on one card too), much less when raise follows raise.
|
||||
const call = v.legal.find((b) => b.type === 'call');
|
||||
if (sit.drawing && call && has('call')) {
|
||||
const raisesNow = v.betLog.filter((e) => e.street === v.street && e.p !== me && RAISES.includes(e.t)).length;
|
||||
const single = myCardsOf(v, me).length === 1;
|
||||
const tolerance = raisesNow <= 1 ? (single ? 0.8 : 0.4) : single ? 0.35 : 0.2;
|
||||
if (values.get('call')! > -tolerance * call.amount) values.set('call', Math.max(values.get('call')!, 0.002 * potNow));
|
||||
}
|
||||
// Facing a bet: raise monsters, call when the hand is worth the price, otherwise die.
|
||||
if (s >= 0.8 && random() < 0.7) {
|
||||
const r = raise(true);
|
||||
if (r) return r;
|
||||
}
|
||||
const price = toCall / (pot + toCall);
|
||||
const allInCall = call.allIn || toCall >= stack;
|
||||
const worth = allInCall ? s >= 0.6 : s >= Math.max(0.3, price + 0.12);
|
||||
const cheapBluff = toCall <= view.baseUnit && random() < 0.3;
|
||||
if (worth || cheapBluff) return act(call)!;
|
||||
return act(by('die')) ?? pick(legal, random);
|
||||
let pickType: BetType;
|
||||
const choices = [...values.keys()];
|
||||
pickType = humanBest(choices, (t) => values.get(t)!, random, level, { small: 0.04 * potNow, critical: Number.POSITIVE_INFINITY });
|
||||
const raises = choices.filter((t) => RAISES.includes(t));
|
||||
// A small bluff: rarely, a weak hand raises into players who showed no strength.
|
||||
const quiet = v.betLog.every((e) => e.p === me || !['half', 'ddadang', 'full', 'quarter'].includes(e.t));
|
||||
const opp = v.seats.filter((s) => s.id !== me && s.inHand && !s.folded).length;
|
||||
if (raises.length && quiet && sit.equity < 0.35 && random() < 0.1 / opp) pickType = raises.includes('half') ? 'half' : raises[0]!;
|
||||
// A trap: a monster sometimes just checks / calls to keep the others in.
|
||||
if (sit.equity > 0.9 && random() < 0.2 && (has('check') || has('call'))) pickType = has('check') ? 'check' : 'call';
|
||||
// Never die when checking is free (it can only lose the pot it already put in).
|
||||
if (pickType === 'die' && has('check')) pickType = 'check';
|
||||
const chosen: Bet | undefined = v.legal.find((b) => b.type === pickType);
|
||||
const action = chosen ? legal.find((a) => a.type === chosen.type) : undefined;
|
||||
return action ?? legal.find((a) => a.type === 'check') ?? pick(legal, random);
|
||||
};
|
||||
|
||||
/** Share of the pot of one 2-card choice (3장 섯다) against the others' possible final hands. */
|
||||
function pairEquity(v: SeotdaView, me: string, pair: [number, number], all: number[], random: () => number): number {
|
||||
const rules = rulesOfView(v.options);
|
||||
const thrown = all.filter((x) => !pair.includes(x));
|
||||
const ranges = rangesOf(v, me);
|
||||
// The others hold 3 cards each (best 2); my pair is fixed and my thrown card is out of their reach.
|
||||
return odds({
|
||||
rules,
|
||||
tieRule: v.options.tieRule,
|
||||
deck: deckOf(v.options),
|
||||
mine: [...pair],
|
||||
dead: thrown,
|
||||
finalSize: 2,
|
||||
oppSize: 3,
|
||||
opponents: ranges.map((r) => r.weight),
|
||||
random,
|
||||
samples: 1200,
|
||||
}).equity;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
/** 섯다 (docs/games/seotda.md). Chips are room-only play points (§12). */
|
||||
/**
|
||||
* 섯다 (docs/games/seotda.md), 한게임 섯다 방식. Amounts are 원 of room-only play money (놀이용 게임머니, §12):
|
||||
* no real value, no exchange. Internal names (`stack`, `startingChips`, `baseUnit`) predate the 원 wording.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
HWATU,
|
||||
@@ -26,29 +29,51 @@ import {
|
||||
type Rng,
|
||||
} from '@bg/engine';
|
||||
import { bestChoice, combos, evalSeotda, hintText, resolve, strengthOf, type HandEval, type HandRules, type SpecialKind } from './hands';
|
||||
import { formatWon, formatWonDelta } from './money';
|
||||
|
||||
export * from './hands';
|
||||
export * from './money';
|
||||
|
||||
const lit = <T extends number>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
/** Starting money (원). Before 2026-10-13 rooms stored chips (500 … 5000); those fall back to the default (`.catch`). */
|
||||
export const STARTING_MONEY = [500_000, 1_000_000, 2_000_000, 5_000_000] as const;
|
||||
/** 기본금 = 판마다 모두 내는 돈 = 삥 (원). */
|
||||
export const BASE_MONEY = [2_000, 10_000, 20_000, 50_000] as const;
|
||||
|
||||
export const seotdaOptionsSchema = z
|
||||
.object({
|
||||
cardMode: z
|
||||
.enum(['two', 'three'])
|
||||
.default('two')
|
||||
.meta({ title: '카드 수', labels: { two: '2장 섯다', three: '3장 섯다(3장 받아 2장 고르기)' } }),
|
||||
.meta({ title: '게임 방식', labels: { two: '2장 섯다', three: '3장 섯다(3장 받아 2장 고르기)' } }),
|
||||
dealMode: z
|
||||
.enum(['twoRounds', 'oneRound'])
|
||||
.default('twoRounds')
|
||||
.meta({ title: '2장 섯다 나눠 주기', labels: { twoRounds: '1장씩 두 번(베팅 2번)', oneRound: '2장 한 번에(베팅 1번)' } }),
|
||||
startingChips: lit(500, 1000, 2000, 5000)
|
||||
.default(1000)
|
||||
.meta({ title: '시작 칩', labels: { 500: '500칩', 1000: '1,000칩', 2000: '2,000칩', 5000: '5,000칩' } }),
|
||||
baseUnit: lit(2, 10, 20, 50)
|
||||
.default(10)
|
||||
.meta({ title: '학교(기본 칩) = 삥', labels: { 2: '2칩', 10: '10칩', 20: '20칩', 50: '50칩' } }),
|
||||
maxRaise: z.enum(['half', 'full']).default('half').meta({ title: '최대 레이즈', labels: { half: '하프까지', full: '풀까지' } }),
|
||||
.enum(['oneRound', 'twoRounds'])
|
||||
.default('oneRound')
|
||||
.meta({ title: '2장 섯다 패 받기', labels: { oneRound: '2장 한 번에 받고 베팅 1번', twoRounds: '1장씩 두 번 받고 베팅 2번' } }),
|
||||
deck: lit(20, 40)
|
||||
.default(20)
|
||||
.catch(20)
|
||||
.meta({ title: '화투 장수', labels: { 20: '20장(1~10월 2장씩)', 40: '40장(1~10월 4장씩)' } }),
|
||||
startingChips: lit(...STARTING_MONEY)
|
||||
.default(1_000_000)
|
||||
.catch(1_000_000)
|
||||
.meta({ title: '시작 금액', labels: { 500000: '50만원', 1000000: '100만원', 2000000: '200만원', 5000000: '500만원' } }),
|
||||
baseUnit: lit(...BASE_MONEY)
|
||||
.default(10_000)
|
||||
.catch(10_000)
|
||||
.meta({ title: '기본금(판마다 내는 돈, 삥)', labels: { 2000: '2,000원', 10000: '1만원', 20000: '2만원', 50000: '5만원' } }),
|
||||
betRule: z
|
||||
.enum(['free', '111', '222', '333', '444'])
|
||||
.default('free')
|
||||
.catch('free')
|
||||
.meta({
|
||||
title: '베팅 규칙',
|
||||
labels: { free: '일반 베팅', 111: '111(선은 하프·다이만)', 222: '222(앞 2명 하프·다이만)', 333: '333(앞 3명 하프·다이만)', 444: '444(앞 4명 하프·다이만)' },
|
||||
}),
|
||||
maxRaise: z.enum(['half', 'full']).default('half').meta({ title: '최대 베팅', labels: { half: '하프까지', full: '풀(판돈만큼)까지' } }),
|
||||
quarter: z.boolean().default(false).catch(false).meta({ title: '쿼터 베팅 버튼' }),
|
||||
endCondition: z
|
||||
.enum(['hands', 'lastStanding'])
|
||||
.default('hands')
|
||||
@@ -58,15 +83,17 @@ export const seotdaOptionsSchema = z
|
||||
.meta({ title: '총 판 수(재경기 제외)', labels: { 10: '10판', 20: '20판', 30: '30판', 50: '50판' } }),
|
||||
schoolUpEvery: lit(0, 5, 10, 15)
|
||||
.default(0)
|
||||
.meta({ title: '학교 2배로 올리기', labels: { 0: '안 올림', 5: '5판마다', 10: '10판마다', 15: '15판마다' } }),
|
||||
.meta({ title: '기본금 2배로 올리기', labels: { 0: '안 올림', 5: '5판마다', 10: '10판마다', 15: '15판마다' } }),
|
||||
rebuy: z
|
||||
.enum(['off', 'limited', 'unlimited'])
|
||||
.default('unlimited')
|
||||
.meta({ title: '칩 다시 받기(리바이)', labels: { off: '안 함(탈락)', limited: '횟수 제한', unlimited: '무제한' } }),
|
||||
.meta({ title: '원을 다 잃으면 다시 받기(리바이)', labels: { off: '안 함(탈락)', limited: '횟수 제한', unlimited: '무제한' } }),
|
||||
rebuyLimit: lit(1, 2, 3).default(1).meta({ title: '리바이 횟수(1인당)', labels: { 1: '1번', 2: '2번', 3: '3번' } }),
|
||||
turnSeconds: lit(15, 20, 30, 60)
|
||||
turnSeconds: z
|
||||
.union([z.literal(15), z.literal(20), z.literal(30), z.literal(60), z.literal(null)])
|
||||
.default(20)
|
||||
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
||||
.catch(20)
|
||||
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||
dealerRule: z.enum(['winner', 'rotate']).default('winner').meta({ title: '다음 판의 선', labels: { winner: '이긴 사람', rotate: '돌아가며' } }),
|
||||
gwangTtaeng: z
|
||||
.enum(['all', 'only38'])
|
||||
@@ -74,20 +101,20 @@ export const seotdaOptionsSchema = z
|
||||
.meta({ title: '광땡 종류', labels: { all: '38·18·13광땡', only38: '38광땡만' } }),
|
||||
ttaengjabi: z
|
||||
.enum(['off', 'strict', 'loose'])
|
||||
.default('strict')
|
||||
.meta({ title: '땡잡이(3·7)', labels: { off: '없음', strict: '3월 광 + 7월 열끗', loose: '3월 + 7월 아무 패' } }),
|
||||
.default('loose')
|
||||
.meta({ title: '땡잡이(3·7)', labels: { off: '없음', strict: '3월 광 + 7월 열끗만', loose: '3월 + 7월 아무 패' } }),
|
||||
amhaeng: z.boolean().default(true).meta({ title: '암행어사(4·7 열끗)' }),
|
||||
gusa: z.boolean().default(true).meta({ title: '구사 재경기(4·9)' }),
|
||||
mungGusa: z
|
||||
.enum(['off', 'upTo8', 'upTo9', 'upToJang'])
|
||||
.default('upTo8')
|
||||
.default('upTo9')
|
||||
.meta({ title: '멍텅구리구사 재경기 범위', labels: { off: '일반 구사로', upTo8: '8땡까지', upTo9: '9땡까지', upToJang: '장땡까지' } }),
|
||||
tieRule: z.enum(['rematch', 'split']).default('rematch').meta({ title: '같은 족보일 때', labels: { rematch: '재경기', split: '나눠 가짐' } }),
|
||||
rejoinCost: z
|
||||
.enum(['none', 'half', 'full'])
|
||||
.default('none')
|
||||
.meta({ title: '구사 재경기 때 다이한 사람', labels: { none: '참가 불가', half: '모인 칩 절반 내고 참가', full: '모인 칩만큼 내고 참가' } }),
|
||||
hints: z.boolean().default(true).meta({ title: '내 족보 이름·족보표 강조' }),
|
||||
.meta({ title: '구사 재경기 때 다이한 사람', labels: { none: '참가 불가', half: '판돈 절반 내고 참가', full: '판돈만큼 내고 참가' } }),
|
||||
hints: z.boolean().default(true).meta({ title: '족보 도우미(내 족보 이름·족보표 표시)' }),
|
||||
maxRematches: lit(1, 2, 3, 5)
|
||||
.default(3)
|
||||
.meta({ title: '한 판의 재경기 최대 횟수(넘으면 나눠 가짐)', labels: { 1: '1번', 2: '2번', 3: '3번', 5: '5번' } }),
|
||||
@@ -97,7 +124,7 @@ export const seotdaOptionsSchema = z
|
||||
})
|
||||
.superRefine((o, ctx) => {
|
||||
if (o.baseUnit * 20 > o.startingChips) {
|
||||
ctx.addIssue({ code: 'custom', path: ['baseUnit'], message: '학교는 시작 칩의 20분의 1 이하여야 해요.' });
|
||||
ctx.addIssue({ code: 'custom', path: ['baseUnit'], message: '기본금은 시작 금액의 20분의 1 이하여야 해요.' });
|
||||
}
|
||||
});
|
||||
export type SeotdaOptions = z.infer<typeof seotdaOptionsSchema>;
|
||||
@@ -192,6 +219,17 @@ export interface SeotdaHand {
|
||||
next: 'rematch' | 'nextHand' | null;
|
||||
ready: PlayerId[];
|
||||
lastAction: Record<PlayerId, { type: BetType; amount: number }>;
|
||||
/** 베팅 규칙 111~444: how many more first-round actions are limited to 하프·다이. */
|
||||
forced: number;
|
||||
/** Public bet log of this (re)match (everyone saw these bets). */
|
||||
log: BetLogEntry[];
|
||||
}
|
||||
|
||||
export interface BetLogEntry {
|
||||
p: PlayerId;
|
||||
t: BetType;
|
||||
amount: number;
|
||||
street: number;
|
||||
}
|
||||
|
||||
export interface HandRecord {
|
||||
@@ -266,6 +304,8 @@ export interface SeotdaSeatView {
|
||||
lastAction: { type: BetType; amount: number } | null;
|
||||
/** Shown after showdown only. */
|
||||
handName: string | null;
|
||||
/** Money won or lost in the finished hand (result screen only). */
|
||||
handDelta: number | null;
|
||||
}
|
||||
|
||||
export interface SeotdaView {
|
||||
@@ -286,6 +326,10 @@ export interface SeotdaView {
|
||||
pots: PotState[];
|
||||
currentBet: number;
|
||||
legal: { type: BetType; amount: number; allIn: boolean }[];
|
||||
/** 베팅 규칙 111~444: the player to act may only 하프 or 다이. */
|
||||
forcedHalf: boolean;
|
||||
/** Public bets of this (re)match, oldest first. */
|
||||
betLog: BetLogEntry[];
|
||||
myHand: { name: string; value: number | null; special: SpecialKind | null; hint: string; strength: 'high' | 'mid' | 'low' | null } | null;
|
||||
myCombos: { cardIds: [number, number]; name: string; value: number; best: boolean }[] | null;
|
||||
myChosen: [number, number] | null;
|
||||
@@ -305,7 +349,7 @@ export interface SeotdaView {
|
||||
|
||||
/** Placeholder better that carries earlier pots so 쿼터/하프/풀 see the whole 모인 칩 (§5.5-2). */
|
||||
const CARRY = '#carried';
|
||||
const HAND_END_MS = 4000;
|
||||
const HAND_END_MS = 5000;
|
||||
const AWAY_MS = 5000;
|
||||
const STANDING_CAP = 300;
|
||||
|
||||
@@ -328,6 +372,28 @@ const contendersOf = (h: SeotdaHand): PlayerId[] =>
|
||||
const betterIdx = (h: SeotdaHand, id: PlayerId): number => (h.betting ? h.betting.players.findIndex((p) => p.id === id) : -1);
|
||||
const maxRebuys = (o: SeotdaOptions): number => (o.rebuy === 'off' ? 0 : o.rebuy === 'limited' ? o.rebuyLimit : Infinity);
|
||||
|
||||
/** 20장: 1~10월의 광·열끗과 띠(8월은 기러기) / 40장: 1~10월 4장 모두 (한게임 "카드 장수"). */
|
||||
export const SEOTDA_DECK_40: number[] = Array.from({ length: 40 }, (_, i) => i);
|
||||
export const deckOf = (o: Pick<SeotdaOptions, 'deck'>): number[] => (o.deck === 40 ? SEOTDA_DECK_40 : SEOTDA_DECK);
|
||||
/** 베팅 규칙 111 → 1 … 444 → 4 limited first-round actions. */
|
||||
const forcedCount = (o: SeotdaOptions): number => (o.betRule === 'free' ? 0 : Number(o.betRule[0]));
|
||||
|
||||
/**
|
||||
* Legal bets of the shared Korean betting module, narrowed to this room: 쿼터 only when the room turns it on, and under
|
||||
* 베팅 규칙 111~444 the first players of the first round may only 하프 (or the raise that is left) or 다이.
|
||||
*/
|
||||
function betsFor(s: SeotdaState, h: SeotdaHand, idx: number): { type: BetType; amount: number; allIn: boolean }[] {
|
||||
if (!h.betting) return [];
|
||||
let out = legalBets(h.betting, idx).map((l) => ({ type: toType(l.kind), amount: l.amount, allIn: l.allIn }));
|
||||
if (!s.options.quarter) out = out.filter((l) => l.type !== 'quarter');
|
||||
if (h.forced > 0 && h.street === 0 && out.length) {
|
||||
const half = out.find((l) => l.type === 'half') ?? out.find((l) => l.type === 'full' || l.type === 'ddadang' || l.type === 'quarter');
|
||||
const keep = half ?? out.find((l) => l.type === 'call' || l.type === 'check');
|
||||
out = out.filter((l) => l === keep || l.type === 'die');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Total chips that must exist: Σ stacks + carried pots + live pot. */
|
||||
export function chipsTotal(s: SeotdaState): number {
|
||||
const h = s.hand;
|
||||
@@ -420,7 +486,7 @@ function startHand(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
||||
phase: 'betting',
|
||||
dealer,
|
||||
order,
|
||||
deck: rng.shuffle(SEOTDA_DECK),
|
||||
deck: rng.shuffle(deckOf(o)),
|
||||
cards: Object.fromEntries(order.map((id) => [id, []])),
|
||||
chosen: Object.fromEntries(order.map((id) => [id, null])),
|
||||
betting: b,
|
||||
@@ -437,6 +503,8 @@ function startHand(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
||||
next: null,
|
||||
ready: [],
|
||||
lastAction: {},
|
||||
forced: forcedCount(o),
|
||||
log: [],
|
||||
};
|
||||
s.hand = h;
|
||||
syncStacks(s);
|
||||
@@ -456,7 +524,7 @@ function startRematch(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
||||
h.order = order;
|
||||
h.phase = 'betting';
|
||||
h.street = 0;
|
||||
h.deck = rng.shuffle(SEOTDA_DECK);
|
||||
h.deck = rng.shuffle(deckOf(s.options));
|
||||
h.cards = Object.fromEntries(order.map((id) => [id, []]));
|
||||
h.chosen = Object.fromEntries(order.map((id) => [id, null]));
|
||||
h.showdown = null;
|
||||
@@ -466,6 +534,8 @@ function startRematch(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
||||
h.rejoinPending = [];
|
||||
h.rematchSet = [];
|
||||
h.lastAction = {};
|
||||
h.forced = forcedCount(s.options);
|
||||
h.log = [];
|
||||
let b = newBetting(
|
||||
order.map((id) => ({ id, stack: seatOf(s, id)!.stack })),
|
||||
{ style: 'korean', baseUnit: s.baseUnit, koreanMax: s.options.maxRaise },
|
||||
@@ -738,11 +808,11 @@ function finishGame(s: SeotdaState, events: GameEvent[]): void {
|
||||
if (byScore) {
|
||||
const sc = scores[top[0]!] ?? 0;
|
||||
const tie = top.length > 1 ? ` (공동 ${top.length}명)` : '';
|
||||
summary = `${s.handsPlayed}판 끝. 1위 ${sc >= 0 ? '+' : ''}${sc.toLocaleString('ko-KR')}칩${tie}${best}`;
|
||||
summary = `${s.handsPlayed}판 끝. 1위 ${formatWonDelta(sc)}${tie}${best}`;
|
||||
} else {
|
||||
summary = `${s.handsPlayed}판 만에 끝났어요. 1위 ${(seatOf(s, top[0]!)?.stack ?? 0).toLocaleString('ko-KR')}칩${best}`;
|
||||
summary = `${s.handsPlayed}판 만에 끝났어요. 1위 ${formatWon(seatOf(s, top[0]!)?.stack ?? 0)}${best}`;
|
||||
}
|
||||
const scoreText = Object.fromEntries(s.seats.map((x) => [x.id, `${(byScore ? scores[x.id]! : x.stack).toLocaleString('ko-KR')}칩`]));
|
||||
const scoreText = Object.fromEntries(s.seats.map((x) => [x.id, byScore ? formatWonDelta(scores[x.id]!) : formatWon(x.stack)]));
|
||||
s.final = { ranking, scores, scoreText, summary };
|
||||
events.push({ type: 'gameEnd', ranking });
|
||||
}
|
||||
@@ -756,6 +826,8 @@ function applyBetAction(s: SeotdaState, id: PlayerId, t: BetType, events: GameEv
|
||||
h.betting = r.state;
|
||||
h.betSeq += 1;
|
||||
h.lastAction[id] = { type: t, amount: r.event.amount };
|
||||
h.log.push({ p: id, t, amount: r.event.amount, street: h.street });
|
||||
if (h.street === 0 && h.forced > 0) h.forced -= 1;
|
||||
syncStacks(s);
|
||||
events.push({ type: 'bet', player: id, kind: t, amount: r.event.amount, allIn: r.event.allIn });
|
||||
}
|
||||
@@ -802,6 +874,7 @@ function progress(s: SeotdaState, rng: Rng, events: GameEvent[]): void {
|
||||
settleFold(s, events);
|
||||
continue;
|
||||
}
|
||||
// 3장 섯다: 2장 → 베팅 → 1장 더 → 3장 중 2장 몰래 고르기 → 마지막 베팅 → 공개.
|
||||
if (h.street === 0 && s.options.cardMode === 'three') {
|
||||
deal(h, h.order.filter((id) => contendersOf(h).includes(id)), 1, events);
|
||||
h.phase = 'choose';
|
||||
@@ -892,8 +965,9 @@ function refreshDeadline(s: SeotdaState, now: number): void {
|
||||
if (h.phase === 'betting' && h.betting?.turn != null) {
|
||||
const id = h.betting.players[h.betting.turn]!.id;
|
||||
key += `|${id}|${h.betSeq}`;
|
||||
ms = seatOf(s, id)!.away ? AWAY_MS : o.turnSeconds * 1000;
|
||||
} else if (h.phase === 'choose') ms = (o.turnSeconds + 10) * 1000;
|
||||
// 시간 무제한 방에서도 자리 비움(연속 시간 초과)은 없으니 기다린다.
|
||||
ms = o.turnSeconds === null ? null : seatOf(s, id)!.away ? AWAY_MS : o.turnSeconds * 1000;
|
||||
} else if (h.phase === 'choose') ms = o.turnSeconds === null ? null : (o.turnSeconds + 10) * 1000;
|
||||
else if (h.phase === 'rejoin') ms = o.decisionSeconds * 1000;
|
||||
else if (h.phase === 'handEnd') ms = HAND_END_MS;
|
||||
}
|
||||
@@ -925,10 +999,61 @@ function isBet(t: string): t is BetType {
|
||||
return (BET_TYPES as string[]).includes(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1 → v2 (2026-10-13, 한게임식 원 표기): amounts were chips (시작 1,000 / 학교 10); now they are 원 at ×1000
|
||||
* (시작 100만원 / 기본 머니 1만원). Games in progress keep their own rules: 쿼터 stays on, no 베팅 규칙, 20장.
|
||||
*/
|
||||
const MONEY_V1 = 1000;
|
||||
function migrateSeotda(old: unknown, from: number): SeotdaState {
|
||||
const s = structuredClone(old) as SeotdaState;
|
||||
if (from >= 2) return s;
|
||||
const o = s.options as SeotdaOptions & Record<string, unknown>;
|
||||
s.options = { ...o, deck: 20, betRule: 'free', quarter: true } as SeotdaOptions;
|
||||
if (s.hand) {
|
||||
s.hand.forced = 0;
|
||||
s.hand.log = [];
|
||||
}
|
||||
return scaleMoney(s, MONEY_V1);
|
||||
}
|
||||
|
||||
/** Multiplies every amount of a state by `k` (in place): options, stacks, pots, bets, history. Integers stay integers for k ≥ 1. */
|
||||
export function scaleMoney(s: SeotdaState, k: number): SeotdaState {
|
||||
const m = (n: number) => Math.round(n * k);
|
||||
s.options = { ...s.options, startingChips: m(s.options.startingChips), baseUnit: m(s.options.baseUnit) } as SeotdaOptions;
|
||||
s.baseUnit = m(s.baseUnit);
|
||||
for (const x of s.seats) {
|
||||
x.stack = m(x.stack);
|
||||
x.stackAtHandStart = m(x.stackAtHandStart);
|
||||
}
|
||||
for (const r of s.history) r.amount = m(r.amount);
|
||||
if (s.stats.biggestPot) s.stats.biggestPot.amount = m(s.stats.biggestPot.amount);
|
||||
const h = s.hand;
|
||||
if (h) {
|
||||
for (const p of h.carried) p.amount = m(p.amount);
|
||||
h.rejoinCost = m(h.rejoinCost);
|
||||
if (h.foldWin) h.foldWin.amount = m(h.foldWin.amount);
|
||||
if (h.showdown) for (const p of h.showdown.pots) p.amount = m(p.amount);
|
||||
for (const a of Object.values(h.lastAction)) a.amount = m(a.amount);
|
||||
for (const e of h.log ?? []) e.amount = m(e.amount);
|
||||
const b = h.betting;
|
||||
if (b) {
|
||||
b.baseUnit = m(b.baseUnit);
|
||||
b.currentBet = m(b.currentBet);
|
||||
b.lastRaise = m(b.lastRaise);
|
||||
for (const p of b.players) {
|
||||
p.stack = m(p.stack);
|
||||
p.round = m(p.round);
|
||||
p.total = m(p.total);
|
||||
}
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definition
|
||||
|
||||
export function playerRange(o: Pick<SeotdaOptions, 'cardMode'>): { min: number; max: number } {
|
||||
return { min: 2, max: o.cardMode === 'three' ? 6 : 10 };
|
||||
export function playerRange(o: Pick<SeotdaOptions, 'cardMode' | 'deck'>): { min: number; max: number } {
|
||||
return { min: 2, max: o.cardMode === 'three' && o.deck !== 40 ? 6 : 10 };
|
||||
}
|
||||
|
||||
export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, SeotdaOptions> = {
|
||||
@@ -936,7 +1061,8 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
nameKo: '섯다',
|
||||
minPlayers: 2,
|
||||
maxPlayers: 10,
|
||||
stateVersion: 1,
|
||||
stateVersion: 2,
|
||||
migrate: migrateSeotda,
|
||||
defaultOptions: seotdaOptionsSchema.parse({}),
|
||||
optionsSchema: seotdaOptionsSchema as unknown as z.ZodType<SeotdaOptions>,
|
||||
actionSchema: seotdaActionSchema as unknown as z.ZodType<SeotdaAction>,
|
||||
@@ -986,7 +1112,7 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
if (a.type === 'timeout') return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
|
||||
if (st.left) return fail('방을 나간 플레이어예요.');
|
||||
if (a.type === 'rebuy') {
|
||||
if (s.phase !== 'rebuy' || !s.rebuyPending.includes(actor)) return fail('지금은 칩을 다시 받을 수 없어요.');
|
||||
if (s.phase !== 'rebuy' || !s.rebuyPending.includes(actor)) return fail('지금은 시작 금액을 다시 받을 수 없어요.');
|
||||
return ok;
|
||||
}
|
||||
const h = s.hand;
|
||||
@@ -996,7 +1122,9 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
const idx = betterIdx(h, actor);
|
||||
if (idx < 0) return fail('이번 판에 참가하지 않았어요.');
|
||||
const err = validateBet(h.betting, idx, { kind: toKind(a.type) } as BetAction);
|
||||
if (!err) return ok;
|
||||
if (!err && betsFor(s, h, idx).some((l) => l.type === a.type)) return ok;
|
||||
if (!err && a.type === 'quarter' && !s.options.quarter) return fail('이 방은 쿼터 베팅을 쓰지 않아요.');
|
||||
if (!err) return fail(`베팅 규칙 ${s.options.betRule}: 지금은 하프 또는 다이만 할 수 있어요.`);
|
||||
if (h.betting.turn === idx && ['ping', 'ddadang', 'quarter', 'half', 'full'].includes(a.type)) {
|
||||
if (a.type === 'full' && s.options.maxRaise === 'half') return fail('이 방은 하프까지만 올릴 수 있어요.');
|
||||
if (a.type === 'ping' && h.betting.opened) return fail('누가 이미 걸어서 삥을 할 수 없어요.');
|
||||
@@ -1017,7 +1145,7 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
}
|
||||
case 'rejoin': {
|
||||
if (h.phase !== 'rejoin' || !h.rejoinPending.includes(actor)) return fail('재참가 대상이 아니에요.');
|
||||
if (a.accept && st.stack < h.rejoinCost) return fail('칩이 모자라 재참가할 수 없어요.');
|
||||
if (a.accept && st.stack < h.rejoinCost) return fail('보유 금액이 모자라 재참가할 수 없어요.');
|
||||
return ok;
|
||||
}
|
||||
case 'ready': {
|
||||
@@ -1070,7 +1198,9 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
events.push({ type: 'timeout', player: actor });
|
||||
if (phase === 'betting') {
|
||||
const b = h!.betting!;
|
||||
applyBetAction(s, actor, toType(timeoutBet(b, betterIdx(h!, actor)).kind), events);
|
||||
const idx = betterIdx(h!, actor);
|
||||
const t = toType(timeoutBet(b, idx).kind);
|
||||
applyBetAction(s, actor, betsFor(s, h!, idx).some((l) => l.type === t) ? t : 'die', events);
|
||||
} else if (phase === 'choose') chooseFor(s, actor, bestChoice(h!.cards[actor]!, rulesOf(s.options)), events);
|
||||
else if (phase === 'rejoin') decideRejoin(s, actor, false, events);
|
||||
else if (phase === 'handEnd') h!.ready.push(actor);
|
||||
@@ -1122,14 +1252,13 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
ready: !!h && h.phase === 'handEnd' && h.ready.includes(x.id),
|
||||
lastAction: h?.lastAction[x.id] ?? null,
|
||||
handName: h?.showdown?.hands.find((y) => y.id === x.id)?.name ?? null,
|
||||
handDelta: h?.phase === 'handEnd' && h.next === 'nextHand' && inHand ? x.stack - x.stackAtHandStart : null,
|
||||
};
|
||||
});
|
||||
const me = viewer && seatOf(s, viewer) ? viewer : null;
|
||||
const myIdx = h && me ? betterIdx(h, me) : -1;
|
||||
const legal =
|
||||
h && b && myIdx >= 0 && h.phase === 'betting' && !seatOf(s, me!)!.left
|
||||
? legalBets(b, myIdx).map((l) => ({ type: toType(l.kind), amount: l.amount, allIn: l.allIn }))
|
||||
: [];
|
||||
h && b && myIdx >= 0 && h.phase === 'betting' && !seatOf(s, me!)!.left ? betsFor(s, h, myIdx) : [];
|
||||
let myHand: SeotdaView['myHand'] = null;
|
||||
let myCombos: SeotdaView['myCombos'] = null;
|
||||
let myDiscard: SeotdaCardView | null = null;
|
||||
@@ -1176,6 +1305,8 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
pots,
|
||||
currentBet: b?.currentBet ?? 0,
|
||||
legal,
|
||||
forcedHalf: !!h && h.phase === 'betting' && h.street === 0 && h.forced > 0,
|
||||
betLog: h?.log ?? [],
|
||||
myHand,
|
||||
myCombos,
|
||||
myChosen,
|
||||
@@ -1238,7 +1369,7 @@ export const seotda: GameDefinition<SeotdaState, SeotdaAction, SeotdaView, Seotd
|
||||
case 'betting': {
|
||||
const idx = betterIdx(h, p);
|
||||
if (idx < 0 || !h.betting) return [];
|
||||
return legalBets(h.betting, idx).map((l) => ({ type: toType(l.kind) }) as SeotdaAction);
|
||||
return betsFor(s, h, idx).map((l) => ({ type: l.type }) as SeotdaAction);
|
||||
}
|
||||
case 'choose':
|
||||
if (!contendersOf(h).includes(p) || h.chosen[p]) return [];
|
||||
|
||||
45
packages/games/src/seotda/money.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 섯다 금액 표기 (docs/games/seotda.md §2, §9): 한게임 섯다처럼 "원"으로, 큰 수는 만·억 단위로 끊어 읽는다.
|
||||
* 방 안에서만 쓰는 놀이용 게임머니라 실제 돈과는 상관없다(§12).
|
||||
*/
|
||||
|
||||
/** 1234 → "1,234원", 15_000 → "1만 5,000원", 123_450_000 → "1억 2,345만원", 0 → "0원". */
|
||||
export function formatWon(n: number, unit = '원'): string {
|
||||
const neg = n < 0;
|
||||
let v = Math.abs(Math.round(n));
|
||||
if (v === 0) return `0${unit}`;
|
||||
const parts: string[] = [];
|
||||
const jo = Math.floor(v / 1e12);
|
||||
v -= jo * 1e12;
|
||||
const eok = Math.floor(v / 1e8);
|
||||
v -= eok * 1e8;
|
||||
const man = Math.floor(v / 1e4);
|
||||
const rest = v - man * 1e4;
|
||||
if (jo) parts.push(`${jo.toLocaleString('ko-KR')}조`);
|
||||
if (eok) parts.push(`${eok.toLocaleString('ko-KR')}억`);
|
||||
if (man) parts.push(`${man.toLocaleString('ko-KR')}만`);
|
||||
if (rest) parts.push(rest.toLocaleString('ko-KR'));
|
||||
return `${neg ? '-' : ''}${parts.join(' ')}${unit}`;
|
||||
}
|
||||
|
||||
/** Signed change: "+1만 5,000원" / "-3,000원" / "0원". */
|
||||
export function formatWonDelta(n: number): string {
|
||||
return n > 0 ? `+${formatWon(n)}` : formatWon(n);
|
||||
}
|
||||
|
||||
/** Short form for tight spots (seat boxes on phones): "1억 2,345만", "12만 3,000" → "12.3만", under 1만 as is. */
|
||||
export function formatWonShort(n: number): string {
|
||||
const v = Math.abs(Math.round(n));
|
||||
const sign = n < 0 ? '-' : '';
|
||||
if (v >= 1e8) {
|
||||
const eok = Math.floor(v / 1e8);
|
||||
const man = Math.floor((v % 1e8) / 1e4);
|
||||
return `${sign}${eok.toLocaleString('ko-KR')}억${man ? ` ${man.toLocaleString('ko-KR')}만` : ''}`;
|
||||
}
|
||||
if (v >= 1e4) {
|
||||
const man = v / 1e4;
|
||||
const txt = Number.isInteger(man) ? man.toLocaleString('ko-KR') : (Math.floor(man * 10) / 10).toLocaleString('ko-KR');
|
||||
return `${sign}${txt}만`;
|
||||
}
|
||||
return `${sign}${v.toLocaleString('ko-KR')}`;
|
||||
}
|
||||
308
packages/games/src/seotda/odds.ts
Normal file
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* 섯다 승률 계산 (docs/games/seotda.md §8.7): from what one player can see (own cards, the room's deck, how many
|
||||
* cards everyone holds, the public bets), enumerate every way the unseen cards can fall and add up the share of the pot
|
||||
* this player gets at the showdown — 땡잡이·암행어사·구사 재경기·동점 included (the real `resolve`).
|
||||
*
|
||||
* The deck is tiny (20 or 40 cards), so heads-up and most 3-handed spots are enumerated exactly (≤ EXACT_LIMIT deals);
|
||||
* bigger tables fall back to a fixed number of random deals. Pure CPU work, a few ms per decision.
|
||||
*/
|
||||
import { bestChoice, evalSeotda, gusaThreshold, type HandEval, type HandRules } from './hands';
|
||||
|
||||
/** Joint deals enumerated exactly up to this many; above it, `SAMPLES` random deals. */
|
||||
export const EXACT_LIMIT = 30_000;
|
||||
export const SAMPLES = 3_000;
|
||||
|
||||
/** Weight of an opponent's possible final hand (its cards, e.g. from the betting so far); 1 = no information. */
|
||||
export type RangeWeight = (cards: number[]) => number;
|
||||
|
||||
export interface OddsInput {
|
||||
rules: HandRules;
|
||||
tieRule: 'rematch' | 'split';
|
||||
/** The room's whole deck (20 or 40 ids). */
|
||||
deck: number[];
|
||||
/** Cards I hold now. */
|
||||
mine: number[];
|
||||
/** Cards each player holds at the showdown: 2 (2장 섯다) or 3 (3장 섯다, best 2 of 3). */
|
||||
finalSize: 2 | 3;
|
||||
/** Cards each opponent holds at the showdown when it differs from mine (3장 섯다 after I chose my pair). */
|
||||
oppSize?: 2 | 3;
|
||||
/** One entry per opponent still in the hand. */
|
||||
opponents: RangeWeight[];
|
||||
/** Cards I can see that nobody can hold any more (none in 섯다 today; kept for 3장 섯다 open cards). */
|
||||
dead?: number[];
|
||||
random?: () => number;
|
||||
/** Random deals when the table is too big to enumerate (default `SAMPLES`). */
|
||||
samples?: number;
|
||||
}
|
||||
|
||||
export interface Odds {
|
||||
/** Expected share of the pot at the showdown (win 1, split 1/k, rematch 1/k of the participants). */
|
||||
equity: number;
|
||||
/** Probability of winning the pot outright. */
|
||||
win: number;
|
||||
/** Probability of a rematch / split that includes me. */
|
||||
tie: number;
|
||||
/** Probability of losing the pot. */
|
||||
lose: number;
|
||||
/** Weighted number of deals looked at, and whether every deal was enumerated. */
|
||||
deals: number;
|
||||
exact: boolean;
|
||||
/** When I still get one card: my equity for each card I may get (weights = how likely, given the others' ranges). */
|
||||
perDraw: { card: number; equity: number; weight: number }[];
|
||||
}
|
||||
|
||||
/** Order-independent numeric key of 2–3 card ids (< 64). */
|
||||
export function cardsKey(cards: readonly number[]): number {
|
||||
let a = cards[0]!;
|
||||
let b = cards[1]!;
|
||||
let c = cards.length > 2 ? cards[2]! : -1;
|
||||
if (a > b) [a, b] = [b, a];
|
||||
if (c >= 0) {
|
||||
if (b > c) [b, c] = [c, b];
|
||||
if (a > b) [a, b] = [b, a];
|
||||
return 1 + a * 4096 + b * 64 + c + 300_000;
|
||||
}
|
||||
return a * 64 + b;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- evaluation tables
|
||||
|
||||
const handCaches = new Map<string, Map<number, HandEval>>();
|
||||
const rulesKey = (r: HandRules) => `${r.gwangTtaeng}|${r.ttaengjabi}|${r.amhaeng}|${r.gusa}|${r.mungGusa}`;
|
||||
|
||||
/** The showdown hand of a set of final cards (2 cards, or the best 2 of 3 as the automatic choice picks them). Cached. */
|
||||
export function finalHand(cards: readonly number[], rules: HandRules): HandEval {
|
||||
const rk = rulesKey(rules);
|
||||
let t = handCaches.get(rk);
|
||||
if (!t) {
|
||||
t = new Map();
|
||||
handCaches.set(rk, t);
|
||||
}
|
||||
const key = cardsKey(cards);
|
||||
let h = t.get(key);
|
||||
if (!h) {
|
||||
const pair = cards.length === 2 ? cards : bestChoice([...cards], rules);
|
||||
h = evalSeotda(pair[0]!, pair[1]!, rules);
|
||||
t.set(key, h);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* My share of the pot when these hands meet at the showdown (index 0 = me): 1 for a win, 1/k for a split or a rematch
|
||||
* among k players, 0 for a loss. Same judgement as `resolve` (땡잡이, 암행어사, 구사 재경기), without allocations.
|
||||
*/
|
||||
export function shareOf(hands: readonly HandEval[], rules: HandRules, _tieRule: 'rematch' | 'split' = 'rematch'): number {
|
||||
const n = hands.length;
|
||||
let vmax = -1;
|
||||
let tj = false;
|
||||
let am = false;
|
||||
for (const h of hands) {
|
||||
if (h.value > vmax) vmax = h.value;
|
||||
if (h.special === 'ttaengjabi') tj = true;
|
||||
else if (h.special === 'amhaeng') am = true;
|
||||
}
|
||||
const mode = tj && vmax >= 901 && vmax <= 909 ? 1 : am && (vmax === 980 || vmax === 990) ? 2 : 0;
|
||||
const inW = (h: HandEval) => (mode === 1 ? h.special === 'ttaengjabi' : mode === 2 ? h.special === 'amhaeng' : h.value === vmax);
|
||||
let w = 0;
|
||||
for (const h of hands) if (inW(h)) w++;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const h = hands[i]!;
|
||||
if ((h.special !== 'gusa' && h.special !== 'mungGusa') || inW(h)) continue;
|
||||
const t = gusaThreshold(h.special, rules);
|
||||
let best = -1;
|
||||
for (let j = 0; j < n; j++) if (j !== i && hands[j]!.value > best) best = hands[j]!.value;
|
||||
if (t !== null && best <= t) return 1 / n;
|
||||
}
|
||||
return inW(hands[0]!) ? 1 / w : 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- enumeration
|
||||
|
||||
function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function choose(n: number, k: number): number {
|
||||
let r = 1;
|
||||
for (let i = 0; i < k; i++) r = (r * (n - i)) / (i + 1);
|
||||
return Math.round(r);
|
||||
}
|
||||
|
||||
/** All k-subsets of `pool` (k ≤ 3). */
|
||||
function subsets(pool: number[], k: number): number[][] {
|
||||
const out: number[][] = [];
|
||||
const n = pool.length;
|
||||
if (k === 0) return [[]];
|
||||
if (k === 1) return pool.map((x) => [x]);
|
||||
for (let i = 0; i < n; i++)
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (k === 2) out.push([pool[i]!, pool[j]!]);
|
||||
else for (let l = j + 1; l < n; l++) out.push([pool[i]!, pool[j]!, pool[l]!]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function odds(input: OddsInput): Odds {
|
||||
const { rules, tieRule, finalSize, opponents } = input;
|
||||
const oppSize = input.oppSize ?? finalSize;
|
||||
const seen = new Set([...input.mine, ...(input.dead ?? [])]);
|
||||
const pool = input.deck.filter((c) => !seen.has(c));
|
||||
const need = finalSize - input.mine.length;
|
||||
const n = opponents.length;
|
||||
const acc = { w: 0, eq: 0, win: 0, tie: 0, lose: 0 };
|
||||
const draws = new Map<number, { w: number; eq: number }>();
|
||||
const handOf = (cards: number[]) => finalHand(cards, rules);
|
||||
const score = (myCards: number[], opp: number[][], weight: number) => {
|
||||
if (weight <= 0) return;
|
||||
const hands = [handOf(myCards), ...opp.map(handOf)];
|
||||
const s = n === 0 ? 1 : shareOf(hands, rules, tieRule);
|
||||
acc.w += weight;
|
||||
acc.eq += weight * s;
|
||||
if (need === 1) {
|
||||
const c = myCards[myCards.length - 1]!;
|
||||
const d = draws.get(c) ?? { w: 0, eq: 0 };
|
||||
d.w += weight;
|
||||
d.eq += weight * s;
|
||||
draws.set(c, d);
|
||||
}
|
||||
if (s === 1) acc.win += weight;
|
||||
else if (s > 0) acc.tie += weight;
|
||||
else acc.lose += weight;
|
||||
};
|
||||
|
||||
// How many joint deals there are: my missing cards, then each opponent's whole hand.
|
||||
let total = choose(pool.length, Math.max(0, need));
|
||||
let left = pool.length - Math.max(0, need);
|
||||
for (let i = 0; i < n; i++) {
|
||||
total *= choose(left, oppSize);
|
||||
left -= oppSize;
|
||||
}
|
||||
const exact = left >= 0 && total <= (input.samples !== undefined ? Math.min(EXACT_LIMIT, input.samples * 4) : EXACT_LIMIT);
|
||||
|
||||
if (exact) {
|
||||
const mineOpts = subsets(pool, Math.max(0, need));
|
||||
for (const extra of mineOpts) {
|
||||
const myCards = [...input.mine, ...extra];
|
||||
const rest = pool.filter((c) => !extra.includes(c));
|
||||
const rec = (i: number, avail: number[], opp: number[][], w: number) => {
|
||||
if (i === n) return score(myCards, opp, w);
|
||||
for (const h of subsets(avail, oppSize)) {
|
||||
const wi = opponents[i]!(h);
|
||||
if (wi <= 0) continue;
|
||||
rec(
|
||||
i + 1,
|
||||
avail.filter((c) => !h.includes(c)),
|
||||
[...opp, h],
|
||||
w * wi,
|
||||
);
|
||||
}
|
||||
};
|
||||
rec(0, rest, [], 1);
|
||||
}
|
||||
} else {
|
||||
// Own PRNG seeded once from the caller's: stays well spread even if `random` is a stub (tests).
|
||||
const random = mulberry32(Math.floor((input.random ?? Math.random)() * 0x100000000) ^ 0x9e3779b9);
|
||||
const deck = [...pool];
|
||||
const take = Math.max(0, need) + n * oppSize;
|
||||
for (let s = 0; s < (input.samples ?? SAMPLES); s++) {
|
||||
// Partial Fisher–Yates: only the cards we need.
|
||||
for (let i = 0; i < Math.min(take, deck.length - 1); i++) {
|
||||
const j = i + Math.floor(random() * (deck.length - i));
|
||||
const t = deck[i]!;
|
||||
deck[i] = deck[j]!;
|
||||
deck[j] = t;
|
||||
}
|
||||
const myCards = [...input.mine, ...deck.slice(0, Math.max(0, need))];
|
||||
const opp: number[][] = [];
|
||||
let w = 1;
|
||||
let at = Math.max(0, need);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const h = deck.slice(at, at + oppSize);
|
||||
at += oppSize;
|
||||
opp.push(h);
|
||||
w *= opponents[i]!(h);
|
||||
}
|
||||
score(myCards, opp, w);
|
||||
}
|
||||
}
|
||||
if (acc.w <= 0) return { equity: 1 / (n + 1), win: 0, tie: 0, lose: 0, deals: 0, exact, perDraw: [] };
|
||||
const perDraw = [...draws.entries()].map(([card, d]) => ({ card, equity: d.w > 0 ? d.eq / d.w : 0, weight: d.w / acc.w }));
|
||||
return { equity: acc.eq / acc.w, win: acc.win / acc.w, tie: acc.tie / acc.w, lose: acc.lose / acc.w, deals: acc.w, exact, perDraw };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- hand strength percentiles (for ranges)
|
||||
|
||||
const pctCache = new Map<string, Map<string, number>>();
|
||||
const pctFast = new Map<string, Map<number, number>>();
|
||||
|
||||
/**
|
||||
* Where a final hand stands among all hands of the deck (0 = weakest, 1 = 38광땡), by its heads-up equity against a
|
||||
* random hand. Used to turn bets into ranges ("a 하프 usually means a strong hand").
|
||||
*/
|
||||
export function strengthPercentile(cards: readonly number[], rules: HandRules, deck: readonly number[], finalSize: 2 | 3): number {
|
||||
const key = `${rulesKey(rules)}|${deck.length}|${finalSize}`;
|
||||
let fast = pctFast.get(key);
|
||||
if (!fast) {
|
||||
fast = new Map();
|
||||
pctFast.set(key, fast);
|
||||
}
|
||||
const ck = cardsKey(cards);
|
||||
const hit = fast.get(ck);
|
||||
if (hit !== undefined) return hit;
|
||||
let t = pctCache.get(key);
|
||||
if (!t) {
|
||||
t = buildPercentiles(rules, [...deck], finalSize);
|
||||
pctCache.set(key, t);
|
||||
}
|
||||
const p = t.get(handKey(finalHand(cards, rules))) ?? 0.5;
|
||||
fast.set(ck, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
const handKey = (h: HandEval) => `${h.value}|${h.special ?? ''}`;
|
||||
|
||||
/**
|
||||
* Hands are grouped by (value, special) — cards of the same month and kind behave the same. Each group's strength is its
|
||||
* heads-up equity against every other pair of the deck; the percentile is the share of pairs with a lower equity.
|
||||
*/
|
||||
function buildPercentiles(rules: HandRules, deck: number[], _finalSize: 2 | 3): Map<string, number> {
|
||||
const pairs = subsets(deck, 2);
|
||||
const evals = pairs.map(([a, b]) => finalHand([a!, b!], rules));
|
||||
const groups = new Map<string, { eq: number; n: number; count: number }>();
|
||||
for (let i = 0; i < pairs.length; i++) {
|
||||
const k = handKey(evals[i]!);
|
||||
let g = groups.get(k);
|
||||
if (!g) {
|
||||
g = { eq: 0, n: 0, count: 0 };
|
||||
groups.set(k, g);
|
||||
// Equity of this representative against every disjoint pair.
|
||||
const [a, b] = pairs[i]!;
|
||||
for (let j = 0; j < pairs.length; j++) {
|
||||
const [c, d] = pairs[j]!;
|
||||
if (c === a || c === b || d === a || d === b) continue;
|
||||
g.eq += shareOf([evals[i]!, evals[j]!], rules, 'rematch');
|
||||
g.n += 1;
|
||||
}
|
||||
}
|
||||
g.count += 1;
|
||||
}
|
||||
const list = [...groups.entries()].map(([k, g]) => ({ k, eq: g.eq / Math.max(1, g.n), count: g.count }));
|
||||
list.sort((x, y) => x.eq - y.eq);
|
||||
const total = list.reduce((s, x) => s + x.count, 0);
|
||||
const out = new Map<string, number>();
|
||||
let below = 0;
|
||||
for (const x of list) {
|
||||
// Middle of the group's band.
|
||||
out.set(x.k, (below + x.count / 2) / total);
|
||||
below += x.count;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
chipsTotal,
|
||||
evalSeotda,
|
||||
resolve,
|
||||
scaleMoney,
|
||||
seotda,
|
||||
type HandEval,
|
||||
type HandRules,
|
||||
@@ -25,12 +26,29 @@ const ev = (a: number, b: number, r: Partial<HandRules> = {}) => evalSeotda(a, b
|
||||
let clock = 1000;
|
||||
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
|
||||
|
||||
/**
|
||||
* Most flow tests were written for 1장씩 두 번 + 쿼터 + strict 땡잡이 + 멍구사 8땡까지 (the defaults before the 한게임
|
||||
* rebuild); they keep those rules explicitly. The 한게임 defaults have their own tests below.
|
||||
*/
|
||||
const CLASSIC: Partial<SeotdaOptions> = { dealMode: 'twoRounds', quarter: true, ttaengjabi: 'strict', mungGusa: 'upTo8' };
|
||||
|
||||
/** Fresh game whose first dealer is `dealer` (seat order = players). */
|
||||
function make(opts: Partial<SeotdaOptions> = {}, players = ['A', 'B', 'C'], dealer = 'A'): SeotdaState {
|
||||
const options = seotda.optionsSchema.parse(opts);
|
||||
/**
|
||||
* The flow tests count in the old small units (시작 1,000 / 기본금 10, i.e. 원 ÷ 1000): `startingChips`/`baseUnit` given
|
||||
* in those units are scaled up for the schema, and the new game is scaled back down (`scaleMoney`, the inverse of the
|
||||
* v1 → v2 migration). The engine itself is unit-free.
|
||||
*/
|
||||
/** Options in the old small units (startingChips 500…5000, baseUnit 2…50). */
|
||||
type OldOpts = Partial<Omit<SeotdaOptions, 'startingChips' | 'baseUnit'>> & { startingChips?: number; baseUnit?: number };
|
||||
|
||||
function make(opts: OldOpts = {}, players = ['A', 'B', 'C'], dealer = 'A'): SeotdaState {
|
||||
const up = { ...opts };
|
||||
if (up.startingChips !== undefined) up.startingChips *= 1000;
|
||||
if (up.baseUnit !== undefined) up.baseUnit *= 1000;
|
||||
const options = seotda.optionsSchema.parse({ ...CLASSIC, ...up });
|
||||
for (let seed = 1; seed < 500; seed++) {
|
||||
const s = seotda.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
if (s.hand!.dealer === dealer) return s;
|
||||
if (s.hand!.dealer === dealer) return scaleMoney(s, 1 / 1000);
|
||||
}
|
||||
throw new Error('no seed with that dealer');
|
||||
}
|
||||
@@ -350,7 +368,7 @@ describe('재경기', () => {
|
||||
expect(s.stats.rematches).toBe(1);
|
||||
});
|
||||
|
||||
function gusaHand(opts: Partial<SeotdaOptions>) {
|
||||
function gusaHand(opts: OldOpts) {
|
||||
let s = make({ dealMode: 'oneRound', ...opts });
|
||||
s = rig(s, { A: [P(4), S(9)], B: [S(1), P(2)], C: [P(5), P(6)] });
|
||||
s = act(s, 'A', { type: 'check' });
|
||||
@@ -377,7 +395,7 @@ describe('재경기', () => {
|
||||
let s = gusaHand({ rejoinCost: 'full' });
|
||||
expect(s.hand!.rejoinCost).toBe(30);
|
||||
s.seats[2]!.stack = 20;
|
||||
expect(reject(s, 'C', { type: 'rejoin', accept: true })).toBe('칩이 모자라 재참가할 수 없어요.');
|
||||
expect(reject(s, 'C', { type: 'rejoin', accept: true })).toBe('보유 금액이 모자라 재참가할 수 없어요.');
|
||||
expect(seotda.legalActions!(s, 'C')).toEqual([{ type: 'rejoin', accept: false }]);
|
||||
s = act(s, 'C', { type: 'timeout' });
|
||||
expect(s.hand!.order).toEqual(['A', 'B']);
|
||||
@@ -547,7 +565,7 @@ describe('timeouts, away, leaving', () => {
|
||||
|
||||
describe('rebuy, elimination, scores', () => {
|
||||
/** Ends the current hand by folds, then sets stacks before the hand-end processing. */
|
||||
function toHandEnd(opts: Partial<SeotdaOptions>, players = ['A', 'B', 'C']): SeotdaState {
|
||||
function toHandEnd(opts: OldOpts, players = ['A', 'B', 'C']): SeotdaState {
|
||||
let s = make({ dealMode: 'oneRound', ...opts }, players);
|
||||
while (s.hand!.phase !== 'handEnd') s = act(s, seotda.activePlayers(s)[0]!, { type: 'die' });
|
||||
return s;
|
||||
@@ -617,10 +635,132 @@ describe('rebuy, elimination, scores', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('한게임 방식 (원 단위, 기본 설정)', () => {
|
||||
/** A game with the real options (no CLASSIC rules, no unit scaling). */
|
||||
function hg(opts: Partial<SeotdaOptions> = {}, players = ['A', 'B', 'C'], dealer = 'A'): SeotdaState {
|
||||
const options = seotda.optionsSchema.parse(opts);
|
||||
for (let seed = 1; seed < 500; seed++) {
|
||||
const s = seotda.setup({ players, options, rng: SeededRng.fromSeed(seedN(seed)), now: 0 });
|
||||
if (s.hand!.dealer === dealer) return s;
|
||||
}
|
||||
throw new Error('no seed with that dealer');
|
||||
}
|
||||
|
||||
test('2장을 한 번에 받고 한 번 베팅한 뒤 공개, 금액은 원 (기본금 1만원 × 3명 = 판돈 3만원)', () => {
|
||||
let s = hg();
|
||||
expect(Object.values(s.hand!.cards).map((c) => c.length)).toEqual([2, 2, 2]);
|
||||
const v = seotda.view(s, 'A');
|
||||
expect([v.pot, v.baseUnit, v.seats[0]!.stack]).toEqual([30_000, 10_000, 990_000]);
|
||||
expect(v.legal.map((l) => l.type)).toEqual(['check', 'ping', 'half', 'die']); // 쿼터는 한게임에 없어 기본으로 꺼 둠
|
||||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||||
expect(s.hand!.phase).toBe('handEnd');
|
||||
expect(s.hand!.showdown).not.toBeNull();
|
||||
});
|
||||
|
||||
test('베팅 규칙 222: 선과 다음 사람은 첫 베팅에서 하프·다이만, 그 뒤는 자유', () => {
|
||||
let s = hg({ betRule: '222' });
|
||||
const v = seotda.view(s, 'A');
|
||||
expect(v.forcedHalf).toBe(true);
|
||||
expect(v.legal.map((l) => l.type)).toEqual(['half', 'die']);
|
||||
expect(reject(s, 'A', { type: 'check' })).toBe('베팅 규칙 222: 지금은 하프 또는 다이만 할 수 있어요.');
|
||||
s = act(s, 'A', { type: 'half' });
|
||||
expect(seotda.view(s, 'B').legal.map((l) => l.type)).toEqual(['half', 'die']);
|
||||
s = act(s, 'B', { type: 'half' });
|
||||
const c = seotda.view(s, 'C');
|
||||
expect(c.forcedHalf).toBe(false);
|
||||
expect(c.legal.map((l) => l.type)).toEqual(['call', 'ddadang', 'half', 'die']);
|
||||
expect(c.betLog.map((e) => [e.p, e.t])).toEqual([
|
||||
['A', 'half'],
|
||||
['B', 'half'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('베팅 규칙 111: 선이 시간을 넘기면 체크가 아니라 다이', () => {
|
||||
let s = hg({ betRule: '111' });
|
||||
s = act(s, 'A', { type: 'timeout' }, 21_000);
|
||||
expect(s.hand!.lastAction.A!.type).toBe('die');
|
||||
});
|
||||
|
||||
test('쿼터를 켠 방만 쿼터를 받음', () => {
|
||||
const off = hg();
|
||||
expect(reject(off, 'A', { type: 'quarter' })).toBe('이 방은 쿼터 베팅을 쓰지 않아요.');
|
||||
const on = hg({ quarter: true });
|
||||
expect(seotda.view(on, 'A').legal.map((l) => l.type)).toContain('quarter');
|
||||
});
|
||||
|
||||
test('40장: 1~10월 4장 모두 쓰고, 3장 섯다도 10명까지', () => {
|
||||
const s = hg({ deck: 40 });
|
||||
const all = [...s.hand!.deck, ...Object.values(s.hand!.cards).flat()].sort((a, b) => a - b);
|
||||
expect(all).toEqual(Array.from({ length: 40 }, (_, i) => i));
|
||||
expect(seotda.playersFor!({ ...seotda.defaultOptions, deck: 40, cardMode: 'three' })).toEqual({ min: 2, max: 10 });
|
||||
});
|
||||
|
||||
test('행동 제한 시간 무제한: 베팅·고르기에 마감이 없고, 판 결과 화면만 시간이 흐름', () => {
|
||||
let s = hg({ turnSeconds: null });
|
||||
expect(s.deadlineAt).toBeNull();
|
||||
for (const p of ['A', 'B', 'C']) s = act(s, p, { type: 'check' });
|
||||
expect(s.hand!.phase).toBe('handEnd');
|
||||
expect(s.deadlineAt).not.toBeNull();
|
||||
const three = hg({ turnSeconds: null, cardMode: 'three' });
|
||||
let t = three;
|
||||
for (const p of ['A', 'B', 'C']) t = act(t, p, { type: 'check' });
|
||||
expect(t.hand!.phase).toBe('choose');
|
||||
expect(t.deadlineAt).toBeNull();
|
||||
});
|
||||
|
||||
test('판이 끝나면 각자 얼마를 따고 잃었는지(handDelta)', () => {
|
||||
let s = hg();
|
||||
s = act(s, 'A', { type: 'half' }); // 1만 5천원
|
||||
s = act(s, 'B', { type: 'die' });
|
||||
s = act(s, 'C', { type: 'die' });
|
||||
const v = seotda.view(s, null);
|
||||
expect(v.foldWin).toEqual({ winner: 'A', amount: 30_000 });
|
||||
expect(v.seats.map((x) => x.handDelta)).toEqual([20_000, -10_000, -10_000]);
|
||||
});
|
||||
|
||||
test('v1(칩) 방 상태를 v2(원)로 옮김: 금액 × 1000, 진행 중 규칙은 그대로(쿼터 켬, 20장, 일반 베팅)', () => {
|
||||
let s = make({ dealMode: 'twoRounds' }); // old units: 시작 1,000 / 학교 10
|
||||
s = act(s, 'A', { type: 'half' });
|
||||
const v1 = structuredClone(s) as unknown as Record<string, unknown>;
|
||||
const o = { ...(v1.options as Record<string, unknown>) };
|
||||
delete o.deck;
|
||||
delete o.betRule;
|
||||
delete o.quarter;
|
||||
v1.options = o;
|
||||
const h = v1.hand as Record<string, unknown>;
|
||||
delete h.forced;
|
||||
delete h.log;
|
||||
const m = seotda.migrate!(v1, 1);
|
||||
expect(seotda.stateVersion).toBe(2);
|
||||
expect([m.options.startingChips, m.options.baseUnit, m.baseUnit]).toEqual([1_000_000, 10_000, 10_000]);
|
||||
expect(m.options).toMatchObject({ deck: 20, betRule: 'free', quarter: true });
|
||||
expect(m.seats.map((x) => x.stack)).toEqual(s.seats.map((x) => x.stack * 1000));
|
||||
expect(chipsTotal(m)).toBe(chipsTotal(s) * 1000);
|
||||
expect(seotda.view(m, 'B').legal.find((l) => l.type === 'call')!.amount).toBe(15_000);
|
||||
expect(m.hand!.log).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('options', () => {
|
||||
test('schema defaults and validation', () => {
|
||||
expect(seotda.defaultOptions).toMatchObject({ cardMode: 'two', dealMode: 'twoRounds', startingChips: 1000, baseUnit: 10, rebuy: 'unlimited' });
|
||||
expect(seotda.optionsSchema.safeParse({ startingChips: 500, baseUnit: 50 }).success).toBe(false);
|
||||
// 한게임 섯다처럼: 2장을 한 번에 받고 한 번 베팅, 20장, 일반 베팅, 쿼터 없음, 땡잡이 3·7 아무 패, 멍구사 9땡까지, 원 단위.
|
||||
expect(seotda.defaultOptions).toMatchObject({
|
||||
cardMode: 'two',
|
||||
dealMode: 'oneRound',
|
||||
deck: 20,
|
||||
betRule: 'free',
|
||||
quarter: false,
|
||||
ttaengjabi: 'loose',
|
||||
mungGusa: 'upTo9',
|
||||
startingChips: 1_000_000,
|
||||
baseUnit: 10_000,
|
||||
rebuy: 'unlimited',
|
||||
turnSeconds: 20,
|
||||
});
|
||||
expect(seotda.optionsSchema.safeParse({ startingChips: 500_000, baseUnit: 50_000 }).success).toBe(false);
|
||||
expect(seotda.optionsSchema.safeParse({ turnSeconds: null }).success).toBe(true);
|
||||
// Rooms saved with the old chip options fall back to the defaults instead of failing.
|
||||
expect(seotda.optionsSchema.parse({ startingChips: 1000, baseUnit: 10 })).toMatchObject({ startingChips: 1_000_000, baseUnit: 10_000 });
|
||||
expect(seotda.playersFor!({ ...seotda.defaultOptions, cardMode: 'three' })).toEqual({ min: 2, max: 6 });
|
||||
expect(seotda.playersFor!(seotda.defaultOptions)).toEqual({ min: 2, max: 10 });
|
||||
expect(() => seotda.setup({ players: 'ABCDEFG'.split(''), options: { ...seotda.defaultOptions, cardMode: 'three' }, rng: rng(), now: 0 })).toThrow();
|
||||
@@ -650,8 +790,10 @@ describe('random playouts', () => {
|
||||
['기본', {}, 4, 4],
|
||||
['2장 한 번에·나눔·풀', { dealMode: 'oneRound', tieRule: 'split', maxRaise: 'full' }, 5, 3],
|
||||
['3장 섯다·재참가 절반', { cardMode: 'three', rejoinCost: 'half', ttaengjabi: 'loose' }, 6, 3],
|
||||
['최후 1인·리바이 없음·회전', { endCondition: 'lastStanding', rebuy: 'off', dealerRule: 'rotate', baseUnit: 50, startingChips: 1000 }, 3, 4],
|
||||
['10명·전액 재참가', { rejoinCost: 'full', mungGusa: 'upToJang', handLimit: 10, startingChips: 500, baseUnit: 2 }, 10, 2],
|
||||
['최후 1인·리바이 없음·회전', { endCondition: 'lastStanding', rebuy: 'off', dealerRule: 'rotate', baseUnit: 50_000, startingChips: 1_000_000 }, 3, 4],
|
||||
['10명·전액 재참가', { rejoinCost: 'full', mungGusa: 'upToJang', handLimit: 10, startingChips: 500_000, baseUnit: 2_000 }, 10, 2],
|
||||
['1장씩·쿼터·베팅 규칙 333', { dealMode: 'twoRounds', quarter: true, betRule: '333' }, 5, 3],
|
||||
['40장·3장 섯다·8명', { deck: 40, cardMode: 'three', betRule: '111' }, 8, 2],
|
||||
['2명·학교 상승·제한 리바이', { schoolUpEvery: 5, rebuy: 'limited', rebuyLimit: 2, handLimit: 30 }, 2, 4],
|
||||
];
|
||||
test.each(configs)('%s: finishes, chips conserved, no leaks, deterministic', (_n, opts, n, runs) => {
|
||||
@@ -673,7 +815,12 @@ describe('random playouts', () => {
|
||||
for (let seed = 1; seed <= LEAK_SEEDS; seed++) {
|
||||
const n = 2 + (seed % 5);
|
||||
const players = Array.from({ length: n }, (_, i) => `P${i}`);
|
||||
const options = seotda.optionsSchema.parse({ cardMode: seed % 3 === 0 ? 'three' : 'two', dealMode: seed % 4 === 1 ? 'oneRound' : 'twoRounds' });
|
||||
const options = seotda.optionsSchema.parse({
|
||||
cardMode: seed % 3 === 0 ? 'three' : 'two',
|
||||
dealMode: seed % 4 === 1 ? 'oneRound' : 'twoRounds',
|
||||
deck: seed % 7 === 0 ? 40 : 20,
|
||||
betRule: seed % 5 === 2 ? '222' : 'free',
|
||||
});
|
||||
const r = SeededRng.fromSeed(seedN(seed));
|
||||
const chooser = SeededRng.fromSeed(seedN(seed + 77));
|
||||
let s = seotda.setup({ players, options, rng: r, now: 0 });
|
||||
|
||||