main.go 2.2 KB

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