Adding Monsters

Hands-on Rust — by Herbert Wolverson (56 / 120)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 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…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.