Commit 3ee11e0eca
Unsigned
Layout: unified · split
DayByDay/Home/CategoryHubView.swift +1 −4
| @@ -18,10 +18,7 @@ struct CategoryHubView: View { | |||
| 18 | } | 18 | } |
| 19 | ForEach(category.games, id: \.self) { game in | 19 | ForEach(category.games, id: \.self) { game in |
| 20 | activity(game.title, systemImage: game.symbol, color: category.color) { | 20 | activity(game.title, systemImage: game.symbol, color: category.color) { |
| 21 | RoundView(source: category.questionSource(for: game), game: game) { | 21 | GameDestination(category: category, game: game) |
| 22 | ChoiceTile(item: $0) | ||
| 23 | } | ||
| 24 | .navigationTitle(game.title) | ||
| 25 | } | 22 | } |
| 26 | } | 23 | } |
| 27 | } | 24 | } |
DayByDay/Quiz/ChoiceTile.swift +16 −2
| @@ -109,16 +109,30 @@ struct ChoiceTile: View { | |||
| 109 | } | 109 | } |
| 110 | } | 110 | } |
| 111 | 111 | ||
| 112 | /// A pile for "Which has the most?": dots only, so the child compares amounts. | ||
| 113 | struct PileTile: View { | ||
| 114 | let item: QuizItem | ||
| 115 | |||
| 116 | var body: some View { | ||
| 117 | Dots(count: item.value(LearnNumber.self)!.numeral, size: 22) | ||
| 118 | .foregroundStyle(.white) | ||
| 119 | .frame(maxWidth: .infinity, maxHeight: .infinity) | ||
| 120 | .background(RoundedRectangle(cornerRadius: 32, style: .continuous).fill(Category.numbers.color)) | ||
| 121 | .contentShape(RoundedRectangle(cornerRadius: 32, style: .continuous)) | ||
| 122 | } | ||
| 123 | } | ||
| 124 | |||
| 112 | /// Solid dots for a quantity, in rows of five. | 125 | /// Solid dots for a quantity, in rows of five. |
| 113 | private struct Dots: View { | 126 | struct Dots: View { |
| 114 | let count: Int | 127 | let count: Int |
| 128 | var size: CGFloat = 16 | ||
| 115 | 129 | ||
| 116 | var body: some View { | 130 | var body: some View { |
| 117 | VStack(spacing: 6) { | 131 | VStack(spacing: 6) { |
| 118 | ForEach(Array(stride(from: 0, to: count, by: 5)), id: \.self) { start in | 132 | ForEach(Array(stride(from: 0, to: count, by: 5)), id: \.self) { start in |
| 119 | HStack(spacing: 6) { | 133 | HStack(spacing: 6) { |
| 120 | ForEach(start..<min(start + 5, count), id: \.self) { _ in | 134 | ForEach(start..<min(start + 5, count), id: \.self) { _ in |
| 121 | Circle().frame(width: 16, height: 16) | 135 | Circle().frame(width: size, height: size) |
| 122 | } | 136 | } |
| 123 | } | 137 | } |
| 124 | } | 138 | } |
DayByDay/Quiz/Counting.swift added +68
| @@ -0,0 +1,68 @@ | |||
| 1 | // | ||
| 2 | // Counting.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | /// "Count with me": five sets of 1 to 10 objects; the child taps each once. | ||
| 7 | nonisolated struct CountingRound { | ||
| 8 | static let length = 5 | ||
| 9 | |||
| 10 | struct Thing: Equatable { | ||
| 11 | let symbol: String | ||
| 12 | let singular: String | ||
| 13 | let plural: String | ||
| 14 | } | ||
| 15 | |||
| 16 | static let things = [ | ||
| 17 | Thing(symbol: "star.fill", singular: "star", plural: "stars"), | ||
| 18 | Thing(symbol: "heart.fill", singular: "heart", plural: "hearts"), | ||
| 19 | Thing(symbol: "leaf.fill", singular: "leaf", plural: "leaves"), | ||
| 20 | Thing(symbol: "moon.fill", singular: "moon", plural: "moons"), | ||
| 21 | Thing(symbol: "fish.fill", singular: "fish", plural: "fish"), | ||
| 22 | ] | ||
| 23 | |||
| 24 | private(set) var target: Int | ||
| 25 | private(set) var thing: Thing | ||
| 26 | /// Object indices in the order they were tapped. | ||
| 27 | private(set) var counted: [Int] = [] | ||
| 28 | private(set) var setsDone = 0 | ||
| 29 | |||
| 30 | var isSetDone: Bool { counted.count == target } | ||
| 31 | var isComplete: Bool { setsDone == Self.length } | ||
| 32 | |||
| 33 | init(using rng: inout some RandomNumberGenerator) { | ||
| 34 | self.init(target: Int.random(in: 1...10, using: &rng), | ||
| 35 | thing: Self.things.randomElement(using: &rng)!, using: &rng) | ||
| 36 | } | ||
| 37 | |||
| 38 | init(target: Int, thing: Thing, using rng: inout some RandomNumberGenerator) { | ||
| 39 | precondition((1...10).contains(target)) | ||
| 40 | self.target = target | ||
| 41 | self.thing = thing | ||
| 42 | } | ||
| 43 | |||
| 44 | /// The new count, or nil if `index` is not an uncounted object. | ||
| 45 | mutating func tap(_ index: Int) -> Int? { | ||
| 46 | guard !isSetDone, (0..<target).contains(index), !counted.contains(index) else { return nil } | ||
| 47 | counted.append(index) | ||
| 48 | return counted.count | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Starts the next set once this one is counted. | ||
| 52 | mutating func nextSet(using rng: inout some RandomNumberGenerator) { | ||
| 53 | guard isSetDone, !isComplete else { return } | ||
| 54 | setsDone += 1 | ||
| 55 | guard !isComplete else { return } | ||
| 56 | let previous = target | ||
| 57 | target = (1...10).filter { $0 != previous }.randomElement(using: &rng)! | ||
| 58 | thing = Self.things.filter { $0 != thing }.randomElement(using: &rng)! | ||
| 59 | counted = [] | ||
| 60 | } | ||
| 61 | |||
| 62 | func summary() -> String { | ||
| 63 | let word = LearnNumber(rawValue: target)!.name | ||
| 64 | return target == 1 | ||
| 65 | ? "\(word)! There is one \(thing.singular)." | ||
| 66 | : "\(word)! There are \(word.lowercased()) \(thing.plural)." | ||
| 67 | } | ||
| 68 | } | ||
DayByDay/Quiz/CountingView.swift added +131
| @@ -0,0 +1,131 @@ | |||
| 1 | // | ||
| 2 | // CountingView.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import SwiftUI | ||
| 7 | |||
| 8 | /// Tap each object to count it aloud; the total is shown and said at the end. | ||
| 9 | struct CountingView: View { | ||
| 10 | @State private var round: CountingRound | ||
| 11 | @State private var showTotal = false | ||
| 12 | @State private var celebrating = false | ||
| 13 | @State private var speechToken = 0 | ||
| 14 | /// Bumped when the screen goes away, so pending work says nothing. | ||
| 15 | @State private var generation = 0 | ||
| 16 | |||
| 17 | private let columns = [GridItem(.adaptive(minimum: 96, maximum: 140), spacing: 16)] | ||
| 18 | private let color = Category.numbers.color | ||
| 19 | |||
| 20 | init() { | ||
| 21 | var rng = SystemRandomNumberGenerator() | ||
| 22 | _round = State(initialValue: CountingRound(using: &rng)) | ||
| 23 | } | ||
| 24 | |||
| 25 | var body: some View { | ||
| 26 | ZStack { | ||
| 27 | if round.isComplete { | ||
| 28 | FinishedView { | ||
| 29 | var rng = SystemRandomNumberGenerator() | ||
| 30 | round = CountingRound(using: &rng) | ||
| 31 | say(prompt, after: 0.3) | ||
| 32 | } | ||
| 33 | } else { | ||
| 34 | board | ||
| 35 | } | ||
| 36 | } | ||
| 37 | .onAppear { say(prompt, after: 0) } | ||
| 38 | .onDisappear { | ||
| 39 | generation += 1 | ||
| 40 | speechToken += 1 | ||
| 41 | SpeechSynthesizer.shared.stop() | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | private var prompt: String { "Tap each \(round.thing.singular) to count." } | ||
| 46 | |||
| 47 | private var board: some View { | ||
| 48 | ScrollView { | ||
| 49 | VStack(spacing: 28) { | ||
| 50 | Button { say(prompt, after: 0) } label: { | ||
| 51 | Label("Hear it again", systemImage: "speaker.wave.2.fill") | ||
| 52 | .font(.system(size: 24, weight: .bold, design: .rounded)) | ||
| 53 | .padding(.horizontal, 28) | ||
| 54 | .padding(.vertical, 16) | ||
| 55 | .background(Capsule().fill(Color(.systemGray6))) | ||
| 56 | } | ||
| 57 | .buttonStyle(.plain) | ||
| 58 | |||
| 59 | Text(showTotal ? "\(round.target)" : " ") | ||
| 60 | .font(.system(size: 96, weight: .heavy, design: .rounded)) | ||
| 61 | .foregroundStyle(color) | ||
| 62 | .frame(height: 110) | ||
| 63 | .accessibilityHidden(!showTotal) | ||
| 64 | |||
| 65 | LazyVGrid(columns: columns, spacing: 16) { | ||
| 66 | ForEach(0..<round.target, id: \.self) { i in | ||
| 67 | Button { tap(i) } label: { object(i) } | ||
| 68 | .buttonStyle(.plain) | ||
| 69 | .accessibilityLabel(round.thing.singular) | ||
| 70 | } | ||
| 71 | } | ||
| 72 | } | ||
| 73 | .padding(24) | ||
| 74 | } | ||
| 75 | .overlay { CelebrationOverlay(isActive: celebrating) } | ||
| 76 | } | ||
| 77 | |||
| 78 | /// Uncounted: the symbol in the numbers color. Counted: white symbol and | ||
| 79 | /// its count on a numbers-colored tile. | ||
| 80 | private func object(_ i: Int) -> some View { | ||
| 81 | let order = round.counted.firstIndex(of: i).map { $0 + 1 } | ||
| 82 | let shape = RoundedRectangle(cornerRadius: 24, style: .continuous) | ||
| 83 | return ZStack { | ||
| 84 | shape.fill(order == nil ? Color.clear : color) | ||
| 85 | if let order { | ||
| 86 | VStack(spacing: 2) { | ||
| 87 | Image(systemName: round.thing.symbol).font(.system(size: 30)) | ||
| 88 | Text("\(order)").font(.system(size: 34, weight: .heavy, design: .rounded)) | ||
| 89 | } | ||
| 90 | .foregroundStyle(.white) | ||
| 91 | } else { | ||
| 92 | Image(systemName: round.thing.symbol) | ||
| 93 | .font(.system(size: 60)) | ||
| 94 | .foregroundStyle(color) | ||
| 95 | } | ||
| 96 | } | ||
| 97 | .frame(height: 104) | ||
| 98 | .contentShape(shape) | ||
| 99 | } | ||
| 100 | |||
| 101 | private func tap(_ i: Int) { | ||
| 102 | guard let count = round.tap(i) else { return } | ||
| 103 | guard round.isSetDone else { | ||
| 104 | say(LearnNumber(rawValue: count)!.name, after: 0) | ||
| 105 | return | ||
| 106 | } | ||
| 107 | let summary = round.summary() | ||
| 108 | SoundEngine.shared.play(.success) | ||
| 109 | showTotal = true | ||
| 110 | celebrating = true | ||
| 111 | say(summary, after: RoundStyle.speechDelay) | ||
| 112 | let words = summary.split(separator: " ").count | ||
| 113 | let gen = generation | ||
| 114 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.5 + 0.45 * Double(words)) { | ||
| 115 | guard gen == generation else { return } | ||
| 116 | celebrating = false | ||
| 117 | showTotal = false | ||
| 118 | var rng = SystemRandomNumberGenerator() | ||
| 119 | round.nextSet(using: &rng) | ||
| 120 | if !round.isComplete { say(prompt, after: 0) } | ||
| 121 | } | ||
| 122 | } | ||
| 123 | |||
| 124 | private func say(_ text: String, after delay: TimeInterval) { | ||
| 125 | speechToken += 1 | ||
| 126 | let token = speechToken, gen = generation | ||
| 127 | DispatchQueue.main.asyncAfter(deadline: .now() + delay) { | ||
| 128 | if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) } | ||
| 129 | } | ||
| 130 | } | ||
| 131 | } | ||
DayByDay/Quiz/FinishedView.swift added +41
| @@ -0,0 +1,41 @@ | |||
| 1 | // | ||
| 2 | // FinishedView.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import SwiftUI | ||
| 7 | |||
| 8 | /// End of a game: cheering mascot, "You did it!", and Play again. | ||
| 9 | struct FinishedView: View { | ||
| 10 | let onPlayAgain: () -> Void | ||
| 11 | |||
| 12 | @State private var speechToken = 0 | ||
| 13 | |||
| 14 | var body: some View { | ||
| 15 | VStack(spacing: 28) { | ||
| 16 | MascotView(mood: .cheering) | ||
| 17 | .frame(width: 180, height: 180) | ||
| 18 | Text("You did it!") | ||
| 19 | .font(.system(size: 48, weight: .heavy, design: .rounded)) | ||
| 20 | Button(action: onPlayAgain) { | ||
| 21 | Label("Play again", systemImage: "arrow.clockwise") | ||
| 22 | .font(.system(size: 28, weight: .bold, design: .rounded)) | ||
| 23 | .foregroundStyle(.white) | ||
| 24 | .padding(.horizontal, 40) | ||
| 25 | .padding(.vertical, 20) | ||
| 26 | .background(Capsule().fill(RoundStyle.playAgainFill)) | ||
| 27 | } | ||
| 28 | .buttonStyle(.plain) | ||
| 29 | } | ||
| 30 | .padding(32) | ||
| 31 | .onAppear { | ||
| 32 | SoundEngine.shared.play(.roundComplete) | ||
| 33 | speechToken += 1 | ||
| 34 | let token = speechToken | ||
| 35 | DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { | ||
| 36 | if token == speechToken { SpeechSynthesizer.shared.speak("You did it!") } | ||
| 37 | } | ||
| 38 | } | ||
| 39 | .onDisappear { speechToken += 1 } | ||
| 40 | } | ||
| 41 | } | ||
DayByDay/Quiz/Game.swift +35
| @@ -5,12 +5,20 @@ | |||
| 5 | 5 | ||
| 6 | nonisolated enum Game: String, CaseIterable { | 6 | nonisolated enum Game: String, CaseIterable { |
| 7 | case findIt, oddOneOut, listen | 7 | case findIt, oddOneOut, listen |
| 8 | case comesNext, weekTrain, yesterdayTomorrow, yearWheel, whichSeason, counting, most | ||
| 8 | 9 | ||
| 9 | var title: String { | 10 | var title: String { |
| 10 | switch self { | 11 | switch self { |
| 11 | case .findIt: "Find it!" | 12 | case .findIt: "Find it!" |
| 12 | case .oddOneOut: "Odd one out" | 13 | case .oddOneOut: "Odd one out" |
| 13 | case .listen: "Listen" | 14 | case .listen: "Listen" |
| 15 | case .comesNext: "What comes next?" | ||
| 16 | case .weekTrain: "Week train" | ||
| 17 | case .yesterdayTomorrow: "Yesterday and tomorrow" | ||
| 18 | case .yearWheel: "Year wheel" | ||
| 19 | case .whichSeason: "Which season?" | ||
| 20 | case .counting: "Count with me" | ||
| 21 | case .most: "Which has the most?" | ||
| 14 | } | 22 | } |
| 15 | } | 23 | } |
| 16 | 24 | ||
| @@ -19,6 +27,21 @@ nonisolated enum Game: String, CaseIterable { | |||
| 19 | case .findIt: "magnifyingglass" | 27 | case .findIt: "magnifyingglass" |
| 20 | case .oddOneOut: "square.grid.2x2.fill" | 28 | case .oddOneOut: "square.grid.2x2.fill" |
| 21 | case .listen: "ear.fill" | 29 | case .listen: "ear.fill" |
| 30 | case .comesNext: "arrow.right.circle.fill" | ||
| 31 | case .weekTrain: "train.side.front.car" | ||
| 32 | case .yesterdayTomorrow: "calendar.day.timeline.left" | ||
| 33 | case .yearWheel: "circle.dashed" | ||
| 34 | case .whichSeason: "leaf.fill" | ||
| 35 | case .counting: "hand.tap.fill" | ||
| 36 | case .most: "chart.bar.fill" | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | /// Played as a `Round` of questions; the rest have their own screens. | ||
| 41 | var usesRound: Bool { | ||
| 42 | switch self { | ||
| 43 | case .findIt, .oddOneOut, .listen, .comesNext, .whichSeason, .most: true | ||
| 44 | case .weekTrain, .yesterdayTomorrow, .yearWheel, .counting: false | ||
| 22 | } | 45 | } |
| 23 | } | 46 | } |
| 24 | } | 47 | } |
| @@ -55,6 +78,13 @@ nonisolated extension Category { | |||
| 55 | var games: [Game] = [.findIt] | 78 | var games: [Game] = [.findIt] |
| 56 | if [.shapes, .animals, .food].contains(self) { games.append(.oddOneOut) } | 79 | if [.shapes, .animals, .food].contains(self) { games.append(.oddOneOut) } |
| 57 | if [.numbers, .animals, .alphabet, .weather].contains(self) { games.append(.listen) } | 80 | if [.numbers, .animals, .alphabet, .weather].contains(self) { games.append(.listen) } |
| 81 | switch self { | ||
| 82 | case .days: games += [.comesNext, .weekTrain, .yesterdayTomorrow] | ||
| 83 | case .months: games += [.comesNext, .yearWheel] | ||
| 84 | case .seasons: games.append(.whichSeason) | ||
| 85 | case .numbers: games += [.counting, .most] | ||
| 86 | default: break | ||
| 87 | } | ||
| 58 | return games | 88 | return games |
| 59 | } | 89 | } |
| 60 | 90 | ||
| @@ -63,6 +93,11 @@ nonisolated extension Category { | |||
| 63 | case .findIt: findIt | 93 | case .findIt: findIt |
| 64 | case .oddOneOut: oddOneOut | 94 | case .oddOneOut: oddOneOut |
| 65 | case .listen: listen | 95 | case .listen: listen |
| 96 | case .comesNext: ComesNext(items: quizItems, noun: self == .days ? "day" : "month") | ||
| 97 | case .whichSeason: WhichSeason() | ||
| 98 | case .most: Most() | ||
| 99 | case .weekTrain, .yesterdayTomorrow, .yearWheel, .counting: | ||
| 100 | preconditionFailure("\(game) is not a question round") | ||
| 66 | } | 101 | } |
| 67 | } | 102 | } |
| 68 | 103 | ||
DayByDay/Quiz/GameDestination.swift added +40
| @@ -0,0 +1,40 @@ | |||
| 1 | // | ||
| 2 | // GameDestination.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import SwiftUI | ||
| 7 | |||
| 8 | /// The screen a hub button opens for one game. | ||
| 9 | struct GameDestination: View { | ||
| 10 | let category: Category | ||
| 11 | let game: Game | ||
| 12 | |||
| 13 | var body: some View { | ||
| 14 | content.navigationTitle(game.title) | ||
| 15 | } | ||
| 16 | |||
| 17 | @ViewBuilder | ||
| 18 | private var content: some View { | ||
| 19 | switch game { | ||
| 20 | case .most: | ||
| 21 | RoundView(source: category.questionSource(for: game), game: game) { PileTile(item: $0) } | ||
| 22 | case .findIt, .oddOneOut, .listen, .comesNext, .whichSeason: | ||
| 23 | RoundView(source: category.questionSource(for: game), game: game) { ChoiceTile(item: $0) } | ||
| 24 | case .weekTrain: | ||
| 25 | SequencePuzzleView(game: game) { | ||
| 26 | var rng = SystemRandomNumberGenerator() | ||
| 27 | return .weekTrain(using: &rng) | ||
| 28 | } | ||
| 29 | case .yesterdayTomorrow: | ||
| 30 | SequencePuzzleView(game: game) { | ||
| 31 | var rng = SystemRandomNumberGenerator() | ||
| 32 | return .yesterdayTomorrow(today: .current, using: &rng) | ||
| 33 | } | ||
| 34 | case .yearWheel: | ||
| 35 | YearWheelView() | ||
| 36 | case .counting: | ||
| 37 | CountingView() | ||
| 38 | } | ||
| 39 | } | ||
| 40 | } | ||
DayByDay/Quiz/OrderSources.swift added +79
| @@ -0,0 +1,79 @@ | |||
| 1 | // | ||
| 2 | // OrderSources.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | nonisolated extension MonthOfYear { | ||
| 7 | /// Same months as `Season.current`. | ||
| 8 | var season: Season { | ||
| 9 | switch self { | ||
| 10 | case .march, .april, .may: .spring | ||
| 11 | case .june, .july, .august: .summer | ||
| 12 | case .september, .october, .november: .fall | ||
| 13 | case .december, .january, .february: .winter | ||
| 14 | } | ||
| 15 | } | ||
| 16 | } | ||
| 17 | |||
| 18 | /// "What day comes after Monday?" The answer is the next item, wrapping | ||
| 19 | /// from the last to the first. The asked item is never a choice. | ||
| 20 | nonisolated struct ComesNext: QuestionSource { | ||
| 21 | let items: [QuizItem] | ||
| 22 | let noun: String | ||
| 23 | |||
| 24 | init(items: [QuizItem], noun: String) { | ||
| 25 | precondition(items.count >= 3) | ||
| 26 | self.items = items | ||
| 27 | self.noun = noun | ||
| 28 | } | ||
| 29 | |||
| 30 | func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question { | ||
| 31 | let starts = items.indices.filter { items[($0 + 1) % items.count] != previous } | ||
| 32 | let i = starts.randomElement(using: &rng)! | ||
| 33 | let asked = items[i] | ||
| 34 | let answer = items[(i + 1) % items.count] | ||
| 35 | let count = min(Round.choiceCount(correctCount: correctCount), items.count - 1) | ||
| 36 | let others = items.filter { $0 != asked && $0 != answer }.shuffled(using: &rng).prefix(count - 1) | ||
| 37 | var facts: [QuizItem: String] = [:] | ||
| 38 | for item in others { facts[item] = "\(answer.name) comes after \(asked.name)." } | ||
| 39 | return Question(prompt: "What \(noun) comes after \(asked.name)?", | ||
| 40 | choices: ([answer] + others).shuffled(using: &rng), | ||
| 41 | answer: answer, facts: facts) | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | /// "Which season is July in?" | ||
| 46 | nonisolated struct WhichSeason: QuestionSource { | ||
| 47 | func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question { | ||
| 48 | let seasons = Category.seasons.quizItems | ||
| 49 | let answer = seasons.filter { $0 != previous }.randomElement(using: &rng)! | ||
| 50 | let season = answer.value(Season.self)! | ||
| 51 | let month = MonthOfYear.allCases.filter { $0.season == season }.randomElement(using: &rng)! | ||
| 52 | let count = Round.choiceCount(correctCount: correctCount) | ||
| 53 | let others = seasons.filter { $0 != answer }.shuffled(using: &rng).prefix(count - 1) | ||
| 54 | var facts: [QuizItem: String] = [:] | ||
| 55 | for item in others { facts[item] = "\(month.name) is in \(answer.name)." } | ||
| 56 | return Question(prompt: "Which season is \(month.name) in?", | ||
| 57 | choices: ([answer] + others).shuffled(using: &rng), | ||
| 58 | answer: answer, facts: facts) | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | /// "Which one has the most?" Choices are piles of 1 to 10; the answer is the largest. | ||
| 63 | nonisolated struct Most: QuestionSource { | ||
| 64 | func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question { | ||
| 65 | let numbers = Category.numbers.quizItems | ||
| 66 | let count = Round.choiceCount(correctCount: correctCount) | ||
| 67 | // The answer needs count - 1 smaller numbers below it. | ||
| 68 | let answer = numbers.filter { $0.value(LearnNumber.self)!.numeral >= count && $0 != previous } | ||
| 69 | .randomElement(using: &rng)! | ||
| 70 | let top = answer.value(LearnNumber.self)!.numeral | ||
| 71 | let others = numbers.filter { $0.value(LearnNumber.self)!.numeral < top } | ||
| 72 | .shuffled(using: &rng).prefix(count - 1) | ||
| 73 | var facts: [QuizItem: String] = [:] | ||
| 74 | for item in others { facts[item] = "That one has \(item.value(LearnNumber.self)!.numeral)." } | ||
| 75 | return Question(prompt: "Which one has the most?", | ||
| 76 | choices: ([answer] + others).shuffled(using: &rng), | ||
| 77 | answer: answer, facts: facts) | ||
| 78 | } | ||
| 79 | } | ||
DayByDay/Quiz/RoundView.swift +2 −21
| @@ -83,27 +83,8 @@ struct RoundView<Choice: View>: View { | |||
| 83 | } | 83 | } |
| 84 | 84 | ||
| 85 | private var finished: some View { | 85 | private var finished: some View { |
| 86 | VStack(spacing: 28) { | 86 | FinishedView { |
| 87 | MascotView(mood: .cheering) | 87 | round = Round(source: source, after: round.current.answer) |
| 88 | .frame(width: 180, height: 180) | ||
| 89 | Text("You did it!") | ||
| 90 | .font(.system(size: 48, weight: .heavy, design: .rounded)) | ||
| 91 | Button { | ||
| 92 | round = Round(source: source, after: round.current.answer) | ||
| 93 | } label: { | ||
| 94 | Label("Play again", systemImage: "arrow.clockwise") | ||
| 95 | .font(.system(size: 28, weight: .bold, design: .rounded)) | ||
| 96 | .foregroundStyle(.white) | ||
| 97 | .padding(.horizontal, 40) | ||
| 98 | .padding(.vertical, 20) | ||
| 99 | .background(Capsule().fill(RoundStyle.playAgainFill)) | ||
| 100 | } | ||
| 101 | .buttonStyle(.plain) | ||
| 102 | } | ||
| 103 | .padding(32) | ||
| 104 | .onAppear { | ||
| 105 | SoundEngine.shared.play(.roundComplete) | ||
| 106 | say("You did it!", after: 0.4) | ||
| 107 | } | 88 | } |
| 108 | } | 89 | } |
| 109 | 90 | ||
DayByDay/Quiz/SequencePuzzle.swift added +78
| @@ -0,0 +1,78 @@ | |||
| 1 | // | ||
| 2 | // SequencePuzzle.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | /// Cards placed one at a time into ordered slots. Tapping or dragging a card | ||
| 7 | /// places it in the next slot; a wrong card waits for `resume()`. | ||
| 8 | nonisolated struct SequencePuzzle { | ||
| 9 | struct Step { | ||
| 10 | let answer: QuizItem | ||
| 11 | let prompt: String | ||
| 12 | /// Said after a wrong card, before "Try again!". | ||
| 13 | let correction: String | ||
| 14 | } | ||
| 15 | |||
| 16 | let steps: [Step] | ||
| 17 | /// The cards on offer, shuffled once. | ||
| 18 | let pool: [QuizItem] | ||
| 19 | /// Labels above the slots; nil for the train. | ||
| 20 | let slotLabels: [String]? | ||
| 21 | /// Said once every slot is filled. | ||
| 22 | let summary: String | ||
| 23 | private(set) var placed: [QuizItem] = [] | ||
| 24 | private(set) var isShowingCorrection = false | ||
| 25 | |||
| 26 | var current: Step? { placed.count < steps.count ? steps[placed.count] : nil } | ||
| 27 | var isSolved: Bool { current == nil } | ||
| 28 | |||
| 29 | mutating func place(_ item: QuizItem) -> AnswerOutcome { | ||
| 30 | guard let current, !isShowingCorrection, !placed.contains(item) else { return .ignored } | ||
| 31 | guard item == current.answer else { | ||
| 32 | isShowingCorrection = true | ||
| 33 | return .incorrect(correctName: current.answer.name) | ||
| 34 | } | ||
| 35 | placed.append(item) | ||
| 36 | return .correct | ||
| 37 | } | ||
| 38 | |||
| 39 | mutating func resume() { | ||
| 40 | isShowingCorrection = false | ||
| 41 | } | ||
| 42 | |||
| 43 | func correction() -> String { | ||
| 44 | guard let current else { return "" } | ||
| 45 | return "\(current.correction) Try again!" | ||
| 46 | } | ||
| 47 | |||
| 48 | /// Sunday to Saturday, from all seven cards. | ||
| 49 | static func weekTrain(using rng: inout some RandomNumberGenerator) -> SequencePuzzle { | ||
| 50 | let days = DayOfWeek.allCases.map { Category.days.item($0) } | ||
| 51 | let steps = days.indices.map { i in | ||
| 52 | i == 0 | ||
| 53 | ? Step(answer: days[0], prompt: "Which day comes first?", correction: "\(days[0].name) comes first.") | ||
| 54 | : Step(answer: days[i], prompt: "What comes after \(days[i - 1].name)?", | ||
| 55 | correction: "\(days[i].name) comes next.") | ||
| 56 | } | ||
| 57 | return SequencePuzzle(steps: steps, pool: days.shuffled(using: &rng), slotLabels: nil, | ||
| 58 | summary: days.map(\.name).joined(separator: ", ") + "!") | ||
| 59 | } | ||
| 60 | |||
| 61 | /// Yesterday, today and tomorrow, from those three cards plus one other day. | ||
| 62 | static func yesterdayTomorrow(today: DayOfWeek, using rng: inout some RandomNumberGenerator) -> SequencePuzzle { | ||
| 63 | func day(_ offset: Int) -> QuizItem { | ||
| 64 | Category.days.item(DayOfWeek(rawValue: (today.rawValue + offset + 7) % 7)!) | ||
| 65 | } | ||
| 66 | let (yesterday, now, tomorrow) = (day(-1), day(0), day(1)) | ||
| 67 | let extra = (2...5).map(day).randomElement(using: &rng)! | ||
| 68 | let steps = [ | ||
| 69 | Step(answer: yesterday, prompt: "Which day was yesterday?", correction: "Yesterday was \(yesterday.name)."), | ||
| 70 | Step(answer: now, prompt: "Which day is today?", correction: "Today is \(now.name)."), | ||
| 71 | Step(answer: tomorrow, prompt: "Which day will it be tomorrow?", correction: "Tomorrow will be \(tomorrow.name)."), | ||
| 72 | ] | ||
| 73 | return SequencePuzzle( | ||
| 74 | steps: steps, pool: [yesterday, now, tomorrow, extra].shuffled(using: &rng), | ||
| 75 | slotLabels: ["Yesterday", "Today", "Tomorrow"], | ||
| 76 | summary: "Yesterday was \(yesterday.name), today is \(now.name), and tomorrow will be \(tomorrow.name)!") | ||
| 77 | } | ||
| 78 | } | ||
DayByDay/Quiz/SequencePuzzleView.swift added +276
| @@ -0,0 +1,276 @@ | |||
| 1 | // | ||
| 2 | // SequencePuzzleView.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import SwiftUI | ||
| 7 | |||
| 8 | /// Week train and yesterday/today/tomorrow: slots on top, cards below. | ||
| 9 | /// Tap a card to place it, or drag it anywhere onto the slots. | ||
| 10 | struct SequencePuzzleView: View { | ||
| 11 | let game: Game | ||
| 12 | let make: () -> SequencePuzzle | ||
| 13 | |||
| 14 | @Environment(ProfileSession.self) private var session | ||
| 15 | @State private var puzzle: SequencePuzzle | ||
| 16 | @State private var praise = PraisePhrases() | ||
| 17 | @State private var dimmed: QuizItem? | ||
| 18 | @State private var celebrating = false | ||
| 19 | @State private var finished = false | ||
| 20 | @State private var speechToken = 0 | ||
| 21 | /// Bumped when the screen goes away, so pending work does nothing. | ||
| 22 | @State private var generation = 0 | ||
| 23 | /// Counts finished games, so a timer from an earlier game is ignored. | ||
| 24 | @State private var solves = 0 | ||
| 25 | |||
| 26 | private let columns = [GridItem(.adaptive(minimum: 130, maximum: 220), spacing: 16)] | ||
| 27 | |||
| 28 | init(game: Game, make: @escaping () -> SequencePuzzle) { | ||
| 29 | self.game = game | ||
| 30 | self.make = make | ||
| 31 | _puzzle = State(initialValue: make()) | ||
| 32 | } | ||
| 33 | |||
| 34 | var body: some View { | ||
| 35 | ZStack { | ||
| 36 | if finished { | ||
| 37 | FinishedView { | ||
| 38 | puzzle = make() | ||
| 39 | finished = false | ||
| 40 | say(puzzle.current?.prompt ?? "", after: 0.3) | ||
| 41 | } | ||
| 42 | } else { | ||
| 43 | board | ||
| 44 | } | ||
| 45 | } | ||
| 46 | .onAppear { say(puzzle.current?.prompt ?? "", after: 0) } | ||
| 47 | .onDisappear { | ||
| 48 | generation += 1 | ||
| 49 | speechToken += 1 | ||
| 50 | SpeechSynthesizer.shared.stop() | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | private var board: some View { | ||
| 55 | ScrollView { | ||
| 56 | VStack(spacing: 28) { | ||
| 57 | Button { say(puzzle.current?.prompt ?? "", after: 0) } label: { | ||
| 58 | Label("Hear it again", systemImage: "speaker.wave.2.fill") | ||
| 59 | .font(.system(size: 24, weight: .bold, design: .rounded)) | ||
| 60 | .padding(.horizontal, 28) | ||
| 61 | .padding(.vertical, 16) | ||
| 62 | .background(Capsule().fill(Color(.systemGray6))) | ||
| 63 | } | ||
| 64 | .buttonStyle(.plain) | ||
| 65 | |||
| 66 | slots | ||
| 67 | .dropDestination(for: String.self) { ids, _ in | ||
| 68 | guard let id = ids.first, let item = puzzle.pool.first(where: { $0.id == id }) else { return false } | ||
| 69 | place(item) | ||
| 70 | return true | ||
| 71 | } | ||
| 72 | |||
| 73 | LazyVGrid(columns: columns, spacing: 16) { | ||
| 74 | // Placed cards keep their spot, hidden, so the rest don't move. | ||
| 75 | ForEach(puzzle.pool) { item in | ||
| 76 | let isPlaced = puzzle.placed.contains(item) | ||
| 77 | Button { place(item) } label: { | ||
| 78 | ChoiceTile(item: item) | ||
| 79 | .frame(height: 130) | ||
| 80 | .opacity(isPlaced ? 0 : dimmed == item ? 0.4 : 1) | ||
| 81 | } | ||
| 82 | .buttonStyle(.plain) | ||
| 83 | .disabled(isPlaced) | ||
| 84 | .accessibilityHidden(isPlaced) | ||
| 85 | .draggable(item.id) { | ||
| 86 | ChoiceTile(item: item).frame(width: 130, height: 130) | ||
| 87 | } | ||
| 88 | .accessibilityLabel(item.name) | ||
| 89 | } | ||
| 90 | } | ||
| 91 | } | ||
| 92 | .padding(24) | ||
| 93 | } | ||
| 94 | .overlay { CelebrationOverlay(isActive: celebrating) } | ||
| 95 | } | ||
| 96 | |||
| 97 | @ViewBuilder | ||
| 98 | private var slots: some View { | ||
| 99 | if let labels = puzzle.slotLabels { | ||
| 100 | HStack(alignment: .top, spacing: 12) { | ||
| 101 | ForEach(Array(labels.enumerated()), id: \.offset) { i, label in | ||
| 102 | VStack(spacing: 8) { | ||
| 103 | Text(label) | ||
| 104 | .font(.system(size: 20, weight: .bold, design: .rounded)) | ||
| 105 | .lineLimit(1) | ||
| 106 | .minimumScaleFactor(0.6) | ||
| 107 | slot(i).frame(height: 130) | ||
| 108 | } | ||
| 109 | .frame(maxWidth: .infinity) | ||
| 110 | } | ||
| 111 | } | ||
| 112 | } else { | ||
| 113 | ScrollViewReader { proxy in | ||
| 114 | ScrollView(.horizontal, showsIndicators: false) { | ||
| 115 | HStack(alignment: .bottom, spacing: 6) { | ||
| 116 | TrainEngine() | ||
| 117 | .frame(width: 130, height: 150) | ||
| 118 | ForEach(puzzle.steps.indices, id: \.self) { i in | ||
| 119 | TrainCar { slot(i) } | ||
| 120 | .frame(width: 130, height: 150) | ||
| 121 | .id(i) | ||
| 122 | } | ||
| 123 | } | ||
| 124 | .padding(.vertical, 4) | ||
| 125 | } | ||
| 126 | // Run edge to edge instead of clipping cars at the page margin. | ||
| 127 | .contentMargins(.horizontal, 24, for: .scrollContent) | ||
| 128 | .padding(.horizontal, -24) | ||
| 129 | .onAppear { proxy.scrollTo(nextCar, anchor: .center) } | ||
| 130 | .onChange(of: puzzle.placed.count) { | ||
| 131 | withAnimation { proxy.scrollTo(nextCar, anchor: .center) } | ||
| 132 | } | ||
| 133 | } | ||
| 134 | } | ||
| 135 | } | ||
| 136 | |||
| 137 | private var nextCar: Int { min(puzzle.placed.count, puzzle.steps.count - 1) } | ||
| 138 | |||
| 139 | /// A placed card, the outlined next slot, or a faint empty slot. | ||
| 140 | @ViewBuilder | ||
| 141 | private func slot(_ i: Int) -> some View { | ||
| 142 | let shape = RoundedRectangle(cornerRadius: 24, style: .continuous) | ||
| 143 | if i < puzzle.placed.count { | ||
| 144 | ChoiceTile(item: puzzle.placed[i]) | ||
| 145 | } else { | ||
| 146 | shape | ||
| 147 | .fill(Color(.systemGray6)) | ||
| 148 | .overlay { | ||
| 149 | shape.strokeBorder(i == puzzle.placed.count ? Category.days.color : Color(.systemGray3), | ||
| 150 | style: StrokeStyle(lineWidth: i == puzzle.placed.count ? 5 : 2, dash: [10, 8])) | ||
| 151 | } | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | private func place(_ item: QuizItem) { | ||
| 156 | guard let step = puzzle.current else { return } | ||
| 157 | let outcome = puzzle.place(item) | ||
| 158 | guard outcome != .ignored else { return } | ||
| 159 | if let profile = session.current { | ||
| 160 | session.store.record(step.answer, chosen: item, game: game, correct: outcome == .correct, for: profile) | ||
| 161 | } | ||
| 162 | switch outcome { | ||
| 163 | case .correct where puzzle.isSolved: | ||
| 164 | let sound: SoundEffect = game == .weekTrain ? .whistle : .success | ||
| 165 | SoundEngine.shared.play(sound) | ||
| 166 | celebrating = true | ||
| 167 | speechToken += 1 | ||
| 168 | solves += 1 | ||
| 169 | let token = speechToken, gen = generation, solve = solves | ||
| 170 | let finish = { | ||
| 171 | guard gen == generation, solve == solves, !finished else { return } | ||
| 172 | celebrating = false | ||
| 173 | finished = true | ||
| 174 | } | ||
| 175 | DispatchQueue.main.asyncAfter(deadline: .now() + SoundEngine.shared.remaining(sound) + 0.2) { | ||
| 176 | guard gen == generation, token == speechToken else { return } | ||
| 177 | // Move on when the whole summary has been said. | ||
| 178 | SpeechSynthesizer.shared.speak(puzzle.summary, completion: finish) | ||
| 179 | } | ||
| 180 | // In case the summary is cut off and never finishes. | ||
| 181 | DispatchQueue.main.asyncAfter(deadline: .now() + 15, execute: finish) | ||
| 182 | case .correct: | ||
| 183 | SoundEngine.shared.play(.success) | ||
| 184 | var rng = SystemRandomNumberGenerator() | ||
| 185 | // One utterance: a second speak() would cut the praise off. | ||
| 186 | say("\(praise.next(using: &rng)) \(puzzle.current?.prompt ?? "")", after: RoundStyle.speechDelay) | ||
| 187 | case .incorrect: | ||
| 188 | SoundEngine.shared.play(.gentleMiss) | ||
| 189 | say(puzzle.correction(), after: RoundStyle.speechDelay) | ||
| 190 | withAnimation(.easeOut(duration: 0.2)) { dimmed = item } | ||
| 191 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { | ||
| 192 | withAnimation { if dimmed == item { dimmed = nil } } | ||
| 193 | puzzle.resume() | ||
| 194 | } | ||
| 195 | case .ignored: | ||
| 196 | break | ||
| 197 | } | ||
| 198 | } | ||
| 199 | |||
| 200 | /// Speaks after `delay` unless something newer was said first. | ||
| 201 | private func say(_ text: String, after delay: TimeInterval) { | ||
| 202 | guard !text.isEmpty else { return } | ||
| 203 | speechToken += 1 | ||
| 204 | let token = speechToken, gen = generation | ||
| 205 | DispatchQueue.main.asyncAfter(deadline: .now() + delay) { | ||
| 206 | if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) } | ||
| 207 | } | ||
| 208 | } | ||
| 209 | } | ||
| 210 | |||
| 211 | enum TrainStyle { | ||
| 212 | /// Visible on both light and dark backgrounds. | ||
| 213 | static let tire = Color(white: 0.45) | ||
| 214 | static let hub = Color(white: 0.75) | ||
| 215 | } | ||
| 216 | |||
| 217 | /// A toy engine facing left, so its cab sits next to the first car. | ||
| 218 | private struct TrainEngine: View { | ||
| 219 | var body: some View { | ||
| 220 | GeometryReader { geo in | ||
| 221 | let w = geo.size.width, h = geo.size.height | ||
| 222 | let color = Category.days.color | ||
| 223 | ZStack(alignment: .topLeading) { | ||
| 224 | // Chimney, cab, boiler. | ||
| 225 | RoundedRectangle(cornerRadius: 4).fill(color) | ||
| 226 | .frame(width: w * 0.16, height: h * 0.22) | ||
| 227 | .offset(x: w * 0.62, y: h * 0.12) | ||
| 228 | RoundedRectangle(cornerRadius: 10).fill(color) | ||
| 229 | .frame(width: w * 0.42, height: h * 0.72) | ||
| 230 | .offset(x: w * 0.02, y: h * 0.08) | ||
| 231 | RoundedRectangle(cornerRadius: 6).fill(.white.opacity(0.85)) | ||
| 232 | .frame(width: w * 0.24, height: h * 0.2) | ||
| 233 | .offset(x: w * 0.11, y: h * 0.16) | ||
| 234 | RoundedRectangle(cornerRadius: 14).fill(color) | ||
| 235 | .frame(width: w * 0.62, height: h * 0.4) | ||
| 236 | .offset(x: w * 0.36, y: h * 0.4) | ||
| 237 | RoundedRectangle(cornerRadius: 3).fill(Color(.systemGray)) | ||
| 238 | .frame(width: w, height: 6) | ||
| 239 | .offset(y: h * 0.82) | ||
| 240 | wheels(w: w, h: h, at: [0.2, 0.5, 0.8]) | ||
| 241 | } | ||
| 242 | .scaleEffect(x: -1) | ||
| 243 | } | ||
| 244 | .accessibilityHidden(true) | ||
| 245 | } | ||
| 246 | } | ||
| 247 | |||
| 248 | /// A flat car with the slot on top and two wheels. | ||
| 249 | private struct TrainCar<Content: View>: View { | ||
| 250 | @ViewBuilder let content: () -> Content | ||
| 251 | |||
| 252 | var body: some View { | ||
| 253 | GeometryReader { geo in | ||
| 254 | let w = geo.size.width, h = geo.size.height | ||
| 255 | ZStack(alignment: .topLeading) { | ||
| 256 | content() | ||
| 257 | .frame(width: w, height: h * 0.8) | ||
| 258 | RoundedRectangle(cornerRadius: 3).fill(Color(.systemGray)) | ||
| 259 | .frame(width: w + 6, height: 6) | ||
| 260 | .offset(x: -3, y: h * 0.82) | ||
| 261 | wheels(w: w, h: h, at: [0.25, 0.75]) | ||
| 262 | } | ||
| 263 | } | ||
| 264 | } | ||
| 265 | } | ||
| 266 | |||
| 267 | private func wheels(w: CGFloat, h: CGFloat, at positions: [CGFloat]) -> some View { | ||
| 268 | let d = h * 0.2 | ||
| 269 | return ForEach(positions, id: \.self) { x in | ||
| 270 | Circle() | ||
| 271 | .fill(TrainStyle.tire) | ||
| 272 | .overlay(Circle().fill(TrainStyle.hub).padding(d * 0.3)) | ||
| 273 | .frame(width: d, height: d) | ||
| 274 | .offset(x: w * x - d / 2, y: h - d) | ||
| 275 | } | ||
| 276 | } | ||
DayByDay/Quiz/YearWheel.swift added +32
| @@ -0,0 +1,32 @@ | |||
| 1 | // | ||
| 2 | // YearWheel.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import Foundation | ||
| 7 | |||
| 8 | /// Geometry of the year wheel. Month `i` (January = 0) is drawn centered | ||
| 9 | /// `i * 30°` clockwise from the pointer at the top; the wheel then turns | ||
| 10 | /// clockwise by its rotation. | ||
| 11 | nonisolated enum YearWheel { | ||
| 12 | static let wedge = 30.0 | ||
| 13 | |||
| 14 | /// The month under the pointer after turning the wheel clockwise by `degrees`. | ||
| 15 | static func month(atRotation degrees: Double) -> MonthOfYear { | ||
| 16 | let index = Int((-degrees / wedge).rounded()) | ||
| 17 | return MonthOfYear.allCases[((index % 12) + 12) % 12] | ||
| 18 | } | ||
| 19 | |||
| 20 | /// The first rotation at least `turns` full turns past `rotation` that | ||
| 21 | /// puts the center of `month` under the pointer. | ||
| 22 | static func target(from rotation: Double, landingOn month: MonthOfYear, turns: Int) -> Double { | ||
| 23 | let index = Double(MonthOfYear.allCases.firstIndex(of: month)!) | ||
| 24 | let base = -index * wedge | ||
| 25 | let minimum = rotation + Double(turns) * 360 | ||
| 26 | return base + 360 * ((minimum - base) / 360).rounded(.up) | ||
| 27 | } | ||
| 28 | |||
| 29 | static func line(for month: MonthOfYear) -> String { | ||
| 30 | "\(month.name)! \(month.name) is in \(month.season.name.lowercased())." | ||
| 31 | } | ||
| 32 | } | ||
DayByDay/Quiz/YearWheelView.swift added +157
| @@ -0,0 +1,157 @@ | |||
| 1 | // | ||
| 2 | // YearWheelView.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import SwiftUI | ||
| 7 | |||
| 8 | extension Season { | ||
| 9 | /// Wedge colors on the year wheel; white labels are at least 3:1 on each. | ||
| 10 | var wheelColor: Color { | ||
| 11 | switch self { | ||
| 12 | case .spring: Color(red: 0.18, green: 0.56, blue: 0.28) | ||
| 13 | case .summer: Color(red: 0.72, green: 0.48, blue: 0.0) | ||
| 14 | case .fall: Color(red: 0.55, green: 0.22, blue: 0.10) | ||
| 15 | case .winter: Color(red: 0.0, green: 0.42, blue: 0.85) | ||
| 16 | } | ||
| 17 | } | ||
| 18 | } | ||
| 19 | |||
| 20 | /// Spin the wheel of months; it says where it lands and which season that is. | ||
| 21 | /// Tapping a month says the same for that month. | ||
| 22 | struct YearWheelView: View { | ||
| 23 | @Environment(\.accessibilityReduceMotion) private var reduceMotion | ||
| 24 | @State private var rotation = 0.0 | ||
| 25 | @State private var spinning = false | ||
| 26 | @State private var speechToken = 0 | ||
| 27 | /// Bumped when the screen goes away, so a pending landing says nothing. | ||
| 28 | @State private var generation = 0 | ||
| 29 | |||
| 30 | private static let spinDuration = 2.5 | ||
| 31 | |||
| 32 | var body: some View { | ||
| 33 | VStack(spacing: 32) { | ||
| 34 | Pointer() | ||
| 35 | .fill(Color.primary) | ||
| 36 | .frame(width: 40, height: 34) | ||
| 37 | .padding(.bottom, -40) | ||
| 38 | .zIndex(1) | ||
| 39 | wheel | ||
| 40 | .aspectRatio(1, contentMode: .fit) | ||
| 41 | .frame(maxWidth: 520) | ||
| 42 | Button(action: spin) { | ||
| 43 | Label("Spin!", systemImage: "arrow.clockwise.circle.fill") | ||
| 44 | .font(.system(size: 32, weight: .heavy, design: .rounded)) | ||
| 45 | .foregroundStyle(.white) | ||
| 46 | .padding(.horizontal, 48) | ||
| 47 | .padding(.vertical, 22) | ||
| 48 | .background(Capsule().fill(Category.months.color)) | ||
| 49 | } | ||
| 50 | .buttonStyle(.plain) | ||
| 51 | .disabled(spinning) | ||
| 52 | } | ||
| 53 | .padding(24) | ||
| 54 | .onAppear { say("Spin the wheel! Or tap a month.") } | ||
| 55 | .onDisappear { | ||
| 56 | generation += 1 | ||
| 57 | speechToken += 1 | ||
| 58 | SpeechSynthesizer.shared.stop() | ||
| 59 | } | ||
| 60 | } | ||
| 61 | |||
| 62 | private var wheel: some View { | ||
| 63 | GeometryReader { geo in | ||
| 64 | let size = min(geo.size.width, geo.size.height) | ||
| 65 | ZStack { | ||
| 66 | ForEach(Array(MonthOfYear.allCases.enumerated()), id: \.offset) { i, month in | ||
| 67 | let center = Double(i) * YearWheel.wedge | ||
| 68 | Wedge(center: center, width: YearWheel.wedge) | ||
| 69 | .fill(month.season.wheelColor) | ||
| 70 | .overlay(Wedge(center: center, width: YearWheel.wedge).stroke(.white, lineWidth: 2)) | ||
| 71 | .contentShape(Wedge(center: center, width: YearWheel.wedge)) | ||
| 72 | .onTapGesture { | ||
| 73 | guard !spinning else { return } | ||
| 74 | say(YearWheel.line(for: month)) | ||
| 75 | } | ||
| 76 | .accessibilityLabel(month.name) | ||
| 77 | .accessibilityAddTraits(.isButton) | ||
| 78 | Text(month.name.prefix(3)) | ||
| 79 | .font(.system(size: size * 0.06, weight: .heavy, design: .rounded)) | ||
| 80 | .foregroundStyle(.white) | ||
| 81 | .offset(y: -size * 0.38) | ||
| 82 | .rotationEffect(.degrees(center)) | ||
| 83 | .allowsHitTesting(false) | ||
| 84 | } | ||
| 85 | Circle() | ||
| 86 | .fill(Color(.systemBackground)) | ||
| 87 | .frame(width: size * 0.24) | ||
| 88 | .overlay(Circle().stroke(Color(.systemGray3), lineWidth: 2)) | ||
| 89 | .allowsHitTesting(false) | ||
| 90 | } | ||
| 91 | .frame(width: size, height: size) | ||
| 92 | .rotationEffect(.degrees(rotation)) | ||
| 93 | .frame(maxWidth: .infinity, maxHeight: .infinity) | ||
| 94 | } | ||
| 95 | } | ||
| 96 | |||
| 97 | private func spin() { | ||
| 98 | guard !spinning else { return } | ||
| 99 | let current = YearWheel.month(atRotation: rotation) | ||
| 100 | let month = MonthOfYear.allCases.filter { $0 != current }.randomElement()! | ||
| 101 | let target = YearWheel.target(from: rotation, landingOn: month, turns: 3) | ||
| 102 | spinning = true | ||
| 103 | speechToken += 1 | ||
| 104 | SpeechSynthesizer.shared.stop() | ||
| 105 | let duration = reduceMotion ? 0 : Self.spinDuration | ||
| 106 | if reduceMotion { | ||
| 107 | rotation = target | ||
| 108 | } else { | ||
| 109 | withAnimation(.timingCurve(0.15, 0.8, 0.3, 1, duration: duration)) { rotation = target } | ||
| 110 | } | ||
| 111 | let gen = generation | ||
| 112 | DispatchQueue.main.asyncAfter(deadline: .now() + duration + 0.1) { | ||
| 113 | spinning = false | ||
| 114 | guard gen == generation else { return } | ||
| 115 | say(YearWheel.line(for: month)) | ||
| 116 | } | ||
| 117 | } | ||
| 118 | |||
| 119 | private func say(_ text: String) { | ||
| 120 | speechToken += 1 | ||
| 121 | let token = speechToken, gen = generation | ||
| 122 | DispatchQueue.main.async { | ||
| 123 | if token == speechToken, gen == generation { SpeechSynthesizer.shared.speak(text) } | ||
| 124 | } | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | /// A pie slice centered `center` degrees clockwise from the top. | ||
| 129 | private struct Wedge: Shape { | ||
| 130 | let center: Double | ||
| 131 | let width: Double | ||
| 132 | |||
| 133 | func path(in rect: CGRect) -> Path { | ||
| 134 | let c = CGPoint(x: rect.midX, y: rect.midY) | ||
| 135 | let r = min(rect.width, rect.height) / 2 | ||
| 136 | // SwiftUI angles start at 3 o'clock; the top is -90°. | ||
| 137 | let start = Angle.degrees(center - width / 2 - 90) | ||
| 138 | let end = Angle.degrees(center + width / 2 - 90) | ||
| 139 | var p = Path() | ||
| 140 | p.move(to: c) | ||
| 141 | p.addArc(center: c, radius: r, startAngle: start, endAngle: end, clockwise: false) | ||
| 142 | p.closeSubpath() | ||
| 143 | return p | ||
| 144 | } | ||
| 145 | } | ||
| 146 | |||
| 147 | /// Downward triangle marking the month that is picked. | ||
| 148 | private struct Pointer: Shape { | ||
| 149 | func path(in rect: CGRect) -> Path { | ||
| 150 | var p = Path() | ||
| 151 | p.move(to: CGPoint(x: rect.minX, y: rect.minY)) | ||
| 152 | p.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) | ||
| 153 | p.addLine(to: CGPoint(x: rect.midX, y: rect.maxY)) | ||
| 154 | p.closeSubpath() | ||
| 155 | return p | ||
| 156 | } | ||
| 157 | } | ||
DayByDay/Sound/SoundSynth.swift +18 −1
| @@ -9,12 +9,14 @@ nonisolated enum SoundEffect: Hashable, CaseIterable, Sendable { | |||
| 9 | case success, gentleMiss, roundComplete | 9 | case success, gentleMiss, roundComplete |
| 10 | case moo, quack, baa, oink, meow, woof, tweet | 10 | case moo, quack, baa, oink, meow, woof, tweet |
| 11 | case rain, wind, thunder | 11 | case rain, wind, thunder |
| 12 | /// Two-tone train whistle, for a finished week train. | ||
| 13 | case whistle | ||
| 12 | /// That many short beeps, for counting. | 14 | /// That many short beeps, for counting. |
| 13 | case beeps(Int) | 15 | case beeps(Int) |
| 14 | 16 | ||
| 15 | static let allCases: [SoundEffect] = | 17 | static let allCases: [SoundEffect] = |
| 16 | [.success, .gentleMiss, .roundComplete, .moo, .quack, .baa, .oink, .meow, .woof, .tweet, | 18 | [.success, .gentleMiss, .roundComplete, .moo, .quack, .baa, .oink, .meow, .woof, .tweet, |
| 17 | .rain, .wind, .thunder] + (1...5).map(SoundEffect.beeps) | 19 | .rain, .wind, .thunder, .whistle] + (1...5).map(SoundEffect.beeps) |
| 18 | } | 20 | } |
| 19 | 21 | ||
| 20 | /// Renders sound effects to mono sample buffers. Every sound fades in and out | 22 | /// Renders sound effects to mono sample buffers. Every sound fades in and out |
| @@ -52,6 +54,8 @@ nonisolated enum SoundSynth { | |||
| 52 | Note(frequency: 783.99, start: 0.4, duration: 0.7), | 54 | Note(frequency: 783.99, start: 0.4, duration: 0.7), |
| 53 | Note(frequency: 1046.5, start: 0.4, duration: 0.7), | 55 | Note(frequency: 1046.5, start: 0.4, duration: 0.7), |
| 54 | ], peak: 0.6) | 56 | ], peak: 0.6) |
| 57 | case .whistle: | ||
| 58 | whistle() | ||
| 55 | case .beeps(let count): | 59 | case .beeps(let count): |
| 56 | mix((0..<count).map { | 60 | mix((0..<count).map { |
| 57 | Note(frequency: 660, start: 0.42 * Double($0), duration: 0.12, harmonics: [1, 0.2]) | 61 | Note(frequency: 660, start: 0.42 * Double($0), duration: 0.12, harmonics: [1, 0.2]) |
| @@ -164,6 +168,19 @@ nonisolated enum SoundSynth { | |||
| 164 | var noise = 0.0 | 168 | var noise = 0.0 |
| 165 | } | 169 | } |
| 166 | 170 | ||
| 171 | /// Two steady, nearly pure tones a major third apart with a little | ||
| 172 | /// vibrato and breath, like a toy train whistle. | ||
| 173 | private static func whistle() -> [Float] { | ||
| 174 | let tones = [600.0, 755.0].enumerated().map { i, f in | ||
| 175 | voiceSamples(Voice(duration: 0.9, pitch: [(0, f * 0.97), (0.15, f), (1, f)], | ||
| 176 | rolloff: 2, maxHarmonics: 6, vibrato: (5.5, 0.006), | ||
| 177 | attack: 0.08, release: 0.2, noise: 0.03), | ||
| 178 | seed: UInt64(10 + i)) | ||
| 179 | } | ||
| 180 | let count = min(tones[0].count, tones[1].count) | ||
| 181 | return normalized(padded((0..<count).map { tones[0][$0] + tones[1][$0] }), peak: 0.4) | ||
| 182 | } | ||
| 183 | |||
| 167 | private static func voice(_ v: Voice, peak: Float) -> [Float] { | 184 | private static func voice(_ v: Voice, peak: Float) -> [Float] { |
| 168 | normalized(padded(voiceSamples(v, seed: 1)), peak: peak) | 185 | normalized(padded(voiceSamples(v, seed: 1)), peak: peak) |
| 169 | } | 186 | } |
DayByDay/SpeechSynthesizer.swift +18 −3
| @@ -9,15 +9,19 @@ import UIKit | |||
| 9 | /// Wrapper around AVSpeechSynthesizer that selects the highest-quality | 9 | /// Wrapper around AVSpeechSynthesizer that selects the highest-quality |
| 10 | /// en-US neural voice available on the device. Falls back gracefully if | 10 | /// en-US neural voice available on the device. Falls back gracefully if |
| 11 | /// premium/enhanced voices haven't been downloaded yet. | 11 | /// premium/enhanced voices haven't been downloaded yet. |
| 12 | final class SpeechSynthesizer { | 12 | final class SpeechSynthesizer: NSObject, AVSpeechSynthesizerDelegate { |
| 13 | static let shared = SpeechSynthesizer() | 13 | static let shared = SpeechSynthesizer() |
| 14 | 14 | ||
| 15 | private let synthesizer = AVSpeechSynthesizer() | 15 | private let synthesizer = AVSpeechSynthesizer() |
| 16 | private let voice: AVSpeechSynthesisVoice? | 16 | private let voice: AVSpeechSynthesisVoice? |
| 17 | private let haptics = UIImpactFeedbackGenerator(style: .rigid) | 17 | private let haptics = UIImpactFeedbackGenerator(style: .rigid) |
| 18 | /// Run when the matching utterance finishes; dropped if it is cut off. | ||
| 19 | private var completions: [ObjectIdentifier: () -> Void] = [:] | ||
| 18 | 20 | ||
| 19 | private init() { | 21 | private override init() { |
| 20 | self.voice = Self.bestAvailableVoice() | 22 | self.voice = Self.bestAvailableVoice() |
| 23 | super.init() | ||
| 24 | synthesizer.delegate = self | ||
| 21 | } | 25 | } |
| 22 | 26 | ||
| 23 | /// Speaks a pre-configured utterance directly. Used for warmup at launch. | 27 | /// Speaks a pre-configured utterance directly. Used for warmup at launch. |
| @@ -25,7 +29,7 @@ final class SpeechSynthesizer { | |||
| 25 | synthesizer.speak(utterance) | 29 | synthesizer.speak(utterance) |
| 26 | } | 30 | } |
| 27 | 31 | ||
| 28 | func speak(_ text: String) { | 32 | func speak(_ text: String, completion: (() -> Void)? = nil) { |
| 29 | // Every speak() call is a card tap, so give a gentle tactile bump | 33 | // Every speak() call is a card tap, so give a gentle tactile bump |
| 30 | // alongside the audio. Prepared just before firing for lowest latency. | 34 | // alongside the audio. Prepared just before firing for lowest latency. |
| 31 | haptics.prepare() | 35 | haptics.prepare() |
| @@ -44,6 +48,7 @@ final class SpeechSynthesizer { | |||
| 44 | utterance.rate = 0.4 | 48 | utterance.rate = 0.4 |
| 45 | utterance.pitchMultiplier = 1.0 | 49 | utterance.pitchMultiplier = 1.0 |
| 46 | utterance.preUtteranceDelay = 0 | 50 | utterance.preUtteranceDelay = 0 |
| 51 | if let completion { completions[ObjectIdentifier(utterance)] = completion } | ||
| 47 | synthesizer.speak(utterance) | 52 | synthesizer.speak(utterance) |
| 48 | } | 53 | } |
| 49 | 54 | ||
| @@ -51,6 +56,16 @@ final class SpeechSynthesizer { | |||
| 51 | synthesizer.stopSpeaking(at: .immediate) | 56 | synthesizer.stopSpeaking(at: .immediate) |
| 52 | } | 57 | } |
| 53 | 58 | ||
| 59 | nonisolated func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { | ||
| 60 | let id = ObjectIdentifier(utterance) | ||
| 61 | Task { @MainActor in completions.removeValue(forKey: id)?() } | ||
| 62 | } | ||
| 63 | |||
| 64 | nonisolated func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) { | ||
| 65 | let id = ObjectIdentifier(utterance) | ||
| 66 | Task { @MainActor in _ = completions.removeValue(forKey: id) } | ||
| 67 | } | ||
| 68 | |||
| 54 | /// Picks the best en-US voice on the device. | 69 | /// Picks the best en-US voice on the device. |
| 55 | /// Filters for en-US, excludes novelty voices, then sorts by quality | 70 | /// Filters for en-US, excludes novelty voices, then sorts by quality |
| 56 | /// descending so premium (3) > enhanced (2) > default (1). | 71 | /// descending so premium (3) > enhanced (2) > default (1). |
DayByDayTests/ContrastTests.swift +19
| @@ -35,6 +35,25 @@ struct ContrastTests { | |||
| 35 | } | 35 | } |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | @Test(arguments: Season.allCases) func wheelColorAgainstWhite(_ season: Season) { | ||
| 39 | for style in Self.styles { | ||
| 40 | #expect(contrast(season.wheelColor, .white, style) >= 3, "\(season)") | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | /// Uncounted objects sit on the page background in the numbers color. | ||
| 45 | @Test func countingObjectsAgainstBackground() { | ||
| 46 | let numbers = DayByDay.Category.numbers.color | ||
| 47 | #expect(contrast(numbers, .white, .light) >= 3) | ||
| 48 | #expect(contrast(numbers, .black, .dark) >= 3) | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Train wheels sit on the page background in both modes. | ||
| 52 | @Test func trainTireAgainstBackgrounds() { | ||
| 53 | #expect(contrast(TrainStyle.tire, .white, .light) >= 3) | ||
| 54 | #expect(contrast(TrainStyle.tire, .black, .dark) >= 3) | ||
| 55 | } | ||
| 56 | |||
| 38 | @Test func playAgainAgainstWhite() { | 57 | @Test func playAgainAgainstWhite() { |
| 39 | #expect(contrast(RoundStyle.playAgainFill, .white, .light) >= 3) | 58 | #expect(contrast(RoundStyle.playAgainFill, .white, .light) >= 3) |
| 40 | } | 59 | } |
DayByDayTests/CountingTests.swift added +81
| @@ -0,0 +1,81 @@ | |||
| 1 | import Testing | ||
| 2 | @testable import DayByDay | ||
| 3 | |||
| 4 | struct CountingTests { | ||
| 5 | func round(target: Int, seed: UInt64 = 51) -> CountingRound { | ||
| 6 | var rng = SeededGenerator(seed: seed) | ||
| 7 | return CountingRound(target: target, thing: CountingRound.things[0], using: &rng) | ||
| 8 | } | ||
| 9 | |||
| 10 | @Test func countsEachObjectOnce() { | ||
| 11 | var r = round(target: 4) | ||
| 12 | #expect(r.tap(0) == 1) | ||
| 13 | #expect(r.tap(1) == 2) | ||
| 14 | #expect(r.tap(1) == nil) | ||
| 15 | #expect(r.tap(2) == 3) | ||
| 16 | #expect(r.counted == [0, 1, 2]) | ||
| 17 | } | ||
| 18 | |||
| 19 | @Test func ignoresOutOfRangeAndDone() { | ||
| 20 | var r = round(target: 2) | ||
| 21 | #expect(r.tap(2) == nil) | ||
| 22 | #expect(r.tap(-1) == nil) | ||
| 23 | _ = r.tap(0); _ = r.tap(1) | ||
| 24 | #expect(r.isSetDone) | ||
| 25 | #expect(r.tap(0) == nil) | ||
| 26 | } | ||
| 27 | |||
| 28 | @Test func setsNeverRepeatTarget() { | ||
| 29 | var rng = SeededGenerator(seed: 52) | ||
| 30 | var r = CountingRound(using: &rng) | ||
| 31 | var previous = r.target | ||
| 32 | for _ in 0..<200 { | ||
| 33 | for i in 0..<r.target { _ = r.tap(i) } | ||
| 34 | r.nextSet(using: &rng) | ||
| 35 | if r.isComplete { | ||
| 36 | r = CountingRound(using: &rng) | ||
| 37 | previous = r.target | ||
| 38 | continue | ||
| 39 | } | ||
| 40 | #expect((1...10).contains(r.target)) | ||
| 41 | #expect(r.target != previous) | ||
| 42 | #expect(r.counted.isEmpty) | ||
| 43 | previous = r.target | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | @Test func completesAfterFiveSets() { | ||
| 48 | var rng = SeededGenerator(seed: 53) | ||
| 49 | var r = CountingRound(using: &rng) | ||
| 50 | for set in 1...CountingRound.length { | ||
| 51 | #expect(!r.isComplete) | ||
| 52 | let ignored = r.nextSetIgnoredUntilDone(using: &rng) | ||
| 53 | #expect(ignored) | ||
| 54 | for i in 0..<r.target { _ = r.tap(i) } | ||
| 55 | r.nextSet(using: &rng) | ||
| 56 | #expect(r.setsDone == set) | ||
| 57 | } | ||
| 58 | #expect(r.isComplete) | ||
| 59 | } | ||
| 60 | |||
| 61 | @Test func summaryCopy() { | ||
| 62 | let star = CountingRound.things[0] | ||
| 63 | #expect(round(target: 1).summary() == "One! There is one \(star.singular).") | ||
| 64 | #expect(round(target: 3).summary() == "Three! There are three \(star.plural).") | ||
| 65 | #expect(star.singular == "star" && star.plural == "stars") | ||
| 66 | } | ||
| 67 | |||
| 68 | @Test func thingsDiffer() { | ||
| 69 | #expect(CountingRound.things.map(\.singular) == ["star", "heart", "leaf", "moon", "fish"]) | ||
| 70 | #expect(CountingRound.things.map(\.plural) == ["stars", "hearts", "leaves", "moons", "fish"]) | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | extension CountingRound { | ||
| 75 | /// nextSet() before the set is done must not advance. | ||
| 76 | mutating func nextSetIgnoredUntilDone(using rng: inout some RandomNumberGenerator) -> Bool { | ||
| 77 | let before = (target, setsDone) | ||
| 78 | nextSet(using: &rng) | ||
| 79 | return target == before.0 && setsDone == before.1 | ||
| 80 | } | ||
| 81 | } | ||
DayByDayTests/GameTests.swift +15 −2
| @@ -1,4 +1,5 @@ | |||
| 1 | import Testing | 1 | import Testing |
| 2 | import UIKit | ||
| 2 | @testable import DayByDay | 3 | @testable import DayByDay |
| 3 | 4 | ||
| 4 | struct GameTests { | 5 | struct GameTests { |
| @@ -10,11 +11,15 @@ struct GameTests { | |||
| 10 | } | 11 | } |
| 11 | #expect(Topic.gridCases.filter { $0.games.contains(.oddOneOut) } == [.shapes, .animals, .food]) | 12 | #expect(Topic.gridCases.filter { $0.games.contains(.oddOneOut) } == [.shapes, .animals, .food]) |
| 12 | #expect(Topic.gridCases.filter { $0.games.contains(.listen) } == [.numbers, .animals, .alphabet, .weather]) | 13 | #expect(Topic.gridCases.filter { $0.games.contains(.listen) } == [.numbers, .animals, .alphabet, .weather]) |
| 14 | #expect(Topic.days.games == [.findIt, .comesNext, .weekTrain, .yesterdayTomorrow]) | ||
| 15 | #expect(Topic.months.games == [.findIt, .comesNext, .yearWheel]) | ||
| 16 | #expect(Topic.seasons.games == [.findIt, .whichSeason]) | ||
| 17 | #expect(Topic.numbers.games == [.findIt, .listen, .counting, .most]) | ||
| 13 | } | 18 | } |
| 14 | 19 | ||
| 15 | @Test(arguments: Topic.gridCases) func everyGameMakesValidQuestions(_ c: Topic) { | 20 | @Test(arguments: Topic.gridCases) func everyGameMakesValidQuestions(_ c: Topic) { |
| 16 | var rng = SeededGenerator(seed: 21) | 21 | var rng = SeededGenerator(seed: 21) |
| 17 | for game in c.games { | 22 | for game in c.games where game.usesRound { |
| 18 | let source = c.questionSource(for: game) | 23 | let source = c.questionSource(for: game) |
| 19 | var previous: QuizItem? | 24 | var previous: QuizItem? |
| 20 | for i in 0..<300 { | 25 | for i in 0..<300 { |
| @@ -112,7 +117,9 @@ struct GameTests { | |||
| 112 | } | 117 | } |
| 113 | 118 | ||
| 114 | @Test func titles() { | 119 | @Test func titles() { |
| 115 | #expect(Game.allCases.map(\.title) == ["Find it!", "Odd one out", "Listen"]) | 120 | #expect(Game.allCases.map(\.title) == ["Find it!", "Odd one out", "Listen", |
| 121 | "What comes next?", "Week train", "Yesterday and tomorrow", | ||
| 122 | "Year wheel", "Which season?", "Count with me", "Which has the most?"]) | ||
| 116 | } | 123 | } |
| 117 | 124 | ||
| 118 | /// The prompt names the rule, so only one choice fits it. | 125 | /// The prompt names the rule, so only one choice fits it. |
| @@ -137,3 +144,9 @@ struct GameTests { | |||
| 137 | } | 144 | } |
| 138 | } | 145 | } |
| 139 | } | 146 | } |
| 147 | |||
| 148 | struct GameSymbolTests { | ||
| 149 | @Test(arguments: Game.allCases) func symbolExists(_ game: Game) { | ||
| 150 | #expect(UIImage(systemName: game.symbol) != nil) | ||
| 151 | } | ||
| 152 | } | ||
DayByDayTests/OrderSourcesTests.swift added +90
| @@ -0,0 +1,90 @@ | |||
| 1 | import Testing | ||
| 2 | @testable import DayByDay | ||
| 3 | |||
| 4 | struct OrderSourcesTests { | ||
| 5 | typealias Topic = DayByDay.Category | ||
| 6 | |||
| 7 | func asked(_ q: Question) -> String { | ||
| 8 | let after = q.prompt.components(separatedBy: "after ").last! | ||
| 9 | return String(after.dropLast()) | ||
| 10 | } | ||
| 11 | |||
| 12 | @Test func monthSeasons() { | ||
| 13 | #expect([MonthOfYear.december, .january, .february].allSatisfy { $0.season == .winter }) | ||
| 14 | #expect(MonthOfYear.march.season == .spring) | ||
| 15 | #expect(MonthOfYear.june.season == .summer) | ||
| 16 | #expect([MonthOfYear.september, .november].allSatisfy { $0.season == .fall }) | ||
| 17 | } | ||
| 18 | |||
| 19 | @Test func comesNextWraps() { | ||
| 20 | var rng = SeededGenerator(seed: 31) | ||
| 21 | let days = ComesNext(items: Topic.days.quizItems, noun: "day") | ||
| 22 | let months = ComesNext(items: Topic.months.quizItems, noun: "month") | ||
| 23 | var sawSaturday = false, sawDecember = false | ||
| 24 | for i in 0..<300 { | ||
| 25 | let d = days.next(correctCount: i % 5, excluding: nil, using: &rng) | ||
| 26 | if asked(d) == "Saturday" { sawSaturday = true; #expect(d.answer.name == "Sunday") } | ||
| 27 | let m = months.next(correctCount: i % 5, excluding: nil, using: &rng) | ||
| 28 | if asked(m) == "December" { sawDecember = true; #expect(m.answer.name == "January") } | ||
| 29 | } | ||
| 30 | #expect(sawSaturday && sawDecember) | ||
| 31 | } | ||
| 32 | |||
| 33 | @Test func comesNextPrompt() { | ||
| 34 | var rng = SeededGenerator(seed: 32) | ||
| 35 | let q = ComesNext(items: Topic.days.quizItems, noun: "day").next(correctCount: 0, excluding: nil, using: &rng) | ||
| 36 | #expect(q.prompt == "What day comes after \(asked(q))?") | ||
| 37 | } | ||
| 38 | |||
| 39 | @Test func comesNextNeverOffersAskedItem() { | ||
| 40 | var rng = SeededGenerator(seed: 33) | ||
| 41 | let source = ComesNext(items: Topic.days.quizItems, noun: "day") | ||
| 42 | var previous: QuizItem? | ||
| 43 | for i in 0..<300 { | ||
| 44 | let q = source.next(correctCount: i % 5, excluding: previous, using: &rng) | ||
| 45 | #expect(!q.choices.map(\.name).contains(asked(q))) | ||
| 46 | #expect(q.answer != previous) | ||
| 47 | previous = q.answer | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | @Test func comesNextCorrection() { | ||
| 52 | var rng = SeededGenerator(seed: 34) | ||
| 53 | let q = ComesNext(items: Topic.days.quizItems, noun: "day").next(correctCount: 0, excluding: nil, using: &rng) | ||
| 54 | let wrong = q.choices.first { $0 != q.answer }! | ||
| 55 | #expect(q.correction(for: wrong) == "\(q.answer.name) comes after \(asked(q)). Try again!") | ||
| 56 | } | ||
| 57 | |||
| 58 | @Test func whichSeasonPromptMatchesAnswer() { | ||
| 59 | var rng = SeededGenerator(seed: 35) | ||
| 60 | for i in 0..<300 { | ||
| 61 | let q = WhichSeason().next(correctCount: i % 5, excluding: nil, using: &rng) | ||
| 62 | let monthName = q.prompt.replacingOccurrences(of: "Which season is ", with: "") | ||
| 63 | .replacingOccurrences(of: " in?", with: "") | ||
| 64 | let month = MonthOfYear.allCases.first { $0.name == monthName }! | ||
| 65 | #expect(Topic.seasons.item(month.season) == q.answer) | ||
| 66 | let wrong = q.choices.first { $0 != q.answer }! | ||
| 67 | #expect(q.correction(for: wrong) == "\(monthName) is in \(q.answer.name). Try again!") | ||
| 68 | } | ||
| 69 | } | ||
| 70 | |||
| 71 | @Test func mostAnswerIsLargest() { | ||
| 72 | var rng = SeededGenerator(seed: 36) | ||
| 73 | var previous: QuizItem? | ||
| 74 | for i in 0..<300 { | ||
| 75 | let q = Most().next(correctCount: i % 5, excluding: previous, using: &rng) | ||
| 76 | let answer = q.answer.value(LearnNumber.self)!.numeral | ||
| 77 | #expect(q.choices.filter { $0 != q.answer }.allSatisfy { $0.value(LearnNumber.self)!.numeral < answer }) | ||
| 78 | #expect(Set(q.choices).count == q.choices.count) | ||
| 79 | #expect(q.answer != previous) | ||
| 80 | previous = q.answer | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | @Test func mostFacts() { | ||
| 85 | var rng = SeededGenerator(seed: 37) | ||
| 86 | let q = Most().next(correctCount: 0, excluding: nil, using: &rng) | ||
| 87 | let wrong = q.choices.first { $0 != q.answer }! | ||
| 88 | #expect(q.correction(for: wrong) == "That one has \(wrong.value(LearnNumber.self)!.numeral). Try again!") | ||
| 89 | } | ||
| 90 | } | ||
DayByDayTests/ReviewExport.swift +48
| @@ -1,5 +1,6 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import SwiftUI | 2 | import SwiftUI |
| 3 | import UIKit | ||
| 3 | import Testing | 4 | import Testing |
| 4 | @testable import DayByDay | 5 | @testable import DayByDay |
| 5 | 6 | ||
| @@ -52,6 +53,53 @@ struct ReviewExport { | |||
| 52 | try png(drawn).write(to: dir.appendingPathComponent("animals-large.png")) | 53 | try png(drawn).write(to: dir.appendingPathComponent("animals-large.png")) |
| 53 | } | 54 | } |
| 54 | 55 | ||
| 56 | @Test func games() async throws { | ||
| 57 | try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) | ||
| 58 | let container = ProfileStore.makeContainer(inMemory: true) | ||
| 59 | let session = ProfileSession(store: ProfileStore(context: container.mainContext)) | ||
| 60 | var rng = SeededGenerator(seed: 1) | ||
| 61 | var train = SequencePuzzle.weekTrain(using: &rng) | ||
| 62 | for d in [DayOfWeek.sunday, .monday, .tuesday] { _ = train.place(DayByDay.Category.days.item(d)) } | ||
| 63 | var slots = SequencePuzzle.yesterdayTomorrow(today: .friday, using: &rng) | ||
| 64 | _ = slots.place(DayByDay.Category.days.item(DayOfWeek.thursday)) | ||
| 65 | let screens: [(String, AnyView)] = [ | ||
| 66 | ("train-start", AnyView(SequencePuzzleView(game: .weekTrain) { .weekTrain(using: &rng) })), | ||
| 67 | ("train", AnyView(SequencePuzzleView(game: .weekTrain) { train })), | ||
| 68 | ("slots", AnyView(SequencePuzzleView(game: .yesterdayTomorrow) { slots })), | ||
| 69 | ("wheel", AnyView(YearWheelView())), | ||
| 70 | ("counting", AnyView(CountingView())), | ||
| 71 | ("piles", AnyView(HStack(spacing: 20) { | ||
| 72 | ForEach([3, 7, 10], id: \.self) { n in | ||
| 73 | PileTile(item: DayByDay.Category.numbers.item(LearnNumber(rawValue: n)!)).frame(width: 170, height: 160) | ||
| 74 | } | ||
| 75 | })), | ||
| 76 | ] | ||
| 77 | for (name, view) in screens { | ||
| 78 | for scheme in [ColorScheme.light, .dark] { | ||
| 79 | let page = view | ||
| 80 | .background(Color(.systemBackground)) | ||
| 81 | .environment(session) | ||
| 82 | .environment(\.colorScheme, scheme) | ||
| 83 | try await windowPNG(page).write(to: dir.appendingPathComponent("game-\(name)-\(scheme).png")) | ||
| 84 | } | ||
| 85 | } | ||
| 86 | } | ||
| 87 | |||
| 88 | /// Renders through a real window, which draws scroll views (ImageRenderer does not). | ||
| 89 | private func windowPNG(_ view: some View, size: CGSize = CGSize(width: 402, height: 874)) async throws -> Data { | ||
| 90 | let scene = try #require(UIApplication.shared.connectedScenes.first as? UIWindowScene) | ||
| 91 | let window = UIWindow(windowScene: scene) | ||
| 92 | window.frame = CGRect(origin: .zero, size: size) | ||
| 93 | window.rootViewController = UIHostingController(rootView: view) | ||
| 94 | window.makeKeyAndVisible() | ||
| 95 | try await Task.sleep(for: .milliseconds(600)) | ||
| 96 | let image = UIGraphicsImageRenderer(size: size).image { _ in | ||
| 97 | window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) | ||
| 98 | } | ||
| 99 | window.isHidden = true | ||
| 100 | return try #require(image.pngData()) | ||
| 101 | } | ||
| 102 | |||
| 55 | private func png(_ view: some View) throws -> Data { | 103 | private func png(_ view: some View) throws -> Data { |
| 56 | let renderer = ImageRenderer(content: view) | 104 | let renderer = ImageRenderer(content: view) |
| 57 | renderer.scale = 2 | 105 | renderer.scale = 2 |
DayByDayTests/SequencePuzzleTests.swift added +88
| @@ -0,0 +1,88 @@ | |||
| 1 | import Testing | ||
| 2 | @testable import DayByDay | ||
| 3 | |||
| 4 | struct SequencePuzzleTests { | ||
| 5 | let days = DayByDay.Category.days | ||
| 6 | |||
| 7 | func day(_ d: DayOfWeek) -> QuizItem { days.item(d) } | ||
| 8 | |||
| 9 | func train(seed: UInt64 = 41) -> SequencePuzzle { | ||
| 10 | var rng = SeededGenerator(seed: seed) | ||
| 11 | return .weekTrain(using: &rng) | ||
| 12 | } | ||
| 13 | |||
| 14 | @Test func trainOrder() { | ||
| 15 | let p = train() | ||
| 16 | #expect(p.steps.map(\.answer) == DayOfWeek.allCases.map(day)) | ||
| 17 | #expect(Set(p.pool) == Set(DayOfWeek.allCases.map(day))) | ||
| 18 | #expect(p.pool.count == 7) | ||
| 19 | #expect(p.steps[0].prompt == "Which day comes first?") | ||
| 20 | #expect(p.slotLabels == nil) | ||
| 21 | } | ||
| 22 | |||
| 23 | @Test(arguments: DayOfWeek.allCases) func yesterdayTomorrowWraps(_ today: DayOfWeek) { | ||
| 24 | var rng = SeededGenerator(seed: 42) | ||
| 25 | let p = SequencePuzzle.yesterdayTomorrow(today: today, using: &rng) | ||
| 26 | let i = today.rawValue | ||
| 27 | let expected = [(i + 6) % 7, i, (i + 1) % 7].map { day(DayOfWeek(rawValue: $0)!) } | ||
| 28 | #expect(p.steps.map(\.answer) == expected) | ||
| 29 | #expect(p.pool.count == 4) | ||
| 30 | #expect(Set(p.pool).count == 4) | ||
| 31 | #expect(Set(expected).isSubset(of: Set(p.pool))) | ||
| 32 | #expect(p.slotLabels == ["Yesterday", "Today", "Tomorrow"]) | ||
| 33 | #expect(p.steps.map(\.prompt) == ["Which day was yesterday?", "Which day is today?", "Which day will it be tomorrow?"]) | ||
| 34 | } | ||
| 35 | |||
| 36 | @Test func correctPlacementAdvances() { | ||
| 37 | var p = train() | ||
| 38 | #expect(p.place(day(.sunday)) == .correct) | ||
| 39 | #expect(p.placed == [day(.sunday)]) | ||
| 40 | #expect(p.current?.prompt == "What comes after Sunday?") | ||
| 41 | } | ||
| 42 | |||
| 43 | @Test func wrongPlacementWaits() { | ||
| 44 | var p = train() | ||
| 45 | #expect(p.place(day(.tuesday)) == .incorrect(correctName: "Sunday")) | ||
| 46 | #expect(p.place(day(.sunday)) == .ignored) | ||
| 47 | p.resume() | ||
| 48 | #expect(p.place(day(.sunday)) == .correct) | ||
| 49 | } | ||
| 50 | |||
| 51 | @Test func placedCardIgnored() { | ||
| 52 | var p = train() | ||
| 53 | _ = p.place(day(.sunday)) | ||
| 54 | #expect(p.place(day(.sunday)) == .ignored) | ||
| 55 | #expect(p.placed.count == 1) | ||
| 56 | } | ||
| 57 | |||
| 58 | @Test func solvedIgnoresInput() { | ||
| 59 | var p = train() | ||
| 60 | for d in DayOfWeek.allCases { #expect(p.place(day(d)) == .correct) } | ||
| 61 | #expect(p.isSolved) | ||
| 62 | #expect(p.current == nil) | ||
| 63 | #expect(p.place(day(.monday)) == .ignored) | ||
| 64 | } | ||
| 65 | |||
| 66 | @Test func corrections() { | ||
| 67 | var rng = SeededGenerator(seed: 43) | ||
| 68 | var p = SequencePuzzle.yesterdayTomorrow(today: .friday, using: &rng) | ||
| 69 | let wrong = p.pool.first { $0 != day(.thursday) }! | ||
| 70 | _ = p.place(wrong) | ||
| 71 | #expect(p.correction() == "Yesterday was Thursday. Try again!") | ||
| 72 | p.resume() | ||
| 73 | _ = p.place(day(.thursday)) | ||
| 74 | #expect(p.correction() == "Today is Friday. Try again!") | ||
| 75 | |||
| 76 | var t = train() | ||
| 77 | #expect(t.correction() == "Sunday comes first. Try again!") | ||
| 78 | _ = t.place(day(.sunday)) | ||
| 79 | #expect(t.correction() == "Monday comes next. Try again!") | ||
| 80 | } | ||
| 81 | |||
| 82 | @Test func solvedSummary() { | ||
| 83 | var rng = SeededGenerator(seed: 44) | ||
| 84 | #expect(SequencePuzzle.yesterdayTomorrow(today: .friday, using: &rng).summary | ||
| 85 | == "Yesterday was Thursday, today is Friday, and tomorrow will be Saturday!") | ||
| 86 | #expect(train().summary == "Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday!") | ||
| 87 | } | ||
| 88 | } | ||
DayByDayTests/SoundSynthTests.swift +1
| @@ -62,6 +62,7 @@ struct SoundSynthTests { | |||
| 62 | for n in 1...5 { | 62 | for n in 1...5 { |
| 63 | #expect(abs(seconds(SoundSynth.render(.beeps(n))) - (0.42 * Double(n - 1) + 0.12)) < 0.02) | 63 | #expect(abs(seconds(SoundSynth.render(.beeps(n))) - (0.42 * Double(n - 1) + 0.12)) < 0.02) |
| 64 | } | 64 | } |
| 65 | #expect((0.6...1.2).contains(seconds(SoundSynth.render(.whistle)))) | ||
| 65 | #expect(SoundSynth.duration(.moo) == seconds(SoundSynth.render(.moo))) | 66 | #expect(SoundSynth.duration(.moo) == seconds(SoundSynth.render(.moo))) |
| 66 | } | 67 | } |
| 67 | 68 | ||
DayByDayTests/SpeechCompletionTests.swift added +24
| @@ -0,0 +1,24 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import DayByDay | ||
| 4 | |||
| 5 | @MainActor | ||
| 6 | @Suite(.serialized, .timeLimit(.minutes(1))) | ||
| 7 | struct SpeechCompletionTests { | ||
| 8 | @Test func completionFiresWhenSpeechEnds() async { | ||
| 9 | let fired: Bool = await withCheckedContinuation { cont in | ||
| 10 | SpeechSynthesizer.shared.speak("One.") { cont.resume(returning: true) } | ||
| 11 | } | ||
| 12 | #expect(fired) | ||
| 13 | } | ||
| 14 | |||
| 15 | @Test func interruptedSpeechDoesNotComplete() async throws { | ||
| 16 | var first = false | ||
| 17 | SpeechSynthesizer.shared.speak("Sunday, Monday, Tuesday, Wednesday.") { first = true } | ||
| 18 | try await Task.sleep(for: .milliseconds(300)) | ||
| 19 | await withCheckedContinuation { cont in | ||
| 20 | SpeechSynthesizer.shared.speak("Two.") { cont.resume() } | ||
| 21 | } | ||
| 22 | #expect(!first) | ||
| 23 | } | ||
| 24 | } | ||
DayByDayTests/YearWheelTests.swift added +31
| @@ -0,0 +1,31 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import DayByDay | ||
| 4 | |||
| 5 | struct YearWheelTests { | ||
| 6 | @Test func monthAtRotation() { | ||
| 7 | #expect(YearWheel.month(atRotation: 0) == .january) | ||
| 8 | #expect(YearWheel.month(atRotation: 30) == .december) | ||
| 9 | #expect(YearWheel.month(atRotation: -30) == .february) | ||
| 10 | #expect(YearWheel.month(atRotation: 360 * 7 + 30) == .december) | ||
| 11 | #expect(YearWheel.month(atRotation: -360 * 5 - 60) == .march) | ||
| 12 | // Within half a wedge of a center still counts as that month. | ||
| 13 | #expect(YearWheel.month(atRotation: 14) == .january) | ||
| 14 | #expect(YearWheel.month(atRotation: 16) == .december) | ||
| 15 | } | ||
| 16 | |||
| 17 | @Test(arguments: MonthOfYear.allCases) func targetLandsOnMonth(_ m: MonthOfYear) { | ||
| 18 | for rotation in [0, 47.5, -800, 12345] { | ||
| 19 | let t = YearWheel.target(from: rotation, landingOn: m, turns: 3) | ||
| 20 | #expect(t >= rotation + 1080) | ||
| 21 | #expect(t < rotation + 1080 + 360) | ||
| 22 | #expect(YearWheel.month(atRotation: t) == m) | ||
| 23 | #expect(abs(t / 30 - (t / 30).rounded()) < 1e-9) | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | @Test func landingLine() { | ||
| 28 | #expect(YearWheel.line(for: .july) == "July! July is in summer.") | ||
| 29 | #expect(YearWheel.line(for: .december) == "December! December is in winter.") | ||
| 30 | } | ||
| 31 | } | ||
docs/superpowers/plans/2026-10-16-part3-ordering-games.md added +219
| @@ -0,0 +1,219 @@ | |||
| 1 | # Part 3: Ordering and Quantity Games Implementation Plan | ||
| 2 | |||
| 3 | > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. | ||
| 4 | |||
| 5 | **Goal:** Ordering games for days, months and seasons (week train, yesterday/today/tomorrow, "what comes after", year wheel, "which season") and quantity games for numbers (count with me, which has the most), each reached from its topic hub. | ||
| 6 | |||
| 7 | **Architecture:** Question-style games reuse `Round`/`RoundView` through new `QuestionSource`s (`ComesNext`, `WhichSeason`, `Most`). Placement games run on a pure `SequencePuzzle` (ordered steps, a card pool, tap or drag to place) drawn by one `SequencePuzzleView` with a train layout and a three-slot layout. The year wheel and counting are their own small models (`YearWheel`, `CountingRound`) with their own views. `Game` gains the new cases; `Game.usesRound` and a `GameDestination` view let the hub open either kind. | ||
| 8 | |||
| 9 | **Tech Stack:** SwiftUI (`draggable`/`dropDestination` with `String` payloads), SwiftData, AVFoundation, Swift Testing, Xcode 27. | ||
| 10 | |||
| 11 | **Spec:** `docs/superpowers/specs/2026-10-16-learning-games-design.md` (part 3). Builds on the part 1 and part 2 plans in this folder. | ||
| 12 | |||
| 13 | ## Global Constraints | ||
| 14 | |||
| 15 | - Effective deployment target is iOS 17.5. | ||
| 16 | - `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`. Pure logic types and extensions are `nonisolated`. | ||
| 17 | - New app files under `DayByDay/`, new tests under `DayByDayTests/`. | ||
| 18 | - No bundled image or audio files. All sound synthesized; all art in SwiftUI shapes and SF Symbols. | ||
| 19 | - Nothing requires reading. Every prompt is spoken; every card shows a symbol plus its name, like the existing day/month/season choice tiles. | ||
| 20 | - Wrong answers: `.gentleMiss` plus a spoken correction. No buzzer, no red X. | ||
| 21 | - Drag is never required: tapping a card places it too. Drop targets are the whole slot area, not a single slot. | ||
| 22 | - Reduce Motion: the year wheel jumps to its result instead of spinning; no other new motion beyond existing celebration. | ||
| 23 | - White content on any new fill is at least 3:1, covered in `ContrastTests`. | ||
| 24 | - Weeks start on Sunday. The season is "Fall". Seasons by month: Mar–May spring, Jun–Aug summer, Sep–Nov fall, Dec–Feb winter (matches `Season.current`). | ||
| 25 | - `Game` raw values are persisted in `AnswerRecord.gameRaw`; never rename existing ones. | ||
| 26 | - No new required SwiftData fields (no `VersionedSchema` yet). | ||
| 27 | - Branch `feat/ordering-games` from `main`. Every commit `Ref #N` (last `Closes #N`). No AI attribution anywhere. | ||
| 28 | - Test command: `xcodebuild test -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 18 Pro'` (add `-only-testing:DayByDayTests/<Suite>`). | ||
| 29 | |||
| 30 | ## Review Focus | ||
| 31 | |||
| 32 | 1. Wrap-around: "What day comes after Saturday?" is Sunday; "after December" is January. Test in Task 1. | ||
| 33 | 2. Yesterday/tomorrow wrap at the week's ends (today Sunday → yesterday Saturday; today Saturday → tomorrow Sunday), for every weekday. Test in Task 3. | ||
| 34 | 3. Repeated or late input on placement games: a card already placed, a tap during a correction, or any tap after the puzzle is solved is ignored and records nothing. Test in Task 3. | ||
| 35 | 4. Year wheel rotation that has accumulated many turns or is negative still maps to the right month, and every spin lands exactly on the chosen month's center. Test in Task 5. | ||
| 36 | 5. Counting: tapping an already-counted object does not count it twice; taps after the set is done are ignored. Test in Task 6. | ||
| 37 | |||
| 38 | --- | ||
| 39 | |||
| 40 | ### Task 0: Branch and issue | ||
| 41 | |||
| 42 | - [ ] **Step 1:** `git checkout -b feat/ordering-games main` | ||
| 43 | - [ ] **Step 2:** `gitbay issue create --title "Part 3: ordering and quantity games" --json --file -` with a body naming the spec and this plan. Note the number as `N`. | ||
| 44 | - [ ] **Step 3:** `git add docs && git commit -m "docs: part 3 plan" -m "Ref #N"` | ||
| 45 | |||
| 46 | ### Task 1: Question sources and catalog | ||
| 47 | |||
| 48 | **Files:** | ||
| 49 | - Create: `DayByDay/Quiz/OrderSources.swift` | ||
| 50 | - Modify: `DayByDay/Quiz/Game.swift`, `DayByDay/Quiz/ChoiceTile.swift` (make `Dots` internal; add `PileTile`) | ||
| 51 | - Test: `DayByDayTests/OrderSourcesTests.swift`, `DayByDayTests/GameTests.swift` | ||
| 52 | |||
| 53 | **Interfaces:** | ||
| 54 | - Produces: | ||
| 55 | - `nonisolated extension MonthOfYear { var season: Season }` (same months as `Season.current`). | ||
| 56 | - `Game` new cases (raw values as written): `comesNext, weekTrain, yesterdayTomorrow, yearWheel, whichSeason, counting, most`. Titles: "What comes next?", "Week train", "Yesterday and tomorrow", "Year wheel", "Which season?", "Count with me", "Which has the most?". Symbols: `arrow.right.circle.fill`, `train.side.front.car`, `calendar.day.timeline.left`, `circle.dashed`, `leaf.fill`, `hand.tap.fill`, `chart.bar.fill`. `var usesRound: Bool` (true for `findIt, oddOneOut, listen, comesNext, whichSeason, most`). | ||
| 57 | - `Category.games` after this task: days `[findIt, comesNext]`, months `[findIt, comesNext]`, seasons `[findIt, whichSeason]`, numbers `[findIt, listen, most]`; others unchanged. Later tasks append their special games. | ||
| 58 | - `nonisolated struct ComesNext: QuestionSource { init(items: [QuizItem], noun: String) }`. Picks an asked item, answer is the next item cyclically. Prompt `"What \(noun) comes after \(asked.name)?"`. The asked item is never a choice. Answer never equals `previous` when possible. Correction fact on a wrong tap: `"\(answer.name) comes after \(asked.name)."` (via `Question.facts` on every wrong choice). | ||
| 59 | - `nonisolated struct WhichSeason: QuestionSource`. Answer is a season; the prompt names a random month of it: `"Which season is \(month.name) in?"`. Choices are 3 or 4 seasons. Fact on a wrong tap: `"\(month.name) is in \(answer.name)."`. | ||
| 60 | - `nonisolated struct Most: QuestionSource`. Choices are distinct `LearnNumber` items from 1...10, answer is the largest. Prompt `"Which one has the most?"`. Fact on a wrong tap: `"That one has \(n)."`. Answer never equals `previous` when possible. | ||
| 61 | - `PileTile(item:)`: number-topic fill with dots only (no numeral), dots larger than in `ChoiceTile`. | ||
| 62 | |||
| 63 | - [ ] **Step 1:** Write failing tests in `OrderSourcesTests`: | ||
| 64 | |||
| 65 | ```swift | ||
| 66 | @Test func monthSeasons() // Dec, Jan, Feb → winter; Mar → spring; Jun → summer; Sep, Nov → fall | ||
| 67 | @Test func comesNextWraps() // seeded draws until asked == Saturday: answer == Sunday; asked == December: answer == January | ||
| 68 | @Test func comesNextNeverOffersAskedItem() // 300 draws: the name between "after " and "?" in the prompt is never a choice's name | ||
| 69 | @Test func whichSeasonPromptMatchesAnswer() // 300 draws: month named in prompt has .season == answer | ||
| 70 | @Test func mostAnswerIsLargest() // 300 draws: answer numeral > every other choice's numeral | ||
| 71 | @Test func mostFacts() // a wrong choice's correction == "That one has 3. Try again!" for numeral 3 | ||
| 72 | ``` | ||
| 73 | |||
| 74 | Update `GameTests.catalog` to the new `games` lists and limit `everyGameMakesValidQuestions` to `game.usesRound`. | ||
| 75 | |||
| 76 | - [ ] **Step 2:** Run `-only-testing:DayByDayTests/OrderSourcesTests -only-testing:DayByDayTests/GameTests`. Expected: build fails (types missing). | ||
| 77 | - [ ] **Step 3:** Implement. | ||
| 78 | - [ ] **Step 4:** Run the same command. Expected: PASS. | ||
| 79 | - [ ] **Step 5:** Commit `feat: what-comes-next, which-season and most question sources`. | ||
| 80 | |||
| 81 | ### Task 2: Hub destinations and finished screen | ||
| 82 | |||
| 83 | **Files:** | ||
| 84 | - Create: `DayByDay/Quiz/GameDestination.swift`, `DayByDay/Quiz/FinishedView.swift` | ||
| 85 | - Modify: `DayByDay/Quiz/RoundView.swift` (use `FinishedView`), `DayByDay/Home/CategoryHubView.swift` | ||
| 86 | |||
| 87 | **Interfaces:** | ||
| 88 | - Produces: | ||
| 89 | - `struct FinishedView: View { init(onPlayAgain: @escaping () -> Void) }`: the existing mascot, "You did it!", Play again button; plays `.roundComplete` and says "You did it!" on appear (moved from `RoundView` unchanged). | ||
| 90 | - `struct GameDestination: View { init(category: Category, game: Game) }`: `RoundView` with `ChoiceTile` for round games, `PileTile` for `.most`; later tasks add the special games to its switch. | ||
| 91 | - Hub uses `GameDestination` for every entry in `category.games`. | ||
| 92 | |||
| 93 | - [ ] **Step 1:** Build. Expected: `BUILD SUCCEEDED`. | ||
| 94 | - [ ] **Step 2:** Full suite. Expected: `** TEST SUCCEEDED **`. | ||
| 95 | - [ ] **Step 3:** Commit `feat: hub destinations for ordering games`. | ||
| 96 | |||
| 97 | ### Task 3: Sequence puzzle model | ||
| 98 | |||
| 99 | **Files:** | ||
| 100 | - Create: `DayByDay/Quiz/SequencePuzzle.swift` | ||
| 101 | - Test: `DayByDayTests/SequencePuzzleTests.swift` | ||
| 102 | |||
| 103 | **Interfaces:** | ||
| 104 | - Produces: `nonisolated struct SequencePuzzle`: | ||
| 105 | - `struct Step { let answer: QuizItem; let prompt: String }` | ||
| 106 | - `let steps: [Step]`, `let pool: [QuizItem]` (cards shown, shuffled once), `private(set) var placed: [QuizItem]`, `private(set) var isShowingCorrection` | ||
| 107 | - `var current: Step?` (nil when solved), `var isSolved: Bool` | ||
| 108 | - `mutating func place(_ item: QuizItem) -> AnswerOutcome`: `.ignored` when solved, during a correction, or when `item` is already placed; `.correct` when `item == current.answer` (appends to `placed`); otherwise `.incorrect(correctName:)` and `isShowingCorrection = true`. | ||
| 109 | - `mutating func resume()` | ||
| 110 | - `func correction(for item: QuizItem) -> String` — `"\(current.answer.name) comes next. Try again!"` for the train; slot puzzles pass their own copy (see below). | ||
| 111 | - `static func weekTrain(using rng: inout some RandomNumberGenerator) -> SequencePuzzle`: steps Sunday…Saturday; first prompt "Which day comes first?", then `"What comes after \(previous.name)?"`; pool is all 7 days shuffled. Correction: `"\(answer) comes next."`. | ||
| 112 | - `static func yesterdayTomorrow(today: DayOfWeek, using rng: inout some RandomNumberGenerator) -> SequencePuzzle`: steps yesterday, today, tomorrow with prompts "Which day was yesterday?", "Which day is today?", "Which day will it be tomorrow?"; pool is those three plus one other day, shuffled. Corrections: `"Yesterday was \(x)."`, `"Today is \(x)."`, `"Tomorrow will be \(x)."`. | ||
| 113 | - `let slotLabels: [String]?` — `["Yesterday", "Today", "Tomorrow"]` for that puzzle, nil for the train. | ||
| 114 | |||
| 115 | - [ ] **Step 1:** Write failing tests: | ||
| 116 | |||
| 117 | ```swift | ||
| 118 | @Test func trainOrder() // steps map to Sunday…Saturday; pool is a permutation of 7 days | ||
| 119 | @Test(arguments: DayOfWeek.allCases) func yesterdayTomorrowWraps(_ today: DayOfWeek) // answers == [today-1, today, today+1] mod 7; pool has 4 distinct days including those 3 | ||
| 120 | @Test func correctPlacementAdvances() // place Sunday → .correct, current.prompt == "What comes after Sunday?" | ||
| 121 | @Test func wrongPlacementWaits() // place Tuesday first → .incorrect(correctName: "Sunday"); place Sunday → .ignored until resume() | ||
| 122 | @Test func placedCardIgnored() // place Sunday, then Sunday again → .ignored | ||
| 123 | @Test func solvedIgnoresInput() // place all 7 → isSolved, any place → .ignored | ||
| 124 | @Test func corrections() // yesterdayTomorrow(today: .friday): wrong on step 0 → "Yesterday was Thursday. Try again!" | ||
| 125 | ``` | ||
| 126 | |||
| 127 | - [ ] **Step 2:** Run `-only-testing:DayByDayTests/SequencePuzzleTests`. Expected: FAIL (type missing). | ||
| 128 | - [ ] **Step 3:** Implement. | ||
| 129 | - [ ] **Step 4:** Run. Expected: PASS. | ||
| 130 | - [ ] **Step 5:** Commit `feat: sequence puzzle model`. | ||
| 131 | |||
| 132 | ### Task 4: Week train and yesterday/tomorrow views, whistle | ||
| 133 | |||
| 134 | **Files:** | ||
| 135 | - Create: `DayByDay/Quiz/SequencePuzzleView.swift` | ||
| 136 | - Modify: `DayByDay/Sound/SoundSynth.swift` (`.whistle`), `DayByDay/Quiz/Game.swift` (days games), `DayByDay/Quiz/GameDestination.swift` | ||
| 137 | - Test: `DayByDayTests/SoundSynthTests.swift`, `DayByDayTests/GameTests.swift` | ||
| 138 | |||
| 139 | **Interfaces:** | ||
| 140 | - Consumes: `SequencePuzzle`, `ChoiceTile`, `FinishedView`, `SoundEngine`, `ProfileStore.record`. | ||
| 141 | - Produces: | ||
| 142 | - `SoundEffect.whistle`: two-tone train whistle (sines near 600 and 750 Hz with soft harmonics, slight vibrato), 0.6–1.2 s, peak ≤ 0.6, included in `allCases`. | ||
| 143 | - `struct SequencePuzzleView: View { init(game: Game, make: @escaping () -> SequencePuzzle) }`: | ||
| 144 | - Top: the slots area. Train layout (no `slotLabels`): an engine shape plus 7 cars in a horizontal scroll, filled cars show the placed day tile, the next empty car is outlined. Slot layout: three labeled slots side by side, label text above each, the current slot outlined. | ||
| 145 | - Bottom: the unplaced pool cards as `ChoiceTile`s. Tap places; `.draggable(item.id)` onto the slots area's `.dropDestination(for: String.self)` places too. | ||
| 146 | - Speaks `current.prompt` on appear and after each correct placement; "Hear it again" button as in `RoundView`. | ||
| 147 | - Correct: `.success` + praise; wrong: `.gentleMiss`, dims the card, speaks the correction, `resume()` after 1.2 s. Each placement is recorded with `record(step.answer, chosen:, game:, correct:)`. | ||
| 148 | - Solved: `.whistle` (train) or `.success` (slots), speaks the full order ("Sunday, Monday, …, Saturday!" or "Yesterday was Thursday, today is Friday, tomorrow will be Saturday!"), then `FinishedView`; Play again calls `make()`. | ||
| 149 | - Days games become `[findIt, comesNext, weekTrain, yesterdayTomorrow]`. | ||
| 150 | |||
| 151 | - [ ] **Step 1:** Add `cueDurations` range for `.whistle` (0.6...1.2) and update `GameTests.catalog`. Run `-only-testing:DayByDayTests/SoundSynthTests -only-testing:DayByDayTests/GameTests`. Expected: FAIL (`.whistle` missing). | ||
| 152 | - [ ] **Step 2:** Implement `.whistle`, the view, catalog and destination. | ||
| 153 | - [ ] **Step 3:** Run the same tests (the parameterized clipping/click/DC tests now cover `.whistle`). Expected: PASS. | ||
| 154 | - [ ] **Step 4:** Simulator check (rendered-image or screenshot, taking two screenshots per step): both layouts render on iPhone 18 Pro; tapping cards places them; a wrong card dims. | ||
| 155 | - [ ] **Step 5:** Commit `feat: week train and yesterday/tomorrow games`. | ||
| 156 | |||
| 157 | ### Task 5: Year wheel | ||
| 158 | |||
| 159 | **Files:** | ||
| 160 | - Create: `DayByDay/Quiz/YearWheel.swift` (model), `DayByDay/Quiz/YearWheelView.swift` | ||
| 161 | - Modify: `DayByDay/Quiz/Game.swift` (months games), `DayByDay/Quiz/GameDestination.swift` | ||
| 162 | - Test: `DayByDayTests/YearWheelTests.swift`, `DayByDayTests/ContrastTests.swift` | ||
| 163 | |||
| 164 | **Interfaces:** | ||
| 165 | - Produces: | ||
| 166 | - `nonisolated enum YearWheel`: month `i` (January = 0) is drawn centered `i * 30°` clockwise from the top pointer before rotation. `static func month(atRotation degrees: Double) -> MonthOfYear` (month under the pointer after rotating the wheel clockwise by `degrees`; any real value). `static func target(from rotation: Double, landingOn month: MonthOfYear, turns: Int) -> Double` (a rotation greater than `rotation` by at least `turns` full turns whose `month(atRotation:)` is `month`, exactly at its center). | ||
| 167 | - `extension Season { var wheelColor: Color }`: spring `(0.18, 0.56, 0.28)`, summer `(0.84, 0.40, 0.08)`, fall `(0.66, 0.30, 0.10)`, winter `(0.0, 0.42, 0.85)`. All ≥ 3:1 against white. | ||
| 168 | - `YearWheelView`: wheel of 12 wedges in season colors with three-letter month labels in white, a pointer at the top, a large "Spin!" button. Spin picks a random month (never the current one), animates to `target(…, turns: 3)` over about 2.5 s with ease-out (Reduce Motion: no animation), then says `"\(month.name)! \(month.name) is in \(season.name)."`. Tapping a wedge says the same for that month. Spin is ignored while spinning. Nothing is recorded (no right or wrong). | ||
| 169 | - Months games become `[findIt, comesNext, yearWheel]`. | ||
| 170 | |||
| 171 | - [ ] **Step 1:** Write failing tests: | ||
| 172 | |||
| 173 | ```swift | ||
| 174 | @Test func monthAtRotation() // 0 → January; 30 → December (wheel turned clockwise brings December under the pointer); -30 → February; 360*7 + 30 → December; -1085 → mapped consistently with the definition | ||
| 175 | @Test(arguments: MonthOfYear.allCases) func targetLandsOnMonth(_ m: MonthOfYear) // for rotations [0, 47.5, -800, 12345]: t = target(from:landingOn:turns: 3); t >= rotation + 1080; month(atRotation: t) == m; (t mod 30) is a center (multiple of 30) | ||
| 176 | @Test(arguments: Season.allCases) func wheelColorAgainstWhite(_ s: Season) // ContrastTests | ||
| 177 | ``` | ||
| 178 | |||
| 179 | - [ ] **Step 2:** Run `-only-testing:DayByDayTests/YearWheelTests -only-testing:DayByDayTests/ContrastTests`. Expected: FAIL. | ||
| 180 | - [ ] **Step 3:** Implement the model, colors, view, catalog and destination. | ||
| 181 | - [ ] **Step 4:** Run. Expected: PASS. Render check: wedges, labels, pointer readable on iPhone 18 Pro. | ||
| 182 | - [ ] **Step 5:** Commit `feat: year wheel`. | ||
| 183 | |||
| 184 | ### Task 6: Count with me | ||
| 185 | |||
| 186 | **Files:** | ||
| 187 | - Create: `DayByDay/Quiz/Counting.swift` (model), `DayByDay/Quiz/CountingView.swift` | ||
| 188 | - Modify: `DayByDay/Quiz/Game.swift` (numbers games), `DayByDay/Quiz/GameDestination.swift` | ||
| 189 | - Test: `DayByDayTests/CountingTests.swift` | ||
| 190 | |||
| 191 | **Interfaces:** | ||
| 192 | - Produces: | ||
| 193 | - `nonisolated struct CountingRound`: `static let length = 5` sets. `struct Thing { let symbol: String; let singular: String; let plural: String }` with five kinds: star, heart, leaf ("leaf"/"leaves"), moon, fish ("fish"/"fish"), using their `.fill` SF Symbols. `private(set) var target: Int` (1...10, never equal to the previous set's), `private(set) var thing: Thing`, `private(set) var counted: [Int]` (object indices in tap order), `private(set) var setsDone: Int`. | ||
| 194 | - `mutating func tap(_ index: Int) -> Int?`: returns the new count, or nil if `index` is out of range, already counted, or the set is done. | ||
| 195 | - `var isSetDone: Bool`, `mutating func nextSet()`, `var isComplete: Bool` (after 5 sets). | ||
| 196 | - `func summary() -> String`: `"\(n)! There \(n == 1 ? "is" : "are") \(n) \(n == 1 ? singular : plural)."` with `n` spelled as a numeral word from `LearnNumber.name`. | ||
| 197 | - `CountingView`: says "Tap each \(singular) to count." The objects sit in a flexible grid in the numbers topic color. Each tap says the number, shows it on the object (white on the topic color), and plays no sound effect. When the set is done it plays `.success`, shows the numeral large, says `summary()`, then moves to the next set after 2.5 s. After 5 sets it shows `FinishedView`. Nothing is recorded. | ||
| 198 | - Numbers games become `[findIt, listen, counting, most]`. | ||
| 199 | |||
| 200 | - [ ] **Step 1:** Write failing tests: | ||
| 201 | |||
| 202 | ```swift | ||
| 203 | @Test func countsEachObjectOnce() // target 4: tap 0,1,1,2 → 1,2,nil,3 | ||
| 204 | @Test func ignoresOutOfRangeAndDone() // tap(target) → nil; after all counted, tap(0) → nil | ||
| 205 | @Test func setsNeverRepeatTarget() // seeded 200 sets: consecutive targets differ, all in 1...10 | ||
| 206 | @Test func completesAfterFiveSets() | ||
| 207 | @Test func summaryCopy() // n=1 → "One! There is one star."; n=3 → "Three! There are three stars." | ||
| 208 | ``` | ||
| 209 | |||
| 210 | - [ ] **Step 2:** Run `-only-testing:DayByDayTests/CountingTests`. Expected: FAIL. | ||
| 211 | - [ ] **Step 3:** Implement the model, view, catalog and destination. | ||
| 212 | - [ ] **Step 4:** Run. Expected: PASS. Then the full suite. Expected: `** TEST SUCCEEDED **`. | ||
| 213 | - [ ] **Step 5:** Commit `feat: count with me`. | ||
| 214 | |||
| 215 | ### Task 7: Reviews, MR, merge | ||
| 216 | |||
| 217 | - [ ] **Step 1:** Export review assets (`TEST_RUNNER_EXPORT_DIR=<scratch> … -only-testing:DayByDayTests/ReviewExport`, adding the whistle and renders of the train, slots, wheel, pile and counting views to `ReviewExport`). Dispatch a fresh art/sound reviewer: block on clear defects (clipping, clicks, harsh or startling sound, unrecognizable drawing, contrast < 3:1); two rounds at most. | ||
| 218 | - [ ] **Step 2:** Dispatch a fresh whole-branch code reviewer with this plan, the spec, the ledger rulings and this Review Focus. One fix pass, each fix RED→GREEN. | ||
| 219 | - [ ] **Step 3:** Full suite green. Push, `gitbay mr create --source feat/ordering-games --target main --title "Part 3: ordering and quantity games"` with `Closes #N` and the unresolved art notes. Squash-merge, delete the branch locally and remotely. | ||