Repository Public License
1// ORIX Alarm2// File: App/Features/Missions/WordScrambleMissionView.swift3// Description: Word Scramble mission: tap letter tiles to rebuild an English or French word; shuffle, and a first-letter hint that costs a mistake.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910struct WordScrambleMissionView: View {11 let mission: ResolvedMission12 let onFinish: (MissionOutcome) -> Void1314 @Environment(\.accessibilityReduceMotion) private var reduceMotion15 @Namespace private var tiles16 @State private var round = 017 /// Tile identifiers (indices into `puzzle.scrambled`) in the order they are laid out in the tray.18 @State private var trayOrder: [Int] = []19 /// Tile placed in each answer slot.20 @State private var slots: [Int?] = []21 @State private var loadedRound = -122 @State private var hintUsed = false23 @State private var mistakes = 024 @State private var feedback: PuzzleFeedback = .none25 @State private var shake = 026 @State private var locked = false27 @State private var finished = false28 @State private var startedAt = Date()2930 private var puzzle: WordScrambleEngine.Puzzle {31 WordScrambleEngine.generate(level: mission.level, round: round, seed: mission.seed, language: mission.step.language)32 }3334 var body: some View {35 let puzzle = puzzle36 MissionScaffold(instruction: String(localized: "Tap the letters in order to rebuild the word."),37 round: round + 1, totalRounds: mission.puzzleRounds) {38 VStack(spacing: 14) {39 PuzzleRoundProgress(current: round, total: mission.puzzleRounds, currentSolved: feedback == .correct)40 HStack {41 Label(puzzle.language == .french ? "Français" : "English", systemImage: "globe")42 Spacer()43 Label("\(puzzle.word.count) letters", systemImage: "textformat.abc")44 }45 .font(.orixCaption).foregroundStyle(Theme.textSecondary)46 .accessibilityElement(children: .combine)47 .accessibilityIdentifier("word.info")4849 if loadedRound == round {50 answerCard(puzzle)51 .modifier(PuzzleShake(trigger: shake, enabled: !reduceMotion))52 Spacer(minLength: 0)53 tray(puzzle)54 Spacer(minLength: 0)55 HStack(spacing: 10) {56 PuzzleAuxButton(title: "Shuffle", symbol: "shuffle", isEnabled: !locked) { shuffleTray() }57 .accessibilityIdentifier("word.shuffle")58 PuzzleAuxButton(title: "Clear", symbol: "arrow.uturn.backward", isEnabled: !locked && slots.indices.contains { slots[$0] != nil && !isHintSlot($0) }) { clear() }59 .accessibilityIdentifier("word.clear")60 PuzzleAuxButton(title: "Hint", symbol: "lightbulb", isEnabled: !locked && !hintUsed) { revealFirstLetter(puzzle) }61 .accessibilityLabel("Reveal the first letter")62 .accessibilityHint("Counts as a mistake")63 .accessibilityIdentifier("word.hint")64 }65 } else {66 Spacer()67 }68 }69 }70 .onAppear { startedAt = Date(); load(puzzle) }71 }7273 // MARK: Layout7475 /// Rows of at most six tiles, balanced (7 → 4 + 3, 9 → 5 + 4).76 private func rows(_ count: Int) -> [Range<Int>] {77 guard count > 6 else { return [0..<count] }78 let first = (count + 1) / 279 return [0..<first, first..<count]80 }8182 private func tileSide(count: Int, width: CGFloat) -> CGFloat {83 let perRow = CGFloat(rows(count).map(\.count).max() ?? 1)84 return min(64, max(40, (width - 8 * (perRow - 1)) / perRow))85 }8687 private func isHintSlot(_ slot: Int) -> Bool { hintUsed && slot == 0 }8889 private func letter(_ puzzle: WordScrambleEngine.Puzzle, _ tile: Int) -> String { String(puzzle.scrambled[tile]).uppercased() }9091 private func answerCard(_ puzzle: WordScrambleEngine.Puzzle) -> some View {92 VStack(spacing: 10) {93 GeometryReader { proxy in94 let side = tileSide(count: slots.count, width: proxy.size.width)95 VStack(spacing: 8) {96 ForEach(rows(slots.count), id: \.lowerBound) { row in97 HStack(spacing: 8) { ForEach(row, id: \.self) { slotView(puzzle, slot: $0, side: side) } }98 }99 }100 .frame(maxWidth: .infinity, maxHeight: .infinity)101 }102 .frame(height: slots.count > 6 ? 136 : 64)103 PuzzleStatusLine(text: statusText, feedback: feedback).accessibilityIdentifier("word.status")104 }105 .frame(maxWidth: .infinity)106 .glassCard(padding: 14, tint: feedback == .none ? nil : feedback.tint)107 .animation(.smooth(duration: 0.25), value: feedback)108 }109110 private var statusText: String {111 switch feedback {112 case .correct: String(localized: "Correct")113 case .wrong: String(localized: "Not a match. Try again.")114 case .none: hintUsed ? String(localized: "First letter revealed") : String(localized: "Tap a placed letter to remove it")115 }116 }117118 private func slotView(_ puzzle: WordScrambleEngine.Puzzle, slot: Int, side: CGFloat) -> some View {119 let shape = RoundedRectangle(cornerRadius: side * 0.26, style: .continuous)120 return ZStack {121 shape.fill(Color.white.opacity(0.04))122 shape.strokeBorder(Color.white.opacity(0.22), style: StrokeStyle(lineWidth: 1.5, dash: [5, 4]))123 if let tile = slots[slot] {124 Button { remove(slot) } label: {125 tileFace(letter(puzzle, tile), side: side, style: isHintSlot(slot) ? .hint : .placed)126 }127 .buttonStyle(.plain)128 .matchedGeometryEffect(id: tile, in: tiles)129 .accessibilityLabel(String(localized: "Position \(slot + 1), letter \(letter(puzzle, tile))"))130 .accessibilityHint(isHintSlot(slot) ? String(localized: "Revealed by the hint") : String(localized: "Removes the letter"))131 .accessibilityIdentifier("word.slot.\(slot)")132 } else {133 Color.clear.accessibilityElement().accessibilityLabel(String(localized: "Position \(slot + 1), empty")).accessibilityIdentifier("word.slot.\(slot)")134 }135 }136 .frame(width: side, height: side)137 }138139 private func tray(_ puzzle: WordScrambleEngine.Puzzle) -> some View {140 GeometryReader { proxy in141 let side = tileSide(count: trayOrder.count, width: proxy.size.width)142 VStack(spacing: 8) {143 ForEach(rows(trayOrder.count), id: \.lowerBound) { row in144 HStack(spacing: 8) {145 ForEach(row, id: \.self) { position in146 let tile = trayOrder[position]147 ZStack {148 RoundedRectangle(cornerRadius: side * 0.26, style: .continuous).fill(Color.white.opacity(0.03))149 if !slots.contains(tile) {150 Button { place(puzzle, tile) } label: { tileFace(letter(puzzle, tile), side: side, style: .tray) }151 .buttonStyle(.plain)152 .matchedGeometryEffect(id: tile, in: tiles)153 .accessibilityLabel(String(localized: "Letter \(letter(puzzle, tile))"))154 .accessibilityIdentifier("word.tile.\(tile)")155 }156 }157 .frame(width: side, height: side)158 }159 }160 }161 }162 .frame(maxWidth: .infinity, maxHeight: .infinity)163 }164 .frame(height: trayOrder.count > 6 ? 136 : 64)165 }166167 private enum TileStyle { case tray, placed, hint }168169 private func tileFace(_ text: String, side: CGFloat, style: TileStyle) -> some View {170 let shape = RoundedRectangle(cornerRadius: side * 0.26, style: .continuous)171 return ZStack(alignment: .topTrailing) {172 Text(text).font(.system(size: side * 0.5, weight: .bold, design: .rounded))173 .foregroundStyle(style == .tray ? Theme.textPrimary : Theme.midnight)174 .frame(width: side, height: side)175 if style == .hint { Image(systemName: "lightbulb.fill").font(.system(size: side * 0.2)).foregroundStyle(Theme.midnight.opacity(0.7)).padding(5) }176 }177 .background {178 switch style {179 case .tray: shape.fill(Theme.surfaceRaised).overlay(shape.strokeBorder(Color.white.opacity(0.3), lineWidth: 1))180 case .placed: shape.fill(feedback == .none ? AnyShapeStyle(Theme.sunriseGradient) : AnyShapeStyle(feedback.tint))181 case .hint: shape.fill(Theme.gold)182 }183 }184 .contentShape(shape)185 }186187 // MARK: Actions188189 private var motion: Animation? { reduceMotion ? nil : .snappy(duration: 0.24) }190191 private func load(_ puzzle: WordScrambleEngine.Puzzle) {192 trayOrder = Array(puzzle.scrambled.indices)193 slots = Array(repeating: nil, count: puzzle.scrambled.count)194 hintUsed = false; feedback = .none; locked = false195 loadedRound = round196 }197198 private func clearWrongState() {199 guard feedback == .wrong else { return }200 feedback = .none201 }202203 private func place(_ puzzle: WordScrambleEngine.Puzzle, _ tile: Int) {204 guard !locked, !slots.contains(tile), let free = slots.firstIndex(where: { $0 == nil }) else { return }205 clearWrongState()206 withAnimation(motion) { slots[free] = tile }207 Haptics.play(.tick); SoundFX.play(.tap)208 if !slots.contains(where: { $0 == nil }) { evaluate(puzzle) }209 }210211 private func remove(_ slot: Int) {212 guard !locked, !isHintSlot(slot), slots[slot] != nil else { return }213 clearWrongState()214 withAnimation(motion) { slots[slot] = nil }215 Haptics.play(.tick)216 }217218 private func clear() {219 clearWrongState()220 withAnimation(motion) { for slot in slots.indices where !isHintSlot(slot) { slots[slot] = nil } }221 Haptics.play(.tick)222 }223224 private func shuffleTray() {225 guard trayOrder.count > 1 else { return }226 let before = trayOrder227 for _ in 0..<8 where trayOrder == before { trayOrder.shuffle() }228 let shuffled = trayOrder229 trayOrder = before230 withAnimation(motion) { trayOrder = shuffled }231 Haptics.play(.selection)232 }233234 /// Puts the first letter of the word in the first slot and locks it. Counts as a mistake.235 private func revealFirstLetter(_ puzzle: WordScrambleEngine.Puzzle) {236 guard !locked, !hintUsed, let first = puzzle.word.first else { return }237 clearWrongState()238 mistakes += 1239 let candidates = puzzle.scrambled.indices.filter { puzzle.scrambled[$0] == first }240 // Prefer a tile already in the first slot, then one still in the tray, then one placed elsewhere.241 guard let tile = candidates.first(where: { slots[0] == $0 }) ?? candidates.first(where: { !slots.contains($0) }) ?? candidates.first else { return }242 withAnimation(motion) {243 if let previous = slots.firstIndex(of: tile) { slots[previous] = nil }244 slots[0] = tile245 hintUsed = true246 }247 Haptics.play(.warning)248 AccessibilityNotification.Announcement(String(localized: "The first letter is \(String(first).uppercased())")).post()249 if !slots.contains(where: { $0 == nil }) { evaluate(puzzle) }250 }251252 private func evaluate(_ puzzle: WordScrambleEngine.Puzzle) {253 let answer = String(slots.compactMap { $0 }.map { puzzle.scrambled[$0] })254 if WordScrambleEngine.validate(puzzle, answer: answer) {255 locked = true256 feedback = .correct257 feedback.signal(announcement: String(localized: "Correct"))258 Task {259 guard await PuzzleTiming.pause(0.9), !finished else { return }260 if round + 1 >= mission.puzzleRounds {261 finished = true262 onFinish(MissionOutcome(result: .completed, mistakes: mistakes, duration: Date().timeIntervalSince(startedAt), rounds: mission.puzzleRounds))263 } else {264 withAnimation(reduceMotion ? nil : .smooth(duration: 0.3)) {265 round += 1266 load(self.puzzle)267 }268 }269 }270 } else {271 mistakes += 1272 feedback = .wrong273 withAnimation(.linear(duration: 0.4)) { shake += 1 }274 feedback.signal(announcement: String(localized: "Not a match. Try again."))275 let attempt = mistakes276 Task {277 // The letters go back to the tray after a moment so the player can start over.278 guard await PuzzleTiming.pause(1.0), attempt == mistakes, feedback == .wrong else { return }279 feedback = .none280 withAnimation(motion) { for slot in slots.indices where !isHintSlot(slot) { slots[slot] = nil } }281 }282 }283 }284}285