Files
joke-app/apps/web/src/games/poker/index.tsx

1345 lines
68 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 포커 화면 (docs/games/poker.md §9). Chips are room-only play points. */
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { BetActionType, LegalBetView, LogEntry, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { PLAYING_CARD_CREDIT, PlayingCard } from '../../components/cards/PlayingCard';
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useChange } from '../card-fx';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { fxAnim, fxMs } from '../../lib/motion';
const MODE_KO: Record<PokerMode, string> = {
holdem: '텍사스 홀덤',
omaha: '오마하',
sevenPoker: '7포커',
sevenHiLo: '7포커 하이로우',
badugi: '바둑이',
fiveDraw: '5카드 드로우',
indian: '인디언 포커',
};
const KOREAN_ORDER: BetActionType[] = ['k.die', 'k.check', 'k.ping', 'k.call', 'k.ddadang', 'k.quarter', 'k.half', 'k.full'];
const BET_KO: Record<BetActionType, string> = {
'k.check': '체크',
'k.ping': '삥',
'k.call': '콜',
'k.ddadang': '따당',
'k.quarter': '쿼터',
'k.half': '하프',
'k.full': '풀',
'k.die': '다이',
'nl.fold': '폴드',
'nl.check': '체크',
'nl.call': '콜',
'nl.raise': '레이즈',
'nl.allIn': '올인',
};
const BET_HELP: Partial<Record<BetActionType, string>> = {
'k.check': '칩을 걸지 않고 넘겨요',
'k.ping': '기본 칩만큼 걸어요',
'k.call': '앞사람만큼 맞춰요',
'k.ddadang': '앞사람이 건 만큼의 두 배',
'k.quarter': '모인 칩의 4분의 1만큼 더',
'k.half': '모인 칩의 절반만큼 더',
'k.full': '모인 칩만큼 더',
'k.die': '이번 판을 포기해요',
};
const SIDE_KO: Record<Side, string> = { high: '하이', low: '로우', swing: '스윙' };
const AWARD_KO = { high: '하이', low: '로우', scoop: '스윙 성공', carry: '넘어온 칩', penalty: '벌칙 칩', refund: '돌려받음' } as const;
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 isCommunity = (m: PokerMode) => m === 'holdem' || m === 'omaha';
const isSevenMode = (m: PokerMode) => m === 'sevenPoker' || m === 'sevenHiLo';
const isDrawMode = (m: PokerMode) => m === 'badugi' || m === 'fiveDraw';
/** Rank of a card id for the client-side "A를 남기면 4장" check. */
const isAce = (c: string) => c[0] === 'A';
const CSS = `
.pk-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); }
.pk-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -50%); width: var(--seat-w, 172px); 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; }
.pk-seat.turn { border-color: var(--focus); }
.pk-seat.me { border-color: var(--primary); }
.pk-seat.me.turn { border-color: var(--focus); }
.pk-seat.win { border-color: #f59e0b; }
.pk-seat.out { opacity: 0.6; }
.pk-center { position: absolute; left: 50%; top: 48%; transform: translate(-50%, -50%); text-align: center; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,.5); max-width: 52%; }
.pk-board { display: flex; gap: 6px; justify-content: center; margin: 6px 0; }
.pk-slot { width: 64px; height: 90px; border-radius: 8px; border: 2px dashed rgba(255,255,255,.35); flex: none; }
.pk-actions { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.pk-actions .btn { min-height: 64px; flex-direction: column; gap: 0; padding: 0 8px; line-height: 1.15; font-size: 1.1rem; }
.pk-actions .btn small { font-weight: 600; font-size: .85rem; opacity: .9; }
.pk-mine { display: flex; gap: 4px; align-items: flex-end; flex-wrap: wrap; justify-content: center; }
.pk-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .78rem; }
.pk-x { position: relative; }
.pk-x::after { content: '✕'; position: absolute; inset: 0; display: grid; place-items: center; color: #dc2626; font-size: 3rem; font-weight: 900; pointer-events: none; }
.pk-raise { display: grid; gap: 8px; }
.pk-raise input[type=range] { width: 100%; min-height: 40px; }
@media (max-width: 719px) {
.pk-table { aspect-ratio: auto; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 10px; border-radius: 20px; border-width: 6px; }
.pk-seat { position: static; transform: none; width: auto; }
.pk-center { position: static; transform: none; grid-column: 1 / -1; order: -1; max-width: none; padding: 8px 0; }
.pk-slot { width: 44px; height: 62px; }
.pk-actions { grid-template-columns: repeat(2, 1fr); }
}
/* The face-down copy that turns away when a card is turned over (see turnOver). */
.pk-back { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; border-radius: 9% / 6.4%; background: #1e3a8a; border: 2px solid #fff;
box-shadow: inset 0 0 0 3px #1e3a8a, inset 0 0 0 5px #93c5fd, 0 1px 3px rgba(0,0,0,.3); backface-visibility: hidden; }
`;
// ---------------------------------------------------------------- seats
function seatBadges(seat: SeatView, v: PokerView): [string, string][] {
const b: [string, string][] = [];
if (seat.status === 'left') b.push(['나감', 'var(--danger)']);
else if (seat.away) b.push(['자리 비움', 'var(--warning)']);
if (seat.status === 'eliminated') b.push(['탈락', 'var(--text-sub)']);
if (seat.status === 'busted' || seat.rebuyPending) b.push(['리바이 대기', 'var(--warning)']);
if (seat.folded) b.push([v.betStyle === 'korean' ? '다이' : '폴드', 'var(--danger)']);
if (seat.allIn) b.push(['올인', 'var(--primary)']);
const contesting = seat.inHand && !seat.folded;
if (contesting && v.handPhase === 'choice') b.push(seat.choiceDone ? ['고름', 'var(--success)'] : ['고르는 중', 'var(--text-sub)']);
if (contesting && v.handPhase === 'draw') b.push(seat.drawDone ? ['냄', 'var(--success)'] : ['바꿀 카드 고르는 중', 'var(--text-sub)']);
if (contesting && v.handPhase === 'declare') b.push(seat.declared ? ['선언함', 'var(--success)'] : ['선언 고르는 중', 'var(--text-sub)']);
if (seat.declare) b.push([`선언: ${SIDE_KO[seat.declare]}`, '#7c3aed']);
if (v.handPhase === 'reveal' && v.waiting.includes(seat.id)) b.push(['카드 공개 고르는 중', 'var(--text-sub)']);
return b;
}
function SeatCards({ seat, v, me }: { seat: SeatView; v: PokerView; me: string | null }) {
const sd = v.showdown?.find((e) => e.id === seat.id);
const cards: { c: ViewCard; key: string; title?: string }[] = [];
if (seat.forehead !== undefined) cards.push({ c: seat.forehead, key: 'f', title: seat.forehead ? undefined : seat.id === me ? '내 이마 카드(나만 못 봐요)' : '이마 카드' });
// Hidden cards arrive as null; at showdown the view already reveals them.
seat.hole.forEach((c, i) => cards.push({ c, key: `h${i}` }));
for (let i = 0; i < seat.choiceCount; i++) cards.push({ c: null, key: `c${i}` });
seat.up.forEach((c, i) => cards.push({ c, key: `u${i}` }));
if (!cards.length) return null;
const best = new Set(sd?.best ?? []);
return (
<div style={{ display: 'flex', flexWrap: 'nowrap', justifyContent: 'center' }} data-fx="seat-cards">
{cards.map((x, i) => (
<PlayingCard
key={x.key}
card={x.c}
size="sm"
highlight={!!x.c && best.has(x.c)}
title={x.title}
style={i > 0 ? { marginLeft: cards.length > 5 ? -24 : -16 } : undefined}
/>
))}
</div>
);
}
function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v: PokerView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: number }) {
const u = userOf(players, seat.id);
const badges = seatBadges(seat, v);
const waiting = v.waiting.includes(seat.id) && v.handPhase !== 'handEnd';
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
const won = v.handPhase === 'handEnd' && v.winners.includes(seat.id);
const sd = v.showdown?.find((e) => e.id === seat.id);
const marks: [string, string, string][] = [];
if (seat.dealer) marks.push(['D', '#facc15', '딜러']);
if (seat.sb) marks.push(['SB', '#93c5fd', '스몰 블라인드']);
if (seat.bb) marks.push(['BB', '#60a5fa', '빅 블라인드']);
if (seat.boss) marks.push(['보스', '#fb923c', '보스(먼저 베팅)']);
return (
<div
className={`pk-seat${waiting ? ' turn anim-glow' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
data-fx-seat={seat.id}
aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${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>
{marks.map(([t, c, title]) => (
<span key={t} className="pk-badge" style={{ background: c, color: '#1f2937' }} title={title}>
{t}
</span>
))}
{waiting && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={seat.id === me} size={28} />}
</div>
<div className="row" style={{ gap: 6, justifyContent: 'space-between' }}>
<Chips n={seat.stack} strong />
{seat.roundBet > 0 && <span className="small" title="이번 라운드에 건 칩">+{seat.roundBet.toLocaleString('ko-KR')}</span>}
</div>
{seat.lastAction && !seat.folded && <span className="small muted">{seat.lastAction}</span>}
{seat.drawCounts.length > 0 && <span className="small muted">바꾼 장수: {seat.drawCounts.join(' · ')}</span>}
{badges.length > 0 && (
<div className="row" style={{ gap: 3 }}>
{badges.map(([t, c]) => (
<span key={t} className="pk-badge" style={{ background: c, color: '#fff' }}>
{t}
</span>
))}
</div>
)}
<SeatCards seat={seat} v={v} me={me} />
{!sd && v.foldShown?.id === seat.id && <strong style={{ color: 'var(--primary)', textAlign: 'center' }}>{v.foldShown.handName}</strong>}
{sd && (
<strong style={{ color: 'var(--primary)', textAlign: 'center' }}>
{sd.handName}
{sd.lowName !== undefined && <span className="small"> / 로우 {sd.lowName ?? '없음'}</span>}
</strong>
)}
</div>
);
}
function CenterInfo({ v, players }: { v: PokerView; players: Record<string, PublicUser> }) {
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
const penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
return (
<div className="pk-center" data-fx="poker-center">
{v.streetName && <div className="pk-badge" style={{ background: '#fde047', color: '#422006', fontSize: '0.95rem', padding: '2px 12px' }}>{v.streetName}</div>}
{isCommunity(v.mode) && (
<div className="pk-board" aria-label="공용 카드" data-fx="poker-board">
{Array.from({ length: 5 }, (_, i) => (v.board[i] ? <PlayingCard key={v.board[i]} card={v.board[i]!} size="md" /> : <span key={`e${i}`} className="pk-slot" aria-hidden />))}
</div>
)}
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite" data-fx="poker-pot">
{formatChips(v.pot)}
</div>
{v.pots.length > 1 && (
<div className="small" style={{ opacity: 0.9 }}>
{v.pots.map((p, i) => (
<div key={i}>
{i === 0 ? '메인' : `사이드 ${i}`}: {formatChips(p.amount)} ({p.eligible.map((id) => nick(players, id)).join('·')})
</div>
))}
</div>
)}
{(v.carryOver > 0 || penalty > 0) && (
<div className="small" style={{ opacity: 0.9 }}>
{v.carryOver > 0 && `지난 판에서 넘어온 칩 ${formatChips(v.carryOver)}`}
{v.carryOver > 0 && penalty > 0 && ' · '}
{penalty > 0 && `벌칙 칩 ${formatChips(penalty)}`}
</div>
)}
<div className="small" style={{ opacity: 0.85, marginTop: 4 }}>
{v.phase === 'finished' ? '게임 끝' : `${Math.max(1, v.handNo)}${limit}판`} · 기본 {formatChips(v.baseUnit)}
{v.level > 1 ? ` (레벨 ${v.level})` : ''}
</div>
</div>
);
}
// ---------------------------------------------------------------- board
function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps<PokerView>) {
const n = v.seats.length;
const myIdx = Math.max(0, v.seats.findIndex((s) => s.id === me));
const [announce, setAnnounce] = useState('');
const prevWaiting = useRef(false);
const mine = isMyTurn(v, me);
const showKey = `${v.handNo}-${v.handPhase}`;
const [banner, showBanner] = useBanner();
usePokerFx(v, me, players, showBanner);
useEffect(() => {
if (mine && !prevWaiting.current) {
haptic(40);
sounds.myTurn();
setAnnounce('내 차례예요.');
} else if (v.toAct && v.toAct !== me) setAnnounce(`${nick(players, v.toAct)}님 차례예요.`);
prevWaiting.current = mine;
}, [mine, v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (v.handPhase !== 'handEnd') return;
setAnnounce(resultLine(v, players));
if (me && v.winners.includes(me)) sounds.win();
}, [showKey]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="board-wrap stack" style={{ gap: 12 }}>
<style>{CSS}</style>
<div className="pk-table" role="region" aria-label="포커 테이블" style={{ '--seat-w': n > 6 ? '150px' : '176px' } 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} v={v} players={players} me={me} deadline={deadline} x={50 + 40 * Math.cos(ang)} y={50 + 38 * Math.sin(ang)} />;
})}
<CenterInfo v={v} players={players} />
</div>
<MyArea v={v} me={me} players={players} act={act} pending={pending} />
<p className="sr-only" aria-live="polite">
{announce}
</p>
{banner}
</div>
);
}
// ---------------------------------------------------------------- sounds + motion (2026-10-13)
/** 포커 sounds on top of the shared palette (synthesized, no files). */
const pokerSfx = {
/** 체크: two knuckle knocks on the felt. */
knock: (delay = 0) => {
for (const d of [0, 120]) {
tone(190, 60, 'sine', 0.22, delay + d, { slideTo: 120 });
noise(35, 0.1, delay + d, 'lowpass', 700);
}
},
/** 다이/폴드: cards slid away to the muck. */
fold: (delay = 0) => {
noise(220, 0.09, delay, 'bandpass', 800, 0.6);
tone(330, 160, 'triangle', 0.05, delay + 40, { slideTo: 200 });
},
/** 올인: a big push of chips with a low swell. */
allIn: (delay = 0) => {
for (let i = 0; i < 7; i++) sfx.chip(delay + i * 45);
tone(140, 360, 'sawtooth', 0.05, delay, { slideTo: 280 });
tone(70, 300, 'sine', 0.14, delay);
},
/** 하이·로우·스윙 선언 공개. */
declare: (delay = 0) => tone(660, 120, 'triangle', 0.1, delay, { slideTo: 990 }),
};
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, fxMs(ms)) : f());
/** Card turned over in place (WAAPI so React's own style/transform stays). */
function flipIn(el: Element | null | undefined, delay = 0): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
fxAnim((el as HTMLElement).animate(
[
{ transform: 'perspective(600px) rotateY(90deg)' },
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.6 },
{ transform: 'perspective(600px) rotateY(0deg)' },
],
{ duration: 420, delay, easing: 'ease', fill: 'backwards', composite: 'add' },
));
}
/**
* A face-down card turned face up (showdown, 인디언 forehead): a face-down copy turns away on top of it, then the real
* (already face-up) card turns in. The copy is fixed-position, never takes clicks and is removed when done.
*/
function turnOver(el: Element | null | undefined, delay = 0): void {
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
const r = el.getBoundingClientRect();
if (!r.width || !r.height) return;
const half = 180;
const back = document.createElement('div');
back.className = 'pk-back';
back.setAttribute('aria-hidden', 'true');
Object.assign(back.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
document.body.appendChild(back);
const a = fxAnim(back.animate([{ transform: 'perspective(600px) rotateY(0deg)' }, { transform: 'perspective(600px) rotateY(-90deg)' }], { duration: half, delay, easing: 'ease-in', fill: 'both' }));
const done = () => back.remove();
a.onfinish = done;
a.oncancel = done;
setTimeout(done, fxMs(delay + half) + 1500);
fxAnim((el as HTMLElement).animate(
[
{ transform: 'perspective(600px) rotateY(90deg)' },
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.65 },
{ transform: 'perspective(600px) rotateY(0deg)' },
],
{ duration: 300, delay: delay + half, easing: 'ease-out', fill: 'backwards', composite: 'add' },
));
}
/** The card elements of a seat on the table (forehead, hole, choice, up — same order as SeatCards). */
const seatCardEls = (id: string): Element[] => [...(seatEl(id)?.querySelector('[data-fx="seat-cards"]')?.children ?? [])];
const myCardEl = (slot: string) => document.querySelector(`[data-fx="poker-mine"] [data-slot="${cssEsc(slot)}"]`);
const cardCount = (s: SeatView) => (s.forehead !== undefined ? 1 : 0) + s.hole.length + s.choiceCount + s.up.length;
/** My visible card slots (ids where I can see them) — a new id means a card just came to me. */
function mySlots(v: PokerView, me: string | null): string[] {
const seat = v.seats.find((s) => s.id === me);
if (!seat) return [];
const out: string[] = [];
seat.hole.forEach((c, i) => out.push(c ?? `h${i}`));
seat.up.forEach((c, i) => out.push(c ?? `u${i}`));
if (v.my.choice) out.push(...v.my.choice);
return out;
}
const sameEntry = (a: LogEntry, b: LogEntry) => a.hand === b.hand && a.by === b.by && a.msg === b.msg;
/** Entries appended to the (sliding, last-30) log since `prev`; null when the two don't line up (resync/jump). */
function newLogEntries(prev: readonly LogEntry[], next: readonly LogEntry[]): LogEntry[] | null {
for (let d = 0; d <= next.length; d++) {
const keep = next.length - d;
if (keep > prev.length) continue;
if (keep === 0) return prev.length === 0 ? [...next] : null;
let ok = true;
for (let i = 0; i < keep && ok; i++) ok = sameEntry(next[i]!, prev[prev.length - keep + i]!);
if (ok) return next.slice(keep);
}
return null;
}
const BET_RE = /^(삥|콜|따당|쿼터|하프|풀|레이즈|벳|올인) (\d+) 칩/;
const DRAW_RE = /(\d)장 바꿈|박스\((\d)장\)/;
/**
* Sounds + motion for every change of the table, mine or anyone else's (log entries and view diffs since the last
* view). Nothing on the first render (join, reload, replay jump).
*/
function usePokerFx(v: PokerView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
const prev = useRef<PokerView | null>(null);
const chipN = (amount: number) => Math.max(1, Math.min(6, Math.round(Math.log2(1 + amount / Math.max(1, v.baseUnit)))));
const center = () => fxEl('poker-center');
const pot = () => fxEl('poker-pot');
/** New hand (or the very first one on mount): antes/blinds to the pot, then cards from the middle to everyone. */
const deal = (p: PokerView | null) => {
sfx.shuffle();
const inHand = v.seats.filter((s) => s.inHand && s.status !== 'left');
inHand.forEach((s, i) => {
if (s.handBet > 0) flyGhost(seatEl(s.id), pot(), { kind: 'chip', count: Math.min(3, chipN(s.handBet)), delay: i * 50 });
});
if (v.pot > 0) later(150, () => sfx.chips(3));
const per = Math.max(0, ...inHand.map(cardCount));
later(320, () => sfx.deal(Math.min(8, per * Math.max(1, inHand.length)), 55));
inHand.forEach((s, i) => {
if (s.id !== me) flyGhost(center(), seatEl(s.id), { count: Math.min(4, cardCount(s)), gap: 90, delay: 320 + i * 60 });
});
const known = new Set(p ? mySlots(p, me) : []);
mySlots(v, me)
.filter((k) => !known.has(k))
.forEach((k, i) => flyFrom(myCardEl(k), center(), { delay: 320 + i * 80, rotate: 10 }));
if (v.seats.find((s) => s.id === me)?.forehead !== undefined) flyFrom(myCardEl('f'), center(), { delay: 320, rotate: -10 });
};
useLayoutEffect(() => {
const p = prev.current;
prev.current = v;
if (!p || p === v) return;
const newHand = v.handNo !== p.handNo && v.handNo > 0;
let t = 0;
if (newHand) {
deal(p);
t = 600;
} else if (v.handNo > 0) {
// Cards dealt during the hand (7포커 streets, 인디언 2nd card …) and community cards.
let dealt = 0;
v.seats.forEach((s) => {
const before = p.seats.find((x) => x.id === s.id);
const k = before ? cardCount(s) - cardCount(before) : 0;
if (k > 0 && s.id !== me) flyGhost(center(), seatEl(s.id), { count: Math.min(4, k), gap: 90, delay: dealt * 70 });
if (k > 0) dealt += k;
});
const known = new Set(mySlots(p, me));
const mine = mySlots(v, me).filter((k) => !known.has(k));
mine.forEach((k, i) => flyFrom(myCardEl(k), center(), { delay: i * 80, rotate: 10 }));
if (dealt > 0) sfx.deal(Math.min(8, dealt), 60);
const boardEl = fxEl('poker-board');
for (let i = p.board.length; i < v.board.length; i++) {
const at = (i - p.board.length) * 140;
flipIn(boardEl?.children[i], at);
later(at, sfx.cardFlip);
}
if (v.board.length > p.board.length) t = (v.board.length - p.board.length) * 140;
// Showdown: hidden cards are turned over seat by seat.
if (v.showdown && !p.showdown) {
let n = 0;
for (const e of v.showdown) {
const s = v.seats.find((x) => x.id === e.id);
if (!s || s.id === me) continue;
const els = seatCardEls(s.id);
const off = s.forehead !== undefined ? 1 : 0;
const at = t + n * 220;
for (let i = 0; i < s.hole.length; i++) turnOver(els[off + i], at + i * 60);
later(at + 120, sfx.cardFlip);
n++;
}
t += n * 220 + 200;
}
// Everyone else folded and the last player showed the cards: turn them over.
const fs = v.foldShown;
if (fs && !p.foldShown && fs.id !== me) {
const s = v.seats.find((x) => x.id === fs.id);
const els = seatCardEls(fs.id);
const off = s?.forehead !== undefined ? 1 : 0;
for (let i = 0; i < (s?.hole.length ?? 0); i++) turnOver(els[off + i], t + i * 60);
later(t + 120, sfx.cardFlip);
t += 400;
}
// 인디언: my own forehead card is shown at the end of the hand.
const myNow = v.seats.find((s) => s.id === me);
const myBefore = p.seats.find((s) => s.id === me);
if (myNow?.forehead && myBefore && !myBefore.forehead) {
turnOver(myCardEl('f'), t);
later(t + 120, sfx.cardFlip);
t += 300;
}
}
const fresh = newLogEntries(p.log, v.log);
if (!fresh || fresh.length > 12) return;
for (const e of fresh) {
const at = t;
const by = e.by;
const msg = e.msg;
if (!by) {
if (msg.includes('오픈 카드를 공개')) {
v.seats.forEach((s, i) => {
if (!s.up.length) return;
const els = seatCardEls(s.id);
flipIn(els[els.length - 1], at + i * 70);
});
later(at, sfx.cardFlip);
later(at + 140, sfx.cardFlip);
t += 200;
} else if (msg.includes('섞')) {
later(at, sfx.shuffle);
} else if (msg.includes('기본 단위가')) {
later(at, sfx.good);
bump(pot());
}
continue;
}
const bet = BET_RE.exec(msg);
if (bet) {
const amount = Number(bet[2]);
const n = chipN(amount);
flyGhost(seatEl(by), pot(), { kind: 'chip', count: n, gap: 60, delay: at });
if (msg.includes('올인')) {
later(at, () => pokerSfx.allIn());
later(at, () => showBanner('올인!', 'red', by === me ? undefined : `${nick(players, by)}님`));
bump(seatEl(by), 'shake');
} else later(at, () => sfx.chips(Math.min(5, n + 1)));
t += 140;
} else if (msg === '체크') {
later(at, () => pokerSfx.knock());
t += 120;
} else if (msg === '다이' || msg === '폴드' || msg.includes('나가서 다이')) {
const s = v.seats.find((x) => x.id === by);
flyGhost(seatEl(by), center(), { count: Math.min(3, s ? Math.max(1, cardCount(s)) : 2), gap: 50, delay: at });
later(at, () => pokerSfx.fold());
t += 130;
} else if (DRAW_RE.test(msg)) {
const m = DRAW_RE.exec(msg)!;
const k = Number(m[1] ?? m[2]);
flyGhost(seatEl(by), center(), { count: k, gap: 60, delay: at });
if (by !== me) flyGhost(center(), seatEl(by), { count: k, gap: 70, delay: at + 300 });
later(at, () => sfx.cardDeal());
later(at + 300, () => sfx.draw(Math.min(4, k)));
t += 150;
} else if (msg.endsWith('패스')) {
later(at, () => pokerSfx.knock());
t += 120;
} else if (msg.startsWith('선언:')) {
later(at, () => pokerSfx.declare());
bump(seatEl(by));
t += 120;
} else if (msg.includes('벌칙')) {
flyGhost(seatEl(by), pot(), { kind: 'chip', count: 4, gap: 50, delay: at });
later(at, sfx.alarm);
bump(seatEl(by), 'shake');
t += 200;
} else if (msg.includes('가져갔어요')) {
flyGhost(pot(), seatEl(by), { kind: 'chip', count: 6, gap: 55, delay: at + 150 });
later(at + 300, sfx.collect);
later(at + 500, () => bump(seatEl(by)));
t += 250;
} else if (msg.includes('다시 받았어요')) {
flyGhost(center(), seatEl(by), { kind: 'coin', count: 5, gap: 60, delay: at });
later(at, sfx.coin);
t += 150;
} else if (msg.includes('자리 비움')) {
later(at, sfx.tick);
}
}
});
// Pot amount pops when it grows (after the chips arrive).
useChange(v.pot, (now, before) => {
if (now > before) later(380, () => bump(pot()));
});
// Mounted right at the start of the game (nothing played yet): show the deal once.
const started = useRef(false);
useLayoutEffect(() => {
if (started.current) return;
started.current = true;
if (v.handNo === 1 && v.handPhase !== 'handEnd' && !v.log.some((e) => e.by !== null)) deal(null);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}
function resultLine(v: PokerView, players: Record<string, PublicUser>): string {
if (!v.awards) return '';
const won = new Map<string, number>();
for (const a of v.awards) if (a.side !== 'refund') won.set(a.to, (won.get(a.to) ?? 0) + a.amount);
if (!won.size) return v.carryOver > 0 ? `동점이라 ${formatChips(v.carryOver)}이 다음 판으로 넘어가요` : '이번 판은 칩을 모두 돌려받았어요';
const parts = [...won].map(([id, amt]) => {
const name = v.showdown?.find((e) => e.id === id)?.handName ?? (v.foldShown?.id === id ? v.foldShown.handName : undefined);
return `${nick(players, id)}님이 ${name ? `${name}(으)로 ` : ''}${formatChips(amt)}을 가져갔어요`;
});
return parts.join(' / ') + (v.foldWin ? ' (모두 포기)' : '');
}
function ResultPanel({ v, players }: { v: PokerView; players: Record<string, PublicUser> }) {
if (!v.awards) return null;
return (
<div className="card stack" style={{ gap: 6, padding: 12 }} aria-live="polite">
<strong>이번 판 결과</strong>
{v.foldWin && (
<span className="small muted">
{v.foldShown ? `한 명만 남았고, ${nick(players, v.foldShown.id)}님이 패를 공개했어요(${v.foldShown.handName}).` : '한 명만 남았고, 패는 공개하지 않았어요.'}
</span>
)}
{v.awards.map((a, i) => {
const sd = v.showdown?.find((e) => e.id === a.to);
const hand = !sd ? '' : a.side === 'low' ? (sd.lowName ? `로우 ${sd.lowName}` : '') : !a.side || a.side === 'high' || a.side === 'scoop' ? sd.handName : '';
return (
<span key={i}>
<strong>{nick(players, a.to)}</strong> {formatChips(a.amount)}
{hand && ` · ${hand}`}
<span className="muted">
{v.awards!.some((x) => x.potIndex > 0) ? ` · ${a.potIndex === 0 ? '메인' : `사이드 ${a.potIndex}`}` : ''}
{a.side ? ` · ${AWARD_KO[a.side]}` : ''}
</span>
</span>
);
})}
{v.awards.every((a) => a.side === 'refund') && v.carryOver > 0 && <span>동점이라 {formatChips(v.carryOver)}이 다음 판으로 넘어가요.</span>}
</div>
);
}
// ---------------------------------------------------------------- my area
interface AreaProps {
v: PokerView;
me: string | null;
players: Record<string, PublicUser>;
act: (a: unknown) => void;
pending: boolean;
}
function MyArea({ v, me, players, act, pending }: AreaProps) {
const seat = v.seats.find((s) => s.id === me);
if (!me || !seat) return v.handPhase === 'handEnd' ? <ResultPanel v={v} players={players} /> : null;
const m = v.my;
return (
<div className="stack" style={{ gap: 10 }}>
{seat.inHand && (
<div className="card stack" style={{ gap: 10, padding: 12 }}>
{m.canChoose && m.choice ? (
<ChoicePicker key={v.handNo} cards={m.choice} act={act} pending={pending} />
) : m.canDraw ? (
<DrawPicker key={`${v.handNo}-${seat.drawCounts.length}`} v={v} hole={seat.hole.filter((c): c is string => !!c)} act={act} pending={pending} />
) : (
<MyCards v={v} seat={seat} />
)}
{(m.handName || m.lowName) && (
<div style={{ textAlign: 'center', fontSize: '1.4rem', fontWeight: 900 }}>
지금: {m.handName}
{m.lowName && <span className="small" style={{ marginLeft: 8 }}>로우 {m.lowName}</span>}
</div>
)}
{seat.folded && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>이번 판은 포기했어요. 내 카드는 나만 볼 수 있어요.</p>}
{v.handPhase === 'choice' && seat.choiceDone && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>골랐어요. 다른 사람을 기다리는 중이에요.</p>}
{v.handPhase === 'draw' && seat.drawDone && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>바꿀 카드를 냈어요. 다른 사람을 기다리는 중이에요.</p>}
{m.canDeclare && <DeclarePicker v={v} act={act} pending={pending} />}
{v.handPhase === 'declare' && seat.declared && !m.canDeclare && (
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
{m.declare ? `${SIDE_KO[m.declare]}(으)로 선언했어요. ` : ''}다른 사람을 기다리는 중이에요.
</p>
)}
</div>
)}
{m.canReveal && <RevealBox v={v} act={act} pending={pending} />}
{v.handPhase === 'reveal' && !m.canReveal && v.waiting[0] && (
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
{nick(players, v.waiting[0])}님이 카드 공개 여부를 고르는 중이에요.
</p>
)}
{seat.inHand && v.handPhase === 'betting' && !seat.folded && !seat.allIn && <BetBar v={v} me={me} players={players} act={act} pending={pending} />}
{v.handPhase === 'handEnd' && <ResultPanel v={v} players={players} />}
{m.canReady && (
<button type="button" className="btn btn-primary btn-block" disabled={pending} onClick={() => act({ type: 'ready' })}>
다음 판으로
</button>
)}
{v.handPhase === 'handEnd' && seat.inHand && seat.ready && seat.status !== 'left' && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>다른 사람을 기다리는 중…</p>}
</div>
);
}
/** Everyone else folded: show my cards to everyone, or keep them hidden (the default when time runs out). */
function RevealBox({ v, act, pending }: { v: PokerView; act: (a: unknown) => void; pending: boolean }) {
return (
<div className="card stack" style={{ gap: 8, padding: 12 }} role="group" aria-label="카드 공개">
<p style={{ margin: 0, textAlign: 'center' }}>
<strong>모두 포기해서 모인 칩 {formatChips(v.pot)}은 내 거예요.</strong> 내 카드를 모두에게 보여 줄까요? 시간이 지나면 공개하지 않아요.
</p>
<div className="row">
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'reveal', show: true })}>
카드 공개
</button>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'reveal', show: false })}>
공개 안 함
</button>
</div>
</div>
);
}
function MyCards({ v, seat }: { v: PokerView; seat: SeatView }) {
const sd = v.showdown?.find((e) => e.id === seat.id);
const best = new Set(sd?.best ?? []);
return (
<div className="pk-mine" aria-label="내 카드" data-fx="poker-mine">
{seat.forehead !== undefined && (
<div className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot="f">
<PlayingCard card={seat.forehead} size="lg" title={seat.forehead ? undefined : '내 이마 카드(나만 못 봐요)'} />
<span className="small muted">이마</span>
</div>
)}
{seat.hole.map((c, i) => (
<div key={`h${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `h${i}`}>
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
{(isSevenMode(v.mode) || v.mode === 'indian') && <span className="small muted">{v.mode === 'indian' ? '손' : '나만 봄'}</span>}
</div>
))}
{seat.up.map((c, i) => (
<div key={`u${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `u${i}`}>
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
<span className="small muted">공개</span>
</div>
))}
</div>
);
}
/** 7포커 초이스: 1) 버릴 카드 2) 보여 줄 카드 → 확인 (§9). */
function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unknown) => void; pending: boolean }) {
const [discard, setDiscard] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const tap = (c: string) => {
sfx.select();
if (!discard) setDiscard(c);
else if (c === discard) {
setDiscard(null);
setOpen(null);
} else setOpen(open === c ? null : c);
};
return (
<div className="stack" style={{ gap: 8 }}>
<p style={{ margin: 0, textAlign: 'center' }}>
<strong>{!discard ? '1단계: 버릴 카드를 누르세요' : !open ? '2단계: 모두에게 보여 줄 카드를 누르세요' : '확인을 누르면 정해져요'}</strong>
<br />
<span className="small muted">버린 카드는 아무에게도 보이지 않아요. 남는 2장은 나만 봐요.</span>
</p>
<div className="pk-mine" data-fx="poker-mine">
{cards.map((c) => (
<span key={c} className={c === discard ? 'pk-x' : undefined} data-slot={c}>
<PlayingCard card={c} size="lg" selected={c === open} dimmed={c === discard} onClick={() => tap(c)} title={c === discard ? '버릴 카드(다시 누르면 취소)' : c === open ? '보여 줄 카드' : undefined} />
</span>
))}
</div>
<div className="row" style={{ justifyContent: 'center' }}>
<button
type="button"
className="btn btn-secondary"
disabled={!discard}
onClick={() => {
setDiscard(null);
setOpen(null);
}}
>
다시 고르기
</button>
<button type="button" className="btn btn-primary" disabled={!discard || !open || pending} onClick={() => act({ type: 'choose', discardId: discard, openId: open })}>
확인
</button>
</div>
</div>
);
}
/** 교환(바둑이 / 5카드 드로우): tap to lift the cards to change. */
function DrawPicker({ v, hole, act, pending }: { v: PokerView; hole: string[]; act: (a: unknown) => void; pending: boolean }) {
const [sel, setSel] = useState<string[]>([]);
const { drawMax, drawAceBonus } = v.my;
const keepsAce = hole.some((c) => isAce(c) && !sel.includes(c));
const limit = drawAceBonus && keepsAce ? drawMax + 1 : drawMax;
const tooMany = sel.length > limit;
const round = v.seats.find((s) => s.id === v.me)?.drawCounts.length ?? 0;
const label = v.mode === 'badugi' ? (['아침', '점심', '저녁'][round] ?? '교환') : '교환';
return (
<div className="stack" style={{ gap: 8 }}>
<p style={{ margin: 0, textAlign: 'center' }}>
<strong>{label}: 바꿀 카드를 누르세요</strong>
<br />
<span className="small muted">
{drawAceBonus ? '3장까지 바꿀 수 있어요(A를 남기면 4장).' : `${drawMax}장까지 바꿀 수 있어요.`} 모두 동시에 내고, 버린 카드는 공개되지 않아요.
</span>
</p>
<div className="pk-mine">
{hole.map((c) => (
<PlayingCard key={c} card={c} size="lg" selected={sel.includes(c)} onClick={() => {
sfx.select();
setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c]));
}}
/>
))}
</div>
{tooMany && <p className="field-error" style={{ margin: 0, textAlign: 'center' }}>{limit}장까지만 바꿀 수 있어요.</p>}
<button type="button" className="btn btn-primary btn-block" disabled={pending || tooMany} onClick={() => act({ type: 'draw', cardIds: sel })}>
{sel.length === 0 ? '패스(안 바꾸기)' : `${sel.length}장 바꾸기`}
</button>
</div>
);
}
function DeclarePicker({ v, act, pending }: { v: PokerView; act: (a: unknown) => void; pending: boolean }) {
const sub: Record<Side, string> = {
high: v.my.handName ?? '',
low: v.my.lowName ?? '로우 없음',
swing: '하이·로우 둘 다 이겨야 해요',
};
return (
<div className="stack" style={{ gap: 8 }}>
<p style={{ margin: 0, textAlign: 'center' }}>
<strong>하이·로우·스윙 중 하나를 선언하세요.</strong> <span className="small muted">모두 고른 뒤 한꺼번에 공개돼요.</span>
</p>
<div className="pk-actions" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
{(['high', 'low', 'swing'] as Side[]).map((side) => (
<button key={side} type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'declare', side })}>
<span>{SIDE_KO[side]}</span>
<small>{sub[side]}</small>
</button>
))}
</div>
</div>
);
}
function BetBar({ v, me, players, act, pending }: AreaProps & { me: string }) {
const myTurn = v.toAct === me;
const legal = new Map<BetActionType, LegalBetView>(v.my.legal.map((l) => [l.type, l]));
const [hover, setHover] = useState<BetActionType | null>(null);
const [confirmFold, setConfirmFold] = useState<BetActionType | null>(null);
const [raising, setRaising] = useState(false);
const seat = v.seats.find((s) => s.id === me)!;
useEffect(() => setRaising(false), [v.handNo, v.street, myTurn]);
const press = (t: BetActionType) => {
if ((t === 'k.die' || t === 'nl.fold') && v.my.toCall === 0) return setConfirmFold(t);
if (t === 'nl.raise') return setRaising(true);
act({ type: t });
};
const korean = v.betStyle === 'korean';
const types: BetActionType[] = korean
? KOREAN_ORDER.filter((t) => t !== 'k.full' || v.options.koreanMaxRaise === 'full')
: ['nl.fold', legal.has('nl.call') ? 'nl.call' : 'nl.check', 'nl.raise', 'nl.allIn'];
const hoverBet = hover ? legal.get(hover) : undefined;
const raise = legal.get('nl.raise');
return (
<div className="stack" style={{ gap: 6 }}>
{raising && raise ? (
<RaisePanel v={v} seat={seat} raise={raise} act={act} pending={pending} onCancel={() => setRaising(false)} />
) : (
<div className="pk-actions" role="group" aria-label="베팅">
{types.map((t) => {
const l = legal.get(t);
const enabled = myTurn && !!l && !pending;
const cls = t === 'k.die' || t === 'nl.fold' ? 'btn-danger' : t.endsWith('check') || t.endsWith('call') ? 'btn-primary' : 'btn-soft';
const amount = t === 'nl.raise' && l ? `${formatChips(l.minTo!)}부터` : l && l.amount > 0 ? `+${formatChips(l.amount)}${l.allIn ? ' 올인' : ''}` : '';
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={() => press(t)}
>
<span>{BET_KO[t]}</span>
<small>{amount || (t === 'k.die' || t === 'nl.fold' ? '포기' : l ? '0 칩' : '-')}</small>
</button>
);
})}
</div>
)}
<p className="small muted" style={{ margin: 0, minHeight: '1.4em', textAlign: 'center' }}>
{myTurn
? hoverBet && BET_HELP[hover!]
? `${BET_KO[hover!]}: ${BET_HELP[hover!]}. 내고 나면 내 칩 ${formatChips(seat.stack - hoverBet.amount)}, 모인 칩 ${formatChips(v.pot + hoverBet.amount)}`
: v.my.toCall > 0
? `내 차례예요. 맞추려면 ${formatChips(v.my.toCall)}이 필요해요.`
: '내 차례예요. 버튼에 적힌 칩이 바로 나가요.'
: v.toAct
? `${nick(players, v.toAct)}님 차례예요.`
: ''}
</p>
{confirmFold && (
<ConfirmSheet
title="체크할 수 있는데 포기할까요?"
body="지금은 칩을 더 내지 않고 넘어갈 수 있어요."
confirm="그래도 포기"
danger
onConfirm={() => {
act({ type: confirmFold });
setConfirmFold(null);
}}
onClose={() => setConfirmFold(null)}
/>
)}
</div>
);
}
/** NL/PL raise: slider + quick buttons (최소, 1/2팟, 팟, 최대) + ∓ 기본 단위, then 확인. Amounts are "총 몇 칩까지". */
function RaisePanel({ v, seat, raise, act, pending, onCancel }: { v: PokerView; seat: SeatView; raise: LegalBetView; act: (a: unknown) => void; pending: boolean; onCancel: () => void }) {
const min = raise.minTo!;
const max = raise.maxTo!;
const [to, setTo] = useState(min);
const clamp = (x: number) => Math.max(min, Math.min(max, Math.round(x)));
const potAfterCall = v.pot + v.my.toCall;
const quick: [string, number][] = [
['최소', min],
['1/2 팟', v.currentBet + Math.floor(potAfterCall / 2)],
['팟', v.currentBet + potAfterCall],
[v.betStyle === 'potLimit' ? '최대' : '올인', max],
];
const add = to - seat.roundBet;
const allIn = to >= seat.roundBet + seat.stack;
return (
<div className="card pk-raise" style={{ padding: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong>
{v.currentBet === 0 ? '벳' : '레이즈'}: 이번 라운드 총 {formatChips(to)}
</strong>
<span className="small muted">
지금 낼 칩 +{formatChips(add)}
{allIn ? ' (올인)' : ''}
</span>
</div>
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
<button type="button" className="btn btn-secondary" aria-label="기본 단위만큼 줄이기" onClick={() => setTo(clamp(to - v.baseUnit))}>
−
</button>
<input type="range" min={min} max={max} step={1} value={to} onChange={(e) => setTo(clamp(Number(e.target.value)))} aria-label="올릴 칩" style={{ flex: 1 }} />
<button type="button" className="btn btn-secondary" aria-label="기본 단위만큼 늘리기" onClick={() => setTo(clamp(to + v.baseUnit))}>
+
</button>
</div>
<div className="row" style={{ gap: 6 }}>
{quick.map(([label, x]) => (
<button key={label} type="button" className="btn btn-soft" style={{ flex: 1 }} onClick={() => setTo(clamp(x))}>
{label}
</button>
))}
</div>
<div className="row" style={{ gap: 6 }}>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} onClick={onCancel}>
취소
</button>
<button type="button" className="btn btn-primary" style={{ flex: 2 }} disabled={pending} onClick={() => act(allIn && v.betStyle === 'noLimit' ? { type: 'nl.allIn' } : { type: 'nl.raise', to })}>
확인: {formatChips(to)}까지
</button>
</div>
</div>
);
}
// ---------------------------------------------------------------- side
const RANKS_INTL = ['스트레이트 플러시(로열 포함)', '포카드', '풀하우스', '플러시', '스트레이트', '트리플', '투페어', '원페어', '하이카드'];
const RANKS_KOREAN = ['로열 스트레이트 플러시', '백 스트레이트 플러시', '스트레이트 플러시', '포카드', '풀하우스', '플러시', '마운틴(A-K-Q-J-10)', '백 스트레이트(A-2-3-4-5)', '스트레이트', '트리플', '투페어', '원페어', '탑(노페어)'];
function HandRanks({ mode, o }: { mode: PokerMode; o: Pick<PokerOptions, 'indianCards' | 'indianDeck' | 'hiLoLow' | 'hiLoQualifier'> }) {
if (mode === 'badugi') {
return (
<div className="small stack" style={{ gap: 4 }}>
<span>낮을수록 좋은 로우 게임이에요. A가 가장 낮아요.</span>
<span>
4장 중 <strong>숫자도 무늬도 겹치지 않는 카드</strong>가 많을수록 셉니다: 메이드(4장) &gt; 베이스(3장) &gt; 투베이스(2장) &gt; 노베이스.
</span>
<span>같은 등급이면 가장 높은 카드부터 비교해 낮은 쪽이 이겨요. 골프(A-2-3-4)가 최강, 세컨드(A-2-3-5), 써드(A-2-4-5).</span>
</div>
);
}
if (mode === 'indian') {
return (
<div className="small stack" style={{ gap: 4 }}>
<span>내 이마 카드는 나만 못 보고, 다른 사람 카드는 다 보여요.</span>
<span>{o.indianDeck === 'd20' ? '10이 가장 높고 A(1)가 가장 낮아요.' : 'A가 가장 높고 2가 가장 낮아요.'} 무늬는 보지 않아요.</span>
{o.indianCards === 2 && <span>2장일 때: 페어 &gt; 노페어. 노페어끼리는 높은 카드 → 낮은 카드 순으로 비교해요.</span>}
</div>
);
}
const korean = isSevenMode(mode);
return (
<div className="stack" style={{ gap: 4 }}>
<ol className="small" style={{ margin: 0, paddingLeft: 20 }}>
{(korean ? RANKS_KOREAN : RANKS_INTL).map((r) => (
<li key={r}>{r}</li>
))}
</ol>
{korean && <span className="small muted">같은 족보면 숫자, 그다음 무늬(♠ &gt; ◆ &gt; ♥ &gt; ♣)로 정해요.</span>}
{mode === 'sevenHiLo' && (
<span className="small muted">
로우: 서로 다른 숫자 5장, 낮을수록 좋음({o.hiLoLow === 'korean' ? '스트레이트·플러시 불인정, 최고 A-2-3-4-6' : '최고 A-2-3-4-5'}
{o.hiLoQualifier === 'eight' ? ', 8 이하만 인정' : ''}).
</span>
)}
{!korean && <span className="small muted">5장이 같은 서열이면 나눠 가져요(무늬는 보지 않아요).</span>}
</div>
);
}
function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<PokerView>) {
const [confirmQuit, setConfirmQuit] = useState(false);
const ranked = [...v.seats].sort((a, b) => b.stack - a.stack);
const scoreBy = v.options.endCondition === 'hands' || v.handsPlayed >= 300;
return (
<>
<style>{CSS}</style>
<PlayChipNotice />
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<div className="row" style={{ justifyContent: 'space-between' }}>
<strong>
{MODE_KO[v.mode]} · {v.phase === 'finished' ? '게임 끝' : `${Math.max(1, v.handNo)}판${v.options.endCondition === 'hands' ? ` / ${v.options.handLimit}판` : ''}`}
</strong>
{v.phase !== 'finished' && v.waiting.length > 0 && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={isMyTurn(v, me)} size={36} />}
</div>
<span className="small muted">
{v.betStyle === 'korean' ? `한국식 베팅(${v.options.koreanMaxRaise === 'full' ? '풀까지' : '하프까지'})` : v.betStyle === 'potLimit' ? '팟리밋' : '노리밋'} · 기본 {formatChips(v.baseUnit)}
</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{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} />
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
{nick(players, s.id)}
{s.rebuys > 0 ? ` · 리바이 ${s.rebuys}` : ''}
{s.status === 'eliminated' ? ' · 탈락' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
</span>
<Chips n={s.stack} />
</li>
))}
</ol>
</div>
{v.result && (
<div className="card stack" style={{ gap: 4, padding: 12 }}>
<strong>최종 순위</strong>
{v.result.ranking.map((g, i) => {
const sc = v.result!.scores[g[0]!] ?? 0;
return (
<span key={i}>
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')}
{scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''}
</span>
);
})}
{scoreBy && <span className="small muted">점수 = 마지막 칩 − 시작 칩 × 리바이 횟수</span>}
{v.stats.bestHand && (
<span className="small">
최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판)
</span>
)}
{v.stats.biggestPot && <span className="small">가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)</span>}
</div>
)}
<details className="card wide-open" open style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보</summary>
<HandRanks mode={v.mode} o={v.options} />
</details>
{v.mode === 'indian' && v.indianUsed.length > 0 && (
<details className="card" style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>이미 나온 카드 ({v.indianUsed.length}장)</summary>
<div className="row" style={{ gap: 2, marginTop: 6 }}>
{v.indianUsed.map((c, i) => (
<PlayingCard key={`${c}${i}`} card={c} size="sm" />
))}
</div>
</details>
)}
{v.log.length > 0 && (
<details className="card" style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
<ol style={{ listStyle: 'none', margin: '8px 0 0', padding: 0, display: 'grid', gap: 2, maxHeight: 200, overflow: 'auto' }}>
{[...v.log].reverse().map((e, i) => (
<li key={i} className="small">
<span className="muted">{e.hand}판</span> {e.by ? `${nick(players, e.by)}: ` : ''}
{e.msg}
</li>
))}
</ol>
</details>
)}
{v.my.canRebuy && !confirmQuit && (
<Sheet onClose={() => {}} label="칩 다시 받기">
<h2>칩을 모두 잃었어요</h2>
<p className="muted">
놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
</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)}>
그만하기
</button>
</div>
</Sheet>
)}
{confirmQuit && v.my.canRebuy && (
<ConfirmSheet
title="여기서 그만할까요?"
body="그만하면 이번 게임에서 탈락하고 구경만 할 수 있어요."
confirm="그만하기"
danger
onConfirm={() => act({ type: 'rebuy', accept: false })}
onClose={() => setConfirmQuit(false)}
/>
)}
</>
);
}
// ---------------------------------------------------------------- status
function isMyTurn(v: PokerView, me: string | null): boolean {
if (!me || v.phase === 'finished' || v.handPhase === 'handEnd') return false;
return v.waiting.includes(me);
}
function statusText(v: PokerView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
if (v.phase === 'rebuy') return v.my.canRebuy ? '칩을 다시 받을지 골라 주세요' : '칩을 다시 받을지 기다리는 중이에요';
const mine = isMyTurn(v, me);
switch (v.handPhase) {
case 'betting':
if (v.toAct === me) return v.my.handName && v.options.hints ? `내 차례예요 · 지금: ${v.my.handName}` : '내 차례예요. 베팅해 주세요';
return v.toAct ? `${nick(players, v.toAct)}님 차례예요` : '카드를 나눠 주는 중이에요';
case 'choice':
return mine ? '내 차례예요. 버릴 카드와 보여 줄 카드를 골라 주세요' : '다른 사람이 카드를 고르는 중이에요';
case 'draw':
return mine ? '내 차례예요. 바꿀 카드를 골라 주세요' : '다른 사람이 바꿀 카드를 고르는 중이에요';
case 'declare':
return mine ? '내 차례예요. 하이·로우·스윙을 선언해 주세요' : '다른 사람이 선언하는 중이에요';
case 'reveal':
return mine ? '모두 포기했어요. 내 카드를 공개할지 골라 주세요' : `${nick(players, v.waiting[0] ?? '')}님이 카드 공개 여부를 고르는 중이에요`;
case 'handEnd':
return resultLine(v, players) || '판이 끝났어요';
default:
return '잠시만 기다려 주세요';
}
}
// ---------------------------------------------------------------- options
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]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
{children}
</div>
);
}
function Options({ value: o, onChange }: OptionsProps<PokerOptions>) {
const [more, setMore] = useState(false);
const set = (patch: Partial<PokerOptions>) => onChange({ ...o, ...patch });
const tooBig = o.baseUnit * 20 > o.startingChips;
const max = o.mode === 'holdem' || o.mode === 'omaha' || (o.mode === 'indian' && o.indianCards === 1 && o.indianDeck === 'd52') ? 10 : 6;
return (
<div className="stack" style={{ gap: 16 }}>
<Field label="게임 모드">
<Seg value={o.mode} options={(Object.keys(MODE_KO) as PokerMode[]).map((m) => [m, MODE_KO[m]])} onChange={(mode) => set({ mode })} />
<span className="small muted">이 모드는 2~{max}명이 할 수 있어요.</span>
</Field>
<Field label="베팅 방식">
<Seg
value={o.betting}
options={[
['auto', '모드 기본'],
['korean', '한국식(삥·따당·하프)'],
['noLimit', '노리밋'],
['potLimit', '팟리밋'],
]}
onChange={(betting) => set({ betting })}
/>
</Field>
<Field label="시작 칩">
<Seg value={o.startingChips} options={[[500, '500'], [1000, '1,000'], [2000, '2,000'], [5000, '5,000']]} onChange={(startingChips) => set({ startingChips })} />
</Field>
<Field label={o.mode === 'holdem' || o.mode === 'omaha' ? '빅 블라인드' : '기본 칩(앤티)'}>
<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>
<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 })} />}
</Field>
<Field label="행동 제한 시간">
<Seg value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
</Field>
{o.mode === 'indian' && (
<Field label="인디언 포커">
<Seg value={o.indianCards} options={[[1, '1장(이마)'], [2, '2장(이마 + 손)']]} onChange={(indianCards) => set({ indianCards })} />
<Seg value={o.indianDeck} options={[['d20', '20장(1~10 두 벌)'], ['d52', '52장']]} onChange={(indianDeck) => set({ indianDeck })} />
</Field>
)}
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
</button>
{more && (
<>
<Field label="한국식 최대 레이즈">
<Seg value={o.koreanMaxRaise} options={[['half', '하프까지'], ['full', '풀까지']]} onChange={(koreanMaxRaise) => set({ koreanMaxRaise })} />
</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>
{o.rebuy !== 'off' && (
<Field label="리바이 고르는 시간">
<Seg value={o.rebuySeconds} options={[[10, '10초'], [15, '15초'], [30, '30초'], [null, '무제한']]} onChange={(rebuySeconds) => set({ rebuySeconds })} />
</Field>
)}
<Field label="기본 칩 2배로 올리기">
<Seg value={o.blindUpEvery} options={[[0, '안 올림'], [5, '5판마다'], [10, '10판마다'], [15, '15판마다']]} onChange={(blindUpEvery) => set({ blindUpEvery })} />
</Field>
<Field label="다음 판 딜러">
<Seg value={o.dealerRule} options={[['rotate', '시계 방향으로'], ['winner', '직전 판 승자']]} onChange={(dealerRule) => set({ dealerRule })} />
</Field>
<Field label="도움 표시">
<Seg value={o.hints ? 'on' : 'off'} options={[['on', '지금 족보 보여 주기'], ['off', '보여 주지 않기']]} onChange={(k) => set({ hints: k === 'on' })} />
</Field>
{o.mode === 'sevenHiLo' && (
<Field label="하이로우 로우 판정">
<Seg value={o.hiLoLow} options={[['korean', '스트레이트·플러시 불인정'], ['aceToFive', 'A-2-3-4-5 최고']]} onChange={(hiLoLow) => set({ hiLoLow })} />
<Seg value={o.hiLoQualifier} options={[['none', '제한 없음'], ['eight', '8 이하만 로우']]} onChange={(hiLoQualifier) => set({ hiLoQualifier })} />
</Field>
)}
{o.mode === 'fiveDraw' && (
<Field label="교환 장수">
<Seg value={o.drawLimit} options={[['any', '0~5장'], ['three', '3장까지(A를 남기면 4장)']]} onChange={(drawLimit) => set({ drawLimit })} />
</Field>
)}
{o.mode === 'indian' && (
<>
<Field label="가장 높은 카드를 단 채 다이하면 벌칙">
<Seg value={o.indianFoldPenalty ? 'on' : 'off'} options={[['on', '벌칙 있음'], ['off', '없음']]} onChange={(k) => set({ indianFoldPenalty: k === 'on' })} />
{o.indianFoldPenalty && <Seg value={o.indianPenaltyUnits} options={[[5, '기본 칩 5배'], [10, '10배'], [20, '20배']]} onChange={(indianPenaltyUnits) => set({ indianPenaltyUnits })} />}
</Field>
<Field label="동점일 때">
<Seg value={o.indianTie} options={[['carry', '다음 판으로 넘김'], ['split', '나눠 가짐']]} onChange={(indianTie) => set({ indianTie })} />
</Field>
<Field label="덱 섞기">
<Seg value={o.indianReshuffle} options={[['whenEmpty', '덱을 다 쓰면(카드 기억)'], ['everyHand', '판마다']]} onChange={(indianReshuffle) => set({ indianReshuffle })} />
</Field>
</>
)}
<Field label="판 결과 보여 주는 시간">
<Seg value={o.handEndSeconds} options={[[3, '3초'], [4, '4초'], [6, '6초'], [10, '10초']]} onChange={(handEndSeconds) => set({ handEndSeconds })} />
</Field>
</>
)}
</div>
);
}
function optionsSummary(o: PokerOptions): string {
const bet = o.betting === 'auto' ? '' : o.betting === 'korean' ? '한국식' : o.betting === 'noLimit' ? '노리밋' : '팟리밋';
return [MODE_KO[o.mode], bet, `시작 ${o.startingChips.toLocaleString('ko-KR')}칩`, `기본 ${o.baseUnit}칩`, o.endCondition === 'hands' ? `${o.handLimit}판` : '최후의 1인', o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`]
.filter(Boolean)
.join(' · ');
}
const MODE_RULES: Record<PokerMode, string> = {
holdem: '각자 2장을 받고, 가운데 공용 카드 5장(플랍 3 → 턴 1 → 리버 1)과 합쳐 가장 좋은 5장을 만들어요. 베팅은 프리플랍·플랍·턴·리버 네 번이에요.',
omaha: '각자 4장을 받는데, 반드시 내 카드 2장 + 공용 카드 3장으로만 5장을 만들어요. 나머지는 홀덤과 같아요.',
sevenPoker: '4장을 받아 1장은 버리고 1장은 모두에게 보여 줘요(초이스). 그다음 공개 카드 3장과 마지막 히든 카드 1장을 받으며 네 번 베팅해요. 7장 중 가장 좋은 5장으로 겨뤄요. 공개 카드가 가장 좋은 사람(보스)이 먼저 베팅해요.',
sevenHiLo: '7포커와 같이 진행한 뒤, 마지막에 하이·로우·스윙 중 하나를 동시에 선언해요. 하이 1등과 로우 1등이 칩을 반씩 나눠 가져요. 스윙은 두 쪽 다 이겨야 모두 가져가고, 하나라도 지면 아무것도 못 받아요.',
badugi: '4장을 받고 아침·점심·저녁 세 번 카드를 바꿀 수 있어요(교환 사이마다 베팅). 숫자와 무늬가 겹치지 않으면서 낮은 카드일수록 좋아요.',
fiveDraw: '5장을 받고 한 번 베팅한 뒤, 원하는 만큼 카드를 바꾸고 다시 베팅해요. 가장 좋은 5장 족보가 이겨요.',
indian: '카드를 이마에 붙이듯 나만 못 보고 다른 사람은 모두 봐요. 상대 카드와 베팅만 보고 내 카드를 짐작해야 해요.',
};
function Rules({ options }: { options?: PokerOptions }) {
const o = options;
const mode = o?.mode ?? 'sevenPoker';
const style = o ? (o.betting !== 'auto' ? o.betting : mode === 'holdem' || mode === 'indian' ? 'noLimit' : mode === 'omaha' ? 'potLimit' : 'korean') : 'korean';
return (
<div className="stack">
<p>
<strong>{MODE_KO[mode]}</strong>: {MODE_RULES[mode]} 칩은 이 방에서만 쓰는 놀이용 점수예요.
</p>
<p>
<strong>베팅</strong>:{' '}
{style === 'korean'
? '체크(안 걸고 넘김), 삥(기본 칩만큼), 콜(앞사람만큼), 따당(앞사람이 건 만큼의 두 배), 쿼터·하프·풀(모인 칩의 4분의 1·절반·전부만큼 더), 다이(포기). 한 라운드에 올리기는 한 번뿐이고, 체크나 콜을 한 뒤에는 같은 라운드에서 올릴 수 없어요.'
: `폴드(포기), 체크, 콜, 레이즈, 올인. 레이즈는 직전 레이즈만큼 이상 올려야 해요.${style === 'potLimit' ? ' 팟리밋은 모인 칩만큼까지만 올릴 수 있어요.' : ''}`}{' '}
칩이 모자라면 가진 만큼 내고 올인하며, 그 이상 걸린 칩은 따로(사이드 팟) 겨뤄요.
</p>
<p>
<strong>혼자 남으면</strong>: 다른 사람이 모두 포기하면 남은 한 명이 모인 칩을 가져가요.{' '}
{mode === 'indian'
? '인디언 포커는 판이 끝나면 모든 카드가 공개돼요.'
: '이때 남은 사람이 카드를 모두에게 보여 줄지([카드 공개]) 숨길지([공개 안 함]) 골라요. 시간이 지나면 공개하지 않아요.'}
</p>
<p>
<strong>족보</strong>
</p>
<HandRanks mode={mode} o={o ?? { indianCards: 1, indianDeck: 'd20', hiLoLow: 'korean', hiLoQualifier: 'none' }} />
{mode === 'indian' && o?.indianFoldPenalty !== false && <p>가장 높은 카드를 이마에 단 채 다이하면 벌칙 칩을 내요. 벌칙 칩은 그 판 승자가 가져가요.</p>}
<p>
<strong>칩이 떨어지면</strong>:{' '}
{o?.rebuy === 'off' ? '탈락하고 구경해요.' : '칩을 다시 받을지 고를 수 있어요. 다시 받은 만큼 최종 점수에서 빠져요.'}{' '}
{o?.endCondition === 'lastStanding' ? '칩을 가진 사람이 한 명 남으면 끝나요.' : '정해진 판 수가 끝나면 (마지막 칩 − 시작 칩 × 다시 받은 횟수)로 순위를 정해요.'}
</p>
{o?.turnSeconds === null ? (
<p>시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 자동 처리돼요. 이렇게 두 번 연속 넘어가면 '자리 비움'이 되고 짧은 제한 시간이 생겨요.</p>
) : (
<p>시간 안에 고르지 않으면 걸린 칩이 없을 때는 체크, 있을 때는 포기로 처리돼요. 두 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 짧아져요.</p>
)}
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
</div>
);
}
const ui: GameUI<PokerView, PokerOptions> = {
Board: PokerBoard,
Side: PokerSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;