Making Monsters Wander Randomly

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 7 Take Turns with the Monsters | TOC | Moving Entites in a Turn-Based Game 👉

Let’s start by making the monsters do something: move randomly through the dungeon. This isn’t the overall behavior you’ll keep for the finished game, but it can still be useful later. For example, adding Confusion effects may force an entity to move randomly. Bats and other irritants might flap randomly around the map. Like most ECS systems, the random movement system provides an option for you to use when adding functionality to your game.

You need a way to indicate that an entity moves randomly. This is best accomplished with a simple component — anything that has the component will wander aimlessly around the map. In components.rs, create a new tag component:

TurnBasedGames/wandering/src/components.rs

​ ​#​[​derive​(Clone, Copy, Debug, PartialEq)]
​ ​pub​ ​struct​ MovingRandomly;

Now that the component exists, you need a system that uses it.

Random Movement System

Create a new file and name it random_move.rs. Place this new file in your src/systems directory. Like the other systems, the new file is a module. The basic structure of the system is similar to the systems you created in Chapter 6, Compose Dungeon Denizens:

--

--

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.