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

SOLVED: Can't find mistake in Day 25 Project

Forums > 100 Days of SwiftUI

My project will build rine, but none of my alerts are apearing and I have no clue why. If anyone could help me figrue out what my error is that would be awsome.

Project: RockPaperScissors Project

3      

A quick look at your code I see the problem is that you've got two alerts, one added to a ZStack, and then another one added to the first alert.

That's not going to work for you as it seems like you can only add one alert to a view. https://stackoverflow.com/a/59116329

What you could do is have a more generic alert that has its content customized based on the reason you're showing it.

So instead of two alerts:

        .alert(isPresented: $winLoseAlertShowing) {
            Alert(title: Text(roundResult), message: Text("You've won \(score)"), dismissButton: .default(Text("Play Agian")){
                self.resetRound()
            })
        }
        .alert(isPresented: $resetGameAlertShowing) {
            Alert(title: Text("Game Over!"), message: Text(gameResult), dismissButton: .default(Text("Reset Game")){
                self.roundCount = 0
                self.score = 0
                self.resetRound()
            })
        }

Use a single generic alert that can show whatever you need to, as well as call whatever method you need when showing the alert. An important thing to remember is that you can store references to methods to pass them around and use in different places with different names.

        .alert(isPresented: $showAlert) {
            Alert(
              title: Text(alertTitle),
              message: Text(alertMessage),
              dismissButton: .default(Text(alertDismissText)){
                alertAction()
            })
        }

Add a method that handles all of the reset game responsibilities:

    func resetGame() {
        self.roundCount = 0
        self.score = 0
        self.resetRound()
    }

And change up the clickButton method:

    func clickButton(_ button: Int) {
        switch roundCount {
            case 0..<10:
                if button == correctAnswer {
                    score += 1
                    alertTitle = "You Win!"
                    alertMessage = "You've won \(score)"
                } else {
                    alertTitle = "You Lose!"
                    alertMessage = "You've won \(score)"
                }

                alertDismissText = "Play Again"
                alertAction = resetRound
                showAlert = true
            case 10:
                alertTitle = "Game Over!"
                alertMessage = "??" //  Whatever gameResult was supposed to show
                alertDismissText = "Reset Game"
                alertAction = resetGame
                showAlert = true
            default:
                return
        }
    }

And then make sure you have more state variables to use for the generic alert:

    @State private var showAlert = false
    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var alertDismissText = ""
    @State private var alertAction = {}

6      

The entire ContentView file that worked for me is below:

//
//  ContentView.swift
//  RockPaperScissors
//
//  Created by Benjamin Keys on 4/16/20.
//  Copyright © 2020 Ben Keys. All rights reserved.
//

import SwiftUI

struct formatText: ViewModifier {
    func body(content: Content) -> some View {
        content
            .foregroundColor(Color("Text Color"))
            .font(.largeTitle)
            .multilineTextAlignment(.center)
    }
}

struct ContentView: View {
    let answers = ["Rock", "Paper", "Scisors"]
    @State private var correctAnswer = Int.random(in: 0..<3)

    @State private var roundResult = ""
    @State private var gameResult = ""

    @State private var roundCount = 0
    @State private var score = 0

    @State private var showAlert = false
    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var alertDismissText = ""
    @State private var alertAction = {}

    var body: some View {
        ZStack{
            LinearGradient(gradient: Gradient(colors: [Color("Background Color 1"), Color("Background Color 2")]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)

            VStack{
                Text("Round \(roundCount)/10")
                    .modifier(formatText())
                    .padding(.bottom, 10.0)

                Text("Score: \(score)")
                    .padding(.bottom)
                    .font(.title)
                    .modifier(formatText())
                    .padding(.bottom, 15.0)

                ForEach(0..<answers.count){number in
                    Button(action: {
                        self.clickButton(number)
                    }) {
                        Text(self.answers[number])
                            .fontWeight(.semibold)
                            .padding(.horizontal, 20)
                            .padding(.vertical, 5)
                    }
                    .background(Color("Button Color"))
                    .foregroundColor(Color("Text Color"))
                    .font(.title)
                    .multilineTextAlignment(.center)
                    .clipShape(Capsule())
                    .overlay(Capsule()
                    .stroke(Color("Outline Color"), lineWidth: 3))
                }
                //.padding(.bottom, 20.0)

                Spacer()
            }
        }
            .padding(.top, 50.0)

        .alert(isPresented: $showAlert) {
            Alert(title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text(alertDismissText)){
                self.alertAction()
            })
        }
    }

    func resetGame() {
        self.roundCount = 0
        self.score = 0
        self.resetRound()
    }

    func clickButton(_ button: Int) {
//        roundCount += 1
        switch roundCount {
            case 0..<10:
                if button == correctAnswer {
                    score += 1
                    alertTitle = "You Win!"
                    alertMessage = "You've won \(score)"
                } else {
                    alertTitle = "You Lose!"
                    alertMessage = "You've won \(score)"
                }

                alertDismissText = "Play Again"
                alertAction = resetRound
                showAlert = true
            case 10:
                alertTitle = "Game Over!"
                alertMessage = "??" //  Whatever gameResult was supposed to show
                alertDismissText = "Reset Game"
                alertAction = resetGame
                showAlert = true
            default:
                return
        }
    }

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

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

Happy hacking!

4      

*I am not an expert. I'm a beginner like you, so take EVERYTHING I say, knowing I could be completely off key. I'm a curious beginner like you.

However, I took a look, and you have both alerts attached to the same stack. SwiftUI can only handle one alert to each item. Since you attached two to the same, the second alert will overwrite the first and SwiftUI will never check for the first. I found this out by changing your initial 'show' values to true, one at a time, which will open the alert when starting the app.

Changing the winLoseAlertShowing = true didn't do anything, but changing the resetGameAlertShowing = true showed the alert when opening the app. Then, if you delete the reset game alert, then it'll show the first alert because it's no longer overridden.

I got it to work with both by attaching one alert to the Button() and one to a Text(). A good way to test it would be set one 'show' value to true and the other to false, then switch them checking both times to make sure the correct alerts shows.

Paul explains it better here: https://www.hackingwithswift.com/quick-start/swiftui/how-to-show-multiple-alerts-in-a-single-view

I hope this helps.

3      

@chadchabot I cant find the algorythm in your code the challenge says:

  • Each turn of the game the app will randomly pick either rock, paper, or scissors.
  • Each turn the app will either prompt the player to win or lose.
  • The player must then tap the correct move to win or lose the game.
  • If they are correct they score a point; otherwise they lose a point.
  • The game ends after 10 questions, at which point their score is shown.

Which as I understand means you are given choice to win or loose i.e. if random picks scissors and asks you to loose then you have to choose paper to win.

So here is what I came up with.


import SwiftUI

struct ContentView: View {
    let rockPaperScissors = ["Rock", "Paper", "Scissors"]
    @State private var move = Int.random(in: 0..<3)
    @State private var myChoice = Bool.random()
    @State private var myMove = 0
    @State private var score = 0
    @State private var message = ""
    @State private var showAlert = false
    @State private var rounds = 0

    var body: some View {

        ZStack{
            LinearGradient(gradient: Gradient(colors: [.white,.gray,.white]),
            startPoint: .top, endPoint: .bottom)

            VStack(spacing: 30){
                Text("Rock Scissors Paper")
                    .fontWeight(.heavy)
                    .padding(.top, 20)
                    .padding(.bottom, 50)

                Text("I did my move")
                HStack{
                    Text("You have to")
                    Text("\(choice(myChoice))")
                        .underline()
                        .fontWeight(.heavy)
                }

                Text("Your move?")

                Picker("Choose your move", selection: $myMove){
                    ForEach(0..<rockPaperScissors.count){
                        Text(self.rockPaperScissors[$0])
                    }
                }.pickerStyle(SegmentedPickerStyle())
                    .background(Color.gray)
                    .clipped()
                    .overlay(Capsule().stroke(Color.black, lineWidth: 2))
                    .labelsHidden()
                    .padding()

                Button(action: {
                    self.math()
                }){
                    Text("Check")
                        .fontWeight(.medium)
                        .font(.title)
                }
                .foregroundColor(.black)
                .overlay(Capsule().stroke(Color.black, lineWidth: 1))
                .shadow(color: .accentColor, radius: 20, x: 5, y: 1)

                Spacer()
                Text("Your score: \(score)")
                    .padding(.bottom)

            }.edgesIgnoringSafeArea(.all)
                .padding(.top)

        }

        .alert(isPresented: $showAlert){
            Alert(title: Text("You \(message)"), 
            message: rounds < 10 ? Text("I chose \(rockPaperScissors[move])") : 
            Text("You played 10 rounds").font(.largeTitle), dismissButton:
            .default(Text(rounds < 10 ? "Continue": "Restart")){
                self.startOver()
                })
        }
    }

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

    func startOver(){
        self.move = Int.random(in: 0..<3)
        self.myChoice = Bool.random()
        self.rounds = rounds < 10 ? rounds + 1 : rounds - 1
    }

    func math(){

        if myChoice {

            if myMove == 3 && move == 0{
                self.score += 1
                message = "Win"
            }

            else if myMove > move {

                self.score += 1
                message = "Win"
            }
            else if myMove == move {message = "Try again"}

            else {
                self.score -= 1
                message = "Lost"}
        }
        else {
            if move == 3 && myMove == 0{
                self.score -= 1
                message = "Lost"
            }

            else if myMove < move {
                self.score += 1
                message = "Win"
            }

            else if move == myMove {message = "Try again"}

            else {
                self.score -= 1
                message = "Lost"}
        }

        self.showAlert = true

    }
}

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

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.