save state
This commit is contained in:
parent
47ead87043
commit
b921f7b7ee
1
server/.gitignore
vendored
1
server/.gitignore
vendored
@ -1 +1,2 @@
|
||||
knyt
|
||||
data/games/*/state.json
|
||||
|
@ -21,4 +21,4 @@ _run-endless-loop:
|
||||
while true; do $(MAKE) run || sleep 3; done
|
||||
|
||||
_run-inotify-restart:
|
||||
inotifyloop . curl -s http://localhost:32039/__intern__/exit
|
||||
inotifyloop --exclude 'data/.*' . curl -s http://localhost:32039/__intern__/exit
|
||||
|
@ -22,4 +22,8 @@ func (app *Application) ContinueGame(usr *user.User, w http.ResponseWriter, r *h
|
||||
}
|
||||
|
||||
gm.ContinueGame()
|
||||
|
||||
if err := app.saveGame(gm); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
|
37
server/src/application/saveGame.go
Normal file
37
server/src/application/saveGame.go
Normal 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
|
||||
}
|
21
server/src/game/getGameState.go
Normal file
21
server/src/game/getGameState.go
Normal 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
|
||||
}
|
@ -65,6 +65,6 @@ func (gm *Game) AddPlayer(usr *user.User) {
|
||||
name: usr.GetName(),
|
||||
isPlaying: false,
|
||||
isIdle: true,
|
||||
score: 7,
|
||||
score: 0,
|
||||
}
|
||||
}
|
||||
|
@ -66,3 +66,8 @@ type Game struct {
|
||||
type GameJson struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type GameStateJson struct {
|
||||
Scores map[string]int `json:"scores"`
|
||||
QuotesPlayed []string `json:"quotesPlayed"`
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user