SPB Git

Repository Public License

ArcadeServices.swift 5.9 KB 151 lines swift

1// ORIX Arcade2// File: ArcadeCore/ArcadeServices.swift3// Description: Composition root shared by the lobby and the games — save store, audio, haptics, session recording, achievements and toasts.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import Observation910struct ArcadeToast: Identifiable, Equatable {11    let id = UUID()12    let title: String13    let detail: String14    let symbol: String15    let tintHex: UInt3216}1718@Observable19final class ArcadeServices {20    let store: SaveStore21    @ObservationIgnored let audio: AudioDirector22    @ObservationIgnored let haptics: HapticsDirector23    private(set) var toasts: [ArcadeToast] = []24    @ObservationIgnored private var pendingToasts: [ArcadeToast] = []25    @ObservationIgnored private var toastTask: Task<Void, Never>?2627    var settings: ArcadeSettings { store.data.settings }28    var save: SaveData { store.data }2930    init(store: SaveStore, audio: AudioDirector, haptics: HapticsDirector) {31        self.store = store32        self.audio = audio33        self.haptics = haptics34        applySettings()35    }3637    /// Standard app wiring. Tests build their own instance with a temporary store and muted audio.38    static func live() -> ArcadeServices {39        ArcadeServices(store: SaveStore(name: LaunchOptions.saveName, reset: LaunchOptions.reset),40                       audio: AudioDirector(enabled: !LaunchOptions.mute),41                       haptics: HapticsDirector())42    }4344    static func preview(directory: URL) -> ArcadeServices {45        ArcadeServices(store: SaveStore(name: "test", directory: directory, reset: true),46                       audio: AudioDirector(enabled: false),47                       haptics: HapticsDirector(enabled: false))48    }4950    // MARK: Settings5152    func updateSettings(_ mutate: (inout ArcadeSettings) -> Void) {53        store.update { mutate(&$0.settings) }54        applySettings()55    }5657    private func applySettings() {58        let s = store.data.settings59        audio.apply(musicOn: s.musicOn, sfxOn: s.sfxOn, musicVolume: Float(s.musicVolume), sfxVolume: Float(s.sfxVolume))60        haptics.enabled = s.hapticsOn61        OrixAppearance.highContrast = s.highContrast62        OrixAppearance.reduceMotionOverride = s.reduceMotion63    }6465    func feedbackTap() {66        audio.play(.tap)67        haptics.play(.tap)68    }6970    // MARK: Sessions and achievements7172    /// Records a finished session: play time, counters, recent list, and the general achievements.73    func recordSession(game: GameID, score: Int, duration: TimeInterval, headline: String, isRecord: Bool) {74        store.update { data in75            data.stats.playTime[game.rawValue, default: 0] += max(0, duration)76            data.stats.sessionCount[game.rawValue, default: 0] += 177            data.stats.recent.insert(SessionRecord(game: game, date: Date(), score: score, duration: duration, headline: headline, isRecord: isRecord), at: 0)78            if data.stats.recent.count > ArcadeStats.recentLimit { data.stats.recent.removeLast(data.stats.recent.count - ArcadeStats.recentLimit) }79        }80        let stats = store.data.stats81        unlock("arcade.first")82        if GameID.allCases.allSatisfy({ stats.sessionCount[$0.rawValue, default: 0] > 0 }) { unlock("arcade.trio") }83        if stats.totalSessions >= 25 { unlock("arcade.regular") }84        if stats.totalPlayTime >= 30 * 60 { unlock("arcade.marathon") }85        if isRecord { unlock("arcade.record") }86        store.flush()87    }8889    /// Adds play time without counting a session (e.g. a run abandoned from the pause menu).90    func addPlayTime(game: GameID, duration: TimeInterval) {91        guard duration > 1 else { return }92        store.update { $0.stats.playTime[game.rawValue, default: 0] += duration }93    }9495    func isUnlocked(_ id: String) -> Bool { store.data.achievements[id] != nil }9697    /// Unlocks an achievement once and shows a toast. Unknown identifiers are ignored.98    @discardableResult99    func unlock(_ id: String) -> Bool {100        guard store.data.achievements[id] == nil, let def = AchievementCatalog.def(id) else { return false }101        store.update { $0.achievements[id] = Date() }102        let theme = def.game.map { GameCatalog.descriptor($0).theme } ?? .orix103        showToast(ArcadeToast(title: def.title, detail: "Achievement unlocked", symbol: def.symbol, tintHex: theme.primaryHex))104        audio.play(.star)105        haptics.play(.success)106        return true107    }108109    /// Toasts are shown one at a time so several unlocks never bury the screen underneath.110    func showToast(_ toast: ArcadeToast) {111        pendingToasts.append(toast)112        guard toastTask == nil else { return }113        toastTask = Task { [weak self] in114            while let self, !self.pendingToasts.isEmpty {115                let next = self.pendingToasts.removeFirst()116                self.toasts = [next]117                try? await Task.sleep(for: .seconds(2.0))118                self.toasts = []119                try? await Task.sleep(for: .milliseconds(250))120            }121            self?.toastTask = nil122        }123    }124125    // MARK: Resume marker126127    func markInterrupted(game: GameID, note: String? = nil) {128        store.update { $0.interrupted = InterruptedSession(game: game, date: Date(), note: note) }129    }130131    func setResumeNote(_ note: String?) {132        guard store.data.interrupted != nil else { return }133        store.update { $0.interrupted?.note = note }134    }135136    func clearInterrupted() {137        guard store.data.interrupted != nil else { return }138        store.update { $0.interrupted = nil }139    }140}141142extension TimeInterval {143    /// "4m 12s", "1h 03m" — for dashboards.144    var playTimeLabel: String {145        let total = Int(self.rounded())146        if total < 60 { return "\(total)s" }147        if total < 3600 { return "\(total / 60)m \(String(format: "%02d", total % 60))s" }148        return "\(total / 3600)h \(String(format: "%02d", (total % 3600) / 60))m"149    }150}151
Files main
Menu

Theme