Hello everyone! I just have a question regarding my code for the War Card Game in which the game behaves somewhat inconsistently.
To illustrate:
The game behaves as normal during the first 3 instances. The player’s card is larger than the CPU’s card and so it increases the value of the player’s score.
However, as you can see in this instance - the player’s card is clearly larger than the CPU’s card - however the CPU’s score is increased instead of the player
Why is this the case? What did I do wrong? I realize that Chris used “playerRand” and “cpuRand” for his if statements, whereas I used “playerCard” and “cpuCard” - however, I do not understand why this wouldn’t work logically. Can someone please explain?
import SwiftUI
struct ContentView: View {
@State var playerCard = "card5" @State var cpuCard = "card9" @State var playerScore = 0 @State var cpuScore = 0 var body: some View { ZStack{ Image("background").ignoresSafeArea() VStack{ Spacer() Image("logo") Spacer() HStack{ Spacer() Image(playerCard) Spacer() Image(cpuCard) Spacer() } Spacer() Button(action: { //Generate a random number between 2 and 14 let playerRand = Int.random (in: 2...14) let cpuRand = Int.random(in: 2...14) //Update the cards playerCard = "card" + String(playerRand) cpuCard = "card" + String(cpuRand) //Update the score if playerCard > cpuCard { playerScore += 1 } else if cpuCard > playerCard { cpuScore += 1 } }) {Image("dealbutton")} Spacer() HStack{ Spacer() VStack{ Text("Player") .foregroundColor(Color.white) .font(.largeTitle) .padding() Text(String(playerScore)) .foregroundColor(Color.white) .font(.title) } Spacer() VStack{ Text("CPU") .foregroundColor(Color.white) .font(.largeTitle) .padding() Text(String(cpuScore)) .foregroundColor(Color.white) .font(.title) } Spacer() } Spacer() } } }
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}