Cross Over To HTML5 Game Development. Use Your Programming Experience To Create Mobile Game
Cross Over To HTML5 Game Development. Use Your Programming Experience To Create Mobile Game
HTML5 Game
Development
Use Your Programming Experience to
Create Mobile Games
—
Zarrar Chishti
www.allitebooks.com
Cross Over to HTML5
Game Development
Use Your Programming
Experience to Create
Mobile Games
Zarrar Chishti
www.allitebooks.com
Cross Over to HTML5 Game Development: Use Your Programming
Experience to Create Mobile Games
Zarrar Chishti
Glasgow, United Kingdom
www.allitebooks.com
Table of Contents
About the Author��������������������������������������������������������������������������������vii
About the Technical Reviewer�������������������������������������������������������������ix
Acknowledgments�������������������������������������������������������������������������������xi
Preface����������������������������������������������������������������������������������������������xiii
Chapter 1: Introduction������������������������������������������������������������������������1
Introducing Our Game: Space Zombies������������������������������������������������������1
Setting up Your Work Environment�������������������������������������������������������������4
Part 1: Setting up Our Folders������������������������������������������������������������������������������������� 4
Part 2: Setting up Our Files������������������������������������������������������������������������������������������ 6
iii
www.allitebooks.com
Table of Contents
iv
www.allitebooks.com
Table of Contents
Zombie Down!����������������������������������������������������������������������������������������119
Part 1: Create Six Bubble Zombie Elements������������������������������������������������������������ 120
Part 2: Activate the Counter Bubble Zombie������������������������������������������������������������ 129
Part 3: Animate the Bubble Zombies����������������������������������������������������������������������� 136
Index�������������������������������������������������������������������������������������������������247
www.allitebooks.com
About the Author
Zarrar Chishti is a software and games
development consultant with over 500 games
developed for companies around the world. He
is sought after to advise on the development
of viral games for major marketing campaigns.
His consultancy and development firm include
prestigious companies such as Turner Media,
British Airways and Channel 4 among the
many clients that keep coming back when a
new product or service is being launched.
After graduating from Glasgow University
in 1996 with a prestigious joint honors degree in Software Engineering,
Zarrar contracted as a software developer in both London and L.A. for 5
years. In 2001 he opened his own software firm in Glasgow and within 2
years was employing 10 staff. This was to grow to 30 in 2005 when he began
to offer games development to his clients.
One of the most notable game projects Zarrar has produced includes
an interactive comic for the popular Ben 10 TV series. The project was a
notable success that took his firm 10 months to deliver. It was rolled out
in over 25 countries in localized language editions. Other projects include
building a series of games for the ever popular Big Brother TV franchise
and an employee training game for Legal and General.
vii
www.allitebooks.com
About the Technical Reviewer
Massimo Nardone has more than 22 years
of experiences in security, web/mobile
development, and cloud and IT architecture.
His true IT passions are security and Android.
He has programmed and taught how to
program with Android, Perl, PHP, Java, VB,
Python, C/C++ and MySQL for more than 20
years.
He holds a master’s degree in computing
science from the University of Salerno, Italy.
He has worked as a project manager, software engineer, research
engineer, chief security architect, information security manager, PCI/SCADA
auditor and senior lead IT security/cloud/SCADA architect for many years.
His technical skills include security, Android, cloud, Java, MySQL,
Drupal, Cobol, Perl, web and mobile development, MongoDB, D3, Joomla,
Couchbase, C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll,
Scratch, and more.
He currently works as chief information security office (CISO) for
Cargotec Oyj.
He worked as visiting lecturer and supervisor for exercises at the
Networking Laboratory of the Helsinki University of Technology (Aalto
University). He holds four international patents (PKI, SIP, SAML, and Proxy
areas).
Massimo has reviewed more than 40 IT books for various publishing
companies. He is the coauthor of Pro Android Games (Apress, 2015).
ix
www.allitebooks.com
Acknowledgments
To Pops - you were an amazing dad who has left a massive hole in our lives.
To my closest friend, who has been (and continues to be) there for me
at the times when it matters the most: my brother Ibrar. Thank you to my
parents, who gave me the most amazing education and start to life. My one
constant and partner in crime, my wife Sadia. My son, whom I am so proud
of (incidentally, he was my initial editor for the book) and my “janno-jaan”
daughters: Sara, Aisha, and Rushda. I would be in a tremendous amount
of trouble if I did not also acknowledge Bella, our Bengal cat.
I would like to say a heartfelt thank you to my agent, Carole. You agreed
to represent me, despite my thick Scottish accent! Your guidance and
patience at the start will always be remembered and appreciated. Also,
thank you to the awesome and gorgeous team at Apress: Aaron and Jessica.
I had a great time working with you both and you made this “noob” feel
like part of the team.
I want to thank two people who have inspired me to write books. My
Latin teacher Mr. Temperely and my favorite author of all time, David Blixt.
I would also like send my love and appreciation to all my staff, both past
and present: Alasdair, George, Paul (the Great), Les, and Claire. Also, my
thanks to those clients that gave me my initial start despite having little or
no experience.
Finally, I would like to thank the nurses and doctors at Monklands
Haematology department who looked after my wife, Sadia. I will always
remember your commitment, passion, and support that you gave to her.
Thank you for sending her home to us.
xi
www.allitebooks.com
Preface
Welcome to the wonderful world of HTML5 game development. Are you
looking for a new challenge or looking to expand your current skill set?
Then get ready to start your journey. This book has been written with a
simple goal in mind: to provide the means for anyone to develop their first
HTML5 game.
This is a great time to break into the most lucrative game development
platform in the world. The global demand for the HTML5 game
development platform has expanded so quickly that it is currently crying
out for seasoned developers from more traditional environments to
cross over. Never before has there been such a widely accepted platform
by literally every manufacturer and operating system. This, in turn,
has convinced marketing departments to move away from traditional
platforms, such as dedicated mobile apps, for the more widely accepted
HTML5 format.
In short, there has never been a better time for a seasoned IT
programmer to cross over and capitalize in this lucrative market with their
much sought-after talents and experience.
I have spent the last five years training developers from a wide range
of programming disciplines to cross-train in HTML5 game development.
Whatever your vocation, whether it be an application databases systems
developer or a professional web developer, with this book you will learn to
evolve your current coding skills to enable you to become eligible for the
biggest gaming platform in the world.
From the first chapter, you immediately see encouraging results as
you power through a challenging and fun project that has been uniquely
designed and developed for this book.
xiii
www.allitebooks.com
Preface
You can build this game using the computer/laptop that you already
have—as long as it switches on and you can run the already installed
Notepad program (if you are using Windows) or TextEdit (if you are on an
Apple Mac).
xiv
Preface
In this section, you will see the actual code that will need to be written. It is
important to ensure that you copy the code exactly as it is written.
On most occasions, you will only need to write the lines that are
written in bold. Also, the lines of code that existed before but have just
been modified are in red.
xv
Preface
In this section, you will see interesting facts and explanations of the code
that has just been written. If you wish to build on your coding knowledge
as you proceed, then you will find a great source of information here.
However, feel free to ignore this section if you just want to get on with
building your game.
Did something go wrong? Did the code you just wrote not work? Not to
worry. You will find common (and some not so common) mistakes here
with solutions on how to fix them.
xvi
CHAPTER 1
Introduction
“If you have a garden and a library,
you have everything you need.”
Marcus Tullius Cicero
(106 BC – 43 BC)
I have been developing software since 1996 and I have developed games
for small and large companies for over a decade now. Like any form of
development in the real world, you need to know why you are building
the game before you think of coding strategies and build processes. In the
gaming world, this comes in the form of the game’s story. This includes the
background, reasons to play, and the goals of the game.
Let’s have a look at a few of the graphics that we will use for the
development.
2
Chapter 1 Introduction
3
Chapter 1 Introduction
4
Chapter 1 Introduction
Once you have your root folder, the next step is to create the subfolders
that you will need for the game. Create four folders inside My_Work_Files.
Name the folders as follows:
• CSS
• Images
• Raw Images
• js
The CSS folder will hold special code files that help structure the design of
the game. All the files in this folder will end in .css.
The js folder will hold all of our JavaScript files, which will form the
engine for our game. They will contain commands and instructions that will
control what happens in our game. All the files in this folder will end in .js.
5
Chapter 1 Introduction
The Images folder, as the name suggests, will contain all the image or
media files that we will need for the game.
The Raw Images folder will not technically be used for raw images. In
our case, we will use this folder as special temporary housing for all of our
media. We will move them into the Images folder when we need them.
Although using an IDE has its benefits, I think that it is worth keeping
in mind this excellent quote about using IDEs for multiple languages:
“Although many IDEs can handle more than one language, few do it
well. Plus, it’s likely overkill if you are just getting started.”
Now that the folders are set up, let’s create the files that you will use to
develop the game.
First, you need to create a default.html file. If you are using an IDE,
click File ➤ Create New and select HTML. If you are using Notepad, open a
new file and save it as default.html.
Your folder should now look like this:
7
Chapter 1 Introduction
Finally, we need to create a file within the CSS folder. Repeat the steps
from earlier (i.e., create a New File and then Save As). The file name to
enter is
> SZ_master.css.
8
Chapter 1 Introduction
9
Chapter 1 Introduction
Dedicated Server
This is the most expensive option. Essentially, you own the computer that
is connected to the Internet. This is only an option if you are either a huge
company or a reseller.
10
Chapter 1 Introduction
Shared Server
This is generally the most economical option for hosting. It is very much
for people like you, who are renting a piece of the server. The main
advantage is the ridiculously low cost, of course. However, as your game
development expertise increases, you may find this option to be limiting
and unfit for your specific needs.
Cloud Hosting
Whereas the prior two options rely on one physical computer, cloud
hosting allows an unlimited number of computers to act as one system.
http://zarrarchishtiauthor.com/downloads/
Click the Download button. This will initiate a download. The browser
will let you know when it has completed. Navigate to your download folder
and locate the downloaded file.
It should be a file called raw_media_1.rar. Now you need to extract the
files from this zipped file in a new folder called Raw Media. Double-click
this folder and you will see the following four folders:
• > Images
• > JS
• > sounds
• > html_web
11
Chapter 1 Introduction
First, copy all four folders to your Raw Images folder, which is in the
My_Work_Files folder.
At this stage, we are only interested in the files inside the JS folder. As
we progress through the game, we will go back to the other folders and
copy the files as needed. Double-click the JS folder (in the Raw Images
folder). Using the same technique as before to copy files, go ahead and
copy all the files, and then paste them into your own js folder (in the My_
Work_Files folder).
Your js folder (in the My_Work_Files folder) should now look like this:
12
Chapter 1 Introduction
The files we copied over from the JS folder are special JavaScript programs
that we can use for our game. Imagine a library of code maintained by
companies like Google that contain functions that make our lives easier.
The files—for instance, jQuery—are fast, small, and feature-rich
JavaScript libraries. Together they make things like HTML document
traversal and manipulation, event handling, animation, and AJAX much
simpler with an easy-to-use API that works across a multitude of browsers.
When using a library such as this, we do not need to ever worry about
how they work. All we need to know is what they do so that we can decide
whether we want to use them in our games.
Another advantage of using libraries such as jQuery is that it runs
exactly the same in all major browsers, including Internet Explorer 6! So no
need to worry about cross-browser issues.
Usually, we link to these files directly from the source servers. The
advantage of doing it this way is that we always get the latest copy of the
code when running our game. However, since we want to be able to play
the game offline, let’s choose to download them into our local folders.
13
Chapter 1 Introduction
http://www.win-rar.com/download.html
14
CHAPTER 2
In the Beginning,
There Was HTML
“Nine people can’t make a baby in a month.”
Fred Brooks
H
ello World
During my 20 years of programming, I have learned many programming
languages. The first project that I always work on is learning how to output
the words “Hello World.” to the screen. I bet that you follow this tradition
too, so let’s develop a “Hello World” page in HTML.
Open the default.html file in Notepad or TextEdit in the My_Work_Files
folder using the same program or IDE that you used in the “Part 2: Setting up
Our Files” section in Chapter 1.
15
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0_2
Chapter 2 In the Beginning, There Was HTML
When the file opens, it should be completely blank. Type the following
lines:
<html>
<head>
</head>
<body>
<div id="SZ_maincontent">
Hello World.
</div>
</body>
</html>
Navigate to the menu, click File and then click on Save. You can now
close this file. Navigate back to the menu, click File, and then click Exit/
Close.
Are you ready to test your very first program?
Go back to the My_Work_Files folder and double-click the default.
html file. This should open in your default Internet browser; for example,
Microsoft Edge, Google Chrome, or Safari.
The page that opens up on the browser should be a completely blank
page with the words “Hello World.” displayed in the top-left corner.
Excellent. Our program works and we have written our first piece of code!
Obviously, this is nowhere near a game yet. All the same, persevere
with the work between now and that point. Rest assured, by the end of
this book, we will have developed the entire game. It will most certainly be
worth it. And you will be learning a lot of different techniques to get you
started on your journey to developing a suite of games!
16
Chapter 2 In the Beginning, There Was HTML
You will notice that the closing tags are basically the same as the
opening tags, with a forward slash preceding it; for example, </div>
signals that you are closing that particular tag.
Please remember that every tag must be closed.
17
www.allitebooks.com
Chapter 2 In the Beginning, There Was HTML
Background Image
The game’s background image does not change, move, or interact with the
gameplay. It provides a backdrop for all the various elements that will be
controlled by the actual game.
First, go to the images folder in the Raw Images folder of the My_Work_
Files folder. Locate the file called SZ_background_image.jpg. You need
to copy this file over to your Images folder, which should then look like this:
Let’s reopen the default.html file. Remove the “Hello World” line by
selecting the line and clicking Delete/Backspace. Now type the following
new line (all the new text is in bold):
<html>
<head>
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg" />
</div>
</body>
</html>
18
Chapter 2 In the Beginning, There Was HTML
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file.
By using the <img> tag, we have defined a background image for our
page. It is important to note that the image is not technically inserted into
our HTML page; rather, the background image has been linked to our
HTML page. The <img> tag has created a holding space for the background
image.
The “Hello World” text should have disappeared, and the background
image is now in its place. It does not look like it’s covering the screen.
Do not worry about that. We will align and resize our images in the next
chapter.
In this section, you came across the <img> tag, which is used when you
want to place an image in your web page.
Inside the <img> tag, you will notice
id="SZ0_0"
As it suggests, this is the ID for the image tag. This ID is used when we
start coding in JavaScript in Chapter 4.
Also, you will have noticed the src tag:
src="images/SZ_background_image.jpg"
src, which stands for “source,” allows you to specify the location of the
image. Earlier in this section, we placed SZ_background_image.jpg in the
images folder. So as you can see, the src is the exact location and the name
of the image file.
19
Chapter 2 In the Beginning, There Was HTML
Now, let’s think back to the previous section, when I said that you
always need to include closing tags. I ended the section by stating that all
tags must be closed. However, the code that we just wrote did not include
</img>. So, did I forget?
What I did there was close our tag within the opening tag. Note that at
the end of our img tag, there is a forward slash before the >. This is another
way to close tags if you do not need add elements outwith what is written
in the opening tag itself.
Let’s analyze our line of code:
• SZ_gun.png
• SZ_reload.png
• SZ_score.png
There will be many more images by the time we finish the game;
however, this is all that we need at this stage.
20
Chapter 2 In the Beginning, There Was HTML
As before, go into the images folder in the Raw Images folder of the
My_Work_Files folder. Locate the three new .png files and copy them over
to your Images folder, which should then look like this:
Now, reopen the default.html file and type the following new lines
(all the new text is in bold):
<html>
<head>
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg" />
<img id="SZ0_1" src="images/SZ_gun.png" />
<img id="SZ0_2" src="images/SZ_reload.png" />
<img id="SZ0_3" src="images/SZ_score.png" />
</div>
</body>
</html>
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file.
21
Chapter 2 In the Beginning, There Was HTML
You should now see the three new images. You may have to scroll
down the web page. Again, do not worry about how the images appear on
the page. Just ensure you can see the background image from before and
the three new images that we just added.
At this stage quite a few people ask me if HTML5 game development
is just the same as being a web developer. Yes in the same way an Xbox
console developer is just a C#/C++ Forms developer. However HTML5
games do not look and feel like a normal website, do they? As you develop
this game you will find out that a HTML5 games developer has to learn
everything about being a web developer and then more. You will need to
work out where the supposed boundaries lie for a web developer and then
learn how far you can push them for your game’s engine.
In this chapter we have managed to code our four initial graphical
elements on to our screen. They may not look like much to look at as they
do not seem to be in the right place nor the right size. However not to
worry, as in the next chapter we will apply CSS to the four images which
will align them exactly where we want them to be.
22
CHAPTER 3
CSS, which stands for Cascading Style Sheets, is a language that is used to
help style and design web sites. It can be used to describe how the page
should look in terms of color, layout, and fonts.
So why do we need this for our game? Previously, we imagined HTML
as the skeleton or bone structure of our game. CSS code will be the look
and appearance of our game. If you are familiar with building web sites,
however, you may be wondering how big a role CSS actually plays in
HTML5 game development.
With the arrival of CSS3, animations in CSS allow the browser to
determine which elements should get GPU layers, which results in
hardware acceleration. Do not start moving all your animations over
to CSS en masse, however. It is generally not a good idea to give every
element its own layer. If you do, then your GPU will run out memory—
quickly. I am sure you will agree that there is no worse feeling as a
developer than when you receive the dreaded “Out of Memory” error.
23
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0_3
Chapter 3 Time to Apply a Little CSS
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
background-colour: red;
}
• selector
• property
As the name suggests, here we define what property
of the tag we wish to apply a style to. In our <html>
example, we defined the height property to style.
24
Chapter 3 Time to Apply a Little CSS
• value
The actual style that you wish to define for the property.
In our case, we decided that the height of our <html>
tag is 100% of the screen size.
Interestingly, you can specify the same parameters for multiple tags by
simply grouping them.
Before testing, we need to link this file into our default.html file.
Reopen the default.html file and type the following new (in bold) line:
<html>
<head>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg" />
<img id="SZ0_1" src="images/SZ_gun.png" />
<img id="SZ0_2" src="images/SZ_reload.png" />
<img id="SZ0_3" src="images/SZ_score.png" />
</div>
</body>
</html>
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file.
You should see the same screen as last time (i.e., the four images) but
with a red background instead of white. This is good because it means that
you successfully linked the CSS file to the main HTML page.
25
Chapter 3 Time to Apply a Little CSS
It is worth noting that we can use the properties min-height and max-
height to override the height property.
• padding: 0 0 0 0;
• position: fixed;
• margin:0;
The margin sets the size of the white space around the
element. In our case, we do not want any white space
around the edges of the screen.
• user-select: none; We can control how our player
interacts with the text elements on the screen by using
the user-select property. In this case, it is set to none,
which means that we do not want the user to select or
click any text elements. The reason for this is that it may
distract from playing the actual game (for example, text
that allows the user to select the high score).
The link tag is the standard way to include a CSS file on the page. The
href specifies the location of the CSS file that we wish to include. The rel
tag specifies the relationship between the HTML file and the CSS file. In
this case, the CSS file acts as a style sheet for the HTML file.
27
Chapter 3 Time to Apply a Little CSS
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
}
img {
max-width: 100%;
height: auto;
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
28
Chapter 3 Time to Apply a Little CSS
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file.
Note that we have removed the background-colour: red; from body
tag. Ensure that you remove that line from your code. Your file should look
exactly like what is shown.
You may be wondering why we have coded the user-select property
in four different ways. The first method is the standard property in CSS
(i.e., user-select). We then go on to define the vendor-prefixed properties
offered by the various rendering engines. This allows properties to be
set specific to each individual browser engine to safely account for
inconsistencies between implementations.
The following are the vendor-prefixed properties that we used:
29
Chapter 3 Time to Apply a Little CSS
You should first notice the background image now covers the entire
screen. Also, the other three images are completely gone from the screen.
Not to worry. They are still there— behind the background image.
The first style added to our CSS was for the <img> tag. This means that the
styles defined apply to every image that we add to our page. I am sure you
will agree that this is a big time-saving technique, because the alternative is
to repeat the styles laboriously for every image that we add.
Anyhow, not every image requires the same styles. You can see the
second style is specifically written for one of the image tags, which is
identified as #SZ0_0.
The styles that we put in the <img> tag are the more generic styles
that should apply to all images. We can then add an individual style to a
specific image and add more styles. We can even override styles that were
written in the <img> tag.
30
Chapter 3 Time to Apply a Little CSS
Before we leave this, why did we call the tag #SZ0_0? If you go back to
Section 2.3, notice the following:
This image is identified as SZ0_0. In CSS, you can identify the image by
placing the hash sign (#) before the ID.
Let’s take a look at the new CSS techniques that we used.
• user-drag: none;
• top: 0; left: 0;
Sets the top and left edge of the image. In this case, we
want the image to always position itself in the top-left
corner of its container.
31
Chapter 3 Time to Apply a Little CSS
• SZ_gun
• SZ_reload
• SZ_score
Now open the SZ_master.css file and type the following new lines
(all new text is in bold):
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
}
img {
max-width: 100%;
height: auto;
user-drag: none;
user-select: none;
32
Chapter 3 Time to Apply a Little CSS
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#SZ0_1 {
position: fixed;
bottom: 0;
right: 0;
}
#SZ0_2 {
position: fixed;
top: 0;
left: 0;
}
#SZ0_3 {
position: fixed;
top: 0;
right: 0;
}
33
Chapter 3 Time to Apply a Little CSS
In this code, we have defined three properties for each of the three
images. However, notice that the properties and their subsequent values
are exactly the same. Earlier, I touched on the fact that we can specify the
same parameters for multiple tags by simply grouping them. So if you wish,
you can try that with the preceding code by replacing the bold code with
the following:
Although you can now see all four images in their aligned positions,
they aren’t quite the right size; however, do not worry about that. In the
next chapter, we will use JavaScript to resize the images.
34
Chapter 3 Time to Apply a Little CSS
In our case, we used fixed along with bottom: 0; right: 0;. In the
previous section, we set the image’s top-left corner; whereas here we can
set the image from the bottom-right corner of its container.
Since we need our gun to always be positioned in the bottom-right
corner of the screen, it makes more sense in this case to use the bottom-
right property rather than the top-left property.
35
CHAPTER 4
Apply Intelligence
with JavaScript
“Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.”
Rick Osborne
As you have learned, HTML is the bone structure and CSS is the look and
appearance of our game. So what does JavaScript bring to the table? JavaScript
is a programming language used for creating interactivity in web sites. So we
could say that we use JavaScript as the master controller of our game.
So why do we need it for our game? The obvious answer is that the
game needs to be able to create the zombies, fire the gun, and respond
to user commands. This is true, but there is a huge amount of other work
that the game needs JavaScript to perform. For example, in the previous
chapter, we discovered a need to resize our images based on the browser
size. Let’s do that now using JavaScript.
//global vars
//need to store the ratio
var ratio;
//need easy access to the width
var newWidth;
//function that gets called when game starts
$(window).load(function () {
//need to grab an instance of our screen
var div = $(window);
//we can now work out the ratio
ratio = (div.width() / 1024);
38
www.allitebooks.com
Chapter 4 Apply Intelligence with JavaScript
//while we are here we can grab the width for future use
newWidth = div.width();
});
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg" />
<img id="SZ0_1" src="images/SZ_gun.png" />
<img id="SZ0_2" src="images/SZ_reload.png" />
<img id="SZ0_3" src="images/SZ_score.png" />
</div>
</body>
</html>
39
Chapter 4 Apply Intelligence with JavaScript
These three new lines involve the <script> tag. In our case, we
chose to link this tag to an external script file through the src attribute.
Alternatively, we could have used the same tag to define a client-side script
containing scripting statements.
Now double-click the default.html file.
Nothing has changed, has it? This is due to the JavaScript code working
on background tasks. Also, we have not yet told it to do anything to our
images. All we did was store a value in the code (i.e., the ratio).
All the same, it would be nice to see if our first bit of code is working.
Let’s add a line of code that will show a message box on our screen. In this
box, we will put the value that our code has just worked out for the ratio.
This is not terribly exciting but at least we get some form of feedback from
our code. Now that is exciting.
Now open the SZ_main.js file and type the following new lines (those
that are in bold):
//global vars
//need to store the ratio
var ratio;
//need easy access to the width
var newWidth;
//function that gets called when game starts
$(window).load(function () {
//need to grab an instance of our screen
var div = $(window);
//we can now work out the ratio
ratio = (div.width() / 1024);
//while we are here we can grab the width for future use
newWidth = div.width();
//We are adding in a temporary bit of code here
window.alert("Hi this is your code and I have just worked out
that the ratio will be "+ratio);
});
40
Chapter 4 Apply Intelligence with JavaScript
What we have here is our code talking to us. It is telling us the value it
worked out for the ratio.
41
Chapter 4 Apply Intelligence with JavaScript
Before we go on, we need to remove the two lines that we just added.
Open the SZ_main.js file. After you remove the two lines, the code should
look like this again:
//global vars
//need to store the ratio
var ratio;
//need easy access to the width
var newWidth;
//function that gets called when game starts
$(window).load(function () {
//need to grab an instance of our screen
var div = $(window);
//we can now work out the ratio
ratio = (div.width() / 1024);
//while we are here we can grab the width for future use
newWidth = div.width();
});
You will create many wonderful functions in this book, and no doubt
in the games that you go on to develop. However, I hope you treasure this
moment as I did back in 1994 when I was learning to code Pascal.
42
Chapter 4 Apply Intelligence with JavaScript
Did the window box not appear? Not to worry. One of these tips should
help:
• Did you miss any semicolons (;) at the end of your lines?
• Did you make sure that you added the three lines of
code in the HTML file?
If your code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
43
Chapter 4 Apply Intelligence with JavaScript
What is a function?
When you start the line with double forward slashes (//), you are telling
the computer to ignore this line. Why would you do that? Well, it is there
for us and it is called a comment line. Its purpose is to leave messages for
ourselves (or other programmers). By leaving messages, we break up the
code and make the whole program easier to read. You can write anything
you like. I like to use it to explain why the code after the comment was
originally written.
You do not have to comment every line; however, I was always taught
to comment as many lines as I code. This may appear overkill to some
programmers; however, I have found that when I return to my code after a
few years, the comments I wrote help me understand the reasoning behind
the code.
44
Chapter 4 Apply Intelligence with JavaScript
Why did we add the other two files to our HTML file?
When it came to adding the SZ_main.js file, we also added jQuery and
jQuery-UI files. These are essentially filled with advanced functions (like
the one you wrote). As long as we use their functions, all we have to do is
add them to our HTML.
These functions are fast, reliable, and rich with features. Some of the
biggest companies in the world use them, as do small game developers like us.
Let’s now look at some of the JavaScript code we wrote.
• var ratio;
• $(window).load(function () {
• newWidth = div.width();
This means we can store the window’s width in our
variable called newWidth.
45
Chapter 4 Apply Intelligence with JavaScript
//main function
function main_call_setupContent() {
//need to resize all elements
//first we set their normal sizes in CSS
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
46
Chapter 4 Apply Intelligence with JavaScript
At some point, you may wish to revisit this function and recode the
flow. I recommend that you place the values of the image IDs into an array;
for example,
You would then also need to place the values for each image into
another array; for example,
You could then code a for loop to execute the same code three times,
substituting the ID with the next value in the ID array, and substituting the
width and height values with the values in the size array.
Open the SZ_main.js file and type the following new lines (the new
text is in bold):
//global vars
//need to store the ratio
var ratio;
//need easy access to the width
var newWidth;
//function that gets called when game starts
$(window).load(function () {
//need to grab an instance of our screen
var div = $(window);
//we can now work out the ratio
ratio = (div.width() / 1024);
//while we are here we can grab the width for future use
newWidth = div.width();
//let’s apply the ratio to our elements
main_call_setupContent();
});
47
Chapter 4 Apply Intelligence with JavaScript
Before we can test, we need to link this file to our default.html file.
Reopen the default.html file and type the following line (the new text is in
bold):
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg" />
<img id="SZ0_1" src="images/SZ_gun.png" />
<img id="SZ0_2" src="images/SZ_reload.png" />
<img id="SZ0_3" src="images/SZ_score.png" />
</div>
</body>
</html>
48
Chapter 4 Apply Intelligence with JavaScript
Where did the ideal sizes come from (for example, the gun: Width
175px and Height 200px)?
The step that is taken before any development can start is the layout design
of each screen. This is where you physically place the elements, like the
gun, on a screen.
49
Chapter 4 Apply Intelligence with JavaScript
You first need to choose a normal size. In our case, we chose the screen
width 1025px and height 800px. Of course, the chances that a user will
have this exact screen size are very slim. This is why we worked out the
ratio earlier.
You can use any software design program, such as Macromedia
Photoshop or Fireworks, to create layout files. Once we create our new
canvas size of 1024 × 800, we can then resize and reposition our elements
exactly where we would like them on the canvas. So, for example, we
placed our gun in the bottom-right corner, with a 175px width and a 200px
height.
We can now apply our ratio to the width and height to get an accurate
size for the screen being used.
We created a function in JavaScript as follows:
• function main_call_setupContent() {
• main_call_setupContent();
Only now are the instructions executed by the program.
50
CHAPTER 5
In this chapter, we’ll work on what we want our gun to do. When the user
presses anywhere on the screen, apart from the Reload button, it should be
treated as a shot. How a shot happens and the consequences of a shot are
dealt with in Chapter 7. For now, let’s look at reacting to a user click.
There will be a few awesome techniques employed, including sprite
sheets for animation and mathematics for fluid movement. As you
build other games in the future, you may find yourself coming back and
reusing these functions and techniques. This is exactly what happens in
commercial game development.
Incidentally, some of the code in this chapter is from a project I did
recently for a children’s game that is hosted in the Kelvingrove Art Gallery
and Museum in Glasgow.
51
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0_5
Chapter 5 Take a Shot: Part 1
Changing the cursor can be done simply using CSS. Open the SZ_
master.css file in our CSS folder. Type the following new line (in bold):
html {
height: 100%;
}
+
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
cursor: crosshair;
}
img {
max-width: 100%;
height: auto;
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
52
Chapter 5 Take a Shot: Part 1
#SZ0_1 {
position: fixed;
bottom: 0;
right: 0;
}
#SZ0_2 {
position: fixed;
top: 0;
left: 0;
}
#SZ0_3 {
position: fixed;
top: 0;
right: 0;
}
Save the file and then close it. Go back to our My_Work_Files folder
and double-click the default.html file.
Notice that the mouse cursor has changed from an arrow to crosshairs.
53
Chapter 5 Take a Shot: Part 1
• e-resize
• move
• nw-resize
• s-resize
• text
• no-drop
• grab
• n-resize
• pointer
• se-resize
• w-resize
• not-allowed
• help
• ne-resize
• progress
• sw-resize
• wait
54
Chapter 5 Take a Shot: Part 1
function rotateGun(e) {
//using the e value we can deduce the X co-ordinates
var xPos = e.clientX;
55
Chapter 5 Take a Shot: Part 1
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" onmousemove="rotateGun(event)" src="images/
SZ_background_image.jpg" />
<img id="SZ0_1" src="images/SZ_gun.png" />
<img id="SZ0_2" src="images/SZ_reload.png" />
<img id="SZ0_3" src="images/SZ_score.png" />
</div>
</body>
</html>
Save the file and then close it. Now double-click the default.html file.
Try moving the mouse along the screen. The gun should rotate as if
looking to aim at the target we are looking to shoot at. I am sure you will
agree that this is far more engaging than a static gun.
56
Chapter 5 Take a Shot: Part 1
Did the code not work? One of the new lines is different from the usual way
we add code. Let’s go through this together:
Open the default.html file.
Locate the line that starts with
Have you added the extra bit of text exactly as it’s shown?
Add the following text:
onmousemove="rotateGun(event)"
between
If your code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
57
Chapter 5 Take a Shot: Part 1
function rotateGun(e) {
The e contains all the information from an event that has occurred. In
this instance, it is a mouse movement on our image, which we declared as
follows:
When the user moves the mouse over this image, our rotateGun
function is called and the data from the movement is passed in.
In the first line, you see that we extract the “clientX” from e. This is the
horizontal coordinate (more commonly referred to as the x axis) of the
mouse event that has just occurred.
So what is this X-axis? Try to imagine the left-to-right user action of
your screen as the X axis. The following image illustrates the relationship
we want with the X-axis and the gun’s rotation.
58
Chapter 5 Take a Shot: Part 1
The maximum rotation between the far left and the far right gun is 50
degrees. So by finding out exactly where we are on the screen, we can use
a mathematical equation to determine what the exact rotation of the gun
should be.
One further point: the code we use to actually rotate the gun is done by
using both JavaScript and CSS. The JavaScript does most of the work here
by namely doing the following:
From here, we hand this value over to CSS, which then actually rotates
the gun.
Feel free to play with the numbers and test the different rotations that
occur; for example, change the following line
Change the 50 to 100. You will notice a far bigger change in how the gun
moves. Keep changing the number until you reach a level of rotation that
you are happy with. If you want to go back, simple type the preceding code.
59
Chapter 5 Take a Shot: Part 1
$("#SZ0_1").css('transform', 'rotate('+amountToRotate+'deg)');
Part 1
Open the SZ_SS.js file in your js folder. When the file opens, it should be
completely blank. Type the following lines:
60
Chapter 5 Take a Shot: Part 1
//also the new height will be our ratio times the height of
the div containing our image
var newHeightx = heightx * ratio2;
61
Chapter 5 Take a Shot: Part 1
A sprite sheet is a special image that contains several images in a tiled grid
arrangement.
Sprite sheets allow games to run faster, and more importantly, to take up
less memory. By compiling several graphics into a single file, you enable
your game to use the graphics while only needing to load a single file.
There are three parts to our sprite sheet. First, the normal static state is
when the gun reloads and when the gun fires. The following illustrates this:
62
Chapter 5 Take a Shot: Part 1
Why did we need to write our own special function to use sprite sheets?
There are many ways to deal with sprite sheets. Each programmer designs
their code to manipulate the sprite sheet that suits them. I have used a
very simple method here, which deals with sprites that have been laid out
linearly.
Also, our game does not require sophisticated use of any sprite sheets.
As you are writing all the code, I wanted to make sure that you only had to
write the minimum amount necessary. However, you can use this code as
a basis for your next game and build on it as you see necessary.
Part 2
Now that we have set up our function to handle any sprite sheets, we can
test it with our gun. First, we need to replace the static image for our gun
with the sprite sheet version.
Go to the images folder in the Raw Images folder of the My_Work_Files
folder. Copy the file named SZ_gun_SS.png to the Images folder, which
should now look like the following screenshot.
63
Chapter 5 Take a Shot: Part 1
Part 3
Next, we need to inform the code that the gun is a sprite sheet and pass all
the information about it (e.g., the image name that you copied).
We will use JavaScript to do this. Reopen the SZ_SS.js file in the js
folder. Type the following new lines (all new text is in bold):
//also the new height will be our ratio times the height of
the div containing our image
var newHeightx = heightx * ratio2;
64
Chapter 5 Take a Shot: Part 1
$(div_name).css('height', newHeightx);
//
//take the image name and apply as a background image to our div
$(div_name).css('background-image', 'url(' + image_name + ')');
65
Chapter 5 Take a Shot: Part 1
Reopen the default.html file and type the following new lines. Please
be careful to replace the existing lines of code so that the entire file looks
like the following code (all new text is in bold):
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.
jpg" onmousemove="rotateGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
66
Chapter 5 Take a Shot: Part 1
<img src="images/SZ_reload.png" />
</div>
<div id="SZ0_3" >
<img src="images/SZ_score.png" />
</div>
</div>
</body>
</html>
In this section, we set up our first sprite sheet with the following code:
setup_SpriteSheet("#SZ0_1","Images/SZ_gun_SS.png",28,150,150);
You may have noticed that we applied a special function to our image.
Let’s take a closer look at each line of this function.
67
Chapter 5 Take a Shot: Part 1
• fps:
• animations: {
We can subdivide the images within a sprite sheet into
individual animations
• duration:
• loop:
• complete: function () {
Part 4
Finally, we need to ensure that we are calling the setup_gun_SS function.
We can do this in the SZ_setupContent file, which initializes all of our
images.
Open the SZ_setupContent.js file and type the following new lines
(all new text is in bold).
68
Chapter 5 Take a Shot: Part 1
//main function
function main_call_setupContent() {
//need to resize all elements
//first we set their normal sizes in CSS
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
69
Chapter 5 Take a Shot: Part 1
Save all the files and then close them. Go back to the My_Work_Files
folder and double-click the default.html file. The gun should look exactly
the same as before. In fact, the whole screen should look the same. This is
good because we have replaced our static image of the gun with a sprite
sheet and told it to show the first image.
Next, we look at using the code we have written to animate the gun
reloading.
Well, this is great news. After all that work, I suppose it is natural to expect
something to be different. Maybe some of those animations like gun-firing
perhaps.
The fact that everything looks normal despite us removing the gun’s
image and replacing it with our massive sprite sheet image is exactly what
we wanted from our code.
Since this is a large portion of code, here are suggestions for some typical
coding errors that may have happened:
Either the gun looks a lot bigger than it should or it looks like a part of the
image has been cut off. This means that there is a problem with the way the
sprite sheet for the gun has been set up; in particular, the setup_gun_SS()
function in the SZ_SS.js file. Please recheck your code and ensure that all
the lines of code are exactly as shown.
If your code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
71
Chapter 5 Take a Shot: Part 1
Before we can test, we need to link this file and the function to the
default.html file. Reopen the default.html file and type the following
new line and an addition to an existing line (all in bold):
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg"
onmousemove="rotateGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
<img src="images/SZ_reload.png" onmousedown="reloadGun
(event)" />
</div>
<div id="SZ0_3" >
<img src="images/SZ_score.png" />
</div>
</div>
</body>
</html>
72
Chapter 5 Take a Shot: Part 1
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file.
When the screen comes up, try to click the Reload button. You should
see that the gun animates. This time, click the button a few times before
the first animation has finished. It’s not smooth, is it? We need to fix this
so that the gun does not accept a reload request until the previous one has
finished.
Reopen the SZ_touch.js file in the js folder. Type the following new
lines (in bold):
Save this file and close it. Go back to the My_Work_Files folder and
double-click the default.html file. Again, click the Reload button a few
times before the first animation has finished. The problem has been solved.
73
Chapter 5 Take a Shot: Part 1
However, we now have another issue: the game only accepts the reload
request once. We cannot make the gun reload after the first try. This is
because we have not reset our flag anywhere in our code. So let’s do that
now. Reopen the SZ_SS.js file and type the following new lines (in bold):
//also the new height will be our ratio times the height of
the div containing our image
var newHeightx = heightx * ratio2;
74
Chapter 5 Take a Shot: Part 1
75
Chapter 5 Take a Shot: Part 1
Why did the gun stop reloading after the first try?
Before we tell our code to run the reload command, we ask it if our flag
(i.e. canIclick) is set to 0. We initialize canIclick to 0 when the program
starts. Once it passes this test, the first thing the code does is set canIclick
to 1.
The next time you press the Reload button, it comes back negative—to
when asked if canIclick is 0. So ideally, we want to reset canIclick back
to 0 once the animation for reloading the gun completes. We do this in a
special subfunction of the animate command. This function specifically
asks if there are any special instructions to be executed once the animation
finishes.
76
Chapter 5 Take a Shot: Part 1
<img src="images/SZ_reload.
png" onmousedown="reloadGun(event)" /> -
As its name suggests, this calls the reloadGun function every time the
image is clicked. The following is a shortened list of the event functions
that we can use.
• onmouseenter
• onmouseleave
• onmouseover
• onmouseout
• onmouseup
77
Chapter 5 Take a Shot: Part 1
78
Chapter 5 Take a Shot: Part 1
In the future, you may have more variables to check before allowing
the user to fire the gun (e.g., if the screen was paused, or at the end of a
level). It would be a good idea at this point to create a function that checks
for all parameter values and then outputs a resulting decision. This output
would then be checked globally by other functions (such as if it is possible
to pause) and the fireGun() function when deciding whether to proceed.
Before we can test, we need to add the function into the default.html
file. Reopen the default.html file. Type the following new line (in bold)
and an addition to an existing line (modified text is in red):
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg"
onmousemove="rotateGun(event)"onmousedown="fireGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
<img src="images/SZ_reload.png"
onmousedown="reloadGun(event)" />
</div>
<div id="SZ0_3" >
79
Chapter 5 Take a Shot: Part 1
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file. Now click anywhere on the screen. The
gun should animate the firing sequence.
By now, the gun should be doing the following:
$("#SZ0_1").animateSprite("play", "fire");
How does the system know what to do with "fire"? If you go back to
the code, notice we wrote the following:
animations: {
static: [0],
reload: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,
18,19,20,21,22,23],
80
Chapter 5 Take a Shot: Part 1
fire: [24,25,26,27,28],
},
One of the animations we defined was called "fire" and it was images
24 to 28 of the individual sprite images.
Note that we inserted two mouse events into an image tag with the
following code:
This is entirely possible because (a) you can have multiple mouse
events defined for an element, and (b) the two mouse events do not
conflict with each other.
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
81
Chapter 5 Take a Shot: Part 1
cursor: crosshair;
}
img {
max-width: 100%;
height: auto;
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#SZ0_1 {
position: fixed;
bottom: 0;
right: 0;
}
#SZ0_2 {
position: fixed;
top: 0;
left: 0;
cursor: pointer;
}
82
Chapter 5 Take a Shot: Part 1
#SZ0_3 {
position: fixed;
top: 0;
right: 0;
}
Save the file and then close it. Go back to the My_Work_Files folder and
double-click the default.html file.
Now when you move the cursor over the Reload button, it should
change instantly into a normal “hand” image. Similarly, when you move
the mouse away from the Reload button, it should change back to the
cursor image.
The next chapter introduces the zombies to our game, which finally
gives our players some interactivity.
The cursor does not change to a pointer when it’s over the Reload
button?
This error may be from the HTML file. First, check that you have inserted
the this line
cursor: pointer;
83
Chapter 5 Take a Shot: Part 1
Should now be
If your code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
84
CHAPTER 6
Where Are
the Zombies?
“Measuring programming progress by lines of code is like
measuring aircraft building progress by weight.”
Bill Gates
Let’s recap what our zombies need to do in our game. We need six zombies
that will walk toward the screen. Each zombie has a sprite sheet with
its walking animation. When a zombie reaches the end of its animation
toward the screen, it needs to reset to its original position.
85
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0_6
Chapter 6 Where Are the Zombies?
86
Chapter 6 Where Are the Zombies?
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
//give it an id
div.id = 'zombie'+whichOne;
87
Chapter 6 Where Are the Zombies?
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<script src="js/SZ_zombie_movement.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg"
onmousemove="rotateGun(event)" onmousedown="fireGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
<img src="images/SZ_reload.png"
onmousedown="reloadGun(event)" />
</div>
<div id="SZ0_3" >
<img src="images/SZ_score.png" />
</div>
</div>
</body>
</html>
88
www.allitebooks.com
Chapter 6 Where Are the Zombies?
Save the file and then close it. Now we can go ahead and further
develop our zombie sprite sheets. Reopen the SZ_SS file in your js folder.
Type the following new lines (all new text is in bold):
//also the new height will be our ratio times the height of
the div containing our image
var newHeightx = heightx * ratio2;
89
Chapter 6 Where Are the Zombies?
//take the image name and apply as a background image to our div
$(div_name).css('background-image', 'url(' + image_name + ')');
90
Chapter 6 Where Are the Zombies?
setup_SpriteSheet("#zombie"+whichOne,"Images/
zombiesSS_"+type_zombie[whichOne-1]+".png",9,20,20);
//need to access a special function in our js/ss.js file
$("#zombie"+whichOne).animateSprite({
fps: 10,
animations: {
static: [0,1,2,3,4,5,6,7],
},
duration: speed_zombie[type_zombie[whichOne-1]-1],
loop: true,
complete: function () {
// use complete only when you set animations with
'loop: false'
//alert("animation End");
}
});
}
91
Chapter 6 Where Are the Zombies?
We now need to call this function in our setup file to create a zombie.
Reopen the SZ_setupContent file in your js folder and type the following
new lines (all new text is in bold):
//main function
function main_call_setupContent() {
//need to resize all elements
//first we set their normal sizes in CSS
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
//Create a zombie
SZ_createZombie(1);
}
We are now ready to test! Save all the files and then close them. Go
back to your My_Work_Files folder and double-click the default.html file.
What you should see is a scientist zombie at the edge of the planet surface.
If you click your browser’s Refresh button (alternatively, you could press
F5), the zombie should appear in a different location (yet still at the edge of
the planet surface). Continue to refresh a few times and test this behavior.
92
Chapter 6 Where Are the Zombies?
We have now managed to spawn a zombie in our game! Our next step
will be to make our zombie come toward us.
• We are using arrays for the first time (see the “Further
Information” section about what arrays are). Ensure
that you are using the square brackets located next to
the P key on your keyboard.
Three exciting features in this section. Let’s explore them a little more.
93
Chapter 6 Where Are the Zombies?
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
//give it an id
div.id = 'zombie'+whichOne;
95
Chapter 6 Where Are the Zombies?
96
Chapter 6 Where Are the Zombies?
}
}, complete: function () {
}
});
}
Save this file and then close it. Go back to the My_Work_Files folder
and double-click the default.html file.
When the screen comes up, you should see the zombie coming toward
you! Depending on your screen resolution, the zombie may overstep the
edge or stop a little before it should. Do not worry about that; we will
handle it in Chapter 8.
Next, let’s look into creating all the zombies that we need for the game.
The following array has text values, but what are they?
These values are what we use for our easing function. An easing
function specifies a zombie’s rate of change over time. The simplest and
most widely used easing value is a linear one. This is where the zombie
moves at a constant speed for the duration of its walk. That would be a
little boring and unrealistic, however.
97
Chapter 6 Where Are the Zombies?
98
Chapter 6 Where Are the Zombies?
//Create a zombie
SZ_createZombie(1);
//main function
function main_call_setupContent() {
//need to resize all elements
//first we set their normal sizes in CSS
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
100
Chapter 6 Where Are the Zombies?
Do not worry about these issues too much at this stage. All of these
concerns are addressed in Chapter 8. Next, we will look at recycling the life
of our zombie so that once it finishes, the element is ready for our program
to use again.
In this section, we came across a for loop to create our six zombies:
By using this loop, we eliminated the need to write the same code to
create a zombie six times. If that had been the case, then imagine if we
were to create 100 zombies!
As shown in the example, loops are essential if you want to run the
same code over and over again with a different value.
101
Chapter 6 Where Are the Zombies?
Here are four different kinds of loops that we can use in our game:
102
Chapter 6 Where Are the Zombies?
//give it an id
div.id = 'zombie'+whichOne;
103
Chapter 6 Where Are the Zombies?
104
Chapter 6 Where Are the Zombies?
//finally let’s make the zombie come towards the screen again
SZ_animateZombie(whichOne);
}
105
Chapter 6 Where Are the Zombies?
Did it not work? This could be due to a few lines that we added around
some existing code. Let’s have a look.
The original line of code was
$zombiex. animate({
Make sure that the new line of code looks like this:
$zombiex.delay(timex[whichOne-1]/2).animate({
Make sure that the new line of code looks like this:
If your code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
106
CHAPTER 7
The good news is that we are near the end. The slightly bad news is that
there will be a fair bit of coding in this chapter. So what will we see at the
end of this chapter?
H
itting a Zombie
You may have noticed that when you try to click a zombie, the gun does
not fire. This is because we have not bound a mouse-click event to the
zombie elements. We can place this mouse-click code in the function
where we create each zombie.
107
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0_7
Chapter 7 Take a Shot: Part 2
Open the SZ_zombie_movement.js file and type the following new lines
(all new text is in bold):
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
//give it an id
div.id = 'zombie'+whichOne;
108
Chapter 7 Take a Shot: Part 2
109
Chapter 7 Take a Shot: Part 2
110
Chapter 7 Take a Shot: Part 2
Navigate to the menu, click File, and then click Save. You can now close
this file.
We are now ready to test! Go back to the My_Work_Files folder and
double-click the default.html file. You should see the gun firing when you
click over any of the zombies coming toward the screen.
This was made possible by adding 'mousedown touchstart' events to
each zombie’s div. When revisiting this project, you may wish to consider
installing a “headshot” type of feature. For this to work, you need to do the
following:
3. If this new div is hit, then give the user more points.
111
Chapter 7 Take a Shot: Part 2
In this line, we have not only bound the mousedown event to each zombie,
but also defined the instructions that execute when that event occurs.
Did the code not work? Check to see if you have typed whichOne (make
sure that the O is a capital letter) in the new code that you have written.
When writing any code from this book, it is extremely important to
be aware that JavaScript makes a sharp distinction between capital and
lowercase letters.
112
Chapter 7 Take a Shot: Part 2
To keep track of the number of hits each zombie has taken, we need to
use an array. Also, we need to remember to reset each zombie’s hit count
when it resets.
Open the SZ_zombie_movement.js file and type the following new lines
(all new text is in bold):
113
Chapter 7 Take a Shot: Part 2
//give it an id
div.id = 'zombie'+whichOne;
}
}
}, complete: function () {
}
});
}
//a function to completely reset our zombie
function SZ_resetZombie(whichOne){
116
Chapter 7 Take a Shot: Part 2
If you are developing levels for this game in the future, you want to add
a check before resetting the zombie. For example, if the result of killing
a zombie is a new level, then rather than just resetting that particular
zombie, you want to reset all the zombies. I would even go as far as making
this operation its own function, which performed all of these checks.
Open the SZ_touch.js file in the js folder. Type the following new
lines (all new text is in bold):
117
Chapter 7 Take a Shot: Part 2
//this function will keep track of the zombie hits and act
accordingly
function zombieHit(whichOne){
Save and close this file. We are now ready to test! Go back to the
My_Work_Files folder and double-click the default.html file.
Now, the zombies should reset before they reach the screen when we
have fired on them the correct number of times. So if we fire once on the
female zombie, she should reset immediately. Similarly, if we fire three
times on the male zombie, he should reset. Finally, if we fire twice on the
scientist zombie, then he should reset.
Next, I introduce our bubble zombies.
118
Chapter 7 Take a Shot: Part 2
• == (equal to)
Zombie Down!
When a zombie has been hit the maximum number of times, it is reset. We
also need the zombie to appear in a bubble, however, to give the illusion
that the zombie has been subdued and dealt with in the game.
To do this, the following needs to completed.
119
Chapter 7 Take a Shot: Part 2
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
121
Chapter 7 Take a Shot: Part 2
122
Chapter 7 Take a Shot: Part 2
123
Chapter 7 Take a Shot: Part 2
//also the new height will be our ratio times the height of
the div containing our image
var newHeightx = heightx * ratio2;
},
duration: 50,
loop: false,
complete: function () {
// use complete only when you set animations with
'loop: false'
//alert("animation End");
//we need to reset our universal flag
canIclick=0;
}
});
}
setup_SpriteSheet("#zombie"+whichOne,"Images/zombiesSS_"+type_
zombie[whichOne-1]+".png",9,20,20);
//need to access a special function in our js/ss.js file
$("#zombie"+whichOne).animateSprite({
fps: 10,
animations: {
static: [0,1,2,3,4,5,6,7],
},
duration: speed_zombie[type_zombie[whichOne-1]-1],
loop: true,
126
Chapter 7 Take a Shot: Part 2
complete: function () {
// use complete only when you set animations with
'loop: false'
//alert("animation End");
}
});
Did the code not work? Check to see if you have typed div2 in the new
code you have written in SZ_zombie_movement.js.
Also in the new code for SZ_SS.js, make sure that you have typed
bubble_zombie and not just zombie (as per the preceding code).
If the code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
128
Chapter 7 Take a Shot: Part 2
129
Chapter 7 Take a Shot: Part 2
130
Chapter 7 Take a Shot: Part 2
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
131
Chapter 7 Take a Shot: Part 2
132
Chapter 7 Take a Shot: Part 2
133
Chapter 7 Take a Shot: Part 2
134
Chapter 7 Take a Shot: Part 2
//finally let's make the zombie come towards the screen again
SZ_animateZombie(whichOne);
}
You can now save and close this file. There is more code to write,
however, let’s quickly test what we have so far. Go back to the My_Work_
Files folder and double-click the default.html file. You should observe
the following changes in our game:
• Please note that you may notice that the zombies may
stop coming all together. This has been done on purpose
for some code that we will write later. For now, just refresh
your browser (press F5) and the game should restart.
Did the code not work? First, check to see that you have modified the SZ_
resetZombie function to include an extra parameter (this code is in red):
Also, the two times that we call this function need to be modified.
Please make sure that your calls look like the following code:
In SZ_touch.js
SZ_resetZombie(whichOne+1,1);
And in SZ_zombie_movement.js
SZ_resetZombie(whichOne,0);
Finally, ensure that the following lines are placed exactly as shown (i.e.,
outside the function call):
If the code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
136
Chapter 7 Take a Shot: Part 2
function rotateGun(e) {
complete: function () {
//now the final animation where the bubble
zombie disappears into space
137
Chapter 7 Take a Shot: Part 2
$(this).delay(150).animate({
//slowly turn the alpha down
opacity: "-="+1,
},{ easing:"easeOutQuint", duration: 1000,
$(this).animate({
I would like to add that this delay() method is best for only certain
game engines where you are delaying between queued jQuery effects. It
doesn't offer a way to cancel the delay; therefore, in certain cases, delay()
is not a replacement for JavaScript's native setTimeout function, which
may be more appropriate.
Next, we need to call our new function. Open the SZ_zombie_
movement.js file in the js folder. Carefully modify some old lines and type
the following new lines (all modified and new text is in bold):
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
139
Chapter 7 Take a Shot: Part 2
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
140
Chapter 7 Take a Shot: Part 2
142
Chapter 7 Take a Shot: Part 2
143
Chapter 7 Take a Shot: Part 2
You can now save and close this file. We are now ready to test our code.
Go back to the My_Work_Files folder and double-click the default.html
file. You should now see the bubble zombies animate upward and then
away into the distance.
Again, please note that you may notice that the zombies may stop
coming all together. This was done on purpose for some code that we will
write later. For now, just refresh your browser (press F5) and the game
should restart.
Next, we will only allow a certain number of shots from our gun before
it needs to be reloaded.
Did the code not work? First, check to see that you have modified the SZ_
resetZombie function to include an extra parameter (the code in red):
and
Also, the tail end of the code in the SZ_movement.js file has a few
repetitive characters. Please make sure that they are all written as shown here:
}
}, complete: function () {
}//end of second complete function
});//end of second animation
144
Chapter 7 Take a Shot: Part 2
If the code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
What is opacity?
145
Chapter 7 Take a Shot: Part 2
The && means logical AND (i.e., if the fx property is opacity AND the
fx position is greater than or equal to 0.1).
The reason we needed to place this check for the position is because
the first value is almost always 0. If we allowed this, then we would be
dividing by zero, which, of course, is undefined. This would lead to
problems and indeterminable behavior.
Finally, we take this value and place it as a scale value for the bubble
zombie. Over time, this makes the bubble zombie appear smaller, thus
giving it the impression of disappearing into the distance.
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
cursor: crosshair;
}
img {
max-width: 100%;
146
Chapter 7 Take a Shot: Part 2
height: auto;
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#SZ0_1 {
position: fixed;
bottom: 0;
right: 0;
}
#SZ0_2 {
position: fixed;
top: 0;
left: 0;
cursor: pointer;
opacity:0;
}
#SZ0_3 {
position: fixed;
top: 0;
right: 0;
}
147
Chapter 7 Take a Shot: Part 2
148
Chapter 7 Take a Shot: Part 2
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
149
Chapter 7 Take a Shot: Part 2
154
Chapter 7 Take a Shot: Part 2
//this function will keep track of the zombie hits and act
accordingly
function zombieHit(whichOne){
155
Chapter 7 Take a Shot: Part 2
How does the code know when to fire and reload the gun?
This is a good question and I would like to point out that the code you
have just entered is probably one of the more complex and interesting we
have written to date. There are two steps to determining the answer to this
question: (1) check and set the opacity of the Reload button, and (2) check
the number of shots fired against the maximum allowed. So let’s take a
closer look at what we wrote.
You will have noticed we deal a lot with opacity; for instance, the first
portion of code we wrote was
opacity:0;
$("#SZ0_2").css('opacity') != 1
var max_shots=5;
var current_shots=0;
156
Chapter 7 Take a Shot: Part 2
Now every time a shot is fired, we can compare the two variables, as
follows:
if(current_shots>=max_shots){
If this is true, we stop any further shots and force the user to reload
their gun.
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
157
Chapter 7 Take a Shot: Part 2
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
158
Chapter 7 Take a Shot: Part 2
159
Chapter 7 Take a Shot: Part 2
160
Chapter 7 Take a Shot: Part 2
SZ_resetZombie(whichOne,0);
} else {
//apply the scale
$(this).css('transform',
'scale('+xx+')');
//record this new scale value
scalex_zombie[whichOne-1]=xx;
}
}
}, complete: function () {
}
});
}
//a function to completely reset our zombie
function SZ_resetZombie(whichOne, zombieBubble_generate){
161
Chapter 7 Take a Shot: Part 2
$bubble_zombiex.css({top: top_position+'px',left:
$zombiex.css("left"), opacity:1});
//apply the scale
$bubble_zombiex.css('transform',
'scale('+scalex_zombie[whichOne-1]+')');
//call our bubble zombie animation function
bubbleZombie_flyAway(whichOne);
}
162
Chapter 7 Take a Shot: Part 2
163
Chapter 7 Take a Shot: Part 2
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
164
Chapter 7 Take a Shot: Part 2
165
Chapter 7 Take a Shot: Part 2
166
Chapter 7 Take a Shot: Part 2
167
Chapter 7 Take a Shot: Part 2
168
Chapter 7 Take a Shot: Part 2
169
Chapter 7 Take a Shot: Part 2
$("#zombie"+whichOne).css("z-index", zindex_current);
//finally let's make the zombie come towards the screen
again
//SZ_animateZombie(whichOne);
}
The z-index is the order of each element. Imagine that all of our elements,
such as the gun image or the score image, are lined up like a pack of cards.
If you slightly spread the cards, you see the top card fully while the ones
underneath are only slightly visible. This is because when cards overlap,
the visibility of one particular card depends on its location from the top.
In the same way, when our elements overlap each other, their visibility
depends on their stack order or z-index. So an element with a bigger
z-index will be more visible when overlapped with an element of a lower
z-index.
170
Chapter 7 Take a Shot: Part 2
This really becomes useful when our zombies, which are continuously
randomly placed, start to overlap each other. JavaScript allows us to
manipulate the z-indices, and therefore we can program the elements
to reorder to ensure that elements that are further away from us are kept
behind those elements that are closer.
while (i < 6) {
171
Chapter 7 Take a Shot: Part 2
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<script src="js/SZ_zombie_movement.js"></script>
172
Chapter 7 Take a Shot: Part 2
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
cursor: crosshair;
}
173
Chapter 7 Take a Shot: Part 2
img {
max-width: 100%;
height: auto;
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#SZ0_1 {
position: fixed;
bottom: 0;
right: 0;
opacity:0;
}
#SZ0_2 {
position: fixed;
top: 0;
left: 0;
cursor: pointer;
opacity:0;
}
174
Chapter 7 Take a Shot: Part 2
#SZ0_3 {
position: fixed;
top: 0;
right: 0;
opacity:0;
}
#SZ0_4 {
position: fixed;
cursor: pointer;
background-size:cover;
opacity:0;
}
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
175
Chapter 7 Take a Shot: Part 2
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
var gameEnded=0;
//Intro or Game Over of game
function start_end_game(whichOne) {
176
Chapter 7 Take a Shot: Part 2
if(whichOne==0){
//START OF GAME
//change the background image
$('#SZ0_4').css('background-image', 'url(images/
splash_intro.png)');
} else {
//GAME OVER
//show the score
$('#SZ0_3').css({opacity:1});
//change the background image
$('#SZ0_4').css('background-image',
'url(images/splash_gameover.png)');
}
//make sure it is half way
$('#SZ0_4').css('top', ($(window).height()/2)-
((701 * ratio_use)/2));
//finally show the intro or game over image
$('#SZ0_4').css({opacity:1});
//stop the user from firing
177
Chapter 7 Take a Shot: Part 2
gameEnded= 1;
}//end of function
//start the game
function start_game() {
//reset the zindex
zindex_current=0;
}//end of function
178
Chapter 7 Take a Shot: Part 2
179
Chapter 7 Take a Shot: Part 2
//this function will keep track of the zombie hits and act
accordingly
function zombieHit(whichOne){
180
Chapter 7 Take a Shot: Part 2
zombieHits_counter[whichOne]++;
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
182
Chapter 7 Take a Shot: Part 2
}
});
183
Chapter 7 Take a Shot: Part 2
184
Chapter 7 Take a Shot: Part 2
//at each step we can manipulate the scale of
our zombie
if (fx.prop == "left") {
//work out the amount to scale
var xx = (fx.pos)*16;
if(gameEnded==1){
xx=999;
}
//do a check to see if we should end this
animation
if(xx>15){
//stop all animation
$(this).stop();
//call a function to reset this zombie
//SZ_resetZombie(whichOne,0);
//game Over
$(this).css({opacity:0});
$(this).stop(true, true);
$(this).finish();
if(gameEnded==0 && xx!=999){
start_end_game(1);
}
} else {
//apply the scale
$(this).css('transform',
'scale('+xx+')');
//record this new scale value
scalex_zombie[whichOne-1]=xx;
185
Chapter 7 Take a Shot: Part 2
186
Chapter 7 Take a Shot: Part 2
$("#zombie"+whichOne).css("z-index", zindex_current);
188
Chapter 7 Take a Shot: Part 2
Did the code not work? We changed a lot of files here, so the advice I give
is to meticulously go through every line of code in each of the files and
compare it to your own. Even the old grayed out code. Have patience and
work through your code.
Here are some problems that I identified:
Make sure that you have the closing tag (shown in red) in the following
line:
Make sure that you place this line above the main function:
Make sure that you are using ratio_use and not ratio in the following
lines:
Make sure that you have commented out (//)the following lines:
// SZ_animateZombie(whichOne);
//SZ_resetZombie(whichOne,0);
If the code is still not working, then please do not hesitate to message
me on Twitter @zarrarchishti.
189
Chapter 7 Take a Shot: Part 2
How does the game know when to show the Intro Splash screen and
when to show the Game Over screen?
When called, the following function stops the game and shows either the
introduction or the Game Over screen:
function start_end_game(whichOne) {
One of the tasks of this function is to show either the intro image or the
Game Over image, depending on the whichOne passed parameter in. The
following lines will show either of those images:
$('#SZ0_4').css('background-image', 'url(images/
splash_intro.png)');
$('#SZ0_4').css('background-image', 'url(images/
splash_gameover.png)');
190
CHAPTER 8
I am sure you have noticed that there is no actual score in our Score box.
What we need in there is some text that increments every time we send a
zombie off into space. To do this, we need to do the following:
191
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0_8
Chapter 8 Add Some Bling to Our Game
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<script src="js/SZ_zombie_movement.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg"
onmousemove="rotateGun(event)" onmousedown="fireGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
<img src="images/SZ_reload.png"
onmousedown="reloadGun(event)" />
</div>
<div id="SZ0_3" style="background-image: url
(images/SZ_score.png);">
<div id="textx">0</div>
</div>
192
Chapter 8 Add Some Bling to Our Game
html {
height: 100%;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
cursor: crosshair;
}
img {
max-width: 100%;
height: auto;
user-drag: none;
user-select: none;
193
Chapter 8 Add Some Bling to Our Game
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
#SZ0_0 {
position: fixed;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#SZ0_1 {
position: fixed;
bottom: 0;
right: 0;
opacity:0;
}
#SZ0_2 {
position: fixed;
top: 0;
left: 0;
cursor: pointer;
opacity:0;
}
#SZ0_3 {
position: fixed;
top: 0;
right: 0;
opacity:0;
background-size:cover;
}
194
Chapter 8 Add Some Bling to Our Game
#SZ0_4 {
position: fixed;
cursor: pointer;
background-size:cover;
opacity:0;
}
#textx {
position: relative;
float: left;
top: 40%;
text-align:center;
font-size: 4vmax;
font-weight: bolder;
colour: white;
font-family: "Arial Black";
}
//main function
function main_call_setupContent() {
//need to resize all elements
//first we set their normal sizes in CSS
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
195
Chapter 8 Add Some Bling to Our Game
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
$('#textx').css('width', '100%');
$('#textx').css('height', '50%');
196
Chapter 8 Add Some Bling to Our Game
var gameEnded=0;
//Intro or Game Over of game
function start_end_game(whichOne) {
//hide the elements
for (i = 1; i < 4; i++) {
//this will get called 3 times
$('#SZ0_'+i).css({opacity:0});
}//for
if(whichOne==0){
//START OF GAME
//change the background image
$('#SZ0_4').css('background-image',
'url(images/splash_intro.png)');
} else {
//GAME OVER
//show the score
$('#SZ0_3').css({opacity:1});
//change the background image
197
Chapter 8 Add Some Bling to Our Game
$('#SZ0_4').css('background-image',
'url(images/splash_gameover.png)');
}
}//end of function
}//end of function
199
Chapter 8 Add Some Bling to Our Game
function rotateGun(e) {
//We will work this out by dividing the current X position by the
overall screen width which if you remember we put in newWidth
var currentXPositionPercentage = xPos/newWidth;
200
Chapter 8 Add Some Bling to Our Game
201
Chapter 8 Add Some Bling to Our Game
Did this not work? If not, it is most likely the code written in default.html.
Originally, the code was this:
Please make sure that you have coded the lines exactly as shown.
If the code is still not working, then please do not hesitate to message
me on Twitter (@zarrarchishti).
202
Chapter 8 Add Some Bling to Our Game
var current_score=0;
current_score++;
updateScore(){ :
$("#textx").text(current_score);
This replaces the text in our text div with the value in the current score
variable. At this point, the screen text value changes.
203
Chapter 8 Add Some Bling to Our Game
204
Chapter 8 Add Some Bling to Our Game
//we want to position our zombie exactly at the tip of the planet
var top_position= $('#SZ0_0').height() * 0.435;
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
//also for our special effect SS
div3.id = 'zombie_effect'+whichOne;
205
Chapter 8 Add Some Bling to Our Game
206
Chapter 8 Add Some Bling to Our Game
fireGun(event);
//acknowledge the hit
if($("#zombie"+whichOne).css('opacity') != 0){
var offset = $(this).offset();
zombieHit(whichOne-1, e.pageX, e.pageY);
}
}
});
}
});
207
Chapter 8 Add Some Bling to Our Game
208
Chapter 8 Add Some Bling to Our Game
209
Chapter 8 Add Some Bling to Our Game
$(this).css("z-index",
i_index);
} //end of if
i++;
}//end of while loop
}
}
}, complete: function () {
}
});
}
210
Chapter 8 Add Some Bling to Our Game
//finally let's make the zombie come towards the screen again
if(zombieBubble_generate==0){
SZ_animateZombie(whichOne);
}
}
211
Chapter 8 Add Some Bling to Our Game
//this function will keep track of the zombie hits and act
accordingly
function zombieHit(whichOne, xx, yy){
$effect_zombiex.css('transform',
'scale('+scalex_zombie[whichOne]+')');
}
214
Chapter 8 Add Some Bling to Our Game
//also the new height will be our ratio times the height of
the div containing our image
var newHeightx = heightx * ratio2;
215
Chapter 8 Add Some Bling to Our Game
setup_SpriteSheet("#zombie"+whichOne,"Images/zombiesSS_"
+type_zombie[whichOne-1]+".png",9,20,20);
//need to access a special function in our js/ss.js file
$("#zombie"+whichOne).animateSprite({
fps: 10,
animations: {
static: [0,1,2,3,4,5,6,7],
},
duration: speed_zombie[type_zombie[whichOne-1]-1],
loop: true,
complete: function () {
// use complete only when you set animations with
'loop: false'
//alert("animation End");
}
});
setup_SpriteSheet("#bubble_zombie"+whichOne,
"Images/SZ_bubble.png",3,20,20);
//need to access a special function in our js/ss.js file
$("#bubble_zombie"+whichOne).animateSprite({
fps: 10,
animations: {
z1: [type_zombie[whichOne-1]-1],
},
duration: 1,
loop: false,
217
Chapter 8 Add Some Bling to Our Game
complete: function () {
// use complete only when you set animations with
'loop: false'
//alert("animation End");
}
});
//not to forget our special effects SS
setup_SpriteSheet("#zombie_effect"+whichOne,"Images/SZ_effect_
ss.png",4,13,15);
//need to access a special function in our js/ss.js file
$("#zombie_effect"+whichOne).animateSprite({
fps: 10,
animations: {
z1: [0,1,2,3],
},
duration: 20,
loop: false,
complete: function () {
// use complete only when you set animations with
'loop: false'
//alert("animation End");
$("#zombie_effect"+whichOne).css({opacity:0});
}
});
}
218
Chapter 8 Add Some Bling to Our Game
To position the special effects, we first need to ensure that we pass through
the x and y coordinates when there is a mouse click on a zombie. We do
this in SZ_zombie_movement.js.
The offset() method returns the coordinates for us. We can then
pass them through to our zombieHit function. This means that we have to
modify the zombieHit function in SZ_touch.js.
We have added two variables that can be passed in for us to use now.
So when we come to position our special effect, we can use our two
new variables for the x and y positions.
219
Chapter 8 Add Some Bling to Our Game
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="sounds/jquery.playSound.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
220
Chapter 8 Add Some Bling to Our Game
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<script src="js/SZ_zombie_movement.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg"
onmousemove="rotateGun(event)" onmousedown="fireGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
<img src="images/SZ_reload.png"
onmousedown="reloadGun(event)" />
</div>
<div id="SZ0_3" style="background-image:
url(images/SZ_score.png);">
<div id="textx">999</div>
</div>
<div id="SZ0_4" onmousedown="start_game();"/>
</div>
</body>
</html>
221
Chapter 8 Add Some Bling to Our Game
Open the SZ_touch.js file and type the following new lines (all new
text is in bold):
222
Chapter 8 Add Some Bling to Our Game
//this function will keep track of the zombie hits and act
accordingly
function zombieHit(whichOne, xx, yy){
223
Chapter 8 Add Some Bling to Our Game
$effect_zombiex.animateSprite("play", "z1");
//apply the scale
$effect_zombiex.css('transform',
'scale('+scalex_zombie[whichOne]+')');
}
Did the sound not work? First, make sure that you have written the
following line as it is shown in your default.html.
<script src="sounds/jquery.playSound.js"></script>
Also, make sure that you have the sounds folder copied, as shown in
Part 1.
224
Chapter 8 Add Some Bling to Our Game
If it is still not working, make sure that the following lines are copied as
shown here; pay attention to the lowercase letters.
$.playSound('sounds/reload');
$.playSound('sounds/fire');
225
Chapter 8 Add Some Bling to Our Game
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="sounds/jquery.playSound.js"></script>
<script src="js/SZ_main.js"></script>
<script src="js/SZ_setupContent.js"></script>
<script src="js/SZ_movement.js"></script>
<script src="js/ss.js"></script>
<script src="js/SZ_SS.js"></script>
<script src="js/SZ_touch.js"></script>
<script src="js/SZ_zombie_movement.js"></script>
<link href="css/SZ_master.css" rel="stylesheet" />
</head>
<body>
<div id="logo"></div>
<div id="box1"></div>
<div id="SZ_maincontent">
<img id="SZ0_0" src="images/SZ_background_image.jpg"
onmousemove="rotateGun(event)" onmousedown="fireGun(event)" />
<div id="SZ0_1" ></div>
<div id="SZ0_2" >
<img src="images/SZ_reload.png" onmousedown="reloadGun
(event)" />
</div>
<div id="SZ0_3" style="background-image:
url(images/SZ_score.png);">
226
Chapter 8 Add Some Bling to Our Game
<div id="textx">999</div>
</div>
<div id="SZ0_4" onmousedown="start_game();"/>
</div>
</body>
</html>
html {
height: 100%;
background: url(../html_web/webBG.jpg);
background-size:cover;
}
body {
padding: 0 0 0 0;
margin: 0;
user-select: none;
cursor: crosshair;
}
img {
max-width: 100%;
height: 100%;
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
227
Chapter 8 Add Some Bling to Our Game
}
#logo {
position: absolute;
z-index:9999;
background: url(../html_web/logo.png);
background-size:cover;
pointer-events:none;
}
#box1 {
position: absolute;
z-index:9998;
background: url(../html_web/box.png);
background-size:cover;
pointer-events:none;
}
#SZ_maincontent {
position: relative;
overflow: hidden;
}
#SZ0_0 {
position: absolute;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#SZ0_1 {
position: absolute;
bottom: 0;
right: 0;
opacity:0;
}
228
Chapter 8 Add Some Bling to Our Game
#SZ0_2 {
position: absolute;
top: 0;
left: 0;
cursor: pointer;
opacity:0;
}
#SZ0_3 {
position: absolute;
top: 0;
right: 0;
opacity:0;
background-size:cover;
}
#SZ0_4 {
position: absolute;
cursor: pointer;
background-size:cover;
opacity:0;
}
#textx {
position: relative;
float: left;
top: 40%;
text-align:center;
font-size: 4vmax;
font-weight: bolder;
colour: white;
font-family: "Arial Black";
}
229
Chapter 8 Add Some Bling to Our Game
//main function
function main_call_setupContent() {
//need to resize all elements
//first we set their normal sizes in CSS
//Main Div
$('#SZ_maincontent').css('width', 600 * ratio);
$('#SZ_maincontent').css('height', 400 * ratio);
//make sure it is half way
$('#SZ_maincontent').css('left',
($(window).width()/2)-((600 * ratio)/2));
$('#SZ_maincontent').css('top',
($(window).height()/2)-((400 * ratio)/2));
//box1
$('#box1').css('width', 631 * ratio);
$('#box1').css('height', 457 * ratio);
//make sure it is half way
$('#box1').css('left', ($(window).width()/2)-
((637 * ratio)/2));
$('#box1').css('top', ($(window).height()/2)-
((457 * ratio)/2));
//logo
$('#logo').css('width', 400 * ratio);
$('#logo').css('height', 146 * ratio);
230
Chapter 8 Add Some Bling to Our Game
//Gun
$('#SZ0_1').css('width', 150 * ratio);
$('#SZ0_1').css('height', 150 * ratio);
//Reload Button
$('#SZ0_2').css('width', 200 * ratio);
$('#SZ0_2').css('height', 90 * ratio);
//Score
$('#SZ0_3').css('width', 235 * ratio);
$('#SZ0_3').css('height', 100 * ratio);
$('#textx').css('width', '100%');
$('#textx').css('height', '50%');
231
Chapter 8 Add Some Bling to Our Game
//Our Gun
setup_gun_SS();
var gameEnded=0;
//Intro or Game Over of game
function start_end_game(whichOne) {
//hide the elements
for (i = 1; i < 4; i++) {
//this will get called 3 times
$('#SZ0_'+i).css({opacity:0});
}//for
if(whichOne==0){
//START OF GAME
232
Chapter 8 Add Some Bling to Our Game
}//end of function
}//end of function
234
Chapter 8 Add Some Bling to Our Game
235
Chapter 8 Add Some Bling to Our Game
//give it an id
div.id = 'zombie'+whichOne;
//also for our bubble zombie
div2.id = 'bubble_zombie'+whichOne;
//also for our special effect SS
div3.id = 'zombie_effect'+whichOne;
236
Chapter 8 Add Some Bling to Our Game
237
Chapter 8 Add Some Bling to Our Game
}
});
}
238
Chapter 8 Add Some Bling to Our Game
240
Chapter 8 Add Some Bling to Our Game
241
Chapter 8 Add Some Bling to Our Game
//finally let's make the zombie come towards the screen again
if(zombieBubble_generate==0){
SZ_animateZombie(whichOne);
}
242
Chapter 8 Add Some Bling to Our Game
You will agree that, with just a few tweaks of code, we have created a
huge improvement in the overall design of our game.
Did it not work? A lot of the code written here are changes to code that was
already written. It is important to go through the bolded code line by line
and ensure that it looks exactly as shown.
Pay careful attention to the changes in SZ_master.css, especially
where we have added the same line to several places.
Finally, take care with changes like this:
// $('#SZ0_4').css('left', ($(window).width()/2)-
((600 * ratio_use)/2));
Please make sure that you have coded the lines exactly as shown.
If it is still not working, then please do not hesitate to message me on
Twitter (@zarrarchishti).
243
Chapter 8 Add Some Bling to Our Game
The game itself is exactly the same; all we did was reduce the amount of
space the game takes on the screen:
<div id="box1"></div>
<div id="logo"></div>
244
Chapter 8 Add Some Bling to Our Game
245
Chapter 8 Add Some Bling to Our Game
Let me know what other games you managed to create using this
engine. Join me on Twitter (@zarrarchishti) and let’s discuss!
246
Index
A D
Absolute, 35 delay() method, 139
alert(), 41, 127, 128 Depth levels, 163–171
animateSprite function, 66 Depths and click zones, 157–171
Animation, 13, 23, 51, 66, 68, 70, 73, div, 17, 45, 94, 111
76, 80, 81, 85, 95, 136, 148, do/while loop, 102
203, 245 duration function, 68
appendChild(), 124
Aptana, 6
Arrays, 47, 93, 94, 97, 113 E
easeInOutQuad, 98
easeInSine, 98
B easeOutQuart, 98
Background-colour, 27 Easing function, 97, 98, 145
Background image, 2, 3, 18–20, 22, Eclipse, 6
28–31, 193 Embedding, 3, 225–244
e.pageX and e.pageY
properties, 212
C
Cascading Style Sheets (CSS), 23–35
Cloud hosting, 11 F
Coding errors, 70 File, 6–14, 226–244
Conditional statements, 119 Fireworks, 50
Counter, 129–136 Fixed, 26, 35
Crosshair cursor, 51, 53, 81, 100 for/in loops, 102
CSSOM View Module, 212 Frames per second (fps), 68
247
© Zarrar Chishti 2017
Z. Chishti, Cross Over to HTML5 Game Development,
https://doi.org/10.1007/978-1-4842-3291-0
Index
G M
Gameplay, 3, 18, 55, 81, 245 Macromedia Photoshop, 50
Gun fire, 57, 60, 62, 70, 76, 78, 111, main_call_setupContent()
157–163 function, 50
Gun reloading, 62, 70, 74, 78 Margin, 26, 27
Math.floor(), 94
Math functions, 94
H Math.random(), 94
Hardware acceleration, 23 Max-width, 31
Hits count, 113–119 Min-width, 31
Hitting zombie, 107–113 Mousedown touchstart events, 111
Hosting server, 10–11
Hypertext Markup Language
(HTML), 15–22 N
NetBeans, 6
newWidth, 45
I
Image resizing, 46–50
<img>, 19, 30 O
insertBefore(), 124 offset() method, 219
onmouseenter, 77
onmouseleave, 77
J, K onmouseout, 77
JavaScript code, 40, 45, 50, 112 onmouseover, 77
onmouseup, 77
Opacity, 145, 156
L
Life cycle generation, 102–106
load(function (), 45 P, Q
Loop option, 68 Padding, 26
Low memory usage, 62 Pascal coding, 42
248
Index
249