我正在用骰子制作游戏。想法是保持/锁定骰子。我把骰子做成按钮,所以现在可以点击它们。示例:我抛出“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")
}
}
答案 0 :(得分:0)
是的,您可以使用布尔值来存储锁定的骰子。
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
}