I’ve finally done it – I’ve created my first HTML5 game! =D

I’m doing a Web Development course this semester, and our first assignment is to build a space invaders HTML5 game. I had never built a game in HTML5 before, so I thought I’d dig up some tutorials to get my feet wet… and here’s what’s come out of it!

catch-the-monster

Catch The Monster!

A simple HTML5 game.

I came across this tutorial on Google, and decided to follow it to build my first game. The tutorial itself is pretty straightforward, but the original source code has some bugs. So, once I built the game according to the tutorial, I went ahead and made some tweaks to remove the bugs from the original code. Now, the game is playable and fun!

You can see my code and demo here.

Here are a list of changes I made to the source code:

1) I’ve added constraints to the game logic so that player no longer goes off screen. In the original game, if you kept pressing the right/left/up/down key indefinitely, your player would disappear off screen, with no end in sight. This really disrupts the game experience, and really confuses the player. So, I’ve added constraints to the code so that the key presses don’t increment or decrement the position of the player beyond a certain point. So that no matter how long you press one of the arrow keys, the player will come to a halt at the edge of the game canvas, instead of disappearing off screen as it did before.

2) I added a simpler function to calculate the random position of the player, by giving a “max” and “min” range. Originally, the source code was using a bunch of arbitrary numbers combined with the Math.random() function in JS to create x and y co-ordinates of the monster on screen. The problem was, this code sometimes created co-ordinates that pushed the monster off screen.

// random number generator from MDN:
/**
 * Returns a random number between min and max
 */
function getRandomArbitary (min, max) {
    return Math.random() * (max - min) + min;
}

By using this simple function in conjunction with the min and max width/height of the visible game field, not only does it make the code more uniform, but…

3) This also results in the monster no longer appearing half or completely off screen. But the monsters still might be hiding behind the “Monsters Caught” counter, so watch out! I considered removing that possibility as well, but decided to leave it in to add an extra layer of difficulty to the game.

Advertisements