Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Arcade9// File : Games/DominoCity/DominoRules.swift10// Description : Domino City — pure rules: tuning constants, piece, stage11// and level model, run tracker (objectives register once),12// precision, scoring and stars.13// Module : Games14// Repository : https://git.spboucher.ai/orix-arcade15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293/// Physical and layout constants, in stage units (the stage is 400 × 600, origin bottom-left, y up).94nonisolated enum DominoTuning {95 static let stageWidth = 400.096 static let stageHeight = 600.097 static let groundTop = 40.098 static let dominoWidth = 10.099 static let dominoHeight = 46.0100 static let dominoSpacing = 26.0101 static let blockWidth = 34.0102 static let blockHeight = 24.0103 static let shotRadius = 11.0104 /// Downward acceleration in stage units per second squared.105 static let gravity = 1050.0106 static let minLaunchSpeed = 220.0107 static let maxLaunchSpeed = 740.0108 static let bouncerSpeed = 900.0109 static let maxDynamicPieces = 80110 /// Explosive pieces: seconds between being disturbed and going off, reach and strength of the blast.111 static let fuse = 0.14112 static let blastRadius = 110.0113 static let blastImpulse = 480_000.0114 /// How far from the centre of a switch or beacon a ball may pass and still score precision.115 static let bullseyeRadius = 5.0116 static let closeRadius = 11.0117118 static func launchSpeed(power: Double) -> Double {119 minLaunchSpeed + power.clamped(0, 1) * (maxLaunchSpeed - minLaunchSpeed)120 }121122 /// Ballistic position of a launched ball before its first contact.123 static func trajectoryPoint(from origin: (x: Double, y: Double), angleDegrees: Double, power: Double, time: Double) -> (x: Double, y: Double) {124 let speed = launchSpeed(power: power)125 let radians = angleDegrees * .pi / 180126 return (origin.x + cos(radians) * speed * time, origin.y + sin(radians) * speed * time - 0.5 * gravity * time * time)127 }128}129130nonisolated enum DominoPieceKind: String, Sendable, CaseIterable {131 /// Static slab (rooftop, street ledge, ramp when rotated, wall).132 case ledge133 case domino, goldDomino134 case block, goldBlock135 /// Loose rolling ball; `held` balls stay parked until their switch fires or, with no switch, until something touches them.136 case ball137 /// Loose plank, used as a bridge.138 case plank139 /// Neon beacon: a target that lights up when anything touches it.140 case bell141 /// Optional bonus pickup.142 case gem143 /// Bullseye switch: opens its linked gates and releases its linked held balls.144 case switchPad145 /// Static barrier removed by a switch.146 case gate147 /// Hazard: swallows any ball that touches it.148 case tar149 /// Trampoline: throws balls upward at a fixed speed.150 case bouncer151 /// Crane ball hanging from `anchor`; frozen while `held`.152 case wreckingBall153 /// Plank on a pivot: push one end down and the other end comes up.154 case seesaw155 /// Static belt that carries whatever touches it at `speed` (positive = towards its local +x).156 case conveyor157 /// Platform that travels back and forth by itself.158 case mover159 /// Explosive crate and explosive domino: go off shortly after being disturbed and throw everything around them.160 case tnt, tntDomino161162 var isTarget: Bool { self == .goldDomino || self == .goldBlock || self == .bell }163 var isExplosive: Bool { self == .tnt || self == .tntDomino }164 /// Free-moving rigid bodies that count toward the chain when disturbed.165 var isDynamic: Bool {166 switch self {167 case .domino, .goldDomino, .block, .goldBlock, .ball, .plank, .wreckingBall, .tnt, .tntDomino: true168 default: false169 }170 }171 /// Pieces introduced by 2.0.172 var isMechanism: Bool { self == .seesaw || self == .conveyor || self == .mover || isExplosive }173}174175nonisolated struct DominoPiece: Sendable, Equatable, Identifiable {176 var id: Int177 var kind: DominoPieceKind178 /// Centre.179 var x: Double180 var y: Double181 var w: Double182 var h: Double183 /// Degrees, counter-clockwise.184 var angle = 0.0185 /// For switches: ids of the gates to open and held pieces to release.186 var links: [Int] = []187 var held = false188 var anchorX = 0.0189 var anchorY = 0.0190 /// Targets: the stage they belong to. Other pieces: unused.191 var stage = 0192 /// Gates and held pieces: opened or released when this stage begins (0 = never by a stage).193 var opensAtStage = 0194 /// Conveyors: belt speed in units per second.195 var speed = 0.0196 /// Movers: displacement at the far end of the path, seconds for a round trip, and where in the trip it starts (0…1).197 var travelX = 0.0198 var travelY = 0.0199 var period = 0.0200 var phase = 0.0201 /// Seesaws: how far the plank may tilt either way, in degrees.202 var limit = 0.0203}204205/// One phase of a level: where the launcher stands, how many impulses it brings, and which 400 × 600 frame the camera shows.206nonisolated struct DominoStage: Sendable, Equatable {207 var launcherX: Double208 var launcherY: Double209 var impulses: Int210 /// Bottom-left corner of the frame, in stage units.211 var originX = 0.0212 var originY = 0.0213}214215/// How well a ball met the centre of a switch or beacon.216nonisolated enum DominoPrecision: Int, Sendable, Equatable {217 case none, close, bullseye218219 var points: Int {220 switch self {221 case .none: 0222 case .close: 100223 case .bullseye: 250224 }225 }226227 /// `miss` is the distance between the target's centre and the line the ball was travelling on.228 static func grade(miss: Double) -> DominoPrecision {229 miss <= DominoTuning.bullseyeRadius ? .bullseye : miss <= DominoTuning.closeRadius ? .close : .none230 }231}232233nonisolated struct DominoShot: Sendable, Equatable {234 /// Launch direction in degrees (0 = right, 90 = up).235 var angle: Double236 /// 0…1.237 var power: Double238 /// Seconds the bot waits once the impulse is ready.239 var delay = 0.5240 /// The bot holds this shot until the given stage has begun.241 var stage = 0242}243244nonisolated struct DominoLevel: Sendable, Equatable, Identifiable {245 var id: Int246 var name: String247 var hint: String248 /// At least one. Clearing the targets of a stage starts the next one.249 var stages: [DominoStage]250 var pieces: [DominoPiece]251 /// Reference solution, also played by the autoplay bot: shots in the order they are fired, across stages.252 var solution: [DominoShot]253 /// Chain length reached by the reference solution; star thresholds derive from it.254 var referenceChain: Int255 /// Pieces that must have joined the chain for the level to count as cleared: the chain reaction is the objective, not a lucky direct hit.256 var chainGoal: Int257258 var launcherX: Double { stages[0].launcherX }259 var launcherY: Double { stages[0].launcherY }260 /// Impulse budget over all stages.261 var impulses: Int { stages.reduce(0) { $0 + $1.impulses } }262 /// Impulses used by the reference solution.263 var par: Int { solution.count }264 var isMultiStage: Bool { stages.count > 1 }265266 var targets: [DominoPiece] { pieces.filter { $0.kind.isTarget } }267 var gems: [DominoPiece] { pieces.filter { $0.kind == .gem } }268 var dynamicCount: Int { pieces.filter { $0.kind.isDynamic }.count }269 func targets(inStage stage: Int) -> [DominoPiece] { pieces.filter { $0.kind.isTarget && $0.stage == stage } }270271 /// Horizontal and vertical extent of every stage frame.272 var bounds: (minX: Double, maxX: Double, minY: Double, maxY: Double) {273 let xs = stages.map(\.originX), ys = stages.map(\.originY)274 return (xs.min() ?? 0, (xs.max() ?? 0) + DominoTuning.stageWidth, ys.min() ?? 0, (ys.max() ?? 0) + DominoTuning.stageHeight)275 }276277 private func referenceStats(chainShare: Double, impulsesUsed: Int) -> DominoRunStats {278 DominoRunStats(targetsHit: targets.count, targetsTotal: targets.count, chain: max(chainGoal, Int(Double(referenceChain) * chainShare)),279 gems: 0, impulsesUsed: impulsesUsed, impulseBudget: impulses, chainGoal: chainGoal)280 }281282 var threeStarScore: Int { DominoRules.score(referenceStats(chainShare: 0.8, impulsesUsed: par)) }283284 /// The least a clear can score: every target, the chain goal, no impulse to spare.285 var bareClearScore: Int { DominoRules.score(referenceStats(chainShare: 0, impulsesUsed: impulses)) }286287 /// Halfway between a bare clear and the three-star mark.288 var twoStarScore: Int { (bareClearScore + threeStarScore) / 2 }289290 /// Structural problems, empty when the level is well formed. Checked by the unit tests for every level.291 func validationProblems() -> [String] {292 var problems: [String] = []293 let ids = pieces.map(\.id)294 if Set(ids).count != ids.count { problems.append("duplicate piece ids") }295 if targets.isEmpty { problems.append("no targets") }296 if stages.isEmpty { return problems + ["no stage"] }297 if stages.contains(where: { $0.impulses < 1 }) || par < 1 || par >= impulses { problems.append("bad impulse budget: the reference must leave an impulse to spare") }298 if solution.contains(where: { !(0...1).contains($0.power) }) { problems.append("solution power out of range") }299 if dynamicCount > DominoTuning.maxDynamicPieces { problems.append("too many dynamic pieces") }300 let area = bounds301 for (index, stage) in stages.enumerated() {302 if !(stage.originX...stage.originX + DominoTuning.stageWidth).contains(stage.launcherX)303 || !(stage.originY + DominoTuning.groundTop...stage.originY + DominoTuning.stageHeight).contains(stage.launcherY) {304 problems.append("launcher of stage \(index) outside its frame")305 }306 if targets(inStage: index).isEmpty { problems.append("stage \(index) has no target") }307 }308 let byID = Dictionary(zip(ids, pieces), uniquingKeysWith: { a, _ in a })309 for piece in pieces {310 if piece.kind != .ledge, !(area.minX - 20...area.maxX + 20).contains(piece.x) || !(area.minY...area.maxY + 60).contains(piece.y) {311 problems.append("piece \(piece.id) outside the stage")312 }313 if piece.w <= 0 || piece.h <= 0 { problems.append("piece \(piece.id) has no size") }314 if piece.kind.isTarget, !stages.indices.contains(piece.stage) { problems.append("target \(piece.id) belongs to a missing stage") }315 if piece.opensAtStage != 0, !(1..<max(stages.count, 1)).contains(piece.opensAtStage) { problems.append("piece \(piece.id) waits for a missing stage") }316 if piece.kind == .switchPad {317 if piece.links.isEmpty { problems.append("switch \(piece.id) has no links") }318 for link in piece.links {319 guard let linked = byID[link] else { problems.append("switch \(piece.id) links to a missing piece"); continue }320 if !(linked.kind == .gate || linked.held) { problems.append("switch \(piece.id) links to a piece it cannot affect") }321 }322 } else if !piece.links.isEmpty {323 problems.append("piece \(piece.id) is not a switch but has links")324 }325 let linked = pieces.contains { $0.kind == .switchPad && $0.links.contains(piece.id) } || piece.opensAtStage > 0326 // A parked ball without a switch is released by the first touch; anything else held needs a switch or a stage.327 if piece.held, piece.kind != .ball, !linked { problems.append("held piece \(piece.id) can never be released") }328 if piece.kind == .gate, !linked { problems.append("gate \(piece.id) can never open") }329 if piece.kind == .conveyor, piece.speed == 0 { problems.append("conveyor \(piece.id) does not move") }330 if piece.kind == .mover, piece.period <= 0 || (piece.travelX == 0 && piece.travelY == 0) { problems.append("mover \(piece.id) does not move") }331 }332 if referenceChain < 1 || referenceChain > dynamicCount { problems.append("reference chain out of range") }333 if chainGoal < 1 || chainGoal > referenceChain { problems.append("chain goal out of range") }334 if !(bareClearScore < twoStarScore && twoStarScore < threeStarScore) { problems.append("star thresholds out of order") }335 return problems336 }337}338339nonisolated struct DominoRunStats: Sendable, Equatable {340 var targetsHit: Int341 var targetsTotal: Int342 var chain: Int343 var gems: Int344 var impulsesUsed: Int345 var impulseBudget: Int346 /// Minimum chain for a clear.347 var chainGoal = 0348 /// Precision points earned on switches and beacons, and how many of them were dead centre.349 var precision = 0350 var bullseyes = 0351 /// Explosive pieces that went off.352 var blasts = 0353354 var targetsDone: Bool { targetsTotal > 0 && targetsHit >= targetsTotal }355 var cleared: Bool { targetsDone && chain >= chainGoal }356 var impulsesLeft: Int { max(0, impulseBudget - impulsesUsed) }357 var completion: Double { targetsTotal == 0 ? 0 : Double(targetsHit) / Double(targetsTotal) }358}359360nonisolated enum DominoRules {361 static let targetPoints = 500362 static let chainPoints = 40363 static let gemPoints = 300364 static let clearBonus = 1000365 static let spareImpulsePoints = 600366367 static func score(_ stats: DominoRunStats) -> Int {368 var total = stats.targetsHit * targetPoints + stats.chain * chainPoints + stats.gems * gemPoints + stats.precision369 if stats.cleared { total += clearBonus + stats.impulsesLeft * spareImpulsePoints }370 return total371 }372373 /// 0 when the level is not cleared; otherwise 1…3 from the level's score thresholds.374 static func stars(level: DominoLevel, stats: DominoRunStats) -> Int {375 guard stats.cleared else { return 0 }376 let total = score(stats)377 return total >= level.threeStarScore ? 3 : total >= level.twoStarScore ? 2 : 1378 }379}380381/// Bookkeeping for one attempt. Every registration returns `true` only the first time, so objectives can never count twice.382nonisolated struct DominoRunTracker: Sendable, Equatable {383 let targetIDs: Set<Int>384 let gemIDs: Set<Int>385 let chainIDs: Set<Int>386 let chainGoal: Int387 private let stageTargets: [Set<Int>]388 private let stageImpulses: [Int]389 private(set) var impulseBudget: Int390 private(set) var stage = 0391 private(set) var hitTargets: Set<Int> = []392 private(set) var collectedGems: Set<Int> = []393 private(set) var chained: Set<Int> = []394 private(set) var firedSwitches: Set<Int> = []395 private(set) var graded: Set<Int> = []396 private(set) var blasted: Set<Int> = []397 private(set) var impulsesUsed = 0398 private(set) var precision = 0399 private(set) var bullseyes = 0400401 init(level: DominoLevel) {402 targetIDs = Set(level.targets.map(\.id))403 gemIDs = Set(level.gems.map(\.id))404 chainIDs = Set(level.pieces.filter { $0.kind.isDynamic }.map(\.id))405 chainGoal = level.chainGoal406 stageTargets = level.stages.indices.map { stage in Set(level.targets(inStage: stage).map(\.id)) }407 stageImpulses = level.stages.map(\.impulses)408 impulseBudget = level.stages.first?.impulses ?? 0409 }410411 var impulsesLeft: Int { impulseBudget - impulsesUsed }412 var stageCount: Int { stageTargets.count }413 var isLastStage: Bool { stage >= stageTargets.count - 1 }414 var stageDone: Bool { stageTargets.indices.contains(stage) && stageTargets[stage].isSubset(of: hitTargets) }415 var targetsDone: Bool { !targetIDs.isEmpty && hitTargets.count == targetIDs.count }416 var cleared: Bool { targetsDone && chained.count >= chainGoal }417 var stats: DominoRunStats {418 DominoRunStats(targetsHit: hitTargets.count, targetsTotal: targetIDs.count, chain: chained.count, gems: collectedGems.count,419 impulsesUsed: impulsesUsed, impulseBudget: stageImpulses.reduce(0, +), chainGoal: chainGoal, precision: precision,420 bullseyes: bullseyes, blasts: blasted.count)421 }422423 mutating func registerTarget(_ id: Int) -> Bool { targetIDs.contains(id) && hitTargets.insert(id).inserted }424 mutating func registerGem(_ id: Int) -> Bool { gemIDs.contains(id) && collectedGems.insert(id).inserted }425 mutating func registerChain(_ id: Int) -> Bool { chainIDs.contains(id) && chained.insert(id).inserted }426 mutating func registerSwitch(_ id: Int) -> Bool { firedSwitches.insert(id).inserted }427 mutating func registerBlast(_ id: Int) -> Bool { blasted.insert(id).inserted }428429 /// Precision is graded once per switch or beacon, by the first ball that reaches it.430 mutating func registerPrecision(_ id: Int, _ grade: DominoPrecision) -> Bool {431 guard graded.insert(id).inserted else { return false }432 precision += grade.points433 if grade == .bullseye { bullseyes += 1 }434 return true435 }436437 /// Consumes one impulse; `false` when the budget is spent.438 mutating func useImpulse() -> Bool {439 guard impulsesUsed < impulseBudget else { return false }440 impulsesUsed += 1441 return true442 }443444 /// Moves to the next stage and adds its impulses to what is left. `false` on the last stage.445 mutating func advanceStage() -> Bool {446 guard !isLastStage else { return false }447 stage += 1448 impulseBudget += stageImpulses[stage]449 return true450 }451}452453nonisolated struct DominoResult: Sendable, Equatable {454 var levelID: Int455 var stats: DominoRunStats456 var score: Int457 var stars: Int458 var duration: TimeInterval459460 var cleared: Bool { stats.cleared }461462 init(level: DominoLevel, stats: DominoRunStats, duration: TimeInterval) {463 levelID = level.id464 self.stats = stats465 score = DominoRules.score(stats)466 stars = DominoRules.stars(level: level, stats: stats)467 self.duration = duration468 }469}470