0
|
1 //
|
6
|
2 // CountryGame.swift
|
0
|
3 // GeoQuiz
|
|
4 //
|
|
5 // Created by Dennis Concepción Martín on 20/9/22.
|
|
6 //
|
|
7
|
|
8 import Foundation
|
5
|
9 import AVFAudio
|
0
|
10
|
6
|
11 class CountryGame: Game, ObservableObject {
|
|
12
|
3
|
13 // Define type of generics
|
6
|
14 typealias T = CountryModel.CountryData
|
|
15
|
|
16 var data: [String: T]
|
|
17 var dataAsked = [String: T]()
|
0
|
18
|
3
|
19 // Data
|
6
|
20 @Published var correctAnswer = (
|
|
21 key: String(),
|
|
22 value: T(flag: String(), currency: String(), population: Int(), capital: String())
|
|
23 )
|
3
|
24
|
|
25 // User
|
6
|
26 @Published var userChoices = [String: T]()
|
0
|
27 @Published var userScore = 0
|
|
28 @Published var userLives = 3
|
6
|
29 @Published var correctAnswers = [String: T]()
|
|
30 @Published var wrongAnswers = [String: T]()
|
3
|
31
|
|
32 // Alerts
|
|
33 @Published var alertTitle = String()
|
|
34 @Published var alertMessage = String()
|
7
|
35 @Published var showingGameOverAlert = false
|
3
|
36 @Published var showingEndGameAlert = false
|
0
|
37 @Published var showingWrongAnswerAlert = false
|
4
|
38 @Published var showingExitGameAlert = false
|
0
|
39
|
3
|
40 // Animations
|
|
41 @Published var scoreScaleAmount = 1.0
|
|
42 @Published var livesScaleAmount = 1.0
|
|
43
|
5
|
44 // Sound effects
|
|
45 @Published var player: AVAudioPlayer?
|
|
46
|
0
|
47 init() {
|
6
|
48 let data: CountryModel = load("countries.json")
|
|
49 self.data = data.countries
|
9
|
50
|
|
51 if let userSettings = UserDefaults.standard.data(forKey: "UserSettings") {
|
|
52 if let decodedUserSettings = try? JSONDecoder().decode(UserSettingsModel.self, from: userSettings) {
|
|
53 userLives = decodedUserSettings.numberOfLives
|
|
54 }
|
|
55 }
|
|
56
|
8
|
57 askQuestion {
|
|
58 selector()
|
|
59 }
|
0
|
60 }
|
|
61 }
|
8
|
62
|
|
63 extension CountryGame {
|
|
64 func selector() {
|
|
65
|
|
66 // Get random choices
|
|
67 var userChoices = [String: T]()
|
|
68
|
|
69 while userChoices.count < 2 {
|
|
70 if let choice = data.randomElement() {
|
|
71 userChoices[choice.key] = choice.value
|
|
72 } else {
|
|
73 fatalError("Couldn't get a random value from data")
|
|
74 }
|
|
75 }
|
|
76
|
|
77 // Get question asked (correct answer)
|
|
78 let correctAnswer = data.first(where: {
|
|
79 !userChoices.keys.contains($0.key) && // Avoid duplicated countries
|
|
80 !dataAsked.keys.contains($0.key) // Avoid countries already asked
|
|
81 })
|
|
82
|
|
83 // Unwrap optional
|
|
84 if let correctAnswer = correctAnswer {
|
|
85 userChoices[correctAnswer.key] = correctAnswer.value
|
|
86 dataAsked[correctAnswer.key] = correctAnswer.value
|
|
87 self.correctAnswer = correctAnswer
|
|
88 } else {
|
|
89 fatalError("Couldn't unwrap optional value")
|
|
90 }
|
|
91
|
|
92 self.userChoices = userChoices
|
|
93 }
|
|
94 }
|