2013-04-10 63 views
0

我正在創建一個處於測驗樣式的FlashCS4應用程序。問題存儲在一個單獨的文本文件中,並通過as3調用到程序中。這一切都很好,但我想知道如何隨機化這些數據,但要確保同一個問題不會被拉兩次。隨機抽取as3中調用變量的順序

例如,當我導航到問題頁面時,我可以顯示問題的每個部分(回答a,b,c,d +問題本身),然後可以進行10次。

我想要做的是使這10個問題從我在文本文件中的(27?)問題中隨機生成。

import flash.geom.Transform; 
    import flash.geom.ColorTransform; 
    import fl.motion.Color; 


var glowFilter:GlowFilter = new GlowFilter(0x000000, 1, 2, 2, 10, 3) 
var questionNumber:int = 0; 
var totalCorrect:int = 0; 
var selectedAnswer:String; 
var checkAnswer:String; 
var correctAnswer:String; 
var questionCount:int = 0; 
var numberOfQuestions:int = 10; 
txt_loggedin_Question.text = (userName); 

//Displays the Question Number which is called in from XML 
txt_QuestionNumber.text = ("Question #"+questions[questionNumber].ref +" of"+numberOfQuestions); 

function CheckAnswer() { 
if (selectedAnswer == correctAnswer){ 
    totalCorrect = totalCorrect + 1; 
    trace("Correct"); 
}else{ 
     totalCorrect = totalCorrect; 
     trace("incorrect"); 
    } 

      questionNumber = questionNumber + 1;  
      questionCount = questionCount + 1; 


    //Random questions set up new variable questioncount 
    if (questionCount == numberOfQuestions){ 
     trace("we are at 10"); 
     gotoAndStop (1, "Result"); 
     //STOP RUN NEXT SCENE 
    }else{ 
     setUpQuestions() 
    } 

有代碼缺少一個公平一點,但我希望這涵蓋了要領,該文件被稱爲一個單獨的頁面上,

var questions:Array = [ ]; 

var request:URLRequest = new URLRequest("1.txt"); 
var loader:URLLoader = new URLLoader(request); 

loader.addEventListener(Event.COMPLETE, completeHandler); 

function completeHandler(event:Event):void 
{ 
// loader data - the questions.txt file 
var data:String = event.target.data; 
// split data by newline for each question 
var lines:Array = data.split("\n"); 

// for every line 
for each (var line:String in lines) 
{ 
    // split line by "||" delimiter 
    var question:Array = line.split("||"); 

    // add the question to the questions array: 
    questions.push({ref: question[0], 
        question: question[1], 
        answerA: question[2], 
        answerB: question[3], 
        answerC: question[4], 
        answerD: question[5], 
        answerE: question[6], 
        correct: question[7], 
        answer: question[8], 
        type: question[9], 
        file: question[10]}); 
} 

} 

所有這一切工作,但唯一我掙扎的是每次在場景加載時從文本文件中隨機生成問題。很抱歉,這個冗長的問題。

感謝您的閱讀。

回答

0

下面是你需要做的步驟:

讓您的問題,如所謂的「orderedQuestions」一個數組列表。

創建一個名爲「shuffledQuestions」的第二個空數組。

創建while循環:

while(orderedQuestions.length > 0){ 
    shuffledQuestions.push(orderedQuestions.splice(Math.floor(Math.random()*orderedQuestions.length),1)); 
} 

環路從排序列表中隨機去掉一個問題,並把它添加到列表洗牌。完成後,您的排序列表將爲空,並且隨機順序中添加所有問題。

+0

謝謝你,整形外科醫生。 – user2221709 2013-04-11 11:55:10

+0

不客氣。很高興這有助於。如果您覺得問題得到解答,您可以點擊接受此答案嗎? – 2013-04-11 16:28:39

+0

對不起,我只是解決了一些設計問題,一旦我實現了它,我會點擊勾號。如果沒問題,再次感謝你。 – user2221709 2013-04-12 16:42:15