骰子轉轉轉 - 基本題
Published in
4 min readMay 23, 2020
Demo :
利用IBAction或是偵測shake動作來做骰子的切換
@IBAction func didTapChangeDiceButton(_ sender: Any) { self.playMusic() self.diceSum = 0 for imageView in dicesImageList { imageView.image = UIImage(named: self.imageName.randomElement()!) self.sum(imageView: imageView)
}}// 偵測晃動
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == .motionShake { self.playMusic() self.diceSum = 0 print("shake") for imageView in dicesImageList {
imageView.image = UIImage(named: self.imageName.randomElement()!) self.sum(imageView: imageView)
}
}
}
利用AVPlayer()來播放骰子滾動的音效,先將音效檔放進project裡
func playMusic() { let fileUrl = Bundle.main.url(forResource: "轉動音效", withExtension: "mp3")! let playerItem = AVPlayerItem(url: fileUrl) player.replaceCurrentItem(with: playerItem) player.play()
}
每次更換骰子圖片,利用if else 來判斷圖片的檔案,加總所有點數
func sum(imageView: UIImageView) { if imageView.image == UIImage(named: "dices_1") { self.diceSum += 1 }else if imageView.image == UIImage(named: "dices_2") { self.diceSum += 2 }else if imageView.image == UIImage(named: "dices_3") { self.diceSum += 3 }else if imageView.image == UIImage(named: "dices_4") { self.diceSum += 4 }else if imageView.image == UIImage(named: "dices_5") { self.diceSum += 5 }else if imageView.image == UIImage(named: "dices_6") { self.diceSum += 6
} self.diceSumLabel.text = "點數:\(self.diceSum)"}
GitHub:
參考資料: