Serialise the World as well

This commit is contained in:
Marc Di Luzio 2020-06-02 17:51:54 +01:00
parent 50c970fea2
commit 68d117e0d8
5 changed files with 76 additions and 31 deletions

View file

@ -1,14 +1,21 @@
package game
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"github.com/google/uuid"
)
// World describes a self contained universe and everything in it
type World struct {
instances map[uuid.UUID]Instance
Instances map[uuid.UUID]Instance `json:"instances"`
// dataPath is the location for the data to be stored
dataPath string
}
// Instance describes a single entity or instance of an entity in the world
@ -20,13 +27,50 @@ type Instance struct {
pos Position
}
const kWorldFileName = "rove-world.json"
// NewWorld creates a new world object
func NewWorld() *World {
func NewWorld(data string) *World {
return &World{
instances: make(map[uuid.UUID]Instance),
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()
@ -37,14 +81,14 @@ func (w *World) CreateInstance() uuid.UUID {
}
// Append the instance to the list
w.instances[id] = instance
w.Instances[id] = instance
return id
}
// GetPosition returns the position of a given instance
func (w World) GetPosition(id uuid.UUID) (Position, error) {
if i, ok := w.instances[id]; ok {
if i, ok := w.Instances[id]; ok {
return i.pos, nil
} else {
return Position{}, fmt.Errorf("no instance matching id")

View file

@ -1,26 +1,27 @@
package game
import (
"os"
"testing"
)
func TestNewWorld(t *testing.T) {
// Very basic for now, nothing to verify
world := NewWorld()
world := NewWorld(os.TempDir())
if world == nil {
t.Error("Failed to create world")
}
}
func TestWorld_CreateInstance(t *testing.T) {
world := NewWorld()
world := NewWorld(os.TempDir())
a := world.CreateInstance()
b := world.CreateInstance()
// Basic duplicate check
if a == b {
t.Errorf("Created identical instances")
} else if len(world.instances) != 2 {
} else if len(world.Instances) != 2 {
t.Errorf("Incorrect number of instances created")
}
}