Beginning Flash Game Programming For Dummies

by Andy Harris

 

 

About the Author

Andy Harris earned a degree in Special Education from Indiana University/Purdue University–Indianapolis (IUPUI). He taught young adults with severe disabilities for several years. He also taught himself enough computer programming to support his teaching habit with freelance programming. Those were the exciting days when computers started to have hard drives, and some computers connected to each other with arcane protocols. He taught programming in those days because it was fun.

Eventually, Andy decided to teach computer science full time, and he still teaches at IUPUI. He lectures in the applied computing program and runs the streaming media lab. He also teaches classes in whatever programming language is in demand at the time. He has developed a large number of online video-based courses and international distance education projects.

Andy has written several books on various computing topics and languages including Java, C#, mobile computing, JavaScript, and PHP/MySQL.

Andy welcomes comments and suggestions about his books. He can be reached at aharris@cs.iupui.edu .

 

Dedication

This book is dedicated to Heather, Elizabeth, Matthew, Jacob, and now Benjamin.

 

Author’s Acknowledgments

Although writing a book often seems like a lonely endeavor, it really takes a lot of talented and dedicated people to make a book on a topic as complex as this. Fortunately, I am blessed by my companions in this process.

First, I give thanks to Him from whom all flows.

Even nonfiction books have heroes. My hero is my wife, Heather. You are the unending delight of my life. Thank you for who you are and for all you do. Thanks also to all my kids. I know it’s rough when Daddy spends so much time writing. I’m done for a little while. Let’s go play! I love you guys.

Thanks to my dear friend Melody Layne who helped me once again take my writing career to a new place.

Thanks to acquisitions editor Katie Feltman. Even when I couldn’t find the restaurant where we had our first meeting, you had faith in me and encouraged me all through the process. Thanks also to project editor Pat O’Brien, the Drill Sergeant For Dummies who can turn even me into an author worthy of the incredible For Dummies series. I’m still learning, Pat. One day, I’ll really get it. Seriously, thanks for all the guidance. I really appreciate learning from you and working with you. Another big thank you goes to copy editor Teresa Artman: I’m amazed how she can take my mush and turn it into something that actually sounds good. And a big thanks to Scott Hofmann for technical editing.

The production process that goes behind a book is dizzying and impressive. I’d like to thank everyone at Wiley for their professionalism. The folks in layout, composition, graphics, proofing, cover work, marketing, and everyone else who worked on this book all deserve three cheers for their terrific work.

Thanks to Macromedia for developing Flash in a way that is adaptable for games and accessible to people who are not wealthy.

Thanks to John Gersting for looking over my code and giving me such good advice and guidance.

A very special thanks to my students, especially those in Web Game Development N451. You always teach me way more than I can ever teach you. Thank you for letting me be your teacher.

 

Publisher’s Acknowledgments

We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.

Some of the people who helped bring this book to market include the following:

Acquisitions, Editorial, and Media Development

Senior Project Editor: Pat O’Brien

Acquisitions Editor: Katie Feltman

Senior Copy Editor: Teresa Artman

Technical Editor: Scott Hofmann

Editorial Manager: Kevin Kirschner

Media Development Specialist: Laura Moss

Media Development Manager: Laura VanWinkle

Media Development Supervisor: Richard Graves

Editorial Assistant: Amanda Foxworth

Cartoons: Rich Tennant (www.the5thwave.com )

Composition Services

Project Coordinator: Adrienne Martinez

Layout and Graphics: Carl Byers, Andrea Dahl, Joyce Haughey, Stephanie D. Jumper, Barbara Moore, Barry Offringa, Lynsey Osborn

Proofreaders: Leeann Harney, Jessica Kramer, Joe Niesen, Carl William Pierce, Rob Springer, TECHBOOKS Production Services

Indexer: TECHBOOKS Production Services

Special Help: Rebecca Senninger

Publishing and Editorial for Technology Dummies

Richard Swadley, Vice President and Executive Group Publisher

Andy Cummings, Vice President and Publisher

Mary Bednarek, Executive Acquisitions Director

Mary C. Corder, Editorial Director

Publishing for Consumer Dummies

Diane Graves Steele, Vice President and Publisher

Joyce Pepple, Acquisitions Director

Composition Services

Gerry Fahey, Vice President of Production Services

Debbie Stailey, Director of Composition Services

Contents

Title

Introduction

What’s Really (Not) Required

About This Book

How This Book Is Organized

Icons Used in This Book

Where to Go from Here

A Final Word

Part I : Basic Flash

Chapter 1: Why You Want to Write Games in Flash

Designing and Writing Games

Game Programming in Flash

Comparing ActionScript with Animation

How You Make a Game

Game Programming 101

Chapter 2: Cruising and Using the Flash Environment

Creating a New Program Project

Adding Buttons

Part II : The Next Steps

Chapter 3: Altered States

State of Nonconfusion

Adding Keyframes

Making a Great Adventure

Chapter 4: Getting with the Program

Different Text for Different Jobs

Building the Greeting Program

On a Roll: Making Random Numbers

Making Decisions with Conditions

Responding to False Conditions

Making Lots of Decisions

Chapter 5: Making an Interactive Game

Introducing the Math Game

Making an Adder

Building the Visual Design

Coding the Pages

Coping with Bugs and Crashes

Part III : Sprites, or Movie Clips

Chapter 6: Introducing Sprites and Movie Clips

Building a Sprite

Don’t Object to Objects

Making a Well-Behaved Object

Overcoming Your Boundaries

Making a Cursor

Chapter 7: Won’t Be Long ’Til You Write Pong

Building the Game Plan

Following the Mouse with the Player Paddle

Adding the Bouncing Ball

Building a Better Bounce

Adding a Computer Opponent

Building Artificial Stupidity

Adding a Scorekeeping Mechanism

Part IV : Getting Control of the Situation

Chapter 8: Keyboard Input and Audio Output

Introducing the Monster Traffic Game

Responding to the Keyboard

Adding Sounds

Chapter 9: It’s Alive! Animating Your Sprites

Creating Animated Sprites

Moving a Sprite under Computer Control

Creating a User-Controlled Sprite

Chapter 10: Building the Monster Traffic Game

Reviewing the Basic Design

Adding More Opponents

Firing Missiles

Testing for Collisions

Adding the Sound Effects

Completing the Program

Part V : Phun with Phuzzy Physics

Chapter 11: Vectors and Gravity

Tower, Give Me a Vector

Doing Vector Conversion in Flash

Using Vector Projection in Motion

Fun with Ballistics

Calculating the Vector from dx and dy

Following the Mouse

Chapter 12: Vehicle Motion

Newton without the Figs

Newton and Vectors

Baby, You Can Drive My Car

Getting Lost in Space

Captain, We’re Caught in a Gravity Well

Building a Better Boat

The Secret of Traction

Chapter 13: The Life and Death of Sprites

Here We Go Loop-de-Loop

Making Many Things with Arrays

Building Sprites Dynamically

Creating Custom Objects

Part VI : The Part of Tens

Chapter 14: Ten Math Concepts for Game Programmers

Managing Velocity

Accelerating an Object

Calculating a Distance

Projecting a Vector

Generating a Vector

Compensating for Gravity

Newton’s Second Law

Generating a Random Integer

Combining Vectors

Sophisticated Vehicle Motion

Chapter 15: Ten Game Starters

Asteroids

Lunar Lander

Egg Cannon

Zelda

Platform Scroller Games

Breakout

Space Invaders

Orbit Matcher

Tile-Based World Games

Whack-an-Author

Introduction

I ’m sure you bought your computer to do all kinds of serious work. Computers are good for homework, e-mail, work, and other perfectly respectable endeavors. But face it: Computers are also all about games. I love games, and I always have. As soon as I started to learn about computers, I wanted to use them to play games. I soon found it even more fun to make games than to play them. Even though I have a (somewhat) respectable career as a computer science teacher, the gaming aspect of computing has stayed with me.

If you’re like me — with a love of games and curious how to write them — this book is for you. Most books on computer programming are pretty boring, but not this one. For example, I show you how to blow up stuff (as in Kaboom!, not as in enlarging a photograph). Most books on computer gaming are really technical, with endless descriptions of graphics primitives and indecipherable function calls. Not this one, though. I get things going as quickly as possible and let Flash do all the dirty work.

Yup, you read right, Flash. The Flash environment has emerged as a terrific tool for writing Web-based games. I dedicate this book to how games are made using this terrific tool. Along the way, you can glean some skills that might be useful in more ordinary programming contexts, too.

Okay, geek-speak disclaimer: Sometimes I have to use geeky words and even a little (gasp) math. Don’t worry, though. Everything I show you has a purpose, and there won’t be a quiz later. I speak English, too, so I promise to explain everything in regular English, with lots of fun analogies. (My favorite is the dog that does trigonometry.)

What’s Really (Not) Required

If you’re not sure you know everything you need to get started, don’t worry! Here’s what I don’t assume you know upfront:

bullet I don’t expect you to be an ace computer user. You should, though, be comfortable with all the ordinary computer operations, like saving/loading files and getting around in your operating system.

bullet You don’t need a super-high-speed computer. Any system that can run Flash MX 2004 will do. These games work on even more humble machines.

bullet You don’t have to be a Flash master, either. If you know how to make really great Flash animations, that’s wonderful but not really necessary. Game programming is different from animation.

bullet You don’t need the most expensive version of Flash (Flash MX 2004 Professional). This version of Flash does add some special features, but you really don’t need any of those features to write wonderful games.

Tip

This book was written using Flash MX 2004 with the latest updates available. If you’re running an earlier version of Flash, some of the programs will still run, but you won’t be able to open the FLA files from the Web site.

bullet You definitely don’t need to be a pasty-faced, mega-caffeine-swilling computer programmer. (However, if that describes you, you’re still going to have a great time, you l33t haxor!) I start from the very beginning, using game programming to teach the basic tenets of programming in any language. Teaser: Stick around for more catapulting cows here than in any COBOL book you’ve ever seen.

So what is required? Only a copy of Flash MX 2004, some determination, and a lot of imagination.

About This Book

Each chapter in the book describes a particular facet of game development. You can read the chapters in any order you wish, especially if you already have some knowledge of Flash or programming. If you’re just starting, however, I recommend reading this book from front to back, simply because programming is a cumulative skill.

If you want, you can just download files from the Web site and start playing away. Most of the examples in the book are much more interesting in real life than I can show in a screen shot. Keep in mind that most of the example games on the Web site are left very simple to illustrate one particular idea. Still, they are pretty fun, and after you play them, I bet you’ll want to read how they were made so you can change them and make your own variant.

Another fun alternative is to start at the very last chapter, which shows how to write ten different styles of games. Choose a game type that you want to master and go back to those chapters you’ll need to pick up the necessary skills. This approach allows you to get to the game you want quickly without having to wade through anything that doesn’t relate directly to that game.

How This Book Is Organized

I organized this book by writing a sophisticated Bayesian filter, artificial intelligence algorithm. Just kidding. Really, I sketched it on a napkin at the breakfast table. Still, I think it makes sense to break the book into a series of sections.

I lovingly named these parts as follows.

Part I: Basic Flash

This part gives you a programmer’s introduction to the Flash environment. You see the various doohickeys and thingamabobs on the screen — and which ones you can ignore. You read how to make text appear and change onscreen, how to respond to button presses, and how to build a basic adventure game.

Part II: Getting with the Program

Time to experience some traditional programming skills (but nothing too boring). In this part, you master text-based input and output, see how to build random numbers, and make the computer perform the basic mathematical operations you’ll use to build space muskrats in later games in the book. I show you how to make a sophisticated math game that generates random math problems. After that, I promise — no more educational games.

Part III: Sprites, or Movie Clips

Here you can use the most important element in Flash: the movie clip. Read here to find out what a sprite is and how you can use movie clips to make them easily in Flash. Then see how to build and control basic movie clips, making them move around onscreen, bashing into walls and each other. For a little ramble down Nostalgia Road, stick with me here to build the all-time classic Pong game.

Part IV: Getting Control of the Situation

Games aren’t much fun if the user doesn’t do anything. This section shows you how to respond to keyboard input and control sprites onscreen via player input. You also see how to add sound effects to your games (so anybody playing your game at work runs the risk of being fired). You discover more sophisticated ways of moving and animating your sprites to make them more realistic. Follow along as I walk you through building a complete game — Monster Traffic — complete with monsters, flames, car alarms, destruction, and mayhem.

Part V: Phun with Phuzzy Physics

Don’t worry — this isn’t anything like Physics 101 with Professor Baldnoggin. Oh, no. The stuff in this section is much more cool than that. Sure, I’ve got to use words like mass and vector at some point, but it’s worth it because you use these ideas to build vehicles that turn realistically, boats that skid around on water, spacecraft that orbit planets realistically, and all kinds of other geeky fun. You also become the true master of your universe as you see how to create and destroy sprites at your slightest whim (Muhahahaha!).

Part VI: The Part of Tens

The famous Part of Tens is a staple of any book in the For Dummies series. The two chapters in this part are pretty handy. The first one outlines the ten most important math concepts for a game programmer. These are ideas that you see throughout the book. Master these, and you master game development in any language. The last chapter is my favorite in the whole book. I wrote starter code for ten different games. I didn’t finish any of them — that’s your job! I did get the basic framework down so you can add your own flourishes. You’ll find several classics (such as Space Invaders, Zelda, and Asteroids ) and a couple of original ideas. You can think of this section as a recipe book to get you started on your own games.

Icons Used in This Book

Certain concepts in any book ought to stand out on the page. With that in mind, this For Dummies book includes a number of margin icons for certain situations:

Tip

Tips are suggestions to make things easier.

TechnicalStuff

Sometimes I have to talk about certain technical things in order to keep my Self-Important Computer Science Instructor Certification. These things are interesting but not crucial, so I mark them with this icon. You don’t need to read them if you don’t want, but memorize some of these paragraphs before you go to your next computer science party. The guests will love you.

Warning(bomb)

Be sure to read text marked with this icon! If you do not follow a warning, bad things could happen: Puffs of black smoke might come out of your monitor, your workspace could be deluged by a plague of frogs, or your program simply won’t work right.

Remember

These tidbits denote info you ought to think about, but it’s not going to cause a disaster if you don’t pay attention.

OnTheWeb

If you’re gonna be a programmer, you gotta have code. Of course, I give you all the source code files for this book, located handily online at

www.dummies.com/go/flashgameprogrammingfd1e

Where to Go from Here

My recommendations on how to proceed? Mainly, have some fun and write some games.

bullet Begin by simply downloading the software and playing the games I’ve put there.

bullet If you’re really new to all this stuff, jump in and start writing games. I put the easiest game programming tasks at the beginning, but you can start wherever you want. If you start in the middle and get confused, just back up until you’re comfortable.

bullet For all other concerns, use the index or jump straight to the chapter you need. (You can always return later at your leisure.)

A Final Word

Thank you for buying this book, and I hope that you find Beginning Flash Game Programming For Dummies fun and valuable. I had a great time writing this book, and I think you’ll have a lot of fun using it to write really terrific games. Have fun, learn a lot, and let me know what you’ve made!

Part I

Basic Flash

In this part . . .

You discover the basic toolset of the Flash environment as a programmer sees it. You give your programs various states and take a tour of all the beginning tools. You finish the section with a complete adventure game.

Chapter 1 shows you how to start thinking like a programmer. I explain how Flash and ActionScript are like other programming languages and some key ways they are different. If you’ve never programmed before, I prepare you with some wisdom about the programming process.

Chapter 2 is about creating Flash projects. You make a button and have it respond when the user clicks it. You find out how to embed your Flash games into Web pages.