Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Foundation game design with HTML5 and javascript V413HAV
Nội dung xem thử
Mô tả chi tiết
In this book, you’ll learn how to:
Implement strategies for making games fun to play and easy to build
Create logic, adventure, and 2D action games in a wide range of genres
Design a character and control it with a keyboard, mouse, or touch interface
Use collision detection to build an interactive game world
Develop intelligent enemies, sound effects, and music
Build robust games with modern JavaScript programming techniques that are
easy to maintain and simple to extend
Foundation Game Design with HTML5 & JavaScript
If you’re looking to turn a good game idea into reality but don’t have extensive programming experience, Foundation Game Design with HTML5 and JavaScript is your ideal first
step. Expert video-game designer Rex van der Spuy teaches you all the technical and creative issues involved in game design, including how to use HTML5, CSS, and JavaScript, the
latest programming languages, with confidence.
Best of all, detailed case studies demonstrate all techniques, and open-ended projects
encourage you to build your own original games. Turn to Foundation Game Design with
HTML5 and JavaScript and find the knowledge and skills you need to get started on a
career as a game designer.
SHELVING CATEGORY
1. WEB DEVELOPMENT / GENERAL
GAME DESIGN WITH HTML5 & JAVASCRIPT
van der
Spuy
FOUNDATION
Available from Apress
Also Available
SOURCE CODE ONLINE
US $44.99
Mac/PC compatible
www.apress.com
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
v
Contents at a Glance
About the Author ..........................................................................................................xvii
About the Technical Reviewer ......................................................................................xix
About the Cover Image Artist .......................................................................................xxi
Acknowledgments .......................................................................................................xxiii
Introduction ...................................................................................................................xxv
Chapter 1: Learning HTML and CSS ...............................................................................1
Chapter 2: Learning JavaScript .....................................................................................59
Chapter 3: Your First Games .......................................................................................111
Chapter 4: Creating a Game World .............................................................................179
Chapter 5: Making Maps ..............................................................................................243
Chapter 6: Game Objects and Animation ...................................................................297
Chapter 7: Game Sprites ..............................................................................................373
Chapter 8: Bumping into Things .................................................................................443
Chapter 9: Making Video Games .................................................................................487
Chapter 10: Maze Games .............................................................................................533
Chapter 11: Platform Games and Physics .................................................................601
Chapter 12: Touch and the Mouse ..............................................................................671
Index ...............................................................................................................................721
xxv
Introduction
In 1980, when I was 10 years old, my parents sat me down and formally announced that they were going to
buy me a computer for Christmas. Somewhere, somehow, they had heard that a computer could, they told me,
“help you with your homework.”
I was astonished.
“Of course it will help me with my homework. Computers are really good for math!” I exclaimed. “And
science too!”
I was going to let them believe whatever they wanted to believe. As long as they got me that computer, fast,
before whatever spell they were under wore off. Because the only thing I wanted a computer for was to play
video games, but no way was I going to let that out of the bag.
All I lived for was video games. My friends and I had spent that whole summer biking around town, looking for
lost change on the sidewalk that we could use to play arcade games with. The closest arcade machine that
didn’t have “bad kids” hanging around it was Ms. Pac Man, which was a 20-minute bike ride away in the corner
of a dingy old diner. But it was worth it, because we had memorized the solutions to all the level maps in our Ms.
Pac Man strategy book and could play for an amazingly long time, to the wonder of the littler kids who gathered
around to watch. When we couldn’t fi nd any quarters we made our own arcade games out of boxes, crayons,
thumbtacks, and plastic coat buttons. And at the end of that summer, we made the most blissful discovery: a
malfunctioning Space Invaders machine that could be played using pennies if you fl icked them in at just the
right angle. I came back from the bank with a roll of 100 pennies, and I spent the last 2 weeks of that August in
an ecstatic, bleary-eyed, space-invading dreamworld.
So that Christmas morning, in a giddy fever, I ripped open the red-and-white candy-cane wrapping paper. It was
everything I had hoped for: a state-of-the-art Commodore Vic-20. It had a whopping 5K of memory, the latest
cassette-tape storage drive, and a display of 16 colors. The computer at school could just display two colors:
green and black. I was in heaven! I fumbled with the instructions and, with trembling hands, carefully plugged
my gleaming new Vic-20 into the family TV set and switched it on.
Nothing happened. The TV was completely blank, except for a small, calmly blinking blue square at the top left
corner of the screen.
“Where are the games?” I thought, “Where’s Ms. Pac Man? Where are the aliens?”
I jiggled the power cable and fi ddled with the wires at the back of the TV. But, no, there was just that steady
blue, blinking square, silently mocking me. This blue square, I discovered, was called the “cursor.” I hated it
and felt sick.
The games, it turned out, came on audio cassettes that you could load into the computer by hooking up the
cassette player and pressing the play button. But you had to buy them. They cost $20 each. The nearest shop
that sold them was a 45-minute drive, in a car, over a mountain. It was impossible—there was just no way. And,
anyway, I was supposed to be using this thing to “do my homework.”
But in the computer’s box I found a book about BASIC programming. I had no idea what that meant and
couldn’t understand anything in that book at all. It was full of all kinds of bits of scrambled English words and
numbers written in big capital letters that were supposed to make the computer do things. “Programming code,”
xxvi
Introduction
it was called. Maybe this was just stuff for grown-ups? “No,” I thought, “computers are for children, and grownups are scared of them.” And so I persisted. At the very back of the book, I found a section called “Programs to
try.” My eye fell across the words “Killer Comet.” It was a video game! Beneath it was a long list of inscrutable
codes. But I fi nally fi gured out that if I could type these codes into my Vic-20, I could play a game.
That was it!
If “programming” means “you can play video games for free,” I was going to fi gure out programming. I spent
the next two days in a frenzy, reading through the book and typing in all those codes, trying to get Killer Comet
to work. I had barely any idea what I was doing and my computer kept displaying “Syntax Error! Syntax Error!
Syntax Error!” over and over again whenever I tried to run the program. I was pulling my hair out and wanted to
scream! But then, late on the second day, something miraculous happened—it worked:
A small white square moved from the top of the screen to the bottom of the screen.
If you pressed the right number of keys in the right way, the square disappeared.
That was all.
It was the most beautiful thing I’d ever seen in my life.
And that’s when I discovered that making video games is way, way, way more fun than playing them. And so,
here, Dear Reader, you have that book that I truly believe should come in the box with every new computer.
Hope you have as much fun reading it as I did writing it!
1
Chapter 1
Learning HTML and CSS
What’s more fun than playing video games? Making them! And this book will show you how. You don’t need to
know anything about programming or any other complicated technical computer-y things. You don’t even need
to know much math. This book will show you everything you need to make great games that you can play on
the Web, on desktop computers, or as apps on mobile phones and tablets.
There are lots and lots of ways to make video games. But you don’t need to know all of them—you only need
to know the best way. By “best,” I mean the easiest and most fun way, and that’s the way that you’re going to
learn from this book. It’s also the way that will give your games the widest audience, give you the most solid set
of game-design skills, and give you the best chance of making a bit of money from it too.
To make games, you have to learn a computer-programming language, which you can use to communicate
with the computer to tell it what to do. A computer-programming language can look a lot like English, and such
languages are easy to learn. People might argue with you that technically HTML and CSS are markup languages,
not programming languages, but I’m going to call them all programming languages here and be done with it.
This book is about making games using a technology suite called HTML5. HTML5 is based on three separate
computer-programming languages that work together:
■ HTML (HyperText Markup Language): A programming languagethat describes how games and applications are structured. Games and most websites are built using HTML.
■ CSS (Cascading Style Sheets): A programming languagethat describes how HTML code should be
visually presented.
■ JavaScript: A programming language that lets you control how your games behave.
Chapter 1
2
You’re going to learn all three languages in this book. In this chapter you’ll learn about HTML and CSS. They’re
extremely easy to use, and what we cover in this chapter will be enough to get you started making games.
You can also use the skills you learn in this chapter to use HTML and CSS to start building websites if that is
something you’d like to do. To make games, you’ll need to learn JavaScript, and that’s what much of the rest
of the book is all about.
These programming languages let you access and control many specialized technologies that are all part
of the HTML5 standard. The most important of these for games is canvas. Canvas is a display technology
that’s great for animation and action games. You’ll learn all about how to use canvas to make games starting
with Chapster 6.
Note: If you already know HTML and CSS, you can jump ahead to Chapter 2to learn
JavaScript. If you already know JavaScript and just want to start making games, jump
ahead to Chapter 3 . If you already know JavaScript and how to program in general, but
you just want to start making games with canvas, Chapters 6 , 7, and 8 are all yours!
What you need
Surprisingly, video-game design can be a relatively low-tech affair. Here’s the basic equipment you’ll need to
make use of this book.
A computer
You need a reasonably up-to-date computer, either running Windows or the latest version of Mac OS X, or even
Linux. You should have basic computer literacy skills, which includes understanding how to make new files and
how to organize them in folders.
Programming software
Luckily, this costs nothing and you probably already have all the programming software you need already
installed on your computer. Here’s what you’ll need:
■ A text editor: If you’re using Windows, Notepad works well. If you’re using Mac OS X, you may use
TextEdit.
■ Safari, Chrome, Firefox, or Opera: These web browsers include some great features for building
and testing HTML5 games. This book will explain how to use them to help you make games. Safari,
Chrome, Firefox, and Opera are available for Windows and Mac. Chrome is available for Linux. If
you’re using a Mac, Safari is already installed on your computer. If you’re using Windows, you can
download Chrome or Safari here: www.google.com/chrome, and www.apple.com/safari/download
This book describes how to use these software programs and tools to program games—you won’t need
anything else.
However, there is some more specialized, but optional, software that you might want to try if you’re doing a lot
of programming and want to make things a little easier for yourself.
Learning HTML and CSS
3
■ Komodo Edit or jEdit: These are free text editors for Windows, Mac OS X, and Linux. They’re specialized for writing programming code. They number each line of code and highlight important programming words in different colors ( syntax highlighting). Both these features make writing code easier
because you can find and change sections of your code more easily. Once you start to get the hang
of programming, and you want to try a slightly more sophisticated text editor than Notepad or TextEdit,
Komodo Edit or jEdit is a good next step.
■ Aptana Studio: This is a free IDE (integrated development environment) based on Eclipse, for
Windows and Mac OS X. It includes syntax highlighting and numbered lines of code, and you can
install a plug-in that helps you debug JavaScript.
■ Dreamweaver: This was, for a long time, the most widely used software for building web pages. It’s
not free and is perhaps overly complex for the simpler needs of a game designer, but it’s specialized
for writing HTML, CSS, and JavaScript code. Dreamweaver is available for Windows and Mac from
Adobe: www.adobe.com.
■ If you’re using Mac OS X, you have two further options. Coda is an efficient code editor with a built-in
JavaScript debugger and a live preview window of what your game looks like as you’re programming
it. Textmate is another excellent OS X-only code editor that also provides a live preview window of
your game, as well as integrated JavaScript debugging. Neither Coda nor Textmate is free, but if you
do a lot of programming they’re probably worth the cost for the time they’ll save you. Both Coda and
Textmate are available through the Mac OS X app store.
HTML5 is a very new and quickly changing technology, and it’s likely that by the time you are reading this there
will be many more, and possibly better, tools for creating HTML5 games than those I’ve listed above. Keep a
lookout for new software, and try everything!
If you already have some experience programming, you probably enjoy just using one of these editors. But if
you’re just starting, they’ll only confuse you. Remember, all you’ll ever really need is a simple text editor and a
good web browser. Keep it simple and you can’t go wrong.
Note: If you decide to use TextEdit with the latest version of Mac OS X, you’ll need to set it
up so that it lets you write in plain text, which is important for programming. Here’s how:
Select Preferences from TextEdit’s main menu.
Select Plain Text in the Format section.
In the Open and Save section, uncheck“add ‘txt’ extension to plain text files”.
Select "ignore rich text commands in HTML files."
Graphic design software(optional)
This book is just about programming games. I won’t show you how to make graphics or illustrations for your
games, so if this is something you’re interested in, you’ll need to learn how. In fact, if you don’t have any experience creating computer graphics, you might want to learn a little bit about it before starting with this book.
Chapter 1
4
The two most widely used applications for making game graphics are Photoshop and Illustrator (both available
from Adobe). Other options are GIMP and Inkscape, both of which are free. Here’s what you should learn about
computer graphic design to make the best use of this book:
■ Making PNG images with alpha transparency
■ Changing the sizes of images and knowing how to crop them
■ Mastering basic illustration skills, such as how to draw characters and game objects
You’ll find many online tutorials and books about how to do these tasks using any of the software already
mentioned.
What kinds of games can I make?
This book is mostly about how to make two-dimensional action, adventure, and arcade games ; it also touches
on puzzle, logic, and strategy games. HTML5 is a fantastic medium for creating these types of games. Each
chapter guides you through every step of the design process, but the projects are very open-ended. I encourage you to come up with your own original ways of using the techniques in your own games. This book starts
with all the basics of computer programming, and we will gradually build on those techniques until you’re making very sophisticated games from scratch. You’re going to learn the simplest possible way of making games
so that you can easily understand how they work and can then develop them into more complex games on
your own.
The games you’ll make you’ll be able to upload for anyone to play on the Web. Or you can package them for
mobile phones and tablet computers, and then sell them through app stores. Everything you’ll need to know to
get started on a professional career as a game designer, from start to finish, is right here in this book.
How hard is it?
It’s about as easy to learn to make games as it is to learn basic conversationin a foreign language or to understand how to read and write music. So if you’ve done one of those tasks before, you’ll know that it’s not hard at
all. You just have to take things slowly, step by step and methodically. Practice the skills you learn as much as
you can, and don’t move on to a new topic until you thoroughly understand the current one. You won’t get any
benefit if you rush through this book. You might spend a few days, a few weeks, or even a few months on any
chapter. Take as much time as you need, because this book isn’t going anywhere! But if you make the effort,
you’ll be a great game designer when you’re finished.
Learning HTML
There are three related programming languagesyou need to know to make games: HTML, CSS, and JavaScript.
We’ll start with the easiest: HTML.
HTML is a kind of computer-programming language known as a markup language . Markup languagescan
describe information. This is different from JavaScript, which is a logical programming language. Logical programming languages are used to analyze and make decisions about information. HTML is used for making
websites, and it is the foundation for making games. It’s currently in version number 5, which is why it’s known
as HTML5.
Learning HTML and CSS
5
Tags
HTML is used to describe information. It uses tags to tell computers the kind of information a document contains. A tag is just a word surrounded by left- and right-pointing arrow characters (sometimes called carets).
Here’s an example of a tag:
<thisIsATag>
Here’s a tag that identifies the heading of a web page.
<h1>The main heading</h1>
<h1> means “Heading 1.” Tags usually come in pairs of an opening tag and a closing tag. The opening tag looks
like this:
<h1>
The closing tag adds a forward slash, /, to show that the tag is now finished describing the information:
</h1>
In this example anything that’s between the opening and closing tags will be identified as a heading, like this:
<h1>Anything between the opening and closing tags is part of the heading</h1>
It’s a really simple system, and you can use it to identify any kind of information in any way you like.
Note: HTML also lets you use stand-alone tags that don’t need to be closed, like this:
<br>
This tag stands for “break,” and it creates a line space in the text. It isn’t used to describe
any containing information.
If you’ve used earlier versions of HTML, you were probably required to write stand-alone
tags with a forward slash at the end of the tag name, to indicate that the tag is self-closing,
like this:
<br />
You don’t have to do this in HTML5.
Tags and the information they contain are called elements. Remember this! When I mention HTML elements
in this book, I’m talking about the tag and whatever is inside it.
Chapter 1
6
Structuring HTML documents
To make a game or website with HTML tags, you have to structure the tags as a document. HTML5 is extremely
flexible and lenient about how to structure HTML documents. However, most games, applications, and websites that are made with HTML follow some standard conventions about how documents are structured and
how to use the tags they’re built with. The reason for this is so that computers reading those documents can
easily interpret the information they contain and display it correctly on any screen. In this section I’m going to
show you how to build a very basic website with the most commonly used HTML tags.
Here’s the classic structurefor building a website with HTML:
<!doctype html>
<html>
<head>
<title>The title of the web page</title>
</head>
<body>
<p>Anything you want to appear on the screen goes inside the body section.</p>
</body>
</html>
You can see that everything is surrounded by a pair of <html></html> tags. Inside those tags are another pair
called <head></head> followed by another pair called <body></body>.
In between the <head> tags you provide any information that you want to tell computers reading your document
what they need to know to display the information correctly. None of the information in the <head> section is
actually visible in the browser window. In this example the <head> section contains an element called <title>.
<head>
<title>The title of the web page</title>
</head>
The <title> element describes the page’s title.
Anything that appears between the <body> tags is visible in the web browser—it’s what you see as a web page.
This is where most of the information of your HTML document will go. In this example, the <body> section contains a sentence that’s inside a <p> tag.
<body>
<p>Anything you want to appear as a paragraph of text on the screen goes inside the body
section.</p>
</body>
The <p> tag stands for paragraph. You use it to display sentences or paragraphs.
Learning HTML and CSS
7
At the very top of the document is a special stand-alone tag that looks like this:
<!doctype html>
This needs to be the first tag in an HTML5 document. It just means, “Hey, computer, this is an HTML5 document!” That’s all.
Building an HTML5 game or website generally means adding tags and information into the <head> and <body>
sections. Lastly, you’ll notice that the tags that are nested inside other tags are indented by two spaces from
the left margin.
<html>
<head>
<title></title>
</head>
<body>
<p></p>
</body>
</html>
The indentation makes it easier to see that the inner tags are being contained inside an outer tag.
Note: It’s a common convention to indent HTML code that is inside enclosing tags.
However, indenting it in this way can sometimes actually make big HTML documents with
long lines of text more difficult to read. As you’ll see in the next example, I’ve chosen not
to indent most of the tags that are inside other tags, except for the short list items and the
page title. You’ll need to decide how you want to indent your HTML code, depending on
what style you find more readable. It doesn’t matter to the web browser how you indent it;
it just makes it easier to read if needed.
Let’s see how we can use this structure to make a very basic web page.
A basic web page
Let’s use what you know about HTML to build a real web page. We’ll look at a web page that’s built using some
of the most common HTML tags.
In the chapter’s source file, you’ll find a file called simpleWebpage .html. Double-click on it, and it will automatically open in a web browser. Figure 1-1 shows you what you’ll see.
Chapter 1
8
This HTML web page is made with the most basic and useful tags. A web page is just a plain text file with an
HTML file extension. Here’s how to view the HTML code that creates this page:
1. Open your text editor, which is either Notepad (Windows) or TextEdit (Mac OS X)
2. Select File ➤ Open and open the simpleWebpage.html file.
Figure 1-1 . A very basic web page
Learning HTML and CSS
9
3. It will load the HTML file, with all the tags visible. This is what you’ll see:
<!doctype html>
<html lang="en">
<head>
<title>A web page</title>
</head>
<body>
<h1>A simple web page</h1>
<p>Everything you see on this page was made using basic HTML tags.</p>
<h2>This is a sub-heading</h2>
<p>You use HTML tags to <em>structure information</em>.
This is a paragraph of text structured with a p tag.</p>
<h2>Making lists</h2>
<p>You can also use tags to <strong>make a list</strong> of things.</p>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
<!-- This is a comment in the document. It won't appear in the web browser-->
<h2>Adding links</h2>
<p>Its easy to create hyperlinks to other web pages, or to create a link
to generate an email. Here's how:</p>
<ul>
<li><a href=" http://www.w3schools.com " target="_blank">Here's a good resource</a>
for learning HTML</li>
<li>If you want to say Hi, <a href="mailto:[email protected]?Subject=Hello%20
there!">Send me an email.</a></li>
</ul>
<p>Add a photo with an img tag, like this:</p>
<img src="ocean.jpg" alt="A photo of the ocean">
</body>
</html>
(Alternatively, you can also select View > View Source from your web browser to view this HTML code.)
Don’t let this scare you! Notice that all the web-page text is surrounded by tags, and each of the tags changes
the way that the text is displayed in the web browser. Figure 1-2is a side-by-side illustration that shows the
Chapter 1
10
effect that the HTML text has on the text in the web browser. I’ve added some blank lines in the HTML document so that it’s a little easier to see where each section begins and ends. However, the web browser ignores
those blank lines and uses its own rules for spacing the text.
Figure 1-2 . The HTML code is interpreted by the web browser to create the page layout
Let’s see how each of these new HTML tags changes the way the text is displayed.
Using an attribute to set the document language
HTML tags can include extra information called attributes. Attributesare added inside the tag, after the tag
name. The following attribute in the <html> tag sets the web page’s language to English.
<html lang="en">
The name of the attribute is lang (for language). "en" stands for English, and it’s assigned to the attribute using
an equal sign lang="en" means that the web-page content is written in English.