LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 36 OF 42

Design a Blackjack Game: Low-Level Design in Java

A card game round with real money rules: cards, a multi-deck shoe with a seeded shuffle, hand values with soft and hard aces, hit, stand, double and split, dealer rules with a soft 17 switch, a round state machine, a wallet and 3 to 2 payouts, players as Strategies (scripted human and bot), observers, thread safety and the follow-ups, with a full Java 17 solution.

Reported atUber

Patterns usedStrategyObserverState

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 24

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 532 lines, with a small main() demo. Save it as Blackjack.java, then run javac Blackjack.java && java Blackjack.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.EnumSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

/** A blackjack table: a seeded shoe, soft and hard hands, player strategies and a round state machine. */
public class Blackjack {

    // ---------- cards ----------
    enum Suit {
        CLUBS('c'), DIAMONDS('d'), HEARTS('h'), SPADES('s');

        final char symbol;

        Suit(char symbol) { this.symbol = symbol; }
    }

    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);

        final String label;
        final int points; // an ace counts 1 here; Hand decides when one ace can count 11

        Rank(String label, int points) {
            this.label = label;
            this.points = points;
        }
    }

    record Card(Rank rank, Suit suit) {
        @Override
        public String toString() { return rank.label + suit.symbol; }
    }

    /** Several decks shuffled together. A seeded Random makes every game repeatable in tests. */
    static final class Shoe {
        private final int decks;
        private final Random rnd;
        private final Deque<Card> cards = new ArrayDeque<>();
        private final int cutAt; // reshuffle before a round once fewer cards than this are left
        private int shuffles;

        Shoe(int decks, Random rnd) {
            if (decks < 1) throw new IllegalArgumentException("need at least one deck");
            this.decks = decks;
            this.rnd = rnd;
            this.cutAt = decks * 52 / 4;
            shuffle();
        }

        private Shoe(List<Card> order) {
            this.decks = 0;
            this.rnd = null;
            this.cutAt = 0;
            cards.addAll(order);
        }

        /** A stacked shoe for tests: cards come out in exactly this order. */
        static Shoe stacked(List<Card> order) { return new Shoe(order); }

        void shuffle() {
            if (decks == 0) throw new IllegalStateException("a stacked shoe is never shuffled");
            List<Card> all = new ArrayList<>(decks * 52);
            for (int d = 0; d < decks; d++)
                for (Suit s : Suit.values())
                    for (Rank r : Rank.values()) all.add(new Card(r, s));
            Collections.shuffle(all, rnd);
            cards.clear();
            cards.addAll(all);
            shuffles++;
        }

        boolean needsShuffle() { return cards.size() < cutAt; }

        Card draw() {
            Card c = cards.poll();
            if (c == null) throw new IllegalStateException("the shoe is empty");
            return c;
        }

        int shuffles() { return shuffles; }
    }

    // ---------- hands ----------
    /** What a strategy may look at. It cannot add cards or change the bet. */
    interface HandView {
        List<Card> cards();

        int value();

        boolean isSoft();
    }

    static final class Hand implements HandView {
        private final List<Card> cards = new ArrayList<>();
        private long bet;
        private boolean fromSplit;
        private boolean done;

        Hand(long bet, boolean fromSplit) {
            this.bet = bet;
            this.fromSplit = fromSplit;
        }

        void add(Card c) { cards.add(c); }

        @Override
        public List<Card> cards() { return List.copyOf(cards); }

        private int hardTotal() {
            int sum = 0;
            for (Card c : cards) sum += c.rank().points;
            return sum;
        }

        private boolean hasAce() {
            for (Card c : cards) if (c.rank() == Rank.ACE) return true;
            return false;
        }

        /** Count every ace as 1, then let one ace count 11 if that does not go over 21. */
        @Override
        public int value() {
            int hard = hardTotal();
            return hasAce() && hard + 10 <= 21 ? hard + 10 : hard;
        }

        /** Soft means one ace is counted as 11, so one more card can never bust the hand. */
        @Override
        public boolean isSoft() { return hasAce() && hardTotal() + 10 <= 21; }

        boolean isBlackjack() { return !fromSplit && cards.size() == 2 && value() == 21; }

        boolean isBust() { return value() > 21; }

        boolean isPair() { return cards.size() == 2 && cards.get(0).rank() == cards.get(1).rank(); }

        @Override
        public String toString() {
            return cards + " = " + value() + (isSoft() ? " soft" : "") + (isBust() ? " BUST" : "");
        }
    }

    // ---------- money ----------
    /** Money in cents. Synchronized because one wallet may be used at more than one table. */
    static final class Wallet {
        private long cents;

        Wallet(long cents) { this.cents = cents; }

        synchronized void debit(long amount) {
            if (amount > cents)
                throw new IllegalStateException("insufficient funds: need " + money(amount)
                        + ", have " + money(cents));
            cents -= amount;
        }

        synchronized void credit(long amount) { cents += amount; }

        synchronized boolean canAfford(long amount) { return amount <= cents; }

        synchronized long balance() { return cents; }
    }

    enum Outcome {
        BLACKJACK, WIN, PUSH, LOSE;

        /** Total paid back to the player, stake included. Blackjack pays 3 to 2, rounded down. */
        long returned(long stake) {
            return switch (this) {
                case BLACKJACK -> stake + stake * 3 / 2;
                case WIN -> stake * 2;
                case PUSH -> stake;
                case LOSE -> 0;
            };
        }
    }

    // ---------- players: Strategy ----------
    enum Action { HIT, STAND, DOUBLE, SPLIT }

    interface PlayerStrategy { Action decide(HandView hand, Card dealerUp, Set<Action> allowed); }

    /** A human: in a real app the UI fills this queue; here the demo scripts it. Empty means stand. */
    static final class ScriptedHuman implements PlayerStrategy {
        private final Deque<Action> script = new ArrayDeque<>();

        ScriptedHuman(Action... actions) { script.addAll(List.of(actions)); }

        @Override
        public Action decide(HandView hand, Card dealerUp, Set<Action> allowed) {
            return script.isEmpty() ? Action.STAND : script.poll();
        }
    }

    /** A short version of basic strategy: sensible, not perfect. Only ever picks allowed actions. */
    static final class SimpleBot implements PlayerStrategy {
        @Override
        public Action decide(HandView h, Card up, Set<Action> allowed) {
            int v = h.value();
            int dealer = up.rank() == Rank.ACE ? 11 : up.rank().points;
            Rank first = h.cards().get(0).rank();
            boolean goodPair = first == Rank.ACE || first == Rank.EIGHT;
            if (allowed.contains(Action.SPLIT) && goodPair) return Action.SPLIT;
            if (allowed.contains(Action.DOUBLE) && !h.isSoft() && (v == 11 || (v == 10 && dealer <= 9)))
                return Action.DOUBLE;
            if (h.isSoft()) return v <= 17 ? Action.HIT : Action.STAND;
            if (v <= 11) return Action.HIT;
            if (v <= 16 && dealer >= 7) return Action.HIT;
            if (v == 12 && dealer <= 3) return Action.HIT;
            return Action.STAND;
        }
    }

    static final class Player {
        final String name;
        final Wallet wallet;
        final PlayerStrategy strategy;
        final List<Hand> hands = new ArrayList<>(); // this round only; a split adds a hand

        Player(String name, Wallet wallet, PlayerStrategy strategy) {
            this.name = name;
            this.wallet = wallet;
            this.strategy = strategy;
        }
    }

    // ---------- table rules, round state, events ----------
    record Rules(boolean dealerHitsSoft17, int maxHands, boolean doubleAfterSplit) {
        static Rules standard() { return new Rules(false, 4, true); }
    }

    enum Phase { BETTING, PLAYER_TURNS, DEALER_TURN, SETTLED }

    interface TableListener { void onEvent(String event); }

    private final Shoe shoe;
    private final Rules rules;
    private final List<Player> seats = new ArrayList<>();
    private final List<TableListener> listeners = new CopyOnWriteArrayList<>();
    private Hand dealer;
    private Phase phase = Phase.SETTLED;
    private long houseCents; // stakes held minus everything paid back

    Blackjack(Shoe shoe, Rules rules) {
        this.shoe = shoe;
        this.rules = rules;
    }

    void subscribe(TableListener l) { listeners.add(l); }

    synchronized void sit(Player p) {
        expect(Phase.SETTLED);
        seats.add(p);
    }

    /** SETTLED to BETTING. The shoe is only reshuffled between rounds, never in the middle of one. */
    synchronized void beginRound() {
        expect(Phase.SETTLED);
        if (shoe.needsShuffle()) {
            shoe.shuffle();
            emit("shoe reshuffled");
        }
        for (Player p : seats) p.hands.clear();
        dealer = null;
        phase = Phase.BETTING;
    }

    synchronized void bet(Player p, long cents) {
        expect(Phase.BETTING);
        if (!seats.contains(p)) throw new IllegalArgumentException(p.name + " is not at this table");
        if (!p.hands.isEmpty()) throw new IllegalStateException(p.name + " has already bet");
        if (cents <= 0) throw new IllegalArgumentException("bet must be positive");
        p.wallet.debit(cents);
        houseCents += cents;
        p.hands.add(new Hand(cents, false));
    }

    /** BETTING to PLAYER_TURNS: two cards each, the dealer's second card face down. */
    synchronized void deal() {
        expect(Phase.BETTING);
        List<Hand> playing = new ArrayList<>();
        for (Player p : seats) playing.addAll(p.hands);
        if (playing.isEmpty()) throw new IllegalStateException("no bets placed");
        dealer = new Hand(0, false);
        for (int round = 0; round < 2; round++) {
            for (Hand h : playing) h.add(shoe.draw());
            dealer.add(shoe.draw());
        }
        emit("dealer shows " + upCard());
        if (dealer.isBlackjack()) { // the dealer peeks: nobody plays against a blackjack
            emit("dealer has blackjack");
            phase = Phase.DEALER_TURN;
        } else {
            phase = Phase.PLAYER_TURNS;
        }
    }

    /** PLAYER_TURNS to DEALER_TURN: every hand of every player, left to right. */
    synchronized void playPlayers() {
        expect(Phase.PLAYER_TURNS);
        for (Player p : seats)
            for (int i = 0; i < p.hands.size(); i++) // a split inserts a hand, so loop by index
                playHand(p, p.hands.get(i));
        phase = Phase.DEALER_TURN;
    }

    private void playHand(Player p, Hand h) {
        int rejected = 0;
        while (!h.done) {
            if (h.value() >= 21) break; // 21 or bust: nothing left to decide
            Set<Action> allowed = allowed(p, h);
            Action a = p.strategy.decide(h, upCard(), allowed);
            if (!allowed.contains(a)) {
                emit("rejected: " + p.name + " may not " + a + " now");
                if (++rejected == 3) break; // a stuck client stands
                continue;
            }
            apply(p, h, a);
        }
        h.done = true;
        emit(p.name + ": " + h);
    }

    private Set<Action> allowed(Player p, Hand h) {
        Set<Action> s = EnumSet.of(Action.HIT, Action.STAND);
        boolean afford = p.wallet.canAfford(h.bet);
        if (h.cards.size() == 2 && afford && (!h.fromSplit || rules.doubleAfterSplit())) s.add(Action.DOUBLE);
        if (h.isPair() && afford && p.hands.size() < rules.maxHands()) s.add(Action.SPLIT);
        return s;
    }

    private void apply(Player p, Hand h, Action a) {
        switch (a) {
            case HIT -> h.add(shoe.draw());
            case STAND -> h.done = true;
            case DOUBLE -> {
                take(p, h.bet);
                h.bet *= 2;
                h.add(shoe.draw());
                h.done = true; // exactly one card after doubling
            }
            case SPLIT -> {
                take(p, h.bet);
                Hand second = new Hand(h.bet, true);
                second.add(h.cards.remove(1));
                h.fromSplit = true; // 21 on a split hand is not a blackjack
                h.add(shoe.draw());
                second.add(shoe.draw());
                p.hands.add(p.hands.indexOf(h) + 1, second);
                emit(p.name + " splits into " + h.cards + " and " + second.cards);
                if (h.cards.get(0).rank() == Rank.ACE) { // split aces get one card each
                    h.done = true;
                    second.done = true;
                }
            }
        }
    }

    private void take(Player p, long cents) {
        p.wallet.debit(cents);
        houseCents += cents;
    }

    /** House rule: draw below 17; on a soft 17, hit only when the table says so. */
    static void playDealer(Hand d, Shoe shoe, Rules rules) {
        while (d.value() < 17 || (d.value() == 17 && d.isSoft() && rules.dealerHitsSoft17()))
            d.add(shoe.draw());
    }

    static Outcome outcome(Hand h, Hand d) {
        if (h.isBust()) return Outcome.LOSE; // the player busted first, so loses even if the dealer busts
        if (h.isBlackjack()) return d.isBlackjack() ? Outcome.PUSH : Outcome.BLACKJACK;
        if (d.isBlackjack()) return Outcome.LOSE;
        if (d.isBust() || h.value() > d.value()) return Outcome.WIN;
        return h.value() == d.value() ? Outcome.PUSH : Outcome.LOSE;
    }

    /** DEALER_TURN to SETTLED: the dealer draws (if anyone is still in), then every hand is paid. */
    synchronized void finishRound() {
        expect(Phase.DEALER_TURN);
        boolean anyLive = false;
        for (Player p : seats) for (Hand h : p.hands) anyLive |= !h.isBust();
        if (anyLive && !dealer.isBlackjack()) playDealer(dealer, shoe, rules);
        emit("dealer: " + dealer);
        for (Player p : seats) {
            for (Hand h : p.hands) {
                Outcome o = outcome(h, dealer);
                long back = o.returned(h.bet);
                p.wallet.credit(back);
                houseCents -= back;
                emit(p.name + " " + o + " on " + money(h.bet) + ", paid " + money(back));
            }
        }
        phase = Phase.SETTLED;
    }

    /** One whole round, used by the bot simulation. Returns false when nobody could bet. */
    boolean playRound(long betEach) {
        beginRound();
        for (Player p : seats) if (p.wallet.canAfford(betEach)) bet(p, betEach);
        if (seats.stream().allMatch(p -> p.hands.isEmpty())) {
            phase = Phase.SETTLED;
            return false;
        }
        deal();
        if (phase == Phase.PLAYER_TURNS) playPlayers();
        finishRound();
        return true;
    }

    private Card upCard() { return dealer.cards.get(0); }

    private void expect(Phase want) {
        if (phase != want) throw new IllegalStateException("expected " + want + " but the round is " + phase);
    }

    private void emit(String e) { for (TableListener l : listeners) l.onEvent(e); }

    synchronized long houseCents() { return houseCents; }

    // ---------- demo ----------
    static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }

    static List<Card> cards(String text) {
        List<Card> out = new ArrayList<>();
        for (String t : text.split(" ")) {
            String label = t.substring(0, t.length() - 1);
            char suit = t.charAt(t.length() - 1);
            Rank rank = null;
            for (Rank r : Rank.values()) if (r.label.equals(label)) rank = r;
            for (Suit s : Suit.values()) if (s.symbol == suit) out.add(new Card(rank, s));
        }
        return out;
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) {
        // 1. A stacked shoe makes one round fully predictable: blackjack, split, double, dealer bust.
        Shoe stacked = Shoe.stacked(cards("As 8c 6h Kh 8d 10c 3s 10d 9h 7c"));
        Blackjack table = new Blackjack(stacked, Rules.standard());
        Player asha = new Player("Asha", new Wallet(100_00), new ScriptedHuman());
        Player ravi = new Player("Ravi", new Wallet(100_00),
                new ScriptedHuman(Action.SPLIT, Action.DOUBLE, Action.SPLIT, Action.STAND));
        table.sit(asha);
        table.sit(ravi);
        table.subscribe(e -> System.out.println("  " + e));
        table.beginRound();
        table.bet(asha, 10_00);
        table.bet(ravi, 10_00);
        table.deal();
        table.playPlayers();
        table.finishRound();
        System.out.println("Asha " + money(asha.wallet.balance()) + ", Ravi " + money(ravi.wallet.balance()));
        check(asha.wallet.balance() == 115_00, "blackjack should pay 3 to 2");
        check(ravi.wallet.balance() == 130_00, "split and double should both win");

        // 2. The state machine and the wallet reject what is not allowed.
        try {
            table.deal();
            throw new AssertionError("dealt with no round open");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        table.beginRound();
        try {
            table.bet(asha, 500_00);
            throw new AssertionError("bet more than the wallet holds");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        // 3. Soft 17: the same cards, two house rules.
        for (boolean hitSoft17 : new boolean[] {false, true}) {
            Shoe s = Shoe.stacked(cards("As 6d 4c"));
            Hand d = new Hand(0, false);
            d.add(s.draw());
            d.add(s.draw());
            playDealer(d, s, new Rules(hitSoft17, 4, true));
            System.out.println((hitSoft17 ? "H17" : "S17") + " dealer: " + d);
            check(d.value() == (hitSoft17 ? 21 : 17), "soft 17 rule");
        }

        // 4. Soft and hard values match a slow check of every way to count the aces.
        Random rnd = new Random(7);
        for (int i = 0; i < 20_000; i++) {
            Hand h = new Hand(0, false);
            int n = 2 + rnd.nextInt(5);
            for (int k = 0; k < n; k++) h.add(new Card(Rank.values()[rnd.nextInt(13)], Suit.SPADES));
            check(h.value() == bestTotal(h.cards()), "hand value " + h);
        }
        System.out.println("Ace values matched a brute force on 20000 hands");

        // 5. Three bots, a seeded six-deck shoe: the same result on every run, and no money is lost.
        Blackjack casino = new Blackjack(new Shoe(6, new Random(42)), Rules.standard());
        List<Player> bots = List.of(new Player("Bot1", new Wallet(1000_00), new SimpleBot()),
                new Player("Bot2", new Wallet(1000_00), new SimpleBot()),
                new Player("Bot3", new Wallet(1000_00), new SimpleBot()));
        bots.forEach(casino::sit);
        int rounds = 0;
        while (rounds < 2000 && casino.playRound(10_00)) {
            rounds++;
            long total = casino.houseCents();
            for (Player p : bots) total += p.wallet.balance();
            check(total == 3000_00, "money created or destroyed");
        }
        System.out.println(rounds + " bot rounds, " + casino.shoe.shuffles() + " shuffles, house "
                + (casino.houseCents() >= 0 ? "won " : "lost ") + money(Math.abs(casino.houseCents())));
        for (Player p : bots) System.out.println("  " + p.name + ": " + money(p.wallet.balance()));
    }

    /** Try every number of aces counted as 11; keep the best total that does not bust. */
    private static int bestTotal(List<Card> cards) {
        int hard = 0, aces = 0;
        for (Card c : cards) {
            hard += c.rank().points;
            if (c.rank() == Rank.ACE) aces++;
        }
        int best = hard;
        for (int k = 1; k <= aces; k++) if (hard + 10 * k <= 21) best = hard + 10 * k;
        return best;
    }
}

Notes

Requirements

Fix the scope first. One dealer and up to seven players at a table. Cards come from a shoe of several decks. Each player bets, gets two cards, and then can hit, stand or double down; splitting a pair comes as an extension. The dealer plays by fixed rules. A win pays one to one, a tie returns the bet, and a natural blackjack pays three to two. Money lives in a wallet. Insurance and chat are out of scope.

Ask the questions that change the code. How many decks? Configurable, six by default. Does the dealer hit a soft seventeen? Casinos differ, so it is a table rule. Can you double after a split? Also a rule. Split aces usually get one card each and stop. And the shoe is reshuffled only between rounds, once a cut card is reached, never in the middle of a hand.

Requirements
  • one dealer, up to seven players
  • a shoe of several decks
  • bet, then two cards each
  • hit, stand, double; split later
  • dealer follows fixed rules
  • win pays 1 to 1, push returns
  • the bet, blackjack pays 3 to 2
  • each player has a wallet
  • human or bot players
  • out of scope: insurance, chat
Clarify first
  • how many decks?
  • configurable, six by default
  • dealer hits a soft 17?
  • a table rule, off by default
  • double after a split?
  • allowed, also a rule
  • split aces?
  • one card each, then stop
  • when to reshuffle?
  • between rounds, at a cut card

Entities

Underline the nouns: table, dealer, shoe, card, player, hand, bet, wallet. The table owns the shoe, the seats and the current phase of the round. One detail shapes the design: a player is not a hand. After a split, one player holds two or more hands, each with its own cards and its own bet. So a player has a list of hands, and the bet lives on the hand, not on the player.

Class diagram

Fixed sets become enums: suit, rank, action, phase and outcome. Each rank stores its points, with the ace stored as one; the hand decides later when an ace may count as eleven. A card is a record of rank and suit, so two cards are equal when they look the same, which is fine because a shoe holds several identical decks. Table rules are one small record too.

Value types
enum Suit { CLUBS, DIAMONDS, HEARTS,
            SPADES }
enum Rank { TWO(2), ..., KING(10), ACE(1) }
record Card(Rank rank, Suit suit)

enum Action { HIT, STAND, DOUBLE, SPLIT }
enum Phase { BETTING, PLAYER_TURNS,
             DEALER_TURN, SETTLED }
enum Outcome { BLACKJACK, WIN, PUSH, LOSE }
record Rules(boolean dealerHitsSoft17,
    int maxHands, boolean doubleAfterSplit)

The shoe

The shoe builds several decks, shuffles them with an injected random generator and deals from a deque. Inject the random source: a seeded one in tests gives the same game every run, and production passes a secure random. When fewer than a quarter of the cards are left, the shoe asks to be reshuffled before the next round. For scenario tests there is also a stacked shoe that deals cards in an exact order.

Shoe
Shoe(int decks, Random rnd)
  all = decks x 52 cards
  Collections.shuffle(all, rnd)
draw(): poll from an ArrayDeque
needsShuffle(): left below cutAt
  cutAt = a quarter of the shoe

static Shoe stacked(List<Card> order)
  fixed order, for scenario tests

Hand value

The ace is the tricky card. The neat trick: count every ace as one, then ask whether adding ten more still stays at or under twenty one. If yes, one ace counts as eleven and the hand is soft. Only one ace can ever be eleven, because two elevens make twenty two. So there is no search over combinations at all, just one sum and one check. Blackjack means two cards making twenty one, and not on a split hand.

Walk an example. Ace and six: the hard total is seven, and adding ten gives seventeen, so this is a soft seventeen. Draw a nine: the hard total is sixteen, and adding ten would be twenty six, so the ace drops back to one and the hand is a hard sixteen. Ace, ace, nine is a soft twenty one. The demo checks this rule against a slow count of every ace combination on twenty thousand random hands.

Hand.value()
int hard = sum of points, ace = 1
if (hasAce() && hard + 10 <= 21)
  return hard + 10;   // soft
return hard;          // hard

isSoft():  an ace is counting 11
isBust():  value() > 21
isBlackjack(): 2 cards, 21,
  and not from a split
Walk one hand
  • A, 6: hard 7, plus 10 fits
  • value 17, soft
  • add 9: hard 16, plus 10 = 26
  • too big: value 16, hard
  • A, A, 9: hard 11, plus 10 = 21
  • value 21, soft
  • the demo checks this against a
  • brute force on 20000 hands

Strategy: players

How a player decides is the Strategy pattern. The interface has one method, decide, which receives a read-only view of the hand, the dealer's face-up card and the set of actions allowed right now, and returns an action. A human strategy returns the next button press. A bot computes a move. A card counting bot or a remote player later is just another class.

PlayerStrategy
interface PlayerStrategy {
  Action decide(HandView hand,
                Card dealerUp,
                Set<Action> allowed);
}

ScriptedHuman: next click from the UI
SimpleBot: short basic strategy
CountingBot, RemotePlayer:
  new classes, table unchanged

Strategy: the bot

The table, not the strategy, decides what is legal. Hit and stand are always allowed. Double needs exactly two cards and enough money for a second bet. Split needs a pair, enough money and room under the hand limit. The bot follows a short version of basic strategy: split aces and eights, double a hard eleven, hit small hands, and hit twelve to sixteen when the dealer shows seven or more.

allowed() and SimpleBot
HIT, STAND: always
DOUBLE: two cards, wallet covers bet
SPLIT: a pair, wallet covers bet,
  hands below maxHands

bot: split aces and eights
  double on hard 11
  hit below 12; hit 12 to 16 vs 7+
  soft: hit to 17, else stand

Round state machine

A round moves through four phases. Begin round opens betting, and this is the only moment the shoe may be reshuffled. Deal moves to player turns, or straight to the dealer's turn if the dealer has blackjack. When every hand is finished, the dealer plays, every hand is paid, and the round is settled. Each public method first checks the phase, so dealing twice or betting mid-hand is simply rejected.

Phases
  • SETTLED to BETTING: beginRound()
  • reshuffle here if needed
  • BETTING to PLAYER_TURNS: deal()
  • dealer blackjack: skip ahead
  • PLAYER_TURNS to DEALER_TURN
  • playPlayers()
  • DEALER_TURN to SETTLED
  • finishRound(): draw, then pay
  • wrong phase: IllegalStateException

Flow: bet and deal

Walk the start of a round. Asha bets ten. The wallet is debited right away, so a bet can never be placed with money the player does not have. Deal gives one card to each hand and one to the dealer, then a second round, with the dealer's second card face down. If the dealer has blackjack, the dealer peeks and the round jumps to settlement, because no decision can beat it.

bet() and deal()
bet: expect(BETTING)
  wallet.debit(cents)
  hands.add(new Hand(cents, false))
deal: one card to each hand,
  one to the dealer, then again
  (dealer second card face down)
dealer.isBlackjack()?
  phase = DEALER_TURN (peek)
else phase = PLAYER_TURNS

Flow: player turn

Each hand is played in a loop. If it is already twenty one or bust, it is finished. Otherwise compute the allowed actions, ask the strategy, and check the answer. An illegal action, like a split on a hand that is not a pair, is rejected and the strategy is asked again; after three bad answers the hand stands, so a broken client cannot freeze the table. Hit adds a card. Double debits a second bet, adds exactly one card and ends the hand.

playHand(player, hand)
while (!hand.done) {
  if (hand.value() >= 21) break;
  allowed = allowed(player, hand);
  a = strategy.decide(view, up, allowed);
  if (!allowed.contains(a)) {
    emit rejected; ask again
    (three strikes: stand)
  } else apply(player, hand, a);
}

Split

Split shows why the bet sits on the hand. Debit a second bet, move the second card into a new hand, and give each hand one fresh card. Mark both as split hands, since twenty one after a split is not a blackjack. The new hand is inserted right after the current one, and because the table loops over hands by index, it is played next. Split aces get one card each and stop.

apply(SPLIT)
wallet.debit(hand.bet)
second = new Hand(hand.bet, true)
second.add(hand.cards.remove(1))
hand.fromSplit = true
hand.add(draw); second.add(draw)
hands.add(indexOf(hand) + 1, second)
split aces: both hands done

loop over hands by index:
  the new hand is played next

Dealer rules

The dealer makes no decisions, so the dealer is not a strategy, just a rule. Draw while below seventeen. On exactly seventeen with a soft ace, draw only if the table rule says hit soft seventeen. With an ace and a six and then a four in the shoe, one rule stands on seventeen and the other ends on twenty one. If every player has already busted, the dealer does not draw at all.

playDealer()
while (d.value() < 17
    || (d.value() == 17 && d.isSoft()
        && rules.dealerHitsSoft17()))
  d.add(shoe.draw());

A, 6 then 4 in the shoe:
  stand on soft 17: dealer has 17
  hit soft 17: dealer has 21
all players bust: dealer skips

Settlement

Settle each hand with checks in a fixed order. A player who busted loses, even if the dealer busts later; that is the house edge. A player blackjack pushes against a dealer blackjack and otherwise pays three to two. A dealer blackjack beats everything else. Then a dealer bust or a higher total wins, equal totals push, and anything else loses. The outcome enum knows how much to pay back, stake included.

outcome(hand, dealer)
player bust: LOSE
player blackjack: dealer bj? PUSH
                  else BLACKJACK
dealer blackjack: LOSE
dealer bust or higher: WIN
equal: PUSH, else LOSE

returned: BJ stake + stake * 3 / 2
  WIN 2 x stake, PUSH stake, LOSE 0

Money

Money is a long count of cents, never a double. Every stake is debited before play, and every payout is a credit, so the wallet never goes negative. Three to two on an odd number of cents rounds down, which you should state. The table keeps a house balance of stakes held minus amounts paid, and the demo checks after every round that wallets plus house always add up to the starting total.

Wallet
synchronized void debit(long amount)
  throws if amount > cents
synchronized void credit(long amount)

money: long cents, never double
10.00 blackjack: 1000 + 1500 cents
odd stakes: 3 / 2 rounds down

test: wallets + house = constant

Observer

The table never prints or draws anything. It publishes events: dealer shows a six, Ravi splits, Asha wins with blackjack and is paid twenty five. A card table view, a casino audit log and a statistics service all subscribe in the same way. Listeners sit in a copy-on-write list, so a spectator can join while the round is running.

Concurrency

On one device there is no concurrency. Online, players click at the same time and retry slow requests. Make the table methods synchronized, so the phase check and the change happen under one lock, or run each table on its own actor thread with actions in a queue. The wallet has its own lock, because one person might play at two tables at once. Different tables never wait on each other.

Online tables
  • table methods synchronized:
  • phase check and change under
  • one lock
  • or one actor thread per table,
  • actions in a queue
  • wallet: its own lock, it may
  • be used at two tables
  • tables never block each other

Extensibility

Interviewers will add rules. Insurance and surrender are new actions plus flags on the rules record. Side bets become a side bet interface settled right after the deal. A card counting bot is a strategy that also subscribes to the table events to see every card. A continuous shuffling machine is a different shoe. Each change is a new class or a small, contained edit.

Extension points
  • insurance, surrender: new
  • Actions + rules flags
  • side bets: a SideBet interface
  • settled after the deal
  • card counting bot: a Strategy
  • that watches the listener
  • continuous shuffler: a Shoe
  • that reshuffles every round
  • tournaments: chips, not cash

Testing

The full code is below the player. A stacked shoe scripts one round exactly: Asha gets blackjack and is paid three to two, Ravi splits eights, doubles on eleven and wins both hands, and one illegal split is rejected. The soft seventeen rule is shown both ways. Then three bots play two thousand rounds from a seeded six deck shoe, with the same result every run and no cent created or lost.

Run it
Ravi splits into [8c, 3s] and [8d, 10d]
Ravi: [8c, 3s, 9h] = 20
rejected: Ravi may not SPLIT now
dealer: [6h, 10c, 7c] = 23 BUST
Asha 115.00, Ravi 130.00
S17 dealer: 17, H17 dealer: 21
Ace values matched brute force
2000 bot rounds, 91 shuffles,
  house won 440.00

Follow-ups

Expect follow-ups. Why is the bet on the hand and not the player? Because splits and doubles change bets per hand. How do you value aces quickly? At most one ace can count as eleven. Is the dealer a strategy? No, the dealer has no choices, only a rule. How do you test without luck? A stacked or seeded shoe. How does a casino fight counting? More decks and an earlier cut card.

Follow-ups to expect
  • why is the bet on the hand?
  • splits and doubles
  • how do you value aces fast?
  • one ace as 11 at most
  • dealer as a Strategy?
  • no: it has no choices
  • test without luck?
  • stacked or seeded shoe
  • stop card counting?
  • more decks, earlier cut card

Say it like this

Here is the short version to say out loud. A table owns a seeded shoe and the seats. A player has a wallet and one or more hands, each with its own bet. Aces count as one, plus ten when it fits. Players are strategies that choose from the actions the table allows. Four phases guard the round, the dealer follows a fixed rule, and wallets plus the house always balance.

In the interview
  • "A table owns a seeded shoe and
  • seats; a player has a wallet
  • and hands, each with its own
  • bet. Aces count one, plus ten
  • if it fits. Players are
  • strategies choosing from allowed
  • actions. Four phases guard the
  • round, and wallets plus house
  • always balance."

Interview questions

How do you compute the value of a hand with aces?

Count every ace as 1 and sum the hand. If there is at least one ace and the sum plus 10 is at most 21, one ace counts as 11 and the hand is soft. Two aces can never both be 11, so no search over combinations is needed.

Why does the bet belong to the Hand and not the Player?

After a split a player holds several hands, each with its own stake, and doubling changes the stake of one hand only. Putting the bet on the hand keeps settlement a simple loop over hands.

How do you make a card game testable when the shuffle is random?

Inject the Random into the Shoe. Tests pass a seeded Random for repeatable long runs, and a stacked shoe that deals a fixed list of cards for exact scenarios. Production passes a SecureRandom.

Should the dealer be a PlayerStrategy?

No. The dealer has no choices: draw below 17, and on a soft 17 follow the table rule. A small static rule driven by a Rules record is clearer than a strategy that pretends to decide.

How do you handle hit soft 17 versus stand on soft 17?

Make it a boolean on the Rules record. The dealer loop draws while the value is below 17, or while it is exactly 17, soft, and the flag is set. The same cards give a different result per table, which the tests check.

How do you stop an action being played in the wrong phase?

Model the round as a state machine with BETTING, PLAYER_TURNS, DEALER_TURN and SETTLED. Every public method checks the current phase first and throws if it does not match, so dealing twice or betting mid-hand is impossible.

How are payouts calculated?

An Outcome enum returns the total paid back with the stake: blackjack pays stake plus stake times 3 / 2, a win pays twice the stake, a push returns the stake and a loss returns nothing. Money is long cents, and odd blackjack payouts round down.

Why does a player who busts lose even if the dealer busts?

The players act first and a bust ends the hand immediately, before the dealer draws. Settlement therefore checks the player bust before anything else. This ordering is where most of the house edge comes from.

How would you run many tables online safely?

Give each table its own lock or actor thread so the phase check and update happen atomically, and reject stale or duplicate actions by phase. Wallets are shared across tables, so they synchronize their own debit and credit.

How would you add a card counting bot?

Write a new PlayerStrategy that also registers as a TableListener, so it sees every card dealt and keeps a running count. It can change its decisions with the count, and a bet-sizing method on the strategy lets it raise bets too. The table itself does not change.