-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.go
57 lines (51 loc) · 1.01 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
package main
type Part struct {
X int
Y int
}
type SnakeBody struct {
Parts []Part
Xspeed int
Yspeed int
}
func (sb *SnakeBody) ChangeDir(vertical int, horizontal int) {
sb.Yspeed = vertical
sb.Xspeed = horizontal
}
func (sb *SnakeBody) Update(width int, height int, longerSnake bool) {
sb.Parts = append(sb.Parts, sb.Parts[len(sb.Parts)-1].GetUpdatedPart(sb, width, height))
if !longerSnake {
sb.Parts = sb.Parts[1:]
}
}
func (sb *SnakeBody) ResetPos(width int, height int) {
snakeParts := []Part{
{
X: int(width / 2),
Y: int(height / 2),
},
{
X: int(width/2) + 1,
Y: int(height / 2),
},
{
X: int(width/2) + 2,
Y: int(height / 2),
},
}
sb.Parts = snakeParts
sb.Xspeed = 1
sb.Yspeed = 0
}
func (sp *Part) GetUpdatedPart(sb *SnakeBody, width int, height int) Part {
newPart := *sp
newPart.X = (newPart.X + sb.Xspeed) % width
if newPart.X < 0 {
newPart.X += width
}
newPart.Y = (newPart.Y + sb.Yspeed) % height
if newPart.Y < 0 {
newPart.Y += height
}
return newPart
}