Day 25 of #100DaysOfSwiftUI

Start 100DaysOfSwiftUI from 2020.Mar.18th.

Day 25: Milestone: Projects 1-3
done with 30 min.

New findings: followings are new findings

  • how to use id: with ForEach, and why ForEach needs to know id
var possibleMoves = ["Rock", "Paper", "Scissors"]

@State var choice = Int.random(in: 0...2)
@State var shouldWin = Bool.random()

@State var scoreTitle = ""
@State var playerScore = 0
@State var showScore = false

var body: some View {
    VStack(spacing: 10) {
        Text("Score : \(playerScore)")
        Text("Computer:  \(possibleMoves[choice])")
        Text(shouldWin ? "Need to win!" : "Need to loose")
        
        HStack {
            Button("Rock") {
                if ( ((self.shouldWin)&&(self.choice == 2)) ||
                    ((!self.shouldWin)&&(self.choice == 1))) {
                    self.playerScore += 3
                    self.scoreTitle = "YOU WIN !"
                } else {
                    self.playerScore -= 1
                    self.scoreTitle = "YOU LOOSE !"
                }
                self.showScore = true
            }
            Button("Paper") {
                if ( ((self.shouldWin)&&(self.choice == 0)) ||
                    ((!self.shouldWin)&&(self.choice == 2))) {
                    self.playerScore += 3
                    self.scoreTitle = "YOU WIN !"
                } else {
                    self.playerScore -= 1
                    self.scoreTitle = "YOU LOOSE !"
                }
                self.showScore = true
            }
            Button("Scissors") {
                if ( ((self.shouldWin)&&(self.choice == 1)) ||
                    ((!self.shouldWin)&&(self.choice == 0))) {
                    self.playerScore += 3
                    self.scoreTitle = "YOU WIN !"
                } else {
                    self.playerScore -= 1
                    self.scoreTitle = "YOU LOOSE !"
                }
                self.showScore = true
            }
        }
    }
    .alert(isPresented: $showScore ) {
        Alert(title: Text(scoreTitle),
              message: Text("your score : \(playerScore)"),
              dismissButton: .default(Text("OK")){
                self.askAgain()
        })
    }
}

func askAgain() {
    choice = Int.random(in: 0...2)
    shouldWin = Bool.random()
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です