forked from mattkelly/snake-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
food.go
69 lines (58 loc) · 1.51 KB
/
food.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
package main
import (
"math/rand"
tl "github.com/JoelOtter/termloop"
)
// Food handles its own collisions with a Snake and places itself randomly
// on the screen. Since there's no top-level controller, it also updates the
// score.
type Food struct {
*tl.Entity
coord Coord
value rune
}
// NewFood creates a new Food at a random position.
func NewFood(value rune) *Food {
f := new(Food)
f.Entity = tl.NewEntity(1, 1, 1, 1)
f.value = value
f.moveToRandomPosition()
return f
}
// Draw draws the Food as a default character.
func (f *Food) Draw(screen *tl.Screen) {
screen.RenderCell(f.coord.x, f.coord.y, &tl.Cell{
Fg: tl.ColorRed,
Ch: f.value,
})
}
// Position returns the x,y position of this Food.
func (f Food) Position() (int, int) {
return f.coord.x, f.coord.y
}
// Size returns the size of this Food - always 1x1.
func (f Food) Size() (int, int) {
return 1, 1
}
// Collide handles collisions with the Snake. It updates the score and places
// the Food randomly on the screen again.
func (f *Food) Collide(collision tl.Physical) {
switch collision.(type) {
case *Snake:
// It better be a snake that we're colliding with...
f.handleSnakeCollision()
}
}
func (f *Food) moveToRandomPosition() {
newX := randInRange(1, border.width-1)
newY := randInRange(1, border.height-1)
f.coord.x, f.coord.y = newX, newY
f.SetPosition(newX, newY)
}
func (f *Food) handleSnakeCollision() {
f.moveToRandomPosition()
IncreaseScore(5, f.value)
}
func randInRange(min, max int) int {
return rand.Intn(max-min) + min
}