comparison GeoQuiz/Logic/GuessTheFlag.swift @ 0:413e2d21333e

first commit
author Dennis C. M. <dennis@denniscm.com>
date Tue, 20 Sep 2022 08:13:26 +0200
parents
children 4dbe0cd9dadc
comparison
equal deleted inserted replaced
-1:000000000000 0:413e2d21333e
1 //
2 // GuessTheFlag.swift
3 // GeoQuiz
4 //
5 // Created by Dennis Concepción Martín on 20/9/22.
6 //
7
8 import Foundation
9
10 class GuessTheFlag: Game, ObservableObject {
11 let countries: [String: String]
12 var countriesAsked = [String: String]()
13
14 @Published var userScore = 0
15 @Published var userLives = 3
16 @Published var questionCounter = 0
17 @Published var alertTitle = ""
18 @Published var alertMessage = ""
19 @Published var showingBuyLivesView = false
20 @Published var showingNoLivesAlert = false
21 @Published var showingWrongAnswerAlert = false
22 @Published var showingEndGameAlert = false
23
24 @Published var userChoices = [String: String]()
25 @Published var countryNameAsked = ""
26
27 init() {
28 let flags: CountryFlags = load("CountryFlags.json")
29 self.countries = flags.countries
30 askQuestion()
31 }
32
33 func askQuestion() {
34 guard questionCounter < countries.count else {
35 self.alertTitle = "Amazing!"
36 self.alertMessage = "You've completed the game."
37 self.showingEndGameAlert = true
38
39 return
40 }
41
42 var userChoices = [String: String]()
43
44 while userChoices.count < 2 {
45 if let country = countries.randomElement() {
46 userChoices[country.key] = country.value
47 } else {
48 fatalError("Couldn't get a random country")
49 }
50 }
51
52 let countryAsked = countries.first(where: {
53 !userChoices.keys.contains($0.key) &&
54 !countriesAsked.keys.contains($0.key)
55 })
56
57 if let countryAsked = countryAsked {
58 userChoices[countryAsked.key] = countryAsked.value
59 self.countriesAsked[countryAsked.key] = countryAsked.value
60 self.countryNameAsked = countryAsked.key
61 } else {
62 fatalError("Couldn't get countryAsked")
63 }
64
65 self.userChoices = userChoices
66 self.questionCounter += 1
67 }
68
69 func answered(userChoice userFlagSymbolGuess: String) {
70 guard let correctFlagSymbolAnswer = countries[countryNameAsked] else {
71 fatalError("Couln't find \(countryNameAsked) in countries dictionary")
72 }
73
74 guard userLives > 0 else {
75 self.alertTitle = "Not enough lives!"
76 self.alertMessage = "Please buy more lives to keep playing"
77 self.showingNoLivesAlert = true
78
79 return
80 }
81
82 if correctFlagSymbolAnswer == userFlagSymbolGuess {
83 hapticSuccess()
84 self.userScore += 1
85 askQuestion()
86 } else {
87 hapticError()
88 self.userLives -= 1
89 self.alertTitle = "Wrong!"
90 self.alertMessage = "That's not the flag of \(countryNameAsked). You have \(userLives) lives left"
91 self.showingWrongAnswerAlert = true
92 }
93 }
94 }