← MAIN
PLACEMENT SEARCH // CROSS-ENTROPY TUNING

TETRIS

Each piece goes wherever the weighted score of the resulting board is highest. Play yourself, or watch the agent.
STATUS LOADING LINES 0 PIECES 0 BEST 0

HOW TO PLAY

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.

Game settings
FEATURE WEIGHTS
NEXT
Keys: ← → move · ↑ or X rotate · ↓ soft drop · space hard drop · P pause · H show agent
More settings

HOW IT WORKS

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 board and the pieces

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

Placement search

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

\text{total}(m) = \text{score}(m) + \begin{cases} \max\limits_{m' \in M(s_m,\, p)} \text{score}(m') & M(s_m,\, p) \neq \varnothing \\ -10^{9} & \text{otherwise} \end{cases}
1213

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

1110719820
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

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

Board features and the score

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

\text{score}(p) = \sum_{k=1}^{9} w_k \, f_k(p)
2425

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.

\begin{aligned} f_1 &= y + \tfrac{q-1}{2} \\ f_2 &= \ell \cdot n \\ f_3 &= \sum_{r=0}^{t-1} \sum_{c=-1}^{9} \big[\, b_{r,c} \neq b_{r,c+1} \,\big] \\ f_4 &= \sum_{c=0}^{9} \sum_{r=0}^{t} \big[\, b_{r-1,c} \neq b_{r,c} \,\big] \\ f_5 &= \sum_{c=0}^{9} \sum_{r=0}^{t-1} \big[\, b_{r,c} = 0 \text{ and } b_{r',c} = 1 \text{ for some } r' \text{ with } r < r' < t \,\big] \\ f_6 &= \sum_{c=0}^{9} \sum_{r=0}^{t-1} k_{r,c} \\ f_7 &= \sum_{c=0}^{9} h_c \\ f_8 &= \sum_{c=0}^{8} \lvert h_c - h_{c+1} \rvert \\ f_9 &= \ell \end{aligned}
20262728293031

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.

k_{r,c} = \begin{cases} k_{r-1,c} + 1 & \text{if } b_{r,c} = 0,\; b_{r,c-1} = 1,\; b_{r,c+1} = 1 \\ 0 & \text{otherwise} \end{cases} \qquad h_c = \max\big(\{0\} \cup \{\, r+1 : b_{r,c} = 1 \,\}\big)
313229

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.

3326
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

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

FeatureWhat it measuresHand-pickedTuned v3 (CEM)GA v2
landing heightHeight of the piece's centre when it lands. Higher is worse.-1.00-2.50-0.35
eroded cellsLines cleared times this piece's cells in them.+1.00+2.51-0.78
row transitionsFilled and empty changes along each row, walls counted as filled.-1.00-1.62+0.13
column transitionsFilled and empty changes up each column, floor counted as filled.-1.00-5.50-0.98
holesEmpty cells with a block somewhere above them.-4.00-5.01-1.18
wellsCumulative well depth: a well of depth d adds 1 + 2 + ... + d.-1.00-2.47-0.16
aggregate heightSum of the column heights.0.00-0.24-0.92
bumpinessSum of height differences between neighbouring columns.0.00+1.32-0.44
lines clearedFull rows this placement completes.0.00-0.19+0.76

Cross-entropy method (v3, the shipped weights)

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

w^{(i)}_j = \operatorname{clip}\big(\mu_j + \sigma_j\, \xi^{(i)}_j\big), \qquad \xi^{(i)}_j \sim \mathcal{N}(0, 1), \qquad \operatorname{clip}(x) = \max\big(-10,\ \min(10, x)\big)
3940
F(w) = \frac{1}{G} \sum_{k=0}^{G-1} L\big(w,\; s_{t,k}\big), \qquad s_{t,k} = 200\,000 + G\,t + k
414243
\begin{aligned} E_t &= \text{the } n_e \text{ samples with the highest } F \\ n_e &= \max\big(2,\ \lceil 0.15 \cdot 20 \rceil\big) = 3 \\ \mu_j &\leftarrow \frac{1}{n_e} \sum_{e \in E_t} e_j \\ \sigma_j &\leftarrow \sqrt{\frac{1}{n_e} \sum_{e \in E_t} \big(e_j - \mu_j\big)^2 + z_t} \\ z_t &= \max\big(0.05,\; 1.0 \cdot (1 - t/20)\big) \end{aligned}
44454647

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

4947
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

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

Genetic algorithm (v2, earlier)

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

w_j \sim \mathcal{U}(-1, 1), \qquad F(w) = \frac{1}{6} \sum_{i=0}^{5} L\big(w,\; s_{g,i}\big), \qquad s_{g,i} = 1\,000 + 6\,g + i
545556
\text{child}_j = \tau_j\, a_j + (1 - \tau_j)\, b_j \;\text{ with probability } 0.8, \qquad \tau_j \sim \mathcal{U}(0, 1) w_j \leftarrow \operatorname{clip}\big(w_j + \varepsilon_j\big) \;\text{ with probability } 0.2, \qquad \varepsilon_j \sim \mathcal{N}(0,\, 0.3^2)
575859

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

6061
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

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

Training and benchmark settings

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

SettingCEM (v3, shipped)GA (v2)Held-out benchmark
Seeds200,000 + 3t + k1,000 + 6g + i50,000 to 50,029
Candidates20 samples, 6 iterations16 genomes, generations 0 to 16random, hand-picked and one tuned set
Games per candidate3 per iteration6 per generation30 per strategy
Piece cap per game100,0002,500100,000
Board10 rows10 rows10 rows, no lookahead
Random seed0 (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

Held-out results

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

\bar{x} \pm t_{0.975,\; n-1} \cdot \frac{s}{\sqrt{n}}
6867

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.

AgentMean lines95% CIMedianMean piecesHit cap
random placement0.0± 0.10140 / 30
hand-picked weights2128.5± 895.686753420 / 30
GA v2 weights388.9± 109.03119930 / 30
CEM v3 weights (shipped)6702.0± 2194.96305167760 / 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.