knowyt/server/src/game/game.go
2022-04-12 14:16:03 +02:00

101 lines
1.8 KiB
Go

package game
import (
"encoding/json"
"fmt"
"os"
"sirlab.de/go/knowyt/engine"
"sirlab.de/go/knowyt/quote"
"time"
)
func NewGameFromFile(id, fileName string) (*Game, error) {
jsonBytes, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
var gmJson GameJson
if err := json.Unmarshal(jsonBytes, &gmJson); err != nil {
return nil, fmt.Errorf("%s: %v\n", fileName, err)
} else {
gm := Game{
id: id,
filename: fileName,
name: gmJson.Name,
created: gmJson.Created,
eng: engine.NewEngine(),
players: make(map[string]playerInfo, 0),
state: STATE_IDLE,
quotes: make(map[string]*quote.Quote, 0),
}
return &gm, nil
}
}
func NewGame(id, fileName, name string) (*Game, error) {
gm := Game{
id: id,
filename: fileName,
name: name,
eng: engine.NewEngine(),
players: make(map[string]playerInfo, 0),
state: STATE_IDLE,
created: time.Now().Unix(),
quotes: make(map[string]*quote.Quote, 0),
}
return &gm, nil
}
func (gm *Game) SaveGame() error {
gm.mu.Lock()
defer gm.mu.Unlock()
gmJson := GameJson{
Name: gm.name,
Created: gm.created,
}
if jsonBytes, err := json.Marshal(gmJson); err != nil {
return err
} else {
if err := os.WriteFile(gm.filename, jsonBytes, 0666); err != nil {
return err
}
}
return nil
}
func (gm *Game) StartEngine() {
gm.eng.Run(gm.populateSyncDataCb)
}
func (gm *Game) GetId() string {
gm.mu.Lock()
defer gm.mu.Unlock()
return gm.id
}
func (gm *Game) GetState() (string, string) {
gm.mu.Lock()
defer gm.mu.Unlock()
return gm.state, gm.phase
}
func (gm *Game) GetName() string {
gm.mu.Lock()
defer gm.mu.Unlock()
return gm.name
}
func (gm *Game) GetEngine() *engine.Engine {
gm.mu.Lock()
defer gm.mu.Unlock()
return gm.eng
}