블랙잭 화면 다시 만듦: 모든 조작을 가운데 판에, 큰 반원 테이블, 숫자·휠·칩 버튼 베팅, 카드 한 장씩 애니메이션

- board.tsx: 판 폭(최대 1180px) 반원 테이블(딜러·카드 슈·인쇄 문구·앞쪽 호의 자리, 내 자리는 가운데 앞 크게)
- 아래 조작판: 내 칩·시간 / 베팅(숫자 입력·Enter, −/+, 마우스 휠·↑↓(Shift 10배), 칩 버튼, 최소·절반·최대·지난 베팅, 막대) / 히트 H·스탠드 S·더블 D·스플릿 P·서렌더 R / 인슈어런스 / 결과·다음 판
- 옆 패널은 칩 순위와 놀이용 칩 안내만
- 카드는 나눠 주는 순서대로 450ms 간격으로 슈에서 날아오고 딜러 홀 카드는 뒤집힘, 합·결과는 카드가 놓인 뒤에
- 엔진: 처음 나눠 주기·딜러 차례에 장당 450ms를 다음 제한 시간에 더함(animLagMs)
- PlayingCard width 속성, 도움말·문서·e2e 스크린샷

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-17 01:29:31 +09:00
parent c10fac8e82
commit 02c2a8508c
8 changed files with 751 additions and 218 deletions

View File

@@ -27,6 +27,8 @@ export interface PlayingCardProps {
/** e.g. "AS", "TD", "X1" (joker). null = face down. */
card: string | null;
size?: CardSize;
/** Exact width in px (overrides `size`). */
width?: number;
selected?: boolean;
dimmed?: boolean;
highlight?: boolean;
@@ -44,8 +46,8 @@ export function cardAria(card: string | null): string {
return `${SUIT_KO[card[1]!]} ${FACE_KO[r] ?? RANK_LABEL[r] ?? r}`;
}
export function PlayingCard({ card, size = 'md', selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
const w = WIDTH[size];
export function PlayingCard({ card, size = 'md', width, selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
const w = width ?? WIDTH[size];
const h = Math.round(w * 1.4);
const lift = selected ? -Math.round(w * 0.22) : 0;
const common: CSSProperties = {

View File

@@ -0,0 +1,690 @@
/**
* 블랙잭 판 화면 (docs/games/blackjack.md §9): 큰 반원 테이블 위에 딜러(위)와 카드 슈(오른쪽 위), 아래 호를 따라
* 참가자 자리(내 자리는 가운데 앞, 크게), 테이블 아래 흰 조작판(베팅 입력·칩 버튼·휠·슬라이더 / 히트·스탠드… /
* 인슈어런스 / 결과). 모든 조작이 판 안에 있다.
*
* 카드는 한 장씩: 서버가 여러 장을 한꺼번에 보내도(처음 나눠 주기, 딜러 차례) 화면은 나눠 주는 순서대로
* BJ_DEAL_STEP_MS 간격으로 슈에서 날아와 놓이고, 합·결과는 카드가 다 놓인 뒤에 보인다.
*/
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
import type { BlackjackView, HandView, SeatView } from '@bg/games/blackjack';
import { BJ_DEAL_STEP_MS, baseCard, handValue } from '@bg/games/blackjack';
import type { PublicUser } from '@bg/shared/lite';
import { PlayingCard } from '../../components/cards/PlayingCard';
import { ChipIcon, formatChips } from '../../components/cards/Chips';
import { TurnTimer } from '../../components/TurnTimer';
import { Avatar } from '../../components/ui';
import { haptic, sfx, sounds } from '../../lib/feedback';
import { usePhone } from '../../lib/media';
import { fxMs } from '../../lib/motion';
import type { BoardProps } from '../types';
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 HAND_KO: Record<HandView['status'], string> = { playing: '', stand: '', bust: '버스트', blackjack: '블랙잭!', charlie: '찰리!', surrender: '서렌더' };
const OUTCOME_KO: Record<NonNullable<HandView['outcome']>, string> = { win: '승', lose: '패', push: '푸시', blackjack: '블랙잭', bonus: '보너스' };
const CSS = `
.bj-wrap { width: 100%; max-width: 1180px; display: flex; flex-direction: column; gap: 12px; align-self: center; }
.bj-table { position: relative; width: 100%; aspect-ratio: 16 / 8.4; min-height: 460px; border: 12px solid var(--wood); border-radius: 48px 48px 50% 50% / 48px 48px 34% 34%;
background:
radial-gradient(ellipse at 50% 20%, rgba(255,255,255,.14) 0%, rgba(255,255,255,0) 55%),
repeating-linear-gradient(45deg, rgba(255,255,255,.03) 0 2px, transparent 2px 16px),
repeating-linear-gradient(-45deg, rgba(255,255,255,.03) 0 2px, transparent 2px 16px),
var(--felt);
box-shadow: inset 0 0 0 2px var(--wood-line), inset 0 0 60px rgba(0,0,0,.3), var(--shadow); color: #fff; overflow: hidden; }
.bj-print { position: absolute; left: 50%; top: 47%; transform: translate(-50%, -50%); text-align: center; pointer-events: none; color: rgba(255,255,255,.55); }
.bj-print b { display: block; font-size: 1.5rem; letter-spacing: .3em; color: rgba(253,230,138,.75); }
.bj-print span { font-size: .8rem; letter-spacing: .08em; }
.bj-print::after { content: ''; display: block; width: 420px; height: 120px; margin: -64px auto 0; border: 2px solid rgba(255,255,255,.12); border-top: 0; border-radius: 0 0 50% 50% / 0 0 100% 100%; }
.bj-dealer { position: absolute; left: 50%; top: 18px; transform: translateX(-50%); display: flex; flex-direction: column; align-items: center; gap: 6px; z-index: 2; }
.bj-dealer .who { display: flex; gap: 8px; align-items: center; font-weight: 900; font-size: .9rem; }
.bj-shoe { position: absolute; right: 7%; top: 20px; width: 70px; height: 92px; z-index: 1; }
.bj-shoe i { position: absolute; inset: 0; border-radius: 8px; background: linear-gradient(160deg, #3b82f6, #1e3a8a); border: 2px solid #fff; box-shadow: 0 2px 4px rgba(0,0,0,.35); }
.bj-shoe i:nth-child(2) { transform: translate(-4px, 4px); } .bj-shoe i:nth-child(3) { transform: translate(-8px, 8px); }
.bj-shoe::after { content: ''; position: absolute; left: -16px; right: -6px; bottom: -12px; height: 34px; border-radius: 8px; background: linear-gradient(180deg, #4b5563, #1f2937); box-shadow: 0 3px 6px rgba(0,0,0,.4); }
.bj-shoe small { position: absolute; left: -16px; right: -6px; bottom: -8px; z-index: 1; text-align: center; font-size: .7rem; font-weight: 800; color: #e5e7eb; }
.bj-total { display: inline-flex; flex: none; white-space: nowrap; align-items: center; justify-content: center; min-width: 34px; padding: 1px 10px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-weight: 900;
font-variant-numeric: tabular-nums; font-size: .95rem; border: 2px solid rgba(255,255,255,.25); }
.bj-total.bust { background: #b91c1c; border-color: #fecaca; }
.bj-total.bj { background: linear-gradient(160deg, #fde047, #f59e0b); color: #5a2a00; border-color: #fff7c2; }
.bj-total.d21 { background: #15803d; }
.bj-cards { display: flex; align-items: flex-end; justify-content: center; min-height: 20px; }
.bj-cards > * + * { margin-left: calc(var(--cw) * -0.42); }
.bj-card-in { animation: bj-in .42s cubic-bezier(.2,.8,.3,1.1) both; }
@keyframes bj-in { from { transform: translate(var(--fx, 260px), var(--fy, -260px)) rotate(-24deg) scale(.6); opacity: 0; } 30% { opacity: 1; } to { transform: none; opacity: 1; } }
.bj-card-flip { animation: bj-flip .46s ease both; }
@keyframes bj-flip { from { transform: perspective(500px) rotateY(90deg); } to { transform: perspective(500px) rotateY(0); } }
.bj-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -100%); z-index: 3; display: flex; flex-direction: column; align-items: center; gap: 5px; }
.bj-seat .hands { display: flex; gap: 14px; align-items: flex-end; }
.bj-hand { position: relative; display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 6px 6px 4px; border-radius: 14px; border: 2px solid transparent; transition: border-color .2s, background .2s; }
.bj-hand.on { border-color: var(--focus); background: rgba(245,158,11,.14); box-shadow: 0 0 18px rgba(245,158,11,.35); }
.bj-hand .meta { display: flex; gap: 5px; align-items: center; }
.bj-tag { font-weight: 900; font-size: .8rem; border-radius: 6px; padding: 0 7px; color: #fff; white-space: nowrap; }
.bj-bet { display: inline-flex; align-items: center; gap: 3px; font-size: .78rem; font-weight: 800; background: rgba(255,255,255,.92); color: #1c1e21; border-radius: 999px; padding: 0 8px 0 3px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.bj-name { display: flex; align-items: center; gap: 6px; background: var(--surface); color: var(--text); border-radius: 999px; padding: 3px 10px 3px 3px; box-shadow: var(--shadow), 0 3px 10px rgba(0,0,0,.2);
font-size: .82rem; font-weight: 800; white-space: nowrap; max-width: 220px; border: 2px solid transparent; }
.bj-name .nm { overflow: hidden; text-overflow: ellipsis; }
.bj-name .ch { color: var(--warning); font-variant-numeric: tabular-nums; }
.bj-seat.turn .bj-name { border-color: var(--focus); }
.bj-seat.me .bj-name { border-color: var(--primary); }
.bj-seat.out { opacity: .55; }
.bj-net { font-weight: 900; font-size: 1rem; text-shadow: 0 1px 3px rgba(0,0,0,.6); }
.bj-net.plus { color: #86efac; } .bj-net.minus { color: #fca5a5; } .bj-net.zero { color: #e5e7eb; }
.bj-wait { font-size: .8rem; opacity: .85; background: rgba(0,0,0,.25); border-radius: 999px; padding: 1px 10px; }
.bj-banner { position: absolute; left: 0; right: 0; top: 42%; z-index: 8; text-align: center; font-size: 3rem; font-weight: 900; color: #fde047; -webkit-text-stroke: 2px #7c2d12;
text-shadow: 0 4px 12px rgba(0,0,0,.6); pointer-events: none; white-space: nowrap; }
/* 조작판: 사이트의 흰 카드 한 장. */
.bj-dock { position: relative; display: flex; gap: 12px; align-items: stretch; padding: 12px; border-radius: var(--radius-lg); background: var(--surface); color: var(--text);
border: 2px solid var(--border); box-shadow: var(--shadow); min-height: 132px; }
.bj-dock.turn { border-color: var(--primary); box-shadow: 0 0 0 4px var(--primary-soft), var(--shadow); }
.bj-dock.turn::before { content: '내 차례'; position: absolute; top: -13px; left: 50%; transform: translateX(-50%); background: var(--primary); color: var(--primary-text); font-weight: 900;
font-size: .8rem; padding: 1px 14px; border-radius: 999px; }
.bj-me { flex: 0 0 150px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; background: var(--surface-2); border-radius: var(--radius); padding: 8px; text-align: center; }
.bj-me .nm { font-weight: 800; font-size: .88rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bj-me .ch { font-weight: 900; font-size: 1.15rem; font-variant-numeric: tabular-nums; }
.bj-main { flex: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; gap: 8px; }
.bj-main p { margin: 0; }
.bj-info { flex: 0 0 170px; display: flex; flex-direction: column; justify-content: center; gap: 2px; font-size: .8rem; color: var(--text-sub); background: var(--surface-2); border-radius: var(--radius); padding: 8px 10px; }
.bj-info b { color: var(--text); }
.bj-betrow { display: flex; gap: 8px; align-items: stretch; flex-wrap: wrap; }
.bj-amount { display: flex; align-items: center; gap: 4px; border: 2px solid var(--primary); border-radius: var(--radius); background: var(--surface); padding: 0 4px; touch-action: none; }
.bj-amount input { width: 7.5em; border: 0; background: none; color: var(--text); font: inherit; font-size: 1.5rem; font-weight: 900; text-align: right; font-variant-numeric: tabular-nums; padding: 4px 2px; outline: none; }
.bj-amount input::-webkit-outer-spin-button, .bj-amount input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
.bj-amount input[type=number] { -moz-appearance: textfield; }
.bj-amount .unit { font-weight: 800; color: var(--text-sub); padding-right: 4px; }
.bj-step { width: 40px; border: 0; border-radius: 10px; background: var(--surface-2); color: var(--text); font-size: 1.3rem; font-weight: 900; cursor: pointer; }
.bj-step:disabled { opacity: .4; cursor: default; }
.bj-chipbtns { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
.bj-chip { --c: #2563eb; width: 52px; height: 52px; border-radius: 50%; border: 0; cursor: pointer; color: #fff; font-weight: 900; font-size: .74rem; font-family: inherit; white-space: nowrap; padding: 0;
background: radial-gradient(circle, var(--c) 0 52%, #fff 53% 58%, var(--c) 59%); box-shadow: 0 2px 4px rgba(0,0,0,.3), inset 0 0 0 3px rgba(255,255,255,.35); }
.bj-chip:hover { transform: translateY(-2px); } .bj-chip:active { transform: translateY(1px); }
.bj-chip:disabled { opacity: .35; cursor: default; transform: none; }
.bj-quick { border: 1px solid var(--border); background: var(--surface); color: var(--text); border-radius: 999px; padding: 4px 12px; font: inherit; font-weight: 800; font-size: .82rem; cursor: pointer; }
.bj-quick:disabled { opacity: .4; cursor: default; }
.bj-range { width: 100%; accent-color: var(--primary); }
.bj-acts { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 8px; }
.bj-act { position: relative; min-height: 56px; border: 2px solid var(--c); border-radius: var(--radius); background: color-mix(in srgb, var(--c) 10%, var(--surface)); color: var(--c);
font: inherit; font-weight: 900; font-size: 1.15rem; cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.15; }
.bj-act small { font-size: .7rem; font-weight: 700; color: var(--text-sub); }
.bj-act kbd { position: absolute; left: 7px; top: 6px; font: inherit; font-size: .68rem; font-weight: 900; background: var(--c); color: #fff; border-radius: 5px; padding: 0 5px; }
.bj-act:hover { background: color-mix(in srgb, var(--c) 18%, var(--surface)); }
.bj-act:active { transform: translateY(1px); }
:root[data-theme='dark'] .bj-act { color: color-mix(in srgb, var(--c) 55%, #fff); }
.bj-help { margin: 0; text-align: center; min-height: 1.4em; }
@media (max-width: 719px) {
.bj-table { aspect-ratio: auto; min-height: 0; border-width: 7px; border-radius: 24px; padding: 12px 8px; display: flex; flex-direction: column; gap: 14px; }
.bj-print, .bj-shoe { display: none; }
.bj-dealer { position: relative; left: auto; top: auto; transform: none; }
.bj-seats { display: flex; flex-wrap: wrap; justify-content: center; gap: 14px 10px; }
.bj-seat { position: relative; left: auto; top: auto; transform: none; }
.bj-seat.me { order: 99; flex-basis: 100%; }
.bj-dock { flex-direction: column; gap: 10px; padding: 10px; }
.bj-me { flex: none; flex-direction: row; justify-content: flex-start; gap: 10px; padding: 6px 10px; }
.bj-info { display: none; }
.bj-amount input { width: 6em; font-size: 1.3rem; }
.bj-banner { position: fixed; top: 40%; font-size: 2.2rem; }
}
`;
// ---------------------------------------------------------------- deal queue (one card at a time)
const DEALER_GROUP = 1e6;
/** A key per card slot: real ids are unique per shoe; the face-down hole gets its own key so turning it is a new card. */
const holeKey = (v: BlackjackView) => `hole-${v.handsPlayed}`;
/**
* Every card the screen has not shown yet gets a landing time, in dealing order (card 1 of everyone, dealer, card 2 of
* everyone, dealer, then hits / dealer draws), BJ_DEAL_STEP_MS apart. Cards render only once they have landed.
*/
function useDealQueue(v: BlackjackView) {
const land = useRef<Map<string, number> | null>(null);
const queueEnd = useRef(0);
const hand = useRef(v.handsPlayed);
const [, setTick] = useState(0);
const now = Date.now();
if (land.current && hand.current !== v.handsPlayed) {
// A new hand: anything still queued from the last one shows at once, so a fast table never falls behind.
hand.current = v.handsPlayed;
for (const [k, at] of land.current) if (at > now) land.current.set(k, 0);
queueEnd.current = now;
}
const step = Math.min(BJ_DEAL_STEP_MS, fxMs(300));
const slots: { key: string; idx: number; group: number }[] = [];
const orderIdx = (id: string) => {
const i = v.order.indexOf(id);
return i < 0 ? v.seats.findIndex((s) => s.id === id) : i;
};
for (const s of v.seats) s.hands?.forEach((h, hi) => h.cards.forEach((c, ci) => slots.push({ key: c, idx: ci, group: orderIdx(s.id) * 10 + hi })));
v.dealer.cards.forEach((c, ci) => slots.push({ key: c ?? holeKey(v), idx: ci, group: DEALER_GROUP }));
if (!land.current) {
// First render (page load / reconnect): everything already on the table is shown at once.
land.current = new Map(slots.map((x) => [x.key, 0]));
} else {
const fresh = slots.filter((x) => !land.current!.has(x.key)).sort((a, b) => a.idx - b.idx || a.group - b.group);
let t = Math.max(now, queueEnd.current);
for (const x of fresh) {
land.current.set(x.key, t);
t += step;
}
if (fresh.length) queueEnd.current = t;
}
const map = land.current;
const pending = slots.filter((x) => (map.get(x.key) ?? 0) > now);
const nextAt = pending.length ? Math.min(...pending.map((x) => map.get(x.key)!)) : 0;
useEffect(() => {
if (!nextAt) return undefined;
const t = setTimeout(() => setTick((n) => n + 1), Math.max(0, nextAt - Date.now()) + 5);
return () => clearTimeout(t);
}, [nextAt]);
return {
shown: (key: string) => (map.get(key) ?? 0) <= now,
/** Cards that landed just now (play the sound / animation). */
landedRecently: (key: string) => {
const at = map.get(key) ?? 0;
return at > 0 && now - at < 600;
},
busy: pending.length > 0,
};
}
// ---------------------------------------------------------------- pieces
function totalOf(cards: string[]): { total: number; soft: boolean } {
return cards.length ? handValue(cards as never) : { total: 0, soft: false };
}
function TotalBadge({ cards, status, final }: { cards: string[]; status?: HandView['status']; final: boolean }) {
if (!cards.length) return null;
const { total, soft } = totalOf(cards);
const bust = total > 21;
const bj = final && status === 'blackjack';
const label = bust ? `${total}` : soft && total < 21 ? `${total - 10}/${total}` : `${total}`;
return <span className={`bj-total${bust ? ' bust' : bj ? ' bj' : total === 21 ? ' d21' : ''}`}>{bj ? '블랙잭' : label}</span>;
}
function DealtCard({ id, width, anim }: { id: string | null; width: number; anim: 'in' | 'flip' | null }) {
// Fly-in offset from the shoe (top right of the table) to this card, measured before the first paint.
const ref = useRef<HTMLSpanElement | null>(null);
const [off, setOff] = useState<CSSProperties>({});
useLayoutEffect(() => {
const el = ref.current;
if (!el || anim !== 'in') return;
const shoe = el.closest('.bj-table')?.querySelector('.bj-shoe')?.getBoundingClientRect();
const r = el.getBoundingClientRect();
if (shoe && shoe.width) setOff({ ['--fx' as string]: `${Math.round(shoe.left - r.left)}px`, ['--fy' as string]: `${Math.round(shoe.top - r.top)}px` });
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
<span ref={ref} className={anim === 'in' ? 'bj-card-in' : anim === 'flip' ? 'bj-card-flip' : undefined} style={{ display: 'inline-block', ...off }}>
<PlayingCard card={id ? baseCard(id as never) : null} width={width} />
</span>
);
}
function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean; width: number; q: ReturnType<typeof useDealQueue>; final: boolean }) {
const cards = h.cards.filter((c) => q.shown(c));
const done = cards.length === h.cards.length;
const tag = final && h.outcome ? OUTCOME_KO[h.outcome] : done ? HAND_KO[h.status] : '';
const color =
h.outcome === 'win' || h.outcome === 'blackjack' || h.outcome === 'bonus' ? '#16a34a' : h.outcome === 'lose' || h.status === 'bust' ? '#dc2626' : h.outcome === 'push' ? '#6b7280' : '#b45309';
return (
<div className={`bj-hand${active ? ' on' : ''}${done && h.status === 'bust' ? ' anim-shake' : ''}`}>
<div className="bj-cards" style={{ ['--cw' as string]: `${width}px`, minHeight: Math.round(width * 1.4) }}>
{cards.map((c) => (
<DealtCard key={c} id={c} width={width} anim={q.landedRecently(c) ? 'in' : null} />
))}
</div>
<div className="meta">
<TotalBadge cards={cards} status={h.status} final={done} />
<span className="bj-bet" title="건 칩">
<ChipIcon size={14} />
{h.bet.toLocaleString('ko-KR')}
{h.doubled ? ' ×2' : ''}
</span>
{tag && (
<span className="bj-tag anim-pop" style={{ background: color }}>
{tag}
</span>
)}
</div>
</div>
);
}
function Seat({ seat, v, me, players, pos, width, q, final }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record<string, PublicUser>; pos: { x: number; y: number } | null; width: number; q: ReturnType<typeof useDealQueue>; final: boolean }) {
const u = userOf(players, seat.id);
const isTurn = v.phase === 'playing' && v.turn === seat.id;
const style = pos ? ({ '--x': `${pos.x}%`, '--y': `${pos.y}%` } as CSSProperties) : undefined;
return (
<div className={`bj-seat${isTurn ? ' turn' : ''}${seat.id === me ? ' me' : ''}${seat.status !== 'playing' ? ' out' : ''}`} style={style} aria-label={`${u.nickname}${seat.id === me ? '(나)' : ''}, ${formatChips(seat.chips)}`}>
{seat.hands ? (
<div className="hands">
{seat.hands.map((h, i) => (
<HandBox key={i} h={h} active={isTurn && i === seat.active} width={width} q={q} final={final} />
))}
</div>
) : v.phase === 'betting' && seat.status === 'playing' ? (
<span className="bj-wait">{seat.betLocked ? `${seat.bet.toLocaleString('ko-KR')} 칩 걸었어요` : '베팅하는 중…'}</span>
) : null}
{final && seat.net !== null && seat.hands && (
<span className={`bj-net anim-slide-up ${seat.net > 0 ? 'plus' : seat.net < 0 ? 'minus' : 'zero'}`}>{seat.net > 0 ? `+${formatChips(seat.net)}` : seat.net < 0 ? `-${formatChips(-seat.net)}` : '본전'}</span>
)}
<div className="bj-name">
<Avatar user={u} size={24} />
<span className="nm">
{u.nickname}
{seat.id === me ? ' (나)' : ''}
</span>
<span className="ch">{seat.chips.toLocaleString('ko-KR')}</span>
{seat.status === 'out' && <span className="small">칩 소진</span>}
{seat.status === 'left' && <span className="small">나감</span>}
</div>
</div>
);
}
/** Seats along the front arc of the table, left to right; I sit in the middle. Dealing goes right → left (first base on the right). */
function arcSlots(v: BlackjackView, me: string | null): { id: string; x: number; y: number }[] {
const ids = (v.order.length ? v.order : v.seats.map((s) => s.id)).filter((id) => v.seats.some((s) => s.id === id));
for (const s of v.seats) if (!ids.includes(s.id)) ids.push(s.id);
let ltr = [...ids].reverse();
const n = ltr.length;
const mid = Math.floor(n / 2);
const mi = me ? ltr.indexOf(me) : -1;
if (mi >= 0) ltr = ltr.map((_, i) => ltr[(i + mi - mid + n) % n]!);
// Few players sit close together at the front; more players spread along the arc.
const span = Math.min(140, 38 * (n - 1));
return ltr.map((id, i) => {
const a = ((n === 1 ? 90 : 90 + span / 2 - (i * span) / (n - 1)) * Math.PI) / 180;
return { id, x: 50 + 42 * Math.cos(a), y: 50 + 45 * Math.sin(a) };
});
}
// ---------------------------------------------------------------- dock (all my controls)
const ACT_KEYS: Record<string, string> = { hit: 'H', stand: 'S', double: 'D', split: 'P', surrender: 'R' };
function BetPanel({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
const range = v.betRange!;
const clamp = (n: number) => Math.min(range.max, Math.max(range.min, Math.round(n / range.step) * range.step));
const last = Number(localStorage.getItem('bj:lastBet') ?? 0) || range.min;
const [amount, setAmount] = useState(() => clamp(last));
const [text, setText] = useState(String(clamp(last)));
const [typing, setTyping] = useState(false);
const set = (n: number) => {
const c = clamp(n);
setAmount(c);
setText(String(c));
sfx.chip();
};
const typed = Number(text.replace(/[^\d]/g, ''));
const bad = typing && (!Number.isFinite(typed) || typed < range.min || typed > range.max || typed % range.step !== 0);
const wheelRef = useRef<HTMLDivElement | null>(null);
const amountRef = useRef(amount);
amountRef.current = amount;
useEffect(() => {
// Wheel over the bet panel: up = more, down = less (Shift = ×10). Non-passive so the page does not scroll.
const el = wheelRef.current;
if (!el) return undefined;
const onWheel = (e: WheelEvent) => {
e.preventDefault();
const k = (e.shiftKey ? 10 : 1) * (e.deltaY < 0 ? 1 : -1);
set(amountRef.current + k * range.step);
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [range.step, range.min, range.max]); // eslint-disable-line react-hooks/exhaustive-deps
const confirm = () => {
const n = typing ? clamp(typed) : amount;
localStorage.setItem('bj:lastBet', String(n));
sfx.chips(3);
act({ type: 'bet', amount: n });
};
const chips: [number, string][] = [
[1, '#2563eb'],
[5, '#dc2626'],
[10, '#15803d'],
[50, '#111827'],
];
return (
<div className="stack" style={{ gap: 8 }} ref={wheelRef}>
<div className="bj-betrow">
<div className="bj-amount" title="숫자를 바로 적거나, 마우스 휠·↑↓ 키로 바꿀 수 있어요">
<button type="button" className="bj-step" aria-label="베팅 줄이기" disabled={pending || amount <= range.min} onClick={() => set(amount - range.step)}>
−
</button>
<input
type="text"
inputMode="numeric"
aria-label={`걸 칩 (${range.min.toLocaleString('ko-KR')}~${range.max.toLocaleString('ko-KR')}, ${range.step} 칩 단위)`}
value={typing ? text : amount.toLocaleString('ko-KR')}
onFocus={(e) => {
setTyping(true);
setText(String(amount));
requestAnimationFrame(() => e.target.select());
}}
onChange={(e) => setText(e.target.value.replace(/[^\d]/g, '').slice(0, 7))}
onBlur={() => {
setTyping(false);
if (text) set(typed);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
if (!pending) confirm();
} else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
const base = typing ? clamp(typed) : amount;
set(base + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1) * range.step);
setTyping(false);
}
}}
/>
<span className="unit">칩</span>
<button type="button" className="bj-step" aria-label="베팅 늘리기" disabled={pending || amount >= range.max} onClick={() => set(amount + range.step)}>
+
</button>
</div>
<button type="button" className="btn btn-primary" style={{ flex: 1, minWidth: 150, fontSize: '1.1rem' }} disabled={pending || bad} onClick={confirm}>
{formatChips(typing && !bad ? clamp(typed) : amount)} 베팅
</button>
</div>
<div className="bj-chipbtns">
{chips.map(([k, c]) => (
<button key={k} type="button" className="bj-chip" style={{ '--c': c } as CSSProperties} disabled={pending || amount >= range.max} onClick={() => set(amount + k * range.step)} aria-label={`${k * range.step} 칩 더하기`}>
+{(k * range.step).toLocaleString('ko-KR')}
</button>
))}
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(range.min)}>
최소
</button>
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(range.max / 2)}>
절반
</button>
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(range.max)}>
최대
</button>
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(last)}>
지난 베팅
</button>
</div>
<input
className="bj-range"
type="range"
aria-label="베팅 칩 조절"
min={range.min}
max={range.max}
step={range.step}
value={amount}
onChange={(e) => set(Number(e.target.value))}
/>
{bad && <span className="small" style={{ color: 'var(--danger)' }}>{`${range.min.toLocaleString('ko-KR')}~${range.max.toLocaleString('ko-KR')} 칩, ${range.step} 칩 단위로 적어 주세요. 적은 값에 가장 가까운 금액으로 맞춰 걸어요.`}</span>}
</div>
);
}
function Actions({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
const my = v.my!;
const list: [string, string, boolean, string, string][] = [
['hit', '히트', my.canHit, '#2563eb', '한 장 더'],
['stand', '스탠드', my.canStand, '#15803d', '여기서 멈춤'],
['double', '더블', my.canDouble, '#b45309', '두 배, 한 장만'],
['split', '스플릿', my.canSplit, '#7c3aed', '둘로 나누기'],
['surrender', '서렌더', my.canSurrender, '#6b7280', '절반 돌려받고 포기'],
];
const press = (t: string) => {
if (pending) return;
sfx.click();
act({ type: t });
};
const pressRef = useRef(press);
pressRef.current = press;
const avail = list.filter((x) => x[2]).map((x) => x[0]);
const availRef = useRef(avail);
availRef.current = avail;
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(ACT_KEYS).find((k) => ACT_KEYS[k] === e.key.toUpperCase());
if (t && availRef.current.includes(t)) {
e.preventDefault();
pressRef.current(t);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);
return (
<div className="bj-acts" role="group" aria-label="내 행동">
{list
.filter((x) => x[2])
.map(([t, label, , c, sub]) => (
<button key={t} type="button" className="bj-act anim-pop" style={{ '--c': c } as CSSProperties} disabled={pending} onClick={() => press(t)} aria-keyshortcuts={ACT_KEYS[t]} title={`${sub} (${ACT_KEYS[t]} 키)`}>
<kbd aria-hidden>{ACT_KEYS[t]}</kbd>
{label}
<small>{sub}</small>
</button>
))}
</div>
);
}
function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean }) {
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
const u = seat ? userOf(players, seat.id) : null;
let main: ReactNode;
if (!seat) main = <p className="muted">구경 중이에요. {v.turn ? `${nick(players, v.turn)}님 차례예요.` : ''}</p>;
else if (v.phase === 'betting')
main = mine ? (
<BetPanel key={v.handsPlayed} v={v} act={act} pending={pending} />
) : seat.betLocked ? (
<p>
<strong>{formatChips(seat.bet)}</strong> 걸었어요. 다른 사람이 걸기를 기다려요.
</p>
) : (
<p className="muted">이번 판은 쉬어요.</p>
);
else if (v.phase === 'insurance')
main = v.insuranceOpen ? (
<>
<p>
<strong>딜러가 A를 보여 줬어요.</strong> 인슈어런스를 걸까요? 딜러가 블랙잭이면 2:1로 돌려받아요.
</p>
<div className="row">
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: true })}>
걸기 ({formatChips(v.insuranceMax)})
</button>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: false })}>
안 함
</button>
</div>
</>
) : (
<p className="muted">인슈어런스 선택을 기다려요.</p>
);
else if (v.phase === 'playing')
main = mine ? <Actions v={v} act={act} pending={pending} /> : <p className="muted">{v.turn ? `${nick(players, v.turn)}님 차례예요.` : '딜러가 카드를 받고 있어요.'}</p>;
else if (v.phase === 'handEnd')
main = (
<>
<p style={{ fontSize: '1.1rem' }}>
{!final ? (
'딜러가 카드를 펼치는 중이에요…'
) : !seat.hands ? (
'이번 판은 쉬었어요.'
) : (
<>
이번 판{' '}
<strong style={{ color: seat.net && seat.net > 0 ? 'var(--success)' : seat.net && seat.net < 0 ? 'var(--danger)' : undefined }}>
{seat.net === null || seat.net === 0 ? '본전이에요' : seat.net > 0 ? `+${formatChips(seat.net)} 땄어요` : `${formatChips(-seat.net)} 잃었어요`}
</strong>
.
</>
)}
</p>
{seat.hands && (
<button type="button" className="btn btn-primary btn-block" disabled={pending || seat.ready} onClick={() => act({ type: 'ready' })}>
{seat.ready ? '다음 판을 기다려요…' : '다음 판'}
</button>
)}
</>
);
else main = <p className="muted">{v.result?.summary ?? '게임이 끝났어요.'}</p>;
const turn = !!seat && mine && v.phase !== 'handEnd';
return (
<div className={`bj-dock${turn ? ' turn' : ''}`}>
{seat && u && (
<div className="bj-me">
<Avatar user={u} size={44} />
<span className="nm">{u.nickname} (나)</span>
<span className="ch">
<ChipIcon size={18} /> {seat.chips.toLocaleString('ko-KR')}
</span>
{mine && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={30} />}
</div>
)}
<div className="bj-main">{main}</div>
<div className="bj-info" aria-label="판 정보">
<span>
<b>{v.handLimit ? `${Math.min(v.handsPlayed + 1, v.handLimit)} / ${v.handLimit}판` : `${v.handsPlayed + 1}판째`}</b>
</span>
<span>
블랙잭 {v.options.blackjackPayout} · 딜러 {v.options.dealerSoft17 === 'hit' ? 'H17' : 'S17'}
</span>
<span>슈에 약 {v.decksLeft}벌 남음</span>
<span>
키: 히트 H · 스탠드 S · 더블 D{v.options.surrender === 'late' ? ' · 서렌더 R' : ''} · 스플릿 P
</span>
</div>
</div>
);
}
// ---------------------------------------------------------------- board
export function isMyTurn(v: BlackjackView, me: string | null): boolean {
if (!me || v.me !== me) return false;
const seat = v.seats.find((s) => s.id === me);
if (!seat) return false;
switch (v.phase) {
case 'betting':
return !seat.betLocked && !!v.betRange;
case 'insurance':
return v.insuranceOpen;
case 'playing':
return v.turn === me && !!v.my;
case 'handEnd':
return !!seat.hands && !seat.ready;
default:
return false;
}
}
export function BlackjackBoard({ view: v, me, players, act, pending, deadline }: BoardProps<BlackjackView>) {
const mine = isMyTurn(v, me);
const phone = usePhone();
const q = useDealQueue(v);
// Results (outcome tags, +/-) wait until every card has landed.
const final = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy;
const d = v.dealer;
const dealerCards = d.cards.map((c) => c ?? holeKey(v)).filter((k) => q.shown(k));
const dealerReal = d.cards.filter((c): c is string => !!c && q.shown(c));
const slots = arcSlots(v, me);
const n = slots.length;
const otherW = phone ? 40 : n > 5 ? 48 : 56;
const myW = phone ? 56 : 76;
// Sounds + my result once the cards are down.
const sounded = useRef(new Set<string>());
const allKeys = [...v.seats.flatMap((s) => s.hands?.flatMap((h) => h.cards) ?? []), ...d.cards.map((c) => c ?? holeKey(v))];
useEffect(() => {
for (const k of allKeys) {
if (!q.shown(k) || sounded.current.has(k)) continue;
sounded.current.add(k);
if (!q.landedRecently(k)) continue;
if (d.cards.indexOf(k) === 1) sfx.cardFlip();
else sfx.cardDeal();
}
});
const [banner, setBanner] = useState<{ text: string; key: number } | null>(null);
const resultFor = useRef<number>(-1);
const mySeat = me ? v.seats.find((s) => s.id === me) : undefined;
useEffect(() => {
if (!final || !mySeat?.hands || resultFor.current === v.handsPlayed) return;
resultFor.current = v.handsPlayed;
const bj = mySeat.hands.some((h) => h.outcome === 'blackjack');
if (bj) setBanner({ text: '블랙잭!', key: Date.now() });
else if (d.bust) setBanner({ text: '딜러 버스트!', key: Date.now() });
if ((mySeat.net ?? 0) > 0) {
sfx.collect();
sounds.win();
haptic([40, 30, 80]);
} else if ((mySeat.net ?? 0) < 0) sounds.lose();
}, [final, v.handsPlayed]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!banner) return undefined;
const t = setTimeout(() => setBanner(null), fxMs(1500));
return () => clearTimeout(t);
}, [banner]);
const prevTurn = useRef(v.turn);
useLayoutEffect(() => {
if (v.turn && v.turn !== prevTurn.current && v.turn === me) {
sounds.myTurn();
haptic(40);
}
prevTurn.current = v.turn;
}, [v.turn]); // eslint-disable-line react-hooks/exhaustive-deps
const dealerDone = dealerCards.length === d.cards.length;
const seatEls = slots.map(({ id, x, y }) => {
const seat = v.seats.find((s) => s.id === id)!;
return <Seat key={id} seat={seat} v={v} me={me} players={players} pos={phone ? null : { x, y }} width={id === me ? myW : otherW} q={q} final={final} />;
});
return (
<div className="bj-wrap">
<style>{CSS}</style>
<div className="bj-table" role="region" aria-label="블랙잭 테이블">
<div className="bj-print" aria-hidden>
<b>BLACKJACK</b>
<span>
블랙잭 {v.options.blackjackPayout} · 딜러는 {v.options.dealerSoft17 === 'hit' ? '소프트 17에서 받아요' : '17 이상이면 멈춰요'}
{v.options.insurance ? ' · 인슈어런스 2:1' : ''}
</span>
</div>
<div className="bj-shoe" aria-hidden>
<i />
<i />
<i />
<small>슈 {v.decksLeft}벌</small>
</div>
<div className="bj-dealer" aria-label={`딜러 ${d.revealed ? d.total : `${d.total} +?`}`}>
<div className="who">
<span>딜러</span>
{dealerReal.length > 0 && (
<TotalBadge cards={d.revealed && dealerDone ? (d.cards as string[]) : dealerReal} status={d.blackjack && dealerDone ? 'blackjack' : undefined} final={d.revealed && dealerDone} />
)}
{!d.revealed && d.cards.length > 1 && dealerDone && <span className="small" style={{ opacity: 0.8 }}>+ ?</span>}
</div>
<div className="bj-cards" style={{ ['--cw' as string]: `${myW}px`, minHeight: Math.round(myW * 1.4) }}>
{d.cards.length === 0 && <span className="bj-wait">베팅이 끝나면 카드를 나눠 줘요</span>}
{d.cards.map((c, i) => {
const k = c ?? holeKey(v);
if (!q.shown(k)) return null;
return <DealtCard key={k} id={c} width={myW} anim={q.landedRecently(k) ? (i === 1 && c ? 'flip' : 'in') : null} />;
})}
</div>
</div>
{phone ? <div className="bj-seats">{seatEls}</div> : seatEls}
{banner && (
<div key={banner.key} className="bj-banner anim-banner" aria-hidden>
{banner.text}
</div>
)}
</div>
<Dock v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} mine={mine} final={final} />
</div>
);
}

View File

@@ -33,7 +33,7 @@ export function helpNow(v: BlackjackView, me: string | null, players: Record<str
if (v.phase === 'betting') {
if (!seat.betLocked && v.betRange) {
return `베팅할 차례예요. 내 칩은 ${chips(seat.chips)}.\n${chips(v.betRange.min)}부터 ${chips(v.betRange.max)}까지 ${v.betRange.step.toLocaleString('ko-KR')} 칩 단위로 걸고 [베팅]을 눌러요. ${goal}`;
return `베팅할 차례예요. 내 칩은 ${chips(seat.chips)}.\n${chips(v.betRange.min)}부터 ${chips(v.betRange.max)}까지 ${v.betRange.step.toLocaleString('ko-KR')} 칩 단위로 걸어요. 아래 판에서 숫자를 바로 적거나, 마우스 휠·↑↓ 키·칩 버튼(+10 등)·막대로 정한 뒤 [베팅](또는 Enter)을 눌러요. ${goal}`;
}
return `베팅을 걸었어요(${chips(seat.bet)}). 다른 사람이 걸면 카드를 나눠 줘요.`;
}
@@ -62,7 +62,7 @@ export function helpNow(v: BlackjackView, me: string | null, players: Record<str
if (my.canDouble) acts.push('[더블]은 베팅을 두 배로 걸고 딱 한 장만 받아요');
if (my.canSplit) acts.push('[스플릿]은 같은 숫자 두 장을 두 손패로 나눠요(베팅 한 번 더)');
if (my.canSurrender) acts.push('[서렌더]는 베팅 절반만 잃고 이 판을 포기해요');
lines.push(acts.join('. ') + '.');
lines.push(acts.join('. ') + '. 키보드로는 H 히트, S 스탠드, D 더블, P 스플릿, R 서렌더예요.');
if ((h?.total ?? 0) >= 17 && !h?.soft) lines.push('17 이상이면 보통 멈춰요. 더 받으면 버스트 위험이 커요.');
return lines.join('\n');
}

View File

@@ -1,35 +1,16 @@
/** 블랙잭 화면 (docs/games/blackjack.md §9). Standard-deck art reuses components/cards/PlayingCard. */
import { useState, type ReactNode } from 'react';
import type { BlackjackOptions, BlackjackView, HandView, SeatView } from '@bg/games/blackjack';
import { baseCard } from '@bg/games/blackjack';
/** 블랙잭 화면 (docs/games/blackjack.md §9): 판·조작은 board.tsx, 여기는 옆 패널(칩 순위)·설정·규칙. */
import type { ReactNode } from 'react';
import type { BlackjackOptions, BlackjackView } from '@bg/games/blackjack';
import type { PublicUser } from '@bg/shared/lite';
import { PLAYING_CARD_CREDIT, PlayingCard } from '../../components/cards/PlayingCard';
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
import { TurnTimer } from '../../components/TurnTimer';
import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard';
import { PlayChipNotice, formatChips } from '../../components/cards/Chips';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { BlackjackBoard, isMyTurn } from './board';
import { helpNow } from './help';
import { quickStart } from './quick';
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
function isMyTurn(v: BlackjackView, me: string | null): boolean {
if (!me || v.me !== me) return false;
const seat = v.seats.find((s) => s.id === me);
if (!seat) return false;
switch (v.phase) {
case 'betting':
return !seat.betLocked && !!v.betRange;
case 'insurance':
return v.insuranceOpen;
case 'playing':
return v.turn === me && !!v.my;
case 'handEnd':
return !!seat.hands && !seat.ready;
default:
return false;
}
}
function statusText(v: BlackjackView, me: string | null, players: Record<string, PublicUser>): string {
switch (v.phase) {
case 'betting':
@@ -45,199 +26,32 @@ function statusText(v: BlackjackView, me: string | null, players: Record<string,
}
}
// ---------------------------------------------------------------- hand rendering
// ---------------------------------------------------------------- side (standings only; every control is on the board)
const HAND_KO: Record<HandView['status'], string> = {
playing: '',
stand: '',
bust: '버스트',
blackjack: '블랙잭!',
charlie: '찰리!',
surrender: '서렌더',
};
const OUTCOME_KO: Record<NonNullable<HandView['outcome']>, string> = {
win: '승', lose: '패', push: '푸시', blackjack: '블랙잭', bonus: '보너스',
};
function totalLabel(h: HandView): string {
if (h.status === 'bust') return `${h.total} 버스트`;
return h.soft ? `${h.total - 10}/${h.total}` : `${h.total}`;
}
function CardRow({ cards, size = 'md' }: { cards: (string | null)[]; size?: 'sm' | 'md' }) {
return (
<div style={{ display: 'flex', gap: 4 }}>
{cards.map((c, i) => (
<PlayingCard key={i} card={c ? baseCard(c) : null} size={size} />
))}
</div>
);
}
function HandBox({ h, active }: { h: HandView; active: boolean }) {
const tag = h.outcome ? OUTCOME_KO[h.outcome] : HAND_KO[h.status];
const color = h.outcome === 'win' || h.outcome === 'blackjack' || h.outcome === 'bonus' ? '#16a34a' : h.outcome === 'lose' || h.status === 'bust' ? '#dc2626' : h.outcome === 'push' ? '#6b7280' : '#b45309';
return (
<div style={{ padding: 6, borderRadius: 10, border: active ? '2px solid #f59e0b' : '2px solid transparent', background: active ? 'rgba(245,158,11,0.12)' : 'transparent' }}>
<CardRow cards={h.cards} size="sm" />
<div className="small" style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 2 }}>
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{totalLabel(h)}</strong>
<span className="muted">{formatChips(h.bet)}{h.doubled ? ' ×2' : ''}</span>
{tag && <strong style={{ color }}>{tag}</strong>}
</div>
</div>
);
}
function SeatHands({ seat, me, players, isTurn }: { seat: SeatView; me: string | null; players: Record<string, PublicUser>; isTurn: boolean }) {
return (
<div style={{ textAlign: 'center' }}>
<div className="small" style={{ fontWeight: 800, marginBottom: 2 }}>
{seat.id === me ? '나' : nick(players, seat.id)}
{seat.net !== null && seat.net !== 0 && <span style={{ color: seat.net > 0 ? '#16a34a' : '#dc2626', marginLeft: 6 }}>{seat.net > 0 ? '+' : ''}{formatChips(seat.net)}</span>}
</div>
<div style={{ display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' }}>
{seat.hands!.map((h, i) => (
<HandBox key={i} h={h} active={isTurn && i === seat.active} />
))}
</div>
<div className="small muted">{formatChips(seat.chips)}</div>
</div>
);
}
// ---------------------------------------------------------------- board
function Board({ view: v, me, players }: BoardProps<BlackjackView>) {
const d = v.dealer;
const dealerTotal = d.revealed ? (d.bust ? `${d.total} 버스트` : d.blackjack ? '블랙잭' : `${d.total}`) : `${d.total} +?`;
const dealt = v.seats.filter((s) => s.hands);
return (
<div style={{ background: 'radial-gradient(circle at 50% 0%, #0f6b3d, #0a4f2d)', borderRadius: 16, padding: 16, color: '#fff' }}>
<div style={{ textAlign: 'center', marginBottom: 12 }}>
<div className="small" style={{ fontWeight: 800, opacity: 0.85 }}>딜러 · {dealerTotal}</div>
<div style={{ display: 'flex', gap: 4, justifyContent: 'center', marginTop: 4, minHeight: 90 }}>
{d.cards.length ? d.cards.map((c, i) => <PlayingCard key={i} card={c ? baseCard(c) : null} size="md" />) : <span className="small" style={{ opacity: 0.7, alignSelf: 'center' }}>베팅을 기다려요</span>}
</div>
</div>
<div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap' }}>
{dealt.length ? (
dealt.map((seat) => <SeatHands key={seat.id} seat={seat} me={me} players={players} isTurn={v.phase === 'playing' && v.turn === seat.id} />)
) : (
<span className="small" style={{ opacity: 0.8 }}>모두 베팅하는 중이에요…</span>
)}
</div>
</div>
);
}
// ---------------------------------------------------------------- side (controls)
function BetControls({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
const range = v.betRange!;
const [amount, setAmount] = useState(range.min);
const amt = Math.min(range.max, Math.max(range.min, Math.round(amount / range.step) * range.step));
const step = (d: number) => setAmount((a) => Math.min(range.max, Math.max(range.min, a + d * range.step)));
return (
<div className="stack" style={{ gap: 8 }}>
<div style={{ display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center' }}>
<button type="button" className="btn btn-secondary" disabled={pending || amt <= range.min} onClick={() => step(-1)} aria-label="베팅 줄이기">−</button>
<strong style={{ minWidth: 90, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>{formatChips(amt)}</strong>
<button type="button" className="btn btn-secondary" disabled={pending || amt >= range.max} onClick={() => step(1)} aria-label="베팅 늘리기">+</button>
</div>
<button type="button" className="btn btn-primary btn-block" disabled={pending} onClick={() => act({ type: 'bet', amount: amt })}>
{formatChips(amt)} 베팅
</button>
</div>
);
}
function ActionButtons({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
const my = v.my!;
const btn = (label: string, type: string, on: boolean, primary = false) =>
on ? (
<button key={type} type="button" className={`btn ${primary ? 'btn-primary' : 'btn-secondary'}`} style={{ flex: 1, minWidth: 72 }} disabled={pending} onClick={() => act({ type })}>
{label}
</button>
) : null;
return (
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{btn('히트', 'hit', my.canHit, true)}
{btn('스탠드', 'stand', my.canStand)}
{btn('더블', 'double', my.canDouble)}
{btn('스플릿', 'split', my.canSplit)}
{btn('서렌더', 'surrender', my.canSurrender)}
</div>
);
}
function Side({ view: v, me, players, act, pending, deadline }: BoardProps<BlackjackView>) {
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
const mine = isMyTurn(v, me);
function Side({ view: v, me, players }: BoardProps<BlackjackView>) {
const ranked = [...v.seats].sort((a, b) => b.chips - a.chips);
return (
<div className="stack" style={{ gap: 12 }}>
{seat && (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Chips n={seat.chips} strong />
{mine && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={28} />}
</div>
)}
{v.phase === 'betting' && seat && (mine ? <BetControls v={v} act={act} pending={pending} /> : seat.betLocked ? <p className="small muted">베팅함: {formatChips(seat.bet)} · 다른 사람을 기다려요</p> : <p className="small muted">이번 판은 쉬어요</p>)}
{v.phase === 'insurance' && (v.insuranceOpen ? (
<div className="stack" style={{ gap: 6 }}>
<p className="small">딜러가 A를 보여 줬어요. 인슈어런스를 걸까요?</p>
<div style={{ display: 'flex', gap: 8 }}>
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: true })}>
걸기 ({formatChips(v.insuranceMax)})
</button>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: false })}>
안 함
</button>
</div>
</div>
) : (
<p className="small muted">인슈어런스 선택을 기다려요</p>
))}
{v.phase === 'playing' && (mine ? <ActionButtons v={v} act={act} pending={pending} /> : <p className="small muted">{v.turn ? `${nick(players, v.turn)}님 차례예요` : '딜러가 카드를 받고 있어요'}</p>)}
{v.phase === 'handEnd' && seat?.hands && (
<div className="stack" style={{ gap: 6 }}>
<p className="small">
이번 판 {seat.net === null || seat.net === 0 ? '비겼어요' : seat.net > 0 ? `+${formatChips(seat.net)} 땄어요` : `${formatChips(seat.net)} 잃었어요`}.
</p>
<button type="button" className="btn btn-primary btn-block" disabled={pending || seat.ready} onClick={() => act({ type: 'ready' })}>
{seat.ready ? '다음 판을 기다려요…' : '다음 판'}
</button>
</div>
)}
<SeatList v={v} me={me} players={players} />
{seat && <PlayChipNotice />}
<div className="card stack" style={{ gap: 4, padding: 12 }}>
<strong>칩 순위</strong>
<ul className="stack" style={{ gap: 4, listStyle: 'none', padding: 0, margin: 0 }}>
{ranked.map((s, i) => (
<li key={s.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 8, opacity: s.status === 'out' || s.status === 'left' ? 0.5 : 1 }}>
<span className="small" style={{ fontWeight: v.turn === s.id ? 800 : 600 }}>
{i + 1}. {s.id === me ? '나' : nick(players, s.id)}
{s.status === 'out' && ' (칩 소진)'}
{s.status === 'left' && ' (나감)'}
</span>
<span className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>{formatChips(s.chips)}</span>
</li>
))}
</ul>
</div>
{me && v.seats.some((s) => s.id === me) && <PlayChipNotice />}
</div>
);
}
function SeatList({ v, me, players }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser> }) {
return (
<ul className="stack" style={{ gap: 4, listStyle: 'none', padding: 0, margin: 0 }}>
{v.seats.map((s) => (
<li key={s.id} style={{ display: 'flex', justifyContent: 'space-between', opacity: s.status === 'out' || s.status === 'left' ? 0.5 : 1 }}>
<span className="small" style={{ fontWeight: v.turn === s.id ? 800 : 500 }}>
{s.id === me ? '나' : nick(players, s.id)}
{s.status === 'out' && ' (칩 소진)'}
{s.status === 'left' && ' (나감)'}
</span>
<span className="small muted">{formatChips(s.chips)}</span>
</li>
))}
</ul>
);
}
// ---------------------------------------------------------------- options (room settings)
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
@@ -375,7 +189,7 @@ function Rules({ options }: { options?: BlackjackOptions }) {
}
const ui: GameUI<BlackjackView, BlackjackOptions> = {
Board,
Board: BlackjackBoard,
Side,
statusText,
isMyTurn,

View File

@@ -96,7 +96,12 @@
- `hands`: `handLimit`판을 마치면 종료. `lastStanding`: 최소 베팅이 가능한 사람이 1명 이하가 되면 종료. 칩 순 등수, `scoreText = "N 칩"`.
## 9. UI/UX
- 가운데 초록 테이블: 위에 딜러(홀 카드 뒷면), 아래 참가자별 손패(합·베팅·결과 뱃지), 차례 손패는 노란 테두리. 오른쪽 패널: 내 칩, 단계별 버튼(베팅 ± / 히트·스탠드·더블·스플릿·서렌더 / 인슈어런스 걸기·안 함 / 다음 판), 자리별 칩 목록, 놀이용 칩 안내, 턴 타이머.
- 2026-10-17 다시 만듦(`apps/web/src/games/blackjack/board.tsx`): 모든 것을 가운데 판에서 보고 누른다(옆 패널은 칩 순위와 놀이용 칩 안내만).
- 테이블: 판 폭(최대 1180px)을 다 쓰는 반원 테이블. 위에 딜러 카드와 합, 오른쪽 위에 카드 슈(남은 벌 수), 가운데에 "BLACKJACK · 블랙잭 3:2 · 딜러 규칙" 인쇄. 참가자는 앞쪽 호를 따라 앉고(사람이 적으면 앞 가운데로 모임, 나눠 주는 순서는 오른쪽 → 왼쪽), 내 자리는 가운데 앞에 큰 카드로. 자리마다 손패(합 뱃지·건 칩·결과 뱃지), 판이 끝나면 +/- 칩, 이름표(아바타·칩). 차례 손패는 노란 테두리.
- 아래 조작판(흰 카드): 내 얼굴·칩·남은 시간 / 단계별 조작 / 판 정보(판 수·배당·S17/H17·슈·단축키). 내 차례면 파란 테두리와 "내 차례" 띠.
- 베팅: 숫자를 바로 적기(Enter로 걸기, 범위·단위가 틀리면 빨간 안내 후 가장 가까운 금액), −/+ 버튼, 판 위 마우스 휠(Shift는 10배)·↑↓ 키, 칩 버튼(+1·5·10·50단위), 최소·절반·최대·지난 베팅(이 기기에 저장), 막대(slider).
- 행동: 히트 H · 스탠드 S · 더블 D · 스플릿 P · 서렌더 R(키보드 단축키, 할 수 있는 것만 보임). 인슈어런스 걸기/안 함, 판 결과와 [다음 판]도 같은 자리.
- 카드 한 장씩: 서버가 여러 장을 한꺼번에 보내도(처음 나눠 주기, 딜러 차례) 화면은 실제 나눠 주는 순서(모두 1장 → 딜러 → 모두 2장 → 딜러 홀 카드)로 `BJ_DEAL_STEP_MS`(450ms) 간격으로 슈에서 날아와 놓이고, 딜러 홀 카드는 뒤집히며 펼쳐진다. 합은 놓인 카드만으로 세고, 승패·+/-는 카드가 다 놓인 뒤에 보인다. 엔진은 처음 나눠 주기와 딜러 차례에 그만큼(장당 450ms)을 다음 제한 시간에 더한다(`animLagMs`). 새 판이 시작되면 밀린 카드는 바로 보인다. 블랙잭·딜러 버스트 배너, 버스트 흔들림, 이기면 효과음.
- 초보자 도움: 30초 요약 3장(목표·행동·배당), `[?] 지금 할 수 있는 것`이 단계와 내 패에 맞춰 안내.
## 10. 테스트 체크리스트

View File

@@ -1489,6 +1489,7 @@ const PLANS: Record<string, Plan> = {
drive: async (pages) => {
let finished = false;
let hands = 0;
const shots = new Set<string>();
for (let t = 0; t < 2000 && !finished; t++) {
if (await pages[0]!.getByRole('dialog', { name: '게임 결과' }).count()) {
finished = true;
@@ -1501,6 +1502,13 @@ const PLANS: Record<string, Plan> = {
const btn = p.getByRole('button', { name }).first();
if ((await btn.count()) && (await btn.isEnabled({ timeout: 150 }).catch(() => false))) {
if (name === '다음 판') hands++;
// Screens: betting panel, my turn (after the one-by-one deal), result — PC and phone, first time each.
const tag = `${typeof name === 'string' ? name : 'bet'}-${(p.viewportSize()?.width ?? 0) < 600 ? 'phone' : 'pc'}`;
if (!shots.has(tag)) {
shots.add(tag);
if (name === '스탠드') await p.waitForTimeout(400);
await p.screenshot({ path: join(SHOTS, `blackjack-${tag}.png`), fullPage: tag.endsWith('phone') });
}
await btn.click({ timeout: 1000 }).catch(() => {});
acted = true;
break;

View File

@@ -89,9 +89,18 @@ function phaseMs(s: BlackjackState): number | null {
}
}
/**
* Time the screen spends dealing one card face up (client deal animation, docs §9). The opening deal and the dealer's
* play add this per card to the next clock, so the turn / result time starts when the cards have landed.
*/
export const BJ_DEAL_STEP_MS = 450;
function setClock(s: BlackjackState, now: number): void {
s.turnStartedAt = now;
const ms = phaseMs(s);
const lag = s.animLagMs ?? 0;
s.animLagMs = 0;
const base = phaseMs(s);
const ms = base === null ? null : base + lag;
s.deadlineMs = ms ?? 0;
s.deadlineAt = ms === null ? null : now + ms;
}
@@ -179,6 +188,7 @@ function deal(s: BlackjackState, ctx: Ctx): void {
s.dealer.push(draw(s, ctx));
s.dealerDown = true;
s.dealerBlackjack = handValue(s.dealer).total === 21;
s.animLagMs = (order.length * 2 + 2) * BJ_DEAL_STEP_MS;
log(s, { t: 'deal' });
ctx.events.push({ type: 'dealt' });
// Naturals are set now; they still compare to the dealer's natural.
@@ -245,6 +255,8 @@ function playDealer(s: BlackjackState, ctx: Ctx): void {
}
if (handValue(s.dealer).total > 21) log(s, { t: 'dealerBust', total: handValue(s.dealer).total });
}
// The hole card turns, then each drawn card lands one by one before the result shows.
s.animLagMs = (s.animLagMs ?? 0) + (s.dealer.length - 1) * BJ_DEAL_STEP_MS;
settleAndEnd(s, ctx);
}

View File

@@ -121,6 +121,8 @@ export interface BlackjackState {
handsPlayed: number;
deadlineAt: number | null;
deadlineMs: number;
/** Extra time for the deal animation, added once to the next clock (absent in older states = 0). */
animLagMs?: number;
turnStartedAt: number;
seq: number;
log: LogEntry[];