SPB Git

Repository Public License

DigScene.swift 28.5 KB 643 lines swift

1// ORIX Arcade2// File: Games/DigToCore/DigScene.swift3// Description: Dig to Core — SpriteKit rendering of a run: pooled tile sprites for the visible rows only, drill, debris, lighting, scanner, touch steering, tutorial hints and effects.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SpriteKit8import Observation910/// HUD values published by the scene about ten times a second.11@Observable12final class DigHUD {13    var depth = 014    var fuel = 1.015    var hull = 1.016    var cargoCount = 017    var cargoCap = 1018    var cargoValue = 019    var finds = 020    var biome = DigBiome.loam21    var banner: String?22    var bannerDetail: String?23    var bannerTick = 024    var hint: String?25    var hintSymbol = "hand.draw.fill"26    var ended = false27}2829final class DigScene: ArcadeScene {30    let dive: DigRun31    let hud: DigHUD32    let skin: DigSkin33    var onEnd: ((DigRunResult) -> Void)?34    /// Set by the SwiftUI layer while the pause menu is up (SpriteKit may unpause a scene on its own when the app returns).35    var gameplayPaused = false3637    private let cols = DigConfig.cols38    private var ts: CGFloat = 3639    private var drillScreenY: CGFloat = 50040    private let tileLayer = SKNode()41    private let markLayer = SKNode()42    private var rows: [Int: [SKSpriteNode?]] = [:]43    private var rowMarks: [Int: SKNode] = [:]44    private var pool: [SKSpriteNode] = []45    private let drill = SKNode()46    private let drillSprite = SKSpriteNode()47    private let lamp = SKSpriteNode()48    private var surface: SKSpriteNode?49    private var scanMarks: [SKSpriteNode] = []5051    private struct Chip { let node: SKSpriteNode; var vx: CGFloat = 0; var vy: CGFloat = 0; var life: CGFloat = 0 }52    private var chips: [Chip] = []53    private var nextChip = 05455    private var targetX: Double56    private var activeTouch: UITouch?57    private var touchStartX: CGFloat = 058    private var targetAtTouch: Double = 059    private let autoplay = LaunchOptions.autoplay60    private var botTimer = 0.061    private var hudTimer = 0.062    private var scanTimer = 0.063    private var drillSoundTimer = 0.064    private var frameTimer = 0.065    private var drillFrame = 066    private var endTimer: Double?67    private var endReported = false6869    // Tutorial and one-time hints.70    private var tutorialStep: Int71    private var tutorialTimer = 0.072    private var hintQueue: [(key: String, text: String, symbol: String)] = []73    private var hintTimer = 0.074    private var seenHints: Set<String>7576    init(services: ArcadeServices, seed: UInt64) {77        let save = services.save.dig78        // Debug launch arguments for captures: -ORIXDigMax YES (maxed drill for this dive), -ORIXDigDepth 600 (start deep).79        let stats = LaunchOptions.flag("DigMax") ? DigStats(levels: Dictionary(uniqueKeysWithValues: DigUpgrade.all.map { ($0.id, $0.maxLevel) })) : DigStats(save: save)80        dive = DigRun(seed: seed, stats: stats, startDepth: LaunchOptions.int("DigDepth") ?? 0)81        hud = DigHUD()82        skin = DigSkin.find(save.selectedSkin)83        targetX = dive.x84        tutorialStep = save.tutorialDone ? 99 : 085        seenHints = Set(save.seenHints)86        super.init(services: services, perfName: "digToCore")87        hud.cargoCap = dive.stats.cargoCap88        backgroundColor = UIColor(hex: DigBiome.loam.backHex)89        world.addChild(tileLayer)90        world.addChild(markLayer)91        markLayer.zPosition = 392        drillSprite.anchorPoint = CGPoint(x: 0.5, y: 0)93        drillSprite.texture = DigArt.drillTexture(skin: skin, frame: 0)94        drill.addChild(drillSprite)95        drill.zPosition = 10096        world.addChild(drill)97        lamp.texture = DigArt.lampTexture98        lamp.zPosition = 30099        addChild(lamp)100        for index in 0..<56 {101            let node = SKSpriteNode(texture: TextureFactory.chip)102            node.isHidden = true103            node.zPosition = 90104            node.colorBlendFactor = 1105            world.addChild(node)106            chips.append(Chip(node: node))107            _ = index108        }109        for _ in 0..<cols {110            let mark = SKSpriteNode(texture: Self.chevron)111            mark.isHidden = true112            mark.zPosition = 320113            mark.colorBlendFactor = 1114            addChild(mark)115            scanMarks.append(mark)116        }117        if tutorialStep == 0 { showHint("Hold and drag anywhere to steer", symbol: "hand.draw.fill") }118    }119120    private static var chevron: SKTexture {121        TextureFactory.texture("dig-chevron", size: CGSize(width: 22, height: 16)) { ctx, size in122            ctx.setFillColor(UIColor.white.cgColor)123            ctx.move(to: CGPoint(x: 1, y: 2)); ctx.addLine(to: CGPoint(x: size.width / 2, y: size.height - 1)); ctx.addLine(to: CGPoint(x: size.width - 1, y: 2))124            ctx.addLine(to: CGPoint(x: size.width / 2, y: 7))125            ctx.closePath()126            ctx.fillPath()127        }128    }129130    // MARK: Layout131132    override func layout() {133        ts = size.width / CGFloat(cols)134        drillScreenY = size.height * 0.64135        // Everything is sized from the tile, so rebuild the visible rows.136        for (_, sprites) in rows { for sprite in sprites { if let sprite { recycle(sprite) } } }137        rows.removeAll()138        for (_, mark) in rowMarks { mark.removeFromParent() }139        rowMarks.removeAll()140        drillSprite.size = CGSize(width: ts * 0.86, height: ts * 0.86 * DigArt.drillPoints.height / DigArt.drillPoints.width)141        lamp.size = CGSize(width: size.width * 2.4, height: size.height * 1.5)142        for chip in chips { chip.node.size = CGSize(width: ts * 0.16, height: ts * 0.16) }143        surface?.removeFromParent()144        let sky = SKSpriteNode(texture: DigArt.surfaceTexture(width: size.width, height: ts * 18))145        sky.anchorPoint = CGPoint(x: 0.5, y: 0)146        sky.size = CGSize(width: size.width, height: ts * 18)147        sky.position = CGPoint(x: size.width / 2, y: 0)148        sky.zPosition = 0149        world.addChild(sky)150        surface = sky151        for (index, mark) in scanMarks.enumerated() {152            mark.position = CGPoint(x: (CGFloat(index) + 0.5) * ts, y: safeInsets.bottom + 22)153        }154        syncCamera()155        syncRows()156    }157158    // MARK: Touch steering (relative drag: the finger never has to cover the drill)159160    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {161        guard activeTouch == nil, let touch = touches.first else { return }162        activeTouch = touch163        touchStartX = touch.location(in: self).x164        targetAtTouch = dive.x165        targetX = dive.x166    }167168    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {169        guard let touch = activeTouch, touches.contains(touch) else { return }170        let dx = touch.location(in: self).x - touchStartX171        targetX = min(max(targetAtTouch + Double(dx / ts) * 1.25, 0), Double(cols))172    }173174    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { release(touches) }175    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { release(touches) }176177    private func release(_ touches: Set<UITouch>) {178        guard let touch = activeTouch, touches.contains(touch) else { return }179        activeTouch = nil180        targetX = dive.x181    }182183    /// Ends the dive on the player's request, banking the haul.184    func surfaceNow() {185        guard dive.ended == nil else { return }186        dive.surface()187        handle(dive.drainEvents())188    }189190    // MARK: Frame191192    override func tick(dt: TimeInterval) {193        guard !gameplayPaused else { return }194        if let timer = endTimer {195            endTimer = timer - dt196            updateChips(CGFloat(dt))197            if timer - dt <= 0, !endReported {198                endReported = true199                onEnd?(dive.result)200            }201            return202        }203        if autoplay {204            botTimer -= dt205            if botTimer <= 0 { botTimer = 0.1; targetX = DigBot.target(for: dive) }206        }207        dive.step(dt: dt, targetX: targetX)208        handle(dive.drainEvents())209        syncCamera()210        syncRows()211        animateDrill(dt)212        updateChips(CGFloat(dt))213        updateTutorial(dt)214215        hudTimer -= dt216        if hudTimer <= 0 {217            hudTimer = 0.1218            hud.depth = dive.depth219            hud.fuel = dive.fuelFraction220            hud.hull = dive.hullFraction221            hud.cargoCount = dive.cargo.count222            hud.cargoValue = dive.cargoValue223            hud.finds = dive.findCoins224            hud.biome = dive.biome225        }226        scanTimer -= dt227        if scanTimer <= 0 { scanTimer = 0.2; updateScanner() }228    }229230    private func syncCamera() {231        worldRestPosition = CGPoint(x: 0, y: drillScreenY + CGFloat(dive.y) * ts)232        // Once the dive has ended the drill is driven by its ending animation, not by the simulation.233        if endTimer == nil { drill.position = CGPoint(x: CGFloat(dive.x) * ts, y: -CGFloat(dive.y) * ts) }234        lamp.position = CGPoint(x: drill.position.x, y: drillScreenY - lamp.size.height * 0.06 + ts * 0.4)235        // Blend the tunnel colour across biome boundaries.236        let row = max(dive.y, 0)237        let biome = DigBiome.at(row: Int(row))238        var color = UIColor(hex: biome.backHex)239        if let next = DigBiome(rawValue: biome.rawValue + 1) {240            let t = (row - Double(next.startRow - 10)) / 10241            if t > 0 { color = color.blended(with: UIColor(hex: next.backHex), CGFloat(min(t, 1))) }242        }243        backgroundColor = color244    }245246    // MARK: Visible rows (pooled)247248    private func syncRows() {249        let first = max(0, Int(((worldRestPosition.y - size.height) / ts).rounded(.down)) - 1)250        let last = Int((worldRestPosition.y / ts).rounded(.down)) + 1251        guard last >= first else { return }252        for row in rows.keys where row < first || row > last {253            if let sprites = rows.removeValue(forKey: row) { for sprite in sprites { if let sprite { recycle(sprite) } } }254            if let mark = rowMarks.removeValue(forKey: row) { mark.removeFromParent() }255        }256        for row in first...last where rows[row] == nil { build(row) }257    }258259    private func build(_ row: Int) {260        var sprites = [SKSpriteNode?](repeating: nil, count: cols)261        for col in 0..<cols {262            let tile = dive.world.tile(col: col, row: row)263            if tile != .air { sprites[col] = makeSprite(tile, col: col, row: row) }264            queueHazardHint(tile)265        }266        rows[row] = sprites267        if let biome = DigBiome.allCases.first(where: { $0.startRow == row && row > 0 }) {268            addMark(row: row, text: biome.title.uppercased(), color: UIColor(hex: biome.accentHex), big: true)269        } else if row > 0, row.isMultiple(of: 50), row < DigConfig.coreRow {270            addMark(row: row, text: "\(row) m", color: UIColor.white.withAlphaComponent(0.55), big: false)271        }272    }273274    private func addMark(row: Int, text: String, color: UIColor, big: Bool) {275        let node = SKNode()276        let line = SKSpriteNode(color: color.withAlphaComponent(big ? 0.55 : 0.22), size: CGSize(width: size.width, height: big ? 2 : 1))277        line.position = CGPoint(x: size.width / 2, y: 0)278        node.addChild(line)279        let label = SKLabelNode.orixLabel(text, size: big ? 13 : 10, color: color)280        label.horizontalAlignmentMode = .left281        label.verticalAlignmentMode = .bottom282        label.position = CGPoint(x: 8, y: 3)283        let plate = SKSpriteNode(color: UIColor.black.withAlphaComponent(0.45), size: CGSize(width: label.frame.width + 10, height: label.frame.height + 5))284        plate.anchorPoint = CGPoint(x: 0, y: 0)285        plate.position = CGPoint(x: 3, y: 1)286        node.addChild(plate)287        node.addChild(label)288        node.position = CGPoint(x: 0, y: -CGFloat(row) * ts)289        markLayer.addChild(node)290        rowMarks[row] = node291    }292293    private func makeSprite(_ tile: DigTile, col: Int, row: Int) -> SKSpriteNode {294        let sprite = pool.popLast() ?? {295            let created = SKSpriteNode()296            tileLayer.addChild(created)297            return created298        }()299        let biome = DigBiome.at(row: row)300        let variant = ((row / 6) & 1) | (((col &* 7 &+ row &* 13) & 1) << 1)301        sprite.texture = DigArt.tile(tile, biome: biome, variant: variant)302        sprite.size = CGSize(width: ts + 0.5, height: ts + 0.5)303        sprite.position = CGPoint(x: (CGFloat(col) + 0.5) * ts, y: -(CGFloat(row) + 0.5) * ts)304        sprite.zPosition = tile.isSolid ? 1 : 2305        sprite.isHidden = false306        sprite.alpha = 1307        sprite.setScale(1)308        sprite.userData = nil309        if !reduceMotion {310            let phase = Double((col &* 31 &+ row &* 17) % 10) / 20311            switch tile {312            case .lava:313                sprite.run(.repeatForever(.sequence([.fadeAlpha(to: 0.72, duration: 0.45 + phase), .fadeAlpha(to: 1, duration: 0.45 + phase)])))314            case .gas:315                sprite.run(.repeatForever(.sequence([.scale(to: 0.9, duration: 0.6 + phase), .scale(to: 1, duration: 0.6 + phase)])))316            case .fuelCell, .repairKit, .chest:317                sprite.run(.repeatForever(.sequence([.scale(to: 1.12, duration: 0.5), .scale(to: 0.98, duration: 0.5)])))318            default: break319            }320        }321        return sprite322    }323324    private func recycle(_ sprite: SKSpriteNode) {325        sprite.removeAllActions()326        sprite.isHidden = true327        pool.append(sprite)328    }329330    /// Brings one cell's sprite in line with the world after a change.331    private func refresh(col: Int, row: Int) {332        guard col >= 0, col < cols, var sprites = rows[row] else { return }333        let tile = dive.world.tile(col: col, row: row)334        if let sprite = sprites[col] { recycle(sprite); sprites[col] = nil }335        if tile != .air { sprites[col] = makeSprite(tile, col: col, row: row) }336        rows[row] = sprites337    }338339    private func cellCentre(_ col: Int, _ row: Int) -> CGPoint {340        CGPoint(x: (CGFloat(col) + 0.5) * ts, y: -(CGFloat(row) + 0.5) * ts)341    }342343    // MARK: Events → feedback344345    private func handle(_ events: [DigEvent]) {346        guard !events.isEmpty else { return }347        var drilledHardness = 0.0348        for event in events {349            switch event {350            case .destroyed(let col, let row, let tile):351                refresh(col: col, row: row)352                let biome = DigBiome.at(row: row)353                let color = tile.isOre || tile == .fossil ? UIColor(hex: tile.colorHex) : UIColor(hex: biome.tileHex.0).lighter(0.1)354                spawnChips(at: cellCentre(col, row), color: color, count: tile == .hardRock ? 4 : 3)355                drilledHardness = max(drilledHardness, tile.hardness(in: biome))356            case .collected(let tile, let col, let row):357                let value = tile.oreValue ?? 0358                if value >= 16 {359                    services.audio.play(.gem, pitch: 0.9 + Float(min(value, 55)) / 110)360                    burst(at: cellCentre(col, row), color: UIColor(hex: tile.colorHex), count: 12, speed: 120, lifetime: 0.5, scale: 0.35, gravity: -120)361                } else {362                    services.audio.play(.coin, pitch: 0.85 + Float(value) / 20, volume: 0.7)363                }364                services.haptics.play(.impact(0.15 + Float(min(value, 55)) / 110))365                floatText("+\(Int((Double(value) * dive.stats.valueMultiplier).rounded()))", at: cellCentre(col, row), color: UIColor(hex: tile.colorHex).lighter(0.3), size: 15)366            case .swapped(let tile, let col, let row):367                services.audio.play(.gem, pitch: 1.2)368                floatText("\(tile.title) kept", at: cellCentre(col, row), color: UIColor(hex: tile.colorHex).lighter(0.3), size: 13)369            case .cargoFull(let col, let row):370                floatText("Hold full", at: cellCentre(col, row), color: UIColor.white.withAlphaComponent(0.7), size: 12)371            case .fuelCell(let col, let row):372                refresh(col: col, row: row)373                services.audio.play(.upgrade, pitch: 1.3, volume: 0.8)374                services.haptics.play(.impact(0.6))375                burst(at: cellCentre(col, row), color: UIColor(hex: DigTile.fuelCell.colorHex), count: 16, speed: 140, lifetime: 0.5, scale: 0.4, gravity: 0)376                floatText("+Fuel", at: cellCentre(col, row), color: UIColor(hex: DigTile.fuelCell.colorHex), size: 17)377            case .repair(let col, let row):378                refresh(col: col, row: row)379                services.audio.play(.confirm, pitch: 1.1)380                services.haptics.play(.impact(0.6))381                burst(at: cellCentre(col, row), color: UIColor(hex: DigTile.repairKit.colorHex), count: 14, speed: 130, lifetime: 0.5, scale: 0.4, gravity: 0)382                floatText("+Hull", at: cellCentre(col, row), color: UIColor(hex: DigTile.repairKit.colorHex), size: 17)383            case .chest(let coins, let col, let row):384                refresh(col: col, row: row)385                services.audio.play(.star)386                services.haptics.play(.success)387                burst(at: cellCentre(col, row), color: UIColor(hex: OrixColor.Hex.gold), count: 26, speed: 200, lifetime: 0.8, scale: 0.45)388                floatText("Treasure +\(coins)", at: cellCentre(col, row), color: UIColor(hex: OrixColor.Hex.gold), size: 18)389            case .fossil(let col, let row):390                services.audio.play(.gem, pitch: 0.7)391                services.haptics.play(.combo(4))392                burst(at: cellCentre(col, row), color: UIColor(hex: DigTile.fossil.colorHex), count: 18, speed: 150, lifetime: 0.7, scale: 0.4)393                floatText("Fossil +\(DigConfig.fossilValue)", at: cellCentre(col, row), color: UIColor(hex: DigTile.fossil.colorHex), size: 17)394            case .lava(let damage, let col, let row):395                refresh(col: col, row: row)396                services.audio.play(.hiss)397                services.haptics.play(.impact(1))398                shake(0.55)399                burst(at: cellCentre(col, row), color: UIColor(hex: DigTile.lava.colorHex), count: 24, speed: 220, lifetime: 0.6, scale: 0.5)400                floatText("−\(Int(damage.rounded())) hull", at: cellCentre(col, row), color: UIColor(hex: OrixColor.Hex.danger), size: 16)401                flashDrill()402            case .gas(let damage, let col, let row):403                for r in (row - 1)...(row + 1) { for c in (col - 1)...(col + 1) { refresh(col: c, row: r) } }404                services.audio.play(.boom, volume: 0.9)405                shake(damage > 0 ? 0.8 : 0.4)406                burst(at: cellCentre(col, row), color: UIColor(hex: DigTile.gas.colorHex), count: 30, speed: 260, lifetime: 0.6, scale: 0.6, gravity: 0)407                if damage > 0 {408                    services.haptics.play(.impact(1))409                    floatText("−\(Int(damage.rounded())) hull", at: cellCentre(col, row), color: UIColor(hex: OrixColor.Hex.danger), size: 16)410                    flashDrill()411                }412            case .milestone(let depth, let bonus):413                services.audio.play(.combo, pitch: 1 + Float(depth) / 2000)414                services.haptics.play(.combo(depth / 100))415                showBanner("\(depth) m", detail: "+\(bonus) credits · fuel topped up")416            case .biome(let biome):417                services.audio.play(.whoosh)418                services.haptics.play(.success)419                showBanner(biome.title, detail: "\(biome.startRow) m · new strata")420                unlockBiome(biome)421            case .lowFuel:422                services.audio.play(.warning)423                services.haptics.play(.warning)424                if tutorialStep >= 99 { showHint("Fuel is low. Look for blue cells.", symbol: "fuelpump.fill", seconds: 3) }425            case .lowHull:426                services.audio.play(.warning, pitch: 0.8)427                services.haptics.play(.warning)428                showHint("Hull critical. Surface to save your cargo.", symbol: "shield.lefthalf.filled", seconds: 4)429            case .blocked:430                services.audio.play(.thud)431                services.haptics.play(.impact(0.7))432                showHint("Steel plates can't be drilled. Slide around.", symbol: "arrow.left.and.right", seconds: 3)433            case .ended(let reason):434                finish(reason)435            }436        }437        if drilledHardness > 0, drillSoundTimer <= 0 {438            drillSoundTimer = 0.1439            services.audio.play(.drill, pitch: Float(max(0.7, 1.25 - drilledHardness * 0.06)), volume: 0.4)440        }441    }442443    private func unlockBiome(_ biome: DigBiome) {444        switch biome {445        case .crystal: services.unlock("dig.crystal")446        case .magma: services.unlock("dig.magma")447        default: break448        }449    }450451    private func flashDrill() {452        guard !reduceMotion else { return }453        drillSprite.removeAction(forKey: "flash")454        drillSprite.run(.sequence([.colorize(with: .red, colorBlendFactor: 0.8, duration: 0.04), .colorize(withColorBlendFactor: 0, duration: 0.3)]), withKey: "flash")455    }456457    private func finish(_ reason: DigEndReason) {458        hud.ended = true459        hud.hint = nil460        hud.fuel = dive.fuelFraction461        hud.hull = dive.hullFraction462        hud.depth = dive.depth463        for mark in scanMarks { mark.isHidden = true }464        endTimer = 1.15465        let tip = CGPoint(x: drill.position.x, y: drill.position.y + ts * 0.5)466        switch reason {467        case .wrecked:468            services.audio.play(.crash)469            services.haptics.play(.failure)470            shake(1)471            burst(at: tip, color: UIColor(hex: 0xFF8A2E), count: 40, speed: 280, lifetime: 0.9, scale: 0.7)472            burst(at: tip, color: UIColor(hex: skin.bodyHex), count: 20, speed: 200, lifetime: 0.9, scale: 0.4, texture: TextureFactory.chip, additive: false)473            drillSprite.run(.group([.fadeOut(withDuration: 0.25), .scale(to: 0.6, duration: 0.25)]))474        case .core:475            services.audio.play(.win)476            services.haptics.play(.success)477            shake(0.6)478            burst(at: tip, color: UIColor(hex: 0xFFE58A), count: 50, speed: 320, lifetime: 1.1, scale: 0.7, gravity: 0)479            endTimer = 1.6480        case .outOfFuel, .surfaced:481            services.audio.play(reason == .surfaced ? .whoosh : .fail, volume: 0.7)482            services.haptics.play(.warning)483            // The rescue winch reels the drill back up the shaft.484            let rise = SKAction.moveBy(x: 0, y: size.height, duration: reduceMotion ? 0.2 : 1.0)485            rise.timingMode = .easeIn486            drill.run(.sequence([.wait(forDuration: 0.15), rise, .hide()]))487        }488    }489490    // MARK: Drill animation and debris491492    private func animateDrill(_ dt: TimeInterval) {493        drillSoundTimer -= dt494        frameTimer -= dt495        if frameTimer <= 0, !dive.isBlocked {496            frameTimer = 0.07497            drillFrame = 1 - drillFrame498            drillSprite.texture = DigArt.drillTexture(skin: skin, frame: drillFrame)499        }500        guard !reduceMotion else { return }501        let tilt = CGFloat(min(max(-dive.vx * 0.022, -0.22), 0.22))502        drillSprite.zRotation += (tilt - drillSprite.zRotation) * 0.25503        drillSprite.position = CGPoint(x: dive.vy < dive.stats.airSpeed * 0.9 ? CGFloat.random(in: -0.6...0.6) : 0, y: 0)504    }505506    private func spawnChips(at point: CGPoint, color: UIColor, count: Int) {507        let scaled = max(1, Int((CGFloat(count) * effectScale).rounded()))508        for _ in 0..<scaled {509            nextChip = (nextChip + 1) % chips.count510            chips[nextChip].node.position = CGPoint(x: point.x + .random(in: -ts * 0.3...ts * 0.3), y: point.y + .random(in: -ts * 0.3...ts * 0.3))511            chips[nextChip].node.color = color512            chips[nextChip].node.alpha = 1513            chips[nextChip].node.isHidden = false514            chips[nextChip].vx = .random(in: -90...90)515            chips[nextChip].vy = .random(in: 40...190)516            chips[nextChip].life = .random(in: 0.35...0.6)517        }518    }519520    private func updateChips(_ dt: CGFloat) {521        for index in chips.indices where chips[index].life > 0 {522            chips[index].life -= dt523            if chips[index].life <= 0 { chips[index].node.isHidden = true; continue }524            chips[index].vy -= 620 * dt525            chips[index].node.position.x += chips[index].vx * dt526            chips[index].node.position.y += chips[index].vy * dt527            chips[index].node.alpha = min(1, chips[index].life * 4)528            chips[index].node.zRotation += 8 * dt529        }530    }531532    // MARK: Scanner533534    private func updateScanner() {535        let range = dive.stats.scannerRows536        guard range > 0, dive.ended == nil else { return }537        let lastVisible = Int((worldRestPosition.y / ts).rounded(.down))538        for col in 0..<cols {539            var best: DigTile?540            var bestRank = 0541            for row in (lastVisible + 1)...(lastVisible + range) {542                let tile = dive.world.tile(col: col, row: row)543                let rank: Int = switch tile {544                case .chest: 5545                case .fossil: 4546                case .fuelCell: 3547                case .repairKit: dive.hullFraction < 0.8 ? 3 : 0548                default: (tile.oreValue ?? 0) >= 16 ? 2 : 0549                }550                if rank > bestRank { bestRank = rank; best = tile }551            }552            let mark = scanMarks[col]553            if let best {554                mark.color = UIColor(hex: best.colorHex)555                if mark.isHidden {556                    mark.isHidden = false557                    mark.alpha = 0.95558                    if !reduceMotion {559                        mark.run(.repeatForever(.sequence([.moveBy(x: 0, y: -5, duration: 0.4), .moveBy(x: 0, y: 5, duration: 0.4)])), withKey: "bob")560                    }561                }562            } else if !mark.isHidden {563                mark.isHidden = true564                mark.removeAction(forKey: "bob")565                mark.position.y = safeInsets.bottom + 22566            }567        }568    }569570    // MARK: Banners, hints and tutorial571572    private func showBanner(_ text: String, detail: String) {573        hud.banner = text574        hud.bannerDetail = detail575        hud.bannerTick += 1576    }577578    private func showHint(_ text: String, symbol: String, seconds: Double = 0) {579        hud.hint = text580        hud.hintSymbol = symbol581        hintTimer = seconds582    }583584    private func queueHazardHint(_ tile: DigTile) {585        let entry: (String, String, String)? = switch tile {586        case .lava: ("lava", "Lava burns the hull. Steer around it.", "flame.fill")587        case .gas: ("gas", "Gas pockets explode: risky, but they clear rock.", "burst.fill")588        case .boulder: ("boulder", "Steel plates can't be drilled. Slide around them.", "square.grid.3x3.fill")589        case .hardRock: ("hardRock", "Dark cracked rock is slow. Go around when you can.", "tortoise.fill")590        case .chest: ("chest", "Treasure! Break into the vault to grab it.", "shippingbox.fill")591        case .repairKit: ("repair", "Green kits repair the hull.", "cross.case.fill")592        default: nil593        }594        guard let entry, !seenHints.contains(entry.0) else { return }595        seenHints.insert(entry.0)596        hintQueue.append((entry.0, entry.1, entry.2))597    }598599    private func updateTutorial(_ dt: TimeInterval) {600        if hintTimer > 0 {601            hintTimer -= dt602            if hintTimer <= 0 { hud.hint = nil }603        }604        switch tutorialStep {605        case 0:606            if dive.lateralTravel > 1.5 {607                tutorialStep = 1608                services.audio.play(.confirm)609                showHint("Drill through ore to collect it", symbol: "diamond.fill")610            }611        case 1:612            if dive.oresCollected >= 2 || dive.depth > 40 {613                tutorialStep = 2614                tutorialTimer = 4.5615                showHint("Fuel is your timer. Blue cells refill it.", symbol: "fuelpump.fill")616            }617        case 2:618            tutorialTimer -= dt619            if tutorialTimer <= 0 {620                tutorialStep = 3621                tutorialTimer = 5622                showHint("When the tank is empty you surface and sell your haul.", symbol: "arrow.up.circle.fill")623            }624        case 3:625            tutorialTimer -= dt626            if tutorialTimer <= 0 {627                tutorialStep = 99628                hud.hint = nil629                services.store.update { $0.dig.tutorialDone = true }630            }631        default:632            // One-time hazard hints, once the basics are done and nothing else is showing.633            if hud.hint == nil, let next = hintQueue.first {634                hintQueue.removeFirst()635                showHint(next.text, symbol: next.symbol, seconds: 4)636                services.store.update { data in637                    if !data.dig.seenHints.contains(next.key) { data.dig.seenHints.append(next.key) }638                }639            }640        }641    }642}643
Files main
Menu

Theme