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