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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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() } |
Sponsor Link