我使用计时器为我的游戏,并希望显示当前的分数,并保存高分。我该怎么做?

时间:2015-10-07 03:55:37

标签: ios swift nstimer

计时器从零开始上升。你持续的时间越多,得分越高。如何显示当前分数并用计时器保存高分?我让计时器工作,但我坚持这个问题。我在spritekit和Swift中!谢谢!

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)


    }

1 个答案:

答案 0 :(得分:1)

不是尝试存储和增加三个单独的值,而是存储单个整数,得分,然后每次显示时计算单独的值更简单。

然后比较并保存你的高分,这是一个简单的整数比较。

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)
}