Full Download (Ebook) Introducing JavaScript Game Development : Build a 2D Game from the Ground Up by Graeme Stuart ISBN 9781484232514, 9781484232521, 1484232518, 1484232526 PDF DOCX
Full Download (Ebook) Introducing JavaScript Game Development : Build a 2D Game from the Ground Up by Graeme Stuart ISBN 9781484232514, 9781484232521, 1484232518, 1484232526 PDF DOCX
com
DOWLOAD EBOOK
ebooknice.com
ebooknice.com
ebooknice.com
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
ebooknice.com
ebooknice.com
Introducing
JavaScript Game
Development
Build a 2D Game from the Ground Up
—
Graeme Stuart
Introducing
JavaScript Game
Development
Build a 2D Game from
the Ground Up
Graeme Stuart
Introducing JavaScript Game Development
Graeme Stuart
Market Harborough, Leicestershire, United Kingdom
Part I: Drawing����������������������������������������������������������������������������������1
Chapter 1: HTML5 and the Canvas Element������������������������������������������3
HTML Primer���������������������������������������������������������������������������������������������������������3
Drawing to the Canvas������������������������������������������������������������������������������������������5
Style the Page to Highlight the Canvas�����������������������������������������������������������������7
Experiment with fillStyle���������������������������������������������������������������������������������������9
Rendering Text����������������������������������������������������������������������������������������������������10
More Shapes and Lines���������������������������������������������������������������������������������������13
Summary������������������������������������������������������������������������������������������������������������16
iii
Table of Contents
iv
Table of Contents
Chapter 9: Inheritance����������������������������������������������������������������������125
Set Up a Template���������������������������������������������������������������������������������������������125
Newton’s Laws of Motion����������������������������������������������������������������������������������127
A General-Purpose Mass Class�������������������������������������������������������������������������128
A Simple Approach to Inheritance���������������������������������������������������������������������133
Asteroids�����������������������������������������������������������������������������������������������������������134
The Ship������������������������������������������������������������������������������������������������������������137
Summary����������������������������������������������������������������������������������������������������������140
v
Table of Contents
Index�������������������������������������������������������������������������������������������������207
vi
About the Author
Graeme Stuart is a self-taught developer
with 15 years of experience building data
analysis tools and web-based applications
using JavaScript, Ruby, and Python. He has a
PhD in energy management, and much of his
programming skill was originally developed
to that end. He taught JavaScript games
programming to first-year undergraduates for
a while, and this book is the result. He now
mostly uses complexity science to encourage
a deep understanding of agile approaches
to software engineering and to justify his
outlandish research ambitions.
vii
About the Technical Reviewer
Aditya Shankar started programming in 1993
when he was first introduced to the world of
computers. With no access to the Internet or
online tutorials at the time, he wrote his first
game in GW-BASIC by painstakingly retyping
code from a book he found at the local library.
After graduating from the Indian Institute
of Technology Madras in 2001, he spent nearly
a decade working as a software consultant,
developing trading and analytics systems
for investment banks and large Fortune 100
companies, before eventually leaving his corporate life behind so he could
focus on doing what he loved.
A self-confessed technology geek, he has spent his time since then
working on his own projects and experimenting with every new language
and technology that he could, including HTML5. During this time, he
became well known for singlehandedly re-creating the famous RTS game
Command and Conquer, as well as Commandos: Behind Enemy Lines,
entirely in HTML5.
Apart from programming, Aditya is passionate about billiards, salsa
dancing, fitness, and personal development. He maintains a personal
website where he writes articles on game programming, personal
development, and billiards, and shares his popular game demos.
When he’s not busy writing or working on his own projects, Aditya
does consulting work with companies to help them launch new software
products and games.
ix
Introduction
This book provides a full set of exercises in which we will build a fully
functional HTML canvas game. Though not a direct clone, the game is
inspired by the 1979 Atari classic, Asteroids. The code is provided for you
and is introduced piece by piece over the various chapters of the book.
If you’d like to try Asteroids, or if you’ve never played it, the the modern
Atari version can be played at https://atari.com/arcade#!/arcade/
asteroids/play. I’ve made a few different gameplay decisions for the
game we create in this book, and I encourage you to attempt to adapt the
game in any direction you like as we go along, if you feel confident in doing
so. It’s all good practice!
Typically, each chapter introduces an area of game design in a generic
way, develops the ideas towards implementing an aspect of the Asteroids
game, and urges you to think about alternative approaches. Towards the
end of the book, the game will be complete, and you should have all the
skills necessary to build a quality game of your own.
During most of the exercises, you’re encouraged to be creative. Go
through the material provided, consider the challenges presented, and
explore the impact of modifying the provided code. There’s no “correct”
way to design a game like this—it involves making many decisions, and the
provided code is only one of thousands of possible ways to do it. So, please,
try it your way if you feel confident enough. That’s a great way to learn
something.
xi
PART I
Drawing
The HTML canvas element, true to its name, provides a blank canvas on
which we can draw our game. Drawing is a fundamental aspect of working
with the HTML canvas element, so in these first few chapters we will
explore how drawing works and learn the fundamentals necessary to draw
our own designs with simple lines and fills. We will also develop some of
the game elements necessary for our Asteroids game clone.
CHAPTER 1
H
TML Primer
HTML (HyperText Markup Language) documents describe content on
the web. When you access a web page, you’re typically downloading and
viewing an HTML document. HTML is a way to organize and add semantic
meaning to multimedia content (text, images, videos, and more) and to
link between documents in a “web” of information.
HTML5 is the current version of the HTML standard. The standard
was originally developed in the early 1990s and has evolved a little since
then. The modern standard allows for the extremely rich experience of
the modern World Wide Web. We’ll be working with the HTML canvas
3
© Graeme Stuart 2017
G. Stuart, Introducing JavaScript Game Development,
https://doi.org/10.1007/978-1-4842-3252-1_1
Chapter 1 HTML5 and the Canvas Element
element, so let’s create our first HTML document and add a canvas
element to it.
Create a file called exercise1.html and type in the basic HTML template
shown in Listing 1-1.
<!doctype html>
<html>
<head>
<title>This is an HTML canvas</title>
</head>
<body>
<h1>This is an HTML canvas</h1>
<canvas id="asteroids" width="400" height="400"></canvas>
</body>
</html>
4
Chapter 1 HTML5 and the Canvas Element
contents are to be rendered and how they behave. The <body> element
contains the content of the document and in this case includes a level one
header <h1> and a <canvas> element.
The <canvas> element provides a JavaScript API (application
programmable interface) for drawing simple shapes and lines. It’s this API
that we will use to render our game.
D
rawing to the Canvas
<script> elements contain JavaScript code that’s executed by the browser.
Add the <script> shown in Listing 1-2 into your document <body> after
the <canvas> element.
<script>
var canvas = document.getElementById("asteroids");
var context = canvas.getContext("2d");
context.strokeStyle = 'dimgrey';
context.lineWidth = 5;
context.rect(75, 75, 250, 250);
context.stroke();
// this is a comment, it has no effect!!!
</script>
You’ll need to reload the page in order for the script to run. The
script runs line by line once the page is loaded. The first line calls the
getElementById method on the global document object. The document
object is defined automatically and provides a programmable interface into
the entire HTML document. The document is loaded into memory as a
tree-like structure often referred to as the DOM (Document Object Model).
In this case we’re using getElementById to get a reference to the <canvas>
element within the DOM using the id value we specified in the HTML.
5
Chapter 1 HTML5 and the Canvas Element
6
Chapter 1 HTML5 and the Canvas Element
<style media="screen">
body {
text-align: center;
font-family: sans-serif;
}
7
Chapter 1 HTML5 and the Canvas Element
canvas {
background-color: black;
}
</style>
Styles allow us to control how the content of the document looks when
it’s rendered by the browser. In this case, we’re specifying that we want the
<body> element to be centrally aligned with a sans-serif font (this applies
to all child elements of the body element, as font-family is inherited by
default). We’re also specifying that <canvas> elements should be drawn
with a black background color. After reloading the page, you should see
something similar to Figure 1-2.
This allows us to see exactly where the canvas edges are and
understand that the rectangle is positioned as specified within the canvas.
I won’t cover styles much more in this book, but they’re a very powerful
technology providing exquisite control over how to render HTML content.
8
Chapter 1 HTML5 and the Canvas Element
9
Chapter 1 HTML5 and the Canvas Element
<script>
var canvas = document.getElementById("asteroids");
var context = canvas.getContext("2d");
context.strokeStyle = 'lightgrey';
context.fillStyle = 'dimgrey';
context.lineWidth = 5;
context.rect(75, 50, canvas.width - 150, canvas.height - 100);
context.stroke();
context.fill();
</script>
R
endering Text
The canvas treats text a lot like a collection of shapes. The outline can be
drawn with the context.strokeText method, or text can be filled with
the context.fillText method. Both methods must be passed a text
string and the (x, y) coordinates (in pixels) at which to render the text.
Before rendering text it’s useful to change the font from the default using
context.font.
Add the two lines in Listing 1-5 to your script.
It seems like nothing has happened, but actually, the text has been
drawn. The problem is that the fillStyle is still set to the same color as
the filled rectangle. The text color and the background color are the same,
so nothing visibly changes.
10
Chapter 1 HTML5 and the Canvas Element
<script>
var canvas = document.getElementById("asteroids");
var context = canvas.getContext("2d");
context.strokeStyle = 'lightgrey';
context.fillStyle = 'dimgrey';
context.lineWidth = 5;
11
Chapter 1 HTML5 and the Canvas Element
The changes are all in the second half of the script. We set the familiar
context properties to some sensible values (note the use of hexadecimal
color codes). We then set a new property context.textAlign to the value
"center". This tells the context to use the central point in the text as the
“anchor.” So, when we actually render the text, the central point in the
text is positioned at the x-coordinate we provide rather than the default
leftmost point. The final few lines set a message variable and draw the text.
First we fill it and then we draw an outline (experiment with swapping the
order of these method calls). This is just the same as before except this
time we’re calculating the x-coordinate rather than specifying a literal
value (such as 110, as before). In this case, we’re aligning the text centrally
on the horizontal axis so we divide the width by 2. See Figure 1-5.
12
Chapter 1 HTML5 and the Canvas Element
context.strokeStyle = '#FFFFFF';
context.lineWidth = 2;
context.beginPath();
context.arc(200, 140, 20, 0, Math.PI * 2);
context.moveTo(200, 160);
context.lineTo(200, 220);
context.moveTo(180, 300);
context.lineTo(185, 260);
context.lineTo(200, 220);
context.lineTo(215, 260);
context.lineTo(220, 300);
context.moveTo(240, 130);
context.lineTo(225, 170);
13
Chapter 1 HTML5 and the Canvas Element
context.lineTo(200, 170);
context.lineTo(175, 180);
context.lineTo(170, 220);
context.stroke();
The script starts by setting the stroke color to white and the line width
to 2 pixels. Then we see two new methods of the context object. The
context.beginPath method begins a new path or resets the current path.
We need to call this because we already had an active path left over from
when we drew the original rectangle. If we don’t call it (try commenting it
out), then we continue the original path, and a line will be drawn from the
rectangle to our first circle. You’ll learn more about paths in Chapter 2.
The circle is drawn using the context.arc method. This method
can be used to draw any circle or portion of a circle. The method takes
five arguments, as follows: the first pair of arguments includes the (x, y)
coordinates (in pixels) of the center of the circle. The third argument is
the radius of the circle, and the fourth and fifth arguments are the starting
angle and finishing angle of the arc (measured in radians). To draw a full
circle, these angles should be 0 and 2π. We access the value of π via the
Math.PI method. We’ll use the built-in JavaScript Math object extensively
in later chapters.
The remaining method calls are all either context.moveTo or context.
lineTo until we finally call context.stroke to draw the path. The context.
moveTo and context.lineTo methods both take two arguments, and in both
cases these are the (x, y) coordinates specifying a location on the canvas in
pixels. They each do exactly what you would expect. To move the “pen” to
a location without drawing a line, call context.moveTo. To draw a line from
the current location to the given location, call context.lineTo.
Follow the code line by line and see how each line of code is necessary
to draw the stick figure shown in Figure 1-6. Try removing or editing some
of the lines to see what happens. Play around until you can predict the
effect of a change.
14
Chapter 1 HTML5 and the Canvas Element
The final image should appear like Figure 1-7. Note how the position
in the code where you insert the new lines makes a difference. If you place
the new code after the context changes, the text outline will be drawn with
a thicker, white line.
15
Chapter 1 HTML5 and the Canvas Element
S
ummary
In this chapter we’ve had a very quick run-through of the basic
technologies we’ll be using to create our game. We’ve created our first
HTML document and viewed it in the browser, we’ve styled our document,
and we’ve written code to manipulate our canvas element.
We’ve seen that the HTML <canvas> element has a programmable
interface, and we’ve used HTML <script> elements with JavaScript code
to draw to the canvas. We’ve been introduced to some of the methods
available in the canvas context and used them to render a motivational
poster to the canvas. And we’ve seen that the interface gives us tools for
drawing lines and filling shapes and that we can control the thickness of
lines and the color of lines and shapes.
We learned a little about the coordinate system and how paths are
constructed. In Chapter 2, we’ll expand on this and try to get a deeper
understanding of how to master the art of drawing what we want on the
HTML canvas.
16
CHAPTER 2
Understanding Paths
Chapter 1 introduced some of the basic methods for drawing to the canvas.
This chapter presents a follow-up exercise that looks more closely at the
canvas coordinate system and explores how to construct paths. These
concepts are critical to understanding the canvas and designing your own
drawing code.
We’ll also start to add a bit more structure to our code. Complex code
can be difficult to comprehend—adding structure is the main way to keep
the complexity under control. Structuring code into functions allows
the development of simpler code that uses those functions. This chapter
introduces functions and goes through the process of refactoring, a crucial
skill that’s necessary to manage code of any complexity.
17
© Graeme Stuart 2017
G. Stuart, Introducing JavaScript Game Development,
https://doi.org/10.1007/978-1-4842-3252-1_2
Chapter 2 Understanding Paths
<!doctype html>
<html>
<head>
<title>More drawing to canvas</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>More drawing to canvas</h1>
<canvas id="asteroids" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("asteroids");
var context = canvas.getContext("2d");
// Grid drawing code goes here
</script>
</body>
</html>
body {
text-align: center;
font-family: sans-serif;
}
canvas {
background-color: black;
}
18
Chapter 2 Understanding Paths
context.strokeStyle = "#00FF00";
context.lineWidth = 0.25;
If you refresh the page, nothing is drawn. That’s because we’re still only
building a path and haven’t yet asked for it to be drawn. Repeat the same
pattern with the horizontal grid lines:
19
Chapter 2 Understanding Paths
Again, we’re drawing each horizontal line in turn from the left of the
canvas (x = 0) to the right (x = canvas.width). The y-coordinate starts at
0 and increases by 10 pixels each iteration until it reaches canvas.height.
Nothing is actually drawn to the canvas until we call context.stroke():
context.stroke();
This then draws the path onto the canvas, as shown in Figure 2-1.
20
Exploring the Variety of Random
Documents with Different Content
ole hoivan tarpeessa, vaan päinvastoin odottaa hoivatakseen
tuotakin, joka tuolta tulee, ja joka jo totisesti alkaa olla hommissaan
retuperällä, tolkkua vailla aivan.
Jos nyt tuo Pekka tuossa olisi oikea mies, niin älyäisi toki hävetä
vanhuksen edessä, jonka äänessä ei ole mitään uhkaavaa — surua
vain. Pitäisi tunnustaa olleensa tyhmä ja avuton leikkipallo tässä
kohtalossa, joka miestä näin on paiskellut. Mutta Pekka tunnustaisi
mieluummin olevansa vaikka roisto kuin leikkipallo. Pekka ei osaa
vielä nöyrtyä. Sitäpaitsi häntä tietysti harmittaa näinikään joutua
kolttosestaan kiinni kuin koulupoika. Siksi hän epäluuloisena
murisee:
"On ja ei ole. Tänään iltajunalla hän meni, eikä kukaan tiedä mihin.
— Muuta ei minulla olekkaan asiaa. Nyt vain tahtoisin tietää
kummalle meistä tämä asia tästälähtien kuuluu."
Tulee kai paha olla, sillä pian alkavat jalat uudelleen haparoida
maata. Kädet tarraavat vesiränniin. Pekka nousee riipuksista
sukkelasti jaloilleen, repäisee huivin kaulastaan, ja hengittää syvään.
Lahja: En.
Lahja: Ei.
Lahja: En tiedä.
Lahja: Niin.
Pekka: Siinä ainakaan ei ole mitään pahaa. Päinvastoin siinä
vasta lienee kylvetty meidän onnemme itu. — Sinä luhistuit minun
silmissäni jo aikoja sitte, muutamana juhannusyönä. Mutta minä
iloitsin siitä. Sinä tulit silloin ihmiseksi. Etkö nyt iloitse siitä että
minäkin olen vain ihminen — parempi siis kuin epäjumala?
Lahja: Niin.
Lahja: Pois.
Pekka: On kyllä, sentakia että sinä olet sen äiti. Siten te olette
minulle samantapainen asia kuin kristityille Uusi Testamentti.
Lahja: Olemmeko me sinulle asioita, eli asia? Mikä sen asian nimi
sinun kielelläsi on?
Lahja: Kyllä.
Pekka: Rajattomasti?
Lahja: Niin.
Pekka: Luulenpa että voimme heti palata kotia. Pue päällesi; minä
puen
Taimin. Juna lähtee tuossa tuokiossa.
Lahja: Mitähän tästä tulee? Tuntuu niin oudolta kuin olisi edessä
uusi elämä.
Valkea: Elämään.
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com