gpt4 book ai didi

swift - 猜测后重新生成随机数

转载 作者:行者123 更新时间:2023-11-30 12:43:13 25 4
gpt4 key购买 nike

我有一个猜谜游戏应用程序,用户尝试猜测正确的数字。到目前为止,除了重置按钮之外,我一切正常,以便用户可以再次玩游戏。在我的重置按钮功能中,我将其设置回图像和标签文本,以便用户重新开始游戏,但它似乎不想再次获得新的随机数,它只是使用相同的数字。

这就是我到目前为止所拥有的......

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()
}

最佳答案

您的randomNumber是一个let常量,因此它被设置一次并且永远不会改变。将其更改为 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()
}

关于swift - 猜测后重新生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com