SPB Git

Repository Public License

DigRun.swift 18.4 KB 443 lines swift

1// ORIX Arcade2// File: Games/DigToCore/DigRun.swift3// Description: Dig to Core — headless run simulation (movement, grid collision, drilling, cargo, hazards, fuel and hull), run results, banking and the autoplay bot.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89nonisolated enum DigEndReason: String, Codable, Sendable {10    case outOfFuel, wrecked, core, surfaced11}1213nonisolated enum DigEvent: Equatable, Sendable {14    /// A terrain tile was removed (drilled, blasted or pulled by the magnet).15    case destroyed(col: Int, row: Int, tile: DigTile)16    case collected(tile: DigTile, col: Int, row: Int)17    /// The hold was full: a cheaper ore was dropped for a better one.18    case swapped(tile: DigTile, col: Int, row: Int)19    case cargoFull(col: Int, row: Int)20    case fuelCell(col: Int, row: Int)21    case repair(col: Int, row: Int)22    case chest(coins: Int, col: Int, row: Int)23    case fossil(col: Int, row: Int)24    case lava(damage: Double, col: Int, row: Int)25    case gas(damage: Double, col: Int, row: Int)26    case milestone(depth: Int, bonus: Int)27    case biome(DigBiome)28    case lowFuel29    case lowHull30    /// Resting on a boulder that must be steered around.31    case blocked32    case ended(DigEndReason)33}3435nonisolated struct DigRunResult: Equatable, Sendable {36    var reason: DigEndReason37    /// Depth reached in metres.38    var depth: Int39    var biome: DigBiome40    var oreCount: Int41    /// Ore value after the refinery bonus, before any wreck loss.42    var oreValue: Int43    var keptFraction: Double44    var oreCoins: Int45    /// Chests, fossils and milestone rewards.46    var findCoins: Int47    var depthCoins: Int48    var coreCoins: Int49    var fossils: Int50    var chests: Int51    var duration: TimeInterval5253    var total: Int { oreCoins + findCoins + depthCoins + coreCoins }54    var lostCoins: Int { oreValue - oreCoins }55}5657nonisolated final class DigRun {58    let world: DigWorld59    let stats: DigStats6061    /// Drill centre, in tiles from the left wall.62    private(set) var x: Double63    /// Depth of the drill tip in tiles (metres). Negative above the surface.64    private(set) var y: Double = -1.465    /// Lateral velocity of the last step, tiles per second (for visuals).66    private(set) var vx: Double = 067    /// Descent velocity of the last step, tiles per second.68    private(set) var vy: Double = 069    private(set) var fuel: Double70    private(set) var hull: Double71    private(set) var cargo: [DigTile] = []72    private(set) var findCoins = 073    private(set) var fossils = 074    private(set) var chests = 075    private(set) var time: TimeInterval = 076    private(set) var ended: DigEndReason?77    private(set) var biome = DigBiome.loam78    private(set) var isBlocked = false79    private(set) var oresCollected = 080    private(set) var lateralTravel: Double = 081    /// Events since the last `drainEvents()`.82    private var events: [DigEvent] = []8384    private var rowResistance: Double = 085    private var nextMilestone = DigConfig.milestoneEvery86    private var warnedFuel = false87    private var warnedHull = false88    private var blockedTime: Double = 08990    /// `startDepth` is a debugging aid (screenshots and captures of deep biomes); normal runs start at the surface.91    init(seed: UInt64, stats: DigStats, startDepth: Int = 0) {92        world = DigWorld(seed: seed)93        self.stats = stats94        x = Double(DigConfig.cols) / 295        fuel = stats.fuelMax96        hull = stats.hullMax97        if startDepth > 0 {98            let row = min(startDepth, DigConfig.coreRow - 30)99            y = Double(row)100            biome = DigBiome.at(row: row)101            nextMilestone = (row / DigConfig.milestoneEvery + 1) * DigConfig.milestoneEvery102            x = Double(DigGenerator.boundaryColumn(seed: seed, boundary: row / DigConfig.chunkRows + 1)) + 0.5103        }104        world.ensure(row: max(0, Int(y)))105    }106107    var depth: Int { max(0, Int(y)) }108    var fuelFraction: Double { max(0, fuel / stats.fuelMax) }109    var hullFraction: Double { max(0, hull / stats.hullMax) }110    var cargoValue: Int { Int((Double(cargo.reduce(0) { $0 + ($1.oreValue ?? 0) }) * stats.valueMultiplier).rounded()) }111112    func drainEvents() -> [DigEvent] {113        defer { events.removeAll(keepingCapacity: true) }114        return events115    }116117    /// Ends the run voluntarily, banking everything.118    func surface() {119        guard ended == nil else { return }120        finish(.surfaced)121    }122123    // MARK: Simulation step124125    /// Advances the run. `targetX` is where the player wants the drill centre, in tiles.126    func step(dt: Double, targetX: Double) {127        guard ended == nil, dt > 0 else { return }128        time += dt129        fuel -= stats.fuelDrain * dt130        let cols = DigConfig.cols, half = DigConfig.halfWidth131132        // Lateral movement, with grid collision against unbreakable tiles and slower travel through solids.133        let goal = min(max(targetX, half), Double(cols) - half)134        var dx = min(max((goal - x) * 14, -stats.lateralSpeed), stats.lateralSpeed) * dt135        if abs(dx) > abs(goal - x) { dx = goal - x }136        let startX = x137        if abs(dx) > 1e-6 {138            let dir: Double = dx > 0 ? 1 : -1139            let leadCol = Int(((x + dx) + dir * half).rounded(.down))140            let top = Int((y - DigConfig.bodyHeight).rounded(.down)), tip = Int(y.rounded(.down))141            var blocked = false142            var hardest = 0.0143            if leadCol >= 0, leadCol < cols, tip >= 0 {144                for r in max(top, 0)...tip {145                    let tile = world.tile(col: leadCol, row: r)146                    if tile.isUnbreakable { blocked = true } else if tile.isSolid { hardest = max(hardest, tile.hardness(in: DigBiome.at(row: r))) }147                }148            }149            if blocked {150                let limit = dir > 0 ? Double(leadCol) - half - 0.001 : Double(leadCol + 1) + half + 0.001151                x = dir > 0 ? max(x, min(x + dx, limit)) : min(x, max(x + dx, limit))152            } else {153                if hardest > 0 { dx *= min(1, max(0.3, stats.drillPower / hardest)) }154                x += dx155            }156        }157        x = min(max(x, half), Double(cols) - half)158159        // Descent: speed depends on what the tip is cutting through; boulders stop it.160        let speed = rowResistance > 0 ? min(stats.airSpeed, DigConfig.baseDrillSpeed * stats.drillPower / rowResistance) : stats.airSpeed161        var newY = y + speed * dt162        let tipRow = Int(y.rounded(.down)), nextRow = Int(newY.rounded(.down))163        isBlocked = false164        if nextRow > tipRow, nextRow >= 0 {165            let c0 = max(0, Int((x - half).rounded(.down))), c1 = min(cols - 1, Int((x + half).rounded(.down)))166            var blockers: [Int] = []167            for c in c0...c1 where world.tile(col: c, row: nextRow).isUnbreakable { blockers.append(c) }168            if blockers.isEmpty {169                rowResistance = 0170            } else {171                newY = Double(nextRow) - 0.0005172                isBlocked = true173                let centre = Int(x.rounded(.down))174                if !blockers.contains(centre) {175                    // Only clipping a boulder's corner: slide into our own column.176                    let aim = Double(centre) + 0.5177                    let slide = min(abs(aim - x), 4 * dt)178                    x += aim > x ? slide : -slide179                }180            }181        }182        if isBlocked {183            blockedTime += dt184            if blockedTime > 0.5 { events.append(.blocked); blockedTime = -4 }185        } else if blockedTime > 0 {186            blockedTime = 0187        }188        vy = (newY - y) / dt189        y = newY190        vx = (x - startX) / dt191        lateralTravel += abs(x - startX)192193        processOverlaps()194        guard ended == nil else { return }195196        // Depth milestones and biome changes.197        let depthNow = depth198        while depthNow >= nextMilestone, nextMilestone < DigConfig.coreRow {199            let bonus = 10 + 5 * (nextMilestone / DigConfig.milestoneEvery)200            findCoins += bonus201            fuel = min(stats.fuelMax, fuel + stats.fuelMax * DigConfig.milestoneFuelFraction)202            events.append(.milestone(depth: nextMilestone, bonus: bonus))203            nextMilestone += DigConfig.milestoneEvery204        }205        let current = DigBiome.at(row: depthNow)206        if current.rawValue > biome.rawValue {207            biome = current208            events.append(.biome(current))209        }210        world.ensure(row: depthNow)211212        if hull <= 0 { finish(.wrecked); return }213        if fuel <= 0 { fuel = 0; finish(.outOfFuel); return }214        if !warnedFuel, fuelFraction < 0.25 { warnedFuel = true; events.append(.lowFuel) }215        if warnedFuel, fuelFraction > 0.4 { warnedFuel = false }216        if !warnedHull, hullFraction < 0.3 { warnedHull = true; events.append(.lowHull) }217        if warnedHull, hullFraction > 0.5 { warnedHull = false }218    }219220    private func processOverlaps() {221        let cols = DigConfig.cols, half = DigConfig.halfWidth222        let tip = Int(y.rounded(.down))223        guard tip >= 0 else { return }224        let top = max(0, Int((y - DigConfig.bodyHeight).rounded(.down)))225        let c0 = max(0, Int((x - half).rounded(.down))), c1 = min(cols - 1, Int((x + half).rounded(.down)))226        let h0 = Int((x - DigConfig.hazardHalf).rounded(.down)), h1 = Int((x + DigConfig.hazardHalf).rounded(.down))227        for r in top...tip {228            for c in c0...c1 {229                let tile = world.tile(col: c, row: r)230                switch tile {231                case .air, .boulder: continue232                case .core:233                    finish(.core)234                    return235                case .lava:236                    guard c >= h0, c <= h1 else { continue }237                    world.set(col: c, row: r, .air)238                    hull -= stats.lavaDamage239                    events.append(.lava(damage: stats.lavaDamage, col: c, row: r))240                case .gas:241                    guard c >= h0, c <= h1 else { continue }242                    explode(col: c, row: r)243                case .fuelCell:244                    world.set(col: c, row: r, .air)245                    fuel = min(stats.fuelMax, fuel + stats.fuelMax * DigConfig.fuelCellFraction)246                    events.append(.fuelCell(col: c, row: r))247                case .repairKit:248                    world.set(col: c, row: r, .air)249                    hull = min(stats.hullMax, hull + DigConfig.repairAmount)250                    events.append(.repair(col: c, row: r))251                case .chest:252                    world.set(col: c, row: r, .air)253                    let coins = 30 + r / 10254                    findCoins += coins255                    chests += 1256                    events.append(.chest(coins: coins, col: c, row: r))257                default:258                    rowResistance = max(rowResistance, tile.hardness(in: DigBiome.at(row: r)))259                    mine(col: c, row: r, tile: tile)260                }261            }262            // Ore magnet: pull ore from neighbouring columns.263            if stats.magnetRange > 0 {264                for c in (c0 - stats.magnetRange)...(c1 + stats.magnetRange) where c >= 0 && c < cols && (c < c0 || c > c1) {265                    let tile = world.tile(col: c, row: r)266                    if tile.isOre { mine(col: c, row: r, tile: tile) }267                }268            }269        }270    }271272    /// Removes a breakable tile and collects whatever it held.273    private func mine(col: Int, row: Int, tile: DigTile) {274        world.set(col: col, row: row, .air)275        events.append(.destroyed(col: col, row: row, tile: tile))276        if tile.isOre {277            collect(tile, col: col, row: row)278        } else if tile == .fossil {279            fossils += 1280            findCoins += DigConfig.fossilValue281            events.append(.fossil(col: col, row: row))282        }283    }284285    private func collect(_ ore: DigTile, col: Int, row: Int) {286        oresCollected += 1287        if cargo.count < stats.cargoCap {288            cargo.append(ore)289            events.append(.collected(tile: ore, col: col, row: row))290            return291        }292        // Hold full: keep the most valuable ore.293        guard let cheapest = cargo.indices.min(by: { (cargo[$0].oreValue ?? 0) < (cargo[$1].oreValue ?? 0) }),294              (cargo[cheapest].oreValue ?? 0) < (ore.oreValue ?? 0) else {295            events.append(.cargoFull(col: col, row: row))296            return297        }298        cargo[cheapest] = ore299        events.append(.swapped(tile: ore, col: col, row: row))300    }301302    /// Gas explosion: clears the 3×3 around each pocket, chains into neighbouring gas, and damages a nearby drill once.303    private func explode(col: Int, row: Int) {304        var queue = [(col, row)]305        var hurt = false306        var index = 0307        while index < queue.count {308            let (cc, cr) = queue[index]309            index += 1310            world.set(col: cc, row: cr, .air)311            if abs(Double(cc) + 0.5 - x) <= 1.9, abs(Double(cr) + 0.5 - (y - 0.45)) <= 1.9 { hurt = true }312            for r in (cr - 1)...(cr + 1) {313                for c in (cc - 1)...(cc + 1) where c >= 0 && c < DigConfig.cols && r >= 0 {314                    let tile = world.tile(col: c, row: r)315                    switch tile {316                    case .air, .boulder, .core, .fuelCell, .repairKit, .chest: continue317                    case .gas: if !queue.contains(where: { $0 == (c, r) }) { queue.append((c, r)) }318                    case .lava: world.set(col: c, row: r, .air)319                    default: mine(col: c, row: r, tile: tile)320                    }321                }322            }323        }324        if hurt { hull -= stats.gasDamage }325        for (offset, centre) in queue.enumerated() {326            events.append(.gas(damage: hurt && offset == 0 ? stats.gasDamage : 0, col: centre.0, row: centre.1))327        }328    }329330    private func finish(_ reason: DigEndReason) {331        ended = reason332        events.append(.ended(reason))333    }334335    // MARK: Result336337    var result: DigRunResult {338        let reason = ended ?? .surfaced339        let value = cargoValue340        let kept = reason == .wrecked ? stats.wreckKeep : 1341        let reached = reason == .core ? DigConfig.coreRow : min(depth, DigConfig.coreRow)342        return DigRunResult(reason: reason, depth: reached, biome: DigBiome.at(row: min(reached, DigConfig.coreRow - 1)), oreCount: cargo.count, oreValue: value,343                            keptFraction: kept, oreCoins: Int((Double(value) * kept).rounded()), findCoins: findCoins, depthCoins: reached / 5,344                            coreCoins: reason == .core ? DigConfig.coreBonus : 0, fossils: fossils, chests: chests, duration: time)345    }346}347348// MARK: - Economy349350nonisolated enum DigEconomy {351    struct Outcome: Equatable, Sendable {352        var isRecord: Bool353        var newSkins: [DigSkin]354    }355356    /// Banks a finished run into the save and unlocks any skins it earned.357    @discardableResult358    static func bank(_ result: DigRunResult, into save: inout DigSave) -> Outcome {359        let isRecord = result.depth > save.bestDepth360        save.bank += result.total361        save.totalBanked += result.total362        save.bestDepth = max(save.bestDepth, result.depth)363        save.runs += 1364        save.fossils += result.fossils365        save.chests += result.chests366        if result.reason == .core { save.coreReached += 1 }367        save.tutorialDone = true368        var unlocked: [DigSkin] = []369        for skin in DigSkin.all where !save.skins.contains(skin.id) && skin.isEarned(by: save) {370            save.skins.append(skin.id)371            unlocked.append(skin)372        }373        return Outcome(isRecord: isRecord, newSkins: unlocked)374    }375376    /// Buys the next level of an upgrade if it is affordable. Returns whether the purchase happened.377    @discardableResult378    static func buy(_ upgrade: DigUpgrade, save: inout DigSave) -> Bool {379        let level = save.level(upgrade)380        guard let cost = upgrade.cost(atLevel: level), save.bank >= cost else { return false }381        save.bank -= cost382        save.upgrades[upgrade.id] = level + 1383        return true384    }385}386387// MARK: - Autoplay bot388389/// A simple look-ahead pilot used for autoplay captures, soak runs and economy tests.390nonisolated enum DigBot {391    static func target(for run: DigRun) -> Double {392        let cols = DigConfig.cols393        let tip = max(Int(run.y.rounded(.down)), -1)394        let here = min(max(Int(run.x.rounded(.down)), 0), cols - 1)395        var best = here, bestScore = -Double.infinity396        for c in 0..<cols {397            var score = -abs(Double(c) + 0.5 - run.x) * 0.9398            for k in 1...9 {399                let tile = run.world.tile(col: c, row: tip + k)400                let near = 1 / Double(k)401                switch tile {402                case .boulder: score -= k <= 7 ? 120 * near : 0403                case .lava: score -= 70 * near404                case .gas: score -= 30 * near405                case .hardRock: score -= 4 * near406                case .fuelCell: score += (run.fuelFraction < 0.9 ? 60 : 12) * near.squareRoot()407                case .repairKit: score += (run.hullFraction < 0.7 ? 40 : 2) * near.squareRoot()408                case .chest: score += 40 * near.squareRoot()409                case .fossil: score += 22 * near.squareRoot()410                case .air: score += 0.6 * near411                default: if let value = tile.oreValue { score += Double(value) * 0.3 * near.squareRoot() }412                }413            }414            // Hazards in the way of the sideways move itself.415            if c != here {416                for between in stride(from: here, through: c, by: c > here ? 1 : -1) {417                    for r in max(tip, 0)...(max(tip, 0) + 1) {418                        let tile = run.world.tile(col: between, row: r)419                        if tile == .lava { score -= 60 } else if tile == .gas { score -= 25 } else if tile == .boulder { score -= 40 }420                    }421                }422            }423            if score > bestScore { bestScore = score; best = c }424        }425        return Double(best) + 0.5426    }427428    /// Plays a whole run headlessly and returns its result.429    static func play(seed: UInt64, stats: DigStats, dt: Double = 1.0 / 60, maxSeconds: Double = 1800) -> DigRunResult {430        let run = DigRun(seed: seed, stats: stats)431        var aim = run.x432        var steps = 0433        while run.ended == nil, run.time < maxSeconds {434            if steps % 6 == 0 { aim = target(for: run) }435            run.step(dt: dt, targetX: aim)436            _ = run.drainEvents()437            steps += 1438        }439        if run.ended == nil { run.surface() }440        return run.result441    }442}443
Files main
Menu

Theme