-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
157 lines (134 loc) · 2.39 KB
/
main.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package main
import (
"fmt"
"os"
"time"
"github.com/veandco/go-sdl2/sdl"
"github.com/veandco/go-sdl2/ttf"
)
var windowW, windowH int
func main() {
sdl.Main(func() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(2)
}
})
}
func run() error {
var w *sdl.Window
var r *sdl.Renderer
var err error
sdl.Do(func() {
err = sdl.Init(sdl.INIT_EVERYTHING)
})
if err != nil {
return fmt.Errorf("could not initialize SDL: %v", err)
}
defer func() {
sdl.Do(func() {
sdl.Quit()
})
}()
sdl.Do(func() {
err = ttf.Init()
})
if err != nil {
return fmt.Errorf("could not initialize TTF: %v", err)
}
defer func() {
sdl.Do(func() {
ttf.Quit()
})
}()
sdl.Do(func() {
w, r, err = sdl.CreateWindowAndRenderer(800, 600, sdl.WINDOW_SHOWN|sdl.WINDOW_FULLSCREEN_DESKTOP)
})
if err != nil {
return fmt.Errorf("could not create window: %v", err)
}
defer func() {
sdl.Do(func() {
w.Destroy()
})
}()
defer func() {
sdl.Do(func() {
r.Destroy()
})
}()
windowW, windowH = w.GetSize()
if err = drawTitle(r, "Flappy Gopher"); err != nil {
return fmt.Errorf("could not draw title: %v", err)
}
time.Sleep(1 * time.Second)
s, err := newScene(r)
if err != nil {
return fmt.Errorf("could not create scene: %v", err)
}
defer s.destroy()
events := make(chan sdl.Event)
errc := s.run(events)
for {
select {
case events <- sdl.WaitEvent():
case err := <-errc:
return err
}
}
}
func drawTitle(r *sdl.Renderer, text string) error {
var f *ttf.Font
var s *sdl.Surface
var t *sdl.Texture
var err error
sdl.Do(func() {
f, err = ttf.OpenFont("resources/fonts/Flappy.ttf", 20)
})
if err != nil {
return fmt.Errorf("could not load font: %v", err)
}
defer func() {
sdl.Do(func() {
f.Close()
})
}()
sdl.Do(func() {
s, err = f.RenderUTF8_Solid(text, sdl.Color{
R: 255,
G: 100,
B: 0,
A: 255,
})
})
if err != nil {
return fmt.Errorf("could not render surface: %v", err)
}
defer func() {
sdl.Do(func() {
s.Free()
})
}()
sdl.Do(func() {
t, err = r.CreateTextureFromSurface(s)
})
if err != nil {
return fmt.Errorf("could not create texture: %v", err)
}
defer func() {
sdl.Do(func() {
t.Destroy()
})
}()
sdl.Do(func() {
r.Clear()
err = r.Copy(t, nil, nil)
})
if err != nil {
return fmt.Errorf("could not copy texture: %v", err)
}
sdl.Do(func() {
r.Present()
})
return nil
}