Repository Public License
1// ORIX Alarm2// File: Packages/AlarmCore/Tests/AlarmCoreTests/HardwareAndCircuitMissionTests.swift3// Description: Tests for the Step Challenge progress logic, the Logic Gates engine and the Maze engine (thousands of seeds).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import XCTest8@testable import AlarmCore910final class StepChallengeTests: XCTestCase {11 func testNormalWalkCompletesAtGoal() {12 var c = StepChallenge(goal: 30)13 var t = 0.014 for reading in stride(from: 4, through: 40, by: 4) {15 t += 2.516 c.ingest(cumulative: reading, at: t)17 }18 XCTAssertTrue(c.isComplete)19 XCTAssertEqual(c.steps, 30)20 XCTAssertEqual(c.remaining, 0)21 XCTAssertEqual(c.progress, 1)22 XCTAssertEqual(c.rejectedReadings, 0)23 }2425 func testProgressIsMonotonicAndNeverExceedsGoal() {26 var rng = SeededGenerator(seed: 7)27 for _ in 0..<500 {28 var c = StepChallenge(goal: Int.random(in: 10...300, using: &rng))29 var previous = 030 var t = 0.031 for _ in 0..<200 {32 t += Double.random(in: 0...6, using: &rng)33 c.ingest(cumulative: Int.random(in: -50...5000, using: &rng), at: t)34 XCTAssertGreaterThanOrEqual(c.steps, previous)35 XCTAssertLessThanOrEqual(c.steps, c.goal)36 previous = c.steps37 }38 }39 }4041 func testDecreasingReadingKeepsProgressAndRebases() {42 var c = StepChallenge(goal: 50)43 c.ingest(cumulative: 10, at: 3)44 XCTAssertEqual(c.steps, 10)45 XCTAssertEqual(c.ingest(cumulative: 2, at: 5), 0)46 XCTAssertEqual(c.steps, 10)47 XCTAssertEqual(c.rejectedReadings, 1)48 XCTAssertEqual(c.ingest(cumulative: 6, at: 8), 4)49 XCTAssertEqual(c.steps, 14)50 }5152 func testAbsurdJumpIsCapped() {53 var c = StepChallenge(goal: 300)54 // 250 steps reported one second after the start: only the burst allowance plus 5 steps/s is credited.55 XCTAssertEqual(c.ingest(cumulative: 250, at: 1), StepChallenge.burstAllowance + 5)56 XCTAssertFalse(c.isComplete)57 XCTAssertEqual(c.rejectedReadings, 1)58 // The same reading again credits nothing more.59 XCTAssertEqual(c.ingest(cumulative: 250, at: 2), 0)60 }6162 func testUnknownBaselineUsesFirstReading() {63 var c = StepChallenge(goal: 20, baseline: nil)64 XCTAssertEqual(c.ingest(cumulative: 8_431, at: 0), 0)65 XCTAssertEqual(c.ingest(cumulative: 8_437, at: 3), 6)66 XCTAssertEqual(c.steps, 6)67 }6869 func testReadingsAfterCompletionAreIgnoredAndGoalIsClamped() {70 var c = StepChallenge(goal: 0)71 XCTAssertEqual(c.goal, 1)72 c.ingest(cumulative: 3, at: 2)73 XCTAssertTrue(c.isComplete)74 XCTAssertEqual(c.ingest(cumulative: 9, at: 4), 0)75 XCTAssertEqual(c.steps, 1)76 }7778 func testTimeGoingBackwardsDoesNotCreditMore() {79 var c = StepChallenge(goal: 300)80 c.ingest(cumulative: 5, at: 10)81 XCTAssertEqual(c.ingest(cumulative: 105, at: 4), StepChallenge.burstAllowance)82 }83}8485final class LogicGatesEngineTests: XCTestCase {86 typealias Engine = LogicGatesEngine8788 func testGateTruthTables() {89 XCTAssertEqual([[false, false], [false, true], [true, false], [true, true]].map(Engine.GateKind.and.output), [false, false, false, true])90 XCTAssertEqual([[false, false], [false, true], [true, false], [true, true]].map(Engine.GateKind.or.output), [false, true, true, true])91 XCTAssertEqual([[false, false], [false, true], [true, false], [true, true]].map(Engine.GateKind.xor.output), [false, true, true, false])92 XCTAssertEqual([[false], [true]].map(Engine.GateKind.not.output), [true, false])93 }9495 func testEvaluateKnownCircuit() {96 // lamp = NOT(A AND B) XOR C97 let puzzle = Engine.Puzzle(switchCount: 3, gates: [98 .init(kind: .and, inputs: [.input(0), .input(1)], layer: 1),99 .init(kind: .not, inputs: [.gate(0)], layer: 2),100 .init(kind: .xor, inputs: [.gate(1), .input(2)], layer: 3),101 ], target: true, initialSwitches: [false, false, true])102 XCTAssertEqual(Engine.evaluate(puzzle, switches: [true, true, false]), [true, false, false])103 XCTAssertEqual(Engine.evaluate(puzzle, switches: [true, false, false]), [false, true, true])104 XCTAssertFalse(Engine.validate(puzzle, answer: puzzle.initialSwitches))105 XCTAssertTrue(Engine.validate(puzzle, answer: [true, true, true]))106 XCTAssertFalse(Engine.validate(puzzle, answer: [true, true]))107 XCTAssertEqual(Engine.solutions(puzzle).count, 4)108 }109110 func testThousandsOfSeedsAreWellFormedSolvableAndNotPresolved() {111 var gateCounts: [Int: Set<Int>] = [:]112 var targets: Set<Bool> = []113 for level in 1...4 {114 for seed in 0..<3000 {115 let round = seed % 5116 let p = Engine.generate(level: level, round: round, seed: UInt64(seed) &* 0x9E37_79B9 &+ 17)117 gateCounts[level, default: []].insert(p.gates.count)118 if level == 4 { targets.insert(p.target) }119 XCTAssertTrue((2...5).contains(p.switchCount))120 XCTAssertEqual(p.initialSwitches.count, p.switchCount)121 XCTAssertLessThanOrEqual(p.layerCount, Engine.maxLayers)122 // Solvable, and not solved in the starting position.123 XCTAssertFalse(Engine.solutions(p).isEmpty, "level \(level) seed \(seed)")124 XCTAssertFalse(Engine.validate(p, answer: p.initialSwitches), "level \(level) seed \(seed)")125 if level < 4 { XCTAssertTrue(p.target) }126 // Tree shape: inputs reference earlier gates only, every switch and gate output used exactly once,127 // switches met in left-to-right order.128 var usedInputs: [Int] = []129 var usedGates: [Int] = []130 for (g, gate) in p.gates.enumerated() {131 XCTAssertEqual(gate.inputs.count, gate.kind.inputCount)132 var deepest = 0133 for signal in gate.inputs {134 switch signal {135 case .input(let i): usedInputs.append(i)136 case .gate(let j):137 XCTAssertLessThan(j, g); usedGates.append(j); deepest = max(deepest, p.gates[j].layer)138 if gate.kind == .not { XCTAssertNotEqual(p.gates[j].kind, .not) }139 }140 }141 XCTAssertEqual(gate.layer, deepest + 1)142 }143 XCTAssertEqual(usedInputs.sorted(), Array(0..<p.switchCount))144 XCTAssertEqual(usedGates.sorted(), Array(0..<(p.gates.count - 1)))145 XCTAssertEqual(leafOrder(p), Array(0..<p.switchCount))146 switch level {147 case 1: XCTAssertEqual(p.gates.count, 1); XCTAssertTrue(p.kinds.isSubset(of: [.and, .or]))148 case 2: XCTAssertEqual(p.gates.count, 2); XCTAssertTrue(p.kinds.isSubset(of: [.and, .or]))149 case 3: XCTAssertEqual(p.gates.count, 3); XCTAssertFalse(p.kinds.isDisjoint(with: [.not, .xor]))150 default: XCTAssertTrue((4...5).contains(p.gates.count)); XCTAssertFalse(p.kinds.isDisjoint(with: [.not, .xor]))151 }152 }153 }154 XCTAssertEqual(gateCounts[4], [4, 5])155 XCTAssertEqual(targets, [true, false])156 }157158 private func leafOrder(_ p: Engine.Puzzle) -> [Int] {159 func leaves(_ s: Engine.Signal) -> [Int] {160 switch s {161 case .input(let i): [i]162 case .gate(let g): p.gates[g].inputs.flatMap(leaves)163 }164 }165 return leaves(.gate(p.gates.count - 1))166 }167168 func testSameSeedSamePuzzleAndRoundsDiffer() {169 for level in 1...4 {170 XCTAssertEqual(Engine.generate(level: level, round: 0, seed: 42), Engine.generate(level: level, round: 0, seed: 42))171 }172 let distinct = Set((0..<20).map { Engine.generate(level: 4, round: $0, seed: 42) })173 XCTAssertGreaterThan(distinct.count, 10)174 }175}176177final class MazeEngineTests: XCTestCase {178 typealias Engine = MazeEngine179180 func testSizesAndKeysByLevel() {181 XCTAssertEqual((0...5).map(Engine.size(forLevel:)), [6, 6, 8, 10, 12, 12])182 XCTAssertEqual((1...4).map(Engine.keyCount(forLevel:)), [0, 0, 1, 2])183 }184185 func testThousandsOfSeedsArePerfectAndSolvable() {186 for level in 1...4 {187 let n = Engine.size(forLevel: level)188 for seed in 0..<1500 {189 let p = Engine.generate(level: level, round: seed % 4, seed: UInt64(seed) &* 0x1234_5677 &+ 3)190 XCTAssertEqual(p.width, n); XCTAssertEqual(p.height, n)191 XCTAssertNotEqual(p.start, p.exit)192 // Perfect maze: every cell reachable and exactly cells - 1 passages (a spanning tree), walls symmetric.193 let distance = Engine.distances(in: p, from: p.start)194 XCTAssertFalse(distance.contains(-1), "level \(level) seed \(seed)")195 var openings = 0196 for y in 0..<n {197 for x in 0..<n {198 let cell = Engine.Cell(x: x, y: y)199 for d in Engine.Direction.allCases where p.isOpen(cell, d) {200 openings += 1201 XCTAssertTrue(p.contains(cell.moved(d)))202 XCTAssertTrue(p.isOpen(cell.moved(d), d.opposite))203 }204 }205 }206 XCTAssertEqual(openings, 2 * (n * n - 1))207 // Keys: right count, distinct, reachable, never on the start or the exit.208 XCTAssertEqual(p.keys.count, Engine.keyCount(forLevel: level))209 XCTAssertEqual(Set(p.keys).count, p.keys.count)210 for key in p.keys {211 XCTAssertTrue(p.contains(key)); XCTAssertNotEqual(key, p.start); XCTAssertNotEqual(key, p.exit)212 XCTAssertGreaterThan(distance[p.index(key)], 0)213 }214 // The solver finds a path, the path validates, and it is at least as long as the direct route.215 guard let path = Engine.shortestPath(p) else { XCTFail("unsolvable: level \(level) seed \(seed)"); continue }216 XCTAssertTrue(Engine.validate(p, answer: path))217 XCTAssertEqual(Engine.shortestPathLength(p), path.count)218 XCTAssertGreaterThanOrEqual(path.count, distance[p.index(p.exit)])219 if p.keys.isEmpty { XCTAssertEqual(path.count, distance[p.index(p.exit)]) }220 XCTAssertGreaterThanOrEqual(path.count, 2 * (n - 1))221 }222 }223 }224225 func testValidateRejectsWallsMissingKeysAndWrongEnd() {226 let p = Engine.generate(level: 4, round: 0, seed: 99)227 let path = Engine.shortestPath(p)!228 XCTAssertTrue(Engine.validate(p, answer: path))229 XCTAssertFalse(Engine.validate(p, answer: Array(path.dropLast())))230 XCTAssertFalse(Engine.validate(p, answer: []))231 // The direct route to the exit skips at least one key (keys are dead ends off the route or the route is longer).232 var noKeys = p; noKeys.keys = []233 let direct = Engine.shortestPath(noKeys)!234 if direct.count < path.count { XCTAssertFalse(Engine.validate(p, answer: direct)) }235 // A move through a wall is rejected.236 let blocked = Engine.Direction.allCases.first { !p.isOpen(p.start, $0) }!237 XCTAssertFalse(Engine.validate(p, answer: [blocked] + path))238 }239240 func testSlideStopsAtWallsJunctionsKeysAndExit() {241 for seed in 0..<300 {242 let p = Engine.generate(level: 1 + seed % 4, round: 0, seed: UInt64(seed))243 for y in 0..<p.height {244 for x in 0..<p.width {245 let cell = Engine.Cell(x: x, y: y)246 for d in Engine.Direction.allCases {247 let path = Engine.slide(in: p, from: cell, d)248 XCTAssertEqual(path.isEmpty, !p.isOpen(cell, d))249 var current = cell250 for (i, next) in path.enumerated() {251 XCTAssertTrue(p.isOpen(current, d)); XCTAssertEqual(current.moved(d), next)252 current = next253 let sideways = p.openDirections(next).contains { $0 != d && $0 != d.opposite }254 let mustStop = sideways || next == p.exit || p.keys.contains(next) || !p.isOpen(next, d)255 XCTAssertEqual(mustStop, i == path.count - 1)256 }257 }258 }259 }260 }261 }262263 func testEveryMazeCanBeSolvedWithSlidesOnly() {264 // The swipe control only offers slides: a breadth-first search over slide stops must still reach every key and the exit.265 for seed in 0..<400 {266 let p = Engine.generate(level: 1 + seed % 4, round: seed % 3, seed: UInt64(seed) &+ 5000)267 var seen: Set<Engine.Cell> = [p.start]268 var crossed: Set<Engine.Cell> = [p.start]269 var queue = [p.start]270 while let cell = queue.popLast() {271 for d in Engine.Direction.allCases {272 let path = Engine.slide(in: p, from: cell, d)273 crossed.formUnion(path)274 if let stop = path.last, seen.insert(stop).inserted { queue.append(stop) }275 }276 }277 XCTAssertTrue(seen.contains(p.exit))278 XCTAssertTrue(Set(p.keys).isSubset(of: seen))279 XCTAssertEqual(crossed.count, p.width * p.height)280 }281 }282283 func testDeterministic() {284 for level in 1...4 {285 XCTAssertEqual(Engine.generate(level: level, round: 1, seed: 7), Engine.generate(level: level, round: 1, seed: 7))286 XCTAssertNotEqual(Engine.generate(level: level, round: 1, seed: 7), Engine.generate(level: level, round: 2, seed: 7))287 }288 }289}290