Last active
September 28, 2015 11:20
-
-
Save zvweiss/42c6dd06625a5b83799b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
typealias Distance = Double | |
struct Position { | |
var x: Double | |
var y: Double | |
} | |
extension Position { | |
func inRange(range: Distance) -> Bool { | |
return sqrt(x * x + y * y) <= range | |
} | |
func minus(p: Position) -> Position { | |
return Position(x: x - p.x, y: y - p.y) | |
} | |
var length: Double { | |
return sqrt(x * x + y * y) | |
} | |
} | |
struct Ship { | |
var position: Position | |
var firingRange: Distance | |
var unsafeRange: Distance | |
} | |
//=============================================FUNCTIONAL with Struct Region | |
struct Region { | |
let lookup: Position -> Bool | |
} | |
extension Region { | |
static func circle(radius: Distance) -> Region { | |
return Region(lookup: { point in point.length <= radius }) | |
} | |
func shifted(offset: Position) -> Region { | |
return Region(lookup: { point in self.lookup(point.minus(offset)) }) | |
} | |
func inverted() -> Region { | |
return Region(lookup: { point in !self.lookup(point) }) | |
} | |
func union(region: Region) -> Region { | |
return Region(lookup: { point in self.lookup(point) || region.lookup(point) }) | |
} | |
func intersection(region: Region) ->Region { | |
return Region(lookup: { point in self.lookup(point) && region.lookup(point) }) | |
} | |
func difference(minus: Region) -> Region { | |
return Region(lookup: { point in self.lookup(point) && !minus.lookup(point) }) | |
} | |
} | |
extension Ship { | |
func canSafelyEngageShip(target: Position, friendly: Position) -> Bool { | |
let unsafeRegion = Region.circle(unsafeRange) | |
return Region.circle(firingRange).difference(unsafeRegion).difference((unsafeRegion).shifted(friendly)).lookup(target) | |
} | |
} | |
//=============================================Example | |
let myShip = Ship(position: Position(x: 10.0, y: 10.0), firingRange: 10.0, unsafeRange: 1.0) | |
let targetShip = Position(x:5.0, y: 5.0) | |
let friendlyShip = Position(x: 10.0, y: 2.0) | |
myShip.canSafelyEngageShip(targetShip, friendly: friendlyShip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment