package game import ( "fmt" "math/rand/v2" "github.com/google/uuid" "github.com/iliadenisov/galaxy/pkg/generator" "github.com/iliadenisov/galaxy/pkg/model/game" ) type Repo interface { SaveTurn(uint, game.Game) error } func NewGame(r Repo, races []string) (uuid.UUID, error) { gameID, err := uuid.NewRandom() if err != nil { return uuid.Nil, fmt.Errorf("generate game uuid: %s", err) } m, err := generator.Generate(func(ms *generator.MapSetting) { ms.Players = uint32(len(races)) }) if err != nil { return uuid.Nil, fmt.Errorf("generate map: %s", err) } if len(races) != len(m.HomePlanets) { return uuid.Nil, fmt.Errorf("generate map: wrong number of home planets: %d, expected: %d ", len(m.HomePlanets), len(races)) } g := &game.Game{ ID: gameID, Race: make([]game.Race, len(races)), } gameMap := &game.Map{ Width: m.Width, Height: m.Height, Planet: make([]game.Planet, 0), } var planetCount uint = 0 for i := range races { raceID, err := uuid.NewRandom() if err != nil { return uuid.Nil, fmt.Errorf("generate race uuid: %s", err) } g.Race[i] = game.Race{ ID: raceID, Name: races[i], Vote: raceID, Drive: 1, Weapons: 1, Shields: 1, Cargo: 1, } gameMap.Planet = append(gameMap.Planet, newPlanet( planetCount, m.HomePlanets[i].HW.RandomName(), raceID, m.HomePlanets[i].HW.Position.X, m.HomePlanets[i].HW.Position.Y, m.HomePlanets[i].HW.Size, m.HomePlanets[i].HW.Size, // HW's pop & ind = size m.HomePlanets[i].HW.Size, m.HomePlanets[i].HW.Resources, game.ResearchDrive.AsType(""), )) planetCount++ for dw := range m.HomePlanets[i].DW { gameMap.Planet = append(gameMap.Planet, newPlanet( planetCount, m.HomePlanets[i].DW[dw].RandomName(), raceID, m.HomePlanets[i].DW[dw].Position.X, m.HomePlanets[i].DW[dw].Position.Y, m.HomePlanets[i].DW[dw].Size, m.HomePlanets[i].DW[dw].Size, // DW's pop & ind = size m.HomePlanets[i].DW[dw].Size, m.HomePlanets[i].DW[dw].Resources, game.ResearchDrive.AsType(""), )) planetCount++ } } for i := range m.FreePlanets { gameMap.Planet = append(gameMap.Planet, newPlanet( planetCount, m.FreePlanets[i].RandomName(), uuid.Nil, m.FreePlanets[i].Position.X, m.FreePlanets[i].Position.Y, m.FreePlanets[i].Size, 0, 0, m.FreePlanets[i].Resources, game.ProductionNone.AsType(""), )) planetCount++ } // TODO: check code below actually works rand.Shuffle(len(gameMap.Planet), func(i, j int) { gameMap.Planet[i].Number, gameMap.Planet[j].Number = gameMap.Planet[j].Number, gameMap.Planet[i].Number }) g.Map = *gameMap if err := r.SaveTurn(0, *g); err != nil { return uuid.Nil, fmt.Errorf("persist: %s", err) } return g.ID, nil } func newPlanet(num uint, name string, owner uuid.UUID, x, y, size, pop, ind, res float64, prod game.ProductionType) game.Planet { return game.Planet{ Name: name, Number: num, Owner: owner, X: x, Y: y, Size: size, Population: pop, Industry: ind, Resources: res, Production: prod, } }