added startGame side band

This commit is contained in:
Stephen McQuay 2013-08-28 23:46:12 -07:00
parent aaaff34448
commit a1470c102a
3 changed files with 36 additions and 7 deletions

View File

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

12
http.go Normal file
View File

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

23
main.go
View File

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