Game Development Reference
In-Depth Information
Chapter 4. Using
HTML5
to
Catch
a
Snake
This chapter is the first part of a two-part series, where we'll build the first version of
a game, and then spice it up with more HTML5 APIs in the next chapter. Both ver-
sions will be complete and playable, but since covering all of the APIs in the same
game within one chapter would make for a very large chapter, we'll break things up
into smaller chunks, and write two separate games.
The first version of the game will cover five new concepts, namely, HTML5's 2D can-
vas API , offline application cache , web workers , typed arrays , and requestAnim-
ationFrame . The canvas element allows us to draw 2D as well as 3D graphics, and
manipulate image data at a very low level, gaining access to individual pixel informa-
tion. Offline application cache, also known as app cache, allows us to cache specific
assets from a server into the user's browser, so that the application can work even
when no internet access is available. Web workers is a thread-like mechanism that al-
lows us to execute JavaScript code in a separate thread from the main UI thread. This
way, the user interface is never blocked, and users don't see a page not respons-
ive warning. Typed arrays is a new native JavaScript data type similar to arrays,
but much more efficient, and specifically designed to handle binary data. Finally, re-
questAnimationFrame is an API offered by the browser to help us perform time-based
animation. Instead of using a JavaScript timer ( setTimeout or setInterval ) mul-
tiple times a second in order to perform animations, we can let the browser do the
heavy lifting, optimizing the animation beyond what we could achieve in JavaScript
alone.
The game
You've certainly seen or played this game before. You control a snake in a 2D grid
only moving up, down, left, or right. When you change the direction in which the
snake's head is moving, each part of the snake's body gradually changes direction as
well, following the head. If you run into a wall, or into the snake's own body, you lose.
If you guide the snake's head over a fruit, the snake's body gets larger. The larger
the snake gets, the more challenging the game becomes. Additionally, the speed at
which the snake moves can be increased for an extra challenge. In order to stay true
Search WWH ::




Custom Search