ICS2O_Actionscript

include component="page" wikiName="jmcintyre" page="course_tabs_header" include component="page" wikiName="jmcintyre" page="menu_ics2O_crumbs"

=ActionScript= [|Source Inspiration]

ActionScript is an object-oriented language originally developed by Macromedia Inc. (now owned by Adobe Systems). It is a dialect of JavaScript, and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of embedded SWF files. The language itself is open-source though typically necessitates the Flash environment to be installed on the developers computer.

Older versions of ActionScript (1.0/2.0), while object-oriented, weren't as able to control the environment as the current version of ActionScript (3.0) - which quickly became widespread in it's adoption.

The ActionScript (AS) language is useful in doing these among many other things:
 * control the playhead of a timeline
 * move things around
 * create and manage user interfaces
 * play sounds
 * control video
 * manage data (xml, lists, etc)
 * communicate with server-side applications (e.g., web servers)

Starting the environment:


Once you're within a your .fla file, code is attached to either a frame, button, or movie clip. You can see in your properties pane what your code is attached to. To ensure you attach it correctly, always select the object or frame you intend to have the script applied to. Afterwards simply begin coding in the AS window.

Once Flash CS4 is up and running you either select Window > Development panels > Actions or simply press F9 to open the AS window. Target FRAME 1 in the timeline by clicking on it. Now type in the following code into your AS window: code // this how we comment in Flash //

var message = "Hello World!"; trace (message); code Save the file someplace (we'll discard it later so the location is irrelevant) as temp.fla. By File>Exporting>Movie you can test the code. The fast way of doing this is by pressing **CTRL+ENTER**.



Notice there's an Output tab at the top. If the tab didn't automatically appear click on it to see the result of your Hello World code being run. Also notice the Flash window popped up the SWF for the animation, which shows a blank screen. That's because we haven't actually ordered Flash to display our code as visual text yet in anything other than the internal compiler.

Notice how when we ran this code we first created a variable called message, we populated the variable with the datum string "Hello World", then we asked the Output pane (actually the Flash Interpreter) to show it with the trace command. The Interpreter has many functions it;
 * runs your programs
 * manages your code
 * listens for instructions
 * performs any AS commands
 * stores your data
 * sends you information
 * calculates values
 * returns error messages

Getting back to our code, notice how each new command line requires that the previous one end in a semicolon ;

Now try the following code: code var message = "ICS2O Rocks!"; trace(message); code This does much the same as the previous example of code. We create the variable, store the datum as a string, then trace it (print it to the output pane). Now apply the following to enhance the code: code var message = "ICS2O Rocks!"; trace(message); var firstName = "enter your name"; trace("Hi there " + firstName + ", nice to meet you.  " + "Don't you think "      + message); code

You can begin to see how we are able to interact with the Flash environment now. While this still runs exclusively behind the scenes (pardon the pun) in the **Interpreter**, the fact that variable names can be called on and ultimately compared against other variables or conditions makes it just like SmallBasic. Also notice in the above example that in line 5 by not putting the semicolon at the end of line 4 we can cause a continuum of code across lines 4 and 5 which is incredibly useful when arguments or a condition becomes ungainly long and you don't want to have to scroll across a long line of code.



Command Structures
In AS, command structures are also allowed. In SmallBasic, they inhabited the structure of the TextWindow or GraphicsWindow, while in AS they exist directly in the root code. For example, look at this code:

code command(argument1, argument2, argument3); code

The command at present is just listed as command (in SmallBasic it could be GraphicsWindow.DrawText). Argument 1...n simply targets what the command affects. For example;

code //for example, in the code // gotoAndPlay(5); // gotoAndPlay is the name of the command // // 5 is the argument being passed (the frame number)// code

Conditional Statements
As in SmallBasic, we can make conditional statements in AS. For example; code if (username == "Mac") { trace ("You are clearly Ub3r!"); } code Notice how we're making equivalent statements with a double equal sign = =. The difference between using a single and double equal sign is that a **single equal sign means it is an operator** (e.g. performing a mathematical function on something) whereas the **double equal is conditional logic comparing one thing to another** in order to make a decision. Also, notice that the contents of the if statement are held within a set of curly brackets (braces). Also notice that the logic IS applied. When trying to run the above code you'll return an error in the interpreter. If instead we added a line of code to make the following:

code var username = "Mac" if (username == "Mac") { trace ("You are clearly Ub3r!"); } code Now the code runs properly. By declaring the datum in the variable as the text string "Mac" you're allowing the logic in the 2nd line of code to be tested properly. By adding else if statements we can expand the condition. code var username = "Bob" if (username == "Mac") { trace ("You are clearly Ub3r!"); } else if (username=="Dave"){ trace ("Not Mac, but Dave!"); } else { trace ("Not Mac or Dave."); }; code

Loops
Repetitive tasks are also addressed in AS as in any other programming language. The structure of a loop is as follows:


 * For Loop**

code var i = 1 for (i; i <= 5; i = i + 1) { trace(i); } code

Instead of having to write the variable onto a different line, AS allows us to consolidate the code into a single line

code for (var i=1; i <= 5; i = i + 1) { trace(i); } code


 * While loop**

The while loop operates much the same. The loop variable is defined, tests against the logic operator <= then counts as i increases.

code var i = 1; while (i <= 5) { trace (i); i = i + 1; }

//note this could also be achieved by setting line 2 to://

// while (i !=6) { //

code

Functions
Every programming language has its ways to abbreviate code by making repetitive tasks easier. In SmallBasic we had the Subroutine. In AS we have the Function command. It separates the code task from the main stream of the code and runs it before returning to where the Function call was made. Just like in Small Basic.

code //calls the function displayArea with the values for variables w and h // // as 15 and 20 respectively // displayArea(15,20)

//is the "subroutine" or function outlining the variable as well as// //the math operation of Width * Height in the trace function// function displayArea (w, h) { trace(w * h); } code Notice we call the function by using the name of the function then brackets with the variables in question inside the brackets).

In SmallBasic there was no good way to end a subroutine without making an exit condition or ending the program. In AS there is inherent exit structure known as the RETURN. It allows the function to quit if a condition is met and return to the code in the place where the function was called.

code //enterSite("hackAttack"); // Function will exit prematurely //enterSite("cactus");     // Function will end naturally

function enterSite(pass) { if(pass != "cactus") { // Exit if the password is wrong: return; }   // This code is reached only if the password is correct. else { trace("Welcome to the Site!"); } } code Try running the above code un-commenting first line 1, running the code, then un-comment line 2 and try running the code with line 1 re-commented.

A neat feature of RETURN is that it can also be the conduit by which data can re-enter the code sequence where the function was called. For example, try a variation on the above code: code enterSite("hackAttack"); // Function will exit prematurely //enterSite("cactus");     // Function will end naturally

var i = 1 for(i;i<=5;i=i+1){ trace(i) }

function enterSite(pass) { if(pass != "cactus") { // Exit if the password is wrong: return(trace("Bob, don't hack")); }   // This code is reached only if the password is correct. else { trace("Welcome to the Site!"); } } code The i loop is simply to indicate where the RETURN has been brought into our code. Notice how the data after return has injected at the main line of code?

Assignment #8: Quiz Version 1
A quick tutorial on FLASH drawing and FLASH use can be found in my grade 10 TGJ2O site here.

Now Flash is a visual creature. AS acts to support and enhance visual elements. While SmallBasic incorporates graphic objects around the structure of Basic, Flash incorporates the AS language around visual elements (though not mandatorily). Other programs like Java can ONLY have code contained to objects. A truly OOP (Object Oriented Programming) language!

We're going to work on a Quiz. It will include visual elements, conditions and functions. The quiz will have the following:
 * 1) two questions; each with three multiple-choice answers
 * 2) users submit their answers by clicking answer buttons
 * 3) user answers are recorded in a variable
 * 4) answer variables are used to calculate the user's score
 * 5) at the end of the quiz, the score is displayed

__**Step 1:**__

Create a new AS 3.0 Flash document. Look at the timeline at the top. Notice the following:



Create the following:
 * a **layer called scripts** on which to place code. Creating layers is as simple as clicking on the insert layer button, then renaming it scripts.
 * keep the scripts layer at the top so it's easy to find (you can drag each layer around hierarchically such that top layer is the closest one to the front).
 * make a **layer called labels** for all labels in our movie
 * make **four layers**for our quiz assets called:
 * quiz end: for the results screen
 * question 2: for the second question screen
 * question 1: for the first question screen
 * choice buttons: for the answer buttons
 * housing: for the background and instructions
 * add 30 frames to all layers. This is done by highlighting the frames at layer 30 and right clicking entering the command **Insert Frame**

__**Step 2:**__ On the right side of the screen you'll see the Properties Panel. Click on the Stage colour box. Input the following HEX code #339900 __ **Step 3:** __ Make sure you're on the housing layer and using the text, tool write "a flash quiz" in the top left corner. Make the font is Arial Black at 52 points and its colour is #66CC00 __**Step 4:**__ Looking at the picture below draw lines in colours #FFFE65, Text "answer all questions and your grade will follow" in #FFFF00, the circles with the outside yellow line of FFFE65 and interior green colour of #66CC00.

__**tep 5:**__ Select the layer question1 and put "q.1" and the question "Who is so tough his beard hides another fist?" in #FFFF00. Give 3 answers in text colour #99FFCC. (Zach Galifanakis, Edward Teach, Chuck Norris)

__**Step 6:**__ Create the question 2 screen by doing the following:
 * select frame 1 of question 1 layer
 * right-click > copy frames
 * select frame 10 of question 2 layer
 * right-click > paste frames
 * right click frame 10 of question 1 layer and convert it to a blank keyframe.
 * select the keyframe at frame 10 of question 2 layer:
 * change the question number from "1" to "2"
 * change the text of the question to, "What is 1/2 man, 1/2 bear, 1/2 pig?"
 * change the multiple choice answers to your answers
 * notice that frames are used to represent application screens

Create the buttons for selecting the answers. Hit F11 for your Symbol Library. There is a drop-down menu in the top right corner of the Library box. Drop the menu down to Create a New Symbol. **Change the symbol type to Button instead of Graphic**. To create a button follow this brief tutorial. While you're not following the tutorial exactly, it will give you an idea of what each state does in order to make a functional button. You don't need the word PLAY in your buttons, simply have them as 3 identical circles. Mine look like this (below left) and, function like the SWF at center.
 * __Step 7:__[[image:ICS2O_Actionscript_quiz2.png align="right"]]**

media type="file" key="ICS2O_Button.swf" width="360" height="270"

At **frame 1 of choice buttons layer**, place three answer button instances (that means dragging the button out of your symbol library onto the stage 3 times). Set instance name for buttons (the box in the properties panel in which you can write - by default it's called ). to: **choice1_btn, choice2_btn, and choice3_btn.** In order to work properly once the name is typed in the box **__ENTER MUST BE PRESSED__**!

__**Step 8:**__ Start the coding for the quiz. We add this code at **frame 1 of scripts layer** which will initialize the movie. It sets the variables for q1answer and q2answer, it keeps track of the score, and then controls the "playhead" of the timeline to stop until further instructed. Notice how when stacking English words together in a variable the beginning of each new word is capitalized, just like the proper form in SmallBasic. For example, totalCorrect is used below.

code // Initialize main timeline variables // next, create variables to store user's answers: var q1Answer;         // User's answer for question 1 var q2Answer;         // User's answer for question 2 //next, create a variable to track number of questions answered correctly: var totalCorrect = 0; // Counts number of correct answers //finally, stop the movie timeline immediately once these global variables have been declared stop; code __**Step 9:**__

Add Frame Labels to help us to navigate. They're like bookmarks that when called on immediately control the playhead (called the shuttle) to move to the frame indicated. We could simply use gotoAndStop(10) or gotoAndPlay(10), but proper etiquette is to label the frame so that if frames get moved around that the structure of the movie plays correctly.

Thus, we will add:
 * at frame 1, labels layer, set the label to **init**
 * at frame 10, labels layer, convert to a blank keyframe
 * at frame 10, labels layer, set the label to **q2**
 * at frame 20, labels layer, convert to a blank keyframe
 * at frame 20, labels layer, set the label to **quizEnd**

Each label is added exactly where we named the instance name for each button - at the top of the properties panel after we've clicked on the respective layer and frame.

By entering the Frame Label we can now quickly direct the shuttle around based on what button has been clicked.

__**Step 10:**__ We now have to add an event handler for the buttons in question 1. That is the control that in SmallBasic allowed us return information to the program to make decisions. For example GraphicsWindow.MouseX or GraphicsWindow.LastKey. In Flash, there are two ways in which code is run. Either the playhead runs into a "global script" (attached to a frame) or by being called by something like user-input or a system notification as a result of an interaction. EVERYTHING in Flash is triggered by an object event (e.g. a key object detects input, a global event on the stage detects when the window is resized, a button object knows when it's been clicked).

We want to now make an event attached to the button being clicked. We don't need to return X or Y values, because it's OOP, the object simply responds to the click on it without any regard for the X/Y positioning (unless we WANT the X/Y position). In this way Flash is fundamentally different from SmallBasic. We want to attach the following logic to our buttons:

//theButton.eventListener ( eventHandlerFunction);//

Effectively this says: 1) our targeted button will 2) respond to the release of our mouse click and will 3) do the following thing.

In our case we want //thebutton// to be buttons 1, 2 and 3, all
 * 1) responding to the appropriate click and
 * 2) recording that it chose either answer 1, 2 or 3.
 * 3) It will then compare that against the right answer.
 * 4) Tally the score,
 * 5) then move the playhead to the next question.

Easily done in SmallBasic. Also easily done in Flash once you know the structure.

For each event (user action or something else) you would like to intercept, you must register a so-called **event listener ** function. In this case it's tied to the button. So, in the SCRIPTS LAYER we'll add this after the initial code we'd placed in there to declare the variables and stop the playhead. code choice1_btn.addEventListener(MouseEvent.CLICK, answer1); //change this to answer2 for button 2//

function answer1(event_object:MouseEvent){     //change this to answer 2 for button 2// q1Answer = 1;       //q1Answer =  2 for button 2 and 3 for button 3// gotoAndStop("q2"); trace(q1Answer); //just to let us know for debugging purposes that we've clicked on the correct button and recorded it's value as the variable// } code

What happens is that the function does two things: new code introduced here is :
 * records the user's choice in q1answer
 * displays question 2
 * //**addEventListener-**// Which is just a way of saying to Flash "Hey, pay attention!"
 * //**event_object:MouseEvent.CLICK**// means that Flash, now paying attention, is paying attention to the MouseEvent which is a click. As can be expected, there are a slew of returns all tied to MouseEvent (X/Y locations, what type button of clicking, double clicking, box-dragging etc...)

Copy and paste the code two more times and change the values for answer 1 to answer 2 and answer 3 as well as q1Answer to 2 for button 2 and q1Answer to 3 for button 3.

__**Step 11: **__

Now we handle the event of question 2. We'll go to Frame 10 in the Scripts Layer and convert the frame to a blank keyframe. Additionally we'll go to the Choice Buttons layer and right click on Frame 10 and convert it to a keyframe. NOT and blank keyframe. We need another copy of the buttons at this point. We need to name these button instances choice21_btn (instead of choice1_btn) choice22_btn (instaed of choice2_btn) and choice23_btn instead of choice3_btn.

Much like the last batch of code applied to the control of the buttons, we'll add the following:

code choice21_btn.addEventListener(MouseEvent.CLICK, answer21);

function answer21(event_object:MouseEvent){ q2Answer = 1; gotoAndStop("quizEnd"); trace(q1Answer); }

choice22_btn.addEventListener(MouseEvent.CLICK, answer22);

function answer22(event_object:MouseEvent){ q2Answer = 2; gotoAndStop("quizEnd"); trace(q1Answer); }

choice23_btn.addEventListener(MouseEvent.CLICK, answer23);

function answer23(event_object:MouseEvent){ q2Answer = 3; gotoAndStop("quizEnd"); trace(q1Answer); }

code

Also notice however that we've listed each of the functions as answer21, answer22 and answer 23 instead of answer1, answer2 and answer3. The reason for this is simple. We've already defined those functions back at frame 1 and we would be duplicating a function name if we used them again.

__**Step 12:**__

We now have to make the end of the quiz which a) looks different and b) calculates the "mark" for the user. To do so at FRAME 20;
 * in the **scripts layer** convert the frame to a keyframe.
 * in the **Question 2 layer** convert the frame to a keyframe.
 * in the **choice buttons layer** convert the frame to a keyframe
 * in the Quiz End layer convert the frame to a blank keyframe
 * in the Housing Layer convert the frame to a keyframe NOT A BLANK KEYFRAME - delete many of the lines etc... until it looks reasonably blank.
 * in the Quiz End layer write text which says the following "Thank you for taking this quiz".

We now need to calculate the mark. The variable:

code var totalCorrect = 0; code was defined at the beginning of the quiz. We'll use it now to evaluate how well the user did. A simple set of conditional statements can calculate that.

In the scripts layer we'll add the following: code if (q1Answer == 3) { totalCorrect = totalCorrect + 1; //standard counter we've seen in SmallBasic trace("Value for Q1 is 1 point"); } else { trace("Wrong answer #1 " + q1Answer); }

if (q2Answer == 3) { totalCorrect++; //simply adds 1 more to the previous value of totalCorrect// trace("Value for Q2 is 1 point"); } else { trace("Wrong answer #2 " + q2Answer); }

//displays final score on interpreter trace("Your total is "+totalCorrect+"/2 points");

//displays the answer on the stage var txtFld:TextField = new TextField; addChild(txtFld); txtFld.text = ("Your total is" + totalCorrect); txtFld.appendText ("/2 points"); //this appends text should you want to do that. //extra bits to un-comment once text output is understood //txtFld.wordWrap = true; //txtFld.textColor = 0xFF00FF //txtFld.width=150 //txtFld.height = 60

code Notice how we "draw text" to be seen on the stage with the variable txtFld? There are a lot of options available once you begin using the textfield entity.

Submit the file into the handin folder as Assignment#8(1).

We can do better however.



There are problems with the approach above. First, the code is spread over 3 areas, so there's room to make mistakes by having to constantly search for code. Second, the code that is there is repetitious w.r.t. the buttons. We had to rename object just so that we could avoid duplication. Wouldn't it be easier to use one single control structure for the buttons?

__**Step 1:**__

Delete all your code from the first version of the Quiz. For now leave all the names/labels but clear the keyframe for choice buttons at frame 10.

To frame 1 of the scripts layer we add the following: code stop; //initialize variables //we use q1answer and q2answer just like last time: var q1answer;               // User's answer for question 1 var q2answer;               // User's answer for question 2 //and we add these new variables: var numQuestions = 2;       // Number of questions in the quiz var correctAnswer1 = 3;     // The correct choice for question 1 var correctAnswer2 = 3;     // The correct choice for question 2 var currentQuestion = 1;    // The question being answered

code

__**Step 2:**__

We're also going to introduce a function for the buttons to handle their responses. Answer. It will a) record the answer and b) advance the quiz

code function answer (choice) { } code This is the fundamental of what Answer will do, it will store the answer under choice. code function answer (choice) { //content for logic goes here afterwards //trace("Question " + currentQuestion + ". The user answered: " + choice); } code
 * __Step 3:__**

By building the trace in we can begin to see if Answer(choice) is doing what it should be. When answer runs, we must set either q1answer or q2answer, but how do we know which one to set? The currentQuestion variable acts like a flag and tells us when currentQuestion is 1, we should set q1answer and when currentQuestion is 2, we should set q2answer. Here's how that looks in code:

code function answer (choice) { // Record the user's answer to this question. if (currentQuestion == 1) { q1answer = choice; } else if (currentQuestion == 2) { q2answer = choice; } //trace("Question " + currentQuestion + ". The user answered: " + choice); //can be moved// } code __**Step 4:**__

Once the answer has been recorded, we advance the quiz. If the current question is the last question then we're going to calculate a score, then display the final results on the screen. If we're not yet done then we'll display the next question. Here is what that would look like:

code function answer (choice) { trace("Question " + currentQuestion + ". The user answered: " + choice); // Record the user's answer to this question. if (currentQuestion == 1) { q1answer = choice; } else if (currentQuestion == 2) { q2answer = choice; }   // If we're on the last question... if (currentQuestion == numQuestions) { //arguably we could have written this as currentQuestion == 2// // ...go to the quiz end frame. gotoAndStop("quizEnd"); // And grade the user. //gradeUser;             // to be uncommented later } else { // ...otherwise, go to the next question frame. gotoAndStop("q"+ (currentQuestion + 1)); //showing how a multiple question quiz would be made, otherwise it's just gotoAndStop(q2); // Note that we're on the next question. currentQuestion++; } }

code

Now let's control the buttons. To do so we use the same code as before where response1 calls a function response1 and we can evaluate code in there to return the answer to the control structure for the logic.
 * __Step 5:__**

code choice1_btn.addEventListener(MouseEvent.CLICK,response1);

code

This is what the code looks like now: code // responds to mouse click evens and records them down in the function answer. Effectively it's is a 1-dimensional array. choice1_btn.addEventListener(MouseEvent.CLICK,response1);

function response1(event_object:MouseEvent){ answer(1) } choice2_btn.addEventListener(MouseEvent.CLICK,response2); function response2(event_object:MouseEvent){ answer(2) } choice3_btn.addEventListener(MouseEvent.CLICK,response3); function response3(event_object:MouseEvent){ answer(3) }

function answer (choice) { trace("Question " + currentQuestion + ". The user answered: " + choice); // Record the user's answer to this question. if (currentQuestion == 1) { q1answer = choice; } else if (currentQuestion == 2) { q2answer = choice; }   // If we're on the last question... if (currentQuestion == numQuestions) { //arguably we could have written this as currentQuestion == 2// // ...go to the quiz end frame. gotoAndStop("quizEnd"); // And grade the user. //gradeUser; } else { // ...otherwise, go to the next question frame. gotoAndStop("q"+ (currentQuestion + 1)); //showing how a multiple question quiz would be made, otherwise it's just gotoAndStop(q2); // Note that we're on the next question. currentQuestion++; } }

code __**Step 6:**__

Finally, we need to still end the quiz and grade it. Let's create a **LOCAL VARIABLE** totalCorrect, setting it to zero. Notice it's not listed in the global variables. Let's uncomment gradeUser at this point. code function gradeUser { trace("Quiz complete. Now grading..."); var totalCorrect=0; } code When the function is complete the variable totalCorrect will dissapear since it is a local variable. Quite handy.

Now - let's calculate the score: code function gradeUser { trace("Quiz complete. Now grading..."); var totalCorrect=0;

if (q1answer==correctAnswer1) { totalCorrect++; } if (q2answer==correctAnswer2) { totalCorrect++; } trace ("You have "+ totalCorrect + " out of a possible " + numQuestions + " answers right.") }

code

Notice however that we have two sequential if statments that could be consolidated. if (q1answer == correctAnswer1) and (q2answer==correctAnswer2) could be looped, then we could have a quiz of any length and it would be functional and easy to use.

This is achieve by: code function gradeUser { trace("Quiz complete. Now grading..."); var totalCorrect=0; for (var i = 1; i <= numQuestions; i++) {                        //loop structure if (this["q" + i + "answer"] == this["correctAnswer" + i]) {   //loop logic evaluates q1answer against correctAnswer1 etc... totalCorrect++;                                              //advances the counter } else { trace("q" + i + "answer is wrong");              //used only to figure out what could be wrong } }  trace ("You have "+ totalCorrect + " out of a possible " + numQuestions + " answers right.") }

code A new piece of useable information is when you want to compare complex conditions is to use the syntax THIS. AFAIK you can use concatenated complex logic against other concatenated complex logic successfully ONLY when that's used.

Again, we will display our text on the output SWF by putting in the following code: code function gradeUser { trace("Quiz complete. Now grading..."); var totalCorrect=0; for (var i = 1; i <= numQuestions; i++) { if (this["q" + i + "answer"] == this["correctAnswer" + i]) { totalCorrect++; } else { trace("q" + i + "answer is wrong"); } }  trace ("You have "+ totalCorrect + " out of a possible " + numQuestions + " answers right.") //displays the answer on the stage var txtFld:TextField = new TextField; addChild(txtFld); txtFld.text = ("Your total is" + totalCorrect); txtFld.appendText ("/2 points"); //this appends text should you want to do that. //extra bits to un-comment once text output is understood //txtFld.wordWrap = true; //txtFld.textColor = 0xFF00FF //txtFld.width=150 //txtFld.height = 60
 * __Step 7__:**

} code Note the text display MUST BE INSIDE the gradeUser function because the totalCorrect variable disappears once the function is finished and thus we can't display it.

Submit this into the handin folder



Assignment # 10: Quiz version 3
Following [|this link,]complete the final version of the quiz using arrays. This will require you to pay special attention in that some of the handlers no longer apply in AS3.0. Look back to your code from the above two versions of the quiz in order to complete the Quiz version 3.

code // Stop the movie at the first question. stop;

// =================== // INIT QUIZ VARIABLES // =================== // Create an array to contain user's answers. var userAnswers = new Array; // Create an array to contain each question's correct answer. var correctAnswers = [3, 2]; // Create a convenience variable to store the number of // questions in the quiz. var numQuestions = correctAnswers.length;

// ===================== // CREATE QUIZ FUNCTIONS // ===================== //  Function: answer //      Desc: Registers the user's answers to quiz questions and //            advances the quiz through its questions. //    Params: choice           The user's answer for the current question. function answer (choice) { // Add the current answer to the list of user answers. userAnswers.push(choice);

// Create a convenient variable to store the number // of the current question. var currentQuestion = userAnswers.length;

// Display the question and answer in the Output window for debugging. trace("Question " + currentQuestion        + ". The user answered: " + userAnswers[userAnswers.length-1]);

// If we're on the last question... if (currentQuestion == numQuestions) { // ...go to the quiz end frame. gotoAndStop("quizEnd"); // And grade the user. gradeUser; } else { // ...otherwise, go to the next question frame. this.gotoAndStop("q"+ (currentQuestion + 1)); } }

//  Function: gradeUser //      Desc: Tallys the user's score at the end of the quiz. function gradeUser { // Report that we're about to grade the quiz in the Output window. trace("Quiz complete. Now grading...");

// Create a local variable to track the // number of questions user answered correctly. var totalCorrect = 0;

// Count how many questions the user answered correctly. // For each question... for (var i=0; i < numQuestions; i++) { // If the user's answer matches the correct answer. if(userAnswers[i] == correctAnswers[i]) { // Give the user a point. totalCorrect++; }   // Display the correct answer and the user's answer // in the Output window for debugging. trace("Question " + (i + 1)        + ". Correct answer: " + correctAnswers[i]         + ". User's answer: "  + userAnswers[i]); }

// Display the final score in the Output window for debugging. trace("User's score: " + totalCorrect + "/" + numQuestions);

// Create an onscreen text field do display the user's score. this.createTextField("totalOutput_txt", 1, 150, 200, 200, 20);

// Show the user's score in an onscreen text field. totalOutput_txt.text = "Your final score is: " + totalCorrect + "/" + numQuestions;

///////////////////////////////////////////////////////////////////////////////////// //NOTE THIS WON'T WORK YOU'LL HAVE TO USE QUIZ 1 AND QUIZ 2 CODE TO DISPLAY THE TEXT// // Customize the font face, size, and color of the text field. var format = new TextFormat; format.size = 16; format.color = 0xC7FF9C; format.font = "_sans"; format.bold = true; totalOutput_txt.setTextFormat(format); } //////////////////////////////////////////////////////////////////////////////////////

// ================================= // DEFINE QUIZ BUTTON EVENT HANDLERS // ================================= // Code executed when button 1 is pressed. choice1_btn.onRelease = function { // Call answer, which records the user's choice // and advances the quiz to the next question. this._parent.answer(1); };

// Code executed when button 2 is pressed. choice2_btn.onRelease = function { this._parent.answer(2); };

// Code executed when button 3 is pressed. choice3_btn.onRelease = function { this._parent.answer(3); }; code Submit this quiz version 3 into the handin folder.



Game-Off #4
Using Flash you are to write a trivia game. It can be simple like the quiz, or more complex like the Who Wants to be a Millionaire series or Jeopardy.

You are to create, in increasing complexity (and thus possible mark-value): OR OR
 * A simple trivia game of 10 questions
 * A more complex interactive game that is more akin to Who Wants to be a Millionaire
 * A more complex interactive game that uses GUI elements as well as a quiz-structure.

Evaluation of the game is the same as for Game #1 and 2 and 3

Mac's evaluation: Your evaluation:
 * Code structure (How easy to follow your code and syntax - including spelling) /5
 * Code logic (Could you game have been written in fewer lines of code? Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional). /5
 * Code functionality (does it work?)
 * No flaws /10
 * Some minor flaws, but still quite functional /8
 * Some major flaws, but code still executes /5
 * Major flaws, code won't execute, but is present /3
 * Game rank (how you fare compared to the others - a sliding scale up to 10. If you submit something that fully functions you automatically get 5). Winner will take 10 points.
 * RANK THE GAMES (link to be released as we get closer)
 * Bonuses:
 * Most ridiculous logic 3 pts
 * Most Enjoyable 3 pts
 * Most hated 3 pts
 * Best looking visually (Graphics) 3 pts