Tag Archives: tutorial

HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

When I started developing the HTML5 version of Command and Conquer, I never expected more than a few close friends to look at the game. (Based on the experience with my last game, Breakout).

Command and Conquer Javascript ScreenshotSo while I spent a lot of time making the game look as close to the original Command and Conquer as possible, I never spent much time optimizing the code. Most of my development and testing was on my own Macbook, and I didn’t pay attention to the image loading time or network traffic.

Unfortunately, this game uses a lot of images.

Each unit can face 32 different directions. This means at least 32 different images for each unit (more if there are animations like ‘harvesting’).

Buildings need a whole set of images for each state – under construction, regular – with different sets of images for healthy and damaged buildings, and for any additional states (like ‘unloading a harvester’). The Construction Yard for example needs 82 different images for it’s animations.

As a result, when the game loaded, it made nearly 1,000 HTTP requests to load all the assets (including images and sounds).

Since most browsers only make a few simultaneous requests at time, downloading all these images took a lot of time, with an overload of HTTP requests.

While this wasn’t a problem when I was testing the code locally, it was a bit of a pain when the code went onto the server. My patient friends ended up waiting for the game to load for 5-10 minutes (sometimes longer) before they could actually start playing.

AdityaRaviShankar.com - Traffic Screen ShotThe problem came when my game hit the front page of Hacker News and Wired.com on the same night, resulting in a slight spike in traffic :). It then got worse when the game got 1,000+ tweets and 1,000+ FB likes in just a few hours. The last time I checked, searching for my game gave over 5,000 google results.

What this meant was my shared hosting server was getting close to 14,000,000 HTTP requests in one day from just my domain.

I don’t think too many shared hosts are designed to take this kind of load, which resulted in my account being disabled with this interesting email from my provider.


Your account adityaravishankar.com on the server quebec.unisonplatform.com was recently found to be causing high load that resulted in slowness/outages of various system services. In order to ensure quality of service to the other clients on this server we regret to inform you that the account had to be disabled to prevent any further interruption of service to our other clients.

If nothing can be done to lower the resource usage you may need to look into purchasing a dedicated server or cloud server which you can find more information about at http://www.eleven2.com. Please contact us as soon as possible to resolve this issue.

I was able to find temporary hosting on another server but the biggest priority was to optimize the way I stored images, which of course brings us to sprite sheets.

Hand of Nod Sprite SheetSprite sheets store all the sprites for an object in a single large image file.

When displaying the images, we calculate the offset of the sprite we want to show and use the ability of the drawImage() method to draw only a part of an image.

Creating these sprite sheets is incredibly simple using ImageMagick’s montage command line tool. This single command will convert a folder full of images into a single row sprite sheet.

After comparing PNG and GIF, I found that PNGs tend to compress the sprite sheets a lot more.

The advantages of using Sprite Sheets?

  1. Fewer HTTP requests – The Command Center went from 81 requests to a SINGLE HTTP request
  2. Better Compression – An advantage of storing the images in a single file is that the header information doesn’t repeat and the combined file’s size is much smaller than the sum of the individual files. The command center went from 496KB in 81 files to only 37KB in a single file. (Less than 8% of the original size, which is incredible)
  3. Easier Manipulation – With all the sprites in a single image file, it became easier to do RGB color manipulations, and I was able to optimize the drawing code for performance.

From almost a 1,000 requests to 120 requests in one simple code rewrite. And the total download size went from a few MBs to around 200KB.

Game load time went from 10+ minutes to under a minute. The bandwidth usage dropped to a tenth of the original. The number of requests dropped to a tenth of the original. And now my shared hosting can survive a very decent amount of traffic.

Moral of the story? When developing a large game that is image heavy, track your network usage and when possible use sprite sheets πŸ™‚

HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

Breakout v0.6 ScreenshotThis is the third in a series of tutorials on developing a full featured version of Breakout.

In the second tutorial, we used setInterval() to add some animation and capture keydown and keyup events to respond to user input.

In this tutorial, we will bring back the bricks we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed. We will also add some sound effects to make the game more fun.

We will use the code from the last tutorial as our starting point.

Lets get started.

First we add back two lines at the beginning of the animate() function to draw the scoreboard and the bricks.

Right now the ball will move over the bricks without bouncing off them.

We need the ball to reverse X direction if it hits the sides of the bricks, reverse Y direction if it hits the top or bottom of the bricks and damage the bricks every time it touches them.

Lets create functions to check whether the ball is colliding with a brick along the X or Y direction, and to damage the brick if it collides.

The collisionXWithBricks() and collisionYWithBricks() functions return true when they bounce against a brick and automatically call explodeBrick() to weaken the brick and update the score. To start using these functions, we modify the collision checking conditions in moveBall() slightly.

At this point, the ball bounces off the bricks as expected and weakens the brick when it hits them. Once the brick is completely destroyed, it disappears and gives the player an extra points.

Not bad. The game works fine, however there is still something missing.

A little sound tends to give players a much more immersive experience and will make the game more fun. With HTML5 Audio, implementing sound is surprisingly easy.

To play sounds, we load files using the Audio() object and play them using its play() method. Browsers are still a little inconsistent about which formats they support. The OGG file format is an open format supported by both Chrome and Firefox (my favorites), which is why we will stick with them for now.

To create the sound we place the two files at the same location as the HTML file and load them by creating new Audio() objects and storing them in variables. The OGG sound files used here are included with the source code.

To play these sounds, all we need to do is invoke the play() method.

We can play the breaking sound whenever a brick is completely destroyed (inside the explodeBrick() function).

And the bounce sound anytime we change X or Y direction for the ball (inside the moveBall() function)

That’s really all there is to it. We have a game with sound effects, animation, keyboard control and increasing scores written entirely in HTML and Javascript.

To make the game more fun, we can add more interesting brick types, sounds and game mechanics.

In my version of the game, the bricks start falling down, we have Cash bricks to give money, Bomb bricks that explode everything nearby, Laser Ammo bricks that let us shoot laser from the paddle and Spider bricks that shriek and start crawling down at the user. Check out the game to see what you think. Leave a comment if you enjoy the game.

I don’t see much point showing people how to implement the exact same features in a game, because at this point it is fairly simple to do. However if you have an interesting idea that you would like to add to the game, leave me a comment below. If we get a few interesting ideas, we can have one more tutorial where we implement the ideas and create our own new version of the game.

If not, stay tuned to learn how to implement a Real Time Strategy game engine entirely in HTML5 and Javascript. Check out Command and Conquer – Programming an RTS game in HTML5 and Javascript.

You can download the finished source code for this tutorial below.

HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input

Breakout v0.6 ScreenshotThis is the second in a series of tutorials on developing a full featured version of Breakout.

In the first tutorial we covered drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

In this tutorial, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input (so we can move the paddle).

We will use the code from the last tutorial as our starting point.

Lets get started.

To animate objects in the game, we need to draw them, move them a little, and then redraw them. To do this, we create an animate() function and place our calls to the drawing functions inside it. For now, lets focus on only the paddle and the ball.

Now we need to figure out a way to call animate() repeatedly at regular intervals. Luckily, Javascript has a function called setInterval() which keeps calling a given function repeatedly at fixed time intervals until the clearInterval() function is called.

We create two functions called startGame() and endGame() to begin the animation and end it. We can also use startGame() to do any pre-game initialization of variables.

Now that the game loop is setup, we need to start moving the elements during the loop.
We start by creating a moveBall() function and calling it from within animate().

The moveBall() function adjusts the ball coordinates by adding the ball speed. We initalize balldeltaX and ballDeltaY when the game starts.

Now that everything is in place, the ball should start moving.
However when we open the file in a browser, we see something weird.

Instead of a moving ball, we have a long black line. The ball keeps moving, however the old balls stay behind, leaving a long trail along the path. We need to clear the earlier objects before drawing new ones.

To do this, we can use the clearRect() method.

This line clears the entire canvas at the beginning of the animation loop. When we run the code now, it looks like a moving ball instead of a long snake.

The next problem is that our ball doesn’t bounce off the walls. It keeps moving past the edge of the canvas and disappears. To fix that, lets add some conditions to check when the ball is moving outside the boundary.

Great! Now the ball is bouncing off the walls properly and when it touches the ground the game ends.

Now lets animate the paddle. To move the paddle, we need to first track the left and right keys and keep track of where the paddle should move during the next animate(). We do this by using the keydown() and keyup() jQuery methods to assign event handlers for these events.

The event handlers check if the key pressed or key released is Left (key code 39) or Right (key code 37) and stores this in a paddleMove variable. We will check this variable every time we animate to see where the paddle needs to move next.

The next thing we need to do is define another movePaddle() function that is called just like moveBall().

We now call this new movePaddle() function from animate() as well.

Great! Now the paddle moves to the left and right when we use the cursor keys.

The last thing we need to do is make the ball bounce if it hits the paddle. We just need to add a condition to the other collision checks in moveBall().

And thats it! The paddle moves perfectly, the ball bounces off the wall and the paddle, and if the ball hits the ground, the game ends.

We have come a long way from an empty rectangle on the browser. Of course, this game is still a little boring with just a ball and paddle.

In the next tutorial, we will bring back the bricks that we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed.

You can download the finished source code for this tutorial below.

Continue to part 3 of this series. HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

HTML5 Game Development Tutorial: Breakout Part I – Introduction to Canvas

Breakout v0.6 ScreenshotThis is the first in a series of tutorials on developing a full featured version of Breakout. This tutorial will cover drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

Before we get started, check out the finished Breakout game demo. With flying bats, falling spiders, laser turrets and exploding bricks, its probably a little different from the typical breakout game. We will be recreating this game over the series.

All of our development will be for HTML5 capable browsers that properly support the HTML5 Canvas and Audio tags (Chrome, Safari, Firefox, Opera and maybe Internet Explorer 9). Make sure you have one of these browsers.

Now let’s get started.

First we create a simple HTML file with a canvas inside it.

We also include jQuery to make cross browser development easier.

To start using the Canvas we need to get its 2d context which then gives us access to all the drawing methods we need.

With this context object, we now have access to the methods that we will need for our game like fillRect(), clearRect() and drawImage().

Now that we can draw, lets start with creating the paddle.

Note that we store all the parameters in variables so that we can easily modify and reuse them later. Drawing the paddle is as simple as using the fillRect() method.

Now lets draw the ball.

Drawing the ball requires the arc() method to draw a circular shape and the fill() method to fill the shape we just created. While drawing the arc, the starting angle is 0 and the ending angle is 2xPI radians (or 360 degrees) which makes a full circle.

Now lets draw the bricks on top.

First we store the bricks layout in an Array making it easier to visualize and modify. Feel free to try adding a few more rows, or changing the numbers to modify the layout.

We then iterate over each row and column and call the drawBrick() method to place the brick correctly. Within drawBrick(), we use a switch statement to set different fill colors for different types of bricks. This function can be extended to add more brick types.

Finally, lets create a simple scoreboard or status bar below.

This uses the fillText() method to write text at the bottom of the canvas.

We can check the output of the code so far by calling each of the functions that we wrote.

Breakout - Tutorial 1 - ScreenshotThis is the final result. We have a complete game screen with all the elements drawn on it programmatically – the bricks, the paddle, the ball and the scoreboard.

It doesn’t seem like much yet. Everything is static. However, because we stored the parameters in variables, all we need to do to move objects around is change the parameter values and call the same functions again. Thats when things start getting interesting.

In part II of this series, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input.

You can download the finished source code for this tutorial below.

Continue to part 2 of this series. HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input

NowJS and Node.js Tutorial – Creating a multi room chat client

NOTE: This is a really old tutorial. The library used in this example (NowJS) has pretty much been abandoned by the developers for several years. You might still be able to find the NowJS library code at the NowJS Github Page.

However if you are trying to create a HTML5 Websocket/Node.js chat client, I’d recommend using Websocket-Node or Socket.IO instead of NowJS.


Node.js is a server side environment for Javascript. NowJS is a framework built on top of Node.js that connects the client side and server side Javascript effortlessly.

The core of NowJS functionality lies in the now object.The now object is special because it exists on the server and the client.

This means variables you set in the now object are automatically synced between client and server. Also server functions can be directly called on the client and client functions can be called directly from the server.

All in realtime.

You can have a working HTTP server up and running in Node.JS with just a few lines of code. For example –

This little snippet of code will create an HTTP server, listen on port 8080, and send back “Hello World” for every request. That’s it. Nothing more needed.

Using NowJS, communication between the client and server side is just as simple.

Client Side:

In this code snippet, the client side sets a variable to ‘someValue’ and calls serverSideFunction(), which is declared only on the server.

Server Side:

The server side is then able to access clientSideVariable, which is declared only on the client.

All the details such as establishing connections and communicating change of data between the server and client are handed automagically by the framework.

In fact writing code using this framework is so simple, the NowJS hello world example is a working chat client and server written in under a dozen lines of code. Go check it out.

As a simple exercise to get comfortable with the NowJS API, we can modify the chat client example to support multiple chat rooms. Let’s take a look at how easy it is.

Server Side (multiroom_server.js)

1. The first thing we need to do is modify the distributeMessage() function to only send messages to users in the same chat room as the user.

We store the name of the server room on the client side (this.now.serverRoom). When the client calls the distributeMessage() function we send the message to everyone in the same chat room by using getGroup() and using the group.now object instead of the everyone.now object. (everyone is just a group that contains all users connected to the server)

2. Next we need to handle the client changing chat rooms.

The getGroup() method fetches the group object if it exists andΒ creates a group if it doesn’t already exist. We use the groups addUser() and removeUser() methods to move the client from the old room to the new room.

Thats about it on the server side.

Client Side (multiroom.html)

3. First we add a drop down with the list of server rooms.

4. Next we call the server side changeRoom() function when the user first connects and whenever the drop down is changed.

5. For extra credit, we can allow the server to dynamically provide the list of rooms when the client connects.

The changes required would be –

Server Side:

Client Side:

That’s really all you need to do. We now have a multi room chat client/server with
i) A drop down on the client side with list of server rooms
ii) On connection with server, client auto populates server room list and enters the first room
iii) Changing drop down changes room
iv) Entering new room clears the screen for the user

This is obviously a fairly barebones version (like the original example), but it serves as a proof of concept of all the essential elements of NowJS communication.

The finished code has some extra comments and a few more features. You can download the complete source code below.