Adding the Adventurer

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Storing the Dungeon Map | TOC | Building a Dungeon 👉

The adventurer is the player’s avatar in the dungeon. The player roams the dungeon, hopefully collecting loot and probably dying at the hands of vicious monsters. The game needs to know what tiles the adventurers can enter so they don’t walk through walls. It also needs to store where the player is, handle moving them with the keyboard, and perform the movement. This section will address each of these requirements.

Extend the Map API

Let’s add some more map functions to support player functionality. You need to determine if an x/y coordinate pair is within the bounds of the map. If you don’t perform bounds-checking, the player can move off the edge of the map, and either wrap around or crash the program. Add the following to your Map implementation:

BasicDungeonCrawler/dungeon_crawl_player/src/map.rs

​ ​pub​ ​fn​ ​in_bounds​(&​self​, point : Point) ​->​ bool {
​ point.x >= 0 && point.x < SCREEN_WIDTH
​ && point.y >= 0 && point.y < SCREEN_HEIGHT
​ }

This function checks that the location specified in point is greater than zero on both the x and y axes, and that it is less than the screen height and width. Chaining multiple tests together with && — short for AND — returns true if all the conditions are met.

--

--

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.