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.
- 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
- 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.
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(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.
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
- 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.
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.
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.
- 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: 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.
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.
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.
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.
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.
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.
- 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.
- 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.
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.
- 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.
- "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."