SPB Git

Repository Public License

DominoCityGame.swift 20.9 KB 370 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/DominoCity/DominoCityGame.swift10// Description      : Domino City — arcade descriptor: trophies, profile11//                    statistics, challenge templates, mastery, reconcile,12//                    reporting of a finished run, animated cover art and the13//                    autoplay log.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 SwiftUI9394enum DominoCityGame {95    // MARK: Statistics (every key is fed by `report` from a real run)9697    nonisolated enum Stat {98        static let toppled = "domino.toppled"99        static let shots = "domino.shots"100        static let clears = "domino.clears"101        static let stars = "domino.stars"102        static let bestChain = "domino.bestChain"103        static let bullseyes = "domino.bullseyes"104        static let blasts = "domino.blasts"105        static let gems = "domino.gems"106        static let aces = "domino.aces"107    }108109    static let stats: [StatDef] = [110        .init(key: Stat.toppled, title: "Pieces toppled", symbol: "rectangle.portrait.on.rectangle.portrait.angled.fill"),111        .init(key: Stat.bestChain, title: "Longest chain", symbol: "link", kind: .best),112        .init(key: Stat.shots, title: "Impulses launched", symbol: "circle.circle.fill"),113        .init(key: Stat.clears, title: "Levels cleared", symbol: "building.2.fill"),114        .init(key: Stat.stars, title: "Stars earned", symbol: "star.fill"),115        .init(key: Stat.aces, title: "One-impulse clears", symbol: "1.circle.fill"),116        .init(key: Stat.bullseyes, title: "Bullseyes", symbol: "scope"),117        .init(key: Stat.blasts, title: "Explosions", symbol: "flame.fill"),118        .init(key: Stat.gems, title: "Gems collected", symbol: "diamond.fill"),119    ]120121    // MARK: Trophies122123    static let achievements: [AchievementDef] = [124        // The six trophies of 0.1, same ids, same meaning.125        .init(id: "domino.first", game: .dominoCity, title: "Ground Breaking", detail: "Clear the first level.", symbol: "hand.point.up.left.fill"),126        .init(id: "domino.perfect", game: .dominoCity, title: "Clean Sweep", detail: "Earn three stars on any level.", symbol: "star.fill"),127        .init(id: "domino.chain", game: .dominoCity, title: "Chain Gang", detail: "Set off a chain of 20 pieces in one run.", symbol: "link", rarity: .rare),128        .init(id: "domino.halfway", game: .dominoCity, title: "Urban Planner", detail: "Clear eight levels.", symbol: "building.2.fill"),129        .init(id: "domino.mayor", game: .dominoCity, title: "Mayor of Rubble", detail: "Clear all fifteen Downtown levels.", symbol: "crown.fill", rarity: .rare),130        .init(id: "domino.constellation", game: .dominoCity, title: "Constellation", detail: "Collect all 45 Downtown stars.", symbol: "sparkles", rarity: .epic),131        // 2.0.132        .init(id: "domino.harbor", game: .dominoCity, title: "New in Town", detail: "Clear the first Harbor level.", symbol: "ferry.fill"),133        .init(id: "domino.relay", game: .dominoCity, title: "Block Party", detail: "Clear a multi-stage level.", symbol: "square.stack.3d.forward.dottedline.fill", rarity: .rare),134        .init(id: "domino.stylist", game: .dominoCity, title: "Fresh Paint", detail: "Unlock a new city theme.", symbol: "paintpalette.fill"),135        .init(id: "domino.governor", game: .dominoCity, title: "Governor", detail: "Clear all thirty levels.", symbol: "building.columns.fill", rarity: .epic),136        .init(id: "domino.galaxy", game: .dominoCity, title: "Galaxy", detail: "Collect all 90 stars.", symbol: "moon.stars.fill", rarity: .legendary),137        .init(id: "domino.toppled500", game: .dominoCity, title: "Wrecking Crew", detail: "Topple 500 pieces.", symbol: "hammer.fill", goal: .total(Stat.toppled, 500)),138        .init(id: "domino.toppled5000", game: .dominoCity, title: "Urban Renewal", detail: "Topple 5,000 pieces.", symbol: "hammer.circle.fill", rarity: .epic,139              goal: .total(Stat.toppled, 5000)),140        .init(id: "domino.shots100", game: .dominoCity, title: "Hundred Pushes", detail: "Launch 100 impulses.", symbol: "circle.circle.fill", goal: .total(Stat.shots, 100)),141        .init(id: "domino.clears100", game: .dominoCity, title: "Career Demolisher", detail: "Clear levels 100 times.", symbol: "checkmark.seal.fill", rarity: .rare,142              goal: .total(Stat.clears, 100)),143        .init(id: "domino.megachain", game: .dominoCity, title: "Unstoppable", detail: "Set off a chain of 30 pieces in one run.", symbol: "bolt.horizontal.fill",144              rarity: .epic, goal: .best(Stat.bestChain, 30)),145        .init(id: "domino.bullseye10", game: .dominoCity, title: "Dead Centre", detail: "Hit 10 bullseyes on switches and beacons.", symbol: "scope", rarity: .rare,146              goal: .total(Stat.bullseyes, 10)),147        .init(id: "domino.blasts25", game: .dominoCity, title: "Demolition Expert", detail: "Set off 25 explosive pieces.", symbol: "flame.fill", rarity: .rare,148              goal: .total(Stat.blasts, 25)),149        .init(id: "domino.aces10", game: .dominoCity, title: "One and Done", detail: "Clear levels with a single impulse 10 times.", symbol: "1.circle.fill", rarity: .rare,150              goal: .total(Stat.aces, 10)),151        .init(id: "domino.gems20", game: .dominoCity, title: "Gem Collector", detail: "Collect 20 gems.", symbol: "diamond.fill", goal: .total(Stat.gems, 20)),152    ]153154    // MARK: Challenges155156    static let challenges: [ChallengeTemplate] = [157        .init(id: "domino.c.toppled", game: .dominoCity, kind: .total, stat: Stat.toppled, title: "Topple %@ pieces in Domino City", symbol: "hammer.fill",158              daily: [40, 100, 200], weekly: 800),159        .init(id: "domino.c.clears", game: .dominoCity, kind: .total, stat: Stat.clears, title: "Clear %@ Domino City levels", symbol: "building.2.fill",160              daily: [2, 4, 7], weekly: 25),161        .init(id: "domino.c.chain", game: .dominoCity, kind: .best, stat: Stat.bestChain, title: "Set off a chain of %@ pieces in one run", symbol: "link",162              daily: [8, 13, 20], weekly: 25),163        .init(id: "domino.c.aces", game: .dominoCity, kind: .total, stat: Stat.aces, title: "Clear %@ levels with a single impulse", symbol: "1.circle.fill",164              daily: [1, 3, 5], weekly: 15),165    ]166167    // MARK: Descriptor168169    static let descriptor = GameDescriptor(170        id: .dominoCity,171        title: "Domino City",172        tagline: "Topple a miniature city with one perfect push.",173        theme: .domino,174        music: .domino,175        preview: { AnyView(DominoCoverArt()) },176        bestLabel: { save in save.domino.hasPlayed ? "★ \(save.domino.totalStars)/\(DominoSave.maxStars)" : nil },177        progress: { save in178            ("\(save.domino.clearedCount) / \(DominoSave.levelCount) levels", Double(save.domino.clearedCount) / Double(DominoSave.levelCount))179        },180        root: { onExit in AnyView(DominoRootView(onExit: onExit)) },181        category: .physics,182        isNew: false,183        achievements: achievements,184        stats: stats,185        challenges: challenges,186        mastery: { save in mastery(save.domino) },187        continueLabel: { save in continueLabel(save.domino) },188        reconcile: { save in reconcile(&save) })189190    /// Half for levels cleared, half for stars: three stars everywhere is full mastery.191    nonisolated static func mastery(_ save: DominoSave) -> Double {192        0.5 * Double(save.clearedCount) / Double(DominoSave.levelCount) + 0.5 * Double(save.totalStars) / Double(DominoSave.maxStars)193    }194195    static func continueLabel(_ save: DominoSave) -> String? {196        guard save.hasPlayed else { return nil }197        let next = save.clearedCount >= DominoSave.levelCount ? save.lastLevel : save.highestUnlocked198        guard let level = DominoLevels.level(next) else { return nil }199        return "Level \(level.id) · \(level.name)"200    }201202    /// Statistics a save already knows (a 0.1 save, or one restored from a backup): never lowers anything, so running it twice changes nothing.203    /// Shots, bullseyes, blasts and gems were not counted before 2.0 and stay at what was really measured.204    nonisolated static func reconcile(_ save: inout SaveData) {205        let domino = save.domino206        func raise(_ key: String, _ value: Int) {207            if Double(value) > (save.statStore.totals[key] ?? 0) { save.statStore.totals[key] = Double(value) }208        }209        raise(Stat.stars, domino.totalStars)210        // Each cleared level was cleared at least once, and toppled at least its best chain... only the first is known for sure.211        raise(Stat.clears, domino.clearedCount)212        if Double(domino.bestChain) > (save.statStore.bests[Stat.bestChain] ?? 0) { save.statStore.bests[Stat.bestChain] = Double(domino.bestChain) }213    }214215    /// Reports one finished attempt to the platform: statistics, one-off experience, trophies. Call once per result, after the save was updated.216    static func report(_ result: DominoResult, level: DominoLevel, outcome: DominoSave.RecordOutcome, services: ArcadeServices) {217        reportActivity(result.stats, services: services)218        services.bestStat(Stat.bestChain, Double(result.stats.chain))219        if result.cleared {220            services.addStat(Stat.clears)221            if result.stats.impulsesUsed == 1 { services.addStat(Stat.aces) }222        }223        if outcome.starsGained > 0 { services.addStat(Stat.stars, Double(outcome.starsGained)) }224        if outcome.firstClear { services.grantOnce("domino.level.\(level.id)", xp: 20, reason: "Level \(level.id) cleared", game: .dominoCity) }225        if outcome.starsGained > 0 {226            for star in (result.stars - outcome.starsGained + 1)...result.stars {227                services.grantOnce("domino.star.\(level.id).\(star)", xp: 10, reason: "Star \(star) on level \(level.id)", game: .dominoCity)228            }229        }230        if result.cleared, result.levelID == 1 { services.unlock("domino.first") }231        if result.stars == 3 { services.unlock("domino.perfect") }232        if result.stats.chain >= 20 { services.unlock("domino.chain") }233        if result.cleared, level.isMultiStage { services.unlock("domino.relay") }234        syncTrophies(services)235    }236237    /// What an attempt really did, whether it finished or was abandoned: impulses launched, pieces toppled, bullseyes, explosions, gems.238    static func reportActivity(_ stats: DominoRunStats, services: ArcadeServices) {239        services.addStat(Stat.shots, Double(stats.impulsesUsed))240        services.addStat(Stat.toppled, Double(stats.chain))241        services.addStat(Stat.bullseyes, Double(stats.bullseyes))242        services.addStat(Stat.blasts, Double(stats.blasts))243        services.addStat(Stat.gems, Double(stats.gems))244    }245246    /// Trophies that follow from the saved progress alone. Safe to call at any time: a trophy unlocks once.247    static func syncTrophies(_ services: ArcadeServices) {248        let save = services.save.domino249        if save.clearedCount >= 8 { services.unlock("domino.halfway") }250        if save.classicCleared >= DominoSave.classicCount { services.unlock("domino.mayor") }251        if save.classicStars >= DominoSave.classicCount * 3 { services.unlock("domino.constellation") }252        if save.bestStars(DominoSave.classicCount + 1) > 0 { services.unlock("domino.harbor") }253        if save.clearedCount >= DominoSave.levelCount { services.unlock("domino.governor") }254        if save.totalStars >= DominoSave.maxStars { services.unlock("domino.galaxy") }255        if DominoTheme.unlocked(stars: save.totalStars).count > 1 { services.unlock("domino.stylist") }256    }257}258259/// Results of autoplay runs, written to Documents/domino-autoplay.json (soak runs and solvability evidence).260nonisolated enum DominoAutoplayLog {261    struct Entry: Codable, Sendable {262        var level: Int263        var cleared: Bool264        var stars: Int265        var score: Int266        var chain: Int267        var targets: Int268        var impulsesUsed: Int269        var seconds: Double270    }271272    static var url: URL {273        FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("domino-autoplay.json")274    }275276    static func append(_ result: DominoResult) {277        var entries = (try? JSONDecoder().decode([Entry].self, from: Data(contentsOf: url))) ?? []278        entries.append(Entry(level: result.levelID, cleared: result.cleared, stars: result.stars, score: result.score, chain: result.stats.chain,279                             targets: result.stats.targetsHit, impulsesUsed: result.stats.impulsesUsed, seconds: result.duration))280        let encoder = JSONEncoder()281        encoder.outputFormatting = [.prettyPrinted]282        try? encoder.encode(entries).write(to: url, options: .atomic)283    }284}285286/// Lobby cover: a row of little towers toppling in a loop under a dusk skyline. Pauses offscreen, under a running game and under Reduce Motion.287struct DominoCoverArt: View {288    var body: some View {289        AnimatedCover(stillTime: 1.25) { context, size, time in290            Self.draw(&context, size, time: time.truncatingRemainder(dividingBy: 4.2))291        }292    }293294    private static func draw(_ context: inout GraphicsContext, _ size: CGSize, time: Double) {295        let w = size.width, h = size.height296        context.fill(Path(CGRect(origin: .zero, size: size)),297                     with: .linearGradient(Gradient(colors: [Color(hex: 0x1B0E33), Color(hex: 0x5A2350), Color(hex: 0xD0604F)]),298                                           startPoint: .zero, endPoint: CGPoint(x: 0, y: h)))299        // Sun.300        context.fill(Path(ellipseIn: CGRect(x: w * 0.66, y: h * 0.16, width: 70, height: 70)),301                     with: .radialGradient(Gradient(colors: [Color(hex: 0xFFE08A), Color(hex: 0xFFB341).opacity(0)]),302                                           center: CGPoint(x: w * 0.66 + 35, y: h * 0.16 + 35), startRadius: 4, endRadius: 40))303        // Far skyline.304        var rng = SeededRNG(seed: 77)305        var x = -10.0306        while x < w {307            let bw = rng.double(in: 22...46), bh = rng.double(in: 40...120)308            context.fill(Path(CGRect(x: x, y: h * 0.62 - bh, width: bw, height: bh + 4)), with: .color(Color(hex: 0x241238).opacity(0.85)))309            var wy = h * 0.62 - bh + 6310            while wy < h * 0.62 - 6 {311                if rng.chance(0.4) {312                    context.fill(Path(CGRect(x: x + rng.double(in: 4...(bw - 8)), y: wy, width: 3, height: 3)), with: .color(Color(hex: 0xFFD27A).opacity(0.7)))313                }314                wy += 9315            }316            x += bw + rng.double(in: 2...10)317        }318        // Street.319        let groundY = h * 0.62320        context.fill(Path(CGRect(x: 0, y: groundY, width: w, height: h - groundY)), with: .color(Color(hex: 0x1A1030)))321        context.fill(Path(CGRect(x: 0, y: groundY, width: w, height: 2)), with: .color(Color(hex: 0xFFB341)))322323        // Dominoes toppling left to right, then standing back up.324        let count = 9325        let spacing = min(30.0, (w - 110) / Double(count))326        let dw = 11.0, dh = 52.0327        let startX = w * 0.5 - spacing * Double(count - 1) / 2 + 14328        let palette: [UInt32] = DominoArt.palette329        let reset = time > 3.4 ? (time - 3.4) / 0.8 : 0330        for index in 0..<count {331            let begin = 0.45 + Double(index) * 0.2332            var progress = ((time - begin) / 0.38).clamped(0, 1)333            progress = progress * progress * (3 - 2 * progress)334            if reset > 0 { progress *= 1 - reset }335            let lean = index == count - 1 ? 86.0 : 62.0336            let isGold = index == count - 1337            var piece = context338            piece.translateBy(x: startX + Double(index) * spacing + dw / 2, y: groundY)339            piece.rotate(by: .degrees(progress * lean))340            let rect = CGRect(x: -dw, y: -dh, width: dw, height: dh)341            let base = Color(hex: isGold ? DominoArt.gold : palette[index % palette.count])342            if isGold {343                piece.fill(Path(ellipseIn: rect.insetBy(dx: -18, dy: -10)),344                           with: .radialGradient(Gradient(colors: [Color(hex: DominoArt.gold).opacity(0.45), .clear]),345                                                 center: CGPoint(x: rect.midX, y: rect.midY), startRadius: 2, endRadius: 40))346            }347            piece.fill(Path(roundedRect: rect, cornerRadius: 2.5), with: .linearGradient(Gradient(colors: [base, base.opacity(0.7)]),348                                                                                           startPoint: CGPoint(x: 0, y: -dh), endPoint: .zero))349            piece.fill(Path(CGRect(x: -dw * 0.3, y: -dh, width: dw * 0.3, height: dh)), with: .color(.black.opacity(0.2)))350            // Windows go dark as the tower falls.351            for row in 0..<6 {352                let lit = (row + index) % 3 != 0 && progress < 0.5353                piece.fill(Path(CGRect(x: -dw + 2, y: -dh + 6 + Double(row) * 7.5, width: dw * 0.5, height: 3)),354                           with: .color(Color(hex: 0xFFF1B8).opacity(lit || isGold ? 0.9 : 0.25)))355            }356        }357        // The impulse ball flying in.358        let ballT = (time / 0.5).clamped(0, 1)359        if reset == 0 {360            let bx = 6 + (startX - 14) * ballT, by = groundY - 44 + 14 * ballT * ballT361            let after = time > 0.5 ? (time - 0.5) : 0362            let ballRect = CGRect(x: bx - 8 - after * 22, y: min(groundY - 16, by + after * after * 160), width: 16, height: 16)363            context.fill(Path(ellipseIn: ballRect.insetBy(dx: -8, dy: -8)),364                         with: .radialGradient(Gradient(colors: [Color(hex: 0xFFB341).opacity(0.5), .clear]),365                                               center: CGPoint(x: ballRect.midX, y: ballRect.midY), startRadius: 2, endRadius: 16))366            context.fill(Path(ellipseIn: ballRect), with: .color(Color(hex: 0xFFE9B0)))367        }368    }369}370
Files main
Menu

Theme