Java Reference
In-Depth Information
Quiz Ninja Project
Now that we have a good understanding of functions, we're going to have a go at refactor-
ing the code for our Quiz Ninja project so that it uses functions to describe the main parts of
the program. Refactoring is the process of improving the code's structure and maintainabil-
ity without changing its behavior.
What we're going to do is replace some of the chunks of code with functions. This will make
the code easier to follow and maintain because if we want to make a change to the function-
ality, all we need to do is change the code inside the relevant function.
Open up the scripts.js file in the js folder and replace all the code with the following:
scripts.js (incomplete)
var quiz = [
["What is Superman's real name?","Clarke Kent"],
["What is Wonderwoman's real name?","Dianna Prince"],
["What is Batman's real name?","Bruce Wayne"]
];
var score = 0 // initialize score
play(quiz);
The first part of this code remains the same ― we set up an array of questions and answers
that is stored in the quiz variable and then declare a score variable initialized to 0 to
keep track of the player's score. The last line contains an important change, though ― we
invoke a function called play() and pass the quiz array to it as an argument. This is the
main game function that contains all the steps of playing the game. Let's write that function
now by adding the following lines of code to the end of our scripts.js file (remember that,
because of hoisting, function definitions can go after they are invoked):
scripts.js (excerpt)
function play(quiz){
// main game loop
for(var i=0, question, answer, max=quiz.length; i<max;
Search WWH ::




Custom Search