-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.go
More file actions
138 lines (114 loc) · 2.09 KB
/
game.go
File metadata and controls
138 lines (114 loc) · 2.09 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
//"fmt"
"image/color"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
const (
sWidth = 640
sHeight = 480
cellSize = 20
)
type Direction int
const (
Up Direction = iota
Down
Left
Right
)
type Point struct {
X int
Y int
}
type Game struct {
snake []Point
direction Direction
food Point
gameover bool
tick int
point int
}
func NewGame() *Game {
g := &Game{
snake : []Point{{5,5}, {4,5}, {3,5}},
direction: Right,
point : 0,
}
g.food = SpawnFood(g.snake)
return g
}
func (g *Game) moveSnake() {
head := g.snake[0]
switch g.direction {
case Up:
head.Y--
case Down:
head.Y++
case Left:
head.X--
case Right:
head.X++
}
g.snake = append([]Point{head}, g.snake...)
g.snake = g.snake[:len(g.snake)-1]
}
func (g *Game) Reset() {
g.snake = []Point{{5, 5}, {4, 5}, {3, 5}}
g.direction = Right
g.food = SpawnFood(g.snake)
g.gameover = false
g.tick = 0
g.point = 0
}
func(g *Game) Update() error {
if g.gameover {
if inpututil.IsKeyJustPressed(ebiten.KeyR) {
g.gameover = false
g.Reset()
}
if ebiten.IsKeyPressed(ebiten.KeyQ) || ebiten.IsKeyPressed(ebiten.KeyEscape) {
return ebiten.Termination
}
return nil
}
HandleInput(g)
g.tick++
if g.tick%8 != 0 {
return nil
}
g.moveSnake()
CheckCollision(g)
if ebiten.IsKeyPressed(ebiten.KeyQ) || ebiten.IsKeyPressed(ebiten.KeyEscape) {
return ebiten.Termination
}
//fmt.Println("Tick:", g.tick, "Head:", g.snake[0], "GameOver:", g.gameover)
return nil
}
func (g *Game) Draw(screen *ebiten.Image) {
screen.Fill(color.Black)
// snake
for _, s := range g.snake {
ebitenutil.DrawRect(
screen,
float64(s.X * cellSize),
float64(s.Y * cellSize),
cellSize,
cellSize,
color.RGBA{0,255,0,255},
)
}
//food
ebitenutil.DrawRect(
screen,
float64(g.food.X*cellSize),
float64(g.food.Y*cellSize),
cellSize,
cellSize,
color.RGBA{255, 0, 0, 255},
)
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
return sWidth, sHeight
}