gpt4 book ai didi

Swift - 锁定/点击按钮

转载 作者:行者123 更新时间:2023-11-30 11:26:11 31 4
gpt4 key购买 nike

我正在用骰子制作游戏。这个想法是持有/锁定骰子。我把骰子做成按钮,这样现在就可以点击它们了。示例:我抛出一个“6”和一个“1”。我点击“6”,所以现在只会抛出“1”。

我对这个有点迷失了,我需要创建 bool 值来保存它们吗?这是我的代码。我真的不知道从哪里开始。

class ViewController: UIViewController {

@IBOutlet weak var dice1: UIButton!
@IBOutlet weak var dice2: UIButton!

var audioPlayer:AVAudioPlayer!


var randomDiceIndex1 : Int = 0
var randomDiceIndex2 : Int = 0

let diceArray = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]

func playSoundWith(fileName: String, fileExtenstion: String) -> Void {
let audioSourceURL: URL!
audioSourceURL = Bundle.main.url(forResource: fileName,
withExtension: fileExtenstion)
if audioSourceURL == nil {
print("Geluid werkt niet")
} else {
do {

audioPlayer = try AVAudioPlayer.init(contentsOf:
audioSourceURL!)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}

override func viewDidLoad() {
super.viewDidLoad()
updateDiceImages()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}


@IBAction func buttonPressed(_ sender: Any) {
updateDiceImages()
playSoundWith(fileName: "dobbelstenen", fileExtenstion: "m4a")
}

func updateDiceImages(){
randomDiceIndex1 = Int(arc4random_uniform(6))
randomDiceIndex2 = Int(arc4random_uniform(6))

dice1.setImage(UIImage(named: diceArray[randomDiceIndex1]), for:
.normal)
dice2.setImage(UIImage(named: diceArray[randomDiceIndex2]), for:
.normal)
}

override func motionEnded(_ motion: UIEventSubtype, with event:
UIEvent?) {
updateDiceImages()
playSoundWith(fileName: "dobbelstenen", fileExtenstion: "m4a")
}
}

最佳答案

是的,您可以使用 bool 值来存储哪些骰子被锁定。

var dice1Locked = false 
var dice2Locked = false

在按钮的 @OBAction 中(即点击按钮时),切换 bool 值:

dice1Locked = !dice1Locked

然后在updateDiceImages中,在更改骰子图像之前检查骰子是否已锁定:

if !dice1Locked {
randomDiceIndex1 = Int(arc4random_uniform(6))
dice1.setImage(UIImage(named: diceArray[randomDiceIndex1]), for:
.normal)
}

if !dice2Locked {
randomDiceIndex2 = Int(arc4random_uniform(6))
dice2.setImage(UIImage(named: diceArray[randomDiceIndex2]), for:
.normal)
}

我还建议您为骰子创建模型,而不是使用按钮:

struct Dice {
var number: Int
var locked: Bool
}

关于Swift - 锁定/点击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50714420/

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