SPB Git

Repository Public License

DigToCoreGame.swift 12.0 KB 222 lines swift

1// ORIX Arcade2// File: Games/DigToCore/DigToCoreGame.swift3// Description: Dig to Core — lobby descriptor, achievements, animated cover art and the root flow (hangar → dive → summary).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI89enum DigToCoreGame {10    static let achievements: [AchievementDef] = [11        .init(id: "dig.first", game: .digToCore, title: "First Descent", detail: "Finish your first dive.", symbol: "arrow.down.circle.fill"),12        .init(id: "dig.crystal", game: .digToCore, title: "Glittering Dark", detail: "Reach the Crystal Caverns.", symbol: "sparkles"),13        .init(id: "dig.fossil", game: .digToCore, title: "Bone Collector", detail: "Dig up 3 fossils.", symbol: "fossil.shell.fill"),14        .init(id: "dig.geared", game: .digToCore, title: "Gearhead", detail: "Own 10 upgrade levels.", symbol: "wrench.and.screwdriver.fill"),15        .init(id: "dig.magma", game: .digToCore, title: "Feel the Heat", detail: "Reach the Magma Veins.", symbol: "flame.fill"),16        .init(id: "dig.core", game: .digToCore, title: "Core Breaker", detail: "Drill all the way to the core.", symbol: "globe.europe.africa.fill"),17    ]1819    static let descriptor = GameDescriptor(20        id: .digToCore, title: "Dig to Core", tagline: "Drill through glowing strata. Upgrade. Dive deeper.", theme: .dig, music: .dig,21        preview: { AnyView(DigCoverView()) },22        bestLabel: { save in save.dig.runs == 0 ? nil : "BEST \(save.dig.bestDepth) M" },23        progress: { save in24            guard save.dig.runs > 0 else { return nil }25            let reached = save.dig.coreReached > 026            return (reached ? "Core reached" : save.dig.deepestBiome.title, reached ? 1 : Double(save.dig.bestDepth) / Double(DigConfig.coreRow))27        },28        root: { onExit in AnyView(DigRootView(onExit: onExit)) })2930    static let creditSymbol = "hexagon.fill"31}3233/// Lobby cover: strata scrolling past a drill. Static when Reduce Motion is on.34struct DigCoverView: View {35    private static let drill = DigArt.drillImage(skin: .rookie, scale: 2)3637    var body: some View {38        if OrixAppearance.reduceMotion {39            canvas(time: 0)40        } else {41            TimelineView(.animation(minimumInterval: 1.0 / 30)) { timeline in42                canvas(time: timeline.date.timeIntervalSinceReferenceDate)43            }44        }45    }4647    private func canvas(time: Double) -> some View {48        Canvas { context, size in49            let tile = size.width / 1150            let scroll = (time * 34).truncatingRemainder(dividingBy: Double(tile) * 200)51            let firstRow = Int(scroll / Double(tile))52            let rowsVisible = Int(size.height / tile) + 253            let drillX = size.width * 0.5 + CGFloat(sin(time * 0.9)) * tile * 1.654            let drillTipY = size.height * 0.555            for r in 0..<rowsVisible {56                let row = firstRow + r57                let y = CGFloat(r) * tile - CGFloat(scroll.truncatingRemainder(dividingBy: Double(tile)))58                let biome = DigBiome.allCases[(row / 14) % DigBiome.allCases.count]59                for c in 0..<11 {60                    let x = CGFloat(c) * tile61                    let rect = CGRect(x: x + 0.5, y: y + 0.5, width: tile - 1, height: tile - 1)62                    // The tunnel carved so far, following the drill's weave.63                    let pathX = size.width * 0.5 + CGFloat(sin((time - Double(drillTipY - y) / 34) * 0.9)) * tile * 1.664                    let carved = y < drillTipY - tile * 0.3 && abs(x + tile / 2 - pathX) < tile * 0.7565                    if carved {66                        context.fill(Path(rect.insetBy(dx: -0.5, dy: -0.5)), with: .color(Color(hex: biome.backHex)))67                        continue68                    }69                    let hash = (row &* 73 &+ c &* 151) % 2370                    let hex = (row / 6) % 2 == 0 ? biome.tileHex.0 : biome.tileHex.171                    context.fill(Path(roundedRect: rect, cornerRadius: 4), with: .color(Color(hex: hex)))72                    context.fill(Path(CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: 2)), with: .color(.white.opacity(0.14)))73                    if hash < 3 {74                        let ore = biome.oreTable[hash % biome.oreTable.count].075                        let gem = Path(ellipseIn: rect.insetBy(dx: tile * 0.28, dy: tile * 0.28))76                        context.fill(gem, with: .color(Color(hex: ore.colorHex)))77                        context.fill(Path(ellipseIn: CGRect(x: rect.midX - tile * 0.12, y: rect.midY - tile * 0.14, width: tile * 0.12, height: tile * 0.1)), with: .color(.white.opacity(0.8)))78                    }79                }80            }81            // Headlamp glow and the drill itself.82            let glow = CGRect(x: drillX - tile * 2.6, y: drillTipY - tile * 2.9, width: tile * 5.2, height: tile * 5.2)83            context.fill(Path(ellipseIn: glow), with: .radialGradient(Gradient(colors: [GameTheme.dig.primary.opacity(0.35), .clear]),84                                                                       center: CGPoint(x: glow.midX, y: glow.midY), startRadius: 0, endRadius: glow.width / 2))85            let drillSize = CGSize(width: tile * 1.5, height: tile * 1.5 * DigArt.drillPoints.height / DigArt.drillPoints.width)86            context.draw(Image(uiImage: Self.drill), in: CGRect(x: drillX - drillSize.width / 2, y: drillTipY - drillSize.height, width: drillSize.width, height: drillSize.height))87        }88        .background(GameTheme.dig.deep)89        .accessibilityHidden(true)90    }91}9293/// Root of the game: owns the flow between hangar, dive and summary, and writes results to the save.94struct DigRootView: View {95    let onExit: () -> Void96    @Environment(ArcadeServices.self) private var services97    @State private var scene: DigScene?98    @State private var isPaused = false99    @State private var result: DigRunResult?100    @State private var isRecord = false101    @State private var showShop = false102    @State private var started = false103104    var body: some View {105        ZStack {106            if let scene {107                GameChrome(theme: .dig, title: "Dig to Core", isPaused: $isPaused, canPause: result == nil && !scene.hud.ended,108                           pauseDetail: "\(scene.hud.depth) m · \(scene.hud.biome.title)", onRestart: restart, onExit: quit) {109                    ZStack {110                        GameSceneView(scene: scene, isPaused: isPaused).id(ObjectIdentifier(scene))111                        DigHUDView(hud: scene.hud, leftHanded: services.settings.leftHanded) { scene.surfaceNow() }112                        if let result { summary(result) }113                    }114                }115                .transition(.opacity)116            } else {117                DigHangarView(showShop: $showShop, onDive: startRun, onExit: onExit)118                    .transition(.opacity)119            }120        }121        .background(OrixColor.void.ignoresSafeArea())122        .onChange(of: isPaused) { _, paused in scene?.gameplayPaused = paused }123        .onAppear {124            guard !started else { return }125            started = true126            services.setResumeNote("In the hangar")127            if LaunchOptions.flag("Dive") { startRun() }128            if LaunchOptions.flag("DigShop") { showShop = true }129        }130    }131132    private func startRun() {133        let seed = LaunchOptions.seed ?? UInt64.random(in: 1...UInt64(Int32.max))134        let created = DigScene(services: services, seed: seed)135        created.onEnd = { finished in finishRun(finished) }136        result = nil137        isPaused = false138        services.setResumeNote("Mid-dive · best \(services.save.dig.bestDepth) m")139        withAnimation(.easeInOut(duration: 0.25)) { scene = created }140    }141142    private func finishRun(_ finished: DigRunResult) {143        var outcome = DigEconomy.Outcome(isRecord: false, newSkins: [])144        services.store.update { outcome = DigEconomy.bank(finished, into: &$0.dig) }145        isRecord = outcome.isRecord146        services.recordSession(game: .digToCore, score: finished.depth, duration: finished.duration,147                               headline: "\(finished.depth) m · \(finished.biome.title) · +\(finished.total) credits", isRecord: outcome.isRecord)148        let save = services.save.dig149        // Achievements are granted now; their toasts are spaced out so they never bury the summary.150        var earned = ["dig.first"]151        if save.fossils >= 3 { earned.append("dig.fossil") }152        if finished.reason == .core { earned.append("dig.core") }153        if save.bestDepth >= DigBiome.crystal.startRow { earned.append("dig.crystal") }154        if save.bestDepth >= DigBiome.magma.startRow { earned.append("dig.magma") }155        let pending = earned.filter { !services.isUnlocked($0) }156        let skins = outcome.newSkins157        Task {158            try? await Task.sleep(for: .seconds(1.2))159            for id in pending {160                services.unlock(id)161                try? await Task.sleep(for: .seconds(1.6))162            }163            for skin in skins {164                services.showToast(ArcadeToast(title: "\(skin.title) skin", detail: "Skin unlocked", symbol: "paintpalette.fill", tintHex: skin.bodyHex))165                try? await Task.sleep(for: .seconds(1.6))166            }167        }168        services.setResumeNote("In the hangar · \(save.bank) credits to spend")169        withAnimation(OrixMotion.decorative(OrixMotion.snappy)) { result = finished }170        if LaunchOptions.autoplay, LaunchOptions.flag("Loop") {171            Task {172                try? await Task.sleep(for: .seconds(2))173                if result != nil { startRun() }174            }175        }176    }177178    private func abandon() {179        if let scene, result == nil { services.addPlayTime(game: .digToCore, duration: scene.dive.time) }180    }181182    private func restart() {183        abandon()184        startRun()185    }186187    private func quit() {188        abandon()189        onExit()190    }191192    private func backToHangar(shop: Bool) {193        result = nil194        isPaused = false195        showShop = shop196        withAnimation(.easeInOut(duration: 0.25)) { scene = nil }197    }198199    private func summary(_ finished: DigRunResult) -> some View {200        let title: String, subtitle: String201        switch finished.reason {202        case .core: (title, subtitle) = ("Core reached!", "You drilled through the whole planet.")203        case .outOfFuel: (title, subtitle) = ("Tank empty", "The winch hauled you up with the full haul.")204        case .wrecked: (title, subtitle) = ("Drill wrecked", "The winch saved \(Int((finished.keptFraction * 100).rounded()))% of the ore.")205        case .surfaced: (title, subtitle) = ("Surfaced", "Safe and sound, cargo intact.")206        }207        var rows = [208            ResultRow(label: "Depth", value: "\(finished.depth) m", systemImage: "arrow.down.to.line", highlight: isRecord),209            ResultRow(label: "Ore sold (\(finished.oreCount))", value: "+\(finished.oreCoins)", systemImage: "diamond.fill"),210        ]211        if finished.lostCoins > 0 { rows.append(ResultRow(label: "Cargo lost", value: "−\(finished.lostCoins)", systemImage: "exclamationmark.triangle.fill")) }212        if finished.findCoins > 0 { rows.append(ResultRow(label: "Finds and milestones", value: "+\(finished.findCoins)", systemImage: "sparkles")) }213        rows.append(ResultRow(label: "Depth bonus", value: "+\(finished.depthCoins)", systemImage: "ruler.fill"))214        if finished.coreCoins > 0 { rows.append(ResultRow(label: "Core bonus", value: "+\(finished.coreCoins)", systemImage: "globe.europe.africa.fill", highlight: true)) }215        return ResultsCard(theme: .dig, title: title, subtitle: "\(subtitle)\n\(finished.biome.title)", score: finished.total, scoreLabel: "CREDITS EARNED",216                           isNewRecord: isRecord, success: finished.reason != .wrecked, rows: rows,217                           primaryTitle: "Dive again", primaryIcon: "arrow.down.circle.fill", onPrimary: startRun,218                           secondaryTitle: "Upgrades", secondaryIcon: "wrench.and.screwdriver.fill", onSecondary: { backToHangar(shop: true) },219                           onExit: onExit)220    }221}222
Files main
Menu

Theme