0
|
1 //
|
6
|
2 // CityGame.swift
|
0
|
3 // GeoQuiz
|
|
4 //
|
6
|
5 // Created by Dennis Concepción Martín on 29/9/22.
|
0
|
6 //
|
|
7
|
|
8 import Foundation
|
5
|
9 import AVFAudio
|
7
|
10 import SwiftUI
|
0
|
11
|
6
|
12 class CityGame: Game, ObservableObject {
|
|
13
|
3
|
14 // Define type of generics
|
6
|
15 typealias T = CityModel.CityData
|
|
16
|
|
17 var data: [String: T]
|
|
18 var dataAsked = [String: T]()
|
0
|
19
|
8
|
20 // Data
|
|
21 @Published var correctAnswer = (
|
|
22 key: String(),
|
|
23 value: T(country: String(), lat: Double(), lon: Double())
|
|
24 )
|
3
|
25
|
|
26 // User
|
6
|
27 @Published var userChoices = [String: T]()
|
0
|
28 @Published var userScore = 0
|
|
29 @Published var userLives = 3
|
6
|
30 @Published var correctAnswers = [String: T]()
|
|
31 @Published var wrongAnswers = [String: T]()
|
3
|
32
|
|
33 // Alerts
|
|
34 @Published var alertTitle = String()
|
|
35 @Published var alertMessage = String()
|
7
|
36 @Published var showingGameOverAlert = false
|
3
|
37 @Published var showingEndGameAlert = false
|
0
|
38 @Published var showingWrongAnswerAlert = false
|
4
|
39 @Published var showingExitGameAlert = false
|
0
|
40
|
3
|
41 // Animations
|
|
42 @Published var scoreScaleAmount = 1.0
|
|
43 @Published var livesScaleAmount = 1.0
|
|
44
|
5
|
45 // Sound effects
|
|
46 @Published var player: AVAudioPlayer?
|
|
47
|
0
|
48 init() {
|
6
|
49 let data: CityModel = load("cities.json")
|
|
50 self.data = data.cities
|
8
|
51 askQuestion {
|
|
52 selector()
|
|
53 }
|
0
|
54 }
|
|
55 }
|
7
|
56
|
|
57 extension CityGame {
|
8
|
58 func selector() {
|
|
59
|
|
60 // Get random choices
|
|
61 var userChoices = [String: T]()
|
|
62
|
|
63 while userChoices.count < 2 {
|
|
64 if let choice = data.randomElement() {
|
|
65 let userChoicesCountry = userChoices.map { $0.value.country }
|
|
66
|
|
67 if !userChoicesCountry.contains(choice.value.country) {
|
|
68 userChoices[choice.key] = choice.value
|
|
69 }
|
|
70 } else {
|
|
71 fatalError("Couldn't get a random value from data")
|
7
|
72 }
|
|
73 }
|
8
|
74
|
|
75 // Get question asked (correct answer)
|
|
76 let userChoicesCountry = userChoices.map { $0.value.country }
|
|
77 let correctAnswer = data.first(where: {
|
|
78 !userChoices.keys.contains($0.key) && // Avoid duplicated cities
|
|
79 !dataAsked.keys.contains($0.key) && // Avoid cities already asked
|
|
80 !userChoicesCountry.contains($0.value.country) // Avoid duplicated country names in userChoices
|
|
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
|
7
|
93 }
|
|
94 }
|
|
95
|