{{draft}}
8. Track the score and win
This is the 8th step out of 10 of the Gamedev Canvas tutorial.
Destroying the bricks is really cool, but to be even more awesome we could keep track of the points awarded for every brick we hit. That way we can see our score throughout the game, and eventually impress our friends. We will need a variable for that:
var score = 0;
And then there's the drawScore()
function:
function drawScore() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText("Score: "+score, 8, 20); }
Drawing the font is similar to drawing a shape. The font definition looks exactly like the one in CSS - we can set the size and font type in the font method. Then there's fillStyle
for the color of the font and fillText
to set the text. First parameter is the text itself where we can add our variable to show the current number of points, and the last two parameters are the coordinates. Adding that to our draw()
function executed on every frame makes it up to date with everything else on the screen:
function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBricks(); drawBall(); drawPaddle(); drawScore(); collisionDetection(); // ... }
Collecting the points works good, but we won't be removing them forever - they will end at some point. It's the main purpose of the game after all, so on every brick we hit we will increase the score and check if we collected all the points already:
score++; if(score == brickRowCount*brickColumnCount) { alert("YOU WIN, CONGRATS!"); document.location.reload(); }
Let's add that to the collisionDetection()
function:
function collisionDetection() { for(c=0; c<brickColumnCount; c++) { for(r=0; r<brickRowCount; r++) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) { dy = -dy; b.status = 0; score++; if(score == brickRowCount*brickColumnCount) { alert("YOU WIN, CONGRATS!"); document.location.reload(); } } } } } }
Thanks to this we'll be able to actually win the game when we destroy all the bricks, which is quite important when it comes to games. The document.location.reload()
will reload the page and start the game again after we click the confirmation alert.
Exercise: add more points per brick hit, print out the number of collected points in the alert.
Now, you can get back to this tutorial's index page or continue to the ninth chapter: Mouse controls.