|
|
@@ -3,9 +3,13 @@ package games
|
|
|
import (
|
|
|
"battlecamp-go-server/board"
|
|
|
"battlecamp-go-server/player"
|
|
|
+ "encoding/json"
|
|
|
+ "log"
|
|
|
"math/rand"
|
|
|
"sync"
|
|
|
"time"
|
|
|
+
|
|
|
+ "github.com/go-stomp/stomp"
|
|
|
)
|
|
|
|
|
|
type Game struct {
|
|
|
@@ -24,7 +28,7 @@ func NewGame(cols, rows int) *Game {
|
|
|
game := &Game{
|
|
|
StartTime: createTime,
|
|
|
Board: board.New(cols, rows),
|
|
|
- Players: make([]*player.Player, 0),
|
|
|
+ Players: make([]*player.Player, 0),
|
|
|
}
|
|
|
|
|
|
return game
|
|
|
@@ -54,11 +58,61 @@ func (g *Game) placePlayer(p *player.Player) {
|
|
|
|
|
|
}
|
|
|
|
|
|
+type updatePlayers struct {
|
|
|
+ GameId int64 `json:"gameId"`
|
|
|
+ Players []*player.Player `json:"players"`
|
|
|
+}
|
|
|
+
|
|
|
+func (g *Game) Move(p *player.Player, direction string, sc *stomp.Conn) bool {
|
|
|
+ if !(direction == "N" || direction == "W" || direction == "S" || direction == "E") {
|
|
|
+ log.Printf("Illigal direction %v", direction)
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ newX := p.Pos.X
|
|
|
+ newY := p.Pos.Y
|
|
|
+
|
|
|
+ switch direction {
|
|
|
+ case "N":
|
|
|
+ newY--
|
|
|
+ case "W":
|
|
|
+ newX--
|
|
|
+ case "S":
|
|
|
+ newY++
|
|
|
+ case "E":
|
|
|
+ newX++
|
|
|
+ }
|
|
|
+
|
|
|
+ //TODO make thread safe
|
|
|
+ if !g.isValidPlayerPos(newX, newY) {
|
|
|
+ log.Printf("Illigal player pos oldX %v oldY %v newX %v newY %v dir %v ", p.Pos.X, p.Pos.Y, newX, newY, direction)
|
|
|
+ return false
|
|
|
+ }
|
|
|
+
|
|
|
+ p.Pos.X = newX
|
|
|
+ p.Pos.Y = newY
|
|
|
+ // END TODO make tread safe
|
|
|
+
|
|
|
+ up := updatePlayers{
|
|
|
+ GameId: g.Id,
|
|
|
+ Players: g.Players,
|
|
|
+ }
|
|
|
+
|
|
|
+ b, _ := json.Marshal(up)
|
|
|
+
|
|
|
+ sc.Send("/topic/go-battlecamp.update", "", b)
|
|
|
+
|
|
|
+ return true
|
|
|
+}
|
|
|
+
|
|
|
func (g *Game) isValidPlayerPos(x, y int) bool {
|
|
|
+ if x < 0 || y < 0 || x >= g.Board.Cols || y >= g.Board.Rows {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+
|
|
|
t := g.Board.Get(x, y)
|
|
|
|
|
|
if t == board.Rock {
|
|
|
- return false;
|
|
|
+ return false
|
|
|
}
|
|
|
|
|
|
return g.getPlayerAt(x, y) == nil
|
|
|
@@ -67,7 +121,7 @@ func (g *Game) isValidPlayerPos(x, y int) bool {
|
|
|
func (g *Game) getPlayerAt(x, y int) *player.Player {
|
|
|
|
|
|
for _, p := range g.Players {
|
|
|
- if (p.Pos.X == x && p.Pos.Y == y) {
|
|
|
+ if p.Pos.X == x && p.Pos.Y == y {
|
|
|
return p
|
|
|
}
|
|
|
}
|
|
|
@@ -78,7 +132,7 @@ func (g *Game) getPlayerAt(x, y int) *player.Player {
|
|
|
func (g *Game) GetPlayer(playerId string) *player.Player {
|
|
|
|
|
|
for _, p := range g.Players {
|
|
|
- if p.Id == playerId{
|
|
|
+ if p.Id == playerId {
|
|
|
return p
|
|
|
}
|
|
|
}
|