Core HTML5 2D Game Programming - David Geary 9780133564242
Core HTML5 2D Game Programming - David Geary 9780133564242
2D Game Programming
This page intentionally left blank
Core HTML5
2D Game Programming
David Geary
The author and publisher have taken care in the preparation of this book, but make no expressed
or implied warranty of any kind and assume no responsibility for errors or omissions. No
liability is assumed for incidental or consequential damages in connection with or arising out
of the use of the information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to your
business, training goals, marketing focus, or branding interests), please contact our corporate
sales department at corpsales@pearsoned.com or (800) 382–3419.
For questions about sales outside the United States, please contact international@pearsoned.com.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use
material from this work, please submit a written request to Pearson Education, Inc., Permissions
Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your
request to (201) 236-3290.
ISBN-13: 978-0-13-356424-2
ISBN-10: 0-13-356424-X
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing, July 2014
Contents
Preface ............................................................................................................ xv
Acknowledgments .......................................................................................... xxi
About the Author ........................................................................................... xxiii
v
vi Contents
4.5 Freeze the Game to Ensure It Resumes Exactly Where It Left Off ..... 107
4.6 Pause the Game When the Window Loses Focus ................................ 108
4.7 Resume a Paused Game with an Animated Countdown .................. 110
4.7.1 Display Toasts (Brief Messages) to Players .............................. 111
4.7.2 Snail Bait’s Countdown .............................................................. 112
4.8 Conclusion ................................................................................................ 115
4.9 Exercises .................................................................................................... 116
Chapter 8: Time, Part I: Finite Behaviors and Linear Motion ................... 207
8.1 Implement an Initial Jump Algorithm .................................................. 209
8.2 Shift Responsibility for Jumping to the Runner .................................. 210
8.3 Implement the Jump Behavior ............................................................... 213
8.4 Time Animations with Stopwatches ..................................................... 214
8.5 Refine the Jump Behavior ....................................................................... 217
8.6 Implement Linear Motion ...................................................................... 220
8.6.1 Ascending ..................................................................................... 221
8.6.2 Descending ................................................................................... 223
8.7 Pause Behaviors ....................................................................................... 225
8.8 Conclusion ................................................................................................ 227
8.9 Exercises .................................................................................................... 227
xv
xvi Preface
I make liberal use of Notes, Tips, Cautions, and Best Practices. Encapsulating
those topics in callouts streamlines the book’s main discussion, and since each
Note, Tip, Caution, and Best Practice has a title (excluding callouts with a single
line), you can decide at a glance whether those ancillary topics are pertinent to
your situation. In general, the book’s main discussion shows you how things
work, whereas the callouts delve into why things work as they do. If you’re in a
hurry, you can quickly get to the bottom of how things work by sticking to the
main discussion, skimming the callouts to make sure you’re not missing anything
important.
Chapters 1–19 of the book chronicle the development of Snail Bait, starting with
a version of the game that simply displays graphics and ending with a full-featured
HTML5 video game. Chapter 20 is the Epilogue, which uses much of what the
book covered in the previous 19 chapters to implement a second video game.
If you plan to read the book, as opposed to using it solely as reference, you will
most likely want to start reading at either Chapter 1 or Chapter 20. If you start at
the beginning, Chapter 20 will be a recap and review of what you learned previ-
ously, in addition to providing new insights such as using polar coordinates and
rotating coordinate systems.
If you start reading at Chapter 20, perhaps even just skimming the chapter, you
can get an idea for what lies behind in the previous 19 chapters. If you start at
Chapter 20, don’t expect to understand a lot of what you read in that chapter the
first time around.
I assume that many readers will want to use this book as a reference, so I’ve in-
cluded references to section headings at the start of each chapter, in addition to
a short discussion at the beginning of each chapter about what the chapter
entails. That will help you locate topics. I’ve also included many step-by-step in-
structions on how to implement features so that you can follow those steps to
implement similar features of your own.
chapter-specific version of the game. See the next section for more information
about chapter-specific versions of Snail Bait.
Prerequisites
No one would think of taking a creative writing class in a language they couldn’t
speak or write. Likewise, you must know JavaScript to implement sophisticated
games with HTML5. JavaScript is a nonnegotiable prerequisite for this book.
Nearly all the code listings in this book are JavaScript, but you still need to know
your way around HTML and CSS. You should also be familiar with computer
graphics and have a good grasp of basic mathematics.
Your Game
Finally, let’s talk about why we’re here. I assume you’re reading this book because
you want to implement a game of your own.
The chapters of this book discuss individual aspects of game programming, such
as implementing sprites or detecting collisions. Although they pertain to Snail
Bait, you will be able to easily translate those aspects to your own game.
Preface xix
The order of the chapters, however, is also significant because it shows you how
to implement a game from start to finish. In the beginning of the book, we gather
raw materials, set up our development environment, and then start development
by drawing the game’s basic graphics. Subsequent chapters add animation, sprites,
sprite behaviors, and so on. If you’re starting a game from scratch, you may want
to follow that same outline, so you can alternate between reading about features
and implementing them on your own.
Before you get started coding in earnest, you should take the time to set up your
development environment and become as familiar as you can with the browser’s
developer tools. You should also make sure you shorten your development cycle
as discussed at the end of Chapter 2. The time you initially spend preparing will
make you more productive later on.
Finally, thank you for buying this book. I can’t wait to see the games you create!
David Geary
Fort Collins, Colorado
2014
Online Resources
Core HTML5 2D Game Programming’s companion website: corehtml5games.com
Play Snail Bait: corehtml5games.com/snailbait
Play Bodega’s Revenge: corehtml5games.com/bodegas-revenge
Download Snail Bait: corehtml5games.com/book/downloads/snailbait
Download Bodega’s Revenge: corehtml5games.com/book/downloads/
bodegas-revenge
David’s “HTML5 2D Game Development” video from O’Reilly: shop.oreilly.
com/product/0636920030737.do.
David’s “HTML5 2D Game Development” series on IBM developerWorks:
www.ibm.com/developerworks/java/library/j-html5-game1/index.html
A video of David speaking about HTML5 game programming at the Atlanta
HTML5 Users Group in 2013: youtube.com/watch?v=S256vAqGY6c
Core HTML5 Canvas at http://amzn.to/1jfuf0C. Take a deep dive into Canvas
with David’s book.
This page intentionally left blank
Acknowledgments
I am fortunate to have a great editor—the only editor I’ve had in nearly twenty
years of writing books—who is always receptive to my ideas for my next book
and who guides my books from conception to completion. This book was no
different. Greg Doench helped shepherd this book through the process from an
idea to a finished book.
I’m also fortunate to have a wonderful copyeditor, Mary Lou Nohr. She has
copyedited every one of my previous books, and she graciously agreed to smooth
out my rough edges once again.
This is the second book that I’ve done with Alina Kirsanova, who’s a wizardess
at taking my PDFs and making them look super. Once again, Julie Nahil oversaw
the production of the book and kept everything on track as we headed to the
printer.
For every book I write, I select reviewers who I think will make the book much
better than I ever could have alone. For this book, I had four excellent reviewers:
Jim O’Hara, Timothy Harrington, Simon Sarris, and Willam Malone. Gintas
Sanders also gave me permission to use his coins in Snail Bait and gave me some
great critiques of the game.
When I shot the “HTML5 2D Game Development” video for O’Reilly, I taught a
class in front of a live audience. One of the audience members asked great ques-
tions and came up with several insights. Jim O’Hara was one of my most consci-
entious reviewers and, as he did in class, provided lots of great questions and
insights.
My editor, Greg Doench, put me in touch with Tim Harrington, who is a Senior
Academic Applications Analyst at Devry University with a background in game
development. Like Jim, Tim came up with lots of insights that made me rethink
how I presented material.
I wanted to find a graphics expert for this book who knew a lot about game pro-
gramming, and I found one. Simon Sarris, who, much to my delight, is not only
both of those things, but is also an excellent writer. He made this book better in
several different ways.
xxi
xxii Acknowledgments
Finally, I was fortunate to have William Malone review this book. William is a
professional game developer who’s implemented games for Sesame Street (see
Cookie Kart Racing at http://bit.ly/1nlSY3N). William made a tremendous dif-
ference in this book by pointing out many subtleties that would’ve escaped me,
especially concerning mobile devices.
About the Author
David is the author of Core HTML5 Canvas and coauthor of Core JavaServer
Faces. David has written several other bestselling books on client- and
server-side Java, including one of the bestselling Java books of all time,
Graphic Java.
xxiii
This page intentionally left blank
CHAPTER 1
Introduction
Topics in This Chapter
• 1.1 Snail Bait — p. 3
• 1.2 HTML5 Game Development Best Practices — p. 10
• 1.3 Special Features — p. 16
• 1.4 Snail Bait’s HTML and CSS — p. 18
• 1.5 Snail Bait’s Humble Beginning — p. 25
• 1.6 The Use of JavaScript in This Book — p. 28
• 1.7 Conclusion — p. 31
• 1.8 Exercises — p. 31
The great thing about software development is that you can make nearly anything
you can imagine come to life on screen. Unencumbered by physical constraints
that hamper engineers in other disciplines, software developers have long used
graphics APIs and UI toolkits to implement creative and compelling applications.
Arguably, the most creative genre of software development is game programming;
few endeavors are more rewarding from a creative standpoint than making the
vision you have for a game become a reality.
The great thing about game programming is that it’s never been more accessible.
With the advent of open source graphics, sound, and music, you no longer need
to be an artist and a musician to implement games. And the development envi-
ronments built into modern browsers are not only free, they contain all the
tools you need to create the most sophisticated games. You need only supply
1
2 Chapter 1 Introduction
• Canvas 2D API
• Timing Control for Script-based Animations
• Audio
• CSS3 Transitions
1.1 Snail Bait 3
In this book we develop Snail Bait entirely from scratch, without any third-party
game frameworks, so you can learn how to implement all the common aspects
of a video game from the ground up. That knowledge will be invaluable whether
you implement a game by using a framework or not.
• d or ← turns the runner to the left and scrolls the background from left to
right.
• k or → turns the runner to the right and scrolls the background from right
to left.
• j makes the runner jump.
• p pauses the game.
4 Chapter 1 Introduction
When the game begins, the player has three lives. Icons representing the number
of remaining lives are displayed above and to the left of the game’s canvas, as
you can see in Figure 1.1. In the runner’s quest to make it to the end of the level,
she must avoid bad guys—bees and bats—while trying to capture valuable items
such as coins, rubies, and sapphires. If the runner collides with bad guys,
she blows up, the player loses a life, and the runner goes back to the beginning
of the level. When she collides with valuable items, the valuable item disappears,
the score increases, and the game plays a pleasant sound effect.
The snail periodically shoots snail bombs (the gray ball shown near the center of
Figure 1.1). The bombs, like bees and bats, blow up the runner when they hit her.
The game ends in one of two ways: the player loses all three lives, or the player
lands on the gold button. If the player lands on the gold button, the player wins
the game and Snail Bait shows the animation depicted in Figure 1.2.
Snail Bait maintains high scores on a server. If the player beats the existing high
score, Snail Bait lets the player enter their name with a heads-up display (HUD),
as shown in Figure 1.3.
1.1 Snail Bait 5
If the player doesn’t win the game or beat the existing high score, Snail Bait
displays game credits, as shown in Figure 1.4.
With the exception of the runner, everything in Snail Bait scrolls continuously in
the horizontal direction. That scrolling further categorizes Snail Bait as a side-
scroller platform game. However, that’s not the only motion in the game, which
leads us to sprites and their behaviors.
• Chrome 13
• Firefox 4
• Internet Explorer 9
• Opera 11
• Safari 5
WASD?
By convention, computer games often use the w, a, s, and d keys to control play.
That convention evolved primarily because it lets right-handed players use the mouse
and keyboard simultaneously. It also leaves the right hand free to press the spacebar
or modifier keys such as CTRL or ALT. Snail Bait doesn’t use WASD because it
doesn’t receive input from the mouse or modifier keys. But you can easily modify
the game’s code to use any combination of keys.
};
Snail Bait defines a runBehavior object, which it passes—in an array with other
behaviors—to the runner sprite’s constructor, along with the sprite’s type (runner)
and its artist (runnerArtist). For every animation frame in which the runner is
visible, the game invokes the runBehavior object’s execute() method. That
execute() method makes it appear as though the runner is running by advancing
through the set of images that depict the runner in various run poses.
See Chapter 2 for more information on obtaining game resources and setting
up a development environment.
game’s animation runs so as to save resources such as CPU and battery power;
after all, why waste resources on a window or tab that’s not visible?
Frame-rate clamping wreaks havoc with most collision detection algorithms be-
cause those algorithms check for collisions every time the game draws an anima-
tion frame; if it takes too long between animation frames, sprites can move past
one another without detection. To avoid collision detection meltdowns resulting
from frame-rate clamping, you must automatically pause the game when the window
loses focus.
When Snail Bait pauses the game, it displays a toast to let the player know the
game is paused, as shown in Figure 1.5.
In addition to pausing and unpausing the game, therefore, you must also freeze
and thaw the game to ensure a smooth transition when the game resumes. We
discuss pausing and freezing the game in more detail in Chapter 4.
12 Chapter 1 Introduction
NOTE: Toasts
A toast—as in raising a glass to one’s health—is information that a game displays
to a player for a short time. A toast can be simple text, as in Figure 1.5, or it can
represent a more traditional dialog box, as in Figure 1.8 on p. 14.
Figure 1.6 Snail Bait’s countdown after the window regains focus
are fully opaque, whereas the lives indicators and scoreboard at the top of the
game are partially transparent, as shown in Figure 1.7. As the game’s instructions
toast fades, that transparency reverses; the lives indicator and scoreboard become
fully opaque, while the checkboxes and instructions become nearly transparent,
as they are in Figure 1.6.
Snail Bait dims elements and fades toasts with CSS3 transitions.
Snail Bait goes to all that trouble to focus attention on what’s currently important.
Initially, players should pay attention to the instructions below the game’s canvas;
once the game is underway, players will be more focused on their score and how
many lives are remaining.
14 Chapter 1 Introduction
Figure 1.10 Snail Bait’s sprite sheet (the gray background is transparent)
16 Chapter 1 Introduction
When Snail Bait draws the game’s sprites, it copies rectangles from the sprite
sheet into the canvas.
1.2.7 Store High Scores and Send Realtime, In-game Metrics to the Server
Most games interact with a server for a variety of reasons. Snail Bait stores high
scores on a server in addition to sending game metrics during gameplay. Snail
Bait does not use any third-party graphics frameworks; however, it does use two
JavaScript frameworks—Node.js and socket.io—to communicate between the
player’s computer and a server. See Chapter 19 for more details.
• Developer backdoor
• Time system
• Particle systems
Snail Bait reveals the developer backdoor, shown in Figure 1.11, when you press
CTRL-d. With the backdoor visible, you can control the rate at which time flows
through the game, making it easy to run the game in slow motion to see how
game events such as collision detection take place. Conversely, you can run
the game faster than normal to determine the best pace for the game.
You can turn collision rectangles on for a better look at exactly how collisions
occur; if the smoking holes obscure your view, you can turn the smoke off by
deselecting the Smoke checkbox. You can also fine-tune the threshold at which
Snail Bait displays the game’s running slowly warning, shown in Figure 1.8, or
you can turn it off entirely, which lets you playtest slow frame rates without Snail
Bait intervening at all.
When you playtest a particular section of the game, you can avoid playing through
the preceding sections every time you test: In addition to the controls at the top
of the game’s canvas, the developer backdoor displays a ruler at the bottom of
the canvas that shows how far the background has scrolled horizontally in pixels.
1.3 Special Features 17
You use those values to restart the game at a particular horizontal location,
thereby avoiding the preceding sections of the game. For convenience, when the
developer backdoor is visible you can also simply drag the game, including
the background and all the sprites, horizontally to reposition the runner.
The developer backdoor lets you control the rate at which time flows through the
game by virtue of Snail Bait’s time system. Everything that happens in Snail Bait
depends on the current game time, which is the elapsed time since the game
started; for example, when the runner begins a jump, the game records the current
game time, and thereafter moves the runner through the jump sequence frame
by frame, depending on how much time has elapsed since the runner began
the jump.
By representing the current game time as the real time, which is Snail Bait’s default
mode, the game runs at its intended rate. However, Snail Bait’s time system can
misrepresent the current game time as something other than the real time; for
example, the time system can consistently report that the current game time is
half of the actual time, causing the game to run at half speed.
Besides letting you control the rate at which time flows through the game, Snail
Bait’s time system is also the source of special effects. When the runner collides
with a bad guy and explodes, Snail Bait slows time to a crawl while transitioning
18 Chapter 1 Introduction
to the next life. Once the transition is complete, Snail Bait returns time to normal,
indicating that it’s time to resume play.
Finally, Snail Bait uses two particle systems to create the illusion of smoke and
fire in the background. In Chapter 16, we take a close look at those particle systems
so you can create similar effects of your own.
Now that you have a high-level understanding of the game, let’s take a look at
some code.
• JavaScript: 5,230
• CSS: 690
• HTML: 350
• snailbait.js: 3,740
• Supporting JavaScript code: 1,500
• Initializing data for sprites: 500
• Creating sprites: 400
• Sprite behavior implementations: 730
• Event handling: 300
• User interface: 225
• Sound: 130
Figure 1.12 Snail Bait’s CSS for the top half of the game
When Snail Bait loads resources, it displays the animation shown in Figure 1.14.
During that animation, none of the game’s elements are visible, which is why all
the elements in Figure 1.12 have their display attribute set to none (with the
exception of snailbait-arena, which has no visible characteristics of its own).
After the game loads resources, it fades in the game’s elements by setting their
display attribute to block and subsequently setting their opacity to 1.0 (fully
opaque). Elements that have a transition associated with their opacity property,
like snailbait-lives, snailbait-score, and snailbait-game-canvas, transition
into view over a specified period of time.
The snailbait-lives element has an absolute position; otherwise, with its default
position of static, it will expand to fit the width of its enclosing DIV, forcing the
score beneath it.
The game canvas, which is an HTML5 canvas element, is where all the game’s
action takes place; it’s the only element in Figure 1.12 that’s not a DIV.
Figure 1.15 shows the HTML elements in the lower half of the game.
Like the lives and score elements in the upper half of the game, the browser does
not display the elements at the bottom during the game’s loading animation, so
those elements are initially invisible and have an opacity transition of five seconds,
1.4 Snail Bait’s HTML and CSS 21
Figure 1.15 Snail Bait’s CSS for the bottom of the game
which Snail Bait uses to fade them and all their contained elements in along with
the score and lives elements at the beginning of the game.
22 Chapter 1 Introduction
<!--
Basic HTML elements for Snail Bait. Elements for things such
as sounds, credits, toasts, developer backdoor, etc. are
omitted for brevity.
-->
<html>
<!-- Head.........................................................-->
<head>
<title>Snail Bait</title>
...
<!-- Body.........................................................-->
<body>
<!-- Arena.....................................................-->
<div id='snailbait-arena'>
...
<div id='snailbait-lives'>
<img id='snailbait-life-icon-left'
src='images/runner-small.png'/>
<img id='snailbait-life-icon-middle'
src='images/runner-small.png'/>
<img id='snailbait-life-icon-right'
src='images/runner-small.png'/>
</div>
1.4 Snail Bait’s HTML and CSS 23
<div id='snailbait-score'>0</div>
...
<div id='snailbait-sound-and-music'>
<div id='snailbait-sound-checkbox-div'
class='snailbait-checkbox-div'>
</div>
<div class='snailbait-checkbox-div'>
Music <input id='snailbait-music-checkbox'
type='checkbox' checked/>
</div>
</div>
<!-- Instructions...........................................-->
<div id='snailbait-instructions'>
<div class='snailbait-keys'>
← / d
<div class='snailbait-explanation'>move left</div>
→ / k
<div class='snailbait-explanation'>move right</div>
</div>
<div class='snailbait-keys'>
j <div class='snailbait-explanation'>jump</div>
</div>
<div class='snailbait-keys'>
p <div class='snailbait-explanation'>pause</div>
</div>
</div>
<div id='snailbait-mobile-instructions'>
(Continues)
24 Chapter 1 Introduction
<div class='snailbait-keys'>
Right
<div class='snailbait-explanation'>
Run right or jump
</div>
</div>
</div>
<!-- Copyright..............................................-->
<!-- JavaScript................................................-->
<!-- Other script tags for the game's other JavaScript files are
omitted for brevity. The final version of the game puts all
the game's JavaScript into a single file. See Chapter 19
for more details about how Snail Bait is deployed. -->
<script src='snailbait.js'></script>
</body>
</html>
The canvas element is where all the action takes place. The canvas comes with a
2D context with a powerful API for implementing 2D games, among other things,
as you will see in Section 3.1, “Draw Graphics and Images with the HTML5 canvas
Element,” on p. 64. The text inside the canvas element is fallback text that the
browser displays only if it does not support HTML5 canvas element.
One final note about the game’s HTML and CSS: Notice that the width and height
of the canvas is set with canvas element attributes in the preceding listing. Those
attributes pertain to both the size of the canvas element and the size of the drawing
surface contained within that element.
On the other hand, using CSS to set the width and height of the canvas element
sets only the size of the element. The drawing surface remains at its default width
and height of 300 × 150 pixels, respectively. That means you will have a mismatch
between the canvas element size and the size of its drawing surface when you
1.5 Snail Bait’s Humble Beginning 25
set the element’s size to something other than the default 300 × 150 pixels, and
in that case the browser scales the drawing surface to fit the element. Most of the time
that effect is unwanted, so it’s a good idea to set the size of the canvas element
with its width and height attributes, and not with CSS.
At this point, you’ve already seen the end of the Snail Bait story. Now let’s go
back to the beginning.
Figure 1.17 shows the starting point for the game, which simply draws the back-
ground and the runner. To start, the runner is not a sprite; instead, the game
draws her directly.
Example 1.3 lists the starting point for the game’s HTML, which is just a distilled
version of the HTML in Example 1.2.
<body>
<div id='snailbait-arena'>
<canvas id='snailbait-game-canvas' width='800' height='400'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
1.5 Snail Bait’s Humble Beginning 27
<!-- JavaScript................................................-->
<script src='snailbait.js'></script>
</body>
</html>
Initially, the arena contains only the game’s canvas, which is 800 pixels wide by
400 pixels high and has a thin blue border. Example 1.4 shows the starting point
for Snail Bait’s CSS.
#snailbait-arena {
margin: 0 auto;
margin-top: 50px;
width: 800px;
height: 400px;
}
#snailbait-game-canvas {
border: 1.5px solid blue;
}
Example 1.5 shows the starting point for Snail Bait’s JavaScript.
function initializeImages() {
background.src = 'images/background.png';
runnerImage.src = 'images/runner.png';
function draw() {
drawBackground();
drawRunner();
}
function drawBackground() {
context.drawImage(background, 0, 0);
}
function drawRunner() {
context.drawImage(runnerImage, 50, 280);
}
// Launch game.........................................................
initializeImages();
The preceding JavaScript accesses the canvas element and subsequently obtains
a reference to the canvas’s 2D context. The code then draws the background and
runner by using the three-argument variant of drawImage() to draw images at a
particular location in the canvas.
The game starts when the background image loads. For now, starting the game
entails simply drawing the background and the runner.
this.LEFT = 1;
...
};
SnailBait.prototype = {
// Methods are defined here
JavaScript objects are instantiated in this book with JavaScript’s new operator, as
shown in Example 1.7.
createSnailSprites: function () {
var snail,
snailArtist = new SpriteSheetArtist(this.spritesheet,
this.snailCells);
[
this.paceBehavior,
this.snailShootBehavior,
new CycleBehavior(
300, // 300ms per image
5000) // 1.5 seconds interlude
]);
snail.width = this.SNAIL_CELLS_WIDTH;
snail.height = this.SNAIL_CELLS_HEIGHT;
(Continues)
30 Chapter 1 Introduction
this.snails.push(snail);
}
},
...
};
This book also defines objects using JSON (JavaScript Object Notation), as shown
in Example 1.8.
this.fallingWhistleSound = {
position: 0.03, // seconds
duration: 1464, // milliseconds
volume: 0.1
};
this.audioChannels = [
{ playing: false, audio: null, },
{ playing: false, audio: null, },
{ playing: false, audio: null, }
];
...
};
Finally, the JavaScript code in this book adheres closely to the subset of JavaScript
discussed in Douglas Crockford’s book JavaScript: The Good Parts. The code in
this book also follows the coding conventions discussed in that book.
1.8 Exercises 31
1.7 Conclusion
Snail Bait is an HTML5 platform game implemented with the canvas element’s
2D API. As you’ll see throughout the rest of this book, that API provides a
powerful and intuitive set of functions that let you implement nearly any 2D
game you can imagine.
In this chapter, we looked at Snail Bait from a high level to get a feel for its features
and to understand some of the best practices it implements. Although you can
get a good grasp of its gameplay from reading this chapter, you will have a
much better understanding of the game if you play it, which you can do at
corehtml5games.com.
At the end of this chapter, we looked at a starting point for Snail Bait that simply
draws the background and the runner. Before we build on that starting point and
begin coding in earnest, however, we’ll take a brief detour in the next chapter
to become familiar with the browser development environment and to see
how to access freely available graphics, sound, and music. If you’re already up
to speed on HTML5 development in general and you know how to access open
source assets online, feel free to skip ahead to Chapter 3.
1.8 Exercises
1. Use a different image for the background.
2. Draw the runner at different locations in the canvas.
3. Draw the background at different locations in the canvas.
4. In the draw() function, draw the runner first and then the background.
5. Remove the width and height attributes from the snailbait-game-canvas
element in index.html and add width and height properties—with the same
values of 800px and 400px, respectively—to the snailbait-game-canvas ele-
ment in the CSS file. When you restart the game, does it look the same as
before? Can you explain the result?
This page intentionally left blank
Index
A scaling games on, 370
add my score button size of image files on, 164
disabling, 534, 539 viewport directives on, 375–376
enabling, 527, 535–536 animate() function, 76–77, 86, 100
event handler for, 536 animate() method (SnailBait), 101, 106,
addBehaviors() method (SmokingHole), 417, 156–160
430–431 double buffering with, 63
addChangeListener() method (Slider), monitoring frame rate with, 464–465
493 naive implementation of, 100
addEventListener() method (window) using time system for, 258–259
during transitions, 327 animated GIFs
for developer backdoor, 483 creating, 54
for jumps, 209–210 for loading sequence, 135, 139
on size or orientation changes, 378 for winning sequence, 467–468
vs. onkeydown, 105 animation frames
addSpriteMethods() method (SmokingHole), drawing, 86–87
416, 421 last, time of, 108, 159
addSpriteProperties() method animation loop. See game loop
(SmokingHole), 415–416 animation timers
addSpritesToSpriteArray() method duration of, 235
(SnailBait), 168, 413 for jumps, 231–233
addTouchEventHandlers() method implementing, 233–235
(SnailBait), 396–397 redefining current time for, 264–265
adjustScore() method (collideBehavior), animations, 53–54, 61–90
441 implementing, 314–320
adjustVerticalPosition() method smooth, 63, 70–75
(BounceBehavior), 243–245 throttled heavily, 108–109
Adobe Illustrator, 64 AnimationTimer object
advance() method (SpriteSheetArtist), getElapsedTime() method, 234–235, 265
163–164 isExpired(), isPaused(), isRunning()
advanceCursor() method (SmokingHole), methods, 234, 265
431 makeEaseXXXEasingFunction() methods,
advanceSpeedSamplesIndex() method 232–233, 238–239, 242, 428
(SnailBait), 466 pause(), unpause() methods, 234, 263, 265
all.css, all.js files, 541–542 prototype object, 264–265
Android reset(), stop() methods, 234, 265
adding an icon to home screen on, 402 start() method, 234, 264
audio sprites on, 401 Apache 2.0 license, 50–51
HTML5 applications on, 364–367 appendFile() method (fs), 526
layout viewport on, 371 appendTo() method (Slider), 493–494, 498
mobile instructions on, 390 Apple, 64, 373
remote debugging for, 365 arc() method (canvas context), 64
595
596 Index