Slide tiles to combine equal numbers into larger tiles and score points. The game ends when no slide is possible.
Use the arrow keys or W, A, S and D, or swipe on the board, to slide the tiles. A 2 or a 4 appears after each move.
Choose AI PLAY to watch the selected agent play, and choose it again to pause. Keys do nothing while it runs.
This page runs three agents on 2048, a one-player sliding-tile game in which a random tile appears after every move. Expectimax searches a few slides ahead and averages over the random tiles, scoring the positions it reaches with a heuristic evaluation: six board features combined with weights found by an automated search. The n-tuple network uses no search. It adds up values stored in lookup tables for patterns of tiles, and those values were learned by temporal-difference (TD) learning, which moves each estimate toward a target built from the estimate for the next position. The third agent is expectimax with the learned values as its evaluation.
The board is a 4 × 4 grid of cells. A cell is empty or holds a tile with the value 2k. The code stores the exponent k in each cell, with 0 for an empty cell, so 1 is a 2, 2 is a 4, and so on. The 16 cells fit in one 64-bit integer, four bits per cell, which lets the code precompute the result of sliding each possible row1.
A move slides every tile in one of four directions as far as it can go. Two equal tiles that meet while sliding merge once into a tile of double value. A move that leaves the board unchanged is not legal, and the agents ignore it2.
Each merge adds the value of its new tile to the score. A merge that produces exponent k therefore scores 2k points, and a move scores the sum over its merges3.
Here g(s,a) is the number of points that move a scores on board s, and k_m is the exponent of the tile that merge m produces. The sum is empty for a move with no merges.
The afterstate is the board right after a move and before the new tile appears. Write s_a for the afterstate of move a. The agents score afterstates, since the spawn that follows is random and the player does not choose it.
After each move, one spawn adds a 2 with probability 0.9 or a 4 with probability 0.1, in one empty cell chosen uniformly at random4. The page's own game uses the same rule5. With |E(s)| empty cells, a given cell receives a 2 with probability 0.9/|E(s)| and a 4 with probability 0.1/|E(s)|.
The game ends when no legal move remains. There is no winning tile, so play continues past 2048.
Example. With 3 empty cells, a 2 lands in any one of them with probability 0.9/3 = 0.3, and a 4 with probability 0.1/3 \approx 0.033.
Expectimax is a tree search for one-player games with random events. Its nodes come in two kinds. A max node is the player's turn: it takes the best value over the legal moves. A chance node is the spawn: its value is the expectation, the probability-weighted average of the values of its outcomes. The value of a move is therefore the average over the tiles that might appear, not the best or the worst of them.
The tree is cut off at a fixed depth, the number of player slides searched. A search of depth d makes d slides with a spawn between consecutive slides, and scores the afterstate reached by the last slide, before its spawn. That scored position is a leaf. Its value is the evaluation of the board: the heuristic below for the tuned agent, or the learned value for the n-tuple search.
Here A(s) is the set of legal moves in s, E(s) the set of empty cells, s{+}2_c the board with a 2 added in cell c, and d the number of search levels still to go. The points term g(s,a) is counted only when \mathbf{1}_{\text{rewards}} = 1, which is the n-tuple search; the tuned agent scores board shape only. The spawn probabilities 0.9 and 0.1 are the constants on lines 190 and 191 of the code, and the share 1/|E(s)| is line 186. At depth 0 both node types return the evaluation of the board. At the root, the value of move a in a pass of depth D is g(s,a)\,\mathbf{1}_{\text{rewards}} + V_{\text{chance}}(s_a, D-1)8.
Iterative deepening runs the search at depth 1, then depth 2, and so on up to depth 20. Each pass that finishes within the time budget of 0.1 s per move9 replaces the answer of the one before it, and a pass cut short by the clock is discarded10. The move played is therefore the best one from the deepest pass that finished in time.
function EXPECTIMAX(board):
for depth ← 1, 2, 3, ... while time remains: # iterative deepening
for each legal direction d:
value[d] ← CHANCE-NODE(RESULT(board, d), depth − 1)
best ← the direction with the largest value
return best
function CHANCE-NODE(board, depth):
if depth = 0:
return EVALUATE(board)
total ← 0
for each empty cell c: # the random spawn
share ← 1 / |EMPTY-CELLS(board)|
total ← total + 0.9 · share · MAX-NODE(board with a 2 at c, depth)
total ← total + 0.1 · share · MAX-NODE(board with a 4 at c, depth)
return total
function MAX-NODE(board, depth):
if depth = 0 or LEGAL-MOVES(board) is empty:
return EVALUATE(board)
return max over the legal directions d of CHANCE-NODE(RESULT(board, d), depth − 1)
function EXPECTIMAX-MOVE(board, budget):
deadline ← now + budget # the time budget for one move
nodes ← 0
moves ← LEGAL-MOVES(board) # (direction, afterstate, points)
if moves is empty:
raise ERROR("no legal moves")
best ← the first legal direction, at depth 0
for depth ← 1 to 20: # the depth limit
table ← empty # transposition table, reset each pass
try:
for each (d, afterstate, points) in moves:
value[d] ← points + CHANCE-NODE(afterstate, depth − 1, 1.0) # points: n-tuple only
on time-limit reached:
stop # keep the answer of the last finished pass
best ← the direction with the largest value[d], its depth, its values
if now ≥ deadline:
stop
best.nodes ← nodes # counts the unfinished pass too
return best
function MAX-NODE(board, depth, prob):
COUNT-NODE()
moves ← LEGAL-MOVES(board)
if moves is empty or depth = 0:
return EVALUATE(board)
if REWARDS:
return max over moves of points + CHANCE-NODE(afterstate, depth − 1, prob)
return max over moves of CHANCE-NODE(afterstate, depth − 1, prob)
function CHANCE-NODE(board, depth, prob):
COUNT-NODE()
if depth = 0 or prob < 0.0001: # probability cutoff
return EVALUATE(board)
if CACHE and (board, depth) is in table:
return table[(board, depth)]
cells ← EMPTY-CELLS(board)
if cells is empty:
return EVALUATE(board)
share ← 1 / |cells|
total ← 0
for each cell c in cells:
total ← total + 0.9 · share · MAX-NODE(board with a 2 at c, depth, prob · 0.9 · share)
total ← total + 0.1 · share · MAX-NODE(board with a 4 at c, depth, prob · 0.1 · share)
if CACHE:
table[(board, depth)] ← total
return total
function COUNT-NODE():
nodes ← nodes + 1
if nodes mod 256 = 0 and now ≥ deadline:
raise time-limit reached
Ties go to the move listed first in the order Up, Down, Left, Right12. The transposition table is a dictionary from a pair (board, depth) to the value already computed for it, so a position reached by a different order of slides is not searched again. Only chance nodes are stored, and the table is emptied at the start of every pass13, so each pass starts from an empty table.
The probability cutoff stops a line once its probability falls below 0.0001. The probability of a line is the product of the spawn probabilities along it from the root. Such a line is evaluated at once rather than searched, so rare deep spawns do not take up the time budget.
The clock is read every 256 nodes. Past the deadline the search raises a time-limit signal, and the pass in progress is dropped. The node count reported by the page is the total for the whole move, including that dropped pass, which is why it can be larger than the work behind the played move.
The cache key is the board and the depth, without the probability. A value computed on one line can therefore be reused on another line that has a different probability. The cutoff is still checked first at every node, so the approximation affects only the values that the cutoff itself would have left alone.
A heuristic evaluation scores a board without looking further ahead. The tuned agent uses a linear evaluation: a sum of six features, each a number computed from the board, with each feature multiplied by its weight. Each feature is oriented so that a larger value is better. The rewards (empty cells, corner, merges, max tile) are zero or positive, and the penalties (monotonic, smooth) are zero or negative.
Here f_k(s) is feature k of board s and w_k its weight. The six weights are the shipped values in the table below. The tuner keeps every weight at zero or above16, but the shipped smooth weight is negative, so its penalty becomes a reward for roughness.
| Feature | What it measures | Tuned weight |
|---|---|---|
| empty | log2 of the number of empty cells plus 1 | 0.7204 |
| monotonic | How far each row and each column is from a single rising or falling run of tiles, in exponents. Rows and columns each take the less-penalised direction. A penalty, zero or below. | 1.0 |
| smooth | Sum over rows and columns of the exponent differences between neighbouring non-empty tiles, with a minus sign. A penalty, zero or below. | −0.129 |
| corner | The largest exponent if it sits in a corner, otherwise 0 | 0.9022 |
| merges | Number of equal adjacent pairs in rows and columns | 0.2986 |
| max_tile | The largest exponent on the board | 0.8174 |
For one line of the board (a row or a column), let a_1, \dots, a_m be the exponents of its non-empty tiles in order, with empty cells skipped. The code computes three quantities per line. The rising and falling penalties are U_\ell and D_\ell, which the code names up and down. The roughness is \rho_\ell, named rough.
The sums U_\ell, D_\ell and \rho_\ell are zero or negative, because each term is subtracted. A line that only rises has U_\ell = 0, and a line that only falls has D_\ell = 0. The roughness \rho_\ell is zero only when all neighbouring non-empty tiles are equal. The rows are written r and the columns c below.
The monotonic feature takes, for rows and for columns separately, the direction with the smaller penalty, so a board that is sorted in either direction loses nothing. The smooth feature sums the roughness of every row and column. The shipped smooth weight is negative, which turns this penalty into a reward for roughness. The sign is discussed under Results.
Here x_{\ell,j} is the exponent of cell j of line \ell, counting empty cells as 0, and the bracket is 1 when its condition holds and 0 otherwise. The merges feature counts pairs of equal tiles in neighbouring cells, over all rows and all columns. Unlike the smooth feature, it does not skip empty cells, so only truly adjacent pairs count.
Here p(s) is the largest exponent on the board, so the largest tile is worth 2^{p(s)}. The corner feature is p(s) when the largest tile sits in one of the four corners of the 4 × 4 grid, and 0 otherwise. The corners are listed as bit shifts in CORNER_SHIFTS21. The empty-cell feature uses a logarithm so that the first few empty cells count for more than later ones.
Example. The row (8, 8, 2, \text{empty}) has exponents (3, 3, 1, 0). Its one non-empty step from 8 to 2 is 3 − 1 = 2 exponents, so U = -2, D = 0, and \rho = -2, and it has one equal adjacent pair, so m = 1. The code returns these values for this row ((1, -2, 0, -2, 1) with the empty count first).
The six weights were fitted by the cross-entropy method (CEM), a search that keeps a Gaussian distribution over candidate weight vectors and moves the distribution toward the best candidates. The fitness of a candidate is the mean final score of a set of games in which the player is greedy: at every move it picks the slide whose afterstate has the highest linear value. This is a one-move lookahead on the features, with no search and no spawn modelled.
Each generation draws a population of candidate weight vectors from the Gaussian, scores every candidate on the same games, keeps the elite (the highest-scoring candidates), and refits the Gaussian to them. The Gaussian starts with mean 1 and standard deviation 2 for every weight22.
Here \theta is a candidate weight vector, \mu and \sigma are the mean and standard deviation of the Gaussian, and \odot is the element-wise product. The vector z^{(k)} holds six independent standard normal draws. The clip at zero keeps a penalty weight from turning into a reward. F(\theta) is the fitness, the mean score over N games, and \mathcal{E} is the elite, the top e candidates by fitness. The constant 0.05 is added to every standard deviation, so the spread never shrinks to zero. The bounded runs used N = 300 games per candidate, e = 8, population 32 and 20 generations.
The final weight vector is divided by its largest entry, so the largest weight becomes 1.0. Dividing by a positive constant does not change which move is greedy, so the scale is set only for readability. The table above shows these scaled weights.
function TUNE-WEIGHTS():
μ ← 1 for each feature; σ ← 2 for each feature
repeat generations times:
sample candidate weight vectors from the Gaussian (μ, σ), clipped at zero
score each candidate by its mean greedy game score
μ ← the mean of the best candidates
σ ← the standard deviation of the best candidates + 0.05
return the best candidate, scaled so its largest weight is 1
function TUNE(generations, population, elite, games):
μ ← (1, 1, 1, 1, 1, 1); σ ← (2, 2, 2, 2, 2, 2) # one entry per feature
best ← μ; best-score ← −infinity
for generation ← 0 to generations − 1:
for k ← 1 to population:
θ(k) ← max(μ + σ · z(k), 0) # z(k): independent standard normal draws
for each candidate k:
F(k) ← mean of GREEDY-SCORE(θ(k), games, seed ← 1000 + generation)
E ← the elite candidates with the largest F
μ ← the mean of E; σ ← the standard deviation of E + 0.05
if max F > best-score:
best ← the candidate with the largest F; best-score ← that F
record the largest and the mean F of this generation
for each candidate in (best, μ):
score ← mean of GREEDY-SCORE(candidate, 2 · games, seed ← 99)
θ ← the candidate with the larger score
return θ / max(θ), rounded to 4 decimals
function GREEDY-SCORE(θ, games, seed):
boards ← NEW-GAMES(games, seed)
scores ← zeros(games)
repeat for at most 5000 moves, while a game has a legal move:
for each legal direction d, in every live game at once:
q(d) ← θ · FEATURES(RESULT(board, d)) # the features, not the points
a ← the direction with the largest q
scores ← scores + points of a
board ← SPAWN(RESULT(board, a))
return scores
The clip at zero is applied before the fitness is measured16. Every candidate in one generation plays the same games, since the seed is 1000 + generation, so the differences in fitness come from the weights. The points are counted in the score but are not used to choose the move: the greedy player maximises \theta \cdot f(s_a) alone.
The best candidate seen in any generation is kept27. At the end, that candidate and the final mean are each scored again on fresh games with seed 99, twice as many as in a generation, and the better one is kept28. The fresh games stop the choice from favouring a candidate that happened to score well on the generation games.
The shipped weights in game2048/data/heuristic_weights.json15 come from an earlier run that the README records as unbounded, with no settings saved. Its smooth weight is negative. The bounded runs saved as results/game2048_heuristic_weights_v2.json29 and results/game2048_heuristic_weights_v3.json30 used python -m game2048.tune --generations 20 --population 32 --elite 8 --games 300 --seed 0, and both ended with a smooth weight of 0.
An n-tuple network is a value function that is a sum of table lookups. A pattern, or tuple, is a fixed set of cells. The exponents in those cells, read in a fixed order, form an index into a lookup table for that pattern. Each cell holds one of 16 exponent values, so a pattern of n cells has 16^n entries, and each entry is a learned number. The network here has six patterns: four of 5 cells, with 16^5 = 1{,}048{,}576 entries each, and two of 6 cells, with 16^6 = 16{,}777{,}216 entries each31.
Each pattern is read under the 8 symmetries of the square board: four rotations, each with and without a left-right mirror. All 8 readings use the same table for their pattern. A board therefore costs 6 × 8 = 48 lookups32.
Here c_{p,j} is the j-th cell of pattern p, n_p is its size (5 or 6), \sigma is one of the 8 symmetries in the group G, and e_x(s) is the exponent in cell x of board s. The index \iota_{p,\sigma}(s) reads the exponents as base-16 digits, with the first cell as the most significant digit. The value V(s) adds the table entry T_p[\cdot] for every pattern and every symmetry. The code sums in float64 and reads the tables as float16 when it serves the network34.
The network's greedy agent chooses the move with the largest points plus learned value of its afterstate35.
The points term g(s,a) is added because V estimates the future points of a board rather than its immediate score, and the agent compares moves by their total.
| Pattern | Cells (row-major, 4 × row + col) | Shape on the 4 × 4 board |
|---|---|---|
| 1 | 0, 1, 2, 3, 4 | XXXX / X... / .... / .... |
| 2 | 4, 5, 6, 7, 8 | .... / XXXX / X... / .... |
| 3 | 0, 1, 2, 4, 5 | XXX. / XX.. / .... / .... |
| 4 | 4, 5, 6, 8, 9 | .... / XXX. / XX.. / .... |
| 5 | 0, 1, 2, 3, 4, 5 | XXXX / XX.. / .... / .... |
| 6 | 0, 1, 2, 4, 5, 6 | XXX. / XXX. / .... / .... |
Patterns 5 and 6 are two of the 6-cell tuples of the 4 × 6-tuple network of Yeh et al., as used in the TDL2048 demo. The other two, cells 4, 5, 6, 7, 8, 9 and cells 4, 5, 6, 8, 9, 10, were left out to keep the 6-cell tables at two37.
The earlier network used six 5-cell patterns. Its patterns 5 and 6 are the transposes of patterns 3 and 4, so under the 8 symmetries they read the same shapes. Each pattern still had its own table, and the tables were learned separately, so the two pairs are not identical functions. The earlier network therefore had four distinct shapes, and two of its patterns repeated shapes with tables learned separately.
Example. For pattern 1 on a board whose cells 0 to 4 have exponents 1, 2, 0, 0, 3, the index under the identity symmetry is 1 \cdot 16^4 + 2 \cdot 16^3 + 0 + 0 + 3 = 73{,}731. Its entry in T_1 is the value that this reading of the row contributes.
TD(0) is the simplest form of temporal-difference learning. It moves the value of a position toward a target made of the reward of the next step plus the learned value of the position after it, rather than waiting for the final score of the game. Here the positions are afterstates, and the reward is the points of the next move. The trainer follows Szubert and Jaskowski (2014), as its docstring states38.
The training is self-play: the network chooses every move in the games it learns from, using its current values, and the games are played in lockstep, as NumPy arrays, 1,000 at once by default. A finished game is restarted at once.
Here \delta is the TD error, p is the previous afterstate of the same game, and s is the current board. The target is 0 when the game ends, and otherwise the best one-step return from s, which is the points of the best move plus the learned value of its afterstate.
Here \theta_i is a table entry, \alpha = 0.1 is the learning rate (the --alpha default in the training command), \alpha / 48 is the step taken by each lookup, and the sum runs over the n_i reads of entry \theta_i in the current batch, one per board and symmetry. Each entry moves by the mean of the errors that read it, not their sum. The sum made shared entries take steps as large as the batch and diverged, so the average is used41.
The learning rate α = 0.1 is split across the 48 lookups of a board, so each lookup takes a step of α / 48 ≈ 0.002142. Tables are float32 during training and written as float16. In memory they take 72 MiB, which is the two 6-cell tables at 32 MiB each plus the four 5-cell tables at 2 MiB each43.
function TRAIN-TD(games):
repeat, with all games moving one step in lockstep:
for each legal move a, in every game at once:
q(a) ← points(a) + V(afterstate of a)
target ← the largest q(a), or 0 if the game has no legal move
V(previous afterstate) ← V(previous afterstate) + α · (target − V(previous afterstate))
play the best move and spawn a tile
return V
function TRAIN-TD(games, minutes, α):
step ← α / 48 # 6 patterns × 8 symmetries
boards ← NEW-GAMES(games)
previous ← empty list of length games
while elapsed time < minutes · 60:
for each direction d: # all four moves, for every game
after(d), gain(d) ← SLIDE(boards, d)
if after(d) differs from boards: # legal
q(d) ← gain(d) + V(after(d))
else:
q(d) ← −infinity
best ← the direction with the largest q
target ← 0 if every q is −infinity, otherwise the largest q
for the games with a previous afterstate, at once: # the TD(0) update
δ ← target − V(previous)
for each table entry θ read by these boards, in every pattern and symmetry:
θ ← θ + step · (the mean of δ over the boards in this batch that read θ)
for the games with no legal move: # game over
record its score and its largest tile
board ← NEW-GAME; score ← 0; previous ← none
for the other games:
previous ← after(best); score ← score + gain(best)
board ← SPAWN(after(best))
if a minute has passed since the last log:
log the mean score and the reach rates of the last 2,000 finished games
write the tables to disk
return V
The step size is shared out across the lookups, as the first line of the full version shows. Each step updates the previous afterstate once, toward the target built from the current board.
The per-weight average is the only batch-specific part of the update. With 1,000 games in a batch, the same table entry is read by many boards at the start of the game, and averaging keeps its step from growing with the batch size.
The trainer keeps a deque of the last 2,000 finished games45. Its log gives the mean score over that window and the share of games that reached each tile, and it logs once more when it stops46. The current network's run predates that final record, so the figures are its last logged record, at 69.04 minutes: 45,514 games, with a mean score of 52,801 over the last 2,000 games, 2048 reached in 86.35% of them and 4096 in 45.6%, from the log in results/game2048_train_log_v2.jsonl47. The earlier network's last record is 42,980 games at 64.1 minutes, in the log results/game2048_train_log_v1.jsonl48.
The tables below are held-out measurements: the seeds used to measure them were not used by the tuner or the trainer49. The greedy rows share one batch seed, 500000, and the 60-game expectimax rows use seeds 500000 to 500059. Intervals are 95%: normal for the mean and Wilson for the rates. The expectimax rows were measured at 50 ms per move (--budget 0.05), half the 0.1 s the live page uses, so they are not a direct measure of the page's agent. The search rows have only 12 games each, so their intervals are wide.
| Agent | Games | Mean score (95% CI) | Reached 2048 | Reached 4096 | Reached 8192 |
|---|---|---|---|---|---|
| Expectimax, tuned features (shipped weights), 50 ms/move | 60 | 16,954 (15,259 to 18,650) | 11.7% (5.8 to 22.2) | 0.0% (0.0 to 6.0) | 0.0% (0.0 to 6.0) |
| Expectimax, tuned features (bounded weights v3), 50 ms/move | 60 | 18,639 (16,461 to 20,817) | 20.0% (11.8 to 31.8) | 0.0% (0.0 to 6.0) | 0.0% (0.0 to 6.0) |
| N-tuple, greedy, earlier network | 3,000 | 43,970 (43,168 to 44,773) | 83.5% (82.1 to 84.8) | 32.1% (30.5 to 33.8) | 2.1% (1.6 to 2.7) |
| N-tuple, greedy, this network | 3,000 | 54,835 (53,791 to 55,879) | 88.1% (86.9 to 89.2) | 48.7% (46.9 to 50.5) | 6.7% (5.9 to 7.7) |
| N-tuple + expectimax, earlier network, 50 ms/move | 12 | 46,459 (32,404 to 60,513) | 75.0% (46.8 to 91.1) | 41.7% (19.3 to 68.0) | 0.0% (0.0 to 24.3) |
| N-tuple + expectimax, this network, 50 ms/move | 12 | 104,144 (82,370 to 125,919) | 100.0% (75.7 to 100.0) | 91.7% (64.6 to 98.5) | 41.7% (19.3 to 68.0) |
The shipped smoothness is the one the current code computes, which skips empty cells50. An earlier definition, which compared only touching tiles, scored 16,988 (15,131 to 18,844) and 10.0% on the same games51. It is not in the current code and is not shown in the table. The greedy one-move results on the features, over 3,000 games with seed 500000, are 7,074 (6,930 to 7,219) for the shipped weights, with a smooth weight of −0.129, and 5,823 (5,709 to 5,936) and 5,768 (5,657 to 5,880) for the two bounded runs, whose smooth weight is 0, as recorded in results/game2048_heuristic_greedy_heldout.md52. The bounded runs score lower under greedy play. Under expectimax the bounded weights scored about 1,700 points higher on 60 games, but the intervals overlap, so the shipped weights were kept as the tuned agent's evaluation.