2015-08-24 54 views
0

我在做一個測驗遊戲。我在交換機的每個「案例」中預訂了所有的問題和答案。我想要按隨機順序選擇案例,但在人回答問題並按下「下一步」按鈕後,函數「randomQuestions」再次起作用,但我不希望它有可能重複先前使用過的相同案例。如何不重複切換案例? (斯威夫特)

func randomQuestions() 
{ 
    var randomNumber = arc4random_uniform(3) 
    while previousNumber == randomNumber 
    { 
     randomNumber = arc4random_uniform(3) 
    } 
    previousNumber = randomNumber 

    switch(randomNumber) 
    { 
    case 0: 
     textoHideUnhide() 
     questionsLabel.text = "What color is the sun?" 
     button1.setTitle("Yellow", forState: UIControlState.Normal) 
     button2.setTitle("Black", forState: UIControlState.Normal) 
     button3.setTitle("Blue", forState: UIControlState.Normal) 
     button4.setTitle("White", forState: UIControlState.Normal) 
     correctAnswer = "1" 
     break 
    case 1: 
     textoHideUnhide() 
     questionsLabel.text = "What color is the moon?" 
     button1.setTitle("Red", forState: UIControlState.Normal) 
     button2.setTitle("Blue", forState: UIControlState.Normal) 
     button3.setTitle("White", forState: UIControlState.Normal) 
     button4.setTitle("Orange", forState: UIControlState.Normal) 
     correctAnswer = "3" 
     break 
    case 2: 
     textoHideUnhide() 
     questionsLabel.text = "What color is the grass?" 
     button1.setTitle("White", forState: UIControlState.Normal) 
     button2.setTitle("Green", forState: UIControlState.Normal) 
     button3.setTitle("Orange", forState: UIControlState.Normal) 
     button4.setTitle("Red", forState: UIControlState.Normal) 
     correctAnswer = "2" 
     break 
    default: 
     break 
} 
+0

你的問題是什麼?你的代碼不工作嗎? – Qbyte

回答

1

,以避免相同的隨機數多次的方式,你可以創建一個數字數組問題,然後你洗牌。

var indices = [0, 1, 2] 

for i in 0 ..< indices.count { 
    var temp = indices[i] 
    var j = arc4random_uniform(indices.count) 
    indices[i] = indices[j] 
    indices[j] = temp 
} 

的第一個問題是,當用戶點擊下一個,你問的問題在indices[1]等在indices[0]提供的號碼和問題。

0

你必須把變量方法外全球(實例)可變

var previousNumber = UInt32.max // declare the variable with an "impossible" value 

func randomQuestions() 
{ 
    var randomNumber : UInt32 
    do { 
    randomNumber = arc4random_uniform(3) 
    } while previousNumber == randomNumber 

    previousNumber = randomNumber 

    switch(randomNumber) { 
    ...