server/http.go

103 lines
2.1 KiB
Go
Raw Normal View History

2013-08-28 23:46:12 -07:00
package main
import (
2013-09-03 23:26:40 -07:00
"bitbucket.org/hackerbots/bot"
2013-09-01 23:00:09 -07:00
"code.google.com/p/go.net/websocket"
"encoding/json"
"fmt"
"log"
2013-08-28 23:46:12 -07:00
"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)
}
2013-09-01 23:00:09 -07:00
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
2013-09-03 23:26:40 -07:00
log.Printf("%+v", games)
2013-09-01 23:00:09 -07:00
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 ...
2013-09-03 23:26:40 -07:00
var gid bot.GameID
2013-09-01 23:00:09 -07:00
err := websocket.JSON.Receive(ws, &gid)
if err != nil {
log.Println("problem parsing the requested game id")
return
}
gameLock.Lock()
2013-09-03 23:26:40 -07:00
game, ok := games[gid.Id]
2013-09-01 23:00:09 -07:00
gameLock.Unlock()
2013-09-03 23:26:40 -07:00
if !ok {
log.Println("ERROR: game not found")
return
}
id := idg.Hash()
2013-09-01 23:00:09 -07:00
conf, err := Negociate(ws, id, 400, 800)
if err != nil {
websocket.JSON.Send(ws, NewFailure(err.Error()))
}
if conf != nil {
p := &player{
2013-09-03 23:26:40 -07:00
Robot: bot.Robot{
2013-09-01 23:00:09 -07:00
Stats: conf.Stats,
Id: id,
Health: conf.Stats.Hp,
2013-09-03 23:26:40 -07:00
Scanners: make([]bot.Scanner, 0)},
send: make(chan *bot.Boardstate),
2013-09-01 23:00:09 -07:00
ws: ws,
2013-09-03 23:26:40 -07:00
game: game,
2013-09-01 23:00:09 -07:00
}
p.reset()
2013-09-03 23:26:40 -07:00
log.Printf("game: %+v", game)
2013-09-01 23:00:09 -07:00
game.register <- p
defer func() {
game.unregister <- p
}()
go p.sender()
p.recv()
log.Printf("%v has been disconnect from this game\n", p.Robot.Id)
} else {
s := &Spectator{
2013-09-03 23:26:40 -07:00
send: make(chan *bot.Boardstate),
2013-09-01 23:00:09 -07:00
ws: ws,
}
game.sregister <- s
defer func() {
game.sunregister <- s
}()
s.sender()
log.Printf("%+v has been disconnect from this game\n", s)
}
}