I am new to SwiftUI and I am stuck here.
I have a "choose right flag game". Currently it can show you 3 flags and you have to choose the one that represents country named above. It keeps score of your game and number of rounds you've played( max is 20 ).
When you hit the 20 game sets all numbers to 0 and you start again.
I want to make it pop-up alert message with "Game over. Your result is (bad, average, good ( based on the amount of scores))!" and button "Restart".
I've made alert massage for every round, but simply "copy-paste" with some changes doesn't work.
How can I do it?
import SwiftUI
struct ContentView: View {
@State private var countries = [
"afghanistan",
"albania",.......//here goes list of countries
"zimbabwe"
].shuffled()
@State private var correctAnaswer = Int.random(in: 0...2)
@State private var score = 0
@State private var showingAlert = false
@State private var endGameAlert = false
@State private var alertTitle = ""
@State private var currentRound = 0
@State private var maxRound = 20
var body: some View {
NavigationView {
VStack{
ForEach((0...2), id:\.self) { number in
Image(self.countries[number])
.border(Color.black, width: 1)
.onTapGesture {
self.flagTapped(number)
}
}
Text("Your Score \(score), current round is \(currentRound) of \(maxRound) ")
Spacer()
}
.background(Image("background").resizable().scaledToFill().edgesIgnoringSafeArea(.all).blur(radius: 20))
.navigationBarTitle(Text(countries[correctAnaswer].uppercased()))
.alert(isPresented: $showingAlert) {
Alert(title: Text(alertTitle),
message:Text("Your score is \(score)"),
dismissButton: .default(Text("Continue")){
self.askQuestion()
})
}
}
}
func flagTapped(_ tag: Int){
if currentRound <= 20 {
if tag == correctAnaswer {
score += 1
currentRound += 1
alertTitle = "Correct"
} else {
score -= 1
currentRound += 1
alertTitle = "Wrong"
}
showingAlert = true
}
else {
endGameAlert = true
score = 0
currentRound = 0
}
}
func askQuestion() {
countries.shuffle()
correctAnaswer = Int.random(in: 0...2)
}
}
