added locking, listing

This commit is contained in:
Stephen McQuay 2013-09-01 22:04:10 -07:00
parent a1470c102a
commit b800f77c24

23
main.go
View File

@ -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)