2021-08-04 22:12:28 +00:00
|
|
|
package game
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2022-03-03 07:40:14 +00:00
|
|
|
"sirlab.de/go/knowyt/engine"
|
|
|
|
"sirlab.de/go/knowyt/quote"
|
2021-08-04 22:12:28 +00:00
|
|
|
)
|
|
|
|
|
2021-08-04 22:52:35 +00:00
|
|
|
func NewGameFromFile(id, fileName string) (*Game, error) {
|
2021-08-04 22:12:28 +00:00
|
|
|
jsonBytes, err := os.ReadFile(fileName)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-08-08 19:57:49 +00:00
|
|
|
var gmJson GameJson
|
|
|
|
if err := json.Unmarshal(jsonBytes, &gmJson); err != nil {
|
2021-08-04 22:12:28 +00:00
|
|
|
return nil, fmt.Errorf("%s: %v\n", fileName, err)
|
|
|
|
} else {
|
2021-08-08 19:57:49 +00:00
|
|
|
gm := Game{
|
2022-03-01 08:41:30 +00:00
|
|
|
id: id,
|
|
|
|
filename: fileName,
|
|
|
|
name: gmJson.Name,
|
|
|
|
eng: engine.NewEngine(),
|
|
|
|
players: make(map[string]playerInfo, 0),
|
|
|
|
state: STATE_IDLE,
|
|
|
|
quotes: make(map[string]*quote.Quote, 0),
|
2021-08-08 19:57:49 +00:00
|
|
|
}
|
2021-08-06 19:46:00 +00:00
|
|
|
|
2021-08-04 22:12:28 +00:00
|
|
|
return &gm, nil
|
|
|
|
}
|
|
|
|
}
|
2021-08-04 22:40:31 +00:00
|
|
|
|
2022-03-01 08:41:30 +00:00
|
|
|
func (gm *Game) SaveGame() error {
|
|
|
|
gm.mu.Lock()
|
|
|
|
defer gm.mu.Unlock()
|
|
|
|
|
|
|
|
gmJson := GameJson{
|
|
|
|
Name: gm.name,
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2021-09-26 21:36:47 +00:00
|
|
|
func (gm *Game) StartEngine() {
|
|
|
|
gm.eng.Run(gm.populateSyncDataCb)
|
|
|
|
}
|
|
|
|
|
2021-08-04 22:40:31 +00:00
|
|
|
func (gm *Game) GetId() string {
|
2021-08-09 09:16:30 +00:00
|
|
|
gm.mu.Lock()
|
|
|
|
defer gm.mu.Unlock()
|
2021-08-04 23:42:21 +00:00
|
|
|
|
2021-08-09 09:16:30 +00:00
|
|
|
return gm.id
|
2021-08-04 23:42:21 +00:00
|
|
|
}
|
2021-08-06 19:46:00 +00:00
|
|
|
|
2021-08-30 16:21:14 +00:00
|
|
|
func (gm *Game) GetState() (string, string) {
|
2021-08-15 15:12:24 +00:00
|
|
|
gm.mu.Lock()
|
|
|
|
defer gm.mu.Unlock()
|
|
|
|
|
2021-08-30 16:21:14 +00:00
|
|
|
return gm.state, gm.phase
|
2021-08-15 15:12:24 +00:00
|
|
|
}
|
|
|
|
|
2021-08-09 09:16:30 +00:00
|
|
|
func (gm *Game) GetName() string {
|
2021-08-09 08:36:19 +00:00
|
|
|
gm.mu.Lock()
|
|
|
|
defer gm.mu.Unlock()
|
|
|
|
|
2021-08-09 09:16:30 +00:00
|
|
|
return gm.name
|
2021-08-06 19:46:00 +00:00
|
|
|
}
|
|
|
|
|
2021-08-09 09:16:30 +00:00
|
|
|
func (gm *Game) GetEngine() *engine.Engine {
|
2021-08-09 08:36:19 +00:00
|
|
|
gm.mu.Lock()
|
|
|
|
defer gm.mu.Unlock()
|
|
|
|
|
2021-08-09 09:16:30 +00:00
|
|
|
return gm.eng
|
2021-08-06 19:46:00 +00:00
|
|
|
}
|