Creating the Game Object

The main game object is a one-off object called, perhaps not surprisingly, Game. Its main purpose is to initialize the game engine for Alien Invasion and run the game loop as well as provide a mechanism for changing the main scene that displays.

Because Alien Invasion doesn’t have an input subsystem, the Game class is also responsible for setting up listeners for keyboard and touch input. To start, only keyboard input is handled; touch input is added in the next chapter.

Now that the game starts to take shape, a few additional considerations are necessary. Instead of just executing code willy-nilly when it is evaluated, it generally makes sense to wait for the page to finish downloading before initializing the game. The Game class takes this into consideration and listens for a “load” event from the window before booting up the game.

The code for the Game class will be added at the top of engine.js.

Implementing the Game Object

Now walk through the 40+ lines of code that make up the Game object a section at a time. (See the full listing at the top of game_class/engine.js in the chapter code.) The class starts off much like the SpriteSheet, as a one-time class instance:

var Game = new function() {

Next is the initialization routine, called with the ID of the canvas element to fill, the sprite data that is passed to the SpriteSheet, and the callback when the game is ready to start.

// Game Initialization this.initialize = function(canvasElementId,sprite_data,callback) ...

Get Professional HTML5 Mobile Game Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.