새 게임 블랙잭: 딜러(하우스) 상대 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);
});