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

SOLVED: Guess the Flag Challenge

Forums > 100 Days of SwiftUI

Hey is anyone willing to share how they solved the challenges for this? I've hit a brick wall :-(

4      

glad that im not the only one , im facing the brick wall every fu*** day, and if you resolve this challenge please tell me :)

3      

Are you having trouble with all 3 challenges? Future projects have you go back and add more and more stuff to this program, so I had to massage my code a bit... but for the first challenge, I believe you just need to add a score property and then increment/decrement it depending on the answer in your function.

//place this with your other variables in ContentView
@State private var userScore = 0

//modify your flagTapped function to include incrementing/decrementing the score
func flagTapped(_ number: Int) {
        if number == correctAnswer {
            scoreTitle = "Correct!"
            userScore += 100
            alertMessage = "Your score went up 100 points."
        } else {
            scoreTitle = "Wrong!"
            userScore -= 100
            alertMessage = "That's flag of \(countries[number])"
        }
        showingScore = true
    }

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

no i finnaly succeed, but i have a bug that i cant fixed. when i click on the flag (correct anwswer), on the next round the opacity of the button i clicked previously is very low and the 2 others button is normal. but when i click on any wrong answer, i dont have this problem. this is my code :

import SwiftUI

struct ContentView: View {

    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy","Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()

    @State private var correctAnswer = Int.random(in: 0...2)

    @State private var showingScore = false
    @State private var scoreTitle = ""
    @State var score = 0
    @State var actualCountry = ""

    @State private var animationAmount = 0.0
    @State private var animation = false

    var body: some View {

        ZStack {

            LinearGradient(gradient: Gradient(colors: [.blue, .black]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)

            VStack(spacing: 30){
                VStack {
                  Text("Tap the flag of")
                    .foregroundColor(.white)
                    Text(countries[correctAnswer])
                        .foregroundColor(.white)
                        .font(.title)
                        .fontWeight(.black)
                }

                ForEach(0 ..< 3) { number in
                    Button(action: {

                        withAnimation(.easeOut(duration: 0.5)) {

                             self.animation = true
                       }
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3){
                                                   self.flagTapped(number)

                                               }

                    }) {
                        Image(self.countries[number])
                            .renderingMode(.original)
                            .clipShape(Capsule())
                            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
                            .shadow(color: .black, radius: 2)

                            .rotation3DEffect(.degrees(number == self.correctAnswer && self.animation ? 360 : 0.0), axis: (x: 0, y: 1, z: 0))
                            .opacity(number != self.correctAnswer && self.animation ? 1 : 1)

                    }

                }

                Spacer()
                Text("score: \(score)")
                .foregroundColor(.white)
                .font(.largeTitle)
                Text("no!! it was \(actualCountry)")
                    .foregroundColor(.white)
                    .font(.largeTitle)

                Spacer()

            }
        }

        .alert(isPresented: $showingScore){
            Alert(title: Text(scoreTitle), message: Text("Your score is \(score) "), dismissButton: .default(Text("Continue")) {
                self.askQuestion()

                })
        }
    }

    func flagTapped(_ number: Int){
        if number == correctAnswer {
          scoreTitle = "Correct"
          score += 10

        }else{
          scoreTitle = "Wrong! this was \(countries[number])"
          score -= 10
          actualCountry = countries[number]

        }
        showingScore = true
    }

    func askQuestion(){
        animation = false
        countries.shuffle()
        correctAnswer = Int.random(in: 0...2)

    }

}

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

4      

maybe there is a better way to make this line :

 .rotation3DEffect(.degrees(number == self.correctAnswer && self.animation ? 360 : 0.0), axis: (x: 0, y: 1, z: 0))
                            .opacity(number != self.correctAnswer && self.animation ? 1 : 1)

3      


import SwiftUI

struct ContentView: View {
    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()

    @State private var corrrectAnswer = Int.random(in: 0...2)

    @State private var showingScore = false
    @State private var scoreTitle = ""
    @State private var usersScore = 0

    var body: some View {
        ZStack{
            LinearGradient(gradient: Gradient(colors: [.blue,.black]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
            VStack(spacing:30){
                VStack{
                    Text("Tap the flag of")
                        .foregroundColor(.white)
                    Text(countries[corrrectAnswer])
                        .foregroundColor(.white)
                        .font(.largeTitle)
                        .fontWeight(.black)
                }
                VStack(spacing:20){
                    ForEach(0..<3){ number in
                        Button(action: {
                            self.flagTapped(number)
                        }){
                            Image(self.countries[number])
                                .renderingMode(.original)
                                .clipShape(Capsule())
                                .overlay(Capsule().stroke(Color.black,lineWidth: 1))
                                .shadow(color: .black, radius: 2)
                        }
                    }
                    VStack{
                        Text("Score:  \(usersScore)")
                            .foregroundColor(.white)
                            .fontWeight(.black)
                            .font(.subheadline)

                    }
                    Spacer()
                }
            }
        }
        .alert(isPresented: $showingScore){
            Alert(title: Text(scoreTitle), message: Text("Your score is \(usersScore)"), dismissButton: .default(Text("Continue")){
                self.askQuestion()})
        }
    }

    func flagTapped(_ number: Int){
        if number == corrrectAnswer{
            scoreTitle = "Right"
            usersScore += 1
        }
        else {
            scoreTitle = "Wrong!\n Thats the flag of \(countries[corrrectAnswer])"
        }
        showingScore = true
    }

    func askQuestion(){
        countries.shuffle()
        corrrectAnswer = Int.random(in: 0...2)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

thank you it was such a simple thing. I couldnt get the number to add up but it was just +=.

im loving this swiftui though.

3      

cant believe that threw me for so long. once i had that the rest of the tasks were simple. you have no idea how complicated I was trying to make it, trying to create a function to add up the numbers

3      

To make the opacity return to normal after the correct flag is tapped, I changed the code to:

.opacity(number == self.correctAnswer && self.animation ? 0 : 1)

Seems to work.

3      

Solved it and made it pretty


import SwiftUI

struct ContentView: View {

    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()

    @State private var correctAnswer = Int.random(in: 0...2)    
    @State private var showingScore = false
    @State private var scoreTitle = ""

    @State private var userScore = 0
    //Property that stores the user score

    var body: some View {

        ZStack {
            LinearGradient(gradient: Gradient(colors: [.black, .black]), startPoint: .top, endPoint: .bottom) .edgesIgnoringSafeArea(.all)

            VStack(spacing: 30) {
                VStack {
                    Text("Tap the flag of")
                        .foregroundColor(.white)
                        .padding(.top, 120)
                    Text(countries[correctAnswer])
                        .foregroundColor(.white)
                        .font(.largeTitle)
                        .fontWeight(.black)
                }

                ForEach(0 ..< 3) { number in Button(action: {
                    self.flagTapped(number)
                }) {
                    Image(self.countries[number])
                        .renderingMode(.original)
                    // tells swift UI to render the original image pixels rather than coloring them as a button
                    .clipShape(Capsule())
                        .overlay(Capsule().stroke(Color.white, lineWidth: 2))
                        .shadow(color: .black, radius: 2)
                    }

                }

                VStack (spacing: 10) {
                    Text("Your Score is:")
                    .foregroundColor(.white)
                        .padding(.top, 20)
                    Text("\(userScore)")
                        .foregroundColor(.white)
                        .fontWeight(.black)
                        .font(.largeTitle)

                }

                Spacer()
            }
        }

        .alert(isPresented: $showingScore) {
            Alert(title: Text(scoreTitle), message: Text("Your score is \(userScore)"), dismissButton: .default(Text("Continue")) {
                self.askQuestion()
                })
        }
    }

    func flagTapped(_ number: Int) {
        if number == correctAnswer {
            scoreTitle = "Yes!"
            userScore += 1
        } else {
            scoreTitle = "Nope! \n That's the flag of \(countries[number])"
        }
        showingScore = true

    }

    //ask Question method resets the game by shuffling up the countires and picking up a new correct answer

    func askQuestion() {
        countries.shuffle()
        correctAnswer = Int.random(in: 0...2)
    }
}

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

See demo here: https://twitter.com/Sunbird3000/status/1293949093513854976?s=20

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.