-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.go
107 lines (86 loc) · 2.13 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"github.com/gdamore/tcell"
"slices"
"sync"
)
type SnakeDirection int
const (
LeftSnakeDirection SnakeDirection = iota
RightSnakeDirection
UpSnakeDirection
DownSnakeDirection
)
var (
keyToDirection = map[tcell.Key]SnakeDirection{
tcell.KeyLeft: LeftSnakeDirection,
tcell.KeyRight: RightSnakeDirection,
tcell.KeyUp: UpSnakeDirection,
tcell.KeyDown: DownSnakeDirection,
}
)
type Snake struct {
body []BoardLocation
direction SnakeDirection
directionMutex sync.Mutex
}
func NewSnake(location BoardLocation) *Snake {
return &Snake{
body: []BoardLocation{location},
direction: LeftSnakeDirection,
}
}
func (s *Snake) move(location BoardLocation) {
s.body = append(s.body, location)
s.body = s.body[1:]
}
func (s *Snake) head() BoardLocation {
return s.body[len(s.body)-1]
}
func (s *Snake) tail() BoardLocation {
return s.body[0]
}
func (s *Snake) nextHead() BoardLocation {
nextHead := s.head()
direction := s.getDirection()
switch direction {
case LeftSnakeDirection:
nextHead.x--
case RightSnakeDirection:
nextHead.x++
case UpSnakeDirection:
nextHead.y--
case DownSnakeDirection:
nextHead.y++
}
return nextHead
}
func (s *Snake) grow(next BoardLocation) {
s.body = append([]BoardLocation{next}, s.body...)
}
func (s *Snake) isIn(x, y int) bool {
return slices.Contains(s.body, BoardLocation{x: x, y: y})
}
func (s *Snake) getDirection() SnakeDirection {
s.directionMutex.Lock()
defer s.directionMutex.Unlock()
return s.direction
}
func (s *Snake) setDirection(direction SnakeDirection) {
s.directionMutex.Lock()
s.direction = direction
s.directionMutex.Unlock()
}
func (s *Snake) isValidDirection(direction SnakeDirection) bool {
if len(s.body) == 1 {
return true
}
currentDirection := s.getDirection()
if (currentDirection == LeftSnakeDirection && direction == RightSnakeDirection) ||
(currentDirection == RightSnakeDirection && direction == LeftSnakeDirection) ||
(currentDirection == UpSnakeDirection && direction == DownSnakeDirection) ||
(currentDirection == DownSnakeDirection && direction == UpSnakeDirection) {
return false
}
return true
}