새 게임 블랙잭: 딜러(하우스) 상대 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:
EJClaw
2026-10-14 05:45:41 +09:00
parent 71bdfd201a
commit 13a89a645e
23 changed files with 2243 additions and 5 deletions

View 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);
});

View 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');
});
});

View 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' };
};

View 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);

View 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[] = [];

View 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;
}
}

View 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;
}

View File

@@ -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 (원카드 외치기·잡기). */

View File

@@ -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,
};

View File

@@ -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명). */

View File

@@ -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);