Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Arcade9// File : Tests/TrafficMayhemTests.swift10// Description : Traffic Mayhem logic tests — lane routing, path conflicts,11// kinematics, collision detection and prediction, spawn12// fairness, scoring, tutorial, long sessions and save data.13// Module : Tests14// 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 XCTest92@testable import ORIXArcade9394final class TrafficMayhemTests: XCTestCase {95 // MARK: Helpers9697 /// Runs a simulation with the bot playing; returns the final sim and every event.98 private func botRun(layout: Int, mode: TrafficSim.Mode = .endless, seed: UInt64, seconds: Double,99 each: ((TrafficSim) -> Void)? = nil) -> (TrafficSim, [TrafficEvent]) {100 var sim = TrafficSim(layout: TrafficLayout.layout(layout), mode: mode, seed: seed)101 var events: [TrafficEvent] = []102 var t = 0.0103 while t < seconds, !sim.isOver {104 for id in TrafficBot.choose(sim) { sim.launch(id, events: &events) }105 events += sim.advance(0.1)106 each?(sim)107 t += 0.1108 }109 return (sim, events)110 }111112 private func gap(_ ka: VehicleKind, _ pa: TrafficPath, _ sa: Double, _ kb: VehicleKind, _ pb: TrafficPath, _ sb: Double) -> Double {113 let ha = pa.heading(at: sa), hb = pb.heading(at: sb)114 return TrafficSim.bodyGap(ka, (pa.point(at: sa), Vec2(x: cos(ha), y: sin(ha))), kb, (pb.point(at: sb), Vec2(x: cos(hb), y: sin(hb)))).0115 }116117 /// True when two car bodies can touch while both are inside the junction.118 private func conflict(_ a: TrafficPath, _ b: TrafficPath) -> Bool {119 var sa = a.stopS120 while sa <= a.exitS + 13 {121 var sb = b.stopS122 while sb <= b.exitS + 13 {123 if gap(.car, a, sa, .car, b, sb) < 0 { return true }124 sb += 3125 }126 sa += 3127 }128 return false129 }130131 private func path(_ layout: TrafficLayout, lane: Int, _ turn: TrafficTurn, nth: Int = 0) -> TrafficPath {132 layout.lanes[lane].paths.map { layout.paths[$0] }.filter { $0.turn == turn }[nth]133 }134135 private func count(_ events: [TrafficEvent], _ match: (TrafficEvent) -> Bool) -> Int { events.filter(match).count }136 private func isCrash(_ e: TrafficEvent) -> Bool { if case .crashed = e { true } else { false } }137 private func isHeartLost(_ e: TrafficEvent) -> Bool { if case .heartLost = e { true } else { false } }138 private func isStormOff(_ e: TrafficEvent) -> Bool { if case .stormedOff = e { true } else { false } }139 private func isImpatient(_ e: TrafficEvent) -> Bool { if case .impatient = e { true } else { false } }140141 // MARK: Routing and geometry142143 func testThreeDistinctLayouts() {144 XCTAssertEqual(TrafficLayout.all.count, 3)145 XCTAssertEqual(TrafficLayout.all.map(\.controlledLanes.count), [4, 3, 6])146 XCTAssertEqual(TrafficLayout.all.map { $0.lanes.filter(\.autonomous).count }, [0, 2, 0])147 XCTAssertEqual(Set(TrafficLayout.all.map(\.name)).count, 3)148 }149150 func testLaneRoutingForEveryLayout() {151 for layout in TrafficLayout.all {152 for (index, p) in layout.paths.enumerated() {153 XCTAssertEqual(p.id, index)154 XCTAssertTrue(layout.lanes[p.lane].paths.contains(p.id), "\(layout.name) path \(p.id) belongs to its lane")155 XCTAssertLessThan(p.stopS, p.exitS)156 XCTAssertLessThan(p.exitS + 300, p.length, "the exit tail leaves the screen")157 // Arc length is consistent with the sampled geometry and the curve has no kinks.158 var previous = p.heading(at: 10)159 var s = 12.0160 while s < p.length - 10 {161 let h = p.heading(at: s)162 var delta = abs(h - previous)163 if delta > .pi { delta = 2 * .pi - delta }164 XCTAssertLessThan(delta, 0.2, "\(layout.name) path \(p.id) turns smoothly at s=\(s)")165 XCTAssertEqual(p.point(at: s).distance(to: p.point(at: s + 2)), 2, accuracy: 0.05)166 previous = h167 s += 2168 }169 // Every path starts off-screen and ends off-screen.170 XCTAssertTrue(abs(p.points[0].x) >= 250 || abs(p.points[0].y) >= 460)171 let end = p.point(at: p.length)172 XCTAssertTrue(abs(end.x) >= 300 || abs(end.y) >= 460)173 }174 for lane in layout.lanes where !lane.autonomous {175 let paths = lane.paths.map { layout.paths[$0] }176 for p in paths {177 XCTAssertEqual(p.stopS, paths[0].stopS, accuracy: 0.001, "paths of one lane share the stop line")178 XCTAssertLessThan(p.point(at: p.stopS - 20).distance(to: paths[0].point(at: p.stopS - 20)), 0.001)179 }180 }181 // Paths that merge into one exit lane end up on the same line, heading the same way.182 for a in layout.paths {183 for b in layout.paths where b.exitLane == a.exitLane {184 XCTAssertLessThan(a.point(at: a.exitS + 60).distance(to: b.point(at: b.exitS + 60)), 0.5, "\(layout.name) exit lane \(a.exitLane)")185 }186 }187 }188 }189190 func testFourCornersTurnsDriveOnTheRight() {191 let layout = TrafficLayout.layout(0)192 let straight = path(layout, lane: 0, .straight), left = path(layout, lane: 0, .left), right = path(layout, lane: 0, .right)193 XCTAssertEqual(straight.point(at: straight.exitS).x, 13, accuracy: 0.01)194 XCTAssertEqual(straight.point(at: straight.exitS).y, 42, accuracy: 0.01)195 XCTAssertEqual(left.point(at: left.exitS).x, -42, accuracy: 0.01)196 XCTAssertEqual(left.point(at: left.exitS).y, 13, accuracy: 0.01, "left turn ends in the westbound lane")197 XCTAssertEqual(right.point(at: right.exitS).x, 42, accuracy: 0.01)198 XCTAssertEqual(right.point(at: right.exitS).y, -13, accuracy: 0.01, "right turn ends in the eastbound lane")199 XCTAssertEqual(abs(left.heading(at: left.exitS + 30)), .pi, accuracy: 0.01)200 XCTAssertEqual(right.heading(at: right.exitS + 30), 0, accuracy: 0.01)201 }202203 func testPathConflictTable() {204 let l = TrafficLayout.layout(0)205 // Lanes: 0 south, 1 east, 2 north, 3 west.206 XCTAssertFalse(conflict(path(l, lane: 0, .straight), path(l, lane: 2, .straight)), "opposing straights pass each other")207 XCTAssertTrue(conflict(path(l, lane: 0, .straight), path(l, lane: 3, .straight)), "crossing straights conflict")208 XCTAssertTrue(conflict(path(l, lane: 0, .straight), path(l, lane: 1, .straight)))209 XCTAssertTrue(conflict(path(l, lane: 0, .left), path(l, lane: 2, .straight)), "a left turn crosses oncoming traffic")210 XCTAssertFalse(conflict(path(l, lane: 0, .right), path(l, lane: 2, .straight)), "a right turn stays clear of oncoming traffic")211 XCTAssertTrue(conflict(path(l, lane: 0, .right), path(l, lane: 3, .straight)), "a right turn merges into the crossing lane")212 XCTAssertFalse(conflict(path(l, lane: 0, .right), path(l, lane: 1, .right)))213 XCTAssertFalse(conflict(path(l, lane: 0, .right), path(l, lane: 2, .right)))214 // The table is symmetric.215 for a in l.paths { for b in l.paths where a.lane != b.lane { XCTAssertEqual(conflict(a, b), conflict(b, a)) } }216217 let m = TrafficLayout.layout(1)218 XCTAssertTrue(conflict(m.paths[0], m.paths[3]), "left turn crosses eastbound traffic")219 XCTAssertTrue(conflict(m.paths[0], m.paths[4]), "left turn merges into westbound traffic")220 XCTAssertTrue(conflict(m.paths[1], m.paths[3]), "right turn merges into eastbound traffic")221 XCTAssertFalse(conflict(m.paths[1], m.paths[4]))222 XCTAssertTrue(conflict(m.paths[2], m.paths[3]), "the turn pocket crosses eastbound traffic")223 XCTAssertFalse(conflict(m.paths[2], m.paths[4]))224 XCTAssertFalse(conflict(m.paths[0], m.paths[1]))225 XCTAssertFalse(conflict(m.paths[1], m.paths[2]))226227 let t = TrafficLayout.layout(2)228 // The avenue straight crosses both streets; the two streets never meet each other.229 XCTAssertTrue(conflict(path(t, lane: 0, .straight), path(t, lane: 2, .straight)))230 XCTAssertTrue(conflict(path(t, lane: 0, .straight), path(t, lane: 4, .straight)))231 XCTAssertFalse(conflict(path(t, lane: 2, .straight), path(t, lane: 4, .straight)))232 XCTAssertFalse(conflict(path(t, lane: 0, .straight), path(t, lane: 1, .straight)))233 }234235 func testWaitingVehiclesNeverSitInAnotherPath() {236 // Whatever crosses, a queued vehicle (even the largest) is never touched: collisions only happen between vehicles the player sent.237 for layout in TrafficLayout.all {238 for lane in layout.controlledLanes {239 let own = layout.paths[lane.paths[0]]240 for slot in 0..<lane.maxQueue {241 let waitingS = own.stopS - 27 - Double(slot) * 59242 for other in layout.paths where other.lane != lane.id {243 var worst = Double.infinity244 var s = 0.0245 while s < other.length {246 worst = min(worst, gap(.truck, own, waitingS, .truck, other, s), gap(.truck, own, waitingS, .bus, other, s))247 s += 4248 }249 XCTAssertGreaterThan(worst, 1, "\(layout.name): lane \(lane.id) slot \(slot) vs path \(other.id)")250 }251 }252 }253 }254 }255256 // MARK: Kinematics257258 func testVehicleStopsAtLineAndAcceleratesWhenSent() {259 var sim = TrafficSim(layout: .layout(0), mode: .endless, seed: 1, tutorial: true)260 _ = sim.advance(6) // tutorial: one car, infinite patience261 let car = sim.vehicles[0]262 let p = sim.path(of: car)263 XCTAssertEqual(car.state, .waiting)264 XCTAssertEqual(car.s + car.half, p.stopS, accuracy: 0.7, "front bumper on the stop line")265 XCTAssertEqual(car.v, 0)266 XCTAssertTrue(sim.launch(car.id))267 XCTAssertFalse(sim.launch(car.id), "a vehicle can only be sent once")268 var top = 0.0, last = car.s, time = 0.0269 while sim.vehicle(car.id)?.state == .crossing {270 _ = sim.advance(TrafficSim.h)271 time += TrafficSim.h272 let v = sim.vehicle(car.id)!273 XCTAssertGreaterThanOrEqual(v.s, last, "never reverses")274 last = v.s275 if v.state == .crossing { top = max(top, v.v) }276 }277 XCTAssertEqual(top, VehicleKind.car.cruise, accuracy: 0.01)278 // Closed form: accelerate at a to v, then cruise, over the junction plus one car length.279 let d = (p.exitS - p.stopS) + VehicleKind.car.length, a = VehicleKind.car.accel, v = VehicleKind.car.cruise280 let expected = v / a + (d - v * v / (2 * a)) / v281 XCTAssertEqual(time, expected, accuracy: 0.06)282 }283284 func testFixedStepIsFrameRateIndependent() {285 var a = TrafficSim(layout: .layout(0), mode: .endless, seed: 9), b = a286 for _ in 0..<600 { _ = a.advance(1.0 / 60) }287 for _ in 0..<1200 { _ = b.advance(1.0 / 120) }288 XCTAssertEqual(a.snapshot, b.snapshot)289 }290291 func testPauseLeavesStateUntouched() {292 var sim = TrafficSim(layout: .layout(2), mode: .endless, seed: 5)293 _ = sim.advance(12)294 let before = sim.snapshot295 XCTAssertTrue(sim.advance(0).isEmpty)296 XCTAssertEqual(sim.snapshot, before, "while paused the scene does not advance the simulation")297 var resumed = sim, control = sim298 _ = resumed.advance(3)299 _ = control.advance(3)300 XCTAssertEqual(resumed.snapshot, control.snapshot)301 }302303 // MARK: Collisions and prediction304305 /// Tutorial step 1 gives a deterministic crossing pair: lane 3 (west) and lane 0 (south), both straight.306 private func crossingPair() -> (TrafficSim, west: Int, south: Int) {307 var sim = TrafficSim(layout: .layout(0), mode: .endless, seed: 3, tutorial: true)308 _ = sim.advance(5)309 sim.launch(sim.vehicles[0].id)310 _ = sim.advance(5)311 XCTAssertEqual(sim.tutorialStep, 1)312 let west = sim.vehicles.first { $0.lane == 3 && $0.state != .cleared }!.id313 let south = sim.vehicles.first { $0.lane == 0 && $0.state != .cleared }!.id314 _ = sim.advance(4)315 return (sim, west, south)316 }317318 func testPredictionMatchesWhatHappens() throws {319 var (sim, west, south) = crossingPair()320 XCTAssertTrue(sim.predict(launching: west).safe, "an empty junction is safe")321 sim.launch(west)322 let prediction = sim.predict(launching: south)323 XCTAssertFalse(prediction.safe)324 let point = try XCTUnwrap(prediction.collisionAt)325 XCTAssertTrue(TrafficLayout.layout(0).boxes[0].expanded(6).contains(point), "the predicted crash is inside the junction")326 // Reality agrees: sending it anyway crashes at the same place.327 var crashSim = sim328 crashSim.launch(south)329 let events = crashSim.advance(3)330 var crashes: [(Vec2, Bool)] = []331 for event in events { if case .crashed(_, _, let at, let forgiven) = event { crashes.append((at, forgiven)) } }332 XCTAssertEqual(crashes.count, 1)333 XCTAssertLessThan(crashes[0].0.distance(to: point), 0.01)334 XCTAssertTrue(crashes[0].1, "tutorial crashes are forgiven")335 XCTAssertEqual(crashSim.hearts, TrafficSim.startHearts)336 // Waiting until the first car is through is predicted safe, and is safe.337 _ = sim.advance(1.2)338 XCTAssertTrue(sim.predict(launching: south).safe)339 sim.launch(south)340 XCTAssertEqual(count(sim.advance(3), isCrash), 0)341 XCTAssertEqual(sim.cleared, 3)342 XCTAssertEqual(sim.tutorialStep, 2)343 }344345 func testCrashCostsOneHeartAndResetsStreak() {346 // Blind play: send every driver the moment they reach the line.347 var sim = TrafficSim(layout: .layout(0), mode: .endless, seed: 11)348 var events: [TrafficEvent] = []349 while !sim.isOver, sim.elapsed < 400 {350 for v in sim.launchable where sim.path(of: v).stopS - (v.s + v.half) < 5 { sim.launch(v.id) }351 let heartsBefore = sim.hearts352 let batch = sim.advance(TrafficSim.h)353 let lost = count(batch, isHeartLost)354 XCTAssertEqual(sim.hearts, heartsBefore - lost)355 XCTAssertEqual(count(batch, isCrash), lost, "one crash costs exactly one heart")356 if lost > 0 { XCTAssertEqual(sim.streak, 0, "a crash resets the streak") }357 events += batch358 }359 XCTAssertTrue(sim.isOver, "blind play does crash")360 XCTAssertEqual(sim.over, .hearts)361 XCTAssertEqual(sim.hearts, 0)362 XCTAssertEqual(count(events, isHeartLost), TrafficSim.startHearts)363 XCTAssertEqual(events.last, .over(.hearts))364 let frozen = sim.snapshot365 XCTAssertTrue(sim.advance(5).isEmpty, "nothing moves after the run is over")366 XCTAssertEqual(sim.snapshot, frozen)367 }368369 func testBodyGapIsSymmetricAndSigned() {370 let a = (Vec2(x: 0, y: 0), Vec2(x: 1, y: 0)), far = (Vec2(x: 0, y: 40), Vec2(x: 0, y: 1)), near = (Vec2(x: 10, y: 4), Vec2(x: 0, y: 1))371 XCTAssertEqual(TrafficSim.bodyGap(.car, a, .bus, far).0, TrafficSim.bodyGap(.bus, far, .car, a).0, accuracy: 1e-9)372 XCTAssertGreaterThan(TrafficSim.bodyGap(.car, a, .bus, far).0, 0)373 XCTAssertLessThan(TrafficSim.bodyGap(.car, a, .car, near).0, 0)374 for kind in VehicleKind.allCases {375 XCTAssertEqual(kind.circleOffsets.max()! + kind.radius, kind.length / 2, accuracy: 0.01, "\(kind) circles reach the bumpers")376 }377 }378379 // MARK: Scoring380381 func testScoringRules() {382 XCTAssertEqual((0...25).map { TrafficScoring.multiplier(streak: $0) },383 [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5])384 XCTAssertEqual(TrafficScoring.points(kind: .car, streakBefore: 0, closeCall: false), 10)385 XCTAssertEqual(TrafficScoring.points(kind: .car, streakBefore: 0, closeCall: true), 15)386 XCTAssertEqual(TrafficScoring.points(kind: .ambulance, streakBefore: 12, closeCall: false), 90)387 XCTAssertEqual(TrafficScoring.points(kind: .truck, streakBefore: 99, closeCall: true), 187)388 XCTAssertEqual(TrafficScoring.survivalBonus(mode: .endless, elapsed: 61.9), 122)389 XCTAssertEqual(TrafficScoring.survivalBonus(mode: .rush, elapsed: 60), 0)390 }391392 func testEveryVehicleScoresExactlyOnce() {393 let (sim, events) = botRun(layout: 0, seed: 21, seconds: 200)394 var ids: [Int] = [], total = 0, lastStreak = 0, closeCalls = 0395 for event in events {396 if case .cleared(let id, let points, let closeCall, let streak, _) = event {397 ids.append(id)398 total += points399 XCTAssertEqual(streak, lastStreak + 1, "streak grows by one per safe passage")400 lastStreak = streak401 if closeCall { closeCalls += 1 }402 }403 if case .heartLost = event { lastStreak = 0 }404 }405 XCTAssertGreaterThan(ids.count, 60)406 XCTAssertEqual(Set(ids).count, ids.count, "no vehicle is counted twice")407 XCTAssertEqual(sim.cleared, ids.count)408 XCTAssertEqual(sim.score, total)409 XCTAssertEqual(sim.closeCalls, closeCalls)410 XCTAssertEqual(sim.finalScore, total + Int(sim.elapsed) * 2)411 XCTAssertEqual(sim.heartsLost, 0, "a careful player never loses a heart")412 }413414 func testCloseCallBonusIsAwardedOncePerNearMiss() {415 // A reckless bot (almost no safety margin) shaves past other cars; each bonus belongs to exactly one cleared vehicle.416 var sim = TrafficSim(layout: .layout(0), mode: .endless, seed: 4)417 var bonuses = 0, clears = 0418 while sim.elapsed < 240, !sim.isOver {419 for id in TrafficBot.choose(sim, margin: 0.2) { sim.launch(id) }420 for event in sim.advance(0.1) {421 if case .cleared(_, _, let closeCall, _, _) = event {422 clears += 1423 if closeCall { bonuses += 1 }424 }425 }426 }427 XCTAssertEqual(sim.heartsLost, 0, "a near miss is not a crash")428 XCTAssertGreaterThan(bonuses, 0)429 XCTAssertLessThan(bonuses, clears)430 XCTAssertEqual(sim.closeCalls, bonuses)431 }432433 // MARK: Spawning, fairness and difficulty434435 func testDifficultyRampsThroughStagesNotRandomness() {436 let layout = TrafficLayout.layout(0)437 var previous = TrafficDifficulty.make(layout: layout, mode: .endless, cleared: 0, elapsed: 0)438 XCTAssertEqual(previous.stage, 1)439 XCTAssertFalse(previous.turns)440 XCTAssertEqual(previous.weights.filter { $0 > 0 }.count, 1, "stage 1 is cars only")441 for cleared in 1...200 {442 let d = TrafficDifficulty.make(layout: layout, mode: .endless, cleared: cleared, elapsed: 10) // outside a rush-hour wave443 XCTAssertGreaterThanOrEqual(d.stage, previous.stage)444 XCTAssertLessThanOrEqual(d.stage - previous.stage, 1, "one new thing at a time")445 XCTAssertLessThanOrEqual(d.spawnInterval, previous.spawnInterval + 1e-9)446 XCTAssertLessThanOrEqual(d.patience, previous.patience + 1e-9)447 let added = d.weights.filter { $0 > 0 }.count - previous.weights.filter { $0 > 0 }.count448 XCTAssertTrue(added == 0 || added == 1)449 previous = d450 }451 XCTAssertEqual(previous.stage, TrafficDifficulty.maxStage)452 XCTAssertGreaterThan(previous.spawnInterval, 0.9)453 // Rush-hour waves only exist at the last stage and are a fixed, predictable rhythm.454 XCTAssertLessThan(TrafficDifficulty.make(layout: layout, mode: .endless, cleared: 200, elapsed: 2).spawnInterval, previous.spawnInterval)455 XCTAssertEqual(TrafficDifficulty.make(layout: layout, mode: .endless, cleared: 20, elapsed: 2).spawnInterval,456 TrafficDifficulty.make(layout: layout, mode: .endless, cleared: 20, elapsed: 10).spawnInterval)457 XCTAssertGreaterThanOrEqual(previous.patience, 7.5)458 for stage in 2...6 { for l in TrafficLayout.all { XCTAssertNotNil(TrafficDifficulty.announcement(layout: l, stage: stage)) } }459 }460461 func testSpawningIsFairOnEveryLayout() {462 // The bot only launches when the predictor says it is safe. If it survives long seeded runs at full difficulty463 // without losing a heart, the spawner never forces a crash and never builds an unwinnable queue.464 for layout in TrafficLayout.all {465 let capacity = layout.controlledLanes.reduce(0) { $0 + $1.maxQueue }466 for seed in [1, 2, 3] as [UInt64] {467 var maxVehicles = 0468 var overlaps = 0, overfull = 0469 let (sim, _) = botRun(layout: layout.id, seed: seed &* 7919, seconds: 420) { sim in470 maxVehicles = max(maxVehicles, sim.vehicles.count)471 for lane in layout.lanes {472 let inLane = sim.vehicles.filter { $0.lane == lane.id && $0.state != .cleared }473 for (ahead, behind) in zip(inLane, inLane.dropFirst()) where (ahead.s - ahead.half) - (behind.s + behind.half) < 1 { overlaps += 1 }474 if !lane.autonomous, inLane.filter({ $0.state != .crossing }).count > lane.maxQueue { overfull += 1 }475 }476 }477 XCTAssertEqual(overlaps, 0, "\(layout.name): vehicles in a lane never overlap")478 XCTAssertEqual(overfull, 0, "\(layout.name): queues never exceed their capacity")479 XCTAssertEqual(sim.heartsLost, 0, "\(layout.name) seed \(seed): no forced crash, no unwinnable queue")480 XCTAssertFalse(sim.isOver)481 XCTAssertEqual(sim.stage, TrafficDifficulty.maxStage, "\(layout.name) seed \(seed) reaches the last stage")482 XCTAssertGreaterThan(sim.cleared, 120, "\(layout.name) seed \(seed) keeps traffic flowing")483 XCTAssertLessThanOrEqual(maxVehicles, capacity + 26, "\(layout.name): vehicle count stays bounded")484 }485 }486 }487488 func testThroughTrafficNeverHitsAnythingOnItsOwn() throws {489 // Main Street with a player who never touches the screen: drivers lose patience, but nothing ever crashes.490 var sim = TrafficSim(layout: .layout(1), mode: .endless, seed: 77)491 var events: [TrafficEvent] = []492 var sawThrough = false493 while !sim.isOver, sim.elapsed < 200 {494 events += sim.advance(0.1)495 sawThrough = sawThrough || sim.vehicles.contains { $0.autonomous }496 }497 XCTAssertTrue(sawThrough)498 XCTAssertEqual(count(events, isCrash), 0)499 XCTAssertEqual(sim.over, .hearts, "ignoring drivers costs hearts")500 XCTAssertEqual(count(events, isStormOff), TrafficSim.startHearts)501 // The first driver gives an audible warning before giving up.502 let firstLoss = try XCTUnwrap(events.firstIndex(where: isStormOff))503 XCTAssertTrue(events[..<firstLoss].contains(where: isImpatient))504 }505506 func testThroughTrafficLeavesReactionTimeAndGaps() {507 let layout = TrafficLayout.layout(1)508 for lane in layout.lanes where lane.autonomous {509 let p = layout.paths[lane.paths[0]]510 // Distance from spawn to the first point inside the junction box, at the fastest through speed.511 var s = 0.0512 while s < p.length, !layout.boxes[0].contains(p.point(at: s)) { s += 1 }513 XCTAssertGreaterThan(s / TrafficSim.throughSpeed(.sport), 2.0, "at least two seconds of warning")514 }515 XCTAssertGreaterThanOrEqual(layout.throughGap, 3.5, "the guaranteed gap fits the slowest truck")516 let hardest = TrafficDifficulty.make(layout: layout, mode: .endless, cleared: 999, elapsed: 999)517 XCTAssertGreaterThan(hardest.patience * VehicleKind.car.patienceFactor, layout.throughPeriod, "every driver sees at least one guaranteed gap")518 }519520 func testPatienceOnlyRunsAtTheStopLine() throws {521 var sim = TrafficSim(layout: .layout(0), mode: .endless, seed: 13)522 var firstLoss: Double?523 var events: [TrafficEvent] = []524 var timedWhileQueued = 0525 while !sim.isOver, sim.elapsed < 120 {526 let batch = sim.advance(0.1)527 if firstLoss == nil, batch.contains(where: isStormOff) { firstLoss = sim.elapsed }528 for v in sim.vehicles where v.state == .approaching && v.patience != v.patienceMax && sim.leader(ofLane: v.lane)?.id != v.id { timedWhileQueued += 1 }529 events += batch530 }531 XCTAssertEqual(timedWhileQueued, 0, "queued drivers are not timed")532 XCTAssertGreaterThan(try XCTUnwrap(firstLoss), 15, "the first driver gets the whole patience window")533 XCTAssertEqual(count(events, isCrash), 0, "an idle player is never crashed into")534 }535536 func testDeterministicForASeed() {537 let a = botRun(layout: 2, seed: 99, seconds: 90), b = botRun(layout: 2, seed: 99, seconds: 90), c = botRun(layout: 2, seed: 100, seconds: 90)538 XCTAssertEqual(a.0.snapshot, b.0.snapshot)539 XCTAssertEqual(a.1, b.1)540 XCTAssertNotEqual(a.0.snapshot, c.0.snapshot)541 }542543 func testRushModeEndsAtSixtySeconds() {544 let (sim, events) = botRun(layout: 0, mode: .rush, seed: 6, seconds: 120)545 XCTAssertEqual(sim.over, .timeUp)546 XCTAssertEqual(sim.elapsed, TrafficSim.rushDuration, accuracy: 0.02)547 XCTAssertEqual(events.last, .over(.timeUp))548 XCTAssertEqual(sim.timeLeft, 0)549 XCTAssertEqual(sim.finalScore, sim.score, "rush has no survival bonus")550 XCTAssertGreaterThan(sim.cleared, 15)551 XCTAssertEqual(sim.stage, 4, "rush starts with everything up to sports cars")552 }553554 func testLongSessionStaysStable() {555 var maxVehicles = 0556 let (sim, _) = botRun(layout: 2, seed: 2024, seconds: 1500) { maxVehicles = max(maxVehicles, $0.vehicles.count) }557 XCTAssertFalse(sim.isOver)558 XCTAssertEqual(sim.heartsLost, 0)559 XCTAssertGreaterThan(sim.cleared, 500)560 XCTAssertLessThanOrEqual(maxVehicles, 44)561 XCTAssertEqual(sim.elapsed, 1500, accuracy: 0.2)562 }563564 // MARK: Tutorial565566 func testTutorialFlow() {567 var sim = TrafficSim(layout: .layout(0), mode: .endless, seed: 8, tutorial: true)568 XCTAssertEqual(sim.tutorialStep, 0)569 _ = sim.advance(10)570 XCTAssertEqual(sim.vehicles.count, 1, "step 0 is a single car")571 XCTAssertEqual(sim.hearts, 3)572 XCTAssertEqual(sim.vehicles[0].patienceFraction, 1, "tutorial drivers never lose patience")573 var events: [TrafficEvent] = []574 while sim.tutorialStep != nil, sim.elapsed < 120 {575 for id in TrafficBot.choose(sim) { sim.launch(id) }576 events += sim.advance(0.1)577 }578 XCTAssertNil(sim.tutorialStep)579 XCTAssertTrue(events.contains(.tutorial(step: 1)))580 XCTAssertTrue(events.contains(.tutorial(step: 2)))581 XCTAssertTrue(events.contains(.tutorial(step: nil)))582 XCTAssertEqual(sim.hearts, 3)583 // Tutorials only run on the first junction in endless mode.584 XCTAssertNil(TrafficSim(layout: .layout(1), mode: .endless, seed: 1, tutorial: true).tutorialStep)585 XCTAssertNil(TrafficSim(layout: .layout(0), mode: .rush, seed: 1, tutorial: true).tutorialStep)586 }587588 // MARK: Save data589590 func testSaveRecordsBestsAndUnlocks() {591 var save = TrafficSave()592 XCTAssertTrue(save.isUnlocked(0))593 XCTAssertFalse(save.isUnlocked(1))594 XCTAssertEqual(save.unlockedCount, 1)595 var result = save.record(layout: 0, mode: .endless, score: 300, cleared: 12)596 XCTAssertTrue(result.isRecord)597 XCTAssertNil(result.unlocked)598 result = save.record(layout: 0, mode: .endless, score: 200, cleared: 30)599 XCTAssertFalse(result.isRecord, "a lower score is not a record")600 XCTAssertEqual(result.unlocked, 1, "clearing 25 in one run unlocks Main Street")601 XCTAssertEqual(save.best(layout: 0, mode: .endless), 300)602 XCTAssertEqual(save.best(layout: 0, mode: .rush), 0, "bests are kept per mode")603 XCTAssertFalse(save.isUnlocked(2))604 result = save.record(layout: 1, mode: .rush, score: 900, cleared: 25)605 XCTAssertEqual(result.unlocked, 2)606 XCTAssertEqual(save.unlockedCount, 3)607 XCTAssertEqual(save.overallBest, 900)608 XCTAssertEqual(save.totalCleared, 67)609 XCTAssertEqual(save.runs, 3)610 }611612 func testSaveRoundTripAndTolerantDecoding() throws {613 var save = TrafficSave()614 _ = save.record(layout: 0, mode: .rush, score: 1234, cleared: 40)615 save.tutorialDone = true616 var data = SaveData()617 data.traffic = save618 let decoded = try SaveCodec.decode(SaveCodec.encode(data))619 XCTAssertEqual(decoded.traffic, save)620 let partial = try JSONDecoder().decode(TrafficSave.self, from: Data(#"{"best":{"0-endless":50},"lastLayout":42,"lastMode":"bogus"}"#.utf8))621 XCTAssertEqual(partial.best(layout: 0, mode: .endless), 50)622 XCTAssertEqual(partial.lastLayout, 2, "out-of-range values are clamped")623 XCTAssertEqual(partial.lastMode, "endless")624 XCTAssertFalse(partial.tutorialDone)625 XCTAssertEqual(try JSONDecoder().decode(TrafficSave.self, from: Data("{}".utf8)), TrafficSave())626 }627}628