因此,我在swift 5上进行了简单的游戏,基本上,我有3..2..1 .. go计时器来启动游戏,然后有3..2..1..stop计时器来停止游戏。游戏。最后是一个显示分数的功能。我需要为每个函数调用等待下一个定时器开始之前等待计时器完成的方法,有什么建议吗?到目前为止,这是我的代码。 (另外,如果您对应用程序还有其他建议,请告诉我,最终目标是注册您在3秒钟内可以执行多少次按钮点击)
var seconds = 3 //Starting seconds
var countDownTimer = Timer()
var gameTimer = Timer()
var numberOfTaps = 0
override func viewDidLoad() {
super.viewDidLoad()
self.startCountdown(seconds: seconds)
self.gameCountdown(seconds: seconds)
self.displayFinalScore()
}
func startCountdown(seconds: Int) {
countDownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
self?.seconds -= 1
if self?.seconds == 0 {
self?.countdownLabel.text = "Go!"
timer.invalidate()
} else if let seconds = self?.seconds {
self?.countdownLabel.text = "\(seconds)"
}
}
}
func gameCountdown(seconds: Int) {
gameTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
self?.seconds -= 1
if self?.seconds == 0 {
self?.countdownLabel.text = "Stop!"
timer.invalidate()
} else if let seconds = self?.seconds {
self?.countdownLabel.text = "\(seconds)"
}
}
}
deinit {
// ViewController going away. Kill the timer.
countDownTimer.invalidate()
}
@IBOutlet weak var countdownLabel: UILabel!
@IBAction func tapMeButtonPressed(_ sender: UIButton) {
if gameTimer.isValid {
numberOfTaps += 1
}
}
func displayFinalScore() {
if !gameTimer.isValid && !countDownTimer.isValid {
countdownLabel.text = "\(numberOfTaps)"
}
}
要实现所需的功能,需要移至viewDidLoad
的函数调用out下方,并将其放在[Cin]块的[[inside中。
Timer
即函数调用self.gameCountdown(seconds: seconds) self.displayFinalScore()
将进入在self.gameCountdown(seconds: seconds)
中启动的定时器块中。这样,当秒数变为0时使计时器无效时,请调用startCountdown
。类似地,在以
gameCountdown
启动的计时器中,当秒数变为0时,您调用gameCountdown
。其他建议。您应该避免检查
self.displayFinalScore
中的属性。您应该禁用并启用“点击我”按钮。即在启动gameCountdown时将其启用,并在结束时将其禁用。类似地,您不需要检查
tapMeButtonPressed
中计时器的状态。它应该只做一件事,即显示最终分数。稍后会为您省去很多麻烦:)。我的2美分。