With our variables initialized, we can create the answer(
) function, which will record the user's answers and
advance the playhead to the next question. The answer(
) function expects one parameter,
choice, which is the number of the user's
answer for each question, so its function declaration begins like
this:
function answer (choice) {
Each time an answer is given, the function increments
currentAnswer, a function property that tracks the
question being answered:
answer.currentAnswer++;
Next, we set the user's choice in a dynamically named timeline
variable that corresponds to the question being answered. We use the
value of the currentAnswer property to determine
the name of our timeline variable (q1answer,
q2answer, etc.):
set ("q" + answer.currentAnswer + "answer", choice);
With the user's choice stored in the appropriate variable, if
we are on the last question, we go to the end of the quiz; otherwise,
we go to the next question, which is at the frame labeled
"q" + (answer.currentAnswer + 1):
if (answer.currentAnswer == numQuestions) {
gotoAndStop ("quizEnd");
} else {
gotoAndStop ("q"+ (answer.currentAnswer + 1));
}
That takes care of our question-answering logic. The
answer( ) function is ready
to handle answers from any question in the quiz. Now let's
build the function that evaluates those answers, gradeUser(
).
The gradeUser( ) function takes no parameters.
It has to compare each user answer with each correct answer and
display the user's score. We handle the comparisons in a
for loop -- we cycle through the loop body
for the number of questions in the quiz:
for (i = 1; i <= numQuestions; i++) {
Inside the loop, a comparison expression tests the user's
answers against the correct answers. Using eval(
), we dynamically retrieve the value of each user-answer
variable and each correct-answer variable. If the two variables are
equal, totalCorrect is incremented:
if (eval("q" + i + "answer") == eval("correctAnswer" + i)) {
totalCorrect++;
}
After the loop finishes, totalCorrect will contain
the number of questions that the user answered correctly. We display
that number by setting the dynamic text field
displayTotal to totalCorrect:
displayTotal = totalCorrect;
Voila! With both functions in place and our quiz variables
initialized, the logic of our quiz system is complete. Notice how
much easier it is to follow the quiz's operation when most of
the code is contained on a single frame? All that's left is to
call the functions from the appropriate points in the quiz.