2021-08-04 22:12:28 +00:00
|
|
|
package game
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
2021-08-04 22:52:35 +00:00
|
|
|
"sirlab.de/go/knyt/engine"
|
2021-08-06 19:46:00 +00:00
|
|
|
"sirlab.de/go/knyt/user"
|
|
|
|
"time"
|
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{
|
|
|
|
id: id,
|
|
|
|
name: gmJson.Name,
|
|
|
|
eng: engine.NewEngine(id),
|
|
|
|
playerTimestamp: make(map[string]time.Time),
|
|
|
|
}
|
2021-08-06 19:46:00 +00:00
|
|
|
|
2021-08-04 23:42:21 +00:00
|
|
|
go gm.eng.Run()
|
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
|
|
|
|
|
|
|
func (gm *Game) GetId() string {
|
|
|
|
return gm.id
|
|
|
|
}
|
2021-08-04 23:42:21 +00:00
|
|
|
|
|
|
|
func (gm *Game) GetEngine() *engine.Engine {
|
|
|
|
return gm.eng
|
|
|
|
}
|
2021-08-06 19:46:00 +00:00
|
|
|
|
|
|
|
func (gm *Game) UpdatePlayerTimestamp(usr *user.User) {
|
|
|
|
gm.playerTimestamp[usr.GetId()] = time.Now()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (gm *Game) GetActivePlayers() []string {
|
|
|
|
players := make([]string, 0)
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
for usrId, timestamp := range gm.playerTimestamp {
|
|
|
|
elapsed := now.Sub(timestamp)
|
|
|
|
|
|
|
|
fmt.Printf("%s: %.0f\n", usrId, elapsed.Seconds())
|
|
|
|
|
|
|
|
if elapsed.Seconds() < 30.0 {
|
|
|
|
players = append(players, usrId)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return players
|
|
|
|
}
|