I am making a game with dices. The idea is to hold/lock a die. I made the dices as buttons so now they can be tapped. Example: I throw a "6" and a "1". I tap the "6", so now only the "1" is going to be thrown.
I'm kinda lost with this one, do I need to make booleans to hold them? Here's my code. I actually don't know where to start.
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")
}
}
Yes you can use booleans to store which dice is locked.
var dice1Locked = false
var dice2Locked = false
In the @OBAction
s of the buttons (ie when the buttons are tapped), toggle the booleans:
dice1Locked = !dice1Locked
Then in updateDiceImages
, check whether the dice is locked before changing its image:
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)
}
I also recommend you to create model for your dice, instead of using buttons:
struct Dice {
var number: Int
var locked: Bool
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.