Search⌘ K

Adding the Monsters

Explore how to add monsters as enemy entities in a Rust-based dungeon crawler game. Learn to create an Enemy tag component, develop a spawn_monster function for random monster types, and utilize iterator chains to place monsters in rooms. Understand how the ECS design allows rendering without altering the rendering system, highlighting modular game entity management.

Monsters have a lot in common with the adventurer; they have a position and render information. However, they aren’t keyboard-controlled, and they shouldn’t have a Player tag. Instead, monsters need an Enemy tag component. Let’s add an Enemy tag component. Adding an Enemy tag in components.rs:

Rust 1.40.0
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Enemy;

An empty structure is all that’s required for a tag class. We still need a way to spawn monsters. Add aspawn_monster() function in spawner.rs. It’s very similar to the player-spawning code:

Rust 1.40.0
pub fn spawn_monster(
ecs: &mut World,
rng: &mut RandomNumberGenerator,
pos : Point
) {
ecs.push(
(Enemy,
pos,
Render{
color: ColorPair::new(WHITE, BLACK),
glyph : match rng.range(0,4) {
0 => to_cp437('E'),
1 => to_cp437('O'),
2 => to_cp437('o'),
_ => to_cp437('g'),
}
}
)
);
}

To make things interesting, the spawning code ...