在swift中生成随机问题

时间:2015-03-28 13:43:01

标签: swift

有人可以帮忙吗?我有一个真假游戏,但是,我希望这些问题可以随机播放/随机播放。我知道以前有过洗牌的答案,但我无法理解它。例如,附加部分中的问题应随机出现。我好几天都在尝试不同的事情。我看了一下arc4random但我很难实现它。我不想用勺子喂食,但我正在寻找一个体面的答案。

这是我的快捷代码

//  ViewController.swift
 //  TrueOrFalse
 //
  // 
   //

     import UIKit


      class ViewController: UIViewController {
        // Classes
         class newLabel:UILabel {
              convenience required init(width:CGFloat,                                     height:CGFloat,              framewidth: CGFloat, frameheight: CGFloat) {
        self.init(frame: CGRectMake(0, 0, framewidth, frameheight))
        self.center = CGPointMake(width, height)
        self.font = UIFont(name: "HelveticaNeue-Medium", size: 18)
    }

}

class newButton:UIButton {
    var button:UIButton!
    convenience required init(width:CGFloat, height:CGFloat, framewidth: CGFloat, frameheight: CGFloat) {
        self.init(frame: CGRectMake(0, 0, framewidth, frameheight))
        self.button = UIButton.buttonWithType(UIButtonType.System) as UIButton
        self.center = CGPointMake(width, height)
    }
}

let width:CGFloat = UIScreen.mainScreen().bounds.width
let height:CGFloat = UIScreen.mainScreen().bounds.height

var model:ToFModel = ToFModel()
var statement:UILabel!
var correctCount:newLabel!
var incorrectCount:newLabel!
var timerCount:newLabel!
var correctAmt:Int = 0
var incorrectAmt:Int = 0
var buttonTrue:newButton!
var buttonFalse:newButton!
var count:Int = 0
var counter:Int = 60
var answer:String!
var wall:UIView!
var lastBool:String!
var displayLastBool:newLabel!
var questionNumber:newLabel!
var frame:UIImageView!
var image:UIImage!
var splashImage:UIImage!
var splashLandingText:UILabel!
var splashButtonStart:newButton!
var timer = NSTimer()
var userDefaults = NSUserDefaults.standardUserDefaults()


func nextIter() {
    statement.text = model.statements[count][0]
    answer = model.statements[count][1]
    questionNumber.text = "Question- \(count+1)/\(model.statements.count)"

    if count == model.statements.count-1{
       statement.textColor = UIColor.redColor()
    }
    else{
        statement.textColor = UIColor.blackColor()
    }
    if count > 0 && count < model.statements.count {

        // displayLastBool.text = ""
        view.addSubview(displayLastBool)
    }
    else {
        displayLastBool.text = ""
    }
    count += 1
}

// View functions
func start(sender:newButton) {
    count = 0
    frame.image = image
    displayLastBool = newLabel(width: 170, height: height*0.27, framewidth: 200, frameheight: 50)

    //Timer
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)

    // Put the image into the frame
    // Remove current stuff
    splashButtonStart.removeFromSuperview()
    splashLandingText.removeFromSuperview()
    // Add stuff to view
    view.addSubview(timerCount)
    view.addSubview(correctCount)
    view.addSubview(incorrectCount)
    view.addSubview(statement)
    view.addSubview(buttonTrue)
    view.addSubview(buttonFalse)
    view.addSubview(questionNumber)
    nextIter()
}


func splashPage() {
    count = 0
    displayLastBool?.removeFromSuperview()

    // Put up the wall
    view.addSubview(wall)
    // Hang the frame on the wall
    wall.addSubview(frame)
    // Put up the text
    view.addSubview(splashLandingText)
    // Put up the button
    view.addSubview(splashButtonStart)
    frame.image = splashImage

}

func reset() {
    correctCount.hidden = true
    incorrectCount.hidden = true
    count = 0
    incorrectAmt = 0
    correctAmt = 0
    correctCount.removeFromSuperview()
    incorrectCount.removeFromSuperview()
    statement.removeFromSuperview()
    buttonFalse.removeFromSuperview()
    buttonTrue.removeFromSuperview()
    questionNumber.removeFromSuperview()
    displayLastBool.removeFromSuperview()
    splashPage()
}

// Boolean detection
func boolResponse(sender:newButton) {
    if count == model.statements.count {
        if answer == String(sender.tag) {
            count = 0
            correctAmt = 0
            incorrectAmt = 0
            correctCount.hidden = true
            incorrectCount.hidden = true

            displayLastBool.hidden = false

            timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)

        }
        else {
            timer.invalidate()
            reset()
        }
    }
    else if answer == String(sender.tag) {
        lastBool = "Correct"
        displayLastBool.textColor = UIColor.greenColor()
        // Correct count increments here
        correctAmt += 1
    }
    else if answer != String(sender.tag) {
        lastBool = "Incorrect"
        displayLastBool.textColor = UIColor.redColor()
        // Incorrect count increments here
        incorrectAmt += 1
        count = 9;
    }
    if count == model.statements.count-1 {
        correctCount.hidden = false
        incorrectCount.hidden = false

        correctCount.text = "Correct- \(correctAmt)"
        //incorrectCount.text = "Incorrect- \(incorrectAmt)"


        //Saving Highscore
        var highscore=userDefaults.integerForKey("highscore")

        if(correctAmt>highscore)
        {
            userDefaults.setInteger(correctAmt, forKey: "highscore")
        }
        var highscoreshow=userDefaults.integerForKey("highscore")
        incorrectCount.text = "High Score- \(highscoreshow)"





        timer.invalidate()
        counter = 60
        timerCount.text = String(counter)
        timerCount.textColor = UIColor.blackColor()
    }
    nextIter()
}

//Timer update function
func updateCounter() {
    timerCount.text = String(counter--)

    if counter <= 9{
        timerCount.textColor = UIColor.redColor()
    }else{
        timerCount.textColor = UIColor.blackColor()
    }

    if counter == 0{
        count=9
        nextIter()
        resetTimer()
    }
}

//Timer reset function
func resetTimer() {
    correctCount.hidden = false
    incorrectCount.hidden = false

    correctCount.text = "Correct- \(correctAmt)"
    incorrectCount.text = "Incorrect- \(incorrectAmt)"
    timer.invalidate()
    counter = 60
    timerCount.text = String(counter)
    timerCount.textColor = UIColor.blackColor()

   // displayLastBool.hidden = true
    //questionNumber.hidden = true
}


// Make an image view that you can modify from any function in this class
var imageView:UIImageView = UIImageView()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.



    // Append




    model.statementsAppend("Sneezes regularly exceed 200 mph.", bool: "0")
    model.statementsAppend("Virtually all Las Vegas gambling casinos ensure that they have no clocks.", bool: "1")
    model.statementsAppend("Two human lungs have a surface area of approximately 750 square feet.", bool: "1")
    model.statementsAppend("The 'black box' in an airplane is colored black.", bool: "0")
    model.statementsAppend("The Statue of Liberty was a gift from Germany to America.", bool: "0")
    model.statementsAppend("Ozone is helpful in the trophosphere but damaging to the stratosphere.", bool: "0")
    model.statementsAppend("The can opener was invented after the can.", bool: "1")
    model.statementsAppend("The world's oldest tree is OVER 9000 years old.", bool:"1")
    model.statementsAppend("Emus can fly.", bool: "0")
    model.statementsAppend("Game Over \n Play again?", bool: "1")




    // Make the wall, the frame, and the image for the frame
    wall = UIView(frame: CGRectMake(0, 0, width, height))
    frame = UIImageView(frame: CGRectMake(0, 0, width, height))

    //Load the text
    statement = UILabel(frame: CGRectMake(0, 0, 280, height))
    statement.center = CGPointMake(width/2, height*0.5)
    statement.textAlignment = NSTextAlignment.Center
    statement.lineBreakMode = NSLineBreakMode.ByWordWrapping
    statement.numberOfLines = 99
    statement.font = UIFont(name: "Arial", size: 24)

    splashImage = UIImage(named: "splashGradient")
    image = UIImage(named: "minimalGradient")

    //Load the counts
    timerCount = newLabel(width: 100, height: height*0.10, framewidth:200, frameheight:100)
    correctCount = newLabel(width: 159, height: height*0.15, framewidth:100, frameheight:50)
    incorrectCount = newLabel(width:147, height: height*0.19, framewidth:130, frameheight:50)
    questionNumber = newLabel(width: 197, height: height*0.23, framewidth: 200, frameheight: 50)

    timerCount.center = CGPointMake(width/2, height*0.09)
    timerCount.textAlignment = NSTextAlignment.Center
    timerCount.font = UIFont(name: "AvenirNext-DemiBold", size: 40)
    timerCount.text = String(counter)

    correctCount.text = "Correct- \(correctAmt)"
    incorrectCount.text = "High Score- \(incorrectAmt)"
    incorrectCount.textColor = UIColor.greenColor()
    lastBool = "Incorrect"

    correctCount.hidden = true
    incorrectCount.hidden = true
    questionNumber.hidden = true

    //Load the buttons
    buttonTrue = newButton(width: 80, height: height/1.2, framewidth: 111, frameheight: 45)
    buttonFalse = newButton(width: 240, height: height/1.2, framewidth: 111, frameheight: 45)
    // Style of button
    buttonTrue.setBackgroundImage(UIImage(named: "true"), forState: UIControlState.Normal)
    buttonFalse.setBackgroundImage(UIImage(named: "false"), forState: UIControlState.Normal)
    // .tag
    buttonTrue.tag = 1
    buttonFalse.tag = 0

    // Functions if button is clicked
    buttonTrue.addTarget(self, action: "boolResponse:", forControlEvents: UIControlEvents.TouchUpInside)
    buttonFalse.addTarget(self, action: "boolResponse:", forControlEvents: UIControlEvents.TouchUpInside)

    // Make the splash button
    splashButtonStart = newButton(width: width/2, height: height*0.8, framewidth: 244, frameheight: 58)
    splashButtonStart.setBackgroundImage(UIImage(named: "splashButton"), forState: UIControlState.Normal)
    splashButtonStart.addTarget(self, action: "start:", forControlEvents: UIControlEvents.TouchUpInside)

    // Configure the text on the splash page
    splashLandingText = UILabel(frame: CGRectMake(0, 0, 280, 280))
    splashLandingText.center = CGPointMake(width/2, height*0.4)
    splashLandingText.textAlignment = NSTextAlignment.Center
    splashLandingText.numberOfLines = 99
    splashLandingText.lineBreakMode = NSLineBreakMode.ByWordWrapping
    splashLandingText.font = UIFont(name: "AvenirNext-DemiBold", size: 24)
    splashLandingText.text = "Impossible True or False \n \n Are you ready to start your journey?"


    // Configure the statement
    splashPage()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

1 个答案:

答案 0 :(得分:1)

我没有试图浏览你的代码。太过分了。 (tldr) 这是一般解决方案。您需要根据自己的需求进行调整。 创建一个包含问题,可能答案和正确答案的结构(如果它们都是真/假问题,您可以跳过可能的答案部分。)让我们称之为questionStruct。

然后创建一个questionStruct结构数组。用问题填充它。

将所有问题列表复制到一系列问题中。我们称之为剩余问题

然后用户arc4random_uniform随机选择一个问题并将其从剩余的问题数组中删除

let index = arc4random_uniform(remainingQuestions.count)
let aQuestion = remainingQuestions.removeAtIndex(index)

当remainingQuestions数组为空时,重新填充所有问题的数组以重新开始。