BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Guess the Flag day 21 Wrong Flags show up for Question?

Forums > SwiftUI

I have been able to create the functioning game however sometimes It will ask to tap flag for say " Nigeria" but none of the options of flags to choose will include the correct flag. Other times it will have the right flag included.

Thank you in advance.

   

@Bnerd  

Share your code :)

   

//
//  ContentView.swift
//  guessflags
//
//  Created by Josh on 9/24/22.
//

import SwiftUI

struct ContentView: View {

    @State private var showingScore = false
    @State private var scoreTitle = ""
    @State private var userScore = 0
    @State private var testArray = ["Omg","Achmed", "Persey"]
    @State private var gamesPlayed = 0
    @State private var gameIsReset = false

    func resetGame() {
        if gamesPlayed == 8 {
            userScore = 0
            gamesPlayed = 0
            print("resetting game! Eight games played!")
        }
        else {
            print("keep playing")
        }
    }

    func flagTapped (_ number: Int) {
        if number == correctAnswer {
            scoreTitle = "Correct!"
            userScore = userScore + 1
        } else {
            scoreTitle = "Wrong! thats the flag of \(countries[number])"
        }
        showingScore = true
        gamesPlayed = gamesPlayed + 1
        resetGame()

    }

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

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

    @State private  var correctAnswer = Int.random(in: 0...3)
    var body: some View {

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

        ZStack {

            RadialGradient(stops: [
                .init(color: Color(red: 0.1, green: 0.2, blue: 0.45), location: 0.3),
                .init(color: Color(red: 0.76, green: 0.15, blue: 0.26), location: 0.3),
            ], center: .top, startRadius: 200, endRadius: 400)
                .ignoresSafeArea()

            VStack {
                Spacer()
                Text("Guess the flag").font(.largeTitle.weight(.bold)).foregroundColor(.white)

            VStack (spacing: 15){

                Text("Tap the flag of").font(.subheadline.weight(.heavy)).foregroundColor(.secondary)
                Text(countries[correctAnswer]).font(.largeTitle.weight(.semibold))

                //loop to show flags as buttons
                ForEach(0..<3) {number in
                    Button {
                  flagTapped(number)

                    } label: {
                        Image(countries[number])
                            .renderingMode(.original).clipShape(Capsule()).shadow(radius: 5)
                    }
                }
            }.frame(maxWidth: .infinity)
                .padding(.vertical, 20)
                .background(.regularMaterial)
                .clipShape(RoundedRectangle(cornerRadius: 20))
                Spacer()
                Text("Score is \(userScore)").foregroundColor(.white)
                Spacer()
            }
            //this alert runs if state change in showingscore
            .alert(scoreTitle, isPresented: $showingScore) {
                Button("Continue", action: askQuestion)
            } message: {
                Text("Your score is \(userScore) and games played are \(gamesPlayed)")
            }.alert("Reset the game", isPresented: $gameIsReset) {
                Button("Continue", action:resetGame)
            }
    }
}

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

    }
}

}

   

@Bnerd  

Check this,

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

You are asking to ask a question for 4 case , 0,1,2 & 3 But, your Button label is

ForEach(0..<3) {number in

Update the Int.Random to 0..2 and you should be ok.

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

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

Reply to this topic…

You need to create an account or log in to reply.

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.