-
Notifications
You must be signed in to change notification settings - Fork 16
/
paths.go
614 lines (471 loc) · 16.1 KB
/
paths.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/*
Package paths is a simple library written in Go made to handle 2D pathfinding for games. All you need to do is generate a Grid,
specify which cells aren't walkable, optionally change the cost on specific cells, and finally get a path from one cell to
another.
*/
package paths
import (
"container/heap"
"fmt"
"math"
)
// A Cell represents a point on a Grid map. It has an X and Y value for the position, a Cost, which influences which Cells are
// ideal for paths, Walkable, which indicates if the tile can be walked on or should be avoided, and a Rune, which indicates
// which rune character the Cell is represented by.
type Cell struct {
X, Y int
Cost float64
Walkable bool
Rune rune
}
func (cell Cell) String() string {
return fmt.Sprintf("X:%d Y:%d Cost:%f Walkable:%t Rune:%s(%d)", cell.X, cell.Y, cell.Cost, cell.Walkable, string(cell.Rune), int(cell.Rune))
}
// Grid represents a "map" composed of individual Cells at each point in the map.
// Data is a 2D array of Cells.
// CellWidth and CellHeight indicate the size of Cells for Cell Position <-> World Position translation.
type Grid struct {
Data [][]*Cell
CellWidth, CellHeight int
}
// NewGrid returns a new Grid of (gridWidth x gridHeight) size. cellWidth and cellHeight changes the size of each Cell in the Grid.
// This is used to translate world position to Cell positions (i.e. the Cell position [2, 5] with a CellWidth and CellHeight of
// [16, 16] would be the world positon [32, 80]).
func NewGrid(gridWidth, gridHeight, cellWidth, cellHeight int) *Grid {
m := &Grid{CellWidth: cellWidth, CellHeight: cellHeight}
for y := 0; y < gridHeight; y++ {
m.Data = append(m.Data, []*Cell{})
for x := 0; x < gridWidth; x++ {
m.Data[y] = append(m.Data[y], &Cell{x, y, 1, true, ' '})
}
}
return m
}
// NewGridFromStringArrays creates a Grid map from a 1D array of strings. Each string becomes a row of Cells, each
// with one rune as its character. cellWidth and cellHeight changes the size of each Cell in the Grid. This is used to
// translate world position to Cell positions (i.e. the Cell position [2, 5] with a CellWidth and CellHeight of
// [16, 16] would be the world positon [32, 80]).
func NewGridFromStringArrays(arrays []string, cellWidth, cellHeight int) *Grid {
m := &Grid{CellWidth: cellWidth, CellHeight: cellHeight}
for y := 0; y < len(arrays); y++ {
m.Data = append(m.Data, []*Cell{})
stringLine := []rune(arrays[y])
for x := 0; x < len(arrays[y]); x++ {
m.Data[y] = append(m.Data[y], &Cell{X: x, Y: y, Cost: 1, Walkable: true, Rune: stringLine[x]})
}
}
return m
}
// NewGridFromRuneArrays creates a Grid map from a 2D array of runes. Each individual Rune becomes a Cell in the resulting
// Grid. cellWidth and cellHeight changes the size of each Cell in the Grid. This is used to translate world position to Cell
// positions (i.e. the Cell position [2, 5] with a CellWidth and CellHeight of [16, 16] would be the world positon [32, 80]).
func NewGridFromRuneArrays(arrays [][]rune, cellWidth, cellHeight int) *Grid {
m := &Grid{CellWidth: cellWidth, CellHeight: cellHeight}
for y := 0; y < len(arrays); y++ {
m.Data = append(m.Data, []*Cell{})
for x := 0; x < len(arrays[y]); x++ {
m.Data[y] = append(m.Data[y], &Cell{X: x, Y: y, Cost: 1, Walkable: true, Rune: arrays[y][x]})
}
}
return m
}
// DataToString returns a string, used to easily identify the Grid map.
func (m *Grid) DataToString() string {
s := ""
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
s += string(m.Data[y][x].Rune) + " "
}
s += "\n"
}
return s
}
// Get returns a pointer to the Cell in the x and y position provided.
func (m *Grid) Get(x, y int) *Cell {
if x < 0 || y < 0 || x >= m.Width() || y >= m.Height() {
return nil
}
return m.Data[y][x]
}
// Height returns the height of the Grid map.
func (m *Grid) Height() int {
return len(m.Data)
}
// Width returns the width of the Grid map.
func (m *Grid) Width() int {
return len(m.Data[0])
}
// CellsByRune returns a slice of pointers to Cells that all have the character provided.
func (m *Grid) CellsByRune(char rune) []*Cell {
cells := make([]*Cell, 0)
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
c := m.Get(x, y)
if c.Rune == char {
cells = append(cells, c)
}
}
}
return cells
}
// AllCells returns a single slice of pointers to all Cells contained in the Grid's 2D Data array.
func (m *Grid) AllCells() []*Cell {
cells := make([]*Cell, 0)
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
cells = append(cells, m.Get(x, y))
}
}
return cells
}
// CellsByCost returns a slice of pointers to Cells that all have the Cost value provided.
func (m *Grid) CellsByCost(cost float64) []*Cell {
cells := make([]*Cell, 0)
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
c := m.Get(x, y)
if c.Cost == cost {
cells = append(cells, c)
}
}
}
return cells
}
// CellsByWalkable returns a slice of pointers to Cells that all have the Cost value provided.
func (m *Grid) CellsByWalkable(walkable bool) []*Cell {
cells := make([]*Cell, 0)
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
c := m.Get(x, y)
if c.Walkable == walkable {
cells = append(cells, c)
}
}
}
return cells
}
// SetWalkable sets walkability across all cells in the Grid with the specified rune.
func (m *Grid) SetWalkable(char rune, walkable bool) {
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
cell := m.Get(x, y)
if cell.Rune == char {
cell.Walkable = walkable
}
}
}
}
// SetCost sets the movement cost across all cells in the Grid with the specified rune.
func (m *Grid) SetCost(char rune, cost float64) {
for y := 0; y < m.Height(); y++ {
for x := 0; x < m.Width(); x++ {
cell := m.Get(x, y)
if cell.Rune == char {
cell.Cost = cost
}
}
}
}
// GridToWorld converts from a grid position to world position, multiplying the value by the CellWidth and CellHeight of the Grid.
func (m *Grid) GridToWorld(x, y int) (float64, float64) {
rx := float64(x * m.CellWidth)
ry := float64(y * m.CellHeight)
return rx, ry
}
// WorldToGrid converts from a grid position to world position, multiplying the value by the CellWidth and CellHeight of the Grid.
func (m *Grid) WorldToGrid(x, y float64) (int, int) {
tx := int(math.Floor(x / float64(m.CellWidth)))
ty := int(math.Floor(y / float64(m.CellHeight)))
return tx, ty
}
// GetPathFromCells returns a Path, from the starting Cell to the destination Cell. diagonals controls whether moving diagonally
// is acceptable when creating the Path. wallsBlockDiagonals indicates whether to allow diagonal movement "through" walls that are
// positioned diagonally.
func (m *Grid) GetPathFromCells(start, dest *Cell, diagonals, wallsBlockDiagonals bool) *Path {
openNodes := minHeap{}
heap.Push(&openNodes, &Node{Cell: dest, Cost: dest.Cost})
checkedNodes := make([]*Cell, 0)
hasBeenAdded := func(cell *Cell) bool {
for _, c := range checkedNodes {
if cell == c {
return true
}
}
return false
}
path := &Path{}
if !start.Walkable || !dest.Walkable {
return nil
}
for {
// If the list of openNodes (nodes to check) is at 0, then we've checked all Nodes, and so the function can quit.
if len(openNodes) == 0 {
break
}
node := heap.Pop(&openNodes).(*Node)
// If we've reached the start, then we've constructed our Path going from the destination to the start; we just have
// to loop through each Node and go up, adding it and its parents recursively to the path.
if node.Cell == start {
var t = node
for true {
path.Cells = append(path.Cells, t.Cell)
t = t.Parent
if t == nil {
break
}
}
break
}
// Otherwise, we add the current node's neighbors to the list of cells to check, and list of cells that have already been
// checked (so we don't get nodes being checked multiple times).
if node.Cell.X > 0 {
c := m.Get(node.Cell.X-1, node.Cell.Y)
n := &Node{c, node, c.Cost + node.Cost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
if node.Cell.X < m.Width()-1 {
c := m.Get(node.Cell.X+1, node.Cell.Y)
n := &Node{c, node, c.Cost + node.Cost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
if node.Cell.Y > 0 {
c := m.Get(node.Cell.X, node.Cell.Y-1)
n := &Node{c, node, c.Cost + node.Cost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
if node.Cell.Y < m.Height()-1 {
c := m.Get(node.Cell.X, node.Cell.Y+1)
n := &Node{c, node, c.Cost + node.Cost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
// Do the same thing for diagonals.
if diagonals {
diagonalCost := .414 // Diagonal movement is slightly slower, so we should prioritize straightaways if possible
up := false
upNeighbor := m.Get(node.Cell.X, node.Cell.Y-1)
if upNeighbor != nil && upNeighbor.Walkable {
up = true
}
down := false
downNeighbor := m.Get(node.Cell.X, node.Cell.Y+1)
if downNeighbor != nil && downNeighbor.Walkable {
down = true
}
left := false
leftNeighbor := m.Get(node.Cell.X-1, node.Cell.Y)
if leftNeighbor != nil && leftNeighbor.Walkable {
up = true
}
right := false
rightNeighbor := m.Get(node.Cell.X+1, node.Cell.Y)
if rightNeighbor != nil && rightNeighbor.Walkable {
right = true
}
if node.Cell.X > 0 && node.Cell.Y > 0 {
c := m.Get(node.Cell.X-1, node.Cell.Y-1)
n := &Node{c, node, c.Cost + node.Cost + diagonalCost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) && (!wallsBlockDiagonals || (left && up)) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
if node.Cell.X < m.Width()-1 && node.Cell.Y > 0 {
c := m.Get(node.Cell.X+1, node.Cell.Y-1)
n := &Node{c, node, c.Cost + node.Cost + diagonalCost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) && (!wallsBlockDiagonals || (right && up)) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
if node.Cell.X > 0 && node.Cell.Y < m.Height()-1 {
c := m.Get(node.Cell.X-1, node.Cell.Y+1)
n := &Node{c, node, c.Cost + node.Cost + diagonalCost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) && (!wallsBlockDiagonals || (left && down)) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
if node.Cell.X < m.Width()-1 && node.Cell.Y < m.Height()-1 {
c := m.Get(node.Cell.X+1, node.Cell.Y+1)
n := &Node{c, node, c.Cost + node.Cost + diagonalCost}
if n.Cell.Walkable && !hasBeenAdded(n.Cell) && (!wallsBlockDiagonals || (right && down)) {
heap.Push(&openNodes, n)
checkedNodes = append(checkedNodes, n.Cell)
}
}
}
}
return path
}
// GetPath returns a Path, from the starting world X and Y position to the ending X and Y position. diagonals controls whether
// moving diagonally is acceptable when creating the Path. wallsBlockDiagonals indicates whether to allow diagonal movement "through" walls
// that are positioned diagonally. This is essentially just a smoother way to get a Path from GetPathFromCells().
func (m *Grid) GetPath(startX, startY, endX, endY float64, diagonals bool, wallsBlockDiagonals bool) *Path {
sx, sy := m.WorldToGrid(startX, startY)
sc := m.Get(sx, sy)
ex, ey := m.WorldToGrid(endX, endY)
ec := m.Get(ex, ey)
if sc != nil && ec != nil {
return m.GetPathFromCells(sc, ec, diagonals, wallsBlockDiagonals)
}
return nil
}
// DataAsStringArray returns a 2D array of runes for each Cell in the Grid. The first axis is the Y axis.
func (m *Grid) DataAsStringArray() []string {
data := []string{}
for y := 0; y < m.Height(); y++ {
data = append(data, "")
for x := 0; x < m.Width(); x++ {
data[y] += string(m.Data[y][x].Rune)
}
}
return data
}
// DataAsRuneArrays returns a 2D array of runes for each Cell in the Grid. The first axis is the Y axis.
func (m *Grid) DataAsRuneArrays() [][]rune {
runes := [][]rune{}
for y := 0; y < m.Height(); y++ {
runes = append(runes, []rune{})
for x := 0; x < m.Width(); x++ {
runes[y] = append(runes[y], m.Data[y][x].Rune)
}
}
return runes
}
// A Path is a struct that represents a path, or sequence of Cells from point A to point B. The Cells list is the list of Cells contained in the Path,
// and the CurrentIndex value represents the current step on the Path. Using Path.Next() and Path.Prev() advances and walks back the Path by one step.
type Path struct {
Cells []*Cell
CurrentIndex int
}
// TotalCost returns the total cost of the Path (i.e. is the sum of all of the Cells in the Path).
func (p *Path) TotalCost() float64 {
cost := 0.0
for _, cell := range p.Cells {
cost += cell.Cost
}
return cost
}
// Reverse reverses the Cells in the Path.
func (p *Path) Reverse() {
np := []*Cell{}
for c := len(p.Cells) - 1; c >= 0; c-- {
np = append(np, p.Cells[c])
}
p.Cells = np
}
// Restart restarts the Path, so that calling path.Current() will now return the first Cell in the Path.
func (p *Path) Restart() {
p.CurrentIndex = 0
}
// Current returns the current Cell in the Path.
func (p *Path) Current() *Cell {
return p.Cells[p.CurrentIndex]
}
// Next returns the next cell in the path. If the Path is at the end, Next() returns nil.
func (p *Path) Next() *Cell {
if p.CurrentIndex < len(p.Cells)-1 {
return p.Cells[p.CurrentIndex+1]
}
return nil
}
// Advance advances the path by one cell.
func (p *Path) Advance() {
p.CurrentIndex++
if p.CurrentIndex >= len(p.Cells) {
p.CurrentIndex = len(p.Cells) - 1
}
}
// Prev returns the previous cell in the path. If the Path is at the start, Prev() returns nil.
func (p *Path) Prev() *Cell {
if p.CurrentIndex > 0 {
return p.Cells[p.CurrentIndex-1]
}
return nil
}
// Same returns if the Path shares the exact same cells as the other specified Path.
func (p *Path) Same(otherPath *Path) bool {
if p == nil || otherPath == nil || len(p.Cells) != len(otherPath.Cells) {
return false
}
for i := range p.Cells {
if len(otherPath.Cells) <= i || p.Cells[i] != otherPath.Cells[i] {
return false
}
}
return true
}
// Length returns the length of the Path (how many Cells are in the Path).
func (p *Path) Length() int {
return len(p.Cells)
}
// Get returns the Cell of the specified index in the Path. If the index is outside of the
// length of the Path, it returns -1.
func (p *Path) Get(index int) *Cell {
if index < len(p.Cells) {
return p.Cells[index]
}
return nil
}
// Index returns the index of the specified Cell in the Path. If the Cell isn't contained
// in the Path, it returns -1.
func (p *Path) Index(cell *Cell) int {
for i, c := range p.Cells {
if c == cell {
return i
}
}
return -1
}
// SetIndex sets the index of the Path, allowing you to safely manually manipulate the Path
// as necessary. If the index exceeds the bounds of the Path, it will be clamped.
func (p *Path) SetIndex(index int) {
if index >= len(p.Cells) {
p.CurrentIndex = len(p.Cells) - 1
} else if index < 0 {
p.CurrentIndex = 0
} else {
p.CurrentIndex = index
}
}
// AtStart returns if the Path's current index is 0, the first Cell in the Path.
func (p *Path) AtStart() bool {
return p.CurrentIndex == 0
}
// AtEnd returns if the Path's current index is the last Cell in the Path.
func (p *Path) AtEnd() bool {
return p.CurrentIndex >= len(p.Cells)-1
}
// Node represents the node a path, it contains the cell it represents.
// Also contains other information such as the parent and the cost.
type Node struct {
Cell *Cell
Parent *Node
Cost float64
}
type minHeap []*Node
func (mH minHeap) Len() int { return len(mH) }
func (mH minHeap) Less(i, j int) bool { return mH[i].Cost < mH[j].Cost }
func (mH minHeap) Swap(i, j int) { mH[i], mH[j] = mH[j], mH[i] }
func (mH *minHeap) Pop() interface{} {
old := *mH
n := len(old)
x := old[n-1]
*mH = old[0 : n-1]
return x
}
func (mH *minHeap) Push(x interface{}) {
*mH = append(*mH, x.(*Node))
}