mardi 31 octobre 2017

Random questions & highscores in swift quiz app

Hey guys im new in swift and i search a function that displays a high score in my quiz app and i also search for a function that randomize the questions without repeating one of them. the score should appear on another view controller after finishing the quiz (or after you answered a question wrong, but that is for the future). thx for your help and sorry for my bad english!

let questions = ["best mother?", "best father?", "best sister?"]
let answers = [["Josi", "Maria", "Annika"], ["Andi", "Uwe", "Jupp"], ["Claudia", "Anna", "Lena"]]

// Variables
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var points = 0;

//Label
@IBOutlet weak var label: UILabel!

//Button
@IBAction func action(_ sender: Any)
{
    if ((sender as AnyObject).tag == Int(rightAnswerPlacement))
    {
        print ("Right!")
        points += 1
    }
    else
    {
        print ("Wrong!")
    }

    if (currentQuestion != questions.count)
    {
        newQuestion()
    }
    else
    {
        performSegue(withIdentifier: "showScore", sender: self)
    }
}

override func viewDidAppear(_ animated: Bool)
{
    newQuestion()
}

//Function that displays new question
func newQuestion()
{
    label.text = questions[currentQuestion]

    rightAnswerPlacement = arc4random_uniform(3)+1

    //Create a button
    var button:UIButton = UIButton()

    var x = 1

    for i in 1...3
    {
        //Create a button
        button = view.viewWithTag(i) as! UIButton

        if (i == Int(rightAnswerPlacement))
        {
            button.setTitle(answers[currentQuestion][0], for: .normal)
        }
        else
        {
            button.setTitle(answers[currentQuestion][x], for: .normal)
            x = 2
        }
    }
        currentQuestion += 1
}




Aucun commentaire:

Enregistrer un commentaire