Mercurial > public > geoquiz
comparison GeoQuiz/Logic/CountryGame.swift @ 8:e09959b4e4a8
fix bugs
author | Dennis C. M. <dennis@denniscm.com> |
---|---|
date | Thu, 06 Oct 2022 11:14:34 +0200 |
parents | d945e52b0704 |
children | 3540c7efc216 |
comparison
equal
deleted
inserted
replaced
7:d945e52b0704 | 8:e09959b4e4a8 |
---|---|
45 @Published var player: AVAudioPlayer? | 45 @Published var player: AVAudioPlayer? |
46 | 46 |
47 init() { | 47 init() { |
48 let data: CountryModel = load("countries.json") | 48 let data: CountryModel = load("countries.json") |
49 self.data = data.countries | 49 self.data = data.countries |
50 askQuestion() | 50 askQuestion { |
51 selector() | |
52 } | |
51 } | 53 } |
52 } | 54 } |
55 | |
56 extension CountryGame { | |
57 func selector() { | |
58 | |
59 // Get random choices | |
60 var userChoices = [String: T]() | |
61 | |
62 while userChoices.count < 2 { | |
63 if let choice = data.randomElement() { | |
64 userChoices[choice.key] = choice.value | |
65 } else { | |
66 fatalError("Couldn't get a random value from data") | |
67 } | |
68 } | |
69 | |
70 // Get question asked (correct answer) | |
71 let correctAnswer = data.first(where: { | |
72 !userChoices.keys.contains($0.key) && // Avoid duplicated countries | |
73 !dataAsked.keys.contains($0.key) // Avoid countries already asked | |
74 }) | |
75 | |
76 // Unwrap optional | |
77 if let correctAnswer = correctAnswer { | |
78 userChoices[correctAnswer.key] = correctAnswer.value | |
79 dataAsked[correctAnswer.key] = correctAnswer.value | |
80 self.correctAnswer = correctAnswer | |
81 } else { | |
82 fatalError("Couldn't unwrap optional value") | |
83 } | |
84 | |
85 self.userChoices = userChoices | |
86 } | |
87 } |