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 tick = flag.Int("tick", 33, "") var verbose = flag.Bool("verbose", false, "") var width = flag.Float64("width", 800, "width of field") var height = flag.Float64("height", 550, "height of field") var delta float64 var g *game var games map[string]*game var idg *IdGenerator var gameLock sync.RWMutex func main() { rand.Seed(time.Now().UnixNano()) flag.Parse() games = make(map[string]*game) idg = NewIdGenerator() delta = float64(*tick) / 1000 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) if err != nil { log.Fatal("unable to start server") } } func startGame(w http.ResponseWriter, req *http.Request) { new_game_name := idg.Hash() _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) conf, err := Negociate(ws, id, *width, *height) if err != nil { websocket.JSON.Send(ws, NewFailure(err.Error())) } if conf != nil { p := &player{ Robot: robot{ Stats: conf.Stats, Id: id, Health: conf.Stats.Hp, Scanners: make([]scanner, 0)}, send: make(chan *boardstate), ws: ws, } p.reset() g.register <- p defer func() { g.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 *boardstate), ws: ws, } g.sregister <- s defer func() { g.sunregister <- s }() s.sender() log.Printf("%+v has been disconnect from this game\n", s) } }