import SwiftUI
struct ContentView: View {
@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Spain", "UK", "Ukraine", "US"].shuffled()
@State private var correctAnswer = Int.random(in: 0...2)
@State private var showingScore = false
@State private var gameEnd = false
@State private var scoreTitle = ""
@State private var endTitle = ""
@State private var questionCount = 0
@State private var keepScore = 0
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: 700)
.ignoresSafeArea()
VStack {
Spacer()
Text("Guess the Flag")
.font(.largeTitle.bold())
.foregroundStyle(.white)
VStack(spacing: 15) {
VStack {
Text("Tap the flag of")
.foregroundStyle(.secondary)
.font(.subheadline.weight(.heavy))
Text(countries[correctAnswer])
.font(.largeTitle.weight(.semibold))
}
ForEach(0..<3) { number in
Button {
flagTapped(number)
}label: {
Image(countries[number])
.clipShape(.capsule)
.shadow(radius: 5)
}
}
}
.frame(maxWidth: .infinity)
.padding(.vertical, 20)
.background(.regularMaterial)
.clipShape(.rect(cornerRadius: 20))
Spacer()
Spacer()
Text("Score: \(keepScore)")
.foregroundStyle(.white)
.font(.title.bold())
Spacer()
Button {
reset()
}
label: {
Text("Reset")
.font(.system(size: 22))
.foregroundColor(.white)
.padding()
.background(Color(red: 0.1, green: 0.2, blue: 0.45))
.clipShape(Capsule())
}
}
.padding()
}
.alert(scoreTitle, isPresented: $showingScore) {
Button("continue", action: askQuestion)
} message: {
Text("\(keepScore) out of \(questionCount)!")
}
.alert(endTitle, isPresented: $gameEnd) {
Button("Reset", action: reset)
}
}
func reset() {
questionCount = 0
keepScore = 0
}
func flagTapped(_ number: Int) {
questionCount += 1
if number == correctAnswer {
scoreTitle = "Correct"
keepScore += 1
} else {
scoreTitle = "Wrong, that's the flag of \(countries[number])"
}
if questionCount <= 7 {
showingScore = true
} else if questionCount == 8 {
gameEnd = true
endTitle = "Game Over! Your score is \(keepScore) out of 8!"
}
}
func askQuestion() {
countries.shuffle()
correctAnswer = Int.random(in: 0...2)
}
}
#Preview {
ContentView()
}