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/CountingView.swift

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

135 lines · 4820 bytes

5 symbols in this file
  1//
  2//  CountingView.swift
  3//  DayByDay
  4//
  5
  6import SwiftUI
  7
  8/// Tap each object to count it aloud; the total is shown and said at the end.
  9struct CountingView: View {
 10    @State private var round: CountingRound
 11    @State private var showTotal = false
 12    @State private var celebrating = false
 13    @State private var mascot = MascotState()
 14    @State private var speechToken = 0
 15    /// Bumped when the screen goes away, so pending work says nothing.
 16    @State private var generation = 0
 17    @ScaledMetric(relativeTo: .largeTitle) private var totalHeight = 110
 18    @ScaledMetric(relativeTo: .largeTitle) private var objectHeight = 104
 19
 20    private let columns = [GridItem(.adaptive(minimum: 96, maximum: 140), spacing: 16)]
 21    private let color = Category.numbers.color
 22
 23    init() {
 24        var rng = SystemRandomNumberGenerator()
 25        _round = State(initialValue: CountingRound(using: &rng))
 26    }
 27
 28    var body: some View {
 29        ZStack {
 30            if round.isComplete {
 31                FinishedView {
 32                    var rng = SystemRandomNumberGenerator()
 33                    round = CountingRound(using: &rng)
 34                    ask(after: 0.3)
 35                }
 36            } else {
 37                board
 38            }
 39        }
 40        .onAppear { ask(after: 0) }
 41        .onDisappear {
 42            generation += 1
 43            speechToken += 1
 44            SpeechSynthesizer.shared.stop()
 45        }
 46    }
 47
 48    private var prompt: String { Lines.countPrompt(round.thing) }
 49
 50    private var board: some View {
 51        ScrollView {
 52            VStack(spacing: 28) {
 53                PromptBar(mascot: $mascot, prompt: prompt) { ask(after: 0) }
 54
 55                Text(showTotal ? "\(round.target)" : " ")
 56                    .font(.heading(96, weight: .heavy))
 57                    .foregroundStyle(color)
 58                    .frame(height: totalHeight)
 59                    .accessibilityHidden(!showTotal)
 60
 61                LazyVGrid(columns: columns, spacing: 16) {
 62                    ForEach(0..<round.target, id: \.self) { i in
 63                        Button { tap(i) } label: { object(i) }
 64                            .buttonStyle(.plain)
 65                            .accessibilityLabel(round.thing.singular)
 66                            .accessibilityValue(round.counted.firstIndex(of: i).map { "\($0 + 1)" } ?? "")
 67                    }
 68                }
 69            }
 70            .padding(24)
 71        }
 72        .overlay { CelebrationOverlay(isActive: celebrating) }
 73    }
 74
 75    /// Uncounted: the symbol in the numbers color. Counted: white symbol and
 76    /// its count on a numbers-colored tile.
 77    private func object(_ i: Int) -> some View {
 78        let order = round.counted.firstIndex(of: i).map { $0 + 1 }
 79        let shape = RoundedRectangle(cornerRadius: 24, style: .continuous)
 80        return ZStack {
 81            shape.fill(order == nil ? Color.clear : color)
 82            if let order {
 83                VStack(spacing: 2) {
 84                    Image(systemName: round.thing.symbol).font(.system(size: 30))
 85                    Text("\(order)").font(.heading(34, weight: .heavy))
 86                }
 87                .foregroundStyle(.white)
 88            } else {
 89                Image(systemName: round.thing.symbol)
 90                    .font(.system(size: 60))
 91                    .foregroundStyle(color)
 92            }
 93        }
 94        .frame(height: objectHeight)
 95        .contentShape(shape)
 96    }
 97
 98    private func tap(_ i: Int) {
 99        guard let count = round.tap(i) else { return }
100        guard round.isSetDone else {
101            say(LearnNumber(rawValue: count)!.name, after: 0)
102            return
103        }
104        let summary = round.summary()
105        SoundEngine.shared.play(.success)
106        mascot.handle(.correct)
107        showTotal = true
108        celebrating = true
109        say(summary, after: RoundStyle.speechDelay)
110        let words = summary.split(separator: " ").count
111        let gen = generation
112        DispatchQueue.main.asyncAfter(deadline: .now() + 1.5 + 0.45 * Double(words)) {
113            guard gen == generation else { return }
114            celebrating = false
115            showTotal = false
116            var rng = SystemRandomNumberGenerator()
117            round.nextSet(using: &rng)
118            if !round.isComplete { ask(after: 0) }
119        }
120    }
121
122    /// Says the prompt, with the mascot asking.
123    private func ask(after delay: TimeInterval) {
124        mascot.handle(.prompt(prompt, after: delay))
125        say(prompt, after: delay)
126    }
127
128    private func say(_ text: String, after delay: TimeInterval) {
129        speechToken += 1
130        let token = speechToken, gen = generation
131        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
132            if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) }
133        }
134    }
135}