krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

Commit aa5837bc1c

aa5837bc1c11724135f3c975fed13f8406c3786c

parent: f3ddc9ab3a

Unsigned

cmc <hello@cleberg.net> · 2026-10-16 23:17 UTC

Part 2: question games (!4)

Find it! for all 11 topics (3 choices, 4 after two right), odd one out for food, animals and shapes, and listen-and-pick for animals, weather, numbers and letters, reached from each topic hub.

- Animals: cow, duck, sheep, pig (drawn in SwiftUI) replace ant and lizard. Item IDs pinned in a test.
- Question engine: `QuestionSource` protocol with `QuestionPicker` (separate answer and distractor pools) and `OddOneOut` (prompt names the odd group's rule).
- Sound: synthesized moo, quack, baa, oink, meow, woof, tweet, rain, wind, thunder and 1–5 beeps; `SoundEngine` renders on first use. Removed unused `.tap`; round-complete arpeggio now as loud as its chord.
- `RoundView`: plays the cue before the prompt, records the tapped item and game, offsets speech 0.25 s after feedback sounds, stops speech on leaving.
- `AnswerRecord` gains optional `chosenID` and `gameRaw` (lightweight migration; checked by installing over a part 1 store).
- `ChoiceTile` with flat fills, covered by `ContrastTests`. `DayByDayTests/ReviewExport` writes WAVs and PNGs when `TEST_RUNNER_EXPORT_DIR` is set.

Art/sound review: two rounds, no blocking defects left. Round 1 blockers fixed: thunder near-inaudible on phone speakers, turtle shell at 2.35:1. Open taste notes:
- Pig ears and duck wing were redrawn after round 2 (floppy ears, wing groove along the top) and not re-reviewed.
- Thunder peak kept at 0.55 rather than the suggested 0.8, to stay under the 0.6 gentleness cap; it is about 4 dB below wind on a speaker estimate.
- Letter "sounds" are spoken example words ("Which letter does ball start with?"); K, Q and X are left out of that game.

Deferred: shapes odd one out at 4 choices always answers circle or oval; `VersionedSchema` before any non-optional schema change (part 7).

Closes #2

Layout: unified · split

AnimalCard.swift +22 −11
@@ -18,10 +18,10 @@ struct AnimalCard: View {
1818 .shadow(color: animal.color.opacity(0.4), radius: 8, y: 4)
1919
2020 VStack(spacing: 16) {
21 Image(systemName: animal.symbol)
21 AnimalIcon(animal: animal)
2222 .font(.system(size: 64))
23 .frame(height: 72)
2324 .foregroundStyle(.white)
24 .symbolRenderingMode(.hierarchical)
2525
2626 Text(animal.name)
2727 .font(.system(size: 32, weight: .bold, design: .rounded))
@@ -46,8 +46,8 @@ struct AnimalCard: View {
4646
4747// MARK: - Animal model
4848
49enum LearnAnimal: Int, CaseIterable, Identifiable {
50 case cat, dog, bird, fish, rabbit, turtle, ladybug, ant, lizard
49nonisolated enum LearnAnimal: Int, CaseIterable, Identifiable {
50 case cat, dog, bird, fish, rabbit, turtle, ladybug, cow, duck, sheep, pig
5151
5252 var id: Int { rawValue }
5353
@@ -60,12 +60,15 @@ enum LearnAnimal: Int, CaseIterable, Identifiable {
6060 case .rabbit: "Rabbit"
6161 case .turtle: "Turtle"
6262 case .ladybug: "Ladybug"
63 case .ant: "Ant"
64 case .lizard: "Lizard"
63 case .cow: "Cow"
64 case .duck: "Duck"
65 case .sheep: "Sheep"
66 case .pig: "Pig"
6567 }
6668 }
6769
68 var symbol: String {
70 /// Nil for animals without an SF Symbol; `AnimalIcon` draws those.
71 var symbol: String? {
6972 switch self {
7073 case .cat: "cat.fill"
7174 case .dog: "dog.fill"
@@ -74,8 +77,7 @@ enum LearnAnimal: Int, CaseIterable, Identifiable {
7477 case .rabbit: "hare.fill"
7578 case .turtle: "tortoise.fill"
7679 case .ladybug: "ladybug.fill"
77 case .ant: "ant.fill"
78 case .lizard: "lizard.fill"
80 case .cow, .duck, .sheep, .pig: nil
7981 }
8082 }
8183
@@ -88,8 +90,17 @@ enum LearnAnimal: Int, CaseIterable, Identifiable {
8890 case .rabbit: Color(red: 0.75, green: 0.6, blue: 0.8) // lavender
8991 case .turtle: Color(red: 0.35, green: 0.7, blue: 0.4) // green
9092 case .ladybug: Color(red: 0.9, green: 0.25, blue: 0.25) // red
91 case .ant: Color(red: 0.3, green: 0.3, blue: 0.3) // dark gray
92 case .lizard: Color(red: 0.45, green: 0.75, blue: 0.35) // lime
93 case .cow: Color(red: 0.35, green: 0.38, blue: 0.45) // slate
94 case .duck: Color(red: 0.95, green: 0.75, blue: 0.2) // yellow
95 case .sheep: Color(red: 0.55, green: 0.6, blue: 0.7) // blue gray
96 case .pig: Color(red: 0.95, green: 0.5, blue: 0.65) // pink
97 }
98 }
99
100 var canFly: Bool {
101 switch self {
102 case .bird, .ladybug, .duck: true
103 default: false
93104 }
94105 }
95106}
BodyPartCard.swift +1 −1
@@ -46,7 +46,7 @@ struct BodyPartCard: View {
4646
4747// MARK: - Body part model
4848
49enum LearnBodyPart: Int, CaseIterable, Identifiable {
49nonisolated enum LearnBodyPart: Int, CaseIterable, Identifiable {
5050 case head, eyes, ears, nose, mouth, hands, fingers, arms, legs, feet, heart, belly
5151
5252 var id: Int { rawValue }
ColorCard.swift +1 −1
@@ -39,7 +39,7 @@ struct ColorCard: View {
3939
4040// MARK: - Color model
4141
42enum LearnColor: Int, CaseIterable, Identifiable {
42nonisolated enum LearnColor: Int, CaseIterable, Identifiable {
4343 case red, orange, yellow, green, blue, purple, pink, brown, black, white
4444
4545 var id: Int { rawValue }
DayByDay/ContentView.swift +1 −1
@@ -10,7 +10,7 @@ import SwiftUI
1010
1111// MARK: - Category model
1212
13enum Category: Int, CaseIterable, Identifiable {
13nonisolated enum Category: Int, CaseIterable, Identifiable {
1414 case today, days, months, seasons, numbers, colors, shapes, animals, alphabet,
1515 weather, bodyParts, food
1616
DayByDay/DayCard.swift +1 −1
@@ -60,7 +60,7 @@ struct DayCard: View {
6060
6161// MARK: - Day model
6262
63enum DayOfWeek: Int, CaseIterable, Identifiable {
63nonisolated enum DayOfWeek: Int, CaseIterable, Identifiable {
6464 case sunday, monday, tuesday, wednesday, thursday, friday, saturday
6565
6666 var id: Int { rawValue }
DayByDay/Home/CategoryHubView.swift +8
@@ -16,6 +16,14 @@ struct CategoryHubView: View {
1616 category.lookAndListenView
1717 .navigationTitle(category.label)
1818 }
19 ForEach(category.games, id: \.self) { game in
20 activity(game.title, systemImage: game.symbol, color: category.color) {
21 RoundView(source: category.questionSource(for: game), game: game) {
22 ChoiceTile(item: $0)
23 }
24 .navigationTitle(game.title)
25 }
26 }
1927 }
2028 .padding(32)
2129 .frame(maxWidth: 640)
DayByDay/MonthCard.swift +1 −1
@@ -60,7 +60,7 @@ struct MonthCard: View {
6060
6161// MARK: - Month model
6262
63enum MonthOfYear: Int, CaseIterable, Identifiable {
63nonisolated enum MonthOfYear: Int, CaseIterable, Identifiable {
6464 case january, february, march, april, may, june,
6565 july, august, september, october, november, december
6666
DayByDay/Profiles/AnswerRecord.swift +8 −1
@@ -11,13 +11,20 @@ import SwiftData
1111final class AnswerRecord {
1212 var categoryRaw: Int
1313 var itemID: String
14 /// The item the child tapped. Nil for answers recorded before part 2.
15 var chosenID: String?
16 /// `Game.rawValue`. Nil for answers recorded before part 2.
17 var gameRaw: String?
1418 var isCorrect: Bool
1519 var timestamp: Date
1620 var profile: Profile?
1721
18 init(categoryRaw: Int, itemID: String, isCorrect: Bool, timestamp: Date, profile: Profile) {
22 init(categoryRaw: Int, itemID: String, chosenID: String? = nil, gameRaw: String? = nil,
23 isCorrect: Bool, timestamp: Date, profile: Profile) {
1924 self.categoryRaw = categoryRaw
2025 self.itemID = itemID
26 self.chosenID = chosenID
27 self.gameRaw = gameRaw
2128 self.isCorrect = isCorrect
2229 self.timestamp = timestamp
2330 self.profile = profile
DayByDay/Profiles/ProfileStore.swift +4 −1
@@ -55,8 +55,11 @@ final class ProfileStore {
5555 try? context.save()
5656 }
5757
58 func record(_ item: QuizItem, correct: Bool, for profile: Profile, at date: Date = .now) {
58 /// `item` is the question's answer; `chosen` is what the child tapped.
59 func record(_ item: QuizItem, chosen: QuizItem? = nil, game: Game? = nil, correct: Bool,
60 for profile: Profile, at date: Date = .now) {
5961 context.insert(AnswerRecord(categoryRaw: item.category.rawValue, itemID: item.id,
62 chosenID: chosen?.id, gameRaw: game?.rawValue,
6063 isCorrect: correct, timestamp: date, profile: profile))
6164 try? context.save()
6265 }
DayByDay/Quiz/AnimalIcon.swift added +140
@@ -0,0 +1,140 @@
1//
2// AnimalIcon.swift
3// DayByDay
4//
5
6import SwiftUI
7
8/// An animal's SF Symbol, or a drawn silhouette for animals SF Symbols lacks.
9/// Both take the current foreground style. Size symbols with `.font` and
10/// drawings with `.frame`.
11struct AnimalIcon: View {
12 let animal: LearnAnimal
13
14 var body: some View {
15 if let symbol = animal.symbol {
16 Image(systemName: symbol)
17 .symbolRenderingMode(.monochrome)
18 } else {
19 Canvas { context, size in
20 // 88% so drawings sit at the same visual weight as the symbols.
21 let scale = min(size.width, size.height) / 100 * 0.88
22 context.translateBy(x: (size.width - 100 * scale) / 2, y: (size.height - 100 * scale) / 2)
23 context.scaleBy(x: scale, y: scale)
24 AnimalDrawing.draw(animal, in: &context)
25 }
26 .accessibilityHidden(true)
27 }
28 }
29}
30
31/// Silhouettes in a 100×100 space. `fill` adds shape, `cut` removes it, so
32/// details show whatever is behind the icon.
33private enum AnimalDrawing {
34 static func draw(_ animal: LearnAnimal, in context: inout GraphicsContext) {
35 switch animal {
36 case .pig: pig(&context)
37 case .cow: cow(&context)
38 case .sheep: sheep(&context)
39 case .duck: duck(&context)
40 default: break
41 }
42 }
43
44 private static func fill(_ context: inout GraphicsContext, _ path: Path) {
45 context.blendMode = .normal
46 context.fill(path, with: .foreground)
47 }
48
49 private static func cut(_ context: inout GraphicsContext, _ path: Path) {
50 context.blendMode = .destinationOut
51 context.fill(path, with: .color(.black))
52 }
53
54 private static func ellipse(_ x: Double, _ y: Double, _ w: Double, _ h: Double) -> Path {
55 Path(ellipseIn: CGRect(x: x, y: y, width: w, height: h))
56 }
57
58 private static func circle(_ cx: Double, _ cy: Double, _ r: Double) -> Path {
59 ellipse(cx - r, cy - r, 2 * r, 2 * r)
60 }
61
62 private static func polygon(_ points: [(Double, Double)]) -> Path {
63 var path = Path()
64 path.addLines(points.map { CGPoint(x: $0.0, y: $0.1) })
65 path.closeSubpath()
66 return path
67 }
68
69 /// Front face: floppy ears folded forward, round head, big snout with nostrils.
70 private static func pig(_ c: inout GraphicsContext) {
71 fill(&c, ellipse(10, 18, 80, 70))
72 cut(&c, polygon([(12, 20), (46, 16), (26, 50)]))
73 fill(&c, polygon([(16, 23), (42, 20), (26, 45)]))
74 cut(&c, polygon([(88, 20), (54, 16), (74, 50)]))
75 fill(&c, polygon([(84, 23), (58, 20), (74, 45)]))
76 cut(&c, circle(40, 50, 5))
77 cut(&c, circle(60, 50, 5))
78 cut(&c, ellipse(27, 55, 46, 31))
79 fill(&c, ellipse(31, 59, 38, 23))
80 cut(&c, ellipse(39, 64, 8, 13))
81 cut(&c, ellipse(53, 64, 8, 13))
82 }
83
84 /// Front face: horns, side ears, a spot, and a wide muzzle with nostrils.
85 private static func cow(_ c: inout GraphicsContext) {
86 fill(&c, polygon([(30, 22), (20, 2), (40, 16)]))
87 fill(&c, polygon([(70, 22), (80, 2), (60, 16)]))
88 fill(&c, ellipse(1, 27, 30, 14))
89 fill(&c, ellipse(69, 27, 30, 14))
90 fill(&c, Path(roundedRect: CGRect(x: 23, y: 12, width: 54, height: 62), cornerRadius: 22))
91 cut(&c, ellipse(30, 18, 16, 13))
92 cut(&c, circle(39, 40, 5))
93 cut(&c, circle(61, 40, 5))
94 cut(&c, ellipse(15, 56, 70, 42))
95 fill(&c, ellipse(19, 60, 62, 34))
96 cut(&c, ellipse(33, 70, 9, 11))
97 cut(&c, ellipse(58, 70, 9, 11))
98 }
99
100 /// Side view facing right: woolly cloud body, four legs, head and ear.
101 private static func sheep(_ c: inout GraphicsContext) {
102 for x in [24.0, 36, 56, 68] {
103 fill(&c, Path(roundedRect: CGRect(x: x, y: 64, width: 8, height: 28), cornerRadius: 4))
104 }
105 fill(&c, ellipse(16, 36, 62, 32))
106 for (x, y) in [(22.0, 50.0), (30, 38), (44, 33), (58, 34), (70, 42), (68, 58), (54, 63), (38, 63), (24, 60)] {
107 fill(&c, circle(x, y, 12))
108 }
109 cut(&c, ellipse(66, 20, 32, 40))
110 fill(&c, ellipse(70, 24, 24, 32))
111 fill(&c, ellipse(62, 28, 16, 8))
112 cut(&c, circle(84, 36, 3.5))
113 }
114
115 /// Side view facing right: body with raised tail, round head, bill, wing.
116 private static func duck(_ c: inout GraphicsContext) {
117 fill(&c, polygon([(18, 64), (4, 40), (32, 56)]))
118 fill(&c, ellipse(10, 48, 74, 38))
119 fill(&c, ellipse(58, 30, 28, 32))
120 fill(&c, circle(70, 32, 16))
121 fill(&c, Path(roundedRect: CGRect(x: 80, y: 30, width: 19, height: 11), cornerRadius: 5))
122 cut(&c, circle(74, 27, 3.5))
123 cut(&c, ellipse(30, 56, 40, 18))
124 fill(&c, ellipse(30, 60, 40, 18))
125 }
126}
127
128#Preview {
129 HStack(spacing: 24) {
130 ForEach([LearnAnimal.cow, .pig, .sheep, .duck, .cat]) { animal in
131 AnimalIcon(animal: animal)
132 .font(.system(size: 64))
133 .frame(width: 80, height: 80)
134 .foregroundStyle(.white)
135 .padding()
136 .background(RoundedRectangle(cornerRadius: 24).fill(Color.brown))
137 }
138 }
139 .padding()
140}
DayByDay/Quiz/ChoiceTile.swift added +136
@@ -0,0 +1,136 @@
1//
2// ChoiceTile.swift
3// DayByDay
4//
5
6import SwiftUI
7
8enum ChoiceStyle {
9 /// Dark enough that every food emoji stands out.
10 static let foodFill = Color(red: 0.24, green: 0.16, blue: 0.10)
11 /// Edge for color swatches, visible on light and dark backgrounds.
12 static let swatchOutline = Color(white: 0.45)
13}
14
15/// One answer choice in a game. Flat fills only: white content sits on the
16/// topic color, which is at least 3:1 against white.
17struct ChoiceTile: View {
18 let item: QuizItem
19
20 @Environment(\.colorScheme) private var colorScheme
21
22 private static let shape = RoundedRectangle(cornerRadius: 32, style: .continuous)
23
24 var body: some View {
25 content
26 .frame(maxWidth: .infinity, maxHeight: .infinity)
27 .padding(12)
28 .background(Self.shape.fill(fill))
29 .overlay {
30 if item.category == .colors {
31 Self.shape.strokeBorder(ChoiceStyle.swatchOutline, lineWidth: 4)
32 } else if item.category == .food, colorScheme == .dark {
33 Self.shape.strokeBorder(.white.opacity(0.25), lineWidth: 2)
34 }
35 }
36 .contentShape(Self.shape)
37 }
38
39 private var fill: Color {
40 switch item.category {
41 case .colors: item.value(LearnColor.self)!.color
42 case .food: ChoiceStyle.foodFill
43 default: item.category.color
44 }
45 }
46
47 @ViewBuilder
48 private var content: some View {
49 switch item.category {
50 case .colors:
51 Color.clear
52 case .food:
53 Text(item.value(LearnFood.self)!.emoji)
54 .font(.system(size: 80))
55 case .animals:
56 AnimalIcon(animal: item.value(LearnAnimal.self)!)
57 .font(.system(size: 72))
58 .frame(width: 100, height: 100)
59 .foregroundStyle(.white)
60 case .weather:
61 symbol(item.value(LearnWeather.self)!.symbol)
62 case .bodyParts:
63 symbol(item.value(LearnBodyPart.self)!.symbol)
64 case .shapes:
65 let shape = item.value(LearnShape.self)!
66 shape.shapeView
67 .frame(width: 90, height: 90)
68 .scaleEffect([.star, .heart].contains(shape) ? 1.15 : 1)
69 case .alphabet:
70 Text(item.value(LearnLetter.self)!.character)
71 .font(.system(size: 80, weight: .heavy, design: .rounded))
72 .foregroundStyle(.white)
73 case .numbers:
74 let number = item.value(LearnNumber.self)!
75 VStack(spacing: 8) {
76 Text("\(number.numeral)")
77 .font(.system(size: 56, weight: .heavy, design: .rounded))
78 Dots(count: number.numeral)
79 }
80 .foregroundStyle(.white)
81 case .days:
82 labeled(item.value(DayOfWeek.self)!.symbol)
83 case .months:
84 labeled(item.value(MonthOfYear.self)!.symbol)
85 case .seasons:
86 labeled(item.value(Season.self)!.symbol)
87 case .today:
88 EmptyView()
89 }
90 }
91
92 private func symbol(_ name: String) -> some View {
93 Image(systemName: name)
94 .font(.system(size: 72))
95 .foregroundStyle(.white)
96 }
97
98 private func labeled(_ name: String) -> some View {
99 VStack(spacing: 10) {
100 Image(systemName: name)
101 .font(.system(size: 52))
102 .frame(height: 60)
103 Text(item.name)
104 .font(.system(size: 26, weight: .bold, design: .rounded))
105 .lineLimit(1)
106 .minimumScaleFactor(0.6)
107 }
108 .foregroundStyle(.white)
109 }
110}
111
112/// Solid dots for a quantity, in rows of five.
113private struct Dots: View {
114 let count: Int
115
116 var body: some View {
117 VStack(spacing: 6) {
118 ForEach(Array(stride(from: 0, to: count, by: 5)), id: \.self) { start in
119 HStack(spacing: 6) {
120 ForEach(start..<min(start + 5, count), id: \.self) { _ in
121 Circle().frame(width: 16, height: 16)
122 }
123 }
124 }
125 }
126 }
127}
128
129#Preview {
130 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 20)], spacing: 20) {
131 ForEach([Category.days, .colors, .food, .animals, .numbers, .shapes, .alphabet, .weather], id: \.self) { c in
132 ChoiceTile(item: c.quizItems[1]).frame(height: 160)
133 }
134 }
135 .padding()
136}
DayByDay/Quiz/Game.swift added +130
@@ -0,0 +1,130 @@
1//
2// Game.swift
3// DayByDay
4//
5
6nonisolated enum Game: String, CaseIterable {
7 case findIt, oddOneOut, listen
8
9 var title: String {
10 switch self {
11 case .findIt: "Find it!"
12 case .oddOneOut: "Odd one out"
13 case .listen: "Listen"
14 }
15 }
16
17 var symbol: String {
18 switch self {
19 case .findIt: "magnifyingglass"
20 case .oddOneOut: "square.grid.2x2.fill"
21 case .listen: "ear.fill"
22 }
23 }
24}
25
26nonisolated extension LearnAnimal {
27 var sound: SoundEffect? {
28 switch self {
29 case .cat: .meow
30 case .dog: .woof
31 case .bird: .tweet
32 case .cow: .moo
33 case .duck: .quack
34 case .sheep: .baa
35 case .pig: .oink
36 default: nil
37 }
38 }
39}
40
41nonisolated extension LearnWeather {
42 var sound: SoundEffect? {
43 switch self {
44 case .rainy: .rain
45 case .windy: .wind
46 case .stormy: .thunder
47 default: nil
48 }
49 }
50}
51
52nonisolated extension Category {
53 /// Games offered in this topic's hub, in order.
54 var games: [Game] {
55 var games: [Game] = [.findIt]
56 if [.shapes, .animals, .food].contains(self) { games.append(.oddOneOut) }
57 if [.numbers, .animals, .alphabet, .weather].contains(self) { games.append(.listen) }
58 return games
59 }
60
61 func questionSource(for game: Game) -> any QuestionSource {
62 switch game {
63 case .findIt: findIt
64 case .oddOneOut: oddOneOut
65 case .listen: listen
66 }
67 }
68
69 private var findIt: QuestionPicker {
70 let article = switch self {
71 case .alphabet: "the letter "
72 case .numbers: "the number "
73 case .animals, .food, .shapes, .bodyParts: "the "
74 default: ""
75 }
76 return QuestionPicker(answers: quizItems) { "Can you find \(article)\($0.name)?" }
77 }
78
79 private var oddOneOut: OddOneOut {
80 switch self {
81 case .food:
82 OddOneOut(group(LearnFood.allCases.filter(\.isFruit), "Which one is a fruit?") { "\($0.name) is a fruit." },
83 group(LearnFood.allCases.filter { !$0.isFruit }, "Which one is a vegetable?") { "\($0.name) is a vegetable." })
84 case .animals:
85 OddOneOut(group(LearnAnimal.allCases.filter(\.canFly), "Which one can fly?") { "\($0.name) can fly." },
86 group(LearnAnimal.allCases.filter { !$0.canFly }, "Which one can't fly?") { "\($0.name) can't fly." })
87 case .shapes:
88 OddOneOut(group(LearnShape.allCases.filter { $0.hasCorners == false }, "Which one is round?") { "\($0.name) is round." },
89 group(LearnShape.allCases.filter { $0.hasCorners == true }, "Which one has corners?") { "\($0.name) has corners." })
90 default:
91 preconditionFailure("No odd one out for \(self)")
92 }
93 }
94
95 private var listen: QuestionPicker {
96 switch self {
97 case .animals:
98 let voiced = items(LearnAnimal.allCases.filter { $0.sound != nil })
99 return QuestionPicker(answers: voiced, prompt: { _ in "Who says this?" },
100 sound: { $0.value(LearnAnimal.self)?.sound })
101 case .weather:
102 return QuestionPicker(answers: items(LearnWeather.allCases.filter { $0.sound != nil }),
103 // Stormy only as an answer: a storm is also rain and wind.
104 distractors: items(LearnWeather.allCases.filter { $0 != .stormy }),
105 prompt: { _ in "What weather sounds like this?" },
106 sound: { $0.value(LearnWeather.self)?.sound })
107 case .numbers:
108 return QuestionPicker(answers: items(LearnNumber.allCases.filter { $0.numeral <= 5 }),
109 prompt: { _ in "How many beeps?" },
110 sound: { $0.value(LearnNumber.self).map { .beeps($0.numeral) } })
111 case .alphabet:
112 // K and Q share C's sound in their example words; X has no starting sound.
113 let letters = items(LearnLetter.allCases.filter { ![.k, .q, .x].contains($0) })
114 return QuestionPicker(answers: letters) {
115 "Which letter does \($0.value(LearnLetter.self)!.exampleWord) start with?"
116 }
117 default:
118 preconditionFailure("No listening game for \(self)")
119 }
120 }
121
122 private func items<T: CaseIterable>(_ values: [T]) -> [QuizItem] {
123 values.map { item($0) }
124 }
125
126 private func group<T: CaseIterable>(_ values: [T], _ question: String,
127 fact: @escaping (QuizItem) -> String) -> OddOneOut.Group {
128 OddOneOut.Group(members: items(values), question: question, fact: fact)
129 }
130}
DayByDay/Quiz/Question.swift +74 −12
@@ -7,21 +7,83 @@ nonisolated struct Question: Equatable {
77 let prompt: String
88 let choices: [QuizItem]
99 let answer: QuizItem
10 /// Played before the prompt is spoken.
11 var sound: SoundEffect? = nil
12 /// What to say about a choice when it is tapped by mistake.
13 var facts: [QuizItem: String] = [:]
14
15 func correction(for tapped: QuizItem) -> String {
16 if let fact = facts[tapped] { return "\(fact) Try again!" }
17 return PraisePhrases.correction(for: answer.name)
18 }
19}
20
21nonisolated protocol QuestionSource {
22 func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question
1023}
1124
12nonisolated struct QuestionPicker {
13 var choiceCount: Int
14 var prompt: (QuizItem) -> String
25/// "Find the one I name" questions. The answer comes from `answers`, the
26/// other choices from `distractors`.
27nonisolated struct QuestionPicker: QuestionSource {
28 let answers: [QuizItem]
29 let distractors: [QuizItem]
30 let prompt: (QuizItem) -> String
31 let sound: (QuizItem) -> SoundEffect?
32
33 init(answers: [QuizItem], distractors: [QuizItem]? = nil,
34 prompt: @escaping (QuizItem) -> String,
35 sound: @escaping (QuizItem) -> SoundEffect? = { _ in nil }) {
36 precondition(!answers.isEmpty)
37 self.answers = answers
38 self.distractors = distractors ?? answers
39 self.prompt = prompt
40 self.sound = sound
41 }
42
43 /// A random answer (never `previous` when there is an alternative) plus
44 /// distinct distractors, shuffled.
45 func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question {
46 let candidates = answers.count > 1 ? answers.filter { $0 != previous } : answers
47 let answer = candidates.randomElement(using: &rng)!
48 let others = distractors.filter { $0 != answer }.shuffled(using: &rng)
49 let count = min(Round.choiceCount(correctCount: correctCount), others.count + 1)
50 let choices = ([answer] + others.prefix(count - 1)).shuffled(using: &rng)
51 return Question(prompt: prompt(answer), choices: choices, answer: answer, sound: sound(answer))
52 }
53}
54
55/// Odd one out: all choices but one come from the same group, and the
56/// prompt names the odd group's rule ("Which one can fly?").
57nonisolated struct OddOneOut: QuestionSource {
58 struct Group {
59 let members: [QuizItem]
60 /// Asked when the answer comes from this group.
61 let question: String
62 let fact: (QuizItem) -> String
63 }
64
65 let groups: (Group, Group)
66
67 init(_ a: Group, _ b: Group) {
68 groups = (a, b)
69 }
1570
16 /// Picks a random answer (never `previous` when there is an alternative)
17 /// plus distinct distractors, shuffled.
18 func next(from items: [QuizItem], excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question {
19 let candidates = items.count > 1 ? items.filter { $0 != previous } : items
71 func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question {
72 let pairs = [(groups.0, groups.1), (groups.1, groups.0)]
73 var count = Round.choiceCount(correctCount: correctCount)
74 var fitting = pairs.filter { $0.0.members.count >= count - 1 }
75 if fitting.isEmpty {
76 count = 3
77 fitting = pairs.filter { $0.0.members.count >= count - 1 }
78 }
79 let (majority, odd) = fitting.randomElement(using: &rng)!
80 let candidates = odd.members.count > 1 ? odd.members.filter { $0 != previous } : odd.members
2081 let answer = candidates.randomElement(using: &rng)!
21 let distractors = items.filter { $0 != answer }
22 .shuffled(using: &rng)
23 .prefix(min(choiceCount, items.count) - 1)
24 let choices = ([answer] + distractors).shuffled(using: &rng)
25 return Question(prompt: prompt(answer), choices: choices, answer: answer)
82 let others = Array(majority.members.shuffled(using: &rng).prefix(count - 1))
83 var facts = [answer: odd.fact(answer)]
84 for item in others { facts[item] = majority.fact(item) }
85 return Question(prompt: odd.question,
86 choices: (others + [answer]).shuffled(using: &rng),
87 answer: answer, facts: facts)
2688 }
2789}
DayByDay/Quiz/QuizItem.swift +13 −1
@@ -10,7 +10,7 @@ nonisolated struct QuizItem: Identifiable, Hashable, Sendable {
1010 let category: Category
1111}
1212
13extension Category {
13nonisolated extension Category {
1414 /// Categories shown in the home grid. Today is reached from the banner.
1515 static var gridCases: [Category] {
1616 allCases.filter { $0 != .today }
@@ -50,7 +50,19 @@ extension Category {
5050 }
5151 }
5252
53 /// The quiz item for one of this category's enum cases.
54 func item(_ value: some CaseIterable) -> QuizItem {
55 quizItems.first { $0.id == "\(key).\(value)" }!
56 }
57
5358 private func items<T>(_ cases: [T], _ name: KeyPath<T, String>) -> [QuizItem] {
5459 cases.map { QuizItem(id: "\(key).\($0)", name: $0[keyPath: name], category: self) }
5560 }
5661}
62
63nonisolated extension QuizItem {
64 /// The enum case this item was made from, if it is of type `T`.
65 func value<T: CaseIterable>(_: T.Type) -> T? {
66 T.allCases.first { id == "\(category.key).\($0)" }
67 }
68}
DayByDay/Quiz/Round.swift +13 −7
@@ -15,8 +15,7 @@ nonisolated enum AnswerOutcome: Equatable {
1515nonisolated struct Round {
1616 static let length = 5
1717
18 private let items: [QuizItem]
19 private let picker: QuestionPicker
18 private let source: any QuestionSource
2019 private var rng: any RandomNumberGenerator
2120 private(set) var current: Question
2221 private(set) var correctCount = 0
@@ -28,11 +27,18 @@ nonisolated struct Round {
2827 /// True once the last correct answer's feedback is done.
2928 var isComplete: Bool { isFinished && !isAwaitingNext }
3029
31 init(items: [QuizItem], picker: QuestionPicker, rng: some RandomNumberGenerator = SystemRandomNumberGenerator()) {
30 /// Choices on screen: 3 to start, 4 once the child has two right.
31 static func choiceCount(correctCount: Int) -> Int {
32 correctCount < 2 ? 3 : 4
33 }
34
35 /// `previous` is the last answer of an earlier round, so a replay does not
36 /// open with it.
37 init(source: any QuestionSource, after previous: QuizItem? = nil,
38 rng: some RandomNumberGenerator = SystemRandomNumberGenerator()) {
3239 var rng: any RandomNumberGenerator = rng
33 self.items = items
34 self.picker = picker
35 self.current = picker.next(from: items, excluding: nil, using: &rng)
40 self.source = source
41 self.current = source.next(correctCount: 0, excluding: previous, using: &rng)
3642 self.rng = rng
3743 }
3844
@@ -55,6 +61,6 @@ nonisolated struct Round {
5561 guard isAwaitingNext else { return }
5662 isAwaitingNext = false
5763 guard !isFinished else { return }
58 current = picker.next(from: items, excluding: current.answer, using: &rng)
64 current = source.next(correctCount: correctCount, excluding: current.answer, using: &rng)
5965 }
6066}
DayByDay/Quiz/RoundView.swift +41 −15
@@ -7,12 +7,14 @@ import SwiftUI
77
88enum RoundStyle {
99 static let playAgainFill = Color(red: 0.18, green: 0.56, blue: 0.28)
10 /// Gap between a feedback sound and the speech that follows it.
11 static let speechDelay = 0.25
1012}
1113
1214/// Runs a round of questions. The caller supplies how each choice looks.
1315struct RoundView<Choice: View>: View {
14 private let items: [QuizItem]
15 private let picker: QuestionPicker
16 private let source: any QuestionSource
17 private let game: Game
1618 private let choice: (QuizItem) -> Choice
1719
1820 @Environment(ProfileSession.self) private var session
@@ -20,14 +22,17 @@ struct RoundView<Choice: View>: View {
2022 @State private var praise = PraisePhrases()
2123 @State private var celebrating = false
2224 @State private var dimmed: QuizItem?
25 /// Bumped whenever something new is said, so a delayed prompt that has
26 /// been overtaken stays quiet.
27 @State private var speechToken = 0
2328
2429 private let columns = [GridItem(.adaptive(minimum: 150, maximum: 320), spacing: 20)]
2530
26 init(items: [QuizItem], picker: QuestionPicker, @ViewBuilder choice: @escaping (QuizItem) -> Choice) {
27 self.items = items
28 self.picker = picker
31 init(source: any QuestionSource, game: Game, @ViewBuilder choice: @escaping (QuizItem) -> Choice) {
32 self.source = source
33 self.game = game
2934 self.choice = choice
30 _round = State(initialValue: Round(items: items, picker: picker))
35 _round = State(initialValue: Round(source: source))
3136 }
3237
3338 var body: some View {
@@ -39,6 +44,10 @@ struct RoundView<Choice: View>: View {
3944 }
4045 }
4146 .onAppear { speakPrompt() }
47 .onDisappear {
48 speechToken += 1
49 SpeechSynthesizer.shared.stop()
50 }
4251 .onChange(of: round.current) { speakPrompt() }
4352 }
4453
@@ -80,7 +89,7 @@ struct RoundView<Choice: View>: View {
8089 Text("You did it!")
8190 .font(.system(size: 48, weight: .heavy, design: .rounded))
8291 Button {
83 round = Round(items: items, picker: picker)
92 round = Round(source: source, after: round.current.answer)
8493 } label: {
8594 Label("Play again", systemImage: "arrow.clockwise")
8695 .font(.system(size: 28, weight: .bold, design: .rounded))
@@ -94,7 +103,7 @@ struct RoundView<Choice: View>: View {
94103 .padding(32)
95104 .onAppear {
96105 SoundEngine.shared.play(.roundComplete)
97 SpeechSynthesizer.shared.speak("You did it!")
106 say("You did it!", after: 0.4)
98107 }
99108 }
100109
@@ -102,21 +111,22 @@ struct RoundView<Choice: View>: View {
102111 let outcome = round.answer(item)
103112 guard outcome != .ignored else { return }
104113 if let profile = session.current {
105 session.store.record(round.current.answer, correct: outcome == .correct, for: profile)
114 session.store.record(round.current.answer, chosen: item, game: game,
115 correct: outcome == .correct, for: profile)
106116 }
107117 switch outcome {
108118 case .correct:
109119 SoundEngine.shared.play(.success)
110120 var rng = SystemRandomNumberGenerator()
111 SpeechSynthesizer.shared.speak(praise.next(using: &rng))
121 say(praise.next(using: &rng), after: RoundStyle.speechDelay)
112122 celebrating = true
113 DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
123 DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) {
114124 celebrating = false
115125 round.advance()
116126 }
117 case .incorrect(let correctName):
127 case .incorrect:
118128 SoundEngine.shared.play(.gentleMiss)
119 SpeechSynthesizer.shared.speak(PraisePhrases.correction(for: correctName))
129 say(round.current.correction(for: item), after: RoundStyle.speechDelay)
120130 withAnimation(.easeOut(duration: 0.2)) { dimmed = item }
121131 DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) {
122132 withAnimation { if dimmed == item { dimmed = nil } }
@@ -127,9 +137,25 @@ struct RoundView<Choice: View>: View {
127137 }
128138 }
129139
140 /// Plays the question's sound cue, if any, then speaks the prompt.
130141 private func speakPrompt() {
131 guard !round.isFinished else { return }
132 SpeechSynthesizer.shared.speak(round.current.prompt)
142 guard !round.isFinished, !round.isAwaitingNext else { return }
143 if let sound = round.current.sound {
144 speechToken += 1
145 SpeechSynthesizer.shared.stop()
146 SoundEngine.shared.play(sound)
147 say(round.current.prompt, after: SoundEngine.shared.remaining(sound) + 0.2)
148 } else {
149 say(round.current.prompt, after: 0)
150 }
151 }
152
153 private func say(_ text: String, after delay: TimeInterval) {
154 speechToken += 1
155 let token = speechToken
156 DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
157 if token == speechToken { SpeechSynthesizer.shared.speak(text) }
158 }
133159 }
134160}
135161
DayByDay/SeasonCard.swift +1 −1
@@ -60,7 +60,7 @@ struct SeasonCard: View {
6060
6161// MARK: - Season model
6262
63enum Season: Int, CaseIterable, Identifiable {
63nonisolated enum Season: Int, CaseIterable, Identifiable {
6464 case spring, summer, fall, winter
6565
6666 var id: Int { rawValue }
DayByDay/Sound/SoundEngine.swift +38 −22
@@ -5,10 +5,10 @@
55
66import AVFoundation
77
8/// Plays pre-rendered sound effects. Buffers are rendered once at startup.
9/// Each effect has its own player node so effects overlap instead of cutting
10/// each other off mid-wave (which clicks). A repeat of an effect that is
11/// still playing is skipped for the same reason.
8/// Plays synthesized sound effects. Each effect is rendered and given its
9/// own player node the first time it plays. Separate players let effects
10/// overlap instead of cutting each other off mid-wave (which clicks). A
11/// repeat of an effect that is still playing is skipped for the same reason.
1212final class SoundEngine {
1313 static let shared = SoundEngine()
1414
@@ -18,25 +18,11 @@ final class SoundEngine {
1818 private var players: [SoundEffect: AVAudioPlayerNode] = [:]
1919 private var busyUntil: [SoundEffect: Date] = [:]
2020
21 private init() {
22 for effect in SoundEffect.allCases {
23 let samples = SoundSynth.render(effect)
24 let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(samples.count))!
25 buffer.frameLength = buffer.frameCapacity
26 samples.withUnsafeBufferPointer { src in
27 buffer.floatChannelData![0].update(from: src.baseAddress!, count: samples.count)
28 }
29 buffers[effect] = buffer
30
31 let player = AVAudioPlayerNode()
32 engine.attach(player)
33 engine.connect(player, to: engine.mainMixerNode, format: format)
34 players[effect] = player
35 }
36 }
21 private init() {}
3722
3823 func play(_ effect: SoundEffect) {
39 guard let buffer = buffers[effect], let player = players[effect] else { return }
24 let buffer = buffer(for: effect)
25 let player = player(for: effect)
4026 let now = Date()
4127 if let busy = busyUntil[effect], busy > now { return }
4228 if !engine.isRunning {
@@ -44,8 +30,38 @@ final class SoundEngine {
4430 try? AVAudioSession.sharedInstance().setActive(true)
4531 try? engine.start()
4632 }
47 busyUntil[effect] = now.addingTimeInterval(Double(buffer.frameLength) / SoundSynth.sampleRate)
33 busyUntil[effect] = now.addingTimeInterval(duration(effect))
4834 player.scheduleBuffer(buffer, at: nil)
4935 if !player.isPlaying { player.play() }
5036 }
37
38 /// Time until `effect` finishes playing; zero when it is not playing.
39 func remaining(_ effect: SoundEffect) -> TimeInterval {
40 max(0, busyUntil[effect]?.timeIntervalSinceNow ?? 0)
41 }
42
43 func duration(_ effect: SoundEffect) -> TimeInterval {
44 Double(buffer(for: effect).frameLength) / SoundSynth.sampleRate
45 }
46
47 private func buffer(for effect: SoundEffect) -> AVAudioPCMBuffer {
48 if let buffer = buffers[effect] { return buffer }
49 let samples = SoundSynth.render(effect)
50 let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(samples.count))!
51 buffer.frameLength = buffer.frameCapacity
52 samples.withUnsafeBufferPointer { src in
53 buffer.floatChannelData![0].update(from: src.baseAddress!, count: samples.count)
54 }
55 buffers[effect] = buffer
56 return buffer
57 }
58
59 private func player(for effect: SoundEffect) -> AVAudioPlayerNode {
60 if let player = players[effect] { return player }
61 let player = AVAudioPlayerNode()
62 engine.attach(player)
63 engine.connect(player, to: engine.mainMixerNode, format: format)
64 players[effect] = player
65 return player
66 }
5167}
DayByDay/Sound/SoundSynth.swift +309 −22
@@ -5,25 +5,30 @@
55
66import Foundation
77
8nonisolated enum SoundEffect: CaseIterable {
9 case success, gentleMiss, tap, roundComplete
8nonisolated enum SoundEffect: Hashable, CaseIterable, Sendable {
9 case success, gentleMiss, roundComplete
10 case moo, quack, baa, oink, meow, woof, tweet
11 case rain, wind, thunder
12 /// That many short beeps, for counting.
13 case beeps(Int)
14
15 static let allCases: [SoundEffect] =
16 [.success, .gentleMiss, .roundComplete, .moo, .quack, .baa, .oink, .meow, .woof, .tweet,
17 .rain, .wind, .thunder] + (1...5).map(SoundEffect.beeps)
1018}
1119
12/// Renders sound effects to mono sample buffers. Notes are sines with soft
13/// harmonics and smooth envelopes, so there are no clicks or harsh edges.
20/// Renders sound effects to mono sample buffers. Every sound fades in and out
21/// smoothly and starts and ends on silence, so there are no clicks.
1422nonisolated enum SoundSynth {
1523 static let sampleRate: Double = 44_100
1624
17 private struct Note {
18 let frequency: Double
19 let start: Double
20 let duration: Double
21 var harmonics: [Double] = [1, 0.3, 0.1]
22 }
23
2425 /// Silence at each end so playback never starts or stops mid-wave.
2526 private static let pad = 0.004
2627
28 static func duration(_ effect: SoundEffect) -> Double {
29 Double(render(effect).count) / sampleRate
30 }
31
2732 static func render(_ effect: SoundEffect) -> [Float] {
2833 switch effect {
2934 case .success:
@@ -36,22 +41,82 @@ nonisolated enum SoundSynth {
3641 mix([
3742 Note(frequency: 329.63, start: 0, duration: 0.17, harmonics: [1, 0.15]),
3843 Note(frequency: 261.63, start: 0.15, duration: 0.18, harmonics: [1, 0.15]),
39 ], peak: 0.3)
40 case .tap:
41 mix([Note(frequency: 880, start: 0, duration: 0.05, harmonics: [1, 0.2])], peak: 0.4)
44 ], peak: 0.45)
4245 case .roundComplete:
4346 mix([
44 Note(frequency: 523.25, start: 0, duration: 0.14),
45 Note(frequency: 659.25, start: 0.12, duration: 0.14),
46 Note(frequency: 783.99, start: 0.24, duration: 0.14),
47 Note(frequency: 523.25, start: 0, duration: 0.14, gain: 2.2),
48 Note(frequency: 659.25, start: 0.12, duration: 0.14, gain: 2.2),
49 Note(frequency: 783.99, start: 0.24, duration: 0.14, gain: 2.2),
4750 Note(frequency: 523.25, start: 0.4, duration: 0.7),
4851 Note(frequency: 659.25, start: 0.4, duration: 0.7),
4952 Note(frequency: 783.99, start: 0.4, duration: 0.7),
5053 Note(frequency: 1046.5, start: 0.4, duration: 0.7),
5154 ], peak: 0.6)
55 case .beeps(let count):
56 mix((0..<count).map {
57 Note(frequency: 660, start: 0.42 * Double($0), duration: 0.12, harmonics: [1, 0.2])
58 }, peak: 0.5)
59 case .moo:
60 voice(Voice(duration: 1.2,
61 pitch: [(0, 105), (0.25, 135), (0.7, 125), (1, 95)],
62 vowels: [(0, [260, 600, 2200]), (0.3, [480, 850, 2300]),
63 (0.75, [380, 700, 2200]), (1, [260, 550, 2200])],
64 bandwidth: 110, rolloff: 1.3, vibrato: (5, 0.01),
65 attack: 0.12, release: 0.25),
66 peak: 0.75)
67 case .meow:
68 voice(Voice(duration: 0.7,
69 pitch: [(0, 480), (0.4, 720), (1, 430)],
70 vowels: [(0, [300, 2300, 3000]), (0.35, [850, 1600, 2800]), (1, [400, 900, 2600])],
71 bandwidth: 300, rolloff: 0.6, attack: 0.04, release: 0.15),
72 peak: 0.35)
73 case .baa:
74 voice(Voice(duration: 0.8,
75 pitch: [(0, 360), (0.15, 330), (1, 300)],
76 vowels: [(0, [350, 1200, 2500]), (0.12, [750, 1650, 2600]), (1, [700, 1500, 2500])],
77 bandwidth: 250, rolloff: 0.5, vibrato: (7, 0.04), tremolo: (7, 0.5),
78 attack: 0.03, release: 0.2),
79 peak: 0.55)
80 case .quack:
81 repeated(at: [0, 0.28], Voice(duration: 0.18,
82 pitch: [(0, 240), (1, 190)],
83 vowels: [(0, [1000, 2500, 3200]), (1, [850, 2000, 3000])],
84 bandwidth: 200, rolloff: 0.2, attack: 0.012, release: 0.05, noise: 0.1),
85 peak: 0.5)
86 case .oink:
87 repeated(at: [0, 0.3], Voice(duration: 0.2,
88 pitch: [(0, 150), (1, 110)],
89 vowels: [(0, [400, 1100, 2400]), (1, [350, 900, 2300])],
90 bandwidth: 150, rolloff: 0.4, tremolo: (30, 0.6),
91 attack: 0.015, release: 0.06, noise: 0.3),
92 peak: 0.75)
93 case .woof:
94 repeated(at: [0, 0.32], Voice(duration: 0.18,
95 pitch: [(0, 320), (0.3, 260), (1, 170)],
96 vowels: [(0, [350, 800, 2300]), (0.25, [650, 1100, 2500]), (1, [500, 900, 2400])],
97 bandwidth: 220, rolloff: 0.4, attack: 0.01, release: 0.07, noise: 0.25),
98 peak: 0.55)
99 case .tweet:
100 tweet()
101 case .rain:
102 rain()
103 case .wind:
104 wind()
105 case .thunder:
106 thunder()
52107 }
53108 }
54109
110 // MARK: - Notes
111
112 private struct Note {
113 let frequency: Double
114 let start: Double
115 let duration: Double
116 var harmonics: [Double] = [1, 0.3, 0.1]
117 var gain: Double = 1
118 }
119
55120 private static func mix(_ notes: [Note], peak: Float) -> [Float] {
56121 let end = notes.map { $0.start + $0.duration }.max()!
57122 var out = [Float](repeating: 0, count: Int((end + 2 * pad) * sampleRate))
@@ -64,18 +129,240 @@ nonisolated enum SoundSynth {
64129 for (n, amp) in note.harmonics.enumerated() {
65130 v += amp * sin(2 * .pi * note.frequency * Double(n + 1) * t)
66131 }
67 out[offset + i] += Float(v * envelope(t, duration: note.duration))
132 out[offset + i] += Float(note.gain * v * envelope(t, duration: note.duration))
68133 }
69134 }
70 let maxAbs = out.map(abs).max() ?? 1
71 return out.map { $0 / maxAbs * peak }
135 return normalized(out, peak: peak)
72136 }
73137
74138 /// Smooth attack, gentle exponential decay, smooth release to zero.
75139 private static func envelope(_ t: Double, duration: Double) -> Double {
76140 let attack = 0.01, release = 0.03
141 return fade(t, duration: duration, attack: attack, release: release) * exp(-3 * t / max(duration, 0.1))
142 }
143
144 // MARK: - Voices
145
146 /// A pitched source whose harmonics are shaped by moving formant peaks,
147 /// the way a mouth shapes a vowel.
148 private struct Voice {
149 var duration: Double
150 /// (fraction of duration, Hz) breakpoints.
151 var pitch: [(Double, Double)]
152 /// (fraction of duration, formant Hz) breakpoints. Empty means no shaping.
153 var vowels: [(Double, [Double])] = []
154 var bandwidth: Double = 150
155 /// Harmonic n is weighted by 1 / n^rolloff.
156 var rolloff: Double = 0.5
157 var maxHarmonics = 60
158 /// (rate Hz, depth as a fraction of pitch).
159 var vibrato: (Double, Double) = (0, 0)
160 /// (rate Hz, depth as a fraction of level).
161 var tremolo: (Double, Double) = (0, 0)
162 var attack = 0.03
163 var release = 0.08
164 var noise = 0.0
165 }
166
167 private static func voice(_ v: Voice, peak: Float) -> [Float] {
168 normalized(padded(voiceSamples(v, seed: 1)), peak: peak)
169 }
170
171 private static func repeated(at starts: [Double], _ v: Voice, peak: Float) -> [Float] {
172 let one = voiceSamples(v, seed: 1)
173 let end = starts.max()! + v.duration
174 var out = [Float](repeating: 0, count: Int(end * sampleRate) + 1)
175 for start in starts {
176 let offset = Int(start * sampleRate)
177 for (i, s) in one.enumerated() where offset + i < out.count { out[offset + i] += s }
178 }
179 return normalized(padded(out), peak: peak)
180 }
181
182 private static func voiceSamples(_ v: Voice, seed: UInt64) -> [Float] {
183 let count = Int(v.duration * sampleRate)
184 var out = [Float](repeating: 0, count: count)
185 var noise = Noise(seed: seed)
186 var phase = 0.0
187 var gains = [Double]()
188 var smoothNoise = 0.0
189 let nyquistGuard = 7_000.0
190 for i in 0..<count {
191 let t = Double(i) / sampleRate
192 let u = t / v.duration
193 let f0 = interpolate(v.pitch, u) * (1 + v.vibrato.1 * sin(2 * .pi * v.vibrato.0 * t))
194 phase += 2 * .pi * f0 / sampleRate
195 let harmonics = min(v.maxHarmonics, Int(nyquistGuard / f0))
196 if i % 32 == 0 {
197 let formants = v.vowels.isEmpty ? [] : interpolate(v.vowels, u)
198 gains = (1...max(harmonics, 1)).map { n in
199 let f = Double(n) * f0
200 var g = formants.isEmpty ? 1 : 0.02
201 for (k, formant) in formants.enumerated() {
202 let d = (f - formant) / v.bandwidth
203 g += pow(0.55, Double(k)) * exp(-d * d)
204 }
205 return g / pow(Double(n), v.rolloff)
206 }
207 }
208 var s = 0.0
209 for n in 0..<min(harmonics, gains.count) {
210 s += gains[n] * sin(Double(n + 1) * phase)
211 }
212 smoothNoise += 0.3 * (noise.next() - smoothNoise)
213 s += v.noise * 4 * smoothNoise
214 let level = 1 - v.tremolo.1 * (0.5 + 0.5 * sin(2 * .pi * v.tremolo.0 * t))
215 out[i] = Float(s * level * fade(t, duration: v.duration, attack: v.attack, release: v.release))
216 }
217 return out
218 }
219
220 /// Three rising chirps, then a short warble.
221 private static func tweet() -> [Float] {
222 let chirp = Voice(duration: 0.09, pitch: [(0, 2500), (1, 4200)], rolloff: 2,
223 maxHarmonics: 2, attack: 0.01, release: 0.03)
224 let warble = Voice(duration: 0.25, pitch: [(0, 3800), (0.5, 3200), (1, 3600)], rolloff: 2,
225 maxHarmonics: 2, vibrato: (25, 0.05), attack: 0.02, release: 0.06)
226 var out = [Float](repeating: 0, count: Int(0.68 * sampleRate))
227 for (start, v) in [(0.0, chirp), (0.13, chirp), (0.26, chirp), (0.42, warble)] {
228 let offset = Int(start * sampleRate)
229 for (i, s) in voiceSamples(v, seed: 1).enumerated() where offset + i < out.count {
230 out[offset + i] += s
231 }
232 }
233 return normalized(padded(out), peak: 0.3)
234 }
235
236 // MARK: - Weather
237
238 /// Soft high hiss with scattered droplets.
239 private static func rain() -> [Float] {
240 let duration = 2.0
241 let count = Int(duration * sampleRate)
242 var noise = Noise(seed: 7)
243 var out = [Float](repeating: 0, count: count)
244 var low = 0.0, body = 0.0
245 for i in 0..<count {
246 low += 0.3 * (noise.next() - low) // soften the top end
247 body += 0.2 * (low - body) // what is left below ~1.4 kHz
248 out[i] = Float(0.5 * (low - body))
249 }
250 for _ in 0..<70 {
251 let start = Int(noise.unit() * (duration - 0.05) * sampleRate)
252 let frequency = 1500 + noise.unit() * 3000
253 let amplitude = 0.15 + noise.unit() * 0.3
254 let length = Int(0.018 * sampleRate)
255 for j in 0..<length where start + j < count {
256 let t = Double(j) / sampleRate
257 let shape = fade(t, duration: 0.018, attack: 0.002, release: 0.006) * exp(-t / 0.005)
258 out[start + j] += Float(amplitude * shape * sin(2 * .pi * frequency * t))
259 }
260 }
261 return finish(out, duration: duration, attack: 0.3, release: 0.4, peak: 0.45)
262 }
263
264 /// Band-passed noise whose center drifts, with a slow swell.
265 private static func wind() -> [Float] {
266 let duration = 2.2
267 let count = Int(duration * sampleRate)
268 var noise = Noise(seed: 11)
269 var out = [Float](repeating: 0, count: count)
270 var y1 = 0.0, y2 = 0.0
271 for i in 0..<count {
272 let t = Double(i) / sampleRate
273 let u = t / duration
274 let center = interpolate([(0, 250), (0.45, 700), (1, 350)], u)
275 let r = 0.995
276 let theta = 2 * .pi * center / sampleRate
277 let y = noise.next() * (1 - r) + 2 * r * cos(theta) * y1 - r * r * y2
278 y2 = y1
279 y1 = y
280 let swell = pow(sin(.pi * u), 1.5) * (1 + 0.3 * sin(2 * .pi * 0.8 * t))
281 out[i] = Float(y * swell)
282 }
283 return finish(out, duration: duration, attack: 0.2, release: 0.4, peak: 0.45)
284 }
285
286 /// Low rolling rumble with a soft start and two swells. No sharp crack.
287 private static func thunder() -> [Float] {
288 let duration = 2.4
289 let count = Int(duration * sampleRate)
290 var noise = Noise(seed: 13)
291 var out = [Float](repeating: 0, count: count)
292 var a = 0.0, b = 0.0
293 for i in 0..<count {
294 let t = Double(i) / sampleRate
295 a += 0.06 * (noise.next() - a)
296 b += 0.06 * (a - b)
297 let swells = exp(-pow((t - 0.35) / 0.3, 2)) + 0.7 * exp(-pow((t - 1.2) / 0.45, 2))
298 out[i] = Float(b * swells)
299 }
300 return finish(dcBlocked(out), duration: duration, attack: 0.15, release: 0.5, peak: 0.55)
301 }
302
303 // MARK: - Helpers
304
305 /// Seeded white noise in -1...1 (SplitMix64), so sounds render the same every time.
306 private struct Noise {
307 var state: UInt64
308 init(seed: UInt64) { state = seed }
309 mutating func unit() -> Double {
310 state &+= 0x9E37_79B9_7F4A_7C15
311 var z = state
312 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
313 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
314 return Double((z ^ (z >> 31)) >> 11) / Double(1 << 53)
315 }
316 mutating func next() -> Double { 2 * unit() - 1 }
317 }
318
319 /// sin² fade-in over `attack` and fade-out over `release`.
320 private static func fade(_ t: Double, duration: Double, attack: Double, release: Double) -> Double {
77321 let rise = t < attack ? pow(sin(.pi / 2 * t / attack), 2) : 1
78 let fall = t > duration - release ? pow(sin(.pi / 2 * (duration - t) / release), 2) : 1
79 return rise * fall * exp(-3 * t / max(duration, 0.1))
322 let fall = t > duration - release ? pow(sin(.pi / 2 * max(0, duration - t) / release), 2) : 1
323 return rise * fall
324 }
325
326 private static func interpolate(_ points: [(Double, Double)], _ u: Double) -> Double {
327 guard let upper = points.firstIndex(where: { $0.0 >= u }), upper > 0 else {
328 return u <= points[0].0 ? points[0].1 : points[points.count - 1].1
329 }
330 let (u0, v0) = points[upper - 1], (u1, v1) = points[upper]
331 return v0 + (v1 - v0) * (u - u0) / (u1 - u0)
332 }
333
334 private static func interpolate(_ points: [(Double, [Double])], _ u: Double) -> [Double] {
335 (0..<points[0].1.count).map { k in interpolate(points.map { ($0.0, $0.1[k]) }, u) }
336 }
337
338 private static func dcBlocked(_ s: [Float]) -> [Float] {
339 var out = s
340 var previousIn: Float = 0, previousOut: Float = 0
341 for i in s.indices {
342 previousOut = s[i] - previousIn + 0.999 * previousOut
343 previousIn = s[i]
344 out[i] = previousOut
345 }
346 return out
347 }
348
349 /// Fades, removes any remaining offset, pads, and normalizes.
350 private static func finish(_ s: [Float], duration: Double, attack: Double, release: Double, peak: Float) -> [Float] {
351 let mean = s.reduce(0, +) / Float(s.count)
352 let shaped = s.enumerated().map { i, x in
353 (x - mean) * Float(fade(Double(i) / sampleRate, duration: duration, attack: attack, release: release))
354 }
355 return normalized(padded(shaped), peak: peak)
356 }
357
358 private static func padded(_ s: [Float]) -> [Float] {
359 let silence = [Float](repeating: 0, count: Int(pad * sampleRate))
360 return silence + s + silence
361 }
362
363 private static func normalized(_ s: [Float], peak: Float) -> [Float] {
364 let maxAbs = s.map(abs).max() ?? 1
365 guard maxAbs > 0 else { return s }
366 return s.map { $0 / maxAbs * peak }
80367 }
81368}
DayByDay/SpeechSynthesizer.swift +4
@@ -47,6 +47,10 @@ final class SpeechSynthesizer {
4747 synthesizer.speak(utterance)
4848 }
4949
50 func stop() {
51 synthesizer.stopSpeaking(at: .immediate)
52 }
53
5054 /// Picks the best en-US voice on the device.
5155 /// Filters for en-US, excludes novelty voices, then sorts by quality
5256 /// descending so premium (3) > enhanced (2) > default (1).
DayByDayTests/ContrastTests.swift +12
@@ -44,4 +44,16 @@ struct ContrastTests {
4444 #expect(contrast(color.symbolColor, color.color, style) >= 3, "\(color) \(style.rawValue)")
4545 }
4646 }
47
48 /// White and black color swatches need an edge that shows on either background.
49 @Test func swatchOutlineAgainstBackgrounds() {
50 #expect(contrast(ChoiceStyle.swatchOutline, .white, .light) >= 3)
51 #expect(contrast(ChoiceStyle.swatchOutline, .black, .dark) >= 3)
52 }
53
54 @Test func foodFillAgainstWhite() {
55 for style in Self.styles {
56 #expect(contrast(ChoiceStyle.foodFill, .white, style) >= 3)
57 }
58 }
4759}
DayByDayTests/GameTests.swift added +139
@@ -0,0 +1,139 @@
1import Testing
2@testable import DayByDay
3
4struct GameTests {
5 typealias Topic = DayByDay.Category
6
7 @Test func catalog() {
8 for c in Topic.gridCases {
9 #expect(c.games.first == .findIt)
10 }
11 #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 }
14
15 @Test(arguments: Topic.gridCases) func everyGameMakesValidQuestions(_ c: Topic) {
16 var rng = SeededGenerator(seed: 21)
17 for game in c.games {
18 let source = c.questionSource(for: game)
19 var previous: QuizItem?
20 for i in 0..<300 {
21 let q = source.next(correctCount: i % 5, excluding: previous, using: &rng)
22 #expect(q.choices.contains(q.answer), "\(c) \(game)")
23 #expect(Set(q.choices).count == q.choices.count, "\(c) \(game)")
24 #expect((3...4).contains(q.choices.count), "\(c) \(game)")
25 #expect(q.answer != previous, "\(c) \(game)")
26 #expect(q.choices.allSatisfy { $0.category == c })
27 #expect(!q.prompt.isEmpty)
28 previous = q.answer
29 }
30 }
31 }
32
33 static func group(_ item: QuizItem) -> Bool {
34 if let a = item.value(LearnAnimal.self) { return a.canFly }
35 if let f = item.value(LearnFood.self) { return f.isFruit }
36 return item.value(LearnShape.self)!.hasCorners!
37 }
38
39 @Test(arguments: [Topic.shapes, .animals, .food]) func oddOneOutHasExactlyOneOddChoice(_ c: Topic) {
40 var rng = SeededGenerator(seed: 22)
41 let source = c.questionSource(for: .oddOneOut)
42 for i in 0..<300 {
43 let q = source.next(correctCount: i % 5, excluding: nil, using: &rng)
44 let odd = Self.group(q.answer)
45 #expect(q.choices.filter { Self.group($0) == odd } == [q.answer], "\(c)")
46 #expect(q.facts.count == q.choices.count)
47 }
48 }
49
50 @Test func oddOneOutLeavesOutHeart() {
51 var rng = SeededGenerator(seed: 23)
52 let heart = Topic.shapes.item(LearnShape.heart)
53 for _ in 0..<300 {
54 #expect(!Topic.shapes.questionSource(for: .oddOneOut)
55 .next(correctCount: 4, excluding: nil, using: &rng).choices.contains(heart))
56 }
57 }
58
59 @Test func oddOneOutFacts() {
60 var rng = SeededGenerator(seed: 24)
61 let q = Topic.food.questionSource(for: .oddOneOut).next(correctCount: 0, excluding: nil, using: &rng)
62 for item in q.choices {
63 let kind = item.value(LearnFood.self)!.isFruit ? "fruit" : "vegetable"
64 #expect(q.facts[item] == "\(item.name) is a \(kind).")
65 }
66 }
67
68 func questions(_ c: Topic, _ game: Game, count: Int = 300) -> [Question] {
69 var rng = SeededGenerator(seed: 25)
70 let source = c.questionSource(for: game)
71 return (0..<count).map { source.next(correctCount: $0 % 5, excluding: nil, using: &rng) }
72 }
73
74 @Test func listenCues() {
75 let animals = questions(.animals, .listen)
76 #expect(animals.allSatisfy { $0.sound != nil && $0.prompt == "Who says this?" })
77 #expect(Set(animals.map(\.answer)).count == 7)
78 let cow = animals.first { $0.answer.value(LearnAnimal.self) == .cow }!
79 #expect(cow.sound == .moo)
80
81 let weather = questions(.weather, .listen)
82 let sounds: [LearnWeather: SoundEffect] = [.rainy: .rain, .windy: .wind, .stormy: .thunder]
83 #expect(weather.allSatisfy { sounds[$0.answer.value(LearnWeather.self)!] == $0.sound })
84 #expect(weather.allSatisfy { $0.prompt == "What weather sounds like this?" })
85
86 let numbers = questions(.numbers, .listen)
87 #expect(numbers.allSatisfy { $0.sound == .beeps($0.answer.value(LearnNumber.self)!.numeral) })
88 #expect(numbers.allSatisfy { $0.answer.value(LearnNumber.self)!.numeral <= 5 && $0.prompt == "How many beeps?" })
89
90 let letters = questions(.alphabet, .listen)
91 let excluded: Set<LearnLetter> = [.k, .q, .x]
92 #expect(letters.allSatisfy { q in q.sound == nil && q.choices.allSatisfy { !excluded.contains($0.value(LearnLetter.self)!) } })
93 let b = letters.first { $0.answer.value(LearnLetter.self) == .b }!
94 #expect(b.prompt == "Which letter does ball start with?")
95 }
96
97 @Test func findItPromptCopy() {
98 func prompt(_ c: Topic, _ value: some CaseIterable) -> String {
99 var rng = SeededGenerator(seed: 26)
100 let target = c.item(value)
101 let source = c.questionSource(for: .findIt)
102 while true {
103 let q = source.next(correctCount: 0, excluding: nil, using: &rng)
104 if q.answer == target { return q.prompt }
105 }
106 }
107 #expect(prompt(.alphabet, LearnLetter.b) == "Can you find the letter b?")
108 #expect(prompt(.numbers, LearnNumber.three) == "Can you find the number Three?")
109 #expect(prompt(.animals, LearnAnimal.cow) == "Can you find the Cow?")
110 #expect(prompt(.days, DayOfWeek.tuesday) == "Can you find Tuesday?")
111 #expect(prompt(.colors, LearnColor.red) == "Can you find Red?")
112 }
113
114 @Test func titles() {
115 #expect(Game.allCases.map(\.title) == ["Find it!", "Odd one out", "Listen"])
116 }
117
118 /// The prompt names the rule, so only one choice fits it.
119 @Test func oddOneOutPromptsNameTheRule() {
120 let expected: [(Topic, (QuizItem) -> String)] = [
121 (.animals, { $0.value(LearnAnimal.self)!.canFly ? "Which one can fly?" : "Which one can't fly?" }),
122 (.food, { $0.value(LearnFood.self)!.isFruit ? "Which one is a fruit?" : "Which one is a vegetable?" }),
123 (.shapes, { $0.value(LearnShape.self)!.hasCorners! ? "Which one has corners?" : "Which one is round?" }),
124 ]
125 for (c, prompt) in expected {
126 for q in questions(c, .oddOneOut) {
127 #expect(q.prompt == prompt(q.answer), "\(c)")
128 }
129 }
130 }
131
132 /// A storm is rain and wind to a child, so it is never offered beside those cues.
133 @Test func stormyNotOfferedForRainOrWind() {
134 let stormy = Topic.weather.item(LearnWeather.stormy)
135 for q in questions(.weather, .listen) where q.answer != stormy {
136 #expect(!q.choices.contains(stormy))
137 }
138 }
139}
DayByDayTests/ProfileStoreTests.swift +11
@@ -70,4 +70,15 @@ struct ProfileStoreTests {
7070 #expect(remaining.count == 1)
7171 #expect(s.all().map(\.name) == ["Sam"])
7272 }
73
74 @Test func recordsChosenItemAndGame() throws {
75 let s = store
76 let maya = try s.create(name: "Maya", avatar: .cat, color: .red, birthday: nil)
77 let days = Category.days.quizItems
78 s.record(days[2], chosen: days[1], game: .findIt, correct: false, for: maya, at: Date(timeIntervalSince1970: 1))
79 s.record(days[3], correct: true, for: maya, at: Date(timeIntervalSince1970: 2))
80 let records = s.answers(for: maya, category: .days).sorted { $0.timestamp < $1.timestamp }
81 #expect(records.map(\.chosenID) == ["days.monday", nil])
82 #expect(records.map(\.gameRaw) == ["findIt", nil])
83 }
7384}
DayByDayTests/QuizItemTests.swift +52
@@ -23,3 +23,55 @@ struct QuizItemTests {
2323 #expect(Category.alphabet.quizItems.first?.name == "a")
2424 }
2525}
26
27struct ItemSetTests {
28 static let pinned: [DayByDay.Category: String] = [
29 .days: "sunday monday tuesday wednesday thursday friday saturday",
30 .months: "january february march april may june july august september october november december",
31 .seasons: "spring summer fall winter",
32 .numbers: "one two three four five six seven eight nine ten",
33 .colors: "red orange yellow green blue purple pink brown black white",
34 .shapes: "circle square triangle star heart oval diamond rectangle",
35 .animals: "cat dog bird fish rabbit turtle ladybug cow duck sheep pig",
36 .alphabet: "a b c d e f g h i j k l m n o p q r s t u v w x y z",
37 .weather: "sunny cloudy rainy snowy windy stormy foggy rainbow",
38 .bodyParts: "head eyes ears nose mouth hands fingers arms legs feet heart belly",
39 .food: "apple banana carrot strawberry grapes lemon broccoli watermelon cherry orange corn pear",
40 ]
41
42 /// Answer history is keyed by these IDs; renaming a case orphans it.
43 @Test(arguments: DayByDay.Category.gridCases) func idsArePinned(_ c: DayByDay.Category) {
44 let names = Self.pinned[c]!.split(separator: " ")
45 #expect(c.quizItems.map(\.id) == names.map { "\(c.key).\($0)" })
46 }
47
48 @Test func itemAndValueRoundTrip() {
49 let cow = DayByDay.Category.animals.item(LearnAnimal.cow)
50 #expect(cow.name == "Cow")
51 #expect(cow.value(LearnAnimal.self) == .cow)
52 #expect(cow.value(LearnFood.self) == nil)
53 }
54
55 @Test func flyers() {
56 #expect(LearnAnimal.allCases.filter(\.canFly) == [.bird, .ladybug, .duck])
57 }
58
59 @Test func vegetables() {
60 #expect(LearnFood.allCases.filter { !$0.isFruit } == [.carrot, .broccoli, .corn])
61 }
62
63 @Test func roundShapes() {
64 #expect(LearnShape.allCases.filter { $0.hasCorners == false } == [.circle, .oval])
65 #expect(LearnShape.heart.hasCorners == nil)
66 }
67
68 @Test func exampleWordsStartWithTheirLetter() {
69 for letter in LearnLetter.allCases where letter != .x {
70 #expect(letter.exampleWord.first == letter.spokenName.first, "\(letter)")
71 }
72 }
73
74 @Test func drawnAnimalsHaveNoSymbol() {
75 #expect(LearnAnimal.allCases.filter { $0.symbol == nil } == [.cow, .duck, .sheep, .pig])
76 }
77}
DayByDayTests/ReviewExport.swift added +74
@@ -0,0 +1,74 @@
1import Foundation
2import SwiftUI
3import Testing
4@testable import DayByDay
5
6/// Writes every sound as WAV and every choice tile as PNG for art and sound
7/// review. Runs only when EXPORT_DIR is set, e.g.
8/// `TEST_RUNNER_EXPORT_DIR=/tmp/review xcodebuild test ... -only-testing:DayByDayTests/ReviewExport`.
9@MainActor
10@Suite(.enabled(if: ProcessInfo.processInfo.environment["EXPORT_DIR"] != nil))
11struct ReviewExport {
12 let dir = URL(fileURLWithPath: ProcessInfo.processInfo.environment["EXPORT_DIR"] ?? NSTemporaryDirectory())
13
14 @Test func sounds() throws {
15 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
16 for effect in SoundEffect.allCases {
17 try wav(SoundSynth.render(effect)).write(to: dir.appendingPathComponent("\(effect).wav"))
18 }
19 }
20
21 @Test func tiles() throws {
22 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
23 for category in DayByDay.Category.gridCases {
24 for scheme in [ColorScheme.light, .dark] {
25 let rows = stride(from: 0, to: category.quizItems.count, by: 4).map {
26 Array(category.quizItems[$0..<min($0 + 4, category.quizItems.count)])
27 }
28 let sheet = VStack(alignment: .leading, spacing: 20) {
29 ForEach(rows, id: \.self) { row in
30 HStack(spacing: 20) {
31 ForEach(row) { ChoiceTile(item: $0).frame(width: 170, height: 160) }
32 }
33 }
34 }
35 .padding(32)
36 .background(Color(.systemBackground))
37 .environment(\.colorScheme, scheme)
38 try png(sheet).write(to: dir.appendingPathComponent("tiles-\(category.key)-\(scheme).png"))
39 }
40 }
41 let drawn = HStack(spacing: 24) {
42 ForEach([LearnAnimal.cow, .duck, .sheep, .pig, .cat]) { animal in
43 AnimalIcon(animal: animal)
44 .font(.system(size: 200))
45 .frame(width: 260, height: 260)
46 .foregroundStyle(.white)
47 .padding(20)
48 .background(RoundedRectangle(cornerRadius: 32).fill(DayByDay.Category.animals.color))
49 }
50 }
51 .padding(32)
52 try png(drawn).write(to: dir.appendingPathComponent("animals-large.png"))
53 }
54
55 private func png(_ view: some View) throws -> Data {
56 let renderer = ImageRenderer(content: view)
57 renderer.scale = 2
58 return try #require(renderer.uiImage?.pngData())
59 }
60
61 /// 16-bit mono PCM.
62 private func wav(_ samples: [Float]) -> Data {
63 let rate = UInt32(SoundSynth.sampleRate)
64 var data = Data()
65 func append<T: FixedWidthInteger>(_ v: T) { withUnsafeBytes(of: v.littleEndian) { data.append(contentsOf: $0) } }
66 let bytes = UInt32(samples.count * 2)
67 data.append(contentsOf: Array("RIFF".utf8)); append(36 + bytes)
68 data.append(contentsOf: Array("WAVEfmt ".utf8)); append(UInt32(16)); append(UInt16(1)); append(UInt16(1))
69 append(rate); append(rate * 2); append(UInt16(2)); append(UInt16(16))
70 data.append(contentsOf: Array("data".utf8)); append(bytes)
71 for s in samples { append(Int16(max(-1, min(1, s)) * Float(Int16.max))) }
72 return data
73 }
74}
DayByDayTests/RoundTests.swift +109 −12
@@ -3,12 +3,12 @@ import Testing
33
44struct RoundTests {
55 let days = Category.days.quizItems
6 let picker = QuestionPicker(choiceCount: 4) { "Can you find \($0.name)?" }
6 var picker: QuestionPicker { QuestionPicker(answers: days) { "Can you find \($0.name)?" } }
77
88 @Test func choicesIncludeAnswerAndAreDistinct() {
99 var rng = SeededGenerator(seed: 1)
1010 for _ in 0..<50 {
11 let q = picker.next(from: days, excluding: nil, using: &rng)
11 let q = picker.next(correctCount: 4, excluding: nil, using: &rng)
1212 #expect(q.choices.count == 4)
1313 #expect(q.choices.contains(q.answer))
1414 #expect(Set(q.choices).count == 4)
@@ -17,27 +17,27 @@ struct RoundTests {
1717
1818 @Test func choiceCountClampsToItemCount() {
1919 var rng = SeededGenerator(seed: 2)
20 let wide = QuestionPicker(choiceCount: 6) { $0.name }
21 let q = wide.next(from: Category.seasons.quizItems, excluding: nil, using: &rng)
22 #expect(q.choices.count == 4)
20 let small = QuestionPicker(answers: Array(Category.seasons.quizItems.prefix(2))) { $0.name }
21 let q = small.next(correctCount: 4, excluding: nil, using: &rng)
22 #expect(q.choices.count == 2)
2323 }
2424
2525 @Test func neverRepeatsPreviousAnswer() {
2626 var rng = SeededGenerator(seed: 3)
2727 let previous = days[0]
2828 for _ in 0..<200 {
29 #expect(picker.next(from: days, excluding: previous, using: &rng).answer != previous)
29 #expect(picker.next(correctCount: 0, excluding: previous, using: &rng).answer != previous)
3030 }
3131 }
3232
3333 @Test func promptUsesClosure() {
3434 var rng = SeededGenerator(seed: 4)
35 let q = picker.next(from: days, excluding: nil, using: &rng)
35 let q = picker.next(correctCount: 0, excluding: nil, using: &rng)
3636 #expect(q.prompt == "Can you find \(q.answer.name)?")
3737 }
3838
3939 @Test func wrongAnswerRetriesSameQuestion() {
40 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 5))
40 var round = Round(source: picker, rng: SeededGenerator(seed: 5))
4141 let question = round.current
4242 let wrong = question.choices.first { $0 != question.answer }!
4343 #expect(round.answer(wrong) == .incorrect(correctName: question.answer.name))
@@ -47,7 +47,7 @@ struct RoundTests {
4747 }
4848
4949 @Test func tapsWhileAwaitingNextAreIgnored() {
50 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 6))
50 var round = Round(source: picker, rng: SeededGenerator(seed: 6))
5151 let answer = round.current.answer
5252 #expect(round.answer(answer) == .correct)
5353 #expect(round.isAwaitingNext)
@@ -57,7 +57,7 @@ struct RoundTests {
5757 }
5858
5959 @Test func finishesAfterFiveCorrect() {
60 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 7))
60 var round = Round(source: picker, rng: SeededGenerator(seed: 7))
6161 for _ in 0..<Round.length {
6262 #expect(!round.isFinished)
6363 _ = round.answer(round.current.answer)
@@ -68,7 +68,7 @@ struct RoundTests {
6868 }
6969
7070 @Test func tapsDuringCorrectionAreIgnored() {
71 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 8))
71 var round = Round(source: picker, rng: SeededGenerator(seed: 8))
7272 let question = round.current
7373 let wrong = question.choices.filter { $0 != question.answer }
7474 #expect(round.answer(wrong[0]) == .incorrect(correctName: question.answer.name))
@@ -79,7 +79,7 @@ struct RoundTests {
7979 }
8080
8181 @Test func finalAnswerCelebratesBeforeCompleting() {
82 var round = Round(items: days, picker: picker, rng: SeededGenerator(seed: 9))
82 var round = Round(source: picker, rng: SeededGenerator(seed: 9))
8383 for _ in 0..<(Round.length - 1) {
8484 _ = round.answer(round.current.answer)
8585 round.advance()
@@ -90,4 +90,101 @@ struct RoundTests {
9090 round.advance()
9191 #expect(round.isComplete)
9292 }
93
94 @Test func choicesGrowWithinRound() {
95 var round = Round(source: picker, rng: SeededGenerator(seed: 10))
96 var counts: [Int] = []
97 for _ in 0..<Round.length {
98 counts.append(round.current.choices.count)
99 _ = round.answer(round.current.answer)
100 round.advance()
101 }
102 #expect(counts == [3, 3, 4, 4, 4])
103 }
104
105 @Test func distractorsComeFromTheirPool() {
106 var rng = SeededGenerator(seed: 11)
107 let source = QuestionPicker(answers: Array(days.prefix(3)), distractors: days) { $0.name }
108 var distractorsSeen = Set<QuizItem>()
109 for _ in 0..<300 {
110 let q = source.next(correctCount: 4, excluding: nil, using: &rng)
111 #expect(days.prefix(3).contains(q.answer))
112 #expect(q.choices.allSatisfy(days.contains))
113 #expect(Set(q.choices).count == 4)
114 distractorsSeen.formUnion(q.choices.filter { $0 != q.answer })
115 }
116 #expect(distractorsSeen.contains { !days.prefix(3).contains($0) })
117 }
118
119 @Test func smallAnswerPoolStillVaries() {
120 var rng = SeededGenerator(seed: 12)
121 let source = QuestionPicker(answers: Array(days.prefix(2)), distractors: days) { $0.name }
122 for _ in 0..<100 {
123 #expect(source.next(correctCount: 0, excluding: days[0], using: &rng).answer == days[1])
124 }
125 }
126
127 @Test func soundComesFromClosure() {
128 var rng = SeededGenerator(seed: 13)
129 let source = QuestionPicker(answers: days, prompt: { $0.name }, sound: { _ in .moo })
130 #expect(source.next(correctCount: 0, excluding: nil, using: &rng).sound == .moo)
131 #expect(picker.next(correctCount: 0, excluding: nil, using: &rng).sound == nil)
132 }
133
134 let food = Category.food
135 var fruits: [QuizItem] { LearnFood.allCases.filter(\.isFruit).map(food.item) }
136 var vegetables: [QuizItem] { LearnFood.allCases.filter { !$0.isFruit }.map(food.item) }
137 var fruitOrVegetable: OddOneOut {
138 OddOneOut(.init(members: fruits, question: "Which one is a fruit?") { "\($0.name) is a fruit." },
139 .init(members: vegetables, question: "Which one is a vegetable?") { "\($0.name) is a vegetable." })
140 }
141
142 @Test func correctionUsesFactWhenPresent() {
143 let apple = food.item(LearnFood.apple), carrot = food.item(LearnFood.carrot)
144 let q = Question(prompt: "", choices: [apple, carrot], answer: carrot, facts: [apple: "Apple is a fruit."])
145 #expect(q.correction(for: apple) == "Apple is a fruit. Try again!")
146 let plain = Question(prompt: "", choices: [apple, carrot], answer: carrot)
147 #expect(plain.correction(for: apple) == "That's Carrot! Try again.")
148 }
149
150 @Test func oddOneOutShape() {
151 var rng = SeededGenerator(seed: 14)
152 for correctCount in [0, 4] {
153 for _ in 0..<300 {
154 let q = fruitOrVegetable.next(correctCount: correctCount, excluding: nil, using: &rng)
155 let oddGroup = fruits.contains(q.answer) ? fruits : vegetables
156 #expect(q.choices.filter(oddGroup.contains) == [q.answer])
157 #expect(q.choices.count == Round.choiceCount(correctCount: correctCount))
158 #expect(Set(q.choices).count == q.choices.count)
159 #expect(q.facts.count == q.choices.count)
160 #expect(q.prompt == (oddGroup == fruits ? "Which one is a fruit?" : "Which one is a vegetable?"))
161 }
162 }
163 }
164
165 @Test func oddOneOutNeverRepeatsPrevious() {
166 var rng = SeededGenerator(seed: 15)
167 let previous = vegetables[0]
168 for _ in 0..<200 {
169 #expect(fruitOrVegetable.next(correctCount: 0, excluding: previous, using: &rng).answer != previous)
170 }
171 }
172
173 @Test func oddOneOutFallsBackToThree() {
174 var rng = SeededGenerator(seed: 16)
175 let source = OddOneOut(.init(members: Array(fruits.prefix(2)), question: "") { $0.name },
176 .init(members: Array(vegetables.prefix(2)), question: "") { $0.name })
177 #expect(source.next(correctCount: 4, excluding: nil, using: &rng).choices.count == 3)
178 }
179
180 @Test func choiceCountGrows() {
181 #expect((0...4).map(Round.choiceCount) == [3, 3, 4, 4, 4])
182 }
183
184 @Test func newRoundAvoidsPreviousAnswer() {
185 for seed in 0..<200 {
186 let round = Round(source: picker, after: days[3], rng: SeededGenerator(seed: UInt64(seed)))
187 #expect(round.current.answer != days[3])
188 }
189 }
93190}
DayByDayTests/SoundSynthTests.swift +71 −1
@@ -21,7 +21,6 @@ struct SoundSynthTests {
2121 }
2222
2323 @Test func durations() {
24 #expect(seconds(SoundSynth.render(.tap)) < 0.08)
2524 #expect((0.3...0.6).contains(seconds(SoundSynth.render(.success))))
2625 #expect((0.25...0.5).contains(seconds(SoundSynth.render(.gentleMiss))))
2726 #expect((0.9...1.6).contains(seconds(SoundSynth.render(.roundComplete))))
@@ -30,4 +29,75 @@ struct SoundSynthTests {
3029 @Test func missIsQuieterThanSuccess() {
3130 #expect(rms(SoundSynth.render(.gentleMiss)) < rms(SoundSynth.render(.success)))
3231 }
32
33 func zeroCrossingRate(_ s: [Float]) -> Double {
34 let crossings = zip(s, s.dropFirst()).filter { ($0 < 0) != ($1 < 0) }.count
35 return Double(crossings) / Double(s.count)
36 }
37
38 /// Number of 10 ms windows whose level rises above 0.1 after falling below 0.02.
39 func onsets(_ s: [Float]) -> Int {
40 let window = Int(SoundSynth.sampleRate / 100)
41 var count = 0, quiet = true
42 for start in stride(from: 0, to: s.count - window, by: window) {
43 let level = rms(Array(s[start..<start + window]))
44 if quiet, level > 0.1 { count += 1; quiet = false }
45 if level < 0.02 { quiet = true }
46 }
47 return count
48 }
49
50 @Test(arguments: SoundEffect.allCases) func noDCOffset(_ e: SoundEffect) {
51 let s = SoundSynth.render(e)
52 #expect(abs(s.reduce(0, +) / Float(s.count)) < 0.01)
53 }
54
55 @Test func cueDurations() {
56 for e in [SoundEffect.moo, .quack, .baa, .oink, .meow, .woof, .tweet] {
57 #expect((0.35...1.6).contains(seconds(SoundSynth.render(e))), "\(e)")
58 }
59 for e in [SoundEffect.rain, .wind, .thunder] {
60 #expect((1.5...2.6).contains(seconds(SoundSynth.render(e))), "\(e)")
61 }
62 for n in 1...5 {
63 #expect(abs(seconds(SoundSynth.render(.beeps(n))) - (0.42 * Double(n - 1) + 0.12)) < 0.02)
64 }
65 #expect(SoundSynth.duration(.moo) == seconds(SoundSynth.render(.moo)))
66 }
67
68 @Test(arguments: 1...5) func beepCountMatches(_ n: Int) {
69 #expect(onsets(SoundSynth.render(.beeps(n))) == n)
70 }
71
72 @Test func allCasesListsFiveBeeps() {
73 #expect(SoundEffect.allCases.filter { if case .beeps = $0 { true } else { false } }.count == 5)
74 }
75
76 @Test func brightAndDarkCues() {
77 #expect(zeroCrossingRate(SoundSynth.render(.tweet)) > 5 * zeroCrossingRate(SoundSynth.render(.moo)))
78 #expect(zeroCrossingRate(SoundSynth.render(.thunder)) < zeroCrossingRate(SoundSynth.render(.rain)) / 5)
79 }
80
81 @Test func arpeggioNotDrownedByChord() {
82 let s = SoundSynth.render(.roundComplete)
83 let split = Int(0.38 * SoundSynth.sampleRate)
84 let first = s[..<split].map(abs).max()!, rest = s[split...].map(abs).max()!
85 #expect(first >= 0.5 * rest)
86 }
87
88 @Test func thunderIsGentle() {
89 let s = SoundSynth.render(.thunder)
90 #expect(s.prefix(Int(0.05 * SoundSynth.sampleRate)).allSatisfy { abs($0) <= 0.2 })
91 #expect(s.map(abs).max()! <= 0.6)
92 }
93
94 /// Level above ~300 Hz, roughly what a phone speaker reproduces.
95 func speakerLevel(_ s: [Float]) -> Float {
96 var low: Float = 0
97 return rms(s.map { x in low += 0.042 * (x - low); return x - low })
98 }
99
100 @Test func thunderAudibleOnSpeakers() {
101 #expect(speakerLevel(SoundSynth.render(.thunder)) >= 0.5 * speakerLevel(SoundSynth.render(.wind)))
102 }
33103}
FoodCard.swift +8 −1
@@ -46,7 +46,7 @@ struct FoodCard: View {
4646
4747// MARK: - Food model
4848
49enum LearnFood: Int, CaseIterable, Identifiable {
49nonisolated enum LearnFood: Int, CaseIterable, Identifiable {
5050 case apple, banana, carrot, strawberry, grapes, lemon,
5151 broccoli, watermelon, cherry, orange, corn, pear
5252
@@ -69,6 +69,13 @@ enum LearnFood: Int, CaseIterable, Identifiable {
6969 }
7070 }
7171
72 var isFruit: Bool {
73 switch self {
74 case .carrot, .broccoli, .corn: false
75 default: true
76 }
77 }
78
7279 var emoji: String {
7380 switch self {
7481 case .apple: "🍎"
LetterCard.swift +9 −1
@@ -39,7 +39,7 @@ struct LetterCard: View {
3939
4040// MARK: - Letter model
4141
42enum LearnLetter: Int, CaseIterable, Identifiable {
42nonisolated enum LearnLetter: Int, CaseIterable, Identifiable {
4343 case a, b, c, d, e, f, g, h, i, j, k, l, m,
4444 n, o, p, q, r, s, t, u, v, w, x, y, z
4545
@@ -55,6 +55,14 @@ enum LearnLetter: Int, CaseIterable, Identifiable {
5555 character.lowercased()
5656 }
5757
58 /// A word whose first sound is this letter's sound. X has none that a
59 /// child would know, so its word ends with the sound instead.
60 var exampleWord: String {
61 ["apple", "ball", "cat", "dog", "egg", "fish", "goat", "hat", "igloo",
62 "jam", "kite", "lion", "moon", "nest", "octopus", "pig", "queen", "rain",
63 "sun", "tiger", "umbrella", "van", "web", "fox", "yo-yo", "zebra"][rawValue]
64 }
65
5866 /// Cycle through 8 bright colors to give variety without unique-per-letter mapping.
5967 var color: Color {
6068 let palette: [Color] = [
NumberCard.swift +1 −1
@@ -63,7 +63,7 @@ struct NumberCard: View {
6363
6464// MARK: - Number model
6565
66enum LearnNumber: Int, CaseIterable, Identifiable {
66nonisolated enum LearnNumber: Int, CaseIterable, Identifiable {
6767 case one = 1, two, three, four, five, six, seven, eight, nine, ten
6868
6969 var id: LearnNumber { self }
ShapeCard.swift +11 −2
@@ -45,7 +45,7 @@ struct ShapeCard: View {
4545
4646// MARK: - Shape model
4747
48enum LearnShape: Int, CaseIterable, Identifiable {
48nonisolated enum LearnShape: Int, CaseIterable, Identifiable {
4949 case circle, square, triangle, star, heart, oval, diamond, rectangle
5050
5151 var id: Int { rawValue }
@@ -63,7 +63,16 @@ enum LearnShape: Int, CaseIterable, Identifiable {
6363 }
6464 }
6565
66 @ViewBuilder
66 /// Nil where a child could reasonably answer either way (a heart's point).
67 var hasCorners: Bool? {
68 switch self {
69 case .circle, .oval: false
70 case .heart: nil
71 default: true
72 }
73 }
74
75 @MainActor @ViewBuilder
6776 var shapeView: some View {
6877 switch self {
6978 case .circle:
WeatherCard.swift +1 −1
@@ -46,7 +46,7 @@ struct WeatherCard: View {
4646
4747// MARK: - Weather model
4848
49enum LearnWeather: Int, CaseIterable, Identifiable {
49nonisolated enum LearnWeather: Int, CaseIterable, Identifiable {
5050 case sunny, cloudy, rainy, snowy, windy, stormy, foggy, rainbow
5151
5252 var id: Int { rawValue }
docs/superpowers/plans/2026-10-16-part2-question-games.md added +230
@@ -0,0 +1,230 @@
1# Part 2: Question 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:** "Find it!" for all 11 grid topics, odd one out for food, animals and shapes, and listen-and-pick for animals, weather, alphabet and numbers, reached from each topic hub.
6
7**Architecture:** `Round` runs any `QuestionSource`: `QuestionPicker` (find it and listen-and-pick, with separate answer and distractor pools and a choice count that grows from 3 to 4 within a round) or `OddOneOut` (two groups, one odd choice). A `Game` enum plus `Category.games` and `Category.questionSource(for:)` hold the per-topic catalog and spoken copy. `RoundView` plays a question's sound cue before the prompt and records the chosen item and game. Choices render through one `ChoiceTile` with flat fills. Animal, weather and beep sounds are synthesized by `SoundSynth` (additive voice with formants, filtered noise) and rendered lazily by `SoundEngine`.
8
9**Tech Stack:** SwiftUI, SwiftData, AVFoundation, Swift Testing, Xcode 27.
10
11**Spec:** `docs/superpowers/specs/2026-10-16-learning-games-design.md` (part 2). Builds on `docs/superpowers/plans/2026-10-16-part1-foundation.md`.
12
13## Global Constraints
14
15- Effective deployment target is iOS 17.5. SF Symbols used must exist on iOS 17. There are no cow, pig, sheep or duck symbols; those are drawn with SwiftUI paths.
16- `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`. Pure logic types are `nonisolated`.
17- New app files under `DayByDay/`, new test files under `DayByDayTests/`.
18- No bundled image or audio files. All sound synthesized at runtime; all art in SwiftUI shapes, SF Symbols, or the emoji the food cards already use.
19- Nothing requires reading. Every prompt is spoken; every choice is a picture, color, numeral or letter shape. Days, months and seasons tiles show their symbol and name, as the existing cards do.
20- Wrong answers: `.gentleMiss` plus spoken correction. No buzzer, no red X.
21- Round length stays 5 correct answers. Choices: 3 for the first two questions, 4 after that.
22- Choice tiles do not reuse `DayCard`, `MonthCard`, `SeasonCard` or any other `*Card`; they use flat fills with content at 3:1 or better, covered in `ContrastTests`.
23- Branch `feat/question-games` from `main`. Every commit `Ref #N` (the last `Closes #N`). No AI attribution anywhere.
24- Test command: `xcodebuild test -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 18 Pro'` (add `-only-testing:DayByDayTests/<Suite>` per task).
25
26## Review Focus
27
281. Odd one out never has two valid answers: exactly one choice is outside the majority group, for every category and choice count. Test in Task 4 (`oddOneOutHasExactlyOneOddChoice`, 300 draws per category).
292. A topic whose answer pool is smaller than the choice count (weather listen has 3 answers; seasons has 4 items) still yields distinct choices and never repeats the previous answer. Tests in Task 3 and Task 4.
303. Tapping "Hear it again" while a sound cue is still playing does not stack the sound or clip; the prompt follows the cue rather than overlapping it. `SoundEngine` skips a repeat of a playing effect (part 1); the replay schedules speech after the cue's duration. Checked by hand in Task 6.
314. Answer history from part 1 keeps loading after `AnswerRecord` gains fields (lightweight migration of optional properties). Checked in Task 5 by launching the part 1 build, answering a question, then installing this build over it.
325. Renaming an item enum case orphans recorded history. Pin every item ID in a test (Task 1).
33
34---
35
36### Task 0: Branch and issue
37
38- [ ] **Step 1:** `git checkout -b feat/question-games main`
39- [ ] **Step 2:** Create the issue, note its number as `N` (it is #2):
40
41```bash
42gitbay issue create --title "Part 2: question games (find it, odd one out, listen and pick)" --file - <<'EOF'
43Implements part 2 of docs/superpowers/specs/2026-10-16-learning-games-design.md.
44Plan: docs/superpowers/plans/2026-10-16-part2-question-games.md
45EOF
46```
47
48- [ ] **Step 3:** `git add docs && git commit -m "docs: part 2 plan" -m "Ref #N"`
49
50### Task 1: Item sets, attributes, drawn animals
51
52**Files:**
53- Modify: `AnimalCard.swift` (enum and card icon), `FoodCard.swift`, `ShapeCard.swift`, `LetterCard.swift` (attributes only)
54- Modify: `DayByDay/Quiz/QuizItem.swift`
55- Create: `DayByDay/Quiz/AnimalIcon.swift`
56- Test: `DayByDayTests/QuizItemTests.swift`
57
58**Interfaces:**
59- Produces:
60 - `LearnAnimal` cases in this order: `cat, dog, bird, fish, rabbit, turtle, ladybug, cow, duck, sheep, pig` (ant and lizard removed). New names "Cow", "Duck", "Sheep", "Pig"; colors cow `(0.35, 0.38, 0.45)`, duck `(0.95, 0.75, 0.2)`, sheep `(0.55, 0.6, 0.7)`, pig `(0.95, 0.5, 0.65)`. `var symbol: String?` (nil for the four drawn animals). `var canFly: Bool` (bird, duck, ladybug).
61 - `LearnFood.isFruit: Bool` (false for carrot, broccoli, corn).
62 - `LearnShape.hasCorners: Bool?` (false for circle and oval, nil for heart, true otherwise).
63 - `LearnLetter.exampleWord: String`: apple, ball, cat, dog, egg, fish, goat, hat, igloo, jam, kite, lion, moon, nest, octopus, pig, queen, rain, sun, tiger, umbrella, van, web, fox, yo-yo, zebra.
64 - `struct AnimalIcon: View { init(animal: LearnAnimal) }`: the SF Symbol, or a white silhouette drawn in a `Canvas` filled with `.foreground` with details cut out (`blendMode = .destinationOut`), so it takes `foregroundStyle` like a symbol. Pig: front face, triangle ears, snout with nostrils. Cow: front face with horns, side ears, wide muzzle with nostrils, one spot. Sheep: side view, cloud body of overlapping circles, four legs, head. Duck: side view, body with raised tail, round head, beak, wing line. `AnimalCard` uses it.
65 - `extension Category { func item(_ value: some CaseIterable) -> QuizItem }` (looks up by `"\(key).\(value)"`) and `extension QuizItem { func value<T: CaseIterable>(_: T.Type) -> T? }`.
66
67- [ ] **Step 1:** Write failing tests:
68
69```swift
70@Test(arguments: Category.gridCases) func idsArePinned(_ c: Category)
71// expected case names per category, space-separated, e.g.
72// .animals: "cat dog bird fish rabbit turtle ladybug cow duck sheep pig"
73// #expect(c.quizItems.map(\.id) == names.split(separator: " ").map { "\(c.key).\($0)" })
74@Test func itemAndValueRoundTrip() // Category.animals.item(LearnAnimal.cow).value(LearnAnimal.self) == .cow; .name == "Cow"
75@Test func flyers() // LearnAnimal.allCases.filter(\.canFly) == [.bird, .ladybug, .duck]
76@Test func vegetables() // LearnFood.allCases.filter { !$0.isFruit } == [.carrot, .broccoli, .corn]
77@Test func roundShapes() // filter { $0.hasCorners == false } == [.circle, .oval]; LearnShape.heart.hasCorners == nil
78@Test func exampleWordsStartWithTheirLetter() // every letter except x: exampleWord.first == character.lowercased().first
79```
80
81- [ ] **Step 2:** Run `-only-testing:DayByDayTests/QuizItemTests`. Expected: build fails.
82- [ ] **Step 3:** Implement. Draw each animal in a 100×100 unit space scaled to the canvas; keep holes at least 6 units wide so they read at 64 pt.
83- [ ] **Step 4:** Run. Expected: PASS.
84- [ ] **Step 5:** Commit `feat: revise animal set and add item attributes` with `Ref #N`.
85
86### Task 2: Synthesized cue sounds
87
88**Files:**
89- Modify: `DayByDay/Sound/SoundSynth.swift`, `DayByDay/Sound/SoundEngine.swift`
90- Test: `DayByDayTests/SoundSynthTests.swift`
91
92**Interfaces:**
93- Produces:
94 - `nonisolated enum SoundEffect: Hashable, CaseIterable { case success, gentleMiss, roundComplete, moo, quack, baa, oink, meow, woof, tweet, rain, wind, thunder, beeps(Int) }` with `allCases` listing `beeps(1)...beeps(5)`. `.tap` is removed (unused).
95 - `SoundSynth.render(_:) -> [Float]` for every case; `SoundSynth.duration(_:) -> Double`.
96 - `SoundEngine.play(_:)` renders and attaches a player on first use of an effect (no startup render of everything). `SoundEngine.duration(_:) -> TimeInterval`.
97- Approach: animals are an additive voice: a time-varying f0, harmonics up to 8 kHz weighted by `1/√n` and by Gaussian formant peaks interpolated between vowel targets over time, optional vibrato and tremolo, optional seeded noise. Weather is seeded noise through one- and two-pole filters (rain: high-passed hiss plus soft windowed droplets; wind: band-pass with a slowly moving center and a swell; thunder: low-passed brown noise with a soft 80 ms attack and two rolling swells, DC-blocked). Beeps: `n` notes at 660 Hz, 0.12 s each, 0.42 s apart. Animal targets: moo f0 110→140→100 Hz, 1.2 s, "oo-ah-oo"; meow 450→700→450 Hz, 0.7 s, "ee-ah-oo"; baa ~330 Hz, 7 Hz vibrato and tremolo, 0.8 s; quack two 0.18 s nasal bursts ~220→180 Hz; oink two 0.2 s grunts 140→110 Hz with 30 Hz roughness; woof two 0.18 s barks 300→180 Hz; tweet three 0.09 s sine sweeps 2.5→4.2 kHz then a short warble.
98 - `roundComplete`: give the arpeggio notes a gain so its peak is at least half the chord's.
99
100- [ ] **Step 1:** Write failing tests (existing `noClipping`, `noClicks`, `notSilent` now run over the new cases too):
101
102```swift
103@Test(arguments: SoundEffect.allCases) func noDCOffset(_ e) // abs(mean) < 0.01
104@Test func cueDurations() // animals 0.35...1.6 s; rain, wind, thunder 1.5...2.6 s; beeps(n) == 0.42*(n-1)+0.12 ± 0.02
105@Test(arguments: 1...5) func beepCountMatches(_ n: Int) // onsets: count of 10 ms windows whose rms rises above 0.1 after being below 0.02 == n
106@Test func brightAndDarkCues() // zeroCrossingRate(.tweet) > 5 * zeroCrossingRate(.moo); zeroCrossingRate(.thunder) < zeroCrossingRate(.rain) / 5
107@Test func arpeggioNotDrownedByChord() // roundComplete: peak of first 0.38 s >= 0.5 * peak of the rest
108@Test func thunderIsGentle() // no sample in the first 50 ms above 0.2; peak <= 0.6
109```
110
111- [ ] **Step 2:** Run `-only-testing:DayByDayTests/SoundSynthTests`. Expected: build fails.
112- [ ] **Step 3:** Implement `SoundSynth` and lazy `SoundEngine`.
113- [ ] **Step 4:** Run. Expected: PASS.
114- [ ] **Step 5:** Commit `feat: synthesize animal, weather and beep cues` with `Ref #N`.
115
116### Task 3: Question sources
117
118**Files:**
119- Modify: `DayByDay/Quiz/Question.swift`, `DayByDay/Quiz/Round.swift`
120- Test: `DayByDayTests/RoundTests.swift`
121
122**Interfaces:**
123- Consumes: `QuizItem`, `SoundEffect`.
124- Produces:
125 - `nonisolated struct Question: Equatable { let prompt: String; let choices: [QuizItem]; let answer: QuizItem; var sound: SoundEffect? = nil; var facts: [QuizItem: String] = [:]; func correction(for tapped: QuizItem) -> String }`. `correction` returns `"\(facts[tapped]!) Try again!"` when a fact exists, else `PraisePhrases.correction(for: answer.name)`.
126 - `nonisolated protocol QuestionSource { func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question }`
127 - `QuestionPicker: QuestionSource { init(answers: [QuizItem], distractors: [QuizItem]? = nil, prompt: @escaping (QuizItem) -> String, sound: @escaping (QuizItem) -> SoundEffect? = { _ in nil }) }`. Answer from `answers`, never `previous` when another exists; distractors from `distractors ?? answers` minus the answer; count `min(Round.choiceCount(correctCount:), pool size)`. `precondition(!answers.isEmpty)`.
128 - `OddOneOut: QuestionSource { struct Group { let members: [QuizItem]; let fact: (QuizItem) -> String }; init(_ a: Group, _ b: Group) }`. Prompt `"Which one is different?"`. Picks an orientation (majority, odd) at random among those where the majority has at least `k - 1` members, lowering `k` to 3 if neither fits; odd answer never `previous` when possible; `facts` holds each choice's group fact.
129 - `Round`: `init(source: any QuestionSource, rng: some RandomNumberGenerator = SystemRandomNumberGenerator())`; `static func choiceCount(correctCount: Int) -> Int` (3 below 2, else 4). The `items:picker:` initializer goes away.
130
131- [ ] **Step 1:** Update `RoundTests` to build rounds from `QuestionPicker(answers: days) { "Can you find \($0.name)?" }` and add:
132
133```swift
134@Test func choicesGrowWithinRound() // counts over 5 correct answers: [3, 3, 4, 4, 4]
135@Test func distractorsComeFromTheirPool() // answers = first 3 days, distractors = all days → answer ∈ first 3, choices ⊂ days, 300 draws
136@Test func smallAnswerPoolStillVaries() // answers of 2 items, 100 draws with previous → answer != previous
137@Test func soundComesFromClosure() // sound: { _ in .moo } → question.sound == .moo
138@Test func correctionUsesFactWhenPresent() // facts [apple: "Apple is a fruit."] → correction(for: apple) == "Apple is a fruit. Try again!"; for another item → "That's \(answer.name)! Try again."
139@Test func oddOneOutShape() // fruits vs vegetables: 300 draws × correctCount 0 and 4 → exactly one choice from the answer's group, the rest from the other; facts.count == choices.count
140@Test func oddOneOutFallsBackToThree() // groups of 2 and 2 at correctCount 4 → 3 choices
141```
142
143- [ ] **Step 2:** Run `-only-testing:DayByDayTests/RoundTests`. Expected: build fails.
144- [ ] **Step 3:** Implement.
145- [ ] **Step 4:** Run. Expected: PASS.
146- [ ] **Step 5:** Commit `feat: add question sources with growing choices and odd one out` with `Ref #N`.
147
148### Task 4: Game catalog
149
150**Files:**
151- Create: `DayByDay/Quiz/Game.swift`
152- Test: `DayByDayTests/GameTests.swift`
153
154**Interfaces:**
155- Consumes: Task 1 attributes, `QuestionPicker`, `OddOneOut`, `SoundEffect`.
156- Produces:
157 - `nonisolated enum Game: String, CaseIterable { case findIt, oddOneOut, listen; var title: String; var symbol: String }`. Titles "Find it!", "Odd one out", "Listen"; symbols `magnifyingglass`, `square.grid.2x2.fill`, `ear.fill`.
158 - `extension Category { var games: [Game]; func questionSource(for game: Game) -> any QuestionSource }`.
159 - Find it, all grid topics. Prompt `"Can you find \(x)?"` where x is `"the letter \(name)"` (alphabet), `"the number \(name)"` (numbers), `"the \(name)"` (animals, food, shapes, body), else `name`.
160 - Odd one out: food (fruit / vegetable, facts "\(name) is a fruit." / "\(name) is a vegetable."), animals (can fly / can't fly, "\(name) can fly." / "\(name) can't fly."), shapes without heart (round / corners, "\(name) is round." / "\(name) has corners.").
161 - Listen: animals with a sound (cat meow, dog woof, bird tweet, cow moo, duck quack, sheep baa, pig oink) as both pools, prompt "Who says this?"; weather answers rainy (rain), windy (wind), stormy (thunder), distractors all weather, prompt "What weather sounds like this?"; numbers one through five, sound `.beeps(n)`, prompt "How many beeps?"; alphabet without k, q, x, no sound, prompt `"Which letter does \(exampleWord) start with?"`.
162
163- [ ] **Step 1:** Write failing tests:
164
165```swift
166@Test func catalog() // every grid topic has .findIt first; oddOneOut exactly for [.animals, .shapes, .food]; listen exactly for [.numbers, .animals, .alphabet, .weather]
167@Test(arguments: Category.gridCases) func everyGameMakesValidQuestions(_ c: Category)
168// for each game, 300 draws at correctCount 0...4: choices distinct, contain answer, count in 3...4 (or the pool size if smaller), prompt not empty
169@Test(arguments: [Category.animals, .shapes, .food]) func oddOneOutHasExactlyOneOddChoice(_ c: Category)
170// using the category's attribute: exactly one choice disagrees with the others
171@Test func listenCues() // animals: every answer has a sound; weather: answers ⊂ {rainy, windy, stormy}; numbers: sound == .beeps(numeral); alphabet: no k/q/x, prompt contains exampleWord, sound nil
172@Test func findItPromptCopy() // "Can you find the letter b?", "Can you find the number Three?", "Can you find the Cow?", "Can you find Tuesday?"
173```
174
175- [ ] **Step 2:** Run `-only-testing:DayByDayTests/GameTests`. Expected: build fails.
176- [ ] **Step 3:** Implement.
177- [ ] **Step 4:** Run. Expected: PASS.
178- [ ] **Step 5:** Commit `feat: add game catalog per topic` with `Ref #N`.
179
180### Task 5: Answer log fields
181
182**Files:**
183- Modify: `DayByDay/Profiles/AnswerRecord.swift`, `DayByDay/Profiles/ProfileStore.swift`
184- Test: `DayByDayTests/ProfileStoreTests.swift`
185
186**Interfaces:**
187- Produces: `AnswerRecord.chosenID: String?`, `AnswerRecord.gameRaw: String?` (both default nil, so existing stores migrate). `ProfileStore.record(_ item: QuizItem, chosen: QuizItem? = nil, game: Game? = nil, correct: Bool, for: Profile, at: Date = .now)`.
188
189- [ ] **Step 1:** Failing test `recordsChosenItemAndGame`: record answer Tuesday, chosen Monday, game `.findIt`, correct false → stored `chosenID == "days.monday"`, `gameRaw == "findIt"`. Existing call sites without the new arguments still compile.
190- [ ] **Step 2:** Run `-only-testing:DayByDayTests/ProfileStoreTests`. Expected: FAIL.
191- [ ] **Step 3:** Implement.
192- [ ] **Step 4:** Run. Expected: PASS. Then: install the `main` build in the simulator, answer a question, install this branch's build over it, open the app: no crash, profile still there.
193- [ ] **Step 5:** Commit `feat: record chosen item and game per answer` with `Ref #N`.
194
195### Task 6: Choice tiles, round view, hub
196
197**Files:**
198- Create: `DayByDay/Quiz/ChoiceTile.swift`
199- Modify: `DayByDay/Quiz/RoundView.swift`, `DayByDay/Home/CategoryHubView.swift`
200- Test: `DayByDayTests/ContrastTests.swift`
201
202**Interfaces:**
203- Consumes: Tasks 1–5.
204- Produces:
205 - `enum ChoiceStyle { static let foodFill: Color; static let swatchOutline: Color }`. `foodFill` `(0.24, 0.16, 0.10)`; `swatchOutline` `Color(white: 0.45)`.
206 - `struct ChoiceTile: View { init(item: QuizItem) }`: rounded rect, corner 32, flat fill. Colors: the color itself as fill with a 4 pt `swatchOutline` border, no text. Food: emoji at 72 pt on `foodFill`. Every other topic: white content on `category.color`: animals `AnimalIcon`, weather/body symbol, shapes `shapeView`, alphabet the letter at 72 pt heavy rounded, numbers numeral plus solid white `DotPattern`-style dots, days/months/seasons symbol plus name.
207 - `RoundView<Choice>`: `init(source: any QuestionSource, game: Game, @ViewBuilder choice:)`. Prompt: if `current.sound` is set, play it, then speak the prompt `SoundEngine.duration + 0.2` s later; "Hear it again" does the same. Records `round.current.answer` with `chosen: tapped`, `game:`. Correct: `.success` now, praise 0.25 s later, advance after 1.8 s. Incorrect: `.gentleMiss` now, `current.correction(for: tapped)` 0.25 s later. "You did it!" spoken 0.4 s after `.roundComplete`.
208 - `CategoryHubView`: one large button per `category.games` after "Look and listen", same style, destination `RoundView(source: category.questionSource(for: game), game: game) { ChoiceTile(item: $0) }.navigationTitle(game.title)`.
209
210- [ ] **Step 1:** Failing tests in `ContrastTests`: `swatchOutlineAgainstBackgrounds` (vs `.white` and `.black` ≥ 3), `foodFillAgainstWhite` (≥ 3). Run `-only-testing:DayByDayTests/ContrastTests`. Expected: build fails.
211- [ ] **Step 2:** Implement `ChoiceTile`, `RoundView`, hub.
212- [ ] **Step 3:** Run the full suite. Expected: `** TEST SUCCEEDED **`.
213- [ ] **Step 4:** In the simulator: each hub shows its games; play one round each of find it (days, colors, food), odd one out (animals), listen (animals, numbers, alphabet, weather); "Hear it again" during a cue does not stack; a wrong odd-one-out tap speaks the tapped item's fact. iPad landscape layout holds four tiles.
214- [ ] **Step 5:** Commit `feat: play find it, odd one out and listen from topic hubs` with `Ref #N`.
215
216### Task 7: Review exports, reviews, MR, merge
217
218**Files:**
219- Create: `DayByDayTests/ReviewExport.swift`
220
221- [ ] **Step 1:** Add `ReviewExport`, enabled only when `EXPORT_DIR` is set (`TEST_RUNNER_EXPORT_DIR` on the xcodebuild command line): writes every `SoundEffect` as 16-bit WAV and every `ChoiceTile` (all items, light and dark), `AnimalIcon` and hub as PNG via `ImageRenderer` at scale 2.
222- [ ] **Step 2:** Run it into the scratchpad. Dispatch a fresh art/sound reviewer with the PNGs, WAVs and source. Block on clear defects (clipping, clicks, harsh or startling sound, unrecognizable drawing, contrast under 3:1). Fix, rerun, second round at most. Unresolved taste notes go in the MR description.
223- [ ] **Step 3:** Fresh whole-branch code review (`git diff main...`). Fix findings that hold up.
224- [ ] **Step 4:** Full suite. Expected: `** TEST SUCCEEDED **`.
225- [ ] **Step 5:** `git push -u origin feat/question-games`; `gitbay mr create --source feat/question-games --target main --title "Part 2: question games" --file -` with a short body ending `Closes #N`.
226- [ ] **Step 6:** `gitbay mr merge <mr> --strategy squash`; `git checkout main && git pull && git branch -D feat/question-games && git push origin --delete feat/question-games`; confirm `gitbay issue show N` is closed (close it if not).
227
228## Deferred
229
230- `VersionedSchema`: the two new fields are optional, so automatic lightweight migration covers them. Adopt a versioned schema in part 7 before any non-optional change.