Designing a Deck of Cards and Blackjack
Difficulty: Beginner Patterns: Flyweight, Factory, Iterator Asked at: Amazon, Adobe, PhonePe, Goldman Sachs
Build a deck, shuffle it, deal from a multi-deck shoe, and score a Blackjack hand. That is the whole scope, and it is a warm-up question only until the interviewer asks the second question: “there are six decks in the shoe, so how many Card objects did you just allocate?”
The first hard part is that a card has no identity, only a value. There are exactly 52 distinct cards in existence, and they never change, so a six-deck shoe should be 312 references to those 52 objects, not 312 objects. Build the 52 once in a static pool keyed by rank and suit, hand them out through a factory, and “is this the same card” collapses from a field-by-field compare into a pointer compare. This is the Flyweight pattern – that lesson’s own intrinsic-versus-extrinsic gloss names rank and suit as the textbook shared state, so link it and move on rather than re-deriving it here. The consequence is where candidates fall over: a shared Card must be deeply immutable, so a mutable faceUp flag cannot live on Card. It belongs on the hand’s view of the card. Put it on Card and turning the dealer’s hole card face up turns face up every copy of that card, in every hand, at every table in the process.
The second hard part is that dealing is iteration, and the cut card is why. The naive deal() pops the last element off a list and reshuffles when the list runs dry. A real shoe places a cut card at a random depth, keeps dealing straight past it to finish the current round, and only reshuffles at the next round boundary. So a shoe is not a stack – it is a cursor over a shuffled sequence with a reshuffle threshold, which is an Iterator carrying state. The interesting consequence is that hasNext() stops meaning “are there cards left” and starts meaning “are we still short of the cut card”, and next() is deliberately allowed to run past it.
Everything else is small. The one piece of real arithmetic in the whole problem is the ace: it is worth 1 or 11, whichever helps, so the Rank enum carries both values and the hand decides which one applies.
💡 A machine-coding round = a timed sitting, commonly around 90 minutes, where you build a small working program and are graded on class design and correctness far more than on algorithmic cleverness. Learn more →
💡 Interning = replacing a value you just built with the one canonical instance equal to it, so every holder of that value ends up pointing at the same object and == becomes a legal way to compare. Learn more →
💡 Shoe = the physical box a dealer deals from, holding several shuffled decks at once. Penetration = how deep into the shoe the dealer has got before reshuffling, expressed as a fraction of the total cards.
💡 Soft hand = a hand holding an ace that is currently being counted as 11, so one more card cannot bust it. Hard hand = every ace in it is counted as 1, so the total only goes up.
Functional Requirements
- Build a standard 52-card deck: 13 ranks across 4 suits, every one of the 52 distinct.
- Shuffle uniformly, and accept a seed so a deal can be reproduced exactly for a test or a dispute.
- A shoe of N decks deals one card at a time from a single shuffled sequence, in order.
- Place a cut card at a random depth; keep dealing past it until the round ends, then reshuffle.
- A hand holds the cards dealt to it plus each card’s face-up state, and scores itself with ace resolution.
- Blackjack rules: natural blackjack, bust, dealer stands on 17, and compare two finished hands to settle.
- Card identity is by value: two aces of spades are the same object, not two equal objects.
Non-Functional Requirements
- Memory is independent of shoe size – exactly 52
Cardinstances exist whether the shoe holds 1 deck or 8. A 312-card shoe is 312 references into the pool. - O(1) deal – a cursor increment and an indexed read, with no element shifting and no reallocation mid-shoe.
- Thread-safe sharing –
Cardand the pool are immutable after class initialisation, so any number of tables can read them concurrently with no locking. Mutable state is confined toShoeandHand, each owned by one table. - Shuffle correctness – every one of the
n!orderings must be equally likely, andequalsandhashCodemust agree so aCardis usable as a map key.
Core Entities
| Entity | Description |
|---|---|
Rank |
The 13 ranks. Each carries its Blackjack value, and ACE carries both 1 and 11 |
Suit |
The 4 suits. Pure identity plus a display glyph; no Blackjack meaning |
Card |
An immutable rank-and-suit pair. Exactly 52 instances exist for the life of the process |
Card.of |
The interning factory. The constructor is private, so no caller can mint a 53rd card |
Shoe |
N decks concatenated into one shuffled sequence, plus a cursor and a cut-card index |
Hand.HeldCard |
One card in one hand: a shared Card reference plus this hand’s faceUp bit |
Hand |
The cards one seat holds, and bestValue(), which resolves aces between 11 and 1 |
BlackjackRules |
isBlackjack, isBust, the dealer’s stand-on-17 policy, and settling two hands |
Outcome |
Enum: PLAYER_BLACKJACK, PLAYER_WIN, DEALER_WIN, PUSH |
Game |
Deals the opening round, accepts hit and stand, and asks the rules to settle |
💡 Value object = a small type with no identity of its own, compared by its contents rather than by which instance you are holding. Card is the purest example in this design: the four of clubs is the four of clubs, and there is no useful question “which four of clubs”.
💡 Hole card = the dealer’s second card, dealt face down. It is the reason faceUp has to be per hand: the same rank and suit may be sitting face up in someone else’s hand at the same moment.
52 cards, 312 references, and one cut card
The naive deck is one line of code and two bugs: it allocates a card per dealt card, and it hangs mutable state on the card.
Take the allocation first. for each deck, for each rank, for each suit, cards.add(new Card(rank, suit)) on a six-deck shoe constructs 312 objects that encode 52 values. The waste is real but modest at one table; the reason to care is not the bytes, it is what the duplication costs you downstream. With 312 unrelated instances, “did that ace of spades already come out of this shoe” is a field-by-field equals walk, new HashSet<>(shoe) only works once you have written equals and hashCode correctly, and a card-counting view has to compare values rather than pointers. Build the 52 once in a static pool, give Card a private constructor, and expose Card.of(rank, suit), and all three of those become pointer operations. The pool is 52 entries, built in a static initialiser, published unmodifiable, and never written again – which also makes it free to share across threads with no synchronisation.
Then the flag. The tempting shortcut is a boolean faceUp on Card, with card.reveal(). It reads beautifully and it is catastrophic the moment the pool exists: the dealer’s hole card and the ace of spades in seat three’s hand are the same object, so revealing one reveals both. Every table in the process shares that bug. The rule that falls out is the Flyweight rule stated as a constraint rather than an aspiration: whatever varies per use cannot live on the shared object. Rank and suit are intrinsic and shared; face-up state, which hand holds it, and what it is worth in this game are extrinsic and belong outside. Here that outside is Hand.HeldCard, a two-field wrapper the hand owns.
Now the shoe. A stack-shaped shoe – pop(), and if (empty) reshuffle() – gets the mechanics wrong in a way that matters for both correctness and for the follow-up questions. Real shoes are not dealt to the last card. A cut card goes in at a random depth, typically somewhere between 60% and 85% of the way down, and when the dealer reaches it the current round still gets its cards; the reshuffle happens after the round, between hands. That is three pieces of state, not one: the shuffled sequence, the cursor, and the cut index. The cursor is the whole mechanism – dealing is cards.get(cursor++), which is O(1), leaves the dealt prefix intact so penetration is derivable at any time, and makes the round reproducible from a seed.
Model it that way and hasNext() changes meaning. It is no longer “is the list non-empty” but “is the cursor still short of the cut card”, which is the question a table actually asks before starting a hand. next() is explicitly allowed to deal past the cut, which is why Shoe does not implement java.util.Iterator – that interface promises next() throws exactly when hasNext() is false, and a shoe breaks that promise on purpose. It is an iterator in shape, with its own contract, and saying so out loud is worth more in an interview than quietly implementing the wrong interface.
One correctness detail on the shuffle, because interviewers do ask. Use Fisher-Yates, which in Java means Collections.shuffle(cards, random). The loop people write from memory – “for each index i, swap cards[i] with cards[random(0, n)]” – is subtly wrong, not merely slower. It makes n independent choices from n options, so there are n^n equally likely runs mapping onto n! orderings, and n! does not divide n^n. For a three-card deck that is 27 equally likely runs spread over 6 orderings, so some orderings come up more often than others. Fisher-Yates fixes it by drawing index i from only the unshuffled remainder, giving exactly n! equally likely runs. This is a correctness argument, not a benchmark.
classDiagram
class Rank {
<<enumeration>>
-String label
-int lowValue
+highValue() int
+isAce() boolean
}
class Suit {
<<enumeration>>
-String glyph
}
class Card {
-Rank rank
-Suit suit
-Map POOL
+of(Rank, Suit) Card
+fullDeck() List~Card~
+equals(Object) boolean
+hashCode() int
}
class Shoe {
-List~Card~ cards
-int cursor
-int cutIndex
+shuffle()
+deal() Card
+hasNext() boolean
+needsReshuffle() boolean
+penetration() double
}
class HeldCard {
-Card card
-boolean faceUp
+reveal()
}
class Hand {
-List~HeldCard~ held
+add(Card, boolean)
+bestValue() int
+isSoft() boolean
}
class BlackjackRules {
-int dealerStandsOn
+isBlackjack(Hand) boolean
+isBust(Hand) boolean
+dealerShouldHit(Hand) boolean
+settle(Hand, Hand) Outcome
}
class Game {
-Shoe shoe
-BlackjackRules rules
+deal()
+hit() boolean
+stand() Outcome
}
Card --> Rank
Card --> Suit
Shoe --> Card
Hand --> HeldCard
HeldCard --> Card
Game --> Shoe
Game --> Hand
Game --> BlackjackRules
💡 In a class diagram the plain arrow means “holds a reference to”. Read Shoe --> Card and HeldCard --> Card as the many-to-one arrows they are: hundreds of references converging on 52 objects, with nothing on Card that lets a holder write back through the arrow. Learn more →
Key classes:
Rank– the 13 ranks with their Blackjack values attached. It carrieslowValue()andhighValue()so the ace’s dual nature is data on the enum rather than anif (rank == ACE)scattered through the scoring code. It does not decide which value applies.Suit– four values and a glyph. It exists so a card’s identity is two enums rather than a parsed string, which is what makes the pool key trivial.Card– the flyweight. Final class, private constructor, two final enum fields, and a static 52-entry pool it publishes throughCard.of. It owns the guarantee that equal cards are identical cards.Shoe– the only mutable thing in the dealing path. It owns the shuffled sequence, the cursor, and the cut index, and it is the single place that answers “deal me a card” and “are we due a reshuffle”.Hand.HeldCard– the extrinsic half of a card: one sharedCardplus this hand’sfaceUpbit. It exists purely soCardcan stay immutable.Hand– the cards one seat holds plus the ace resolution inbestValue(). This is the class with actual logic in it, and the one an interviewer will read line by line.BlackjackRules– every house rule in one object: what counts as a natural, what busts, when the dealer stands, and who wins. Swapping this object swaps the game.Game– the round orchestrator. It checks the cut card at the round boundary, deals the opening four cards with the hole card face down, and routes hit and stand into the rules.
Design Patterns
| Pattern | Where | Why |
|---|---|---|
| Flyweight | The static 52-entry pool inside Card |
A six-deck shoe holds 312 references to 52 objects, so card identity is a pointer compare |
| Factory | Card.of(rank, suit) |
The constructor is private, so there is no way to obtain an un-interned card by accident |
| Iterator | Shoe’s cursor, hasNext and next |
Dealing is a position in a shuffled sequence; the cut card is iterator state, not a special case |
| Strategy | The shuffle algorithm, and BlackjackRules itself |
Swap Fisher-Yates for a seeded or riffle shuffle, or swap the whole rules object to deal a different game from the same shoe |
| Builder (extension) | ShoeBuilder |
Deck count, penetration band, shuffler and seed are four optional knobs; a builder beats four overloaded constructors |
💡 Flyweight pattern = share one immutable instance per distinct value and keep the per-use state outside it. Here the split is exact: rank and suit are shared, face-up state and ownership sit on Hand.HeldCard.
💡 Factory pattern = put object creation behind a method that decides what to return. Card.of never constructs anything after class initialisation; it is a pool lookup wearing a constructor’s clothes.
💡 Iterator pattern = make traversal an object that owns a position, so the collection keeps its storage private. The shoe’s twist is that its hasNext() is about the cut card rather than the end of the list, which is why it defines its own contract instead of implementing java.util.Iterator.
💡 Strategy pattern = one interface, interchangeable implementations chosen by the caller. Two seams use it here: how the shoe is randomised, and which game’s rules score the hands.
💡 Builder pattern = assemble an object through named steps when it has several optional settings. new Shoe(6, rng, 0.60, 0.85) is already hard to read at the call site; ShoeBuilder is the fix if a fifth knob arrives.
Data Structures
| Component | Structure | Why |
|---|---|---|
| Card pool | HashMap of 52 entries, key rank.ordinal() * 4 + suit.ordinal(), built in a static block |
O(1) lookup, built once, published unmodifiable so every thread can read it without a lock |
| Shoe contents | ArrayList<Card> holding deckCount * 52 references |
O(1) indexed read, and an 8-deck shoe costs 416 pointers rather than 416 objects |
| Deal position | a single int cursor |
O(1) deal with no shifting, and the dealt prefix stays in place so penetration is derivable |
| Cut card | a single int cutIndex |
“Are we due a reshuffle” is one integer compare, and the threshold is data rather than control flow |
| Hand | ArrayList<HeldCard>, initial capacity 11 |
Insertion order is display order, and 11 cards is the true maximum for a Blackjack hand |
| Ace resolution | running total plus a highAces counter |
One pass, then at most four demotions. No subset search over which aces count as 11 |
The consequential choice is the cursor. deal() as cards.get(cursor++) instead of cards.remove(0) is the difference between O(1) and O(n) per card – removing from the front of an ArrayList shifts every remaining element – but the complexity is the smaller half of it. Keeping the dealt cards in the list is what makes the other requirements expressible at all: penetration is cursor / size, the cut card is an index into the same list, “what came out this shoe” is the prefix [0, cursor), and replaying a round means reseeding and re-reading the same indices. A pop-shaped shoe throws all of that away one card at a time.
💡 Penetration = cursor / size, the fraction of the shoe already dealt. It is the number the cut card encodes, and the number a counting player cares about, which is why the shoe exposes it rather than hiding it behind “cards remaining”.
Complete Code
Rank.java
The 13 ranks with their Blackjack values attached. The ace is the only rank worth two different amounts, so it carries both and refuses to choose – lowValue() is 1, highValue() is 11, and the hand resolves which one applies.
package cards.model;
public enum Rank {
TWO("2", 2), THREE("3", 3), FOUR("4", 4), FIVE("5", 5),
SIX("6", 6), SEVEN("7", 7), EIGHT("8", 8), NINE("9", 9),
TEN("10", 10), JACK("J", 10), QUEEN("Q", 10), KING("K", 10),
ACE("A", 1);
private final String label;
private final int lowValue;
Rank(String label, int lowValue) {
this.label = label;
this.lowValue = lowValue;
}
public String label() { return label; }
/** The value this rank always contributes. For ACE this is the hard 1. */
public int lowValue() { return lowValue; }
/** The most this rank can contribute. Differs from lowValue only for ACE. */
public int highValue() { return this == ACE ? 11 : lowValue; }
public boolean isAce() { return this == ACE; }
@Override public String toString() { return label; }
}
from enum import Enum
class Rank(Enum):
"""(label, low_value). ACE is the only rank worth two amounts, so it carries
both and lets the hand choose; nothing here knows the rest of the hand."""
TWO = ("2", 2)
THREE = ("3", 3)
FOUR = ("4", 4)
FIVE = ("5", 5)
SIX = ("6", 6)
SEVEN = ("7", 7)
EIGHT = ("8", 8)
NINE = ("9", 9)
TEN = ("10", 10)
JACK = ("J", 10)
QUEEN = ("Q", 10)
KING = ("K", 10)
ACE = ("A", 1)
def __init__(self, label: str, low_value: int) -> None:
self.label = label
self.low_value = low_value
self.is_ace = label == "A"
self.high_value = 11 if self.is_ace else low_value
def __str__(self) -> str:
return self.label
#pragma once
#include <string>
enum class Rank {
Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace
};
// Free functions keep Rank a plain enum class while holding the values in one
// place. Indexed by the enumerator, so the tables cannot drift out of order.
inline int lowValue(Rank r) {
static const int values[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1 };
return values[static_cast<int>(r)];
}
inline bool isAce(Rank r) { return r == Rank::Ace; }
inline int highValue(Rank r) { return isAce(r) ? 11 : lowValue(r); }
inline std::string label(Rank r) {
static const char* labels[] = {
"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"
};
return labels[static_cast<int>(r)];
}
// Frozen objects stand in for Java enums: one instance per rank, never written.
const RANK_TABLE = [
["TWO", "2", 2], ["THREE", "3", 3], ["FOUR", "4", 4], ["FIVE", "5", 5],
["SIX", "6", 6], ["SEVEN", "7", 7], ["EIGHT", "8", 8], ["NINE", "9", 9],
["TEN", "10", 10], ["JACK", "J", 10], ["QUEEN", "Q", 10], ["KING", "K", 10],
["ACE", "A", 1],
];
const Rank = Object.freeze(Object.fromEntries(
RANK_TABLE.map(([name, label, low]) => {
const isAce = label === "A";
return [name, Object.freeze({ name, label, low, high: isAce ? 11 : low, isAce })];
})
));
const RANKS = Object.freeze(Object.values(Rank));
Suit.java
Four values and a glyph. A suit has no Blackjack meaning at all; it exists so a card’s identity is two enums rather than a parsed string, which is what makes the pool key one multiply and one add.
package cards.model;
public enum Suit {
// Unicode escapes rather than literal glyphs, so the source survives any
// file encoding: club, diamond, heart, spade.
CLUBS("c", "\u2663"),
DIAMONDS("d", "\u2666"),
HEARTS("h", "\u2665"),
SPADES("s", "\u2660");
private final String code;
private final String glyph;
Suit(String code, String glyph) {
this.code = code;
this.glyph = glyph;
}
public String code() { return code; }
public String glyph() { return glyph; }
@Override public String toString() { return glyph; }
}
from enum import Enum
class Suit(Enum):
CLUBS = ("c", "\u2663")
DIAMONDS = ("d", "\u2666")
HEARTS = ("h", "\u2665")
SPADES = ("s", "\u2660")
def __init__(self, code: str, glyph: str) -> None:
self.code = code
self.glyph = glyph
def __str__(self) -> str:
return self.glyph
#pragma once
#include <string>
enum class Suit { Clubs, Diamonds, Hearts, Spades };
inline std::string glyph(Suit s) {
static const char* glyphs[] = { "\u2663", "\u2666", "\u2665", "\u2660" };
return glyphs[static_cast<int>(s)];
}
inline std::string code(Suit s) {
static const char* codes[] = { "c", "d", "h", "s" };
return codes[static_cast<int>(s)];
}
function makeSuit(name, code, glyph) {
return Object.freeze({ name, code, glyph });
}
const Suit = Object.freeze({
CLUBS: makeSuit("CLUBS", "c", "\u2663"),
DIAMONDS: makeSuit("DIAMONDS", "d", "\u2666"),
HEARTS: makeSuit("HEARTS", "h", "\u2665"),
SPADES: makeSuit("SPADES", "s", "\u2660"),
});
const SUITS = Object.freeze(Object.values(Suit));
Card.java
The flyweight, and the class an interviewer will look at first. Final class, private constructor, two final enum fields, and a static 52-entry pool published through Card.of. Because the pool is the only source of instances, equal cards are identical cards and == is a legal comparison.
package cards.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A card is a value, not an entity. There are exactly 52 of them, they never
* change, and two aces of spades are not merely equal -- they are the same
* object. The constructor is private, the 52 instances are built once into a
* static pool, and of() hands out references into it, so a six-deck shoe is
* 312 pointers to 52 objects.
*
* Nothing mutable may ever be added to this class. Whether a card is face up
* belongs to the hand holding it, not to the card: see Hand.HeldCard.
*/
public final class Card implements Comparable<Card> {
/** Key = rank.ordinal() * 4 + suit.ordinal(), so keys are 0..51 and unique. */
private static final Map<Integer, Card> POOL;
static {
Map<Integer, Card> pool = new HashMap<>(64);
for (Rank rank : Rank.values()) {
for (Suit suit : Suit.values()) {
pool.put(key(rank, suit), new Card(rank, suit));
}
}
// Published once and never written again, which is what makes the pool
// readable from any number of threads with no synchronisation.
POOL = Collections.unmodifiableMap(pool);
}
private final Rank rank;
private final Suit suit;
/** Private: the 52 cards already exist, and nobody gets to mint a 53rd. */
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
private static int key(Rank rank, Suit suit) {
return rank.ordinal() * Suit.values().length + suit.ordinal();
}
/** The interning factory. Always returns the one shared instance for this value. */
public static Card of(Rank rank, Suit suit) {
Card card = POOL.get(key(rank, suit));
if (card == null) {
throw new IllegalArgumentException("no such card: " + rank + suit);
}
return card;
}
/** One deck: 52 references in rank-then-suit order, and zero new Card objects. */
public static List<Card> fullDeck() {
List<Card> deck = new ArrayList<>(52);
for (Rank rank : Rank.values()) {
for (Suit suit : Suit.values()) {
deck.add(of(rank, suit));
}
}
return deck;
}
/** Always 52, however many decks are in play. Worth asserting in a test. */
public static int distinctCards() { return POOL.size(); }
public Rank rank() { return rank; }
public Suit suit() { return suit; }
/**
* Value equality, so a Card is a legal HashMap key and HashSet member.
* Since the pool is the only source of instances, the field compare is
* only reachable by a Card that arrived through deserialisation -- the
* identity check on the first line is the real path.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Card)) return false;
Card other = (Card) o;
return rank == other.rank && suit == other.suit;
}
/** 0..51 and collision-free, so a 64-bucket map never chains. */
@Override public int hashCode() { return key(rank, suit); }
/** Rank first, then suit. Enough for a stable display order in a hand. */
@Override
public int compareTo(Card other) {
int byRank = Integer.compare(rank.ordinal(), other.rank.ordinal());
return byRank != 0 ? byRank : Integer.compare(suit.ordinal(), other.suit.ordinal());
}
@Override public String toString() { return rank.label() + suit.glyph(); }
}
from dataclasses import dataclass
from functools import lru_cache
from typing import List
@dataclass(frozen=True, slots=True)
class Card:
"""frozen=True buys immutability plus __eq__ and __hash__ in one line.
Build cards only through Card.of, so every holder shares one instance."""
rank: Rank
suit: Suit
@staticmethod
@lru_cache(maxsize=None)
def of(rank: Rank, suit: Suit) -> "Card":
# lru_cache IS the pool. The first call per (rank, suit) constructs,
# every later call returns that same object, so
# Card.of(ACE, SPADES) is Card.of(ACE, SPADES) evaluates True.
return Card(rank, suit)
@staticmethod
def full_deck() -> List["Card"]:
return [Card.of(r, s) for r in Rank for s in Suit]
@staticmethod
def distinct_cards() -> int:
return Card.of.cache_info().currsize
def __str__(self) -> str:
return f"{self.rank.label}{self.suit.glyph}"
#pragma once
#include <string>
#include <vector>
#include "Rank.h"
#include "Suit.h"
/**
* Immutable value with a private constructor. of() returns a const reference
* into one static 52-entry pool, so a six-deck shoe stores 312 pointers.
*/
class Card {
Rank rank_;
Suit suit_;
Card(Rank r, Suit s) : rank_(r), suit_(s) {}
static std::vector<Card> build() {
std::vector<Card> p;
p.reserve(52);
for (int r = 0; r < 13; ++r)
for (int s = 0; s < 4; ++s)
p.push_back(Card(static_cast<Rank>(r), static_cast<Suit>(s)));
return p;
}
/** Function-local static: built once, thread-safe initialisation since C++11. */
static const std::vector<Card>& pool() {
static const std::vector<Card> p = build();
return p;
}
static int key(Rank r, Suit s) {
return static_cast<int>(r) * 4 + static_cast<int>(s);
}
public:
static const Card& of(Rank r, Suit s) { return pool()[key(r, s)]; }
/** A deck is 52 pointers into the pool. Copying Cards would defeat the point. */
static std::vector<const Card*> fullDeck() {
std::vector<const Card*> deck;
deck.reserve(52);
for (int r = 0; r < 13; ++r)
for (int s = 0; s < 4; ++s)
deck.push_back(&of(static_cast<Rank>(r), static_cast<Suit>(s)));
return deck;
}
static std::size_t distinctCards() { return pool().size(); }
Rank rank() const { return rank_; }
Suit suit() const { return suit_; }
bool operator==(const Card& o) const { return rank_ == o.rank_ && suit_ == o.suit_; }
std::string toString() const { return label(rank_) + glyph(suit_); }
};
// The pool is module-private: no code outside this file can reach it.
const POOL = new Map();
class Card {
static #sealed = false;
constructor(rank, suit) {
if (Card.#sealed) {
throw new Error("use Card.of(rank, suit) -- the 52 cards already exist");
}
this.rank = rank;
this.suit = suit;
Object.freeze(this); // shared, therefore unwritable
}
static #key(rank, suit) {
return rank.name + ":" + suit.name;
}
/** The interning factory: a Map lookup wearing a constructor's clothes. */
static of(rank, suit) {
const card = POOL.get(Card.#key(rank, suit));
if (!card) throw new Error("no such card: " + rank.label + suit.code);
return card;
}
static fullDeck() {
return RANKS.flatMap((r) => SUITS.map((s) => Card.of(r, s)));
}
static get distinctCards() {
return POOL.size;
}
toString() {
return this.rank.label + this.suit.glyph;
}
// Static initialisation block: build the 52, then close the door.
static {
for (const r of RANKS) {
for (const s of SUITS) {
POOL.set(Card.#key(r, s), new Card(r, s));
}
}
Card.#sealed = true;
}
}
Shoe.java
N decks concatenated into one shuffled sequence, plus a cursor and a cut-card index. Note the deliberate split between hasNext() – “can the table start another hand without reshuffling” – and canDeal(), which is the only method that cares whether any cards physically remain.
package cards.shoe;
import cards.model.Card;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* N decks as one shuffled sequence with a cursor over it. Dealing is iteration:
* deal() is an indexed read plus a cursor bump, O(1), and the list never shrinks.
*
* The cut card sits at a random depth inside a penetration band. Crossing it
* does NOT stop the deal -- the round in progress finishes, and the table calls
* needsReshuffle() at the next round boundary.
*
* This is an iterator in shape but deliberately NOT a java.util.Iterator: that
* interface promises next() throws exactly when hasNext() is false, and here
* hasNext() is about the cut card while deal() is allowed to run past it.
*/
public class Shoe {
private static final int CARDS_PER_DECK = 52;
private final int deckCount;
private final List<Card> cards; // references into Card's pool, not copies
private final Random random;
private final double minPenetration;
private final double maxPenetration;
private int cursor; // index of the next card to deal
private int cutIndex; // the cut card sits in front of this index
/** House default: reshuffle somewhere between 60% and 85% of the way down. */
public Shoe(int deckCount, Random random) {
this(deckCount, random, 0.60, 0.85);
}
public Shoe(int deckCount, Random random, double minPenetration, double maxPenetration) {
if (deckCount < 1) {
throw new IllegalArgumentException("a shoe needs at least one deck");
}
if (minPenetration <= 0 || maxPenetration > 1 || minPenetration >= maxPenetration) {
throw new IllegalArgumentException("need 0 < min < max <= 1 for the penetration band");
}
this.deckCount = deckCount;
this.random = random;
this.minPenetration = minPenetration;
this.maxPenetration = maxPenetration;
this.cards = new ArrayList<>(deckCount * CARDS_PER_DECK);
for (int d = 0; d < deckCount; d++) {
cards.addAll(Card.fullDeck()); // 52 more references; still only 52 objects
}
shuffle();
}
/**
* Fisher-Yates, by way of Collections.shuffle: walk from the end and swap
* each element with a random index drawn from the unshuffled prefix. All n!
* orderings come out equally likely.
*
* The loop people write from memory -- "for each i, swap cards[i] with
* cards[random(0, n)]" -- is not uniform. It makes n independent choices
* from n options, so n^n equally likely runs map onto n! orderings, and n!
* does not divide n^n. Some orderings are strictly more likely. That is a
* correctness bug, not a performance one.
*/
public final void shuffle() {
Collections.shuffle(cards, random);
cursor = 0;
int lo = (int) Math.floor(cards.size() * minPenetration);
int hi = (int) Math.floor(cards.size() * maxPenetration);
cutIndex = lo + random.nextInt(Math.max(1, hi - lo));
}
/**
* "Is the cursor still short of the cut card?" -- the question a table asks
* before starting a hand. This is NOT about running out of cards.
*/
public boolean hasNext() { return cursor < cutIndex; }
/** The cut card has been passed, so this shoe is due a reshuffle after the round. */
public boolean needsReshuffle() { return !hasNext(); }
/** Physical exhaustion. Only false if one round somehow ran to the last card. */
public boolean canDeal() { return cursor < cards.size(); }
/** O(1). Deals past the cut card on purpose: the round finishes first. */
public Card deal() {
if (!canDeal()) {
throw new NoSuchElementException("shoe exhausted -- shuffle before dealing");
}
return cards.get(cursor++);
}
/** The prefix already dealt, which is exactly what a counting view would read. */
public List<Card> dealtSoFar() {
return List.copyOf(cards.subList(0, cursor));
}
public double penetration() { return (double) cursor / cards.size(); }
public int dealtCount() { return cursor; }
public int remaining() { return cards.size() - cursor; }
public int cutIndex() { return cutIndex; }
public int size() { return cards.size(); }
public int deckCount() { return deckCount; }
}
import random as rnd
from typing import List
class Shoe:
"""N decks as one shuffled sequence plus a cursor. Card is as in the Java
tab. random.shuffle is Fisher-Yates; pass a seeded Random to reproduce a deal."""
def __init__(self, deck_count: int, rng: rnd.Random,
min_pen: float = 0.60, max_pen: float = 0.85) -> None:
if deck_count < 1:
raise ValueError("a shoe needs at least one deck")
if not (0 < min_pen < max_pen <= 1):
raise ValueError("need 0 < min < max <= 1 for the penetration band")
self._rng, self._min_pen, self._max_pen = rng, min_pen, max_pen
# References, not copies: 6 * 52 entries over 52 objects.
self._cards: List[Card] = [c for _ in range(deck_count) for c in Card.full_deck()]
self._cursor = 0
self._cut_index = 0
self.shuffle()
def shuffle(self) -> None:
self._rng.shuffle(self._cards) # Fisher-Yates, uniform over all n! orderings
self._cursor = 0
lo = int(len(self._cards) * self._min_pen)
hi = int(len(self._cards) * self._max_pen)
self._cut_index = lo + self._rng.randrange(max(1, hi - lo))
def has_next(self) -> bool:
"""Still short of the cut card, so another hand may start."""
return self._cursor < self._cut_index
def needs_reshuffle(self) -> bool:
return not self.has_next()
def can_deal(self) -> bool:
"""Physical exhaustion, which is a different question entirely."""
return self._cursor < len(self._cards)
def deal(self) -> Card:
if not self.can_deal():
raise IndexError("shoe exhausted -- shuffle before dealing")
card = self._cards[self._cursor]
self._cursor += 1
return card
def dealt_so_far(self) -> tuple:
return tuple(self._cards[:self._cursor])
@property
def penetration(self) -> float:
return self._cursor / len(self._cards)
@property
def dealt_count(self) -> int:
return self._cursor
@property
def remaining(self) -> int:
return len(self._cards) - self._cursor
@property
def cut_index(self) -> int:
return self._cut_index
def __len__(self) -> int:
return len(self._cards)
#pragma once
#include <algorithm>
#include <random>
#include <stdexcept>
#include <vector>
#include "Card.h"
/**
* Holds pointers into Card's pool, so an 8-deck shoe is 416 pointers over
* 52 objects. std::shuffle is Fisher-Yates.
*/
class Shoe {
std::vector<const Card*> cards_;
std::mt19937 rng_;
double minPen_, maxPen_;
std::size_t cursor_ = 0;
std::size_t cutIndex_ = 0;
public:
Shoe(int deckCount, std::uint32_t seed, double minPen = 0.60, double maxPen = 0.85)
: rng_(seed), minPen_(minPen), maxPen_(maxPen) {
if (deckCount < 1) throw std::invalid_argument("a shoe needs at least one deck");
cards_.reserve(static_cast<std::size_t>(deckCount) * 52);
for (int d = 0; d < deckCount; ++d) {
auto deck = Card::fullDeck();
cards_.insert(cards_.end(), deck.begin(), deck.end());
}
shuffle();
}
void shuffle() {
std::shuffle(cards_.begin(), cards_.end(), rng_);
cursor_ = 0;
auto lo = static_cast<std::size_t>(cards_.size() * minPen_);
auto hi = static_cast<std::size_t>(cards_.size() * maxPen_);
std::uniform_int_distribution<std::size_t> pick(0, hi > lo ? hi - lo - 1 : 0);
cutIndex_ = lo + pick(rng_);
}
/** Short of the cut card, not "cards remain". */
bool hasNext() const { return cursor_ < cutIndex_; }
bool needsReshuffle() const { return !hasNext(); }
bool canDeal() const { return cursor_ < cards_.size(); }
const Card& deal() {
if (!canDeal()) throw std::out_of_range("shoe exhausted -- shuffle before dealing");
return *cards_[cursor_++];
}
double penetration() const {
return static_cast<double>(cursor_) / static_cast<double>(cards_.size());
}
std::size_t dealtCount() const { return cursor_; }
std::size_t remaining() const { return cards_.size() - cursor_; }
std::size_t cutIndex() const { return cutIndex_; }
std::size_t size() const { return cards_.size(); }
};
// Math.random cannot be seeded, so a tiny deterministic PRNG goes in instead.
// A reproducible deal is a requirement, not a nicety: it is how a disputed
// round gets replayed.
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a = (a + 0x6D2B79F5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
class Shoe {
#cards;
#cursor = 0;
#cutIndex = 0;
#rand;
#minPen;
#maxPen;
constructor(deckCount, seed = 42, minPen = 0.60, maxPen = 0.85) {
if (deckCount < 1) throw new Error("a shoe needs at least one deck");
this.#rand = mulberry32(seed);
this.#minPen = minPen;
this.#maxPen = maxPen;
this.#cards = [];
for (let d = 0; d < deckCount; d++) {
this.#cards.push(...Card.fullDeck()); // references, not copies
}
this.shuffle();
}
/** Fisher-Yates written out: index j is drawn only from the unshuffled prefix. */
shuffle() {
const a = this.#cards;
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(this.#rand() * (i + 1));
const tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
this.#cursor = 0;
const lo = Math.floor(a.length * this.#minPen);
const hi = Math.floor(a.length * this.#maxPen);
this.#cutIndex = lo + Math.floor(this.#rand() * Math.max(1, hi - lo));
}
hasNext() { return this.#cursor < this.#cutIndex; } // the cut card question
needsReshuffle() { return !this.hasNext(); }
canDeal() { return this.#cursor < this.#cards.length; } // the empty question
deal() {
if (!this.canDeal()) throw new Error("shoe exhausted -- shuffle before dealing");
return this.#cards[this.#cursor++];
}
dealtSoFar() { return this.#cards.slice(0, this.#cursor); }
get penetration() { return this.#cursor / this.#cards.length; }
get dealtCount() { return this.#cursor; }
get remaining() { return this.#cards.length - this.#cursor; }
get cutIndex() { return this.#cutIndex; }
get size() { return this.#cards.length; }
}
Hand.java
The hand owns everything per-use about a card, which is what lets Card stay shared and immutable. bestValue() is the one method in this design with real logic in it: count every ace as 11, then demote aces to 1 one at a time while the total is busting.
package cards.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Hand {
/**
* This hand's view of one dealt card: the shared Card plus the bits that
* are true of this hand only. faceUp lives here and not on Card because
* the same Card instance may be face down in front of the dealer and face
* up in seat three at the same moment.
*/
public static final class HeldCard {
private final Card card; // shared, immutable
private boolean faceUp; // per hand, mutable
HeldCard(Card card, boolean faceUp) {
this.card = card;
this.faceUp = faceUp;
}
public Card card() { return card; }
public boolean isFaceUp() { return faceUp; }
public void reveal() { faceUp = true; }
@Override public String toString() { return faceUp ? card.toString() : "[??]"; }
}
// 11 is the true maximum for a Blackjack hand: four aces, four twos and
// three threes reach exactly 21.
private final List<HeldCard> held = new ArrayList<>(11);
public void add(Card card, boolean faceUp) { held.add(new HeldCard(card, faceUp)); }
public void add(Card card) { add(card, true); }
public List<HeldCard> cards() { return Collections.unmodifiableList(held); }
public int size() { return held.size(); }
public void revealAll() { held.forEach(HeldCard::reveal); }
/**
* Returns [total, acesStillCountedAsEleven].
*
* Count every ace as 11 first, then demote one ace at a time from 11 to 1
* while the total is over 21. Each demotion costs exactly 10, so the first
* total at or under 21 is the best this hand can claim; if no demotion
* saves it, the fully hard total comes back and the caller sees the bust.
* One pass plus at most four demotions, so O(n) with no search over which
* subset of aces counts high.
*/
private int[] resolve() {
int total = 0;
int highAces = 0;
for (HeldCard h : held) {
Rank rank = h.card().rank();
total += rank.highValue(); // ACE contributes 11 at this point
if (rank.isAce()) highAces++;
}
while (total > 21 && highAces > 0) {
total -= 10; // demote one ace from 11 to 1
highAces--;
}
return new int[] { total, highAces };
}
/** The best total this hand can claim, or the hard total if it busts either way. */
public int bestValue() { return resolve()[0]; }
/** True while an ace still counts as 11, so one more card cannot bust the hand. */
public boolean isSoft() { return resolve()[1] > 0; }
/** Two cards of the same rank: the precondition for a split. */
public boolean isPair() {
return held.size() == 2
&& held.get(0).card().rank() == held.get(1).card().rank();
}
@Override
public String toString() {
String shown = held.stream().map(HeldCard::toString).collect(Collectors.joining(" "));
boolean anyHidden = held.stream().anyMatch(h -> !h.isFaceUp());
if (anyHidden) return shown + " (value hidden)";
return shown + " = " + bestValue() + (isSoft() ? " soft" : " hard");
}
}
from dataclasses import dataclass
from typing import List, Tuple
@dataclass(slots=True)
class HeldCard:
"""Mutable on purpose, and separate from Card on purpose."""
card: Card
face_up: bool = True
def reveal(self) -> None:
self.face_up = True
def __str__(self) -> str:
return str(self.card) if self.face_up else "[??]"
class Hand:
def __init__(self) -> None:
self._held: List[HeldCard] = []
def add(self, card: Card, face_up: bool = True) -> None:
self._held.append(HeldCard(card, face_up))
@property
def cards(self) -> Tuple[HeldCard, ...]:
return tuple(self._held)
def reveal_all(self) -> None:
for h in self._held:
h.reveal()
def _resolve(self) -> Tuple[int, int]:
"""(total, aces_still_counted_as_eleven). Every ace starts at 11, then
demotes to 1 one at a time while the total busts."""
total = 0
high_aces = 0
for h in self._held:
total += h.card.rank.high_value
if h.card.rank.is_ace:
high_aces += 1
while total > 21 and high_aces > 0:
total -= 10
high_aces -= 1
return total, high_aces
def best_value(self) -> int:
return self._resolve()[0]
def is_soft(self) -> bool:
return self._resolve()[1] > 0
def is_pair(self) -> bool:
return len(self._held) == 2 and self._held[0].card.rank is self._held[1].card.rank
def __len__(self) -> int:
return len(self._held)
def __str__(self) -> str:
shown = " ".join(str(h) for h in self._held)
if any(not h.face_up for h in self._held):
return f"{shown} (value hidden)"
texture = "soft" if self.is_soft() else "hard"
return f"{shown} = {self.best_value()} {texture}"
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "Card.h"
/** The shared Card plus this hand's own mutable bit. */
struct HeldCard {
const Card* card;
bool faceUp;
std::string toString() const { return faceUp ? card->toString() : "[??]"; }
};
class Hand {
std::vector<HeldCard> held_;
/** (total, acesStillCountedAsEleven) */
std::pair<int, int> resolve() const {
int total = 0;
int highAces = 0;
for (const auto& h : held_) {
total += highValue(h.card->rank());
if (isAce(h.card->rank())) ++highAces;
}
while (total > 21 && highAces > 0) {
total -= 10;
--highAces;
}
return { total, highAces };
}
public:
Hand() { held_.reserve(11); }
void add(const Card& card, bool faceUp = true) {
HeldCard h;
h.card = &card;
h.faceUp = faceUp;
held_.push_back(h);
}
void revealAll() {
for (auto& h : held_) h.faceUp = true;
}
int bestValue() const { return resolve().first; }
bool isSoft() const { return resolve().second > 0; }
std::size_t size() const { return held_.size(); }
const std::vector<HeldCard>& cards() const { return held_; }
std::string toString() const {
std::string shown;
bool anyHidden = false;
for (const auto& h : held_) {
if (!shown.empty()) shown += " ";
shown += h.toString();
if (!h.faceUp) anyHidden = true;
}
if (anyHidden) return shown + " (value hidden)";
return shown + " = " + std::to_string(bestValue()) + (isSoft() ? " soft" : " hard");
}
};
class HeldCard {
constructor(card, faceUp = true) {
this.card = card; // shared, frozen
this.faceUp = faceUp; // per hand, mutable
}
reveal() { this.faceUp = true; }
toString() { return this.faceUp ? this.card.toString() : "[??]"; }
}
class Hand {
#held = [];
add(card, faceUp = true) { this.#held.push(new HeldCard(card, faceUp)); }
get cards() { return [...this.#held]; }
get size() { return this.#held.length; }
revealAll() {
for (const h of this.#held) h.reveal();
}
/** [total, acesStillCountedAsEleven] */
#resolve() {
let total = 0;
let highAces = 0;
for (const h of this.#held) {
total += h.card.rank.high;
if (h.card.rank.isAce) highAces++;
}
while (total > 21 && highAces > 0) {
total -= 10;
highAces--;
}
return [total, highAces];
}
bestValue() { return this.#resolve()[0]; }
isSoft() { return this.#resolve()[1] > 0; }
toString() {
const shown = this.#held.map((h) => h.toString()).join(" ");
if (this.#held.some((h) => !h.faceUp)) return shown + " (value hidden)";
return shown + " = " + this.bestValue() + (this.isSoft() ? " soft" : " hard");
}
}
BlackjackRules.java
Every house rule in one object: what counts as a natural, what busts, when the dealer stands, and who wins. Game depends on this rather than inlining 21, which is what makes “now deal Baccarat from the same shoe” a new class instead of a rewrite.
package cards.rules;
import cards.model.Hand;
public class BlackjackRules {
public static final int TARGET = 21;
public enum Outcome {
PLAYER_BLACKJACK("player blackjack, pays 3 to 2"),
PLAYER_WIN("player wins"),
DEALER_WIN("dealer wins"),
PUSH("push, bet returned");
private final String description;
Outcome(String description) { this.description = description; }
public String description() { return description; }
}
private final int dealerStandsOn;
private final boolean dealerHitsSoft17;
/** The common table rule: stand on 17, including soft 17. */
public BlackjackRules() { this(17, false); }
public BlackjackRules(int dealerStandsOn, boolean dealerHitsSoft17) {
this.dealerStandsOn = dealerStandsOn;
this.dealerHitsSoft17 = dealerHitsSoft17;
}
/** A natural: exactly two cards totalling 21. Three cards to 21 is 21, not a blackjack. */
public boolean isBlackjack(Hand hand) {
return hand.size() == 2 && hand.bestValue() == TARGET;
}
public boolean isBust(Hand hand) { return hand.bestValue() > TARGET; }
/** The player may act while not busted and not already sitting on 21. */
public boolean canAct(Hand hand) {
return !isBust(hand) && hand.bestValue() < TARGET;
}
/**
* The dealer has no choices, only a policy, and this is the only place it
* lives: draw below the stand threshold, and optionally draw on soft 17.
*/
public boolean dealerShouldHit(Hand dealer) {
int value = dealer.bestValue();
if (value < dealerStandsOn) return true;
return dealerHitsSoft17 && value == dealerStandsOn && dealer.isSoft();
}
/** Settle a finished round from the player's point of view. The order matters. */
public Outcome settle(Hand player, Hand dealer) {
boolean playerNatural = isBlackjack(player);
boolean dealerNatural = isBlackjack(dealer);
if (playerNatural && dealerNatural) return Outcome.PUSH;
if (playerNatural) return Outcome.PLAYER_BLACKJACK;
if (dealerNatural) return Outcome.DEALER_WIN;
// The player acts first, so a player bust pays the house even when the
// dealer would have gone on to bust as well.
if (isBust(player)) return Outcome.DEALER_WIN;
if (isBust(dealer)) return Outcome.PLAYER_WIN;
int p = player.bestValue();
int d = dealer.bestValue();
if (p > d) return Outcome.PLAYER_WIN;
if (d > p) return Outcome.DEALER_WIN;
return Outcome.PUSH;
}
}
from enum import Enum
class Outcome(Enum):
PLAYER_BLACKJACK = "player blackjack, pays 3 to 2"
PLAYER_WIN = "player wins"
DEALER_WIN = "dealer wins"
PUSH = "push, bet returned"
class BlackjackRules:
TARGET = 21
def __init__(self, stands_on: int = 17, hits_soft_17: bool = False) -> None:
self._stands_on = stands_on
self._hits_soft_17 = hits_soft_17
def is_blackjack(self, hand: Hand) -> bool:
"""Exactly two cards to 21. Three cards to 21 is 21, not a blackjack."""
return len(hand) == 2 and hand.best_value() == self.TARGET
def is_bust(self, hand: Hand) -> bool:
return hand.best_value() > self.TARGET
def can_act(self, hand: Hand) -> bool:
return not self.is_bust(hand) and hand.best_value() < self.TARGET
def dealer_should_hit(self, dealer: Hand) -> bool:
"""The dealer has no choices, only a policy, and it lives here alone."""
value = dealer.best_value()
if value < self._stands_on:
return True
return self._hits_soft_17 and value == self._stands_on and dealer.is_soft()
def settle(self, player: Hand, dealer: Hand) -> Outcome:
if self.is_blackjack(player) and self.is_blackjack(dealer):
return Outcome.PUSH
if self.is_blackjack(player):
return Outcome.PLAYER_BLACKJACK
if self.is_blackjack(dealer):
return Outcome.DEALER_WIN
# The player acts first, so a player bust pays the house regardless.
if self.is_bust(player):
return Outcome.DEALER_WIN
if self.is_bust(dealer):
return Outcome.PLAYER_WIN
p, d = player.best_value(), dealer.best_value()
if p > d:
return Outcome.PLAYER_WIN
if d > p:
return Outcome.DEALER_WIN
return Outcome.PUSH
#pragma once
#include "Hand.h"
// What differs from the Java tab: the outcome is a plain enum class with a
// free describe() rather than an enum carrying a field.
enum class Outcome { PlayerBlackjack, PlayerWin, DealerWin, Push };
inline const char* describe(Outcome o) {
switch (o) {
case Outcome::PlayerBlackjack: return "player blackjack, pays 3 to 2";
case Outcome::PlayerWin: return "player wins";
case Outcome::DealerWin: return "dealer wins";
case Outcome::Push: return "push, bet returned";
}
return "unknown";
}
class BlackjackRules {
int standsOn_;
bool hitsSoft17_;
public:
static constexpr int kTarget = 21;
explicit BlackjackRules(int standsOn = 17, bool hitsSoft17 = false)
: standsOn_(standsOn), hitsSoft17_(hitsSoft17) {}
bool isBlackjack(const Hand& h) const { return h.size() == 2 && h.bestValue() == kTarget; }
bool isBust(const Hand& h) const { return h.bestValue() > kTarget; }
bool canAct(const Hand& h) const { return !isBust(h) && h.bestValue() < kTarget; }
bool dealerShouldHit(const Hand& dealer) const {
int value = dealer.bestValue();
if (value < standsOn_) return true;
return hitsSoft17_ && value == standsOn_ && dealer.isSoft();
}
Outcome settle(const Hand& player, const Hand& dealer) const {
bool pn = isBlackjack(player);
bool dn = isBlackjack(dealer);
if (pn && dn) return Outcome::Push;
if (pn) return Outcome::PlayerBlackjack;
if (dn) return Outcome::DealerWin;
if (isBust(player)) return Outcome::DealerWin; // the player acts first
if (isBust(dealer)) return Outcome::PlayerWin;
int p = player.bestValue();
int d = dealer.bestValue();
if (p > d) return Outcome::PlayerWin;
if (d > p) return Outcome::DealerWin;
return Outcome::Push;
}
};
const Outcome = Object.freeze({
PLAYER_BLACKJACK: "player blackjack, pays 3 to 2",
PLAYER_WIN: "player wins",
DEALER_WIN: "dealer wins",
PUSH: "push, bet returned",
});
class BlackjackRules {
static TARGET = 21;
#standsOn;
#hitsSoft17;
constructor(standsOn = 17, hitsSoft17 = false) {
this.#standsOn = standsOn;
this.#hitsSoft17 = hitsSoft17;
}
/** Exactly two cards to 21. Three cards to 21 is 21, not a blackjack. */
isBlackjack(hand) { return hand.size === 2 && hand.bestValue() === BlackjackRules.TARGET; }
isBust(hand) { return hand.bestValue() > BlackjackRules.TARGET; }
canAct(hand) { return !this.isBust(hand) && hand.bestValue() < BlackjackRules.TARGET; }
dealerShouldHit(dealer) {
const value = dealer.bestValue();
if (value < this.#standsOn) return true;
return this.#hitsSoft17 && value === this.#standsOn && dealer.isSoft();
}
settle(player, dealer) {
const pn = this.isBlackjack(player);
const dn = this.isBlackjack(dealer);
if (pn && dn) return Outcome.PUSH;
if (pn) return Outcome.PLAYER_BLACKJACK;
if (dn) return Outcome.DEALER_WIN;
if (this.isBust(player)) return Outcome.DEALER_WIN; // the player acts first
if (this.isBust(dealer)) return Outcome.PLAYER_WIN;
const p = player.bestValue();
const d = dealer.bestValue();
if (p > d) return Outcome.PLAYER_WIN;
if (d > p) return Outcome.DEALER_WIN;
return Outcome.PUSH;
}
}
Game.java
The round orchestrator, and the only class that knows about round boundaries. It checks the cut card exactly once per round – here, before the opening deal – so a reshuffle can never happen mid-hand.
package cards;
import cards.model.Card;
import cards.model.Hand;
import cards.rules.BlackjackRules;
import cards.rules.BlackjackRules.Outcome;
import cards.shoe.Shoe;
public class Game {
private final Shoe shoe;
private final BlackjackRules rules;
private Hand player;
private Hand dealer;
public Game(Shoe shoe, BlackjackRules rules) {
this.shoe = shoe;
this.rules = rules;
}
/**
* Start a round. This is the ONE place the cut card is acted on: mid-round
* the shoe keeps dealing past it, and the reshuffle lands here, between hands.
*/
public void deal() {
if (shoe.needsReshuffle()) {
System.out.printf(" (cut card passed at %.0f%% penetration -- reshuffling)%n",
shoe.penetration() * 100);
shoe.shuffle();
}
player = new Hand();
dealer = new Hand();
player.add(shoe.deal(), true);
dealer.add(shoe.deal(), true);
player.add(shoe.deal(), true);
dealer.add(shoe.deal(), false); // the hole card: face down in THIS hand only
}
/** Player takes one card. Returns true while the player may still act. */
public boolean hit() {
Card card = shoe.deal();
player.add(card, true);
System.out.println(" player hits " + card + " -> " + player);
return rules.canAct(player);
}
/** Player stands. The dealer reveals, plays the fixed policy, then we settle. */
public Outcome stand() {
dealer.revealAll();
System.out.println(" dealer shows " + dealer);
if (!rules.isBust(player)) {
while (rules.dealerShouldHit(dealer)) {
Card card = shoe.deal();
dealer.add(card, true);
System.out.println(" dealer draws " + card + " -> " + dealer);
}
}
return rules.settle(player, dealer);
}
public Hand playerHand() { return player; }
public Hand dealerHand() { return dealer; }
public Shoe shoe() { return shoe; }
}
class Game:
"""Shoe, Hand, BlackjackRules and Outcome are as in the tabs above."""
def __init__(self, shoe: Shoe, rules: BlackjackRules) -> None:
self._shoe, self._rules = shoe, rules
self._player, self._dealer = Hand(), Hand()
def deal(self) -> None:
"""The one place the cut card is acted on: between hands, never inside one."""
if self._shoe.needs_reshuffle():
print(f" (cut card passed at {self._shoe.penetration:.0%} -- reshuffling)")
self._shoe.shuffle()
self._player, self._dealer = Hand(), Hand()
self._player.add(self._shoe.deal(), True)
self._dealer.add(self._shoe.deal(), True)
self._player.add(self._shoe.deal(), True)
self._dealer.add(self._shoe.deal(), False) # hole card, face down here only
def hit(self) -> bool:
card = self._shoe.deal()
self._player.add(card, True)
print(f" player hits {card} -> {self._player}")
return self._rules.can_act(self._player)
def stand(self) -> Outcome:
self._dealer.reveal_all()
print(f" dealer shows {self._dealer}")
if not self._rules.is_bust(self._player):
while self._rules.dealer_should_hit(self._dealer):
card = self._shoe.deal()
self._dealer.add(card, True)
print(f" dealer draws {card} -> {self._dealer}")
return self._rules.settle(self._player, self._dealer)
@property
def player_hand(self) -> Hand:
return self._player
@property
def dealer_hand(self) -> Hand:
return self._dealer
#pragma once
#include <iostream>
#include "BlackjackRules.h"
#include "Shoe.h"
/** What differs from the Java tab: the shoe is held by reference, since one
* shoe is shared by the table and must not be copied into the game. */
class Game {
Shoe& shoe_;
BlackjackRules rules_;
Hand player_;
Hand dealer_;
public:
Game(Shoe& shoe, BlackjackRules rules) : shoe_(shoe), rules_(rules) {}
/** The one place the cut card is acted on: between hands, never inside one. */
void deal() {
if (shoe_.needsReshuffle()) {
std::cout << " (cut card passed -- reshuffling)\n";
shoe_.shuffle();
}
player_ = Hand();
dealer_ = Hand();
player_.add(shoe_.deal(), true);
dealer_.add(shoe_.deal(), true);
player_.add(shoe_.deal(), true);
dealer_.add(shoe_.deal(), false); // hole card
}
bool hit() {
const Card& card = shoe_.deal();
player_.add(card, true);
std::cout << " player hits " << card.toString() << "\n";
return rules_.canAct(player_);
}
Outcome stand() {
dealer_.revealAll();
std::cout << " dealer shows " << dealer_.toString() << "\n";
if (!rules_.isBust(player_)) {
while (rules_.dealerShouldHit(dealer_)) {
dealer_.add(shoe_.deal(), true);
std::cout << " dealer draws to " << dealer_.toString() << "\n";
}
}
return rules_.settle(player_, dealer_);
}
const Hand& playerHand() const { return player_; }
const Hand& dealerHand() const { return dealer_; }
};
class Game {
#shoe;
#rules;
#player = new Hand();
#dealer = new Hand();
constructor(shoe, rules) {
this.#shoe = shoe;
this.#rules = rules;
}
/** The one place the cut card is acted on: between hands, never inside one. */
deal() {
if (this.#shoe.needsReshuffle()) {
const pct = Math.round(this.#shoe.penetration * 100);
console.log(" (cut card passed at " + pct + "% penetration -- reshuffling)");
this.#shoe.shuffle();
}
this.#player = new Hand();
this.#dealer = new Hand();
this.#player.add(this.#shoe.deal(), true);
this.#dealer.add(this.#shoe.deal(), true);
this.#player.add(this.#shoe.deal(), true);
this.#dealer.add(this.#shoe.deal(), false); // hole card
}
hit() {
const card = this.#shoe.deal();
this.#player.add(card, true);
console.log(" player hits " + card + " -> " + this.#player);
return this.#rules.canAct(this.#player);
}
stand() {
this.#dealer.revealAll();
console.log(" dealer shows " + this.#dealer);
if (!this.#rules.isBust(this.#player)) {
while (this.#rules.dealerShouldHit(this.#dealer)) {
this.#dealer.add(this.#shoe.deal(), true);
console.log(" dealer draws to " + this.#dealer);
}
}
return this.#rules.settle(this.#player, this.#dealer);
}
get playerHand() { return this.#player; }
get dealerHand() { return this.#dealer; }
}
Demo.java (Runnable end-to-end)
Five labelled blocks: the identity fact that a 312-card shoe holds 52 objects, the same Card object sitting face up in one hand and face down in another, hand scoring with a natural, a soft 17 that demotes its ace, a bust and a three-card 21 that is not a blackjack, a dealt round settled by the rules, and the cut card flipping hasNext() while cards physically remain.
package cards;
import cards.model.Card;
import cards.model.Hand;
import cards.model.Rank;
import cards.model.Suit;
import cards.rules.BlackjackRules;
import cards.rules.BlackjackRules.Outcome;
import cards.shoe.Shoe;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
public class Demo {
public static void main(String[] args) {
BlackjackRules rules = new BlackjackRules();
// ---------- 1. Identity: 52 objects behind a 312-card shoe ----------
System.out.println("=== 1. A six-deck shoe is 312 references to 52 objects ===");
List<Card> sixDecks = new ArrayList<>();
for (int d = 0; d < 6; d++) sixDecks.addAll(Card.fullDeck());
Card aceA = Card.of(Rank.ACE, Suit.SPADES);
Card aceB = Card.of(Rank.ACE, Suit.SPADES);
expect("references in a six-deck shoe", 312, sixDecks.size());
expect("distinct Card objects in it", 52, new HashSet<>(sixDecks).size());
expect("Card.distinctCards()", 52, Card.distinctCards());
expect("Card.of(ACE,SPADES) == Card.of(ACE,SPADES)", true, aceA == aceB);
expect("and equals() agrees with ==", true, aceA.equals(aceB));
expect("a different card is not ==", false, aceA == Card.of(Rank.ACE, Suit.HEARTS));
// ---------- 2. faceUp is per hand, not per card ----------
System.out.println("\n=== 2. The same Card, face up here and face down there ===");
Hand seatThree = new Hand();
Hand house = new Hand();
seatThree.add(aceA, true); // the same object...
house.add(aceB, false); // ...dealt face down in this hand
System.out.println(" seat three : " + seatThree);
System.out.println(" dealer : " + house);
expect("both hands hold the same object", true,
seatThree.cards().get(0).card() == house.cards().get(0).card());
System.out.println(" one is visible and one is not, which no flag on Card could express");
// ---------- 3. Hand scoring ----------
System.out.println("\n=== 3. Hand scoring, including the ace ===");
Hand natural = new Hand();
natural.add(Card.of(Rank.ACE, Suit.SPADES));
natural.add(Card.of(Rank.KING, Suit.DIAMONDS));
System.out.println(" " + natural);
expect("natural: value", 21, natural.bestValue());
expect("natural: isBlackjack", true, rules.isBlackjack(natural));
Hand soft = new Hand();
soft.add(Card.of(Rank.ACE, Suit.HEARTS));
soft.add(Card.of(Rank.SIX, Suit.CLUBS));
System.out.println(" " + soft);
expect("soft 17: value", 17, soft.bestValue());
expect("soft 17: isSoft", true, soft.isSoft());
soft.add(Card.of(Rank.NINE, Suit.SPADES)); // 11+6+9 = 26, so the ace demotes
System.out.println(" " + soft);
expect("after the nine: value", 16, soft.bestValue());
expect("after the nine: isSoft", false, soft.isSoft());
expect("after the nine: isBust", false, rules.isBust(soft));
Hand fourAces = new Hand();
for (Suit suit : Suit.values()) fourAces.add(Card.of(Rank.ACE, suit));
System.out.println(" " + fourAces);
expect("four aces: value", 14, fourAces.bestValue()); // 11 + 1 + 1 + 1
Hand busted = new Hand();
busted.add(Card.of(Rank.TEN, Suit.CLUBS));
busted.add(Card.of(Rank.SEVEN, Suit.DIAMONDS));
busted.add(Card.of(Rank.EIGHT, Suit.HEARTS));
System.out.println(" " + busted);
expect("bust: value", 25, busted.bestValue());
expect("bust: isBust", true, rules.isBust(busted));
Hand threeSevens = new Hand();
threeSevens.add(Card.of(Rank.SEVEN, Suit.CLUBS));
threeSevens.add(Card.of(Rank.SEVEN, Suit.DIAMONDS));
threeSevens.add(Card.of(Rank.SEVEN, Suit.HEARTS));
System.out.println(" " + threeSevens);
expect("three sevens: value", 21, threeSevens.bestValue());
expect("three sevens: isBlackjack", false, rules.isBlackjack(threeSevens));
// ---------- 4. A dealt round ----------
System.out.println("\n=== 4. Dealing a round from a seeded shoe ===");
Shoe shoe = new Shoe(6, new Random(42));
Game game = new Game(shoe, rules);
game.deal();
System.out.println(" player : " + game.playerHand());
System.out.println(" dealer : " + game.dealerHand());
// Simple player policy, just to drive the round: draw below 17.
while (rules.canAct(game.playerHand()) && game.playerHand().bestValue() < 17) {
game.hit();
}
Outcome outcome = game.stand();
System.out.println(" result : " + outcome + " (" + outcome.description() + ")");
System.out.println(" dealt " + shoe.dealtCount() + " cards, " + shoe.remaining() + " left");
// ---------- 5. The cut card is a threshold, not the end of the list ----------
System.out.println("\n=== 5. The cut card ===");
System.out.println(" cut card sits at index " + shoe.cutIndex() + " of " + shoe.size());
while (shoe.hasNext()) shoe.deal(); // deal right up to the cut card
System.out.printf(" hasNext() went false after %d cards, at %.0f%% penetration%n",
shoe.dealtCount(), shoe.penetration() * 100);
expect("needsReshuffle()", true, shoe.needsReshuffle());
expect("canDeal() -- cards physically remain", true, shoe.canDeal());
expect("cards still in the shoe is positive", true, shoe.remaining() > 0);
System.out.println(" the round in progress still gets its cards; the reshuffle waits");
game.deal(); // round boundary: Game reshuffles here, not mid-hand
expect("penetration reset by the new round", true, shoe.dealtCount() == 4);
System.out.println(" player : " + game.playerHand());
System.out.println(" dealer : " + game.dealerHand());
}
/** Labelled expected-versus-actual, so a wrong answer is visible rather than plausible. */
private static void expect(String label, Object expected, Object actual) {
System.out.printf(" %-44s expected: %-6s actual: %-6s %s%n",
label, expected, actual, expected.equals(actual) ? "ok" : "MISMATCH");
}
}
# Rank, Suit, Card, Shoe, Hand, BlackjackRules and Game as in the tabs above.
import random
def expect(label, want, got) -> None:
"""Labelled expected-versus-actual, so a wrong answer is visible."""
flag = "ok" if want == got else "MISMATCH"
print(f" {label:<40} expected: {want!s:<6} actual: {got!s:<6} {flag}")
def hand_of(*pairs) -> Hand:
h = Hand()
for rank, suit in pairs:
h.add(Card.of(rank, suit))
return h
def main() -> None:
rules = BlackjackRules()
six_decks = [c for _ in range(6) for c in Card.full_deck()]
ace_a, ace_b = Card.of(Rank.ACE, Suit.SPADES), Card.of(Rank.ACE, Suit.SPADES)
print("=== 1. A six-deck shoe is 312 references to 52 objects ===")
expect("references in a six-deck shoe", 312, len(six_decks))
expect("distinct objects by identity", 52, len(set(id(c) for c in six_decks)))
expect("Card.of(A, S) is Card.of(A, S)", True, ace_a is ace_b)
expect("a different card is not it", False, ace_a is Card.of(Rank.ACE, Suit.HEARTS))
print("\n=== 2. The same Card, face up here and face down there ===")
seat_three, house = Hand(), Hand()
seat_three.add(ace_a, True)
house.add(ace_b, False)
print(f" seat three : {seat_three}")
print(f" dealer : {house}")
print("\n=== 3. Hand scoring, including the ace ===")
natural = hand_of((Rank.ACE, Suit.SPADES), (Rank.KING, Suit.DIAMONDS))
expect("natural: value", 21, natural.best_value())
expect("natural: is_blackjack", True, rules.is_blackjack(natural))
soft = hand_of((Rank.ACE, Suit.HEARTS), (Rank.SIX, Suit.CLUBS))
expect("soft 17: value", 17, soft.best_value())
expect("soft 17: is_soft", True, soft.is_soft())
soft.add(Card.of(Rank.NINE, Suit.SPADES)) # 11+6+9 = 26, so the ace demotes
expect("after the nine: value", 16, soft.best_value())
expect("after the nine: is_soft", False, soft.is_soft())
expect("four aces: value", 14, hand_of(*((Rank.ACE, s) for s in Suit)).best_value())
busted = hand_of((Rank.TEN, Suit.CLUBS), (Rank.SEVEN, Suit.DIAMONDS),
(Rank.EIGHT, Suit.HEARTS))
expect("bust: value", 25, busted.best_value())
expect("bust: is_bust", True, rules.is_bust(busted))
sevens = hand_of(*((Rank.SEVEN, s) for s in (Suit.CLUBS, Suit.DIAMONDS, Suit.HEARTS)))
expect("21 in three cards is no blackjack", False, rules.is_blackjack(sevens))
print("\n=== 4. A round, then the cut card ===")
shoe = Shoe(6, random.Random(42))
game = Game(shoe, rules)
game.deal()
print(f" player : {game.player_hand}")
print(f" dealer : {game.dealer_hand}")
while rules.can_act(game.player_hand) and game.player_hand.best_value() < 17:
game.hit()
print(f" result : {game.stand().value}")
while shoe.has_next():
shoe.deal()
print(f" has_next() false after {shoe.dealt_count} cards, {shoe.penetration:.0%} deep")
expect("needs_reshuffle()", True, shoe.needs_reshuffle())
expect("can_deal(): cards remain", True, shoe.can_deal())
game.deal() # round boundary: the reshuffle lands here
expect("new round dealt four cards", 4, shoe.dealt_count)
if __name__ == "__main__":
main()
// Rank, Suit, Card, Shoe, Hand, BlackjackRules and Game as in the tabs above.
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include "Game.h"
static std::string yn(bool b) { return b ? "true" : "false"; }
static void expect(const std::string& label, const std::string& want, const std::string& got) {
std::cout << " " << label << " expected: " << want << " actual: " << got
<< (want == got ? " ok" : " MISMATCH") << "\n";
}
static Hand handOf(std::vector<std::pair<Rank, Suit>> pairs) {
Hand h;
for (const auto& p : pairs) h.add(Card::of(p.first, p.second));
return h;
}
int main() {
BlackjackRules rules;
std::cout << "=== 1. A six-deck shoe is 312 pointers to 52 objects ===\n";
std::vector<const Card*> sixDecks;
for (int d = 0; d < 6; ++d) {
auto deck = Card::fullDeck();
sixDecks.insert(sixDecks.end(), deck.begin(), deck.end());
}
std::set<const Card*> distinct(sixDecks.begin(), sixDecks.end());
const Card& aceA = Card::of(Rank::Ace, Suit::Spades);
const Card& aceB = Card::of(Rank::Ace, Suit::Spades);
expect("pointers in a six-deck shoe", "312", std::to_string(sixDecks.size()));
expect("distinct Card objects ", "52", std::to_string(distinct.size()));
expect("one address per card value ", "true", yn(&aceA == &aceB));
std::cout << "\n=== 2. The same Card, face up here and face down there ===\n";
Hand seatThree;
Hand house;
seatThree.add(aceA, true);
house.add(aceB, false);
std::cout << " seat three : " << seatThree.toString() << "\n"
<< " dealer : " << house.toString() << "\n";
std::cout << "\n=== 3. Hand scoring, including the ace ===\n";
Hand natural = handOf({ { Rank::Ace, Suit::Spades }, { Rank::King, Suit::Diamonds } });
expect("natural: value ", "21", std::to_string(natural.bestValue()));
expect("natural: isBlackjack ", "true", yn(rules.isBlackjack(natural)));
Hand soft = handOf({ { Rank::Ace, Suit::Hearts }, { Rank::Six, Suit::Clubs } });
expect("soft 17: value ", "17", std::to_string(soft.bestValue()));
soft.add(Card::of(Rank::Nine, Suit::Spades)); // 11+6+9 = 26, the ace demotes
expect("after the nine: value", "16", std::to_string(soft.bestValue()));
expect("after the nine: soft ", "false", yn(soft.isSoft()));
Hand busted = handOf({ { Rank::Ten, Suit::Clubs },
{ Rank::Seven, Suit::Diamonds },
{ Rank::Eight, Suit::Hearts } });
expect("bust: value ", "25", std::to_string(busted.bestValue()));
expect("bust: isBust ", "true", yn(rules.isBust(busted)));
std::cout << "\n=== 4. A round, then the cut card ===\n";
Shoe shoe(6, 42u);
Game game(shoe, rules);
game.deal();
std::cout << " player : " << game.playerHand().toString() << "\n";
while (rules.canAct(game.playerHand()) && game.playerHand().bestValue() < 17) game.hit();
std::cout << " result : " << describe(game.stand()) << "\n";
while (shoe.hasNext()) shoe.deal();
expect("needsReshuffle() ", "true", yn(shoe.needsReshuffle()));
expect("canDeal(): cards left", "true", yn(shoe.canDeal()));
return 0;
}
// Rank, Suit, Card, Shoe, Hand, BlackjackRules and Game as in the tabs above.
function expect(label, want, got) {
const flag = want === got ? "ok" : "MISMATCH";
console.log(" " + label.padEnd(40) + " expected: " + String(want).padEnd(6)
+ " actual: " + String(got).padEnd(6) + " " + flag);
}
function handOf(...pairs) {
const h = new Hand();
for (const [rank, suit] of pairs) h.add(Card.of(rank, suit));
return h;
}
function main() {
const rules = new BlackjackRules();
const sixDecks = [];
for (let d = 0; d < 6; d++) sixDecks.push(...Card.fullDeck());
const aceA = Card.of(Rank.ACE, Suit.SPADES);
const aceB = Card.of(Rank.ACE, Suit.SPADES);
console.log("=== 1. A six-deck shoe is 312 references to 52 objects ===");
expect("references in a six-deck shoe", 312, sixDecks.length);
expect("distinct Card objects in it", 52, new Set(sixDecks).size);
expect("Card.of(A,S) === Card.of(A,S)", true, aceA === aceB);
expect("a different card is not ===", false, aceA === Card.of(Rank.ACE, Suit.HEARTS));
console.log("\n=== 2. The same Card, face up here and face down there ===");
const seatThree = new Hand();
const house = new Hand();
seatThree.add(aceA, true);
house.add(aceB, false);
console.log(" seat three : " + seatThree);
console.log(" dealer : " + house);
console.log("\n=== 3. Hand scoring, including the ace ===");
const natural = handOf([Rank.ACE, Suit.SPADES], [Rank.KING, Suit.DIAMONDS]);
expect("natural: value", 21, natural.bestValue());
expect("natural: isBlackjack", true, rules.isBlackjack(natural));
const soft = handOf([Rank.ACE, Suit.HEARTS], [Rank.SIX, Suit.CLUBS]);
expect("soft 17: value", 17, soft.bestValue());
expect("soft 17: isSoft", true, soft.isSoft());
soft.add(Card.of(Rank.NINE, Suit.SPADES)); // 11+6+9 = 26, so the ace demotes
expect("after the nine: value", 16, soft.bestValue());
expect("after the nine: isSoft", false, soft.isSoft());
expect("four aces: value", 14, handOf(...SUITS.map((s) => [Rank.ACE, s])).bestValue());
const busted = handOf([Rank.TEN, Suit.CLUBS], [Rank.SEVEN, Suit.DIAMONDS],
[Rank.EIGHT, Suit.HEARTS]);
expect("bust: value", 25, busted.bestValue());
expect("bust: isBust", true, rules.isBust(busted));
const sevens = handOf([Rank.SEVEN, Suit.CLUBS], [Rank.SEVEN, Suit.DIAMONDS],
[Rank.SEVEN, Suit.HEARTS]);
expect("21 in three cards is no blackjack", false, rules.isBlackjack(sevens));
console.log("\n=== 4. A round, then the cut card ===");
const shoe = new Shoe(6, 42);
const game = new Game(shoe, rules);
game.deal();
console.log(" player : " + game.playerHand);
console.log(" dealer : " + game.dealerHand);
while (rules.canAct(game.playerHand) && game.playerHand.bestValue() < 17) game.hit();
console.log(" result : " + game.stand());
while (shoe.hasNext()) shoe.deal();
expect("needsReshuffle()", true, shoe.needsReshuffle());
expect("canDeal(): cards remain", true, shoe.canDeal());
game.deal(); // round boundary: the reshuffle lands here
expect("new round dealt four cards", 4, shoe.dealtCount);
}
main();
Sequence Diagram – One Round at the Table
💡 A sequence diagram reads top to bottom as time passing: each vertical line is one object staying alive, and each horizontal arrow is one call from the object on the left to the object on the right.
sequenceDiagram
participant P as Player
participant G as Game
participant S as Shoe
participant PH as Hand player
participant R as BlackjackRules
P->>G: deal()
G->>S: needsReshuffle()
S-->>G: cursor is short of the cut card
G->>S: deal() four times
S-->>G: four Card references from the 52-entry pool
G->>PH: add(card, faceUp true)
Note over G,PH: dealer's second card is added with faceUp false
P->>G: hit()
G->>S: deal()
S-->>G: Card
G->>PH: add(card, faceUp true)
G->>PH: bestValue()
PH->>PH: every ace as 11, then demote while over 21
PH-->>G: total
alt total over 21
G->>R: settle(player, dealer)
R-->>P: DEALER_WIN
else player stands
G->>R: dealerShouldHit(dealer)
R-->>G: true while below 17
G->>S: deal() to the dealer
G->>R: settle(player, dealer)
R-->>P: Outcome
end
The branch worth reading twice is the one that is not in the diagram: nowhere does the shoe reshuffle. Crossing the cut card mid-round changes nothing about the round, because the only needsReshuffle() call is the first message of the next one.
How to Extend
| Extension | Implementation |
|---|---|
| Seeded, reproducible deals | A Shuffler interface with FisherYatesShuffler(seed); Shoe takes one instead of a Random, and a replay reseeds it |
| A different randomisation | New RiffleShuffler implements Shuffler for a casino-style imperfect shuffle. Shoe does not change |
| Jokers, or a 54-card deck | Add Rank.JOKER; the pool, Card.of and every holder are unchanged because the key is the enum pair |
| Split and double down | A new PlayerSeat class owning a List<Hand>; Game loops over seats and then over each seat’s hands |
| Another game on the same shoe | A new rules class beside BlackjackRules. Card, Shoe and Hand are game-agnostic already |
| Running count display | A RunningCount listener registered on Shoe; the shoe publishes each dealt card, and the count reads dealtSoFar() |
| Configurable shoe | ShoeBuilder with decks, penetrationBand, shuffler and seed, replacing the four-argument constructor |
| Persisting a round | A RoundLog of rank-and-suit pairs; replaying it through Card.of gives back the very same instances |
💡 That last row is interning twice over: the log stores values, and rehydrating a value through Card.of lands on the one canonical object rather than a copy, so a replayed round compares == against the original. Learn more →
What Interviewers Look For
- ✅ Cards are interned, not allocated – a six-deck shoe is 312 references to 52 objects, built once in a static pool and handed out by a factory.
- ✅ The constructor is private – if callers can
new Card(...), the pool is a suggestion and==is a lie. Closing that door is the point of the factory. - ✅
faceUpis not onCard– the candidate notices that sharing forces immutability, and moves per-hand state onto the hand’s own wrapper rather than the shared value. - ✅
equalsandhashCodeare both there and agree – without them aCardis not a usable map key, and “which cards have come out” needs a linear scan. - ✅ Dealing is a cursor, not a pop – O(1) per card, the dealt prefix survives, and penetration and replay both fall out of keeping the list intact.
- ✅ The cut card is modelled, and acted on between rounds – a reshuffle that can fire mid-hand is a rules bug, so the check belongs at the round boundary in
Game. - ✅ Fisher-Yates, and knowing why the naive swap loop is wrong –
n^nequally likely runs cannot spread evenly overn!orderings. Stated as correctness, not as speed. - ✅ The ace is resolved in the hand – count every ace as 11 and demote while busting, which is O(n) with no search, and leaves
Rankcarrying data rather than decisions.
Related Designs
- Snake and Ladder – the other dice-and-board warm-up, and the cleanest place to see a turn loop separated from the rules that score it
- Tic-Tac-Toe – the same Strategy seam used for win rules instead of house rules, with running tallies in place of ace resolution
- Snake Game – a deque as the game’s core data structure, the same way the shoe’s cursor is the core of dealing
- Music Player – the Iterator pattern again, where shuffle and repeat are traversal objects rather than flags on the playlist
Related Concepts
Scale this design past a single process and these are the concepts it runs into:
- Unique IDs → – a shuffle seed is an identifier for a deal, so it has to be unique per round and never reused across tables; the same generator that stamps round IDs can supply it, which is what makes “replay round 8841” meaningful
- Idempotency → – a
dealrequest resent after a client timeout must not advance the cursor twice, so the round carries a key and the server returns the already-dealt cards instead of burning two more - WebSockets vs SSE → – every other seat needs each dealt card pushed as it happens, and the hole card is the reason the push is per hand: the same
Cardgoes out face up to one client and hidden to the rest
Discussion
Newest first