package game import ( "encoding/json" "fmt" "os" "sirlab.de/go/knowyt/engine" "sirlab.de/go/knowyt/fileutil" "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 { lang := gmJson.Lang if lang == "" { lang = "de" } gm := Game{ id: id, filename: fileName, name: gmJson.Name, lang: lang, 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, lang string) (*Game, error) { gm := Game{ id: id, filename: fileName, name: name, lang: lang, 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, Lang: gm.lang, Created: gm.created, } if jsonBytes, err := json.Marshal(gmJson); err != nil { return err } else { if err := fileutil.SaveFile(gm.filename, jsonBytes); 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) GetLang() string { gm.mu.Lock() defer gm.mu.Unlock() return gm.lang } func (gm *Game) GetEngine() *engine.Engine { gm.mu.Lock() defer gm.mu.Unlock() return gm.eng }