krz/daybyday

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

docs/superpowers/plans/2026-10-16-part2-question-games.md

main
daybyday/docs/superpowers/plans/2026-10-16-part2-question-games.md rendered · source · history · blame · raw

230 lines · 21011 bytes

12 symbols in this file
  1# Part 2: Question Games Implementation Plan
  2
  3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
  4
  5**Goal:** "Find it!" for all 11 grid topics, odd one out for food, animals and shapes, and listen-and-pick for animals, weather, alphabet and numbers, reached from each topic hub.
  6
  7**Architecture:** `Round` runs any `QuestionSource`: `QuestionPicker` (find it and listen-and-pick, with separate answer and distractor pools and a choice count that grows from 3 to 4 within a round) or `OddOneOut` (two groups, one odd choice). A `Game` enum plus `Category.games` and `Category.questionSource(for:)` hold the per-topic catalog and spoken copy. `RoundView` plays a question's sound cue before the prompt and records the chosen item and game. Choices render through one `ChoiceTile` with flat fills. Animal, weather and beep sounds are synthesized by `SoundSynth` (additive voice with formants, filtered noise) and rendered lazily by `SoundEngine`.
  8
  9**Tech Stack:** SwiftUI, SwiftData, AVFoundation, Swift Testing, Xcode 27.
 10
 11**Spec:** `docs/superpowers/specs/2026-10-16-learning-games-design.md` (part 2). Builds on `docs/superpowers/plans/2026-10-16-part1-foundation.md`.
 12
 13## Global Constraints
 14
 15- Effective deployment target is iOS 17.5. SF Symbols used must exist on iOS 17. There are no cow, pig, sheep or duck symbols; those are drawn with SwiftUI paths.
 16- `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`. Pure logic types are `nonisolated`.
 17- New app files under `DayByDay/`, new test files under `DayByDayTests/`.
 18- No bundled image or audio files. All sound synthesized at runtime; all art in SwiftUI shapes, SF Symbols, or the emoji the food cards already use.
 19- Nothing requires reading. Every prompt is spoken; every choice is a picture, color, numeral or letter shape. Days, months and seasons tiles show their symbol and name, as the existing cards do.
 20- Wrong answers: `.gentleMiss` plus spoken correction. No buzzer, no red X.
 21- Round length stays 5 correct answers. Choices: 3 for the first two questions, 4 after that.
 22- Choice tiles do not reuse `DayCard`, `MonthCard`, `SeasonCard` or any other `*Card`; they use flat fills with content at 3:1 or better, covered in `ContrastTests`.
 23- Branch `feat/question-games` from `main`. Every commit `Ref #N` (the last `Closes #N`). No AI attribution anywhere.
 24- Test command: `xcodebuild test -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 18 Pro'` (add `-only-testing:DayByDayTests/<Suite>` per task).
 25
 26## Review Focus
 27
 281. Odd one out never has two valid answers: exactly one choice is outside the majority group, for every category and choice count. Test in Task 4 (`oddOneOutHasExactlyOneOddChoice`, 300 draws per category).
 292. A topic whose answer pool is smaller than the choice count (weather listen has 3 answers; seasons has 4 items) still yields distinct choices and never repeats the previous answer. Tests in Task 3 and Task 4.
 303. Tapping "Hear it again" while a sound cue is still playing does not stack the sound or clip; the prompt follows the cue rather than overlapping it. `SoundEngine` skips a repeat of a playing effect (part 1); the replay schedules speech after the cue's duration. Checked by hand in Task 6.
 314. Answer history from part 1 keeps loading after `AnswerRecord` gains fields (lightweight migration of optional properties). Checked in Task 5 by launching the part 1 build, answering a question, then installing this build over it.
 325. Renaming an item enum case orphans recorded history. Pin every item ID in a test (Task 1).
 33
 34---
 35
 36### Task 0: Branch and issue
 37
 38- [ ] **Step 1:** `git checkout -b feat/question-games main`
 39- [ ] **Step 2:** Create the issue, note its number as `N` (it is #2):
 40
 41```bash
 42gitbay issue create --title "Part 2: question games (find it, odd one out, listen and pick)" --file - <<'EOF'
 43Implements part 2 of docs/superpowers/specs/2026-10-16-learning-games-design.md.
 44Plan: docs/superpowers/plans/2026-10-16-part2-question-games.md
 45EOF
 46```
 47
 48- [ ] **Step 3:** `git add docs && git commit -m "docs: part 2 plan" -m "Ref #N"`
 49
 50### Task 1: Item sets, attributes, drawn animals
 51
 52**Files:**
 53- Modify: `AnimalCard.swift` (enum and card icon), `FoodCard.swift`, `ShapeCard.swift`, `LetterCard.swift` (attributes only)
 54- Modify: `DayByDay/Quiz/QuizItem.swift`
 55- Create: `DayByDay/Quiz/AnimalIcon.swift`
 56- Test: `DayByDayTests/QuizItemTests.swift`
 57
 58**Interfaces:**
 59- Produces:
 60  - `LearnAnimal` cases in this order: `cat, dog, bird, fish, rabbit, turtle, ladybug, cow, duck, sheep, pig` (ant and lizard removed). New names "Cow", "Duck", "Sheep", "Pig"; colors cow `(0.35, 0.38, 0.45)`, duck `(0.95, 0.75, 0.2)`, sheep `(0.55, 0.6, 0.7)`, pig `(0.95, 0.5, 0.65)`. `var symbol: String?` (nil for the four drawn animals). `var canFly: Bool` (bird, duck, ladybug).
 61  - `LearnFood.isFruit: Bool` (false for carrot, broccoli, corn).
 62  - `LearnShape.hasCorners: Bool?` (false for circle and oval, nil for heart, true otherwise).
 63  - `LearnLetter.exampleWord: String`: apple, ball, cat, dog, egg, fish, goat, hat, igloo, jam, kite, lion, moon, nest, octopus, pig, queen, rain, sun, tiger, umbrella, van, web, fox, yo-yo, zebra.
 64  - `struct AnimalIcon: View { init(animal: LearnAnimal) }`: the SF Symbol, or a white silhouette drawn in a `Canvas` filled with `.foreground` with details cut out (`blendMode = .destinationOut`), so it takes `foregroundStyle` like a symbol. Pig: front face, triangle ears, snout with nostrils. Cow: front face with horns, side ears, wide muzzle with nostrils, one spot. Sheep: side view, cloud body of overlapping circles, four legs, head. Duck: side view, body with raised tail, round head, beak, wing line. `AnimalCard` uses it.
 65  - `extension Category { func item(_ value: some CaseIterable) -> QuizItem }` (looks up by `"\(key).\(value)"`) and `extension QuizItem { func value<T: CaseIterable>(_: T.Type) -> T? }`.
 66
 67- [ ] **Step 1:** Write failing tests:
 68
 69```swift
 70@Test(arguments: Category.gridCases) func idsArePinned(_ c: Category)
 71// expected case names per category, space-separated, e.g.
 72// .animals: "cat dog bird fish rabbit turtle ladybug cow duck sheep pig"
 73// #expect(c.quizItems.map(\.id) == names.split(separator: " ").map { "\(c.key).\($0)" })
 74@Test func itemAndValueRoundTrip()   // Category.animals.item(LearnAnimal.cow).value(LearnAnimal.self) == .cow; .name == "Cow"
 75@Test func flyers()                  // LearnAnimal.allCases.filter(\.canFly) == [.bird, .ladybug, .duck]
 76@Test func vegetables()              // LearnFood.allCases.filter { !$0.isFruit } == [.carrot, .broccoli, .corn]
 77@Test func roundShapes()             // filter { $0.hasCorners == false } == [.circle, .oval]; LearnShape.heart.hasCorners == nil
 78@Test func exampleWordsStartWithTheirLetter() // every letter except x: exampleWord.first == character.lowercased().first
 79```
 80
 81- [ ] **Step 2:** Run `-only-testing:DayByDayTests/QuizItemTests`. Expected: build fails.
 82- [ ] **Step 3:** Implement. Draw each animal in a 100×100 unit space scaled to the canvas; keep holes at least 6 units wide so they read at 64 pt.
 83- [ ] **Step 4:** Run. Expected: PASS.
 84- [ ] **Step 5:** Commit `feat: revise animal set and add item attributes` with `Ref #N`.
 85
 86### Task 2: Synthesized cue sounds
 87
 88**Files:**
 89- Modify: `DayByDay/Sound/SoundSynth.swift`, `DayByDay/Sound/SoundEngine.swift`
 90- Test: `DayByDayTests/SoundSynthTests.swift`
 91
 92**Interfaces:**
 93- Produces:
 94  - `nonisolated enum SoundEffect: Hashable, CaseIterable { case success, gentleMiss, roundComplete, moo, quack, baa, oink, meow, woof, tweet, rain, wind, thunder, beeps(Int) }` with `allCases` listing `beeps(1)...beeps(5)`. `.tap` is removed (unused).
 95  - `SoundSynth.render(_:) -> [Float]` for every case; `SoundSynth.duration(_:) -> Double`.
 96  - `SoundEngine.play(_:)` renders and attaches a player on first use of an effect (no startup render of everything). `SoundEngine.duration(_:) -> TimeInterval`.
 97- Approach: animals are an additive voice: a time-varying f0, harmonics up to 8 kHz weighted by `1/√n` and by Gaussian formant peaks interpolated between vowel targets over time, optional vibrato and tremolo, optional seeded noise. Weather is seeded noise through one- and two-pole filters (rain: high-passed hiss plus soft windowed droplets; wind: band-pass with a slowly moving center and a swell; thunder: low-passed brown noise with a soft 80 ms attack and two rolling swells, DC-blocked). Beeps: `n` notes at 660 Hz, 0.12 s each, 0.42 s apart. Animal targets: moo f0 110→140→100 Hz, 1.2 s, "oo-ah-oo"; meow 450→700→450 Hz, 0.7 s, "ee-ah-oo"; baa ~330 Hz, 7 Hz vibrato and tremolo, 0.8 s; quack two 0.18 s nasal bursts ~220→180 Hz; oink two 0.2 s grunts 140→110 Hz with 30 Hz roughness; woof two 0.18 s barks 300→180 Hz; tweet three 0.09 s sine sweeps 2.5→4.2 kHz then a short warble.
 98  - `roundComplete`: give the arpeggio notes a gain so its peak is at least half the chord's.
 99
100- [ ] **Step 1:** Write failing tests (existing `noClipping`, `noClicks`, `notSilent` now run over the new cases too):
101
102```swift
103@Test(arguments: SoundEffect.allCases) func noDCOffset(_ e)       // abs(mean) < 0.01
104@Test func cueDurations()   // animals 0.35...1.6 s; rain, wind, thunder 1.5...2.6 s; beeps(n) == 0.42*(n-1)+0.12 ± 0.02
105@Test(arguments: 1...5) func beepCountMatches(_ n: Int)   // onsets: count of 10 ms windows whose rms rises above 0.1 after being below 0.02 == n
106@Test func brightAndDarkCues()  // zeroCrossingRate(.tweet) > 5 * zeroCrossingRate(.moo); zeroCrossingRate(.thunder) < zeroCrossingRate(.rain) / 5
107@Test func arpeggioNotDrownedByChord() // roundComplete: peak of first 0.38 s >= 0.5 * peak of the rest
108@Test func thunderIsGentle()    // no sample in the first 50 ms above 0.2; peak <= 0.6
109```
110
111- [ ] **Step 2:** Run `-only-testing:DayByDayTests/SoundSynthTests`. Expected: build fails.
112- [ ] **Step 3:** Implement `SoundSynth` and lazy `SoundEngine`.
113- [ ] **Step 4:** Run. Expected: PASS.
114- [ ] **Step 5:** Commit `feat: synthesize animal, weather and beep cues` with `Ref #N`.
115
116### Task 3: Question sources
117
118**Files:**
119- Modify: `DayByDay/Quiz/Question.swift`, `DayByDay/Quiz/Round.swift`
120- Test: `DayByDayTests/RoundTests.swift`
121
122**Interfaces:**
123- Consumes: `QuizItem`, `SoundEffect`.
124- Produces:
125  - `nonisolated struct Question: Equatable { let prompt: String; let choices: [QuizItem]; let answer: QuizItem; var sound: SoundEffect? = nil; var facts: [QuizItem: String] = [:]; func correction(for tapped: QuizItem) -> String }`. `correction` returns `"\(facts[tapped]!) Try again!"` when a fact exists, else `PraisePhrases.correction(for: answer.name)`.
126  - `nonisolated protocol QuestionSource { func next(correctCount: Int, excluding previous: QuizItem?, using rng: inout some RandomNumberGenerator) -> Question }`
127  - `QuestionPicker: QuestionSource { init(answers: [QuizItem], distractors: [QuizItem]? = nil, prompt: @escaping (QuizItem) -> String, sound: @escaping (QuizItem) -> SoundEffect? = { _ in nil }) }`. Answer from `answers`, never `previous` when another exists; distractors from `distractors ?? answers` minus the answer; count `min(Round.choiceCount(correctCount:), pool size)`. `precondition(!answers.isEmpty)`.
128  - `OddOneOut: QuestionSource { struct Group { let members: [QuizItem]; let fact: (QuizItem) -> String }; init(_ a: Group, _ b: Group) }`. Prompt `"Which one is different?"`. Picks an orientation (majority, odd) at random among those where the majority has at least `k - 1` members, lowering `k` to 3 if neither fits; odd answer never `previous` when possible; `facts` holds each choice's group fact.
129  - `Round`: `init(source: any QuestionSource, rng: some RandomNumberGenerator = SystemRandomNumberGenerator())`; `static func choiceCount(correctCount: Int) -> Int` (3 below 2, else 4). The `items:picker:` initializer goes away.
130
131- [ ] **Step 1:** Update `RoundTests` to build rounds from `QuestionPicker(answers: days) { "Can you find \($0.name)?" }` and add:
132
133```swift
134@Test func choicesGrowWithinRound()        // counts over 5 correct answers: [3, 3, 4, 4, 4]
135@Test func distractorsComeFromTheirPool()  // answers = first 3 days, distractors = all days → answer ∈ first 3, choices ⊂ days, 300 draws
136@Test func smallAnswerPoolStillVaries()    // answers of 2 items, 100 draws with previous → answer != previous
137@Test func soundComesFromClosure()          // sound: { _ in .moo } → question.sound == .moo
138@Test func correctionUsesFactWhenPresent()  // facts [apple: "Apple is a fruit."] → correction(for: apple) == "Apple is a fruit. Try again!"; for another item → "That's \(answer.name)! Try again."
139@Test func oddOneOutShape()                 // fruits vs vegetables: 300 draws × correctCount 0 and 4 → exactly one choice from the answer's group, the rest from the other; facts.count == choices.count
140@Test func oddOneOutFallsBackToThree()      // groups of 2 and 2 at correctCount 4 → 3 choices
141```
142
143- [ ] **Step 2:** Run `-only-testing:DayByDayTests/RoundTests`. Expected: build fails.
144- [ ] **Step 3:** Implement.
145- [ ] **Step 4:** Run. Expected: PASS.
146- [ ] **Step 5:** Commit `feat: add question sources with growing choices and odd one out` with `Ref #N`.
147
148### Task 4: Game catalog
149
150**Files:**
151- Create: `DayByDay/Quiz/Game.swift`
152- Test: `DayByDayTests/GameTests.swift`
153
154**Interfaces:**
155- Consumes: Task 1 attributes, `QuestionPicker`, `OddOneOut`, `SoundEffect`.
156- Produces:
157  - `nonisolated enum Game: String, CaseIterable { case findIt, oddOneOut, listen; var title: String; var symbol: String }`. Titles "Find it!", "Odd one out", "Listen"; symbols `magnifyingglass`, `square.grid.2x2.fill`, `ear.fill`.
158  - `extension Category { var games: [Game]; func questionSource(for game: Game) -> any QuestionSource }`.
159  - Find it, all grid topics. Prompt `"Can you find \(x)?"` where x is `"the letter \(name)"` (alphabet), `"the number \(name)"` (numbers), `"the \(name)"` (animals, food, shapes, body), else `name`.
160  - Odd one out: food (fruit / vegetable, facts "\(name) is a fruit." / "\(name) is a vegetable."), animals (can fly / can't fly, "\(name) can fly." / "\(name) can't fly."), shapes without heart (round / corners, "\(name) is round." / "\(name) has corners.").
161  - Listen: animals with a sound (cat meow, dog woof, bird tweet, cow moo, duck quack, sheep baa, pig oink) as both pools, prompt "Who says this?"; weather answers rainy (rain), windy (wind), stormy (thunder), distractors all weather, prompt "What weather sounds like this?"; numbers one through five, sound `.beeps(n)`, prompt "How many beeps?"; alphabet without k, q, x, no sound, prompt `"Which letter does \(exampleWord) start with?"`.
162
163- [ ] **Step 1:** Write failing tests:
164
165```swift
166@Test func catalog()  // every grid topic has .findIt first; oddOneOut exactly for [.animals, .shapes, .food]; listen exactly for [.numbers, .animals, .alphabet, .weather]
167@Test(arguments: Category.gridCases) func everyGameMakesValidQuestions(_ c: Category)
168// for each game, 300 draws at correctCount 0...4: choices distinct, contain answer, count in 3...4 (or the pool size if smaller), prompt not empty
169@Test(arguments: [Category.animals, .shapes, .food]) func oddOneOutHasExactlyOneOddChoice(_ c: Category)
170// using the category's attribute: exactly one choice disagrees with the others
171@Test func listenCues()  // animals: every answer has a sound; weather: answers ⊂ {rainy, windy, stormy}; numbers: sound == .beeps(numeral); alphabet: no k/q/x, prompt contains exampleWord, sound nil
172@Test func findItPromptCopy() // "Can you find the letter b?", "Can you find the number Three?", "Can you find the Cow?", "Can you find Tuesday?"
173```
174
175- [ ] **Step 2:** Run `-only-testing:DayByDayTests/GameTests`. Expected: build fails.
176- [ ] **Step 3:** Implement.
177- [ ] **Step 4:** Run. Expected: PASS.
178- [ ] **Step 5:** Commit `feat: add game catalog per topic` with `Ref #N`.
179
180### Task 5: Answer log fields
181
182**Files:**
183- Modify: `DayByDay/Profiles/AnswerRecord.swift`, `DayByDay/Profiles/ProfileStore.swift`
184- Test: `DayByDayTests/ProfileStoreTests.swift`
185
186**Interfaces:**
187- Produces: `AnswerRecord.chosenID: String?`, `AnswerRecord.gameRaw: String?` (both default nil, so existing stores migrate). `ProfileStore.record(_ item: QuizItem, chosen: QuizItem? = nil, game: Game? = nil, correct: Bool, for: Profile, at: Date = .now)`.
188
189- [ ] **Step 1:** Failing test `recordsChosenItemAndGame`: record answer Tuesday, chosen Monday, game `.findIt`, correct false → stored `chosenID == "days.monday"`, `gameRaw == "findIt"`. Existing call sites without the new arguments still compile.
190- [ ] **Step 2:** Run `-only-testing:DayByDayTests/ProfileStoreTests`. Expected: FAIL.
191- [ ] **Step 3:** Implement.
192- [ ] **Step 4:** Run. Expected: PASS. Then: install the `main` build in the simulator, answer a question, install this branch's build over it, open the app: no crash, profile still there.
193- [ ] **Step 5:** Commit `feat: record chosen item and game per answer` with `Ref #N`.
194
195### Task 6: Choice tiles, round view, hub
196
197**Files:**
198- Create: `DayByDay/Quiz/ChoiceTile.swift`
199- Modify: `DayByDay/Quiz/RoundView.swift`, `DayByDay/Home/CategoryHubView.swift`
200- Test: `DayByDayTests/ContrastTests.swift`
201
202**Interfaces:**
203- Consumes: Tasks 1–5.
204- Produces:
205  - `enum ChoiceStyle { static let foodFill: Color; static let swatchOutline: Color }`. `foodFill` `(0.24, 0.16, 0.10)`; `swatchOutline` `Color(white: 0.45)`.
206  - `struct ChoiceTile: View { init(item: QuizItem) }`: rounded rect, corner 32, flat fill. Colors: the color itself as fill with a 4 pt `swatchOutline` border, no text. Food: emoji at 72 pt on `foodFill`. Every other topic: white content on `category.color`: animals `AnimalIcon`, weather/body symbol, shapes `shapeView`, alphabet the letter at 72 pt heavy rounded, numbers numeral plus solid white `DotPattern`-style dots, days/months/seasons symbol plus name.
207  - `RoundView<Choice>`: `init(source: any QuestionSource, game: Game, @ViewBuilder choice:)`. Prompt: if `current.sound` is set, play it, then speak the prompt `SoundEngine.duration + 0.2` s later; "Hear it again" does the same. Records `round.current.answer` with `chosen: tapped`, `game:`. Correct: `.success` now, praise 0.25 s later, advance after 1.8 s. Incorrect: `.gentleMiss` now, `current.correction(for: tapped)` 0.25 s later. "You did it!" spoken 0.4 s after `.roundComplete`.
208  - `CategoryHubView`: one large button per `category.games` after "Look and listen", same style, destination `RoundView(source: category.questionSource(for: game), game: game) { ChoiceTile(item: $0) }.navigationTitle(game.title)`.
209
210- [ ] **Step 1:** Failing tests in `ContrastTests`: `swatchOutlineAgainstBackgrounds` (vs `.white` and `.black` ≥ 3), `foodFillAgainstWhite` (≥ 3). Run `-only-testing:DayByDayTests/ContrastTests`. Expected: build fails.
211- [ ] **Step 2:** Implement `ChoiceTile`, `RoundView`, hub.
212- [ ] **Step 3:** Run the full suite. Expected: `** TEST SUCCEEDED **`.
213- [ ] **Step 4:** In the simulator: each hub shows its games; play one round each of find it (days, colors, food), odd one out (animals), listen (animals, numbers, alphabet, weather); "Hear it again" during a cue does not stack; a wrong odd-one-out tap speaks the tapped item's fact. iPad landscape layout holds four tiles.
214- [ ] **Step 5:** Commit `feat: play find it, odd one out and listen from topic hubs` with `Ref #N`.
215
216### Task 7: Review exports, reviews, MR, merge
217
218**Files:**
219- Create: `DayByDayTests/ReviewExport.swift`
220
221- [ ] **Step 1:** Add `ReviewExport`, enabled only when `EXPORT_DIR` is set (`TEST_RUNNER_EXPORT_DIR` on the xcodebuild command line): writes every `SoundEffect` as 16-bit WAV and every `ChoiceTile` (all items, light and dark), `AnimalIcon` and hub as PNG via `ImageRenderer` at scale 2.
222- [ ] **Step 2:** Run it into the scratchpad. Dispatch a fresh art/sound reviewer with the PNGs, WAVs and source. Block on clear defects (clipping, clicks, harsh or startling sound, unrecognizable drawing, contrast under 3:1). Fix, rerun, second round at most. Unresolved taste notes go in the MR description.
223- [ ] **Step 3:** Fresh whole-branch code review (`git diff main...`). Fix findings that hold up.
224- [ ] **Step 4:** Full suite. Expected: `** TEST SUCCEEDED **`.
225- [ ] **Step 5:** `git push -u origin feat/question-games`; `gitbay mr create --source feat/question-games --target main --title "Part 2: question games" --file -` with a short body ending `Closes #N`.
226- [ ] **Step 6:** `gitbay mr merge <mr> --strategy squash`; `git checkout main && git pull && git branch -D feat/question-games && git push origin --delete feat/question-games`; confirm `gitbay issue show N` is closed (close it if not).
227
228## Deferred
229
230- `VersionedSchema`: the two new fields are optional, so automatic lightweight migration covers them. Adopt a versioned schema in part 7 before any non-optional change.