From b800f77c2432314163de11c19620c820aaa92863 Mon Sep 17 00:00:00 2001 From: Stephen McQuay Date: Sun, 1 Sep 2013 22:04:10 -0700 Subject: [PATCH] added locking, listing --- main.go | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index f02501e..5be1222 100644 --- a/main.go +++ b/main.go @@ -2,18 +2,18 @@ package main import ( "code.google.com/p/go.net/websocket" + "encoding/json" "flag" "fmt" "log" "math/rand" "net/http" + "sync" "time" ) var addr = flag.String("addr", ":8666", "http service address") -var velocity = flag.Float64("velocity", 30, "") var tick = flag.Int("tick", 33, "") -var weapon_radius = flag.Int("weapon_radius", 35, "") var verbose = flag.Bool("verbose", false, "") var width = flag.Float64("width", 800, "width of field") var height = flag.Float64("height", 550, "height of field") @@ -23,6 +23,7 @@ var g *game var games map[string]*game var idg *IdGenerator +var gameLock sync.RWMutex func main() { rand.Seed(time.Now().UnixNano()) @@ -35,6 +36,7 @@ func main() { http.Handle("/ws/", websocket.Handler(addPlayer)) http.Handle("/game/start/", JsonHandler(startGame)) + http.Handle("/game/list/", JsonHandler(listGames)) // http.Handle("/game/stop/", stopGame) err := http.ListenAndServe(*addr, nil) @@ -46,13 +48,28 @@ func main() { func startGame(w http.ResponseWriter, req *http.Request) { new_game_name := idg.Hash() - _g := NewGame() + _g := NewGame(*width, *height) go _g.run() + gameLock.Lock() games[new_game_name] = _g + 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) { id := fmt.Sprintf("robot%d", <-g.robot_id)