[英]Swift - Locking/tapping a button
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".
示例:我抛出“ 6”和“ 1”。 I tap the "6", so now only the "1" is going to be thrown.
我点击“ 6”,所以现在只抛出“ 1”。
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: 在按钮的
@OBAction
中(即,点击按钮时),切换布尔值:
dice1Locked = !dice1Locked
Then in updateDiceImages
, check whether the dice is locked before changing its image: 然后在
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)
}
I also recommend you to create model for your dice, instead of using buttons: 我还建议您为骰子创建模型,而不要使用按钮:
struct Dice {
var number: Int
var locked: Bool
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.