rove/pkg/maths/bearing.go

98 lines
1.9 KiB
Go
Raw Normal View History

2020-07-10 18:24:54 +01:00
package maths
import (
"fmt"
"strings"
)
2020-06-09 18:09:51 +01:00
// Bearing describes a compass direction
type Bearing int
const (
2020-06-30 23:59:58 +01:00
// North describes a 0,1 vector
2020-06-09 18:09:51 +01:00
North Bearing = iota
2020-06-30 23:59:58 +01:00
// NorthEast describes a 1,1 vector
NorthEast
2020-06-30 23:59:58 +01:00
// East describes a 1,0 vector
East
2020-06-30 23:59:58 +01:00
// SouthEast describes a 1,-1 vector
SouthEast
2020-06-30 23:59:58 +01:00
// South describes a 0,-1 vector
South
2020-06-30 23:59:58 +01:00
// SouthWest describes a -1,-1 vector
SouthWest
2020-06-30 23:59:58 +01:00
// West describes a -1,0 vector
West
2020-06-30 23:59:58 +01:00
// NorthWest describes a -1,1 vector
NorthWest
)
2020-06-09 18:09:51 +01:00
// bearingString simply describes the strings associated with a direction
type bearingString struct {
Long string
Short string
}
2020-06-09 18:09:51 +01:00
// bearingStrings is the set of strings for each direction
var bearingStrings = []bearingString{
{"North", "N"},
{"NorthEast", "NE"},
{"East", "E"},
{"SouthEast", "SE"},
{"South", "S"},
{"SouthWest", "SW"},
{"West", "W"},
{"NorthWest", "NW"},
}
// String converts a Direction to a String
2020-06-09 18:09:51 +01:00
func (d Bearing) String() string {
return bearingStrings[d].Long
}
// ShortString converts a Direction to a short string version
2020-06-09 18:09:51 +01:00
func (d Bearing) ShortString() string {
return bearingStrings[d].Short
}
// BearingFromString gets the Direction from a string
func BearingFromString(s string) (Bearing, error) {
2020-06-09 18:09:51 +01:00
for i, d := range bearingStrings {
2020-07-06 18:04:10 +01:00
if strings.EqualFold(d.Long, s) || strings.EqualFold(d.Short, s) {
2020-06-09 18:09:51 +01:00
return Bearing(i), nil
}
}
return -1, fmt.Errorf("unknown bearing: %s", s)
}
2020-07-10 18:24:54 +01:00
var bearingVectors = []Vector{
{X: 0, Y: 1}, // N
{X: 1, Y: 1}, // NE
{X: 1, Y: 0}, // E
{X: 1, Y: -1}, // SE
{X: 0, Y: -1}, // S
{X: -1, Y: -1}, // SW
{X: -1, Y: 0}, // W
{X: -1, Y: 1}, // NW
}
// Vector converts a Direction to a Vector
2020-07-10 18:24:54 +01:00
func (d Bearing) Vector() Vector {
2020-06-09 18:09:51 +01:00
return bearingVectors[d]
}
// IsCardinal returns if this is a cardinal (NESW)
func (d Bearing) IsCardinal() bool {
switch d {
case North:
fallthrough
case East:
fallthrough
case South:
fallthrough
case West:
return true
}
return false
}