How to keep a total of how many points have been scored overall

萝らか妹 提交于 2019-12-13 06:02:52

问题


I want to keep a track of how many points have been scored overall in game over as many games as the person plays. For example, if a person plays the game 25 times and scores 100 each time then their total score would be 2500. This is the method I am using to increment the score in the game:

let waitScore = SKAction.waitForDuration(1.0) //add score every second
let incrementScore = SKAction.runBlock ({
    ++self.score
    self.scoreLabel.text = "\(self.score)"}) //update score label with score
self.runAction(SKAction.repeatActionForever(SKAction.sequence([waitScore,incrementScore])))

The total score will be displayed in a different scene, so I guess I need to save the total score using NSUser defaults, load it in the game scene where the score is being counted and somehow add the loaded total score to the current score then save the total score?! I hope this makes sense.


回答1:


  • Define a convenience constant totalScoreKey somewhere outside a class

    let totalScoreKey = "totalScore"
    
  • In the AppDelegate class register the key totalScore, for example in the init method

      override init()
      {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let defaultValues = [totalScoreKey: 0]
        userDefaults.registerDefaults(defaultValues)
      }
    
  • getTotalScore() reads and returns the total score.
    The method can be implemented in any class

      func getTotalScore() -> Int
      {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        return userDefaults.integerForKey(totalScoreKey)
      }
    
  • updateTotalScore() reads the total score from user defaults adds the value in self.score and writes the value back.
    The method must be implemented in the class which contains the variable score

      func updateTotalScore()
      {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        var totalScore = userDefaults.integerForKey(totalScoreKey)
        totalScore += self.score
        userDefaults.setInteger(totalScore, forKey: totalScoreKey)
      }
    



回答2:


Write:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:10 forKey:@"score"];
[defaults synchronize];

Read:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger score = [defaults integerForKey:@"score"];


来源:https://stackoverflow.com/questions/31771159/how-to-keep-a-total-of-how-many-points-have-been-scored-overall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!