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 {
Animating bool
Frames 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)
sBatch.Draw(w)
if rs.Frame < rs.Frames {
rs.Frame++
if rs.Frame > rs.Frames {
rs.Animating = false
}
return rs
}

42
main.go
View File

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