Browse Source

add CreatePlanet and put planet in solar system

master
arnaucube 5 years ago
parent
commit
5965f2dec1
11 changed files with 141 additions and 45 deletions
  1. +5
    -3
      database/database.go
  2. +3
    -2
      endpoint/handlers.go
  3. +0
    -10
      models/galaxy.go
  4. +5
    -3
      models/planet.go
  5. +12
    -0
      models/solarsystem.go
  6. +3
    -1
      models/user.go
  7. +86
    -0
      services/gamesrv/gamesrv.go
  8. +6
    -9
      services/usersrv/usersrv.go
  9. +1
    -2
      test/package.json
  10. +13
    -15
      test/test.js
  11. +7
    -0
      utils/utils.go

+ 5
- 3
database/database.go

@ -3,9 +3,10 @@ package database
import mgo "gopkg.in/mgo.v2" import mgo "gopkg.in/mgo.v2"
type Db struct { type Db struct {
Users *mgo.Collection
Planets *mgo.Collection
Galaxies *mgo.Collection
Users *mgo.Collection
Planets *mgo.Collection
SolarSystems *mgo.Collection
Galaxies *mgo.Collection
} }
func New(url string, databaseName string) (*Db, error) { func New(url string, databaseName string) (*Db, error) {
@ -24,6 +25,7 @@ func New(url string, databaseName string) (*Db, error) {
db := Db{} db := Db{}
db.Users = session.DB(databaseName).C("users") db.Users = session.DB(databaseName).C("users")
db.Planets = session.DB(databaseName).C("planets") db.Planets = session.DB(databaseName).C("planets")
db.SolarSystems = session.DB(databaseName).C("solarsystems")
db.Galaxies = session.DB(databaseName).C("galaxies") db.Galaxies = session.DB(databaseName).C("galaxies")
return &db, nil return &db, nil

+ 3
- 2
endpoint/handlers.go

@ -50,12 +50,13 @@ type LoginMsg struct {
func handleLogin(c *gin.Context) { func handleLogin(c *gin.Context) {
var loginMsg LoginMsg var loginMsg LoginMsg
c.BindJSON(&loginMsg) c.BindJSON(&loginMsg)
user, err := userservice.Login(loginMsg.Email, loginMsg.Password)
token, user, err := userservice.Login(loginMsg.Email, loginMsg.Password)
if err != nil { if err != nil {
fail(c, err, "error on login") fail(c, err, "error on login")
return return
} }
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"user": user,
"token": token,
"user": user,
}) })
} }

+ 0
- 10
models/galaxy.go

@ -1,10 +0,0 @@
package models
type Galaxy struct {
SolarSystem []string
}
type SolarSystem struct {
Id string
Planets []string // array with ids of the planets
}

+ 5
- 3
models/planet.go

@ -1,8 +1,10 @@
package models package models
import "gopkg.in/mgo.v2/bson"
type Planet struct { type Planet struct {
Id string
Size int64 // fields
Id bson.ObjectId `json:"id", bson:"_id, omitempty"`
Size int64 // fields/slots
Name string Name string
OwnerId string
OwnerId bson.ObjectId
} }

+ 12
- 0
models/solarsystem.go

@ -0,0 +1,12 @@
package models
import "gopkg.in/mgo.v2/bson"
const GALAXYSIZE = 50
const SOLARSYSTEMSIZE = 15
type SolarSystem struct {
Id bson.ObjectId `json:"id", bson:"_id, omitempty"`
Position int64 // position of the solar system in the galaxy, the maximum position is GALAXYSIZE-1
Planets []bson.ObjectId // array with ids of the planets, if empty is equal to ""
}

+ 3
- 1
models/user.go

@ -1,12 +1,14 @@
package models package models
import "gopkg.in/mgo.v2/bson"
type Resource struct { type Resource struct {
Value int64 Value int64
Max int64 Max int64
} }
type User struct { type User struct {
Id string
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Name string Name string
Password string Password string
Email string Email string

+ 86
- 0
services/gamesrv/gamesrv.go

@ -0,0 +1,86 @@
package gamesrv
import (
"fmt"
"github.com/arnaucube/gogame/database"
"github.com/arnaucube/gogame/models"
"github.com/arnaucube/gogame/utils"
"gopkg.in/mgo.v2/bson"
)
type Service struct {
db *database.Db
}
func New(db *database.Db) *Service {
return &Service{
db,
}
}
// CreatePlanet is used when a user conquers a planet
func (srv Service) CreatePlanet(userId bson.ObjectId) (*models.SolarSystem, *models.Planet, error) {
size := int64(250) // TODO get rand inside a range
name := "planetname" // TODO get random name
newPlanet := models.Planet{
Size: size,
Name: name,
OwnerId: userId,
}
err := srv.db.Planets.Insert(newPlanet)
if err != nil {
return nil, nil, err
}
var planet *models.Planet
err = srv.db.Planets.Find(bson.M{"name": name}).One(&planet)
if err != nil {
return nil, nil, err
}
// now put the planet in a solar system
// get random solar system
systemPosition := utils.RandInRange(0, models.GALAXYSIZE)
solarSystem, err := srv.PutPlanetInSolarSystem(systemPosition, planet)
// TODO if error is returned because there is no empty slots for planets in the solar system in systemPosition, get another systemPosition and try again
return solarSystem, planet, err
}
func (srv Service) PutPlanetInSolarSystem(position int64, planet *models.Planet) (*models.SolarSystem, error) {
var solarSystem models.SolarSystem
err := srv.db.SolarSystems.Find(bson.M{"position": position}).One(&solarSystem)
if err != nil {
// solar system non existing yet
// create a solarsystem with empty planets
var emptyPlanets []bson.ObjectId
for i := 0; i < models.SOLARSYSTEMSIZE; i++ {
emptyPlanets = append(emptyPlanets, "")
}
newSolarSystem := models.SolarSystem{
Position: position,
Planets: emptyPlanets[:15],
}
err = srv.db.SolarSystems.Insert(newSolarSystem)
if err != nil {
return nil, err
}
err := srv.db.SolarSystems.Find(bson.M{"position": position}).One(&solarSystem)
return &solarSystem, err
}
// get free slots in solarSystem
posInSolarSystem := utils.RandInRange(0, models.SOLARSYSTEMSIZE)
if solarSystem.Planets[posInSolarSystem] != "" {
// not empty slot, take another one TODO
// if there are no empty slots, return error
fmt.Println("not empty slot")
}
// store planet in solar system
solarSystem.Planets[posInSolarSystem] = planet.Id
err = srv.db.SolarSystems.Update(bson.M{"position": position}, solarSystem)
return &solarSystem, err
}

+ 6
- 9
services/usersrv/usersrv.go

@ -57,15 +57,16 @@ func (srv Service) Register(name, password, email string) (*models.User, error)
var signingKey = []byte("TODO") // TODO var signingKey = []byte("TODO") // TODO
func (srv Service) Login(email, password string) (*models.User, error) {
func (srv Service) Login(email, password string) (*string, *models.User, error) {
var user models.User var user models.User
err := srv.db.Users.Find(bson.M{"email": email}).One(&user) err := srv.db.Users.Find(bson.M{"email": email}).One(&user)
if err != nil { if err != nil {
return nil, errors.New("user not exist")
return nil, nil, errors.New("user not exist")
} }
if !checkPasswordHash(password, user.Password) { if !checkPasswordHash(password, user.Password) {
return nil, errors.New("error with password")
return nil, nil, errors.New("error with password")
} }
user.Password = ""
// create jwt // create jwt
token := jwt.New(jwt.SigningMethodHS256) token := jwt.New(jwt.SigningMethodHS256)
@ -76,12 +77,8 @@ func (srv Service) Login(email, password string) (*models.User, error) {
tokenString, err := token.SignedString(signingKey) tokenString, err := token.SignedString(signingKey)
if err != nil { if err != nil {
return nil, errors.New("error creating token")
return nil, nil, errors.New("error creating token")
} }
// TODO
// reuse Password parameter, to put there the token
user.Password = tokenString
return &user, err
return &tokenString, &user, err
} }

+ 1
- 2
test/package.json

@ -17,7 +17,6 @@
}, },
"homepage": "https://github.com/arnaucube/gogame#readme", "homepage": "https://github.com/arnaucube/gogame#readme",
"dependencies": { "dependencies": {
"axios": "^0.19.0",
"sleep": "^6.1.0"
"axios": "^0.19.0"
} }
} }

+ 13
- 15
test/test.js

@ -1,22 +1,20 @@
const axios = require('axios'); const axios = require('axios');
const sleep = require('sleep');
const url = 'http://127.0.0.1:5000'; const url = 'http://127.0.0.1:5000';
let newUser = {
name: 'user00',
password: 'user00password',
email: 'user00@email.com'
};
axios.post(url + '/register', newUser)
.then(function (res) {
console.log(res.data);
})
.catch(function (error) {
console.log(error.response.data);
});
// let newUser = {
// name: 'user00',
// password: 'user00password',
// email: 'user00@email.com'
// };
// axios.post(url + '/register', newUser)
// .then(function (res) {
// console.log(res.data);
// })
// .catch(function (error) {
// console.error(error.response.data);
// });
// sleep.sleep(3);
let user = { let user = {
email: 'user00@email.com', email: 'user00@email.com',
@ -27,5 +25,5 @@ axios.post(url + '/login', user)
console.log(res.data); console.log(res.data);
}) })
.catch(function (error) { .catch(function (error) {
console.log(error.response.data);
console.error(error.response.data);
}); });

+ 7
- 0
utils/utils.go

@ -0,0 +1,7 @@
package utils
import "math/rand"
func RandInRange(min, max int) int64 {
return int64(rand.Intn(max-min) + min)
}

Loading…
Cancel
Save