WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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()
        }
    }

1      

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

1      

Thank you so much !!

1      

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()
    }
}

1      

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()
                })
            }
        }
    }
}

1      

thank you very much @Greenamberred.

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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.