Java Reference
In-Depth Information
The
ask()
function accepts a
question
parameter. This combination of function name
and parameter name is used to make the code very descriptive ― it reads almost like an
English sentence: "Ask the question". It uses a prompt dialog and returns the text entered
by the player, which is then saved in a variable called
answer
.
The
check()
function is written after the
ask()
function and has an
answer
parameter.
This combination of function name and parameter name again make the code read more
like an English sentence. Naming functions in this way means that we don't need to use
comments to explain what the code does in this case, as it's self-explanatory:
scripts.js
(excerpt)
function check(answer) {
if(answer === quiz[i][1]){ // quiz[i][1] is the ith
answer
alert("Correct!");
// increase score by 1
score++;
} else {
alert("Wrong!");
}
}
This function uses the same logic that we used in the last chapter to check if the answer
entered by the player is the same as the answer stored in the array. If it is, then we increase
the score by
1
and if it isn't then we show an alert dialog to say so.
When all the questions have been asked and all the answers have been checked, the pro-
gram breaks out of the loop and then invokes the
gameOver()
function. This is also
defined at the bottom of the
playQuiz
function as follows:
scripts.js
(excerpt)
function gameOver(){
// inform the player that the game has finished and
tell them
↵
how many points they have scored
alert("Game Over, you scored " + score + " points");
}
}
