簡體   English   中英

Swift-鎖定/點擊按鈕

[英]Swift - Locking/tapping a button

我正在用骰子制作游戲。 這個想法是保持/鎖定骰子。 我把骰子做成按鈕,所以現在可以點擊它們了。 示例:我拋出“ 6”和“ 1”。 我點擊“ 6”,所以現在只拋出“ 1”。

我有點迷失了這個,我需要讓布爾值容納它們嗎? 這是我的代碼。 我實際上不知道從哪里開始。

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

是的,您可以使用布爾值來存儲哪個骰子被鎖定。

var dice1Locked = false 
var dice2Locked = false

在按鈕的@OBAction中(即,點擊按鈕時),切換布爾值:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM