Contents
Figure 1: Expectimax Explained: Game AI for Games with Chance (Build a 2048 Bot) — dice are the whole point: when the other side of the board is luck, you average over outcomes instead of assuming the worst
Minimax assumes your opponent plays perfectly. That works for tic-tac-toe, but what happens when the "opponent" is a dice roll or a random tile spawn? Treating randomness as a clever adversary makes your AI far too pessimistic. Expectimax fixes this by averaging over random outcomes instead of fearing them. I will explain the algorithm, build a 2048 engine and bot in Python, and show what depth really buys you. I ran the experiments below, and I will flag where my sample sizes run thin.
Why Minimax Falls Short
In 2048, you pick a direction, tiles slide and merge, and then the game drops a new tile on a random empty square: a 2 with 90% probability, a 4 with 10%. You do not face an enemy. You face luck.
Early 2048 bots treated the game as adversarial and used depth-limited minimax. That approach is sub-optimal, because the game is not trying to hurt you: a spawn that looks "worst" is often just unlikely. A better model treats spawns as random events with known probabilities, and that model is expectimax (also called expectiminimax when a game has both opponents and chance).
The Expectimax Tree
Expectimax alternates two kinds of nodes:
- Max nodes (your turn): try all four moves and take the best value.
- Chance nodes (the game's turn): consider every possible spawn, weight each outcome by its probability, and take the average.
The value of a chance node is an expected value: every empty cell gets equal probability, and each cell spawns a 2 with probability 0.9 or a 4 with probability 0.1. That is the whole difference from minimax. Where minimax picks the worst case at its opponent's nodes, expectimax picks the average. In the code below, depth d means d of your moves, each followed by one random spawn.
Build the 2048 Engine
Speed matters, since a search evaluates thousands of boards per move. The classic trick: store the board as four rows, and precompute how any single row slides. Each cell holds an exponent (0 for empty, 1 for a 2-tile, 2 for a 4-tile, and so on), and a cached function slides a row left and returns the merge score:
from functools import lru_cache
@lru_cache(maxsize=None)
def slide_left(row):
tiles = [x for x in row if x]
out, gained, i = [], 0, 0
while i < len(tiles):
if i + 1 < len(tiles) and tiles[i] == tiles[i+1]:
out.append(tiles[i] + 1); gained += 1 << (tiles[i] + 1); i += 2
else:
out.append(tiles[i]); i += 1
out += [0] * (4 - len(out))
return tuple(out), gained
Every other move derives from this one. Moving right means reverse, slide, reverse. Moving up or down means transpose, then do the same:
def transpose(b):
return tuple(tuple(b[r][c] for r in range(4)) for c in range(4))
def move(b, direction): # 0 left, 1 right, 2 up, 3 down
src = b if direction < 2 else transpose(b)
if direction in (1, 3):
src = tuple(tuple(reversed(r)) for r in src)
rows = [slide_left(r) for r in src]
new = tuple(r for r, _ in rows)
if direction in (1, 3):
new = tuple(tuple(reversed(r)) for r in new)
if direction >= 2:
new = transpose(new)
gained = sum(g for _, g in rows)
return None if new == b else (new, gained)
def empties(b):
return [(i, j) for i in range(4) for j in range(4) if b[i][j] == 0]
def put(b, i, j, v):
nb = [list(r) for r in b]
nb[i][j] = v
return tuple(tuple(r) for r in nb)
The cache turns each row into a lookup after its first appearance, and a move returns None when nothing changes, which gives you legality checking for free.
The Evaluation Function
A depth-limited search cannot play every game to the end, so it needs a heuristic to score boards. The standard ingredients:
- Empty cells: more empty space means more room to maneuver.
- Monotonicity: rows and columns that rise or fall steadily keep big tiles organized.
- Smoothness: neighboring tiles with similar values merge more easily.
- Corner strategy: keep the largest tile in a corner, so one weighted-matrix variant puts its biggest weights in one corner.
One write-up describes weights that grow steeply, so a single large tile in the corner dominates the score. My heuristic scores each row and column with a cached function. The structure follows common open-source 2048 AIs, and I recalled the constants from memory, so treat them as a starting point to tune, not gospel:
@lru_cache(maxsize=None)
def row_h(row):
s = empty = merges = prev = counter = 0
for x in row:
s += x ** 3.5
if x == 0: empty += 1
else:
if prev == x: counter += 1
elif counter > 0: merges += 1 + counter; counter = 0
prev = x
if counter > 0: merges += 1 + counter
left = right = 0.0
for i in range(1, 4):
if row[i-1] > row[i]: left += row[i-1]**4 - row[i]**4
else: right += row[i]**4 - row[i-1]**4
return 200000.0 + 270.0*empty + 700.0*merges - 47.0*min(left, right) - 11.0*s
def heur(b):
return sum(row_h(r) for r in b) + sum(row_h(c) for c in zip(*b))
Each row earns points for empty cells and potential merges, loses points for broken monotonicity, and loses a little for large tile sums.
The Expectimax Code
The search itself takes about 25 lines. Max nodes loop over moves, chance nodes average over spawns, and a cache stores values for boards the search reaches by different move orders:
class Expectimax:
def __init__(self, depth): self.depth = depth; self.cache = {}
def player(self, b, d):
if d == 0: return heur(b)
best = None
for m in range(4):
r = move(b, m)
if r:
v = self.chance(r[0], d)
best = v if best is None or v > best else best
return 0.0 if best is None else best # no legal move: game over
def chance(self, b, d):
key = (b, d)
if key in self.cache: return self.cache[key]
es = empties(b)
if not es: return self.player(b, d) # nothing to spawn
tot = 0.0
for (i, j) in es:
tot += 0.9 * self.player(put(b, i, j, 1), d - 1)
tot += 0.1 * self.player(put(b, i, j, 2), d - 1)
v = tot / len(es)
self.cache[key] = v
return v
def choose(self, b):
self.cache = {}
scored = [(self.chance(r[0], self.depth), m)
for m in range(4) if (r := move(b, m))]
return max(scored)[1] if scored else None
That cache plays the role of a transposition table. It matters: boards repeat constantly across different move orders, and memoising them turns exponential re-search into a lookup.
Results From My Runs
I compared five agents, each playing games with fixed random seeds:
| Agent | Games | Mean score | ≥512 | ≥1024 | ≥2048 | ≥4096 | s/move |
|---|---|---|---|---|---|---|---|
| Random moves | 200 | 1,062 | 0% | 0% | 0% | 0% | ~0 |
| Greedy (heuristic only) | 100 | 4,447 | 28% | 0% | 0% | 0% | ~0.02 |
| Expectimax depth 1 | 100 | 4,261 | 20% | 2% | 0% | 0% | 0.1 |
| Expectimax depth 2 | 30 | 25,344 | 97% | 90% | 57% | 7% | 2.0 |
| Expectimax depth 3 | 3 | 50,421 | 100% | 100% | 100% | 33% | 30.0 |
Here is how I read it, carefully:
- Random play is hopeless. It never reached 512, and its best tile was 256.
- A good heuristic alone gets you partway. Greedy play, which just picks the move with the best resulting board, reached 512 in 28% of games.
- Depth 1 did not help. Averaging over one spawn gave no gain over greedy in my runs. My interpretation, which I have not tested: depth 1 only smooths the evaluation over spawn luck and still cannot see your own follow-up move.
- Depth 2 changes everything. Once the search plans a move, a spawn, and a second move, the bot reached 2048 in 57% of 30 games, with a mean score near 25,000.
- Depth 3 looks stronger but my sample is tiny. All three games reached 2048 and one hit 4096, at about 30 seconds per move. Three games cannot support any rate, so treat that row as a hint. Depth 3 games were slow enough in pure Python that I stopped there.
I did not tune the heuristic, so a better evaluation function would likely lift every row. Published bots report stronger results, but different implementations, heuristics, depth definitions, and hardware make those numbers incomparable with mine.
Making It Faster
Real 2048 bots push depth much further. The techniques that matter:
- Transposition tables: cache boards you have already scored, as the code above does.
- Iterative deepening with a time limit: search depth 1, then 2, then deeper until the clock runs out.
- Bitboards: pack the board into a 64-bit integer and use row lookup tables. Robert Xiao's open-source expectimax player does this and reports searching millions of moves per second.
- Sampling chance nodes: when many cells are empty, evaluate a random subset of spawns instead of all of them, trading accuracy for speed.
- Pruning: some projects combine expectiminimax with alpha-beta pruning, but pruning works less cleanly at chance nodes, because you must bound an average of several outcomes. Validate before you rely on it.
- Parallelism: split the search across cores, which is how published bots reach deeper searches.
Where Expectimax Fits
Expectimax suits games with known probabilities and visible state: backgammon, 2048, and card games with a known deck composition. Its limits matter too:
- It needs a model of the randomness. If you do not know the probabilities, you cannot average.
- It maximizes expected value. Sometimes you want to maximize win probability or minimise disaster, which is a different objective.
- The heuristic carries a lot of weight. A poor evaluation function wastes deep searches.
- The tree grows fast. Chance nodes multiply the branching factor by the number of outcomes.
Reinforcement learning is the alternative, and it is worth reading about. But treat a strong expectimax bot as the baseline any learned agent has to beat, the same lesson that shows up in RL versus classical solver comparisons.
Common Pitfalls
- Using
minat chance nodes. You get a timid, pessimistic bot. - Forgetting probabilities. A 4 spawns 10% of the time, not 50%.
- Ignoring terminal states. A board with no legal moves needs a clear, usually terrible, score.
- Evaluating after the chance node versus before. Be consistent about where your heuristic applies.
- Skipping the cache. Without transpositions, depth 3 explodes.
- Judging from a handful of games. 2048 is high-variance; run dozens of seeded games before you trust a number.
- Tuning on the test seeds. Hold out seeds when you adjust heuristic weights.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Algorithms for Decision Making | expectimax, Markov decision processes, and decision making under uncertainty, with free online chapters and code that extend the ideas here well beyond 2048. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it after your depth-2 bot reaches its first 2048. The book's treatment of chance nodes and utility makes more sense once you have watched an average beat a worst-case assumption in your own code.
Wrapping Up
Expectimax extends minimax to games with randomness: max nodes pick your best move, and chance nodes return the probability-weighted average of the outcomes. For 2048, a decent heuristic plus a two-move lookahead took my bot from a 0% to a 57% rate of reaching 2048, and caching plus a fast row-based engine keeps the search cheap.
Copy the code, run depth 2 over 30 seeds, and watch the best tile climb. Then tune the heuristic constants and see how far you get. If depth 2 already beats greedy by that much, imagine what a tuned evaluation and a bitboard would do. What tile will your bot reach?
Frequently Asked Questions
What is expectimax in simple terms?
Expectimax extends minimax to games with randomness. Max nodes pick your best move, while chance nodes average over every random outcome weighted by its probability. The result is the move with the highest expected score rather than the best guaranteed score.
What is the difference between minimax and expectimax?
Minimax assumes the other player chooses the worst outcome for you, which is right for an opponent and too pessimistic for a dice roll. Expectimax replaces the min node with a probability-weighted average, so luck is modelled instead of feared.
Why is expectimax used for 2048?
In 2048 the only "opponent" is a random tile spawn: a 2 with 90% probability and a 4 with 10%, placed on a uniformly random empty cell. Expectimax can average over those spawns exactly, which is closer to the real game than treating spawns as adversarial.
How deep should the expectimax search go in 2048?
Deeper is better but exponentially slower. A depth-2 search, meaning two of your moves with a spawn after each, is enough to reach 2048 in roughly half my games; depth 3 is stronger but costs tens of seconds per move in pure Python. Caching and a fast board representation matter as much as depth.
Can reinforcement learning beat expectimax at 2048?
Sometimes, but expectimax with a good heuristic is a strong baseline. RL removes the need for a hand-written evaluation function but needs far more training and gives no guarantee about the worst case. Compare any learned agent against expectimax before claiming an improvement.
Sources
[1]Russell and Norvig, Artificial Intelligence: A Modern Approach (4th edition) — expectiminimax, stochastic games, and evaluation functions: aima.cs.berkeley.edu[2]Gabriele Cirulli, 2048 — the original game and its spawn rules (90% twos, 10% fours): github.com[3]Robert Xiao, 2048-ai — an expectimax player with a bitboard representation and edge/corner heuristics: github.com[4]Kochenderfer, Wheeler, and Wray, Algorithms for Decision Making — chance nodes, expected utility, and decision making under uncertainty: algorithmsbook.com[5]Sutton and Barto, Reinforcement Learning: An Introduction (2nd edition) — the learned alternative to explicit search: incompleteideas.net
