ROCK, PAPER, SCISSORS
var scib = new Throw(scissorsbx,scissorsby,8,50,50,"rgb(0,0,200)","scissors.jpg");
As in our previous applications, an array named everything is declared and initialized to the empty array.
We push all three variables onto the everything array so we can treat them systematically.
everything.push(rockb);
everything.push(paperb);
everything.push(scib);
For example, to draw all the buttons, we use a function called drawall that iterates over the elements in
the everything array.
function drawall() {
ctx.clearRect(0,0,cwidth,cheight);
var i;
for (i=0;i<everything.length;i++) {
everything[i].draw();
}
}
Again, this is more general than required, but its useful, especially when it comes to object-oriented
programming, to keep things as general as possible.
But how to make these graphics act as clickable buttons? Because these are drawn on the canvas, the
code needs to set up the click event handling for the whole canvas and then use coding to check which, if
any, button was clicked.
In the slingshot game described in Chapter 4, you saw code in which the function handling the mousedown
event for the whole canvas made a calculation to see if the mouse cursor was on the ball. In the quiz show
described in Chapter 6, we set up event handling for each country and capital block. The built-in
JavaScript mechanism indicated which object had received, so to speak, the click event. This application
is like the slingshot.
We set up the event handling in the init function, explained in full in the next section. The task is to get
JavaScript to listen for the mouse click event and then do what we specify when the click happens. What
we want is for the function choose to be invoked. The following two lines accomplish this task.
canvas1 = document.getElementById('canvas');
canvas1.addEventListener('click',choose,false);
Tip: Our code needs to distinguish between the element with the id canvas and the property of this
element returned by getContext('2d'). Thats just the way the HTML5 folks decided to do it. It is
not something you could have deduced on your own.
The choose function has the tasks of determining which type of throw was selected, generating the
computer move and setting up the display of that move, and applying the rules of the game. Right now,
were just going to take a look at the code that determines what button has been clicked.
The code starts by handling differences among the browsers. Functions that are invoked as a result of a
call to addEventListener are called with a parameter holding information about the event. This
parameter, ev as we are calling it in the choose function, is examined to see what attributes exist to be