The Tetris Randomiser in 20 Lines of Code
2015-07-17
The Tetris Randomiser that chooses the next tetromino, implemented in Groovy. It could have been shorter, but with efficiency trade-offs.
I chose to implement the TGM2 variant, as described on the Tetris Wiki.
(Update: the wiki has since been updated with a version of the algorithm that is slightly different from the one described when this post was originally made – I’ve written a new version of the algorithm that is 35 lines long!)
def rng = new Random()def blocks = ['T', 'I', 'L', 'J', 'S', 'Z', 'O']def history = ['Z', 'S', 'Z', 'S'] as ArrayDequedef maxTilePosition = 4def nextPiece = {def blockfor (i in 1..6) {block = blocks[rng.]if (!(block in history)) break}maxTilePosition = 7history.history.return block}
It can be called by doing something like:
20.times { print }
With output:
TIJLZTSIJLOSIZTJSOLI