HTML and CSS Reference
In-Depth Information
Generating the computer move
Generating the computer move is similar to generating a throw of the dice, as we did in the dice game in
Chapter 2. In the rock-paper-scissors game, we want a random selection from three possible throws
instead of six possible die faces. We get that number with the line:
var compch = Math.floor(Math.random()*3);
The call to the built-in method
Math.random()
produces a number from zero up to, but not including, 1.
Multiplying this by
3
produces a number from 0 up to, but not including, 3. Applying
Math.floor
produces
a whole number not larger than its argument. It rounds the number down, knocking off any values over the
highest integer floor. Therefore, the expression on the right produces 0, 1, or 2, which is exactly what we
want. This value is assigned to
compch
which is declared (set up) as a variable.
The code takes the computer move, one of the numbers 0, 1, or 2 chosen by the calculation involving the
random function, and uses it as an index for the
choices
array:
var choices = ["rock.jpg","paper.gif","scissors.jpg"];
These three elements refer to the same three pictures used in the buttons.
At this point, just in case you were concerned, the ordering rock, paper, scissors is arbitrary. We need to
be consistent, but the ordering does not matter. If, at every instance, we made the ordering paper,
scissors, rock, everything would still work. The player never sees the encoding of 0 for rock, 1 for paper,
and 2 for scissors.
The next lines in the
choose
function extract one of the file names and assign it to the
src
attribute of an
Image variable
compimg
.
var compchn = choices[compch];
compimg.src = compchn;
The name of the local variable,
compchn
, stands for computer choice name. The
compimg
variable is a
global variable holding an Image object. The code sets its
src
property to the name of the appropriate
image file, which will be used to display the computer move.
To implement the rules of the game, I set up two arrays:
var beats = [
["TIE: you both threw rock.","You win: paper covers rock.",
➥
"You lose: rock crushes scissors."],
["You lose: paper covers rock.","TIE: you both threw paper.",
➥
"You win: scissors cuts paper."],
["You win: rock crushes scissors.","You lose: scissors cuts paper.",
➥
"TIE: you both threw scissors"]];
And:
var points = [
[0,1,-1],
[-1,0,1],
[1,-1,0]];
Each of these is an array of arrays. The first holds all the messages and the second holds the amount to
add to the score of the player. Adding 1 increases the player's score. Adding a -1 decreases the player's