Chapter 12
Using States and State Machines

In the previous chapter, you started using the Entity Component System (ECS) architecture. As you were learning about this popular game design pattern, you built four separate components for the Val’s Revenge game.

In this chapter, you’ll pick up where you left off, adding two more components: one to handle collectible items, and one to manage the physics bodies. You’ll also begin to add more gameplay- and game state–related logic, such as what happens when players find treasure and food, or what happens when they pick up keys that Val can use to unlock doors.

Game State and the State Pattern

images/aside-icons/info.png

Finding the definition of game state isn’t that easy. Not because it’s a made-up term—that’s not it at all. The problem is that game state is actually part of a larger design pattern known as the state pattern, which is closely related to the concept of a finite-state machine (FSM). Using the state pattern, you’re able to track the state of an object—in other words, the way something is with respect to its attributes. For example, whether or not the game is in progress.

Traditionally, game developers would manage game state and state-related logic using a series of if statements. For example, in the GameScene class, you might add code similar to this:

 if​ gameInProgress == ​true​ {
 // do this
 } ​else​ {
 // do this instead
 }

Although this sort of code works—in fact, you used something similar in Restarting the Game—you do have another option: use states and state machines.

With states and state machines, you’re able to define distinct states within your game, such as if the game is in progress or not. You can then set up and use state machines to handle moving between the different states, giving you more control of what happens when exiting and entering the different states. More important, you can define what occurs when your game is currently in one state versus another.

With GameplayKit, you use the GKState and GKStateMachine superclasses to create and manage your game states. In Val’s Revenge, you’ll create a player state machine to track when players have keys in their inventory versus when they do not. You’ll use this information to determine whether or not Val can unlock the dungeon doors that stand in her way of fortune and glory.

Now that you have an idea of what you’ll be doing in this chapter, it’s time to jump into the code, starting with setting up the different game states.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset