Building a Quiz Application


In this task you'll build a quiz application utilizing the JavaScript-to-Flash and Flash-to- JavaScript communication you learned in this lesson. The quiz uses a timer that is built in Flash. The quiz is built using JavaScript. Each time a new question is displayed, JavaScript has to notify the timer to start. When the timer stops, it has to notify JavaScript to disallow responses to the current question.

1.

Open counter1.fla from the Lesson15/Start directory.

The document contains the assets you need to complete this task. On the main Timeline there are three layers: Actions, Hand, and Face. The Hand and Face layers have instances of movie clip symbols on them. The instance on the Hand layer is named handClip. The artwork within the symbol is aligned so that the bottom of the line is at 0,0; when it is rotated, the point around which it rotates is the bottom of the line.

2.

Select the keyframe on the Actions layer and open the Actions panel by pressing F9. Then add the following two import statements to the Script pane:

    import flash.external.ExternalInterface;     import mx.transitions.Tween;


You'll use ExternalInterface to enable Flash-to-JavaScript and JavaScript-to-Flash communication. The Tween class is used to rotate the hand on the timer.

3.

Declare a variable to use for the programmatic tweens.

    var watchTween:Tween;


You'll want to have a reference to the current Tween object so that you can stop it if necessary.

4.

Register a function called startCountdown() so that it can be called from JavaScript. The function referenced is called startCountdown(), and the name of the function as it is callable from JavaScript is also startCountdown().

    ExternalInterface.addCallback("startCountdown", this, startCountdown);


The startCountdown() function that you'll define in the next step causes the hand to rotate.

5.

Define the startCountdown() function so it starts a new Tween object that rotates handClip 360 degrees. Define the function so it accepts a parameter that specifies the duration of the tween in seconds. Add a listener object to the Tween object so it gets notified when the tween completes.

   function startCountdown(seconds:Number):Void {      watchTween.stop();      watchTween = new Tween(handClip, "_rotation", null, 0, 360, seconds, true);      watchTween.addListener(true);    }


You want to initially stop any existing tween, so if the timer is reset while a previous tween was in progress, the onMotionFinished() function won't get called for the aborted tween. Use a Tween object to rotate the hand 360 degrees in the specified number of seconds.

6.

Define an onMotionFinished() function that gets called when the tween completes. Define the function to call a JavaScript function called stopCountdown().

    function onMotionFinished():Void {       ExternalInterface.call("stopCountdown");     }


When the hand has rotated 360 degrees, Flash Player will call onMotionFinished(). In turn, have the function call the JavaScript function called stopCountdown().

7.

Publish the SWF file and HTML page.

You'll need to test the application in a web browser, so publish the necessary files.

8.

Edit the HTML page. Make sure that allowScriptAccess is set to always and note the name parameter and attribute values.

If you saved the Flash document as counter1.fla, the name parameter and attribute will likely have the value of counter1. If you've made any changes to filenames, and the name parameter and attribute have different values, you can either rename them or you can simply make necessary changes in the code that follows in the next few steps.

9.

Define an onLoad handler for the <body> tag so that it calls a function named initialize().

   <body bgcolor="#ffffff" onLoad="initialize();">


The initialize() function will then get called after the HTML content has loaded. You can use the function to retrieve the Flash object reference.

10.

Define a <script languge="JavaScript"> section within the document <head> tag. Define a variable called countdownTimer to store a reference to the Flash object and define an initialize() function that assigns the correct reference.

    <script language="JavaScript">       var countdownTimer;       function initialize() {         if(navigator.appName.indexOf("Microsoft") != -1) {           countdownTimer= window.document.countdownTimerObject;         }         else {           countdownTimer= document.countdownTimerEmbed;         }       }     </script>


The preceding code simply retrieves the correct Flash object reference and assigns it to the countdownTimer variable.

11.

Add an HTML form below the <object> and <embed> tags. Use the following HTML code:

   <form name="quiz">      <textarea name="message" cols="50" rows="5"></textarea>      <br />      <input type="radio" value="true" name="response"    onClick="userRespond(true);" />true      <br />      <input type="radio" value="false" name="response"    onClick="userRespond(false);" />false      <br />      <input type="button" name="next" value="Next"    onClick="displayNextQuizItem();" />    </form>


Notice that the form has a name of quiz. That's important because it's how you can reference the form from JavaScript. You'll use the message textarea to display quiz questions as well as the number of correct responses. The two radio buttons both have the same responses: one is for true responses and the second is for false responses. Each has an onClick handler that calls a custom JavaScript function called userRepond(). In the case of the true radio button, it passes the function a value of true, and in the case of the false radio button, it passes the function a value of false. The button calls a custom JavaScript function called displayNextQuizItem() when clicked.

12.

Within the <script> tag, define an array of the quiz questions, an array of correct responses, an array for storing the user responses, and an index variable to iterate through the quiz questions .

  var quizItems = ["The ExternalInterface class is used primarily ¬     for displaying bitmaps within Flash.", "ExternalInterface ¬     was introduced in Flash Player 5.", "ExternalInterface.call() ¬     works synchronously so that any value returned by the ¬     function is available to Flash Player immediately after ¬     invoking call().", "ExternalInterface works only if every ¬     movie clip within the SWF is unrotated."];   var correctResponses = [false, false, true, false];   var responses = new Array(correctResponses.length);   var quizIndex = -1;


The quizItems array contains four elements, as does the correctResponses array. The elements of the arrays correspond to one another. For example, the correct response to the first quiz question is false, whereas the correct response to the third quiz question is true. The responses array, though initially empty, will also have elements that correspond to the elements of the quizItems and correctResponses arrays. For example, the user's response to the first quiz question is stored in the first element of the responses array. The quizIndex is the index of the current element from the quizItems array. Initialize the variable to -1 so that when it is first incremented it will correspond to the first element of the quizItems array.

13.

Update the initialize() function so that it disables the textarea and radiobuttons when the quiz starts.

   function initialize() {      if(navigator.appName.indexOf("Microsoft") != -1) {        countdownTimer= window.document.countdownTimerObject;      }      else {        countdownTimer= document.countdownTimerEmbed;      }      document.forms.quiz.elements.message.disabled = true;      document.forms.quiz.elements.response[0].disabled = true;      document.forms.quiz.elements.response[1].disabled = true;    }


When the quiz starts, make the textarea and radiobuttons disabled so that the user cannot click on them. To start the quiz, the user has to click the next buttonthe only form element that's not disabled.

14.

Define a function to display the next quiz item.

   function displayNextQuizItem() {      quizIndex++;      if(quizIndex >= quizItems.length) {        displayResponses();        return;      }      document.forms.quiz.elements.message.disabled = false;      document.forms.quiz.elements.message.value = quizItems[quizIndex];      document.forms.quiz.elements.response[0].checked = false;      document.forms.quiz.elements.response[1].checked = false;      document.forms.quiz.elements.response[0].disabled = false;      document.forms.quiz.elements.response[1].disabled = false;      countdownTimer.startCountdown(5);    }


The preceding function might seem daunting at first. However, as you look more closely, you'll see that it's not too difficult. It starts by incrementing quizIndex so that it effectively moves to the next quiz question. It then checks whether the quizIndex value corresponds to a valid element in quizItems. If it doesn't, you know that the user has completed the quiz. Therefore, it calls the function that displays the number of correct responses.

Assuming that the user hasn't yet completed the quiz, the function continues by enabling the message textarea and radiobuttons. It resets the states of the radiobuttons so they are deselected, and it displays the text of the current quiz question in the textarea. It also calls the startCountdown() function for the timer Flash object, passing it a value of 5 seconds. If you want to allow the user more time to respond to each quiz question, you can simply use a number greater than 5.

15.

Define the userRespond() function for handling user responses.

   function userRespond(response) {      responses[quizIndex] = response;    }


When the user responds, log the response in the responses array.

16.

Define the stopCountdown() function that is called from Flash when the timer stops.

   function stopCountdown() {      document.forms.quiz.elements.message.disabled = true;      document.forms.quiz.elements.response[0].disabled = true;      document.forms.quiz.elements.response[1].disabled = true;    }


When the timer stops, you'll recall, it calls a JavaScript function named stopCountdown(). The function needs only to disable the message textarea and the radiobutton instances so the user can no longer respond.

17.

Define the displayResponses() function to display how many correct responses the user got during the quiz.

   function displayResponses() {      document.forms.quiz.elements.message.disabled = false;      var correct = 0;      for(var i = 0; i < correctResponses.length; i++) {        if(responses[i] == correctResponses[i]) {          correct++;        }      }      document.forms.quiz.elements.message.value = correct + " correct responses";    }


The displayResponses() function loops through each element in the correctResponses array and compares the user's responses to the correct responses. It then displays the number of correct responses in the message textarea.

18.

Test the application.

Open the HTML page in a browser. Click the Next button to start the quiz. Reply to each item before the timer stops. Click Next to continue to the next item. Once you've responded to each item the quiz will score, and it will tell you how many correct responses you got.




Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net