HTML5 Guidelines for Web Developers

(coco) #1

226 Chapter 8—Web Storage and Offline Web Applications


8.4.3.3 JavaScript Functions of the Game
The HTML part of our example was not very exciting, but the JavaScript part of
the game is much more interesting. The previously mentioned window.onload
function initializes a new object game with the type click2tick and then calls the
init function of this object:

window.onload = function() {
var game = new click2tick();
game.init();
};

To keep the JavaScript code as flexible as possible, the entire game function is
wrapped in a library (GameLib), made accessible with all functions as global object:

(function () {
var GameLib = function () {
var elem = {};
var image, canvas, context;
...
};
// expose object
  window.click2tick = GameLib;
}());

In the second-to-last line of the listing, the window object is assigned the GameLib
class with the new name click2tick. The init function of this class loads the
existing games, initializes the canvas element, and starts the first game (see List-
ing 8.2):

Listing 8.2 The init function for the GameLib library
this.init = function() {
// build game-selection pulldown
var o = ''
for (var i=0; i<gamedata.length; i++) {
o += addOpt(i,gamedata[i].title);
}
_get('selGame').innerHTML = o;
_get('selGame').options.selectedIndex = 0;
_get('selGame').onchange = function() {
startGame(this.value);
};

// define empty image used for map later
image = new Image();

canvas = document.querySelector("CANVAS");
context = canvas.getContext('2d');
Free download pdf