Java Reference
In-Depth Information
i++) {
question = quiz[i][0];
answer = ask(question);
check(answer);
}
// end of main game loop
gameOver();
}
This function also contains a number of functions that help to describe how the game runs,
without getting bogged down with too much of the actual logic. It loops through the quiz
array and selects a question. This is an array containing the question at index 0 and the cor-
responding answer at index 1 that is stored in the variable question . The next step is to
ask the question (by invoking the ask() function), then checks the answer the player gives
(by invoking the check() function). After we have looped through every question in the
quiz array, the game is over, so the gameOver() function is invoked. This shows how
code can be simplified abstracting it into separate functions that are descriptively named.
It is also useful as it allows us to change the content of the functions at a later time; if we
decide that the way to check a question will change, for example, all we need to do is edit
the check() function.
Now we need to write the ask() and check() functions. These functions need to be
placed inside the play() function as nested functions. This will give them access to any
variables defined inside the play() function, which is important as they both require ac-
cess to the variables that are defined within the scope of the play() function. So these
functions must also be defined inside the scope of the play() function in order to have
access to the variables.
First of all, let's write the ask() function. This goes at the bottom of the play() function
block (before the closing curly brace):
scripts.js (excerpt)
function ask(question) {
return prompt(question); // quiz[i][0] is the ith
questions
}
Search WWH ::




Custom Search