Separate input and render goroutines

This commit is contained in:
Luke Meyers 2020-02-08 22:36:29 -08:00
parent 9c2dafd5fc
commit f29c115db6
2 changed files with 49 additions and 39 deletions

View File

@ -17,7 +17,6 @@ import (
) )
type RenderState struct { type RenderState struct {
Animating bool
Frames int Frames int
Frame int Frame int
} }
@ -87,9 +86,8 @@ func Render(rs RenderState, sOld, sNew game.State, w *pixelgl.Window, sb spriteB
renderSpawnPoints(sBatch, sNew.SpawnPoints, w.Bounds(), colors) renderSpawnPoints(sBatch, sNew.SpawnPoints, w.Bounds(), colors)
sBatch.Draw(w) sBatch.Draw(w)
if rs.Frame < rs.Frames {
rs.Frame++ rs.Frame++
if rs.Frame > rs.Frames {
rs.Animating = false
} }
return rs return rs
} }

42
main.go
View File

@ -29,7 +29,6 @@ func run() error {
s := game.NewState() s := game.NewState()
rs := gfx.RenderState{ rs := gfx.RenderState{
Animating: true,
Frames: 15, Frames: 15,
} }
sb, err := gfx.NewSpriteBank() sb, err := gfx.NewSpriteBank()
@ -39,20 +38,30 @@ func run() error {
sOld := s sOld := s
turn := 1 turn := 1
cmdC := make(chan []game.Command)
go func() { cmdC <- game.PollCommands(s) }()
stateCA := make(chan game.State)
stateCB := make(chan game.State)
go func(s game.State, sOld game.State, stateC <-chan game.State) {
var ( var (
frames = 0 frames = 0
second = time.Tick(time.Second) second = time.Tick(time.Second)
) )
cmdC := make(chan []game.Command)
go func() { cmdC <- game.PollCommands(s) }()
for !w.Closed() { for !w.Closed() {
if rs.Animating { if rs.Frame == rs.Frames {
rs = gfx.Render(rs, sOld, s, w, *sb) select {
if !rs.Animating { case ss := <-stateCA:
sOld = s sOld = s
s = ss
rs.Frame = 0
default:
} }
}
rs = gfx.Render(rs, sOld, s, w, *sb)
w.Update() w.Update()
frames++ frames++
@ -62,15 +71,14 @@ func run() error {
frames = 0 frames = 0
default: default:
} }
} else { }
}(s, sOld, stateCA)
for !w.Closed() {
switch { switch {
case w.Pressed(pixelgl.KeyQ): case w.Pressed(pixelgl.KeyQ):
return nil return nil
case w.Pressed(pixelgl.KeySpace) || true: case w.Pressed(pixelgl.KeySpace):
//log.Printf("TURN %d", turn)
rs.Animating = true
rs.Frame = 0
cmds := <-cmdC cmds := <-cmdC
s = game.UpdateState(s, sOld, cmds) s = game.UpdateState(s, sOld, cmds)
turn++ turn++
@ -79,12 +87,16 @@ func run() error {
sOld = s sOld = s
turn = 1 turn = 1
} }
go func() { cmdC <- game.PollCommands(s) }() go func() {
s := <-stateCB
cmdC <- game.PollCommands(s)
}()
stateCA <- s
stateCB <- s
} }
w.UpdateInput() w.UpdateInput()
} }
}
return nil return nil
} }