-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
74 lines (59 loc) · 1.44 KB
/
router.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"strconv"
"github.com/gin-gonic/gin"
models "server/models"
)
func (e *Env) getPlayer(id int) *models.Player {
for _, player := range e.players {
if player.Id == id {
return player
}
}
return nil
}
func (e *Env) nextId() int {
maxId := 0
for _, player := range e.players {
if player.Id > maxId {
maxId = player.Id
}
}
return maxId + 1
}
func SetupRouter(env *Env) *gin.Engine {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/player/:id/position", env.getPlayerPosition)
r.POST("/player/:id/move", env.updatePlayerPosition)
r.POST("/create", env.createPlayer)
return r
}
func (e *Env) getPlayerPosition(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
c.JSON(200, gin.H{
"x":e.getPlayer(id).Position.X,
"y":e.getPlayer(id).Position.Y,
})
}
func (e *Env) updatePlayerPosition(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var translation models.Vec2d
c.BindJSON(&translation)
e.getPlayer(id).Position.X += translation.X
e.getPlayer(id).Position.Y += translation.Y
fmt.Println(e.getPlayer(id).Position.X)
fmt.Println(e.getPlayer(id).Position.Y)
}
func (e *Env) createPlayer(c *gin.Context) {
var newPlayer models.Player
c.BindJSON(&newPlayer)
newPlayer.Id = e.nextId()
e.players = append(e.players, &newPlayer)
c.JSON(200, newPlayer)
}