谁能告诉我逻辑有什么问题?
我做了一个十五岁的游戏,遇到了一个问题。我需要确保所有十五个按钮都以正确的方式排列:
逻辑:
每次触摸一个按钮
1. 函数 makeMove() 改变一个按钮的位置。
2.函数checkGameOver()检查所有按钮是否排列正确,如果是,则函数showAlert()弹出一个窗口。
问题:
放置所有按钮后,showAlert() 不会触发,我需要再次触摸任何按钮以获取弹出窗口
谢谢你。
func makeMove(button: UIButton) {
var currentButtonNumber = button.tag - 1
if ( currentButtonNumber >= 0 && currentButtonNumber <= 15 ) && button.tag != 4 && button.tag != 8 && button.tag != 12 {
guard buttons[button.tag - 1].backgroundColor != .none else {
buttons[button.tag - 1].backgroundColor = .yellow
buttons[button.tag - 1].setTitle(button.titleLabel?.text, for: .normal)
buttons[button.tag].backgroundColor = .none
button.setTitle("", for: .normal)
return
}
}
currentButtonNumber = button.tag + 1
if ( currentButtonNumber >= 0 && currentButtonNumber <= 15 ) && button.tag != 3 && button.tag != 7 && button.tag != 11 {
guard buttons[button.tag + 1].backgroundColor != .none else {
buttons[button.tag + 1].backgroundColor = .yellow
buttons[button.tag + 1].setTitle(button.titleLabel?.text, for: .normal)
buttons[button.tag].backgroundColor = .none
button.setTitle("", for: .normal)
return
}
}
currentButtonNumber = button.tag - 4
if currentButtonNumber >= 0 && currentButtonNumber <= 15 {
guard buttons[button.tag - 4].backgroundColor != .none else {
buttons[button.tag - 4].backgroundColor = .yellow
buttons[button.tag - 4].setTitle(button.titleLabel?.text, for: .normal)
buttons[button.tag].backgroundColor = .none
button.setTitle("", for: .normal)
return
}
}
currentButtonNumber = button.tag + 4
if currentButtonNumber >= 0 && currentButtonNumber <= 15 {
guard buttons[button.tag + 4].backgroundColor != .none else {
buttons[button.tag + 4].backgroundColor = .yellow
buttons[button.tag + 4].setTitle(button.titleLabel?.text, for: .normal)
buttons[button.tag].backgroundColor = .none
button.setTitle("", for: .normal)
return
}
}
}
func showAlert() {
var minutes = 0
var seconds = 0
if timerCounter < 60 {
seconds = timerCounter
} else if timerCounter == 60 {
minutes = 1
seconds = 0
} else {
seconds = timerCounter % 60
minutes = (timerCounter - seconds) / 60
}
let alert = UIAlertController(title: "Congratulations!",
message: "You spent \(minutes) minutes and \(seconds) seconds", preferredStyle: .alert)
let action = UIAlertAction(title: "OK",
style: .default, handler: {
action in
self.setNewGame()
})
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func checkGameOver() -> Bool {
var isGameOver = false
var rightOrderCounter = 0
for number in 0...14 {
if (buttons[number].titleLabel?.text == String(number + 1)) {
rightOrderCounter += 1
} else {
rightOrderCounter = 0
break
}
}
if rightOrderCounter == 15 {
isGameOver = true
}
return isGameOver
}
@IBAction func moveButton(button: UIButton) {
makeMove(button: button)
if self.checkGameOver() {
self.stopTimer()
self.showAlert()
}
}