Battle Game In Haskell #2 – Fighting using recursion and Either
Welcome back! Last time we laid the basics of the battle game by applying damage to a unit. However, we had to specify the amount of damage, while it would be more realistic that the damage results from a hit of a hostile unit.
Shooting a unit
The following modifications include some refactors (record accessor for
cond utility), and more importantly the
shoot function where a unit shoots and damages an other unit. The
main function was also updated to demonstrate the changes.
Fighting until death
While a single shot is more than nothing, let’s make two units fight until death on an encounter. The
fight function might need some explanation: The first (or left) unit shoots the second (or right) one, so the right unit may be dead already. The
maybe function is the folding function for the
Maybe data type, it converts both
Just x and
Nothing to a value of a given type. Here we apply it for the damaged right unit, and if it is dead, then the left unit is the winner. Otherwise the roles are swapped, and the right unit gets to shoot the left one. Note that since we deliberately swap the roles in the next fight, the result of that fight needs to be swapped back too. The resulting full Main.hs file is here, which also includes a custom
Show instance for
Unit so units are printed a bit nicer.
So now we can get two hostile units together, and observe the final outcome of the battle. However, we have no information on how did the fight reach that outcome. This is especially frustrating if we would like to animate the process of the fight, instead of just making one of the units disappear. Therefore next time we will add logging using the
Writer monad (combined with some monad transformers), so the full flow of events will be captured. Happy hacking!