DayByDay/Quiz/Round.swift
66 lines · 2188 bytes
4 symbols in this file
1//
2// Round.swift
3// DayByDay
4//
5
6nonisolated enum AnswerOutcome: Equatable {
7 case correct
8 case incorrect(correctName: String)
9 case ignored
10}
11
12/// A fixed-length run of questions. A wrong answer keeps the same question and
13/// waits for `resume()`; a correct one waits for `advance()`. Answers are
14/// ignored while either kind of feedback plays.
15nonisolated struct Round {
16 static let length = 5
17
18 private let source: any QuestionSource
19 private var rng: any RandomNumberGenerator
20 private(set) var current: Question
21 private(set) var correctCount = 0
22 private(set) var isAwaitingNext = false
23 private(set) var isShowingCorrection = false
24
25 var isFinished: Bool { correctCount == Round.length }
26
27 /// True once the last correct answer's feedback is done.
28 var isComplete: Bool { isFinished && !isAwaitingNext }
29
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()) {
39 var rng: any RandomNumberGenerator = rng
40 self.source = source
41 self.current = source.next(correctCount: 0, excluding: previous, using: &rng)
42 self.rng = rng
43 }
44
45 mutating func answer(_ item: QuizItem) -> AnswerOutcome {
46 guard !isAwaitingNext, !isShowingCorrection, !isFinished else { return .ignored }
47 guard item == current.answer else {
48 isShowingCorrection = true
49 return .incorrect(correctName: current.answer.name)
50 }
51 correctCount += 1
52 isAwaitingNext = true
53 return .correct
54 }
55
56 mutating func resume() {
57 isShowingCorrection = false
58 }
59
60 mutating func advance() {
61 guard isAwaitingNext else { return }
62 isAwaitingNext = false
63 guard !isFinished else { return }
64 current = source.next(correctCount: correctCount, excluding: current.answer, using: &rng)
65 }
66}