Haskell World logo Haskell WorldWrite code, build worlds
Games

Building Tetris in Haskell With Gloss: What the Types Caught

Every term, around week six, a student in my intro programming course asks the same thing: "This is nice, but can you actually build anything fun in Haskell?" They have written list functions, a few type classes, maybe a parser.

A Tetris board beside Haskell type signatures on a code editor screen

Every term, around week six, a student in my intro programming course asks the same thing: "This is nice, but can you actually build anything fun in Haskell?" They have written list functions, a few type classes, maybe a parser. What they have not done is make something move on a screen, and they suspect that the language that made them think so hard about types will collapse the moment they need a game loop.

So last spring I built a Tetris clone in Haskell, using the Gloss graphics library, to show them. It came to about 380 lines. What surprised me was not that it worked, but which bugs the compiler caught before I ever ran it, and which ones it let straight through. That split is the most useful thing I can tell anyone thinking of writing a small game in Haskell.

Why Gloss makes the game loop disappear

Gloss hides the event loop behind one function. Its signature is the whole architecture of the game:

play :: Display -> Color -> Int -> world -> (world -> Picture) -> (Event -> world -> world) -> (Float -> world -> world) -> IO ()

You hand it a window description, a background colour, a number of simulation steps per second, an initial world, and three pure functions: one to draw the world, one to react to input, one to advance time. Gloss calls them for you. There is no mutable state you manage directly. The entire game is a value of your own world type, transformed over and over.

For students, this is the moment things click. A game turns out to be a fold over events. Our earlier piece on how game logic maps to functional patterns describes the idea in general; Gloss makes it concrete in a dozen lines.

The bugs the types caught

Rows and columns, swapped

Tetris is a 10 by 20 grid, and the classic bug is mixing up x and y. Early on, I represented positions as plain (Int, Int) pairs. I wrote a collision check that indexed the board as row then column, and a drawing function that assumed column then row. The pieces fell sideways. No compiler would catch that with bare tuples.

The fix took ten minutes: two newtypes, Row and Col, and a position record with named fields. Every place that had the order wrong became a type error, and there were four of them, two in code I had not even tested yet. This is the single change I would recommend to anyone writing a grid game in a typed language.

Pieces that could not exist

There are exactly seven tetrominoes: I, O, T, S, Z, J and L. I declared them as a sum type with deriving (Enum, Bounded), which meant I could list all seven with [minBound .. maxBound] and never write the list by hand. When I wrote the function that returns each piece's cells, GHC's incomplete pattern warning, which I always turn on with -Wall, told me I had forgotten the L piece. In a dynamically typed version, I would have found out when an L finally spawned and the game crashed.

Randomness that did not fit

Modern Tetris games use a "7-bag" randomiser: shuffle all seven pieces, deal them out, then shuffle again. It guarantees you never wait more than 12 pieces for a particular shape. My first attempt reached for randomRIO inside the update function, and of course it would not compile, since the update function is pure and returns a world, not IO world.

That error annoyed me for about a minute and then improved the design. I put a StdGen inside the world record and threaded it through. The result: the game is now fully deterministic given a seed, which meant I could write tests that played a fixed sequence of pieces and checked the board afterwards. I would not have bothered with that otherwise.

The bugs the types did not catch

This is where I want to push back on a claim I hear from Haskell enthusiasts, including, a few years ago, me: "if it compiles, it works." For a game, it does not, and pretending otherwise sets students up for disappointment.

Rotation was the worst part. Real Tetris uses the Super Rotation System, where a rotation that would collide with a wall or another block tries up to four alternative offsets, called wall kicks, before giving up. The I piece has its own kick table, different from the other pieces. I copied the tables in, compiled, and the game ran. And the I piece behaved wrongly against the right wall, because I had flipped the sign on two offsets. The types were perfectly happy. The tables are just lists of integer pairs, and every wrong pair is still a valid pair.

The other bug was in timing. Gloss passes the update function the elapsed time as a Float in seconds. I subtracted it from a gravity timer and dropped the piece when the timer went below zero, but I reset the timer to its full value rather than adding to it. At high speeds, leftover time was thrown away, and pieces fell noticeably slower than intended. Again, the types had no opinion.

Types are very good at stopping you from mixing up kinds of things. They are no help when you have the right kind of thing with the wrong value in it.

What caught both bugs was property-based testing with QuickCheck. For rotation, I wrote a property that rotating any piece four times in empty space returns it to the original position. For timing, a property that the total number of drops over a simulated minute matched the speed setting within one. Each took about twenty lines and found a real bug.

What I tell students now

A small game is one of the best second projects in Haskell, better than another parser. It forces you to model state, deal with time, and handle input, and Gloss keeps the boilerplate tiny. The type system will catch a meaningful share of your mistakes, especially the structural ones. It will not catch numeric or rule mistakes, and games are full of rules.

If you are newer to the language, start with our beginner's guide to Haskell, and if deriving instances still feels like magic, type classes with real examples covers what Enum and Bounded are doing.

Try it over a weekend

Install Gloss, define a World record holding a board, a falling piece and a StdGen, and get a single O piece falling and stopping at the floor. Before you add the other six pieces, write newtypes for rows and columns. Then, when you add rotation, write the four-rotations QuickCheck property before you write the kick tables. You will find out quickly which bugs your types catch for you and which ones are still your job. More game-flavoured programming lives in our games section.

AS
Adil Sato

Adil Sato teaches programming concepts at a community college and writes online guides for the questions students ask most in the second week of class, not the first. His focus is on making type systems, monads, and functional patterns understandable without reducing them to metaphors that break down the moment you try to use them for real work.

More posts by Adil

More in Games

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto