Search code examples
iosswiftnstimer

Im using a timer for my game and would like to show the current score and save the high score. How would I do this?


The timer starts at zero and goes up. The more time you last the higher the score. How would I show the current score and save the high score with a timer? I got the timer to work but Im stuck at this problem. Im in spritekit and in Swift! Thanks!

func updateTimer() {

    fractions += 1
    if fractions == 100 {

        seconds += 1
        fractions = 0
    }

    if seconds == 60 {

        minutes += 1
        seconds = 0
    }

    let fractionsString = fractions > 9 ? "\(fractions)" : "0\(fractions)"
    let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
    let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"


    timerString = "\(minutesString):\(secondsString).\(fractionsString)"
    countUpLabel.text = timerString

}

 //EDIT..............

  func saveHighScore() {

    let defaults=NSUserDefaults()


    let highscore=defaults.integerForKey("highscore")


    if(timerString > highscore)
    {
        defaults.setInteger(timerString, forKey: "highscore")
    }
    let highscoreshow = defaults.integerForKey("highscore")

    endOfGameHighScoreLabel.text = String(highscoreshow)


    }

Solution

  • Rather than trying to store and increment the three separate values, it is simpler to store a single integer, score, and then calculate the separate value each time for display.

    Then to compare and save your high score it is a simple integer comparison.

    func updateTimer() {
        self.score++
        countUpLabel.text=self.timeStringForScore(self.score)
    }
    
    
    func timeStringForScore(score:Int) -> String {
        let minutes:Int=score/6000;
        let seconds:Int=(score-minutes*6000)/100
        let fractions:Int = score-minutes*6000-seconds*100
        return String(format: "%02d:%02d:%02d", minutes,seconds,fractions)
    }
    
    func saveHighScore() {  
        let defaults=NSUserDefaults()
        let highscore=defaults.integerForKey("highscore")
        if(self.score > highscore)
        {
            defaults.setInteger(self.score, forKey: "highscore")
        }
    
        endOfGameHighScoreLabel.text = self.timeStringForScore(highscore)
    }