krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Quiz/SortRound.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDay/Quiz/SortRound.swift history · blame · raw

63 lines · 2274 bytes

5 symbols in this file
 1//
 2//  SortRound.swift
 3//  DayByDay
 4//
 5
 6/// Six foods, one at a time, into a fruit bin or a vegetable bin.
 7nonisolated struct SortRound {
 8    let foods: [LearnFood]
 9    private(set) var fruitBin: [LearnFood] = []
10    private(set) var vegetableBin: [LearnFood] = []
11    private(set) var isShowingCorrection = false
12
13    init(using rng: inout some RandomNumberGenerator) {
14        let fruit = LearnFood.allCases.filter(\.isFruit).shuffled(using: &rng).prefix(3)
15        let vegetables = LearnFood.allCases.filter { !$0.isFruit }.shuffled(using: &rng).prefix(3)
16        foods = Array(fruit + vegetables).shuffled(using: &rng)
17    }
18
19    private var sorted: Int { fruitBin.count + vegetableBin.count }
20    var current: LearnFood? { sorted < foods.count ? foods[sorted] : nil }
21    var isDone: Bool { current == nil }
22
23    var prompt: String? { current.map(Self.question) }
24
25    mutating func place(isFruit: Bool) -> AnswerOutcome {
26        guard let food = current, !isShowingCorrection else { return .ignored }
27        guard isFruit == food.isFruit else {
28            isShowingCorrection = true
29            return .incorrect(correctName: food.name)
30        }
31        if isFruit { fruitBin.append(food) } else { vegetableBin.append(food) }
32        return .correct
33    }
34
35    mutating func resume() {
36        isShowingCorrection = false
37    }
38
39    func correction() -> String {
40        current.map { "\(Self.fact(for: $0)) Try again!" } ?? ""
41    }
42
43    static func question(for food: LearnFood) -> String {
44        let name = food.name.lowercased()
45        switch food {
46        case .grapes:          return "Are grapes a fruit or a vegetable?"
47        case .corn, .broccoli: return "Is \(name) a fruit or a vegetable?"
48        default:               return "Is the \(name) a fruit or a vegetable?"
49        }
50    }
51
52    static func fact(for food: LearnFood) -> String {
53        let name = food.name.lowercased()
54        let kind = food.isFruit ? "fruit" : "vegetable"
55        switch food {
56        case .grapes:          return "Grapes are a \(kind)."
57        case .corn, .broccoli: return "\(food.name) is a \(kind)."
58        default:
59            let article = "aeiou".contains(name.first!) ? "An" : "A"
60            return "\(article) \(name) is a \(kind)."
61        }
62    }
63}