Tetris in HTML5 for Noobs: Part 9 – Finishing Touches

The last thing I’m going to do for this tutorial series is show how to implement the scoring and level mechanism. The idea of the game is that as you clear lines, you get points to increase your score. After you get enough points, you move on to the next level, where the blocks fall faster. To add this we’ll use three more global variables, defined at the start of the script.

In the initialization function, we’ll set the starting values for these variables.

Note that I’ve used the timestep variable when initializing the timer. It’s usually a good idea to use variables whenever possible for things like this, so that you can change the value for all instances at once. If I had made the dimensions of the game state grid variables instead of hard coding them, it would be easy to modify the game to use a giant grid, for example.

The only time the score can change is when a line is cleared, so that’s where we’ll add this next code segment.

Each time a line is cleared, we increment the score variable. Every 10 lines, the level will also increase. When this happens, we compute a new timestep variable and reset the game timer. The values here can be adjusted to set the difficulty of the game by changing the rate at which each new level increases the game speed. The last line updates the score and level display in our HTML document. We need to add an id attribute to the div element containing the score so that it can be referenced in our code.

The getElementById function searches the document object (in this case our entire file) for an element with an id value of "score". It then sets the HTML content of that element to the string that we provide. JavaScript uses the “+” symbol to concatenate two strings of text, and because it is a weakly typed language, we can include our variables here directly. This effectively updates the score display with the current values of the variables. The final version of the code should look like this:

You can see what the final game looks like here. I hope you’ve enjoyed following along with me as I made this game and hopefully you’ve learned something about HTML, JavaScript, or game programming. Be aware that the methods I presented are by no means the only way of doing things. My goal was to give some insight into how I go about solving problems and to do it without assuming any background knowledge. Again, let me recommend w3schools as a great reference resource and a place to learn more about web development. If you’re interested, you can always continue to improve this game by adding more features, such as a window to show which block is coming next, or a way to keep track of high scores. Regardless, I hope you had fun and will continue to make fun and interesting games.

Updated: February 20, 2015 — 2:23 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

DrewBuck.com © 2015 Frontier Theme