Roguelike game in C++ - Adding a rudimentary monster to the game
Posted on August 1, 2012 by Paul
The code for this post is on GitHub: https://github.com/sol-prog/roguelike.
Last time we’ve added a real map to the game, generated with a Perlin noise function. But where is the fun in a roguelike game without a monster ? In this post, we are going to add a rudimentary monster to our game, that will chase the main character. The player task will be to dodge the monster and stay alive …
Our monster will be dumb, all he knows is to chase the main character on the map. Because I’m more interested in testing an idea for a chasing algorithm, we are not going to create a separate class for the monster, we’ll refactor the code and add some AI to our monster in a future tutorial. For now we could use the Character class to initialize our monster:
Now, that we have a monster in our game, we could add it to the map in the game_loop function:
What about the chasing algorithm ? We could use a simple idea based on the Euclidean distance for moving the monster:
- Check the up, down, left and right neighbor positions for our monster.
- If a cell (neighbor) is free, calculate the distance between this cell and the main character position.
- Move in the cell that minimize the distance between the monster and the main character.
We’ll start by creating a new member function in Frame, that will check if the target position is free to move in or not:
For now, we could add the tracking (chasing) algorithm in the game_loop function just after the main character movements, this code will be moved to a Monster class in our next article from this series:
Let’s see the new code in action. When the game starts, we have the main character, @, and the monster, M, in their initial positions:
A screenshot of the game after a few movements, note how the monster follows the player character:
I’ve also made a small movie for showing how you can play the game:
In the next article, we are going to refactor the code for the monster, in order to be able to add more than one monster to the screen. We could also define areas on which a monster can see the main character. When you have ten monsters on your game, it won’t be much fun if every monster from the game can see the position of the player character and start chasing it. We could create a few kind of monsters with different characteristics. Also the main character should have a sword or some other weapon to be able to kill or stop a monster …
All posts from this series:
- Roguelike game in C++ - Introduction
- Roguelike game in C++ - Bootstrap
- Roguelike game in C++ - Adding a map to the game
- Roguelike game in C++ - Map generation with Perlin noise
- Roguelike game in C++ - Adding a rudimentary monster to the game
If you are interested in learning more about the new C++11 syntax I would recommend reading The C++ Programming Language by Bjarne Stroustrup.
or, Professional C++ by M. Gregoire, N. A. Solter, S. J. Kleper: