/
main.go
503 lines (432 loc) · 11 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package main
import (
"errors"
"fmt"
"math/rand"
"runtime"
"time"
"github.com/go-gl/gl"
glfw "github.com/go-gl/glfw3"
)
var (
ship *Ship
bullets []*Bullet
torpedos []*Torpedo
mines []*Mine
asteroids []*Asteroid
explosions []*Explosion
bigExplosions []*BigExplosion
gameWidth float64
gameHeight float64
fieldSize float64 = 400
fullscreen bool = false
altEnter bool = false
colorsInverted bool = false
wireframe bool = true
paused bool = false
rng = rand.New(rand.NewSource(time.Now().UnixNano()))
score int = 0
highscore int = 0
showHighscore bool = true
difficulty int = 6
debug bool = true
)
func errorCallback(err glfw.ErrorCode, desc string) {
fmt.Printf("%v: %v\n", err, desc)
}
func main() {
runtime.LockOSThread()
glfw.SetErrorCallback(errorCallback)
if !glfw.Init() {
panic("can't init glfw!")
}
defer glfw.Terminate()
var window *glfw.Window = initGame()
runGameLoop(window)
fmt.Printf("Your highscore was %d points!\n", highscore)
}
func keyCallback(window *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
//fmt.Printf("%v, %v, %v, %v\n", key, scancode, action, mods)
if key == glfw.KeyEscape && action == glfw.Press {
window.SetShouldClose(true)
}
if !paused {
if key == glfw.KeyLeft {
if action == glfw.Press {
ship.RotateLeft(true)
} else if action == glfw.Release {
ship.RotateLeft(false)
}
} else if key == glfw.KeyRight {
if action == glfw.Press {
ship.RotateRight(true)
} else if action == glfw.Release {
ship.RotateRight(false)
}
}
if key == glfw.KeyUp {
if action == glfw.Press {
ship.Accelerate(true)
} else if action == glfw.Release {
ship.Accelerate(false)
}
} else if key == glfw.KeyDown {
if action == glfw.Press {
ship.Decelerate(true)
} else if action == glfw.Release {
ship.Decelerate(false)
}
}
if key == glfw.KeySpace || key == glfw.KeyX {
if action == glfw.Press {
ship.Shoot(true)
} else if action == glfw.Release {
ship.Shoot(false)
}
}
if (key == glfw.KeyY || key == glfw.KeyZ || key == glfw.KeyLeftShift || key == glfw.KeyRightShift) && action == glfw.Press {
ship.DropMine()
}
if (key == glfw.KeyC || key == glfw.KeyLeftControl || key == glfw.KeyRightControl) && action == glfw.Press {
ship.ShootTorpedo()
}
}
if key == glfw.KeyEnter && action == glfw.Press { //&& mods == glfw.ModAlt {
altEnter = true
}
if key == glfw.KeyF1 && action == glfw.Press {
switchHighscore()
}
if key == glfw.KeyF2 && action == glfw.Press {
switchColors()
}
if key == glfw.KeyF3 && action == glfw.Press {
switchWireframe()
}
if (key == glfw.KeyF9 || key == glfw.KeyR || key == glfw.KeyBackspace) && action == glfw.Press {
score = 0
resetGame()
}
if (key == glfw.KeyPause || key == glfw.KeyP) && action == glfw.Press {
paused = !paused
}
if key == glfw.KeyN && action == glfw.Press && isGameWon() {
difficulty += 3
resetGame()
}
if debug && key == glfw.KeyF10 && action == glfw.Press {
for _, asteroid := range asteroids {
if asteroid.IsAlive() {
asteroid.Destroy()
}
}
for _, mine := range mines {
if mine.IsAlive() {
mine.Destroy()
}
}
}
}
func reshapeWindow(window *glfw.Window, width, height int) {
ratio := float64(width) / float64(height)
gameWidth = ratio * fieldSize
gameHeight = fieldSize
gl.Viewport(0, 0, width, height)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, gameWidth, 0, gameHeight, -1.0, 1.0)
gl.MatrixMode(gl.MODELVIEW)
if wireframe {
gl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE)
}
}
func initWindow() (window *glfw.Window, err error) {
monitor, err := glfw.GetPrimaryMonitor()
if err != nil {
return nil, err
}
videomode, err := monitor.GetVideoMode()
if err != nil {
return nil, err
}
if videomode.Height < 480 || videomode.Width < 640 {
return nil, errors.New("unsupported resolution!")
}
ratio := float64(videomode.Width) / float64(videomode.Height)
if fullscreen {
glfw.WindowHint(glfw.Decorated, 0)
window, err = glfw.CreateWindow(videomode.Width, videomode.Height, "Golang Asteroids!", nil, nil)
if err != nil {
return nil, err
}
window.SetPosition(0, 0)
} else {
glfw.WindowHint(glfw.Decorated, 1)
window, err = glfw.CreateWindow(int(ratio*480), 480, "Golang Asteroids!", nil, nil)
if err != nil {
return nil, err
}
window.SetPosition(videomode.Width/2-320, videomode.Height/2-240)
}
window.SetKeyCallback(keyCallback)
window.SetFramebufferSizeCallback(reshapeWindow)
window.MakeContextCurrent()
gl.Init()
gl.ClearColor(gl.GLclampf(Colorize(0)), gl.GLclampf(Colorize(0)), gl.GLclampf(Colorize(0)), 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
width, height := window.GetFramebufferSize()
reshapeWindow(window, width, height)
return window, nil
}
func switchHighscore() {
showHighscore = !showHighscore
}
func switchColors() {
colorsInverted = !colorsInverted
gl.ClearColor(gl.GLclampf(Colorize(0)), gl.GLclampf(Colorize(0)), gl.GLclampf(Colorize(0)), 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
}
func switchWireframe() {
wireframe = !wireframe
if wireframe {
gl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE)
} else {
gl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL)
}
}
func isGameWon() bool {
return len(asteroids) == 0 && ship.IsAlive()
}
func isGameLost() bool {
return !ship.IsAlive()
}
func initGame() *glfw.Window {
window, err := initWindow()
if err != nil {
panic(err)
}
resetGame()
return window
}
func resetGame() {
// init ship
ship = NewShip(gameWidth/2, gameHeight/2, 0, 0.01)
// create a couple of random asteroids
asteroids = nil
for i := 1; i <= difficulty; i++ {
CreateAsteroid(2+rng.Float64()*8, 3)
}
bullets = nil
mines = nil
explosions = nil
torpedos = nil
bigExplosions = nil
}
func drawHighScore() {
if score > highscore {
highscore = score
}
if showHighscore {
DrawString(10, fieldSize-32, 1, Color{0.5, 0.5, 0.5}, fmt.Sprintf("highscore: %d", highscore))
}
}
func drawCurrentScore() {
DrawString(10, fieldSize-20, 1, Color{1, 1, 1}, fmt.Sprintf("score: %d", score))
}
func drawWinningScreen() {
DrawString(fieldSize/2-20, fieldSize/2+10, 5, Color{1, 1, 1}, fmt.Sprintf("You won!"))
DrawString(fieldSize/2-120, fieldSize/2-20, 1.5, Color{1, 1, 1}, fmt.Sprintf("Press R to restart current level"))
DrawString(fieldSize/2-120, fieldSize/2-50, 1.5, Color{1, 1, 1}, fmt.Sprintf("Press N to advance to next difficulty level"))
}
func drawGameOverScreen() {
DrawString(fieldSize/2-20, fieldSize/2+10, 5, Color{1, 1, 1}, fmt.Sprintf("Game Over!"))
DrawString(fieldSize/2-120, fieldSize/2-20, 1.5, Color{1, 1, 1}, fmt.Sprintf("Press R to restart current level"))
}
func addScore(value int) {
if ship.IsAlive() {
score = score + value
}
}
func runGameLoop(window *glfw.Window) {
for !window.ShouldClose() {
// update objects
updateObjects()
// hit detection
hitDetection()
// ---------------------------------------------------------------
// draw calls
gl.Clear(gl.COLOR_BUFFER_BIT)
drawCurrentScore()
drawHighScore()
if isGameWon() {
drawWinningScreen()
} else if isGameLost() {
drawGameOverScreen()
}
// draw everything 9 times in a 3x3 grid stitched together for seamless clipping
for x := -1.0; x < 2.0; x++ {
for y := -1.0; y < 2.0; y++ {
gl.MatrixMode(gl.MODELVIEW)
gl.PushMatrix()
gl.Translated(gameWidth*x, gameHeight*y, 0)
drawObjects()
gl.PopMatrix()
}
}
gl.Flush()
window.SwapBuffers()
glfw.PollEvents()
// switch resolution
if altEnter {
window.Destroy()
fullscreen = !fullscreen
var err error
window, err = initWindow()
if err != nil {
panic(err)
}
altEnter = false
gl.LineWidth(1)
if fullscreen {
gl.LineWidth(2)
}
}
}
}
func drawObjects() {
ship.Draw(false)
for _, bullet := range bullets {
bullet.Draw(false)
}
for _, torpedo := range torpedos {
torpedo.Draw(false)
}
for _, mine := range mines {
mine.Draw(false)
}
for _, asteroid := range asteroids {
asteroid.Draw(true)
}
for _, explosion := range explosions {
explosion.Draw()
}
for _, bigExplosion := range bigExplosions {
bigExplosion.Draw(false)
}
}
func updateObjects() {
//check if objects are still alive
var bullets2 []*Bullet
for _, bullet := range bullets {
if bullet.IsAlive() {
bullets2 = append(bullets2, bullet)
}
}
bullets = bullets2
var torpedos2 []*Torpedo
for _, torpedo := range torpedos {
if torpedo.IsAlive() {
torpedos2 = append(torpedos2, torpedo)
}
}
torpedos = torpedos2
var mines2 []*Mine
for _, mine := range mines {
if mine.IsAlive() {
mines2 = append(mines2, mine)
}
}
mines = mines2
var asteroids2 []*Asteroid
for _, asteroid := range asteroids {
if asteroid.IsAlive() {
asteroids2 = append(asteroids2, asteroid)
}
}
asteroids = asteroids2
var explosions2 []*Explosion
for _, explosion := range explosions {
if explosion.IsAlive() {
explosions2 = append(explosions2, explosion)
}
}
explosions = explosions2
var bigExplosions2 []*BigExplosion
for _, bigExplosion := range bigExplosions {
if bigExplosion.IsAlive() {
bigExplosions2 = append(bigExplosions2, bigExplosion)
}
}
bigExplosions = bigExplosions2
// call their update func
ship.Update()
for _, bullet := range bullets {
bullet.Update()
}
for _, torpedo := range torpedos {
torpedo.Update()
}
for _, mine := range mines {
mine.Update()
}
for _, asteroid := range asteroids {
asteroid.Update()
}
for _, explosion := range explosions {
explosion.Update()
}
for _, bigExplosion := range bigExplosions {
bigExplosion.Update()
}
}
func hitDetection() {
for _, asteroid := range asteroids {
for _, bullet := range bullets {
if IsColliding(&asteroid.Entity, &bullet.Entity) {
asteroid.Destroy()
bullet.Destroy()
}
}
// for _, torpedo := range torpedos {
// if IsColliding(&asteroid.Entity, &torpedo.Entity) {
// asteroid.Destroy()
// torpedo.Destroy()
// }
// }
for _, mine := range mines {
if IsColliding(&asteroid.Entity, &mine.Entity) {
asteroid.Destroy()
mine.Destroy()
}
}
for _, bigExplosion := range bigExplosions {
if IsColliding(&asteroid.Entity, &bigExplosion.Entity) {
asteroid.Destroy()
}
}
if ship.IsAlive() && IsColliding(&asteroid.Entity, &ship.Entity) {
asteroid.Destroy()
ship.Destroy()
}
}
// for _, torpedo := range torpedos {
// if ship.IsAlive() && IsColliding(&torpedo.Entity, &ship.Entity) {
// torpedo.Destroy()
// ship.Destroy()
// }
// }
for _, bigExplosion := range bigExplosions {
if ship.IsAlive() && IsColliding(&bigExplosion.Entity, &ship.Entity) {
ship.Destroy()
}
}
for _, mine := range mines {
if ship.IsAlive() && IsColliding(&mine.Entity, &ship.Entity) {
mine.Destroy()
ship.Destroy()
}
}
}