server/http.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()
games.Lock()
games.m[new_game_name] = _g
log.Printf("%+v", games)
games.Unlock()
w.Write([]byte(fmt.Sprintf(`{"id": "%s"}`, new_game_name)))
}
func listGames(w http.ResponseWriter, req *http.Request) {
games.RLock()
defer games.RUnlock()
ids := make([]string, 0)
for id, _ := range games.m {
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
}
games.Lock()
game, ok := games.m[gid.Id]
games.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)
}
}