/
test08.go
141 lines (121 loc) · 2.58 KB
/
test08.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
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
139
140
141
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Šedesátá třetí část
// Programovací jazyk Go a 2D grafika – kostra jednoduché hry
// https://www.root.cz/clanky/programovaci-jazyk-go-a-2d-grafika-kostra-jednoduche-hry/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z šedesáté třetí části:
// https://github.com/tisnik/go-root/blob/master/article_63/README.md
package main
import (
"log"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
)
const (
width = 640
height = 480
)
type Game interface {
initialize()
finalize()
redraw()
eventLoop()
}
type gameState struct {
Window *sdl.Window
PrimarySurface *sdl.Surface
Image *sdl.Surface
X, Y int32
}
func NewGame() gameState {
return gameState{
Window: nil,
PrimarySurface: nil,
Image: nil,
}
}
func (state *gameState) initialize() {
err := sdl.Init(sdl.INIT_VIDEO)
if err != nil {
panic(err)
}
state.Window, err = sdl.CreateWindow("SDL2 example #8", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
width, height, sdl.WINDOW_SHOWN)
if err != nil {
panic(err)
}
state.PrimarySurface, err = state.Window.GetSurface()
if err != nil {
panic(err)
}
state.Image, err = img.Load("globe.png")
if err != nil {
panic(err)
}
state.X = width/2 - state.Image.W/2
state.Y = height/2 - state.Image.H/2
}
func (state *gameState) finalize() {
state.PrimarySurface.Free()
state.Image.Free()
state.Window.Destroy()
sdl.Quit()
}
func (state *gameState) redraw() {
state.PrimarySurface.FillRect(nil, sdl.MapRGB(state.PrimarySurface.Format, 192, 255, 192))
dstRect := sdl.Rect{
X: state.X,
Y: state.Y,
W: 0,
H: 0,
}
err := state.Image.Blit(nil, state.PrimarySurface, &dstRect)
if err != nil {
panic(err)
}
state.Window.UpdateSurface()
}
func (state *gameState) eventLoop() {
var event sdl.Event
done := false
for !done {
event = sdl.PollEvent()
switch t := event.(type) {
case *sdl.QuitEvent:
done = true
case *sdl.KeyboardEvent:
keyCode := t.Keysym.Sym
if t.State == sdl.PRESSED {
switch keyCode {
case sdl.K_ESCAPE:
done = true
case sdl.K_q:
done = true
case sdl.K_LEFT:
state.X -= 2
case sdl.K_RIGHT:
state.X += 2
case sdl.K_UP:
state.Y -= 2
case sdl.K_DOWN:
state.Y += 2
}
}
}
state.redraw()
sdl.Delay(20)
}
log.Println("Quitting")
}
func main() {
game := NewGame()
game.initialize()
defer game.finalize()
sdl.Delay(10)
game.eventLoop()
}