From 2d506dfc9874b58848abc5caedc184150d261151 Mon Sep 17 00:00:00 2001 From: giongto35 Date: Sat, 13 Apr 2019 12:32:33 +0800 Subject: [PATCH] Fix save load race condition by event queue --- ui/director.go | 10 ++++++---- ui/gameview.go | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/ui/director.go b/ui/director.go index a8d73bc9..592db041 100644 --- a/ui/director.go +++ b/ui/director.go @@ -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 } -} \ No newline at end of file +} diff --git a/ui/gameview.go b/ui/gameview.go index 4380379c..805bc8c5 100644 --- a/ui/gameview.go +++ b/ui/gameview.go @@ -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