ࡱ > 9 ; 6 7 8 a ; bjbj .V M\M\3 X X X X X l l l l , D l ( t ( ' ' ' ' ' ' ' $ ) F, ' X ' X X ' X X ' ' # $ @<ߕ # ' ' 0 ( # , , , $ $ , X #$ d > , I $ m ' ' R ( , > : JavaScript Tutorial: Alternative coin toss This tutorial describes how to prepare a coin toss program using HTML5, namely drawing the coin faces on canvas and using clicking on the canvas as the event that triggers the action. It would be beneficial to have read my tutorial for a coin toss using a form and an img tag. This repeats much of the material and it is important to appreciate what is the same and what is different. The starting screen for the HTML5 coin toss is When the player clicks in the outlined rectangle, a coin face appears: In this case, this is the tail (reverse) of the Native American $1 coin series. When I clicked again on a different place, this screen appeared: It is important to recognize that the action is based on pseudo-random processing, so you may not get tail / head /tail / head, etc. Repeating the format of the other tutorial, here are the critical tasks to be done. Key Design Issues Task: Generate a value randomly between zero and one. Logic: JavaScript, in common with most other programming systems, has facilities for generating what are termed pseudo-random numbers. The qualifier 'pseudo' is used because the computer system performs a well-defined procedure but the results appear to be random. Solution: We will use the JavaScript function Math.random that generates a fraction from zero to (just under) one. Task: Make a decision, choosing to execute one set of statements versus another based on a value. Logic: JavaScript, in common with most other programming systems, has conditional statements. Solution: Use JavaScript's if statement. An expression, called the condition, is evaluated. If it is true, then one set of statements is executed; otherwise, another set is executed. The if statement is a form of compound statement. That is, it contains individual statements. Task: Make an image appear on the canvas Logic: HTML5 and JavaScript provide ways to draw images on canvas at specified x, y positions and with specified width and height. Solution: Acquire (and modify as appropriate) image files representing the head and tail of a coin. Write the JavaScript that sets up Image objects and use the decision logic to draw one or the other on the canvas at a particular place. This is var head = new Image(); head.src = "head.gif"; var tail = new Image(); tail.src="tail.gif"; In the clauses of the if statement, you will write either if (Math.random()>.5) { ctx.drawImage(head,mx,my, 100,100); } else { ctx.drawImage(tail,mx,my,100, 100); } The calculation for mx and my are described in the next task. Task: Implement the tossing of the coin. Logic: You want the player to click on the canvas, indicated by an outline. HTML5 JavaScript provides a way to set up this event. Solution: The event handling is done using the addEventListener method. canvas1 = document.getElementById('canvas'); canvas1.addEventListener('click',toss,false); The exact coordinates of the click will be used to position the image drawn. Unfortunately, this requires some browser-specific coding. The following works in the browsers I've tested (Chrome, Firefox). I'm told it works for Opera and Safari: (Note: I have made some updates to this to take care of a new problem with Chrome.) function toss(e) { var mx; var my; if (!e) var e = window.event; if (e.pageX || e.pageY) { mx = e.pageX; my = e.pageY; } else if (e.clientX || e.clientY) { mx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; my = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } This example has some of this code in separate function, called getCoords. HYPERLINK "http://faculty.purchase.edu/jeanine.meyer/html5/bunnycover.html" http://faculty.purchase.edu/jeanine.meyer/html5/bunnycover.html The mx and my are the positions where the mouse cursor was located within the canvas. Now keep in mind that the drawImage method positions an image using the upper left corner to be at the specified coordinates. Since I want the center of the image to appear at the point clicked by the mouse, I wrote code to adjust these values: mx = mx -50; my = my-50; Background After spending some time learning that computers do just what we tell them to do, you may ask how can we get 'the computer' to do something that appears to be random. Because random results are what is required for games and other applications, such as testing that a system works under a variety of conditions, the developers of languages such as JavaScript have developed what is called pseudo-random functions. The term 'pseudo' is meant to convey that in one sense, this is not random behavior at all. The code executed is as defined as the code for addition or subtraction. It is just that the result appears to be random. One common technique is to for the code to go to the place in memory that holds the time. This could be a sequence of bits (a bit is a 1 or a zero) typically 64 bits long. The next step is to take the middle 32 bits of this sequence, multiply it by itself, take the middle 32 bits of the answer and interpret this as a fraction between zero (including zero) and not more than one (not including the value 1). You do not need to know or fully understand the particular algorithm used. To produce the coin toss program (and others), you just need to know that JavaScript has many mathematical functions available for your use. The format for calling these functions is as methods of the Math object. The one for random values, is Math.random(). Whenever you use this expression, JavaScript will generate a value greater than or equal to zero and less than one. You will put the logic for coin tossing in a function defined within a script tag in the head section of the HTML document. This function is invoked through a call to addEventListener as a method to the canvas element. See code below for setting up the variable canvas1 to BE the canvas element. Implementation You need to do some preparation before testing any code, so you may as well do it right away. Prepare 2 image files: head.gif tail.gif You can download images of coins. The terminology used is obverse and reverse as opposed to head and tail. Since my implementation was to make the coin images appear anywhere, including on top of each other, I decided that it would be nice if the surrounding for each round image was transparent, so a white background wouldn't appear on top of an image previously drawn as shown below: This meant that after downloading the two images, which were jpg files, I opened them up in Corel Paint Shop Pro and used Export GIF Optimizer to save them with the white converted to be transparent. Adobe PhotoShop has a similar facility. Make sure both of these files are in the same folder as the code you are about to produce. We now describe the coding. We do this using the language of HTML. This is to help you understand the components of the file and not just copy and paste. Open up Text Pad or Text Wrangler or, if you have it Adobe Dreamweaver. Create the standard boilerplate for an HTML5 page with a canvas element. I'm showing the DOCTYPE tag because some browsers may require it. I also included the instructions to Click to toss coin.