Tutorial: Pause Your Game in Flash AS3

This tutorial teaches you how to set up your game so that everything stops when you hit the “pause” button.


[SWF]http://www.untoldentertainment.com/blog/tutorials/gameLoop/gameLoop.swf, 550, 300[/SWF]

This is a bit of structural/best-practices advice i gleaned when i was learning C# programming in XNA for the Xbox 360. Flash/Actionscript behaves a little differently than other programs. The way many games are programmed, there is one giant loop, and everything takes place in that loop.

Flash encourages you to throw code all over the place – on frames, on movie clips, in separate .as files – but Flash coders could really benefit from the sanity and cleanliness that a master loop brings.

Here Comes the Code

At its most basic, this is what we’re talking about:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package 
{
	import flash.display.MovieClip;
	import flash.events.Event;
 
	public class Main extends MovieClip
	{
		private var isPaused:Boolean; // This is the variable that holds our paused/unpaused state
 
		public function Main()
		{
			// Unpause the game:
			isPaused = false; 
			// Add an event listener to keep an eye (ear?) on the built-in ENTER_FRAME event.
			// Every time Flash processes a frame tick, doMasterGameLoop will execute:
			addEventListener(Event.ENTER_FRAME, doMasterGameLoop);
		}
 
		private function doMasterGameLoop(e:Event = null):void
		{
			// This is the main game loop that does all the work.  It's the
			// "gateway" to everything our game does.  If the game is paused,
			// nothing in the game loop happens.
			if (!isPaused)
			{
				update();
				draw();
			}			
		}
 
		private function update():void
		{
			// Tweak all your numbers and math stuff here
		}
 
		private function draw():void
		{
			// Update all your graphics here			
		}
	}
}

So all you need to do is rig up a “PAUSE” button that toggles the isPaused variable when you click it. When the game is paused, stuff won’t happen. Unpaused? Stuff happens.

Whiling Away the Hours

If you come from another programming language, you might be accustomed to seeing the game loop built in a while statement. Actionscript is a different beast when it comes to while. The whole program runs on frame ticks, meaning it will execute your code according to the frame rate you’ve set in your fla file. A framerate of 12 fps (frames per second) means that Flash will try to run your code 12 times a second. “Try” is the operative word – the code will only execute according to the processor’s ability.

There are ways to get your code to execute more quickly than the set frame rate, but for our purposes, since we’re talking about the ENTER_FRAME event, we’re talking about code executing on frame ticks according to the set frame rate.

If you try to put your master game loop in a while statement in Actionscript 3, here’s what’ll happen:

  1. first frame tick: code is executed
  2. interpreter hits the while statement
  3. there is no escape or break condition in the while statement, so Flash keeps trying to execute those commands in the same frame tick
  4. after a prescribed number of seconds, Flash poops out and you get an endless loop error

So instead, think of Flash as having one big automatic while loop, and you’re tucking all of your code inside it.

Keep Em Separated

To a native flashcoder, it may look odd to see two separate processes – update and draw – in the game loop. The way games in other languages work is that first, an update process figures out where everything in the game should be – bullets, enemies, the player character, the power-ups – and then in the draw process, all of the graphics for those things get refreshed on the screen in their (sometimes) new positions.

One mixed blessing with Flash is that code and graphics are married. If you update the x position of a movieclip, you’re updating both the logic and the display. They’re fused together. This is one of the reasons Flash makes for rapid prototyping, but it can also mess you up when you’re trying to do something complicated.

The hard lesson i’ve learned over many years of development is to divorce your code from your graphics, wherever it makes sense. Let’s say you have bullets in your game. You might be tempted to have all your little bullet01, bullet02 … bulletn movieclips on the stage, and then update their x/y co-ordinates to move them around. Then, when you want to find out where your bullets are, you loop through everything on the stage that’s of type “bullet” and have the bullet movieclips report their positions.

A better way to do it is to create a Bullet object (class). It has properties for xPosition, yPosition and graphic. In the update process, you change the xPosition and yPosition properties based on where the bullet should be. In the draw process, you set the positions of the bullets’ graphics:

1
2
graphic.x = xPosition;
graphic.y = yPosition;

There are better examples of where this separation of logic and display is useful – i’m just introducting the concept simply for now.

Pausing Sprites

One of the other things Flash does to save you time is to give nearly every on-screen object an automatically-looping timeline. If you create a 3-frame MovieClip object and put it on the stage, it will automatically animate. Good! But since it’s not controlled by code, but rather by some secret behind-the-scenes process, it won’t stop when you hit the “pause” button. Not so good!

What you really want to do, and it takes quite a bit more work, is to create a class to represent your on-screen object (we’ll call them “sprites”, although the term has slightly different connotations in ActionScript), and keep track of which frame the sprite should display. So on your update process, you figure out which frame to display, and on your draw process, you send the MovieClip to that frame. That’s a far better example of what i’m talking about re: separating code from display, but it’s a bit beyond the scope of this tutorial. Let’s just see our pause button simply doing what it does one more time:


[SWF]http://www.untoldentertainment.com/blog/tutorials/gameLoop/gameLoop.swf, 550, 300[/SWF]

Hooray! You can download the source code here:

http://www.untoldentertainment.com/blog/tutorials/gameLoop/gameLoop.zip

We’ll tackle programmatic sprites in another tutorial!

For more Flash AS3 Tutorials and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

21 thoughts on “Tutorial: Pause Your Game in Flash AS3

  1. kaolin fire

    Sweet! This is the perfect intro level for a friend I want to get into flash game dev, I think, without having the time to actually say all these things myself ;) :D

    Reply
  2. Ryan

    Glad it was useful to you! When i first thought about writing tutorials, i was worried that i would look pompous, or that i would write things that greater minds would scoff at because they were too basic. But one of the most popular posts on the site is the tutorial about throwing a random number in Flash, which is dead simple. There’s a place in this world for entry-level tutes, i think.

    http://www.untoldentertainment.com/blog/2008/03/23/as3-tutorial-mathrandom/

    Reply
  3. David Clements

    I was that intro level friend. I enjoyed the tutorial, very clear writing and clear idea of what it does. Thanks for posting it. BTW, you didn’t sound pompous at all.

    Reply
    1. Ryan

      Phew! i may have finally supressed it then.

      Check out our Flash/Actionscript 911 page, David. We keep a white board in the office with tutorial ideas on sticky notes. If there’s something you want to learn, let me know and i’ll add it to our tutorials todo list.

      Reply
  4. Jean-Guy Niquet

    Although this is one approach it is certainly not the most efficient. A better approach is to use a message that will broadcast to all objects that the game is paused. The objects in the game will have a listener that receives these messages and does it’s appropriate action based on the “paused” message. We try to avoid using ENTER_FRAME whenever possible.

    Reply
    1. Ryan

      What do you use in place of a loop, Jean-Guy? You can’t use while, and you seem morally opposed to Event.ENTER_FRAME … you’re not using intervals, are you?

      Reply
    1. Ryan

      How do you get anything accomplished without somehow repeating code? How would you create a looping animated sprite, for example, using only listeners and broadcasters?

      Reply
  5. Jean-Guy Niquet

    If I need something to loop I would simply create a function in the class attached to the object that can gotoAndPlay the frame it will loop on. I’m not sure why I would want a listener to make something loop, that is not how a listener works. A listener simply listens for a message that is broadcast out, it doesn’t do anything other than call a function. We see this in your code when you add your ENTER_FRAME listener. You are telling the player that at some point a String will be broadcast called “ENTER FRAME”. When that string is broadcast then call the function doMasterGameLoop. Since a listener really just listens for a String you can easily create your own. If scoped properly you can attach these listeners to any object, you have implied that it will be added to the Main MovieClip by not defining that before the listener. Conversely if I am inside of a MovieClip I can add a listener to the Controller Class or Main Clip to listen to messages coming from outside of my current class. I can then call the function for the object in this class to pause or stop. We used this method on the following game so that we could keep somethings paused while others play when you press pause.

    http://www.ytv.com/programming/shows/kidvskat/games/invaders/game.asp

    Another option we have used on some of our games that implemented pause is to recursively go through the objects on the stage and stop them by accessing the pause/resume functions in each of the objects. This is a quick and dirty way of pausing when you know EVERYTHING will need to pause. You can protect yourself in either method by implementing an Interface that forces you to create a pause/resume function.

    Reply
    1. Ryan

      Do you have different people all replying to this post under your name?

      You: Using listeners and broadcasters replaces the need for loops.
      Me: How would you create a looping animated sprite, for example, using only listeners and broadcasters?
      You: I’m not sure why I would want a listener to make something loop, that is not how a listener works.

      It’s like an Abbot and Costello routine over here.

      My point is that you need to loop your code somewhere, somehow. You’ve decided to use the built-in automatic timeline loop in Flash (via gotoAndPlay). This whole tutorial is about not having to rely on the timeline.

      While you’re correct, you *can* individually loop through everything on stage and call a pause (or stop()) method, this tutorial is specifically about how to NOT do that.

      For the record, i’m very comfortable with listeners and event dispatchers in Flash … i assume you’d explaining them here for the benefit of other readers? :)

      Reply
  6. Menzoic

    I don’t see the advantage to separating logic from graphics, it seems like a nostalgic thing to do. As Jean -Guy Niquet mentioned a custom listener specifically made for Pause would be better fit than an enterFrame event. I’ve been working on a PauseResume class that uses describeType to find out what listeners an object has running but my hard drive crashed and I have to start all over again :( This time with back-ups.

    Reply
    1. Ryan

      Menzoic – i don’t know enough about patterns to answer you intelligently, but maybe it’s a pattern thing? The pattern(?) i’m describing has One Class to Rule Them All. On its loop, it tells all active objects to update, as long as the game isn’t paused. Seems simple to me.

      i still don’t understand the method that you and Jean-Guy are proposing. i know how to write custom listeners … i just don’t know how you create a project with animation and frame-based code without referring to some kind of loop. Enlighten me. Can you paste some code?

      – Ryan

      Reply
  7. Menzoic

    Ryan – I still don’t understand the need to separate logic from graphics. If the game is paused neither the logic or graphics need to update.

    I read more of Jean-Guy’s comments and I noticed he is opposing the use of enterFrame for the animation. That is not my view, I was referencing comment 5. In comment 5 Jean-Guy was only saying that the check for the “isPaused” variable shouldn’t be in an enterFrame event. There should be a function that would be a handler to a Pause event listener. In you example you can include the check for pause because you are already using enterFrame to animate the ball. The game that I was making the PauseResume event for contained objects that did not have any enterFrame events but instead Tweens, Timer, and other events. Some objects in my game didn’t animate at all. In my case simply not calling an update wouldn’t pause my objects. I needed to have a function would remove any specific listeners active in that object.

    Reply
  8. lala

    debate is getting strange, ne ways, i wanted to suggest, on “game loop” search, on whole web, i found this one best explained which i can understand easily,
    i really appriciate, if you extend this little more in future part 2, where u give example or when to update or when to draw, little confused, thanks..

    Reply
  9. jarofed

    Thank you for this tutorial, Ryan. I am currently working at development of tower defense flash game and have a need to create pause/speed up buttons. I think that your method will fit perfectly!

    Reply
  10. Web tips

    Hi Ryan, I’m a beginner in flash. I found the solution very simple and very well explained.. so, its the best way to me for implementing a pause and resume functionality for a flash game i’m developing. Thank you!

    Reply
  11. Pingback: Seven Common Flash Game Complaints (and How to Avoid Them) — Michael James Williams

  12. ilsa

    Hi Ryan – first of all, thanks for all your tutorials. I find them easy to understand as well as entertaining :) I’d like to try and apply your approach in pausing a flash game. I know this is a 2-year old post but I hope you can update/fix the broken links (e.g. to download the zip file: http://www.untoldentertainment.com/blog/tutorials/gameLoop/gameLoop.zip, as well as the links in your ‘Flash and Actionscript 911’ page – I happen to stumble over your tutorial pages via google. Wanted to view the rest on the 911 page of yours but keep being headered to a 404 page). Thanks again!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *