Introducing HTML5 GameDevelopmentJesse FreemanBeijing Cambridge Farnham Köln Sebastopol

Introducing HTML5 Game Developmentby Jesse FreemanCopyright 2012 Game Cook, Inc. All rights reserved.Printed in the United States of America.Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.O’Reilly books may be purchased for educational, business, or sales promotional use. Online editionsare also available for most titles ( For more information, contact ourcorporate/institutional sales department: (800) 998-9938 or [email protected]: Mary TreselerDevelopment Editor: Kristin L. KellyProduction Editor: Kristen BorgCover Designer: Karen MontgomeryInterior Designer: David FutatoIllustrator: Robert RomanoRevision History for the First Edition:2012-02-10First releaseSee 9781449315177 for release details.Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks ofO’Reilly Media, Inc. Introducing HTML5 Game Development, the image of a gemmous dragonet, andrelated trade dress are trademarks of O’Reilly Media, Inc.Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of atrademark claim, the designations have been printed in caps or initial caps.While every precaution has been taken in the preparation of this book, the publisher and author assumeno responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.ISBN: 978-1-449-31517-7[LSI]

I would like to dedicate this book to Ed Love, whowas my teacher, mentor, and good friend when Iwent to Florida State University. He was a veryimportant person in my life and his sudden passingindirectly motivated me to explore computer art,which snowballed into what I do

Table of ContentsPreface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix1. Introduction To Impact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Why Use Impact?Setting Up a Local EnvironmentInstall WebStorm/PHPStormInstall Apache/PHP/MySQLOther Hosting OptionsSetting Up a New Impact ProjectModulesHow Classes WorkCore ClassesHow Inner Classes WorkLevel Editor12233467810112. Working With Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Sprites and Sprite SheetsScripting in PhotoshopWorking with Sprites in PhotoshopOptimizing Sprites131416173. Introduction To Game Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19What is Game Design?Sample Game Design DocumentGameplayExploring a MapCombatCompleting a MapDeathMain info

BossesEquipmentInventoryEquipping ItemsWeapons and ArmorLeveling UpWinning the GameComing Up With IdeasBooks to Read2323232424252525264. Building A Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Creating Our First LevelSaving/Loading Maps in WeltmeisterCollisionMapsThe Main ClassCustomizing the Main ClassKey BindingCreating the Player ClassUsing Your Sprite SheetAdding Simple PhysicsDefining Animation SequencesCreating a Monster ClassCollision Detectiontype PropertycheckAgainst Propertycollides PropertyHealthWeaponsFiring the WeaponAdd Multiple WeaponsKilling EntitiesRespawning the PlayerCreate Death AnimationsAdding Grenade ExplosionsCustomizing the CameraLoading New 6162645. Working With Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Creating Font Sprite SheetsAdding Text to Your Game69706. Working With Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Adding Sounds73vi Table of

Adding MusicMobile Browser Sound Compatibility Issues74757. Creating Game Screens and HUDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Extending Impact’s Game ClassCreating a Start ScreenPlayer Stats ScreenCreating the Game Over ScreenAdding In-Game HUDGame RewardsIn-Game Analytics777880848687888. Debugging Your Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Impact’s DebuggerPublishing Your GameBaking Your GameMobile Web SupportCompiling for Native iOS93969697989. Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103References and Links104Table of Contents

PrefaceAbout This BookThis relatively short book attempts to cover a very large topic. While this book is considered an introduction to building HTML5 games with Impact, a JavaScript gameframework, it is also intended to be a companion guide to help you get started making,and more importantly, finishing your games. I have created a high-level overview ofwhat I consider to be the most important parts of making a game with Impact, alongwith what you should keep in mind or research further in order to become a bettergame developer. This book will take you step-by-step through the process of creatinga 2D side-scrolling game with Impact, and how to publish it to the web and even package it up as a native iOS app.I have also worked very hard to condense all this material as much as possible. Thatbeing said, when topics are larger than the scope of this book, I do my best to pointyou in the right direction so you can find more information. Making games is hard workand requires not only technical skills, but also a lot of planning and commitment tocompleting the project. While following this book may not guarantee a hit game, it willmost certainly prepare you to complete the game you start, which any game developerwill tell you is probably the hardest part.Who This Book Is ForIntroducing HTML5 Game Development is a book targeting all levels of game developers. Having prior programing knowledge (especially being familiar with JavaScript)doesn’t hurt, but it’s not necessarily a requirement. In this book, we will cover howImpact works and build the basic foundation of a game with it. We will also cover alittle bit about game design and how to publish your Impact games to the Web, desktop,and mobile. For mobile deployment, we will look at how to publish your game as anative app on iOS

Who This Book Is Not ForThis book is not for developers who are looking to build fully cross-browser and mobilegames with JavaScript. While HTML5 has come a long way in the past few years, weare still far away from widespread adoption of the underlying technologies Impact relieson, such as Canvas, sound, and advanced user input. That doesn’t mean it isn’t possibleto make a cross-platform game with Impact but before we move on, I just want to setyour expectations correctly. Impact requires modern browsers and even on mobiledevices with browsers that support HTML5, you will still run into audio issues thatmay affect the ability of your game to run correctly for everyone.Conventions Used in This BookThe following typographical conventions are used in this book:ItalicIndicates new terms, URLs, email addresses, filenames, and file extensions.Constant widthUsed for program listings, as well as within paragraphs to refer to program elementssuch as variable or function names, databases, data types, environment variables,statements, and keywords.Constant width boldShows commands or other text that should be typed literally by the user.Constant width italicShows text that should be replaced with user-supplied values or by values determined by context.This icon signifies a tip, suggestion, or general note.This Book’s Example FilesYou can download the example files for this book from this /In the example files, you will find all the files necessary for the book. In addition to thegame source code, you will also find the source code for the iOS version of the finalgame. Since Impact’s source code cannot be distributed with this book’s examples, youwill have to supply your own copy of Impact to make these examples work. Make sureyou read the included ReadMe.txt file for information on what is included with thedownload and how to correctly set it up.x

Using Code ExamplesThis book is here to help you get your job done. In general, you may use the code inthis book in your programs and documentation. You do not need to contact us forpermission unless you’re reproducing a significant portion of the code. For example,writing a program that uses several chunks of code from this book does not requirepermission. Selling or distributing a CD-ROM of examples from O’Reilly books doesrequire permission. Answering a question by citing this book and quoting examplecode does not require permission. Incorporating a significant amount of example codefrom this book into your product’s documentation does require permission.We appreciate, but do not require, attribution. An attribution usually includes the title,author, publisher, and ISBN. For example: “Introducing HTML5 Game Developmentby Jesse Freeman (O’Reilly). Copyright 2012 Game Cook, Inc., 978-1-4493-1517-7.”If you feel your use of code examples falls outside fair use or the permission given above,feel free to contact us at [email protected] To Use This BookDevelopment rarely happens in a vacuum. In today’s world, email, Twitter, blog posts,coworkers, friends, and colleagues all play a vital role in helping you solve developmentproblems. Consider this book yet another resource at your disposal to help you solvethe development problems you will encounter. The content is arranged in such a waythat solutions should be easy to find and easy to understand. However, this book doeshave a big advantage: it is available anytime of the day or night.Safari Books OnlineSafari Books Online is an on-demand digital library that lets you easilysearch over 7,500 technology and creative reference books and videos tofind the answers you need quickly.With a subscription, you can read any page and watch any video from our library online.Read books on your cell phone and mobile devices. Access new titles before they areavailable for print, and get exclusive access to manuscripts in development and postfeedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit fromtons of other time-saving features.O’Reilly Media has uploaded this book to the Safari Books Online service. To have fulldigital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at

How to Contact UsPlease address comments and questions concerning this book to the publisher:O’Reilly Media, Inc.1005 Gravenstein Highway NorthSebastopol, CA 95472800-998-9938 (in the United States or Canada)707-829-0515 (international or local)707-829-0104 (fax)We have a web page for this book, where we list errata, examples, and any additionalinformation. You can access this page oTo comment or ask technical questions about this book, send email to:[email protected] more information about our books, courses, conferences, and news, see our websiteat us on Facebook: us on Twitter: us on YouTube: First and foremost, I would like to thank my wife and son for all their support while Iwas making this book. I’d also like to thank my parents and family for all their helpand support over the years. I also have a lot of respect for all the thought leaders in thedevelopment community who continue to inspire me, such as Keith Peters, John Lindquist, Jesse Warden, Chuck Freedman, Sean McCracken, Michael Labriola, Nate Beck,Troy Gilbert, Joel Hooks, Brendan Lee, Scott Penberthy, Seb Lee-Delisle, Rich Shupe,and especially Jobe Makar who taught me how to make Flash games years ago.Thank you as well to Mary Treseler and Rich Tretola from O’Reilly Media, Inc., forproviding me with this opportunity and to Dominic Szablewski for his feedback on thisbook and for creating such a great game framework. I also couldn’t have done this bookwithout the help from my amazing tech editors: Riche Shupe, Gareth Parker andRichard Davey.Finally I wanted to give a special thanks to Dan Wolfe for creating the splash screenart for Resident Raver, as well as for his artistic help on my other games. And I can’tforget my good friend Frank Pirozzi for inspiring me to create Resident Raver and shoota video of it back in college.xii

CHAPTER 1Introduction To ImpactImpact is a JavaScript game framework created by Dominic Szablewski. Impact takesadvantage of the modern browser’s Canvas element in order to create high-performance2D games on the Web and even mobile. One of the biggest advantages of using Impactis that it is easy to pick up, comes with very good code examples, has an active community, and has a very robust level editor called Weltmeister. The only barrier of entryis the licensing fee for the software, since it is not open source. After purchasing alicense, you do get the full source code, the Weltmeister level editor, and free currentmajor version updates (1.x). While there are other open source and free JavaScript gameframeworks out there, Impact has an extra level of polish I haven’t seen with anythingelse so far.Why Use Impact?Perhaps one of the most appealing factors of buying Impact is the inclusion of a sampleObjective-C project that allows you to compile your Web game into a native iOS app.This enables your game to take advantage of OpenGL for graphics and OpenAL forsound instead of the Canvas and Audio elements in the mobile Safari browser. Thissolution gives your game almost native-like performance on iOS, and it can be packagedup and sold in the Apple Store just like a native app.Here are some links to help you learn more about Impact and examples of it in action:Site: http://impactjs.comForum:

Tools you will need:PHPFor saving levels created with Weltmeister.ApacheFor locally hosting and testing your game.IDEsImpact has no IDE dependencies; you can create your games with any simple texteditor. I prefer to use WebStorm or PHPStorm since these IDEs, which are madeby JetBrains, offer code hinting, project management, refactoring, and debugging.BrowsersImpact works very well on WebKit browsers, especially Chrome, but any modernbrowser with support for Canvas and the Audio tag should also work.Setting Up a Local EnvironmentBefore getting started, we are going to have to set up a simple Web development environment in order to take full advantage of Impact and its level editor. Plus, by settingup a local development environment, we can simulate what it will be like to host thegame in a production environment. Let’s take a look at configuring Apache, the IDE,and Impact itself.Install WebStorm/PHPStormWhile you can use any basic text editor, I prefer to use an IDE that offers a more robustset of features such as code hinting, refactoring, project management, version controlintegration, and a debugger. JetBrains has two IDEs that both handle JavaScript/HTML5 development. If you only plan on doing JavaScript development, I would suggest using WebStorm. If you need to do HTML5 and PHP development (which comesin handy since Impact’s level editor uses PHP) you should look at PHPStorm.Installing these applications is straightforward. Here are URLs for each orm IDE has a 30-day trial and after the trial costs 99 for a license. There are a lot ofresources out there on how to use each IDE, so I am not going to cover it here.2 Chapter 1: Introduction To

Install Apache/PHP/MySQLThere are many guides for installing Apache and PHP on your operating system ofchoice. Here are some simple one-click solutions to help get you up and running asquickly as possible:MacFor Mac, you should use an all-in-one solution such as MAMP ( This is a free one-click solution for getting Apache, PHP, andMySQL set up on your Mac. Likewise, you can also use the built-in version of PHPthat comes with OS X, but you will need to do some manual configuration ofApache to get it working. Simply do a search for “Enabling PHP in Mac OS X” inorder to find instructions.PCJust like on Mac, there are some excellent one-click solutions for setting up Apache,PHP, and MySQL. I have used XAMP ( in the past, and have had excellent success with it.Other Hosting OptionsIf you prefer not to work on a LAMP (Linux, Apache, MySQL, PHP) stack you cancheck out the following projects that allow you to run Impact on different hostingenvironments:Node.jsConner Petzold made a Node.js module that allows Impact to run on a Node HTTPserver. His Node-Impact module is on GitHub at can run Impact on IIS and .NET thanks to Mike Hamilton’s ImpactJSIIS-.NET-API project, which you can find at Chris Darroch put together a Sinatra backend for Impact. Just remove the .phpextensions for the API calls in your lib/weltmeister/config.js and fire upimpact.rb, which you can find at Esposito has a GitHub project that implements a backend server in Python forImpact to let you develop multiple games at once. You can check out the projectat Hosting Options

Setting Up a New Impact ProjectImpact is a self-contained project. Each game you create will require you to copy thedefault Impact project folder (which you get once you buy a license) into a new locationon your server and start from scratch. Impact is set up so you can easily do all yourwork from your local host.To get started, copy the Impact project into your local host. You should see the following files (Figure 1-1).Figure 1-1. Impact project files.As you can see, I have renamed my impact folder residentraver, which is the name ofthe game we are going to create in this book. Here is a quick breakdown of everythingin the folder:index.htmlThis is the main .html file that runs your game.libThis is the core code for Impact and where you will store your own game-specificJS files. This also contains the source code for Weltmeister.mediaThis is the assets directory, and where all game art and sound files will go.toolsThis directory contains .php scripts to minify your game’s JS files and make itharder for people to have access to the game’s source code. This is part of the licenseand is important so you don’t accidentally distribute the source code.weltmeister.htmlThis is the level editor’s .html file.You should now have everything you need to run your first game. If you open yourbrowser and navigate to http://localhost/residentraver1 you should see the followingpage (Figure 1-2).1. Based on how Apache is set up on your computer, you may have a different URL for your localhost. Ifyou are using MAMP, it may be http://localhost:8888, or with XAMP it is http://localhost. Refer to yourApache documentation for the correct URL.4 Chapter 1: Introduction To

Figure 1-2. This is what you will see when you run an Impact game for the first time.Before moving on, I just wanted to take a quick moment to look at the index.html fileand how it is set up. Open it up in your editor and you should see the following HTMLcode:1234567891011121314 !DOCTYPE html html head title Impact Game /title style type "text/css" html,body {background-color: #000;color: #fff;font-family: helvetica, arial, sans-serif;margin: 0;padding: 0;font-size: 12pt;}Setting Up a New Impact Project

151617181920212223242526272829303132#canvas {position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;border: 1px solid #555;} /style script type "text/javascript" src "lib/impact/impact.js" /script script type "text/javascript" src "lib/game/main.js" /script /head body canvas id "canvas" /canvas /body /html Outside of the style tag, you may notice there isn’t a lot of code actually embedded inthe page. We have two script tags that load in the impact.js framework and ourmain.js JavaScript file. Finally the only tag in body is the Canvas element.The Canvas element is part of the HTML5 spec and is what actuallyallows Impact to run in the browsers. Think of the canvas as an imagethat we can draw bitmap data into. Impact takes care of all the underlying code we would have had to write in order to display game graphicsto the screen. You can learn more about how the Canvas tag works ment. It’s also important to notethat the Canvas element only works in modern browsers such asChrome 13 , Safari 3.2 , Firefox 6 and IE 9 . For a full list of browsersthat support the Canvas element, go to canvas.You can also add your own HTML code around the Canvas element and design thispage to look like any other HTML file. Just keep in mind that we use the canvas id inour game in order to tell impact where to render our game’s graphics to, so don’t changeit unless you update your game’s initialization logic.Now we are ready to learn more about the Impact framework.ModulesImpact’s source code is organized into modules. Since JavaScript itself does not havean include() function that can load other JavaScript source files into an object, Impacthas its own system. A module typically looks like this:6 Chapter 1: Introduction To

nes(function(){// code for this module});The first block defines the module name '', which directly corresponds tothe file name. Modules and their dependencies typically reside in the lib/ folder of yourImpact project directory, and subdirectories are included in a path to these files usingobject-model dot syntax. Therefore, the my-file.js file sits in the lib/game/my-file.js.The second block defines any additional files that will be loaded at runtime. SinceJavaScript itself does not have an established way to load other JavaScript source filesinto an object, Impact has its own system. The modules listed in the .requires()method will be loaded from the lib/impact/game.js, lib/impact/image.js, and lib/game/other-file.js project directory, respectively. These required files will be loadedbefore the module’s body and before the last block of the above module example isexecuted.The last step the module takes is to execute the function passed to the .defines()method. This linear process allows you to control when code is loaded and run. It’simportant to follow Impact’s file naming and location structure since it will try to automatically load these resources for you during the pre-load phase. Next, we’ll talk alittle more about classes in Impact and how they work.How Classes WorkIn JavaScript, there is no real notion of a traditional class structure like you have inother OOP languages. In JavaScript, everything is an Object. While this allows JavaScript to be incredibly flexible, it also makes it difficult to structure your code in areusable way. To solve this issue, Impact has a pseudo-class object, which is the basisof every class we will create in our game.Impact’s class object is based on John Resig’s simple JavaScript inheritance code ce), but it isextended with deep copying of properties and static instantiation.Here is an example of how we can create a new person class by building off of Impact’score Class object:How Classes Work

1234567891011// Create a new class "Person"var Person ig.Class.extend({name: '',init: function( name ) { name;}});// Instantiate an object of the first classvar e new Person('John Doe');; // John DoeYou may have noticed that we actually extend the functionality of the ig.Class objectvia the .extend() method.In traditionally class based languages, the extends keyword allows us tocopy over the existing functionality of another class. This is what willallow us to infuse additional functionality into all of our game classeswithout having to actually duplicate code all over the place.In addition to extending off of ig.Class, you can actually extend off of any custom classyou create. Again, in order to extend another class you simply use the .extend() functionality. Here we are going to extend off of our person class to create a new zombieclass:12345678910// Create another class by extending the "Person" classvar Zombie Person.extend({init: function( name ) {this.parent( 'Zombie: ' name );}});// Instantiate an object of the second classvar p new Zombie('John Doe');; // Zombie: John DoeAll classes that are created with .extend() will also have an .extend() method that canbe used for further subclassing. When working inside of extended classes, you canuse .this and .parent for scope. You will see later on how splitting up core logic intoindividual classes will help expostulate functionality and make our game code easierto maintain while we develop it.Core ClassesImpact is made up of several core classes that revolve around the game framework andall the necessary systems such as rendering, maps, sounds, and more. All the classesare in the ig namespace, which is set up by the core class. Here is a list of the mainclasses used in Impact along with a short description of what they do:8 Chapter 1: Introduction To

ig CoreThe ig object provides the module definition and loading capabilities as well assome utility functions.AnimationAn ig.Animation object takes care of animating an entity or BackgroundMap tiles.Frames from an AnimationSheet—an image with all animation frames—are drawnas specified by the animation’s frameTime and sequence.AnimationSheetig.AnimationSheet is a thin wrapper around an ig.Image object. It specifies thewidth and height properties for each animation frame in the sheet. It is used by theig.Animation class.BackgroundMapAn ig.BackgroundMap draws tiles from a Tileset, as indicated by its 2D data array.CollisionMapAn ig.Collision takes a 2D TileMap and allows tracing against it for collisions.EntityInteractive objects in the game world are typically subclassed from this base entityclass. It provides animation, drawing, and basic physics. Subclassing your entitiesfrom ig.Entity ensures that it can be added to the game world, react to the CollisionMap along with other entities, and be added to a level within Weltmeister.FontAn ig.Font object loads a specially formatted font image and allows you to drawtext with it.Gameig.Game is the main hub for your game. It hosts all currently active entities, BackgroundMaps, and a CollisionMap. You can subclass your own game class fromig.Game.Imageig.Image is a wrapper around image resources (.png, .gif, .jpeg). It takes care ofloading and scaling the source image. You can draw the whole image by calling .draw() or just one tile of it by calling .drawTile().Inputig.Input handles all keyboard and mouse input.Loaderig.Loader is the default pre-loader for all images and sounds that the game needs.By default, it displays a white progress bar on a black background.Mapig.Map is the base class for ig.BackgroundMap and ig.CollisionMap. It only providesbasic access to the tiles in the map data.Core Classes

Musicig.Music offers the ability to play a list of background music in order or randomly.SoundAn instance of ig.Sound represents a sound file to be used as background music orgame sound.SoundManagerThe SoundManager takes care of loading sounds and providing them forig.Music and ig.Sound instances. An instance of the SoundManager is automatically created at ig.soundManager by the ig.main() function.Systemig.System takes care of starting and stopping the run loop and calls the .run()method on the current game object. It also does the housekeeping for ig.Input andprovides some utility methods.TimerThe ig.Timer has two distinct modes of operation. You can either get the differenceby calling .delta() between the current time and the timer’s target time (as set bythe constructor or .set()) or just get the current tick—the time since the last callto .tick().You can learn more about each of these classes and their methods on Impact’s websiteunder the documentation section at Inner Classes WorkIn traditional class-based languages, you usually have the option to put a class insideof another class’s package structure. These are called inner classes. Impact h

Introducing HTML5 Game Development is a book targeting all levels of game develop-ers. Having prior programing knowledge (especially being familiar with JavaScript) doesn't hurt, but it's not necessarily a requirement. In this book, we will cover how Impact works and build the basic foundation of a game with it. We will also cover a