Browse Source

allow cors origin in config file, move resources from user to planet

master
arnaucube 5 years ago
parent
commit
edfa4e6751
10 changed files with 250 additions and 233 deletions
  1. +1
    -0
      config.yaml
  2. +3
    -2
      config/config.go
  3. +1
    -1
      constants/constants.go
  4. +2
    -14
      endpoint/handlers.go
  5. +1
    -1
      endpoint/serve.go
  6. +0
    -3
      go.sum
  7. +226
    -1
      models/planet.go
  8. +1
    -128
      models/user.go
  9. +11
    -81
      services/gamesrv/gamesrv.go
  10. +4
    -2
      services/usersrv/usersrv.go

+ 1
- 0
config.yaml

@ -1,6 +1,7 @@
server:
serviceapi: 0.0.0.0:5000
adminapi: 127.0.0.1:5001
corsoriginsallowed: http://127.0.0.1:8080
mongodb:
url: 127.0.0.1:27017
database: "gogame"

+ 3
- 2
config/config.go

@ -9,8 +9,9 @@ import (
type Config struct {
Server struct {
ServiceApi string
AdminApi string
ServiceApi string
AdminApi string
CorsOriginsAllowed string
}
Mongodb struct {
Url string

+ 1
- 1
constants/constants.go

@ -5,7 +5,7 @@ package constants
const GALAXYSIZE = 50
const SOLARSYSTEMSIZE = 15
const UniverseAcceleration = 1
const UniverseAcceleration = 5
const MineVelocity = 1
// extra

+ 2
- 14
endpoint/handlers.go

@ -73,15 +73,9 @@ func handleGetUser(c *gin.Context) {
fail(c, err, "error on getting user")
return
}
// resources, err := user.GetResources()
// if err != nil {
// fail(c, err, "error on getting user resources")
// return
// }
c.JSON(200, gin.H{
"user": user,
// "resources": resources,
})
}
@ -94,15 +88,9 @@ func handleGetResources(c *gin.Context) {
fail(c, err, "error on getting user")
return
}
resources, err := user.GetResources()
if err != nil {
fail(c, err, "error on getting user resources")
return
}
c.JSON(200, gin.H{
"user": user,
"resources": resources,
"user": user,
})
}
@ -132,7 +120,7 @@ func handleGetPlanet(c *gin.Context) {
return
}
planet, err := gameservice.GetBuildings(user, bson.ObjectIdHex(planetid))
planet, err := gameservice.GetPlanet(user, bson.ObjectIdHex(planetid))
if err != nil {
fail(c, err, "error upgrading building")
return

+ 1
- 1
endpoint/serve.go

@ -24,7 +24,7 @@ var gameservice *gamesrv.Service
func newApiService() *gin.Engine {
api := gin.Default()
api.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://127.0.0.1:8080"},
AllowOrigins: []string{serverConfig.Server.CorsOriginsAllowed},
AllowMethods: []string{"GET", "POST"},
AllowHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,

+ 0
- 3
go.sum

@ -96,9 +96,7 @@ github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab h1:n8cgpHzJ5+EDyDri2s/GC7a9+qK3/YEGnBsd0uS/8PY=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab/go.mod h1:y1pL58r5z2VvAjeG1VLGc8zOQgSOzbKN7kMHPvFXJ+8=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
@ -183,7 +181,6 @@ golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

+ 226
- 1
models/planet.go

@ -1,8 +1,11 @@
package models
import (
"errors"
"strconv"
"time"
"github.com/arnaucube/gogame/database"
"gopkg.in/mgo.v2/bson"
)
@ -13,11 +16,21 @@ type Process struct {
Ends time.Time
}
type Resources struct {
Metal int64
Crystal int64
Deuterium int64
Energy int64
}
type Planet struct {
Db *database.Db
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Size int64 // fields/slots
LastUpdated time.Time
Size int64 // fields/slots
Name string
OwnerId bson.ObjectId
Resources Resources
Buildings map[string]int64
CurrentBuild Process
Research Process
@ -33,3 +46,215 @@ type Planet struct {
RessearchLab int64
*/
}
func NewPlanet(db *database.Db, size int64, name string, ownerId bson.ObjectId) (*Planet, error) {
newPlanet := Planet{
Db: db,
Size: size,
Name: name,
OwnerId: ownerId,
Resources: Resources{
Metal: 500,
Crystal: 500,
Deuterium: 500,
Energy: 500,
},
}
// in case that wants to start with resources plants
newPlanet.Buildings = make(map[string]int64)
newPlanet.Buildings["metalmine"] = 1
newPlanet.Buildings["crystalmine"] = 1
newPlanet.Buildings["deuteriummine"] = 1
newPlanet.Buildings["energymine"] = 1
err := db.Planets.Insert(newPlanet)
if err != nil {
return nil, err
}
var planet *Planet
err = db.Planets.Find(bson.M{"ownerid": newPlanet.OwnerId}).One(&planet)
if err != nil {
return nil, err
}
return planet, nil
}
func (p *Planet) GetFromDb() error {
var planet Planet
err := p.Db.Planets.Find(bson.M{"_id": p.Id}).One(&planet)
if err != nil {
return err
}
planet.Db = p.Db
p = &planet
return nil
}
func (p *Planet) StoreInDb() error {
p.LastUpdated = time.Now()
err := p.Db.Planets.Update(bson.M{"_id": p.Id}, p)
return err
}
// GetResources updates the values of resources and returns the value, also updates the user.Resources
// Resource types: metal, crystal, deuterium, energy
func (p *Planet) GetResources() (*Resources, error) {
// get current values
err := p.GetFromDb()
if err != nil {
return nil, err
}
// calculate Delta time = currentTime - p.LastUpdated
delta := time.Since(p.LastUpdated).Seconds()
// get Resource-Plant level in each planet
// and calculate growth = ResourcePlant.Level for each planet
var metalGrowth, crystalGrowth, deuteriumGrowth, energyGrowth int64
metalGrowth = metalGrowth + MetalGrowth(p.Buildings["metalmine"], int64(delta))
crystalGrowth = crystalGrowth + MetalGrowth(p.Buildings["crystalmine"], int64(delta))
deuteriumGrowth = deuteriumGrowth + MetalGrowth(p.Buildings["deuteriummine"], int64(delta))
energyGrowth = energyGrowth + MetalGrowth(p.Buildings["energymine"], int64(delta))
// calculate newAmount = oldAmount + growth
p.Resources.Metal = p.Resources.Metal + metalGrowth
p.Resources.Crystal = p.Resources.Crystal + crystalGrowth
p.Resources.Deuterium = p.Resources.Deuterium + deuteriumGrowth
p.Resources.Energy = p.Resources.Energy + energyGrowth
// store new amount to user db
err = p.StoreInDb()
if err != nil {
return nil, err
}
// return user
return &p.Resources, nil
}
// SpendResources checks if user has enough resources, then substracts the resources, and updates the amounts in the database
func (p *Planet) SpendResources(r Resources) error {
err := p.GetFromDb()
if err != nil {
return err
}
if p.Resources.Metal < r.Metal {
return errors.New("not enough metal resources")
}
if p.Resources.Crystal < r.Crystal {
return errors.New("not enough crystal resources")
}
if p.Resources.Deuterium < r.Deuterium {
return errors.New("not enough deuterium resources")
}
if p.Resources.Energy < r.Energy {
return errors.New("not enough energy resources")
}
p.Resources.Metal = p.Resources.Metal - r.Metal
p.Resources.Crystal = p.Resources.Crystal - r.Crystal
p.Resources.Deuterium = p.Resources.Deuterium - r.Deuterium
p.Resources.Energy = p.Resources.Energy - r.Energy
err = p.StoreInDb()
if err != nil {
return err
}
return nil
}
func (p *Planet) GetBuildingCost(building string) (Resources, error) {
switch building {
case "metalmine":
return MetalMineCost(p.Buildings["metalmine"] + 1), nil
case "crystalmine":
return CrystalMineCost(p.Buildings["crystalmine"] + 1), nil
case "deuteriummine":
return DeuteriumMineCost(p.Buildings["deuteriummine"] + 1), nil
case "energymine":
return EnergyMineCost(p.Buildings["energymine"] + 1), nil
case "fusionreactor":
return FussionReactorCost(p.Buildings["fusionreactor"] + 1), nil
case "roboticsfactory":
return RoboticsFactoryCost(p.Buildings["roboticsfactory"] + 1), nil
case "shipyard":
return ShipyardCost(p.Buildings["shipyard"] + 1), nil
case "metalstorage":
return MetalStorageCost(p.Buildings["metalstorage"] + 1), nil
case "crystalstorage":
return CrystalStorageCost(p.Buildings["crystalstorage"] + 1), nil
case "deuteriumstorage":
return DeuteriumStorageCost(p.Buildings["deuteriumstorage"] + 1), nil
case "ressearchlab":
return RessearchLabCost(p.Buildings["ressearchlab"] + 1), nil
case "alliancedepot":
return AllianceDepotCost(p.Buildings["alliancedepot"] + 1), nil
case "missilesilo":
return MissileSiloCost(p.Buildings["missilesilo"] + 1), nil
case "spacedock":
return SpaceDockCost(p.Buildings["spacedock"] + 1), nil
default:
return Resources{}, errors.New("building not found")
}
}
// CheckCurrentBuild checks if the planet has a ongoing building in process, and if has finished
// in case that has finished, updates it in db
func (p *Planet) CheckCurrentBuild() (bool, error) {
if p.CurrentBuild.Title != "" {
// the planet is building something, check if has ended
if p.CurrentBuild.Ends.Unix() < time.Now().Unix() {
// upgrade level of building in planet
p.Buildings[p.CurrentBuild.Building] += 1
// build end
p.CurrentBuild.Title = ""
p.CurrentBuild.Building = ""
// store in db
err := p.Db.Planets.Update(bson.M{"_id": p.Id}, p)
if err != nil {
return true, err
}
return false, nil
}
return true, nil
}
return false, nil
}
func (p *Planet) UpgradeBuilding(building string) error {
busy, err := p.CheckCurrentBuild()
if err != nil {
return err
}
if busy {
return errors.New("busy")
}
// get current building level, and get the needed resources for next level
resourcesNeeded, err := p.GetBuildingCost(building)
if err != nil {
return err
}
// get time cost of the build
timei64 := ConstructionTime(resourcesNeeded, p.Buildings[building]+1)
endsTime := time.Now().Add(time.Second * time.Duration(timei64))
// if user have enough resources to upgrade the building, upgrade the building
err = p.SpendResources(resourcesNeeded)
if err != nil {
return err
}
// add current task to planet
p.CurrentBuild.Building = building
p.CurrentBuild.Title = building + " - Level " + strconv.Itoa(int(p.Buildings[building]))
p.CurrentBuild.Ends = endsTime
// store planet in db
err = p.Db.Planets.Update(bson.M{"_id": p.Id}, p)
return nil
}

+ 1
- 128
models/user.go

@ -1,20 +1,12 @@
package models
import (
"errors"
"time"
"github.com/arnaucube/gogame/database"
"gopkg.in/mgo.v2/bson"
)
type Resources struct {
Metal int64
Crystal int64
Deuterium int64
Energy int64
}
// UserDb is the data in DB
type UserDb struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
@ -22,17 +14,15 @@ type UserDb struct {
Password string
Email string
LastUpdated time.Time
Resources Resources
Planets []bson.ObjectId
}
// User is the data in memory, after getting it from DB
type User struct {
db *database.Db
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Name string
LastUpdated time.Time
db *database.Db
Resources Resources
Planets []bson.ObjectId
}
@ -43,12 +33,6 @@ func NewUser(db *database.Db, name, password, email string) (*User, error) {
Password: password,
Email: email,
LastUpdated: time.Now(),
Resources: Resources{
Metal: 500,
Crystal: 500,
Deuterium: 500,
Energy: 500,
},
}
err := db.Users.Insert(newUser)
if err != nil {
@ -64,7 +48,6 @@ func UserDbToUser(db *database.Db, u UserDb) *User {
Name: u.Name,
LastUpdated: u.LastUpdated,
db: db,
Resources: u.Resources,
Planets: u.Planets,
}
}
@ -72,7 +55,6 @@ func UserDbToUser(db *database.Db, u UserDb) *User {
func (u *User) StoreInDb() error {
err := u.db.Users.Update(bson.M{"_id": u.Id}, bson.M{"$set": bson.M{
"lastupdated": time.Now(),
"resources": u.Resources,
"planets": u.Planets,
}})
return err
@ -97,112 +79,3 @@ func (u *User) GetPlanets() ([]Planet, error) {
}
return planets, nil
}
// GetResources updates the values of resources and returns the value, also updates the user.Resources
// Resource types: metal, crystal, deuterium, energy
func (u *User) GetResources() (*Resources, error) {
// get current values
err := u.GetFromDb()
if err != nil {
return nil, err
}
// calculate Delta time = currentTime - u.LastUpdated
delta := time.Since(u.LastUpdated).Seconds()
// get planets
planets, err := u.GetPlanets()
if err != nil {
return nil, err
}
// get Resource-Plant level in each planet
// and calculate growth = ResourcePlant.Level for each planet
var metalGrowth, crystalGrowth, deuteriumGrowth, energyGrowth int64
for _, planet := range planets {
metalGrowth = metalGrowth + MetalGrowth(planet.Buildings["metalmine"], int64(delta))
crystalGrowth = crystalGrowth + MetalGrowth(planet.Buildings["crystalmine"], int64(delta))
deuteriumGrowth = deuteriumGrowth + MetalGrowth(planet.Buildings["deuteriummine"], int64(delta))
energyGrowth = energyGrowth + MetalGrowth(planet.Buildings["energymine"], int64(delta))
}
// calculate newAmount = oldAmount + growth
u.Resources.Metal = u.Resources.Metal + metalGrowth
u.Resources.Crystal = u.Resources.Crystal + crystalGrowth
u.Resources.Deuterium = u.Resources.Deuterium + deuteriumGrowth
u.Resources.Energy = u.Resources.Energy + energyGrowth
// store new amount to user db
err = u.StoreInDb()
if err != nil {
return nil, err
}
// return user
return &u.Resources, nil
}
// SpendResources checks if user has enough resources, then substracts the resources, and updates the amounts in the database
func (u *User) SpendResources(r Resources) error {
err := u.GetFromDb()
if err != nil {
return err
}
if u.Resources.Metal < r.Metal {
return errors.New("not enough metal resources")
}
if u.Resources.Crystal < r.Crystal {
return errors.New("not enough crystal resources")
}
if u.Resources.Deuterium < r.Deuterium {
return errors.New("not enough deuterium resources")
}
if u.Resources.Energy < r.Energy {
return errors.New("not enough energy resources")
}
u.Resources.Metal = u.Resources.Metal - r.Metal
u.Resources.Crystal = u.Resources.Crystal - r.Crystal
u.Resources.Deuterium = u.Resources.Deuterium - r.Deuterium
u.Resources.Energy = u.Resources.Energy - r.Energy
err = u.StoreInDb()
if err != nil {
return err
}
return nil
}
func (u *User) GetBuildingCost(planet Planet, building string) (Resources, error) {
switch building {
case "metalmine":
return MetalMineCost(planet.Buildings["metalmine"] + 1), nil
case "crystalmine":
return CrystalMineCost(planet.Buildings["crystalmine"] + 1), nil
case "deuteriummine":
return DeuteriumMineCost(planet.Buildings["deuteriummine"] + 1), nil
case "energymine":
return EnergyMineCost(planet.Buildings["energymine"] + 1), nil
case "fusionreactor":
return FussionReactorCost(planet.Buildings["fusionreactor"] + 1), nil
case "roboticsfactory":
return RoboticsFactoryCost(planet.Buildings["roboticsfactory"] + 1), nil
case "shipyard":
return ShipyardCost(planet.Buildings["shipyard"] + 1), nil
case "metalstorage":
return MetalStorageCost(planet.Buildings["metalstorage"] + 1), nil
case "crystalstorage":
return CrystalStorageCost(planet.Buildings["crystalstorage"] + 1), nil
case "deuteriumstorage":
return DeuteriumStorageCost(planet.Buildings["deuteriumstorage"] + 1), nil
case "ressearchlab":
return RessearchLabCost(planet.Buildings["ressearchlab"] + 1), nil
case "alliancedepot":
return AllianceDepotCost(planet.Buildings["alliancedepot"] + 1), nil
case "missilesilo":
return MissileSiloCost(planet.Buildings["missilesilo"] + 1), nil
case "spacedock":
return SpaceDockCost(planet.Buildings["spacedock"] + 1), nil
default:
return Resources{}, errors.New("building not found")
}
}

+ 11
- 81
services/gamesrv/gamesrv.go

@ -1,10 +1,7 @@
package gamesrv
import (
"errors"
"fmt"
"strconv"
"time"
"github.com/arnaucube/gogame/constants"
"github.com/arnaucube/gogame/database"
@ -28,24 +25,7 @@ func (srv Service) CreatePlanet(userId bson.ObjectId) (*models.SolarSystem, *mod
size := int64(250) // TODO get rand inside a range
name := "planetname" // TODO get random name
newPlanet := models.Planet{
Size: size,
Name: name,
OwnerId: userId,
}
// in case that wants to start with resources plants
newPlanet.Buildings = make(map[string]int64)
newPlanet.Buildings["metalmine"] = 1
newPlanet.Buildings["crystalmine"] = 1
newPlanet.Buildings["deuteriummine"] = 1
newPlanet.Buildings["energymine"] = 1
err := srv.db.Planets.Insert(newPlanet)
if err != nil {
return nil, nil, err
}
var planet *models.Planet
err = srv.db.Planets.Find(bson.M{"ownerid": newPlanet.OwnerId}).One(&planet)
planet, err := models.NewPlanet(srv.db, size, name, userId)
if err != nil {
return nil, nil, err
}
@ -95,77 +75,27 @@ func (srv Service) PutPlanetInSolarSystem(position int64, planet *models.Planet)
return &solarSystem, err
}
// CheckCurrentBuild checks if the planet has a ongoing building in process, and if has finished
// in case that has finished, updates it in db
func (srv Service) CheckCurrentBuild(planet *models.Planet) (bool, error) {
if planet.CurrentBuild.Title != "" {
// the planet is building something, check if has ended
if planet.CurrentBuild.Ends.Unix() < time.Now().Unix() {
// upgrade level of building in planet
planet.Buildings[planet.CurrentBuild.Building] += 1
// build end
planet.CurrentBuild.Title = ""
planet.CurrentBuild.Building = ""
// store in db
err := srv.db.Planets.Update(bson.M{"_id": planet.Id}, planet)
if err != nil {
return true, err
}
return false, nil
}
return true, nil
}
return false, nil
}
func (srv Service) GetBuildings(user *models.User, planetid bson.ObjectId) (*models.Planet, error) {
func (srv Service) GetPlanet(user *models.User, planetid bson.ObjectId) (*models.Planet, error) {
var planet models.Planet
err := srv.db.Planets.Find(bson.M{"_id": planetid, "ownerid": user.Id}).One(&planet)
if err != nil {
return nil, err
}
_, err = srv.CheckCurrentBuild(&planet)
planet.Db = srv.db
_, err = planet.CheckCurrentBuild()
if err != nil {
return nil, err
}
_, err = planet.GetResources()
return &planet, err
}
func (srv Service) UpgradeBuilding(user *models.User, planetid bson.ObjectId, building string) (*models.Planet, error) {
// get planet
var planet models.Planet
err := srv.db.Planets.Find(bson.M{"_id": planetid}).One(&planet)
if err != nil {
return nil, err
}
busy, err := srv.CheckCurrentBuild(&planet)
if err != nil {
return nil, err
}
if busy {
return nil, errors.New("busy")
}
// get current building level, and get the needed resources for next level
resourcesNeeded, err := user.GetBuildingCost(planet, building)
planet, err := srv.GetPlanet(user, planetid)
if err != nil {
return nil, err
}
// get time cost of the build
timei64 := models.ConstructionTime(resourcesNeeded, planet.Buildings[building]+1)
endsTime := time.Now().Add(time.Second * time.Duration(timei64))
// if user have enough resources to upgrade the building, upgrade the building
err = user.SpendResources(resourcesNeeded)
if err != nil {
return nil, err
}
// add current task to planet
planet.CurrentBuild.Building = building
planet.CurrentBuild.Title = building + " - Level " + strconv.Itoa(int(planet.Buildings[building]))
planet.CurrentBuild.Ends = endsTime
// store planet in db
err = srv.db.Planets.Update(bson.M{"_id": planet.Id}, planet)
return &planet, nil
err = planet.UpgradeBuilding(building)
return planet, err
}

+ 4
- 2
services/usersrv/usersrv.go

@ -50,6 +50,9 @@ func (srv Service) Register(name, password, email string) (*models.User, error)
}
_, planet, err := srv.gamesrv.CreatePlanet(user.Id)
if err != nil {
return nil, err
}
user.Planets = append(user.Planets, planet.Id)
user.StoreInDb()
@ -92,8 +95,7 @@ func (srv Service) GetUserById(userid bson.ObjectId) (*models.User, error) {
return nil, err
}
user := models.UserDbToUser(srv.db, userDb)
_, err = user.GetResources()
return user, err
return user, nil
}
func (srv Service) GetUserPlanetsById(userid bson.ObjectId) ([]*models.Planet, error) {

Loading…
Cancel
Save