47 lines
1.2 KiB
Swift
47 lines
1.2 KiB
Swift
import Foundation
|
|
|
|
public struct Vertex: Sendable, Hashable {
|
|
public static let zero: Vertex = Vertex(0, 0)
|
|
static let up: Vertex = Vertex(0, 1)
|
|
static let down: Vertex = Vertex(0, -1)
|
|
static let right: Vertex = Vertex(1, 0)
|
|
static let left: Vertex = Vertex(-1, 0)
|
|
static let cardinals: [Vertex] = [Vertex.up, Vertex.down, Vertex.right, Vertex.left]
|
|
|
|
public let x: Int
|
|
public let y: Int
|
|
|
|
init(_ x: Int, _ y: Int) {
|
|
self.x = x
|
|
self.y = y
|
|
}
|
|
|
|
static func + (lhs: Self, rhs: Self) -> Self {
|
|
Vertex(lhs.x + rhs.x, lhs.y + rhs.y)
|
|
}
|
|
|
|
static func - (lhs: Self, rhs: Self) -> Self {
|
|
Vertex(lhs.x - rhs.x, lhs.y - rhs.y)
|
|
}
|
|
|
|
static func * (lhs: Self, rhs: Int) -> Self {
|
|
Vertex(lhs.x * rhs, lhs.y * rhs)
|
|
}
|
|
|
|
static func / (lhs: Self, rhs: Int) -> Self {
|
|
Vertex(lhs.x / rhs, lhs.y / rhs)
|
|
}
|
|
|
|
static func % (lhs: Self, rhs: Self) -> Self {
|
|
Vertex((lhs.x + rhs.x) % rhs.x, (lhs.y + rhs.y) % rhs.y)
|
|
}
|
|
|
|
func distance(target: Vertex, size: Vertex) -> Int {
|
|
let dx = abs(x - target.x)
|
|
let dy = abs(y - target.y)
|
|
let wx = min(dx, size.x - dx)
|
|
let wy = min(dy, size.y - dy)
|
|
return Int(sqrt(Float(wx * wx + wy * wy)))
|
|
}
|
|
}
|