forked from ax4w/GoSnake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apple.go
69 lines (63 loc) · 1.32 KB
/
apple.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 (
"github.com/veandco/go-sdl2/sdl"
"math/rand"
)
func randomPosition() int32 {
return int32(rand.Intn(((windowSize - blockSize) - blockSize) + blockSize))
}
func areApplesOverlappingSnakeBody(x, y int32) bool {
for _, v := range snake {
if x >= v.X-blockSize && x <= v.X+blockSize &&
y >= v.Y-blockSize && y <= v.Y+blockSize {
return true
}
}
return false
}
func areApplesOverlapping(x, y int32) bool {
for _, v := range apples {
if x >= v.X-blockSize && x <= v.X+blockSize &&
y >= v.Y-blockSize && y <= v.Y+blockSize {
return true
}
}
return false
}
func renderApples(renderer *sdl.Renderer) {
for _, v := range apples {
err := renderer.SetDrawColor(48, 53, 48, 255)
if err != nil {
panic(err.Error())
}
err = renderer.FillRect(&sdl.Rect{
X: v.X,
Y: v.Y,
W: blockSize,
H: blockSize,
},
)
if err != nil {
return
}
err = renderer.Copy(
appleTexture,
&sdl.Rect{W: blockSize, H: blockSize},
&sdl.Rect{X: v.X, Y: v.Y, W: blockSize + 5, H: blockSize + 5},
)
}
}
func initApples() {
for i := 0; i < appleCount; i++ {
x := randomPosition()
y := randomPosition()
for areApplesOverlapping(x, y) || areApplesOverlappingSnakeBody(x, y) {
x = randomPosition()
y = randomPosition()
}
apples = append(apples, &apple{
X: x,
Y: y,
})
}
}