Files
joke-app/apps/web/src/games/seotda/board.tsx

725 lines
37 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 섯다 판 화면 (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>
);
}