added ability to autovivify games in debug mode

This commit is contained in:
Stephen McQuay 2013-10-18 20:48:22 -07:00
parent 2edc7c61af
commit d19b3f71fa
4 changed files with 36 additions and 17 deletions

View File

@ -18,13 +18,7 @@ func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
func startGame(w http.ResponseWriter, req *http.Request) { func startGame(w http.ResponseWriter, req *http.Request) {
log.Println("asked to create a game") log.Println("asked to create a game")
new_game_name := idg.Hash() new_game_name := idg.Hash()
games.getOrCreate(new_game_name)
_g := NewGame(new_game_name, *width, *height)
go _g.run()
games.Lock()
games.m[new_game_name] = _g
games.Unlock()
game_json := struct { game_json := struct {
Id string `json:"id"` Id string `json:"id"`

32
game.go
View File

@ -2,8 +2,10 @@ package main
import ( import (
v "bitbucket.org/hackerbots/vector" v "bitbucket.org/hackerbots/vector"
"errors"
"log" "log"
"sort" "sort"
"sync"
"time" "time"
) )
@ -37,6 +39,36 @@ type Scanner struct {
Stats Stats `json:"stats"` Stats Stats `json:"stats"`
} }
type MapLock struct {
m map[string]*game
sync.RWMutex
}
func (ml *MapLock) getOrCreate(id string) (*game, error) {
ml.Lock()
g, ok := games.m[id]
ml.Unlock()
if ok {
return g, nil
}
if !*debug {
return nil, errors.New("game not found")
}
new_game_name := idg.Hash()
_g := NewGame(id, *width, *height)
go _g.run()
ml.Lock()
ml.m[new_game_name] = _g
ml.Unlock()
return _g, nil
}
type game struct { type game struct {
id string id string
players map[*player]bool players map[*player]bool

View File

@ -8,7 +8,6 @@ import (
"net/http" "net/http"
"os" "os"
"runtime/pprof" "runtime/pprof"
"sync"
"time" "time"
) )
@ -18,16 +17,12 @@ var verbose = flag.Bool("verbose", false, "")
var width = flag.Float64("width", 800, "width of field") var width = flag.Float64("width", 800, "width of field")
var height = flag.Float64("height", 550, "height of field") var height = flag.Float64("height", 550, "height of field")
var profile = flag.String("pprof", "", "if specified will run with pprof") var profile = flag.String("pprof", "", "if specified will run with pprof")
var debug = flag.Bool("debug", false, "automatically create games if they don't exist")
var delta float64 var delta float64
var idg *IdGenerator var idg *IdGenerator
type MapLock struct {
m map[string]*game
sync.RWMutex
}
// This is the main, global collection of games // This is the main, global collection of games
var games MapLock var games MapLock

View File

@ -99,11 +99,9 @@ func addPlayer(ws *websocket.Conn) {
return return
} }
games.Lock() game, err := games.getOrCreate(gid.Id)
game, ok := games.m[gid.Id]
games.Unlock()
if !ok { if err != nil {
log.Printf("ERROR: game %s not found", gid.Id) log.Printf("ERROR: game %s not found", gid.Id)
websocket.JSON.Send(ws, NewFailure("game 404")) websocket.JSON.Send(ws, NewFailure("game 404"))
return return