새 게임 블랙잭: 딜러(하우스) 상대 1~7명·놀이용 칩. 공식 규칙(6벌 S17·블랙잭 3:2·A/10 peek·아무 두 장 더블·DAS·4손패 스플릿·에이스 한 장)을 기본값으로, 한국 하우스 룰(5·6카드 찰리, 7-7-7 보너스 3:1, 배당 6:5·2:1·1:1, H17, 더블 9~11·10~11, 에이스 자유 히트·다시 스플릿, 레이트 서렌더, 인슈어런스)을 방 설정으로
- 엔진 packages/games/src/blackjack/(options·types·rules·index·bot): 베팅→인슈어런스→플레이→딜러→결과 단계 상태 기계, 비공개는 딜러 홀 카드와 슈뿐(재셔플마다 카드 id 유일), 칩은 하우스 상대로 정산 - 컴퓨터: 기본 전략(S17 차트) + 레벨 1~60(쉬움은 딜러 흉내·인슈어런스 가끔, 어려움은 차트대로·인슈어런스 거절) - 웹 apps/web/src/games/blackjack/: 초록 테이블·손패·단계별 버튼·방 설정 변형, 30초 요약·도움말, 표준 카드 아트 재사용 - 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·게임 탭, 문서(games/blackjack.md·README·로드맵·결정 사항), e2e/games.e2e.ts - 검증: 엔진·봇 테스트, 무작위 플레이(여러 옵션) JSON 왕복·정보 누출 없음, 전체 테스트 2,611개·타입 검사·웹 빌드 통과, bun e2e/games.e2e.ts blackjack 통과 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -5,11 +5,11 @@
|
||||
|
||||
운영 중: https://game.tkrmagid.kr
|
||||
|
||||
## 게임 (33개)
|
||||
## 게임 (34개)
|
||||
| 종류 | 게임 |
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루 |
|
||||
| 순발력·대화 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임 |
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
|
||||
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
|
||||
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)을 뺀 30개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)을 뺀 31개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
|
||||
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
|
||||
|
||||
68
apps/web/src/games/blackjack/help.ts
Normal file
68
apps/web/src/games/blackjack/help.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/** 블랙잭 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { BlackjackView, SeatView } from '@bg/games/blackjack';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const nm = (players: Record<string, PublicUser>, id: string | null | undefined) => `${(id && players[id]?.nickname) || '다른 사람'}님`;
|
||||
const chips = (n: number) => `${n.toLocaleString('ko-KR')} 칩`;
|
||||
|
||||
function handsLeftLine(v: BlackjackView): string {
|
||||
if (v.handLimit === null) return '칩이 가장 많은 한 사람이 남을 때까지 해요.';
|
||||
return `모두 ${v.handLimit}판 중 ${Math.min(v.handsPlayed + 1, v.handLimit)}판째예요.`;
|
||||
}
|
||||
|
||||
function mySeat(v: BlackjackView): SeatView | undefined {
|
||||
return v.me ? v.seats.find((s) => s.id === v.me) : undefined;
|
||||
}
|
||||
|
||||
export function helpNow(v: BlackjackView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const goal = '딜러보다 21에 가깝게 만들면 이겨요. 21을 넘기면(버스트) 바로 져요.';
|
||||
if (v.phase === 'finished') {
|
||||
return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
|
||||
}
|
||||
|
||||
const seat = mySeat(v);
|
||||
const dealerUp = v.dealer.cards[0] ? `딜러가 보여 준 카드 합은 ${v.dealer.total}이에요.` : '';
|
||||
|
||||
// Spectator or someone who is sitting out this hand.
|
||||
if (!seat || !seat.hands) {
|
||||
if (v.phase === 'betting') return `모두 베팅하는 중이에요.\n${goal} ${handsLeftLine(v)}`;
|
||||
if (v.phase === 'playing' && v.turn) return `${nm(players, v.turn)} 차례예요. ${dealerUp}\n${goal}`;
|
||||
if (v.phase === 'handEnd') return `이번 판 결과가 나왔어요. ${dealerUp}\n잠시 뒤 다음 판으로 넘어가요.`;
|
||||
return `${goal} ${handsLeftLine(v)}`;
|
||||
}
|
||||
|
||||
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.bet)}). 다른 사람이 걸면 카드를 나눠 줘요.`;
|
||||
}
|
||||
|
||||
if (v.phase === 'insurance') {
|
||||
if (v.insuranceOpen) {
|
||||
return `딜러가 A를 보여 줬어요. 인슈어런스를 걸지 고르는 중이에요.\n걸면 베팅의 절반(${chips(v.insuranceMax)})을 내고, 딜러가 블랙잭이면 2:1로 돌려받아요. 아니면 잃어요. 보통은 안 거는 게 유리해요.`;
|
||||
}
|
||||
return '인슈어런스를 골랐어요. 다른 사람을 기다려요.';
|
||||
}
|
||||
|
||||
if (v.phase === 'handEnd') {
|
||||
const net = seat.net ?? 0;
|
||||
const outcome = net > 0 ? `${chips(net)}을 땄어요!` : net < 0 ? `${chips(-net)}을 잃었어요.` : '비겼어요(그대로).';
|
||||
return `이번 판 결과: ${outcome} 지금 내 칩은 ${chips(seat.chips)}.\n잠시 뒤 다음 판으로 넘어가요. [다음 판]을 누르면 바로 넘어가요.`;
|
||||
}
|
||||
|
||||
// playing
|
||||
if (v.turn !== v.me || !v.my) {
|
||||
return `${nm(players, v.turn)} 차례예요. ${dealerUp}\n내 패는 그대로 두고 기다려요.`;
|
||||
}
|
||||
const h = seat.hands[seat.active];
|
||||
const my = v.my;
|
||||
const lines = [`내 차례예요. 지금 내 ${seat.hands.length > 1 ? `${seat.active + 1}번째 손패 ` : ''}합은 ${h?.total ?? 0}${h?.soft ? '(소프트)' : ''}이에요. ${dealerUp}`];
|
||||
const acts: string[] = ['[히트]로 한 장 더 받거나 [스탠드]로 멈춰요'];
|
||||
if (my.canDouble) acts.push('[더블]은 베팅을 두 배로 걸고 딱 한 장만 받아요');
|
||||
if (my.canSplit) acts.push('[스플릿]은 같은 숫자 두 장을 두 손패로 나눠요(베팅 한 번 더)');
|
||||
if (my.canSurrender) acts.push('[서렌더]는 베팅 절반만 잃고 이 판을 포기해요');
|
||||
lines.push(acts.join('. ') + '.');
|
||||
if ((h?.total ?? 0) >= 17 && !h?.soft) lines.push('17 이상이면 보통 멈춰요. 더 받으면 버스트 위험이 커요.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
389
apps/web/src/games/blackjack/index.tsx
Normal file
389
apps/web/src/games/blackjack/index.tsx
Normal file
@@ -0,0 +1,389 @@
|
||||
/** 블랙잭 화면 (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';
|
||||
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 type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
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':
|
||||
return isMyTurn(v, me) ? '베팅하세요' : '베팅을 기다려요';
|
||||
case 'insurance':
|
||||
return v.insuranceOpen ? '인슈어런스를 고르세요' : '인슈어런스 선택을 기다려요';
|
||||
case 'playing':
|
||||
return v.turn === me ? '내 차례예요' : v.turn ? `${nick(players, v.turn)}님 차례예요` : '딜러 차례예요';
|
||||
case 'handEnd':
|
||||
return '이번 판 결과';
|
||||
case 'finished':
|
||||
return v.result?.summary ?? '게임이 끝났어요';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- hand rendering
|
||||
|
||||
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);
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
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 }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{label}</strong>
|
||||
{children}
|
||||
{help && <span className="small muted">{help}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const onOff: [boolean, string][] = [
|
||||
[false, '끄기'],
|
||||
[true, '켜기'],
|
||||
];
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<BlackjackOptions>) {
|
||||
const set = (patch: Partial<BlackjackOptions>) => onChange({ ...o, ...patch });
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<Field label="덱 수">
|
||||
<Seg label="덱 수" value={o.decks} options={[[1, '1벌'], [2, '2벌'], [4, '4벌'], [6, '6벌'], [8, '8벌']]} onChange={(decks) => set({ decks })} />
|
||||
</Field>
|
||||
<Field label="딜러 소프트 17" help={o.dealerSoft17 === 'stand' ? '딜러는 소프트 17에서 멈춰요(S17·공식).' : '딜러는 소프트 17에서 한 장 더 받아요(H17).'}>
|
||||
<Seg label="딜러 소프트 17" value={o.dealerSoft17} options={[['stand', '스탠드(S17)'], ['hit', '히트(H17)']]} onChange={(dealerSoft17) => set({ dealerSoft17 })} />
|
||||
</Field>
|
||||
<Field label="블랙잭 배당">
|
||||
<Seg label="블랙잭 배당" value={o.blackjackPayout} options={[['3:2', '3:2'], ['6:5', '6:5'], ['2:1', '2:1'], ['1:1', '1:1']]} onChange={(blackjackPayout) => set({ blackjackPayout })} />
|
||||
</Field>
|
||||
<Field label="더블다운">
|
||||
<Seg label="더블다운" value={o.doubleRule} options={[['any', '아무 두 장'], ['9to11', '9~11'], ['10to11', '10~11'], ['none', '안 함']]} onChange={(doubleRule) => set({ doubleRule })} />
|
||||
</Field>
|
||||
<Field label="스플릿 후 더블(DAS)">
|
||||
<Seg label="스플릿 후 더블" value={o.doubleAfterSplit} options={onOff} onChange={(doubleAfterSplit) => set({ doubleAfterSplit })} />
|
||||
</Field>
|
||||
<Field label="스플릿 최대 손패 수">
|
||||
<Seg label="스플릿 최대 손패 수" value={o.splitMaxHands} options={[[2, '2개'], [3, '3개'], [4, '4개']]} onChange={(splitMaxHands) => set({ splitMaxHands })} />
|
||||
</Field>
|
||||
<Field label="에이스 스플릿" help={o.hitSplitAces ? '에이스를 나눈 뒤에도 자유롭게 받을 수 있어요.' : '에이스를 나누면 각각 한 장만 받아요(공식).'}>
|
||||
<Seg label="에이스 스플릿 후" value={o.hitSplitAces} options={[[false, '한 장만'], [true, '자유 히트']]} onChange={(hitSplitAces) => set({ hitSplitAces })} />
|
||||
</Field>
|
||||
<Field label="에이스 다시 스플릿">
|
||||
<Seg label="에이스 다시 스플릿" value={o.resplitAces} options={onOff} onChange={(resplitAces) => set({ resplitAces })} />
|
||||
</Field>
|
||||
<Field label="서렌더" help={o.surrender === 'late' ? '딜러 블랙잭 확인 뒤 베팅 절반만 잃고 포기할 수 있어요.' : '서렌더가 없어요.'}>
|
||||
<Seg label="서렌더" value={o.surrender} options={[['none', '없음'], ['late', '레이트']]} onChange={(surrender) => set({ surrender })} />
|
||||
</Field>
|
||||
<Field label="인슈어런스(딜러 A일 때)">
|
||||
<Seg label="인슈어런스" value={o.insurance} options={onOff} onChange={(insurance) => set({ insurance })} />
|
||||
</Field>
|
||||
<Field label="(하우스 룰) 카드 찰리" help={o.charlie === 'off' ? '' : `${o.charlie === 'five' ? '5' : '6'}장까지 버스트하지 않으면 자동으로 이겨요.`}>
|
||||
<Seg label="카드 찰리" value={o.charlie} options={[['off', '없음'], ['six', '6장'], ['five', '5장']]} onChange={(charlie) => set({ charlie })} />
|
||||
</Field>
|
||||
<Field label="(하우스 룰) 7-7-7 보너스" help="7 세 장(21)이면 3:1로 받아요.">
|
||||
<Seg label="7-7-7 보너스" value={o.sevenTriple} options={onOff} onChange={(sevenTriple) => set({ sevenTriple })} />
|
||||
</Field>
|
||||
<Field label="시작 칩">
|
||||
<Seg label="시작 칩" value={o.startingChips} options={[[500, '500'], [1000, '1,000'], [2000, '2,000'], [5000, '5,000']]} onChange={(startingChips) => set({ startingChips })} />
|
||||
</Field>
|
||||
<Field label="최소 베팅(단위)">
|
||||
<Seg label="최소 베팅" value={o.minBet} options={[[10, '10'], [20, '20'], [50, '50'], [100, '100']]} onChange={(minBet) => set({ minBet })} />
|
||||
</Field>
|
||||
<Field label="게임 종료">
|
||||
<Seg label="게임 종료" value={o.endCondition} options={[['hands', '정해진 판 수'], ['lastStanding', '최후 1인']]} onChange={(endCondition) => set({ endCondition })} />
|
||||
</Field>
|
||||
{o.endCondition === 'hands' && (
|
||||
<Field label="판 수">
|
||||
<Seg label="판 수" value={o.handLimit} options={[[5, '5판'], [10, '10판'], [20, '20판'], [30, '30판']]} onChange={(handLimit) => set({ handLimit })} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="행동 제한 시간">
|
||||
<Seg label="행동 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: BlackjackOptions): string {
|
||||
const parts = [`${o.decks}벌`, `BJ ${o.blackjackPayout}`, o.dealerSoft17 === 'hit' ? 'H17' : 'S17'];
|
||||
if (o.charlie !== 'off') parts.push(o.charlie === 'five' ? '5카드 찰리' : '6카드 찰리');
|
||||
if (o.sevenTriple) parts.push('7트리플');
|
||||
if (o.surrender === 'late') parts.push('서렌더');
|
||||
parts.push(o.endCondition === 'hands' ? `${o.handLimit}판` : '최후 1인');
|
||||
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function Rules({ options }: { options?: BlackjackOptions }) {
|
||||
const o: BlackjackOptions = {
|
||||
decks: 6, dealerSoft17: 'stand', blackjackPayout: '3:2', doubleRule: 'any', doubleAfterSplit: true, splitMaxHands: 4,
|
||||
resplitAces: false, hitSplitAces: false, surrender: 'none', insurance: true, charlie: 'off', sevenTriple: false,
|
||||
startingChips: 1000, minBet: 10, endCondition: 'hands', handLimit: 10, betSeconds: 20, turnSeconds: 20, handEndSeconds: 4, awaySeconds: 5,
|
||||
...(options ?? {}),
|
||||
};
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
딜러를 상대로 카드 합을 <strong>21에 가깝게</strong> 만드는 게임이에요. 2~10은 숫자대로, J·Q·K는 10, A는 1이나 11 중 좋은 쪽으로 세요. 21을 넘으면(버스트) 바로 져요.
|
||||
</p>
|
||||
<p>
|
||||
먼저 베팅을 걸면 모두 두 장씩 받고, 딜러는 한 장을 펼치고 한 장을 가려요. 처음 두 장이 A+10이면 <strong>블랙잭</strong>(배당 {o.blackjackPayout})이에요.
|
||||
</p>
|
||||
<p>
|
||||
내 차례에 <strong>히트</strong>(한 장 더), <strong>스탠드</strong>(멈춤)를 골라요. 처음 두 장이면 <strong>더블</strong>(베팅 두 배, 한 장만){o.doubleRule === 'none' ? '은 꺼져 있어요' : o.doubleRule === 'any' ? '을 아무 때나' : `는 합 ${o.doubleRule === '9to11' ? '9~11' : '10~11'}에서만`} 할 수 있고, 같은 숫자 두 장이면 <strong>스플릿</strong>(최대 {o.splitMaxHands}손패)으로 나눠요{o.doubleAfterSplit ? '(스플릿 뒤에도 더블 가능)' : ''}. 에이스를 나누면 {o.hitSplitAces ? '자유롭게 더 받아요' : '각각 한 장만 받아요'}.
|
||||
</p>
|
||||
{o.surrender === 'late' && <p><strong>서렌더</strong>: 처음 두 장일 때 베팅 절반만 잃고 그 판을 포기할 수 있어요.</p>}
|
||||
{o.insurance && <p><strong>인슈어런스</strong>: 딜러가 A를 펼치면 베팅 절반을 더 걸 수 있어요. 딜러가 블랙잭이면 2:1로 돌려받고, 아니면 잃어요.</p>}
|
||||
<p>
|
||||
모두 멈추면 딜러가 가린 카드를 펼치고 <strong>{o.dealerSoft17 === 'hit' ? '소프트 17까지 받고' : '17 이상이면 멈추고'}</strong> 승부해요. 딜러가 버스트거나 내 수가 더 크면 1:1로 받고, 같으면 푸시(비김), 작으면 져요.
|
||||
</p>
|
||||
{o.charlie !== 'off' && <p><strong>카드 찰리</strong>(하우스 룰): 버스트하지 않고 {o.charlie === 'five' ? '5' : '6'}장을 모으면 자동으로 이겨요.</p>}
|
||||
{o.sevenTriple && <p><strong>7-7-7 보너스</strong>(하우스 룰): 7 세 장(21)이면 3:1로 받아요.</p>}
|
||||
<p>
|
||||
{o.endCondition === 'hands' ? `${o.handLimit}판을 치고 칩이 가장 많은 사람이 이겨요.` : '칩이 가장 많은 한 사람이 남을 때까지 해요.'}
|
||||
{o.turnSeconds === null ? ' 이 방은 행동 시간 제한이 없어요.' : ` 시간 안에 고르지 않으면 자동으로 멈춰요(스탠드).`}
|
||||
</p>
|
||||
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<BlackjackView, BlackjackOptions> = {
|
||||
Board,
|
||||
Side,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
75
apps/web/src/games/blackjack/quick.tsx
Normal file
75
apps/web/src/games/blackjack/quick.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
/** 블랙잭 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** A 46 × 64 card at (x, y) showing a rank + suit. */
|
||||
function Card({ r = '', s, x, y, down }: { r?: string; s?: string; x: number; y: number; down?: boolean }) {
|
||||
const red = s === '♥' || s === '◆';
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`}>
|
||||
<rect width={46} height={64} rx={7} fill={down ? '#1e3a8a' : '#fffef9'} stroke="#334155" strokeWidth={2} />
|
||||
{down ? (
|
||||
<rect x={6} y={6} width={34} height={52} rx={4} fill="none" stroke="#93c5fd" strokeWidth={2} strokeDasharray="4 3" />
|
||||
) : (
|
||||
<>
|
||||
<text x={8} y={20} fontSize={16} fontWeight={900} fill={red ? '#dc2626' : '#111827'}>
|
||||
{r}
|
||||
</text>
|
||||
<text x={23} y={46} textAnchor="middle" fontSize={22} fill={red ? '#dc2626' : '#111827'}>
|
||||
{s}
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 150" width={250} height={150} aria-hidden>
|
||||
<text x={12} y={16} fontSize={12} fontWeight={800} fill="#6b7280">딜러</text>
|
||||
<Card r="K" s="♠" x={12} y={22} />
|
||||
<Card x={58} y={22} down />
|
||||
<text x={12} y={96} fontSize={12} fontWeight={800} fill="#6b7280">나 (합 20)</text>
|
||||
<Card r="10" s="♥" x={12} y={102} />
|
||||
<Card r="Q" s="♣" x={58} y={102} />
|
||||
<text x={150} y={78} fontSize={20} fontWeight={900} fill="#15803d">21에 가깝게!</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '딜러는 카드 한 장을 가리고, 내 두 장은 합이 20',
|
||||
title: '딜러보다 21에 가깝게',
|
||||
text: '카드 두 장을 받아요. 2~10은 숫자대로, J·Q·K는 10, A는 1 또는 11. 21을 넘기면(버스트) 바로 져요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
{['히트', '스탠드', '더블', '스플릿'].map((t, i) => (
|
||||
<g key={t} transform={`translate(${8 + i * 60} 40)`}>
|
||||
<rect width={52} height={40} rx={10} fill="#1d4ed8" />
|
||||
<text x={26} y={25} textAnchor="middle" fontSize={13} fontWeight={800} fill="#fff">
|
||||
{t}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
<text x={125} y={100} textAnchor="middle" fontSize={13} fill="#374151">한 장 더 받거나 멈추고, 두 배로 걸거나 쌍패를 나눠요</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '히트·스탠드·더블·스플릿 버튼',
|
||||
title: '히트·스탠드·더블·스플릿',
|
||||
text: '내 차례에 히트(한 장 더), 스탠드(멈춤). 처음 두 장이면 더블(두 배로 걸고 한 장), 같은 숫자면 스플릿으로 두 손패로 나눠요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<Card r="A" s="♠" x={16} y={16} />
|
||||
<Card r="K" s="♥" x={58} y={16} />
|
||||
<text x={118} y={40} fontSize={15} fontWeight={900} fill="#b45309">블랙잭!</text>
|
||||
<text x={118} y={62} fontSize={14} fontWeight={800} fill="#15803d">3 : 2 배당</text>
|
||||
<text x={16} y={100} fontSize={13} fill="#374151">딜러는 17이 될 때까지 받고 멈춰요</text>
|
||||
</svg>
|
||||
),
|
||||
alt: 'A와 K로 만든 블랙잭은 3대 2 배당',
|
||||
title: '블랙잭은 3:2',
|
||||
text: '처음 두 장이 A+10이면 블랙잭(3:2). 다들 멈추면 딜러가 17까지 받아요. 딜러가 버스트거나 내 수가 더 크면 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(33);
|
||||
expect(IDS).toHaveLength(34);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
@@ -35,6 +35,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
uno: () => import('./uno'),
|
||||
liar: () => import('./liar'),
|
||||
'magical-athlete': () => import('./magical-athlete'),
|
||||
blackjack: () => import('./blackjack'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
@@ -32,6 +32,7 @@ export const GAME_ICON: Record<string, string> = {
|
||||
uno: '🌈',
|
||||
liar: '🤥',
|
||||
'magical-athlete': '🏃',
|
||||
blackjack: '🂡',
|
||||
};
|
||||
|
||||
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
|
||||
@@ -40,6 +41,6 @@ export const UPCOMING: string[] = [];
|
||||
/** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */
|
||||
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] },
|
||||
];
|
||||
|
||||
@@ -110,6 +110,12 @@
|
||||
- 진행 결과: 테스트 2,520개 통과(+선택 22개), 타입 검사·빌드 통과, 게임 33종 전부·채팅·컴퓨터 E2E 통과.
|
||||
- 남은 문제: 구십구 E2E는 판이 아주 빨리 끝나면(실제 5턴) "턴이 너무 적음" 검사에 걸릴 때가 있다(예전부터 있던 검사, 다시 돌리면 통과).
|
||||
|
||||
## 블랙잭 추가 (2026-10-14)
|
||||
- 딜러(하우스) 상대 1~7명, 놀이용 칩. 공식 규칙(6벌 S17·3:2·peek)을 기본값으로, 한국 하우스 룰(5·6카드 찰리, 7-7-7 보너스, 배당·H17·서렌더·인슈어런스)을 방 설정으로.
|
||||
- 엔진 `packages/games/src/blackjack/`(options·types·rules·index·bot), 공유 덱 헬퍼(`@bg/engine` cards), 베팅→인슈어런스→플레이→딜러→결과 단계 상태 기계. 비공개 정보는 딜러 홀 카드와 슈뿐(재셔플마다 카드 id 유일).
|
||||
- 컴퓨터는 기본 전략(S17 차트) + 레벨(1~60)로 쉬움은 딜러 흉내·인슈어런스 가끔, 어려움은 차트대로·인슈어런스 거절.
|
||||
- **진행 결과(2026-10-14)**: 게임 34종. 블랙잭 엔진·봇 테스트 통과, 무작위 플레이(여러 옵션) JSON 왕복·비공개 정보 누출 없음, 전체 타입 검사·웹 빌드 통과, `bun e2e/games.e2e.ts blackjack`(브라우저 2개로 한 세션) 통과.
|
||||
|
||||
## 순서 원칙
|
||||
- 플랫폼(M1)의 안정성 기능이 먼저다. 게임은 그 위에 하나씩 얹는다.
|
||||
- 각 게임은 "규칙 모듈 + 테스트 통과 → 화면 → E2E 한 판" 순서로 완성하고 다음 게임으로 간다.
|
||||
|
||||
@@ -64,6 +64,7 @@
|
||||
| 라이어 게임 (2026-10-12) | 라이어 1명, 설명 1바퀴, 동점은 한 번 더 투표 후 또 동점이면 라이어 승, 정답은 직접 적기 | 주제, 바보 모드, 2바퀴, 목록에서 고르기, 단계별 시간 |
|
||||
| 루미큐브 (2026-10-14) | 루미큐브 앱 방식: 칸 판에 끌어다 놓기, 옮기는 타일 모두에게 보이기, 되돌리기 = 차례 처음으로, 시간 초과는 무조건 되돌리고 1장, 틀린 완료는 알려 주고 계속 | 종이 규칙서(시간 초과 3장·올바른 배치 자동 완료), 옮기는 타일 비공개, 인원수만큼 판, 첫 등록 0·20·50점, 조커 50점 |
|
||||
| 야단법석 달리기 (2026-10-13) | 4~6명은 선수 4명(경주마다 1명), 2~3명은 8명(둘씩), 경주 4번·1등 3점 2등 1점, 원작 선수 36명 중 24명 | 순한 판·거친 판, 뒤로 갈수록 커지는 점수표 |
|
||||
| 블랙잭 (2026-10-14) | 카지노 공식: 6벌 슈, 딜러 S17, 블랙잭 3:2, 아무 두 장 더블·DAS 허용, 4손패까지 스플릿(에이스는 한 장만), 서렌더 없음, 인슈어런스 제공, 딜러 A/10 peek, 10판·놀이용 칩 1,000 | 덱 1~8, H17, 배당 6:5·2:1·1:1, 더블 9~11·10~11·없음, 에이스 자유 히트·다시 스플릿, 레이트 서렌더, 5·6카드 찰리, 7-7-7 보너스(3:1), 최후 1인 |
|
||||
|
||||
## 게임 그림 출처 (2026-10-13)
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
| `uno` | 우노 | 2~10 | M9 |
|
||||
| `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 |
|
||||
| `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 |
|
||||
| `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
114
docs/games/blackjack.md
Normal file
114
docs/games/blackjack.md
Normal file
@@ -0,0 +1,114 @@
|
||||
# 블랙잭 (`blackjack`)
|
||||
|
||||
> 마일스톤: 2026-10 새 게임 · 인원: 최소 1 ~ 최대 7명 · 예상 시간: 약 10~20분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 딜러(하우스)를 상대로 카드 합을 21에 가깝게 만드는 세계에서 가장 유명한 카지노 카드 게임. 플레이어끼리 겨루지 않고 각자 딜러와 승부한다.
|
||||
- 놀이용 칩으로 베팅한다(docs/04 §6). 실제 돈과 무관하고 충전·환전이 없다.
|
||||
- 인원: 혼자서도 딜러와 할 수 있고(1명), 카지노 테이블 자리 수에 맞춰 최대 7명까지. 딜러는 사람이 아니라 규칙대로 움직이는 하우스다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
공식 규칙이 기본값이고, 한국에서 많이 쓰는 하우스 룰은 방 설정으로 켠다.
|
||||
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `decks` | 덱 수(슈) | 1 / 2 / 4 / 6 / 8 | 6 |
|
||||
| `dealerSoft17` | 딜러 소프트 17 | stand(S17) / hit(H17) | stand |
|
||||
| `blackjackPayout` | 블랙잭 배당 | 3:2 / 6:5 / 2:1 / 1:1 | 3:2 |
|
||||
| `doubleRule` | 더블다운 허용 | any / 9to11 / 10to11 / none | any |
|
||||
| `doubleAfterSplit` | 스플릿 후 더블(DAS) | 허용 / 불가 | 허용 |
|
||||
| `splitMaxHands` | 스플릿 최대 손패 수 | 2 / 3 / 4 | 4 |
|
||||
| `resplitAces` | 에이스 다시 스플릿 | 허용 / 불가 | 불가 |
|
||||
| `hitSplitAces` | 에이스 스플릿 후 자유 히트 | 허용 / 한 장만 | 한 장만 |
|
||||
| `surrender` | 서렌더 | none / late(레이트) | none |
|
||||
| `insurance` | 인슈어런스(딜러 A) | 제공 / 없음 | 제공 |
|
||||
| `charlie` | (하우스 룰) 카드 찰리 | off / six / five | off |
|
||||
| `sevenTriple` | (하우스 룰) 7-7-7 보너스(3:1) | 켜기 / 끄기 | 끄기 |
|
||||
| `startingChips` | 시작 칩 | 500 / 1,000 / 2,000 / 5,000 | 1,000 |
|
||||
| `minBet` | 최소 베팅(단위) | 10 / 20 / 50 / 100 | 10 |
|
||||
| `endCondition` | 게임 종료 | hands / lastStanding | hands |
|
||||
| `handLimit` | 판 수(정해진 판 수) | 5 / 10 / 20 / 30 | 10 |
|
||||
| `betSeconds` / `turnSeconds` | 베팅·행동 제한 시간(무제한 선택 가능) | 15/20/30(/60) / null | 20 |
|
||||
| `handEndSeconds` | 결과 보여 주는 시간 | 3 / 4 / 6 / 10 | 4 |
|
||||
|
||||
## 3. 구성물
|
||||
- 표준 52장 덱 × `decks`벌을 섞은 슈. 카드는 `components/cards/PlayingCard`로 그린다(그림카드·조커 실제 아트, CC0). 카드 id에는 섞을 때마다 바뀌는 접미사가 붙어 전역적으로 유일하다(`baseCard`로 벗겨 표시).
|
||||
- 놀이용 칩.
|
||||
|
||||
## 4. 준비(셋업)
|
||||
- 모두 `startingChips`로 시작. 슈를 섞는다.
|
||||
- 매 판 시작 때 `minBet` 이상 걸 수 있는 사람만 참가한다. 슈가 25% 미만으로 줄면 다음 판 시작 때 새로 섞는다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
1. **베팅**: 참가자가 동시에 베팅(최소~가진 칩, 단위 `minBet`)을 건다.
|
||||
2. **딜**: 참가자 2장(공개), 딜러는 1장 공개 + 1장(홀 카드) 뒤집어 받는다. A+10이면 내추럴 블랙잭.
|
||||
3. **인슈어런스**(옵션): 딜러 공개 카드가 A면 참가자가 베팅 절반까지 인슈어런스를 건다. 모두 답하면 딜러가 블랙잭인지 확인한다. 딜러 공개 카드가 A/10이면 블랙잭 여부를 먼저 확인(peek)하고, 블랙잭이면 그 자리에서 정산한다.
|
||||
4. **플레이**: 자리 순서대로 각자 손패에 대해
|
||||
- **히트**(한 장 더), **스탠드**(멈춤)
|
||||
- **더블**: 처음 두 장일 때 베팅을 두 배로 걸고 딱 한 장만 받는다(`doubleRule`·DAS 조건).
|
||||
- **스플릿**: 같은 값 두 장을 두 손패로 나눈다(각각 한 장씩 받음, `splitMaxHands`까지). 에이스를 나누면 기본은 각 한 장만(`hitSplitAces`·`resplitAces`로 완화).
|
||||
- **서렌더**: 레이트 서렌더가 켜져 있고 처음 두 장이면 베팅 절반만 잃고 포기.
|
||||
- 21에 닿으면 자동 스탠드, 21 초과면 버스트(즉시 패). 찰리 수에 닿으면 자동 승(charlie).
|
||||
5. **딜러**: 모두 끝나면 홀 카드를 공개하고 `dealerSoft17` 규칙대로 17까지(또는 소프트 17까지) 받는다. 살아 있는(스탠드) 손패가 없으면 받지 않는다.
|
||||
6. **정산** 후 결과를 `handEndSeconds` 동안 보여 주고, 모두 [다음 판]을 누르면 다음 판으로.
|
||||
|
||||
## 6. 승패와 점수 계산
|
||||
한 손패 기준(베팅 = 스테이크):
|
||||
- 버스트/패: −베팅. 서렌더: −베팅/2.
|
||||
- 내추럴 블랙잭: 딜러도 블랙잭이면 푸시, 아니면 `blackjackPayout`(3:2 → +1.5배).
|
||||
- 딜러 블랙잭: 블랙잭이 아닌 모든 손패는 패.
|
||||
- 찰리: +1배. 7-7-7 보너스(옵션): +3배.
|
||||
- 그 외: 딜러 버스트거나 내 합 > 딜러 합 → +1배, 같으면 푸시, 작으면 패.
|
||||
- 인슈어런스: 딜러 블랙잭이면 +2배(2:1), 아니면 −인슈어런스.
|
||||
- 칩은 하우스를 상대로 오르내린다(플레이어끼리 보존되지 않음). 게임 종료 시 칩이 많은 순으로 등수, 결과 점수는 `"N 칩"`.
|
||||
|
||||
## 7. 지역 룰 / 하우스 룰 (옵션으로 켜고 끄기)
|
||||
- **카드 찰리**(5장/6장): 버스트 없이 그 장수를 모으면 자동 승. 한국 집·동호회에서 흔한 룰.
|
||||
- **7-7-7 보너스**: 7 세 장(21)이면 3:1. 한국에서 블랙잭 이상으로 쳐 주는 룰.
|
||||
- **블랙잭 배당 2:1** 등 완화된 배당, **딜러 H17**, **서렌더/인슈어런스 끄기**도 방 설정으로 조절.
|
||||
|
||||
## 8. 엔진 설계
|
||||
### 8.1 상태(State)
|
||||
`packages/games/src/blackjack/types.ts`의 `BlackjackState`: `seats`(칩·상태), `shoe`(비공개)+`shoeGen`, `dealer`+`dealerDown`+`dealerBlackjack`, 참가자별 `rounds`(베팅·손패 배열·인슈어런스·ready), `order`, `turn`, `phase`(betting/insurance/playing/handEnd/finished), `handsPlayed`, 마감 시각, `log`, `result`.
|
||||
|
||||
### 8.2 액션
|
||||
| type | payload | 누가 / 언제 | 검증 |
|
||||
|---|---|---|---|
|
||||
| `bet` | amount | 참가자 / 베팅 단계 | min~max, 단위 배수, 칩 충분 |
|
||||
| `insurance` | take | 참가자 / 인슈어런스 단계 | 아직 미응답, (걸면)칩 충분 |
|
||||
| `hit`/`stand` | — | 차례인 사람 / 플레이 | 활성 손패가 playing |
|
||||
| `double` | — | 차례 / 플레이 | `canDouble` |
|
||||
| `split` | — | 차례 / 플레이 | `canSplit` |
|
||||
| `surrender` | — | 차례 / 플레이 | `canSurrender` |
|
||||
| `ready` | — | 참가자 / 결과 단계 | 아직 미준비 |
|
||||
| `timeout`/`leave` | — | 시스템 | — |
|
||||
|
||||
### 8.3 공개/비공개 정보 (view)
|
||||
- 플레이어 손패는 모두 공개(앞면). 비공개는 **딜러 홀 카드**(공개 전)와 **슈 전체**뿐. `secretsOf`가 이 둘을 돌려주어 어떤 view에도 새지 않음을 테스트로 강제한다. 홀 카드는 공개 전 `null`로 표시.
|
||||
|
||||
### 8.4 랜덤 요소
|
||||
- 슈 셔플(시드 RNG). (재)셔플마다 `shoeGen`을 올려 카드 id를 유일하게 유지.
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김
|
||||
- 베팅 시간 초과 → 최소 베팅 자동, 인슈어런스 → 거절, 플레이 → 스탠드, 결과 → 자동 준비. 자리 비움(연속 시간 초과)은 `awaySeconds`로 짧게. `leave`는 들고 있던 단계를 자동 처리한다.
|
||||
|
||||
### 8.6 종료 조건과 결과(GameResult)
|
||||
- `hands`: `handLimit`판을 마치면 종료. `lastStanding`: 최소 베팅이 가능한 사람이 1명 이하가 되면 종료. 칩 순 등수, `scoreText = "N 칩"`.
|
||||
|
||||
## 9. UI/UX
|
||||
- 가운데 초록 테이블: 위에 딜러(홀 카드 뒷면), 아래 참가자별 손패(합·베팅·결과 뱃지), 차례 손패는 노란 테두리. 오른쪽 패널: 내 칩, 단계별 버튼(베팅 ± / 히트·스탠드·더블·스플릿·서렌더 / 인슈어런스 걸기·안 함 / 다음 판), 자리별 칩 목록, 놀이용 칩 안내, 턴 타이머.
|
||||
- 초보자 도움: 30초 요약 3장(목표·행동·배당), `[?] 지금 할 수 있는 것`이 단계와 내 패에 맞춰 안내.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] `handValue` 소프트/하드 에이스, 덱 접미사 무시
|
||||
- [x] 정산: 블랙잭 3:2·6:5, 푸시, 버스트, 서렌더, 딜러 버스트, 찰리, 7-7-7
|
||||
- [x] 흐름: 베팅→딜→플레이→딜러→결과, 칩 비음 없음
|
||||
- [x] 무작위 플레이(여러 옵션) JSON 왕복·비공개 정보 누출 없음·시간 초과 합법·종료
|
||||
- [x] 봇: 1~60 레벨, 사람 1명 타임아웃 + 나머지 봇 전원이 판을 끝냄(bots.test)
|
||||
- [x] 웹: 30초 요약·도움말, E2E `bun e2e/games.e2e.ts blackjack`(브라우저 2개로 한 세션)
|
||||
|
||||
## 11. 참고 자료
|
||||
- 나무위키 "블랙잭(플레잉 카드)", 일반 카지노 공식 규칙(S17·3:2·peek), 한국 하우스 룰(5카드 찰리·7트리플).
|
||||
|
||||
## 12. 메모
|
||||
- "블랙잭"은 일반 명칭으로 상표 문제 없음. 칩은 놀이용 점수로만 표기(돈 표현 금지, docs/04 §6).
|
||||
@@ -1181,6 +1181,43 @@ async function magicalStep(p: Page, phone: boolean, st: { picks: number; selects
|
||||
}
|
||||
|
||||
const PLANS: Record<string, Plan> = {
|
||||
blackjack: {
|
||||
// PC host + phone guest. Each hand: bet the minimum, stand (decline insurance), then press 다음 판, until the
|
||||
// session ends (10 hands). Smoke test only — the rules are covered by the engine tests.
|
||||
players: 2,
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '판 수' }).getByRole('button', { name: '5판' }).click();
|
||||
await host.getByText('5판').first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
let finished = false;
|
||||
let hands = 0;
|
||||
for (let t = 0; t < 2000 && !finished; t++) {
|
||||
if (await pages[0]!.getByRole('dialog', { name: '게임 결과' }).count()) {
|
||||
finished = true;
|
||||
break;
|
||||
}
|
||||
let acted = false;
|
||||
for (const p of pages) {
|
||||
const labels: (RegExp | string)[] = [/베팅$/, '스탠드', '안 함', '다음 판'];
|
||||
for (const name of labels) {
|
||||
const btn = p.getByRole('button', { name }).first();
|
||||
if ((await btn.count()) && (await btn.isEnabled({ timeout: 150 }).catch(() => false))) {
|
||||
if (name === '다음 판') hands++;
|
||||
await btn.click({ timeout: 1000 }).catch(() => {});
|
||||
acted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (acted) break;
|
||||
}
|
||||
if (!acted) await pages[0]!.waitForTimeout(120);
|
||||
}
|
||||
if (!finished) throw new Error(`blackjack did not finish (${hands} hands advanced)`);
|
||||
await pages[0]!.screenshot({ path: join(SHOTS, 'blackjack-result-pc.png') });
|
||||
console.log(` blackjack: finished after ${hands} hands`);
|
||||
},
|
||||
},
|
||||
rummikub: {
|
||||
// PC host + phone guest, first meld "없음" so hint plays happen early; 10 real turns through the UI.
|
||||
lobby: async (host) => {
|
||||
|
||||
174
packages/games/src/blackjack/blackjack.test.ts
Normal file
174
packages/games/src/blackjack/blackjack.test.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, playoutSeeds, randomPlayout, seedN, type CardId, type RngState } from '@bg/engine';
|
||||
import {
|
||||
blackjack,
|
||||
buildShoe,
|
||||
chipsNonNegative,
|
||||
handValue,
|
||||
settleHand,
|
||||
setupBlackjack,
|
||||
type BlackjackOptions,
|
||||
type BlackjackState,
|
||||
type Hand,
|
||||
} from './index';
|
||||
|
||||
const rng = (seed = 1) => SeededRng.fromSeed(seedN(seed));
|
||||
|
||||
function make(opts: Partial<BlackjackOptions> = {}, players = ['A', 'B'], shoe?: CardId[]): BlackjackState {
|
||||
const options = blackjack.optionsSchema.parse(opts);
|
||||
return setupBlackjack({ players, options, rng: rng(), now: 0 }, shoe ? { shoe } : undefined);
|
||||
}
|
||||
|
||||
const hand = (cards: CardId[], over: Partial<Hand> = {}): Hand => ({
|
||||
cards,
|
||||
bet: 100,
|
||||
status: 'stand',
|
||||
fromSplit: false,
|
||||
frozenAces: false,
|
||||
doubled: false,
|
||||
outcome: null,
|
||||
net: 0,
|
||||
...over,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- hand value
|
||||
|
||||
describe('handValue', () => {
|
||||
test('소프트/하드 에이스', () => {
|
||||
expect(handValue(['AS', '6H'])).toEqual({ total: 17, soft: true });
|
||||
expect(handValue(['AS', '6H', 'KD'])).toEqual({ total: 17, soft: false });
|
||||
expect(handValue(['AS', 'AD', '9C'])).toEqual({ total: 21, soft: true });
|
||||
expect(handValue(['KS', 'QD', '2C'])).toEqual({ total: 22, soft: false });
|
||||
expect(handValue(['AS', 'KD'])).toEqual({ total: 21, soft: true });
|
||||
});
|
||||
test('덱 접미사를 무시해요', () => {
|
||||
expect(handValue(['AS#0', 'KD#3'])).toEqual({ total: 21, soft: true });
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- settlement
|
||||
|
||||
describe('settleHand', () => {
|
||||
const o = blackjack.optionsSchema.parse({});
|
||||
test('내추럴 블랙잭은 3:2', () => {
|
||||
expect(settleHand(hand(['AS', 'KD'], { bet: 100 }), ['9H', '7C'], false, o)).toEqual({ outcome: 'blackjack', net: 150 });
|
||||
});
|
||||
test('딜러 블랙잭엔 푸시', () => {
|
||||
expect(settleHand(hand(['AS', 'KD']), ['AH', 'QC'], true, o)).toEqual({ outcome: 'push', net: 0 });
|
||||
});
|
||||
test('버스트는 베팅을 잃어요', () => {
|
||||
expect(settleHand(hand(['KS', 'QD', '5C'], { status: 'bust', bet: 100 }), ['9H', '8C'], false, o)).toEqual({ outcome: 'lose', net: -100 });
|
||||
});
|
||||
test('서렌더는 절반만 잃어요', () => {
|
||||
expect(settleHand(hand(['KS', '6D'], { status: 'surrender', bet: 100 }), ['9H', '8C'], false, o)).toEqual({ outcome: 'lose', net: -50 });
|
||||
});
|
||||
test('딜러 버스트면 이겨요', () => {
|
||||
expect(settleHand(hand(['KS', '8D'], { bet: 100 }), ['9H', '5C', 'KD'], false, o)).toEqual({ outcome: 'win', net: 100 });
|
||||
});
|
||||
test('6:5 블랙잭 배당', () => {
|
||||
const o65 = blackjack.optionsSchema.parse({ blackjackPayout: '6:5' });
|
||||
expect(settleHand(hand(['AS', 'KD'], { bet: 100 }), ['9H', '7C'], false, o65)).toEqual({ outcome: 'blackjack', net: 120 });
|
||||
});
|
||||
test('5카드 찰리는 자동 승', () => {
|
||||
const oc = blackjack.optionsSchema.parse({ charlie: 'five' });
|
||||
expect(settleHand(hand(['2S', '3D', '2C', '4H', '5S'], { status: 'charlie', bet: 100 }), ['KH', '9C'], false, oc)).toEqual({ outcome: 'win', net: 100 });
|
||||
});
|
||||
test('7-7-7 보너스는 3:1', () => {
|
||||
const o7 = blackjack.optionsSchema.parse({ sevenTriple: true });
|
||||
expect(settleHand(hand(['7S', '7D', '7C'], { bet: 100 }), ['KH', '9C'], false, o7)).toEqual({ outcome: 'bonus', net: 300 });
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- flow
|
||||
|
||||
describe('flow', () => {
|
||||
test('setup은 베팅 단계에서 시작해요', () => {
|
||||
const s = make();
|
||||
expect(s.phase).toBe('betting');
|
||||
expect(blackjack.activePlayers(s).sort()).toEqual(['A', 'B']);
|
||||
expect(s.seats.every((x) => x.chips === 1000)).toBe(true);
|
||||
});
|
||||
|
||||
test('베팅을 걸면 칩이 묶이고 모두 걸면 딜이 돼요', () => {
|
||||
let s = make();
|
||||
s = blackjack.apply(s, 'A', { type: 'bet', amount: 100 }, { rng: rng(2), now: 1 }).state;
|
||||
expect(s.seats.find((x) => x.id === 'A')!.chips).toBe(900);
|
||||
expect(s.phase).toBe('betting');
|
||||
s = blackjack.apply(s, 'B', { type: 'bet', amount: 50 }, { rng: rng(3), now: 2 }).state;
|
||||
expect(['insurance', 'playing', 'handEnd']).toContain(s.phase);
|
||||
expect(s.rounds['A']!.hands[0]!.cards).toHaveLength(2);
|
||||
expect(s.dealer).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('히트로 버스트하면 손패가 끝나요', () => {
|
||||
// Shoe (drawn from the front): A B dealerUp A B dealerHole, then A's hit card.
|
||||
const shoe: CardId[] = ['KS', 'KH', '5D', 'QC', '9S', '7H', 'QD', '2C'];
|
||||
let s = make({ insurance: false }, ['A', 'B'], shoe);
|
||||
s = blackjack.apply(s, 'A', { type: 'bet', amount: 100 }, { rng: rng(), now: 1 }).state;
|
||||
s = blackjack.apply(s, 'B', { type: 'bet', amount: 100 }, { rng: rng(), now: 2 }).state;
|
||||
expect(s.phase).toBe('playing');
|
||||
const aHand = s.rounds['A']!.hands[0]!;
|
||||
expect(aHand.cards).toEqual(['KS', 'QC']); // 20
|
||||
s = blackjack.apply(s, 'A', { type: 'hit' }, { rng: rng(), now: 3 }).state;
|
||||
expect(s.rounds['A']!.hands[0]!.status).toBe('bust'); // +QD = 30
|
||||
});
|
||||
|
||||
test('전체 흐름: 한 판을 끝까지', () => {
|
||||
let s = make({ insurance: false, handLimit: 5 });
|
||||
let now = 1;
|
||||
const step = (p: string, a: Parameters<typeof blackjack.apply>[2]) => {
|
||||
s = blackjack.apply(s, p, a, { rng: rng(now), now: now++ }).state;
|
||||
};
|
||||
step('A', { type: 'bet', amount: 100 });
|
||||
step('B', { type: 'bet', amount: 100 });
|
||||
// Play until the hand ends.
|
||||
let guard = 0;
|
||||
while (s.phase === 'playing' && guard++ < 50) {
|
||||
const who = s.turn!;
|
||||
step(who, { type: 'stand' });
|
||||
}
|
||||
expect(s.phase).toBe('handEnd');
|
||||
expect(s.dealerDown).toBe(false);
|
||||
for (const seat of s.seats) expect(seat.chips).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- random playouts
|
||||
|
||||
describe('random playouts (invariants)', () => {
|
||||
const OPTS: Partial<BlackjackOptions>[] = [
|
||||
{},
|
||||
{ insurance: false, charlie: 'five' },
|
||||
{ dealerSoft17: 'hit', surrender: 'late', sevenTriple: true, decks: 1 },
|
||||
{ blackjackPayout: '6:5', splitMaxHands: 4, hitSplitAces: true, resplitAces: true, endCondition: 'lastStanding' },
|
||||
{ doubleRule: '9to11', doubleAfterSplit: false, minBet: 50, startingChips: 500, decks: 2 },
|
||||
];
|
||||
const seeds = playoutSeeds(120);
|
||||
for (const opts of OPTS) {
|
||||
test(`옵션 ${JSON.stringify(opts)}`, () => {
|
||||
for (let i = 1; i <= seeds; i++) {
|
||||
const players = ['A', 'B', 'C'].slice(0, 2 + (i % 2));
|
||||
const report = randomPlayout(blackjack, {
|
||||
players,
|
||||
options: blackjack.optionsSchema.parse(opts),
|
||||
seed: seedN(i),
|
||||
maxSteps: 4000,
|
||||
invariant: (st) => {
|
||||
if (!chipsNonNegative(st as BlackjackState)) throw new Error('chips went negative');
|
||||
},
|
||||
});
|
||||
expect(report.finished).toBe(true);
|
||||
const res = blackjack.result(report.finalState as BlackjackState)!;
|
||||
expect(res.ranking.flat().sort()).toEqual([...players].sort());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- deck
|
||||
|
||||
test('buildShoe는 덱당 52장, 중복 없는 id', () => {
|
||||
const shoe = buildShoe(2);
|
||||
expect(shoe).toHaveLength(104);
|
||||
expect(new Set(shoe).size).toBe(104);
|
||||
});
|
||||
55
packages/games/src/blackjack/bot.test.ts
Normal file
55
packages/games/src/blackjack/bot.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN, type CardId } from '@bg/engine';
|
||||
import { blackjack, setupBlackjack, type BlackjackAction, type BlackjackState } from './index';
|
||||
import { blackjackBot } from './bot';
|
||||
|
||||
const rng = (seed = 1) => SeededRng.fromSeed(seedN(seed));
|
||||
|
||||
/** Run a hand to the point the given bot seat must first act, then ask the bot. */
|
||||
function decideFor(shoe: CardId[], seat = 'A', level?: number): { s: BlackjackState; action: BlackjackAction } {
|
||||
const options = blackjack.optionsSchema.parse({ insurance: false });
|
||||
let s = setupBlackjack({ players: ['A', 'B'], options, rng: rng(), now: 0 }, { shoe });
|
||||
let now = 1;
|
||||
// Both bet the minimum.
|
||||
for (const p of ['A', 'B']) s = blackjack.apply(s, p, { type: 'bet', amount: 10 }, { rng: rng(now), now: now++ }).state;
|
||||
// Advance to the requested seat's turn.
|
||||
let guard = 0;
|
||||
while (s.phase === 'playing' && s.turn !== seat && guard++ < 20) {
|
||||
s = blackjack.apply(s, s.turn!, { type: 'stand' }, { rng: rng(now), now: now++ }).state;
|
||||
}
|
||||
const legal = blackjack.legalActions!(s, seat);
|
||||
const action = blackjackBot({ me: seat, view: blackjack.view(s, seat), legal, random: () => 0.99, level });
|
||||
return { s, action };
|
||||
}
|
||||
|
||||
describe('blackjackBot basic strategy', () => {
|
||||
test('하드 16 vs 딜러 10 → 히트(스탠드 아님)', () => {
|
||||
// A: KS + 6D = 16, dealer up 10 (TH), hole irrelevant, B: 9C 9S.
|
||||
const shoe: CardId[] = ['KS', '9C', 'TH', '6D', '9S', '2H', '5C', '5D', '5H'];
|
||||
const { action } = decideFor(shoe, 'A', 60);
|
||||
expect(action.type).toBe('hit');
|
||||
});
|
||||
|
||||
test('하드 20 vs 딜러 10 → 스탠드', () => {
|
||||
const shoe: CardId[] = ['KS', '9C', 'TH', 'QD', '9S', '2H', '5C'];
|
||||
const { action } = decideFor(shoe, 'A', 60);
|
||||
expect(action.type).toBe('stand');
|
||||
});
|
||||
|
||||
test('딜러 A일 때 어려움 컴퓨터는 인슈어런스를 거절', () => {
|
||||
const options = blackjack.optionsSchema.parse({});
|
||||
let s = setupBlackjack({ players: ['A', 'B'], options, rng: rng(), now: 0 }, { shoe: ['KS', '9C', 'AH', '6D', '9S', 'KD', '2C', '3C'] });
|
||||
let now = 1;
|
||||
for (const p of ['A', 'B']) s = blackjack.apply(s, p, { type: 'bet', amount: 10 }, { rng: rng(now), now: now++ }).state;
|
||||
expect(s.phase).toBe('insurance');
|
||||
const action = blackjackBot({ me: 'A', view: blackjack.view(s, 'A'), legal: blackjack.legalActions!(s, 'A'), random: () => 0.5, level: 55 });
|
||||
expect(action).toEqual({ type: 'insurance', take: false });
|
||||
});
|
||||
|
||||
test('베팅 단계에서는 베팅 액션을 내요', () => {
|
||||
const options = blackjack.optionsSchema.parse({});
|
||||
const s = setupBlackjack({ players: ['A', 'B'], options, rng: rng(), now: 0 });
|
||||
const action = blackjackBot({ me: 'A', view: blackjack.view(s, 'A'), legal: blackjack.legalActions!(s, 'A'), random: () => 0.1, level: 10 });
|
||||
expect(action.type).toBe('bet');
|
||||
});
|
||||
});
|
||||
113
packages/games/src/blackjack/bot.ts
Normal file
113
packages/games/src/blackjack/bot.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* 블랙잭 computer player: plays basic strategy (S17 chart), scaled by level. 어려움 computers follow the chart and
|
||||
* never take insurance; 쉬움 computers often just "mimic the dealer" (hit under 17, stand otherwise), skip doubles
|
||||
* and splits, and sometimes take insurance. Bets flat at the minimum, with stronger computers occasionally raising.
|
||||
*/
|
||||
import type { BotLevel } from '../bots/persona';
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import { pick } from '../bots/policy';
|
||||
import { cardPoints } from './rules';
|
||||
import type { BlackjackAction, BlackjackView, HandView } from './types';
|
||||
|
||||
type Move = 'hit' | 'stand' | 'double' | 'split' | 'surrender';
|
||||
|
||||
const easy = (l?: BotLevel) => l !== undefined && l <= 20;
|
||||
const hard = (l?: BotLevel) => l === undefined || l > 40;
|
||||
|
||||
/** Basic strategy move for the active hand against the dealer upcard (dealer value 2..11, A = 11). */
|
||||
function basicMove(h: HandView, up: number, pair: boolean): Move {
|
||||
const t = h.total;
|
||||
if (pair) {
|
||||
const r = cardPoints(h.cards[0]!); // 2..11 (A = 11, tens = 10)
|
||||
if (r === 11) return 'split'; // A,A
|
||||
if (r === 10) return 'stand';
|
||||
if (r === 9) return up === 7 || up >= 10 ? 'stand' : 'split';
|
||||
if (r === 8) return 'split';
|
||||
if (r === 7) return up <= 7 ? 'split' : 'hit';
|
||||
if (r === 6) return up <= 6 ? 'split' : 'hit';
|
||||
if (r === 5) return up <= 9 ? 'double' : 'hit'; // play as a hard 10
|
||||
if (r === 4) return 'hit';
|
||||
if (r === 3 || r === 2) return up <= 7 ? 'split' : 'hit';
|
||||
}
|
||||
if (h.soft) {
|
||||
// soft total: an ace counts as 11.
|
||||
if (t >= 19) return 'stand';
|
||||
if (t === 18) return up <= 6 ? 'double' : up <= 8 ? 'stand' : 'hit';
|
||||
if (t === 17) return up >= 3 && up <= 6 ? 'double' : 'hit';
|
||||
if (t === 16 || t === 15) return up >= 4 && up <= 6 ? 'double' : 'hit';
|
||||
return up >= 5 && up <= 6 ? 'double' : 'hit'; // soft 13,14
|
||||
}
|
||||
// hard total
|
||||
if (t >= 17) return 'stand';
|
||||
if (t >= 13) return up <= 6 ? 'stand' : 'hit';
|
||||
if (t === 12) return up >= 4 && up <= 6 ? 'stand' : 'hit';
|
||||
if (t === 11) return up <= 10 ? 'double' : 'hit';
|
||||
if (t === 10) return up <= 9 ? 'double' : 'hit';
|
||||
if (t === 9) return up >= 3 && up <= 6 ? 'double' : 'hit';
|
||||
return 'hit';
|
||||
}
|
||||
|
||||
/** Late surrender: hard 16 vs 9/10/A, hard 15 vs 10. */
|
||||
function wantsSurrender(h: HandView, up: number): boolean {
|
||||
if (h.soft) return false;
|
||||
if (h.total === 16) return up === 9 || up >= 10 || up === 11;
|
||||
if (h.total === 15) return up === 10;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** When the chart says double but it isn't allowed, fall back to hit (low/soft) or stand. */
|
||||
function withoutDouble(h: HandView): Move {
|
||||
return h.soft || h.total <= 11 ? 'hit' : 'stand';
|
||||
}
|
||||
|
||||
export const blackjackBot: BotStrategy<BlackjackView, BlackjackAction> = ({ view, legal, random, level }) => {
|
||||
const types = new Set(legal.map((a) => a.type));
|
||||
|
||||
// Betting: minimum by default; strong computers sometimes bet a step higher.
|
||||
if (types.has('bet')) {
|
||||
const bets = legal.filter((a): a is { type: 'bet'; amount: number } => a.type === 'bet').sort((a, b) => a.amount - b.amount);
|
||||
if (hard(level) && bets.length > 1 && random() < 0.35) return bets[1]!;
|
||||
return bets[0]!;
|
||||
}
|
||||
|
||||
// Insurance: basic strategy never insures; weak computers sometimes do.
|
||||
if (types.has('insurance')) {
|
||||
const take = legal.find((a) => a.type === 'insurance' && a.take);
|
||||
if (take && easy(level) && random() < 0.3) return take;
|
||||
return { type: 'insurance', take: false };
|
||||
}
|
||||
|
||||
if (types.has('ready')) return { type: 'ready' };
|
||||
|
||||
// Playing: decide for the active hand.
|
||||
const my = view.my;
|
||||
const seat = view.seats.find((x) => x.id === view.me);
|
||||
const h = seat?.hands?.[seat.active];
|
||||
if (!my || !h) return pick(legal, random);
|
||||
const up = view.dealer.cards[0] ? cardPoints(view.dealer.cards[0]) : 10;
|
||||
const pair = h.cards.length === 2 && cardPoints(h.cards[0]!) === cardPoints(h.cards[1]!);
|
||||
|
||||
// Surrender first (only when available and the chart calls for it).
|
||||
if (my.canSurrender && !easy(level) && wantsSurrender(h, up)) return { type: 'surrender' };
|
||||
|
||||
let move = basicMove(h, up, pair);
|
||||
|
||||
// 쉬움 computers often just mimic the dealer and avoid fancy plays.
|
||||
if (easy(level) && random() < 0.5) {
|
||||
move = h.soft ? (h.total <= 17 ? 'hit' : 'stand') : h.total < 17 ? 'hit' : 'stand';
|
||||
} else if (!hard(level) && random() < 0.12) {
|
||||
// 보통 computers lapse occasionally.
|
||||
move = move === 'double' ? withoutDouble(h) : move;
|
||||
}
|
||||
|
||||
// Map the desired move onto a legal action, with sensible fallbacks.
|
||||
if (move === 'split' && my.canSplit) return { type: 'split' };
|
||||
if (move === 'double') {
|
||||
if (my.canDouble) return { type: 'double' };
|
||||
move = withoutDouble(h);
|
||||
}
|
||||
if (move === 'split') move = h.total <= 11 || h.soft ? 'hit' : h.total >= 17 ? 'stand' : up <= 6 ? 'stand' : 'hit';
|
||||
if (move === 'surrender') move = 'hit';
|
||||
if (move === 'hit' && my.canHit) return { type: 'hit' };
|
||||
return { type: 'stand' };
|
||||
};
|
||||
772
packages/games/src/blackjack/index.ts
Normal file
772
packages/games/src/blackjack/index.ts
Normal file
@@ -0,0 +1,772 @@
|
||||
/** 블랙잭 (docs/games/blackjack.md). Pure and deterministic; state is JSON. Players vs. the house with 놀이용 chips. */
|
||||
import {
|
||||
fail,
|
||||
ok,
|
||||
type CardId,
|
||||
type GameDefinition,
|
||||
type GameEvent,
|
||||
type GameResult,
|
||||
type PlayerId,
|
||||
type Rng,
|
||||
type Validation,
|
||||
} from '@bg/engine';
|
||||
import { blackjackOptionsSchema, type BlackjackOptions } from './options';
|
||||
import {
|
||||
blackjackActionSchema,
|
||||
type BlackjackAction,
|
||||
type BlackjackState,
|
||||
type BlackjackView,
|
||||
type Hand,
|
||||
type LogEntry,
|
||||
type PlayerResult,
|
||||
type Round,
|
||||
type Seat,
|
||||
type SeatView,
|
||||
} from './types';
|
||||
import {
|
||||
buildShoe,
|
||||
canDouble,
|
||||
canSplit,
|
||||
canSurrender,
|
||||
charlieCount,
|
||||
dealerPeeks,
|
||||
dealerShouldHit,
|
||||
handValue,
|
||||
isAce,
|
||||
isNaturalBlackjack,
|
||||
isPair,
|
||||
settleHand,
|
||||
} from './rules';
|
||||
|
||||
export * from './rules';
|
||||
export * from './types';
|
||||
|
||||
const LOG_MAX = 60;
|
||||
const RECENT = 12;
|
||||
const AWAY_AFTER = 2;
|
||||
|
||||
interface Ctx {
|
||||
rng: Rng;
|
||||
now: number;
|
||||
events: GameEvent[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
/** Distributive omit so each log variant keeps its own fields. */
|
||||
type LogInput = LogEntry extends infer T ? (T extends LogEntry ? Omit<T, 'seq'> : never) : never;
|
||||
|
||||
function log(s: BlackjackState, e: LogInput): void {
|
||||
s.log.push({ seq: s.seq, ...e } as LogEntry);
|
||||
if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX);
|
||||
}
|
||||
|
||||
const seatOf = (s: BlackjackState, p: PlayerId): Seat | undefined => s.seats.find((x) => x.id === p);
|
||||
const betUnit = (o: BlackjackOptions): number => o.minBet;
|
||||
|
||||
/** Max bet a player may place: a whole number of units up to their chips (and a sane table cap). */
|
||||
function maxBet(chips: number, o: BlackjackOptions): number {
|
||||
const unit = betUnit(o);
|
||||
const cap = Math.floor(chips / unit) * unit;
|
||||
return Math.max(unit, Math.min(cap, o.startingChips * 4));
|
||||
}
|
||||
|
||||
function phaseMs(s: BlackjackState): number | null {
|
||||
const o = s.options;
|
||||
switch (s.phase) {
|
||||
case 'betting':
|
||||
case 'insurance':
|
||||
return o.betSeconds === null ? null : o.betSeconds * 1000;
|
||||
case 'playing': {
|
||||
const seat = s.turn ? seatOf(s, s.turn) : undefined;
|
||||
if (seat && seat.timeoutsInRow >= AWAY_AFTER) return o.awaySeconds * 1000;
|
||||
return o.turnSeconds === null ? null : o.turnSeconds * 1000;
|
||||
}
|
||||
case 'handEnd':
|
||||
return o.handEndSeconds * 1000;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function setClock(s: BlackjackState, now: number): void {
|
||||
s.turnStartedAt = now;
|
||||
const ms = phaseMs(s);
|
||||
s.deadlineMs = ms ?? 0;
|
||||
s.deadlineAt = ms === null ? null : now + ms;
|
||||
}
|
||||
|
||||
/** Draw one card from the shoe (reshuffling a fresh shoe if it ever runs dry mid-hand). */
|
||||
function draw(s: BlackjackState, ctx: Ctx): CardId {
|
||||
if (s.shoe.length === 0) {
|
||||
s.shoeGen++;
|
||||
s.shoe = ctx.rng.shuffle(buildShoe(s.options.decks, s.shoeGen));
|
||||
s.used = 0;
|
||||
}
|
||||
const c = s.shoe.shift()!;
|
||||
s.used++;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Marks a hand finished when it busts, hits a Charlie, reaches 21, or is a frozen split ace. */
|
||||
function finalize(h: Hand, o: BlackjackOptions): void {
|
||||
if (h.status !== 'playing') return;
|
||||
const { total } = handValue(h.cards);
|
||||
if (total > 21) {
|
||||
h.status = 'bust';
|
||||
return;
|
||||
}
|
||||
const cc = charlieCount(o);
|
||||
if (cc !== null && h.cards.length >= cc) {
|
||||
h.status = 'charlie';
|
||||
return;
|
||||
}
|
||||
if (total === 21 || h.frozenAces) h.status = 'stand';
|
||||
}
|
||||
|
||||
const participants = (s: BlackjackState): PlayerId[] => s.order.filter((p) => s.rounds[p]?.inHand);
|
||||
|
||||
// ---------------------------------------------------------------- hand lifecycle
|
||||
|
||||
/** Opens the betting phase for a new hand, or ends the game when nobody can play. */
|
||||
function startHand(s: BlackjackState, ctx: Ctx): void {
|
||||
const o = s.options;
|
||||
// Anyone who can't cover the minimum bet is out for good.
|
||||
for (const seat of s.seats) if (seat.status === 'playing' && seat.chips < betUnit(o)) seat.status = 'out';
|
||||
const able = s.seats.filter((seat) => seat.status === 'playing');
|
||||
if (able.length === 0) return finishGame(s, ctx, false);
|
||||
// Reshuffle between hands when the shoe is low (~25% penetration). The first hand uses the shoe from setup.
|
||||
if (s.handsPlayed > 0 && s.shoe.length < s.options.decks * 52 * 0.25) {
|
||||
s.shoeGen++;
|
||||
s.shoe = ctx.rng.shuffle(buildShoe(o.decks, s.shoeGen));
|
||||
s.used = 0;
|
||||
}
|
||||
s.order = able.map((seat) => seat.id);
|
||||
s.rounds = {};
|
||||
for (const seat of able) {
|
||||
seat.chipsAtHandStart = seat.chips;
|
||||
s.rounds[seat.id] = {
|
||||
bet: 0,
|
||||
betLocked: false,
|
||||
hands: [],
|
||||
active: 0,
|
||||
insurance: 0,
|
||||
insuranceAnswered: false,
|
||||
ready: false,
|
||||
inHand: true,
|
||||
};
|
||||
}
|
||||
s.dealer = [];
|
||||
s.dealerDown = true;
|
||||
s.dealerBlackjack = false;
|
||||
s.turn = null;
|
||||
s.phase = 'betting';
|
||||
setClock(s, ctx.now);
|
||||
}
|
||||
|
||||
function allBetsIn(s: BlackjackState): boolean {
|
||||
return participants(s).every((p) => s.rounds[p]!.betLocked);
|
||||
}
|
||||
|
||||
/** Deals the opening cards and moves to insurance / playing / immediate settle. */
|
||||
function deal(s: BlackjackState, ctx: Ctx): void {
|
||||
const o = s.options;
|
||||
const order = participants(s);
|
||||
for (const p of order) s.rounds[p]!.hands = [{ cards: [], bet: s.rounds[p]!.bet, status: 'playing', fromSplit: false, frozenAces: false, doubled: false, outcome: null, net: 0 }];
|
||||
for (const p of order) s.rounds[p]!.hands[0]!.cards.push(draw(s, ctx));
|
||||
s.dealer.push(draw(s, ctx));
|
||||
for (const p of order) s.rounds[p]!.hands[0]!.cards.push(draw(s, ctx));
|
||||
s.dealer.push(draw(s, ctx));
|
||||
s.dealerDown = true;
|
||||
s.dealerBlackjack = handValue(s.dealer).total === 21;
|
||||
log(s, { t: 'deal' });
|
||||
ctx.events.push({ type: 'dealt' });
|
||||
// Naturals are set now; they still compare to the dealer's natural.
|
||||
for (const p of order) {
|
||||
const h = s.rounds[p]!.hands[0]!;
|
||||
if (isNaturalBlackjack(h)) h.status = 'blackjack';
|
||||
}
|
||||
const up = s.dealer[0]!;
|
||||
if (o.insurance && isAce(up)) {
|
||||
s.phase = 'insurance';
|
||||
setClock(s, ctx.now);
|
||||
return;
|
||||
}
|
||||
if (dealerPeeks(up) && s.dealerBlackjack) return settleAndEnd(s, ctx);
|
||||
startPlaying(s, ctx);
|
||||
}
|
||||
|
||||
function resolveInsurance(s: BlackjackState, ctx: Ctx): void {
|
||||
// Pay/collect insurance now that everyone has answered.
|
||||
if (s.dealerBlackjack) return settleAndEnd(s, ctx);
|
||||
startPlaying(s, ctx);
|
||||
}
|
||||
|
||||
function startPlaying(s: BlackjackState, ctx: Ctx): void {
|
||||
s.phase = 'playing';
|
||||
s.turn = null;
|
||||
advance(s, ctx);
|
||||
}
|
||||
|
||||
/** Finds the next hand that needs a decision, or runs the dealer when every player is done. */
|
||||
function advance(s: BlackjackState, ctx: Ctx): void {
|
||||
const order = participants(s);
|
||||
// Continue from the current player, then move on.
|
||||
let startIdx = s.turn ? order.indexOf(s.turn) : 0;
|
||||
if (startIdx < 0) startIdx = 0;
|
||||
for (let k = 0; k < order.length; k++) {
|
||||
const p = order[(startIdx + k) % order.length]!;
|
||||
const r = s.rounds[p]!;
|
||||
const from = p === s.turn ? r.active : 0;
|
||||
for (let i = from; i < r.hands.length; i++) {
|
||||
if (r.hands[i]!.status === 'playing') {
|
||||
r.active = i;
|
||||
s.turn = p;
|
||||
setClock(s, ctx.now);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Everybody is done: the dealer plays.
|
||||
s.turn = null;
|
||||
playDealer(s, ctx);
|
||||
}
|
||||
|
||||
function playDealer(s: BlackjackState, ctx: Ctx): void {
|
||||
s.dealerDown = false;
|
||||
ctx.events.push({ type: 'reveal' });
|
||||
const live = participants(s).some((p) => s.rounds[p]!.hands.some((h) => h.status === 'stand'));
|
||||
if (live && !s.dealerBlackjack) {
|
||||
while (dealerShouldHit(s.dealer, s.options)) {
|
||||
const c = draw(s, ctx);
|
||||
s.dealer.push(c);
|
||||
log(s, { t: 'dealer', card: c, total: handValue(s.dealer).total });
|
||||
ctx.events.push({ type: 'dealerCard', card: c });
|
||||
}
|
||||
if (handValue(s.dealer).total > 21) log(s, { t: 'dealerBust', total: handValue(s.dealer).total });
|
||||
}
|
||||
settleAndEnd(s, ctx);
|
||||
}
|
||||
|
||||
/** Settles every hand (and insurance) against the dealer and enters the result phase. */
|
||||
function settleAndEnd(s: BlackjackState, ctx: Ctx): void {
|
||||
s.dealerDown = false;
|
||||
const o = s.options;
|
||||
for (const p of participants(s)) {
|
||||
const seat = seatOf(s, p)!;
|
||||
const r = s.rounds[p]!;
|
||||
for (const h of r.hands) {
|
||||
const { outcome, net } = settleHand(h, s.dealer, s.dealerBlackjack, o);
|
||||
h.outcome = outcome;
|
||||
h.net = net;
|
||||
seat.chips += h.bet + net; // return the stake plus/minus the result
|
||||
}
|
||||
if (r.insurance > 0) seat.chips += s.dealerBlackjack ? r.insurance * 3 : 0;
|
||||
const net = seat.chips - seat.chipsAtHandStart;
|
||||
log(s, { t: 'result', p, net });
|
||||
r.ready = false;
|
||||
}
|
||||
ctx.events.push({ type: 'result' });
|
||||
s.phase = 'handEnd';
|
||||
setClock(s, ctx.now);
|
||||
}
|
||||
|
||||
function closeHand(s: BlackjackState, ctx: Ctx): void {
|
||||
s.handsPlayed++;
|
||||
const o = s.options;
|
||||
for (const seat of s.seats) if (seat.status === 'playing' && seat.chips < betUnit(o)) seat.status = 'out';
|
||||
const able = s.seats.filter((seat) => seat.status === 'playing');
|
||||
const handsDone = o.endCondition === 'hands' && s.handsPlayed >= o.handLimit;
|
||||
const lastStanding = o.endCondition === 'lastStanding' && able.length <= 1;
|
||||
if (handsDone || lastStanding || able.length === 0) return finishGame(s, ctx, false);
|
||||
startHand(s, ctx);
|
||||
}
|
||||
|
||||
function finishGame(s: BlackjackState, ctx: Ctx, abandoned: boolean): void {
|
||||
const ranked = [...s.seats].sort((a, b) => b.chips - a.chips);
|
||||
const ranking: PlayerResult[] = [];
|
||||
let rank = 0;
|
||||
let prev: number | null = null;
|
||||
ranked.forEach((seat, i) => {
|
||||
if (prev === null || seat.chips !== prev) rank = i + 1;
|
||||
prev = seat.chips;
|
||||
ranking.push({ player: seat.id, rank, chips: seat.chips, left: seat.status === 'left' });
|
||||
});
|
||||
const topChips = ranked[0]?.chips ?? 0;
|
||||
const winner = ranked.filter((seat) => seat.chips === topChips && seat.status !== 'left').map((seat) => seat.id);
|
||||
const summary = abandoned
|
||||
? '다른 사람이 모두 나가서 게임이 끝났어요'
|
||||
: winner.length === 1
|
||||
? `${s.handsPlayed}판을 치고 칩이 가장 많은 사람이 이겼어요! ${topChips.toLocaleString('ko-KR')} 칩`
|
||||
: `${s.handsPlayed}판을 쳤어요. 칩이 같은 ${winner.length}명이 공동 1등!`;
|
||||
s.result = { ranking, winner, summary, abandoned };
|
||||
s.phase = 'finished';
|
||||
s.turn = null;
|
||||
s.deadlineAt = null;
|
||||
ctx.events.push({ type: 'gameEnd', winner });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- player actions
|
||||
|
||||
function lockBet(s: BlackjackState, ctx: Ctx, p: PlayerId, amount: number): void {
|
||||
const seat = seatOf(s, p)!;
|
||||
const r = s.rounds[p]!;
|
||||
const amt = Math.max(betUnit(s.options), Math.min(amount, maxBet(seat.chips, s.options)));
|
||||
r.bet = amt;
|
||||
r.betLocked = true;
|
||||
seat.chips -= amt;
|
||||
log(s, { t: 'bet', p, amount: amt });
|
||||
if (allBetsIn(s)) deal(s, ctx);
|
||||
else setClock(s, ctx.now);
|
||||
}
|
||||
|
||||
function answerInsurance(s: BlackjackState, ctx: Ctx, p: PlayerId, take: boolean): void {
|
||||
const seat = seatOf(s, p)!;
|
||||
const r = s.rounds[p]!;
|
||||
r.insuranceAnswered = true;
|
||||
if (take) {
|
||||
const amt = Math.min(Math.floor(r.bet / 2), Math.floor(seat.chips / 1));
|
||||
r.insurance = amt;
|
||||
seat.chips -= amt;
|
||||
log(s, { t: 'insurance', p, amount: amt });
|
||||
}
|
||||
if (participants(s).every((q) => s.rounds[q]!.insuranceAnswered)) resolveInsurance(s, ctx);
|
||||
else setClock(s, ctx.now);
|
||||
}
|
||||
|
||||
function dealTo(s: BlackjackState, ctx: Ctx, h: Hand): CardId {
|
||||
const c = draw(s, ctx);
|
||||
h.cards.push(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
function doHit(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const r = s.rounds[p]!;
|
||||
const h = r.hands[r.active]!;
|
||||
const c = dealTo(s, ctx, h);
|
||||
finalize(h, s.options);
|
||||
const total = handValue(h.cards).total;
|
||||
if (h.status === 'bust') log(s, { t: 'bust', p, total });
|
||||
else if (h.status === 'charlie') log(s, { t: 'charlie', p, cards: h.cards.length });
|
||||
else log(s, { t: 'hit', p, card: c, total });
|
||||
ctx.events.push({ type: 'playerCard', player: p, card: c });
|
||||
advance(s, ctx);
|
||||
}
|
||||
|
||||
function doStand(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const r = s.rounds[p]!;
|
||||
const h = r.hands[r.active]!;
|
||||
h.status = 'stand';
|
||||
log(s, { t: 'stand', p, total: handValue(h.cards).total });
|
||||
advance(s, ctx);
|
||||
}
|
||||
|
||||
function doDouble(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const seat = seatOf(s, p)!;
|
||||
const r = s.rounds[p]!;
|
||||
const h = r.hands[r.active]!;
|
||||
seat.chips -= h.bet;
|
||||
h.bet *= 2;
|
||||
h.doubled = true;
|
||||
const c = dealTo(s, ctx, h);
|
||||
h.status = handValue(h.cards).total > 21 ? 'bust' : 'stand';
|
||||
log(s, { t: 'double', p, card: c, total: handValue(h.cards).total });
|
||||
ctx.events.push({ type: 'playerCard', player: p, card: c });
|
||||
advance(s, ctx);
|
||||
}
|
||||
|
||||
function doSplit(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const seat = seatOf(s, p)!;
|
||||
const o = s.options;
|
||||
const r = s.rounds[p]!;
|
||||
const i = r.active;
|
||||
const h = r.hands[i]!;
|
||||
const [a, b] = h.cards as [CardId, CardId];
|
||||
const aces = isAce(a);
|
||||
seat.chips -= h.bet;
|
||||
const h2: Hand = { cards: [b], bet: h.bet, status: 'playing', fromSplit: true, frozenAces: false, doubled: false, outcome: null, net: 0 };
|
||||
h.cards = [a];
|
||||
h.fromSplit = true;
|
||||
r.hands.splice(i + 1, 0, h2);
|
||||
log(s, { t: 'split', p });
|
||||
ctx.events.push({ type: 'split', player: p });
|
||||
for (const hh of [h, h2]) {
|
||||
dealTo(s, ctx, hh);
|
||||
if (aces) {
|
||||
const gotAce = isAce(hh.cards[1]!);
|
||||
hh.frozenAces = !(o.hitSplitAces || (o.resplitAces && gotAce && r.hands.length < o.splitMaxHands));
|
||||
}
|
||||
finalize(hh, o);
|
||||
}
|
||||
r.active = i;
|
||||
advance(s, ctx);
|
||||
}
|
||||
|
||||
function doSurrender(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const r = s.rounds[p]!;
|
||||
const h = r.hands[r.active]!;
|
||||
h.status = 'surrender';
|
||||
log(s, { t: 'surrender', p });
|
||||
advance(s, ctx);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- system actions
|
||||
|
||||
function autoPlay(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
// Timeout / away default: stand (never bust yourself).
|
||||
doStand(s, ctx, p);
|
||||
}
|
||||
|
||||
function applyTimeout(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const seat = seatOf(s, p);
|
||||
if (seat) seat.timeoutsInRow++;
|
||||
switch (s.phase) {
|
||||
case 'betting':
|
||||
return lockBet(s, ctx, p, betUnit(s.options));
|
||||
case 'insurance':
|
||||
return answerInsurance(s, ctx, p, false);
|
||||
case 'playing':
|
||||
return autoPlay(s, ctx, p);
|
||||
case 'handEnd':
|
||||
return markReady(s, ctx, p);
|
||||
}
|
||||
}
|
||||
|
||||
function markReady(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const r = s.rounds[p];
|
||||
if (r) r.ready = true;
|
||||
if (participants(s).every((q) => s.rounds[q]!.ready || seatOf(s, q)!.status === 'left')) closeHand(s, ctx);
|
||||
}
|
||||
|
||||
function applyLeave(s: BlackjackState, ctx: Ctx, p: PlayerId): void {
|
||||
const seat = seatOf(s, p);
|
||||
if (!seat || seat.status === 'left') return;
|
||||
seat.status = 'left';
|
||||
const r = s.rounds[p];
|
||||
// Resolve whatever this player was holding up.
|
||||
if (r?.inHand) {
|
||||
if (s.phase === 'betting' && !r.betLocked) lockBet(s, ctx, p, betUnit(s.options));
|
||||
else if (s.phase === 'insurance' && !r.insuranceAnswered) answerInsurance(s, ctx, p, false);
|
||||
else if (s.phase === 'playing' && s.turn === p) {
|
||||
for (const h of r.hands) if (h.status === 'playing') h.status = 'stand';
|
||||
advance(s, ctx);
|
||||
} else if (s.phase === 'handEnd' && !r.ready) markReady(s, ctx, p);
|
||||
}
|
||||
// End if only one (or no) player is still present.
|
||||
const present = s.seats.filter((x) => x.status === 'playing');
|
||||
if (s.phase !== 'finished' && present.length <= 1 && (s.phase === 'handEnd' || s.phase === 'betting')) {
|
||||
if (present.length === 0) finishGame(s, ctx, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- validate
|
||||
|
||||
function validate(s: BlackjackState, actor: PlayerId, a: BlackjackAction): Validation {
|
||||
const seat = seatOf(s, actor);
|
||||
if (!seat) return fail('이 게임의 플레이어가 아니에요.');
|
||||
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
|
||||
if (a.type === 'leave') return seat.status === 'left' ? fail('이미 나갔어요.') : ok;
|
||||
if (a.type === 'timeout') return activePlayers(s).includes(actor) ? ok : fail('지금은 시간 초과를 적용할 수 없어요.');
|
||||
const r = s.rounds[actor];
|
||||
if (!r?.inHand) return fail('이번 판에 참가하지 않았어요.');
|
||||
switch (a.type) {
|
||||
case 'bet': {
|
||||
if (s.phase !== 'betting') return fail('지금은 베팅할 때가 아니에요.');
|
||||
if (r.betLocked) return fail('이미 베팅했어요.');
|
||||
const unit = betUnit(s.options);
|
||||
const hi = maxBet(seat.chips, s.options);
|
||||
if (a.amount < unit || a.amount > hi) return fail(`${unit.toLocaleString('ko-KR')}~${hi.toLocaleString('ko-KR')} 칩 사이로 걸어 주세요.`);
|
||||
if (a.amount % unit !== 0) return fail(`${unit.toLocaleString('ko-KR')} 칩 단위로 걸어 주세요.`);
|
||||
return ok;
|
||||
}
|
||||
case 'insurance': {
|
||||
if (s.phase !== 'insurance') return fail('지금은 인슈어런스를 고를 때가 아니에요.');
|
||||
if (r.insuranceAnswered) return fail('이미 골랐어요.');
|
||||
if (a.take && seat.chips < Math.floor(r.bet / 2)) return fail('인슈어런스를 걸 칩이 부족해요.');
|
||||
return ok;
|
||||
}
|
||||
case 'hit':
|
||||
case 'stand':
|
||||
case 'double':
|
||||
case 'split':
|
||||
case 'surrender': {
|
||||
if (s.phase !== 'playing' || s.turn !== actor) return fail('지금은 내 차례가 아니에요.');
|
||||
const h = r.hands[r.active];
|
||||
if (!h || h.status !== 'playing') return fail('지금은 행동할 수 없어요.');
|
||||
if (a.type === 'double' && !canDouble(h, seat.chips, s.options)) return fail('지금은 더블다운할 수 없어요.');
|
||||
if (a.type === 'split' && !canSplit(h, r.hands.length, seat.chips, s.options)) return fail('지금은 스플릿할 수 없어요.');
|
||||
if (a.type === 'surrender' && !canSurrender(h, r.hands.length, s.options)) return fail('지금은 서렌더할 수 없어요.');
|
||||
return ok;
|
||||
}
|
||||
case 'ready':
|
||||
if (s.phase !== 'handEnd') return fail('아직 판이 끝나지 않았어요.');
|
||||
return r.ready ? fail('이미 준비했어요.') : ok;
|
||||
default:
|
||||
return fail('알 수 없는 행동이에요.');
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- apply
|
||||
|
||||
function apply(prev: BlackjackState, actor: PlayerId, a: BlackjackAction, { rng, now }: { rng: Rng; now: number }) {
|
||||
const s = structuredClone(prev);
|
||||
const ctx: Ctx = { rng, now, events: [] };
|
||||
s.seq += 1;
|
||||
const seat = seatOf(s, actor);
|
||||
if (seat && a.type !== 'timeout' && a.type !== 'leave') seat.timeoutsInRow = 0;
|
||||
switch (a.type) {
|
||||
case 'timeout':
|
||||
applyTimeout(s, ctx, actor);
|
||||
break;
|
||||
case 'leave':
|
||||
applyLeave(s, ctx, actor);
|
||||
break;
|
||||
case 'bet':
|
||||
lockBet(s, ctx, actor, a.amount);
|
||||
break;
|
||||
case 'insurance':
|
||||
answerInsurance(s, ctx, actor, a.take);
|
||||
break;
|
||||
case 'hit':
|
||||
doHit(s, ctx, actor);
|
||||
break;
|
||||
case 'stand':
|
||||
doStand(s, ctx, actor);
|
||||
break;
|
||||
case 'double':
|
||||
doDouble(s, ctx, actor);
|
||||
break;
|
||||
case 'split':
|
||||
doSplit(s, ctx, actor);
|
||||
break;
|
||||
case 'surrender':
|
||||
doSurrender(s, ctx, actor);
|
||||
break;
|
||||
case 'ready':
|
||||
markReady(s, ctx, actor);
|
||||
break;
|
||||
}
|
||||
return { state: s, events: ctx.events };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
function handView(h: Hand) {
|
||||
const { total, soft } = handValue(h.cards);
|
||||
return { cards: [...h.cards], total, soft, status: h.status, bet: h.bet, doubled: h.doubled, outcome: h.outcome, net: h.net };
|
||||
}
|
||||
|
||||
function seatView(s: BlackjackState, seat: Seat): SeatView {
|
||||
const r = s.rounds[seat.id];
|
||||
const dealtIn = !!r?.inHand && r.hands.length > 0;
|
||||
const net = s.phase === 'handEnd' || s.phase === 'finished' ? seat.chips - seat.chipsAtHandStart : null;
|
||||
return {
|
||||
id: seat.id,
|
||||
chips: seat.chips,
|
||||
status: seat.status,
|
||||
hands: dealtIn ? r!.hands.map(handView) : null,
|
||||
active: r?.active ?? 0,
|
||||
insurance: r?.insurance ?? 0,
|
||||
bet: r?.bet ?? 0,
|
||||
betLocked: !!r?.betLocked,
|
||||
ready: !!r?.ready,
|
||||
isTurn: s.phase === 'playing' && s.turn === seat.id,
|
||||
net,
|
||||
};
|
||||
}
|
||||
|
||||
function myTurnInfo(s: BlackjackState, me: PlayerId): BlackjackView['my'] {
|
||||
if (s.phase !== 'playing' || s.turn !== me) return null;
|
||||
const seat = seatOf(s, me)!;
|
||||
const r = s.rounds[me]!;
|
||||
const h = r.hands[r.active];
|
||||
if (!h || h.status !== 'playing') return null;
|
||||
return {
|
||||
canHit: true,
|
||||
canStand: true,
|
||||
canDouble: canDouble(h, seat.chips, s.options),
|
||||
canSplit: canSplit(h, r.hands.length, seat.chips, s.options),
|
||||
canSurrender: canSurrender(h, r.hands.length, s.options),
|
||||
};
|
||||
}
|
||||
|
||||
function view(s: BlackjackState, viewer: PlayerId | null): BlackjackView {
|
||||
const me = viewer && seatOf(s, viewer) ? viewer : null;
|
||||
const o = s.options;
|
||||
const dealerCards: (CardId | null)[] = s.dealer.map((c, i) => (i === 1 && s.dealerDown ? null : c));
|
||||
const visible = s.dealerDown ? s.dealer.slice(0, 1) : s.dealer;
|
||||
const dv = handValue(visible);
|
||||
const r = me ? s.rounds[me] : undefined;
|
||||
const betRange = me && s.phase === 'betting' && r?.inHand && !r.betLocked ? { min: betUnit(o), max: maxBet(seatOf(s, me)!.chips, o), step: betUnit(o) } : null;
|
||||
const insuranceOpen = !!(me && s.phase === 'insurance' && r?.inHand && !r.insuranceAnswered);
|
||||
return {
|
||||
options: o,
|
||||
me,
|
||||
phase: s.phase,
|
||||
handsPlayed: s.handsPlayed,
|
||||
handLimit: o.endCondition === 'hands' ? o.handLimit : null,
|
||||
dealer: {
|
||||
cards: dealerCards,
|
||||
total: dv.total,
|
||||
soft: dv.soft,
|
||||
revealed: !s.dealerDown,
|
||||
blackjack: !s.dealerDown && s.dealerBlackjack,
|
||||
bust: !s.dealerDown && handValue(s.dealer).total > 21,
|
||||
},
|
||||
seats: s.seats.map((seat) => seatView(s, seat)),
|
||||
order: [...s.order],
|
||||
turn: s.phase === 'playing' ? s.turn : null,
|
||||
decksLeft: Math.max(1, Math.round(s.shoe.length / 52)),
|
||||
betRange,
|
||||
my: me ? myTurnInfo(s, me) : null,
|
||||
insuranceOpen,
|
||||
insuranceMax: me && r ? Math.floor(r.bet / 2) : 0,
|
||||
turnStartedAt: s.turnStartedAt,
|
||||
deadlineTotalMs: s.deadlineMs,
|
||||
recent: s.log.slice(-RECENT),
|
||||
result: s.result,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- queries for the server / tests
|
||||
|
||||
function activePlayers(s: BlackjackState): PlayerId[] {
|
||||
switch (s.phase) {
|
||||
case 'betting':
|
||||
return participants(s).filter((p) => !s.rounds[p]!.betLocked);
|
||||
case 'insurance':
|
||||
return participants(s).filter((p) => !s.rounds[p]!.insuranceAnswered);
|
||||
case 'playing':
|
||||
return s.turn ? [s.turn] : [];
|
||||
case 'handEnd':
|
||||
return participants(s).filter((p) => !s.rounds[p]!.ready && seatOf(s, p)!.status !== 'left');
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function legalActions(s: BlackjackState, p: PlayerId): BlackjackAction[] {
|
||||
if (!activePlayers(s).includes(p)) return [];
|
||||
const seat = seatOf(s, p)!;
|
||||
const r = s.rounds[p]!;
|
||||
switch (s.phase) {
|
||||
case 'betting': {
|
||||
const unit = betUnit(s.options);
|
||||
const hi = maxBet(seat.chips, s.options);
|
||||
const mid = Math.floor(hi / unit / 2) * unit;
|
||||
const amts = [...new Set([unit, Math.max(unit, mid), hi])];
|
||||
return amts.map((amount) => ({ type: 'bet', amount }));
|
||||
}
|
||||
case 'insurance': {
|
||||
const out: BlackjackAction[] = [{ type: 'insurance', take: false }];
|
||||
if (seat.chips >= Math.floor(r.bet / 2) && r.bet >= 2) out.push({ type: 'insurance', take: true });
|
||||
return out;
|
||||
}
|
||||
case 'playing': {
|
||||
const h = r.hands[r.active];
|
||||
if (!h || h.status !== 'playing') return [];
|
||||
const out: BlackjackAction[] = [{ type: 'hit' }, { type: 'stand' }];
|
||||
if (canDouble(h, seat.chips, s.options)) out.push({ type: 'double' });
|
||||
if (canSplit(h, r.hands.length, seat.chips, s.options)) out.push({ type: 'split' });
|
||||
if (canSurrender(h, r.hands.length, s.options)) out.push({ type: 'surrender' });
|
||||
return out;
|
||||
}
|
||||
case 'handEnd':
|
||||
return [{ type: 'ready' }];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Secrets no view may show: the hole card while face down and the whole shoe. Attributed to every player. */
|
||||
function secretsOf(s: BlackjackState): string[] {
|
||||
const out = [...s.shoe];
|
||||
if (s.dealerDown && s.dealer[1]) out.push(s.dealer[1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
function result(s: BlackjackState): (GameResult & { handsPlayed: number }) | null {
|
||||
if (!s.result) return null;
|
||||
const ranking: PlayerId[][] = [];
|
||||
const byRank = new Map<number, PlayerId[]>();
|
||||
for (const r of s.result.ranking) byRank.set(r.rank, [...(byRank.get(r.rank) ?? []), r.player]);
|
||||
for (const rank of [...byRank.keys()].sort((a, b) => a - b)) ranking.push(byRank.get(rank)!);
|
||||
const scores: Record<PlayerId, number> = {};
|
||||
const scoreText: Record<PlayerId, string> = {};
|
||||
for (const r of s.result.ranking) {
|
||||
scores[r.player] = r.chips;
|
||||
scoreText[r.player] = `${r.chips.toLocaleString('ko-KR')} 칩`;
|
||||
}
|
||||
return {
|
||||
ranking,
|
||||
scores,
|
||||
scoreText,
|
||||
summary: s.result.summary,
|
||||
reason: s.result.abandoned ? 'abandoned' : 'normal',
|
||||
handsPlayed: s.handsPlayed,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- setup + definition
|
||||
|
||||
export interface FixedDeal {
|
||||
shoe?: CardId[];
|
||||
}
|
||||
|
||||
export function setupBlackjack(ctx: { players: PlayerId[]; options: BlackjackOptions; rng: Rng; now: number }, fixed?: FixedDeal): BlackjackState {
|
||||
const o = ctx.options;
|
||||
if (ctx.players.length < 1 || ctx.players.length > 7) throw new Error('블랙잭은 1~7명이 할 수 있어요.');
|
||||
const s: BlackjackState = {
|
||||
options: o,
|
||||
seats: ctx.players.map((id) => ({ id, chips: o.startingChips, status: 'playing', timeoutsInRow: 0, chipsAtHandStart: o.startingChips })),
|
||||
shoe: fixed?.shoe ? [...fixed.shoe] : ctx.rng.shuffle(buildShoe(o.decks)),
|
||||
shoeGen: 0,
|
||||
used: 0,
|
||||
dealer: [],
|
||||
dealerDown: true,
|
||||
dealerBlackjack: false,
|
||||
rounds: {},
|
||||
order: [],
|
||||
turn: null,
|
||||
phase: 'betting',
|
||||
handsPlayed: 0,
|
||||
deadlineAt: null,
|
||||
deadlineMs: 0,
|
||||
turnStartedAt: ctx.now,
|
||||
seq: 0,
|
||||
log: [],
|
||||
result: null,
|
||||
};
|
||||
startHand(s, { rng: ctx.rng, now: ctx.now, events: [] });
|
||||
return s;
|
||||
}
|
||||
|
||||
export const blackjack: GameDefinition<BlackjackState, BlackjackAction, BlackjackView, BlackjackOptions> = {
|
||||
id: 'blackjack',
|
||||
nameKo: '블랙잭',
|
||||
minPlayers: 1,
|
||||
maxPlayers: 7,
|
||||
stateVersion: 1,
|
||||
defaultOptions: blackjackOptionsSchema.parse({}),
|
||||
optionsSchema: blackjackOptionsSchema,
|
||||
actionSchema: blackjackActionSchema as unknown as GameDefinition<BlackjackState, BlackjackAction, BlackjackView, BlackjackOptions>['actionSchema'],
|
||||
setup: ({ players, options, rng, now }) => setupBlackjack({ players, options, rng, now }),
|
||||
validate,
|
||||
apply,
|
||||
view,
|
||||
activePlayers,
|
||||
deadline: (s) => s.deadlineAt,
|
||||
timeoutPlayers: activePlayers,
|
||||
onTimeout: () => ({ type: 'timeout' }),
|
||||
onLeave: (s, p) => {
|
||||
const seat = seatOf(s, p);
|
||||
if (!seat || s.phase === 'finished' || seat.status === 'left' || seat.status === 'out') return null;
|
||||
return { type: 'leave' };
|
||||
},
|
||||
result,
|
||||
legalActions,
|
||||
secretsOf,
|
||||
};
|
||||
|
||||
/** Test helper: every chip is accounted for against the house (seats never go negative). */
|
||||
export const chipsNonNegative = (s: BlackjackState): boolean => s.seats.every((seat) => seat.chips >= 0);
|
||||
78
packages/games/src/blackjack/options.ts
Normal file
78
packages/games/src/blackjack/options.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
/** 블랙잭 options (docs/games/blackjack.md §2). Official rules by default; Korean house-rule variants are room settings. */
|
||||
import { z } from 'zod';
|
||||
|
||||
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
export const blackjackOptionsSchema = z
|
||||
.object({
|
||||
decks: lit(1, 2, 4, 6, 8)
|
||||
.default(6)
|
||||
.meta({ title: '덱 수', labels: { 1: '1벌', 2: '2벌', 4: '4벌', 6: '6벌(카지노 기본)', 8: '8벌' } }),
|
||||
dealerSoft17: z
|
||||
.enum(['stand', 'hit'])
|
||||
.default('stand')
|
||||
.meta({ title: '딜러 소프트 17', labels: { stand: '스탠드(S17·공식)', hit: '히트(H17)' } }),
|
||||
blackjackPayout: z
|
||||
.enum(['3:2', '6:5', '2:1', '1:1'])
|
||||
.default('3:2')
|
||||
.meta({ title: '블랙잭 배당', labels: { '3:2': '3:2(공식)', '6:5': '6:5', '2:1': '2:1', '1:1': '1:1(같음)' } }),
|
||||
doubleRule: z
|
||||
.enum(['any', '9to11', '10to11', 'none'])
|
||||
.default('any')
|
||||
.meta({ title: '더블다운', labels: { any: '아무 두 장(공식)', '9to11': '합 9~11만', '10to11': '합 10~11만', none: '안 함' } }),
|
||||
doubleAfterSplit: z.boolean().default(true).meta({ title: '스플릿 후 더블(DAS)', labels: { true: '허용', false: '불가' } }),
|
||||
splitMaxHands: lit(2, 3, 4)
|
||||
.default(4)
|
||||
.meta({ title: '스플릿 최대 손패 수', labels: { 2: '2개(1번)', 3: '3개(2번)', 4: '4개(3번)' } }),
|
||||
resplitAces: z.boolean().default(false).meta({ title: '에이스 다시 스플릿', labels: { true: '허용', false: '불가(공식)' } }),
|
||||
hitSplitAces: z.boolean().default(false).meta({ title: '에이스 스플릿 후', labels: { true: '자유롭게 히트', false: '한 장만(공식)' } }),
|
||||
surrender: z
|
||||
.enum(['none', 'late'])
|
||||
.default('none')
|
||||
.meta({ title: '서렌더(기권)', labels: { none: '없음', late: '레이트(딜러 블랙잭 확인 후, 베팅 절반)' } }),
|
||||
insurance: z.boolean().default(true).meta({ title: '인슈어런스(딜러 A일 때)', labels: { true: '제공', false: '없음' } }),
|
||||
// Korean house rules ---------------------------------------------------
|
||||
charlie: z
|
||||
.enum(['off', 'six', 'five'])
|
||||
.default('off')
|
||||
.meta({ title: '(하우스 룰) 카드 찰리', labels: { off: '없음', six: '6장 찰리', five: '5장 찰리' } }),
|
||||
sevenTriple: z.boolean().default(false).meta({ title: '(하우스 룰) 7-7-7 보너스(3:1)', labels: { true: '켜기', false: '끄기' } }),
|
||||
// Chips / session ------------------------------------------------------
|
||||
startingChips: lit(500, 1000, 2000, 5000)
|
||||
.default(1000)
|
||||
.meta({ title: '시작 칩', labels: { 500: '500 칩', 1000: '1,000 칩', 2000: '2,000 칩', 5000: '5,000 칩' } }),
|
||||
minBet: lit(10, 20, 50, 100)
|
||||
.default(10)
|
||||
.meta({ title: '최소 베팅(단위)', labels: { 10: '10 칩', 20: '20 칩', 50: '50 칩', 100: '100 칩' } }),
|
||||
endCondition: z
|
||||
.enum(['hands', 'lastStanding'])
|
||||
.default('hands')
|
||||
.meta({ title: '게임 종료', labels: { hands: '정해진 판 수', lastStanding: '최후 1인(칩)' } }),
|
||||
handLimit: lit(5, 10, 20, 30)
|
||||
.default(10)
|
||||
.meta({ title: '판 수(정해진 판 수일 때)', labels: { 5: '5판', 10: '10판', 20: '20판', 30: '30판' } }),
|
||||
/** null = 무제한 (no clock; a dropped connection still gets auto moves after the room's grace time). */
|
||||
betSeconds: lit(15, 20, 30, null)
|
||||
.default(20)
|
||||
.meta({ title: '베팅 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', null: '무제한' } }),
|
||||
turnSeconds: lit(15, 20, 30, 60, null)
|
||||
.default(20)
|
||||
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||
handEndSeconds: lit(3, 4, 6, 10)
|
||||
.default(4)
|
||||
.meta({ title: '판 결과 보여 주는 시간', labels: { 3: '3초', 4: '4초', 6: '6초', 10: '10초' } }),
|
||||
awaySeconds: lit(3, 5, 10)
|
||||
.default(5)
|
||||
.meta({ title: '자리 비움일 때 제한 시간', labels: { 3: '3초', 5: '5초', 10: '10초' } }),
|
||||
})
|
||||
.superRefine((o, ctx) => {
|
||||
if (o.minBet * 4 > o.startingChips) {
|
||||
ctx.addIssue({ code: 'custom', path: ['minBet'], message: '시작 칩은 최소 베팅의 4배 이상이어야 해요.' });
|
||||
}
|
||||
});
|
||||
|
||||
export type BlackjackOptions = z.infer<typeof blackjackOptionsSchema>;
|
||||
|
||||
/** The admin sets these; rooms always use the admin value (none here — hosts may set every blackjack option). */
|
||||
export const blackjackAdminOnly: readonly string[] = [];
|
||||
147
packages/games/src/blackjack/rules.ts
Normal file
147
packages/games/src/blackjack/rules.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
/** Pure blackjack rules: deck, hand value, dealer play, double/split/surrender legality, settlement. */
|
||||
import { rankOf, standardDeck, type CardId } from '@bg/engine';
|
||||
import type { BlackjackOptions } from './options';
|
||||
import type { Hand, Outcome } from './types';
|
||||
|
||||
/**
|
||||
* A fresh shoe of `decks` standard 52-card decks (no jokers). `gen` makes every card id unique across
|
||||
* reshuffles (e.g. "KS#3-1"), so a card drawn before a reshuffle never collides with a card in the new shoe.
|
||||
* The `#…` suffix is ignored by `rankOf`/`cardPoints`; the web strips it with `baseCard` before drawing.
|
||||
*/
|
||||
export function buildShoe(decks: number, gen = 0): CardId[] {
|
||||
const out: CardId[] = [];
|
||||
for (let d = 0; d < decks; d++) out.push(...standardDeck(0).map((c) => `${c}#${gen}-${d}` as CardId));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Strips the shoe/deck suffix for display, e.g. "KS#3-1" → "KS". */
|
||||
export const baseCard = (c: CardId): CardId => c.split('#')[0] as CardId;
|
||||
|
||||
/** Point value of a card id (ignores the `#deck` suffix). T/J/Q/K = 10, A = 11 (soft), else face. */
|
||||
export function cardPoints(c: CardId): number {
|
||||
const r = rankOf(c);
|
||||
if (r === 'A') return 11;
|
||||
if (r === 'T' || r === 'J' || r === 'Q' || r === 'K') return 10;
|
||||
return Number(r);
|
||||
}
|
||||
|
||||
export const isAce = (c: CardId): boolean => rankOf(c) === 'A';
|
||||
|
||||
/** Best total treating aces as 11 then dropping to 1 while busting. `soft` = an ace still counts as 11. */
|
||||
export function handValue(cards: CardId[]): { total: number; soft: boolean } {
|
||||
let total = 0;
|
||||
let aces = 0;
|
||||
for (const c of cards) {
|
||||
total += cardPoints(c);
|
||||
if (isAce(c)) aces++;
|
||||
}
|
||||
let soft = aces > 0;
|
||||
while (total > 21 && aces > 0) {
|
||||
total -= 10;
|
||||
aces--;
|
||||
}
|
||||
soft = aces > 0 && total <= 21;
|
||||
return { total, soft };
|
||||
}
|
||||
|
||||
export const isBust = (cards: CardId[]): boolean => handValue(cards).total > 21;
|
||||
|
||||
/** A natural blackjack: exactly two cards worth 21 that did not come from a split. */
|
||||
export function isNaturalBlackjack(hand: Hand): boolean {
|
||||
return !hand.fromSplit && hand.cards.length === 2 && handValue(hand.cards).total === 21;
|
||||
}
|
||||
|
||||
/** Charlie count (cards that auto-win without busting), or null when the house rule is off. */
|
||||
export function charlieCount(o: BlackjackOptions): number | null {
|
||||
return o.charlie === 'off' ? null : o.charlie === 'five' ? 5 : 6;
|
||||
}
|
||||
|
||||
/** Three sevens (7-7-7 = 21) bonus. */
|
||||
export function isSevenTriple(o: BlackjackOptions, cards: CardId[]): boolean {
|
||||
return o.sevenTriple && cards.length === 3 && cards.every((c) => rankOf(c) === '7');
|
||||
}
|
||||
|
||||
/** Dealer draws per the soft-17 rule. */
|
||||
export function dealerShouldHit(cards: CardId[], o: BlackjackOptions): boolean {
|
||||
const { total, soft } = handValue(cards);
|
||||
if (total < 17) return true;
|
||||
if (total === 17 && soft && o.dealerSoft17 === 'hit') return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Dealer peeks for blackjack when the upcard is an ace or a ten-value card (American rules). */
|
||||
export function dealerPeeks(upcard: CardId): boolean {
|
||||
return cardPoints(upcard) === 10 || isAce(upcard);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- player action legality
|
||||
|
||||
export function canDouble(hand: Hand, chips: number, o: BlackjackOptions): boolean {
|
||||
if (hand.cards.length !== 2 || hand.status !== 'playing') return false;
|
||||
if (hand.frozenAces) return false;
|
||||
if (hand.fromSplit && !o.doubleAfterSplit) return false;
|
||||
if (chips < hand.bet) return false;
|
||||
const { total } = handValue(hand.cards);
|
||||
if (o.doubleRule === 'none') return false;
|
||||
if (o.doubleRule === '9to11') return total >= 9 && total <= 11;
|
||||
if (o.doubleRule === '10to11') return total >= 10 && total <= 11;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Two cards share a split value (any two ten-value cards count as a pair). */
|
||||
export function isPair(cards: CardId[]): boolean {
|
||||
if (cards.length !== 2) return false;
|
||||
return cardPoints(cards[0]!) === cardPoints(cards[1]!);
|
||||
}
|
||||
|
||||
export function canSplit(hand: Hand, handCount: number, chips: number, o: BlackjackOptions): boolean {
|
||||
if (hand.status !== 'playing' || !isPair(hand.cards)) return false;
|
||||
if (handCount >= o.splitMaxHands) return false;
|
||||
if (chips < hand.bet) return false;
|
||||
// Re-splitting aces only when allowed.
|
||||
if (hand.fromSplit && isAce(hand.cards[0]!) && !o.resplitAces) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function canSurrender(hand: Hand, handCount: number, o: BlackjackOptions): boolean {
|
||||
return o.surrender === 'late' && handCount === 1 && !hand.fromSplit && hand.cards.length === 2 && hand.status === 'playing';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- settlement
|
||||
|
||||
/** Settles one player hand against the dealer. Returns the outcome and net chips (bet already counts as committed). */
|
||||
export function settleHand(hand: Hand, dealer: CardId[], dealerBlackjack: boolean, o: BlackjackOptions): { outcome: Outcome; net: number } {
|
||||
const bet = hand.bet;
|
||||
if (hand.status === 'surrender') return { outcome: 'lose', net: -Math.round(bet / 2) };
|
||||
if (hand.status === 'bust') return { outcome: 'lose', net: -bet };
|
||||
if (isNaturalBlackjack(hand)) {
|
||||
if (dealerBlackjack) return { outcome: 'push', net: 0 };
|
||||
return { outcome: 'blackjack', net: Math.round(bet * blackjackMultiplier(o)) };
|
||||
}
|
||||
// Dealer blackjack beats every non-blackjack hand.
|
||||
if (dealerBlackjack) return { outcome: 'lose', net: -bet };
|
||||
if (hand.status === 'charlie') {
|
||||
if (isSevenTriple(o, hand.cards)) return { outcome: 'bonus', net: bet * 3 };
|
||||
return { outcome: 'win', net: bet };
|
||||
}
|
||||
if (isSevenTriple(o, hand.cards)) return { outcome: 'bonus', net: bet * 3 };
|
||||
const me = handValue(hand.cards).total;
|
||||
const dv = handValue(dealer);
|
||||
const dealerBust = dv.total > 21;
|
||||
if (dealerBust || me > dv.total) return { outcome: 'win', net: bet };
|
||||
if (me < dv.total) return { outcome: 'lose', net: -bet };
|
||||
return { outcome: 'push', net: 0 };
|
||||
}
|
||||
|
||||
export function blackjackMultiplier(o: BlackjackOptions): number {
|
||||
switch (o.blackjackPayout) {
|
||||
case '3:2':
|
||||
return 1.5;
|
||||
case '6:5':
|
||||
return 1.2;
|
||||
case '2:1':
|
||||
return 2;
|
||||
case '1:1':
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
200
packages/games/src/blackjack/types.ts
Normal file
200
packages/games/src/blackjack/types.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
/** 블랙잭 types: options re-export, actions, state, view (docs/games/blackjack.md §8). */
|
||||
import { z } from 'zod';
|
||||
import type { CardId, PlayerId } from '@bg/engine';
|
||||
|
||||
export { blackjackOptionsSchema, blackjackAdminOnly, type BlackjackOptions } from './options';
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
export const blackjackActionSchema = z.union([
|
||||
z.object({ type: z.literal('bet'), amount: z.number().int().min(0).max(1_000_000) }),
|
||||
z.object({ type: z.literal('insurance'), take: z.boolean() }),
|
||||
z.object({ type: z.literal('hit') }),
|
||||
z.object({ type: z.literal('stand') }),
|
||||
z.object({ type: z.literal('double') }),
|
||||
z.object({ type: z.literal('split') }),
|
||||
z.object({ type: z.literal('surrender') }),
|
||||
z.object({ type: z.literal('ready') }),
|
||||
]);
|
||||
export type BlackjackClientAction = z.infer<typeof blackjackActionSchema>;
|
||||
/** Client actions plus system-only ones (timer, leaving) that are not in the schema. */
|
||||
export type BlackjackAction = BlackjackClientAction | { type: 'timeout' } | { type: 'leave' };
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
export type Phase = 'betting' | 'insurance' | 'playing' | 'handEnd' | 'finished';
|
||||
export type SeatStatus = 'playing' | 'out' | 'left';
|
||||
/** How a single (possibly split) hand ended. */
|
||||
export type HandStatus = 'playing' | 'stand' | 'bust' | 'blackjack' | 'charlie' | 'surrender';
|
||||
export type Outcome = 'win' | 'lose' | 'push' | 'blackjack' | 'bonus';
|
||||
|
||||
export interface Seat {
|
||||
id: PlayerId;
|
||||
chips: number;
|
||||
status: SeatStatus;
|
||||
timeoutsInRow: number;
|
||||
/** Chips at the start of the current hand (for the result card delta). */
|
||||
chipsAtHandStart: number;
|
||||
}
|
||||
|
||||
export interface Hand {
|
||||
cards: CardId[];
|
||||
bet: number;
|
||||
status: HandStatus;
|
||||
/** This hand came from a split. */
|
||||
fromSplit: boolean;
|
||||
/** Split aces that may only take one card. */
|
||||
frozenAces: boolean;
|
||||
/** This hand was doubled (exactly one extra card). */
|
||||
doubled: boolean;
|
||||
/** Filled at settlement. */
|
||||
outcome: Outcome | null;
|
||||
/** Net chips for this hand at settlement (can be negative). */
|
||||
net: number;
|
||||
}
|
||||
|
||||
export interface Round {
|
||||
/** Base bet locked in the betting phase. */
|
||||
bet: number;
|
||||
betLocked: boolean;
|
||||
hands: Hand[];
|
||||
/** Index of the hand currently being played. */
|
||||
active: number;
|
||||
/** Insurance side bet (0 = none / declined). */
|
||||
insurance: number;
|
||||
insuranceAnswered: boolean;
|
||||
/** Pressed ready at handEnd. */
|
||||
ready: boolean;
|
||||
/** Player joined this hand (had chips when betting opened). */
|
||||
inHand: boolean;
|
||||
}
|
||||
|
||||
export type LogEntry =
|
||||
| { seq: number; t: 'bet'; p: PlayerId; amount: number }
|
||||
| { seq: number; t: 'deal' }
|
||||
| { seq: number; t: 'hit'; p: PlayerId; card: CardId; total: number }
|
||||
| { seq: number; t: 'stand'; p: PlayerId; total: number }
|
||||
| { seq: number; t: 'double'; p: PlayerId; card: CardId; total: number }
|
||||
| { seq: number; t: 'split'; p: PlayerId }
|
||||
| { seq: number; t: 'surrender'; p: PlayerId }
|
||||
| { seq: number; t: 'bust'; p: PlayerId; total: number }
|
||||
| { seq: number; t: 'charlie'; p: PlayerId; cards: number }
|
||||
| { seq: number; t: 'insurance'; p: PlayerId; amount: number }
|
||||
| { seq: number; t: 'dealer'; card: CardId; total: number }
|
||||
| { seq: number; t: 'dealerBust'; total: number }
|
||||
| { seq: number; t: 'result'; p: PlayerId; net: number };
|
||||
|
||||
export interface PlayerResult {
|
||||
player: PlayerId;
|
||||
rank: number;
|
||||
chips: number;
|
||||
left: boolean;
|
||||
}
|
||||
|
||||
export interface BlackjackResult {
|
||||
ranking: PlayerResult[];
|
||||
winner: PlayerId[];
|
||||
summary: string;
|
||||
abandoned: boolean;
|
||||
}
|
||||
|
||||
export interface BlackjackState {
|
||||
options: import('./options').BlackjackOptions;
|
||||
seats: Seat[];
|
||||
/** Remaining cards in the shoe (secret). */
|
||||
shoe: CardId[];
|
||||
/** Shuffle generation; bumped on every (re)shuffle to keep card ids unique across shoes. */
|
||||
shoeGen: number;
|
||||
/** Cards already used since the last shuffle (for the penetration display). */
|
||||
used: number;
|
||||
/** Dealer cards; [0] = upcard, [1] = hole (secret while `dealerDown`). */
|
||||
dealer: CardId[];
|
||||
dealerDown: boolean;
|
||||
dealerBlackjack: boolean;
|
||||
/** Per-player round state, only for seats dealt into this hand. */
|
||||
rounds: Record<PlayerId, Round>;
|
||||
/** Seat order of participants this hand. */
|
||||
order: PlayerId[];
|
||||
/** Current player in the playing phase. */
|
||||
turn: PlayerId | null;
|
||||
phase: Phase;
|
||||
handsPlayed: number;
|
||||
deadlineAt: number | null;
|
||||
deadlineMs: number;
|
||||
turnStartedAt: number;
|
||||
seq: number;
|
||||
log: LogEntry[];
|
||||
result: BlackjackResult | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- view
|
||||
|
||||
export interface HandView {
|
||||
cards: CardId[];
|
||||
total: number;
|
||||
soft: boolean;
|
||||
status: HandStatus;
|
||||
bet: number;
|
||||
doubled: boolean;
|
||||
outcome: Outcome | null;
|
||||
net: number;
|
||||
}
|
||||
|
||||
export interface SeatView {
|
||||
id: PlayerId;
|
||||
chips: number;
|
||||
status: SeatStatus;
|
||||
/** This hand: null if not dealt in (no chips / joined late). */
|
||||
hands: HandView[] | null;
|
||||
active: number;
|
||||
insurance: number;
|
||||
bet: number;
|
||||
betLocked: boolean;
|
||||
ready: boolean;
|
||||
isTurn: boolean;
|
||||
/** Net chips this hand, shown at handEnd. */
|
||||
net: number | null;
|
||||
}
|
||||
|
||||
export interface DealerView {
|
||||
/** While face down, the hole shows as null. */
|
||||
cards: (CardId | null)[];
|
||||
/** Total of the visible cards (upcard only while down). */
|
||||
total: number;
|
||||
soft: boolean;
|
||||
revealed: boolean;
|
||||
blackjack: boolean;
|
||||
bust: boolean;
|
||||
}
|
||||
|
||||
export interface MyTurnInfo {
|
||||
canHit: boolean;
|
||||
canStand: boolean;
|
||||
canDouble: boolean;
|
||||
canSplit: boolean;
|
||||
canSurrender: boolean;
|
||||
}
|
||||
|
||||
export interface BlackjackView {
|
||||
options: import('./options').BlackjackOptions;
|
||||
me: PlayerId | null;
|
||||
phase: Phase;
|
||||
handsPlayed: number;
|
||||
handLimit: number | null;
|
||||
dealer: DealerView;
|
||||
seats: SeatView[];
|
||||
order: PlayerId[];
|
||||
turn: PlayerId | null;
|
||||
/** Decks still in the shoe (rounded, public). */
|
||||
decksLeft: number;
|
||||
/** My betting range this hand (betting phase). */
|
||||
betRange: { min: number; max: number; step: number } | null;
|
||||
my: MyTurnInfo | null;
|
||||
/** Insurance choice is open for me now. */
|
||||
insuranceOpen: boolean;
|
||||
insuranceMax: number;
|
||||
turnStartedAt: number;
|
||||
deadlineTotalMs: number;
|
||||
recent: LogEntry[];
|
||||
result: BlackjackResult | null;
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import { connectFourBot } from '../connect-four/bot';
|
||||
import { unoBot } from '../uno/bot';
|
||||
import { liarBot } from '../liar/bot';
|
||||
import { magicalAthleteBot } from '../magical-athlete/bot';
|
||||
import { blackjackBot } from '../blackjack/bot';
|
||||
|
||||
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
@@ -71,6 +72,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
'old-maid': oldMaidBot,
|
||||
uno: unoBot,
|
||||
'magical-athlete': magicalAthleteBot,
|
||||
blackjack: blackjackBot,
|
||||
};
|
||||
|
||||
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */
|
||||
|
||||
@@ -32,6 +32,7 @@ import { connectFour } from './connect-four';
|
||||
import { uno } from './uno';
|
||||
import { liar } from './liar';
|
||||
import { magicalAthlete } from './magical-athlete';
|
||||
import { blackjack } from './blackjack';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -67,4 +68,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[uno.id]: uno,
|
||||
[liar.id]: liar,
|
||||
[magicalAthlete.id]: magicalAthlete,
|
||||
[blackjack.id]: blackjack,
|
||||
};
|
||||
|
||||
@@ -58,6 +58,7 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'uno',
|
||||
'liar',
|
||||
'magical-athlete',
|
||||
'blackjack',
|
||||
];
|
||||
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */
|
||||
|
||||
@@ -44,6 +44,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
|
||||
{ id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true },
|
||||
{ id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true },
|
||||
{ id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true },
|
||||
];
|
||||
|
||||
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);
|
||||
|
||||
Reference in New Issue
Block a user