HTML and CSS Reference
In-Depth Information
This should appear reasonable for describing four sets of audio files, but you may be wondering how
the code knows which one to play. We could insert id attributes in each <audio> tag. However, lets
do something else instead in order to demonstrate more JavaScript thats useful in many situations.
You have seen the method document.getElementById . There is a similar method:
document.getElementsByTagname . The line:
musicelements = document.getElementsByTagName("audio");
extracts all elements of the tag name indicated by the parameter and creates an array, which, in this line
of code, assigns the array to a variable named musicelements . We use this line in the init function so
its performed at the very start of the application. We construct another array of arrays, this one called
music, and add two other global variables:
var music = [
[3,1,0],
[1,3,2],
[0,2,3]];
var musicelements;
var musicch;
You can check that music and beats are parallel structures with 0 standing for rock crushing scissors, 1
for paper covering rock, 2 for scissors cutting paper, and 3 for a tie. The choose function will have the
extra line:
musicch = music[compch][i];
The musicch variable—the name stands for choice for music—will hold 0, 1, 2, or 3. This sets up
something to happen in the flyin function when the animation is complete. We don't play the clip
immediately, as explained in my confession above.
musicelements[musicch].play();
The zeroth, first, second, or third element in musicelements is referenced by the indexing using musicch ,
then its play method is invoked and the clip is played.
Starting off
The application starts by setting up a call to a function in the onLoad attribute of the <body> tag. This has
been the practice in the other games. The init function performs several tasks. It sets the initial score
value to zero. This is necessary just in case the player reloads the document; it is a quirk of HTML that
form data may not be reset by the browser. The function extracts values from the canvas element to be
used for drawing ( ctx ) and for the event handling ( canvas1 ). This needs to happen after the whole
document is loaded because until then the canvas element does not exist. The function draws the three
buttons and sets up the font for the text drawn on the canvas and the fill style. After that, nothing happens
unless and until the player clicks the mouse button over one of the three symbols.
Now that weve examined the specific features of HTML5 and JavaScript used for this game, along with
some programming techniques, such as the use of arrays of arrays, lets take a closer look at the code.
 
Search WWH ::




Custom Search