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)
}

63
src/game/master_test.go Normal file
View File

@@ -0,0 +1,63 @@
package game
import (
"local/sandbox/cards/src/entity"
"testing"
)
func TestMasterGetCreateGetList(t *testing.T) {
gm := NewTestMaster(t)
id := "game"
if games, err := gm.ListGames(); err != nil {
t.Fatal(err)
} else if len(games) != 0 {
t.Fatal(games)
}
if _, err := gm.GetGame(id); err == nil {
t.Fatal(err)
}
if err := gm.CreateGame(id); err != nil {
t.Fatal(err)
}
if _, err := gm.GetGame(id); err != nil {
t.Fatal(err)
}
if games, err := gm.ListGames(); err != nil {
t.Fatal(err)
} else if len(games) != 1 {
t.Fatal(games)
}
}
func TestMasterUpdate(t *testing.T) {
gm := NewTestMaster(t)
id := "game"
err := gm.CreateGame(id)
if err != nil {
t.Fatal(err)
}
game, err := gm.GetGame(id)
if err != nil {
t.Fatal(err)
}
game.Players.Add(entity.Player{
ID: "hi",
})
game.Pot = 123
err = gm.ReplaceGame(id, game)
if err != nil {
t.Fatal(err)
}
game2, err := gm.GetGame(id)
if err != nil {
t.Fatal(err)
}
if game2.Equals(game) {
t.Fatalf("replace+get don't match:\nwant\t%+v\ngot\t%+v", game, game2)
}
}

4
src/game/rule.go Normal file
View File

@@ -0,0 +1,4 @@
package game
type Rule interface {
}