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-part3-ordering-games.md

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/docs/superpowers/plans/2026-10-16-part3-ordering-games.md rendered · source · history · blame · raw

219 lines · 19386 bytes

11 symbols in this file
  1# Part 3: Ordering and Quantity Games Implementation Plan
  2
  3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
  4
  5**Goal:** Ordering games for days, months and seasons (week train, yesterday/today/tomorrow, "what comes after", year wheel, "which season") and quantity games for numbers (count with me, which has the most), each reached from its topic hub.
  6
  7**Architecture:** Question-style games reuse `Round`/`RoundView` through new `QuestionSource`s (`ComesNext`, `WhichSeason`, `Most`). Placement games run on a pure `SequencePuzzle` (ordered steps, a card pool, tap or drag to place) drawn by one `SequencePuzzleView` with a train layout and a three-slot layout. The year wheel and counting are their own small models (`YearWheel`, `CountingRound`) with their own views. `Game` gains the new cases; `Game.usesRound` and a `GameDestination` view let the hub open either kind.
  8
  9**Tech Stack:** SwiftUI (`draggable`/`dropDestination` with `String` payloads), SwiftData, AVFoundation, Swift Testing, Xcode 27.
 10
 11**Spec:** `docs/superpowers/specs/2026-10-16-learning-games-design.md` (part 3). Builds on the part 1 and part 2 plans in this folder.
 12
 13## Global Constraints
 14
 15- Effective deployment target is iOS 17.5.
 16- `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`. Pure logic types and extensions are `nonisolated`.
 17- New app files under `DayByDay/`, new tests under `DayByDayTests/`.
 18- No bundled image or audio files. All sound synthesized; all art in SwiftUI shapes and SF Symbols.
 19- Nothing requires reading. Every prompt is spoken; every card shows a symbol plus its name, like the existing day/month/season choice tiles.
 20- Wrong answers: `.gentleMiss` plus a spoken correction. No buzzer, no red X.
 21- Drag is never required: tapping a card places it too. Drop targets are the whole slot area, not a single slot.
 22- Reduce Motion: the year wheel jumps to its result instead of spinning; no other new motion beyond existing celebration.
 23- White content on any new fill is at least 3:1, covered in `ContrastTests`.
 24- Weeks start on Sunday. The season is "Fall". Seasons by month: Mar–May spring, Jun–Aug summer, Sep–Nov fall, Dec–Feb winter (matches `Season.current`).
 25- `Game` raw values are persisted in `AnswerRecord.gameRaw`; never rename existing ones.
 26- No new required SwiftData fields (no `VersionedSchema` yet).
 27- Branch `feat/ordering-games` from `main`. Every commit `Ref #N` (last `Closes #N`). No AI attribution anywhere.
 28- Test command: `xcodebuild test -project DayByDay.xcodeproj -scheme DayByDay -destination 'platform=iOS Simulator,name=iPhone 18 Pro'` (add `-only-testing:DayByDayTests/<Suite>`).
 29
 30## Review Focus
 31
 321. Wrap-around: "What day comes after Saturday?" is Sunday; "after December" is January. Test in Task 1.
 332. Yesterday/tomorrow wrap at the week's ends (today Sunday → yesterday Saturday; today Saturday → tomorrow Sunday), for every weekday. Test in Task 3.
 343. Repeated or late input on placement games: a card already placed, a tap during a correction, or any tap after the puzzle is solved is ignored and records nothing. Test in Task 3.
 354. Year wheel rotation that has accumulated many turns or is negative still maps to the right month, and every spin lands exactly on the chosen month's center. Test in Task 5.
 365. Counting: tapping an already-counted object does not count it twice; taps after the set is done are ignored. Test in Task 6.
 37
 38---
 39
 40### Task 0: Branch and issue
 41
 42- [ ] **Step 1:** `git checkout -b feat/ordering-games main`
 43- [ ] **Step 2:** `gitbay issue create --title "Part 3: ordering and quantity games" --json --file -` with a body naming the spec and this plan. Note the number as `N`.
 44- [ ] **Step 3:** `git add docs && git commit -m "docs: part 3 plan" -m "Ref #N"`
 45
 46### Task 1: Question sources and catalog
 47
 48**Files:**
 49- Create: `DayByDay/Quiz/OrderSources.swift`
 50- Modify: `DayByDay/Quiz/Game.swift`, `DayByDay/Quiz/ChoiceTile.swift` (make `Dots` internal; add `PileTile`)
 51- Test: `DayByDayTests/OrderSourcesTests.swift`, `DayByDayTests/GameTests.swift`
 52
 53**Interfaces:**
 54- Produces:
 55  - `nonisolated extension MonthOfYear { var season: Season }` (same months as `Season.current`).
 56  - `Game` new cases (raw values as written): `comesNext, weekTrain, yesterdayTomorrow, yearWheel, whichSeason, counting, most`. Titles: "What comes next?", "Week train", "Yesterday and tomorrow", "Year wheel", "Which season?", "Count with me", "Which has the most?". Symbols: `arrow.right.circle.fill`, `train.side.front.car`, `calendar.day.timeline.left`, `circle.dashed`, `leaf.fill`, `hand.tap.fill`, `chart.bar.fill`. `var usesRound: Bool` (true for `findIt, oddOneOut, listen, comesNext, whichSeason, most`).
 57  - `Category.games` after this task: days `[findIt, comesNext]`, months `[findIt, comesNext]`, seasons `[findIt, whichSeason]`, numbers `[findIt, listen, most]`; others unchanged. Later tasks append their special games.
 58  - `nonisolated struct ComesNext: QuestionSource { init(items: [QuizItem], noun: String) }`. Picks an asked item, answer is the next item cyclically. Prompt `"What \(noun) comes after \(asked.name)?"`. The asked item is never a choice. Answer never equals `previous` when possible. Correction fact on a wrong tap: `"\(answer.name) comes after \(asked.name)."` (via `Question.facts` on every wrong choice).
 59  - `nonisolated struct WhichSeason: QuestionSource`. Answer is a season; the prompt names a random month of it: `"Which season is \(month.name) in?"`. Choices are 3 or 4 seasons. Fact on a wrong tap: `"\(month.name) is in \(answer.name)."`.
 60  - `nonisolated struct Most: QuestionSource`. Choices are distinct `LearnNumber` items from 1...10, answer is the largest. Prompt `"Which one has the most?"`. Fact on a wrong tap: `"That one has \(n)."`. Answer never equals `previous` when possible.
 61  - `PileTile(item:)`: number-topic fill with dots only (no numeral), dots larger than in `ChoiceTile`.
 62
 63- [ ] **Step 1:** Write failing tests in `OrderSourcesTests`:
 64
 65```swift
 66@Test func monthSeasons()            // Dec, Jan, Feb → winter; Mar → spring; Jun → summer; Sep, Nov → fall
 67@Test func comesNextWraps()          // seeded draws until asked == Saturday: answer == Sunday; asked == December: answer == January
 68@Test func comesNextNeverOffersAskedItem()   // 300 draws: the name between "after " and "?" in the prompt is never a choice's name
 69@Test func whichSeasonPromptMatchesAnswer()  // 300 draws: month named in prompt has .season == answer
 70@Test func mostAnswerIsLargest()     // 300 draws: answer numeral > every other choice's numeral
 71@Test func mostFacts()               // a wrong choice's correction == "That one has 3. Try again!" for numeral 3
 72```
 73
 74Update `GameTests.catalog` to the new `games` lists and limit `everyGameMakesValidQuestions` to `game.usesRound`.
 75
 76- [ ] **Step 2:** Run `-only-testing:DayByDayTests/OrderSourcesTests -only-testing:DayByDayTests/GameTests`. Expected: build fails (types missing).
 77- [ ] **Step 3:** Implement.
 78- [ ] **Step 4:** Run the same command. Expected: PASS.
 79- [ ] **Step 5:** Commit `feat: what-comes-next, which-season and most question sources`.
 80
 81### Task 2: Hub destinations and finished screen
 82
 83**Files:**
 84- Create: `DayByDay/Quiz/GameDestination.swift`, `DayByDay/Quiz/FinishedView.swift`
 85- Modify: `DayByDay/Quiz/RoundView.swift` (use `FinishedView`), `DayByDay/Home/CategoryHubView.swift`
 86
 87**Interfaces:**
 88- Produces:
 89  - `struct FinishedView: View { init(onPlayAgain: @escaping () -> Void) }`: the existing mascot, "You did it!", Play again button; plays `.roundComplete` and says "You did it!" on appear (moved from `RoundView` unchanged).
 90  - `struct GameDestination: View { init(category: Category, game: Game) }`: `RoundView` with `ChoiceTile` for round games, `PileTile` for `.most`; later tasks add the special games to its switch.
 91  - Hub uses `GameDestination` for every entry in `category.games`.
 92
 93- [ ] **Step 1:** Build. Expected: `BUILD SUCCEEDED`.
 94- [ ] **Step 2:** Full suite. Expected: `** TEST SUCCEEDED **`.
 95- [ ] **Step 3:** Commit `feat: hub destinations for ordering games`.
 96
 97### Task 3: Sequence puzzle model
 98
 99**Files:**
100- Create: `DayByDay/Quiz/SequencePuzzle.swift`
101- Test: `DayByDayTests/SequencePuzzleTests.swift`
102
103**Interfaces:**
104- Produces: `nonisolated struct SequencePuzzle`:
105  - `struct Step { let answer: QuizItem; let prompt: String }`
106  - `let steps: [Step]`, `let pool: [QuizItem]` (cards shown, shuffled once), `private(set) var placed: [QuizItem]`, `private(set) var isShowingCorrection`
107  - `var current: Step?` (nil when solved), `var isSolved: Bool`
108  - `mutating func place(_ item: QuizItem) -> AnswerOutcome`: `.ignored` when solved, during a correction, or when `item` is already placed; `.correct` when `item == current.answer` (appends to `placed`); otherwise `.incorrect(correctName:)` and `isShowingCorrection = true`.
109  - `mutating func resume()`
110  - `func correction(for item: QuizItem) -> String` — `"\(current.answer.name) comes next. Try again!"` for the train; slot puzzles pass their own copy (see below).
111  - `static func weekTrain(using rng: inout some RandomNumberGenerator) -> SequencePuzzle`: steps Sunday…Saturday; first prompt "Which day comes first?", then `"What comes after \(previous.name)?"`; pool is all 7 days shuffled. Correction: `"\(answer) comes next."`.
112  - `static func yesterdayTomorrow(today: DayOfWeek, using rng: inout some RandomNumberGenerator) -> SequencePuzzle`: steps yesterday, today, tomorrow with prompts "Which day was yesterday?", "Which day is today?", "Which day will it be tomorrow?"; pool is those three plus one other day, shuffled. Corrections: `"Yesterday was \(x)."`, `"Today is \(x)."`, `"Tomorrow will be \(x)."`.
113  - `let slotLabels: [String]?` — `["Yesterday", "Today", "Tomorrow"]` for that puzzle, nil for the train.
114
115- [ ] **Step 1:** Write failing tests:
116
117```swift
118@Test func trainOrder()                    // steps map to Sunday…Saturday; pool is a permutation of 7 days
119@Test(arguments: DayOfWeek.allCases) func yesterdayTomorrowWraps(_ today: DayOfWeek)  // answers == [today-1, today, today+1] mod 7; pool has 4 distinct days including those 3
120@Test func correctPlacementAdvances()      // place Sunday → .correct, current.prompt == "What comes after Sunday?"
121@Test func wrongPlacementWaits()           // place Tuesday first → .incorrect(correctName: "Sunday"); place Sunday → .ignored until resume()
122@Test func placedCardIgnored()             // place Sunday, then Sunday again → .ignored
123@Test func solvedIgnoresInput()            // place all 7 → isSolved, any place → .ignored
124@Test func corrections()                   // yesterdayTomorrow(today: .friday): wrong on step 0 → "Yesterday was Thursday. Try again!"
125```
126
127- [ ] **Step 2:** Run `-only-testing:DayByDayTests/SequencePuzzleTests`. Expected: FAIL (type missing).
128- [ ] **Step 3:** Implement.
129- [ ] **Step 4:** Run. Expected: PASS.
130- [ ] **Step 5:** Commit `feat: sequence puzzle model`.
131
132### Task 4: Week train and yesterday/tomorrow views, whistle
133
134**Files:**
135- Create: `DayByDay/Quiz/SequencePuzzleView.swift`
136- Modify: `DayByDay/Sound/SoundSynth.swift` (`.whistle`), `DayByDay/Quiz/Game.swift` (days games), `DayByDay/Quiz/GameDestination.swift`
137- Test: `DayByDayTests/SoundSynthTests.swift`, `DayByDayTests/GameTests.swift`
138
139**Interfaces:**
140- Consumes: `SequencePuzzle`, `ChoiceTile`, `FinishedView`, `SoundEngine`, `ProfileStore.record`.
141- Produces:
142  - `SoundEffect.whistle`: two-tone train whistle (sines near 600 and 750 Hz with soft harmonics, slight vibrato), 0.6–1.2 s, peak ≤ 0.6, included in `allCases`.
143  - `struct SequencePuzzleView: View { init(game: Game, make: @escaping () -> SequencePuzzle) }`:
144    - Top: the slots area. Train layout (no `slotLabels`): an engine shape plus 7 cars in a horizontal scroll, filled cars show the placed day tile, the next empty car is outlined. Slot layout: three labeled slots side by side, label text above each, the current slot outlined.
145    - Bottom: the unplaced pool cards as `ChoiceTile`s. Tap places; `.draggable(item.id)` onto the slots area's `.dropDestination(for: String.self)` places too.
146    - Speaks `current.prompt` on appear and after each correct placement; "Hear it again" button as in `RoundView`.
147    - Correct: `.success` + praise; wrong: `.gentleMiss`, dims the card, speaks the correction, `resume()` after 1.2 s. Each placement is recorded with `record(step.answer, chosen:, game:, correct:)`.
148    - Solved: `.whistle` (train) or `.success` (slots), speaks the full order ("Sunday, Monday, …, Saturday!" or "Yesterday was Thursday, today is Friday, tomorrow will be Saturday!"), then `FinishedView`; Play again calls `make()`.
149  - Days games become `[findIt, comesNext, weekTrain, yesterdayTomorrow]`.
150
151- [ ] **Step 1:** Add `cueDurations` range for `.whistle` (0.6...1.2) and update `GameTests.catalog`. Run `-only-testing:DayByDayTests/SoundSynthTests -only-testing:DayByDayTests/GameTests`. Expected: FAIL (`.whistle` missing).
152- [ ] **Step 2:** Implement `.whistle`, the view, catalog and destination.
153- [ ] **Step 3:** Run the same tests (the parameterized clipping/click/DC tests now cover `.whistle`). Expected: PASS.
154- [ ] **Step 4:** Simulator check (rendered-image or screenshot, taking two screenshots per step): both layouts render on iPhone 18 Pro; tapping cards places them; a wrong card dims.
155- [ ] **Step 5:** Commit `feat: week train and yesterday/tomorrow games`.
156
157### Task 5: Year wheel
158
159**Files:**
160- Create: `DayByDay/Quiz/YearWheel.swift` (model), `DayByDay/Quiz/YearWheelView.swift`
161- Modify: `DayByDay/Quiz/Game.swift` (months games), `DayByDay/Quiz/GameDestination.swift`
162- Test: `DayByDayTests/YearWheelTests.swift`, `DayByDayTests/ContrastTests.swift`
163
164**Interfaces:**
165- Produces:
166  - `nonisolated enum YearWheel`: month `i` (January = 0) is drawn centered `i * 30°` clockwise from the top pointer before rotation. `static func month(atRotation degrees: Double) -> MonthOfYear` (month under the pointer after rotating the wheel clockwise by `degrees`; any real value). `static func target(from rotation: Double, landingOn month: MonthOfYear, turns: Int) -> Double` (a rotation greater than `rotation` by at least `turns` full turns whose `month(atRotation:)` is `month`, exactly at its center).
167  - `extension Season { var wheelColor: Color }`: spring `(0.18, 0.56, 0.28)`, summer `(0.84, 0.40, 0.08)`, fall `(0.66, 0.30, 0.10)`, winter `(0.0, 0.42, 0.85)`. All ≥ 3:1 against white.
168  - `YearWheelView`: wheel of 12 wedges in season colors with three-letter month labels in white, a pointer at the top, a large "Spin!" button. Spin picks a random month (never the current one), animates to `target(…, turns: 3)` over about 2.5 s with ease-out (Reduce Motion: no animation), then says `"\(month.name)! \(month.name) is in \(season.name)."`. Tapping a wedge says the same for that month. Spin is ignored while spinning. Nothing is recorded (no right or wrong).
169  - Months games become `[findIt, comesNext, yearWheel]`.
170
171- [ ] **Step 1:** Write failing tests:
172
173```swift
174@Test func monthAtRotation()          // 0 → January; 30 → December (wheel turned clockwise brings December under the pointer); -30 → February; 360*7 + 30 → December; -1085 → mapped consistently with the definition
175@Test(arguments: MonthOfYear.allCases) func targetLandsOnMonth(_ m: MonthOfYear)  // for rotations [0, 47.5, -800, 12345]: t = target(from:landingOn:turns: 3); t >= rotation + 1080; month(atRotation: t) == m; (t mod 30) is a center (multiple of 30)
176@Test(arguments: Season.allCases) func wheelColorAgainstWhite(_ s: Season)   // ContrastTests
177```
178
179- [ ] **Step 2:** Run `-only-testing:DayByDayTests/YearWheelTests -only-testing:DayByDayTests/ContrastTests`. Expected: FAIL.
180- [ ] **Step 3:** Implement the model, colors, view, catalog and destination.
181- [ ] **Step 4:** Run. Expected: PASS. Render check: wedges, labels, pointer readable on iPhone 18 Pro.
182- [ ] **Step 5:** Commit `feat: year wheel`.
183
184### Task 6: Count with me
185
186**Files:**
187- Create: `DayByDay/Quiz/Counting.swift` (model), `DayByDay/Quiz/CountingView.swift`
188- Modify: `DayByDay/Quiz/Game.swift` (numbers games), `DayByDay/Quiz/GameDestination.swift`
189- Test: `DayByDayTests/CountingTests.swift`
190
191**Interfaces:**
192- Produces:
193  - `nonisolated struct CountingRound`: `static let length = 5` sets. `struct Thing { let symbol: String; let singular: String; let plural: String }` with five kinds: star, heart, leaf ("leaf"/"leaves"), moon, fish ("fish"/"fish"), using their `.fill` SF Symbols. `private(set) var target: Int` (1...10, never equal to the previous set's), `private(set) var thing: Thing`, `private(set) var counted: [Int]` (object indices in tap order), `private(set) var setsDone: Int`.
194  - `mutating func tap(_ index: Int) -> Int?`: returns the new count, or nil if `index` is out of range, already counted, or the set is done.
195  - `var isSetDone: Bool`, `mutating func nextSet()`, `var isComplete: Bool` (after 5 sets).
196  - `func summary() -> String`: `"\(n)! There \(n == 1 ? "is" : "are") \(n) \(n == 1 ? singular : plural)."` with `n` spelled as a numeral word from `LearnNumber.name`.
197  - `CountingView`: says "Tap each \(singular) to count." The objects sit in a flexible grid in the numbers topic color. Each tap says the number, shows it on the object (white on the topic color), and plays no sound effect. When the set is done it plays `.success`, shows the numeral large, says `summary()`, then moves to the next set after 2.5 s. After 5 sets it shows `FinishedView`. Nothing is recorded.
198  - Numbers games become `[findIt, listen, counting, most]`.
199
200- [ ] **Step 1:** Write failing tests:
201
202```swift
203@Test func countsEachObjectOnce()      // target 4: tap 0,1,1,2 → 1,2,nil,3
204@Test func ignoresOutOfRangeAndDone()  // tap(target) → nil; after all counted, tap(0) → nil
205@Test func setsNeverRepeatTarget()     // seeded 200 sets: consecutive targets differ, all in 1...10
206@Test func completesAfterFiveSets()
207@Test func summaryCopy()               // n=1 → "One! There is one star."; n=3 → "Three! There are three stars."
208```
209
210- [ ] **Step 2:** Run `-only-testing:DayByDayTests/CountingTests`. Expected: FAIL.
211- [ ] **Step 3:** Implement the model, view, catalog and destination.
212- [ ] **Step 4:** Run. Expected: PASS. Then the full suite. Expected: `** TEST SUCCEEDED **`.
213- [ ] **Step 5:** Commit `feat: count with me`.
214
215### Task 7: Reviews, MR, merge
216
217- [ ] **Step 1:** Export review assets (`TEST_RUNNER_EXPORT_DIR=<scratch> … -only-testing:DayByDayTests/ReviewExport`, adding the whistle and renders of the train, slots, wheel, pile and counting views to `ReviewExport`). Dispatch a fresh art/sound reviewer: block on clear defects (clipping, clicks, harsh or startling sound, unrecognizable drawing, contrast < 3:1); two rounds at most.
218- [ ] **Step 2:** Dispatch a fresh whole-branch code reviewer with this plan, the spec, the ledger rulings and this Review Focus. One fix pass, each fix RED→GREEN.
219- [ ] **Step 3:** Full suite green. Push, `gitbay mr create --source feat/ordering-games --target main --title "Part 3: ordering and quantity games"` with `Closes #N` and the unresolved art notes. Squash-merge, delete the branch locally and remotely.