Battling Through to the Exit
Explore how to implement a battle system in Elixir by building enemy lists, managing character hit points, and designing module contracts. Understand how to create engaging game challenges using Elixir's functional programming concepts and module behaviors.
We'll cover the following...
Our game needs a challenge, or it won’t be fun. A challenge will reduce the chances of the player winning and let them feel like they overcame something when they do win.
For our challenge, we’ll implement a room with an enemy. The hero and the enemy will fight, and the first one to reach zero hit points is defeated. We need to build a list of enemies, create functions to reduce and restore character hit points, build a battle module, and create a room that can trigger a battle. Once we have a room-trigger contract, we need to follow it strictly.
The first step will be to construct a list of enemies, creating the lib/dungeon_crawl/enemies.ex file with the following code:
We’ve used the same DungeonCrawl.Character struct of the hero to create the enemies. It’s a list of suggested enemies. Feel free to create more or change the list. The next step is to create functions that permit the reduction or restoration of a character’s hit points and another function that displays the character’s current hit points. Let’s write these functions in the DungeonCrawl.Character module:
The take_damage/2 function receives a character and the number of hit points ...