main.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build darwin || linux
  5. // Flappy Gopher is a simple one-button game that uses the
  6. // mobile framework and the experimental sprite engine.
  7. package main
  8. import (
  9. "math/rand"
  10. "time"
  11. "golang.org/x/mobile/app"
  12. "golang.org/x/mobile/event/key"
  13. "golang.org/x/mobile/event/lifecycle"
  14. "golang.org/x/mobile/event/paint"
  15. "golang.org/x/mobile/event/size"
  16. "golang.org/x/mobile/event/touch"
  17. "golang.org/x/mobile/exp/gl/glutil"
  18. "golang.org/x/mobile/exp/sprite"
  19. "golang.org/x/mobile/exp/sprite/clock"
  20. "golang.org/x/mobile/exp/sprite/glsprite"
  21. "golang.org/x/mobile/gl"
  22. )
  23. func main() {
  24. rand.Seed(time.Now().UnixNano())
  25. app.Main(func(a app.App) {
  26. var glctx gl.Context
  27. var sz size.Event
  28. for e := range a.Events() {
  29. switch e := a.Filter(e).(type) {
  30. case lifecycle.Event:
  31. switch e.Crosses(lifecycle.StageVisible) {
  32. case lifecycle.CrossOn:
  33. glctx, _ = e.DrawContext.(gl.Context)
  34. onStart(glctx)
  35. a.Send(paint.Event{})
  36. case lifecycle.CrossOff:
  37. onStop()
  38. glctx = nil
  39. }
  40. case size.Event:
  41. sz = e
  42. case paint.Event:
  43. if glctx == nil || e.External {
  44. continue
  45. }
  46. onPaint(glctx, sz)
  47. a.Publish()
  48. a.Send(paint.Event{}) // keep animating
  49. case touch.Event:
  50. if down := e.Type == touch.TypeBegin; down || e.Type == touch.TypeEnd {
  51. game.Press(down)
  52. }
  53. case key.Event:
  54. if e.Code != key.CodeSpacebar {
  55. break
  56. }
  57. if down := e.Direction == key.DirPress; down || e.Direction == key.DirRelease {
  58. game.Press(down)
  59. }
  60. }
  61. }
  62. })
  63. }
  64. var (
  65. startTime = time.Now()
  66. images *glutil.Images
  67. eng sprite.Engine
  68. scene *sprite.Node
  69. game *Game
  70. )
  71. func onStart(glctx gl.Context) {
  72. images = glutil.NewImages(glctx)
  73. eng = glsprite.Engine(images)
  74. game = NewGame()
  75. scene = game.Scene(eng)
  76. }
  77. func onStop() {
  78. eng.Release()
  79. images.Release()
  80. game = nil
  81. }
  82. func onPaint(glctx gl.Context, sz size.Event) {
  83. glctx.ClearColor(1, 1, 1, 1)
  84. glctx.Clear(gl.COLOR_BUFFER_BIT)
  85. now := clock.Time(time.Since(startTime) * 60 / time.Second)
  86. game.Update(now)
  87. eng.Render(scene, now, sz)
  88. }