Functional Hangman with ZIO

Scalaz-ZIO is generating a lot of hype in the Scala community. I checked it out by copying an implementation of the guessing game “Hangman” from a talk by John De Goes. It’s basically the same code with a couple of minor gameplay enhancements and importantly it’s updated to the new ZIO. It’s a lot of fun to play and to code.

The Hangman game

This is the main function of the game, the one which you run by calling

Running the game in the IO App

hangmanGame is virtually unchanged from John’s talk except that it has been updated to ZIO rather than IO. It also uses Random from zio to choose random words. It may sound odd but I tested the game a lot with both the scala.util.Random and the zio.random.Random and the zio version seems to work much better. Most of the game logic is in the gameLoop function:

Slight changes from John’s version include the new type signature of course, and the use of ZIO.succeed (instead of IO.now). Also a slight enhancement that I added was to tell the player what the correct answer was when they lose. Overall it was a good exercise to learn ZIO, and the migration from IO to ZIO was pretty painless, with good compiler errors that guided me toward the right type signatures.

The code is available on my github:

https://github.com/spf3000/functional-hangman