HTML and CSS Reference
In-Depth Information
score by 1, which is the effect we want when the player loses a round. Adding 0 leaves the score as is.
Now, you may think that it would be easier to do nothing in the case of ties rather than add zero, but
handling this in a uniform way is the easier approach in terms of coding, and adding zero may actually take
less time than doing an if test to see if it was a tie.
The first index into each array will come from the computer move, compch , and the second index, i ,
indicating the element in the inner array, will come from the player move. The beats and points arrays are
called parallel structures. The beats array is for the text message and the points array is for the scoring.
Let's check that the information is correct by picking a computer move, say scissors, which corresponds
to 2, and picking a player move, say rock, which corresponds to 0. In the beats array, the value for the
computer move tells us to go to the array with index value 2. (I am avoiding saying the second array, since
arrays start with index 0, not with 1. The value indicated by 2 is the third element of the array). The element
is:
["You win: rock crushes scissors.","You lose: scissors cuts paper.",
"TIE: you both threw scissors"]];
Now use the player value, namely 0, to index this array. The result is "You win: rock crushes
scissors." and this is exactly what we want. Doing the same thing with the points array, the element
with index 2 is
[1,-1,0]
and the value with index 0 into this array is 1, also exactly what we want: the player's score will be
adjusted by 1.
result = beats[compch][i];
newscore +=points[compch][i];
Recall that the operator += in a statement
a += b;
is interpreted as follows:
Get the value of the variable a
Apply the + operator to this value and the value of the expression b
Assign the result back to the variable a
The second step is written in a general way since this could apply to + interpreted as addition of numbers
as well as concatenation of strings. In this particular situation, the second step is:
Add a and b
This result gets assigned back to the variable a.
The two variables, result and newscore , are global variables. This means they are available to other
functions and this is how we use them: set in one function and referenced for use in another.
The score is presented using a form element in the body element of the HTML document.
<form name="f">
Score: <input name="score" value="0" size="3"/>
</form>
 
Search WWH ::




Custom Search