diff --git a/game.go b/game.go index 6634f85..6532a50 100644 --- a/game.go +++ b/game.go @@ -12,7 +12,7 @@ type game struct { splosions map[*splosion]bool register chan *player unregister chan *player - id chan int + robot_id chan int turn int spectators map[*Spectator]bool sregister chan *Spectator @@ -59,10 +59,10 @@ func NewBoardstate(id int) *boardstate { } func (g *game) run() { - g.id = make(chan int) + g.robot_id = make(chan int) go func() { for i := 0; ; i++ { - g.id <- i + g.robot_id <- i } }() @@ -120,6 +120,8 @@ func (g *game) run() { for p := range g.players { if p.Robot.Health > 0 { log.Printf("Robot %v Wins", p.Robot.Id) + log.Printf("game over: %+v", g) + return } p.reset() } diff --git a/http.go b/http.go new file mode 100644 index 0000000..bc1fa2d --- /dev/null +++ b/http.go @@ -0,0 +1,12 @@ +package main + +import ( + "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) +} diff --git a/main.go b/main.go index b289050..f02501e 100644 --- a/main.go +++ b/main.go @@ -21,16 +21,21 @@ var height = flag.Float64("height", 550, "height of field") var delta float64 var g *game +var games map[string]*game +var idg *IdGenerator + 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)) - - g = NewGame() - go g.run() + http.Handle("/game/start/", JsonHandler(startGame)) + // http.Handle("/game/stop/", stopGame) err := http.ListenAndServe(*addr, nil) if err != nil { @@ -38,8 +43,18 @@ func main() { } } +func startGame(w http.ResponseWriter, req *http.Request) { + new_game_name := idg.Hash() + + _g := NewGame() + go _g.run() + + games[new_game_name] = _g + w.Write([]byte(fmt.Sprintf(`{"id": "%s"}`, new_game_name))) +} + func addPlayer(ws *websocket.Conn) { - id := fmt.Sprintf("robot%d", <-g.id) + id := fmt.Sprintf("robot%d", <-g.robot_id) conf, err := Negociate(ws, id, *width, *height) if err != nil {