Becasue of the structure of the XML file, it is difficult to scramble the XML Itself. Instead, we make a list of the question: 0,1,2, etc. and then scramble that list.
//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
var questionList:Array=new Array();
//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
//functions
function initQuiz(e:Event): void {
xmlQuiz = XML(xmlLoader.data); //parse the xml to make it usable
shuffleQuestions();
getQuestion(); //get first question
} //initQuiz
function shuffleQuestions(): void {
var count,i,r,temp:int;
count=xmlQuiz.child("*").length();
//put the index in the array: 0,1,2,3,4 etc.
for(i=0;i<count;i++) {
questionList[i]=i; //put the index in the array
}
trace(questionList);
//shuffle the list
for(i=0;i<count;i++) {
r=(int)(Math.random()*count); //random item
//swap i and r items
temp=questionList[i];
questionList[i]=questionList[r];
questionList[r]=temp;
}
trace(questionList);
}
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
getQuestion();
}
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 qnum:int=questionList[ques]
lblQuestion.text=xmlQuiz.item[qnum].question;
firstTry=true;
var i:int;
for(i=0;i<4;i++) {//get the choices
this["choice"+i].label=xmlQuiz.item[qnum].choice[i];
}
answer=xmlQuiz.item[qnum].answer;
lblMessage.text="Question #"+(ques+1); //5 questions are 0,1,2,3,4
} //getQuestion
Save the fla file to your computer to experiment.To do: