Scoring the quiz is a critical part of this application. Fortunately, it's easy to implement. You'll create a new variable called score and initialize it to 0. Then you'll test each response against the correct answer, and if there's a match you'll increment the score by 1.
1. | With Frame 1 of the actions layer selected, open the Actions panel. Just under the stop() action near the top, add the following script: var inited:Boolean = false; if (!inited) { var score:Number = 0; inited = true; } |
This is an initialization script. You want the script to run once, and only once. To ensure this, you'll create a variable with a Boolean data type, which means it can be true or false; in this case, you'll create a variable called inited. You'll set this variable's value to false initially. Then you'll have a script inside an if statement. As you'll recall, if statements run only if the condition specified in parentheses is true. The if statement checks to see whether the inited variable is false (the ! operator means "not"), and if inited is false, the code inside the curly braces is executed.
Two lines of code are executed inside the if block. The first creates a new variable with the Number data type, and initializes it to 0. No other part of your script does anything with this variable yet. The second line sets the value of inited to true, which means that the if block won't execute again.
You should also update the comment above this block to summarize this new block of code.
In the next step, you'll add to the q1_button code block so that the score will be incremented if the user answers the question correctly.
2. | In the q1_button code block, just before trace(q1_radio.selection.data);, add the following code block. Update the comment above accordingly . if (q1_radio.selection.data == "d") { score++; } |
This code block tests to see whether the data in the radio button the user selected matches "d," which is the correct answer to the question. If there is a match, the user answered correctly, and 1 point is added to score. Note that score++; is a shortcut. In longhand, it means score = score + 1;.
3. | Add a new line of code just above or below the existing trace() line in this block, as follows. Then test the file, choosing the fourth radio button once, and choosing any other radio button once . trace("The current score is " + score); |
You're outputting the current score value in the Output window, which will enable you to verify that the code is actually working. Because you're now tracing two values to the Output window, you might find it hard to figure out which is which. To prevent this problem, you add the string "The current score is" to the parameter, which will make the output easier to read.
When you test the file, the output block displays the selected option and the score. The score updates to 1 if you select the fourth option, and remains at 0 if you do anything else.