/
snake.go
86 lines (70 loc) · 1.15 KB
/
snake.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
package snake
import "errors"
// Allowed snake movement directions
const (
RIGHT direction = 1 + iota
LEFT
UP
DOWN
)
type direction int
type snake struct {
body []coord
direction direction
length int
}
func newSnake(d direction, b []coord) *snake {
return &snake{
length: len(b),
body: b,
direction: d,
}
}
func (s *snake) changeDirection(d direction) {
opposites := map[direction]direction{
RIGHT: LEFT,
LEFT: RIGHT,
UP: DOWN,
DOWN: UP,
}
if o := opposites[d]; o != 0 && o != s.direction {
s.direction = d
}
}
func (s *snake) head() coord {
return s.body[len(s.body)-1]
}
func (s *snake) die() error {
return errors.New("Died")
}
func (s *snake) move() error {
h := s.head()
c := coord{x: h.x, y: h.y}
switch s.direction {
case RIGHT:
c.x++
case LEFT:
c.x--
case UP:
c.y++
case DOWN:
c.y--
}
if s.isOnPosition(c) {
return s.die()
}
if s.length > len(s.body) {
s.body = append(s.body, c)
} else {
s.body = append(s.body[1:], c)
}
return nil
}
func (s *snake) isOnPosition(c coord) bool {
for _, b := range s.body {
if b.x == c.x && b.y == c.y {
return true
}
}
return false
}