DayByDay/Mascot/MascotState.swift
54 lines · 1599 bytes
1//
2// MascotState.swift
3// DayByDay
4//
5
6import Foundation
7
8nonisolated enum MascotMood: CaseIterable {
9 case idle, asking, cheering, puzzled, waving
10}
11
12/// Something in a game the mascot reacts to.
13nonisolated enum MascotEvent: Equatable {
14 /// A prompt being said, after an optional sound cue.
15 case prompt(String, after: TimeInterval = 0)
16 case correct
17 case wrong
18 case greet
19}
20
21/// The mascot's mood in a game. Each event sets a mood that holds for a
22/// while, then `settle` puts it back to idle unless a newer event came in.
23nonisolated struct MascotState: Equatable {
24 private(set) var mood: MascotMood = .idle
25 /// Bumped by every event, so a settle for an older one does nothing.
26 private(set) var ticket = 0
27 private(set) var hold: TimeInterval = 0
28
29 mutating func handle(_ event: MascotEvent) {
30 switch event {
31 case .prompt: mood = .asking
32 case .correct: mood = .cheering
33 case .wrong: mood = .puzzled
34 case .greet: mood = .waving
35 }
36 ticket += 1
37 hold = Self.hold(for: event)
38 }
39
40 mutating func settle(_ ticket: Int) {
41 if ticket == self.ticket { mood = .idle }
42 }
43
44 /// How long the event's mood lasts. A prompt lasts through its sound cue
45 /// and roughly as long as it takes to say.
46 static func hold(for event: MascotEvent) -> TimeInterval {
47 switch event {
48 case .prompt(let text, let delay): delay + 0.5 + 0.45 * Double(text.split(separator: " ").count)
49 case .correct: 1.8
50 case .wrong: 1.6
51 case .greet: 2.4
52 }
53 }
54}