DayByDay/Quiz/Counting.swift
68 lines · 2385 bytes
1//
2// Counting.swift
3// DayByDay
4//
5
6/// "Count with me": five sets of 1 to 10 objects; the child taps each once.
7nonisolated struct CountingRound {
8 static let length = 5
9
10 struct Thing: Equatable {
11 let symbol: String
12 let singular: String
13 let plural: String
14 }
15
16 static let things = [
17 Thing(symbol: "star.fill", singular: "star", plural: "stars"),
18 Thing(symbol: "heart.fill", singular: "heart", plural: "hearts"),
19 Thing(symbol: "leaf.fill", singular: "leaf", plural: "leaves"),
20 Thing(symbol: "moon.fill", singular: "moon", plural: "moons"),
21 Thing(symbol: "fish.fill", singular: "fish", plural: "fish"),
22 ]
23
24 private(set) var target: Int
25 private(set) var thing: Thing
26 /// Object indices in the order they were tapped.
27 private(set) var counted: [Int] = []
28 private(set) var setsDone = 0
29
30 var isSetDone: Bool { counted.count == target }
31 var isComplete: Bool { setsDone == Self.length }
32
33 init(using rng: inout some RandomNumberGenerator) {
34 self.init(target: Int.random(in: 1...10, using: &rng),
35 thing: Self.things.randomElement(using: &rng)!, using: &rng)
36 }
37
38 init(target: Int, thing: Thing, using rng: inout some RandomNumberGenerator) {
39 precondition((1...10).contains(target))
40 self.target = target
41 self.thing = thing
42 }
43
44 /// The new count, or nil if `index` is not an uncounted object.
45 mutating func tap(_ index: Int) -> Int? {
46 guard !isSetDone, (0..<target).contains(index), !counted.contains(index) else { return nil }
47 counted.append(index)
48 return counted.count
49 }
50
51 /// Starts the next set once this one is counted.
52 mutating func nextSet(using rng: inout some RandomNumberGenerator) {
53 guard isSetDone, !isComplete else { return }
54 setsDone += 1
55 guard !isComplete else { return }
56 let previous = target
57 target = (1...10).filter { $0 != previous }.randomElement(using: &rng)!
58 thing = Self.things.filter { $0 != thing }.randomElement(using: &rng)!
59 counted = []
60 }
61
62 func summary() -> String {
63 let word = LearnNumber(rawValue: target)!.name
64 return target == 1
65 ? "\(word)! There is one \(thing.singular)."
66 : "\(word)! There are \(word.lowercased()) \(thing.plural)."
67 }
68}