Stephen McQuay
fb0e6d92d7
turns out we were never exiting the loop even when all bots left. Games now shut down when there ever has been bots and they all leave (or are killed, I think).
103 lines
2.1 KiB
Go
103 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bitbucket.org/hackerbots/bot"
|
|
"code.google.com/p/go.net/websocket"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type JsonHandler func(http.ResponseWriter, *http.Request)
|
|
|
|
func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
h(w, req)
|
|
}
|
|
|
|
func startGame(w http.ResponseWriter, req *http.Request) {
|
|
new_game_name := idg.Hash()
|
|
|
|
_g := NewGame(new_game_name, *width, *height)
|
|
go _g.run()
|
|
|
|
gameLock.Lock()
|
|
games[new_game_name] = _g
|
|
log.Printf("%+v", games)
|
|
gameLock.Unlock()
|
|
|
|
w.Write([]byte(fmt.Sprintf(`{"id": "%s"}`, new_game_name)))
|
|
}
|
|
|
|
func listGames(w http.ResponseWriter, req *http.Request) {
|
|
gameLock.RLock()
|
|
defer gameLock.RUnlock()
|
|
ids := make([]string, 0)
|
|
for id, _ := range games {
|
|
ids = append(ids, id)
|
|
}
|
|
if err := json.NewEncoder(w).Encode(ids); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
func addPlayer(ws *websocket.Conn) {
|
|
// route to appropriate game ...
|
|
var gid bot.GameID
|
|
err := websocket.JSON.Receive(ws, &gid)
|
|
if err != nil {
|
|
log.Println("problem parsing the requested game id")
|
|
return
|
|
}
|
|
|
|
gameLock.Lock()
|
|
game, ok := games[gid.Id]
|
|
gameLock.Unlock()
|
|
|
|
if !ok {
|
|
log.Println("ERROR: game not found")
|
|
websocket.JSON.Send(ws, bot.NewFailure("game 404"))
|
|
return
|
|
}
|
|
|
|
id := idg.Hash()
|
|
|
|
conf, err := Negociate(ws, id, game.width, game.height)
|
|
if err != nil {
|
|
websocket.JSON.Send(ws, bot.NewFailure(err.Error()))
|
|
}
|
|
|
|
if conf != nil {
|
|
p := &player{
|
|
Robot: bot.Robot{
|
|
Stats: conf.Stats,
|
|
Id: id,
|
|
Health: conf.Stats.Hp,
|
|
Scanners: make([]bot.Scanner, 0)},
|
|
send: make(chan *bot.Boardstate),
|
|
ws: ws,
|
|
}
|
|
p.reset()
|
|
log.Printf("game: %+v", game)
|
|
game.register <- p
|
|
defer func() {
|
|
game.unregister <- p
|
|
}()
|
|
go p.sender()
|
|
p.recv()
|
|
log.Printf("game %s: %v has been disconnect from this game\n", gid, p.Robot.Id)
|
|
} else {
|
|
s := &Spectator{
|
|
send: make(chan *bot.Boardstate),
|
|
ws: ws,
|
|
}
|
|
game.sregister <- s
|
|
defer func() {
|
|
game.sunregister <- s
|
|
}()
|
|
s.sender()
|
|
log.Printf("%+v has been disconnect from this game\n", s)
|
|
}
|
|
}
|