Files
galaxy-game/pkg/game/controller.go
T
Ilia Denisov 04fc96dc8f commands A, W
2025-09-30 20:44:10 +03:00

75 lines
1.5 KiB
Go

package game
import (
"fmt"
"github.com/google/uuid"
"github.com/iliadenisov/galaxy/pkg/model/game"
"github.com/iliadenisov/galaxy/pkg/repo"
)
type ctrl struct {
param Param
repo Repo
}
type Param struct {
StoragePath string
}
func LoadState(configure func(*Param)) (g game.Game, err error) {
control(configure, func(c *ctrl) { c.executeInit(func(r Repo) { g, err = c.repo.LoadState() }) })
return
}
func GenerateGame(configure func(*Param), races []string) (gameID uuid.UUID, err error) {
control(configure, func(c *ctrl) { c.executeInit(func(r Repo) { gameID, err = newGame(r, races) }) })
return
}
func newController(configure func(*Param)) (*ctrl, error) {
c := &Param{
StoragePath: ".",
}
if configure != nil {
configure(c)
}
r, err := repo.NewFileRepo(c.StoragePath)
if err != nil {
return nil, err
}
return &ctrl{
param: *c,
repo: r,
}, nil
}
func control(configure func(*Param), consumer func(*ctrl)) error {
c, err := newController(configure)
if err != nil {
return err
}
consumer(c)
return nil
}
func (c *ctrl) executeInit(consumer func(Repo)) error {
if err := c.repo.Lock(); err != nil {
return fmt.Errorf("execute: lock failed: %s", err)
}
consumer(c.repo)
return c.repo.Release()
}
func (c *ctrl) execute(consumer func(Repo, game.Game)) error {
if err := c.repo.Lock(); err != nil {
return fmt.Errorf("execute: lock failed: %s", err)
}
g, err := c.repo.LoadState()
if err != nil {
return err
}
consumer(c.repo, g)
return c.repo.Release()
}