快速保存高分

时间:2017-03-28 19:33:16

标签: 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)")

}

1 个答案:

答案 0 :(得分:0)

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

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

从userdefaults中检索高分:

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

我希望它有所帮助。干杯。 :