-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirections.go
118 lines (108 loc) · 2.46 KB
/
directions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
)
// Bitflags for cardinal directions (North, South, East or West)
type Direction byte
const (
BadDir Direction = 0 //0000 0000 Used when not recognised.
North Direction = 1 //0000 0001
East Direction = 2 //0000 0010
South Direction = 4 //0000 0100
West Direction = 8 //0000 1000
DirMask Direction = 15 //0000 1111 For masking cardinal directions.
)
// Converts a Direction into a human-readable string.
func dirToString(dir Direction) string {
switch dir {
case North:
return "North"
case East:
return "East"
case South:
return "South"
case West:
return "West"
}
return "NaD"
}
// Helper function that produces an array of the Direction string and the
// first character of that string. E.g. North => []string{"North","N"}
func dirToCommandStrings(dir Direction) []string {
full := dirToString(dir)
return []string{full, string(full[0])}
}
// Invert cardinal Direction 'dir'. E.g. North => South
func invertDir(dir Direction) Direction {
switch dir {
case North:
return South
case East:
return West
case South:
return North
case West:
return East
}
return BadDir
}
func invertDirString(dirString string) string {
switch dirString {
case "North":
return "South"
case "South":
return "North"
case "East":
return "West"
case "West":
return "East"
}
return "Unknown"
}
// Get the cardinal direction to i2 from i1
func cardinalDirBetween(i1, i2, width int) Direction {
if (i1-i2)%width == 0 {
if i1 > i2 {
return North
}
return South
}
diff := i1 - i2
if diff < 0 {
diff *= -1
}
if i1-i2 < width {
if i1 > i2 {
return West
}
return East
}
return BadDir
}
// Returns a map of direction bitflags to the indices in that direction from
// the input directions.
func flagToIndicies(tm *TextMap, index int, dirFlag Direction) map[Direction]int {
output := make(map[Direction]int)
if n := index - tm.width; dirFlag&North == North {
output[North] = n
}
if e := index + 1; dirFlag&East == East {
output[East] = e
}
if s := index + tm.width; dirFlag&South == South {
output[South] = s
}
if w := index - 1; dirFlag&West == West {
output[West] = w
}
return output
}
// Returns the index in a TextMap, tm that is Direction, dir, from a starting
// point, index.
func flagToIndex(tm *TextMap, index int, dir Direction) (int, error) {
if output, ok := flagToIndicies(tm, index, dir)[dir]; ok {
return output, nil
} else {
return 0, fmt.Errorf("No index in that direction.")
}
}