Java Reference
In-Depth Information
call this
function until it isn't
if(option === question ||
options.indexOf(option.answer) !==
-1) {
return chooseOption();
}
return option;
}
}
In the code, we first set the asked property of the question to true to stop the question
from being asked again later in the game. We then create an empty array called options
to store the different options that will be presented to the player. Two options are chosen
using the nested function called chooseOption() . This uses the random() function
to pick a question at random from all the questions, and then checks to see if that question
has already been chosen (and therefore already in the options array) or is currently being
asked. If either of these are true, the function calls itself again and does this recursively
until it eventually returns a valid option. After two options have been chosen, the actu-
al question is inserted into the options array at a random place. This is done using the
splice() array method with the return value of the random() function given as an ar-
gument.
The function then loops through each question held in the options array and creates a
button element with a value attribute that corresponds to its answer property. Each but-
ton is then appended to the form as a child element, so three buttons will be presented to
the player, one of which will present the correct answer.
The answer will be submitted when the player clicks on one of the buttons contained in
the form. This means that we need to change the event listener to listen for click events
instead of the submit event. Change the code for the event listener to the following:
// add event listener to form for when it's submitted
$form.addEventListener('click', function(event) {
check(event.target.value);
}, false);
Search WWH ::




Custom Search