UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

DAY 25 Challenge - Please help

Forums > 100 Days of SwiftUI

hello

i'm very new to programming and i have just start the 100 Days of SwitUI. I really need help because it's been two days since I try to solve the first challenge.

I create the buttons in a ForEach and try to access the button selected by the user to check. But the score is very werdly count (i understand that my check function is call several times...)

Your help would be very much appreciated.

Thank you

my code:

struct ContentView: View {

    var choice = ["Rock", "Paper", "Scissors"]
    @State var score = 0

    @State private var computerChoice = Int.random(in: 0 ..< 3)
    @State private var shouldWin = Bool.random()

    var body: some View {

        Form {
            Text("Score: \(score)")
            Text("Computer has choosen:")
            Text("\(choice[computerChoice])").bold().padding()
            Text("You have to \(shouldWin ? "WIN" : "LOOSE")")
            HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 40) {
                ForEach(0 ..< 3) { item in
                    Button(action: {
                        self.checkChoice(item)
                        self.next()
                    }) {
                        Text("\(choice[item])").padding()
                    }
                }
            }
        }
    }

    func checkChoice(_ item: Int) {
        if shouldWin == true {
            if computerChoice == item {
                score -= 1
            }
            else if computerChoice == 0 && item == 2 {
                print("you loose, you choose Scissors and computeur Rock")
            }
            else if computerChoice == 1 && item == 0 {
                print("you loose, you choose Rock and computeur Paper")
            }
            else if computerChoice == 2 && item == 1 {
                print("you loose, you choose Paper and computeur Scissors")
            } else {
                score += 1
            }
        } else {
            if computerChoice == 0 && item == 2 {
                print("you win, you choose Scissors and computeur Rock")
                score += 1
            }
            else if computerChoice == 1 && item == 0 {
                print("you win, you choose Rock and computeur Paper")
                score += 1
            }
            else if computerChoice == 2 && item == 1 {
                print("you win, you choose Paper and computeur Scissors")
                score += 1
            } else {
                score -= 1
            }

        }

    }

    func next() {
        computerChoice = Int.random(in: 0 ..< 3)
        shouldWin = Bool.random()
    }
}

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

3      

I am a bit busy to debug your code now, but I have written this long time ago, hope it helps.

https://github.com/EpiGardenia/100DaysOfSwiftUI/tree/master/Day25_Milestone1

3      

Thank you so much !!

3      

i try to improve my code, unfortunately i still have an issue:

in the ForEach I get the index of the button to check the answer, but the ForEach repeats 3 times and so the function to check the answer... i don't understand why the function to check repeats 3 times in my code and not in the other solution i could find.

struct ContentView: View {

    var choice = ["Rock", "Paper", "Scissors"]
    @State var score = 0

    @State private var computerChoice = Int.random(in: 0 ..< 3)
    @State private var shouldWin = Bool.random()
    var goodAnswer: Int {
        if shouldWin == true {
        if computerChoice == 2 {
            return 0
        } else {
            return computerChoice + 1
        }
        }
        else {
            if computerChoice == 2 {
                return 1
            } else if computerChoice == 1 {
                return 0
            } else {
                return 2
        }
    }
    }

    var body: some View {

        Form {
            Text("Score: \(score)")
            Text("Computer has choosen:")
            Text("\(choice[computerChoice])").bold().padding()
            Text("You have to \(shouldWin ? "WIN" : "LOOSE")")
            HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 40) {
                ForEach(0 ..< 3, id:\.self) { item in
                    Button(action: {
                        self.checkChoice(item)
                    }, label: {
                        Text("\(choice[item])").padding()
                    })
                }
            }
        }
    }

    func checkChoice(_ item: Int) {
        if item == self.goodAnswer {
            score += 1
            next()
        }
        else {
            score -= 1
            next()
        }
    }

    func next() {
        computerChoice = Int.random(in: 0 ..< 3)
        shouldWin = Bool.random()
    }
}

3      

Your main problem is down to using a Form. The form processed once per item (in this case 3 times). Change it to something like a VStack, instead.

Also you do not need the id: \.self, as 0 ..< 3 is range that is already uniquely identified.

var body: some View {

    VStack{
        Text("Score: \(score)")
        Text("Computer has choosen:")
        Text("\(choice[computerChoice])").bold().padding()
        Text("You have to \(shouldWin ? "WIN" : "LOOSE")")
        HStack(alignment: .center, spacing: 40) {
            ForEach(0 ..< 3) { item in
                Button(action: {
                    self.checkChoice(item)
                }, label: {
                    Text("\(choice[item])").padding()
                })
            }
        }
    }
}

3      

thank you very much @Greenamberred.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.