ios - 快速保存高分

标签 ios swift xcode

我给了这个代码,我想给这个项目加高分。我想自己做这件事,但无法让它发挥作用。有人可以帮助我实现这一目标吗?

我试图用 timeInterval 进行操作,但没有成功,这是我从 GitHub 上学习的项目,我试图请作者帮助我,但他没有回答。

    fileprivate extension ViewController {
  func setupPlayerView() {
    playerView.bounds.size = CGSize(width: radius * 2, height: radius * 2)
    playerView.layer.cornerRadius = radius
    playerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

    view.addSubview(playerView)
  }

  func startEnemyTimer() {
    enemyTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(generateEnemy(timer:)), userInfo: nil, repeats: true)
  }

  func stopEnemyTimer() {
    guard let enemyTimer = enemyTimer,
      enemyTimer.isValid else {
        return
    }
    enemyTimer.invalidate()
  }

  func startDisplayLink() {
    displayLink = CADisplayLink(target: self, selector: #selector(tick(sender:)))
    displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
  }

  func stopDisplayLink() {
    displayLink?.isPaused = true
    displayLink?.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
    displayLink = nil
  }

  func getRandomColor() -> UIColor {
    let index = arc4random_uniform(UInt32(colors.count))
    return colors[Int(index)]
  }

  func getEnemyDuration(enemyView: UIView) -> TimeInterval {
    let dx = playerView.center.x - enemyView.center.x
    let dy = playerView.center.y - enemyView.center.y
    return TimeInterval(sqrt(dx * dx + dy * dy) / enemySpeed)
  }

  func gameOver() {
    stopGame()
    displayGameOverAlert()
  }

  func stopGame() {
    stopEnemyTimer()
    stopDisplayLink()
    stopAnimators()
    gameState = .gameOver

  }

  func prepareGame() {
    removeEnemies()
    centerPlayerView()
    popPlayerView()
    startLabel.isHidden = false
    clockLabel.text = "00:00.000"
    gameState = .ready
  }

  func startGame() {
    startEnemyTimer()
    startDisplayLink()
    startLabel.isHidden = true
    beginTimestamp = 0
    gameState = .playing
  }

  func removeEnemies() {
    enemyViews.forEach {
      $0.removeFromSuperview()
    }
    enemyViews = []
  }

  func stopAnimators() {
    playerAnimator?.stopAnimation(true)
    playerAnimator = nil
    enemyAnimators.forEach {
      $0.stopAnimation(true)
    }
    enemyAnimators = []
  }

  func updateCountUpTimer(timestamp: TimeInterval) {
    if beginTimestamp == 0 {
      beginTimestamp = timestamp
    }
    elapsedTime = timestamp - beginTimestamp
    clockLabel.text = format(timeInterval: elapsedTime)
  }


    func highscore(timestamp: TimeInterval) {
        if beginTimestamp == 0 {
            beginTimestamp = timestamp
        }
        elapsedTime = timestamp - beginTimestamp
        highscoreLabel.text = format(timeInterval: elapsedTime)
    }


  func format(timeInterval: TimeInterval) -> String {
    let interval = Int(timeInterval)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let milliseconds = Int(timeInterval * 1000) % 1000
    return String(format: "%02d:%02d.%03d", minutes, seconds, milliseconds)
  }

  func checkCollision() {
    enemyViews.forEach {
      guard let playerFrame = playerView.layer.presentation()?.frame,
        let enemyFrame = $0.layer.presentation()?.frame,
        playerFrame.intersects(enemyFrame) else {
          return
      }
      gameOver()
    }
  }

  func movePlayer(to touchLocation: CGPoint) {
    playerAnimator = UIViewPropertyAnimator(duration: playerAnimationDuration,
                                            dampingRatio: 0.5,
                                            animations: { [weak self] in
                                              self?.playerView.center = touchLocation
                                            })
    playerAnimator?.startAnimation()
  }

  func moveEnemies(to touchLocation: CGPoint) {
    for (index, enemyView) in enemyViews.enumerated() {
      let duration = getEnemyDuration(enemyView: enemyView)
      enemyAnimators[index] = UIViewPropertyAnimator(duration: duration,
                                                     curve: .linear,
                                                     animations: {
                                                       enemyView.center = touchLocation
                                                    })
      enemyAnimators[index].startAnimation()
    }
  }

  func displayGameOverAlert() {
    let (title, message) = getGameOverTitleAndMessage()
    let alert = UIAlertController(title: "Game Over", message: message, preferredStyle: .alert)
    let action = UIAlertAction(title: title, style: .default,
                               handler: { _ in
                                self.prepareGame()
      }
    )
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)
  }

  func getGameOverTitleAndMessage() -> (String, String) {
    let elapsedSeconds = Int(elapsedTime) % 60
    switch elapsedSeconds {
    case 0..<10: return ("I try again", "You need more practice")
    case 10..<30: return ("Maybe Another try?", "No bad, just play more")
    case 30..<60: return ("Play again", "You are like Ninja")
    default:
      return ("WOW", "You are simply the best")
    }



  }

我知道我设法获得了分数状态,但我无法保存高分,这有什么问题

    func updateBest(){

    var defaults=UserDefaults()
    var highscore=defaults.integer(forKey: "highscore")

    if(Int(elapsedTime)) > highscore
    {
        defaults.set(Int(self.elapsedTime), forKey: "highscore")
    }
    var highscoreshow=defaults.integer(forKey: "highscore")

    highscoreLabel.text = "\(highscoreshow)"
    print("hhScore reported: \(highscoreLabel.text)")
  //  clockLabel.text = "\(elapsedTime)"
  //  print("play reported: \(clockLabel.text)")

}

最佳答案

将高分保存到用户默认值:

let highscore : String = "\(Int(self.elapsedTime))"
UserDefaults.standard.set(highscore, forKey: "highscore")

从 userdefaults 中检索高分:

highscoreLabel.text = (UserDefaults.standard.value(forKey: "highscore") as? String)

希望对你有所帮助。干杯。 :]

关于ios - 快速保存高分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43078362/

相关文章:

swift - 如何使用通用 NSFetchedResultsController 进行初始化?

swift - 我的 Xcode 无法识别结构变量

ios - id 标识符 swift

swift - 如何从 string.index 获取 Int?

ios - Swift 2 : Call can throw, 但未标记为 'try' 错误未处理

ios - 在 Swift 中使用 CocoaPods 时如何实现 Nuance Speechkit

ios - 代表另一家公司在 Apple App Store 中发布应用程序

ios - 在应用程序终止后运行代码......可能吗? (Xcode 8, swift 3)

iphone - 以编程方式创建新的 UiImageView

iphone - iOS 中文章搜索的搜索栏