← MAIN
06 // MARKOV DECISION PROCESS

BLACKJACK

Play hands against the dealer, with the exact best move shown beside every hand.
BANKROLL 500 HOUSE EDGE — RECORD 0 · 0 · 0 NET 0

HOW TO PLAY

The goal is to end with more chips than you started with, by beating the dealer's total without going over 21. Pick a bet and press DEAL, then choose HIT, STAND, DOUBLE or SPLIT, or press t, s, d or p.

The ADVISOR lists the expected chips of each legal move for your hand, from the exact table. Press LEARN to watch the Monte Carlo learner work out the same table from simulated hands.

Game settings
TABLE RULES
DECKS6 · reshuffle at 75%
DEALERstands on all 17s
BLACKJACKpays 3:2
SPLIT / DOUBLEone split · double any two
DEALER
Choose a bet and deal.
YOU
Keys: t hit · s stand · d double · p split · h hint · enter deal
BASIC STRATEGY · EXACT
StandHit DoubleSplit
Solving the table…
MONTE CARLO LEARNER
HANDS 0 AGREEMENT — VALUE LOST —
More settings
Agreement counts the decisive cells: those where the exact best move beats the runner-up by at least 0.01 of a bet.

HOW IT WORKS

Blackjack contains chance, but its rules and the deck's make-up fix every probability, so the best play can be computed exactly. This page uses two methods on the same rules. The first is an exact solver that uses **dynamic programming**, which computes the values of small sub-problems first and reuses them for larger ones. It produces the advisor and the basic-strategy table. The second is a **Monte Carlo** learner. Monte Carlo methods estimate a quantity by averaging the outcomes of random simulations. The learner starts with no knowledge of the probabilities and learns from simulated hands, and its table is then compared with the exact one. While it learns, the learner never reads the solver's values.

Rules and parameters

The rules are the same in the exact solver, the learner and the playable table. The module docstring lists them1, and the playable table follows the same rules2. Each row of the table below points to the code that sets it.

Rule or parameterWhat it meansValue
DecksShoe used for play and simulation6 decks, reshuffled after 75% is dealt34
DealerStands on every total of 17 or more, soft 17 included (S17)DEALER_STAND = 1756
Dealer peekChecks for blackjack under an ace or a ten, before the player actsdealer blackjack ends the round7
BlackjackNatural pays on the bet; a player natural against a dealer natural pushes3:2 (1.5 per unit)89
DoubleDoubles the bet and takes exactly one cardany two cards10
SplitTwo hands from a pair; split aces take one card each and stop; doubling after a split is allowedone split, two hands1112
Exploration rateLearner's epsilon after a number of hands0.2 / (1 + hands / 2000), floor 0.011314
Hands per runChoices on the page, and the server cap10,000, 40,000, 100,000 (cap 100,000)15
Decisive cellCell counted in agreement only if the best action beats the runner-up by this much0.01 of a bet (321 of 330 cells)1617

How these were chosen: the rules are fixed choices, not learned. They match the TABLE RULES panel. The 6-deck shoe and the 75% reshuffle point are the defaults of the shoe class3. The exploration constants (start 0.2, floor 0.01, the 2,000-hand scale) and the 0.01 decisive margin were set by hand, and the repository has no sweep over them. The exact solver assumes an infinite deck, so its table is basic strategy for that model. The shoe is where the measured result departs from it.

Dynamic programming (exact)

The solver uses the **infinite-deck** model, in which every card is an independent draw with the probabilities of its value. Under that model the player's decisions form a **Markov decision process** (MDP): a model in which the agent picks an action in each state, and the next state depends only on the current state and the chosen action. A state here is the hard total of the player's hand, whether it holds an ace, whether it still has two cards, and the dealer's upcard18.

A hit always adds a card, so every state's value depends only on states with a larger hard total. The values can therefore be computed from the largest totals downwards, in a recursion with no cycles. This is **backward induction**, the dynamic-programming step that fills in values from the end of the process back to the start. The recursion is **memoised**, which means each result is stored once and reused, so every state is solved once1920.

The dealer draws until its best total is 17 or more, and soft 17 stands. The dealer's final total therefore falls on 17, 18, 19, 20, 21 or bust. For each hard total and ace flag, the solver computes the chance of each outcome by recursing on the dealer's next card, weighted by that card's chance215.

\text{DEALER}(h, a) = \begin{cases} \mathbf{e}_{\text{bust}} & \text{if } h \gt 21 \\ \mathbf{e}_{t-17} & \text{if } t = \text{TOTAL}(h, a) \ge 17 \\ \sum_{v} p_v\,\text{DEALER}\bigl(h + v,\ a \lor [v = 1]\bigr) & \text{otherwise} \end{cases}
21
\text{TOTAL}(h, a) = \begin{cases} h + 10 & \text{if } a \text{ and } h + 10 \le 21 \\ h & \text{otherwise} \end{cases}
22

Here h is a hard total, with every ace counted as 1, and a is true when the hand holds an ace. t is the best total. \mathbf{e}_k is the unit vector with a 1 in position k of the six outcomes, ordered 17, 18, 19, 20, 21 and bust, so bust is position 523. The chance of a card of value v is p_v = 4/13 for v = 10, since the ten, jack, queen and king each have that value, and p_v = 1/13 for the ace (v = 1) through 924. The bracket [v = 1] is 1 when the card is an ace, so a \lor [v = 1] keeps the ace flag.

2122
function DEALER(hard, ace):
    # chances of 17, 18, 19, 20, 21, bust
    if hard > 21:
        return the outcome bust
    best ← TOTAL(hard, ace)
    if best ≥ 17:
        return the outcome best − 17            # soft 17 stands (S17)
    result ← zeros for the six outcomes
    for each card value v with chance p(v):
        result ← result + p(v) × DEALER(hard + v, ace or v = 1)
    return result

Full version. The memo is the @cache decorator on the dealer recursion, so each (hard, ace) pair is computed once25. The total is computed with the ace as 11 only when that keeps the hand at 21 or less, which is what makes a soft total soft22. The division by 1 − p_bj is the renormalisation described next, and it is applied to every outcome.

With an ace or a ten showing, the dealer may hold a blackjack. The hole card that would make it is a ten under an ace, or an ace under a ten. The solver removes that card and rescales the others, because the player's decisions are made only in the cases where the peek found no blackjack. The chance of a dealer blackjack is kept for the last step26.

\mathbf{d}_u = \frac{1}{1 - p_{\text{BJ}}} \sum_{h \ne h^*_u} p_h\,\text{DEALER}\bigl(u + h,\ [u = 1] \lor [h = 1]\bigr), \qquad p_{\text{BJ}} = \begin{cases} p_{10} & u = 1 \\ p_{1} & u = 10 \\ 0 & \text{otherwise} \end{cases}
26

Here u is the upcard value, and h^*_u is the hole card that makes a blackjack with it (10 under an ace, 1 under a ten). For upcards 2 to 9 nothing is removed and p_{\text{BJ}} = 0. \mathbf{d}_u is the dealer's distribution over the six outcomes, given that there is no blackjack.

For each player state the solver computes the value of every legal action, in units of the bet: +1 for a win, −1 for a loss and 0 for a push. Standing compares the player's total T with the dealer's distribution. A dealer bust pays 1. Otherwise the player wins against each dealer total below T, loses to each total above it, and pushes on a tie27.

V_{\text{stand}}(T) = d_{\text{bust}} + \sum_{t=17}^{21} d_t\,\bigl([T \gt t] - [T \lt t]\bigr)
27

Here d_t is the chance that the dealer finishes on total t, and d_{\text{bust}} is the chance that it busts. The brackets are 1 when their comparison holds and 0 otherwise.

Hitting draws one card. If the hard total goes past 21 the hand busts and loses the bet. Otherwise the player continues from a state with a larger hard total, and its best action is already known. Doubling doubles the bet, takes exactly one card and then must stand28.

Q_{\text{hit}}(h, a) = \sum_{v} p_v \begin{cases} -1 & \text{if } h + v \gt 21 \\ \max\bigl(Q_{\text{stand}}, Q_{\text{hit}}\bigr)(h + v,\ a \lor [v = 1]) & \text{otherwise} \end{cases}
20
Q_{\text{double}}(h, a) = 2 \sum_{v} p_v \begin{cases} -1 & \text{if } h + v \gt 21 \\ V_{\text{stand}}\bigl(\text{TOTAL}(h + v,\ a \lor [v = 1])\bigr) & \text{otherwise} \end{cases}
29

Here Q_a(h, a) is the conditional value of action a, meaning the value with no dealer blackjack. The factor 2 in the double is the doubled bet. In the hit formula, the maximum is taken over stand and hit only, because the state reached has more than two cards and cannot double.

Split. A pair of value r can split, and its two hands are then worth one unit each. The formula for the split is written for each card x that completes one hand. An ace split takes one card each and stands on the soft total 1 + x, which is its only action. Any other split hand can hit or double, but it cannot split again30.

Q_{\text{split}}(r) = 2 \sum_{x} p_x \begin{cases} V_{\text{stand}}\bigl(\text{TOTAL}(1 + x,\ \text{true})\bigr) & \text{if } r = 1 \\ \max\bigl(Q_{\text{stand}}, Q_{\text{hit}}, Q_{\text{double}}\bigr)(r + x,\ [x = 1]) & \text{otherwise} \end{cases}
30

Here r is the card value of the pair (1 for a pair of aces), and x is the card that completes one of the two hands. Under the infinite deck the two hands are independent, so the split is twice the average, over x, of one hand's best play.

313227
function VALUES(hard, ace, two, u):
    # conditional on no dealer blackjack
    dist ← the dealer's outcomes for upcard u
    values ← {stand: STAND-VALUE(TOTAL(hard, ace), dist)}
    values[hit] ← 0
    for each card value v with chance p(v):
        if hard + v > 21:
            values[hit] ← values[hit] − p(v)       # busted: lose the bet
        else:
            values[hit] ← values[hit] + p(v) × max(VALUES(hard + v, ace or v = 1, no, u))
    if two:
        values[double] ← 2 × (the same sum, with one card and then a stand)
    return values

Full version. VALUES is _state and STAND-VALUE is stand_value in solver.py3127. The split values come from PAIR-VALUES30, and ADJUST applies the peek33. A pair's non-split actions are valued as a two-card hand with the pair's total, since PAIR-VALUES calls VALUES with that total and the two-card flag set. The ace flag is kept with the hard total, so a soft total stays soft after a hit. The memo is keyed by the two-card flag too, because a hand with two cards may double and a longer hand may not.

A dealer blackjack costs the opening bet whatever the player does, because the peek ends the round before the player acts. Each conditional value Q_a is therefore mapped to V_a = -p_{\text{BJ}} + (1 - p_{\text{BJ}})\,Q_a33. The map is increasing, so the best action is the same with or without the peek. A player natural pays 3:2 unless the dealer has a blackjack, which pushes it. Its value is therefore (1 - p_{\text{BJ}}) \times 1.534.

Example. Against a dealer 6, the dealer's outcome distribution is 17: 0.165, 18: 0.106, 19: 0.106, 20: 0.102, 21: 0.097, and bust: 0.423, from the code26. A hard 11 that stands is worth 0.423 − 0.577 = −0.154, because 11 loses to every total from 17 to 21. Hitting once is worth 0.334, and doubling is worth 0.667. The exact table therefore doubles 11 against a 6.

Basic strategy and the advisor

The strategy table has 33 rows and 10 upcards, 330 cells in all. The rows are the hard totals 5 to 19, the soft totals A,2 to A,9, and the ten pairs (A,A to 10,10). Hard 4 and hard 20 have no two-card form except the pairs 2,2 and 10,10, so those pairs stand in for them35. Each cell shows the action with the highest value, and the cell's brightness shows that value. The advisor uses the same values for the exact hand in front of the player, with the same peek, natural and split-ace rules3637.

3637
function ADVISE(cards, u):
    # best action for one hand
    values ← ACTION-VALUES(cards, u)
    return the action with the highest value

Full version. ACTION-VALUES is hand_values, which the advisor and the simulation call, and ADVISE is basic_action, whose results are cached, up to 200,000 entries3637. The natural check comes first. A split hand that makes 21 is not a natural, so it falls through to the normal values and pays 1:1. A hand from a split can never split again, so the pair branch is skipped for it.

\text{EDGE} = -\sum_{u} \sum_{c_1} \sum_{c_2} p_u\,p_{c_1}\,p_{c_2}\,\max_{a}\, Q_a(c_1, c_2, u)
38

Here u is the upcard, and c_1 and c_2 are the player's first two cards, each drawn independently from the infinite deck. Q_a includes the peek, and the maximum is the best action for that opening hand. A positive edge means the house wins on average. With perfect basic strategy the edge is 0.570% of each bet38.

Monte Carlo control (the learner)

Monte Carlo control learns action values from sampled episodes, here simulated hands, and improves its policy as it goes. The action value Q(s, a) is the expected payoff of taking action a in state s and then playing on. The learner estimates Q as the average payoff of the hands in which that action was taken. It draws cards from the same infinite deck as the solver, so the two are comparable39.

Each round starts from a uniformly chosen cell of the strategy table: an upcard, and a two-card hand that makes the row. Without this, rare starts such as a two-card 5 against a 6 would be seen only a few times in a thousand hands. Starting from a state does not bias that state's estimates, because a value is the payoff from that state onward. The first decision of each round is chosen uniformly among the legal actions, so each action at each cell is tried about equally often over a run404142.

Stand, hit and double each have one estimate per upcard, hard total and ace flag. The future after a stand or hit does not depend on how many cards the hand already holds, so every hand that passes through a state teaches the same estimate. Double is offered only on two cards. Split has one estimate per pair4344.

The learner uses no discounting. The only reward arrives when a round settles, and each decision is credited with the payoffs of the hands it affected, in units of the opening bet. A double pays twice45. A split credits its decision with the sum of its two hands' payoffs, because the split is worth both hands464748. The learner's hands are table cells, and none of them is an ace and a ten, so a natural is never learned. Its 3:2 payout is used only by the advisor.

Q(s, a) \leftarrow Q(s, a) + \frac{G - Q(s, a)}{N(s, a)}
49

Here G is the payoff credited to the decision, and N(s, a) is the number of visits to that state and action, including this one. The update is an incremental form of the average, so after N updates Q is the mean of all N payoffs.

Exploration is epsilon-greedy. The exploration rate \varepsilon starts at 0.2, halves at 2,000 hands and decays further, with a floor of 0.011314.

\varepsilon(n) = \max\!\left(0.01,\ \frac{0.2}{1 + n / 2000}\right)
1314

Here n is the number of hands played so far. The rate is 0.2 at the start, 0.1 at 2,000 hands, and reaches the floor of 0.01 at 38,000 hands.

a = \begin{cases} \text{uniform over the legal actions} & \text{if it is the first decision of the hand, or with probability } \varepsilon \\ \arg\max_{a \in A(s)} Q(s, a) & \text{otherwise} \end{cases}
50

Here A(s) is the set of legal actions in state s. An action that has never been tried has Q = 0. Ties go to the option listed first, because the comparison is strict51.

521441
function LEARN(hands):
    # Monte Carlo control with exploring starts
    played ← 0
    repeat hands times:
        ε ← the exploration rate after played hands
        upcard, cards ← a uniform random cell of the strategy table
        play one round from that start, with CHOOSE and ε
        for each decision in the round:          # every visit counts
            UPDATE(the decision, the payoff it affected)
        played ← played + 1

Full version. LEARN and EPISODE are run and _episode in learner.py5352. Hands that begin with a dealer blackjack are skipped, but they still count toward the hands played, so the exploration schedule runs on the same count the page reports54.

A split is a single decision that is credited with both hands. Its entry in the log is replaced when the split happens, so the decision is credited with the sum of the two hands' payoffs, not with the first hand alone55. Only one split is allowed per round, so only the opening hand can have a pair value.

The dealer plays once, after the player's decisions, and only when some hand is still live. The engine settles a round the same way, with the dealer drawing only when a hand has neither busted nor been dealt a natural5657.

4450
function CHOOSE(options, ε, first):
    if first or a random number is below ε:
        return a uniform random option
    return the option with the highest Q               # untried options count as 0

Full version. CHOOSE is _choose, OPTIONS is _options, and HAND is the constructor of _Hand504458. The options are built so that a pair can split only as the opening hand, and double is offered only on two cards. The ace-and-ten natural is never generated by the learner, because the start cells never contain one.

49
function UPDATE(slot, payoff):
    N[slot] ← N[slot] + 1
    Q[slot] ← Q[slot] + (payoff − Q[slot]) ÷ N[slot]     # running mean of the payoffs

Example. A decision affects three hands with payoffs +1, −1 and +1. The running mean after each update is 1, then 0, then 1/3. That equals the plain average (1 − 1 + 1) ÷ 3, which is the point of the incremental form.

Training and tuning

Training is simulation only. Each run starts with empty statistics and no stored model. The page asks the server for 16 snapshots of one run, and each snapshot is the learner's greedy table after an evenly spaced number of hands5960. With a fixed seed, every run gives the same snapshots. The page picks a new random seed each time, so its live numbers differ from the seed 1 results below.

The learner's only parameters are the exploration schedule described above. The exact table only scores the snapshots. It never changes the learner's estimates, so nothing is tuned against it during training.

Results

Two measures compare the learner with the exact table. Agreement is the share of the decisive cells where the learner's greedy move is the exact best move. Value lost is the mean exact value given up per cell by following the learner's moves. An untried cell counts as its worst action for value lost, and as a miss for agreement. Both are computed from the same exact table61.

\text{agreement} = \frac{\#\{c \in D : \pi(c) = a^*(c)\}}{|D|}, \qquad \text{value lost} = \frac{1}{|C|} \sum_{c \in C} \bigl(V^*(c) - V(c, \pi(c))\bigr)
61

Here C is the 330 table cells, and D is the set of decisive cells, 321 of them. \pi(c) is the learner's greedy move in cell c, a^*(c) is the exact best move, V^*(c) is the exact value of that best move, and V(c, \pi(c)) is the exact value of the learner's move. The exact values are taken without the peek, because the learner's rounds never include a dealer blackjack62.

Learning curve. With seed 1, the learner agrees with the exact table on 64.8% of the decisive cells after 20,000 hands, 72.6% after 40,000, 74.5% after 60,000, 75.4% after 80,000 and 78.2% after 100,000. The value lost per cell falls from 0.072 to 0.023 over the same hands. Agreement keeps rising, more slowly as the hands increase63.

HandsAgreement, decisive cellsValue lost per cell
20,00064.8%0.072
40,00072.6%0.039
60,00074.5%0.030
80,00075.4%0.028
100,00078.2%0.023

Shoe check. The exact table was also played through the 6-deck shoe, with its reshuffle at 75%, for 200,000 rounds at seed 1. The measured return is −0.662% of each unit bet, with a standard error of 0.256%. The infinite-deck edge is −0.570%, so the shoe result is within half a standard error of the model6465.