save state

This commit is contained in:
Settel 2021-09-19 23:31:24 +02:00
parent 47ead87043
commit b921f7b7ee
7 changed files with 70 additions and 2 deletions

1
server/.gitignore vendored
View File

@ -1 +1,2 @@
knyt knyt
data/games/*/state.json

View File

@ -21,4 +21,4 @@ _run-endless-loop:
while true; do $(MAKE) run || sleep 3; done while true; do $(MAKE) run || sleep 3; done
_run-inotify-restart: _run-inotify-restart:
inotifyloop . curl -s http://localhost:32039/__intern__/exit inotifyloop --exclude 'data/.*' . curl -s http://localhost:32039/__intern__/exit

View File

@ -22,4 +22,8 @@ func (app *Application) ContinueGame(usr *user.User, w http.ResponseWriter, r *h
} }
gm.ContinueGame() gm.ContinueGame()
if err := app.saveGame(gm); err != nil {
fmt.Println(err)
}
} }

View File

@ -0,0 +1,37 @@
package application
import (
"encoding/json"
"os"
"path"
"sirlab.de/go/knyt/game"
)
func (app *Application) saveGame(gm *game.Game) error {
gameJson := gm.GetGameState()
jsonString, errMarshal := json.MarshalIndent(gameJson, "", " ")
if errMarshal != nil {
return errMarshal
}
dirName := path.Join(app.config.DataDir, "games", gm.GetId())
f, err := os.CreateTemp(dirName, "state.tmp-*.json")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(jsonString); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
fileName := path.Join(dirName, "state.json")
if err := os.Rename(f.Name(), fileName); err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,21 @@
package game
func (gm *Game) GetGameState() GameStateJson {
gm.mu.Lock()
defer gm.mu.Unlock()
stateJson := GameStateJson{
Scores: make(map[string]int, 0),
QuotesPlayed: make([]string, 0),
}
for id, pi := range gm.players {
stateJson.Scores[id] = pi.score
}
for id, quote := range gm.quotes {
if quote.IsPlayed() {
stateJson.QuotesPlayed = append(stateJson.QuotesPlayed, id)
}
}
return stateJson
}

View File

@ -65,6 +65,6 @@ func (gm *Game) AddPlayer(usr *user.User) {
name: usr.GetName(), name: usr.GetName(),
isPlaying: false, isPlaying: false,
isIdle: true, isIdle: true,
score: 7, score: 0,
} }
} }

View File

@ -66,3 +66,8 @@ type Game struct {
type GameJson struct { type GameJson struct {
Name string `json:"name"` Name string `json:"name"`
} }
type GameStateJson struct {
Scores map[string]int `json:"scores"`
QuotesPlayed []string `json:"quotesPlayed"`
}