Javascript Game Tutorial

Javascript, as a game development language, is becoming more and more popular. With the addition of the new(ish) HTML5 APIs, Javascript has become more powerful, and has the featureset necessary to create full-fledged games. One reason for Javascript’s new found game development popularity is its portability. A single Javascript based game can be played on any device with a browser, or packaged into an app on iOS, Android or Windows 8 devices.

Even Microsoft sees the viability of HTML5 and Javascript game development and has offered a popular series of ‘Web Camps’ featuring HTML5 gaming.

Our Javascript Game
In this tutorial we’re going to develop a simple Javascript-based game. The game art was developed by LearnToProgram’s graphic designer, Alexandria. We also will make use of the CreateJS library, which is designed to foster interactivity in HTML5 / Javascript based documents. Our game is a simple shooting game in which the player aims the target at the enemy bats. Successfully shooting the bat earns the player points. If the player misses, points are deducted.

Figure 1: In the game, the player has 60 seconds to shoot as many bats as possible.

This game makes use of many of the common elements in game coding. User interaction with the mouse, animation, sound, and hit detection are all part of the code base for the game. The game also provides a great starting point for your own expansion and experimentation.

Downloading the Game and Assets
For your convenience, the game is available on GitHub for you to download. Point your browser at and click the download button on the bottom right-hand corner of the screen to download a .zip of all game files.

Once you unzip the files you can see all of the components that make up the game.

Figure 2: The Javascript game on GitHub. Note the Download ZIP button in the bottom right corner of the interface.

Included in the game are the following types of files:

HTML: The frame that holds the game and allows it to be loaded into the browser.
CSS: The stylesheet is used, in this case, to reset all of the styles and negate styles in the default stylesheet within the browser.

HTML Code for the Game
The purpose of the HTML file is to provide a load page for the browser. The HTML has a single display element: the canvas on which the game is played. The HTML code is listed here:

As you can see, the HTML does little but provide scaffolding for the project. We link to several code sources within the HTML document. First, we link to normalize.css, which is a reset stylesheet. A reset stylesheet is designed to ameliorate minor differences between the browsers’ rendering styles by setting the baseline for most style rules to zero. Next, I include the CreateJS library. I make extensive use of the CreateJS library in the game project, and include it via its available CDN link. Including the link to the library (instead of downloading the library and including it via local files) makes the application more lightweight, but at the same time, does require an internet connection for the game to function.

The final link in the HTML file is to the init.js file which contains my Javascript code for the game. In the body of the HTML I have a canvas element, which is the surface that will be used to play the game.

Figure 3: The game makes extensive use of the CreateJS library which makes working with elements such as spritesheets, sprites and sounds easier.

Now let’s take a closer look at the Javascript code that is the heart of the game. We’ll break it down section by section.

The initial part of the init.js code file has a number of global variable declarations. For the sake of completeness I’ll include them here, but I won’t discuss them at length until we encounter them in the code listing.

A few of the global variables are initialized here as well. For the width and height of this particular game, I set constants. In a more complete game, I would make the height and width variable to adapt to different kinds of screens, but, for the purpose of coming up with a workable example, I didn’t include that feature.

The next anonymous function will execute when the window.onload event has fired, after all components have been loaded in to the window. First we set up the canvas:

The CreateJS library has an object known as a stage. This may sound familiar to Actionscript programmers, as the concept is borrowed directly from the Flash world. Once we get the canvas context and width and height set to the constants expressed earlier, we instantiate the stage object. The stage object will manage the hierarchy of assets that appear on stage, as well as provide a consistent timer for our animations.

Next within the function triggered by the window.onload event, we’ll set up our asset queue and our sound component.

The asset queue allows us to preload objects all at once, which makes life easier with unpredictable server speeds. Using the queue’s on() method, we’ve delegated the queueLoaded() function to run once the entire queue is loaded. We’ve also told the sound object that we have .ogg sound assets as an alternative to .mp3 files.

Now we’ll set up the manifest, which is the list of assets we’re loading in to the queue itself.

You’ll note that the manifest is used to load several types of different assets. Here we have .mp3 files, and .png graphics which act as both spritesheets and individual graphics that will be used in the program. The queue.load() method loads the manifest into the browser DOM.

The final part of the window.onload delegate function starts a timer that will be used to run the timer for the game itself.

Next we’ll look at the queueLoaded() function which runs when all the items in the manifest are loaded in to the DOM. The first part of this function configures some important components for the game.

The first lines of code load the backgroundImage graphic to the stage. Note that the image first must be retrieved from the queue via queue.getResult(), and instantiated as a createjs.Bitmap object. That object can be displayed on the stage via the addChild() method.

Since the stage is designed for images and animation, the next sections of code create bitmap text objects that display the timer and the score at specified locations. Finally, a background sound–earlier loaded with the manifest–is played and looped indefinitely.

The next step is key. We’re going to set up the SpriteSheet for the two animations that are used in the game. The SpriteSheets are designed to place all of the images that make up an animation in one place.

The code to configure the SpriteSheets follows:

Each SpriteSheet instance is created with information about the image from the queue, the size of the individual frames on the SpriteSheet and then the animation itself. As you can see, the first animation has 5 frames that are 198px x 117px.

The SpriteSheet objects are used to create the object sprites that appear on the stage. I wrote a separate function called createEnemy() that handles this process:

The remaining code in the queueLoaded() function creates the crosshair graphic which the user will use to aim the gun. The ticker code is used to set the speed of the animation occurring on the stage and to also fire a tickEvent() function that will be used to update various parts of the game interface.

Also here we set the callback functions that deal with the user moving the mouse or clicking on the mouse button to fire the gun.

The tickEvent() callback function is used to adjust the speed and position of the enemy bat animation. The code first checks to make sure that the position of the enemy sprite is within the bounds of the game HEIGHT and WIDTH constants. If outside, it reverses the direction of the speed (separately along the X and Y axes) by multiplying its speed by -1. In essence, this reverses the direction of movement of the object. After the speed is altered or reversed as necessary, new X and Y coordinates are set for the sprite instance named animation.

The next function simply moves the crosshair as the mouse moves. I’ve offset the position of the crosshair by 45 pixels so that the mouse pointer appears in the middle of the crosshair instead of on the corner.

The next function is really the heart of the game. In the function I use a crude collision detection technique to see if the shot was within 40 pixels of the X and Y position of the enemy sprite. Note that the position of the sprite is returned as a floating point number so Javascript’s Math.round() function was used.

If, based on this technique, the user’s shot was determined to be a hit, several things will happen. First, the enemy sprite will be removed from the stage and the batDeath() function called. This function runs the batDeath animation you saw earlier. The player score is incremented, a sound effect is played and the enemy sprites’ speed is increased to make the game more difficult. The bitmap text for the score is updated at this point as well.

After a random time increment of up to 3.5 seconds, a new instance of the enemy bat sprite is created and the game continues.

If the shot is determined to be a miss, 10 is subtracted from the player score and the new score bitmap is displayed.

You’ll remember that during the game initialization process we started a Javascript timer that calls this updateTime() function each second.

This function increments the gameTime variable by 1. If the gameTime is greater than 60, the game is over, components are removed from the stage and a “Game Over” sound effect is played.

This game is designed to be a starting point. See what modifications you can make to improve playability, performance, or simply make the game more interesting. I’d love to see what you do! Get in touch with me via email: [email protected].
By: Mark Lassoff

1 Comment

  1. I was watching these videos on your Roku channel, and video three didn’t have audio.

    This is a great little game. My son and I will have a lot of fun playing with this.

Leave a Reply

Your email address will not be published.