Main menu

Post navigation

Tetris in Haskell

As a functional programming language, Haskell has some benefits, and some weaknesses. One such weakness is input and output. For my Computer Science 8 class at Dartmouth, my partner and I had to create a game of Tetris for our final project.

The Tetris game was based on some board libraries given to us as part of the assignment. The major tasks included creating pieces, stopping pieces from continually dropping when they hit the board or would go off the screen, making sure left and right moves and rotations would keep the piece entirely on the screen, and deciding when the game is over. In addition, we added on optional components of a pause button, a game over screen, and scoring.

I am including here some snippits of the code from the assignment as I found creating Tetris in Haskell required some tricky things.

This code sample split down a defined “Region” into defined “Shapes” and then allowed coordinates to be taken from these for use in calculations. The code is limited to dealing with Rectangles and Polygons, and it eliminates duplicate coordinates to speed up later calculations.

Finally, the Maybe monad – which at first using Haskell seemed like an unneeded alternative for if-then statements – was used many times in this program. Using if-thens may have worked in some places, but the case of and pattern matching allowed by the Maybe type was very helpful. Here is one example, taken from a function which was waiting for a specific keypress to continue: