SPB Git

Repository Public License

DominoSave.swift 9.3 KB 194 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/DominoCity/DominoSave.swift10// Description      : Domino City — persisted progress: stars and best score per11//                    level (the first fifteen entries are the 0.1 levels),12//                    unlock rules, best chain, chosen theme and tutorial flag.13//                    Decodes 0.1 saves unchanged.14// Module           : Games15// Repository       : https://git.spboucher.ai/orix-arcade16// Created          : 2026-11-2117// Last Modified    : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394nonisolated struct DominoSave: Codable, Equatable, Sendable {95    /// Downtown (levels 1–15, shipped in 0.1) followed by Harbor (16–30, added in 2.0).96    static let levelCount = 3097    static let classicCount = 1598    /// Downtown levels to clear before the Harbor district opens.99    static let harborRequirement = 10100    static let maxStars = levelCount * 3101102    /// Best stars per level (index 0 = level 1). Holds the fifteen Downtown entries of a 0.1 save and grows as Harbor levels are played.103    var stars: [Int] = Array(repeating: 0, count: DominoSave.classicCount)104    /// Best score per level, same layout. Scores only ever go up, so a best set under the 0.1 rules is kept.105    var scores: [Int] = Array(repeating: 0, count: DominoSave.classicCount)106    var attempts = 0107    var bestChain = 0108    var tutorialDone = false109    /// Last level opened, so the level list can highlight it.110    var lastLevel = 1111    /// Chosen visual theme (`DominoTheme.id`).112    var theme = DominoTheme.dusk.id113114    init() {}115116    init(from decoder: Decoder) throws {117        let c = try decoder.container(keyedBy: CodingKeys.self)118        stars = Self.fitted(try c.decodeIfPresent([Int].self, forKey: .stars) ?? []).map { $0.clamped(0, 3) }119        scores = Self.fitted(try c.decodeIfPresent([Int].self, forKey: .scores) ?? []).map { max(0, $0) }120        attempts = max(0, try c.decodeIfPresent(Int.self, forKey: .attempts) ?? 0)121        bestChain = max(0, try c.decodeIfPresent(Int.self, forKey: .bestChain) ?? 0)122        tutorialDone = try c.decodeIfPresent(Bool.self, forKey: .tutorialDone) ?? false123        lastLevel = (try c.decodeIfPresent(Int.self, forKey: .lastLevel) ?? 1).clamped(1, Self.levelCount)124        let wanted = DominoTheme.named(try c.decodeIfPresent(String.self, forKey: .theme) ?? DominoTheme.dusk.id)125        theme = wanted.isUnlocked(stars: stars.reduce(0, +)) ? wanted.id : DominoTheme.dusk.id126    }127128    /// At least the fifteen Downtown entries (padded when a file is short), at most the whole catalogue.129    private static func fitted(_ values: [Int]) -> [Int] {130        Array((values + Array(repeating: 0, count: max(0, classicCount - values.count))).prefix(levelCount))131    }132133    var totalStars: Int { stars.reduce(0, +) }134    var clearedCount: Int { stars.filter { $0 > 0 }.count }135    var classicCleared: Int { stars.prefix(Self.classicCount).filter { $0 > 0 }.count }136    var classicStars: Int { stars.prefix(Self.classicCount).reduce(0, +) }137    var harborCleared: Int { stars.dropFirst(Self.classicCount).filter { $0 > 0 }.count }138    var perfectCount: Int { stars.filter { $0 == 3 }.count }139    var hasPlayed: Bool { attempts > 0 }140    var totalScore: Int { scores.reduce(0, +) }141    var harborOpen: Bool { classicCleared >= Self.harborRequirement }142143    /// Every cleared level unlocks the next one; the Harbor district opens once enough of Downtown is cleared.144    func isUnlocked(_ level: Int) -> Bool {145        guard (1...Self.levelCount).contains(level) else { return false }146        if level == 1 { return true }147        if level == Self.classicCount + 1 { return harborOpen }148        return bestStars(level - 1) > 0149    }150151    /// The level to play next: the first one that is open and not yet cleared (the last level once everything is cleared).152    var highestUnlocked: Int {153        (1...Self.levelCount).first { isUnlocked($0) && bestStars($0) == 0 } ?? Self.levelCount154    }155156    func bestStars(_ level: Int) -> Int { stars.indices.contains(level - 1) ? stars[level - 1] : 0 }157    func bestScore(_ level: Int) -> Int { scores.indices.contains(level - 1) ? scores[level - 1] : 0 }158159    struct RecordOutcome: Equatable, Sendable {160        var isNewBestScore: Bool161        var isNewBestStars: Bool162        /// Stars gained over the previous best.163        var starsGained = 0164        var firstClear = false165        var unlockedLevel: Int?166        /// This attempt opened the Harbor district.167        var openedHarbor = false168        var unlockedThemes: [String] = []169    }170171    /// Stores an attempt. Bests only ever go up; a first clear unlocks the following level.172    @discardableResult173    mutating func record(_ result: DominoResult) -> RecordOutcome {174        guard (1...Self.levelCount).contains(result.levelID) else { return .init(isNewBestScore: false, isNewBestStars: false, unlockedLevel: nil) }175        let index = result.levelID - 1176        let openBefore = (1...Self.levelCount).filter(isUnlocked)177        let themesBefore = DominoTheme.unlocked(stars: totalStars).map(\.id)178        if stars.count <= index { stars += Array(repeating: 0, count: index + 1 - stars.count) }179        if scores.count <= index { scores += Array(repeating: 0, count: index + 1 - scores.count) }180        attempts += 1181        bestChain = max(bestChain, result.stats.chain)182        let wasCleared = stars[index] > 0183        let newScore = result.cleared && result.score > scores[index]184        let gained = max(0, result.stars - stars[index])185        if newScore { scores[index] = result.score }186        if gained > 0 { stars[index] = result.stars }187        let newlyOpen = (1...Self.levelCount).filter(isUnlocked).filter { !openBefore.contains($0) }188        let opened = newlyOpen.first { $0 == result.levelID + 1 } ?? newlyOpen.first189        let themes = DominoTheme.unlocked(stars: totalStars).map(\.id).filter { !themesBefore.contains($0) }190        return .init(isNewBestScore: newScore, isNewBestStars: gained > 0, starsGained: gained, firstClear: !wasCleared && result.cleared,191                     unlockedLevel: opened, openedHarbor: newlyOpen.contains(Self.classicCount + 1), unlockedThemes: themes)192    }193}194
Files main
Menu

Theme