Blackjack: hidden cards, phases, turn timers, chips
What you'll build
- A blackjack table with a dealer and a hidden hole card
- Betting and playing phases with turn timers
- Chips held in a wallet with reservations and payouts
You will walk through examples/blackjack: up to five players, each playing their own hand
against the house. This tutorial assumes you finished tic-tac-toe
and the quiz, so defineGame, actions, reject() and view() are not
explained again. Here you meet cards, phases that hand over to each other, turn timers and
money.
A hand in three phases
Section titled “A hand in three phases”A hand moves through three phases, declared under phases in one defineGame call:
betting: everyone bets at once, against a timer (a round, as in the quiz).play: players take turns to hit, stand or double.dealer: the dealer plays, the hands are settled and the next hand is scheduled.
Each phase has its own actions, so hit simply does not exist while people are betting.
ctx.phase.go('play') moves on. See phases for the full model.
Cards and shuffling
Section titled “Cards and shuffling”shoehive/cards has the card helpers. A Card is a two-character string such as 'AS' or
'TD'. shoe(6) is an unshuffled stack of six decks, and blackjackValue(cards) scores a hand
as { total, soft, blackjack, bust }.
Shuffle with ctx.random, never Math.random(). It is the table's seeded generator, so a
replay or a test with a fixed seed deals the same cards. The deal code runs when the play
phase starts:
onEnter: ({ state, ctx }) => { // Reshuffle when the shoe runs low. if (state.shoe.length < 52) state.shoe = ctx.random.shuffle(shoe(ctx.options.decks)); const draw = () => state.shoe.pop()!; for (let i = 0; i < 2; i++) { for (const hand of state.hands) hand?.cards.push(draw()); state.dealer.push(draw()); } for (const hand of state.hands) { if (hand && blackjackValue(hand.cards).blackjack) hand.done = true; } ctx.emit('dealt', { hand: state.handNumber }); // The engine moves the first turn past naturals after onEnter; with every hand // done (all naturals) there is no turn to play. if (state.hands.every((h) => !h || h.done)) ctx.phase.go('dealer');},The shoe lives in state, so it is saved and replayed with the table. It is also secret,
which the view below takes care of.
Betting: a round and a wallet
Section titled “Betting: a round and a wallet”The betting phase is a round with closeWhen: 'all-submitted' and a 20 second limit.
bet is a once action, so each seat bets once. When the round closes, onClose starts the
deal if anyone bet, or opens a new round if nobody did.
betting: { rounds: { durationMs: BET_MS, closeWhen: 'all-submitted', onOpen: ({ state }) => { state.handNumber += 1; state.dealer = []; state.hands = state.hands.map(() => null); }, onClose: ({ state, ctx }) => { if (state.hands.some((h) => h !== null)) ctx.phase.go('play'); else ctx.round.next(); // nobody bet: open betting again }, }, actions: { bet: { once: true, input: z.object({ amount: z.number().int().positive() }), async run({ state, seat, input, ctx }) { const { minBet, maxBet } = ctx.options; if (input.amount < minBet || input.amount > maxBet) reject('BET_OUT_OF_RANGE', { minBet, maxBet }); if (!(await ctx.wallet.reserve(seat, input.amount, betKey(state.handNumber, seat)))) reject('INSUFFICIENT_FUNDS'); state.bankroll[seat]! -= input.amount; state.hands[seat] = { bet: input.amount, doubled: false, cards: [], done: false, outcome: null, }; }, }, },},The bet is money, so it goes through ctx.wallet (see
wallets and real-money safety and
ADR 0007):
await ctx.wallet.reserve(seat, amount, key)takes the amount out of the player's available balance and returnstrue, orfalsewhen they cannot afford it. It runs immediately because the action needs the answer. Here afalsebecomesreject('INSUFFICIENT_FUNDS'), so the whole action is undone.commit(key),release(key)andcredit(seat, amount, key)do not return anything. They are held back and sent only after the action has been saved, so money never moves for a state change that did not happen.- The key names the reservation. It must be unique at the table, so the example builds it from the hand and seat number: one key per hand per seat.
const betKey = (hand: number, seat: number) => `bet:${String(hand)}:${String(seat)}`;const doubleKey = (hand: number, seat: number) => `double:${String(hand)}:${String(seat)}`;const payKey = (hand: number, seat: number) => `pay:${String(hand)}:${String(seat)}`;
const PAYOUT: Record<Outcome, number> = { blackjack: 2.5, win: 2, push: 1, lose: 0, bust: 0 };double reserves the same stake again, under its own key. Amounts are whole numbers (chips,
or cents), never fractions.
Turns, skipping and the turn timer
Section titled “Turns, skipping and the turn timer”The play phase declares who may act and what happens to a slow player:
turns: { skip: ({ seat, state }) => { const hand = state.hands[seat]; return !hand || hand.done; }, timeoutMs: TURN_MS, onTimeout: 'autoStand',},- Turns go round the seats in order.
skippasses over seats with no hand, and over hands that are already done (a natural blackjack, or a stand). Bothhitandstandend by callingctx.turn.next(), and when no seat is left they callctx.phase.go('dealer'). timeoutMsarms a 30 second timer each time the turn changes. When it fires, Shoehive runs the action named inonTimeoutwith{ seat }as input.- That action must exist, and it should be
internal: it cannot be sent by a client, only by a timer or by your own code. Otherwise any player could stand for somebody else.
autoStand: { internal: true, input: z.object({ seat: z.number().int() }), run({ state, input, ctx }) { const hand = state.hands[input.seat]; if (hand && !hand.done) finishHand(hand, ctx); },},For other clocks see timers and turn clocks. The dealer
phase uses one more, ctx.timers.after('nextHand', NEXT_HAND_MS, 'nextHand'), which runs the
internal nextHand action five seconds later to start betting again.
The dealer and settlement
Section titled “The dealer and settlement”When the dealer phase starts, the dealer draws to 17, then every hand is scored. For each hand the code commits the reservations (the stake is now really spent) and credits the winnings, which include the stake back on a win or a push:
onEnter: ({ state, ctx }) => { const anyLive = state.hands.some((h) => { const value = h && blackjackValue(h.cards); return value && !value.bust && !value.blackjack; }); // Dealer draws to 17 and stands on all 17s. while (anyLive && blackjackValue(state.dealer).total < 17) state.dealer.push(state.shoe.pop()!); const dealer = blackjackValue(state.dealer); state.hands.forEach((hand, seat) => { if (!hand) return; const value = blackjackValue(hand.cards); let outcome: Outcome; if (value.bust) outcome = 'bust'; else if (value.blackjack) outcome = dealer.blackjack ? 'push' : 'blackjack'; else if (dealer.blackjack) outcome = 'lose'; else if (dealer.bust || value.total > dealer.total) outcome = 'win'; else if (value.total === dealer.total) outcome = 'push'; else outcome = 'lose'; hand.outcome = outcome; ctx.wallet.commit(betKey(state.handNumber, seat)); if (hand.doubled) ctx.wallet.commit(doubleKey(state.handNumber, seat)); const payout = Math.floor(hand.bet * PAYOUT[outcome]); if (payout > 0) ctx.wallet.credit(seat, payout, payKey(state.handNumber, seat)); state.bankroll[seat]! += payout; }); ctx.timers.after('nextHand', NEXT_HAND_MS, 'nextHand');},Net effect for a 100 chip bet that wins: 100 reserved at the bet, committed at settlement,
200 credited. A loss credits nothing. Because the credit key is pay:<hand>:<seat>, it
cannot pay twice for one hand even if something retries.
Leaving mid-hand
Section titled “Leaving mid-hand”A player can stand up at any time, and their money must not get stuck. onStand handles it:
before the deal (no cards yet) the bet is released, so it returns to their balance. After the
deal the bet is forfeit, so it is committed.
onSit: async ({ state, seat, ctx }) => { state.bankroll[seat!] = await ctx.wallet.balance(seat!);},onStand: ({ state, seat, ctx }) => { const hand = state.hands[seat!]; if (hand?.outcome === null) { // Before the deal the bet comes back; once cards are out it is forfeit. const keys = [betKey(state.handNumber, seat!)]; if (hand.doubled) keys.push(doubleKey(state.handNumber, seat!)); for (const key of keys) { if (hand.cards.length === 0) ctx.wallet.release(key); else ctx.wallet.commit(key); } } state.bankroll[seat!] = 0; state.hands[seat!] = null;},onSit copies the wallet balance into state.bankroll. That number is only for display; the
wallet stays the source of truth.
Hiding the hole card
Section titled “Hiding the hole card”The dealer's second card must stay face down until the dealer plays. The view builds what
each client may see, and hideCard turns a card into null:
view: ({ state, ctx }) => { const revealDealer = ctx.phase === 'dealer'; return { handNumber: state.handNumber, bankroll: state.bankroll, hands: state.hands, // The hole card (the dealer's second card) stays face down until the dealer plays. dealer: revealDealer ? state.dealer : state.dealer.map((card, i) => (i === 1 ? hideCard(card) : card)), dealerTotal: revealDealer ? blackjackValue(state.dealer).total : null, shoe: { remaining: state.shoe.length }, };},Two details matter. The dealer's total is null until the reveal, so the total cannot give
the card away. And the shoe is sent as a count only, so nobody can read the next card.
Clients receive views, never state, so there is nothing to peek at. More patterns in
hidden information.
Run it with a wallet
Section titled “Run it with a wallet”A game that calls ctx.wallet needs a wallet on the server. Without one, every call fails
with WALLET_NOT_CONFIGURED. MemoryWallet is an in-memory ledger for development:
const shoehive = createServer({ games: [blackjack], wallet: new MemoryWallet({ startingBalance: 1000 }), devtools, ...(secret ? { secret } : {}),});Every new player starts with 1000. For real money you implement the Wallet interface on
your own database or payment service, and the rest of the game does not change. Shoehive is
bookkeeping, not a licensed gaming system: read
wallets and real-money safety first.
Test the money and the secrets
Section titled “Test the money and the secrets”createTestTable gives every player a MemoryWallet balance of 1000 and exposes it as
t.wallet. This test checks that bets are reserved, that the hole card is hidden from every
viewer, including spectators, and that the shoe never leaves the server:
it('reserves bets, deals, and hides the hole card from every viewer', async () => { const t = await createTestTable(blackjack, { players: 2, options: {} }); await t.act(0, 'bet', { amount: 100 }); await t.act(1, 'bet', { amount: 50 }); expect(await t.wallet.balance('p0')).toBe(900); expect(await t.wallet.balance('p1')).toBe(950); expect(t.meta.phase).toBe('play'); expect(t.state.dealer).toHaveLength(2); for (const viewer of [0, 1, 'spectator'] as const) { const view = t.viewOf(viewer); expect(view.dealer[1]).toBeNull(); expect(view.dealerTotal).toBeNull(); expect(JSON.stringify(view)).not.toContain(t.state.dealer[1]!); expect(view).not.toHaveProperty('shoe.cards'); } expect(t.state.bankroll.slice(0, 2)).toEqual([900, 950]); expect(t.events.map((e) => e.name)).toContain('dealt');});Time is fake in tests. t.advance(ms) moves the clock, so you can check the turn timer
without waiting 30 seconds. t.runtime.idle() waits for the deferred wallet operations, then
the test checks each balance, t.walletErrors and a replay:
it('plays a full hand: turns, timeout auto-stand, dealer play and wallet payouts', async () => { const t = await createTestTable(blackjack, { players: 2, options: {} }); await t.act(0, 'bet', { amount: 100 }); await t.act(1, 'bet', { amount: 100 }); // With the default test seed neither player has a natural, so both get a turn. expect(t.meta.turn?.seat).toBe(0); await t.act(0, 'stand'); expect(t.meta.turn?.seat).toBe(1); await t.advance(TURN_MS); // seat 1 times out and auto-stands expect(t.meta.phase).toBe('dealer'); expect(t.viewOf(0).dealer).toEqual(t.state.dealer); expect(blackjackValue(t.state.dealer).total).toBeGreaterThanOrEqual(17); await t.runtime.idle(); for (const seat of [0, 1]) { const hand = t.state.hands[seat]!; const expected = { blackjack: 250, win: 200, push: 100, lose: 0, bust: 0 }[hand.outcome!]; expect(await t.wallet.balance(`p${String(seat)}`)).toBe(START - 100 + expected); expect(t.state.bankroll[seat]).toBe(START - 100 + expected); } expect(t.walletErrors).toEqual([]); await t.advance(NEXT_HAND_MS); expect(t.meta.phase).toBe('betting'); expect(t.state.handNumber).toBe(2); await t.verifyReplay();});And the release on leaving before the deal:
it('returns the bet to a player who leaves before the deal', async () => { const t = await createTestTable(blackjack, { players: 2, options: {} }); await t.act(0, 'bet', { amount: 100 }); expect(await t.wallet.balance('p0')).toBe(900); await t.stand(0); await t.runtime.idle(); expect(await t.wallet.balance('p0')).toBe(START);});More in testing games.
Where next
Section titled “Where next”- Try it:
pnpm build:web && pnpm startinexamples/blackjack, then open two browsers. - Add a rule: insurance, or a blackjack payout of 6 to 5. Change
PAYOUTand see which tests fail. - Next tutorial: Texas Hold'em, with side pots and per-seat hidden hands.
