我有一个猜谜游戏应用程序,用户试图猜出正确的数字。到目前为止,除了我的重置按钮之外我一切正常,所以用户可以再次玩。在我的重置按钮功能中,我让它将图像和标签文本设置回来,以便用户启动游戏结束,但它似乎不想再次获得新的随机数,它只使用相同的数字。
这就是我到目前为止......
let randomNumber = arc4random_uniform(100)//gets random number
func randomGuess() {
let userGuess = Int(guess.text!)
print(randomNumber)
if(userGuess != nil) {
if(Int(randomNumber) == userGuess) {
lblResult.text = "You win!"
imgCandy.image = UIImage.animatedImage(with:images, duration: 1)
} else {
if(Int(randomNumber) < userGuess!) {
lblResult.text = "Too high - guess again!"
imgCandy.image = UIImage(named: "tooHigh.png")
} else {
lblResult.text = "Too low - guess again!"
imgCandy.image = UIImage(named: "tooLow.png")
}
}
} else {
lblResult.text = "A number from 0-99 is required"
imgCandy.image = UIImage(named: "gumballs.jpg")
}
}
@IBAction func btnGuess(_ sender: Any) {
randomGuess()
}
@IBAction func btnReset(_ sender: Any) {
imgCandy.image = UIImage(named: "gumballs.jpg")
lblResult.text = "Ready? Pick a number from 0-99"
randomGuess()
}
答案 0 :(得分:0)
您的randomNumber
是让常数,因此设置一次并且永远不会更改。将其更改为var
:
var randomNumber = arc4random_uniform(100)
然后在btnReset(_:)
函数中重新设置:
@IBAction func btnReset(_ sender: Any) {
imgCandy.image = UIImage(named: "gumballs.jpg")
lblResult.text = "Ready? Pick a number from 0-99"
randomNumber = arc4random_uniform(100)
randomGuess()
}