Hack74.Design Web-based Flash Games

Hack 74. Design Web-based Flash Games

Bring your retro game concepts to life with animation .

If you're looking to expose your games to as many people as possible, Macromedia's Flash is one of those rare cross-platform tools whose reach extends as far as the eye can see. You need a Gamecube to play Smash Bros. You need an Xbox to play Halo. You need a Windows PC to run an .exe . With Flash, all you need is a web browser. Anyone who has access to the Internet ( certainly a sizeable percentage of gamers) can experience your vision without the need for specific hardware or expensive upgrades.

While Flash's Interactive Development Environment (IDE) makes it easy to keep track of the objects you're working with, it is by no means a substitute for coding. The latest version of Flash MX, without writing any of your own code, gives your applications about the same capabilities as Flash 1.

You can download a free, 30-day trial of Flash MX from www.macromedia.com (you'll have to register). It's fully functional, comes with plenty of helpful tutorials and documentation, and any games you create will remain playable forever. If you find that you want to continue using Flash after the trial expires , you can purchase a copy from Macromedia for $400. This hack is going to assume you're familiar with basic Flash terms such as the stage, timeline, panel, as well as the standard drawing tools and their various settings. If you're already scratching your head, spend some time with the samples Macromedia provides. You can find them under the Help menu, or in the FL_Getting_Started.pdf file bundled with the installer.

Before you get started creating a game, familiarize yourself with the Flash IDEit's fully customizable, and it's to your benefit to take advantage.

Since I cut my teeth on Flash 5, I've reconfigured several keyboard shortcuts on my personal copy to match what I'm familiar with (I'll be using the default shortcuts, so you won't have to change anything if you're using a freshly-installed copy of Flash).

8.3.1. Set the Stage

You need an actual game before you can have multiple difficulty levels and realistic explosions. So before you even open Flash, spend some time brainstorming and planning the overall structure of your game. The idea is to come out with clear ideas for what objects are required, what properties they will have, and what actions they need to be able to do. Don't get bogged down with programming details during the planning stage; record your ideas in clear, readable English (or whatever your native language is). Right now, an object is something that appears in your game (e.g., a car), properties are things describing it (e.g., speed, acceleration), and actions are what it's capable of (e.g., turning, braking).

For this hack, we'll be building an extremely simple game skeleton somewhat reminiscent of Missile Command. There will be no focus on graphics or soundthey can be added in at any time with virtually no effort. It won't look like much, but the finished product will be a complete, easily upgradeable game that encompasses all the major aspects of game design.

8.3.1.1. Game requirements.

Remember, there's no code being written at this point. Write down your ideas in plain language so everyone involved in the project can understand what needs to be done. Our game will need:



A goal

There has to be a point to playing a game. What fun is a game with no direction? "Beat the high score" and "Save the princess" are good goals, but "Stomp on enemies" isn't. The goal for this game is to shoot enough enemy missiles to save the city.



Score

The player's score will be the determining factor for whether they've won, lost, or are still playing. The score should increase when the player destroys a missile and decrease if the player misses one.



Missiles

Missiles should start offscreen and make their way from the top of the screen to the bottom. Since they're moving objects, they need to keep track of their speed and acceleration. This implementation will also include a wait timer, so there isn't a constant rain of missiles. If clicked, the missile is destroyed , and the player gets a point. If it makes it to the bottom, the player loses a point.

That's all this hack's example requires, but for a complete game you design, this is the point in the process when you should list sounds, animations, difficulty levels, and other aspects. For larger projects, it may help to list the objects first, and come back to fill in their properties and actions later.

Now that we have a clear description of what we need, it's time to bring our idea to life! If you haven't already, open up Flash and create a new Flash Document. Make sure the Library panel is visible (press F11 if it is not).

Conceptually, a game is nothing more than a list of different possible scenarios (more commonly called "states"). Each state is connected to one or more other states, and the game moves between them via the player's actions. Figure 8-13 shows an RPG character exploring a town. States are represented in boxes, actions in ovals.

Figure 8-13. Different game states while exploring a town

8.3.1.2. Prepare the elements.

The concept of states translates very well into Flash; each game state should be a single frame on the main timeline. This game will have three states, so click on Frame 1 and push F6 twice to insert two new frames. Using the Properties panel (located at the bottom of the screen by default), name the three frames "game," "win," and "lose" respectively as shown in Figure 8-14.

Figure 8-14. Labeling the "win" frame

Get in the habit of giving frames meaningful names . It's easy to remember that "win" is frame two at first, but as you build games with more and more states, it gets difficult to keep track of everything. Moving a single frame to a new position would require you to change every reference to it. By naming important frames, you'll be able to access them no matter where they go.


Go to the "win" frame and use the Text tool to write "You win!" in the middle of the stage. The font, size , and color are up to you. Go to the "lose" frame and do the same thing, this time writing "You lose!"

Next up is drawing the missiles. Click on the "game" frame and draw a square or circle. You can use whatever colors you like, but make sure the shape is filled with a solid color. Alternatively, you can import a graphic by pressing Ctrl+R (Command+R on the Mac). Once your graphic is ready, use the Arrow tool to select it and press F8 to convert it to a Symbol. Name it "missile" and set its behavior as "Movie Clip." Drag it to the top of the game's work area, just above the stage. Finally, using the Info panel, change the Missile's length and width to 50 pixels by 50 pixels.

The last bit of prep work is setting up the score display. Use the Text tool to write the word "Score" in the upper-right corner of the stage. Below it, make a Dynamic Text box by selecting "Dynamic Text" from the Properties panel. Now would be a good time to save the file.

8.3.2. Begin Coding

Now that you've laid the foundation, it's time to whip out some Actionscript and make those missiles fire.

From its humble beginnings in Flash 4, Actionscript has evolved into a robust, sophisticated language that has turned Flash from an animation studio to a jack-of-all-trades web-programming tool. Its syntax is based on JavaScript, but it has some unique points as well (describing them goes beyond the scope of this hack; check out the Flash documentation for more info). Flash MX 2004 is the first version to feature Actionscript 2.0, which boasts full object-oriented programming capabilities. While we won't need these advanced features for this simple game, they are invaluable for large-scale web applications and heavy-duty game engines. It wouldn't hurt to take a look at the built-in Actionscript references; they're located under the help menu and in the FL_ActionScript_Ref.pdf file bundled with the installer.

Since Actionscript can be used with Frames, Buttons , and Movie Clips, knowing where to use it is just as important as how:

  • Actionscript on Frames should be restricted to initializing variables and writing functions. Be sure to consider the scope of your code; global functions and variables belong on the main timeline, while properties specific to a Movie Clip belong within that Movie Clip.

  • Actionscript on Buttons, naturally, is for player-triggered events. Actionscript's event handlers can only react to mouse clicks and key presses, so their use is limited to simple actions like jumping to a particular frame, or sending and receiving data across the Web.

  • Movie Clips are like Flash Movies unto themselves , and should be thought of as such. They're clickable, so they can be used like buttons to react to user input. However, their true strength lies in the ability to listen for and react to various events and changes within the movie itself.

8.3.2.1. Set up global variables.

Click on Frame 1 of the main timeline and open up the Actions panel (Press F9 if it's not visible), and type the following (the commented line numbers are for your reference and don't have to be included in your code):

 stop();  //Line 1 score = 0; //Line 2 

The stop() function on the first frame is crucial. Try compiling the movie (Press Ctrl+Enter on Windows, Command+Return on the Mac) without itthe game will immediately play to its end and the player simply sees "You lose!" Not exactly the kind of game that keeps players coming back, right? Remember, Flash is an animation tool at its core , so it treats everything as a movie. stop() only halts playback; code will continue to execute and Movie Clips will continue to play.

Head back to the stage and click on the Dynamic Text box you made earlier and take a look at the Properties panel. Notice the var field? You can bind a Dynamic Text box to any variable in your project, such as the number of frames it contains or the X position of a button. You will be assigning the player's score to this one, so click the var field and type in "score". Press Ctrl+Enter (Command+Return on the Mac) at this point to compile the movie to an .swf file. You should see "SCORE 0" in the upper-right corner of the movie as shown in Figure 8-15.

Figure 8-15. Setting the Dynamic Text field to display the score

8.3.2.2. Launch the missiles.

As fun as having a working scoreboard is, it'd be nice if the player could somehow get points. This requires the missiles to be operational, so go back to your project and double-click on the missile. You're now in symbol-editing mode, and the timeline has changed from the main movie's to the missile's. Click frame 1 of the missile's timeline and add the following code:

 velocity = 1;                       //Line 1 acceleration = .5;                  //Line 2 timer = Math.floor(random(29));     //Line 3 function fire()                    //Line 4 { } function resetMissile()            //Line 5 { } 

velocity refers to the initial speed of the missile. In Flash, positioning is all done in pixels, so a velocity of 1 means that whenever the missile moves, it will move by one pixel.

acceleration is the rate at which the missile's speed is increasing. Whenever the missile accelerates, its speed will increase by two.

timer is used to delay the missile's launch by a small amount of time. This prevents multiple missiles from all falling at the same time, and adds a general element of randomness to the game.

fire() will eventually control the missile's descent. It will be called when timer reaches a certain value.

resetMissile() will eventually re-initialize the missile to a random position and fire it again. It will be called when the player clicks the missile, or when it reaches the bottom of the screen.

Return to the main timeline for a moment by clicking Scene 1 above the timeline. Select the missile (only click once!), go to the Actions panel, and type:

 onClipEvent(enterFrame)           //Line 1 { if(this.timer == 30)           //Line 2 { this.fire();              //Line 3 } else this.timer++;             //Line 4 } on(press)                      //Line 5  {   resetMissile();              //Line 6  _parent.score++;             //Line 7  } 

What's with all this on stuff? They're called handlers Flash elements that sit around waiting for a particular event to happen. When it does, they "handle" it by executing their code. The onClipEvent handler is one of the most useful and powerful features of Movie Clipsif the clip is on the stage, the code within the handler executes every frame of the movie. Meaning, if your frame rate is 20 frames per second, the code will execute 20 times per second. Handlers are what allow a game to remain playable even though playback has been stopped ; i.e., even though the movie is paused on frame one, it's still running at 20 fps, so buttons remain clickable, and Movie Clips continue to run.

The generic on handler is strictly for reactions to user input. press refers to the Movie Clip or button in question being clicked on.

So what exactly happens? Here's how it all goes down:

  • Line 1 specifies that the following code should be executed on every single frame of the movie.

  • Line 2 checks to see if this particular missile is ready to fire. If so, fire() is called and the missile is set into motion.

  • Line 4 increments the timer if it's not time for the missile to launch.

  • Line 5 reacts to the user clicking on the actual body of the missile.

  • Line 6 calls resetMissile() , which resets each missile's variables to their initial values and repositions it at the top of the screen.

  • Line 7 increases the player's score by a point. _parent refers to the main timeline, where the score variable resides.

    When working with object paths in Flash, it's always better to use relative, not absolute, references. The main timeline is also accessible with _root , however, it's preferable to use _parent . If your game were to be loaded dynamically into another Flash movie, any calls to _root wouldn't work. Similarly, when working with Movie Clips and objects, use this to refer to an internal property or method. Your code will be much easier to read and you'll avoid problems with duplicate variable names.


    Double-click on the missile to re-enter symbol editing mode, and click on frame 1. Go to the body of the fire() function and type in:

     this.velocity += this.acceleration; //Line 1 this._y += this.velocity;           //Line 2 if(this._y > Stage.height)       //Line 3 { _parent.score--;               //Line 4 resetMissile();               //Line 5 } 

  • Line 1 increases the speed of the missile's descent.

  • Line 2 moves the missile down the stage, towards the bottom.

  • Line 3 checks to see if the missile has hit the bottom of the stage. It's preferable to use Stage.height instead of an actual number in case you change the movie's dimensions later.

  • Line 4 subtracts a point from the player's score, as a penalty for letting the missile hit.

Last but not least, we have resetMissile() . The program simply reuses each missile clip once it's been destroyed or reached the bottom. Go to resetMissile() 's body and enter the following code:

 this._x = Math.floor(random(Stage.width) - this._width);         //Line 1 this._y = -(Math.floor(random(100) + this._height));             //Line 2 this.vel = 1;                                                    //Line 3 this.timer = Math.floor(random(29));                             //Line 4 

  • Line 1 moves the missile to a random position on the X-axis. By default, a Movie Clip's origin is its upper-left corner, so the -this._width ensures that the entire missile will be onscreen.

  • Line 2 puts the missile somewhere between 50 and 150 pixels above the stage. This will cause some missiles to be faster than others when they hit the screen, adding a bit of variety to the game.

  • Line 3 resets the missile's velocity.

  • Line 4 resets the missile's timer to a random value.

The game is nearly complete! This is an excellent time to test the movie, so press Ctrl+Enter (Command+Return on the Mac) and grab your mouse. If you typed everything correctly, your "missile" should repeatedly drop from the top of the screen. You may be able to see it reappearing and sitting still after each cycle; Flash zooms out and shows offscreen objects in the test environment. This will also affect the Stage's width and height variables, so select "Show all" from the View Magnification menu, or press Ctrl+3 (Command+3 on a Mac).

The missile's movement probably seems slow and choppy. That's because the velocity, acceleration, and timer were all written with a frame rate of 30 fps in mind, which is the standard minimum frame rate for games today. To change your game's frame rate, go back to the work area and hit Ctrl+J (or Command+J on Macintosh) to access the Document Properties shown in Figure 8-16. Change the frame rate to 30 and close the window. You can also change the background color, if you wish.

To increase the difficulty, click on the missile, copy it, and paste two of them onto the work area. Spread them out across the top of the stage, and test your movie again. A little harder now, right?

Figure 8-16. Changing the game's frame rate

8.3.3. Make the Game Winnable

Looking at the current state of our project, it does everything required, except accomplish the goal. In its current state, the game isn't winnable or losable. To remedy this, you need to constantly keep an eye on the player's score and take them to the win/lose frames once it passes a certain threshold.

You could do the score checking in fire() or the on handlers of the missile, but that results in a poorly organized code structure that'll be hard to update. You would have to make sure all your missiles had the new score checking code, and if you decided to change the conditions for winning and losing, you'd have to go back and edit them all. The better (and most common) solution is to make a movie clip whose sole purpose is to check the score. This "action clip" will allow you to complete the game and keep the code separated logically.

Go to the Library panel (Press F11 if it's not visible) and click the File-Plus icon in the lower-left corner. You'll be prompted to name your new symbol; call it "checker" and make sure its behavior is set to Movie Clip. You'll be taken into symbol-editing mode once you hit OK. Draw a small box somewhere in the middle (size and color are unimportant), and then head back to the main timeline. Drag "checker" from the library onto the work area (keep it offscreen), click it, open up the Actions panel, and type:

 onClipEvent(enterFrame) { if(_parent.score >= 5) { _parent.gotoAndStop("win"); } else if(_parent.score <= -5) { _parent.gotoAndStop("lose"); } } 

There's no new code here; every frame, the "checker" clip looks at the score and directs the player to the "win" or "lose" screen if their score is high or low enough. Press Ctrl+Enter/Command+Return once more and enjoy the completed game!

8.3.4. Hacking the Hack

This game isn't much to look at (see Figure 8-17), but remember, replacing and updating graphics in Flash takes seconds. A small face-lift gives the game a lot more credibility; you can draw directly in Flash, or press Ctrl+R (Command+R on the Mac) to import a picture. Use some graphics to replace the black squares and make a background (see Figure 8-18), and spice up the win/lose screens!

Figure 8-17. Our missile game, before updating the graphics

Figure 8-18. and after

Other things to consider are explosion animations for the missiles, multiple difficulties, or moving to a new level with more missiles after reaching a certain score. With the knowledge of how to apply game programming principles to Flash, it becomes trivial to add the "complex" features that supposedly make the game what it is. As long as you keep your code well organized and have a clear vision for your game, there's no limit to what you can do with Flash.

Matt DelGiudice



Retro Gaming Hacks
Retro Gaming Hacks: Tips & Tools for Playing the Classics
ISBN: 0596009178
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Chris Kohler

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net