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

Need help with the "Rock - Paper - Scissors" Challenge (Day 25)

Forums > 100 Days of SwiftUI

@lorem  

Hello everyone,

I'm a graphic designer learning Swift UI, so I don't have much prior programming knowledge. I've been on the course up to day 25 and am having a hard time in the "Rock - Paper - Scissors" challenge.

First, I'm looking for a way so that when the alert shows a "Restart" button (when the player has reached 10 rounds), the action changes to gameOver to reset the game. Currently, when I've played 10 rounds, the "Restart" button appears but the gameOver action has not been assigned.

Second, I want to convert those integers to a String, because currently I'm using integers to represent "Rock"[0], "Paper"[1] and "Scissors"[2].

Here's the code I'm working on, I know it's a bit messy and any advice is welcome.

Thanks!

import SwiftUI

struct ContentView: View {
    let choices = ["Rock", "Paper", "Scissors"]

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

    @State private var playerScore = 0
    @State private var myCurrentChoice = 0

    @State private var printMessages = ""
    @State private var showMessage = false

    @State private var checkRound = 0

    var body: some View {
        ZStack {
            RadialGradient(stops: [
                .init(color: Color(red: 0.0, green: 0.3, blue: 0.0), location: 0.3),
                .init(color: Color(red: 0.6, green: 0.7, blue: 0.0), location: 0.3),
            ], center: .top, startRadius: 200, endRadius: 700)
                .ignoresSafeArea()

                VStack {
                    Spacer()
                    Spacer()
                    Text("Rock - Paper - Scissors")
                        .font(.title.weight(.bold))
                        .foregroundStyle(.black)
                        .padding(.bottom, 40)
                    //Text("App choice: \(appCurrentChoice)")

                    Text("Your choice: \(myCurrentChoice)")

                    HStack {
                        Picker("Choose your move", selection: $myCurrentChoice) {
                            ForEach(0..<choices.count){
                                Text(self.choices[$0])
                            }
                        }
                        .pickerStyle(.segmented)
                        .padding(.horizontal, 20)

                    }

                    Button(action: {self.math() }) {
                        Text("Check")

                    }
                    .buttonStyle(.bordered)
                    .padding(30)

                    Text("Your score: \(playerScore)")
                        .font(.title2)

                    Spacer()
                    Spacer()
                }
                .background(.regularMaterial)
                .frame(maxWidth: 350, maxHeight: 350)
                .clipShape(RoundedRectangle(cornerRadius: 20))
        }

        .alert(isPresented: $showMessage) {
            Alert(
                title: Text("\(printMessages)"),
                message: Text("App choice: \(appCurrentChoice), Your choice: \(myCurrentChoice)"),
                dismissButton: .default(Text(checkRound < 10 ? "Continue" : "Restart")){
                    self.resetRound()})
        }
    }

    func choice(_ choice: Bool) -> String{
            choice ? "WIN" : "LOSE"
        }

    func resetRound() {
        checkRound += 1
        appCurrentChoice = Int.random(in: 0..<3)
    }

    func gameOver() {
        checkRound = 0
        playerScore = 0
        resetRound()
    }

    func math() {
        if winOrLose == true {
            if myCurrentChoice == 3 && appCurrentChoice == 0 {
                self.playerScore += 1
                printMessages = "You Win!"
            } else if myCurrentChoice > appCurrentChoice {
                self.playerScore += 1
                printMessages = "You Win!"
            } else if myCurrentChoice == appCurrentChoice {
                printMessages = "Draw"
            } else {
                self.playerScore -= 1
                printMessages = "You Lose!"
            }
        } else {
            if appCurrentChoice == 3 && myCurrentChoice == 0 {
                self.playerScore -= 1
                printMessages = "Lose"
            } else if appCurrentChoice < myCurrentChoice {
                self.playerScore += 1
                printMessages = "You Win!"
            } else if appCurrentChoice == myCurrentChoice {
                printMessages = "Draw"
            } else {
                self.playerScore -= 1
                printMessages = "You Lose!"
            }
            self.showMessage = true
        }
    }

}

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

2      

@Bnerd  

First one I would do it like this:

func resetRound() {
if checkRound < 10 {
checkRound += 1
        appCurrentChoice = Int.random(in: 0..<3)
} else {
gameOver() 
    }

Second , did you try to cast them in a String?

3      

@lorem  

Thank you @ioannisfa,

I solved the first problem, didn't expect such a piece of code to solve the problem so quickly.

But I'm still stuck on the second problem, can you give me some suggestions?

2      

@Bnerd  

Ok now I think I got what you meant on your second question before. Although how you did it works, you could just make your myCurrentChoice into an array same to the first array you have

    @State private var myCurrentChoice = ["Rock", "Paper", "Scissors"]

and use these array in your func.

Now I would suggest to have a look on how Genie solved it which is the way Paul suggested and it's much quicker and cleaner. https://www.hackingwithswift.com/forums/100-days-of-swiftui/day-25-rock-paper-scissors/14854/15694

P.S. You will see that I almost did a similar solution to yours in the beginning.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

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.