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") return } id := idg.Hash() conf, err := Negociate(ws, id, 400, 800) if err != nil { websocket.JSON.Send(ws, 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("%v has been disconnect from this game\n", 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) } }