-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmechanics.go
60 lines (49 loc) · 1.48 KB
/
mechanics.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
package main
import (
"math/rand"
"github.com/golang-cz/snake/proto"
)
func (s *Server) createSnake(username string) (uint64, error) {
s.lastSnakeId++
randOffset := uint(rand.Intn(10) - rand.Intn(10))
snakeId := s.lastSnakeId
s.state.Snakes[snakeId] = &proto.Snake{
Id: snakeId,
Name: username,
Color: randColor(),
Body: []*proto.Square{
{X: 36, Y: 35 + randOffset},
{X: 35, Y: 35 + randOffset},
{X: 34, Y: 35 + randOffset},
},
Direction: &right,
}
return snakeId, nil
}
func turnSnake(snake *proto.Snake, direction *proto.Direction, buf int) error {
lastDirection := *snake.Direction
if len(snake.NextDirections) > 0 {
lastDirection = *snake.NextDirections[len(snake.NextDirections)-1]
}
// Same direction.
if lastDirection == *direction {
return proto.ErrTurnSameDirection
}
// Disallow turnabouts.
switch {
case lastDirection == proto.Direction_up && *direction == proto.Direction_down:
return proto.ErrTurnAbout
case lastDirection == proto.Direction_down && *direction == proto.Direction_up:
return proto.ErrTurnAbout
case lastDirection == proto.Direction_left && *direction == proto.Direction_right:
return proto.ErrTurnAbout
case lastDirection == proto.Direction_right && *direction == proto.Direction_left:
return proto.ErrTurnAbout
}
if len(snake.NextDirections) > buf {
snake.NextDirections = append(snake.NextDirections[:buf], direction)
} else {
snake.NextDirections = append(snake.NextDirections, direction)
}
return nil
}