Building a Smarter Monster
Learn how to make monsters smarter by giving them perfect knowledge of the dungeon's floor plan.
Monsters that move randomly offer very little threat, but monsters that are too intelligent can make a game unplayable. Finding a nice balance is the key to making a fun, yet challenging game.
Tagging the new behavior
Start by adding another component to indicate that the monster is chasing the player. Add the following in components.rs
,
#[derive(Clone, Copy, Debug, PartialEq)]pub struct ChasingPlayer;
This component is similar to the other tag components we’ve added. It doesn’t contain any data, because the tag’s existence serves only as a flag indicating that behavior should occur.
Replace all MovingRandomly
tags with ChasingPlayer
in spawner.rs
:
pub fn spawn_monster(ecs: &mut World,rng: &mut RandomNumberGenerator,pos : Point) {let (hp, name, glyph) = match rng.roll_dice(1,10) {1..=8 => goblin(),_ => orc()};ecs.push((Enemy,pos,Render{color: ColorPair::new(WHITE, BLACK),glyph,},ChasingPlayer{},Health{current: hp, max: hp},Name(name)));}
This code ensures that we replace the random movement behavior with the new chasing behavior we’re about to create. If you feel like some variety, you can always have some monsters continue to move randomly.
Now, let’s create a system to implement the player-chasing behavior.
Supporting pathfinding with traits
Pathfinding is the general term in game development for an algorithm that helps an entity find its way from point A to point B. There are many different pathfinding algorithms available, some of which are provided by bracket-lib.
The bracket-lib library is designed to be generic, so it doesn’t know the exact details of our game. bracket-lib offers map-related services through traits. We’ve explored traits several times before.
When we #[derive(..)]
services, we’re using Rust shorthand to implement traits. Our tick()
function is part of the implementation of the GameState
trait.pathfinding requires that you implement two traits for your map: Algorithm2D
and BaseMap
. Let’s take a moment to learn a bit more about traits. We’ll write our own traits soon, in Creating Traits.
The Rust documentation defines a trait as follows:
“A ...