Files
joke-app/packages/games/src/blackjack/index.ts
EJClaw 13a89a645e 새 게임 블랙잭: 딜러(하우스) 상대 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>
2026-10-14 05:45:41 +09:00

773 lines
26 KiB
TypeScript

/** 블랙잭 (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);