如何保持总共得到了多少分 [英] How to keep a total of how many points have been scored overall

查看:71
本文介绍了如何保持总共得到了多少分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录在该人参加的比赛中总得分多少.例如,如果一个人玩游戏 25 次,每次得分 100,那么他们的总得分为 2500.这是我在游戏中使用的增加得分的方法:

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

总分将显示在不同的场景中,所以我想我需要使用 NSUser 默认值保存总分,将其加载到正在计算分数的游戏场景中,并以某种方式将加载的总分添加到当前分数然后保存总分?!我希望这是有道理的.

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.

推荐答案

  • 在类之外的某处定义一个方便的常量totalScoreKey

    let totalScoreKey = "totalScore"
    

  • 在 AppDelegate 类中注册键 totalScore,例如在 init 方法中

      override init()
      {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let defaultValues = [totalScoreKey: 0]
        userDefaults.registerDefaults(defaultValues)
      }
    

  • getTotalScore() 读取并返回总分.
    该方法可以在任何类中实现

  • 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() 从用户默认值中读取总分,将值添加到 self.score 中并将该值写回.
    该方法必须在包含变量 score

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

  • 这篇关于如何保持总共得到了多少分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆