-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrid.go
73 lines (62 loc) · 1.41 KB
/
grid.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
package main
import (
"image"
"math"
"strings"
"github.com/golang-cz/snake/proto"
)
type grid []string
func (g grid) String() string {
var b strings.Builder
b.WriteByte('\n')
b.WriteString(strings.Repeat("▮", len(g)+2))
b.WriteByte('\n')
for _, row := range g {
b.WriteString("▮")
b.WriteString(row)
b.WriteString("▮")
b.WriteByte('\n')
}
b.WriteString(strings.Repeat("▮", len(g)+2))
b.WriteByte('\n')
return b.String()
}
// Neighbours implements the astar.Graph interface
func (g grid) Neighbours(p image.Point) []image.Point {
offsets := []image.Point{
image.Pt(0, -1), // North
image.Pt(1, 0), // East
image.Pt(0, 1), // South
image.Pt(-1, 0), // West
}
res := make([]image.Point, 0, 4)
for _, off := range offsets {
q := p.Add(off)
if g.isFreeAt(q) {
res = append(res, q)
}
}
return res
}
func (g grid) isFreeAt(p image.Point) bool {
return g.isInBounds(p) && g.get(p) != rune(0)
}
func (g grid) isInBounds(p image.Point) bool {
return p.Y >= 0 && p.X >= 0 && p.Y < len(g) && p.X < len(g[p.Y])
}
func (g grid) put(p image.Point, c rune) {
g[p.Y] = g[p.Y][:p.X] + string(c) + g[p.Y][p.X+1:]
}
func (g grid) get(p image.Point) rune {
return rune(g[p.Y][p.X])
}
func distance(p, q image.Point) float64 {
d := q.Sub(p)
return math.Sqrt(float64(d.X*d.X + d.Y*d.Y))
}
func squareToPoint(s *proto.Square) image.Point {
return image.Point{
X: int(s.X),
Y: int(s.Y),
}
}