Extract persistence code into own class

This commit is contained in:
Marc Di Luzio 2020-06-02 19:16:02 +01:00
parent 4c76530832
commit c5ebbc3c40
9 changed files with 163 additions and 149 deletions

View file

@ -1,11 +1,7 @@
package game
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"github.com/google/uuid"
)
@ -30,47 +26,12 @@ type Instance struct {
const kWorldFileName = "rove-world.json"
// NewWorld creates a new world object
func NewWorld(data string) *World {
func NewWorld() *World {
return &World{
Instances: make(map[uuid.UUID]Instance),
dataPath: data,
}
}
// path returns the full path to the data file
func (w *World) path() string {
return path.Join(w.dataPath, kWorldFileName)
}
// Load will load the accountant from data
func (w *World) Load() error {
// Don't load anything if the file doesn't exist
_, err := os.Stat(w.path())
if os.IsNotExist(err) {
fmt.Printf("File %s didn't exist, loading with fresh world data\n", w.path())
return nil
}
if b, err := ioutil.ReadFile(w.path()); err != nil {
return err
} else if err := json.Unmarshal(b, &w); err != nil {
return err
}
return nil
}
// Save will save the accountant data out
func (w *World) Save() error {
if b, err := json.MarshalIndent(w, "", "\t"); err != nil {
return err
} else {
if err := ioutil.WriteFile(w.path(), b, os.ModePerm); err != nil {
return err
}
}
return nil
}
// Adds an instance to the game
func (w *World) CreateInstance() uuid.UUID {
id := uuid.New()