Data Loading...

THE ESSENTIAL GUIDE TO HTML5 USING GAMES TO LEARN HTML5 AND JAVASCRIPT Flipbook PDF

Friendsof an Apress Company- The Essential Guide to HTML5 Using Games to Learn HTML5 and JavaScript by Jeanine Meyer.


127 Views
28 Downloads
FLIP PDF 9.87MB

DOWNLOAD FLIP

REPORT DMCA

HTML5 Using Games to Learn HTML5 and JavaScript

CONTENTS

The Essential Guide to HTML5 Using Games to Learn HTML5 and JavaScript

Jeanine Meyer

i

CONTENTS

The Essential Guide to HTML5: Using Games to Learn HTML5 and JavaScript Copyright © 2010 by Jeanine Meyer

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-3383-1 ISBN-13 (electronic): 978-1-4302-3384-8 Printed and bound in the United States of America (POD) Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logos, or image we use the names, logos, or images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. Distributed to the book trade worldwide by Springer Science+Business Media LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. For information on translations, please e-mail [email protected] or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is freely available to readers at www.friendsofed.com in the Downloads section.

Credits President and Publisher: Paul Manning Lead Editor: Ben Renow-Clarke Technical Reviewer: Cheridan Kerr Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh

Coordinating Editor: Debra Kelly Copy Editor: Sharon Terdeman Compositor: Bronkella Publishing Indexer: Brenda Miller Artist: April Milne Cover Artist; Corné van Dooren Cover Designer: Anna Ishchenko

CONTENTS

To Daniel, Aviva, Anne, Esther, and Joseph, who is still in our lives, and for the newest members of the family: Allison, Liam, and Grant.

iii

CONTENTS

Contents at a Glance Contents at a Glance................................................................................................ iv Contents..................................................................................................................... v About the Author ...................................................................................................... x About the Technical Reviewer ............................................................................... xi Acknowledgments ................................................................................................... xii Introduction ............................................................................................................ xiii Chapter 1: The Basics ............................................................................................... 1 Chapter 2: Dice Game ............................................................................................. 21 Chapter 3: Bouncing Ball ........................................................................................ 67 Chapter 4: Cannonball and Slingshot ..................................................................... 97 Chapter 5: The Memory (aka Concentration) Game ............................................ 141 Chapter 6: Quiz...................................................................................................... 179 Chapter 7: Mazes ................................................................................................... 213 Chapter 8: Rock, Paper, Scissors ........................................................................ 259 Chapter 9: Hangman .............................................................................................. 287 Chapter 10: Blackjack............................................................................................ 317 Index ....................................................................................................................... 347

iv

CONTENTS

Contents Contents at a Glance................................................................................................ iv Contents..................................................................................................................... v About the Author ...................................................................................................... x About the Technical Reviewer ............................................................................... xi Acknowledgments ................................................................................................... xii Introduction ............................................................................................................ xiii Chapter 1: The Basics ............................................................................................... 1 Introduction .....................................................................................................................................................1 Critical requirements .......................................................................................................................................3 HTML5, CSS, and JavaScript features ..........................................................................................................4 Basic HTML structure and tags ..................................................................................................................4 JavaScript programming ...........................................................................................................................10 Building the application and making it your own ..........................................................................................11 Testing and uploading the application..........................................................................................................19 Summary ........................................................................................................................................................19

Chapter 2: Dice Game ............................................................................................. 21 Introduction ...................................................................................................................................................21 Critical requirements .....................................................................................................................................24 HTML5, CSS, and JavaScript features ........................................................................................................24 Pseudo-random processing and mathematical expressions..................................................................24 Variables and assignment statements .....................................................................................................25 Programmer-defined functions .................................................................................................................26 Conditional statements: if and switch ......................................................................................................27 Drawing on the canvas ..............................................................................................................................29 Building the application and making it your own ..........................................................................................38 Throwing a single die .................................................................................................................................40 Throwing two dice ......................................................................................................................................47 The complete game of craps .....................................................................................................................55

v

CONTENTS

Testing and uploading the application..........................................................................................................65 Summary ........................................................................................................................................................65

Chapter 3: Bouncing Ball ........................................................................................ 67 Introduction ...................................................................................................................................................67 Critical requirements .....................................................................................................................................70 HTML5, CSS, JavaScript features ...............................................................................................................70 Drawing a ball, image, and gradient ..........................................................................................................70 Building the application and making it your own ..........................................................................................80 Testing and uploading the application..........................................................................................................96 Summary ........................................................................................................................................................96

Chapter 4: Cannonball and Slingshot ..................................................................... 97 Introduction ...................................................................................................................................................97 Critical requirements ...................................................................................................................................100 HTML5, CSS, and JavaScript features ......................................................................................................101 Arrays and programmer-defined objects ................................................................................................101 Rotations and translations for drawing...................................................................................................103 Drawing line segments.............................................................................................................................107 Mouse events for pulling on the slingshot..............................................................................................108 Changing the list of items displayed using array splice ........................................................................110 Distance between points .........................................................................................................................110 Building the application and making it your own ........................................................................................111 Cannonball: with cannon, angle, and speed ..........................................................................................118 Slingshot: using a mouse to set parameters of flight ............................................................................128 Testing and uploading the application........................................................................................................140 Summary ......................................................................................................................................................140

Chapter 5: The Memory (aka Concentration) Game ............................................ 141 Introduction .................................................................................................................................................141 Critical requirements ...................................................................................................................................146 HTML5, CSS, JavaScript features .............................................................................................................146 Representing cards .................................................................................................................................146 Using Date for timing ...............................................................................................................................147 Providing a pause ....................................................................................................................................148

vi

CONTENTS

Drawing text .............................................................................................................................................149 Drawing polygons ....................................................................................................................................151 Shuffling cards.........................................................................................................................................152 Implementing clicking on a card..............................................................................................................152 Preventing certain types of cheating .....................................................................................................153 Building the application and making it your own ........................................................................................154 Testing and uploading the application........................................................................................................177 Summary ......................................................................................................................................................177

Chapter 6: Quiz...................................................................................................... 179 Introduction .................................................................................................................................................179 Critical requirements ...................................................................................................................................183 HTML5, CSS, and JavaScript features ......................................................................................................184 Storing and retrieving information in arrays ...........................................................................................184 Creating HTML during program execution ..............................................................................................186 Changing elements by modifying CSS using JavaScript code .............................................................189 Text feedback using form and input elements .......................................................................................190 Presenting video......................................................................................................................................191 Building the application and making it your own ........................................................................................193 Testing and uploading the application........................................................................................................210 Summary ......................................................................................................................................................210

Chapter 7: Mazes ................................................................................................... 213 Introduction .................................................................................................................................................213 Critical requirements ...................................................................................................................................218 HTML5, CSS, and JavaScript features ......................................................................................................219 Representation of walls and the token ...................................................................................................219 Mouse events to build and position a wall ..............................................................................................219 Detecting the arrow keys ........................................................................................................................220 Collision detection: token and any wall ..................................................................................................222 Using local storage ..................................................................................................................................224 Encoding />. This particular tag will display the image held in the file home.gif. These tags are the markup. It is through the use of tags that hyperlinks, images, and other media are included in web pages. Basic HTML can include directives for formatting in a language called Cascading Style Sheets (CSS) and programs for interaction in a language called JavaScript. Browsers, such as Firefox and Chrome, interpret the HTML along with any CSS and JavaScript to produce what we experience when we visit a web site. HTML holds the content of the web site, with tags providing information on the nature and structure of the content as well as references to images and other media. CSS specifies the formatting. The same content can be formatted in different ways. JavaScript is a programming language thats used to make the web site dynamic and interactive. In all but the smallest working groups, different people may be responsible for the HTML, CSS, and JavaScript, but its always a good idea to have a basic understanding of how these different tools work together. If you are already familiar with the basics of HTML and how CSS and JavaScript can be added together, you may want to skip ahead to the next chapter. Still, it may be worth casting your eye over the content in this chapter, to make sure you are up to speed on everything before we start on the first core examples.

1

CHAPTER 1

The latest version of HTML (and its associated CSS and JavaScript) is HTML5. It is generating considerable excitement because of features such as the canvas for displaying pictures and animation; support for video and audio; and new tags for defining common document elements such as header, section, and footer. You can create a sophisticated, highly interactive web site with the new HTML5. As of this writing, not all browsers accept all the features, but you can get started learning HTML5, CSS, and JavaScript now. Learning JavaScript will introduce you to general programming concepts that will be beneficial if you try to learn any other programming language or if you work with programmers as part of a team. The approach Ill use in this book is to explain HTML5, CSS, and JavaScript concepts in the context of specific examples, most of which will be familiar games. Along the way, Ill use small examples to demonstrate specific features. Hopefully, this will help you both understand what you want to do and appreciate how to do it. You will know where we are headed as I explain the concepts and details. The task for this chapter is to build a web page of links to other web sites. In this way, youll get a basic understanding of the structure of an HTML document, with a small amount of CSS code and JavaScript code. For this and other examples, please think of how to make the project meaningful to you. The page could be a list of your own projects, favorite sites, or sites on a particular topic. For each site, youll see text and a hyperlink. The second example includes some extra formatting in the form of boxes around the text, pictures, and the day's date and time. Figure 1-1 and Figure 1-2 show the different examples Ive created.

Figure 1-1. An annotated list of games

2

THE BASICS

Figure 1-2. Favorite sites, with extra formatting When you reload the Favorite Sites page, the date and time will change to the current date and time according to your computer.

Critical requirements The requirements for the list of links application are the very fundamental requirements for building a web page containing text, links, and images. For the example shown in Figure 1-1, each entry appears as a paragraph. In the example shown in Figure 1-2, in contrast, each entry has a box around it. The second example also includes images and a way to obtain the current day, date, and time. Later applications will require more discussion, but for this one well go straight to how to implement it using HTML, CSS, and JavaScript.

3

CHAPTER 1

HTML5, CSS, and JavaScript features As I noted, HTML documents are text, so how do we specify links, pictures, formatting, and coding? The answer is in the markup, that is, the tags. Along with the HTML that defines the content, youll typically find CSS styles, which can be specified either inside the HTML document or in an external document. You might also include JavaScript for interactivity, again specified in the HTML document or in an external document. Well start with a look at how you can build simple HTML tags, and how you can add inline CSS and JavaScript all within the same document.

Basic HTML structure and tags An HTML element begins with a starting tag, which is followed by the element content and an ending tag. The ending tag includes a / symbol followed by the element type, for example /head. Elements can be nested within elements. A standard HTML document looks like this:

Very simple example

This will appear as is.

Note that Ive indented the nested tags here to make them more obvious, but HTML itself ignores this indentation (or whitespace, as its known), and you dont need to add it to your own files. In fact, for most of the examples throughout this book I wont be indenting my code. This document consists of the html element, indicated by the starting tag and ending with the closing tag: . HTML documents typically have a head and a body element, as this one has. This head element contains one element, title. The HTML title shows up different places in different browsers. Figure 1-3 shows the title, "Very Simple Example" at the top-left portion of the screen and also on a tab in Firefox.

Figure 1-3. The HTML title in two places in Firefox

4

THE BASICS

In most cases, you will create something within the body of the web page that youll think of as a title, but it wont be the HTML title! Figure 1-3 also shows the body of the web page: the short piece of text. Notice that the words html, head, title and body do not appear. The tags “told” the browser how to display the HTML document. We can do much more with text, but let's go on to see how to get images to appear. This requires an img element. Unlike html, head, and body elements that use starting and ending tags, the img element just uses one tag. It is called a singleton tag. Its element type is img (not image) and you put all the information with the tag itself using what are termed attributes. What information? The most important item is the name of the file that holds the image. The tag

tells the browser to look for a file with the name frog and the file type jpg. In this case, the browser looks in the same directory or folder as the HTML file. You can also refer to image files in other places and Ill show this later. The src stands for source. It is termed an attribute of the element. The slash before the > indicates that this is a singleton tag. There are common attributes for different element types, but most element types have additional attributes. Another attribute for img elements is the width attribute.

This specifies that the image should be displayed with a width of 200 pixels. The height will be whatever is necessary to keep the image at its original aspect ratio. If you want specific widths and heights, even if that may distort the image, specify both width and height attributes.

Tip: Youll see examples (maybe even some of mine) in which the slash is omitted and which work just fine, but it is considered good practice to include it. Similarly, youll see examples in which there are no quotation marks around the name of the file. HTML is more forgiving in terms of syntax (punctuation) than most other programming systems. Finally, youll see HTML documents that start with a very fancy tag of type !DOCTYPE and have the HTML tag include other information. At this point, we don't need this so I will keep things as simple as I can (but no simpler, to quote Einstein).

Producing hyperlinks is similar to producing images. The type of element for a hyperlink is a and the important attribute is href. Jeanine Meyer's Academic Activities As you can see, this element has a starting and ending tag. The content of the element, whatever is between the two tags—in this case, Jeanine Meyer's Academic Activities—is what shows up in blue and underlined. The starting tag begins with a. One way to remember this is to think of it as the most important element in HTML, so it uses the first letter of the alphabet. You can also think of an anchor, which is what the a actually stands for, but that isn't as meaningful for me. The href attribute (think hypertext reference) specifies the web site where the browser goes when the hyperlink is clicked. Notice that this is a full Web address (called a Universal Resource Locator, or URL, for short). We can combine a hyperlink element with an img element to produce a picture on the screen that a user can click on. Remember that elements can be nested within other elements. Instead of putting text after the starting tag, put an tag:

5

CHAPTER 1



Lets put these examples together now:

Second example

This will appear as is.

Jeanine Meyer's Academic Activities

I created the HTML file, saved it as second.html, and then opened it up in the Chrome browser. Figure 1-4 shows what is displayed.

Figure 1-4. Example with images and hyperlinks This produces the text; the image in its original width and height; the image with the width fixed at 200 pixels and height proportional; a hyperlink that will take you to my web page (I promise); and another link that uses an image that will also take you to my web page. However, this isn't quite what I had in mind. I wanted these elements spaced down the page. This demonstrates something you need to remember: HTML ignores line breaks and other white space. If you want a line break, you have to specify it. One way is to use the br singleton tag. Ill show other ways later. Take a look at the following modified code. Notice that the
tags dont need to be on a line by themselves.

6

THE BASICS

Second example

This will appear as is.






Jeanine Meyer's Academic Activities


Figure 1-5 shows what this code produces.

Figure 1-5. Text, images, and links with line breaks There are many HTML element types: the h1 through h6 heading elements produce text of different sizes; there are various elements for lists and tables, and others for forms. CSS, as well see in a moment, is also used for formatting. You can select different fonts, background colors, and colors for the text, and control the layout of the document. Its considered good practice to put formatting in CSS, interactivity in JavaScript, and keep the HTML for the content. HTML5 provides new structural elements, such as article, section, footer, and header, and this makes it even easier to put the formatting in CSS. Doing

7

CHAPTER 1

this lets you easily change the formatting and the interactions. Formatting, including document layout, is a large topic. In this book, I stick to the basics.

Using cascading style sheets CSS is a special language just for formatting. A style is essentially a rule that specifies how a particular element will be formatted. This means you can put style information in a variety of places: a separate file, a style element located in the head element, or a style within the HTML document, perhaps within the one element you want to format in a particular way. The styling information cascades, trickles down, unless a different style is specified. To put it another way, the style closest to the element is the one thats used. For example, you might use your official company fonts as given in the style section in the head element to flow through most of the text, but include specification within the local element to style one particular piece of text. Because that style is closest to the element, it is the one that is used. The basic format includes an indicator of what is to be formatted followed by one or more directives. In the application for this chapter (available at www.friendsofed.com/downloads.html), Ill specify the formatting for elements of type section, namely a border or box around each item, margins, padding, and alignment, and a background of white. The complete HTML document in Listing 1-1 is a mixture (some would say a mess!) of features. The elements body and p (paragraph) are part of the original version of HTML. The section element is one of the new element types added in HTML5. The section element does need formatting, unlike body and p, which have default formatting that the body and each p element will start on a new line. CSS can modify the formatting of old and new element types. Notice that the background color for the text in the section is different from the background color for the text outside the section. In the code in Listing 1-1, I specify styles for the body element (there is just one) and the section element If I had more than one section element, the styling would apply to each of them. The style for the body specifies a background color and a color for the text. CSS accepts a set of 16 colors by name, including black, white, red, blue, green, cyan, and pink. You can also specify color using RGB (red green blue) hexadecimal codes, but youll need to use a graphics program, such as Adobe Photoshop, Corel Paint Shop Pro, or Adobe Flash Professional to figure out the RGB values, or you can experiment. I used Paint Shop Pro to determine the RGB values for the green in the frog head picture and used that for the border as well. The text-align directives are just what they sound like: they indicate whether to center the material or align it to the left. The font-size sets the size of text in pixels. Borders are tricky and dont appear to be consistent across browsers. Here Ive specified a solid green border of 4 pixels. The width specification for section indicates that the browser should use 85 percent of the window, whatever that is. The specification for p sets the width of the paragraph at 250 pixels. Padding refers to the spacing between the text and the borders of the section. The margin is the spacing between the section and its surroundings. Listing 1-1. A Complete HTML Document with Styles

CSS example

The background here is tan and the text is the totally arbitrary RED GREEN BLUE value #EE015.
Within the section, the background color is white. There is text with additional HTML markup, followed by a paragraph with text. Then, outside the section there will be text, followed by an image, more text and then a hyperlink.

The border color of the section matches the color of the frog image.


As you may have noticed, I like origami. The next image represents a frog head.

If you want to learn how to fold it, go to the Meyer Family Origami Page

This produces the screen shown in Figure 1-6.

9

CHAPTER 1

Figure 1-6. Sample CSS styles

Tip: Dont be concerned if you dont understand everything immediately—youll find lots of help on the Web. In particular, see the official source for HTML 5 at http://dev.w3.org/html5/ spec/Overview.html .

There are many things you can do with CSS. You can use it to specify formatting for types of elements, as shown above; you can specify that elements are part of a class; and you can identify individual elements using the id attribute. In Chapter 6 where we create a quiz, I use CSS to position specific elements in the window and then JavaScript to move them around.

JavaScript programming JavaScript is a programming language with built-in features for accessing parts of an HTML document, including styles in the CSS element. It is termed a scripting language to distinguish it from compiled languages, such as C++. Compiled languages are translated all at once, prior to use, while scripting languages are interpreted line by line by browsers. This text assumes no prior programming experience or knowledge of JavaScript, but it may help to consult other books, such as Getting Started with JavaScript, by Terry McNavage (friends of ED, 2010), or online sources such as http://en.wikipedia.org/wiki/JavaScript. Each browser owns its version of JavaScript. An HTML document holds JavaScript in a script element, located in the head element. To display the time and date information as shown in Figure 1-2, I put the following within the head element of the HTML document:

JavaScript, like other programming languages, is made up of statements of various types. In later chapters, Ill show you assignment statements, compound statements such as if and switch and for

10

THE BASICS

statements, and statements that create what are called programmer-defined functions. A function is one or more statements that work together in a block and can be called anytime you need that functionality. Functions save writing out the same code over and over. JavaScript supplies many built-in functions. Certain functions are associated with objects (more on this later) and are called methods. The code document.write("hello"); is a JavaScript statement that invokes the write method of the document object with the argument "hello". An argument is additional information passed to a function or method. Statements are terminated by semicolons. This piece of code will write out the literal string of characters h, e, l, l, o as part of the HTML document. The document.write method writes out anything within the parentheses. Since I wanted the information written out to change as the date and time change, I needed a way to access the current date and time, so I used the built-in JavaScript Date function. This function produces an object with the date and time. Later, youll see how to use Date objects to compute how long it takes for a player to complete a game. For now, all I want to do is display the current date and time information, and thats just what the code document.write(Date()); does. To use the formal language of programming: this code calls (invokes) the write method of the document object, a built-in piece of code. The period (.) indicates that the write to be invoked is a method associated with the document produced by the HTML file. So, something is written out as part of the HTML document. What is written out? Whatever is between the opening parenthesis and the closing parenthesis. And what is that? It is the result of the call to the built-in function Date. The Date function gets information maintained by the local computer and hands it off to the write method. Date also requires the use of parentheses, which is why you see so many. The write method displays the date and time information as part of the HTML document, as shown in Figure 1-2. The way these constructs are combined is typical of programming languages. The statement ends with a semi-colon. Why not a period? A period has other uses in JavaScript, such as indicating methods and also for decimal points for numbers. Natural languages, such as English, and programming languages have much in common: different types of statements; punctuation using certain symbols; and a grammar for the correct positioning of elements. In programming, we use the term notation instead of punctuation, and syntax instead of grammar. Both programming languages and natural languages also let you build up quite complex statements out of separate parts. However, there is a fundamental difference: As I tell my students, chances are good that much of what I say in class is not grammatically correct, but theyll still understand me. But when youre “talking” to a computer via a programming language, your code must be perfect in terms of the grammatical rules of the language to get what you want. The good news is that unlike a human audience, computers do not exhibit impatience or any other human emotion so you can take the time you need to get things right. Theres also some bad news that may take you a while to appreciate: If you make a mistake in grammar— termed a syntactic error—in HTML, CSS, or JavaScript, the browser still tries to display something. Its up to you figure out what and where the problem is when you don't get the results you wanted in your work.

Building the application and making it your own You build an HTML document using a text editor and you view/test/play the document using a browser. Though you can use any text editor program to write the HTML, I suggest TextPad for PCs and TextWrangler for Macs. These are shareware, which makes them relatively inexpensive. Dont use a word

11

CHAPTER 1

processing program, which may insert non-text characters. Notepad also works, though TextPad has benefits such as color-coding that Ill demonstrate. To use the editor, you open it up and type in the code. Figure 1-7 shows what the TextPad screen looks like.

Figure 1-7. Starting off in TextPad You will want to save your work frequently and, most important, save it as the file type .html. In TextPad, click on File ➤ Save As and then change the Save as type to HTML, as shown in Figure 1-8.

Figure 1-8. Saving a file as type HTML

12

THE BASICS

Notice that I gave the file a name and that I can also change the folder from My Documents to something else if I want. After saving the file, and clicking on Configure ➤ Word Wrap (to make the long lines visible on the screen), the window appears as shown in Figure 1-9.

Figure 1-9. After saving the file as HTML and invoking word wrap The color coding, which youll see only after the file is saved as HTML, indicates tags and quoted strings. This can be valuable for catching many errors. Now lets delve into the HTML coding, first for the list of annotated links and then for the favorite sites. The code uses the features described in the previous section. Table 1-1 shows the complete code for this application: paragraphs of text with links to different files, all located in the same folder.

13

CHAPTER 1

Table 1-1. The “My games” Annotated Links Code Code

Explanation

Opening html tag

Opening head tag

Annotated links

Opening title tag, the title text and closing title tag

Opening body tag

My games

Opening h1 tag, text and then closing h1 tag. This will make “My games” appear in a big font. The actual font will be the default.



Opening p for paragraph tag

The Dice game presents the game called craps.

Text with an a element. The opening a tag has the attribute href set to the value craps.html. Presumably this is a file in the same folder as this HTML file. The contents of the a element—whatever is between the and the —will be displayed, first in blue and then in mauve once clicked, and underlined.



Closing p tag



Opening p tag

The Cannonball is See the previous case. The a element here a ballistics simulation. A ball appears to move refers to the cannonball.html file and the on the screen in an arc. The program determines displayed text is Cannonball. when the ball hits the ground or the target. The player can adjust the speed and the angle.



Closing p tag



Opening p tag

14

THE BASICS

Code

Explanation

The Slingshot simulates shooting a slingshot. A ball moves on the screen, with the angle and speed depending on how far the player has pulled back on the slingshot using the mouse.

See previous. This paragraph contains the hyperlink to slingshot.html.



Closing p tag



Opening p tag

The Concentration/memory game presents a set of plain rectangles you can think of as the backs of cards. The player clicks on first one and then another and pictures are revealed. If the two pictures represent a match, the two cards are removed. Otherwise, the backs are displayed. The game continues until all matches are made. The time elapsed is calculated and displayed.

See previous. This paragraph contains the hyperlink to memory.html.



Closing p tag



Opening p tag

The Quiz game presents the player with 4 boxes holding names of countries and 4 boxes holding names of capital cities. These are selected randomly from a larger list. The player clicks to indicate matches and the boxes are moved to put the guessed boxes together. The program displays whether or not the player is correct.

See previous. This paragraph contains the hyperlink to quiz1.html



Closing p tag



Opening p tag

15

CHAPTER 1

Code

Explanation

The Maze program is a multi-stage game. The player builds a maze by using the mouse to build walls. The player then can move a token through the maze. The player can also save the maze on the local computer using a name chosen by the player and retrieve it later, even after closing the browser or turning off the computer.

See previous. This paragraph contains the hyperlink to maze.html.



Closing p tag

Closing body tag

Closing html tag

The Favorite Site code has the features of the annotated list with the addition of formatting: a green box around each item and a picture in each item. See Table 1-2. Table 1-2. The Favorites Sites Code Code

Explanation

Opening html tag

Opening head tag

Annotated links

Complete title element: opening and closing tag and Annotated links in between

Closing style tag

Closing script tag

Opening body tag

Favorite Sites

Text surrounded by h3 and /h3 tags. This make the text appear somewhat larger than the norm.

Opening article tag

The Jeanine Meyer's Academic Activities displays information on my current and past courses, along with publications and other activities.

This text will be subject to the style specified. It includes an a element. Notice that the value for the href attribute is a relative reference: it says: go to the parent folder of the current folder and then to the index.html file. Two periods (..) is computer-speak for “go back a folder level”, so if we were in the tree/fruit/apple folder, then ../index.html would take us back to the fruit folder to find the index file, and ../../index.html would take us back to the tree folder.

Closing article tag

Opening article tag

17

CHAPTER 1

Code

Explanation

See previous. Notice that the value for the href attribute The Stolen Chair Theatre
tag. This will force a line break. Company is the web site of a theatre company performing mainly in New York City. This is the postcard for their Summer, 2010 production.


An img tag. The source of the image is the file postcard.jpg. The width is set at 300 pixels.

Closing article tag

Opening article tag

The friends of ED publishers is the site for the publishers of this book.


See previous. This also refers to a Web address. A
tag will force a line break before the image.

An img element. The source is friendsofed.gif. The width is set at 300 pixels.

Closing article tag

Closing body tag

Closing html tag

It is pretty straightforward how to make this application your own: use your own favorite sites. In most browsers, you can download and save image files if you want to use a site logo for the hyperlink, or you can include other pictures. It is my understanding that making a list of sites with comments and including images such as logos is within the practice called “fair use,” but I am not a lawyer. For the most part, people like links to their sites. It doesnt affect the legal question, but you can also choose to set the src in the img tag to the Web address of the site where the image lives if youd rather not download a particular image file to your computer and then upload it to your web site. Web addresses can be absolute or relative. An absolute address starts with http://. A relative address is relative to the location of the HTML file. In my example, the postcard.jpg and the friendsofed.gif are both located in the same folder as my HTML file. They are there because I put them there! For large projects, many people put all the images in a subfolder called images and write addresses as "images/postcard.gif". You also can make this application your own by changing the formatting. Styles can be used to specify fonts, including specific font, font family, and size. This lets you pick a favorite font, and also specify

18

THE BASICS

what font to use if the preferred font is not available on the user's computer. You can specify the margin and padding or vary independently the margin-top, margin-left, padding-top, and so forth.

Testing and uploading the application You need to have all the files, in this case the single HTML file plus all image files, in the same folder unless you are using full Web addresses. For the links to work, you need to have the correct addresses for all href attributes. My examples show how to do this for HTML files in the same folder or for HTML files somewhere else on the Web. You can start testing your work even if it is not completely done. For example, you can put in a single img element or a single a element. Open up a browser, such as Firefox, Chrome, or Safari (I didnt mention Internet Explorer because it does not yet support some of the HTML5 features Ill be using in other tutorials, though support is coming in IE9). In Firefox, click on File and then Open file and browse to your HTML file. In Chrome, press Ctrl on the PC (CMD on the MAC) and o and then browse to the file and click OK to open it. You should see something like my examples. Click on the hyperlinks to get to the other sites. Reload the page using the reload icon for the browser and observe the different time. If you don't see what you expect—something like my examples—you need to examine your code. Common mistakes are

• •



missing or mismatched opening and closing tags. wrong name for image files or HTML files, or wrong file extension for the image files. You can use image files of type JPG, GIF, or PNG but the file extension named in the tag must match the actual file type of the image. missing quotation marks. The color coding, as available in TextPad and some other editors, can help you identify this.

Summary In this chapter, you learned how to compose HTML documents with text, images, and hyperlinks. This included

• • • • •

the basic tags, including html, head, title, style, script, body. the img element for displaying images. the a element for hyperlinks. simple formatting using a style element written following Cascading Style Sheet (CSS) rules. a single line of JavaScript code to provide date and time information.

This chapter was just the beginning, though its possible to produce beautiful and informative web pages using basic HTML, with or without Cascading Style Sheets. In the next chapter, you will learn how to include randomness and interactivity in an application, and how to use the canvas element, the critical feature of HTML5.

19

CHAPTER 1

20

Chapter 2

Dice Game In this chapter, we will cover

• • • •

drawing on canvas random processing game logic form output

Introduction Among the most important new features in HTML5 is the canvas. This element provides a way for developers to make line drawings, include images, and position text in a totally free-form fashion, a significant improvement over the older HTML. Although you could do some fancy formatting in the earlier versions, layouts tended to be boxy and pages less dynamic. How do you draw on the canvas? You use a scripting language, usually JavaScript. I will show you how to draw on canvas and Ill explain the important features of JavaScript that well need to build an implementation of the dice game called craps: how to define a function, how to invoke what is termed pseudo-random behavior, how to implement the logic of this particular game, and how to display information to a player. Before we go any further, though, you need to understand the basics of the game. The game of craps has the following rules: The player throws a pair of dice. The sum of the two top faces is what matters so a 1 and a 3 is the same as 2 and 2. The sum of two 6-sided dice can be any number from 2 to 12. If the player throws a 7 or 11 on the first throw, the player wins. If the player throws a 2, 3, or 12, the player loses. For any other result (4, 5, 6, 8, 9, 10), this result is recorded as what is called the player's point and a follow-up throw is required. On follow-up throws, a throw of 7 loses and a throw of the player's point wins. For anything else, the game continues with the follow-up throw rules. Lets see what our game play might look like. Figure 2-1 shows the result of a throw of two ones at the start of the game.

21

CHAPTER 2

Figure 2-1. First throw, resulting in a loss for the player It is not apparent here, but our dice game application draws the die faces each time using the canvas tag. This means its not necessary to download images of individual die faces. A throw of two 1s means a loss for the player since the rules define 2, 3, or 12 on a first throw as a loss. The next example shows a win for the player, a 7 on a first throw, as shown in Figure 2-2.

Figure 2-2. A 7 on a first throw means the player wins. Figure 2-3 shows the next throw—an 8. This is neither a win nor a loss, but means there must be a followup throw.

22

DICE GAME

Figure 2-3. An 8 means a follow-up throw with a players point of 8 carried over. Let's assume that the player eventually throws an 8 again, as indicated in Figure 2-4.

Figure 2-4. Its another throw of 8, the point value, so the player wins. As the previous sequence shows, the only thing that counts is the sum of the values on the faces of the dice. The point value was set with two 4s, but the game was won with a 2 and a 6. The rules indicate that a game will not always take the same number of throws of the dice. The player can win or lose on the first throw, or there may be any number of follow-up throws. It is the game builder's job is to build a game that works—and working means following the rules, even if that means play goes on and on. My students sometimes act as if their games only work if they win. In a correct implementation of the game, players will win and lose.

23

CHAPTER 2

Critical requirements The requirements for building the dice game begin with simulating the random throwing of dice. At first, this seems impossible since programming means specifying exactly what the computer will do. Luckily, JavaScript, like most other programming languages, has a built-in facility that produces results that appear to be random. Sometimes languages make use of the middle bits (1s and 0s) of a very long string of bits representing the time in milliseconds. The exact method isnt important to us. We will assume that the JavaScript furnished by the browser does an okay job with this, which is called pseudo-random processing. Assuming now that we can randomly get any number from 1 to 6 and do it twice for the two die faces, we need to implement the rules of the game. This means we need a way to keep track of whether we are at a first throw or a follow-up throw. The formal name for this is the application state, which means the way things are right now, and is important in both games and other types of applications. Then we need to use constructs that make decisions based on conditions. Conditional constructs such as if and switch are a standard part of programming languages, and youll soon understand why computer science teachers like me—who have never been in a casino or a back alley—really like the game of craps. We need to give the player a way to throw the dice, so well implement a button on the screen to click for that. Then we need to provide information back to the player on what happened. For this application, I produced graphical feedback by drawing dice faces on the screen and also displayed information as text to indicate the stage of the game, the point value, and the result. The older term for interactions with users was input-output (I/O), back when that interaction mainly involved text. The term graphical user interface (GUI) is now commonly used to indicate the vast variety of ways that users interact with computer systems. These include using the mouse to click on a specific point on the screen or combining clicks with dragging to simulate the effect of moving an object (see the slingshot game in Chapter 4). Drawing on the screen requires the use of a coordinate system to specify points. Coordinate systems for the computer screen are implemented in similar ways in most programming languages, as Ill explain shortly.

HTML5, CSS, and JavaScript features Lets now take a look at the specific features of HTML5, CSS, and JavaScript that provide what we need to implement the craps game.

Pseudo-random processing and mathematical expressions Pseudo-random processing in JavaScript is performed using a built-in method called Math.random. Formally, random is a method of the Math class. The Math.random method generates a number from 0 up to, but not including 1, resulting in a decimal number, for example, 0.253012. This may not seem immediately useful for us, but its actually a very simple process to convert that number into one we can use. We multiply that number, whatever it is, by 6, which produces a number from 0 up to but not including 6. For example, if we multiply the .253012 by 6 we get 1.518072. Thats almost what we need, but not quite. The next step is to strip away the fraction and keep the whole number. To do that, we make use of another Math method, Math.floor. This method produces a whole number after removing any fractional part. As the name suggests, the floor method rounds down. In our particular case, we started with .253012, then arrived at 1.518072, so the result is the whole number 1. In general, when we multiply our random number by 6 and floor it, well get a number from 0 to 5. The final step is to add a 1, because our goal is to get a number from 1 to 6, over and over again, with no particular pattern.

24

DICE GAME

You can use a similar approach to get whole numbers in any range. For example, if you want the numbers 1 to 13, youd multiply the random number by 13 and then add 1. This could be useful for a card game. Youll see similar examples throughout this book. We can combine all of these steps together into what is called an expression. Expressions are combinations of constants, methods, and function calls, and some things well explore later. We put these items together using operators, such as + for addition and * for multiplication. Remember from Chapter 1 how tags can be combined—nesting a tag within another tag—and the one line of JavaScript code we used in the Favorite Sites application: document.write(Date()); We can use a similar process here. Instead of having to write the random call and then the floor method as separate statements, we can pass the random call as an argument of the floor method. Take a look at this code fragment: 1+Math.floor(Math.random()*6) This expression will produce a number from 1 to 6. I call it a code fragment because it isn't quite a statement. The operators + and * refer to the arithmetic operations and are the same as youd use in normal math. The order of operations starts from the inside and works out.

• • • •

Invoke Math.random() to get a decimal number from 0 up to, but not quite 1. Multiply the result by 6. Take that and strip away the fraction, leaving the whole number, using Math.floor. Add 1.

Youll see a statement with this expression in our final code, but we need to cover a few other things first.

Variables and assignment statements Like other programming languages, JavaScript has a construct called a variable, which is essentially a place to put a value, such as a number. It is a way of associating a name with a value. You can use the value later by referencing the name. One analogy is to office holders. In the USA, we speak of “the president.” Now, in 2010, the president is Barack Obama. Before January 21, 2009, it was George W. Bush. The value held by the term “the president” changes. In programming, the value of the variable can vary as well, hence the name. The term var is used to declare a variable. The names of variables and functions, described in the next section, are up to the programmer. There are rules: no internal blanks and the name must start with an alphabetic character. Don't make the names too long as you don't want to type too much, but don't make them so short you forget what they are. You do need to be consistent, but you don't need to obey the rules of English spelling. For example, if you want to set up a variable to hold the sum of values and you believe that sum is spelled som, thats fine. Just make sure you use som all the time. But if you want to refer to something thats a part of JavaScript, such as function or document or random, you need to use the spelling that JavaScript expects. You should avoid using the names of built-in constructs in JavaScript (such as random or floor) for your variables. Try to make the names unique, but still easily understandable. One common method of writing variable names is to use whats called camel case. This involves starting your variable name in lower case, then using a capital letter to denote when a new word starts, for example, numberOfTurns or

25

CHAPTER 2

userFirstThrow. You can see why its called camel case—the capitals form “humps” in the word. You dont have to use this naming method, but its a convention many programmers follow. The line of code that will hold the pseudo-random expression explained in the previous section is a particular type of statement called an assignment statement. For example, var ch = 1+Math.floor(Math.random()*); sets the variable named ch to the value that is the result of the expression on the right-hand side of the equal sign. When used in a var statement, it also would be termed an initialization statement. The = symbol is used for setting initial values for variables as in this situation and in the assignment statements to be described next. I chose to use the name ch as shorthand for choice. This is meaningful for me. In general, though, if you need to choose between a short name and a longer one that you will remember, pick the longer one! Notice that the statement ends with a semi-colon. You may ask, why not a period? The answer is that a period is used in two other situations: as a decimal point and for accessing methods and properties of objects, as in document.write. Assignment statements are the most common type of statements in programming. Heres an example of an assignment statement for a variable already defined: bookname = "The Essential Guide to HTML5"; The use of the equal sign may be confusing. Think of it as making it true that the left-hand side equals whats produced by the right-hand side. Youll encounter many other variables and other uses of operators and assignment statements in this book.

Caution: The var statement defining a variable is called a declaration statement. JavaScript, unlike many other languages, allows programmers to omit declaration statements and just start to use a variable. I try to avoid doing that, but you will see it in many online examples.

For the game of craps, we need variables that define the state of the game, namely whether it is a first throw or a follow-up throw, and what the player's point is (remember that the point is the value of the previous throw). In our implementation, these values will be held by so-called global variables, variables defined with var statements outside of any function definition so as to retain their value (the values of variables declared inside of functions disappear when the function stops executing). You dont always need to use variables. For example, the first application we create here sets up variables to hold the horizontal and vertical position of the dice. I could have put literal numbers in the code because I don't change these numbers, but since I refer to these values in several different places, storing the values in variables mean that if I want to change one or both, I only need to make the change in one place.

Programmer-defined functions JavaScript has many built-in functions and methods, but it doesnt have everything you might need. For example, as far as I know, it does not have functions specifically for simulating the throwing of dice. So JavaScript lets us define and use our own functions. These functions can take arguments, like the Math.floor method, or not, like Math.random. Arguments are values that may be passed to the function. Think of them as extra information. The format for a function definition is the term function followed by the name you want to give the function, followed by parentheses holding the names of any arguments, followed by an open bracket, some code, and then a closed bracket. As I note in the previous sections,

26

DICE GAME

the programmer chooses the name. Heres an example of a function definition that returns the product of the two arguments. As the name indicates, you could use it to compute the area of a rectangle. function areaOfRectangle(wd,ln) { return wd * ln; } Notice the return keyword. This tells JavaScript to send the result of the function back to us. In our example, this lets us write something like rect1 = areaOfRectangle(5,10), which would assign a value of 50 (5  10) to our rect1 variable. The function definition would be written as code within the script element. It might or might not make sense to define this function in real life because it is pretty easy to write multiplication in the code, but it does serve as a useful example of a programmer-defined function. Once this definition is executed, which probably would be when the HTML file is loaded, other code can use the function just by calling its name, as in areaOfRectangle(100,200) or areaOfRectangle(x2x1,y2-y1). The second expression assumes that x1, x2, y1, y2 refer to coordinate values that are defined elsewhere. Functions also can be called by setting certain tag attributes. For example, the body tag can include a setting for the onLoad attribute:

My JavaScript code contains the definition of a function I call init. Putting this into the body element means that JavaScript will invoke my init function when the browser first loads the HTML document or whenever the player clicks on the reload/refresh button. Similarly, making use of one of the new features of HTML5, I could include the button element: Throw dice This creates a button holding the text Throw dice. When the player clicks it, JavaScript invokes the throwdice function I defined in the script element. The form element, to be described later, could invoke a function in a similar way.

Conditional statements: if and switch The craps game has a set of rules. One way to summarize the rules is to say, if it is a first-throw situation, we check for certain values of the dice throw. If its not the first throw, we check for other values of the dice throw. JavaScript provides the if and switch statements for such purposes. The if statement is based on conditions, which can be a comparison or a check for equality—for example, is a variable named temp greater than 85 or does the variable named course hold the value "Programming Games". Comparisons produce two possible logical values—true or false. So far youve seen values that are numbers and values that are strings of characters. Logical values are yet another width="400" height="300"> Your browser doesn't support the HTML5 element canvas.

If an HTML file with this coding is opened by a browser that does not recognize canvas, the message Your browser doesn't support the HTML5 element canvas. appears on the screen. If you were preparing web pages for all common browsers, you could choose to direct visitors to your site to something else or try another strategy. In this book, I just focus on HTML5. The HTML canvas tag defines this element to have an id of "canvas". This could have been anything, but theres no harm in using canvas. You can have more than one canvas, however, and in that case, you would need to use distinct values for each id. Thats not what we do for this application, though, so we dont have to worry about it. The attributes of width and height are set to specify the dimensions of this canvas element. Now that weve seen the canvas in the body, lets look at the JavaScript. The first step in drawing on the canvas is to define the appropriate object in the JavaScript code. To do this, I need a variable so I set up one named ctx with the line var ctx; outside of any function definition. This makes it a global variable that can be accessed or set from any function. The ctx variable is something thats needed for all drawing. I chose to name my variable ctx, short for context, copying many of the examples Ive seen online. I could have chosen any name. Later in the code (youll see all the code in the examples that follow, and you can download it from www.friendsofed.com/downloads.html), I write the code to set the value of ctx. ctx = document.getElementById('canvas').getContext('2d'); What this does is first get the element in the document with the id 'canvas' and then extract what is called the '2d' context. We can all anticipate that the future may bring other contexts! For now, we use the 2d one. In the JavaScript coding, you can draw rectangles, paths including line segments and arcs, and position image files on the canvas. You can also fill in the rectangles and the paths. Before we do this, however, we need to tackle coordinate systems and radian measures. Just as a global positioning system uses latitude and longitude to define your location on the map, we need a way to specify points on the screen. These points are called pixels, and we used them in the previous chapter to specify the width of images and the thickness of borders. The pixel is a pretty small unit of measurement, as you can see if you do any experiments. However, its not enough for everyone to agree on the linear unit. We also need to agree on the point from which we are measuring, just as GPS systems use the Greenwich Meridian and the equator. For the two-dimensional rectangle that is the

30

DICE GAME

canvas, this goes by the name origin or registration point. The origin is the upper left corner of the canvas element. Note that in Chapter 6, when we describe the quiz show by creating and positioning elements in the HTML document and not in a canvas element, the coordinate system is similar. The origin is still the upper left corner of the window. This is different from what you may recall from analytical geometry or from making graphs. The horizontal numbers increase in value moving from left to right. The vertical numbers increase in value moving down the screen. The standard way to write coordinates is to put the horizontal value first, followed by the vertical value. In some situations, the horizontal value is referred to as the x value and the vertical, the y value. In other situations, the horizontal value is the left (think of it as from the left) and the vertical value is the top (think of it as from the top). Figure 2-5 shows the layout of a browser window 900 pixels wide by 600 high. The numbers indicate the coordinate values of the corners and the middle.

Figure 2-5. Coordinate system for browser window. Now well look at several statements for drawing, and then put them together to draw simple shapes (see Figures 2-6 through 2-10). After that well see how to draw the dots and rectangles to represent die faces. Heres the HTML5 JavaScript code for drawing a rectangle: ctx.strokeRect(100,50,200,300); This draws a hollow rectangle, with its top left corner 100 pixels from the left side and 50 pixels down from the top. The rectangle has width 200, and height 300. This statement would use whatever the current settings are for line width and for color. The next piece of code demonstrates setting the line width to 5 and the color of the stroke, that is, the outline to the indicated RGB value, namely red. The rectangle is drawn using the values in the variables x, y, w, and h. ctx.lineWidth = 5; ctx.strokeStyle = "rgb(255,0,0)"; ctx.strokeRect(x,y,w,h);

31

CHAPTER 2

This snippet ctx.fillStyle = "rgb(0,0,255)"; ctx.fillRect(x,y,w,h); draws a solid blue rectangle at the indicated position and dimensions. If you want to draw a blue rectangle with a red outline, you use two lines of code: ctx.fillRect(x,y,w,h); ctx.strokeRect(x,y,w,h); HTML5 lets you draw so-called paths consisting of arcs and line segments. Line segments are drawn using a combination of ctx.moveTo and ctx.lineTo. Ill cover them in a number of chapters: for the slingshot game in Chapter 4, the memory game using polygons in Chapter 5, and Hangman in Chapter 9. In the cannon ball game in Chapter 4, Ill also show you how to tilt a rectangle, and the Hangman game in Chapter 9 demonstrates how to draw ovals. In this chapter, Ill focus on the arcs. You start a path using ctx.beginPath(); and end it, with the path being drawn, with either ctx.closePath(); ctx.stroke(); or ctx.closePath(); ctx.fill(); An arc can be a whole circle or part of a circle. In the dice applications, we draw only whole circles to represent the pips on the face of each die, but Ill explain how arcs work in general to make the code less mysterious. The method for drawing arcs has the following format: ctx.arc(cx, cy, radius, start_angle, end_angle, direction); where cx, cy, and radius are the center horizontal and vertical coordinates and the radius of the circle. To explain the next two parameters requires discussing ways to measure angles. Youre familiar with the degree unit for angles: we speak of making a 180-degree turn, meaning a u-turn, and a 90-degree angle is produced by two perpendicular lines. But most computer programming languages use another system, called radians. Heres one way to visualize radians—think of taking the radius of a circle and laying it on the circle itself. You can dig into your memory and realize that it won't be a neat fit, because there are 2* PI radians around the circle, somewhat more than 6. So if we want to draw an arc that is a whole circle, we specify a starting angle of 0 and an end angle of 2*PI. Luckily, the Math class furnishes a constant Math.PI that is the value of PI (to as much accuracy, as many decimal places, as necessary), so in the code, we write 2*Math.PI. If we want to specify an arc that is half a circle, we use Math.PI, while a rightangle (90 degrees) will be .5*Math.PI. The arc method requires one more argument, direction. How are we drawing these arcs? Think of the movement of the hands on a clock face. In HTML 5, clockwise is the false direction and counterclockwise is the true direction. (Don't ask why. Thats just the way its specified in HTML5.) I use the built-in JavaScript values true and false. This will be important when we need to draw arcs that are not whole circles. The nature of the particular problem dictates how you define the angles if you need to draw arcs that are not full circles.

32

DICE GAME

Here are some examples, with the complete code, for you to create (using TextPad or TextWrangler) and then vary to test your understanding. The first one draws an arc, representing a smile.

Smile



Your browser doesn't support the HTML5 element canvas.

Figure 2-6 shows a portion of the screen with the arc produced by this code.

Figure 2-6. The “smile” produced by the expression ctx.arc(200,200,50,0,Math.PI, false); You can look ahead to Figures 2-11, 2-12 and 2-13 in which I captured more of the screen to see the positioning of the drawing. Please vary the numbers in your own example so you can gain an understanding of how the coordinate system works and how big a pixel actually is. Before going on to see a frown, try making the arc wider or taller or changing the color. Then try moving the whole arc up, down, left, and right. Hint: you need to change the line ctx.arc(200, 200,50,0,Math.PI, false); Change the 200,200 to reset the center of the circle and the 50 to change the radius.

33

CHAPTER 2

Now, lets go on with other variations. Do take each one and experiment with it. Changing the last parameter of the arc method to true: ctx.arc(200,200,50,0,Math.PI,true); makes the arc go in a counterclockwise direction. The complete code is:

Frown



Your browser doesn't support the HTML5 element canvas.

Notice that I also changed the title. This code produces the screen shown in Figure 2-7.

Figure 2-7. The “frown” produced by the expression ctx.arc(200,200,50,0,Math.PI, true); Putting in the statement to close the path before the stroke: ctx.closePath(); ctx.stroke();

34

DICE GAME

in the frown example, will “finish off” the arc. The complete code is

Frown



Your browser doesn't support the HTML5 element canvas.

This produces the screen show in Figure 2-8.

Figure 2-8. The frown becomes a half-circle by adding ctx.closePath(); before ctx.stroke(); The closePath command is not always necessary, but its good practice to include it. Experiment here and also look ahead to the drawing of the slingshot in Chapter 5 and the drawing of the hangman figure in Chapter 9. If you want the path filled in, you use ctx.fill() in place of ctx.stroke(), which produces a black, filled-in shape as shown in Figure 2-9. The complete code is

35

CHAPTER 2

Smile



Your browser doesn't support the HTML5 element canvas.

Black is the default color.

Figure 2-9. Filling in the half circle using ctx.fill() If you want a shape to be filled and have a distinct outline, you use both the fill and the stroke commands and specify different colors using the fillStyle and strokeStyle properties. The color scheme is based on the same red/green/blue codes introduced in Chapter 1. You can experiment or use a tool such as Photoshop or Paint Shop Pro to get the colors you want. Here is the complete code:

Smile



Your browser doesn't support the HTML5 element canvas.

This code produces a half circle filled in with purple (a combination of red and blue), with a stroke, that is, an outline of pure red as shown in Figure 2-10. The coding specifies a path, then draws the path as a fill, and then draws the path as a stroke.

Figure 2-10. Using fill and stroke with different colors A full circle is produced by many different commands, including: ctx.arc(200,200,50,0, 2*Math.PI, true); ctx.arc(200,200,50, 0, 2*Math.PI, false); ctx.arc(200,200,50, .5*Math.PI, 2.5*Math.PI, false); You may as well stick with the first one—its as good as any other. Note that I still use the closePath command. A circle may be a closed figure in geometric terms, but that doesnt matter in terms of JavaScript. If you think of the canvas element as a canvas on which you put some ink or paint, you realize youll need to erase the canvas or the appropriate part of it to draw something new. To do this, HTML5 supplies the command ctx.clearRect(x,y,width,height);

37

CHAPTER 2

Later examples show how to draw a slingshot (Chapter 4), polygons for the memory/concentration game (Chapter 5), walls for a maze (Chapter 7), and the stick figure in Hangman (Chapter 9). Now lets get back to what we need for the dice game.

Displaying text output using a form It is possible to write text on the canvas (see Chapter 5), but for the craps application, I chose to use a form, an element in both the older and current versions of HTML. I don't use the form for input from the player. I do use it for outputting information on the results of the throw of the dice. The HTML5 specification indicates new ways to set up forms, including checking or validating the type and range of input. The application in the next chapter demonstrates validation. I used the following HTML to produce the form for the dice game:

Stage: Point: Outcome:

The form starts with a name attribute. The text Stage:, Point:, and Outcome: appear next to the input fields. The input tags—notice these are singleton tags—have both name and value fields. These names will be used by the JavaScript code. You can put any HTML within a form and a form within any HTML. Because the dice game uses the new button element, I just added the form element with the fields used for displaying information to the player, without including an input element of type submit. Alternatively, I could have used a standard form with a submit input field (eliminating the need for the new button element) with the following code:

Stage: Point: Outcome:

The input element of type submit produces a button on the screen. These are all the concepts we need to build the craps application. We can now go ahead and code it.

Building the application and making it your own You may have already tried using the HTML5, CSS, and JavaScript constructs described in this chapter in small examples. Hint: please do. The only way to learn is to make your own examples. As a way to build up to the craps application, we will now look at three applications:

• • •

38

throwing a single die and reloading to throw again throwing two dice by using a button the complete game of craps

DICE GAME

Figure 2-11 shows a possible opening screen for the first application. I say possible because it won't always be a 4. I deliberately captured this screenshot to show practically all of the window so you can see where the drawing is located on the screen.

Figure 2-11. The single die application Figure 2-12 shows the opening screen of the application for throwing a pair of dice. All that appears is the button.

Figure 2-12. The opening screen of the pair of dice application Lastly, Figure 2-13 shows the screen after the player clicks on the button.

39

CHAPTER 2

Figure 2-13. Clicking the button to throw the pair of dice It is good technique to build your application in incremental steps. These applications are built using a text editor, such as TextPad or TextWrangler. Remember to save the file as type .html— and do this early and often. You dont have to finish before saving. When you complete the first application and have saved and tested it, you can save it once more using a new name and then make the modifications to this new copy to be the second application. Do the same for the third application.

Throwing a single die The purpose of this first application is to display a random die face on the canvas, with circles laid out in the standard way. For any application, there are generally many approaches that would work. I realized that I could get double duty out of some of the coding, because the pattern for the 3 die face could be made by combining the 2 and 1 patterns. Similarly, the pattern for 5 is a combination of 4 and 1. The pattern for 6 is a combination of the one for 4 and something unique. I could have put all the coding into the init function or used a single drawface function. In any case, this made sense to me and I programmed and debugged it fairly fast. Table 2-1 lists all the functions and indicates what calls what. Table 2-2 shows the complete code, explaining what each line does. Table 2-1. Functions in the Singe Die Throw Application Function

Invoked By / Called By

Calls

Init

invoked by action of the onLoad in the tag

drawface

drawface

called by init

draw1, draw2, draw4, draw6, draw2mid

draw1

called by drawface in 3 places for 1, 3 and 5

40

DICE GAME

draw2

called by drawface in 2 faces for 2 and 3

draw4

called by drawface in 3 places for 4, 5 and 6

draw2mid

called by drawface in 1 place for 6

Table 2-2. The Complete Code for the Throwing a Single Die Application Code

Explanation Opening html tag



Opening head tag

Throwing 1 die

Full title element

Close script element

Close head element

Starting body tag, with onLoad attribute set to invoke the init() function

Set up canvas and provide notice if browser doesnt accept canvas element

Your browser doesn't support the HTML5 element canvas.



46

Close body and close html elements.

DICE GAME

If you like, you can put comments in your code. Comments are pieces of text that are ignored by the browser but are there to remind you and, perhaps, others who will look at this program later, what is going on. One form of comment starts with two slashes on a line. Everything to the right of the slashes is ignored. For larger comments, you use a slash and an asterisk to start the comment and an asterisk and a slash to end it. /* This is a comment. */ This is a case of do as I say, not as I do. Since Im using tables to put comments on every line and you can consider the whole chapter a comment, I haven't included comments in the code. You should, however. HINT: when I was developing this code (and any code involving a random effect, I did not want to have to do the initial testing with the random coding. So, right after the line var ch = 1+Math.floor(Math.random()*6); I put the line ch

= 1;

and tested it, then I changed it to ch = 2; and so on. I removed this line (or commented it out using // ) when I was done with this phase of testing. This falls under general advice, to avoid having to play a game, in all its complexity, while developing it.

Throwing two dice The next application makes use of a button to give the player something to do, rather than just reloading the webpage, and it also simulates the throwing of a pair of dice. Before looking at the code, think about what you can carry over from the first application. The answer is: most of it. This second application will need to do something about the positioning of the two die faces, using two more variables for this, dx and dy. It also needs to repeat the code using Math.random and calling drawface twice to produce both die faces. And there needs to be a change in what invokes a throw. Table 2-3, which describes the functions calling and being called is essentially the same as Table 2-1, except now theres a function called throwdice, which is invoked by an action set up by the onClick attribute of the button tag. Table 2-4 contains the full HTML document for the application of throwing two dice. Table 2-3. Functions in the Two-Dice Application Function

Invoked By / Called By

Calls

throwdice

invoked by action of the onClick in the tag

drawface

drawface

called by init

draw1, draw2, draw4, draw6, draw2mid

draw1

called by drawface in 3 places for 1, 3 and 5

47

CHAPTER 2

draw2

called by drawface in 2 faces for 2 and 3

draw4

called by drawface in 3 places for 4, 5 and 6

draw2mid

called by drawface in 1 place for 6

Table 2-4. The Complete Two-Dice Application Code

Explanation

Opening html tag

Opening head tag

Throwing dice

Full title element

Close script element

Close head element

Starting body tag

Canvas tag start

Your browser doesn't support the HTML5 element canvas.

Set up canvas and provide notice if browser doesnt accept canvas element

Close canvas tag




Line break

54

DICE GAME

Code

Explanation

Throw dice

Button element (note attribute onClick setting to invoke throwdice)

Close body tag

Close html tag

The complete game of craps The third application is the complete game of craps. Again, much can be carried over from the previous application. However, now we need to add in the rules of the game. Among other things, this will mean using the conditional statements if and switch, as well as global variables, that is variables defined outside of any function definition, to keep track of whether or not it is a first turn (firstturn) and what is the player's point (point). The function table is identical to the one given for the second application (Table 2-3), so I won't repeat it. Table 2-5 holds the code for this application. The new action is all in the throwdice function. I will comment the new lines. Table 2-5. The Complete Craps Application Code

Explanation

Craps game



Your browser doesn't support the HTML5 element canvas.

62

DICE GAME


Throw dice

Start a form named f

Stage:

With the text Stage: right before it, set up an input field named stage

Point:

Outcome:

With the text Outcome: right before it, set up an input field named outcome

Close the form

Close body

Close html

Making the application your own Making this application your own is not as straightforward as with the favorite sites application, because the rules of craps are the rules of craps. However, there are many things you can do. Change the size and color of the dice faces, using fillRect and setting fillStyle to different colors. Change the color and size of the whole canvas. Change the text for the outcomes to something more colorful. You also can implement other games using standard or specially made dice. You can look ahead to the next chapter and learn about drawing images on the canvas instead of drawing each die face using arcs and rectangles. HTML5 provides a way to bring in external image files. The drawback to this approach is that you do have to keep track of these separate files. You can develop coding for keeping score. For a gambling game, you can start the player with a fixed amount of money, say 100 of whatever the currency unit is, and deduct some amount, say 10, for playing a game, and add some amount, say 20, if and only if the player wins. You can add this bankroll information as part of the form element in the body:

Stage: Point: Outcome: Bank roll:

63

CHAPTER 2

JavaScript (and other programming languages) distinguish between numbers and strings of characters representing numbers. That is, the value "100" is a string of characters, "1","0", and "0". The value 100 is a number. In either case, however, the value of a variable is stored as a sequence of 1s and 0s. For numbers, this will be the number represented as a binary number. For strings of characters, each character will be represented using a standard coding system, such as ASCII or UNICODE. In some situations, JavaScript will make the conversion from one ; ctx.arc(ballx, bally, ballrad,0,Math.PI*2,true); ctx.fill(); For the first version of the bouncing ball, the box is drawn as a rectangle outline. The width of the outline, termed the stroke, is set using ctx.lineWidth = ballrad; You can experiment with the line width. Keep in mind that if you make the width small and set the ball to travel fast, the ball can bounce past the wall in one step. The statement that draws the rectangle is ctx.strokeRect(boxx,boxy,boxwidth,boxheight); I put the code for the ball before the code for the rectangle so the rectangle would be on top. I thought this looked better for the bouncing. The second version of the program displays an image for the ball. This requires code to set up an img object using the new operator with a call to Image(), assigning that to a variable, and giving the src property a value. In the application, we do all this in a single statement, but lets take a look at the individual parts. You read about var statements in Chapter 2. Such statements define, or declare, a variable. It is okay to use the name img for our var here; theres no conflict with the HTML img element. The new operator is wellnamed: it creates a new object, in this case of the built-in type Image. The Image function does not take any arguments, so there are just opening and closing parentheses. Image objects have attributes, just like HTML elements such as img do. The particular image used is indicated by the value of the src attribute. Here, "pearl.jpg" is the name of an image file located in the same folder as the HTML document. The following two statements set up the img variable and set its src (source) to the address, the URL, of the image file. var img = new Image(); img.src="pearl.jpg"; For your application, use the name of an image file youve chosen. It can be of type JPG, PNG, or GIF, and be sure to either put it in the same folder as your HTML document or include the entire path. Be careful about matching the case both in the name and the extension. To draw this image on the canvas, we need a single line of code specifying the image object, the location for the upper left corner of the image, and the width and length to be used in the display of the image. As was the case with the rectangles, this code is a call of a method of a context object, so I use the variable ctx defined in the init function. I need to adjust the ballx and bally values I used for the center of the circle to indicate this upper corner. I use 2 times the ball radius for both the width and the length. The statement is ctx.drawImage(img,ballx-ballrad,bally-ballrad,2*ballrad,2*ballrad);

71

CHAPTER 3

Let's take a break now. Its your turn, dear reader, to do some work. Consider the following HTML document:

The Origami Frog



Your browser doesn't support the HTML5 element canvas.

Find your own image file and use its name in place of frogface.gif. Change the title to something appropriate. Experiment with the line ctx.drawImage(img,10,20,100,100); That is, change the 10, 20 to reposition the image, and change the 100,100 to change the width and the height. Make the changes and see if the program responds as you intended. Remember that as you specify the width and height, you could be changing the shape—the aspect ratio—of the picture. Now try another exercise: drawing two images on the canvas. Youll need to have two different variables in place of img. For this task, give the variables distinctive names. If you are emulating Dr. Seuss, you can use thing1 and thing2; otherwise, choose something meaningful to you! Now, on to more drawing! Lets see how to use gradients for this version of the program. You can use gradients to set the fillStyle property. I didn't want to have the ball on top of a filled in rectangle, so I needed to figure out how to draw the four walls separately. A gradient is a type of object in HTML5. There are linear gradients and radial gradients. In this application we use a linear gradient. The code defines a variable to be a gradient object, using a method of a canvas context that we defined earlier with the variable ctx. The code for the gradient looks like this: var grad; grad=ctx.createLinearGradient(boxx,boxy,boxx+boxwidth,boxy+boxheight); The gradient stretches out over a rectangle shape.

72

BOUNCING BALL

Gradients involve sets of colors. A typical practice is to write code to set what are called the color stops, such as to make the gradient be a rainbow. For this, I set up an array of arrays in a variable named hue. You can think of an array as a holder for a collection of values. Whereas a variable can hold only one value, an array can hold many. In the next chapter, youll read about an array named everything that will hold all the objects to be drawn on the screen. In Chapter 9, which describes the Hangman game, the word list is an array of words. Youll read about many applications of arrays in this book. Heres a concrete example. The following var statement sets up a variable to be a specific array: var family

= ["Daniel","Aviva", "Allison", "Grant", "Liam"];

The variable family is an array. Its >



This is a good example for you to take the time to write and run, both because it showcases timing events and also because it will make you appreciate how long a second lasts. The code takes the value out of the secs input field in the form named f, converts that value to a number, adds 1 to that number, and then converts it back to a string to assign as the value of the secs element. Try replacing the single statement inside the increase function with the statement document.f.secs.value = 1+document.f.secs.value; and see what happens. This is a lesson in the difference between numbers and character strings. Please play around with this little example. If you want to make the numbers go up in smaller increments, change the 1000 to 250 and the 1 to .25. This makes the script show quarter-second changes. If you want to allow your code to stop a particular event, you can set up a global variable (one thats outside of any function). I use a variable named tev, my shorthand for timing event. var tev; You would then modify the setInterval call to be: tev = setInterval(moveball,100); When you wanted to stop this event, youd include this code: clearInterval(tev); To reiterate, the setInterval function sets up a timing event that keeps occurring until it is cleared. If you know you want an event to happen just once, the setTimeout method sets up exactly one event. You can use either method to produce the same results, but JavaScript furnishes both to make things easier. For the bouncing ball application, the moveball function calculates a new position for the ball, does the calculations to check for collisions and when they occur, redirects the ball and draws a new display. This is done over and over—the calls to moveball keep happening because we used setInterval.

77

CHAPTER 3

Calculating a new position and collision detection Now that we know how to draw, and how to clear and redraw, and we know how to do something at fixed intervals, the challenge is how to calculate the new positions and how to do collision detection. Well do this by declaring variables ballx and bally to hold the x and y coordinates of the ball's center; ballvx and ballvy to hold the amount by which the ball position is to be changed, and ballboundx, inboxboundx, ballboundy and inboxboundy to indicate a box slightly smaller than the actual box for the collision calculation. The amounts by which the ball position is to be changed are initialized to 4 and 8 (totally arbitrarily) and are changed if and when a player makes a valid change (see next section) and clicks on the change button. These amounts are termed displacements or deltas and, less formally, velocities or speeds. The change in direction is pretty simple in this situation. If the ball “hits” a vertical wall, the horizontal displacement must change sign; i.e., if the ball was moving 4 units to the right and we hit a wall, we add -4 to its position, which starts it moving to the left. The vertical displacement stays the same. The hit is determined by comparing the next horizontal value with the boundary. Similarly, if the ball “hits” a horizontal wall as determined by comparing the vertical position with the appropriate boundary, the vertical displacement changes sign while the horizontal displacement remains the same. The change is for the next iteration. The check for collisions is done four times, that is, for each of the 4 walls. The calculation consists of comparing the proposed new x or y value, as appropriate, with the boundary condition for the particular wall. The tentative new position is adjusted if the ball center goes past one of the four walls to be exactly at the boundary. This has the effect of making the ball go slightly behind each wall or appear to be squeezed by each wall. The boundary values are set up to be just inside the box with the upper corner at boxx, boxy, a width of boxwidth, and a height of boxheight. I could use a more complex calculation to compare any point on the circle with any point on the walls. However, there is a more fundamental principle involved here. There are no walls and no ball. This is a simulation based on calculations. The calculations are done at intervals. If the ball is moving fast enough and the walls are thin enough, thinner than the ballrad specified here, the ball can escape the box. This is why I do the calculation in terms of the next move and a slightly smaller box. var var var var

boxboundx = boxboundy = inboxboundx inboxboundy

boxwidth+boxx-ballrad; boxheight+boxy-ballrad; = boxx+ballrad; = boxy+ballrad;

Here is the code for the moveandcheck function, the function that checks for collisions and reposition the ball: function moveandcheck() { var nballx = ballx + ballvx; var nbally = bally +ballvy; if (nballx > boxboundx) { ballvx =-ballvx; nballx = boxboundx; } if (nballx < inboxboundx) { nballx = inboxboundx ballvx = -ballvx; } if (nbally > boxboundy) { nbally = boxboundy;

78

BOUNCING BALL

ballvy =-ballvy; } if (nbally < inboxboundy) { nbally = inboxboundy; ballvy = -ballvy; } ballx = nballx; bally = nbally; } You might say that not much actually happens here and youd be correct. The variables ballx and bally are modified to be used later when things get drawn to the canvas. It is not obvious from this code, but do keep in mind that vertical values (y values) increase going down the screen and horizontal values (x values) increase going from left to right.

Validation Caution: As of this writing, some validation works in Chrome, and perhaps other browsers, but not in Firefox.

HTML5 provides new facilities for validating form input. The creator of a form can specify that an input field is of type number as opposed to text, and HTML5 will immediately check that the user/player entered a number. Similarly, we can specify max and min values. The code for the form is

Horizontal velocity
Vertical velocity

The input is still text, that is, a string of characters, but the values are to be text that can be interpreted as a number in the indicated range. Other types of input include "email" and "URL" and it is very handy to have HTML5 check these. Of course, you can check any character string to see if its a number using isNumber and more complicated coding, including regular expressions (patterns of characters that can be matched against), to check for valid email addresses and URLs. One common tactic for checking an e-mail address is to make the user type it in twice so you can compare the two and make sure the user hasnt made any mistakes. We want to take advantage of the work HTML5 will do for us, but we also want to let the user/player know if something is wrong. You can use HTML5 and CSS to do this, by specifying a style for valid and invalid input. input:valid {background:green;} input:invalid {background:red;}

79

CHAPTER 3

HTML5 validation is not fully operational in all browsers, so I won't spend a lot of time on it. If youre using a compliant browser, such as Chrome, you can test out the example given in the next section. Notice that the ball keeps bouncing even if an invalid value, say "abc" is entered where a number was specified, because the program continues to use the current settings.

Tip: Validating input and generating appropriate feedback to users is important in any application. Among the new features HTML5 provides is a pattern attribute in the input element in which a special language called regular expressions can be used to specify valid input. Put HTML5 regular expressions into a search field to find up-to-date information.

HTML page reload Before continuing, I want to mention some issues that may cause unexpected problems. Browsers come with reload/refresh buttons. The document is reloaded when the button is clicked. We made use of this in the simple die throw application in Chapter 2. However, at times you may want to prevent a reload and, in such cases, you can put a return (false); in functions that dont have anything to return to keep the page from reloading. When a document has a form, reloading does not always reinitialize the form input. You may need to leave the page and then reload it using the full URL. Lastly, browsers try to use files previously downloaded to the client (user) computer rather than requesting files from a server based on inspection of the date and time. The files on the client computer are stored in what is called the cache. If you think you made a change but the browser isn't displaying the latest version, you may need to take steps such as clearing the cache.

Building the application and making it your own I will now explain the code for the basic bouncing ball application; the application that uses an image for the ball and gradients for the walls; and the one that validates the input. Table 3-1 shows all the function calls and what is being called. This is the same for all three applications. Table 3-1. Functions in the Bouncing Ball Applications Function

Invoked By/Called By

Calls

init

Action of onLoad in the body tag

moveball

moveball

Invoked directly by init and by action of setInterval

moveandcheck

moveandcheck

Invoked by moveball

change

Invoked by action of onSubmit in the form tag

The moveandcheck code could be part of the moveball function. I chose to separate it because it is a good practice to define functions that perform specific actions. Generally, more, smaller functions are

80

BOUNCING BALL

better than fewer, larger ones when youre developing applications. By the way, when doing your own programming, dont forget to put comments in the code as described in Chapter 2. And add blank lines to make the code more readable. Table 3-2 shows the code for the basic bouncing ball application and explains what each line does. Table 3-2. The Bouncing Ball Application Code

Explanation

Start html

Start head

Bouncing Ball with inputs

Close script

Close head

Start body element. Set up call to init function

Start of canvas element

Your browser doesn't support the HTML5 element canvas.

Message for non-compliant browsers

Close canvas element




Line break

84

BOUNCING BALL

Code

Explanation

Start of form. Give name and id (may need for some browsers). Set up action on submit button.

Horizontal velocity

Label an input field for horizontal velocity




Line break

Vertical velocity

Label an input field for vertical velocity

Submit button

Close form

Close body

Close html

The application that uses an image as the ball and the gradient-filled walls is very similar. Table 3-3 shows all the code—but I just comment the code that is different. Im not being lazy; the idea is to let you see how each application is built on the previous one. Table 3-3. The Second Application, with an Image as the Ball and Gradient-Filled Walls Code

Explanation

Bouncing Ball with inputs



This browser doesn't support the HTML5 canvas element.




Horizontal velocity
Vertical velocity

90

BOUNCING BALL

Code

Explanation



I chose to put the modest change of the style information in the first application. Table 3-4 shows the third bouncing ball application, with form validation. Again, I have only commented the new code, but I include all the code for completeness sake. Table 3-4. The Third Bouncing Ball Application, with Form Validation Code

Explanation

Bouncing Ball with inputs



94

BOUNCING BALL

Code

Explanation

Your browser doesn't support the HTML5 element canvas.




Horizontal velocity
Vertical velocity



There are many ways you can make this application your own. You can select your own image for the ball and experiment with the colors for the walls, with or without the gradients. You can change the position and the dimensions of each wall. You can add text and HTML markup to the page. You can change the look of the form. You can include more than one ball, keeping track of the positions of each. If you decide to use two balls, you need two sets of variables and two lines of code for each one line you had before. One systematic way to do this is to use the search function in the editor to find all instances of ball and, for each line, substitute two lines, so in place of ballx, you have ball1x and ball2x, and in place of the var ballx = 50; use var ball1x = 50; var ball2x = 250; This puts the second ball 200 pixels over on the canvas. You would also need a second set of all the comparisons for the walls.

95

CHAPTER 3

If you want to use more than two balls, you may want to consider using arrays. Subsequent chapters will show you how to handle sets of objects. You also can try writing code that slows the ball each time it hits a wall. This is a nice effect and does simulate a real physical result. In each of the places in the code where the direction is changed by changing the sign of the appropriate variable, add in a factor to decrease the absolute value. For example, if I chose to decrease the value by 10%, I would write if (nballx > boxboundx) { ballvx =-ballvx *.9; nballx = boxboundx; } This means that the incremental change in the vertical direction would go down to 90% of what it was.

Testing and uploading the application The first and third applications are complete in the HTML documents. The second application requires the image file to be present in the same folder. You can access files anywhere on the Web, but you need to make sure you include the correct address. For example, if you upload the HTML document to a folder called mygames and upload pearl.jpg to a subfolder of mygames named images, the line indicating this must be img.src = "images/pearl.jpg"; You must also use accurate file extensions, such as JPG, that indicate the correct file type. Some browsers are forgiving but many are not. You can try to submit bad > var ctx; function init(){ ctx = document.getElementById('canvas').getContext('2d'); ctx.fillStyle = "rgb(250,0,0)"; ctx.fillRect(50,50,100,200); ctx.fillStyle = "rgb(0,0,250)"; ctx.fillRect(50,50,5,5); }



Your browser doesn't support the HTML5 element canvas.



103

CHAPTER 4

The result is shown in Figure 4-6.

Figure 4-6. Rectangle (no rotation) In this exercise, the goal is to rotate the large rectangle, pivoting on the upper-left corner where the small blue square is. I want the rotation to be counterclockwise. One slight complication, common to most programming languages, is that the angle input for rotations as well as the trigonometry functions must be in radians, not degrees. Radians were explained in Chapter 2, but heres a reminder. Instead of 360 degrees in a full circle, the measurement is based on two times the mathematical constant pi radians in a circle. Fortunately, we can use the built-in feature of JavaScript, Math.PI. One pi radians is equivalent to 180 degrees and pi divided by 2 is equivalent to a right angle, 90 degrees. To specify a rotation of 30 degrees, we use pi divided by 6 or, in coding, Math.PI/6. To change the init function given previously to do a rotation, I put in a rotation of negative pi divided by 6 (equivalent to 30 degrees going counterclockwise), draw the red rectangle, and then rotate back, undo the rotation, to draw the blue square: function init(){ ctx = document.getElementById('canvas').getContext('2d'); ctx.fillStyle = "rgb(250,0,0)"; ctx.rotate(-Math.PI/6); ctx.fillRect(50,50,100,200); ctx.rotate(Math.PI/6); ctx.fillStyle = "rgb(0,0,250)"; ctx.fillRect(50,50,5,5); } Unfortunately, the drawing in Figure 4-7 is not what I wanted.

104

CANNONBALL AND SLINGSHOT

Figure 4-7. Drawing and rotating a rectangle The problem is the rotation point is at the origin, (0,0) and not at the corner of the red rectangle. So, I need to write code to perform a translation, then the rotation, then a translation back in order to draw at the correct place. I can do this using features of HTML5. All drawing on the canvas is done in terms of a coordinate system, and I can use the save and restore operations to save the current coordinate system—the position and orientation of the axes—and then restore it to make follow-on drawings. Heres the code. function init(){ ctx = document.getElementById('canvas').getContext('2d'); ctx.fillStyle = "rgb(250,0,0)"; ctx.save(); ctx.translate(50,50); ctx.rotate(-Math.PI/6); ctx.translate(-50,-50); ctx.fillRect(50,50,100,200); ctx.restore(); ctx.fillStyle = "rgb(0,0,250)"; ctx.fillRect(50,50,5,5); } The rotate method expects an angle in radian units and clockwise is the positive direction. So my code is rotating 30 degrees counterclockwise, producing what I had in mind, as shown in Figure 4-8.

Figure 4-8. Save, translate, rotate, translate, restore

105

CHAPTER 4

By the way, we can't expect our players to put in angles using radians. They, and we, are too accustomed to degrees (90 degrees is a right angle, 180 degrees is your arc when you make a u-turn, etc.). The program must do the work. The conversion from degrees to radians is to multiply by pi/180.

Note: Most programming languages use radians for angles in trig functions. Flash uses degrees in certain situations and radians in others, so in some ways JavaScript is less confusing by only using radians.

With this background, I add to the information in the everything array indications as to whether there is to be a rotation and, if so, the required translation point. This is my idea. It has nothing to do with HTML5 or JavaScript, and it could have been done differently. The underlying task is to create and maintain information on objects in the simulated scene. The canvas feature of HTML5 provides a way to draw pictures and display images, but it does not retain information on objects! The items in the everything array for the second and third applications are themselves arrays. The first (0 th index) value points to the object. The second (1st index) is true or false. A value of true means that a rotation angle value and x and y values for translation follow. In practice, this means that the inner arrays have either two values, with the last one being false, or five values.

Note: At this point, you may be thinking: she set up a general system just to rotate the cannon. Why not put in something just for the cannon? The answer is we could, but the general system does work and something just for the cannon might have had just as much coding.

The first application uses horizontal and vertical displacement values picked up from the form. The player must think of the two separate values. For the second application, the player inputs two values again, but they are different. One is the speed out of the mouth of the cannon and the other is the angle of the cannon. The program does the rest. The initial and unchanging horizontal displacement and the initial vertical displacement are calculated from the player's input: the velocity out of the cannon and an angle. The calculation is based on standard trigonometry. Luckily, JavaScript provides the trig functions as part of the Math class of built-in methods. Figure 4-9 shows the calculation of the displacement values from the out of cannon and angle values specified by the player. The minus sign for the vertical is due to the way JavaScript screen coordinates have y values increasing going down the screen.

106

CANNONBALL AND SLINGSHOT

Figure 4-9. Calculating horizontal * vertical displacements At this point, you may want to skip ahead to read about the implementation of the cannonball applications. You can then come back to read about what is required for the slingshot.

Drawing line segments For the slingshot application, I have added a new object type by defining two functions, Sling and drawsling. My idealized slingshot is represented by 4 positions, as shown in Figure 4-10. Please understand that we could have done this in a number of different ways.

Figure 4-10. The idealized slingshot Drawing the slingshot consists of drawing four line segments based on the four points. The bx,by point will change as Ill describe in the next section. HTML5 lets us draw line segments as part of a path. Weve already used paths for drawing circles. You can draw a path as a stroke or as a fill. For the circles, we used the fill method, but for the slingshot, I just want lines. Drawing a line may involve two steps: move to one end of the line and then draw it. HTML5 provides the moveTo and lineTo methods. The path is not drawn until the stroke or fill method is invoked. The drawsling function is a good illustration of line drawing. function drawsling() { ctx.strokeStyle = this.strokeStyle; ctx.lineWidth = 4; ctx.beginPath();

107

CHAPTER 4

ctx.moveTo(this.bx,this.by); ctx.lineTo(this.s1x,this.s1y); ctx.moveTo(this.bx,this.by); ctx.lineTo(this.s2x,this.s2y); ctx.moveTo(this.s1x,this.s1y); ctx.lineTo(this.s2x,this.s2y); ctx.lineTo(this.s3x,this.s3y); ctx.stroke(); } It does the following:

• • • •

adds adds adds adds

to path a line from bx,by to s1x,s1y to path a line from bx,by to s2x,s2y to path a line from s1x,s1y to s2x,s2y to path a line from s2x,s2y to s3x,s3y

As always, the way to learn this is to experiment with your own designs. If theres no invocation of moveTo, the next lineTo draws from the destination of the last lineTo. Think of holding a pen in your hand and either moving it on the paper or lifting it up and moving without drawing anything. You also can connect arcs. Chapter 5 demonstrates drawing polygons.

Mouse events for pulling on the slingshot The slingshot application replaces form input with mouse drag and drop operations. This is appealing because its closer to the physical act of pulling back on a slingshot. When the player presses down on the mouse button, it is the first of a sequence of events to be managed by the program. Here is pseudo-code for what needs to be done. When the player presses the mouse button, check if the mouse is on top of the ball. If not, do nothing. If so, set a variable named inmotion. If the mouse is moving, check inmotion. If it is set, move the ball and the strings of the slingshot. Keep doing this until the mouse button is released. When the player releases the mouse button, reset inmotion to false. Calculate the angle and initial velocity of the ball and from these calculate the horizontal velocity and the initial vertical velocity. Start the ball moving. You can use HTML5 and JavaScript to set up event handling for pressing the standard (left) mouse button, moving the mouse, and releasing the mouse button. The code uses a method based on the canvas element directly, not the so-called context. Here is the code, which is in the init function: canvas1 = document.getElementById('canvas'); canvas1.addEventListener('mousedown',findball,false); canvas1.addEventListener('mousemove',moveit,false); canvas1.addEventListener('mouseup',finish,false); Now because this event is in terms of the whole canvas, the findball function must determine if the mouse is over the ball. The first task is to get the mouse x and y coordinates. Unfortunately, different browsers implement mouse events in different ways. The following works for Firefox, Chrome, and Safari.

108

CANNONBALL AND SLINGSHOT

When other browsers, such as Internet Explorer, support HTML5, this code will need to be checked and, possibly, modified. if ( ev.layerX || ev.layerX==0) { mx= ev.layerX; my = ev.layerY; } else if (ev.offsetX || ev.offsetX==0 ) { mx = ev.offsetX; my = ev.offsetY; } This works because if ev.layerX does not exist, its value will be interpreted as false. If ev.layerX does exist but has value 0, its value will also be interpreted as false, but ev.layerX==0 will be true. Think of this code as saying: is there a good ev.layerX value? If so, let's use it. Otherwise, let's try ev.offsetX. If neither of these work, mx and my will not get set and I should add another else clause to tell the player that the code doesn't work in his browser. Now, the next step is to determine if the (mx,my) point is on the ball. I am repeating myself, but it is important to understand that the ball is now the equivalent of ink or paint on canvas and we cant go any further without determining whether the (mx,my) point is on top of the ball. How do we do this? We can calculate how far (mx,my) is from the center of the ball and see if thats less than the radius of the ball. There is a standard formula for distance in the plane. My code is a slight variation on this idea. It makes the determination by calculating the square of the distance and comparing it to the square of the ball's radius. I do this to avoid computing the square root. If the mouse click was on the ball, that is, within a radius distance of the center of the ball, this function sets the global variable inmotion to true. The findball function ends with a call to drawall(). Whenever the mouse moves, theres a call to the moveit function where we check whether inmotion is true. If it isn't, nothing happens. If it is, the same code as before is used to get the mouse coordinates and the ball's center, and the bx,by values for the slingshot are set to the mouse coordinates. This has the effect of dragging the ball and stretching the slingshot strings. When the mouse button is released, we call the finish function, which doesn't do anything if inmotion is not true. When would this happen? If the player is moving the mouse around not on the ball and pressing and releasing the button. If inmotion is true, the function immediately sets it to false and does the calculations to determine the flight of the ball, generating the information that in the earlier cannonball application was entered by the player using a form. The information is the angle with the horizontal and the distance of the ball to the straight part of the slingshot. This is the angle formed by (bx,by) to (s1x, s1y), and the horizontal and the distance from (bx,by) to (s1x, s1y), more precisely, the square of the distance. I use Math.atan2 to do these calculations: calculating an angle from change in x and change in y. This is a variant of the arctangent function. I use the distsq function to determine the square of the distance from (bx,by) to (s1x, s1y). I want to make the velocity dependent on this value. Pulling the strings back farther would mean a faster flight. I did some experiments and decided that using the square and dividing by 700 produced a nice arc.

109

CHAPTER 4

The last step is to put in a call first to drawall() and then to setInterval to set up the timing event. Again, finish does an analogous job to fire in the first and second applications. In the first application, our player entered the horizontal and initial vertical values. In the second application, the player entered an angle (in degrees) and a velocity out of the mouth of the cannon, and the program did the rest. In slingshot, we did away with a form and numbers and provided a way for the player to pull back, or virtually pull back, on a slingshot. The program had more to do, both in terms of responding to mouse events and calculations.

Changing the list of items displayed using array splice The last task to explain is the replacement of the target image with another picture. Since I wanted two different effects, I used different approaches. For the second application, I wanted the ball to disappear along with the original target and display what I set up in the variable htarget. What I do is keep track of where the original target was placed on the everything array and remove it and substitute htarget. Similarly, I remove the ball from the everything array. For the slingshot operation, I don't remove the target but change its img property to be feathers. Please note that in the code, chicken and feathers are Image objects. Each has a src property that points to a file. var chicken = new Image(); chicken.src = "chicken.jpg"; var feathers = new Image(); feathers.src = "feathers.gif"; For both of these operations, I use the array method splice. It has two forms: you can just remove any number of elements or you can remove and then insert elements. The general form of splice is arrayname.splice(index where splice is to occur, number of iterms to be removed, new item(s) to be added) If more than one item is to be added, there are more arguments. In my code, I add a single item, which is itself an array. My representation of objects in the everything array uses an array for each object. The second argument of the array indicates if there is any rotation. The following two lines of code do what I need: remove the target, stick in htarget with no rotation, and then remove the ball. everything.splice(targetindex,1,[htarget,false]); everything.splice(ballindex,1); By the way, if I simply wanted to remove the last item in an array, I could use the method pop. In this situation, however, the target may be somewhere in the middle of the everything array, so I need to write code to keep track of its index value.

Distance between points There are two places in the slingshot program in which I use the distance between points or, more accurately, the square of the distance. I need to find out if the mouse cursor is on top of the ball and I want to make the initial velocity—the equivalent of the velocity out of the cannon— depending on the stretch, so to speak, of the slingshot, the distance (bx,by) to (s1x, s1y). The formula for the distance between two points x1,y1 and x2,y2 is the square root of the sum of the squares of (x1-x2) and (y1-y2). I decided to avoid the computation of taking a square root by just computing the sum of the squares. This provides the same test for the mouse cursor being on top of the ball. For the other task, I decided it was okay to use the

110

CANNONBALL AND SLINGSHOT

square of the distance for the initial velocity. I experimented with some numbers and, as I mentioned earlier, 700 seemed to work.

Building the application and making it your own Lets now take a look at the code for the basic firing of a cannonball, without a cannon, based on horizontal and initial vertical speeds; the firing of a cannonball from a cannon, based on angle and initial speed out of the cannon; and the slingshot, based on angle and initial speed determined from the position of the mouse. As in previous chapters, Ill present the functions and what they call or are called by for each application. In this case, the tables are similar, though not identical, for all three applications. The calling is more varied than previous examples in that there are situations in which functions are invoked because they are named as methods of a programmer-defined object or as part of a declaration (var) statement. This is a characteristic of object-oriented, event-driven programming. Ill also present the complete code for each application in its own table, along with an explanation of what each line does. Table 4-1 shows the functions for the basic cannonball application. Table 4-1. Functions in the Simplest Cannonball Application Function

Invoked By / Called By

Calls

init

Action of the onLoad in body tag

drawall

drawall

Invoked directly by init, fire, change

Calls the draw method of all objects in the everything array. These are the functions drawball, drawrects.

fire

Invoked by action of the onSubmit attribute drawall in form

change

Invoked by action of the setInterval function called in fire

Ball

Invoked directly by code in a var statement

Myrectangle

Invoked directly by code in a var statement

drawball

Invoked by call of the draw method for the one Ball object

drawrects

Invoked by call of the draw method for the target object

moveball

Invoked by call of the moveit method for the one Ball object

drawall, calls the moveit method of cball, which is moveball

111 3

CHAPTER 4

Table 4-2 shows the complete code for the simplest application, with the ball moving in an arc and no actual cannon. Table 4-2. The First Cannonball Application Code

Explanation

Opening html tag

Opening head tag

Cannonball

Complete title element



Close script element

Close head element

Open body and set call to init

Define canvas

Your browser doesn't support the HTML5 element canvas.

Warning to users of non-compliant browsers

Close canvas




Line break

Starting form tag, with name and id. This sets up call to fire.

Set velocities and fire cannonball.


Label and line break

Horizontal displacement

Label and specification of input field




Line break

Initial vertical displacement

Label and specification of input field

Submit input element

Close form element

117

CHAPTER 4

Code

Explanation

Close body element

Close html element

You certainly can make improvements to this application, but it probably makes more sense to first make sure you understand it as is and then move on to the next.

Cannonball: with cannon, angle, and speed Our next application adds a rectangle to represent the cannon, a picture for the original target instead of the simple rectangle used in the first application, and a second picture for the hit target. The cannon rotates as specified by input in the form. I made the everything array an array of arrays because I needed a way to add the rotation and translation information. I also decided to make the result more dramatic when the cannonball hits the target. This means the code in the change function for checking for a collision is the same, but the code in the if-true clause removes the old target, puts in the hit target, and removes the ball. Now, having said all this, most of the coding is the same. Table 4-3, which shows the functions, has two additional lines for Picture and drawAnImage. Table 4-3. Functions in the Second Cannonball Application Function

Invoked By / Called By

Calls

init

Action of the onLoad in body tag

drawall

drawall

Invoked directly by init, fire, change

Calls the draw method of all objects in the everything array. These are the functions drawball, drawrects.

fire

Invoked by action of the onSubmit attribute in form

drawall

change

Invoked by action of the setInterval function called in fire

drawall, calls the moveit method of cball, which is moveball

Ball

Invoked directly by code in a var statement

Myrectangle

Invoked directly by code in a var statement

drawball

Invoked by call of the draw method for the one Ball object

drawrects

Invoked by call of the draw method for the target object

118

CANNONBALL AND SLINGSHOT

Function

Invoked By / Called By

Calls

moveball

Invoked by call of the moveit method for the one Ball object

Picture

Invoked directly by code in var statements

drawAnImage

Invoked by call of the draw method for a Picture object

Table 4-4 shows the complete code for the second application, but only the changed lines have comments. Table 4-4. The Second Cannonball Application Explanation

Code

Cannonball



126

Remove target and insert htarget

Remove the ball

CANNONBALL AND SLINGSHOT

Code

Explanation

Your browser doesn't support the HTML5 element canvas.




Set velocity, angle and fire cannonball.
Velocity out of cannon

Label indicating that this is the velocity out of mouth of cannon


Angle

Label indicating that this is the angle of the cannon



This application provides many possibilities for you to make it your own. You can change the cannon, the ball, the ground, and the target. If you don't want to use images, you can use drawings for the target and the hit target. You can draw other things on the canvas. You just need to make sure that the cannonball (or whatever you set your projectile to be) is on top or wherever you want it to be. You could, for example, make the ground cover up the ball. You can use an animated gif for any Image object, including the htarget. You could also use images for the cannon and the ball. One possibility is to use an animated gif file to represent a spinning cannonball. Remember that all image files referenced in the code must be in the same folder as the uploaded HTML file. If they are in a different place on the Web, make sure the reference is correct.

127

CHAPTER 4

The support for audio and video in HTML5 varies across the browsers. You can look ahead to the presentation of video as a reward for completing the quiz in Chapter 6, and to the audio presented as part of the rock-paper-scissors game in Chapter 8. If you want to tackle this subject, it would be great to have a sound when the cannonball hits the target and a video clip showing the target exploding. Moving away from the look of the game, you can invent a scoring system, perhaps keeping track of attempts versus hits.

Slingshot: using a mouse to set parameters of flight The slingshot application is built on the cannonball application. There are differences, but much is the same. Reviewing and understanding how more complicated applications are built on simpler ones will help you to create your own work. Creating the slingshot application involves designing the slingshot, and implementing the mouse events to move the ball and parts of the slingshot, and then fire the ball. The form is absent because the player's moves are just the mouse actions. In addition, I used a somewhat different approach for what to do when the target was hit. I check for the ball to intersect with an area within the target by 40 pixels. That is, I require the ball to hit the middle of the chicken! When theres a hit, I change the target.src value to be another Image element, going from a picture of a chicken to a picture of feathers. Moreover, I don't stop the animation, so the ball only stops when it hits the ground. As I indicated earlier, I don't have the slingshot slings return to their original position, as I wanted to see the position to plan my next attempt. Table 4-5 shows the functions calling and being called in the slingshot application. This table is quite similar to the one for the cannonball applications. Table 4-5. Functions in the Slingshot Application Function

Invoked By / Called By

Calls

init

Action of the onLoad in body tag

drawall

drawall

Invoked directly by init,

Calls the draw method of all objects in the everything array. These are the functions drawball, drawrects.

fire, change findball

Invoked by action of addEventListener in init for the mousedown event

distsq

Called by findball

moveit

Invoked by action of addEventListener in init for the mousemove event

drawall

finish

Invoked by action of the addEventListener in init for the mouseup event

drawall

128

drawall

CANNONBALL AND SLINGSHOT

Function

Invoked By / Called By

Calls

change

Invoked by action of the setInterval function drawall, calls the moveit method of called in finish cball, which is moveball.

Ball

Invoked directly by code in a var statement

Myrectangle

Invoked directly by code in a var statement

drawball

Invoked by call of the draw method for the one Ball object

drawrects

Invoked by call of the draw method for the target object

moveball

Invoked by call of the moveit method for the one Ball object

Picture

Invoked directly by code in var statements

drawAnImage

Invoked by call of the draw method for a picture object

Sling

Invoked directly by code in var statements

drawsling

Invoked by call of the draw method for mysling

Table 4-6 shows the code for the slingshot application, with the new or changed lines commented. Notice that the form is absent from the body element. Before looking at the code, try to identify what parts will be the same as in the cannonball application and what would be different. Table 4-6. The Slingshot Application Code

Explanation

Slingshot pulling back



Your browser doesn't support the HTML5 element canvas.


Hold mouse down and drag ball. Releasing the mouse button will shoot the slingshot. Slingshot remains at the last position. Reload page to try again.

Instructions for using mouse



139

CHAPTER 4

Testing and uploading the application These applications can be created without external image files, but using images for the target and the hit target is fun, so you remember to include those files when you upload your project. You can choose your own targets. Perhaps you feel kindly towards chickens! Youll need to test that the program performs correctly in three situations: when the ball plops down to the left of the target, when the ball hits the target, and when the ball sails over the target. Note that I massaged the values so that the chicken needs to be hit in the middle, so it is possible for the ball to touch the head or tail and not cause the feathers to appear. You can vary the position of the cannon and its target and hit target, and the slingshot and the chicken and the feathers, by changing the variables such as startrockx, and you can modify the gravity variable. If you put the slingshot closer to the target, you can have more ways to hit the chicken: pulling more to the left for a direct shot versus pulling down for more of a lob. Enjoy! As I mentioned, you could use an animated gif for the hit target in either the cannonball or slingshot applications. This would produce a nice effect.

Summary In this chapter, you learned how to create two ballistics applications. It is important to understand how they are the same and how they are different. The programming techniques and HTML5 features include

• • • • • • • •

programmer-defined objects setInterval to set up a timing event for the animation, as done for the bouncing ball building an array using the push method and using the array as a list of what to display modifying arrays using the splice method the use of trig functions with calculations to rotate the cannon and to resolve the horizontal and vertical velocities so as to simulate gravity using a form for player input handling mouse events (mousedown, mousemove, mouseup), with addEventListener to obtain player input move drawing arcs, rectangles, lines and images on a canvas

The technique of programmer-defined objects and the use of an array of objects to display will come up again in later chapters. The next chapter focuses on a familiar game known as either memory or concentration. It will use a different timing event as well as the Date function, introduced in Chapter 1.

140

Chapter 5

The Memory (aka Concentration) Game In this chapter, we will cover

• • • • • •

drawing polygons placing text on the canvas programming techniques for representing information programming a pause calculating elapsed time one method of shuffling a set of card objects

Introduction This chapter demonstrates two versions of a card game known variously as memory or concentration. Cards appear face down, and the player turns over two at a time (by clicking on them) in an attempt to find matched pairs. The program removes matches from the board but [virtually] flips back cards that do not match. When players make all the matches, the game shows the elapsed time. The first version of the game I describe uses polygons for the face cards; the second uses family photos. Youll notice other differences, which were made to illustrate several HTML5 features, but I also urge you to think about what the versions have in common. Figure 5-1 shows the opening screen of version one. When a player completes the game, the form that keeps track of matches also shows the elapsed time.

141

CHAPTER 5

Figure 5-1. Opening screen of the memory game, version one Figure 5-2 displays the result after a player has clicked on two cards (the purple squares). The depicted polygons dont match, so after a pause the program replaces them with images of the card backs, making the cards appear to have flipped over.

Figure 5-2. Two card fronts: no match

142

THE MEMORY (AKA CONCENTRATION) GAME

When two cards match, the application removes them and notes the match in the form (Figure 5-3).

Figure 5-3. The application has removed the two cards that matched. As illustrated in Figure 5-4, the game displays the result—in this case, 6 matches in 36 seconds—when the player finishes.

Figure 5-4. Version one of the game after the player has completed it.

143

CHAPTER 5

In version two of the game, the card fronts display photographs of people rather than polygons. And note that although many memory games consider images to be the same only if theyre completely identical, this one is similar to a 2 of Hearts matching a 2 of Diamonds in a deck of playing cards. To illustrate a programming point, well define a match as the same person, even in differing pictures. This requires a method of encoding the information we use to determine matching states. Version two of the game also demonstrates writing text on the canvas, as you can see in Figure 5-5, which depicts the opening screen.

Figure 5-5. The memory game, version two, opening screen To see one possible result of clicking on two cards in our new game, look at Figure 5-6.

Figure 5-6. This screen shows non-matching photos.

144

THE MEMORY (AKA CONCENTRATION) GAME

Because the result shows two different people—after pausing to let the player view both pictures—the application flips the cards over and lets the player try again. Figure 5-7 shows a successful selection— two images of the same person (albeit in different pictures).

Figure 5-7. This screenshot shows a match (different scenes, but the same person). The application removes matched images from the board. When all cards are removed, the time taken to complete the game appears along with instructions on how to play again, as shown in Figure 5-8.

Figure 5-8. The final screen of the game (photo version). All images have been matched, so no cards appear. You can play the game using photos available for download from the books page on the Friends of ED web site (www.friendsofed.com/), but its more fun to use your own. You can start with a small number—say two or three pairs of images—then work up to images of the whole family, class, or club. And for version one of the game, you can replace the polygons with your own designs.

145 7

CHAPTER 5

Critical requirements The digital versions of the games require ways to represent the card backs (which are all the same) and the fronts with their distinct polygons or photos. The applications must also be able to tell which cards match and where cards are on the board. Additionally, players require feedback. In the real-world game, participants flip over two cards and look for a match (which takes a few moments). If theres none, they flip the cards face down again. The computer program must show the faces of the selected cards and pause after revealing the second card so players have time to see the two faces. This pause is an example of something required for a computer implementation that occurs more-or-less naturally when people play the game. The application should also display the current number of pairs found and, when the game is complete, the length of time participants took to find them all. The polygon and photo versions of the program use different approaches to accomplish these tasks. Heres a summary of what the two game versions must do:

• • • • • •

Draw the card backs. Shuffle the cards before a player makes an initial selection so the same array of choices doesnt appear every time. Detect when a player clicks on a card, and distinguish between a first and a second click. On detecting a click, show the appropriate card face by: drawing polygons in the case of game version one or displaying the correct photograph for version two. Remove pairs that match. Operate appropriately even if those pesky players do the unexpected, such as clicking on the same card twice or on an empty space formerly occupied by a card.

HTML5, CSS, JavaScript features Lets go over the specific HTML5 and JavaScript features that provide what we need to implement the games. Well build on material covered previously: the general structure of HTML documents; how to draw rectangles, images, and paths made up of line segments on a canvas element; programmer-defined and built-in functions; programmer objects; the form element; and arrays. New HTML5 and JavaScript features include the time out event, the use of Date objects for the calculation of elapsed time, writing and drawing text on the canvas, and several useful programming techniques that youll find valuable in future applications. As in the previous chapters, this section describes the HTML5 features and programming techniques in general terms. You can see all the code in context in the “Building the Application” section. If you like, you can skip to that section to see the code, then return here for explanations of how the features work.

Representing cards When we hold a physical card in our hands, we can see what it is. Theres a card face and back, and the backs are all the same. We can clearly determine the cards positions on the game board and whether their faces or backs show. To implement a computer game, we must represent—encode—all that information. Encoding is an essential part of creating many computer applications, not just games.

146

THE MEMORY (AKA CONCENTRATION) GAME

In this chapter (and throughout the book), I describe one way to accomplish the task. Keep in mind, though, that theres rarely just one way to implement a feature of an application. That said, different strategies for building an application will likely have some techniques in common. Our approach to handling cards will employ a programmer-defined object. Creating a programmer-defined object in JavaScript involves writing the constructor function; in this case well call it Card. The advantage of using programmer-defined objects is that JavaScript provides the dot notation needed to access information and code for objects of a common type. We did this for the cannonball and slingshot games in Chapter 4. Well give the Card object properties that will hold the cards location (sx and sy) and dimensions (swidth and sheight), a pointer to a function to draw a back for the card, and for each case, the information that specifies the appropriate front (info). In the case of a polygon, the value of info will indicate the number of sides to be drawn. (In a later section well discuss the code for drawing it.) For a photo card face, the value will be a reference, img, to an Image object weve created. The object will hold a specific image file along with a number (info) that ties together pictures that match. To draw the image for the file, well use the built-in drawImage method. Needless to say, the cards dont exist as physical entities, with two sides. The application draws the cards face or back on the canvas where the player expects to see it. The function flipback draws the cards back. To give the appearance of a removed card, flipback effectively erases a card by drawing a rectangle thats the color of the board. Both applications use a function named makedeck to prepare the deck, a process that includes creation of the Card objects. For the polygon version of the game, we store the number of sides (from three to eight) in the Card objects. The application draws no polygons during setup, though. The photos version sets up an array called pairs, listing the image file names for the photos. You can follow this example to create your own family or group memory game.

Tip: If you use the online code to play the game, as noted earlier, you can download the image files. To make the game your own, you need to upload the pictures and then change the code to reference your files. The code indicates what you need to change.

The makedeck function creates the Image objects and uses the pairs array to set the src property to the image object. When the code creates Card objects, it puts in the index value that controls the pairs array so that matched photos have the same value. As in the polygon version, the application draws no image on the canvas during the creation of the deck. On the screen, the cards all appear the same; the information is different, though. These cards are in fixed positions—shuffling comes later. The code interprets position information, the sx and sy properties, differently for Card and Polygon. In the first case, the information refers to the upper-left corner. In the second case, the value identifies the center of the polygon. You can compute one from the other, though.

Using Date for timing We need a way to determine how long the player took to make all the matches. JavaScript provides a way to measure elapsed time. You can view the code in context in the “Building the Application section.” Here I

147

CHAPTER 5

provide an explanation of how to determine the number of seconds between two distinct events in a running program. A call to Date() generates an object with date and time information. The two lines starttime = new Date(); starttime = Number(starttime.getTime()); store the number of milliseconds (thousands of a second) since the start of 1970 in the variable starttime. (The reason JavaScript uses 1970 doesnt matter.) When either of our two memory programs determines the game is over, it invokes Date() again as follows: var now = new Date(); var nt = Number(now.getTime()); var seconds = Math.floor(.5+(nt-starttime)/1000); This code

1.

creates a new Date object and stores it in the variable now.

2.

extracts the time using getTime, converts it to Number, and assigns it to the variable nt. This means nt holds the number of milliseconds from the start of 1970 until the point at which the code called Date. The program then subtracts the saved starting time, starttime, from the current time, nt.

3.

divides by 1,000 to get to seconds.

4.

adds .5 and invokes Math.floor to round the result up or down to whole seconds.

If you need more precision than seconds provides, omit or modify the last step. You can use this code whenever you need to calculate time elapsed between two events in a program.

Providing a pause When we play memory using real cards, we dont consciously pause before flipping nonmatching cards face down. But as noted earlier, our computer implementation must provide a pause so players have time to see the two differing cards. You may recall from chapters 3 and 4 that the animation applications— bouncing ball, cannonball, and slingshot—used the JavaScript function setInterval to set up events at fixed time intervals. We can employ a related function, setTimeout, in our memory games. (To see the complete code in context, go to the “Building the Application” section.) Lets see how to set up the event and what happens when the pause time runs out. The setTimeout function sets up a single event, which we can use to impose a pause. The choose function, called when a player clicks on the canvas, first checks the firstpick variable to determine if the person has made a first or second selection. In either case, the program draws the card front on the canvas in the same spot as the card back. If the click was a second choice and the two cards match, the code sets the variable matched to true or false, depending on whether the cards did or didnt match. If the application determines that the game isnt over, the code invokes setTimeout(flipback,1000);

148

THE MEMORY (AKA CONCENTRATION) GAME

This leads to a call to the flipback function in 1,000 milliseconds (1 second). The function flipback then uses the matched variable to determine whether to redraw card backs or erase the cards by drawing rectangles with the table background color at the appropriate card locations. You can use setTimeout to set up any individual timed events. You need to specify the time interval and the function you want invoked when the interval expires. Remember that the time unit is milliseconds.

Drawing text HTML5 includes a mechanism for placing text on the canvas. This provides a much more dynamic, flexible way to present text than previous versions. You can create some good effects by combining text placement with the drawing of rectangles, lines, arcs, and images weve already demonstrated. In this section, well outline the steps for placing text in a canvas element, and well include a short example that you can try. If you want, skip ahead to the “Building the Application” section to view the complete description of the code that produces what you see in Figures 5-5 through 5-8 for the photos version of the memory game. To put text on the canvas, we write code that sets the font, and then we use fillText to draw a string of characters starting at a specified x-y location. The following example creates words using an eclectic set of fonts (see the caution note later in the section).

Fonts



Your browser doesn't support the HTML5 element canvas.

This HTML document produces the screenshot shown in Figure 5-9.

149

CHAPTER 5

Figure 5-9. Text in different fonts drawn on the canvas, produced using the font and fillText functions

Caution: Make sure you pick fonts that will be present on the computers of all your players. In Chapter 10 youll learn how to use a CSS feature, called font-family, that provides a systematic way to specify a primary font and backups.

Note that although what you see appears to be text, youre actually looking at ink on the canvas—that is, bitmap images of text, not a text field that you can modify in place. This means that to change the text, we need to write code that will completely erase the current image. We do so by setting the fillStyle to the value we placed in the variable tablecolor earlier, and use fillRect at the appropriate location and with the necessary dimensions. After creating the text image, the next step is to set fillStyle to a color other than tablecolor. Well use the color we chose for the card backs. For the opening screen display of the photograph memory game, heres the code to set the font used for all text: ctx.font="bold 20pt sans-serif"; Using the sans-serif font makes sense, since its a standard font present on any computer. Putting together what weve done to this point, heres the code to display the number of matches at a particular point in the game: ctx.fillStyle= tablecolor; ctx.fillRect(10,340,900,100); ctx.fillStyle=backcolor; ctx.fillText ("Number of matches so far: "+String(count),10,360);

150

THE MEMORY (AKA CONCENTRATION) GAME

The first two statements erase the current tally and the next two put in the updated result. The expression "Number of matches so far: "+String(count) deserves more explanation. It accomplishes two tasks:

• •

It takes the variable count, which is a number, and turns it into a string of characters. It concatenates the constant string "Number of matches so far: " with the result of String(count).

The concatenation demonstrates that the plus sign has two meanings in JavaScript: If the operands are numbers, the sign indicates addition. If the operands are character strings, it indicates the two strings should be concatenated—put together. A fancy phrase for a single symbol having several meanings is operator overloading. What will JavaScript do if one operand is a string and the other a number? The answer depends on which of the two operands is what >

156

Start the script element. The type specification isnt necessary but is included here because youll see it.

var ctx;

Variable that holds the canvas context

var firstpick = true;

Declare and initialize firstpick

var firstcard;

Declare a variable to hold the info defining the first pick

var secondcard;

Declare a variable to hold the info defining the second pick

var frontbgcolor = "rgb(251,215,73)";

Set the background color value for the card fronts

var polycolor = "rgb(254,11,0)";

Set the color value for the polygons

var backcolor = "rgb(128,0,128)";

Set the color value for card backs

THE MEMORY (AKA CONCENTRATION) GAME

var tablecolor = "rgb(255,255,255)";

Set the color value for the board (table)

var cardrad = 30;

Set the radius for the polygons

var deck = [];

Declare the deck, initially an empty array

var firstsx = 30;

Set the position in x of the first card

var firstsy = 50;

Set the position in y of the first card

var margin = 30;

Set the spacing between cards

var cardwidth = 4*cardrad;

Set the card width to four times the radius of the polygons

var cardheight = 4*cardrad;

Set the card height to four times the radius of the polygons

var matched;

This variable is set in choose and used in flipback

var starttime;

This variable is set in init and used to calculate elapsed time

function Card(sx,sy,swidth,sheight,info) {

Header for the Card function, setting up card objects

this.sx = sx;

Set the horizontal coordinate

this.sy = sy;

… vertical coordinate

this.swidth = swidth;

… width

157

CHAPTER 5

this.sheight = sheight;

…. height

this.info = info;

… info (the number of sides)

this.draw = drawback;

Specify how to draw

}

Close the function

function makedeck() {

Function header for setting up the deck

var i;

Used in the for loop

var acard;

Variable to hold the first of a pair of cards

var bcard;

Variable to hold the second of a pair of cards

var cx = firstsx;

Variable to hold the x coordinate. Start out at the first x position.

var cy = firstsy;

Will hold the y coordinate. Start out at the first y position.

for(i=3;i