arnaucube
arnaucube/gogame-oldPublic Self-hosted repository
add UpgradeBuilding functionallity
arnaucube arnaucube@gmail.com
Fri, 14 Jun 2019 23:29:16 +0200
commit

c38f7762f4be118cdb31e4583a5aa0b1e74a8b6c

parent

c07b4edd62d0e0e3c57ee182931522bc58a42908

M cmd/server.go → cmd/server.go

@@ -35,7 +35,7 @@ if err != nil {

return err } - apiService := endpoint.Serve(config.C, db, userservice) + apiService := endpoint.Serve(config.C, db, userservice, gameservice) apiService.Run(config.C.Server.ServiceApi) return nil
M constants/constants.go → constants/constants.go

@@ -1,5 +1,9 @@

package constants +import ( + "github.com/arnaucube/gogame/models" +) + // game constants const GALAXYSIZE = 50

@@ -31,3 +35,28 @@ 1,

5, 10, } + +// BuildingsNeededResources hold +// map with all the buildings, that each one is a map with the levels of the buildings with the needed ressources +var BuildingsNeededResources = map[string]map[int64]models.Resources{ + "metalplant": map[int64]models.Resources{ + 1: models.Resources{ + Metal: 50, + Crystal: 50, + Deuterium: 50, + Energy: 50, + }, + 2: models.Resources{ + Metal: 70, + Crystal: 70, + Deuterium: 70, + Energy: 70, + }, + 3: models.Resources{ + Metal: 90, + Crystal: 90, + Deuterium: 90, + Energy: 90, + }, + }, +}
M endpoint/handlers.go → endpoint/handlers.go

@@ -1,8 +1,11 @@

package endpoint import ( + "fmt" + "github.com/fatih/color" "github.com/gin-gonic/gin" + "gopkg.in/mgo.v2/bson" ) func fail(c *gin.Context, err error, msg string) {

@@ -64,14 +67,14 @@

func handleGetResources(c *gin.Context) { userid := c.Param("userid") - user, err := userservice.GetUserById(userid) + user, err := userservice.GetUserById(bson.ObjectIdHex(userid)) if err != nil { fail(c, err, "error on getting user") return } resources, err := user.GetResources() if err != nil { - fail(c, err, "error on getting user") + fail(c, err, "error on getting user resources") return }

@@ -80,3 +83,49 @@ "user": user,

"resources": resources, }) } + +func handleGetUserPlanets(c *gin.Context) { + userid := c.Param("userid") + + planets, err := userservice.GetUserPlanetsById(bson.ObjectIdHex(userid)) + if err != nil { + fail(c, err, "error on getting user planets") + return + } + + c.JSON(200, gin.H{ + "planets": planets, + }) +} + +type BuildMsg struct { + PlanetId string + Building string +} + +func handlePostUpgradeBuilding(c *gin.Context) { + userid := c.Param("userid") + var buildMsg BuildMsg + err := c.BindJSON(&buildMsg) + if err != nil { + fail(c, err, "error parsing json") + return + } + fmt.Println(buildMsg) + + user, err := userservice.GetUserById(bson.ObjectIdHex(userid)) + if err != nil { + fail(c, err, "error on getting user") + return + } + + planet, err := gameservice.UpgradeBuilding(user, bson.ObjectIdHex(buildMsg.PlanetId), buildMsg.Building) + if err != nil { + fail(c, err, "error upgrading building") + return + } + + c.JSON(200, gin.H{ + "planet": planet, + }) +}
M endpoint/serve.go → endpoint/serve.go

@@ -3,6 +3,7 @@

import ( "github.com/arnaucube/gogame/config" "github.com/arnaucube/gogame/database" + "github.com/arnaucube/gogame/services/gamesrv" "github.com/arnaucube/gogame/services/usersrv" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin"

@@ -11,6 +12,7 @@

var serverConfig config.Config var db *database.Db var userservice *usersrv.Service +var gameservice *gamesrv.Service func newApiService() *gin.Engine { api := gin.Default()

@@ -22,12 +24,15 @@ api.POST("/login", handleLogin)

// TODO add jwt checker api.GET("/resources/:userid", handleGetResources) + api.GET("/planets/:userid", handleGetUserPlanets) + api.POST("/buildings/:userid", handlePostUpgradeBuilding) return api } -func Serve(cnfg config.Config, _db *database.Db, _userservice *usersrv.Service) *gin.Engine { +func Serve(cnfg config.Config, _db *database.Db, _userservice *usersrv.Service, _gameservice *gamesrv.Service) *gin.Engine { serverConfig = cnfg db = _db userservice = _userservice + gameservice = _gameservice return newApiService() }
M models/planet.go → models/planet.go

@@ -2,7 +2,8 @@ package models

import "gopkg.in/mgo.v2/bson" -type BuildingsList struct { +/* +BuildingsList MetalMine int64 CrystalMine int64 DeuteriumMine int64

@@ -11,11 +12,11 @@ FusionReactor int64

RoboticsFactory int64 Shipyard int64 RessearchLab int64 -} +*/ type Planet struct { Id bson.ObjectId `json:"id" bson:"_id,omitempty"` Size int64 // fields/slots Name string OwnerId bson.ObjectId - Buildings BuildingsList + Buildings map[string]int64 }
M models/user.go → models/user.go

@@ -1,6 +1,7 @@

package models import ( + "errors" "fmt" "time"

@@ -42,6 +43,12 @@ Name: name,

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 {

@@ -117,10 +124,10 @@ var metalGrowth, crystalGrowth, deuteriumGrowth, energyGrowth int64

for _, planet := range planets { fmt.Println("planet", planet) // TODO find correct formulas - metalGrowth = metalGrowth + ((1 + planet.Buildings.MetalMine) * int64(delta)) - crystalGrowth = crystalGrowth + ((1 * planet.Buildings.CrystalMine) * int64(delta)) - deuteriumGrowth = deuteriumGrowth + ((1 * planet.Buildings.DeuteriumMine) * int64(delta)) - energyGrowth = energyGrowth + ((1 * planet.Buildings.EnergyMine) * int64(delta)) + metalGrowth = metalGrowth + ((1 + planet.Buildings["metalmine"]) * int64(delta)) + crystalGrowth = crystalGrowth + ((1 + planet.Buildings["crystalmine"]) * int64(delta)) + deuteriumGrowth = deuteriumGrowth + ((1 + planet.Buildings["deuteriummine"]) * int64(delta)) + energyGrowth = energyGrowth + ((1 + planet.Buildings["energymine"]) * int64(delta)) } // calculate newAmount = oldAmount + growth u.Resources.Metal = u.Resources.Metal + metalGrowth

@@ -137,3 +144,34 @@

// 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 +}
M services/gamesrv/gamesrv.go → services/gamesrv/gamesrv.go

@@ -29,13 +29,14 @@ newPlanet := models.Planet{

Size: size, Name: name, OwnerId: userId, - Buildings: models.BuildingsList{ - MetalMine: 1, - CrystalMine: 1, - DeuteriumMine: 1, - EnergyMine: 1, - }, } + // in case that wants to start with resources plants + // newPlanet.Buildings = make(map[string]int64) + // newPlanet.Buildings["metalplant"] = 1 + // newPlanet.Buildings["crystalplant"] = 1 + // newPlanet.Buildings["deuteriumplant"] = 1 + // newPlanet.Buildings["energyplant"] = 1 + err := srv.db.Planets.Insert(newPlanet) if err != nil { return nil, nil, err

@@ -90,3 +91,26 @@ err = srv.db.SolarSystems.Update(bson.M{"position": position}, solarSystem)

return &solarSystem, 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 + } + + // get current building level, and get the needed resources for next level + resourcesNeeded := constants.BuildingsNeededResources[building][planet.Buildings[building]+1] + + // if user have enough resources to upgrade the building, upgrade the building + err = user.SpendResources(resourcesNeeded) + if err != nil { + return nil, err + } + // upgrade level of building in planet + planet.Buildings[building] += 1 + // store planet in db + err = srv.db.Planets.Update(bson.M{"_id": planet.Id}, planet) + return &planet, nil +}
M services/usersrv/usersrv.go → services/usersrv/usersrv.go

@@ -82,13 +82,22 @@

return &tokenString, user, err } -func (srv Service) GetUserById(userid string) (*models.User, error) { +func (srv Service) GetUserById(userid bson.ObjectId) (*models.User, error) { var userDb models.UserDb - err := srv.db.Users.Find(bson.M{"_id": bson.ObjectIdHex(userid)}).One(&userDb) + err := srv.db.Users.Find(bson.M{"_id": userid}).One(&userDb) if err != nil { return nil, err } return models.UserDbToUser(srv.db, userDb), nil +} + +func (srv Service) GetUserPlanetsById(userid bson.ObjectId) ([]*models.Planet, error) { + var planets []*models.Planet + err := srv.db.Planets.Find(bson.M{"ownerid": userid}).All(&planets) + if err != nil { + return nil, err + } + return planets, err } // func (srv Service) GetUser(id bson.ObjectId) (*models.User, error) {
M test/test.py → test/test.py

@@ -41,9 +41,39 @@ t.rStatus("get /resources", r)

jsonR = r.json() print(jsonR) -time.sleep(4) +time.sleep(1) r = requests.get(URL + "/resources/"+ userid) t.rStatus("get /resources", r) +jsonR = r.json() +print(jsonR) + +r = requests.get(URL + "/resources/"+ userid) +t.rStatus("get /resources", r) +jsonR = r.json() +print(jsonR) + +r = requests.get(URL + "/planets/"+userid) +t.rStatus("post /planets/:userid", r) +jsonR = r.json() +print(jsonR) +print(jsonR["planets"][0]) +planetid = jsonR["planets"][0]["id"] + +d = { + "planetid": planetid, + "building": "metalplant", +} +r = requests.post(URL + "/buildings/"+userid, json=d) +t.rStatus("post /building/:userid", r) +jsonR = r.json() +print(jsonR) + +d = { + "planetid": planetid, + "building": "ressearchlab", +} +r = requests.post(URL + "/buildings/"+userid, json=d) +t.rStatus("post /building/:userid", r) jsonR = r.json() print(jsonR)