a blog for those who code

Tuesday 3 November 2015

Bouncing Ball Game using HTML5 Canvas Element - Part 2

In this post we will be discussing about bouncing ball game using HTML5 Canvas Element and requestAnimationFrame. This post is continuation of Bouncing Ball Game using HTML5 Canvas Element - Part 1, where we have created Paddle Class and added some keyboard interaction to move the paddle. To know more about Keyboard and Mouse Interaction with Canvas Element you can check Keyboard and Mouse Interaction to HTML5 Canvas Element.


At first we will be creating a Brick Class as shown below :

function Bricks() {
  this.width = 99; this.columns = 10; this.rows = 10; this.height = 9;
  this.x = 0; this.y = 0; this.padding = 1;
  
  this.initBrickArray = function() {
    for(i = 0; i < this.rows; i++) {
      bricksArray[i] = new Array(this.columns);
      for(j = 0; j < this.columns; j++) {
        bricksArray[i][j] = 1;
      }
    }
  }
  
  this.draw = function() {
    context.save(); var x1 = 0; var y1 = 0;
    for(i = 0; i < this.rows; i++) {
      y1 = 0;
      for(j = 0; j < this.columns; j++) {
        if(bricksArray[i][j] === 1) {
          context.fillRect(y1 + this.padding, x1 + this.padding, this.width, this.height);
          y1 += this.width + this.padding;
        }
        else {
          y1 += this.width + this.padding;
        }
      }
      x1 += this.height + this.padding;
    }
  }
}

This class will create a number of bricks starting from the top left corner. We then initialize a global bricksArray which will have value 1 or 0 (1 denotes brick is visible). Then we will draw brick rectangles based on the values of bricksArray on the canvas.

When the game ends we are giving a notification to the user that game has ended and you scored this much using the below code.

var count = 0;
for(var i = 0; i < bricks.rows; i++) {
  for(var j = 0; j < bricks.columns; j++) {
    if(bricksArray[i][j] === 0) {
      count += 1;
    }
  }
}
document.getElementById("result").innerHTML = "Game Ended, you Scored " + count;

Full Source Code


Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

No comments:

Post a Comment