I'm very new with Swift code and I have problems with the challenge: Make the game show only 8 questions, at which point they see a final alert judging their score and can restart the game.
I created a new variable "questionAsked" to count the number of times is asking about the flags. Then I have created a "reset" method along with a variable so that when "questionAsk" reaches 8, the alert to restart the game comes out.
Now I have problems with inserting this method into the code. Could you help me if I'm on track or what do I have to do to make it work?
Thank you very much!
//
// ContentView.swift
// GuessTheFlag
//
// Created by Lucas on 10/11/21.
//
import SwiftUI
struct ContentView: View {
@State private var showingScore = false
@State private var scoreTitle = ""
@State private var score = 0
@State private var endGame = false
@State private var questionAsked = 0
@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)
var body: some View {
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: 800)
.ignoresSafeArea()
VStack {
Spacer()
Text("Guess the Flag")
.font(.largeTitle.bold())
.foregroundColor(.white)
VStack (spacing: 15){
VStack {
Text("Tap the flag of")
.font(.subheadline.weight(.heavy))
.foregroundStyle(.secondary)
Text(countries[correctAnswer])
.font(.largeTitle.weight(.semibold))
}
ForEach(0..<3) { number in
Button {
flagTapped(number)
} label: {
Image(countries[number])
.renderingMode(.original)
.clipShape(Capsule())
.shadow(radius: 10)
}
}
}
.frame(maxWidth: .infinity)
.padding(.vertical, 20)
.background(.ultraThinMaterial)
.clipShape(RoundedRectangle(cornerRadius: 40))
Spacer()
Spacer()
Text("Question: \(questionAsked)")
Text("Score: \(score) ")
.foregroundColor(.white)
.font(.title.bold())
Spacer()
}
.padding()
}
.alert(scoreTitle, isPresented: $showingScore) {
Button("Continue", action: askQuestion)
} message: {
Text("Your score is \(score)")
}
.alert(scoreTitle, isPresented: $endGame) {
Button("Continue", action: askQuestion)
} message: {
Text("Great! Your final score is \(score)")
}
}
func flagTapped(_ number: Int) {
if number == correctAnswer {
scoreTitle = "Correct!"
score += 1
} else {
scoreTitle = "Wrong! That's the flag of \(countries[number])"
}
showingScore = true
}
func askQuestion() {
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
questionAsked += 1
}
func reset() {
if questionAsked == 8 {
endGame = true
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}