This commit is contained in:
Bel LaPointe
2021-03-13 15:59:07 -06:00
parent cb42bdc8d0
commit 4bf83b3e40
20 changed files with 267 additions and 13 deletions

73
src/game/master.go Normal file
View File

@@ -0,0 +1,73 @@
package game
import (
"local/sandbox/cards/src/config"
"local/sandbox/cards/src/consts"
"local/sandbox/cards/src/entity"
"local/sandbox/cards/src/storage"
"testing"
)
type Master struct {
config config.Config
storage Storage
locks *storage.RWLockMap
}
type Storage interface {
CreateGame(string) error
GetGame(string) (entity.Game, error)
ListGames() ([]string, error)
ReplaceGame(string, entity.Game) error
}
func NewMaster(config config.Config, s Storage) *Master {
return &Master{
config: config,
storage: s,
locks: storage.NewRWLockMap(),
}
}
func (gm *Master) ListGames() ([]string, error) {
return gm.storage.ListGames()
}
func (gm *Master) GetGame(id string) (entity.Game, error) {
gm.locks.RLock(id)
defer gm.locks.RUnlock(id)
game, err := gm.storage.GetGame(id)
if game.Players == nil {
game.Players = make(entity.Players, 0)
}
return game, err
}
func (gm *Master) CreateGame(id string) error {
gm.locks.Lock(id)
defer gm.locks.Unlock(id)
if _, err := gm.storage.GetGame(id); err == nil {
return consts.ErrGameExists
}
return gm.storage.CreateGame(id)
}
func (gm *Master) ReplaceGame(id string, game entity.Game) error {
gm.locks.Lock(id)
defer gm.locks.Unlock(id)
if _, err := gm.storage.GetGame(id); err != nil {
return err
}
return gm.storage.ReplaceGame(id, game)
}
func NewTestMaster(t *testing.T) *Master {
config := config.NewTestConfig(t)
storage := storage.NewStorage(config)
return NewMaster(config, storage)
}