Adding a Score

There’s still one obvious piece to the game that is clearly missing: a point system for users to brag about to their friends. This is something that you can remedy quickly by adding a new game board to the game.

Add the contents of Listing 3-4 to the bottom of engine.js.

Listing 3-4: GamePoints

var GamePoints = function() {
  Game.points = 0;
  var pointsLength = 8;
  this.draw = function(ctx) {
    ctx.save();

    ctx.font = "bold 18px arial";
    ctx.fillStyle= "#FFFFFF";

    var txt = "" + Game.points;

    var i = pointsLength - txt.length, zeros = "";
    while(i-- > 0) { zeros += "0"; }

    ctx.fillText(zeros + txt,10,20);

    ctx.restore();
  }
  this.step = function(dt) { }
}

This object has one purpose in its life: to draw the score in the top left of the game. The current score for the game is stored directly on the Game object in a property named points. Every time a new GamePoints object is created, the game assumes a new game is beginning and resets the score to 0.

For every frame, the game grabs the current score and pads it with leading zeros so that it’s always pointsLength digits long. It then calls fillText to draw the points onto the screen.

To get the points onto the page, a GamePoints object needs to be created. Open up game.js and add the initializer to the fifth board:

var playGame = function() {
  var board = new GameBoard();
  board.add(new PlayerShip());
  board.add(new Level(level1,winGame));
  Game.setBoard(3,board);
  Game.setBoard(5,new GamePoints(0));
};

Board 5 was chosen because ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.