Part 6 : Pausing The Game

Now, we are almost done with the code for this lesson. The only thing left to do is create a way to pause the game. Recall this line of code from the constructor of HomeWars.as

Key.addListener(this);

This code allows HomeWars to listen for keyboard events. Why do we need this? Because our HomeWars main game loop is going to have a function to pause the game. While pause is not essential to the lesson, is is a great way to show the power of everything we have covered in this lesson. You see, by using EventBroadcaster, and our simplified state machine, we have centralized the execution of everything is our game. Every object that moves requires the Move and Render events to be broadcast from the HomeWars class from the fSTATE_PLAY() function. By simply waiting for the [p] key to be pressed with an onKeyDown event, and setting a boolean variable named pauseGame accordingly, we can freeze every object in the game until the [p] key is pressed again. The code for this is below.
function onKeyDown() {

  if (Key.getCode() == PAUSE_KEY_CODE) {
   if (pauseGame) {
    pauseGame=false;
   } else {
    pauseGame=true;
   }

  }
 }

function fSTATE_PLAY() {

  if (!pauseGame) {
   dispatchEvent({type:"Move"});
   dispatchEvent({type:"Render"});
  }
 }

Now that all the code is complete, let’s test the final .swf for this lesson:

Move with the [<-][ ->] arrows keys, fire with [space], pause with [p].

And that ends lesson #1. Don’t worry if you could not follow along the whole time. All the code is available here as a single download, or individually: HomeWars.as, Player.as, TitleScreen.as, Missile.as, homewars_lesson1.fla

Read the rest of the series: ‘Anatomy of a Flash Game’

  1. Anatomy of a Flash Game: Lesson 1 – Setting up the game
  2. Anatomy of a Flash Game: Lesson 2 – Creating Enemies & The Game Environment
  3. Anatomy of a Flash Game: Lesson 3 – MochiAds, MochiBot and MochiAds Leaderboards