SPB Git

Repository Public License

ColorSequenceMissionView.swift 9.2 KB 200 lines swift

1// ORIX Alarm2// File: App/Features/Missions/ColorSequenceMissionView.swift3// Description: Color Sequence mission: a growing sequence of panels (each with its own colour and shape) is played, then repeated by the player.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct ColorSequenceMissionView: View {11    let mission: ResolvedMission12    let onFinish: (MissionOutcome) -> Void1314    private enum Phase: Equatable { case playing, input, solved, failed }1516    /// A panel is identified by a colour and by a shape, so colour is never the only cue.17    private struct Panel {18        let name: String19        let symbol: String20        let color: Color21    }2223    private static let panels: [Panel] = [24        Panel(name: String(localized: "Circle"), symbol: "circle.fill", color: Theme.azure),25        Panel(name: String(localized: "Triangle"), symbol: "triangle.fill", color: Theme.ember),26        Panel(name: String(localized: "Square"), symbol: "square.fill", color: Theme.violet),27        Panel(name: String(localized: "Star"), symbol: "star.fill", color: Theme.gold),28        Panel(name: String(localized: "Diamond"), symbol: "diamond.fill", color: Theme.success),29        Panel(name: String(localized: "Hexagon"), symbol: "hexagon.fill", color: Theme.peach),30    ]3132    @Environment(\.accessibilityReduceMotion) private var reduceMotion33    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver34    @State private var round = 035    @State private var phase: Phase = .playing36    /// Panel lit right now (playback, or the player's last tap).37    @State private var active: Int?38    /// Position being played, for the progress pips.39    @State private var playhead = 040    @State private var entered: [Int] = []41    @State private var wrongPanel: Int?42    @State private var mistakes = 043    @State private var shake = 044    @State private var playToken = 045    @State private var flashToken = 046    @State private var finished = false47    @State private var startedAt = Date()4849    private var puzzle: ColorSequenceEngine.Puzzle { ColorSequenceEngine.generate(level: mission.level, round: round, seed: mission.seed) }5051    var body: some View {52        let puzzle = puzzle53        MissionScaffold(instruction: String(localized: "Watch the sequence, then repeat it in the same order."),54                        round: round + 1, totalRounds: mission.puzzleRounds) {55            VStack(spacing: 14) {56                PuzzleRoundProgress(current: round, total: mission.puzzleRounds, currentSolved: phase == .solved)57                pips(puzzle)58                panelGrid(puzzle)59                    .modifier(PuzzleShake(trigger: shake, enabled: !reduceMotion))60                PuzzleStatusLine(text: statusText(puzzle), feedback: phase == .solved ? .correct : (phase == .failed ? .wrong : .none))61                    .accessibilityIdentifier("color.status")62                PuzzleAuxButton(title: "Replay sequence", symbol: "play.circle", isEnabled: phase == .input) {63                    mistakes += 1; playToken += 164                }65                .accessibilityHint("Counts as a mistake")66                .accessibilityIdentifier("color.replay")67            }68        }69        .onAppear { startedAt = Date() }70        .task(id: playToken) { await play() }71    }7273    /// One pip per element of the sequence: filled as the sequence plays, then as the player repeats it.74    private func pips(_ puzzle: ColorSequenceEngine.Puzzle) -> some View {75        let filled = phase == .playing ? playhead : (phase == .solved ? puzzle.sequence.count : entered.count)76        return HStack(spacing: 6) {77            ForEach(0..<puzzle.sequence.count, id: \.self) { index in78                Circle()79                    .fill(index < filled ? AnyShapeStyle(phase == .playing ? Theme.gold : (phase == .failed ? Theme.danger : Theme.success)) : AnyShapeStyle(Theme.surfaceRaised))80                    .overlay(Circle().strokeBorder(Theme.hairline))81                    .frame(width: 12, height: 12)82            }83        }84        .frame(maxWidth: .infinity, minHeight: 16)85        .animation(reduceMotion ? nil : .snappy(duration: 0.15), value: filled)86        .accessibilityElement()87        .accessibilityLabel("Sequence")88        .accessibilityValue(phase == .playing ? String(localized: "\(puzzle.sequence.count) panels") : String(localized: "\(entered.count) of \(puzzle.sequence.count) repeated"))89    }9091    private func panelGrid(_ puzzle: ColorSequenceEngine.Puzzle) -> some View {92        let rows = puzzle.panelCount / 293        return VStack(spacing: 12) {94            ForEach(0..<rows, id: \.self) { row in95                HStack(spacing: 12) {96                    panelButton(puzzle, row * 2)97                    panelButton(puzzle, row * 2 + 1)98                }99            }100        }101        .frame(maxHeight: .infinity)102    }103104    private func panelButton(_ puzzle: ColorSequenceEngine.Puzzle, _ index: Int) -> some View {105        let panel = Self.panels[index]106        let isLit = active == index, isWrong = wrongPanel == index107        let shape = RoundedRectangle(cornerRadius: 28, style: .continuous)108        return Button { tap(puzzle, index) } label: {109            ZStack {110                shape.fill(panel.color.opacity(isLit ? 1 : 0.20))111                shape.strokeBorder(isWrong ? Theme.danger : panel.color.opacity(isLit ? 1 : 0.75), lineWidth: isWrong ? 4 : 2)112                Image(systemName: isWrong ? "xmark" : panel.symbol)113                    .font(.system(size: 52, weight: .bold))114                    .foregroundStyle(isWrong ? Theme.danger : (isLit ? Theme.midnight : panel.color))115            }116            .frame(maxWidth: .infinity, minHeight: 88, maxHeight: .infinity)117            .contentShape(shape)118            .shadow(color: panel.color.opacity(isLit ? 0.75 : 0), radius: 18)119            .scaleEffect(isLit && !reduceMotion ? 1.04 : 1)120        }121        .buttonStyle(.plain)122        .animation(reduceMotion ? nil : .easeOut(duration: 0.12), value: isLit)123        .allowsHitTesting(phase == .input)124        .accessibilityLabel(panel.name)125        .accessibilityValue(isLit ? String(localized: "lit") : (isWrong ? String(localized: "wrong") : ""))126        .accessibilityIdentifier("color.panel.\(index)")127    }128129    private func statusText(_ puzzle: ColorSequenceEngine.Puzzle) -> String {130        switch phase {131        case .playing: String(localized: "Watch… \(puzzle.sequence.count) panels")132        case .input: String(localized: "Your turn: \(entered.count) of \(puzzle.sequence.count)")133        case .solved: String(localized: "Correct")134        case .failed: String(localized: "Not quite. Watch again.")135        }136    }137138    // MARK: Flow139140    private func play() async {141        let puzzle = puzzle142        phase = .playing; entered = []; active = nil; wrongPanel = nil; playhead = 0143        if voiceOver {144            // The spoken sequence replaces the flashes, which VoiceOver cannot follow.145            let names = puzzle.sequence.map { Self.panels[$0].name }.joined(separator: ", ")146            AccessibilityNotification.Announcement(String(localized: "Sequence: \(names)")).post()147        }148        guard await PuzzleTiming.pause(0.7) else { return }149        for (position, panel) in puzzle.sequence.enumerated() {150            active = panel; playhead = position + 1151            Haptics.play(.tick)152            guard await PuzzleTiming.pause(puzzle.stepDuration) else { return }153            active = nil154            guard await PuzzleTiming.pause(max(puzzle.stepDuration * 0.4, 0.16)) else { return }155        }156        phase = .input157    }158159    private func tap(_ puzzle: ColorSequenceEngine.Puzzle, _ index: Int) {160        guard phase == .input else { return }161        entered.append(index)162        if ColorSequenceEngine.isCorrectPrefix(puzzle, partial: entered) {163            Haptics.play(.tick); SoundFX.play(.tap)164            flash(index)165            guard ColorSequenceEngine.validate(puzzle, answer: entered) else { return }166            phase = .solved167            PuzzleFeedback.correct.signal(announcement: String(localized: "Correct"))168            Task {169                guard await PuzzleTiming.pause(0.9), !finished else { return }170                if round + 1 >= mission.puzzleRounds {171                    finished = true172                    onFinish(MissionOutcome(result: .completed, mistakes: mistakes, duration: Date().timeIntervalSince(startedAt), rounds: mission.puzzleRounds))173                } else {174                    round += 1; playToken += 1175                }176            }177        } else {178            mistakes += 1179            phase = .failed; wrongPanel = index; active = nil180            withAnimation(.linear(duration: 0.4)) { shake += 1 }181            PuzzleFeedback.wrong.signal(announcement: String(localized: "Not quite. The sequence is played again."))182            Task {183                guard await PuzzleTiming.pause(1.2) else { return }184                playToken += 1185            }186        }187    }188189    /// Briefly lights the panel the player tapped.190    private func flash(_ index: Int) {191        flashToken += 1192        let token = flashToken193        active = index194        Task {195            guard await PuzzleTiming.pause(0.2), token == flashToken, phase != .playing else { return }196            active = nil197        }198    }199}200
Files main
Menu

Theme