Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/MazeMissionView.swift3// Description: Maze Escape mission: guide a glowing orb through a generated maze by swipes, arrow buttons or optional tilt; keys unlock the exit at higher levels.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import CoreMotion9import SwiftUI1011/// Device-motion gravity readings for the optional tilt control. Callbacks arrive on a private queue.12nonisolated final class MazeTiltSensor: @unchecked Sendable {13 private let manager = CMMotionManager()14 private let queue: OperationQueue = {15 let q = OperationQueue(); q.maxConcurrentOperationCount = 1; q.name = "ai.spboucher.orix.alarm.maze-tilt"; return q16 }()1718 var isAvailable: Bool { manager.isDeviceMotionAvailable }1920 func start(onGravity: @escaping @Sendable (_ x: Double, _ y: Double) -> Void) {21 guard manager.isDeviceMotionAvailable, !manager.isDeviceMotionActive else { return }22 manager.deviceMotionUpdateInterval = 1.0 / 15.023 manager.startDeviceMotionUpdates(to: queue) { motion, _ in24 guard let gravity = motion?.gravity else { return }25 onGravity(gravity.x, gravity.y)26 }27 }2829 func stop() { if manager.isDeviceMotionActive { manager.stopDeviceMotionUpdates() } }30}3132struct MazeMissionView: View {33 typealias Engine = MazeEngine34 let mission: ResolvedMission35 let onFinish: (MissionOutcome) -> Void36 @Environment(\.accessibilityReduceMotion) private var reduceMotion3738 @State private var round = 039 @State private var puzzle: Engine.Puzzle40 @State private var position: Engine.Cell41 @State private var trail: [Engine.Cell]42 @State private var collected: Set<Engine.Cell> = []43 @State private var moves = 044 @State private var shortest: Int45 @State private var solved = false46 @State private var lockedHint = false47 @State private var lockedBumps = 048 @State private var moveDuration = 0.1249 @State private var started = Date()50 @State private var finished = false51 // Tilt control (off by default).52 @State private var tilt = MazeTiltSensor()53 @State private var tiltEnabled = false54 @State private var tiltBaseline: (x: Double, y: Double)?55 @State private var lastTiltMove = Date.distantPast5657 init(mission: ResolvedMission, onFinish: @escaping (MissionOutcome) -> Void) {58 self.mission = mission; self.onFinish = onFinish59 let first = Engine.generate(level: mission.level, round: 0, seed: mission.seed)60 _puzzle = State(initialValue: first)61 _position = State(initialValue: first.start)62 _trail = State(initialValue: [first.start])63 _shortest = State(initialValue: Engine.shortestPathLength(first) ?? 0)64 }6566 private var keysLeft: Int { puzzle.keys.filter { !collected.contains($0) }.count }67 private var exitOpen: Bool { keysLeft == 0 }6869 private var instruction: String {70 switch puzzle.keys.count {71 case 0: String(localized: "Swipe or use the arrows to guide the light to the sun.")72 case 1: String(localized: "Collect the key, then guide the light to the sun.")73 default: String(localized: "Collect the \(puzzle.keys.count) keys, then guide the light to the sun.")74 }75 }7677 var body: some View {78 MissionScaffold(instruction: instruction, round: round + 1, totalRounds: mission.rounds) {79 VStack(spacing: 12) {80 statusRow81 maze82 .aspectRatio(1, contentMode: .fit)83 .id(round)84 .transition(.opacity)85 Group {86 if solved {87 Label("You are out", systemImage: "checkmark.circle.fill").foregroundStyle(Theme.success)88 } else if lockedHint {89 Label(puzzle.keys.count > 1 ? "The exit is locked: collect every key first." : "The exit is locked: collect the key first.", systemImage: "lock.fill").foregroundStyle(Theme.gold)90 } else {91 Text(" ")92 }93 }94 .font(.orixCaption).frame(minHeight: 18).accessibilityIdentifier("maze.feedback")95 controls96 Spacer(minLength: 0)97 }98 .contentShape(Rectangle())99 .gesture(DragGesture(minimumDistance: 14).onEnded { value in100 let dx = value.translation.width, dy = value.translation.height101 move(abs(dx) > abs(dy) ? (dx > 0 ? .right : .left) : (dy > 0 ? .down : .up))102 })103 }104 .onAppear { started = Date() }105 .onDisappear { tilt.stop() }106 }107108 // MARK: Status109110 private var statusRow: some View {111 HStack {112 if puzzle.keys.isEmpty {113 Label("Exit open", systemImage: "sun.max.fill").foregroundStyle(Theme.gold)114 } else {115 HStack(spacing: 6) {116 ForEach(puzzle.keys.indices, id: \.self) { i in117 let has = collected.contains(puzzle.keys[i])118 Image(systemName: has ? "key.fill" : "key").foregroundStyle(has ? Theme.gold : Theme.textTertiary)119 }120 Text(exitOpen ? "Exit open" : "Exit locked").foregroundStyle(exitOpen ? Theme.gold : Theme.textSecondary)121 Image(systemName: exitOpen ? "lock.open.fill" : "lock.fill").foregroundStyle(exitOpen ? Theme.gold : Theme.textSecondary)122 }123 .accessibilityElement(children: .ignore)124 .accessibilityLabel(exitOpen ? "All keys collected. The exit is open." : "\(puzzle.keys.count - keysLeft) of \(puzzle.keys.count) keys collected. The exit is locked.")125 }126 Spacer()127 Text("\(moves) moves · shortest \(shortest)").monospacedDigit().foregroundStyle(Theme.textTertiary)128 .accessibilityLabel("\(moves) cells travelled. The shortest route is \(shortest).")129 }130 .font(.orixCaption)131 .accessibilityIdentifier("maze.status")132 }133134 // MARK: Maze135136 private var maze: some View {137 GeometryReader { geo in138 board(side: min(geo.size.width, geo.size.height))139 .frame(maxWidth: .infinity, maxHeight: .infinity)140 }141 .accessibilityElement(children: .ignore)142 .accessibilityLabel("Maze, \(puzzle.width) by \(puzzle.height)")143 .accessibilityValue(spokenPosition)144 .accessibilityIdentifier("maze.board")145 }146147 private func board(side: CGFloat) -> some View {148 let cell = side / CGFloat(puzzle.width)149 let center: @Sendable (Engine.Cell) -> CGPoint = { c in CGPoint(x: (CGFloat(c.x) + 0.5) * cell, y: (CGFloat(c.y) + 0.5) * cell) }150 let puzzle = puzzle, trail = trail151 let midnight = Theme.midnight, violet = Theme.violet, gold = Theme.gold152 return ZStack {153 Canvas { ctx, _ in154 let board = Path(roundedRect: CGRect(x: 0, y: 0, width: side, height: side), cornerRadius: 10)155 ctx.fill(board, with: .color(midnight.opacity(0.55)))156 // Soft trail of the most recent cells, fading towards the oldest.157 // Each part is one path drawn in its own layer, so overlapping passes do not add up.158 let recent = Array(trail.suffix(40))159 let parts: [(cells: ArraySlice<Engine.Cell>, color: Color, opacity: Double)] = [160 (recent.prefix(max(recent.count - 11, 0)), violet, 0.32), (recent.suffix(12), violet.mix(with: gold, by: 0.75), 0.5),161 ]162 for part in parts where part.cells.count > 1 {163 var line = Path()164 line.addLines(part.cells.map(center))165 ctx.drawLayer { layer in166 layer.opacity = part.opacity167 layer.stroke(line, with: .color(part.color), style: StrokeStyle(lineWidth: cell * 0.26, lineCap: .round, lineJoin: .round))168 }169 }170 // Start marker.171 let s = center(puzzle.start)172 ctx.stroke(Path(ellipseIn: CGRect(x: s.x - cell * 0.22, y: s.y - cell * 0.22, width: cell * 0.44, height: cell * 0.44)),173 with: .color(.white.opacity(0.35)), style: StrokeStyle(lineWidth: 1.5, dash: [3, 3]))174 // Walls.175 var walls = Path()176 for y in 0..<puzzle.height {177 for x in 0..<puzzle.width {178 let c = Engine.Cell(x: x, y: y)179 let ox = CGFloat(x) * cell, oy = CGFloat(y) * cell180 if !puzzle.isOpen(c, .up), y > 0 { walls.move(to: CGPoint(x: ox, y: oy)); walls.addLine(to: CGPoint(x: ox + cell, y: oy)) }181 if !puzzle.isOpen(c, .left), x > 0 { walls.move(to: CGPoint(x: ox, y: oy)); walls.addLine(to: CGPoint(x: ox, y: oy + cell)) }182 }183 }184 walls.addRoundedRect(in: CGRect(x: 1.5, y: 1.5, width: side - 3, height: side - 3), cornerSize: CGSize(width: 9, height: 9))185 ctx.stroke(walls, with: .color(violet.opacity(0.35)), style: StrokeStyle(lineWidth: 7, lineCap: .round, lineJoin: .round))186 ctx.stroke(walls, with: .color(Color(red: 0.80, green: 0.78, blue: 1.0)), style: StrokeStyle(lineWidth: 2.5, lineCap: .round, lineJoin: .round))187 }188189 ForEach(puzzle.keys.indices, id: \.self) { i in190 if !collected.contains(puzzle.keys[i]) {191 Image(systemName: "key.fill").font(.system(size: cell * 0.5, weight: .bold)).foregroundStyle(Theme.gold)192 .shadow(color: Theme.gold.opacity(0.9), radius: 6)193 .position(center(puzzle.keys[i]))194 .transition(.scale.combined(with: .opacity))195 }196 }197198 exitBeacon(cell: cell).position(center(puzzle.exit))199200 Circle()201 .fill(RadialGradient(colors: [.white, Theme.peach, Theme.sunrise], center: .center, startRadius: 0, endRadius: cell * 0.3))202 .frame(width: cell * 0.52, height: cell * 0.52)203 .shadow(color: Theme.gold.opacity(0.95), radius: cell * 0.3)204 .position(center(position))205 .animation(reduceMotion ? nil : .easeOut(duration: moveDuration), value: position)206 }207 .frame(width: side, height: side)208 }209210 private func exitBeacon(cell: CGFloat) -> some View {211 ZStack {212 if exitOpen {213 Circle().stroke(Theme.gold.opacity(0.7), lineWidth: 2).frame(width: cell * 0.86, height: cell * 0.86)214 .phaseAnimator(reduceMotion ? [false] : [false, true]) { view, phase in215 view.scaleEffect(phase ? 1.12 : 0.85).opacity(phase ? 0.25 : 1)216 } animation: { _ in .easeInOut(duration: 1.1) }217 Image(systemName: "sun.max.fill").font(.system(size: cell * 0.56, weight: .bold)).foregroundStyle(Theme.sunriseGradient)218 .shadow(color: Theme.sunrise.opacity(0.9), radius: 8)219 } else {220 Circle().stroke(.white.opacity(0.45), style: StrokeStyle(lineWidth: 1.5, dash: [3, 3])).frame(width: cell * 0.8, height: cell * 0.8)221 Image(systemName: "lock.fill").font(.system(size: cell * 0.42, weight: .bold)).foregroundStyle(Theme.textSecondary)222 }223 }224 }225226 private var spokenPosition: String {227 let open = puzzle.openDirections(position).map(name).joined(separator: ", ")228 let dx = puzzle.exit.x - position.x, dy = puzzle.exit.y - position.y229 var parts = [String(localized: "You are in column \(position.x + 1), row \(position.y + 1). Open: \(open).")]230 parts.append(String(localized: "The exit is \(abs(dx)) columns to the \(dx >= 0 ? "right" : "left") and \(abs(dy)) rows \(dy >= 0 ? "down" : "up")."))231 if keysLeft > 0 { parts.append(String(localized: "Keys left: \(keysLeft).")) }232 return parts.joined(separator: " ")233 }234235 private func name(_ d: Engine.Direction) -> String {236 switch d {237 case .up: String(localized: "up"); case .right: String(localized: "right")238 case .down: String(localized: "down"); case .left: String(localized: "left")239 }240 }241242 // MARK: Controls243244 private var controls: some View {245 HStack(alignment: .center, spacing: 0) {246 Group {247 if tilt.isAvailable {248 Button { setTilt(!tiltEnabled) } label: {249 VStack(spacing: 4) {250 Image(systemName: tiltEnabled ? "iphone.gen3.radiowaves.left.and.right" : "iphone.gen3").font(.title3)251 Text(tiltEnabled ? "Tilt on" : "Tilt off").font(.system(size: 11, weight: .semibold, design: .rounded))252 }253 .foregroundStyle(tiltEnabled ? Theme.midnight : Theme.textSecondary)254 .frame(width: 64, height: 58)255 .background(tiltEnabled ? AnyShapeStyle(Theme.nightGradient) : AnyShapeStyle(Theme.surfaceRaised), in: RoundedRectangle(cornerRadius: 16, style: .continuous))256 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Theme.hairline))257 }258 .buttonStyle(.plain)259 .accessibilityLabel("Tilt control").accessibilityValue(tiltEnabled ? "On" : "Off")260 .accessibilityHint("Tilt the iPhone to roll the light.")261 .accessibilityIdentifier("maze.tilt")262 } else {263 Color.clear264 }265 }266 .frame(width: 70, height: 58)267 Spacer(minLength: 0)268 VStack(spacing: 8) {269 arrow(.up, "chevron.up")270 HStack(spacing: 8) {271 arrow(.left, "chevron.left"); arrow(.down, "chevron.down"); arrow(.right, "chevron.right")272 }273 }274 Spacer(minLength: 0)275 Color.clear.frame(width: 70, height: 58)276 }277 }278279 private func arrow(_ direction: Engine.Direction, _ symbol: String) -> some View {280 let open = puzzle.isOpen(position, direction) && !solved281 return Button { move(direction) } label: {282 Image(systemName: symbol).font(.system(size: 24, weight: .bold))283 .foregroundStyle(open ? Theme.textPrimary : Theme.textTertiary)284 .frame(width: 66, height: 54)285 .background(open ? Theme.surfaceRaised : Theme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))286 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(open ? Color.white.opacity(0.3) : Theme.hairline))287 }288 .buttonStyle(.plain)289 .disabled(!open)290 .accessibilityLabel("Move \(name(direction))")291 .accessibilityHint(open ? "" : "Blocked by a wall")292 .accessibilityIdentifier("maze.move.\(name(direction))")293 }294295 // MARK: Logic296297 private func move(_ direction: Engine.Direction) {298 guard !solved, !finished else { return }299 let path = Engine.slide(in: puzzle, from: position, direction)300 guard let stop = path.last else { Haptics.play(.tick); return }301 moves += path.count302 trail.append(contentsOf: path)303 if trail.count > 80 { trail.removeFirst(trail.count - 80) }304 moveDuration = 0.07 + 0.045 * Double(path.count)305 position = stop306 SoundFX.play(.tap)307 if puzzle.keys.contains(stop), !collected.contains(stop) {308 withAnimation(reduceMotion ? nil : .snappy) { _ = collected.insert(stop) }309 Haptics.play(.success)310 lockedHint = false311 } else if stop == puzzle.exit {312 if exitOpen {313 solved = true; lockedHint = false314 Haptics.play(.success); SoundFX.play(.correct)315 Task {316 try? await Task.sleep(for: .milliseconds(900))317 advance()318 }319 } else {320 lockedBumps += 1321 lockedHint = true322 Haptics.play(.warning)323 let bump = lockedBumps324 Task {325 try? await Task.sleep(for: .seconds(3))326 if bump == lockedBumps { lockedHint = false }327 }328 }329 } else {330 Haptics.play(.selection)331 }332 if UIAccessibility.isVoiceOverRunning {333 AccessibilityNotification.Announcement(solved ? String(localized: "You are out.") : spokenPosition).post()334 }335 }336337 private func advance() {338 guard !finished else { return }339 if round + 1 >= mission.rounds {340 finished = true341 tilt.stop()342 onFinish(MissionOutcome(result: .completed, mistakes: 0, duration: Date().timeIntervalSince(started), rounds: mission.rounds))343 return344 }345 let next = Engine.generate(level: mission.level, round: round + 1, seed: mission.seed)346 withAnimation(reduceMotion ? nil : .smooth) {347 round += 1; puzzle = next; position = next.start; trail = [next.start]; collected = []348 moves = 0; shortest = Engine.shortestPathLength(next) ?? 0; solved = false; lockedHint = false349 }350 }351352 private func setTilt(_ on: Bool) {353 tiltEnabled = on354 Haptics.play(.selection)355 guard on else { tilt.stop(); return }356 tiltBaseline = nil357 tilt.start { x, y in358 Task { @MainActor in tilted(x, y) }359 }360 }361362 /// The posture at the moment tilt is switched on is the neutral position; leaning past a threshold rolls the light one slide at a time.363 private func tilted(_ x: Double, _ y: Double) {364 guard tiltEnabled, !solved else { return }365 guard let base = tiltBaseline else { tiltBaseline = (x, y); return }366 let dx = x - base.x, dy = y - base.y367 guard max(abs(dx), abs(dy)) > 0.22, Date().timeIntervalSince(lastTiltMove) > 0.4 else { return }368 let direction: Engine.Direction = abs(dx) > abs(dy) ? (dx > 0 ? .right : .left) : (dy > 0 ? .up : .down)369 guard puzzle.isOpen(position, direction) else { return }370 lastTiltMove = Date()371 move(direction)372 }373}374