Create a Whack-a-Mole Game in HTML5 With EaselJS
A few weeks ago, I showed you how to create a Whack-a-Mole (well, Whack-a-Worm) game using Flash and AS3. Now, following on from my introduction to EaselJS, we'll see how to use that library to create the same game with the HTML5 canvas and JavaScript.
Step 1: Brief Overview
Using pre made graphics we will code an entertaining Whack A Mole like game in HTML5 using the EaselJS library.
The player will be able to click the worms on the screen and get points.
Step 2: Interface
A simple and friendly interface will be used, this involves multiple shapes, buttons, bitmaps and more. The worm graphic used in this tutorial was downloaded from here under a Creative Commons License.
The interface graphic resources necessary for this tutorial can be found in the attached download.
Step 3: Get EaselJS
The EaselJS library will be used to build our game - make sure you read the Getting Started tutorial if you're new to this library.
You can download EaselJS from its official website.
Step 4: HTML Structure
Let's prepare our HTML document, it is a simple HTML structure to begin writing our app.
1 |
|
2 |
<!DOCTYPE html>
|
3 |
<html>
|
4 |
<head>
|
5 |
<title>Whack A Worm</title> |
6 |
</head>
|
7 |
<body>
|
8 |
</body>
|
9 |
</html>
|
Step 5: Hide Mobile Hightlight
Let's add a little bit of CSS too, this line will remove the default highlight when you tap on an element using a mobile browser; without this the mobile experience would decrease drastically.
1 |
|
2 |
<!DOCTYPE html>
|
3 |
<html>
|
4 |
<head>
|
5 |
<title>Whack A Worm</title> |
6 |
|
7 |
<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style> |
8 |
|
9 |
</head>
|
10 |
<body>
|
11 |
</body>
|
12 |
</html>
|
Step 6: JavaScript Libraries
The following code adds the necessary JavaScript libraries for our app to work.
1 |
|
2 |
<!DOCTYPE html>
|
3 |
<html>
|
4 |
<head>
|
5 |
<title>Whack A Worm</title> |
6 |
|
7 |
<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style> |
8 |
|
9 |
<script src="easel.js"></script> |
10 |
<script src="Tween.js"></script> |
11 |
<script src="WhackAWorm.js"></script> |
12 |
</head>
|
13 |
<body>
|
14 |
</body>
|
15 |
</html>
|
Step 7: Call Main Function
In the next lines we call our constructor, this is the main function that will be created later in our JavaScript code.
1 |
|
2 |
<!DOCTYPE html>
|
3 |
<html>
|
4 |
<head>
|
5 |
<title>Whack A Worm</title> |
6 |
|
7 |
<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style> |
8 |
|
9 |
<script src="easel.js"></script> |
10 |
<script src="Tween.js"></script> |
11 |
<script src="WhackAWorm.js"></script> |
12 |
|
13 |
</head>
|
14 |
<body onload="Main();"> |
15 |
</body>
|
16 |
</html>
|
Step 8: Canvas Tag
The Canvas is added in this line. We assign an ID to reference it later and also set its width and height.
1 |
|
2 |
<!DOCTYPE html>
|
3 |
<html>
|
4 |
<head>
|
5 |
<title>Whack A Worm</title> |
6 |
|
7 |
<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style> |
8 |
|
9 |
<script src="easel.js"></script> |
10 |
<script src="Tween.js"></script> |
11 |
<script src="WhackAWorm.js"></script> |
12 |
|
13 |
</head>
|
14 |
<body onload="Main();"> |
15 |
<canvas id="WhackAWorm" width="480" height="320"></canvas> |
16 |
</body>
|
17 |
</html>
|
Step 9: JavaScript
Let's begin our app creation!
Open your preferred JavaScript editor (any text editor will work, but you won't have syntax highlighting) and prepare to write your awesome app. Remember to save the file with a .js
extension in your project folder.
Step 10: Define Canvas
We'll start by defining all the graphic and logic variables.
The next variables represent the HTML canvas element and the stage that will be linked to it. The stage variable will behave in a similar way to the AS3 stage.
1 |
|
2 |
/* Define Canvas */
|
3 |
|
4 |
var canvas; |
5 |
var stage; |
Step 11: Background
This variable will store the title background image. (You can download the image above, or get it from the tutorial's source ZIP file.)
1 |
|
2 |
/* Background */
|
3 |
|
4 |
var titleBg; |
Step 12: Title View
This is the Title View, which will be the first interactive screen to appear in our game. These variables store its components:
1 |
|
2 |
/* Title View */
|
3 |
|
4 |
var titleBgImg = new Image(); |
5 |
var titleBg; |
6 |
var playBtnImg = new Image(); |
7 |
var playBtn; |
8 |
var creditsBtnImg = new Image(); |
9 |
var creditsBtn; |
10 |
var titleView = new Container(); |
Step 13: Credits
This view will show the credits, year and copyright of the game, and these variables will be used to store it.
1 |
|
2 |
/* Credits */
|
3 |
|
4 |
var creditsViewImg = new Image(); |
5 |
var creditsView; |
Step 14: Game View Background
The background for the Game View.
1 |
|
2 |
/* Game Bg */
|
3 |
|
4 |
var gameBgImg = new Image(); |
5 |
var gameBg; |
Step 15: Alert
An alert will be shown when all the Worms have popped up, and will display the final score the player reached.
1 |
|
2 |
/* Alert */
|
3 |
|
4 |
var alertBgImg = new Image(); |
5 |
var alertBg; |
Step 16: Score
The score value will be handled by the next variable.
1 |
|
2 |
/* Score */
|
3 |
|
4 |
var score; |
Step 17: Worms
The following variables are used to store the worms' graphics and to refer to the last worm that was visible.
1 |
|
2 |
/* Worms */
|
3 |
|
4 |
var wormImg = new Image(); |
5 |
var worm; |
6 |
var lastWorm; |
Step 18: Position Arrays
Arrays are used to store the worms final position. This is used to move the worm to the correct hole position when performing the pop-out animation.
1 |
|
2 |
var wormsX = [80, 198, 338, 70, 225, 376, 142, 356]; |
3 |
var wormsY = [11, 51, 34, 110, 136, 96, 211, 186]; |
Step 19: Additional Variables
These are the other variables we'll use; read the comments in the code to know more about them. (Some are self-explanatory.)
1 |
|
2 |
var centerX = 240; |
3 |
var centerY = 160; |
4 |
var gfxLoaded = 0; //used as a preloader |
5 |
|
6 |
var timerSource; |
7 |
var currentWorms = 0; //worms already shown |
8 |
var wormsHit = 0; |
9 |
var totalWorms = 10; //total of worms to display |
Step 20: Main() Function
The Main()
function will be the first to execute when the web page is loaded, because it is referred to in the onload
attribute of the HTML document (see Step 7).
It calls the necessary functions to start the game. Check those functions in the next steps.
1 |
|
2 |
function Main() |
3 |
{
|
4 |
//code...
|
5 |
}
|
Step 21: Link Canvas
This code gets the HTML canvas ID and links it to the EaselJS Stage class. This will make the stage variable behave like the stage class in AS3.
1 |
|
2 |
/* Link Canvas */
|
3 |
|
4 |
canvas = document.getElementById('WhackAWorm'); |
5 |
stage = new Stage(canvas); |
Step 22: Enable Mouse Events
Mouse Events are disabled by default in EaselJS to improve performance; since we need those in the game we add the following line.
1 |
|
2 |
stage.mouseEventsEnabled = true; |
Step 23: Load Graphics
This code is used to preload the graphics with the help of a function that we'll write later. It sets the Image object we created before to the source PNG file in our document folder. A name is given to detect which image is loaded and lastly the function that hadles the loaded images is called.
1 |
|
2 |
/* Load GFX */
|
3 |
|
4 |
titleBgImg.src = 'titleBg.png'; |
5 |
titleBgImg.name = 'titleBg'; |
6 |
titleBgImg.onload = loadGfx; |
7 |
|
8 |
gameBgImg.src = 'gameBg.png'; |
9 |
gameBgImg.name = 'gameBg'; |
10 |
gameBgImg.onload = loadGfx; |
11 |
|
12 |
playBtnImg.src = 'playBtn.png'; |
13 |
playBtnImg.name = 'playBtn'; |
14 |
playBtnImg.onload = loadGfx; |
15 |
|
16 |
creditsBtnImg.src = 'creditsBtn.png'; |
17 |
creditsBtnImg.name = 'creditsBtn'; |
18 |
creditsBtnImg.onload = loadGfx; |
19 |
|
20 |
creditsViewImg.src = 'creditsView.png'; |
21 |
creditsViewImg.name = 'credits'; |
22 |
creditsViewImg.onload = loadGfx; |
23 |
|
24 |
alertBgImg.src = 'alertBg.png'; |
25 |
alertBgImg.name = 'alertBg'; |
26 |
alertBgImg.onload = loadGfx; |
27 |
|
28 |
wormImg.src = 'worm.png'; |
29 |
wormImg.name = 'worm'; |
30 |
wormImg.onload = loadGfx; |
Step 24: Set Ticker
The Ticker object provides a centralized tick or heartbeat, broadcast at a set interval through the tick()
callback.
The following code sets the frame rate to 30 and deines the stage as the listener for the ticks.
The TweenJS class will listen to this tick to perform the animations.
1 |
|
2 |
/* Ticker */
|
3 |
|
4 |
Ticker.setFPS(30); |
5 |
Ticker.addListener(stage); |
Step 25: Preload Function
Every time a graphic is loaded this function will run. It will assign each image to a bitmap object and check whether all the elements are loaded before proceeding. As you can see only five images are assigned to a bitmap but the gfxLoaded
variable waits until seven items are loaded; this is so that it waits for the CreditsView and Worms graphic to be set in memory.
1 |
|
2 |
function loadGfx(e) |
3 |
{
|
4 |
if(e.target.name = 'titleBg'){titleBg = new Bitmap(titleBgImg);} |
5 |
if(e.target.name = 'gameBg'){gameBg = new Bitmap(gameBgImg);} |
6 |
if(e.target.name = 'playBtn'){playBtn = new Bitmap(playBtnImg);} |
7 |
if(e.target.name = 'creditsBtn'){creditsBtn = new Bitmap(creditsBtnImg);} |
8 |
if(e.target.name = 'alertBg'){alertBg = new Bitmap(alertBgImg);} |
9 |
/* --CreditsView
|
10 |
--Worms */
|
11 |
|
12 |
gfxLoaded++; |
13 |
|
14 |
if(gfxLoaded == 7) |
15 |
{
|
16 |
addTitleView(); |
17 |
}
|
18 |
}
|
Step 26: Add Game View
When all the graphics are loaded the game background is added to the stage, it will be later covered by the Title View, this is to show something behind it when this view is tweened and removed.
1 |
|
2 |
function addTitleView() |
3 |
{
|
4 |
/* Add GameView BG */
|
5 |
|
6 |
stage.addChild(gameBg); |
Step 27: Title View
Now we place the TitleView in the stage and call a function that will add the mouse listeners to the buttons.
1 |
|
2 |
/* Title Screen */
|
3 |
|
4 |
playBtn.x = centerX - 25; |
5 |
playBtn.y = centerY + 35; |
6 |
|
7 |
creditsBtn.x = centerX - 40; |
8 |
creditsBtn.y = centerY + 80; |
9 |
|
10 |
titleView.addChild(titleBg, playBtn, creditsBtn); |
11 |
|
12 |
stage.addChild(titleView); |
13 |
|
14 |
startButtonListeners('add'); |
15 |
|
16 |
stage.update(); |
17 |
}
|
Step 28: Start Button Listeners
This function adds the necesary listeners to the TitleView buttons.
1 |
|
2 |
function startButtonListeners(action) |
3 |
{
|
4 |
if(action == 'add') |
5 |
{
|
6 |
titleView.getChildAt(1).onPress = showGameView; |
7 |
titleView.getChildAt(2).onPress = showCredits; |
8 |
}
|
9 |
else
|
10 |
{
|
11 |
titleView.getChildAt(1).onPress = null; |
12 |
titleView.getChildAt(2).onPress = null; |
13 |
}
|
14 |
}
|
Step 29: Show Credits
The Credits screen is shown when the user clicks the credits button, a mouse listener is added to the full image to remove it.
1 |
|
2 |
function showCredits() |
3 |
{
|
4 |
playBtn.visible = false; |
5 |
creditsBtn.visible = false; |
6 |
creditsView = new Bitmap(creditsViewImg); |
7 |
stage.addChild(creditsView); |
8 |
creditsView.x = -203; |
9 |
|
10 |
Tween.get(creditsView).to({x:0}, 200).call(function(){creditsView.onPress = hideCredits;}); |
11 |
}
|
Step 30: Hide Credits
When the Credits screen is clicked it will be tweened back and removed from the stage.
1 |
|
2 |
function hideCredits() |
3 |
{
|
4 |
playBtn.visible = true; |
5 |
creditsBtn.visible = true; |
6 |
Tween.get(creditsView).to({x:-203}, 200).call(function(){creditsView.onPress = null; stage.removeChild(creditsView); creditsView = null;}); |
7 |
}
|
Milestone
Let's stop here to make a quick test and make sure that our game code is working.
Take a look at the milestone here.
Keep in mind that some lines have been commented as some functions haven't been created yet.
Remember that the Milestones are included in the source files, so if for some reason your file doesn't mimic this one take a look at the source to see what could be causing that.
Step 31: Show Game View
The following lines remove the Title screen and leave the Game Screen visible. It also calls a function that will show the first worm.
1 |
|
2 |
function showGameView() |
3 |
{
|
4 |
Tween.get(titleView).to({x: -480}, 200).call( |
5 |
function(){ |
6 |
startButtonListeners('rmv'); |
7 |
stage.removeChild(titleView); |
8 |
titleView = null; |
9 |
showWorm(); |
10 |
}
|
11 |
);
|
12 |
}
|
Step 32: Score Text
This code creates the Text object that will display the score.
1 |
|
2 |
score = new Text('0' + '/' + totalWorms, 'bold 15px Arial', '#EEE'); |
3 |
score.maxWidth = 1000; //fix for Chrome 17 |
4 |
score.x = 58; |
5 |
score.y = 21; |
6 |
stage.addChild(score); |
Step 33: Check for Game Over
This code checks whether the Worms shown have passed the limit and calls an Alert if true.
1 |
|
2 |
function showWorm() |
3 |
{
|
4 |
if(currentWorms == totalWorms) |
5 |
{
|
6 |
showAlert(); |
7 |
}
|
Step 34: Remove Last Worm
This code checks whether a worm has been added and removes it if so.
1 |
|
2 |
else
|
3 |
{
|
4 |
if(lastWorm != null) |
5 |
{
|
6 |
lastWorm.onPress = null; |
7 |
stage.removeChild(lastWorm); |
8 |
stage.update(); |
9 |
lastWorm = null; |
10 |
}
|
Step 35: Calculate Random Worm
The next line calculates a random number that will be used in the positions
array to place a worm in a random hole.
1 |
|
2 |
var randomPos = Math.floor(Math.random() * 8); |
Step 36: Add Worm
Now we create the worm and place it; a mouse listener is also added to handle the player clicks.
1 |
|
2 |
var worm = new Bitmap(wormImg); |
3 |
|
4 |
worm.x = wormsX[randomPos]; |
5 |
worm.y = wormsY[randomPos]; |
6 |
stage.addChild(worm); |
7 |
worm.onPress = wormHit; |
8 |
|
9 |
lastWorm = worm; |
Step 37: Animation
A little animation will be displayed when the worm comes out: a small tween to its scaleY property. When the animation is finished the currentWorms
variable increases and the showWorm()
function is called again; this will create a loop that will end once the currentWorms
variable reaches the value of totalWorms
.
1 |
|
2 |
lastWorm.scaleY = 0.3; |
3 |
lastWorm.y += 42; |
4 |
stage.update(); |
5 |
|
6 |
Tween.get(lastWorm).to({scaleY: 1, y: wormsY[randomPos]}, 200).wait(1000).call(function(){currentWorms++; showWorm()}); |
Step 38: Hit Worm
This function handles a Worm's being clicked; it will basically raise the score and destroy the clicked worm.
1 |
|
2 |
function wormHit() |
3 |
{
|
4 |
wormsHit++; |
5 |
score.text = wormsHit + '/' + totalWorms; |
6 |
|
7 |
lastWorm.onPress = null; |
8 |
stage.removeChild(lastWorm); |
9 |
lastWorm = null; |
10 |
stage.update(); |
11 |
}
|
Step 39: Show Alert
This function will stop the game and reveal the final score, showing and tweening the alert background.
1 |
|
2 |
function showAlert() |
3 |
{
|
4 |
alertBg.x = centerX - 120; |
5 |
alertBg.y = -80; |
6 |
stage.addChild(alertBg); |
7 |
|
8 |
Tween.get(alertBg).to({y:centerY - 80}, 200).call(function() |
9 |
{
|
10 |
Ticker.removeAllListeners(); |
11 |
var score = new Text(wormsHit + '/' + totalWorms, 'bold 20px Arial', '#EEE'); |
12 |
score.maxWidth = 1000; //fix for Chrome 17 |
13 |
score.x = 220; |
14 |
score.y = 205; |
15 |
stage.addChild(score); |
16 |
stage.update(); |
17 |
});
|
18 |
}
|
Step 40: Test
Save your work (if you haven't) and open the HTML file in the browser to see your HTML5 game working!
Conclusion
As you can see many of the game variables/parameters can be modified and adapted to your needs, so try creating your own version of the game!
I hope you liked this tutorial, thank you for reading!