/
snek.go
88 lines (74 loc) · 1.33 KB
/
snek.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
package goSnek
import (
"image/color"
"math/rand"
"time"
"github.com/hajimehoshi/ebiten/v2"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const (
Width = 600
Height = 600
Scale = 60
Fps = 10
)
type Game struct {
body []Body
pos Body
dir Body
food Body
size int
snakeSize int
bodyImage *ebiten.Image
op ebiten.DrawImageOptions
frameCount int
}
func NewGame() *Game {
g := &Game{
size: Width / Scale,
pos: Body{
x: Scale / 2,
y: Scale / 2,
},
dir: Body{
x: 1,
y: 0,
},
snakeSize: 3,
}
g.bodyImage = ebiten.NewImage(g.size, g.size)
g.bodyImage.Fill(color.White)
return g
}
type Body struct {
x int
y int
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return Width, Height
}
func (g *Game) Update() error {
if dir, ok := g.Dir(); ok {
g.dir = dir
}
g.frameCount++
if g.frameCount >= 60/Fps {
g.frameCount = 0
g.pos = moveSnek(g.pos, g.dir)
g.body = append(g.body, Body{x: g.pos.x, y: g.pos.y})
for len(g.body) > g.snakeSize {
g.body = removeAt(g.body, 0)
}
}
return nil
}
func (g *Game) Draw(screen *ebiten.Image) {
for i := range g.body {
b := g.body[i]
g.op.GeoM.Reset()
g.op.GeoM.Translate(float64(b.x*g.size), float64(b.y*g.size))
screen.DrawImage(g.bodyImage, &g.op)
}
}