I wanted to learn reinforcement learning by building every layer myself: the game, the baseline to beat, the bridge to Python, the agent, and a way to watch it. The result is Tetris ML (source), a Tetris engine in Go, a DQN agent trained with PyTorch, and a viewer that shows the agent playing and learning. This post goes through it in order and spends as much time on what did not work as on what did.
Updated 2026-10-19: two guesses from the first version are now tested, and there are three new sections on a second agent that uses hold, tucks, spins and T-spins, plus a short one on keeping the dependencies patched.
Why Tetris, and why Go
Tetris is small enough to train on a laptop and still has the parts that make RL interesting: a long horizon (a bad placement hurts ten pieces later), a reward that is rare early on (you cannot clear a line by chance), and a state space too big to enumerate.
I wrote the game in Go because I wanted a fast, deterministic engine with no rendering in it, and did the learning in Python because PyTorch lives there. The one rule I held myself to: training never depends on rendering.
engine (Go, deterministic)
→ server (gRPC, one game per stream)
→ Gymnasium env (Python)
→ DQN training (PyTorch)
→ metrics + snapshots → viewer (Ebitengine)
→ exported agents/*.json → viewer
The engine
The engine has the board, the seven tetrominoes, a 7-bag randomizer, SRS rotation with wall kicks, gravity, locking, line clears and game over. Two decisions mattered later:
- Everything is seeded. One seed fixes the whole piece sequence, so any game can be replayed exactly and two agents can be compared on identical games. This paid off three times: in the baseline, in checking the Go-Python bridge, and in the viewer's replays.
- Rows grow upward and four hidden rows sit above the visible 20. Pieces spawn in the hidden rows; a game ends when a new piece overlaps the stack or a piece locks entirely above the field.
Gravity is simple on purpose: each Step applies one action and then one gravity tick, and a piece that cannot fall locks at once. There is no lock delay. That keeps the environment small, at the cost of realism. (The viewer needed gravity on a timer, so I later split Step into Apply and Gravity without changing Step. Hold, a lock delay and T-spins came later still, see "Making it playable".)
A baseline before any learning
Before training anything I wanted a number to beat. The usual cheap trick is to stop thinking in moves and think in placements: for each piece, list every (rotation, column) it can be dropped at, look at the board that would result, and score it. The score is a weighted sum of four features: aggregate height, holes, bumpiness and lines cleared. I used a widely published set of weights (from Yiyuan Lee's Tetris AI write-up) and did not tune them.
On 100 seeded games, capped at 1000 pieces per game, that heuristic scored 42,591 on average and survived the cap in 96 of 100 games.
That last number was the first lesson. A baseline that never loses cannot rank anything on survival. Raising the cap to 10,000 pieces still left half the games capped (51 of 100). From here on I compared agents on score at a fixed cap and kept in mind that the cap hides differences.
| Cap (pieces) | Avg score | Avg lines | Avg pieces | Hit cap |
|---|---|---|---|---|
| 1,000 | 42,591 | 390.9 | 988.6 | 96/100 |
| 10,000 | 318,458 | 2,915.5 | 7,315.8 | 51/100 |
Bridging Go and Python
The engine runs as a gRPC server: one bidirectional Play stream is one game. The client sends Reset(seed) and then placements, and every request gets back the state, the reward and the list of valid placements. A Python Gymnasium environment talks to it, and vectorized environments run several games in parallel. The action is a single integer, rot * 12 + (x + 2), with an action mask for the valid ones. On my machine, 4 environments reached about 5,200 steps per second and 8 reached about 7,100, where a step is one piece placement.
Checking that the bridge was right was harder than building it. The obvious test, "a random agent gets the same numbers on both sides", does not work: a random agent almost never clears a line in its first 20 pieces, so the scores are near zero and tell you nothing, and Go and Python use different random number generators anyway. So I wrote a deterministic agent whose choice depends only on the piece count, ran it on both sides over 200 seeds, and compared score, lines and pieces per game.
placement index = (7 * pieces) mod count
All 200 games matched. It does not test rewards (the Go unit tests do that), but it does prove both sides see the same game.
The agent
The network does not output a value per action. It scores the board after a placement (the afterstate) from the same four features the heuristic uses, and the agent plays the placement with the highest score. The training target is the usual DQN one: the reward plus the discounted best value among the next piece's placements, from a slowly updated target network.
target = r + gamma * max over next afterstates of V_target(s')
The network is a small MLP (4-64-64-1). The rest is standard: a 50k replay buffer, a hard target update every 1,000 steps, Adam at 1e-3, batch 128, gamma 0.99, and epsilon decaying from 1 to 0.01 over 50,000 steps out of 100,000. Rewards are the line-clear score divided by 100. Training games use seeds from 1,000,000 up, validation (10 greedy games every 10,000 steps) uses 5001-5010 to pick the best checkpoint, and the final numbers use the baseline seeds 1-100, which the agent never trained on.
I ran two reward setups against each other. The raw one gives the line-clear score. The shaped one adds a potential-based term, which changes the learning signal without changing which policy is best:
shaping = gamma * phi(s') - phi(s)
phi = -(0.5 * holes + 0.05 * aggregate_height)
The final network is the animation at the top.
What worked
On the baseline seeds, with a 3000-piece cap:
| Agent | Avg score | Avg lines | Avg pieces |
|---|---|---|---|
| Random placement (1000-piece cap) | 2 | 0.0 | 22.0 |
| Heuristic | 119,880 | 1,098.8 | 2,764.2 |
| DQN, 3 training seeds (mean) | 172,673 | 1,179.8 | 2,962.2 |
| Double DQN, 3 training seeds (mean) | 173,305 | 1,179.4 | 2,961.1 |
The agent beats the heuristic it started from by about 44% on score while playing about as many lines, because it clears them in bigger groups. I first wrote that as a guess and checked it afterwards: 83% of the heuristic's cleared lines come from single-line clears, against 16% for the DQN, which gets 61% of its lines from doubles and 7% from tetrises. A single is worth 100 points per line and a tetris 200, so the same number of lines is worth much more. The heuristic's pieces are lower mainly because 17 of its 100 games ended before the cap; the learned agents rarely did.
The formulation did most of the work. Scoring afterstates and acting on placements shrinks the problem so much that the raw-reward agent was already reaching the 500-piece validation cap after 10,000 steps.
Here is the same comparison with the clear sizes, and with a cap of 3,000 and of 10,000 pieces (seeds 1-100, one training seed each, since only one network per variant is exported):
| Agent | Cap | Avg score | Score / piece | Hit cap | Singles | Doubles | Triples | Tetrises |
|---|---|---|---|---|---|---|---|---|
| Heuristic | 3,000 | 119,880 | 43.4 | 83/100 | 83.0% | 14.2% | 2.3% | 0.5% |
| DQN (seed 0) | 3,000 | 173,983 | 59.0 | 96/100 | 15.9% | 61.4% | 15.4% | 7.4% |
| Double DQN (seed 0) | 3,000 | 173,757 | 58.5 | 99/100 | 18.6% | 59.4% | 14.9% | 7.0% |
| Heuristic | 10,000 | 318,458 | 43.5 | 51/100 | 82.8% | 14.4% | 2.3% | 0.5% |
| DQN (seed 0) | 10,000 | 562,349 | 59.2 | 90/100 | 16.1% | 61.4% | 15.3% | 7.2% |
| Double DQN (seed 0) | 10,000 | 554,858 | 58.6 | 85/100 | 18.5% | 59.2% | 15.1% | 7.1% |
The clear-size columns are the share of all cleared lines that came from clears of that size. I ran these with the Go baseline tool, which can now run any exported network (go run ./cmd/baseline -agent agents/raw.json) using the same code as the viewer. At the 3,000 cap it reproduces the PyTorch evaluation exactly (173,983 for the DQN seed 0, 119,880 for the heuristic), which doubles as a check that the Go and PyTorch networks agree.
What did not work, or did not matter
- The shaped reward did not help, and it got worse before it got better. In its single run the validation score collapsed to about zero (roughly 20 pieces per game) between 20,000 and 60,000 steps and recovered only after epsilon reached its floor at 50,000. At the 1000-piece cap the final scores were 58,539 (raw) and 57,692 (shaped), which is within noise. I have a guess about why (the hole penalty rewarding safe-looking placements while the value estimates are still wrong) but I did not test it.
- Double DQN made no measurable difference. Over three seeds each, it was 0.4% ahead on score (+632), against a spread of about 2,400 points between seeds of the same variant. A likely reason, also untested: the value depends on only four features, so there is little overestimation to correct. I skipped dueling heads on purpose because the network has no per-action outputs to split.
- The measurement was the real problem. At a 1000-piece cap every agent looked the same, so I moved to 3000, and the strongest agents still sat within a few percent of each other. Two fixes helped. Score per piece barely moves with the cap (heuristic 43.4 at 3,000 pieces and 43.5 at 10,000; DQN 59.0 and 59.2), so it compares agents without depending on where I stop the game. And raising the cap to 10,000 pieces finally showed a survival gap that 3,000 hid: the heuristic reached the cap in 51 of 100 games, the DQN in 90 and the Double DQN in 85. The learned agents are more robust, not just higher-scoring. The 90 versus 85 is one training seed each and I do not read anything into it. One of the Double DQN's games ended after only 268 pieces, which alone is enough to pull its average down.
- Things I did not try: PPO, a CNN on the raw board, and a human-versus-agent mode. I also have not re-run the clear-size and 10,000-cap measurements on the other training seeds, because only one network per variant is exported. That is the first thing to do before claiming anything about the spread between seeds.
| Agent | Training seed | Avg score | Avg lines | Avg pieces |
|---|---|---|---|---|
| DQN | 0 | 173,983 | 1,173.3 | 2,948.3 |
| DQN | 1 | 172,449 | 1,195.8 | 3,000.0 |
| DQN | 2 | 171,587 | 1,170.3 | 2,938.4 |
| Double DQN | 0 | 173,757 | 1,184.5 | 2,972.7 |
| Double DQN | 1 | 172,417 | 1,179.8 | 2,962.1 |
| Double DQN | 2 | 173,742 | 1,173.8 | 2,948.6 |
Watching it learn
A plain learning curve says little, so I built a viewer with Ebitengine and a training mode. The training process writes a metrics log and a snapshot of the network every 5,000 steps (including the untrained one at step 0), and the viewer replays the same seed with each snapshot, next to charts for score, validation, loss and epsilon. Because it just reads files, the same view works on a run that is still going. There is also a heatmap of the agent's value for every candidate placement of the current piece, which makes it easy to see when the agent is sure and when it is choosing between near-equal moves.
The viewer runs the exported network itself from JSON, no Python needed. Each exported file carries test vectors computed by PyTorch, and a Go test checks that the Go network reproduces them. The GIFs in this post were recorded by the viewer.
Making it playable
The placement agent only ever picks a final column and rotation, so it never needed the parts of Tetris that make it feel like Tetris. I added them to the engine and the viewer's human mode, as a way to play against what I had built:
- Hold piece. Swap the current piece with a stored one, once per piece.
- Lock delay. A piece resting on the stack waits half a second before it locks, and every move or rotation restarts the wait, at most 15 times per piece, so you cannot stall forever. This is the mechanic that makes sliding and tucking a piece in at the last moment possible.
- T-spins. A T piece that ends on a rotation with three of its four corners blocked scores 400, 800, 1200 or 1600 for 0 to 3 lines. This is the simple three-corner rule, with no mini T-spins.
- Ghost piece showing where a piece would land.
- Five-piece preview. The engine now queues the next five pieces and the viewer shows them in a column. The piece order is unchanged (same 7-bag, one draw per piece), so every seeded result above still holds; the agents still only see the next piece.
The playable game does not touch the placement training: that agent still plays through the placement API, which never rotates in place, so every number above is unchanged. The engine's Step still locks immediately; the lock delay lives in the viewer.
Giving the agent the whole game
A placement agent cannot tuck, slide or spin, so I tried to give it everything. Teaching it key presses directly would make a T-spin a five-step sequence with no reward until the end, the sparse-reward problem again and worse. Instead I wrote a search: from the spawn position, a breadth-first search over left, right, rotate and soft drop finds every spot where a piece can lock, and with hold, every spot for the piece a hold would bring in. That is about 43 candidate moves per position, and the agent picks one. A move remembers the keys that get there, so the viewer can play it out and you can watch the slide or the spin. The server exposes it as a second gRPC stream, PlayMoves, and the Python side as a second environment where the action is an index into the listed moves.
A scripted baseline already benefits. The same four hand-set heuristic weights, now choosing among all moves, reached the 1,000-piece cap in all 20 games (the placement version did in 96 of 100) and made about 24 T-spins and 292 holds per game, without knowing what a T-spin is. The weights say nothing about them; the search simply finds them.
The learned agent failed four times, then worked when I hid the board. I gave the network the board, the held piece and the next piece as input, because four summary features cannot describe a T-slot. In four runs (random initialisation, heuristic warm start, with and without a game-over penalty) it stayed at about 22 pieces per game, which is what random play does, while the placement agent reaches the cap within 10,000 steps. The pipeline was not the cause: a hand-built network with the heuristic weights survives all 500 pieces through the same code, and so does the untrained warm-started network. Training itself degraded it.
I had two suspects. First, the 200 raw board inputs add noise that swamps small differences between candidate moves. Second, a zero-line T-spin pays 400 points, more than a double, which could bait a greedy policy. I tested them one at a time. Paying nothing for zero-line T-spins did not help (the run was worse, 14 pieces per game at 20,000 steps). Hiding the board from the network did: at 30,000 steps it survived 496 of 500 pieces in validation, with 189 lines, 54 T-spins and 217 holds per game, and two more training seeds learned too, both a bit later than the first. So the raw board input is what breaks learning. Why, I can only guess: noise, too much capacity, or the way the input interacts with the warm start would look the same from where I stand.
I then tried to give the board back without breaking it, by multiplying the board inputs by a small number. With Adam that makes the board weights change that many times less per step. At 0.1 the run stayed flat (about 30 pieces per game, so I stopped it at 40,000 steps). At 0.01 it learned, but slowly: it was still under 140 pieces at 70,000 steps and only reached 486 at 90,000. The agent it produced is clearly worse than the board-hidden ones, and its games show why: it builds tall one-column towers with holes underneath. I looked at what its network responds to. Adding a hole changes its value by 0.02 on average, against 1.14 for the board-hidden agent, while a single filled board cell changes it by about 0.4, twenty times more than a hole. It has all but stopped caring about holes and attached its value to individual cells, which do not carry over to new boards. That is my reading of the numbers; I did not test it. So a network can use the board, but only if the board is made 100 times quieter, and what it gets out of it is not better play.
The result, on the 100 seeds the agent never trained on, with a 3,000-piece cap:
| Agent | Score | Lines | Pieces | Reached the cap | Score / piece | T-spins / game |
|---|---|---|---|---|---|---|
| Placement DQN | 173,983 | 1,173 | 2,948 | 96/100 | 59.0 | - |
| Scripted agent choosing among all moves | 164,331 | 1,199 | 3,000 | 100/100 | 54.8 | 70 |
| Learned move agent, seed 0, final network | 241,493 | 985 | 2,481 | 66/100 | 97.4 | 233 |
| Learned move agent, seed 1 | 236,973 | 913 | 2,308 | 54/100 | 102.7 | 254 |
| Learned move agent, seed 2, best-validation network | 285,432 | 1,157 | 2,905 | 94/100 | 98.3 | 313 |
| Learned move agent, seed 2, final network | 104,800 | 406 | 1,046 | 8/100 | 100.2 | 106 |
| Board visible at scale 0.01, final network | 121,679 | 574 | 1,474 | 21/100 | 82.5 | 140 |
The board-hidden agents score about 44% to 74% more than the scripted one when they hold together, and they get there with T-spins, which pay 400 to 1,600 points: 233 to 313 per game against 70, so at least 93,000 of seed 0's 241,000 points. They do not clear more lines (0.40 per piece, the same as every other agent); their clears just shift towards doubles (48% of seed 0's lines, against 90% singles for the scripted agent). They are less robust: they die before 3,000 pieces in 6% to 46% of the games for the good checkpoints, where the scripted agent never does. A higher score and a worse survival rate is a trade, not a clear win, and the score is partly my reward design: a zero-line T-spin pays 400, so an agent can be paid well for a risky stack. Move-agent scores include T-spin points, so they are not directly comparable with the placement scores.
The part I would not skip: one training run is not one agent. The seed 2 network that scored 285,432 at 80,000 steps scored 104,800 at 100,000, with 8 of 100 games reaching the cap. For seed 0 it went the other way: the checkpoint I would have picked from 10 validation games scored 206,816 and the last one 241,493. Averaged over the three seeds, the best-validation picks score 243,074 and the final networks 194,422. The spread inside one run is as large as the gap to the scripted agent, so "the learned agent is better" is something I can say about what it can reach, not about what a given training run gives you. What I would try next: more validation games, a decaying learning rate, and averaging the last checkpoints.
One more detail worth keeping. The board-hidden agent does not find T-spin slots by looking; I think it finds them because the move list already contains them with their reward, but I did not test that.
A 40-line sprint bot
The next goal was a different one: clear 40 lines as fast as possible, the way TETR.IO's 40 LINES mode is scored. The engine has no clock, so I had to decide what "fast" means. I chose key presses: a move costs the keys it takes (every rotation, hold and the final hard drop is one, a held soft drop is one, and a slide into a wall or the stack is one, as with a DAS slide, while stopping in the open costs a press per step), and the agent minimizes the total. A game ends at 40 lines. Because every move's cost scales with the same number of seconds per key, that number changes what the clock shows and not which moves are best. The agent learns on a shaped reward: minus the key time of each move plus a fixed credit per cleared line, so every win collects the same credit and the line credit never changes which win is fastest; it only makes winning worth more than dying.
I downloaded the replay of the current 40 LINES world record and read its numbers: 13.263 s, 100 pieces, 272 inputs (2.72 per piece, 30 of them holds). That is 0.0488 s per input, which is what turns key counts into a human clock. On a bot the limit is not fingers, so I also report a bot clock of one key per game frame (1/60 s). Those two clocks are not the same kind of number, so the key count is the honest comparison.
It learned to finish, then slowly to be quicker. After 10,000 steps it cleared 40 lines in 3 of 10 validation games. From 20,000 steps on it finished every one, at about 450 key presses, and by 80,000 steps that was about 406; it then stayed between 406 and 427. On the 100 seeds it never trained on, with the board hidden from the network as before, the best-validation network (80,000 steps) finished 100 of 100 games with 418.4 keys on average (median 415, fastest 386, slowest 479) and 108 pieces, 100 being the minimum. The final network finished 99 of 100 at 419.1. Go and Python agree exactly (100/100, 418.4, minimum 386), so the viewer shows what was measured.
| Pieces | Keys | Keys / piece | Bot clock (1/60 s per key) | Human clock (0.0488 s per key) | |
|---|---|---|---|---|---|
| World-record replay | 100 | 272 | 2.72 | 4.5 s | 13.3 s |
| Sprint agent, average of 100 games | 108 | 418 | 3.9 | 7.0 s | 20.4 s |
| Sprint agent, fastest game | 103 | 386 | 3.7 | 6.4 s | 18.8 s |
It does not beat the record player's inputs. The agent uses about 54% more keys and 8 more pieces. Its fast bot-clock time comes from assuming one key per frame, not from better play, so I do not call it the fastest bot; it is a bot that finishes reliably under a simple model that has no gravity, lock delay or DAS timing. My key count may also differ a little from TETR.IO's definition of an input, so the 20 s figure is an estimate. Each validation used only 10 games and the curve is flat after 60,000 steps, so I read it as a plateau around 410 to 420 keys, not as a trend.
Two bugs in the viewer were worth fixing along the way. The move search stores a straight drop as about 20 single-row soft drops, so the viewer made the piece creep down and turn at the last second; it now plays a soft-drop run as one instant action, and the search puts slides and rotations before the drop whenever that lands on the same cells. The second run, now training, gives the network two compact board-shape inputs instead of the 200 raw cells it could not learn from: the height of each column and the depth of the well each one forms.
Keeping it patched
Before calling the project done I ran govulncheck on it. It found about two dozen vulnerabilities in the Go standard library, all because the toolchain on my machine was Go 1.25.4, plus some in golang.org/x/net, which gRPC pulls in. The scan says the code reaches some of them through gRPC and Ebitengine, though the server only listens on the loopback address, and they were easy to remove. The fix was to move go.mod to the newer toolchain (Go 1.27.2, which the go command downloads by itself) and upgrade x/net and its neighbours. The newer x/net needs Go 1.26, so the minimum Go version in the README went up from 1.25 to 1.26. govulncheck now reports nothing and the tests pass. pip-audit on the Python side was clean the whole time.
Limits worth stating
- The placement agents never tuck, spin or hold. They train fast and play within a ceiling.
- The move agent has three training seeds, and its checkpoints vary a lot within one run. It ends early in up to half of the 3,000-piece games, and it only learns if the board is hidden or scaled down 100 times.
- The move search assumes the piece can be steered at will, with no gravity and no lock delay, so real play with a 500 ms gravity could not do every listed move.
- T-spins use the three-corner rule only, with no mini T-spins, and a zero-line T-spin pays 400. There are no combos and no back-to-back bonuses.
- The agents see one next piece, even though the engine and viewer now queue five.
- The placement variants have at most three training seeds each, and one for the shaped reward.
- Evaluation is capped at 3,000 pieces (10,000 for the survival check), which still hides differences between the strongest agents.
- Tested on Windows 11 and Linux.
What I would do next
Fix the checkpoint instability first (more validation games, a decaying learning rate, averaging the last checkpoints), then give the move agent its board back without breaking it, for example with compact slot features such as column heights and wells instead of 200 raw cells (a sprint run with exactly those inputs is training now, and I have no result yet). After that: PPO as a genuinely different algorithm instead of another variation on DQN, a survival-focused measure, and the other training seeds for the placement measurements above.
The code, the original plan, the move-agent notes (docs/MOVES.md) and all the run notes are in the repository.