Creating Obstacles and Keeping Score

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding the Player | TOC | Wrap-Up 👉

The other key part of Flappy Dragon is dodging obstacles. Let’s add walls to the game, with gaps through which the dragon may fly. Add another struct to your program:

FirstGameFlappyAscii/flappy_dragon/src/main.rs

​ ​struct​ Obstacle {
​ x: i32,
​ gap_y: i32,
​ size: i32
​ }

Obstacles have an x value, defining their position in world-space (to match the player’s world-space x value). The gap_y variable defines the center of the gap through which the dragon may pass. size defines the length of the gap in the obstacle.

You’ll need to define a constructor for the obstacle:

FirstGameFlappyAscii/flappy_dragon/src/main.rs

​ ​impl​ Obstacle {
​ ​fn​ ​new​(x: i32, score: i32) ​->​ Self {
​ ​let​ ​mut​ random = ​RandomNumberGenerator​::​new​();
​ Obstacle {
​ x,
» gap_y: random​.range​(10, 40),
​ size: ​i32​::​max​(2, 20 ​-​ score)
​ }
​ }

Computers are not very good at generating genuinely random numbers. However, there are many algorithms for generating “pseudo-random” numbers. bracket-lib includes one known as xorshift, wrapped in convenient access functions.

The constructor creates a new RandomNumberGenerator and uses it to place the obstacle at a random position. range…

--

--

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.