import Darwin
struct Position { let x, y: Float }
typealias Distance = Float
// Start with a simple Battleship with a certain weapon reach
class Battleship
{
let weaponRange: Distance = 5.0
func shouldFireAtTarget(target: Position) -> Bool
{
return hypot(target.x, target.y) <= weaponRange
}
}
let battleship = Battleship()
battleship.shouldFireAtTarget(Position(x: 2, y: 3))
battleship.shouldFireAtTarget(Position(x: 9, y: 15))
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Add ability to be shifted from the origin
class Battleship2
{
let weaponReach: Distance = 5.0
let ownPosition: Position
init(ownPosition: Position)
{
self.ownPosition = ownPosition
}
func shouldFireAtTarget(target: Position) -> Bool
{
let dx = target.x - ownPosition.x
let dy = target.y - ownPosition.y
let targetDistance = hypot(dx, dy)
return targetDistance <= weaponReach
}
}
let battleship2 = Battleship2(ownPosition: Position(x: 10, y: 12))
battleship2.shouldFireAtTarget(Position(x: 2, y: 3))
battleship2.shouldFireAtTarget(Position(x: 9, y: 15))
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Don't fire too close to self
class Battleship3
{
let weaponReach: Distance = 5.0
let ownPosition: Position
let safeDistance: Distance = 1.0
init(ownPosition: Position)
{
self.ownPosition = ownPosition
}
func shouldFireAtTarget(target: Position) -> Bool
{
let dx = target.x - ownPosition.x
let dy = target.y - ownPosition.y
let targetDistance = hypot(dx, dy)
return (targetDistance <= weaponReach
&& targetDistance > safeDistance)
}
}
let battleship3 = Battleship3(ownPosition: Position(x: 10, y: 12))
battleship3.shouldFireAtTarget(Position(x: 9, y: 15))
battleship3.shouldFireAtTarget(Position(x: 10.5, y: 12)) // too close to us
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Avoid friendly fire
class Battleship4
{
let weaponReach: Distance = 5.0
let ownPosition: Position
let safeDistance: Distance = 1.0
let friendlyPosition: Position
init(ownPosition: Position, friendlyPosition: Position)
{
self.ownPosition = ownPosition
self.friendlyPosition = friendlyPosition
}
func shouldFireAtTarget(target: Position) -> Bool
{
let dx = target.x - ownPosition.x
let dy = target.y - ownPosition.y
let targetDistance = hypot(dx, dy)
let friendlyDx = friendlyPosition.x - target.x
let friendlyDy = friendlyPosition.y - target.y
let friendlyDistance = hypot(friendlyDx, friendlyDy)
return (targetDistance <= weaponReach
&& targetDistance > safeDistance
&& friendlyDistance >= safeDistance)
}
}
let battleship4 = Battleship4(ownPosition: Position(x: 10, y: 12), friendlyPosition: Position(x: 12, y: 9))
battleship4.shouldFireAtTarget(Position(x: 9, y: 15))
battleship4.shouldFireAtTarget(Position(x: 12.25, y: 9.25)) // too close to friendly