DayByDay/Quiz/RoundView.swift
189 lines · 6429 bytes
8 symbols in this file
1//
2// RoundView.swift
3// DayByDay
4//
5
6import SwiftUI
7
8enum RoundStyle {
9 static let playAgainFill = Color(red: 0.18, green: 0.56, blue: 0.28)
10 /// Gap between a feedback sound and the speech that follows it.
11 static let speechDelay = 0.25
12}
13
14/// Runs a round of questions. The caller supplies how each choice looks.
15struct RoundView<Choice: View>: View {
16 private let source: any QuestionSource
17 private let game: Game
18 private let choice: (QuizItem) -> Choice
19
20 @Environment(ProfileSession.self) private var session
21 /// Choices get wider as the text on them grows.
22 @ScaledMetric(relativeTo: .title2) private var choiceWidth: CGFloat = 150
23 @State private var round: Round
24 @State private var praise = PraisePhrases()
25 @State private var celebrating = false
26 @State private var dimmed: QuizItem?
27 @State private var mascot = MascotState()
28 /// Bumped whenever something new is said, so a delayed prompt that has
29 /// been overtaken stays quiet.
30 @State private var speechToken = 0
31
32 private var columns: [GridItem] {
33 [GridItem(.adaptive(minimum: choiceWidth, maximum: max(choiceWidth, 320)), spacing: 20)]
34 }
35
36 init(source: any QuestionSource, game: Game, @ViewBuilder choice: @escaping (QuizItem) -> Choice) {
37 self.source = source
38 self.game = game
39 self.choice = choice
40 _round = State(initialValue: Round(source: source))
41 }
42
43 var body: some View {
44 Group {
45 if round.isComplete {
46 finished
47 } else {
48 question
49 }
50 }
51 .onAppear { speakPrompt() }
52 .onDisappear {
53 speechToken += 1
54 SpeechSynthesizer.shared.stop()
55 }
56 .onChange(of: round.current) { speakPrompt() }
57 }
58
59 private var question: some View {
60 ScrollView {
61 VStack(spacing: 28) {
62 PromptBar(mascot: $mascot, prompt: round.current.prompt, action: speakPrompt)
63
64 ProgressDots(filled: round.correctCount, total: Round.length)
65
66 if !round.current.shown.isEmpty {
67 ShownItems(items: round.current.shown)
68 }
69
70 LazyVGrid(columns: columns, spacing: 24) {
71 ForEach(round.current.choices) { item in
72 Button { tap(item) } label: {
73 choice(item)
74 .frame(minHeight: 160)
75 .opacity(dimmed == item ? 0.4 : 1)
76 }
77 .buttonStyle(.plain)
78 .accessibilityLabel(item.name)
79 }
80 }
81 }
82 .padding(32)
83 }
84 .overlay { CelebrationOverlay(isActive: celebrating) }
85 }
86
87 private var finished: some View {
88 FinishedView {
89 round = Round(source: source, after: round.current.answer)
90 }
91 }
92
93 private func tap(_ item: QuizItem) {
94 let outcome = round.answer(item)
95 guard outcome != .ignored else { return }
96 if let profile = session.current {
97 session.store.record(round.current.answer, chosen: item, game: game,
98 correct: outcome == .correct, for: profile)
99 }
100 switch outcome {
101 case .correct:
102 SoundEngine.shared.play(.success)
103 mascot.handle(.correct)
104 var rng = SystemRandomNumberGenerator()
105 say(praise.next(using: &rng), after: RoundStyle.speechDelay)
106 celebrating = true
107 DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
108 celebrating = false
109 round.advance()
110 }
111 case .incorrect:
112 SoundEngine.shared.play(.gentleMiss)
113 mascot.handle(.wrong)
114 say(round.current.correction(for: item), after: RoundStyle.speechDelay)
115 withAnimation(.easeOut(duration: 0.2)) { dimmed = item }
116 DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
117 withAnimation { if dimmed == item { dimmed = nil } }
118 round.resume()
119 }
120 case .ignored:
121 break
122 }
123 }
124
125 /// Plays the question's sound cue, if any, then speaks the prompt.
126 private func speakPrompt() {
127 guard !round.isFinished, !round.isAwaitingNext else { return }
128 if let sound = round.current.sound {
129 speechToken += 1
130 SpeechSynthesizer.shared.stop()
131 SoundEngine.shared.play(sound)
132 let delay = SoundEngine.shared.remaining(sound) + 0.2
133 mascot.handle(.prompt(round.current.prompt, after: delay))
134 say(round.current.prompt, after: delay)
135 } else {
136 mascot.handle(.prompt(round.current.prompt))
137 say(round.current.prompt, after: 0)
138 }
139 }
140
141 private func say(_ text: String, after delay: TimeInterval) {
142 speechToken += 1
143 let token = speechToken
144 DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
145 if token == speechToken { SpeechSynthesizer.shared.speak(text) }
146 }
147 }
148}
149
150/// The items a question is about, above the choices: "red + yellow = ?".
151private struct ShownItems: View {
152 let items: [QuizItem]
153
154 var body: some View {
155 HStack(spacing: 12) {
156 ForEach(Array(items.enumerated()), id: \.offset) { i, item in
157 if i > 0 { sign("+") }
158 ChoiceTile(item: item).frame(width: 90, height: 90)
159 }
160 if items.count > 1 { sign("= ?") }
161 }
162 .accessibilityElement(children: .ignore)
163 .accessibilityLabel(items.map(\.name).joined(separator: " and "))
164 }
165
166 private func sign(_ text: String) -> some View {
167 Text(text)
168 .font(.heading(36, weight: .heavy))
169 .lineLimit(1)
170 .fixedSize()
171 }
172}
173
174/// Filled dots showing how many correct answers are done in this round.
175private struct ProgressDots: View {
176 let filled: Int
177 let total: Int
178
179 var body: some View {
180 HStack(spacing: 12) {
181 ForEach(0..<total, id: \.self) { i in
182 Circle()
183 .fill(i < filled ? Color.yellow : Color(.systemGray5))
184 .frame(width: 22, height: 22)
185 }
186 }
187 .accessibilityHidden(true)
188 }
189}