Creating Different Game Modes

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Understanding the Game Loop | TOC | Adding the Player 👉

Games typically run in modes. Modes specify what the game should do on the current tick, for example, displaying the main menu or the game over screen. In computer science, this is often formalized as a state machine. It’s a good idea to start by defining your game’s basic mode structure, which acts as an outline for the rest of the program.

Flappy Dragon requires three modes:

  1. Menu: The player is waiting at the main menu.
  2. Playing: Game play is in progress.
  3. End: The game is over.

Transitions between these modes are relatively straightforward:

images/FirstGameFlappyAscii/StateTransition.png

Game modes are best represented as an enum. Enumerations allow you to limit the value of a variable to one of a set of possible states. Underneath the prelude import, add a GameMode enumeration to represent the available game modes:

FirstGameFlappyAscii/flappy_states/src/main.rs

​​①​​enum​ GameMode {
​​②​ Menu,
​ Playing,
​ End,
​ }

​①​
GameMode is an enum, like the ones you used in the treehouse example.

--

--

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.