// Ants vs. SomeBees, in Swift. A project for cs.dorian.page's Swift tutorial, // after the tower-defense game in CS61A's third project (UC Berkeley). // // Run the tests: swift ants.swift test // Run one problem: swift ants.swift test 5 // Watch a game: swift ants.swift play // // Write your code between each `BEGIN PROBLEM` and `END PROBLEM` line. // Everything else is provided; read it, but do not change it. // MARK: - Provided: places /// A place in the tunnel. `exit` leads toward the ants' base; `entrance` /// leads toward the hive the bees come from. class Place { let name: String let exit: Place? var entrance: Place? var bees: [Bee] = [] var ant: Ant? var isHive: Bool { false } init(_ name: String, exit: Place? = nil) { self.name = name self.exit = exit // BEGIN PROBLEM 1 // Make this place the entrance of its exit. // END PROBLEM 1 } /// Put an insect here. Returns false if an ant cannot be added. @discardableResult func addInsect(_ insect: Insect) -> Bool { insect.addTo(self) } func removeInsect(_ insect: Insect) { insect.removeFrom(self) } } /// The bees' home, at the far end of the tunnel. Ants never target it. final class Hive: Place { override var isHive: Bool { true } } // MARK: - Provided: insects class Insect { class var damage: Int { 0 } class var isWaterproof: Bool { false } var health: Int weak var place: Place? init(health: Int) { self.health = health } var damage: Int { type(of: self).damage } var isWaterproof: Bool { type(of: self).isWaterproof } /// Lose `amount` health, and leave the place when health reaches zero. func reduceHealth(_ amount: Int) { health -= amount if health <= 0 { zeroHealthCallback() place?.removeInsect(self) } } func zeroHealthCallback() {} func action(_ game: GameState) {} @discardableResult func addTo(_ place: Place) -> Bool { self.place = place return true } func removeFrom(_ place: Place) { self.place = nil } } class Bee: Insect { override class var damage: Int { 1 } override class var isWaterproof: Bool { true } override init(health: Int = 3) { super.init(health: health) } func sting(_ ant: Ant) { ant.reduceHealth(damage) } func moveTo(_ destination: Place) { place?.removeInsect(self) destination.addInsect(self) } /// Bees are blocked by any ant that blocks the path. func isBlocked() -> Bool { place?.ant?.blocksPath ?? false } override func action(_ game: GameState) { guard let place else { return } if isBlocked(), let ant = place.ant { sting(ant) } else if let destination = place.exit { moveTo(destination) } } override func addTo(_ place: Place) -> Bool { place.bees.append(self) return super.addTo(place) } override func removeFrom(_ place: Place) { place.bees.removeAll { $0 === self } super.removeFrom(place) } } class Ant: Insect { class var foodCost: Int { 0 } class var displayName: String { "Ant" } var isContainer: Bool { false } var blocksPath: Bool { true } var isDoubled = false /// Each kind of ant sets its starting health by overriding this. class var startingHealth: Int { 1 } required init() { super.init(health: Self.startingHealth) } var foodCost: Int { type(of: self).foodCost } /// Extra damage from the queen (Problem 10), applied at most once. var damageBonus = 0 override var damage: Int { super.damage + damageBonus } // BEGIN PROBLEM 7 func canContain(_ other: Ant) -> Bool { false } override func addTo(_ place: Place) -> Bool { if place.ant == nil { place.ant = self } else { // Problem 7: if one of the two ants is a container that can // hold the other, store it there; otherwise fail. return false } return super.addTo(place) } override func removeFrom(_ place: Place) { if place.ant === self { place.ant = nil // Problem 7: a container leaves its ant behind. } // Problem 7: also handle removing an ant stored in a container. super.removeFrom(place) } // END PROBLEM 7 // BEGIN PROBLEM 10 func doubleDamage() { // Problem 10: double this ant's damage, at most once. } // END PROBLEM 10 } // MARK: - Problems 2 to 6: ants // BEGIN PROBLEM 2 class HarvesterAnt: Ant { // Food cost 2. Each turn, add one food to the game. } // END PROBLEM 2 // BEGIN PROBLEM 3 class ThrowerAnt: Ant { override class var foodCost: Int { 3 } override class var damage: Int { 1 } override class var displayName: String { "Thrower" } class var minRange: Int { 0 } class var maxRange: Int { Int.max } /// The first bee in the nearest place, from this ant's place toward the /// hive, within range. Bees in the hive are never targeted. func nearestBee() -> Bee? { return nil // Replace this line. } override func action(_ game: GameState) { nearestBee()?.reduceHealth(damage) } } // END PROBLEM 3 // BEGIN PROBLEM 4 class ShortThrower: ThrowerAnt { // Food cost 2; targets bees at most 3 places away. } class LongThrower: ThrowerAnt { // Food cost 2; targets bees at least 5 places away. } // END PROBLEM 4 // BEGIN PROBLEM 5 class FireAnt: Ant { override class var foodCost: Int { 5 } override class var damage: Int { 3 } override class var displayName: String { "Fire" } override class var startingHealth: Int { 3 } /// Reflect damage to every bee here, plus this ant's damage if it dies. override func reduceHealth(_ amount: Int) { super.reduceHealth(amount) // Replace this line. } } // END PROBLEM 5 // BEGIN PROBLEM 6 class WallAnt: Ant { // Food cost 4 and 4 health. It does nothing but stand in the way. } class HungryAnt: Ant { override class var foodCost: Int { 4 } override class var displayName: String { "Hungry" } static let chewDuration = 3 private(set) var turnsLeftChewing = 0 override func action(_ game: GameState) { // Your code here. } } // END PROBLEM 6 // MARK: - Problems 7 and 8: containers // BEGIN PROBLEM 7 class ContainerAnt: Ant { override var isContainer: Bool { true } private(set) var antContained: Ant? override func canContain(_ other: Ant) -> Bool { return false // Replace this line. } func storeAnt(_ ant: Ant) { // Your code here. } func removeAnt(_ ant: Ant) { // Your code here. } override func action(_ game: GameState) { // Your code here. } } // END PROBLEM 7 // BEGIN PROBLEM 8 class BodyguardAnt: ContainerAnt { // Food cost 4 and 2 health. It only protects. } class TankAnt: ContainerAnt { // Food cost 6, damage 1, and 2 health. Each turn, let the contained ant // act, then damage every bee in this place. } // END PROBLEM 8 // MARK: - Problems 9 and 10: water and the queen // BEGIN PROBLEM 9 final class Water: Place { // Insects that are not waterproof lose all their health when added. } class ScubaThrower: ThrowerAnt { // Food cost 6, and waterproof. } // END PROBLEM 9 // BEGIN PROBLEM 10 final class QueenAnt: ScubaThrower { override class var foodCost: Int { 7 } override class var displayName: String { "Queen" } /// Throw like a scuba thrower, then double the damage of every ant /// behind the queen (toward the base), each at most once. override func action(_ game: GameState) { super.action(game) } override func zeroHealthCallback() { // The game is lost when the queen falls. } } // END PROBLEM 10 // MARK: - Provided: the game /// Set when a queen's health reaches zero; the game is then lost. var queenFell = false final class GameState { var food: Int let base: Place let tunnel: [Place] // tunnel[0] is next to the base let hive: Hive init(length: Int, food: Int, water: Set = []) { self.food = food base = Place("Base") var places: [Place] = [] var exit = base for index in 0.. Ant? { guard kind.foodCost <= food else { return nil } let ant = kind.init() guard tunnel[index].addInsect(ant) else { return nil } food -= kind.foodCost return ant } var ants: [Ant] { tunnel.flatMap { place -> [Ant] in guard let ant = place.ant else { return [] } return [ant] } } var bees: [Bee] { (tunnel + [hive]).flatMap(\.bees) } var beesAtBase: Bool { !base.bees.isEmpty } } // MARK: - Tests (do not edit below this line) var onlyProblem: Int? = nil var passed = 0 var failed = 0 var failedProblems = Set() func check(_ problem: Int, _ description: String, _ actual: @autoclosure () -> T, _ expected: T) { if let only = onlyProblem, only != problem { return } let value = actual() if value == expected { passed += 1 } else { failed += 1 failedProblems.insert(problem) print("✗ Problem \(problem): \(description)") print(" expected \(expected), got \(value)") } } /// A container with no special behavior, for testing Problem 7. final class TestContainer: ContainerAnt {} /// Add bees with the given health to a place, returning them. func addBees(_ place: Place, _ healths: Int...) -> [Bee] { healths.map { health in let bee = Bee(health: health) place.addInsect(bee) return bee } } func runTests() { // Problem 1: entrances check(1, "each place is the entrance of its exit", { let base = Place("base") let first = Place("first", exit: base) let second = Place("second", exit: first) return [base.entrance === first, first.entrance === second, second.entrance == nil] }(), [true, true, true]) check(1, "the tunnel links up to the hive", { let game = GameState(length: 3, food: 0) return [game.tunnel[0].entrance === game.tunnel[1], game.tunnel[2].entrance === game.hive] }(), [true, true]) // Problem 2: HarvesterAnt check(2, "harvesters cost 2", HarvesterAnt.foodCost, 2) check(2, "harvesting adds one food", { let game = GameState(length: 2, food: 2) let ant = game.deploy(HarvesterAnt.self, at: 0)! ant.action(game) ant.action(game) return game.food }(), 2) check(2, "cannot deploy without enough food", GameState(length: 2, food: 1).deploy(HarvesterAnt.self, at: 0) == nil, true) // Problem 3: ThrowerAnt check(3, "throwers cost 3 and deal 1 damage", [ThrowerAnt.foodCost, ThrowerAnt.damage], [3, 1]) check(3, "targets the nearest bee toward the hive", { let game = GameState(length: 5, food: 10) let thrower = game.deploy(ThrowerAnt.self, at: 0) as! ThrowerAnt let far = addBees(game.tunnel[4], 3)[0] let near = addBees(game.tunnel[2], 3)[0] return [thrower.nearestBee() === near, thrower.nearestBee() !== far] }(), [true, true]) check(3, "a bee in its own place is nearest", { let game = GameState(length: 3, food: 10) let thrower = game.deploy(ThrowerAnt.self, at: 1) as! ThrowerAnt _ = addBees(game.tunnel[2], 3) let here = addBees(game.tunnel[1], 3)[0] return thrower.nearestBee() === here }(), true) check(3, "ignores bees behind it", { let game = GameState(length: 3, food: 10) let thrower = game.deploy(ThrowerAnt.self, at: 1) as! ThrowerAnt _ = addBees(game.tunnel[0], 3) return thrower.nearestBee() == nil }(), true) check(3, "never targets the hive", { let game = GameState(length: 2, food: 10) let thrower = game.deploy(ThrowerAnt.self, at: 0) as! ThrowerAnt _ = addBees(game.hive, 3) return thrower.nearestBee() == nil }(), true) check(3, "throwing reduces health", { let game = GameState(length: 3, food: 10) let thrower = game.deploy(ThrowerAnt.self, at: 0)! let bee = addBees(game.tunnel[2], 2)[0] thrower.action(game) let afterOne = bee.health thrower.action(game) return [afterOne, bee.health, game.tunnel[2].bees.count] }(), [1, 0, 0]) // Problem 4: ShortThrower and LongThrower check(4, "costs", [ShortThrower.foodCost, LongThrower.foodCost], [2, 2]) check(4, "short throwers reach at most 3 places", { let game = GameState(length: 8, food: 10) let short = game.deploy(ShortThrower.self, at: 0) as! ThrowerAnt _ = addBees(game.tunnel[4], 3) let outOfRange = short.nearestBee() == nil let near = addBees(game.tunnel[3], 3)[0] return [outOfRange, short.nearestBee() === near] }(), [true, true]) check(4, "long throwers ignore bees closer than 5", { let game = GameState(length: 8, food: 10) let long = game.deploy(LongThrower.self, at: 0) as! ThrowerAnt _ = addBees(game.tunnel[3], 3) let tooClose = long.nearestBee() == nil let far = addBees(game.tunnel[5], 3)[0] return [tooClose, long.nearestBee() === far] }(), [true, true]) // Problem 5: FireAnt check(5, "fire ants cost 5, deal 3, and start with 3 health", [FireAnt.foodCost, FireAnt.damage, FireAnt().health], [5, 3, 3]) check(5, "reflects damage to every bee here", { let place = Place("p") let fire = FireAnt() place.addInsect(fire) let bees = addBees(place, 5, 5) fire.reduceHealth(1) return bees.map(\.health) + [fire.health] }(), [4, 4, 2]) check(5, "adds its damage when it dies", { let place = Place("p") let fire = FireAnt() place.addInsect(fire) let bees = addBees(place, 6, 9) fire.reduceHealth(3) return bees.map(\.health) + [place.ant == nil ? 1 : 0] }(), [0, 3, 1]) check(5, "several bees can die at once", { let place = Place("p") let fire = FireAnt() place.addInsect(fire) _ = addBees(place, 1, 1, 1) fire.reduceHealth(1) return place.bees.count }(), 0) // Problem 6: WallAnt and HungryAnt check(6, "walls cost 4 and have 4 health", [WallAnt.foodCost, WallAnt().health], [4, 4]) check(6, "a wall blocks bees", { let game = GameState(length: 2, food: 10) let wall = game.deploy(WallAnt.self, at: 0)! let bee = addBees(game.tunnel[0], 3)[0] bee.action(game) return [wall.health, bee.place === game.tunnel[0] ? 1 : 0] }(), [3, 1]) check(6, "hungry ants eat a whole bee, then chew", { let game = GameState(length: 2, food: 10) let hungry = game.deploy(HungryAnt.self, at: 0)! let bees = addBees(game.tunnel[0], 5, 5) var remaining: [Int] = [] for _ in 0..<5 { hungry.action(game) remaining.append(game.tunnel[0].bees.count) } return remaining + [bees[1].health] }(), [1, 1, 1, 1, 0, 0]) // Problem 7: containers in general (tested with a plain container) check(7, "two ordinary ants cannot share a place", { let place = Place("p") let first = HarvesterAnt() let added = [place.addInsect(first), place.addInsect(ThrowerAnt())] return added + [place.ant === first] }(), [true, false, true]) check(7, "a container can hold one ordinary ant", [ TestContainer().canContain(ThrowerAnt()), TestContainer().canContain(TestContainer()), ], [true, false]) check(7, "a container added second protects the ant already there", { let place = Place("p") let thrower = ThrowerAnt() let container = TestContainer() let added = [place.addInsect(thrower), place.addInsect(container)] return added + [place.ant === container, container.antContained === thrower, thrower.place === place] }(), [true, true, true, true, true]) check(7, "an ant added second goes into the container", { let place = Place("p") let container = TestContainer() let thrower = ThrowerAnt() place.addInsect(container) let added = place.addInsect(thrower) return [added, place.ant === container, container.antContained === thrower] }(), [true, true, true]) check(7, "a full container takes no more", { let place = Place("p") place.addInsect(TestContainer()) place.addInsect(ThrowerAnt()) return [place.addInsect(HarvesterAnt()), place.addInsect(TestContainer())] }(), [false, false]) check(7, "removing a container leaves its ant", { let place = Place("p") let container = TestContainer() let thrower = ThrowerAnt() place.addInsect(container) place.addInsect(thrower) place.removeInsect(container) return [place.ant === thrower, thrower.place === place] }(), [true, true]) check(7, "removing the contained ant empties the container", { let place = Place("p") let container = TestContainer() let thrower = ThrowerAnt() place.addInsect(container) place.addInsect(thrower) place.removeInsect(thrower) return [place.ant === container, container.antContained == nil] }(), [true, true]) check(7, "a container lets its ant act", { let game = GameState(length: 3, food: 0) let container = TestContainer() game.tunnel[0].addInsect(container) game.tunnel[0].addInsect(ThrowerAnt()) let bee = addBees(game.tunnel[2], 3)[0] container.action(game) return bee.health }(), 2) // Problem 8: BodyguardAnt and TankAnt check(8, "costs and health", [BodyguardAnt.foodCost, BodyguardAnt().health, TankAnt.foodCost, TankAnt().health], [4, 2, 6, 2]) check(8, "when the bodyguard dies, the ant is exposed", { let game = GameState(length: 2, food: 20) let thrower = game.deploy(ThrowerAnt.self, at: 0)! game.deploy(BodyguardAnt.self, at: 0) let bee = addBees(game.tunnel[0], 3)[0] bee.action(game) bee.action(game) return [game.tunnel[0].ant === thrower, thrower.health == 1] }(), [true, true]) check(8, "a tank damages every bee in its place and lets its ant act", { let game = GameState(length: 3, food: 20) let tank = game.deploy(TankAnt.self, at: 1)! game.deploy(ThrowerAnt.self, at: 1) let bees = addBees(game.tunnel[1], 3, 1) tank.action(game) return bees.map(\.health) + [game.tunnel[1].bees.count] }(), [1, 0, 1]) check(8, "two containers cannot share", { let place = Place("p") place.addInsect(BodyguardAnt()) return place.addInsect(TankAnt()) }(), false) // Problem 9: water check(9, "ants drown in water", { let game = GameState(length: 3, food: 20, water: [1]) let harvester = game.deploy(HarvesterAnt.self, at: 1) return [harvester?.health ?? -1, game.tunnel[1].ant == nil ? 1 : 0] }(), [0, 1]) check(9, "scuba throwers and bees survive water", { let game = GameState(length: 3, food: 20, water: [1]) let scuba = game.deploy(ScubaThrower.self, at: 1)! let bee = addBees(game.tunnel[1], 3)[0] return [game.tunnel[1].ant === scuba, bee.place === game.tunnel[1]] }(), [true, true]) check(9, "scuba throwers still throw", { let game = GameState(length: 4, food: 20, water: [1]) let scuba = game.deploy(ScubaThrower.self, at: 1)! let bee = addBees(game.tunnel[3], 3)[0] scuba.action(game) return [ScubaThrower.foodCost, bee.health] }(), [6, 2]) // Problem 10: QueenAnt check(10, "the queen costs 7 and throws", { let game = GameState(length: 4, food: 20) let queen = game.deploy(QueenAnt.self, at: 2)! let bee = addBees(game.tunnel[3], 3)[0] queen.action(game) return [QueenAnt.foodCost, bee.health] }(), [7, 2]) check(10, "doubles the damage of ants behind her, once", { queenFell = false let game = GameState(length: 4, food: 30) let thrower = game.deploy(ThrowerAnt.self, at: 0)! let queen = game.deploy(QueenAnt.self, at: 2)! let ahead = game.deploy(ThrowerAnt.self, at: 3)! queen.action(game) let once = thrower.damage queen.action(game) return [once, thrower.damage, ahead.damage] }(), [2, 2, 1]) check(10, "also doubles a contained ant", { let game = GameState(length: 4, food: 30) let thrower = game.deploy(ThrowerAnt.self, at: 0)! game.deploy(BodyguardAnt.self, at: 0) let queen = game.deploy(QueenAnt.self, at: 1)! queen.action(game) return thrower.damage }(), 2) check(10, "the game is lost if the queen falls", { queenFell = false let game = GameState(length: 2, food: 20) let queen = game.deploy(QueenAnt.self, at: 0)! queen.reduceHealth(queen.health) return queenFell }(), true) let total = passed + failed if failed == 0 && total > 0 { print("\(total) of \(total) checks passed.") print(onlyProblem.map { "Problem \($0) passed." } ?? "All tests passed.") } else { print("\(passed) of \(total) checks passed. Problems to revisit: \(failedProblems.sorted()).") } } /// Draw the tunnel: base on the left, hive on the right. func draw(_ game: GameState, turn: Int) { let cells = game.tunnel.map { place -> String in let ant = place.ant.map { String(type(of: $0).displayName.prefix(4)) } ?? (place is Water ? "~~~~" : "....") let bees = place.bees.isEmpty ? " " : "B\(place.bees.count)" return "\(ant.padding(4))\(bees)" } print("turn \(String(turn).padding(3)) food \(String(game.food).padding(3)) Base | " + cells.joined(separator: " | ") + " | Hive: \(game.hive.bees.count)") } extension String { func padding(_ width: Int) -> String { count >= width ? self : self + String(repeating: " ", count: width - count) } } /// A scripted game with your ants, drawn turn by turn. func playGame() { queenFell = false let game = GameState(length: 9, food: 12, water: [4]) let waves = [2: 1, 4: 2, 7: 2, 10: 3, 14: 3, 18: 4] let plan: [Int: (Ant.Type, Int)] = [ 0: (HarvesterAnt.self, 0), 1: (HarvesterAnt.self, 1), 3: (ThrowerAnt.self, 2), 5: (ThrowerAnt.self, 3), 8: (WallAnt.self, 6), 9: (ScubaThrower.self, 4), 12: (FireAnt.self, 5), 15: (LongThrower.self, 0), 17: (BodyguardAnt.self, 2), ] for turn in 0..<40 { if let count = waves[turn] { for _ in 0.. waves.keys.max()! { print("Every bee is gone. The ants win!") return } } print("Time is up: the ants held the tunnel.") } let arguments = Array(CommandLine.arguments.dropFirst()) switch arguments.first { case "test": onlyProblem = arguments.dropFirst().first.flatMap { Int($0) } runTests() case "play": playGame() default: print("Usage: swift ants.swift test [problem] | swift ants.swift play") }