Stack the falling pieces so that full rows clear. The game ends when a new piece cannot appear at the top centre of the board.
Move with the arrow keys, rotate with ↑, X or Z, soft drop with ↓, and hard drop with space. On a phone, the buttons under the board do the same. P pauses.
AI PLAYS hands the moves to the agent, and SHOW AGENT marks its choice for the current piece while you play. The agent starts on the TUNED weights when they load, and HAND-PICKED switches to the hand-written set.
For each falling piece, the agent tries every rotation and every column, scores the board that each placement would leave, and chooses the highest score. That score is a weighted sum of nine features of the board. The shipped weights were tuned automatically. The features, the search and the game rules were written by hand.
The playfield in the game on this page is 10 columns wide and 20 rows high, and row 0 is the bottom row. The board is stored as one integer per row, a bitmask: bit x of a row's integer is set when column x of that row is filled. A row is therefore an integer from 0 to 1023, and a full row is 1023. Clearing a full row is a single comparison. The page's JavaScript uses the same layout.123
There are seven pieces, I, O, T, S, Z, J and L, each made of four cells. A rotation is one distinct orientation of a piece. O has one rotation, I, S and Z have two, and the other three have four.45 Pieces come from a 7-bag: the seven pieces are shuffled and dealt in that order, then the next bag is shuffled. No piece goes more than 12 draws without appearing. A seed fixes the whole sequence, so every strategy in the benchmark plays the same games.6
A piece spawns in the top two rows. The search treats its move as a straight drop from there, and the piece rests at the lowest row where the next row down would overlap a filled cell.7 When it rests, it locks: its cells are written into the board, and every full row is removed, with the rows above it moving down by one.8
A placement is a choice of rotation and leftmost column. A placement is legal when the piece can sit at the top of the board in that column. On an empty board, the counts are 9 for O, 17 for I, S and Z, and 34 for T, J and L.910 Each legal placement is scored on the board that results after the piece locks and full rows clear. The agent takes the highest score.
A greedy search uses only the score of the current piece. With one-piece lookahead, the search also uses the preview, the piece that comes next. It keeps the six best placements of the current piece, a beam of width six. For each one, it finds the best placement of the preview on the resulting board, and adds that score to the candidate's own score. The candidate with the largest sum is chosen.11
Here m is one of the six best placements of the current piece, s_m the board after m locks, p the preview piece, and M(s, p) the set of legal placements of p on board s. Each m' is scored with the same weights on s_m. If the preview has no legal placement, the bonus is -10^{9}, which makes that candidate a forced game over and avoids it unless all six are.
Example. On an empty board the I piece has 17 placements: 7 in its horizontal rotation and 10 in its vertical one. The search scores all 17 and keeps the highest.
The page computes the same placements, feature values and scores in JavaScript, and a test checks that its legal placements match the Python search on the same boards.1415 Each decision is made when a piece spawns, and again when the weights or the lookahead setting change. Every candidate is shown as a ghost. The page then animates the piece turning and sliding to the chosen column and drops it. The slide is shown but is not part of the search. The piece always locks at the chosen placement. When turning and sliding cannot reach it, for example when a block overhangs the path near the top, the piece locks there at once with no animation, so the move the panel describes is the move that happens.16
Game over means that a piece cannot be placed. In the Python training and benchmark games, that happens when no rotation and column is legal. The page's AI uses that same rule, so it plays the same games as the benchmark. Play by hand is different, because a person cannot place a piece by search. In that mode the game ends as soon as the next piece cannot appear at its spawn position, which is the top centre with rotation 0, even if the piece could be placed elsewhere.1718
function BEST-MOVE(board, piece, weights, preview):
moves ← LEGAL-MOVES(board, piece, weights) # every rotation and column
if preview is none:
return the move with the highest score
for each of the six best moves m: # a beam of width six
bonus ← highest score of the preview on the board after m, or −1e9 if none
total ← score(m) + bonus
return the move with the highest total
function BEST-MOVE(board, piece, weights, preview, top-k):
moves ← LEGAL-MOVES(board, piece, weights)
if moves is empty:
return none, moves # no legal placement: game over
if preview is none:
return the first move with the highest score, moves
ranked ← the top-k moves sorted by score, highest first # stable: ties keep search order
best ← none
for each m in ranked:
nxt ← LEGAL-MOVES(board after m, preview, weights)
if nxt is empty:
bonus ← −1e9 # the preview cannot be placed: forced game over
else:
bonus ← the highest score in nxt
total ← score(m) + bonus
if best is none or total > total of best: # strict: an earlier candidate keeps a tie
best ← m, with total as its total
return best, moves
function LEGAL-MOVES(board, piece, weights):
out ← empty list
for each rotation index ri with rotation rot of piece:
for px from 0 to W − rot.width: # px is the leftmost column of the piece
py ← DROP-ROW(board, rot, px)
if py is none:
continue # the spawn spot in this column is blocked
(new-board, lines, eroded) ← LOCK(board, rot, px, py)
(rows, cols, holes, wells, agg, bump) ← BOARD-FEATURES(new-board)
feats ← (py + (rot.height − 1) / 2, eroded, rows, cols, holes, wells, agg, bump, lines)
score ← sum of weights × feats
append (piece, ri, px, py, lines, feats, score, new-board, score) to out
return out
function DROP-ROW(board, rot, px):
y ← number of rows in board − rot.height # the top row of the piece is the top row of the board
if not FITS(board, rot, px, y):
return none
while y > 0 and FITS(board, rot, px, y − 1): # step down while the next row is free
y ← y − 1
return y
function FITS(board, rot, px, py):
if px < 0 or px + rot.width > W or py < 0:
return false
for each row i of rot.masks: # masks[0] is the bottom row of the piece
if py + i < number of rows in board and board[py + i] & (rot.masks[i] << px) ≠ 0:
return false
return true
function LOCK(board, rot, px, py):
rows ← copy of board
for each row i of rot.masks:
if py + i < number of rows in board:
rows[py + i] ← rows[py + i] | (rot.masks[i] << px) # OR the piece into the row
lines ← number of rows in rows equal to full
cleared ← sum of popcount(rot.masks[i]) over piece rows i whose row is full after the piece is added
kept ← the rows that are not full, in order
new-board ← kept, followed by lines empty rows at the top
return new-board, lines, lines × cleared # the third value is the eroded piece cells
The stable sort keeps equal scores in search order, which is rotation first and then column. The strict comparison means that the first candidate to reach a tie keeps it. Without a preview, the search takes the first move with the highest score, the same choice a max over the moves would make.
DROP-ROW returns none when the piece cannot sit at the top in that column, so the column is skipped. When every column is blocked, the list of legal placements is empty.
Erosion is the eroded piece cells feature. It is the number of lines cleared times the piece's own cells in those rows, so a placement that clears lines with many of its cells scores higher.21
After a placement locks and full rows clear, nine features are measured on the resulting board. The first six are the features of Dellacherie's set, a hand-designed set of Tetris features from Pierre Dellacherie's controller: landing height, eroded piece cells, row transitions, column transitions, holes and wells. The last three are board-shape counts: aggregate height, bumpiness and lines cleared. The score of a placement is the weighted sum of its features, and the agent takes the highest score.2223
Here f_k(p) is feature k of placement p, in the order of the feature list, and w_k is its weight. The weights are signed, so a negative weight penalises its feature. Since the agent takes the highest score, multiplying every weight by the same positive number does not change its choice.
The symbols for the nine features are these. Let b_{r,c} be 1 when the cell in row r and column c is filled after the placement, and 0 otherwise. Walls count as filled: b_{r,-1} = b_{r,10} = 1 for every row, and the floor counts as filled below row 0. Let t be one more than the highest filled row, or 0 on an empty board, so rows at or above t are empty. The height h_c of column c is the row number of its highest filled cell plus one, or 0 if the column is empty. For the piece, y is its bottom row, q its height in cells, n its cells in the cleared rows, and \ell the number of lines cleared.
Here f_1 is the landing height, the height of the piece's centre when it lands. f_2 is eroded piece cells, the lines cleared times the piece's cells in them. f_3 counts the row transitions: the changes between filled and empty cells along each row up to the top, with the two walls counted as filled. f_4 counts the column transitions in the same way up each column, with the floor counted as filled and the empty space above the top as empty. f_5 counts the holes, empty cells with a filled cell somewhere above them. f_6 counts the wells, defined below. f_7 is the aggregate height, the sum of the column heights. f_8 is the bumpiness, the sum of the height differences between neighbouring columns. f_9 is the number of lines cleared.
A well cell is an empty cell with a filled cell on each side. The count k_{r,c} is the length of the run of well cells in column c that ends at row r, with k_{-1,c} = 0. A run of length d adds 1 + 2 + \cdots + d to f_6, which is the cumulative well depth. The column height h_c is the definition used for f_7 and f_8.
Example. A column that is empty between two filled columns, with depth 3 in consecutive rows, adds 1 + 2 + 3 = 6 to the wells feature.
function BOARD-FEATURES(board):
row-transitions ← filled/empty changes along each row, walls counted as filled
column-transitions ← filled/empty changes up each column, floor counted as filled
holes ← empty cells that have a filled cell above them
wells ← each run of well cells in a column adds 1 + 2 + ... + depth
aggregate ← sum of the column heights
bumpiness ← sum of height differences between neighbouring columns
return the six counts
function BOARD-FEATURES(board):
t ← 0 # one above the highest filled row
for r from number of rows − 1 down to 0:
if board[r] ≠ 0:
t ← r + 1
break
row-transitions ← 0
for r from 0 to t − 1:
row-transitions ← row-transitions + TRANSITIONS(board[r])
column-transitions ← 0
prev ← full # the floor counts as filled
for r from 0 to t − 1:
column-transitions ← column-transitions + popcount(prev ⊕ board[r])
prev ← board[r]
column-transitions ← column-transitions + popcount(prev) # the top row against the empty space above
seen ← 0 # the OR of the rows above the current row
holes ← 0
aggregate ← 0
heights ← ten zeros
for r from t − 1 down to 0:
holes ← holes + popcount(seen & ~board[r] & full) # empty cells with a filled cell above
for each column c whose bit is set in board[r] & ~seen: # the column's top is in this row
heights[c] ← r + 1
seen ← seen | board[r]
aggregate ← aggregate + popcount(seen) # each column counts once for each row it reaches
bumpiness ← sum of |heights[c] − heights[c + 1]| for c from 0 to 8
wells ← 0
run ← ten zeros # run[c]: length of the well run in column c so far
for r from 0 to t − 1:
left ← ((board[r] << 1) | 1) & full # bit c: column c − 1 filled, a wall for c = 0
right ← (board[r] >> 1) | (1 << 9) # bit c: column c + 1 filled, a wall for c = 9
well ← ~board[r] & left & right & full
for c from 0 to 9:
if bit c of well is set:
run[c] ← run[c] + 1
wells ← wells + run[c]
else:
run[c] ← 0
return row-transitions, column-transitions, holes, wells, aggregate, bumpiness
function TRANSITIONS(mask):
e ← (mask << 1) | 1 | (1 << 11) # bit 0 and bit 11 are walls, bits 1 to 10 are the cells
return popcount((e ⊕ (e >> 1)) & 2047) # bit k is set where bits k and k + 1 differ
The walk from the top down finds the holes and the heights in one pass. The variable \text{seen} holds every filled cell above the current row, so an empty cell that is in \text{seen} is a hole, and a column first reached in row r has height r + 1.
Rows above the top are empty and are not read, so the empty space above the stack does not change the row or the hole counts. The column transitions still see that space, through the final term that compares the top row with an empty row.
Row transitions use a lookup table over all 1,024 row patterns, so each row costs one table read. The wells counter resets to zero in any row where the column is not a well cell, so each run of depth d adds 1 + 2 + \cdots + d in total.
The table below lists the nine weights. The hand-picked set uses the six Dellacherie features with rounded, hand-chosen sizes, and zero on the other three. It was not tuned here. The v3 set is the CEM result, started from the hand-picked set. The v2 set is the GA result, started from random weights. The weights only make sense together, since the choice depends on their relative sizes.343536
| Feature | What it measures | Hand-picked | Tuned v3 (CEM) | GA v2 |
|---|---|---|---|---|
| landing height | Height of the piece's centre when it lands. Higher is worse. | -1.00 | -2.50 | -0.35 |
| eroded cells | Lines cleared times this piece's cells in them. | +1.00 | +2.51 | -0.78 |
| row transitions | Filled and empty changes along each row, walls counted as filled. | -1.00 | -1.62 | +0.13 |
| column transitions | Filled and empty changes up each column, floor counted as filled. | -1.00 | -5.50 | -0.98 |
| holes | Empty cells with a block somewhere above them. | -4.00 | -5.01 | -1.18 |
| wells | Cumulative well depth: a well of depth d adds 1 + 2 + ... + d. | -1.00 | -2.47 | -0.16 |
| aggregate height | Sum of the column heights. | 0.00 | -0.24 | -0.92 |
| bumpiness | Sum of height differences between neighbouring columns. | 0.00 | +1.32 | -0.44 |
| lines cleared | Full rows this placement completes. | 0.00 | -0.19 | +0.76 |
The cross-entropy method (CEM) is a search over parameter vectors. It keeps a probability distribution over them, here a Gaussian, samples candidates from it, and moves the distribution toward the best candidates. Szita and Lorincz (2006) applied a noisy version of this method to learning Tetris weights, and the shipped weights come from it.37
Each iteration samples 20 weight vectors, scores each one by playing games, keeps the best 15% as the elite set, and refits the Gaussian to the elites. The Gaussian has a mean and a variance for each weight, so the nine weights are sampled independently. The noise is an extra variance added at every refit. It keeps the distribution wide, so the search does not collapse onto one early elite.38
Here \mu_j and \sigma_j are the mean and standard deviation of weight j, and \xi is a standard normal draw. The clip keeps each weight between −10 and 10, the same limit as the GA. L(w, s) is the number of lines that the greedy agent with weights w clears on seed s, playing until game over or until 100,000 pieces. Iteration t uses the three seeds 200\,000 + 3t + k, so each iteration plays its own games, and every sample in an iteration plays the same games. The elite count is n_e = 3. The noise z_t starts at 1.0, falls by 0.05 each iteration, and stops at its floor of 0.05 from iteration 19.
Example. In the committed run's last iteration, t = 5, so z_t = 0.75. The elite mean of that iteration was 6,869.4 lines.48
function CROSS-ENTROPY(iterations, samples):
mu ← the hand-picked weights # the mean starts at the hand-picked set
sigma ← 1.0 for each of the nine weights
repeat iterations times:
draw samples weight vectors from the Gaussian (mu, sigma), clipped to ±10
score each one by its mean lines over this iteration's games
elites ← the best 15% of the samples
mu ← the mean of the elites
sigma ← the spread of the elites, plus a shrinking extra variance
return mu # the final mean, not a sample
function CROSS-ENTROPY(iterations, samples, games):
mu ← the hand-picked weights # the mean starts at the hand-picked set
sigma ← 1.0 for each of the nine weights # the standard deviations
n-elite ← max(2, ceil(0.15 × samples)) # 3 of the 20 samples
best ← none
for t from 0 to iterations − 1:
seeds ← 200000 + games × t + k for k from 0 to games − 1 # fresh seeds for this iteration
for i from 0 to samples − 1:
w[i] ← for each weight j: clip(mu[j] + sigma[j] × (a standard normal draw), −10, 10)
fit[i] ← mean of LINES(w[i], s) over the seeds s
order ← the sample indices sorted by fit, highest first
elites ← the first n-elite samples in order
if best is none or fit[order[0]] > fitness of best: # kept for reference only
best ← w[order[0]], with its fitness
z ← max(0.05, 1.0 × (1 − t / 20)) # the extra variance (the noise)
for each weight j:
mu[j] ← the mean of elites[j] over the elites
sigma[j] ← sqrt(the mean over the elites of (elite[j] − mu[j]) squared, plus z)
return mu # the final mean, not a sampled vector
function LINES(w, s):
play the greedy agent with weights w on seed s, until game over or 100000 pieces
return the lines cleared
The noise is the part that keeps the search from collapsing. Without it, the variance can shrink quickly, and the search stops exploring. The extra term z_t sets a floor for the variance that falls over the run.
The returned weights are the final mean \mu, and that mean is not one of the samples. The training fitness reported for the run is the elite mean of the last iteration, which scores the samples and not \mu itself. The best single sample is recorded only for reference, since it was picked on the same games that scored it.5051
The committed run used 6 iterations, 20 samples per iteration, 3 games per sample, an elite fraction of 0.15, a 10-row training board, a cap of 100,000 pieces, an initial standard deviation of 1.0 and sampler seed 0. Its mean after the sixth refit is the shipped set. Its training fitness, 6,869.4 lines, is the elite mean of the last iteration.3552
The genetic algorithm (GA) was the first tuner. It keeps a population of weight vectors called genomes. Each generation makes a new population from the fittest genomes, using selection (keeping the better parents), crossover (combining two parents) and mutation (small random changes). Its result, v2, cleared fewer lines than the hand-picked weights on held-out games, so the shipped weights come from the CEM. The GA remains in the code, and its training log is committed.53
Here L(w, s) is the lines cleared by the greedy agent with weights w on seed s, with each game capped at 2,500 pieces. In the first formula, g is the generation number, and each generation plays six games with its own seeds, so no generation plays another generation's games. In the second, a and b are the two parents. Each gene has its own \tau_j. Crossover happens with probability 0.8, and otherwise the child copies the first parent. Each gene mutates with probability 0.2, and a mutated gene gets a Gaussian step with standard deviation 0.3.
A tournament draws three different genomes at random and keeps the fittest. Each child uses two tournaments, one for each parent. The population has 16 genomes, and the two fittest are copied unchanged into the next generation, which is called elitism. The loop evaluates generations 0 to 16. That is 17 evaluations and 16 rounds of breeding, the 16 generations of the setting plus the random starting generation.60
function GENETIC-TUNE(generations):
pop ← 16 random weight vectors, each weight uniform in [−1, 1]
for each generation from 0 to generations:
score each genome by its mean lines over this generation's games
nxt ← the two best genomes, copied unchanged
while nxt has fewer than 16 genomes:
choose two parents by tournament
child ← crossover of the parents, then mutation
add child to nxt
pop ← nxt
return the best genome seen in any generation
function GENETIC-TUNE(generations, population, games):
pop ← population random genomes, each weight drawn uniformly from [−1, 1]
for gen from 0 to generations: # generation 0 is the random start
seeds ← 1000 + games × gen + k for k from 0 to games − 1 # fresh seeds for this generation
for each genome g in pop:
fit[g] ← mean of LINES(g, s) over seeds, each game capped at 2500 pieces
order ← the genomes sorted by fit, highest first
record the best, mean and worst fit of this generation
if gen = generations:
stop
nxt ← copies of the two best genomes # elitism: copied unchanged
while size of nxt < population:
p1 ← TOURNAMENT(pop, fit, 3)
p2 ← TOURNAMENT(pop, fit, 3)
child ← CROSSOVER(p1, p2)
append MUTATE(child) to nxt
pop ← nxt
return the best genome seen in any generation, with its fitness
function TOURNAMENT(pop, fit, k):
picks ← k different genomes chosen at random
return the pick with the highest fit
function CROSSOVER(p1, p2):
if a random number is at least 0.8:
return a copy of p1
for each weight j:
τ ← a random number in [0, 1)
child[j] ← τ × p1[j] + (1 − τ) × p2[j]
return child
function MUTATE(genome):
for each weight j:
if a random number is below 0.2:
genome[j] ← clip(genome[j] + a Gaussian step with standard deviation 0.3, −10, 10)
return genome
The two copied genomes are re-evaluated on the next generation's seeds, so an elite's fitness can change from one generation to the next. Elitism keeps good weights in the population, but it does not guarantee that they stay the best.
The reported result is the best genome seen in any generation. Its fitness is measured on the games of the generation where it was found. Because it was chosen for that score, the score is optimistic. For v2, that is 804.5 lines on generation 16's games.3662
The training games and the benchmark games come from separate seed ranges: 200,000 upward for the CEM, 1,000 upward for the GA, and 50,000 to 50,029 for the benchmark. A test checks that two GA generations share no seed.6364
| Setting | CEM (v3, shipped) | GA (v2) | Held-out benchmark |
|---|---|---|---|
| Seeds | 200,000 + 3t + k | 1,000 + 6g + i | 50,000 to 50,029 |
| Candidates | 20 samples, 6 iterations | 16 genomes, generations 0 to 16 | random, hand-picked and one tuned set |
| Games per candidate | 3 per iteration | 6 per generation | 30 per strategy |
| Piece cap per game | 100,000 | 2,500 | 100,000 |
| Board | 10 rows | 10 rows | 10 rows, no lookahead |
| Random seed | 0 (sampler) | 0 (population and breeding) | one seed per game for random placement |
The table gives the settings recorded for the committed runs. The benchmark column describes the held-out runs, which are logged with the results below.6566
The benchmark plays every strategy on the same 30 seeds and reports the mean lines with a 95% confidence interval. The interval is the mean plus or minus the t value times the standard error, where the standard error is the sample standard deviation divided by the square root of the number of games.67
Here \bar{x} is the mean number of lines over the games, s the sample standard deviation, and n the number of games. With 30 games, t_{0.975,\,29} = 2.045, which the code reads from its table of two-sided 95% values.
| Agent | Mean lines | 95% CI | Median | Mean pieces | Hit cap |
|---|---|---|---|---|---|
| random placement | 0.0 | ± 0.1 | 0 | 14 | 0 / 30 |
| hand-picked weights | 2128.5 | ± 895.6 | 867 | 5342 | 0 / 30 |
| GA v2 weights | 388.9 | ± 109.0 | 311 | 993 | 0 / 30 |
| CEM v3 weights (shipped) | 6702.0 | ± 2194.9 | 6305 | 16776 | 0 / 30 |
The random, hand-picked and CEM v3 rows come from the v3 run. The GA v2 row comes from the earlier run, which used the v2 weights.6970
The seeds are 50,000 to 50,029 on the 10-row board with no lookahead. Every game was played to game over, with a cap of 100,000 pieces, and no game reached the cap. The CEM weights are the only committed set that beats the hand-picked weights on these seeds. Their 95% intervals do not overlap: 4,507 to 8,897 for the CEM weights, and 1,233 to 3,024 for the hand-picked weights.
There are four caveats. The CEM was one training run of 6 iterations, so the weights are not converged. Training used a 10-row board, but the page plays 20 rows, so these numbers do not measure the page's game. The benchmark uses the Python game-over rule, not the stricter rule on the page. The 20-row results file uses an older table layout and was run on the 10-by-20 board with a 2,000-piece cap.7172
In that 20-row file, every hand-picked, GA and lookahead game reached the 2,000-piece cap while still alive. Each piece adds 4 cells, and each line removes 10, so 2,000 pieces can clear at most 4 × 2,000 / 10 = 800 lines. That is why the survivors sit near 800 lines. The file measures the cap, not the strategies.