我有这个应用程序按下一个按钮使得得分上升一,直到你达到50以上,然后按下按钮将2添加到得分。但问题是,每按一次按钮都会将级别改为1。这是我的代码:
import UIKit
class ViewController: UIViewController {
// OUTLETS
@IBOutlet weak var score: UILabel!
@IBOutlet weak var levelLabel: UILabel!
@IBAction func add(_ sender: Any) {
add()
}
// VARIABLES
var scoreVar = 0
let levelUpAt = [10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000]
var currentLevel = 1
var toAdd = 1
// FUNCTIONS
// Below code adds to the score
func add() {
if (scoreVar - 1 < levelUpAt[currentLevel - 1] && levelUpAt.indices.contains(currentLevel)) { // Complicated math-y if statment THANK YOU RASHWAN L (STACK OVERFLOW) FOR HELPING
currentLevel += 1 // Change level
toAdd += 1 // Change toAdd
levelLabel.text = "Level \(currentLevel)" // Change the level label
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
} else {
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
}
}
}
答案 0 :(得分:0)
看起来if
条件应该运行else
代码,反之亦然。要比较的第一个值是scoreVar
而不是scoreVar - 1
。
func add() {
if (scoreVar < levelUpAt[currentLevel - 1] && levelUpAt.indices.contains(currentLevel)) { // Complicated math-y if statment THANK YOU RASHWAN L (STACK OVERFLOW) FOR HELPING
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
} else {
currentLevel += 1 // Change level
toAdd += 1 // Change toAdd
levelLabel.text = "Level \(currentLevel)" // Change the level label
scoreVar += toAdd // Adds toAdd (level amount) to scoreVar
score.text = "\(scoreVar)"; // Updates text to match
}
}