In this example we load an XML file to create a quiz. Notice the structure of the XML file and compare it to the code.

Get Adobe Flash player
//variables used for the game
var ques:int=0;    //keeps track of which question to ask next
var score:int=0;   //add to score if they get it on first try
var answer:String; //stores the correct answer
var firstTry:Boolean; //only give points if they get it on first try
var i:int; //for any loop

//variables used to load the XML
var xmlFile:URLRequest = new URLRequest("quiz.xml"); //same directory as page 
var xmlLoader:URLLoader = new URLLoader(xmlFile); //starts loading the xml file
var xmlQuiz:XML=new XML();  //will store the xml after it is loaded
xmlLoader.addEventListener("complete", initQuiz); //when  file is loaded, call initQuiz

//add event listener for each of the option buttons
for(i=0;i<4;i++)  {
   this["choice"+i].addEventListener(MouseEvent.CLICK, checkAnswer);
} //add event listener

function initQuiz(e:Event): void {
  xmlQuiz = XML(xmlLoader.data); //parse the xml to make it usable 
  getQuestion(); //get first question
} //initQuiz

function checkAnswer(e:MouseEvent): void {
	if(e.target.label==answer)   { //if answer selected  is the right answer
	    if(firstTry) score++; //add a point if they got it on the 1st try
	    ques++; //next question
	    if(ques<xmlQuiz.child("*").length())  { //check if there are more questions
	   else gameOver();
	} //right
	else  {
	   lblMessage.text="Try again.";
	   firstTry=false; //no points if they don't get it on the first try
	} //wrong
} //checkAnswer

function gameOver(): void {
   lblMessage.text="Game over. You scored "+score/xmlQuiz.child("*").length()*100;
} //gameOver

function getQuestion(): void {
   var i:int;
   for(i=0;i<4;i++)  {//get the choices
  lblMessage.text="Question #"+(ques+1); //5 questions are 0,1,2,3,4
} //getQuestion
Save the fla file to your computer to experiment.
Save the xml file to the same directory.

To do:

  • Add another question to the quiz.
  • Add "bells and whistles" to the quiz game!

NEXT: Shuffle the Questions