Fix save load race condition by event queue

This commit is contained in:
giongto35 2019-04-13 12:32:33 +08:00
parent 58f3d244e2
commit 2d506dfc98
2 changed files with 33 additions and 4 deletions

View file

@ -16,7 +16,7 @@ type Director struct {
inputChannel chan int
closedChannel chan bool
roomID string
hash string
hash string
}
const FPS = 60
@ -94,7 +94,8 @@ func (d *Director) PlayGame(path string) {
func (d *Director) SaveGame() error {
if d.hash != "" {
return d.view.console.SaveState(savePath(d.hash))
d.view.Save(d.hash)
return nil
} else {
return nil
}
@ -102,8 +103,9 @@ func (d *Director) SaveGame() error {
func (d *Director) LoadGame() error {
if d.hash != "" {
return d.view.console.LoadState(savePath(d.hash))
d.view.Load(d.hash)
return nil
} else {
return nil
}
}
}

View file

@ -36,6 +36,9 @@ type GameView struct {
// equivalent to the list key pressed const above
keyPressed [NumKeys * 2]bool
savingPath string
loadingPath string
imageChannel chan *image.RGBA
inputChannel chan int
}
@ -108,12 +111,36 @@ func (view *GameView) Update(t, dt float64) {
}
console := view.console
view.updateControllers()
view.UpdateEvents()
console.StepSeconds(dt)
// fps to set frame
view.imageChannel <- console.Buffer()
}
func (view *GameView) Save(hash string) {
// put saving event to queue, process in updateEvent
view.savingPath = savePath(view.hash)
}
func (view *GameView) Load(path string) {
// put saving event to queue, process in updateEvent
view.loadingPath = savePath(view.hash)
}
func (view *GameView) UpdateEvents() {
// If there is saving event, save and discard the save event
if view.savingPath != "" {
view.console.SaveState(view.savingPath)
view.savingPath = ""
}
// If there is loading event, save and discard the load event
if view.loadingPath != "" {
view.console.LoadState(view.loadingPath)
view.loadingPath = ""
}
}
func (view *GameView) updateControllers() {
// Divide keyPressed to player 1 and player 2
// First 8 keys are player 1