Learn how a little extra code can enhance HTML5 games

With a little code, you can add new game elements to make even a simple game like Pong more engagingscreenshot

You can download the complete source code for this project here (http://sdrv.ms/10B0H6l).

Also, check out my GitHub, it’s stuffed full of free to use templates and projects to help you get started developing for Windows 8(http://bit.ly/ScruffyGit)

In this post from Susan Ibach (http://bit.ly/12XrgUC), you learned how to change the art and “re-skin” the HTML5 pong template but I want to show you how you can take even a simple template like Pong and make the game more engaging. Right now our pong game is a little boring and the challenge never really changes. One way we can spice the game up and add some actual challenge is with pick-ups. In this post we are going to add two pick-ups to the game, one to speed the ball up and one to slow it down.

Here is what we will cover:

  • Changing the speed of the ball
  • Setting up the new art assets
  • Displaying the pick-ups in the game
  • Tying it all together to make our pick-ups work

If your looking for more of an introduction to the HTML5 Pong template check out this post here (http://bit.ly/12XrgUC).

Changing the speed of the ball

Let’s start out with modifying the speed of our ball. This is fairly simple, but will be very useful when we start adding our pick-ups. Download the HTML5 Pong template here (http://bit.ly/html5pong), fire up Visual Studio, open the project and we will get started.

Once you have the project loaded we are going to go into our default.js file and make some slight adjustment to change the balls speed.

Screen 1

We are looking for the variable declarations for our ball speed var xSpeed and var ySpeed (see image below). These are the values that control the speed of the ball. If you increase the values the ball speeds up, if you decrease them the ball slows down. Go ahead and modify the values now and run the game, you should see the ball moving at a different speed. Now that you now what variables control the speed, our next step is going to be to adjust this in our game. We do that in our next section when we add some pick-ups, so lets go ahead and jump into that.

     // Variables //
    var title; //The games title
    var playerScore; //The main player score
    var cpuScore; //The CPU score
    var cpuSpeed = 4.1; //The speed of the CPU paddle; the faster it is the harder the game is
    var xSpeed = 6; //Used for the ball 
    var ySpeed = 6; //Used for the ball and the player paddle
    var winScore = '10'; //When the player or cpu hit this score the game is over


Setting up the new art assets

We are going to need some art to act as the images for our pick-ups. This will be what the player sees to let them know what pick-up it is. The next few steps will help guide you in getting this new art setup and ready.

Here is a link to the art assets I used for the pick-ups (http://sdrv.ms/17pL0lE) feel free to change this with your own art.

Once you have either downloaded or selected your art go ahead and import it into our project. You can do this by right clicking on the “Assets” folder and selecting “Add” then “Existing Item”.

 Screen 2

Browse to where your art is located and select the two images for your power ups and click “Add”

Ok so now that we have imported our art we need to add a few variables to hold the images so can use them in our game. Below is the code to do this, again the highlighted lines are new.

     // Graphics //
    var backgroundImage, backgroundBitmap; //The background graphic
    var playerImage, playerBitmap,player2Image, player2Bitmap; //The player paddles graphics
    var ballImage, ballBitmap; //The ball graphic
    var cpuImage, cpuBitmap,cpu2Image, cpu2Bitmap; //The CPU paddles
    var winImage, winBitmap; //The winning popup
    var loseImage, loseBitmap; //The losing popup
    var pausedImage, pausedBitmap; //The Image we show when paused
    var speedUpImage, speedDownImage, speedUpBitmap, speedDownBitmap; //pick-up images

Then we need to add our new images to the preload manifest so that they will load with the rest of our content. Scroll down in the code till you find initialize function and add the highlighted code to the manifest.

                            { src: "Assets/pause.png", id: "paused" },
                            { src: "Assets/bg.png", id: "bg" },
                            { src: "Assets/paddle.png", id: "cpu" },
                            { src: "Assets/paddle.png", id: "player" },
                            { src: "Assets/paddle2.png", id: "cpu2" },
                            { src: "Assets/paddle2.png", id: "player2" },
                            { src: "Assets/ball.png", id: "ball" },
                            { src: "Assets/win.png", id: "win" },
                            { src: "Assets/lose.png", id: "lose" },
                            { src: "Assets/speedUp.png", id: "speedUp" },
                            { src: "Assets/slowDown.png", id: "speedDown" },
                            { src: "Assets/playerScore.mp3", id: "playerScore" },
                            { src: "Assets/enemyScore.mp3", id: "enemyScore" },
                            { src: "Assets/hit.mp3", id: "hit" },

Remember to change the name of the files to match up with your art assets.

The last step we need to take in setting up the art assets is to create the bitmap images. This is the step where we will scale and prepare the images to be used on the stage. Add the following code to the prepareGame() function right between the “lose” and “pause” image code.

         speedDownImage = preload.getResult("speedDown"); 
        speedDownBitmap = new createjs.Bitmap(speedDownImage);
        speedDownBitmap.scaleX = SCALE_X; 
        speedDownBitmap.scaleY = SCALE_Y;

        speedUpImage = preload.getResult("speedUp");
        speedUpBitmap = new createjs.Bitmap(speedUpImage);
        speedUpBitmap.scaleX = SCALE_X;
        speedUpBitmap.scaleY = SCALE_Y;

That takes care of the art setup, now its time to write the code that will make the pick-ups appear in the game.

Displaying the pick-ups on the stage

So we have now have our art setup and ready, now its time to look at how we are going to display the pick-ups in the game. In my game I decided that I wanted one of the two pick-ups to display based on how many times the ball hit a paddle. I'm going to show you the technique I used to make this happen.

The first thing we will need to do is create a couple of variables, one will keep track of how many times the ball hits a paddle and the second will keep track if a pick-up is available. Add the following lines to the top of our default.js file, right after the “winScore” variable.

     var hits = 0;
    var powerUpAvail = true;

Now that we have are variables lets look at the code that will randomly pick and display our pick-ups. Add the following code to the top of the PlayGame() function. We will walk through it, so don’t worry if it doesn’t immediately make sense.

          if (hits > 1 && hits % 3 == 0 && powerUpAvail) {

            var randomPower = Math.floor(Math.random() * 3);

            switch (randomPower) {
                case 1:
                    var randomX = Math.floor(Math.random() * canvas.width);
                    var randomY = Math.floor(Math.random() * canvas.height);
                    speedUpBitmap.x = randomX;
                    speedUpBitmap.y = randomY;
                    powerUpAvail = false;
                    hits = 0;
                case 2:
                    var randomX = Math.floor(Math.random() * canvas.width);
                    var randomY = Math.floor(Math.random() * canvas.height);
                    speedDownBitmap.x = randomX;
                    speedDownBitmap.y = randomY;
                    powerUpAvail = false;
                    hits = 0;


        if (hits > 1 && hits % 10 == 0 && !powerUpAvail) {
            powerUpAvail = true;


The starting line of code here is our first condition and it runs checks on our hit counter and if we have a pick-up available. It actually reads as follows: if hits is greater than one and if the hits is a factor of three with no remainder, and if a pick-up is available, then run the code inside the statement.

Inside the statement, the first line will create a variable and assign it a random number between one and two. After that we have our switch case. This case is based on our random number we created in the first line. If the number is one we will display the speed up pick-up and if the number is two we will display our slow down pick-up. The code inside of the case is the same for both the speed up and slow down pick-up so we will just go through the lines once. The first thing we do inside our case is create two random variables, one for our x position value and one for our y position value. The following lines set these variables to a random number between 0 and the height or width of the canvas respectively.

            var randomX = Math.floor(Math.random() * canvas.width);

                    var randomY = Math.floor(Math.random() * canvas.height);

We then set the pick-ups bitmaps position to these random values with the next two lines of code. After that we add the pick-ups bitmap to the game stage, set the powerUpAvail value to false, and finally we reset our hit counter to zero.

The last chunk in the code section is our second condition. This condition is a lot like our first with two differences. The first is in this condition we check to see if our hit counter is a factor of ten with no remainder and the second is we check to see if the pick-up is NOT available. If this condition is met then we run the code inside the statement. These lines of code are pretty straightforward. The first two remove any pick-ups from the game stage and the final line sets our powerUpAvail variable back to true.

I know that was a lot to go through and I promise that is as hard as the coding will get with this project. With this code in place we will be able to randomly choose and randomly place a pick-up in our game. We have one last step before we can see the pick-ups displaying in our game, we need to add a few lines of code to increment our hit counter and ultimately trigger our conditions to display and remove the pick-ups. So lets go ahead and do that by adding the following highlighted lines of code to our PlayGame() function.

         // Cpu collision //
        if (ballBitmap.x >= cpuBitmap.x - ((ballImage.width * SCALE_X) * 0.5) &&
        (ballBitmap.y <= cpuBitmap.y + ((cpuImage.height * SCALE_Y) * 0.5) &&
        ballBitmap.y >= cpuBitmap.y - ((cpuImage.height * SCALE_Y) * 0.5))) {
            xSpeed *= -1;

        // Player collision //
        if (ballBitmap.x <= playerBitmap.x + ((ballImage.width * SCALE_X) * 0.5) &&
            (ballBitmap.y <= playerBitmap.y + ((playerImage.height * SCALE_Y) * 0.5) &&
            ballBitmap.y >= playerBitmap.y - ((playerImage.height * SCALE_Y) * 0.5))) {
            xSpeed *= -1;

Ok, with those two lines of code added we can fire up our game and will see our pick-ups appearing and disappearing. You will quickly notice that they still don’t do anything when you pass through them with the ball, that’s our next step, tying it all together and making our pick-ups work.

Tying it all together to make our pick-ups work

We are almost there only a few more steps to tie everything together and get our pick-ups working in the game. Right now our pick-ups are appearing and disappearing but when we pass through them the don’t actually do anything. In order to make them do something we need to check if the ball has in fact hit the pick-up bitmap and if it does then we can add the pick-ups affect to the game. Lets go ahead and add that check to our PlayGame() function, the code below will do just that. Add this right after the player collision code.

         //Pick-up collision
        if (Math.sqrt((ballBitmap.x - speedUpBitmap.x) * (ballBitmap.x - speedUpBitmap.x)
                + (ballBitmap.y - speedUpBitmap.y) * (ballBitmap.y - speedUpBitmap.y))
            < ((speedUpImage.width / 2) + (ballImage.width / 2)) * SCALE_X) {
            speedUpBitmap.x = -200;
            speedUpBitmap.y = -900;
            xSpeed *= 2;
            ySpeed *= 2;
            powerUpAvail = true;
            hits = 0;

        if (Math.sqrt((ballBitmap.x - speedDownBitmap.x) * (ballBitmap.x - speedDownBitmap.x)
                + (ballBitmap.y - speedDownBitmap.y) * (ballBitmap.y - speedDownBitmap.y))
            < ((speedDownImage.width / 2) + (ballImage.width / 2)) * SCALE_X) {
            speedDownBitmap.x = -200;
            speedDownBitmap.y = -900;
            xSpeed /= 2;
            ySpeed /= 2;
            powerUpAvail = true;
            hits = 0;

There is a little bit of code here so lets take a step through it and see what is going on. The first thing we are doing in the code is checking to see if our ball has collided with our pick-up, if it is we will run the code in the statement. This is a simple algorithm that uses some basic trigonometry to find the distance between the ball’s center and the pick-up’s center. Again this code is the same for both pick-ups so I wont run through it twice. Once inside the statement the next line of code will remove the pick-up bitmap from the game stage. Then we set the position of the bitmap well off the game canvas. We do this so that we can reset it and us it once the it has been chosen again. After that is the code that will actually effect the balls speed. If it is the speed up pick-up we will double the current speed of the ball, if it is the slow down pick up we will cut the current speed in half. We then reset the powerUpAvail variable to true and set the hit counter variable back to zero.

One last step to tie this whole pick-up system together. We are going to add a few lines of code to our reset function. This is so that all of the pick-up effects are undone when some scores a point or the game restarts. Ok lets add the following lines to the Reset() function.

         hits = 0; //clear our hits
        //Reset our speeds
        xSpeed = 6;
        ySpeed = 6;

That’s it! If you run your game now you will be able to use the pick-ups and they will affect the game in the manner they should. As you can see this has added a whole new level of game play to our basic pong, but don’t stop here there are way more things you can do to spice the game.

As a next step try experimenting on your own and maybe add some things like:

  • Sounds when you hit a pick-up
  • A pick-up that changes the paddle height
  • Multiple ball pick-up

The options are endless!