Ronald Peterson 10 tahun lalu
induk
melakukan
d2d64c6c40
2 mengubah file dengan 28 tambahan dan 7 penghapusan
  1. 19 2
      games/game.go
  2. 9 5
      urlrouter.go

+ 19 - 2
games/game.go

@@ -63,6 +63,11 @@ type updatePlayers struct {
 	Players []*player.Player `json:"players"`
 }
 
+type stompGameEnd struct {
+	Type   string `json:"type"`
+	GameId int64  `json:"gameId"`
+}
+
 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)
@@ -91,19 +96,31 @@ func (g *Game) Move(p *player.Player, direction string, sc *stomp.Conn) bool {
 	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", "application/json;charset=utf-8", b, stomp.SendOpt.NoContentLength)
 
-	sc.Send("/topic/go-battlecamp.update", "", b)
+	if g.isWinner(p) {
+		g.EndTime = time.Now().Unix()
+		ge := stompGameEnd{
+			Type:   "GAME_END",
+			GameId: g.Id,
+		}
+		c, _ := json.Marshal(ge)
+		sc.Send("/topic/go-battlecamp.game", "application/json;charset=utf-8", c, stomp.SendOpt.NoContentLength)
+	}
 
 	return true
 }
 
+func (g *Game) isWinner(p *player.Player) bool {
+	return g.Board.Finish.X == p.Pos.X && g.Board.Finish.Y == p.Pos.Y
+}
+
 func (g *Game) isValidPlayerPos(x, y int) bool {
 	if x < 0 || y < 0 || x >= g.Board.Cols || y >= g.Board.Rows {
 		return false

+ 9 - 5
urlrouter.go

@@ -1,14 +1,15 @@
 package main
 
 import (
-	"log"
 	"battlecamp-go-server/games"
 	"battlecamp-go-server/player"
 	"encoding/json"
 	"fmt"
+	"log"
 	"net/http"
 	"strconv"
 
+	"github.com/go-stomp/stomp"
 	"github.com/julienschmidt/httprouter"
 )
 
@@ -85,6 +86,10 @@ func joinGame(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
 
 	e := json.NewEncoder(w)
 	e.Encode(&p)
+
+	b, _ := json.Marshal(p)
+	stompConnection.Send("/topic/go-battlecamp.update", "application/json;charset=utf-8", b, stomp.SendOpt.NoContentLength)
+
 	log.Printf("Player %v joined game %v", p.Id, game.Id)
 }
 
@@ -121,14 +126,13 @@ func movePlayer(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
 	p := g.GetPlayer(playerId)
 	w.Header().Set("Content-Type", "application/json")
 	direction := ps.ByName("direction")
-	
+
 	result := g.Move(p, direction, stompConnection)
-	
+
 	if !result {
 		http.Error(w, "Bad request", http.StatusBadRequest)
 	}
-	
-	
+
 	e := json.NewEncoder(w)
 	e.Encode(p.Pos)
 	log.Printf("Player %v moved in direction %v\n", p.Id, direction)