🪶

SwiftUIでサイコロを振る

に公開

🎲サイコロゲームを作ってみた!

SwiftUIでサイコロをふる簡単なゲームを作ってみたいと思った。。。
「できるのか???」

できるはず。lottiefilesというアニメーション素材を使えばできた!

https://lottiefiles.com/

こちらの青いサイコロの素材を使用した。
https://lottiefiles.com/free-animation/dice-roll-purple-U94g53sIy8

SwiftUIで使用するには、こちらのライブラリをSPMで追加します。
https://developers.lottiefiles.com/docs/dotlottie-player/dotlottie-ios/

GitHubのURLを貼り付ける👇
https://github.com/LottieFiles/dotlottie-ios

SwiftUIのImageにもサイコロはあるみたいでこちらも使っております。ロジックを使って、1とか6とか表示できるように工夫してます!

ライブラリを追加したら、ソースコードを書く!

import SwiftUI
import DotLottie

struct ContentView: View {
    @State private var diceNumber = 1
    @State private var isAnimating = false
    
    var body: some View {
        VStack {
            Button(action: {
                rollDice()
            }) {
                Text("Roll the Dice")
                    .font(.largeTitle)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
            .padding()
            
            if isAnimating {
                AnimationView()
            } else {
                VStack {
                    Image(systemName: "die.face.\(diceNumber)")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 100, height: 100)
                    
                    if diceNumber == 6 {
                        Text("アガリ!")
                            .font(.title)
                            .foregroundColor(.red)
                            .padding()
                    }
                }
            }
        }
    }
    
    private func rollDice() {
        isAnimating = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            diceNumber = Int.random(in: 1...6)
            isAnimating = false
        }
    }
    
    struct AnimationView: View {
        var body: some View {
            DotLottieAnimation(fileName: "dice", config: AnimationConfig(autoplay: true, loop: false)).view()
        }
    }
}

#Preview {
    ContentView()
}

動作はこんな感じですね!
gif画像なので早く動いている。。。。

最後に

今回は、lottiefilesを使用してサイコロのアニメーションを簡単に導入してダイスゲームをSwiftUIで作ってみました!

サイコロ以外のゲームを作るのにもアニメーションの素材が生かせそうなので色々試してみてください。

Discussion