Back in 1989, Nintendo released Tetris for the NES. This detailed article first explains themechanics of how Tetris works, then builds an AI to play the game.
To understand the mechanics of the game, the ROM source was explored. Since the NES was based of the MOS 6502 microprocessor, this involves looking at the 6502 assembly. The article details how the blocks (called Tetriminos) are created and how they move across the screen. The linear feedback shift register used for random number generation is examined. Even details of the legal screen and demo mode are explained.
After the tour through how Tetris works, an algorithm for the AI is presented. This AI is implemented in Lua inside of the FCEUX NES/Famicom emulator. It works by evaluating all of the possible places to put each new Tetrimino, and choosing the best based on a number of criteria. The weighting for each criterion was determined by using a particle swarm optimization.
The source for both the Lua version and a Java version of the code is available with the article. Everything you need to run the AI is available for free, except the Tetris ROM. If you’re interested in how 8 bit games were built, this dissection is a great read.