Back

Game States

Reading

Refresher

A control flow statement is anything that branches your code into different paths, hence the term, control flow.

If statements are examples of control flow as well as switch statements, and they are important for telling your program which state it is in.

Finite State Machines

Here is a turnstile, implemented at many stores and transit locations. As you can see the turnstile can be in only 1 state at a particular point in time and the diagram details how you will move between states.

Finite State Machines

Explaining all the intricacies of finite state machines is beyond the scope of this course but your game and all software programs are finite state machines.

Your application will maintain the state it is in (start, playing, won, lost, ...) and using control flow statements in your game loop you will show the correct state and allow the player to move between states.

Game State

Your game will at some point be in different states of play. Whether it's the intro screen, level 1, level 2, ..., or a final credit scene.

We're going to look at two ways to manage this state

Game State with if statements

Game State with if statements

Notice how we're calling methods from the main draw loop instead of putting all the code inside the if statements. This will keep our main loop clean and easy to understand which state calls which method. It's great for debugging and keeps everything readable.

Game state with switch statement

Game state with switch

Much cleaner than the if statements in my opinion. This may be the optimal choice for your program.

Avoid huge blocks of code in your main draw loop, use methods, and if necessary put them in another tab for better navigation and code readability.

Switching States

Switching States

Create a method to clear any ArrayLists and reinstantiate objects that need it. This will ensure that your program continues to run smooth no matter what level you're on or how long your user plays.

Avoid huge blocks of code in your main draw loop.
Use methods for your different states, and if necessary put them in another tab for better navigation and code readability.
Reset objects before starting a new level.

HUDs

A HUD or heads up display, will let your user know what is going on during the game. Typical information includes health, score, lives, but you're free to include anything you want.

Health Bar

Health Bar

In order to draw a bar you must first calculate the percentage of health remaining for the player. This gives you a number between 0-1.

You may want to calculate the health percentage only when the player health changes and store this inside the player class. This will improve performance since you won't be calculating this percentage every frame.