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

main
daybyday/DayByDay/Quiz/YearWheelView.swift history · blame · raw

159 lines · 5994 bytes

7 symbols in this file
  1//
  2//  YearWheelView.swift
  3//  DayByDay
  4//
  5
  6import SwiftUI
  7
  8extension Season {
  9    /// Wedge colors on the year wheel; white labels are at least 3:1 on each.
 10    var wheelColor: Color {
 11        switch self {
 12        case .spring: Color(red: 0.18, green: 0.56, blue: 0.28)
 13        case .summer: Color(red: 0.72, green: 0.48, blue: 0.0)
 14        case .fall:   Color(red: 0.55, green: 0.22, blue: 0.10)
 15        case .winter: Color(red: 0.0, green: 0.42, blue: 0.85)
 16        }
 17    }
 18}
 19
 20/// Spin the wheel of months; it says where it lands and which season that is.
 21/// Tapping a month says the same for that month.
 22struct YearWheelView: View {
 23    @Environment(\.accessibilityReduceMotion) private var reduceMotion
 24    @State private var rotation = 0.0
 25    @State private var spinning = false
 26    @State private var speechToken = 0
 27    /// Bumped when the screen goes away, so a pending landing says nothing.
 28    @State private var generation = 0
 29
 30    private static let spinDuration = 2.5
 31
 32    var body: some View {
 33        VStack(spacing: 32) {
 34            Pointer()
 35                .fill(Color.primary)
 36                .frame(width: 40, height: 34)
 37                .padding(.bottom, -40)
 38                .zIndex(1)
 39            wheel
 40                .aspectRatio(1, contentMode: .fit)
 41                .frame(maxWidth: 520)
 42            Button(action: spin) {
 43                Label("Spin!", systemImage: "arrow.clockwise.circle.fill")
 44                    .font(.heading(32, weight: .heavy))
 45                    .foregroundStyle(.white)
 46                    .padding(.horizontal, 48)
 47                    .padding(.vertical, 22)
 48                    .background(Capsule().fill(Category.months.color))
 49            }
 50            .buttonStyle(.plain)
 51            .disabled(spinning)
 52        }
 53        .padding(24)
 54        .onAppear { say(Lines.spinPrompt) }
 55        .onDisappear {
 56            generation += 1
 57            speechToken += 1
 58            SpeechSynthesizer.shared.stop()
 59        }
 60    }
 61
 62    private var wheel: some View {
 63        GeometryReader { geo in
 64            let size = min(geo.size.width, geo.size.height)
 65            ZStack {
 66                ForEach(Array(MonthOfYear.allCases.enumerated()), id: \.offset) { i, month in
 67                    let center = Double(i) * YearWheel.wedge
 68                    Wedge(center: center, width: YearWheel.wedge)
 69                        .fill(month.season.wheelColor)
 70                        .overlay(Wedge(center: center, width: YearWheel.wedge).stroke(.white, lineWidth: 2))
 71                        .contentShape(Wedge(center: center, width: YearWheel.wedge))
 72                        .onTapGesture {
 73                            guard !spinning else { return }
 74                            say(YearWheel.line(for: month))
 75                        }
 76                        .accessibilityLabel(month.name)
 77                        .accessibilityAddTraits(.isButton)
 78                    // Part of the picture: sized to the wedge, not the text size.
 79                    Text(month.name.prefix(3))
 80                        .font(.custom(HeadingFont.extraBold, fixedSize: size * 0.06))
 81                        .foregroundStyle(.white)
 82                        .offset(y: -size * 0.38)
 83                        .rotationEffect(.degrees(center))
 84                        .allowsHitTesting(false)
 85                        .accessibilityHidden(true)
 86                }
 87                Circle()
 88                    .fill(Color(.systemBackground))
 89                    .frame(width: size * 0.24)
 90                    .overlay(Circle().stroke(Color(.systemGray3), lineWidth: 2))
 91                    .allowsHitTesting(false)
 92            }
 93            .frame(width: size, height: size)
 94            .rotationEffect(.degrees(rotation))
 95            .frame(maxWidth: .infinity, maxHeight: .infinity)
 96        }
 97    }
 98
 99    private func spin() {
100        guard !spinning else { return }
101        let current = YearWheel.month(atRotation: rotation)
102        let month = MonthOfYear.allCases.filter { $0 != current }.randomElement()!
103        let target = YearWheel.target(from: rotation, landingOn: month, turns: 3)
104        spinning = true
105        speechToken += 1
106        SpeechSynthesizer.shared.stop()
107        let duration = reduceMotion ? 0 : Self.spinDuration
108        if reduceMotion {
109            rotation = target
110        } else {
111            withAnimation(.timingCurve(0.15, 0.8, 0.3, 1, duration: duration)) { rotation = target }
112        }
113        let gen = generation
114        DispatchQueue.main.asyncAfter(deadline: .now() + duration + 0.1) {
115            spinning = false
116            guard gen == generation else { return }
117            say(YearWheel.line(for: month))
118        }
119    }
120
121    private func say(_ text: String) {
122        speechToken += 1
123        let token = speechToken, gen = generation
124        DispatchQueue.main.async {
125            if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) }
126        }
127    }
128}
129
130/// A pie slice centered `center` degrees clockwise from the top.
131private struct Wedge: Shape {
132    let center: Double
133    let width: Double
134
135    func path(in rect: CGRect) -> Path {
136        let c = CGPoint(x: rect.midX, y: rect.midY)
137        let r = min(rect.width, rect.height) / 2
138        // SwiftUI angles start at 3 o'clock; the top is -90°.
139        let start = Angle.degrees(center - width / 2 - 90)
140        let end = Angle.degrees(center + width / 2 - 90)
141        var p = Path()
142        p.move(to: c)
143        p.addArc(center: c, radius: r, startAngle: start, endAngle: end, clockwise: false)
144        p.closeSubpath()
145        return p
146    }
147}
148
149/// Downward triangle marking the month that is picked.
150private struct Pointer: Shape {
151    func path(in rect: CGRect) -> Path {
152        var p = Path()
153        p.move(to: CGPoint(x: rect.minX, y: rect.minY))
154        p.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
155        p.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
156        p.closeSubpath()
157        return p
158    }
159}