/
astar.go
214 lines (168 loc) · 4.13 KB
/
astar.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package exercises
import (
"container/heap"
"fmt"
"image"
"strings"
"time"
)
var (
nm nodeMap
sm stateMap
)
type Pather interface {
GetNeighbors() []Pather
PathNeighborCost(to Pather) float64
PathEstimatedCost(to Pather) float64
}
type Direction rune
const (
UpDir Direction = 'u'
DownDir Direction = 'd'
RightDir Direction = 'r'
LeftDir Direction = 'l'
)
type node struct {
pather Pather
history []Direction
cost float64
rank float64
parent *node
open bool
closed bool
index int
}
type nodeMap map[Pather]*node
func (nm nodeMap) get(p Pather) *node {
n, ok := nm[p]
if !ok {
n = &node{pather: p}
nm[p] = n
}
return n
}
type stateMap map[Pather]map[string]*node
func (sm stateMap) get(p Pather, hist ...Direction) *node {
// not safe for concurrent use
var sb strings.Builder
for _, d := range hist {
sb.WriteRune(rune(d))
}
hash := sb.String()
if sm[p] == nil {
sm[p] = make(map[string]*node)
}
n, ok := sm[p][hash]
if !ok {
n = &node{pather: p, history: hist}
sm[p][hash] = n
}
return n
}
func getNodeHash(n *node) string {
if n == nil {
return ""
}
const hashLen = 4
var hash string
i := 0
for v := n; v != nil && i < hashLen; v = v.parent {
// fmt.Printf("v=%+v\n", v)
if v.pather == nil {
hash += "<nil>"
} else {
hash += fmt.Sprintf("<%d-%d>", v.pather.(*Block).Position.X, v.pather.(*Block).Position.Y)
}
i++
}
return hash
}
func (c *City) Path(start, end Pather) ([]Pather, float64, bool) {
frames := []*image.RGBA{generateBackgroundImage(c, nil)}
fmt.Printf("Path from %v to %v\n", start.(*Block).Position, end.(*Block).Position)
nm = nodeMap{}
// sm = stateMap{}
pq := &priorityQueue{}
heap.Init(pq)
fromNode := nm.get(start)
// fromNode := sm.get(start, RightDir)
fromNode.open = true
heap.Push(pq, fromNode)
// loop until we get to goal or queue is empty
for i := 0; ; i++ {
if pq.Len() == 0 {
// There's no path to the goal
return nil, 0, false
}
current, ok := heap.Pop(pq).(*node)
if !ok {
fmt.Println("failed to pop from queue")
return nil, 0, false
}
// hist := getNodeHash(current)
// DEBUG: generate animation frame
if i%500 == 0 {
p := buildPath(current)
frame, err := c.GenerateFrame(p, fmt.Sprintf("%s cost=%.0f", p[0].(*Block).Position.String(), nm[p[0]].cost))
// frame, err := c.GenerateFrame(p, fmt.Sprintf("%s cost=%.0f", p[0].(*Block).Position.String(), sm[p[0]][hist].cost))
if err == nil {
frames = append(frames, frame)
}
}
current.open = false
current.closed = true
if current == nm.get(end) {
// if isEnd(current, end) {
// DEBUG: generate animation
fmt.Printf("generating animation (%d frames)\n", len(frames))
outfile := fmt.Sprintf("./images/p1-%s.png", time.Now().Format("20060102_150405"))
err := GenerateAPNG(frames, outfile)
if err != nil {
fmt.Println("failed to generate animation")
}
// Found a path to the goal.
return buildPath(current), current.cost, true
}
addNeighborsToQueue(current, end, pq)
}
}
func isEnd(n *node, end Pather) bool {
if n == nil || n.pather == nil {
return false
}
b, ok := n.pather.(*Block)
if !ok {
return false
}
return b.Position == end.(*Block).Position
}
func buildPath(n *node) []Pather {
path := []Pather{}
curr := n
for curr != nil {
path = append(path, curr.pather)
curr = curr.parent
}
return path
}
func addNeighborsToQueue(current *node, to Pather, pq *priorityQueue) {
for _, neighbor := range current.pather.GetNeighbors() {
cost := current.cost + current.pather.PathNeighborCost(neighbor)
neighborNode := nm.get(neighbor)
// if we have a better path (lower cost), update the neighbor and make it active
if cost < neighborNode.cost {
if neighborNode.open { // FIX: it's more efficient to update the node than remove/add
heap.Remove(pq, neighborNode.index)
}
neighborNode.open = false
neighborNode.closed = false
}
if !neighborNode.open && !neighborNode.closed {
neighborNode.cost = cost
neighborNode.open = true
neighborNode.rank = cost + neighbor.PathEstimatedCost(to)
neighborNode.parent = current
heap.Push(pq, neighborNode)
}
}
}