BLACK FRIDAY: Save 50% 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.

2      

@Bnerd  

Share your code :)

2      

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

    }
}

}

2      

@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.

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.