Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/LogicGatesMissionView.swift3// Description: Logic Gates mission: flip switches feeding a small circuit of AND / OR / NOT / XOR gates until the lamp reaches its target state.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910extension LogicGatesEngine.GateKind {11 var name: String {12 switch self { case .and: "AND"; case .or: "OR"; case .not: "NOT"; case .xor: "XOR" }13 }14 /// One-line rule in plain language.15 var rule: String {16 switch self {17 case .and: String(localized: "on only if both inputs are on")18 case .or: String(localized: "on if at least one input is on")19 case .xor: String(localized: "on if exactly one input is on")20 case .not: String(localized: "flips its input: on becomes off, off becomes on")21 }22 }23}2425/// Positions of switches (bottom row), gates (one row per layer) and the lamp (top) inside the drawing area.26private struct CircuitLayout {27 typealias Engine = LogicGatesEngine28 static let gateSize = CGSize(width: 70, height: 40)29 static let switchSize = CGSize(width: 60, height: 56)30 static let lampSize: CGFloat = 583132 let switchCenters: [CGPoint]33 let gateCenters: [CGPoint]34 let lampCenter: CGPoint35 /// Free height between two rows of gates.36 let gap: CGFloat37 private let puzzle: Engine.Puzzle3839 init(puzzle: Engine.Puzzle, size: CGSize) {40 self.puzzle = puzzle41 let rows = CGFloat(puzzle.layerCount + 1)42 let rowHeight = min((size.height - Self.switchSize.height / 2 - Self.lampSize / 2 - 4) / rows, 116)43 let switchY = size.height / 2 + rowHeight * rows / 2 + (Self.lampSize - Self.switchSize.height) / 444 let slot = min(size.width / CGFloat(max(puzzle.switchCount, 1)), 104)45 let left = (size.width - slot * CGFloat(puzzle.switchCount)) / 246 let switches = (0..<puzzle.switchCount).map { CGPoint(x: left + slot * (CGFloat($0) + 0.5), y: switchY) }47 var gates: [CGPoint] = []48 for gate in puzzle.gates {49 let xs = gate.inputs.map { signal -> CGFloat in50 switch signal {51 case .input(let i): switches.indices.contains(i) ? switches[i].x : size.width / 252 case .gate(let g): gates.indices.contains(g) ? gates[g].x : size.width / 253 }54 }55 gates.append(CGPoint(x: xs.reduce(0, +) / CGFloat(max(xs.count, 1)), y: switchY - rowHeight * CGFloat(gate.layer)))56 }57 switchCenters = switches58 gap = max(rowHeight - Self.gateSize.height, 8)59 gateCenters = gates60 lampCenter = CGPoint(x: gates.last?.x ?? size.width / 2, y: switchY - rowHeight * rows)61 }6263 /// Point where the wire leaves a switch or a gate (its top edge).64 func outlet(_ signal: Engine.Signal) -> CGPoint {65 switch signal {66 case .input(let i): CGPoint(x: switchCenters[i].x, y: switchCenters[i].y - Self.switchSize.height / 2)67 case .gate(let g): CGPoint(x: gateCenters[g].x, y: gateCenters[g].y - Self.gateSize.height / 2)68 }69 }7071 /// Point where input `k` enters gate `g` (its bottom edge).72 func inlet(gate g: Int, input k: Int) -> CGPoint {73 let count = puzzle.gates[g].inputs.count74 let dx: CGFloat = count == 1 ? 0 : (k == 0 ? -17 : 17)75 return CGPoint(x: gateCenters[g].x + dx, y: gateCenters[g].y + Self.gateSize.height / 2)76 }77}7879struct LogicGatesMissionView: View {80 typealias Engine = LogicGatesEngine81 let mission: ResolvedMission82 let onFinish: (MissionOutcome) -> Void83 @Environment(\.accessibilityReduceMotion) private var reduceMotion8485 @State private var round = 086 @State private var puzzle: Engine.Puzzle87 @State private var switches: [Bool]88 @State private var mistakes = 089 @State private var started = Date()90 @State private var solved = false91 @State private var wrongMessage: String?92 @State private var shakes = 093 @State private var focusedKind: Engine.GateKind?94 @State private var finished = false9596 init(mission: ResolvedMission, onFinish: @escaping (MissionOutcome) -> Void) {97 self.mission = mission; self.onFinish = onFinish98 let first = Engine.generate(level: mission.level, round: 0, seed: mission.seed)99 _puzzle = State(initialValue: first)100 _switches = State(initialValue: first.initialSwitches)101 }102103 private var values: [Bool] { Engine.evaluate(puzzle, switches: switches) }104 private var lampOn: Bool { values.last ?? false }105 private static let letters = ["A", "B", "C", "D", "E"]106107 var body: some View {108 MissionScaffold(instruction: puzzle.target ? String(localized: "Flip the switches until the lamp is ON, then check.") : String(localized: "Careful: this time the lamp must be OFF. Flip the switches, then check."),109 round: round + 1, totalRounds: mission.rounds) {110 VStack(spacing: 8) {111 GeometryReader { geo in circuit(CircuitLayout(puzzle: puzzle, size: geo.size)) }112 .frame(minHeight: 220)113 .modifier(ShakeEffect(animatableData: CGFloat(shakes)))114 .id(round)115 .transition(.opacity)116 legend117 Group {118 if solved {119 Label("Correct", systemImage: "checkmark.circle.fill").foregroundStyle(Theme.success)120 } else if let wrongMessage {121 Label(wrongMessage, systemImage: "xmark.octagon.fill").foregroundStyle(Theme.danger)122 } else {123 Text(" ")124 }125 }126 .font(.orixCaption).frame(minHeight: 18).accessibilityIdentifier("logic.feedback")127 Button("Check") { submit() }128 .buttonStyle(PrimaryButtonStyle()).disabled(solved).accessibilityIdentifier("logic.submit")129 }130 }131 .onAppear { started = Date() }132 }133134 // MARK: Circuit135136 private func circuit(_ layout: CircuitLayout) -> some View {137 let values = values138 func isOn(_ signal: Engine.Signal) -> Bool {139 switch signal { case .input(let i): switches[i]; case .gate(let g): values[g] }140 }141 let gold = Theme.gold142 return ZStack {143 Canvas { ctx, _ in144 func wire(_ points: [CGPoint], on: Bool) {145 var path = Path()146 path.addLines(points)147 if on {148 // On: thick, solid, glowing.149 ctx.stroke(path, with: .color(gold.opacity(0.28)), style: StrokeStyle(lineWidth: 11, lineCap: .round, lineJoin: .round))150 ctx.stroke(path, with: .color(gold), style: StrokeStyle(lineWidth: 4.5, lineCap: .round, lineJoin: .round))151 } else {152 // Off: thin and dashed, so the state never depends on colour alone.153 ctx.stroke(path, with: .color(.white.opacity(0.42)), style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round, dash: [3, 6]))154 }155 }156 for (g, gate) in puzzle.gates.enumerated() {157 for (k, signal) in gate.inputs.enumerated() {158 let from = layout.outlet(signal), to = layout.inlet(gate: g, input: k)159 let bendY = to.y + min(layout.gap / 2, 18)160 wire([from, CGPoint(x: from.x, y: bendY), CGPoint(x: to.x, y: bendY), to], on: isOn(signal))161 }162 }163 if !puzzle.gates.isEmpty {164 let from = layout.outlet(.gate(puzzle.gates.count - 1))165 wire([from, CGPoint(x: layout.lampCenter.x, y: layout.lampCenter.y + CircuitLayout.lampSize / 2)], on: lampOn)166 }167 }168 .animation(nil, value: switches)169 .accessibilityHidden(true)170171 lamp(labelOnLeft: layout.lampCenter.x > layout.switchCenters.map(\.x).reduce(0, +) / CGFloat(max(layout.switchCenters.count, 1)) + 1).position(layout.lampCenter)172 ForEach(puzzle.gates.indices, id: \.self) { g in173 gateView(puzzle.gates[g].kind, on: values[g]).position(layout.gateCenters[g])174 }175 ForEach(0..<puzzle.switchCount, id: \.self) { i in176 switchView(i).position(layout.switchCenters[i])177 }178 }179 }180181 private func lamp(labelOnLeft: Bool) -> some View {182 let matches = lampOn == puzzle.target183 return ZStack {184 Circle().fill(lampOn ? AnyShapeStyle(RadialGradient(colors: [Theme.peach, Theme.gold, Theme.sunrise], center: .center, startRadius: 2, endRadius: 36)) : AnyShapeStyle(Theme.deepIndigo))185 .overlay(Circle().strokeBorder(lampOn ? Theme.peach : Color.white.opacity(0.35), style: StrokeStyle(lineWidth: 2, dash: lampOn ? [] : [3, 5])))186 .shadow(color: lampOn ? Theme.gold.opacity(0.85) : .clear, radius: 22)187 Image(systemName: lampOn ? "lightbulb.max.fill" : "lightbulb.slash")188 .font(.system(size: 25, weight: .semibold)).foregroundStyle(lampOn ? Theme.midnight : Theme.textSecondary)189 }190 .frame(width: CircuitLayout.lampSize, height: CircuitLayout.lampSize)191 .overlay(alignment: labelOnLeft ? .trailing : .leading) {192 VStack(alignment: labelOnLeft ? .trailing : .leading, spacing: 2) {193 Text(lampOn ? "Lamp ON" : "Lamp OFF").font(.orixHeadline).foregroundStyle(lampOn ? Theme.gold : Theme.textSecondary)194 Label(puzzle.target ? "Goal: ON" : "Goal: OFF", systemImage: matches ? "checkmark.circle.fill" : "target")195 .font(.orixCaption).foregroundStyle(matches ? Theme.success : Theme.textTertiary)196 }197 .fixedSize().offset(x: (CircuitLayout.lampSize + 12) * (labelOnLeft ? -1 : 1))198 }199 .animation(reduceMotion ? nil : .snappy(duration: 0.2), value: lampOn)200 .accessibilityElement(children: .ignore)201 .accessibilityLabel("Lamp")202 .accessibilityValue(lampOn ? (puzzle.target ? "On. Goal reached." : "On. It must be off.") : (puzzle.target ? "Off. It must be on." : "Off. Goal reached."))203 .accessibilityIdentifier("logic.lamp")204 }205206 private func gateView(_ kind: Engine.GateKind, on: Bool) -> some View {207 Button {208 focusedKind = focusedKind == kind ? nil : kind; Haptics.play(.selection)209 } label: {210 VStack(spacing: 0) {211 Text(kind.name).font(.system(size: 16, weight: .bold, design: .rounded))212 Text(on ? "on" : "off").font(.system(size: 10, weight: .semibold, design: .rounded)).foregroundStyle(on ? Theme.gold : Theme.textTertiary)213 }214 .foregroundStyle(Theme.textPrimary)215 .frame(width: CircuitLayout.gateSize.width, height: CircuitLayout.gateSize.height)216 .background(Theme.deepIndigo.mix(with: Theme.indigo, by: 0.6), in: RoundedRectangle(cornerRadius: 14, style: .continuous))217 .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous)218 .strokeBorder(on ? Theme.gold : Color.white.opacity(0.35), lineWidth: on ? 2.5 : 1.2))219 .overlay(RoundedRectangle(cornerRadius: 17, style: .continuous).strokeBorder(Theme.azure, lineWidth: 2).padding(-4).opacity(focusedKind == kind ? 1 : 0))220 .shadow(color: on ? Theme.gold.opacity(0.4) : .clear, radius: 8)221 }222 .buttonStyle(.plain)223 .accessibilityLabel("\(kind.name) gate")224 .accessibilityValue(on ? "Output on" : "Output off")225 .accessibilityHint("\(kind.name): \(kind.rule)")226 }227228 private func switchView(_ i: Int) -> some View {229 let on = switches[i]230 let letter = Self.letters[i % Self.letters.count]231 return Button {232 guard !solved else { return }233 switches[i].toggle()234 wrongMessage = nil235 Haptics.play(.selection); SoundFX.play(.tap)236 } label: {237 VStack(spacing: 1) {238 Text(letter).font(.system(size: 13, weight: .bold, design: .rounded)).opacity(0.75)239 Image(systemName: on ? "power.circle.fill" : "power.circle").font(.system(size: 18, weight: .semibold))240 Text(on ? "ON" : "OFF").font(.system(size: 11, weight: .heavy, design: .rounded))241 }242 .foregroundStyle(on ? Theme.midnight : Theme.textPrimary)243 .frame(width: CircuitLayout.switchSize.width, height: CircuitLayout.switchSize.height)244 .background(on ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(Theme.deepIndigo.mix(with: Theme.indigo, by: 0.5)), in: RoundedRectangle(cornerRadius: 16, style: .continuous))245 .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(on ? Theme.peach : Color.white.opacity(0.35), lineWidth: 1.5))246 .shadow(color: on ? Theme.sunrise.opacity(0.5) : .clear, radius: 10)247 .contentShape(Rectangle())248 }249 .buttonStyle(.plain)250 .accessibilityLabel("Switch \(letter)")251 .accessibilityValue(on ? "On" : "Off")252 .accessibilityAddTraits(.isToggle)253 .accessibilityIdentifier("logic.switch.\(i)")254 }255256 private var legend: some View {257 VStack(alignment: .leading, spacing: 4) {258 ForEach([Engine.GateKind.and, .or, .xor, .not].filter(puzzle.kinds.contains), id: \.self) { kind in259 HStack(alignment: .firstTextBaseline, spacing: 8) {260 Text(kind.name).font(.system(size: 12, weight: .bold, design: .rounded))261 .frame(width: 40, height: 20).background(focusedKind == kind ? Theme.azure.opacity(0.5) : Theme.surfaceRaised, in: RoundedRectangle(cornerRadius: 7, style: .continuous))262 Text(kind.rule).font(.orixCaption).foregroundStyle(focusedKind == kind ? Theme.textPrimary : Theme.textSecondary)263 .fixedSize(horizontal: false, vertical: true)264 }265 .accessibilityElement(children: .ignore)266 .accessibilityLabel("\(kind.name): \(kind.rule)")267 }268 HStack(spacing: 14) {269 HStack(spacing: 6) {270 Capsule().fill(Theme.gold).frame(width: 26, height: 4.5)271 Text("thick line: on")272 }273 HStack(spacing: 6) {274 Line().stroke(.white.opacity(0.5), style: StrokeStyle(lineWidth: 2, lineCap: .round, dash: [3, 6])).frame(width: 26, height: 2)275 Text("dotted line: off")276 }277 }278 .font(.system(size: 11, weight: .medium, design: .rounded)).foregroundStyle(Theme.textTertiary)279 .accessibilityElement(children: .ignore).accessibilityLabel("Thick lines carry an on signal, dotted lines an off signal.")280 }281 .frame(maxWidth: .infinity, alignment: .leading)282 .glassCard(padding: 10, radius: 18)283 .accessibilityIdentifier("logic.legend")284 }285286 // MARK: Logic287288 private func submit() {289 guard !solved, !finished else { return }290 if Engine.validate(puzzle, answer: switches) {291 solved = true; wrongMessage = nil292 Haptics.play(.success); SoundFX.play(.correct)293 Task {294 try? await Task.sleep(for: .milliseconds(900))295 advance()296 }297 } else {298 mistakes += 1299 wrongMessage = puzzle.target ? String(localized: "Not yet: the lamp is still off.") : String(localized: "Not yet: the lamp is still on.")300 Haptics.play(.failure); SoundFX.play(.wrong)301 if reduceMotion { shakes += 1 } else { withAnimation(.linear(duration: 0.4)) { shakes += 1 } }302 }303 }304305 private func advance() {306 guard !finished else { return }307 if round + 1 >= mission.rounds {308 finished = true309 onFinish(MissionOutcome(result: .completed, mistakes: mistakes, duration: Date().timeIntervalSince(started), rounds: mission.rounds))310 return311 }312 let next = Engine.generate(level: mission.level, round: round + 1, seed: mission.seed)313 withAnimation(reduceMotion ? nil : .smooth) {314 round += 1; puzzle = next; switches = next.initialSwitches315 solved = false; wrongMessage = nil; focusedKind = nil316 }317 }318}319320private nonisolated struct Line: Shape {321 func path(in rect: CGRect) -> Path {322 var p = Path()323 p.move(to: CGPoint(x: rect.minX, y: rect.midY)); p.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))324 return p325 }326}327328/// Horizontal shake for a wrong answer; `animatableData` counts shakes.329private nonisolated struct ShakeEffect: GeometryEffect {330 var animatableData: CGFloat331 func effectValue(size: CGSize) -> ProjectionTransform {332 ProjectionTransform(CGAffineTransform(translationX: 8 * sin(animatableData * .pi * 4), y: 0))333 }334}335