繁体   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