Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/MathMissionView.swift3// Description: Math Blitz mission: one question at a time, large custom keypad (or four choices for estimation), immediate feedback.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct MathMissionView: View {11 let mission: ResolvedMission12 let onFinish: (MissionOutcome) -> Void1314 @Environment(\.accessibilityReduceMotion) private var reduceMotion15 @State private var round = 016 @State private var digits = ""17 @State private var negative = false18 @State private var mistakes = 019 @State private var feedback: PuzzleFeedback = .none20 @State private var wrongChoice: Int?21 @State private var shake = 022 @State private var locked = false23 @State private var finished = false24 @State private var startedAt = Date()2526 private var puzzle: MathEngine.Puzzle { MathEngine.generate(level: mission.level, round: round, seed: mission.seed) }2728 var body: some View {29 let puzzle = puzzle30 MissionScaffold(instruction: instruction(for: puzzle), round: round + 1, totalRounds: mission.puzzleRounds) {31 VStack(spacing: 14) {32 PuzzleRoundProgress(current: round, total: mission.puzzleRounds, currentSolved: feedback == .correct)33 questionCard(puzzle)34 .modifier(PuzzleShake(trigger: shake, enabled: !reduceMotion))35 .id(round)36 .transition(reduceMotion ? .opacity : .asymmetric(insertion: .move(edge: .trailing).combined(with: .opacity), removal: .move(edge: .leading).combined(with: .opacity)))37 if puzzle.isMultipleChoice { choices(puzzle) } else { keypad(puzzle) }38 }39 }40 .onAppear { startedAt = Date() }41 }4243 private func instruction(for puzzle: MathEngine.Puzzle) -> String {44 switch puzzle.category {45 case .estimation: String(localized: "Estimate: tap the closest value.")46 case .missingNumber: String(localized: "Find the missing number.")47 case .sequence: String(localized: "Find the next number.")48 default: String(localized: "Solve it and tap Check.")49 }50 }5152 // MARK: Question5354 private func questionCard(_ puzzle: MathEngine.Puzzle) -> some View {55 VStack(spacing: 10) {56 Text(puzzle.prompt)57 .font(.system(size: 42, weight: .bold, design: .rounded)).monospacedDigit()58 .lineLimit(1).minimumScaleFactor(0.4)59 .foregroundStyle(Theme.textPrimary)60 .frame(maxWidth: .infinity)61 .accessibilityLabel("Question")62 .accessibilityValue(puzzle.prompt)63 .accessibilityIdentifier("math.question")64 if !puzzle.isMultipleChoice {65 HStack(spacing: 10) {66 Text("=").font(.system(size: 30, weight: .medium, design: .rounded)).foregroundStyle(Theme.textTertiary).accessibilityHidden(true)67 Text(answerText.isEmpty ? "?" : answerText)68 .font(.system(size: 46, weight: .semibold, design: .rounded)).monospacedDigit()69 .foregroundStyle(answerText.isEmpty ? AnyShapeStyle(Theme.textTertiary) : (feedback == .none ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(feedback.tint)))70 .contentTransition(reduceMotion ? .identity : .numericText())71 .animation(.snappy(duration: 0.2), value: answerText)72 .lineLimit(1).minimumScaleFactor(0.5)73 .accessibilityLabel("Your answer")74 .accessibilityValue(answerText.isEmpty ? String(localized: "empty") : answerText)75 .accessibilityIdentifier("math.answer")76 }77 }78 PuzzleStatusLine(text: statusText(puzzle), feedback: feedback)79 .accessibilityIdentifier("math.feedback")80 }81 .frame(maxWidth: .infinity)82 .glassCard(padding: 16, tint: feedback == .none ? nil : feedback.tint)83 .animation(.smooth(duration: 0.25), value: feedback)84 }8586 private var answerText: String { digits.isEmpty ? (negative ? "−" : "") : (negative ? "−" : "") + digits }8788 private func statusText(_ puzzle: MathEngine.Puzzle) -> String {89 switch feedback {90 case .correct: String(localized: "Correct")91 case .wrong: String(localized: "Not quite. Try again.")92 case .none: puzzle.isMultipleChoice ? String(localized: "Which value is nearest?") : String(localized: "Type your answer")93 }94 }9596 // MARK: Keypad9798 private func keypad(_ puzzle: MathEngine.Puzzle) -> some View {99 VStack(spacing: 10) {100 ForEach([[1, 2, 3], [4, 5, 6], [7, 8, 9]], id: \.self) { row in101 HStack(spacing: 10) { ForEach(row, id: \.self) { digitKey($0) } }102 }103 HStack(spacing: 10) {104 key(label: "±", symbol: "plus.forwardslash.minus", identifier: "math.key.negative", accessibility: "Negative sign") { toggleNegative() }105 digitKey(0)106 key(label: "⌫", symbol: "delete.left.fill", identifier: "math.key.delete", accessibility: "Delete") { deleteDigit() }107 }108 Button { submit(puzzle) } label: { Label("Check", systemImage: "checkmark") }109 .buttonStyle(PrimaryButtonStyle())110 .disabled(digits.isEmpty || locked)111 .accessibilityIdentifier("math.submit")112 .padding(.top, 2)113 }114 }115116 private func digitKey(_ digit: Int) -> some View {117 Button { append(digit) } label: {118 Text("\(digit)").font(.system(size: 32, weight: .semibold, design: .rounded)).monospacedDigit()119 .frame(maxWidth: .infinity, minHeight: 60, maxHeight: 78)120 }121 .buttonStyle(MathKeyStyle())122 .accessibilityIdentifier("math.key.\(digit)")123 }124125 private func key(label: String, symbol: String, identifier: String, accessibility: LocalizedStringKey, action: @escaping () -> Void) -> some View {126 Button(action: action) {127 Image(systemName: symbol).font(.system(size: 26, weight: .semibold))128 .frame(maxWidth: .infinity, minHeight: 60, maxHeight: 78)129 }130 .buttonStyle(MathKeyStyle(isAuxiliary: true))131 .accessibilityLabel(accessibility)132 .accessibilityIdentifier(identifier)133 }134135 private func clearWrongState() {136 guard feedback == .wrong else { return }137 feedback = .none; digits = ""; negative = false138 }139140 private func append(_ digit: Int) {141 guard !locked else { return }142 clearWrongState()143 guard digits.count < MathEngine.maxAnswerDigits else { Haptics.play(.warning); return }144 if digits == "0" { digits = "" }145 digits.append(String(digit))146 Haptics.play(.tick); SoundFX.play(.tap)147 }148149 private func deleteDigit() {150 guard !locked else { return }151 clearWrongState()152 if !digits.isEmpty { digits.removeLast() } else { negative = false }153 Haptics.play(.tick)154 }155156 private func toggleNegative() {157 guard !locked else { return }158 clearWrongState()159 negative.toggle()160 Haptics.play(.tick)161 }162163 private func submit(_ puzzle: MathEngine.Puzzle) {164 guard !locked, let value = Int(digits) else { return }165 evaluate(puzzle, answer: negative ? -value : value)166 }167168 // MARK: Choices (estimation)169170 private func choices(_ puzzle: MathEngine.Puzzle) -> some View {171 VStack(spacing: 12) {172 ForEach(Array(puzzle.choices.enumerated()), id: \.offset) { index, value in173 let isWrong = wrongChoice == value, isRight = feedback == .correct && value == puzzle.answer174 Button {175 guard !locked else { return }176 wrongChoice = MathEngine.validate(puzzle, answer: value) ? nil : value177 evaluate(puzzle, answer: value)178 } label: {179 HStack {180 Text(value.formatted(.number.grouping(.automatic))).font(.system(size: 30, weight: .semibold, design: .rounded)).monospacedDigit()181 Spacer()182 Image(systemName: isRight ? "checkmark.circle.fill" : (isWrong ? "xmark.circle.fill" : "circle"))183 .font(.title2).foregroundStyle(isRight ? Theme.success : (isWrong ? Theme.danger : Theme.textTertiary))184 }185 .padding(.horizontal, 22)186 .frame(maxWidth: .infinity, minHeight: 68, maxHeight: 92)187 }188 .buttonStyle(MathKeyStyle(tint: isRight ? Theme.success : (isWrong ? Theme.danger : nil)))189 .accessibilityLabel("\(value)")190 .accessibilityValue(isRight ? String(localized: "correct") : (isWrong ? String(localized: "wrong") : ""))191 .accessibilityIdentifier("math.choice.\(index)")192 }193 Spacer(minLength: 0)194 }195 }196197 // MARK: Flow198199 private func evaluate(_ puzzle: MathEngine.Puzzle, answer: Int) {200 if MathEngine.validate(puzzle, answer: answer) {201 locked = true202 feedback = .correct203 feedback.signal(announcement: String(localized: "Correct"))204 Task {205 guard await PuzzleTiming.pause(0.75) else { return }206 advance()207 }208 } else {209 mistakes += 1210 feedback = .wrong211 withAnimation(.linear(duration: 0.4)) { shake += 1 }212 feedback.signal(announcement: String(localized: "Not quite. Try again."))213 let attempt = mistakes214 Task {215 // The same question stays; the wrong entry is cleared after a moment (or as soon as a key is pressed).216 guard await PuzzleTiming.pause(1.1), attempt == mistakes, feedback == .wrong else { return }217 feedback = .none; digits = ""; negative = false; wrongChoice = nil218 }219 }220 }221222 private func advance() {223 guard !finished else { return }224 if round + 1 >= mission.puzzleRounds {225 finished = true226 onFinish(MissionOutcome(result: .completed, mistakes: mistakes, duration: Date().timeIntervalSince(startedAt), rounds: mission.puzzleRounds))227 } else {228 withAnimation(reduceMotion ? nil : .smooth(duration: 0.35)) {229 round += 1230 digits = ""; negative = false; feedback = .none; wrongChoice = nil231 }232 locked = false233 }234 }235}236237/// Glass key of the math keypad, with a clear pressed state.238private struct MathKeyStyle: ButtonStyle {239 var isAuxiliary = false240 var tint: Color? = nil241 func makeBody(configuration: Configuration) -> some View {242 let shape = RoundedRectangle(cornerRadius: 20, style: .continuous)243 configuration.label244 .foregroundStyle(isAuxiliary ? Theme.gold : Theme.textPrimary)245 .background {246 shape.fill((tint ?? .white).opacity(configuration.isPressed ? 0.30 : (tint == nil ? (isAuxiliary ? 0.06 : 0.11) : 0.20)))247 .overlay { shape.strokeBorder(tint?.opacity(0.8) ?? Color.white.opacity(configuration.isPressed ? 0.45 : 0.14), lineWidth: 1) }248 }249 .contentShape(shape)250 .scaleEffect(configuration.isPressed ? 0.95 : 1)251 .animation(.snappy(duration: 0.12), value: configuration.isPressed)252 }253}254