refactor: battle at controller
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/google/uuid"
|
||||
e "github.com/iliadenisov/galaxy/internal/error"
|
||||
"github.com/iliadenisov/galaxy/internal/model/game"
|
||||
)
|
||||
|
||||
func (c *Cache) ShipClass(ri int, name string) (*game.ShipType, int, bool) {
|
||||
i := slices.IndexFunc(c.g.Race[ri].ShipTypes, func(st game.ShipType) bool { return st.Name == name })
|
||||
if i < 0 {
|
||||
return nil, -1, false
|
||||
}
|
||||
return &c.g.Race[ri].ShipTypes[i], i, true
|
||||
}
|
||||
|
||||
func (c *Cache) CreateShipType(raceName, typeName string, drive float64, ammo int, weapons, shileds, cargo float64) error {
|
||||
ri, err := c.raceIndex(raceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.createShipTypeInternal(ri, typeName, drive, ammo, weapons, shileds, cargo)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Cache) createShipTypeInternal(ri int, name string, drive float64, ammo int, weapons, shileds, cargo float64) (int, error) {
|
||||
if err := checkShipTypeValues(drive, ammo, weapons, shileds, cargo); err != nil {
|
||||
return -1, err
|
||||
}
|
||||
n, ok := validateTypeName(name)
|
||||
if !ok {
|
||||
return -1, e.NewEntityTypeNameValidationError("%q", n)
|
||||
}
|
||||
if st := slices.IndexFunc(c.g.Race[ri].ShipTypes, func(st game.ShipType) bool { return st.Name == name }); st >= 0 {
|
||||
return -1, e.NewEntityTypeNameDuplicateError("ship type %w", c.g.Race[ri].ShipTypes[st].Name)
|
||||
}
|
||||
c.g.Race[ri].ShipTypes = append(c.g.Race[ri].ShipTypes, game.ShipType{
|
||||
ID: uuid.New(),
|
||||
ShipTypeReport: game.ShipTypeReport{
|
||||
Name: n,
|
||||
Drive: drive,
|
||||
Weapons: weapons,
|
||||
Shields: shileds,
|
||||
Cargo: cargo,
|
||||
Armament: uint(ammo),
|
||||
},
|
||||
})
|
||||
return len(c.g.Race[ri].ShipTypes) - 1, nil
|
||||
}
|
||||
|
||||
func checkShipTypeValues(d float64, a int, w, s, c float64) error {
|
||||
if !checkShipTypeValueDWSC(d) {
|
||||
return e.NewDriveValueError(d)
|
||||
}
|
||||
if !checkShipTypeValueDWSC(w) {
|
||||
return e.NewWeaponsValueError(w)
|
||||
}
|
||||
if !checkShipTypeValueDWSC(s) {
|
||||
return e.NewShieldsValueError(s)
|
||||
}
|
||||
if !checkShipTypeValueDWSC(c) {
|
||||
return e.NewCargoValueError(s)
|
||||
}
|
||||
if a < 0 {
|
||||
return e.NewShipTypeArmamentValueError(a)
|
||||
}
|
||||
if (w == 0 && a > 0) || (a == 0 && w > 0) {
|
||||
return e.NewShipTypeArmamentAndWeaponsValueError("A=%d W=%.0f", a, w)
|
||||
}
|
||||
if d == 0 && w == 0 && s == 0 && c == 0 && a == 0 {
|
||||
return e.NewShipTypeShipTypeZeroValuesError()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkShipTypeValueDWSC(v float64) bool {
|
||||
return v == 0 || v >= 1
|
||||
}
|
||||
Reference in New Issue
Block a user