Adding Monsters
Hands-on Rust — by Herbert Wolverson (56 / 120)
👈 Managing Complexity with Systems | TOC | Collision Detection 👉
Monsters have a lot in common with the player. They have a position and render information. They aren’t keyboard controlled and they shouldn’t have a Player tag. Instead, monsters need an Enemy tag component. Open components.rs, and add an Enemy tag:
EntitiesComponentsAndSystems/dungeonecs/src/components.rs
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Enemy;
An empty structure is all that’s required for a tag class. You still need a way to spawn monsters. Open spawner.rs, and add a spawn_monster function. It’s very similar to the player spawning code:
EntitiesComponentsAndSystems/dungeonecs/src/spawner.rs
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 spice things up a bit, the spawning code randomly selects one of four monster types…