Mercurial > public > geoquiz
diff 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 |
line wrap: on
line diff
--- a/GeoQuiz/Logic/CountryGame.swift Tue Oct 04 18:54:24 2022 +0200 +++ b/GeoQuiz/Logic/CountryGame.swift Thu Oct 06 11:14:34 2022 +0200 @@ -47,6 +47,41 @@ init() { let data: CountryModel = load("countries.json") self.data = data.countries - askQuestion() + askQuestion { + selector() + } } } + +extension CountryGame { + func selector() { + + // Get random choices + var userChoices = [String: T]() + + while userChoices.count < 2 { + if let choice = data.randomElement() { + userChoices[choice.key] = choice.value + } else { + fatalError("Couldn't get a random value from data") + } + } + + // Get question asked (correct answer) + let correctAnswer = data.first(where: { + !userChoices.keys.contains($0.key) && // Avoid duplicated countries + !dataAsked.keys.contains($0.key) // Avoid countries already asked + }) + + // Unwrap optional + if let correctAnswer = correctAnswer { + userChoices[correctAnswer.key] = correctAnswer.value + dataAsked[correctAnswer.key] = correctAnswer.value + self.correctAnswer = correctAnswer + } else { + fatalError("Couldn't unwrap optional value") + } + + self.userChoices = userChoices + } +}