Commit aa5837bc1c
Unsigned
Layout: unified · split
AnimalCard.swift +22 −11
| @@ -18,10 +18,10 @@ struct AnimalCard: View { | |||
| 18 | .shadow(color: animal.color.opacity(0.4), radius: 8, y: 4) | 18 | .shadow(color: animal.color.opacity(0.4), radius: 8, y: 4) |
| 19 | 19 | ||
| 20 | VStack(spacing: 16) { | 20 | VStack(spacing: 16) { |
| 21 | Image(systemName: animal.symbol) | 21 | AnimalIcon(animal: animal) |
| 22 | .font(.system(size: 64)) | 22 | .font(.system(size: 64)) |
| 23 | .frame(height: 72) | ||
| 23 | .foregroundStyle(.white) | 24 | .foregroundStyle(.white) |
| 24 | .symbolRenderingMode(.hierarchical) | ||
| 25 | 25 | ||
| 26 | Text(animal.name) | 26 | Text(animal.name) |
| 27 | .font(.system(size: 32, weight: .bold, design: .rounded)) | 27 | .font(.system(size: 32, weight: .bold, design: .rounded)) |
| @@ -46,8 +46,8 @@ struct AnimalCard: View { | |||
| 46 | 46 | ||
| 47 | // MARK: - Animal model | 47 | // MARK: - Animal model |
| 48 | 48 | ||
| 49 | enum LearnAnimal: Int, CaseIterable, Identifiable { | 49 | nonisolated enum LearnAnimal: Int, CaseIterable, Identifiable { |
| 50 | case cat, dog, bird, fish, rabbit, turtle, ladybug, ant, lizard | 50 | case cat, dog, bird, fish, rabbit, turtle, ladybug, cow, duck, sheep, pig |
| 51 | 51 | ||
| 52 | var id: Int { rawValue } | 52 | var id: Int { rawValue } |
| 53 | 53 | ||
| @@ -60,12 +60,15 @@ enum LearnAnimal: Int, CaseIterable, Identifiable { | |||
| 60 | case .rabbit: "Rabbit" | 60 | case .rabbit: "Rabbit" |
| 61 | case .turtle: "Turtle" | 61 | case .turtle: "Turtle" |
| 62 | case .ladybug: "Ladybug" | 62 | case .ladybug: "Ladybug" |
| 63 | case .ant: "Ant" | 63 | case .cow: "Cow" |
| 64 | case .lizard: "Lizard" | 64 | case .duck: "Duck" |
| 65 | case .sheep: "Sheep" | ||
| 66 | case .pig: "Pig" | ||
| 65 | } | 67 | } |
| 66 | } | 68 | } |
| 67 | 69 | ||
| 68 | var symbol: String { | 70 | /// Nil for animals without an SF Symbol; `AnimalIcon` draws those. |
| 71 | var symbol: String? { | ||
| 69 | switch self { | 72 | switch self { |
| 70 | case .cat: "cat.fill" | 73 | case .cat: "cat.fill" |
| 71 | case .dog: "dog.fill" | 74 | case .dog: "dog.fill" |
| @@ -74,8 +77,7 @@ enum LearnAnimal: Int, CaseIterable, Identifiable { | |||
| 74 | case .rabbit: "hare.fill" | 77 | case .rabbit: "hare.fill" |
| 75 | case .turtle: "tortoise.fill" | 78 | case .turtle: "tortoise.fill" |
| 76 | case .ladybug: "ladybug.fill" | 79 | case .ladybug: "ladybug.fill" |
| 77 | case .ant: "ant.fill" | 80 | case .cow, .duck, .sheep, .pig: nil |
| 78 | case .lizard: "lizard.fill" | ||
| 79 | } | 81 | } |
| 80 | } | 82 | } |
| 81 | 83 | ||
| @@ -88,8 +90,17 @@ enum LearnAnimal: Int, CaseIterable, Identifiable { | |||
| 88 | case .rabbit: Color(red: 0.75, green: 0.6, blue: 0.8) // lavender | 90 | case .rabbit: Color(red: 0.75, green: 0.6, blue: 0.8) // lavender |
| 89 | case .turtle: Color(red: 0.35, green: 0.7, blue: 0.4) // green | 91 | case .turtle: Color(red: 0.35, green: 0.7, blue: 0.4) // green |
| 90 | case .ladybug: Color(red: 0.9, green: 0.25, blue: 0.25) // red | 92 | 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 | 93 | case .cow: Color(red: 0.35, green: 0.38, blue: 0.45) // slate |
| 92 | case .lizard: Color(red: 0.45, green: 0.75, blue: 0.35) // lime | 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 | ||
| 93 | } | 104 | } |
| 94 | } | 105 | } |
| 95 | } | 106 | } |
BodyPartCard.swift +1 −1
| @@ -46,7 +46,7 @@ struct BodyPartCard: View { | |||
| 46 | 46 | ||
| 47 | // MARK: - Body part model | 47 | // MARK: - Body part model |
| 48 | 48 | ||
| 49 | enum LearnBodyPart: Int, CaseIterable, Identifiable { | 49 | nonisolated enum LearnBodyPart: Int, CaseIterable, Identifiable { |
| 50 | case head, eyes, ears, nose, mouth, hands, fingers, arms, legs, feet, heart, belly | 50 | case head, eyes, ears, nose, mouth, hands, fingers, arms, legs, feet, heart, belly |
| 51 | 51 | ||
| 52 | var id: Int { rawValue } | 52 | var id: Int { rawValue } |
ColorCard.swift +1 −1
| @@ -39,7 +39,7 @@ struct ColorCard: View { | |||
| 39 | 39 | ||
| 40 | // MARK: - Color model | 40 | // MARK: - Color model |
| 41 | 41 | ||
| 42 | enum LearnColor: Int, CaseIterable, Identifiable { | 42 | nonisolated enum LearnColor: Int, CaseIterable, Identifiable { |
| 43 | case red, orange, yellow, green, blue, purple, pink, brown, black, white | 43 | case red, orange, yellow, green, blue, purple, pink, brown, black, white |
| 44 | 44 | ||
| 45 | var id: Int { rawValue } | 45 | var id: Int { rawValue } |
DayByDay/ContentView.swift +1 −1
| @@ -10,7 +10,7 @@ import SwiftUI | |||
| 10 | 10 | ||
| 11 | // MARK: - Category model | 11 | // MARK: - Category model |
| 12 | 12 | ||
| 13 | enum Category: Int, CaseIterable, Identifiable { | 13 | nonisolated enum Category: Int, CaseIterable, Identifiable { |
| 14 | case today, days, months, seasons, numbers, colors, shapes, animals, alphabet, | 14 | case today, days, months, seasons, numbers, colors, shapes, animals, alphabet, |
| 15 | weather, bodyParts, food | 15 | weather, bodyParts, food |
| 16 | 16 | ||
DayByDay/DayCard.swift +1 −1
| @@ -60,7 +60,7 @@ struct DayCard: View { | |||
| 60 | 60 | ||
| 61 | // MARK: - Day model | 61 | // MARK: - Day model |
| 62 | 62 | ||
| 63 | enum DayOfWeek: Int, CaseIterable, Identifiable { | 63 | nonisolated enum DayOfWeek: Int, CaseIterable, Identifiable { |
| 64 | case sunday, monday, tuesday, wednesday, thursday, friday, saturday | 64 | case sunday, monday, tuesday, wednesday, thursday, friday, saturday |
| 65 | 65 | ||
| 66 | var id: Int { rawValue } | 66 | var id: Int { rawValue } |
DayByDay/Home/CategoryHubView.swift +8
| @@ -16,6 +16,14 @@ struct CategoryHubView: View { | |||
| 16 | category.lookAndListenView | 16 | category.lookAndListenView |
| 17 | .navigationTitle(category.label) | 17 | .navigationTitle(category.label) |
| 18 | } | 18 | } |
| 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 | } | ||
| 19 | } | 27 | } |
| 20 | .padding(32) | 28 | .padding(32) |
| 21 | .frame(maxWidth: 640) | 29 | .frame(maxWidth: 640) |
DayByDay/MonthCard.swift +1 −1
| @@ -60,7 +60,7 @@ struct MonthCard: View { | |||
| 60 | 60 | ||
| 61 | // MARK: - Month model | 61 | // MARK: - Month model |
| 62 | 62 | ||
| 63 | enum MonthOfYear: Int, CaseIterable, Identifiable { | 63 | nonisolated enum MonthOfYear: Int, CaseIterable, Identifiable { |
| 64 | case january, february, march, april, may, june, | 64 | case january, february, march, april, may, june, |
| 65 | july, august, september, october, november, december | 65 | july, august, september, october, november, december |
| 66 | 66 | ||
DayByDay/Profiles/AnswerRecord.swift +8 −1
| @@ -11,13 +11,20 @@ import SwiftData | |||
| 11 | final class AnswerRecord { | 11 | final class AnswerRecord { |
| 12 | var categoryRaw: Int | 12 | var categoryRaw: Int |
| 13 | var itemID: String | 13 | 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? | ||
| 14 | var isCorrect: Bool | 18 | var isCorrect: Bool |
| 15 | var timestamp: Date | 19 | var timestamp: Date |
| 16 | var profile: Profile? | 20 | var profile: Profile? |
| 17 | 21 | ||
| 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) { | ||
| 19 | self.categoryRaw = categoryRaw | 24 | self.categoryRaw = categoryRaw |
| 20 | self.itemID = itemID | 25 | self.itemID = itemID |
| 26 | self.chosenID = chosenID | ||
| 27 | self.gameRaw = gameRaw | ||
| 21 | self.isCorrect = isCorrect | 28 | self.isCorrect = isCorrect |
| 22 | self.timestamp = timestamp | 29 | self.timestamp = timestamp |
| 23 | self.profile = profile | 30 | self.profile = profile |
DayByDay/Profiles/ProfileStore.swift +4 −1
| @@ -55,8 +55,11 @@ final class ProfileStore { | |||
| 55 | try? context.save() | 55 | try? context.save() |
| 56 | } | 56 | } |
| 57 | 57 | ||
| 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) { | ||
| 59 | context.insert(AnswerRecord(categoryRaw: item.category.rawValue, itemID: item.id, | 61 | context.insert(AnswerRecord(categoryRaw: item.category.rawValue, itemID: item.id, |
| 62 | chosenID: chosen?.id, gameRaw: game?.rawValue, | ||
| 60 | isCorrect: correct, timestamp: date, profile: profile)) | 63 | isCorrect: correct, timestamp: date, profile: profile)) |
| 61 | try? context.save() | 64 | try? context.save() |
| 62 | } | 65 | } |
DayByDay/Quiz/AnimalIcon.swift added +140
| @@ -0,0 +1,140 @@ | |||
| 1 | // | ||
| 2 | // AnimalIcon.swift | ||
| 3 | // DayByDay | ||
| 4 | // | ||
| 5 | |||
| 6 | import 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`. | ||
| 11 | struct 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. | ||
| 33 | private 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 | |||
| 6 | import SwiftUI | ||
| 7 | |||
| 8 | enum 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. | ||
| 17 | struct 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. | ||
| 113 | private 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 | |||
| 6 | nonisolated 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 | |||
| 26 | nonisolated 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 | |||
| 41 | nonisolated 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 | |||
| 52 | nonisolated 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 { | |||
| 7 | let prompt: String | 7 | let prompt: String |
| 8 | let choices: [QuizItem] | 8 | let choices: [QuizItem] |
| 9 | let answer: QuizItem | 9 | 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 | |||
| 21 | nonisolated protocol QuestionSource { | ||
| 22 | func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question | ||
| 10 | } | 23 | } |
| 11 | 24 | ||
| 12 | nonisolated struct QuestionPicker { | 25 | /// "Find the one I name" questions. The answer comes from `answers`, the |
| 13 | var choiceCount: Int | 26 | /// other choices from `distractors`. |
| 14 | var prompt: (QuizItem) -> String | 27 | nonisolated 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?"). | ||
| 57 | nonisolated 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 | } | ||
| 15 | 70 | ||
| 16 | /// Picks a random answer (never `previous` when there is an alternative) | 71 | func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question { |
| 17 | /// plus distinct distractors, shuffled. | 72 | let pairs = [(groups.0, groups.1), (groups.1, groups.0)] |
| 18 | func next(from items: [QuizItem], excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question { | 73 | var count = Round.choiceCount(correctCount: correctCount) |
| 19 | let candidates = items.count > 1 ? items.filter { $0 != previous } : items | 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 | ||
| 20 | let answer = candidates.randomElement(using: &rng)! | 81 | let answer = candidates.randomElement(using: &rng)! |
| 21 | let distractors = items.filter { $0 != answer } | 82 | let others = Array(majority.members.shuffled(using: &rng).prefix(count - 1)) |
| 22 | .shuffled(using: &rng) | 83 | var facts = [answer: odd.fact(answer)] |
| 23 | .prefix(min(choiceCount, items.count) - 1) | 84 | for item in others { facts[item] = majority.fact(item) } |
| 24 | let choices = ([answer] + distractors).shuffled(using: &rng) | 85 | return Question(prompt: odd.question, |
| 25 | return Question(prompt: prompt(answer), choices: choices, answer: answer) | 86 | choices: (others + [answer]).shuffled(using: &rng), |
| 87 | answer: answer, facts: facts) | ||
| 26 | } | 88 | } |
| 27 | } | 89 | } |
DayByDay/Quiz/QuizItem.swift +13 −1
| @@ -10,7 +10,7 @@ nonisolated struct QuizItem: Identifiable, Hashable, Sendable { | |||
| 10 | let category: Category | 10 | let category: Category |
| 11 | } | 11 | } |
| 12 | 12 | ||
| 13 | extension Category { | 13 | nonisolated extension Category { |
| 14 | /// Categories shown in the home grid. Today is reached from the banner. | 14 | /// Categories shown in the home grid. Today is reached from the banner. |
| 15 | static var gridCases: [Category] { | 15 | static var gridCases: [Category] { |
| 16 | allCases.filter { $0 != .today } | 16 | allCases.filter { $0 != .today } |
| @@ -50,7 +50,19 @@ extension Category { | |||
| 50 | } | 50 | } |
| 51 | } | 51 | } |
| 52 | 52 | ||
| 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 | |||
| 53 | private func items<T>(_ cases: [T], _ name: KeyPath<T, String>) -> [QuizItem] { | 58 | private func items<T>(_ cases: [T], _ name: KeyPath<T, String>) -> [QuizItem] { |
| 54 | cases.map { QuizItem(id: "\(key).\($0)", name: $0[keyPath: name], category: self) } | 59 | cases.map { QuizItem(id: "\(key).\($0)", name: $0[keyPath: name], category: self) } |
| 55 | } | 60 | } |
| 56 | } | 61 | } |
| 62 | |||
| 63 | nonisolated 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 { | |||
| 15 | nonisolated struct Round { | 15 | nonisolated struct Round { |
| 16 | static let length = 5 | 16 | static let length = 5 |
| 17 | 17 | ||
| 18 | private let items: [QuizItem] | 18 | private let source: any QuestionSource |
| 19 | private let picker: QuestionPicker | ||
| 20 | private var rng: any RandomNumberGenerator | 19 | private var rng: any RandomNumberGenerator |
| 21 | private(set) var current: Question | 20 | private(set) var current: Question |
| 22 | private(set) var correctCount = 0 | 21 | private(set) var correctCount = 0 |
| @@ -28,11 +27,18 @@ nonisolated struct Round { | |||
| 28 | /// True once the last correct answer's feedback is done. | 27 | /// True once the last correct answer's feedback is done. |
| 29 | var isComplete: Bool { isFinished && !isAwaitingNext } | 28 | var isComplete: Bool { isFinished && !isAwaitingNext } |
| 30 | 29 | ||
| 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()) { | ||
| 32 | var rng: any RandomNumberGenerator = rng | 39 | var rng: any RandomNumberGenerator = rng |
| 33 | self.items = items | 40 | self.source = source |
| 34 | self.picker = picker | 41 | self.current = source.next(correctCount: 0, excluding: previous, using: &rng) |
| 35 | self.current = picker.next(from: items, excluding: nil, using: &rng) | ||
| 36 | self.rng = rng | 42 | self.rng = rng |
| 37 | } | 43 | } |
| 38 | 44 | ||
| @@ -55,6 +61,6 @@ nonisolated struct Round { | |||
| 55 | guard isAwaitingNext else { return } | 61 | guard isAwaitingNext else { return } |
| 56 | isAwaitingNext = false | 62 | isAwaitingNext = false |
| 57 | guard !isFinished else { return } | 63 | 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) |
| 59 | } | 65 | } |
| 60 | } | 66 | } |
DayByDay/Quiz/RoundView.swift +41 −15
| @@ -7,12 +7,14 @@ import SwiftUI | |||
| 7 | 7 | ||
| 8 | enum RoundStyle { | 8 | enum RoundStyle { |
| 9 | static let playAgainFill = Color(red: 0.18, green: 0.56, blue: 0.28) | 9 | 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 | ||
| 10 | } | 12 | } |
| 11 | 13 | ||
| 12 | /// Runs a round of questions. The caller supplies how each choice looks. | 14 | /// Runs a round of questions. The caller supplies how each choice looks. |
| 13 | struct RoundView<Choice: View>: View { | 15 | struct RoundView<Choice: View>: View { |
| 14 | private let items: [QuizItem] | 16 | private let source: any QuestionSource |
| 15 | private let picker: QuestionPicker | 17 | private let game: Game |
| 16 | private let choice: (QuizItem) -> Choice | 18 | private let choice: (QuizItem) -> Choice |
| 17 | 19 | ||
| 18 | @Environment(ProfileSession.self) private var session | 20 | @Environment(ProfileSession.self) private var session |
| @@ -20,14 +22,17 @@ struct RoundView<Choice: View>: View { | |||
| 20 | @State private var praise = PraisePhrases() | 22 | @State private var praise = PraisePhrases() |
| 21 | @State private var celebrating = false | 23 | @State private var celebrating = false |
| 22 | @State private var dimmed: QuizItem? | 24 | @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 | ||
| 23 | 28 | ||
| 24 | private let columns = [GridItem(.adaptive(minimum: 150, maximum: 320), spacing: 20)] | 29 | private let columns = [GridItem(.adaptive(minimum: 150, maximum: 320), spacing: 20)] |
| 25 | 30 | ||
| 26 | init(items: [QuizItem], picker: QuestionPicker, @ViewBuilder choice: @escaping (QuizItem) -> Choice) { | 31 | init(source: any QuestionSource, game: Game, @ViewBuilder choice: @escaping (QuizItem) -> Choice) { |
| 27 | self.items = items | 32 | self.source = source |
| 28 | self.picker = picker | 33 | self.game = game |
| 29 | self.choice = choice | 34 | self.choice = choice |
| 30 | _round = State(initialValue: Round(items: items, picker: picker)) | 35 | _round = State(initialValue: Round(source: source)) |
| 31 | } | 36 | } |
| 32 | 37 | ||
| 33 | var body: some View { | 38 | var body: some View { |
| @@ -39,6 +44,10 @@ struct RoundView<Choice: View>: View { | |||
| 39 | } | 44 | } |
| 40 | } | 45 | } |
| 41 | .onAppear { speakPrompt() } | 46 | .onAppear { speakPrompt() } |
| 47 | .onDisappear { | ||
| 48 | speechToken += 1 | ||
| 49 | SpeechSynthesizer.shared.stop() | ||
| 50 | } | ||
| 42 | .onChange(of: round.current) { speakPrompt() } | 51 | .onChange(of: round.current) { speakPrompt() } |
| 43 | } | 52 | } |
| 44 | 53 | ||
| @@ -80,7 +89,7 @@ struct RoundView<Choice: View>: View { | |||
| 80 | Text("You did it!") | 89 | Text("You did it!") |
| 81 | .font(.system(size: 48, weight: .heavy, design: .rounded)) | 90 | .font(.system(size: 48, weight: .heavy, design: .rounded)) |
| 82 | Button { | 91 | Button { |
| 83 | round = Round(items: items, picker: picker) | 92 | round = Round(source: source, after: round.current.answer) |
| 84 | } label: { | 93 | } label: { |
| 85 | Label("Play again", systemImage: "arrow.clockwise") | 94 | Label("Play again", systemImage: "arrow.clockwise") |
| 86 | .font(.system(size: 28, weight: .bold, design: .rounded)) | 95 | .font(.system(size: 28, weight: .bold, design: .rounded)) |
| @@ -94,7 +103,7 @@ struct RoundView<Choice: View>: View { | |||
| 94 | .padding(32) | 103 | .padding(32) |
| 95 | .onAppear { | 104 | .onAppear { |
| 96 | SoundEngine.shared.play(.roundComplete) | 105 | SoundEngine.shared.play(.roundComplete) |
| 97 | SpeechSynthesizer.shared.speak("You did it!") | 106 | say("You did it!", after: 0.4) |
| 98 | } | 107 | } |
| 99 | } | 108 | } |
| 100 | 109 | ||
| @@ -102,21 +111,22 @@ struct RoundView<Choice: View>: View { | |||
| 102 | let outcome = round.answer(item) | 111 | let outcome = round.answer(item) |
| 103 | guard outcome != .ignored else { return } | 112 | guard outcome != .ignored else { return } |
| 104 | if let profile = session.current { | 113 | 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) | ||
| 106 | } | 116 | } |
| 107 | switch outcome { | 117 | switch outcome { |
| 108 | case .correct: | 118 | case .correct: |
| 109 | SoundEngine.shared.play(.success) | 119 | SoundEngine.shared.play(.success) |
| 110 | var rng = SystemRandomNumberGenerator() | 120 | var rng = SystemRandomNumberGenerator() |
| 111 | SpeechSynthesizer.shared.speak(praise.next(using: &rng)) | 121 | say(praise.next(using: &rng), after: RoundStyle.speechDelay) |
| 112 | celebrating = true | 122 | celebrating = true |
| 113 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { | 123 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.8) { |
| 114 | celebrating = false | 124 | celebrating = false |
| 115 | round.advance() | 125 | round.advance() |
| 116 | } | 126 | } |
| 117 | case .incorrect(let correctName): | 127 | case .incorrect: |
| 118 | SoundEngine.shared.play(.gentleMiss) | 128 | SoundEngine.shared.play(.gentleMiss) |
| 119 | SpeechSynthesizer.shared.speak(PraisePhrases.correction(for: correctName)) | 129 | say(round.current.correction(for: item), after: RoundStyle.speechDelay) |
| 120 | withAnimation(.easeOut(duration: 0.2)) { dimmed = item } | 130 | withAnimation(.easeOut(duration: 0.2)) { dimmed = item } |
| 121 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { | 131 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { |
| 122 | withAnimation { if dimmed == item { dimmed = nil } } | 132 | withAnimation { if dimmed == item { dimmed = nil } } |
| @@ -127,9 +137,25 @@ struct RoundView<Choice: View>: View { | |||
| 127 | } | 137 | } |
| 128 | } | 138 | } |
| 129 | 139 | ||
| 140 | /// Plays the question's sound cue, if any, then speaks the prompt. | ||
| 130 | private func speakPrompt() { | 141 | private func speakPrompt() { |
| 131 | guard !round.isFinished else { return } | 142 | guard !round.isFinished, !round.isAwaitingNext else { return } |
| 132 | SpeechSynthesizer.shared.speak(round.current.prompt) | 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 | } | ||
| 133 | } | 159 | } |
| 134 | } | 160 | } |
| 135 | 161 | ||
DayByDay/SeasonCard.swift +1 −1
| @@ -60,7 +60,7 @@ struct SeasonCard: View { | |||
| 60 | 60 | ||
| 61 | // MARK: - Season model | 61 | // MARK: - Season model |
| 62 | 62 | ||
| 63 | enum Season: Int, CaseIterable, Identifiable { | 63 | nonisolated enum Season: Int, CaseIterable, Identifiable { |
| 64 | case spring, summer, fall, winter | 64 | case spring, summer, fall, winter |
| 65 | 65 | ||
| 66 | var id: Int { rawValue } | 66 | var id: Int { rawValue } |
DayByDay/Sound/SoundEngine.swift +38 −22
| @@ -5,10 +5,10 @@ | |||
| 5 | 5 | ||
| 6 | import AVFoundation | 6 | import AVFoundation |
| 7 | 7 | ||
| 8 | /// Plays pre-rendered sound effects. Buffers are rendered once at startup. | 8 | /// Plays synthesized sound effects. Each effect is rendered and given its |
| 9 | /// Each effect has its own player node so effects overlap instead of cutting | 9 | /// own player node the first time it plays. Separate players let effects |
| 10 | /// each other off mid-wave (which clicks). A repeat of an effect that is | 10 | /// overlap instead of cutting each other off mid-wave (which clicks). A |
| 11 | /// still playing is skipped for the same reason. | 11 | /// repeat of an effect that is still playing is skipped for the same reason. |
| 12 | final class SoundEngine { | 12 | final class SoundEngine { |
| 13 | static let shared = SoundEngine() | 13 | static let shared = SoundEngine() |
| 14 | 14 | ||
| @@ -18,25 +18,11 @@ final class SoundEngine { | |||
| 18 | private var players: [SoundEffect: AVAudioPlayerNode] = [:] | 18 | private var players: [SoundEffect: AVAudioPlayerNode] = [:] |
| 19 | private var busyUntil: [SoundEffect: Date] = [:] | 19 | private var busyUntil: [SoundEffect: Date] = [:] |
| 20 | 20 | ||
| 21 | private init() { | 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 | } | ||
| 37 | 22 | ||
| 38 | func play(_ effect: SoundEffect) { | 23 | 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) | ||
| 40 | let now = Date() | 26 | let now = Date() |
| 41 | if let busy = busyUntil[effect], busy > now { return } | 27 | if let busy = busyUntil[effect], busy > now { return } |
| 42 | if !engine.isRunning { | 28 | if !engine.isRunning { |
| @@ -44,8 +30,38 @@ final class SoundEngine { | |||
| 44 | try? AVAudioSession.sharedInstance().setActive(true) | 30 | try? AVAudioSession.sharedInstance().setActive(true) |
| 45 | try? engine.start() | 31 | try? engine.start() |
| 46 | } | 32 | } |
| 47 | busyUntil[effect] = now.addingTimeInterval(Double(buffer.frameLength) / SoundSynth.sampleRate) | 33 | busyUntil[effect] = now.addingTimeInterval(duration(effect)) |
| 48 | player.scheduleBuffer(buffer, at: nil) | 34 | player.scheduleBuffer(buffer, at: nil) |
| 49 | if !player.isPlaying { player.play() } | 35 | if !player.isPlaying { player.play() } |
| 50 | } | 36 | } |
| 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 | } | ||
| 51 | } | 67 | } |
DayByDay/Sound/SoundSynth.swift +309 −22
| @@ -5,25 +5,30 @@ | |||
| 5 | 5 | ||
| 6 | import Foundation | 6 | import Foundation |
| 7 | 7 | ||
| 8 | nonisolated enum SoundEffect: CaseIterable { | 8 | nonisolated enum SoundEffect: Hashable, CaseIterable, Sendable { |
| 9 | case success, gentleMiss, tap, roundComplete | 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) | ||
| 10 | } | 18 | } |
| 11 | 19 | ||
| 12 | /// Renders sound effects to mono sample buffers. Notes are sines with soft | 20 | /// Renders sound effects to mono sample buffers. Every sound fades in and out |
| 13 | /// harmonics and smooth envelopes, so there are no clicks or harsh edges. | 21 | /// smoothly and starts and ends on silence, so there are no clicks. |
| 14 | nonisolated enum SoundSynth { | 22 | nonisolated enum SoundSynth { |
| 15 | static let sampleRate: Double = 44_100 | 23 | static let sampleRate: Double = 44_100 |
| 16 | 24 | ||
| 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 | |||
| 24 | /// Silence at each end so playback never starts or stops mid-wave. | 25 | /// Silence at each end so playback never starts or stops mid-wave. |
| 25 | private static let pad = 0.004 | 26 | private static let pad = 0.004 |
| 26 | 27 | ||
| 28 | static func duration(_ effect: SoundEffect) -> Double { | ||
| 29 | Double(render(effect).count) / sampleRate | ||
| 30 | } | ||
| 31 | |||
| 27 | static func render(_ effect: SoundEffect) -> [Float] { | 32 | static func render(_ effect: SoundEffect) -> [Float] { |
| 28 | switch effect { | 33 | switch effect { |
| 29 | case .success: | 34 | case .success: |
| @@ -36,22 +41,82 @@ nonisolated enum SoundSynth { | |||
| 36 | mix([ | 41 | mix([ |
| 37 | Note(frequency: 329.63, start: 0, duration: 0.17, harmonics: [1, 0.15]), | 42 | Note(frequency: 329.63, start: 0, duration: 0.17, harmonics: [1, 0.15]), |
| 38 | Note(frequency: 261.63, start: 0.15, duration: 0.18, harmonics: [1, 0.15]), | 43 | Note(frequency: 261.63, start: 0.15, duration: 0.18, harmonics: [1, 0.15]), |
| 39 | ], peak: 0.3) | 44 | ], peak: 0.45) |
| 40 | case .tap: | ||
| 41 | mix([Note(frequency: 880, start: 0, duration: 0.05, harmonics: [1, 0.2])], peak: 0.4) | ||
| 42 | case .roundComplete: | 45 | case .roundComplete: |
| 43 | mix([ | 46 | mix([ |
| 44 | Note(frequency: 523.25, start: 0, duration: 0.14), | 47 | Note(frequency: 523.25, start: 0, duration: 0.14, gain: 2.2), |
| 45 | Note(frequency: 659.25, start: 0.12, duration: 0.14), | 48 | Note(frequency: 659.25, start: 0.12, duration: 0.14, gain: 2.2), |
| 46 | Note(frequency: 783.99, start: 0.24, duration: 0.14), | 49 | Note(frequency: 783.99, start: 0.24, duration: 0.14, gain: 2.2), |
| 47 | Note(frequency: 523.25, start: 0.4, duration: 0.7), | 50 | Note(frequency: 523.25, start: 0.4, duration: 0.7), |
| 48 | Note(frequency: 659.25, start: 0.4, duration: 0.7), | 51 | Note(frequency: 659.25, start: 0.4, duration: 0.7), |
| 49 | Note(frequency: 783.99, start: 0.4, duration: 0.7), | 52 | Note(frequency: 783.99, start: 0.4, duration: 0.7), |
| 50 | Note(frequency: 1046.5, start: 0.4, duration: 0.7), | 53 | Note(frequency: 1046.5, start: 0.4, duration: 0.7), |
| 51 | ], peak: 0.6) | 54 | ], 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() | ||
| 52 | } | 107 | } |
| 53 | } | 108 | } |
| 54 | 109 | ||
| 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 | |||
| 55 | private static func mix(_ notes: [Note], peak: Float) -> [Float] { | 120 | private static func mix(_ notes: [Note], peak: Float) -> [Float] { |
| 56 | let end = notes.map { $0.start + $0.duration }.max()! | 121 | let end = notes.map { $0.start + $0.duration }.max()! |
| 57 | var out = [Float](repeating: 0, count: Int((end + 2 * pad) * sampleRate)) | 122 | var out = [Float](repeating: 0, count: Int((end + 2 * pad) * sampleRate)) |
| @@ -64,18 +129,240 @@ nonisolated enum SoundSynth { | |||
| 64 | for (n, amp) in note.harmonics.enumerated() { | 129 | for (n, amp) in note.harmonics.enumerated() { |
| 65 | v += amp * sin(2 * .pi * note.frequency * Double(n + 1) * t) | 130 | v += amp * sin(2 * .pi * note.frequency * Double(n + 1) * t) |
| 66 | } | 131 | } |
| 67 | out[offset + i] += Float(v * envelope(t, duration: note.duration)) | 132 | out[offset + i] += Float(note.gain * v * envelope(t, duration: note.duration)) |
| 68 | } | 133 | } |
| 69 | } | 134 | } |
| 70 | let maxAbs = out.map(abs).max() ?? 1 | 135 | return normalized(out, peak: peak) |
| 71 | return out.map { $0 / maxAbs * peak } | ||
| 72 | } | 136 | } |
| 73 | 137 | ||
| 74 | /// Smooth attack, gentle exponential decay, smooth release to zero. | 138 | /// Smooth attack, gentle exponential decay, smooth release to zero. |
| 75 | private static func envelope(_ t: Double, duration: Double) -> Double { | 139 | private static func envelope(_ t: Double, duration: Double) -> Double { |
| 76 | let attack = 0.01, release = 0.03 | 140 | 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 { | ||
| 77 | let rise = t < attack ? pow(sin(.pi / 2 * t / attack), 2) : 1 | 321 | 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 | 322 | let fall = t > duration - release ? pow(sin(.pi / 2 * max(0, duration - t) / release), 2) : 1 |
| 79 | return rise * fall * exp(-3 * t / max(duration, 0.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 } | ||
| 80 | } | 367 | } |
| 81 | } | 368 | } |
DayByDay/SpeechSynthesizer.swift +4
| @@ -47,6 +47,10 @@ final class SpeechSynthesizer { | |||
| 47 | synthesizer.speak(utterance) | 47 | synthesizer.speak(utterance) |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | func stop() { | ||
| 51 | synthesizer.stopSpeaking(at: .immediate) | ||
| 52 | } | ||
| 53 | |||
| 50 | /// Picks the best en-US voice on the device. | 54 | /// Picks the best en-US voice on the device. |
| 51 | /// Filters for en-US, excludes novelty voices, then sorts by quality | 55 | /// Filters for en-US, excludes novelty voices, then sorts by quality |
| 52 | /// descending so premium (3) > enhanced (2) > default (1). | 56 | /// descending so premium (3) > enhanced (2) > default (1). |
DayByDayTests/ContrastTests.swift +12
| @@ -44,4 +44,16 @@ struct ContrastTests { | |||
| 44 | #expect(contrast(color.symbolColor, color.color, style) >= 3, "\(color) \(style.rawValue)") | 44 | #expect(contrast(color.symbolColor, color.color, style) >= 3, "\(color) \(style.rawValue)") |
| 45 | } | 45 | } |
| 46 | } | 46 | } |
| 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 | } | ||
| 47 | } | 59 | } |
DayByDayTests/GameTests.swift added +139
| @@ -0,0 +1,139 @@ | |||
| 1 | import Testing | ||
| 2 | @testable import DayByDay | ||
| 3 | |||
| 4 | struct 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 { | |||
| 70 | #expect(remaining.count == 1) | 70 | #expect(remaining.count == 1) |
| 71 | #expect(s.all().map(\.name) == ["Sam"]) | 71 | #expect(s.all().map(\.name) == ["Sam"]) |
| 72 | } | 72 | } |
| 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 | } | ||
| 73 | } | 84 | } |
DayByDayTests/QuizItemTests.swift +52
| @@ -23,3 +23,55 @@ struct QuizItemTests { | |||
| 23 | #expect(Category.alphabet.quizItems.first?.name == "a") | 23 | #expect(Category.alphabet.quizItems.first?.name == "a") |
| 24 | } | 24 | } |
| 25 | } | 25 | } |
| 26 | |||
| 27 | struct 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 @@ | |||
| 1 | import Foundation | ||
| 2 | import SwiftUI | ||
| 3 | import 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)) | ||
| 11 | struct 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 | |||
| 3 | 3 | ||
| 4 | struct RoundTests { | 4 | struct RoundTests { |
| 5 | let days = Category.days.quizItems | 5 | 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)?" } } |
| 7 | 7 | ||
| 8 | @Test func choicesIncludeAnswerAndAreDistinct() { | 8 | @Test func choicesIncludeAnswerAndAreDistinct() { |
| 9 | var rng = SeededGenerator(seed: 1) | 9 | var rng = SeededGenerator(seed: 1) |
| 10 | for _ in 0..<50 { | 10 | 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) |
| 12 | #expect(q.choices.count == 4) | 12 | #expect(q.choices.count == 4) |
| 13 | #expect(q.choices.contains(q.answer)) | 13 | #expect(q.choices.contains(q.answer)) |
| 14 | #expect(Set(q.choices).count == 4) | 14 | #expect(Set(q.choices).count == 4) |
| @@ -17,27 +17,27 @@ struct RoundTests { | |||
| 17 | 17 | ||
| 18 | @Test func choiceCountClampsToItemCount() { | 18 | @Test func choiceCountClampsToItemCount() { |
| 19 | var rng = SeededGenerator(seed: 2) | 19 | var rng = SeededGenerator(seed: 2) |
| 20 | let wide = QuestionPicker(choiceCount: 6) { $0.name } | 20 | let small = QuestionPicker(answers: Array(Category.seasons.quizItems.prefix(2))) { $0.name } |
| 21 | let q = wide.next(from: Category.seasons.quizItems, excluding: nil, using: &rng) | 21 | let q = small.next(correctCount: 4, excluding: nil, using: &rng) |
| 22 | #expect(q.choices.count == 4) | 22 | #expect(q.choices.count == 2) |
| 23 | } | 23 | } |
| 24 | 24 | ||
| 25 | @Test func neverRepeatsPreviousAnswer() { | 25 | @Test func neverRepeatsPreviousAnswer() { |
| 26 | var rng = SeededGenerator(seed: 3) | 26 | var rng = SeededGenerator(seed: 3) |
| 27 | let previous = days[0] | 27 | let previous = days[0] |
| 28 | for _ in 0..<200 { | 28 | 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) |
| 30 | } | 30 | } |
| 31 | } | 31 | } |
| 32 | 32 | ||
| 33 | @Test func promptUsesClosure() { | 33 | @Test func promptUsesClosure() { |
| 34 | var rng = SeededGenerator(seed: 4) | 34 | 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) |
| 36 | #expect(q.prompt == "Can you find \(q.answer.name)?") | 36 | #expect(q.prompt == "Can you find \(q.answer.name)?") |
| 37 | } | 37 | } |
| 38 | 38 | ||
| 39 | @Test func wrongAnswerRetriesSameQuestion() { | 39 | @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)) |
| 41 | let question = round.current | 41 | let question = round.current |
| 42 | let wrong = question.choices.first { $0 != question.answer }! | 42 | let wrong = question.choices.first { $0 != question.answer }! |
| 43 | #expect(round.answer(wrong) == .incorrect(correctName: question.answer.name)) | 43 | #expect(round.answer(wrong) == .incorrect(correctName: question.answer.name)) |
| @@ -47,7 +47,7 @@ struct RoundTests { | |||
| 47 | } | 47 | } |
| 48 | 48 | ||
| 49 | @Test func tapsWhileAwaitingNextAreIgnored() { | 49 | @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)) |
| 51 | let answer = round.current.answer | 51 | let answer = round.current.answer |
| 52 | #expect(round.answer(answer) == .correct) | 52 | #expect(round.answer(answer) == .correct) |
| 53 | #expect(round.isAwaitingNext) | 53 | #expect(round.isAwaitingNext) |
| @@ -57,7 +57,7 @@ struct RoundTests { | |||
| 57 | } | 57 | } |
| 58 | 58 | ||
| 59 | @Test func finishesAfterFiveCorrect() { | 59 | @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)) |
| 61 | for _ in 0..<Round.length { | 61 | for _ in 0..<Round.length { |
| 62 | #expect(!round.isFinished) | 62 | #expect(!round.isFinished) |
| 63 | _ = round.answer(round.current.answer) | 63 | _ = round.answer(round.current.answer) |
| @@ -68,7 +68,7 @@ struct RoundTests { | |||
| 68 | } | 68 | } |
| 69 | 69 | ||
| 70 | @Test func tapsDuringCorrectionAreIgnored() { | 70 | @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)) |
| 72 | let question = round.current | 72 | let question = round.current |
| 73 | let wrong = question.choices.filter { $0 != question.answer } | 73 | let wrong = question.choices.filter { $0 != question.answer } |
| 74 | #expect(round.answer(wrong[0]) == .incorrect(correctName: question.answer.name)) | 74 | #expect(round.answer(wrong[0]) == .incorrect(correctName: question.answer.name)) |
| @@ -79,7 +79,7 @@ struct RoundTests { | |||
| 79 | } | 79 | } |
| 80 | 80 | ||
| 81 | @Test func finalAnswerCelebratesBeforeCompleting() { | 81 | @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)) |
| 83 | for _ in 0..<(Round.length - 1) { | 83 | for _ in 0..<(Round.length - 1) { |
| 84 | _ = round.answer(round.current.answer) | 84 | _ = round.answer(round.current.answer) |
| 85 | round.advance() | 85 | round.advance() |
| @@ -90,4 +90,101 @@ struct RoundTests { | |||
| 90 | round.advance() | 90 | round.advance() |
| 91 | #expect(round.isComplete) | 91 | #expect(round.isComplete) |
| 92 | } | 92 | } |
| 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 | } | ||
| 93 | } | 190 | } |
DayByDayTests/SoundSynthTests.swift +71 −1
| @@ -21,7 +21,6 @@ struct SoundSynthTests { | |||
| 21 | } | 21 | } |
| 22 | 22 | ||
| 23 | @Test func durations() { | 23 | @Test func durations() { |
| 24 | #expect(seconds(SoundSynth.render(.tap)) < 0.08) | ||
| 25 | #expect((0.3...0.6).contains(seconds(SoundSynth.render(.success)))) | 24 | #expect((0.3...0.6).contains(seconds(SoundSynth.render(.success)))) |
| 26 | #expect((0.25...0.5).contains(seconds(SoundSynth.render(.gentleMiss)))) | 25 | #expect((0.25...0.5).contains(seconds(SoundSynth.render(.gentleMiss)))) |
| 27 | #expect((0.9...1.6).contains(seconds(SoundSynth.render(.roundComplete)))) | 26 | #expect((0.9...1.6).contains(seconds(SoundSynth.render(.roundComplete)))) |
| @@ -30,4 +29,75 @@ struct SoundSynthTests { | |||
| 30 | @Test func missIsQuieterThanSuccess() { | 29 | @Test func missIsQuieterThanSuccess() { |
| 31 | #expect(rms(SoundSynth.render(.gentleMiss)) < rms(SoundSynth.render(.success))) | 30 | #expect(rms(SoundSynth.render(.gentleMiss)) < rms(SoundSynth.render(.success))) |
| 32 | } | 31 | } |
| 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 | } | ||
| 33 | } | 103 | } |
FoodCard.swift +8 −1
| @@ -46,7 +46,7 @@ struct FoodCard: View { | |||
| 46 | 46 | ||
| 47 | // MARK: - Food model | 47 | // MARK: - Food model |
| 48 | 48 | ||
| 49 | enum LearnFood: Int, CaseIterable, Identifiable { | 49 | nonisolated enum LearnFood: Int, CaseIterable, Identifiable { |
| 50 | case apple, banana, carrot, strawberry, grapes, lemon, | 50 | case apple, banana, carrot, strawberry, grapes, lemon, |
| 51 | broccoli, watermelon, cherry, orange, corn, pear | 51 | broccoli, watermelon, cherry, orange, corn, pear |
| 52 | 52 | ||
| @@ -69,6 +69,13 @@ enum LearnFood: Int, CaseIterable, Identifiable { | |||
| 69 | } | 69 | } |
| 70 | } | 70 | } |
| 71 | 71 | ||
| 72 | var isFruit: Bool { | ||
| 73 | switch self { | ||
| 74 | case .carrot, .broccoli, .corn: false | ||
| 75 | default: true | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 72 | var emoji: String { | 79 | var emoji: String { |
| 73 | switch self { | 80 | switch self { |
| 74 | case .apple: "🍎" | 81 | case .apple: "🍎" |
LetterCard.swift +9 −1
| @@ -39,7 +39,7 @@ struct LetterCard: View { | |||
| 39 | 39 | ||
| 40 | // MARK: - Letter model | 40 | // MARK: - Letter model |
| 41 | 41 | ||
| 42 | enum LearnLetter: Int, CaseIterable, Identifiable { | 42 | nonisolated enum LearnLetter: Int, CaseIterable, Identifiable { |
| 43 | case a, b, c, d, e, f, g, h, i, j, k, l, m, | 43 | case a, b, c, d, e, f, g, h, i, j, k, l, m, |
| 44 | n, o, p, q, r, s, t, u, v, w, x, y, z | 44 | n, o, p, q, r, s, t, u, v, w, x, y, z |
| 45 | 45 | ||
| @@ -55,6 +55,14 @@ enum LearnLetter: Int, CaseIterable, Identifiable { | |||
| 55 | character.lowercased() | 55 | character.lowercased() |
| 56 | } | 56 | } |
| 57 | 57 | ||
| 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 | |||
| 58 | /// Cycle through 8 bright colors to give variety without unique-per-letter mapping. | 66 | /// Cycle through 8 bright colors to give variety without unique-per-letter mapping. |
| 59 | var color: Color { | 67 | var color: Color { |
| 60 | let palette: [Color] = [ | 68 | let palette: [Color] = [ |
NumberCard.swift +1 −1
| @@ -63,7 +63,7 @@ struct NumberCard: View { | |||
| 63 | 63 | ||
| 64 | // MARK: - Number model | 64 | // MARK: - Number model |
| 65 | 65 | ||
| 66 | enum LearnNumber: Int, CaseIterable, Identifiable { | 66 | nonisolated enum LearnNumber: Int, CaseIterable, Identifiable { |
| 67 | case one = 1, two, three, four, five, six, seven, eight, nine, ten | 67 | case one = 1, two, three, four, five, six, seven, eight, nine, ten |
| 68 | 68 | ||
| 69 | var id: LearnNumber { self } | 69 | var id: LearnNumber { self } |
ShapeCard.swift +11 −2
| @@ -45,7 +45,7 @@ struct ShapeCard: View { | |||
| 45 | 45 | ||
| 46 | // MARK: - Shape model | 46 | // MARK: - Shape model |
| 47 | 47 | ||
| 48 | enum LearnShape: Int, CaseIterable, Identifiable { | 48 | nonisolated enum LearnShape: Int, CaseIterable, Identifiable { |
| 49 | case circle, square, triangle, star, heart, oval, diamond, rectangle | 49 | case circle, square, triangle, star, heart, oval, diamond, rectangle |
| 50 | 50 | ||
| 51 | var id: Int { rawValue } | 51 | var id: Int { rawValue } |
| @@ -63,7 +63,16 @@ enum LearnShape: Int, CaseIterable, Identifiable { | |||
| 63 | } | 63 | } |
| 64 | } | 64 | } |
| 65 | 65 | ||
| 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 | ||
| 67 | var shapeView: some View { | 76 | var shapeView: some View { |
| 68 | switch self { | 77 | switch self { |
| 69 | case .circle: | 78 | case .circle: |
WeatherCard.swift +1 −1
| @@ -46,7 +46,7 @@ struct WeatherCard: View { | |||
| 46 | 46 | ||
| 47 | // MARK: - Weather model | 47 | // MARK: - Weather model |
| 48 | 48 | ||
| 49 | enum LearnWeather: Int, CaseIterable, Identifiable { | 49 | nonisolated enum LearnWeather: Int, CaseIterable, Identifiable { |
| 50 | case sunny, cloudy, rainy, snowy, windy, stormy, foggy, rainbow | 50 | case sunny, cloudy, rainy, snowy, windy, stormy, foggy, rainbow |
| 51 | 51 | ||
| 52 | var id: Int { rawValue } | 52 | 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 | |||
| 28 | 1. 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). | ||
| 29 | 2. 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. | ||
| 30 | 3. 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. | ||
| 31 | 4. 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. | ||
| 32 | 5. 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 | ||
| 42 | gitbay issue create --title "Part 2: question games (find it, odd one out, listen and pick)" --file - <<'EOF' | ||
| 43 | Implements part 2 of docs/superpowers/specs/2026-10-16-learning-games-design.md. | ||
| 44 | Plan: docs/superpowers/plans/2026-10-16-part2-question-games.md | ||
| 45 | EOF | ||
| 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. | ||