Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 12
Module 5 · Design problems II: lockers, vending and blackjack · Chapter 12 of 28
Online Blackjack: Shoe, Hands, Dealer Rules and Payouts
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps, Design Patterns in TypeScript: Creational, Structural and Behavioural and Parking Lot: Floors, Spots, Tickets and Fees. Next up: Meeting Scheduler: Rooms, Calendars, Conflicts and Invites.
Part 1 · Requirements
What the table must do
At an online blackjack table, software deals the cards, plays the dealer and pays the bets, so every rule of the game is a line of code. This chapter builds one table with a single player, a shoe, a dealer and a payout rule you can swap.
As in the parking lot chapter, the functional requirements come first. Blackjack has many house rules, so we state ours.
- The game uses a shoe, a box holding six shuffled 52-card decks, 312 cards in all.
- A card is worth its number. Jack, queen and king are worth 10. An ace is worth 1 or 11, whichever suits the hand.
- A player bets chips before the deal. In our model a bet is a multiple of 10 chips between 10 and 500.
- The deal goes player, dealer face up, player, dealer face down. The face-down card is the hole card.
- A natural is an ace and a ten-value card as the first two cards. It pays 3 to 2.
- If either side has a natural after the deal, the round ends at once. Two naturals tie.
- The player may hit to take a card, stand to stop, or double, which doubles the bet, takes exactly one card and stands. In our model a double is allowed on any first two cards.
- A hand over 21 is a bust and loses at once.
- The dealer then draws below 17 and stands on every 17, soft 17 included.
- A higher total wins and pays 1 to 1. A tie is a push and returns the bet.
Published rules agree on card values, the 3 to 2 natural, the dealer drawing to 17 and the push. Tables differ on whether the dealer draws on a soft 17 (a 17 counting an ace as 11) and on which totals may be doubled, so those two lines are our model's choices.
A prompt such as "design blackjack" leaves rules open, so ask the questions whose answers change a class or a method.
Quality, numbers and scope
Non-functional requirements say how well the system behaves. The shuffle must be fair, so every order of the shoe is equally likely. The table must be testable: tests need to know exactly which cards come out, so the random source is injected. And a refused action must change nothing, so a rejected double leaves the chips and the hand as they were.
Chips are whole numbers. A bet that is a multiple of 10 makes every payout in this chapter a whole number: 3 to 2 needs an even bet (3 to 2 on 10 chips is 15), and the 6 to 5 rule of a later lesson needs a multiple of 5 (6 to 5 on 10 chips is 12).
We rejected two designs. The first picks a random card each time without removing it, as if rolling dice. Cards would repeat, and a shoe would never run out. The second shuffles by swapping each card with a random card anywhere in the shoe. It looks right and is not. The shuffle lesson counts the orders it produces and shows the bias.
| Must | Should | Out of scope |
|---|---|---|
| Shoe, deal, hit, stand, double, dealer rule, payouts | Split, a reshuffle marker, other payout rules | Several players, side bets, card counting, chip purchases |
Check yourself
A player bets 10 chips and is dealt an ace and a king. The dealer has no natural. How many chips come back?
- 25: the 10 chips staked plus 15 won, because a natural pays 3 to 2.
Why is the random source injected instead of called directly?
- A test can then supply a known shuffle, so the cards and the result are exact.
Why must bets be multiples of 10 in our model?
- So that every payout is a whole number of chips. 3 to 2 alone needs only an even bet, and 6 to 5 needs a multiple of 5; a multiple of 10 satisfies both.
Part 2 · Use cases
Actors and use cases
An actor is someone outside the system who uses it. A use case is one goal an actor wants to reach. At our table there is one actor, the player. The dealer is part of the system, because software plays it by a fixed rule.
A use case diagram shows actors, their use cases and how those relate. Include means a use case always runs another as part of itself. Extend means an exceptional case adds steps to a base case under a condition. Standing always includes the dealer playing, which always includes settling the bets. A bust extends hitting, because only some hits end in a bust.
The blue box is the actor and the pills are use cases, with the exceptional one in red. An arrow from the actor means the actor starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". The UML chapter explains why the extend arrow is drawn from the base case here.
Read the diagram as a checklist of goals. Each pill becomes one or two methods and a few tests. "Join a table" sits beside the player in the top row, so the player's five use cases fit rows of at most four nodes and every arrow runs down or left to right. Notice that the player never starts "Dealer plays" or "Settle and pay". They are consequences, and the system runs them.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Join a table | Player sits with a stack of chips | None in our model |
| Place a bet | Chips leave the stack and the bet is recorded | Not a multiple of 10, out of range, not enough chips: refuse |
| Hit | One card is added to the hand | Bust: the round ends. Round not under way: refuse |
| Stand | The player stops and the dealer plays | Round not under way: refuse |
| Double | Bet doubles, one card, then stand | More than two cards, not enough chips: refuse |
| Settle and pay | Each hand is judged and the policy pays | A natural on either side ends the round at the deal |
Every alternative is a named refusal, and each one must change nothing. A refused bet leaves the stack as it was. A refused double leaves the bet as it was. We will assert both.
One decision shapes the design. The round has stages, and each action is legal in only some of them. A hit is meaningful only during the player's turn. Writing the stages down first gives us a state machine to build, and it tells us which actions to refuse in which stage.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name that is reported but not run, and each turns into a real test as the code lands.
test.todo('a player joins a table with chips'); test.todo('the player places a bet'); test.todo('the player hits for a card'); test.todo('the player stands and the dealer plays'); test.todo('the player doubles for one card'); test.todo('the round settles and pays');
✔ a player joins a table with chips (0.6512ms) # TODO ✔ the player places a bet (0.096ms) # TODO ✔ the player hits for a card (0.0747ms) # TODO ✔ the player stands and the dealer plays (0.0605ms) # TODO ✔ the player doubles for one card (0.0872ms) # TODO ✔ the round settles and pays (0.0745ms) # TODO ℹ tests 6 ℹ todo 6
Output (durations vary)
All six names are reported as todo, and none counts as passed. Later lessons replace them with tests that pass. If a name never gets a test, the requirement behind it was probably missed.
Why does the player not start the use case "Dealer plays"?
- It follows from standing and needs no choice, so the system runs it by a fixed rule.
Which relation links hit and bust, and in which direction does the diagram draw it?
- Extend: bust is an exceptional case of hit. The diagram draws it from hit to bust, labelled "extended by".
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: shoe, deck, card, hand, player, dealer, chips, bet, round, table, payout. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Card | Plain value: rank and suit | Two values and no behaviour |
| Deck | Function deck() | It builds 52 cards and holds nothing |
| Shoe | Class Shoe, behind CardSource | Holds the order of the cards and hands them out |
| Hand | Class Hand | Cards, a bet and rules for value, bust and natural |
| Player | Class Player | Guards the chip count |
| Dealer | A Hand and a rule function | The dealer has no choices to model |
| Round | Class Round | The stages and the legal actions |
| Table | Class Table | Builds rounds for one player and one shoe |
| Payout | Interface PayoutPolicy | The 3 to 2 rule is the one thing tables change |
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 2..* means two or more.
player: PlayernewRound(): Roundnamechips: numberdebit(n), credit(n)state: RoundStatebet(n), deal()hit(), stand(), double()results: Result[]cards: Card[]bet: numbervalue: total, softisBust, isNaturalrank: A to Ksuit: S H D Cdraw(): Cardprepare()?cards, nextremainingreturned(result, bet): chipsnatural pays 3 to 2- Table 1 → 1 Player
- Table 1 → 0..1 Round
- Table 1 → 1 CardSource (interface)
- Table 1 → 1 PayoutPolicy (interface)
- Round 1 → 2..* Hand
- Hand 1 → 2..* Card (value)
- Shoe → CardSource (interface)
- ThreeToTwo → PayoutPolicy (interface)
Read the links like sentences. A table has one player, one card source and one payout policy. It creates one round at a time. A round holds one or more player hands and the dealer's hand, so it is drawn as two or more hands. Every hand holds at least two cards. The shoe and the three-to-two policy each fill an interface.
The skeleton in TypeScript
As in the parking lot chapter, a compiler checks the diagram before anything else. We start with the card types. They are plain unions and tables, because enum is not erasable syntax and Node's type stripping rejects it.
export const SUITS = ['S', 'H', 'D', 'C'] as const; export const RANKS = [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', ] as const; export type Suit = (typeof SUITS)[number]; export type Rank = (typeof RANKS)[number]; export interface Card { readonly rank: Rank; readonly suit: Suit; } // An ace counts 1 here; the hand adds 10 when that helps. export const POINTS: Record<Rank, number> = { A: 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, J: 10, Q: 10, K: 10, };
An ace is stored as 1. The hand will add 10 when that helps, which keeps one number per rank. The errors come next.
export type BlackjackCode = | 'BAD_STATE' | 'BAD_BET' | 'NO_CHIPS' | 'SHOE_EMPTY' | 'CANNOT_DOUBLE' | 'CANNOT_SPLIT'; export class BlackjackError extends Error { readonly code: BlackjackCode; constructor(code: BlackjackCode, message: string) { super(message); this.name = 'BlackjackError'; this.code = code; } }
Every refusal is a BlackjackError with a code from a closed set. Callers and tests branch on the code, never on the message. The random source is an interface with one method, and a small seeded generator stands behind it for demos.
export interface Random { // a whole number from min up to, but not including, max int(min: number, max: number): number; } export class SystemRandom implements Random { int(min: number, max: number): number { return randomInt(min, max); } }
SystemRandom calls crypto.randomInt, whose upper bound is excluded. The method says so in its comment, and the shuffle relies on it. Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
Why is the dealer a rule and not a class?
- The dealer makes no choices. A function from a hand to "draw or stand" says everything.
Why does Round depend on CardSource and not on Shoe?
Part 4 · Round lifecycle and dealing
The stages of a round
A state machine lists the states, the events that cause moves and the events a state refuses. Our round has five stages. In betting the player places a bet. In dealing the first four cards go out. In player turn the player acts. In dealer turn the dealer draws by rule. In settled the bets are paid and the round is over.
Watch for the cards going out and the player acting before the dealer
Read it as steps
A round moves through five stages, and a settled round refuses further actions.
Two details are easy to miss. After the deal there are two ways forward: a round with no natural moves to the player's turn, and a round with a natural goes straight to settled. And the last step of the scene is a refusal: a hit on a settled round answers BAD_STATE.
The dealer turn is a stage inside stand. The method does not return until the dealer has finished and the round is settled, so no caller can ever send a hit during the dealer's turn. The stage is still real, and the round records every stage it enters in a history list, which the driver prints. If cards were dealt with animation delays and a pause between draws, the dealer turn would become observable, and the same table of legal actions would refuse a hit there.
From bet to payout
Now follow one round through the objects. The player bets 20 chips. The round takes the chips out of the player's stack first, so a bet the player cannot cover fails before anything is set. The deal draws four cards from the shoe, one at a time in the order player, dealer up, player, dealer hole.
Watch for the bet leaving the stack before any card is dealt
Read it as steps
The bet leaves the stack first, cards come from the shoe, and a policy decides the payout.
The order matters. The bet leaves the stack before the first card is dealt. Each decision draws from the same shoe. And the round never decides what a win pays: it asks the payout policy, which answers 40 for a win on a bet of 20, the stake plus the same again. Because the policy returns chips handed back, stake included, a loss is 0 and a push is the bet itself.
This is the rule from the use case lesson: a check that can fail comes before a change. A bet is validated, then the chips are debited, then the hand exists.
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. This one seats a player with 100 chips, builds a six-deck shoe with a seeded shuffle, bets 20 and plays a simple strategy: hit while the hand is below 17, then stand.
const show2 = (h: Hand) => `${h.cards.map(show).join(' ')} = ${h.value.total}`; const player = new Player('Asha', 100); const shoe = buildShoe(6, new SeededRandom(SEED)); const table = new Table(player, shoe, new ThreeToTwo()); const round = table.newRound(); round.bet(20); round.deal(); console.log('you: ', show2(round.hands[0])); console.log('dealer shows', show(round.dealer.cards[0])); const hand = round.hands[0]; while (round.state === 'player-turn' && hand.value.total < 17) { round.hit(); console.log('hit: ', show2(round.hands[0])); } if (round.state === 'player-turn') round.stand(); console.log('dealer:', show2(round.dealer)); console.log('result:', round.results[0], 'chips:', player.chips); console.log('states:', round.history.join(' > '));
you: 4S 10D = 14 dealer shows 3C hit: 4S 10D 6D = 20 dealer: 3C 4C 8S AD JC = 26 result: win chips: 120 states: betting > dealing > player-turn > dealer-turn > settled
Output (the seed is 1, so it repeats)
The player started with 14 and hit a 6 for 20. The dealer showed a 3 and kept drawing: a 4 and an 8 made 15, an ace made 16, and a jack made 26, a bust. The player wins, so 40 chips came back and the stack went from 80 to 120. The last line lists every stage the round went through.
A different seed shows the other way through the deal. With seed 11 the dealer is dealt an ace and a queen, a natural.
you: 8S 9H = 17 dealer shows AD dealer: AD QH = 21 result: lose chips: 80 states: betting > dealing > settled
Output: node demo.ts 11
The player's 17 never got to act. The stages are betting > dealing > settled, with no player turn, and the 20 chips are lost.
Why does a natural skip the player turn?
- The round is already decided at the deal, so it moves from dealing straight to settled.
Why does the shoe come out the same on every run of the driver?
Part 5 · Code: shuffle, score and play
A fair shuffle
A shuffle is fair when every order of the shoe is equally likely. The classic method is Fisher-Yates: walk from the last position to the second, and swap each card with one at or before it, chosen at random.
// Fisher-Yates: walk from the end, swap each card with one at or // before it. Every ordering is equally likely. export function shuffle<T>(items: readonly T[], random: Random): T[] { const a = [...items]; for (let i = a.length - 1; i > 0; i--) { const j = random.int(0, i + 1); [a[i], a[j]] = [a[j], a[i]]; } return a; }
The upper bound i + 1 is exclusive, so j can equal i and a card can stay where it is. That choice is what makes the result uniform. The tempting variant swaps each card with a random card anywhere, and it looks equally mixed. We checked both by shuffling three cards 60,000 times with a seeded generator and counting how often each of the six orders came out.
// The tempting shuffle: swap every card with a random one anywhere. function naive<T>(items: readonly T[], random: Random): T[] { const a = [...items]; for (let i = 0; i < a.length; i++) { const j = random.int(0, a.length); [a[i], a[j]] = [a[j], a[i]]; } return a; } const count = (method: typeof shuffle) => { const random = new SeededRandom(2024); const seen = new Map<string, number>(); for (let i = 0; i < 60000; i++) { const key = method(['a', 'b', 'c'], random).join(''); seen.set(key, (seen.get(key) ?? 0) + 1); } return [...seen].sort().map(([k, n]) => `${k}:${n}`).join(' '); }; console.log('Fisher-Yates', count(shuffle)); console.log('naive swap ', count(naive));
Fisher-Yates abc:10075 acb:10100 bac:10086 bca:9807 cab:10019 cba:9913 naive swap abc:8812 acb:11033 bac:11102 bca:11065 cab:8925 cba:9063
Output (seeded, so it repeats)
Fisher-Yates gives every order close to 10,000 appearances, the exact share of 60,000 divided by six. The naive swap gives about 8,800 for abc and about 11,000 for acb. Nothing in the naive code looks wrong, and the table of counts is the only thing that shows it. A test that checks the distribution is the way to catch it.
Counting paths explains the numbers. On three cards the naive swap makes three choices of three positions, so it has 3 × 3 × 3 = 27 equally likely paths, and 27 does not divide evenly by six orders. We listed every path with a short script: acb, bac and bca each come from 5 paths and the other three orders from 4, which predicts about 11,111 and 8,889 out of 60,000. Fisher-Yates makes a choice of three and then a choice of two, 3 × 2 = 6 paths, exactly one for each order.
Scoring a hand
A hand's value follows one rule: count every ace as 1, then add 10 once if there is an ace and that does not pass 21. At most one ace can count as 11, because two would already make 22.
export interface Score { total: number; soft: boolean; // an ace is counting as 11 } export function score(cards: readonly Card[]): Score { let total = 0; let aces = 0; for (const c of cards) { total += POINTS[c.rank]; if (c.rank === 'A') aces += 1; } const soft = aces > 0 && total + 10 <= 21; return { total: soft ? total + 10 : total, soft }; }
The hand is soft when an ace is counting as 11. A soft hand cannot bust on the next card, because the ace can drop back to 1 and give back 10 points. We ran the function on five hands.
const hands = ['AS 6H', 'AS 6H KD', 'AS AH 9C', 'KS 6H 8D', 'AS KH']; for (const text of hands) { const s = score(parse(text)); console.log(text.padEnd(10), s.total, s.soft ? 'soft' : 'hard'); }
AS 6H 17 soft AS 6H KD 17 hard AS AH 9C 21 soft KS 6H 8D 24 hard AS KH 21 soft
Output
An ace and a six are a soft 17. Add a king and the ace must count as 1, so the hand is a hard 17. Two aces and a nine make a soft 21. A king, a six and an eight bust at 24, and an ace with a king is 21.
A Hand wraps the cards with the bet and two derived facts.
export class Hand { readonly cards: Card[] = []; bet: number; readonly fromSplit: boolean; constructor(bet: number, fromSplit = false) { this.bet = bet; this.fromSplit = fromSplit; } add(card: Card): void { this.cards.push(card); } get value(): Score { return score(this.cards); } get isBust(): boolean { return this.value.total > 21; } // Two cards worth 21, and not made by splitting. get isNatural(): boolean { return this.cards.length === 2 && this.value.total === 21 && !this.fromSplit; } }
isNatural needs exactly two cards, a total of 21 and no split. The fromSplit flag is there so that a later extension can mark split hands, since a 21 made after a split is not a natural.
The round and the dealer
The round enforces the stages. Every action starts with a check, then changes things.
bet(amount: number): void { this.#require('betting'); if (this.hands.length > 0) { throw new BlackjackError('BAD_STATE', 'already bet'); } const ok = Number.isInteger(amount) && amount % 10 === 0; if (!ok || amount < MIN_BET || amount > MAX_BET) { throw new BlackjackError('BAD_BET', `bet ${amount}`); } this.#player.debit(amount); // throws before anything is set this.hands.push(new Hand(amount)); }
bet checks the stage, the amount and the chips before it creates a hand. debit throws if the stack is short, and it throws before the hand exists, so a refused bet leaves nothing behind. The deal uses the order of the draws.
deal(): void { this.#require('betting'); if (this.hands.length === 0) { throw new BlackjackError('BAD_STATE', 'place a bet first'); } this.#go('dealing'); const mine = this.hands[0]; mine.add(this.#source.draw()); this.dealer.add(this.#source.draw()); // face up mine.add(this.#source.draw()); this.dealer.add(this.#source.draw()); // hole card if (mine.isNatural || this.dealer.isNatural) this.#settle(); else this.#go('player-turn'); }
The player's actions are short because the hand and the stages do the work.
hit(): void { this.#require('player-turn'); const hand = this.hands[this.active]; hand.add(this.#source.draw()); if (hand.value.total >= 21) this.#next(); } stand(): void { this.#require('player-turn'); this.#next(); } double(): void { this.#require('player-turn'); const hand = this.hands[this.active]; if (hand.cards.length !== 2) { throw new BlackjackError('CANNOT_DOUBLE', 'only on two cards'); } this.#player.debit(hand.bet); // throws NO_CHIPS before any change hand.bet *= 2; hand.add(this.#source.draw()); this.#next(); }
A hit that reaches 21 or more ends the turn on its own. A double checks the card count first, debits the extra chips before changing the bet, and then ends the turn too. The finish applies the dealer rule and the payouts.
#next(): void { this.active += 1; if (this.active < this.hands.length) return; this.#go('dealer-turn'); if (this.hands.some((h) => !h.isBust)) { while (dealerDraws(this.dealer)) { this.dealer.add(this.#source.draw()); } } this.#settle(); } #settle(): void { for (const hand of this.hands) { const result = judge(hand, this.dealer); this.results.push(result); this.#player.credit(this.#policy.returned(result, hand.bet)); } this.#go('settled'); }
Tests that sit on the edges
Hand and payout tests are plain, and each one checks a rule that is easy to get wrong.
test('an ace counts 11 until that would bust the hand', () => { assert.deepEqual(score(parse('AS 6H')), { total: 17, soft: true }); const hard = score(parse('AS 6H KD')); assert.deepEqual(hard, { total: 17, soft: false }); }); test('two aces and a nine make a soft 21', () => { assert.deepEqual(score(parse('AS AH 9C')), { total: 21, soft: true }); }); test('face cards and tens are worth 10, and 24 is a bust', () => { assert.equal(score(parse('KS QH')).total, 20); assert.equal(hand('KS 6H 8D').isBust, true); });
✔ an ace counts 11 until that would bust the hand (2.0116ms) ✔ two aces and a nine make a soft 21 (0.1725ms) ✔ face cards and tens are worth 10, and 24 is a bust (0.257ms) ✔ only two cards made 21 by dealing are a natural (0.2244ms) ✔ results compare totals, with a push on a tie (2.0629ms) ✔ a bust loses even if the dealer also busts (0.1465ms) ✔ a natural beats 21 but ties another natural (0.169ms) ✔ three to two pays 25 chips back on a bet of 10 (0.1669ms) ℹ tests 8 ℹ pass 8 ℹ fail 0
Output (durations vary)
The round tests use rig, a helper that stacks the shoe from a string of cards, so each test knows the exact deal. A soft hand takes a hit that a hard hand would not survive, and a bust ends the round without the dealer drawing.
test('a soft hand survives a hit that a hard hand would not', () => { const { round } = start('AS 9H 6D 7C 10S'); round.hit(); assert.equal(round.hands[0].value.total, 17); assert.equal(round.hands[0].value.soft, false); assert.equal(round.state, 'player-turn'); }); test('a bust loses at once and the dealer does not draw', () => { const { player, round } = start('KS 9H 6D 7C QD'); round.hit(); assert.equal(round.state, 'settled'); assert.deepEqual(round.results, ['lose']); assert.equal(round.dealer.cards.length, 2); assert.equal(player.chips, 90); });
✔ the deal goes player, dealer up, player, dealer hole (1.9838ms) ✔ a player natural pays three to two (0.2815ms) ✔ two naturals push and the bet comes back (0.1662ms) ✔ a dealer natural ends the round before the player acts (0.1623ms) ✔ a soft hand survives a hit that a hard hand would not (0.1983ms) ✔ a bust loses at once and the dealer does not draw (0.2681ms) ✔ the dealer draws to 17 and the player wins with 20 (0.2429ms) ✔ the dealer stands on a soft 17 (0.2571ms) ✔ a double takes one card, doubles the bet and stands (0.297ms) ✔ a double on three cards is refused and changes nothing (0.6797ms) ✔ a double without the chips is refused (0.2271ms) ✔ hit after the round has ended is refused (0.1926ms) ✔ bad bets are refused before any chips move (0.2725ms) ℹ tests 13 ℹ pass 13 ℹ fail 0
Output (durations vary)
Part 6 · Extensions and trade-offs
Every use case, tested
The use case lesson left six test.todo names. With the table in place, each becomes a real test that drives it the way the player would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
test('a player joins a table with chips', () => { const { player, table } = rig('KS 9H 9D 7C'); assert.equal(table.player, player); assert.equal(player.chips, 100); }); test('the player places a bet', () => { const { player, table } = rig('KS 9H 9D 7C'); const round = table.newRound(); round.bet(30); assert.equal(player.chips, 70); assert.equal(round.state, 'betting'); }); test('the player hits for a card', () => { const { table } = rig('2S 9H 3D 7C 4S'); const round = table.newRound(); round.bet(10); round.deal(); round.hit(); assert.equal(round.hands[0].cards.length, 3); });
The other three cover a stand, a double and the settlement of a natural.
✔ a player joins a table with chips (0.9734ms) ✔ the player places a bet (0.307ms) ✔ the player hits for a card (0.3153ms) ✔ the player stands and the dealer plays (0.3535ms) ✔ the player doubles for one card (0.2757ms) ✔ the round settles and pays (0.9042ms) ℹ tests 6 ℹ pass 6 ℹ fail 0 ℹ todo 0
Output (durations vary)
Six pass and no todo is left. Each name is the sentence the use case lesson wrote, so goals and tests read side by side.
Splitting a pair
A split turns two cards of the same rank into two hands. The player puts up a second bet equal to the first, each card becomes the start of a hand, and each hand gets one more card. The round already holds a list of hands, so the data model needs no change. The change is one new method, a loop in the finish that skips hands already at 21, and one word in Hand: fromSplit stops being readonly.
split(): void { this.#require('player-turn'); const hand = this.hands[this.active]; const [first, second] = hand.cards; const pair = hand.cards.length === 2 && first.rank === second.rank; if (!pair || this.hands.length > 1) { throw new BlackjackError('CANNOT_SPLIT', 'one pair, once'); } this.#player.debit(hand.bet); // throws before any change const other = new Hand(hand.bet, true); other.add(hand.cards.pop() as Card); hand.fromSplit = true; hand.add(this.#source.draw()); other.add(this.#source.draw()); this.hands.splice(this.active + 1, 0, other); if (hand.value.total >= 21) this.#next(); }
The method checks everything before it changes anything: a pair, no earlier split and enough chips. In our model a hand is split once only, and split aces play like any other pair. Published rules usually give each split ace exactly one more card, and some allow splitting again up to four hands; both would be a few more checks in split and hit. Both hands are marked fromSplit, so a 21 on either one is a plain 21 and not a natural. The finish moves on to the next hand, and skips a hand that is already at 21.
test('a split plays two hands and settles each on its own', () => { const { player, round } = start('8S 9H 8D 7C 3S KS KD 2H'); round.split(); assert.equal(round.hands.length, 2); assert.deepEqual(round.hands.map((h) => h.value.total), [11, 18]); round.hit(); round.stand(); assert.deepEqual(round.results, ['win', 'push']); assert.equal(player.chips, 110); }); test('a 21 made by splitting pays one to one, not three to two', () => { const { player, round } = start('AS 9H AD 7C KS 5S 2C'); round.split(); assert.equal(round.active, 1); round.stand(); assert.deepEqual(round.results, ['win', 'lose']); assert.equal(player.chips, 100); });
✔ a split plays two hands and settles each on its own (2.0886ms) ✔ a 21 made by splitting pays one to one, not three to two (0.2021ms) ✔ a split needs a pair (0.4795ms) ✔ a hand that was split once cannot split again (0.1844ms) ✔ a split without the chips is refused (0.1869ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
Reshuffling and other payouts
A real shoe is not dealt to the last card. A cut card is placed near the end, and the shoe is reshuffled before the next round once it is reached. In our model the shoe reshuffles between rounds, never during one, when fewer than a set number of cards remain. CutShoe wraps a shoe and uses the optional prepare hook that Table already calls before each round.
// Reshuffles before a round once fewer than `cut` cards remain. export class CutShoe implements CardSource { readonly #decks: number; readonly #random: Random; readonly #cut: number; #shoe: Shoe; constructor(decks: number, random: Random, cut: number) { this.#decks = decks; this.#random = random; this.#cut = cut; this.#shoe = buildShoe(decks, random); } draw(): Card { return this.#shoe.draw(); } prepare(): void { if (this.#shoe.remaining < this.#cut) { this.#shoe = buildShoe(this.#decks, this.#random); } } get remaining(): number { return this.#shoe.remaining; } }
A second table rule is a new class and nothing else. Some tables pay 6 to 5 for a natural, which is 22 chips back on a bet of 10 and not 25.
export class SixToFive extends ThreeToTwo { override returned(result: Result, bet: number): number { if (result === 'blackjack') return bet + (bet * 6) / 5; return super.returned(result, bet); } }
test('the shoe reshuffles between rounds past the cut', () => { const shoe = new CutShoe(1, new SeededRandom(3), 26); for (let i = 0; i < 20; i++) shoe.draw(); shoe.prepare(); assert.equal(shoe.remaining, 32); for (let i = 0; i < 10; i++) shoe.draw(); assert.equal(shoe.remaining, 22); shoe.prepare(); assert.equal(shoe.remaining, 52); });
The test draws 20 cards from one deck and calls prepare: 32 remain, above the cut of 26, so nothing happens. Ten more draws leave 22, below the cut, and the next prepare rebuilds the shoe to 52. The second test checks the 6 to 5 payout.
✔ the shoe reshuffles between rounds past the cut (1.1318ms) ✔ six to five pays 22 chips back on a bet of 10 (0.1929ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output (durations vary)
Insurance is a third extension we did not build. It is offered when the dealer's face-up card is an ace, costs half the original bet and pays 2 to 1 if the hole card is worth 10, and it is settled apart from the main hand. It would add a stage between dealing and player turn and a second bet to the round, so it is a bigger change than a new policy. Naming the stage first, as the state machine did, shows where the work would go.
Where this design is weak
Every design has costs. One seat per table keeps the round simple, and several players would need a turn order across hands. Our round checks both hands for a natural after every deal. Published rules have the dealer look at the hole card only when the face-up card is an ace or a ten-value card. The outcome is the same, because a dealer natural always shows one of those, but a real table never shows the hole card early, and a screen that drew our round card by card would have to hide it. The Round class owns the stages, the actions and the finish, and would be the first thing to split if the rules grew. And history records stages for a reader, but does not guard anything: the guards are the checks at the top of each action.
| Term | Meaning |
|---|---|
| Shoe | A box of several shuffled decks that the dealer draws from |
| Natural | An ace and a ten-value card as the first two cards |
| Soft hand | A hand in which an ace is counting as 11 |
| Push | A tie, which returns the bet |
| Fisher-Yates | A shuffle that swaps each position with one at or before it |
Why does a 21 made by splitting aces pay 1 to 1?
- A natural needs the first two cards dealt, and a split hand is marked fromSplit, so its 21 is a plain win.
Why is a new payout rule a new class?
- The round asks the policy what a result pays, so the round never changes.
A CutShoe(1, random, 26) starts a round with 27 cards left, and the round uses 8. What happens before the next round, and why not during this one?
All chapters · Previous: Vending Machine: States, Payments and Making Change