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

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

299 lines · 11991 bytes

11 symbols in this file
  1//
  2//  SequencePuzzleView.swift
  3//  DayByDay
  4//
  5
  6import SwiftUI
  7
  8/// Week train and yesterday/today/tomorrow: slots on top, cards below.
  9/// Tap a card to place it, or drag it anywhere onto the slots.
 10struct SequencePuzzleView: View {
 11    let game: Game
 12    let make: () -> SequencePuzzle
 13
 14    @Environment(ProfileSession.self) private var session
 15    /// Cards and train cars grow with the text on the labeled cards.
 16    @ScaledMetric(relativeTo: .title2) private var card: CGFloat = 140
 17    @State private var puzzle: SequencePuzzle
 18    @State private var praise = PraisePhrases()
 19    @State private var dimmed: QuizItem?
 20    @State private var mascot = MascotState()
 21    @State private var celebrating = false
 22    @State private var finished = false
 23    @State private var speechToken = 0
 24    /// Bumped when the screen goes away, so pending work does nothing.
 25    @State private var generation = 0
 26    /// Counts finished games, so a timer from an earlier game is ignored.
 27    @State private var solves = 0
 28
 29    private var columns: [GridItem] { [GridItem(.adaptive(minimum: card, maximum: max(card, 220)), spacing: 16)] }
 30
 31    init(game: Game, make: @escaping () -> SequencePuzzle) {
 32        self.game = game
 33        self.make = make
 34        _puzzle = State(initialValue: make())
 35    }
 36
 37    var body: some View {
 38        ZStack {
 39            if finished {
 40                FinishedView {
 41                    puzzle = make()
 42                    finished = false
 43                    ask(after: 0.3)
 44                }
 45            } else {
 46                board
 47            }
 48        }
 49        .onAppear { ask(after: 0) }
 50        .onDisappear {
 51            generation += 1
 52            speechToken += 1
 53            SpeechSynthesizer.shared.stop()
 54        }
 55    }
 56
 57    private var board: some View {
 58        ScrollView {
 59            VStack(spacing: 28) {
 60                PromptBar(mascot: $mascot, prompt: puzzle.current?.prompt) { ask(after: 0) }
 61
 62                slots
 63                    .dropDestination(for: String.self) { ids, _ in
 64                        guard let id = ids.first, let item = puzzle.pool.first(where: { $0.id == id }) else { return false }
 65                        place(item)
 66                        return true
 67                    }
 68
 69                LazyVGrid(columns: columns, spacing: 16) {
 70                    // Placed cards keep their spot, hidden, so the rest don't move.
 71                    ForEach(puzzle.pool) { item in
 72                        let isPlaced = puzzle.placed.contains(item)
 73                        Button { place(item) } label: {
 74                            ChoiceTile(item: item)
 75                                .frame(height: card)
 76                                .opacity(isPlaced ? 0 : dimmed == item ? 0.4 : 1)
 77                        }
 78                        .buttonStyle(.plain)
 79                        .disabled(isPlaced)
 80                        .accessibilityHidden(isPlaced)
 81                        .draggable(item.id) {
 82                            ChoiceTile(item: item).frame(width: card, height: card)
 83                        }
 84                        .accessibilityLabel(item.name)
 85                    }
 86                }
 87            }
 88            .padding(24)
 89        }
 90        .overlay { CelebrationOverlay(isActive: celebrating) }
 91    }
 92
 93    @ViewBuilder
 94    private var slots: some View {
 95        if let labels = puzzle.slotLabels {
 96            // Stacked when the labels no longer fit side by side.
 97            ViewThatFits(in: .horizontal) {
 98                HStack(alignment: .top, spacing: 12) { labeledSlots(labels) }
 99                VStack(spacing: 16) { labeledSlots(labels) }
100            }
101        } else {
102            ScrollViewReader { proxy in
103                ScrollView(.horizontal, showsIndicators: false) {
104                    HStack(alignment: .bottom, spacing: 6) {
105                        TrainEngine()
106                            .frame(width: card, height: card * 15 / 14)
107                        ForEach(puzzle.steps.indices, id: \.self) { i in
108                            TrainCar { slot(i) }
109                                .frame(width: card, height: card * 15 / 14)
110                                .id(i)
111                        }
112                    }
113                    .padding(.vertical, 4)
114                }
115                // Run edge to edge instead of clipping cars at the page margin.
116                .contentMargins(.horizontal, 24, for: .scrollContent)
117                .padding(.horizontal, -24)
118                .onAppear { proxy.scrollTo(nextCar, anchor: .center) }
119                .onChange(of: puzzle.placed.count) {
120                    withAnimation { proxy.scrollTo(nextCar, anchor: .center) }
121                }
122            }
123        }
124    }
125
126    private func labeledSlots(_ labels: [String]) -> some View {
127        ForEach(Array(labels.enumerated()), id: \.offset) { i, label in
128            VStack(spacing: 8) {
129                Text(label)
130                    .font(.heading(20))
131                slot(i).frame(height: card)
132            }
133            .frame(maxWidth: .infinity)
134        }
135    }
136
137    private var nextCar: Int { min(puzzle.placed.count, puzzle.steps.count - 1) }
138
139    /// A placed card, the outlined next slot, or a faint empty slot.
140    private func slot(_ i: Int) -> some View {
141        let shape = RoundedRectangle(cornerRadius: 24, style: .continuous)
142        return Group {
143            if i < puzzle.placed.count {
144                ChoiceTile(item: puzzle.placed[i])
145            } else {
146                shape
147                    .fill(Color(.systemGray6))
148                    .overlay {
149                        shape.strokeBorder(i == puzzle.placed.count ? Category.days.color : Color(.systemGray3),
150                                           style: StrokeStyle(lineWidth: i == puzzle.placed.count ? 5 : 2, dash: [10, 8]))
151                    }
152            }
153        }
154        .accessibilityElement(children: .ignore)
155        .accessibilityLabel(i < puzzle.placed.count ? puzzle.placed[i].name : "Empty")
156    }
157
158    private func place(_ item: QuizItem) {
159        guard let step = puzzle.current else { return }
160        let outcome = puzzle.place(item)
161        guard outcome != .ignored else { return }
162        if let profile = session.current {
163            session.store.record(step.answer, chosen: item, game: game, correct: outcome == .correct, for: profile)
164        }
165        switch outcome {
166        case .correct where puzzle.isSolved:
167            let sound: SoundEffect = game == .weekTrain ? .whistle : .success
168            SoundEngine.shared.play(sound)
169            mascot.handle(.correct)
170            celebrating = true
171            speechToken += 1
172            solves += 1
173            let token = speechToken, gen = generation, solve = solves
174            let finish = {
175                guard gen == generation, solve == solves, !finished else { return }
176                celebrating = false
177                finished = true
178            }
179            DispatchQueue.main.asyncAfter(deadline: .now() + SoundEngine.shared.remaining(sound) + 0.2) {
180                guard gen == generation, token == speechToken else { return }
181                // Move on when the whole summary has been said.
182                SpeechSynthesizer.shared.speak(puzzle.summary, completion: finish)
183            }
184            // In case the summary is cut off and never finishes.
185            DispatchQueue.main.asyncAfter(deadline: .now() + 15, execute: finish)
186        case .correct:
187            SoundEngine.shared.play(.success)
188            mascot.handle(.correct)
189            var rng = SystemRandomNumberGenerator()
190            // One utterance: a second speak() would cut the praise off.
191            say("\(praise.next(using: &rng)) \(puzzle.current?.prompt ?? "")", after: RoundStyle.speechDelay)
192            askAfterCheer()
193        case .incorrect:
194            SoundEngine.shared.play(.gentleMiss)
195            mascot.handle(.wrong)
196            say(puzzle.correction(), after: RoundStyle.speechDelay)
197            withAnimation(.easeOut(duration: 0.2)) { dimmed = item }
198            DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
199                withAnimation { if dimmed == item { dimmed = nil } }
200                puzzle.resume()
201            }
202        case .ignored:
203            break
204        }
205    }
206
207    /// Praise and the next prompt are one line; the owl asks once the cheer is over.
208    private func askAfterCheer() {
209        let ticket = mascot.ticket, gen = generation
210        DispatchQueue.main.asyncAfter(deadline: .now() + mascot.hold) {
211            guard gen == generation, ticket == mascot.ticket, let prompt = puzzle.current?.prompt else { return }
212            mascot.handle(.prompt(prompt))
213        }
214    }
215
216    /// Says the current step's prompt, with the mascot asking.
217    private func ask(after delay: TimeInterval) {
218        let prompt = puzzle.current?.prompt ?? ""
219        mascot.handle(.prompt(prompt, after: delay))
220        say(prompt, after: delay)
221    }
222
223    /// Speaks after `delay` unless something newer was said first.
224    private func say(_ text: String, after delay: TimeInterval) {
225        guard !text.isEmpty else { return }
226        speechToken += 1
227        let token = speechToken, gen = generation
228        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
229            if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) }
230        }
231    }
232}
233
234enum TrainStyle {
235    /// Visible on both light and dark backgrounds.
236    static let tire = Color(white: 0.45)
237    static let hub = Color(white: 0.75)
238}
239
240/// A toy engine facing left, so its cab sits next to the first car.
241private struct TrainEngine: View {
242    var body: some View {
243        GeometryReader { geo in
244            let w = geo.size.width, h = geo.size.height
245            let color = Category.days.color
246            ZStack(alignment: .topLeading) {
247                // Chimney, cab, boiler.
248                RoundedRectangle(cornerRadius: 4).fill(color)
249                    .frame(width: w * 0.16, height: h * 0.22)
250                    .offset(x: w * 0.62, y: h * 0.12)
251                RoundedRectangle(cornerRadius: 10).fill(color)
252                    .frame(width: w * 0.42, height: h * 0.72)
253                    .offset(x: w * 0.02, y: h * 0.08)
254                RoundedRectangle(cornerRadius: 6).fill(.white.opacity(0.85))
255                    .frame(width: w * 0.24, height: h * 0.2)
256                    .offset(x: w * 0.11, y: h * 0.16)
257                RoundedRectangle(cornerRadius: 14).fill(color)
258                    .frame(width: w * 0.62, height: h * 0.4)
259                    .offset(x: w * 0.36, y: h * 0.4)
260                RoundedRectangle(cornerRadius: 3).fill(Color(.systemGray))
261                    .frame(width: w, height: 6)
262                    .offset(y: h * 0.82)
263                wheels(w: w, h: h, at: [0.2, 0.5, 0.8])
264            }
265            .scaleEffect(x: -1)
266        }
267        .accessibilityHidden(true)
268    }
269}
270
271/// A flat car with the slot on top and two wheels.
272private struct TrainCar<Content: View>: View {
273    @ViewBuilder let content: () -> Content
274
275    var body: some View {
276        GeometryReader { geo in
277            let w = geo.size.width, h = geo.size.height
278            ZStack(alignment: .topLeading) {
279                content()
280                    .frame(width: w, height: h * 0.8)
281                RoundedRectangle(cornerRadius: 3).fill(Color(.systemGray))
282                    .frame(width: w + 6, height: 6)
283                    .offset(x: -3, y: h * 0.82)
284                wheels(w: w, h: h, at: [0.25, 0.75])
285            }
286        }
287    }
288}
289
290private func wheels(w: CGFloat, h: CGFloat, at positions: [CGFloat]) -> some View {
291    let d = h * 0.2
292    return ForEach(positions, id: \.self) { x in
293        Circle()
294            .fill(TrainStyle.tire)
295            .overlay(Circle().fill(TrainStyle.hub).padding(d * 0.3))
296            .frame(width: d, height: d)
297            .offset(x: w * x - d / 2, y: h - d)
298    }
299}