SPB Git

Repository Public License

MemoryMatrixMissionView.swift 12.5 KB 262 lines swift

1// ORIX Alarm2// File: App/Features/Missions/MemoryMatrixMissionView.swift3// Description: Memory Matrix mission: lit cells are shown (all at once, or one after another), hidden, then reproduced by the player.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct MemoryMatrixMissionView: View {11    let mission: ResolvedMission12    let onFinish: (MissionOutcome) -> Void1314    private enum Phase: Equatable { case showing, input, solved, failed }1516    @Environment(\.accessibilityReduceMotion) private var reduceMotion17    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver18    @State private var round = 019    @State private var phase: Phase = .showing20    /// Cells lit right now during the presentation.21    @State private var lit: Set<Int> = []22    /// `true` when the whole pattern stays on screen until the player says they are ready (VoiceOver).23    @State private var waitingForReady = false24    @State private var selection: [Int] = []25    @State private var mistakes = 026    @State private var shake = 027    @State private var playToken = 028    @State private var finished = false29    @State private var startedAt = Date()3031    private var puzzle: MemoryMatrixEngine.Puzzle { MemoryMatrixEngine.generate(level: mission.level, round: round, seed: mission.seed) }3233    var body: some View {34        let puzzle = puzzle35        MissionScaffold(instruction: puzzle.sequential ? String(localized: "Watch the order, then tap the cells in the same order.")36                                                       : String(localized: "Memorise the lit cells, then tap them."),37                        round: round + 1, totalRounds: mission.puzzleRounds) {38            VStack(spacing: 14) {39                PuzzleRoundProgress(current: round, total: mission.puzzleRounds, currentSolved: phase == .solved)40                HStack(spacing: 8) {41                    Label(puzzle.sequential ? "Order matters" : "Any order", systemImage: puzzle.sequential ? "list.number" : "square.grid.3x3.fill")42                    Spacer()43                    Label("\(puzzle.cells.count) cells", systemImage: "sparkles")44                }45                .font(.orixCaption).foregroundStyle(Theme.textSecondary)46                grid(puzzle)47                    .modifier(PuzzleShake(trigger: shake, enabled: !reduceMotion))48                PuzzleStatusLine(text: statusText(puzzle), feedback: phase == .solved ? .correct : (phase == .failed ? .wrong : .none))49                    .accessibilityIdentifier("memory.status")50                footer(puzzle)51            }52        }53        .onAppear { startedAt = Date() }54        .task(id: playToken) { await present() }55    }5657    // MARK: Grid5859    private func grid(_ puzzle: MemoryMatrixEngine.Puzzle) -> some View {60        GeometryReader { proxy in61            let spacing: CGFloat = puzzle.size >= 5 ? 8 : 1062            let side = min(proxy.size.width, proxy.size.height)63            let cell = (side - spacing * CGFloat(puzzle.size - 1)) / CGFloat(puzzle.size)64            VStack(spacing: spacing) {65                ForEach(0..<puzzle.size, id: \.self) { row in66                    HStack(spacing: spacing) {67                        ForEach(0..<puzzle.size, id: \.self) { column in68                            cellView(puzzle, index: row * puzzle.size + column, side: cell)69                        }70                    }71                }72            }73            .frame(width: side, height: side)74            .frame(maxWidth: .infinity, maxHeight: .infinity)75        }76        .aspectRatio(1, contentMode: .fit)77        .frame(maxHeight: .infinity)78    }7980    private enum CellState { case idle, lit, selected, right, wrong, missed }8182    private func state(_ puzzle: MemoryMatrixEngine.Puzzle, _ index: Int) -> CellState {83        switch phase {84        case .showing: return lit.contains(index) ? .lit : .idle85        case .input: return selection.contains(index) ? .selected : .idle86        case .solved: return puzzle.cells.contains(index) ? .right : .idle87        case .failed:88            if selection.contains(index) {89                let ok = puzzle.sequential ? puzzle.cells.firstIndex(of: index) == selection.firstIndex(of: index) : puzzle.cells.contains(index)90                return ok ? .right : .wrong91            }92            return puzzle.cells.contains(index) ? .missed : .idle93        }94    }9596    private func cellView(_ puzzle: MemoryMatrixEngine.Puzzle, index: Int, side: CGFloat) -> some View {97        let state = state(puzzle, index)98        let shape = RoundedRectangle(cornerRadius: side * 0.24, style: .continuous)99        let order: Int? = {100            guard puzzle.sequential else { return nil }101            switch state {102            case .selected, .right, .wrong: return selection.firstIndex(of: index).map { $0 + 1 } ?? puzzle.cells.firstIndex(of: index).map { $0 + 1 }103            case .lit: return waitingForReady ? puzzle.cells.firstIndex(of: index).map { $0 + 1 } : nil104            case .missed: return puzzle.cells.firstIndex(of: index).map { $0 + 1 }105            case .idle: return nil106            }107        }()108        return Button { tap(puzzle, index) } label: {109            ZStack {110                switch state {111                case .idle: shape.fill(Theme.surfaceRaised)112                case .lit: shape.fill(Theme.sunriseGradient).shadow(color: Theme.sunrise.opacity(0.7), radius: 14)113                case .selected: shape.fill(Theme.nightGradient)114                case .right: shape.fill(Theme.success.opacity(0.85))115                case .wrong: shape.fill(Theme.danger.opacity(0.85))116                case .missed: shape.fill(Theme.gold.opacity(0.16))117                }118                shape.strokeBorder(state == .missed ? Theme.gold : Color.white.opacity(state == .idle ? 0.12 : 0.4),119                                   style: StrokeStyle(lineWidth: state == .missed ? 2 : 1, dash: state == .missed ? [6, 5] : []))120                Group {121                    if let order {122                        Text("\(order)").font(.system(size: side * 0.4, weight: .bold, design: .rounded)).monospacedDigit()123                    } else {124                        switch state {125                        case .selected: Image(systemName: "circle.fill").font(.system(size: side * 0.2))126                        case .right: Image(systemName: "checkmark").font(.system(size: side * 0.34, weight: .bold))127                        case .wrong: Image(systemName: "xmark").font(.system(size: side * 0.34, weight: .bold))128                        case .lit: Image(systemName: "sun.max.fill").font(.system(size: side * 0.36))129                        case .idle, .missed: EmptyView()130                        }131                    }132                }133                .foregroundStyle(state == .lit ? Theme.midnight : (state == .missed ? Theme.gold : .white))134            }135            .frame(width: side, height: side)136            .contentShape(shape)137            .scaleEffect(state == .lit && !reduceMotion ? 1.04 : 1)138        }139        .buttonStyle(.plain)140        .animation(reduceMotion ? nil : .snappy(duration: 0.2), value: state)141        .allowsHitTesting(phase == .input)142        .accessibilityLabel(accessibilityLabel(puzzle, index, state, order))143        .accessibilityIdentifier("memory.cell.\(index)")144    }145146    private func accessibilityLabel(_ puzzle: MemoryMatrixEngine.Puzzle, _ index: Int, _ state: CellState, _ order: Int?) -> String {147        let place = String(localized: "Row \(puzzle.row(of: index) + 1), column \(puzzle.column(of: index) + 1)")148        let suffix: String149        switch state {150        case .idle: return place151        case .lit: suffix = order.map { String(localized: "lit, number \($0)") } ?? String(localized: "lit")152        case .selected: suffix = order.map { String(localized: "selected, number \($0)") } ?? String(localized: "selected")153        case .right: suffix = String(localized: "correct")154        case .wrong: suffix = String(localized: "wrong")155        case .missed: suffix = String(localized: "missed")156        }157        return "\(place), \(suffix)"158    }159160    private func statusText(_ puzzle: MemoryMatrixEngine.Puzzle) -> String {161        switch phase {162        case .showing: waitingForReady ? String(localized: "Explore the grid, then continue.") : (puzzle.sequential ? String(localized: "Watch the order…") : String(localized: "Memorise…"))163        case .input: String(localized: "\(selection.count) of \(puzzle.cells.count) selected")164        case .solved: String(localized: "Correct")165        case .failed: String(localized: "Not quite. Watch again.")166        }167    }168169    @ViewBuilder170    private func footer(_ puzzle: MemoryMatrixEngine.Puzzle) -> some View {171        if phase == .showing && waitingForReady {172            Button("Hide and answer") {173                lit = []; waitingForReady = false174                phase = .input175            }176            .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("memory.ready")177        } else {178            HStack(spacing: 10) {179                PuzzleAuxButton(title: "Clear", symbol: "arrow.uturn.backward", isEnabled: phase == .input && !selection.isEmpty) {180                    selection = []; Haptics.play(.tick)181                }182                .accessibilityIdentifier("memory.clear")183                PuzzleAuxButton(title: "Show again", symbol: "eye", isEnabled: phase == .input) {184                    mistakes += 1; playToken += 1185                }186                .accessibilityHint("Counts as a mistake")187                .accessibilityIdentifier("memory.replay")188            }189        }190    }191192    // MARK: Flow193194    private func present() async {195        let puzzle = puzzle196        withAnimation(reduceMotion ? nil : .smooth(duration: 0.25)) { phase = .showing; selection = []; lit = [] }197        waitingForReady = false198        guard await PuzzleTiming.pause(0.55) else { return }199        if voiceOver {200            // A brief flash cannot be explored with VoiceOver: the pattern stays until the player is ready.201            lit = Set(puzzle.cells); waitingForReady = true202            AccessibilityNotification.Announcement(String(localized: "\(puzzle.cells.count) cells are lit. Explore the grid, then choose Hide and answer.")).post()203            return204        }205        if puzzle.sequential {206            for cell in puzzle.cells {207                lit = [cell]; Haptics.play(.tick)208                guard await PuzzleTiming.pause(puzzle.displayDuration) else { return }209                lit = []210                guard await PuzzleTiming.pause(0.16) else { return }211            }212        } else {213            lit = Set(puzzle.cells); Haptics.play(.tick)214            guard await PuzzleTiming.pause(puzzle.displayDuration) else { return }215            lit = []216        }217        guard await PuzzleTiming.pause(0.15) else { return }218        phase = .input219    }220221    private func tap(_ puzzle: MemoryMatrixEngine.Puzzle, _ index: Int) {222        guard phase == .input else { return }223        if puzzle.sequential {224            guard !selection.contains(index) else { return }225            selection.append(index)226            Haptics.play(.tick); SoundFX.play(.tap)227            if !MemoryMatrixEngine.isCorrectPrefix(puzzle, partial: selection) { fail() }228            else if selection.count == puzzle.cells.count { conclude(puzzle) }229        } else {230            if let position = selection.firstIndex(of: index) { selection.remove(at: position) } else { selection.append(index) }231            Haptics.play(.tick); SoundFX.play(.tap)232            if selection.count == puzzle.cells.count { conclude(puzzle) }233        }234    }235236    private func conclude(_ puzzle: MemoryMatrixEngine.Puzzle) {237        guard MemoryMatrixEngine.validate(puzzle, answer: selection) else { fail(); return }238        phase = .solved239        PuzzleFeedback.correct.signal(announcement: String(localized: "Correct"))240        Task {241            guard await PuzzleTiming.pause(0.9), !finished else { return }242            if round + 1 >= mission.puzzleRounds {243                finished = true244                onFinish(MissionOutcome(result: .completed, mistakes: mistakes, duration: Date().timeIntervalSince(startedAt), rounds: mission.puzzleRounds))245            } else {246                round += 1; playToken += 1247            }248        }249    }250251    private func fail() {252        mistakes += 1253        phase = .failed254        withAnimation(.linear(duration: 0.4)) { shake += 1 }255        PuzzleFeedback.wrong.signal(announcement: String(localized: "Not quite. The pattern is shown again."))256        Task {257            guard await PuzzleTiming.pause(1.5) else { return }258            playToken += 1259        }260    }261}262
Files main
Menu

Theme