bugfix for incorrect logic in game creation

This commit is contained in:
Stephen McQuay 2013-10-18 23:55:52 -07:00
parent c80acb478b
commit c074397c1f
3 changed files with 18 additions and 9 deletions

View File

@ -17,13 +17,16 @@ func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
func startGame(w http.ResponseWriter, req *http.Request) {
log.Println("asked to create a game")
new_game_name := idg.Hash()
games.getOrCreate(new_game_name)
g, err := games.get("", true)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
game_json := struct {
Id string `json:"id"`
}{
Id: new_game_name,
Id: g.id,
}
if err := json.NewEncoder(w).Encode(game_json); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)

13
game.go
View File

@ -44,7 +44,10 @@ type MapLock struct {
sync.RWMutex
}
func (ml *MapLock) getOrCreate(id string) (*game, error) {
// get is a function that returns a game if found, and creates one if
// not found and force is true. In order to get a hash (rather than use
// the string you pass) send "" for id.
func (ml *MapLock) get(id string, force bool) (*game, error) {
ml.Lock()
g, ok := games.m[id]
ml.Unlock()
@ -53,17 +56,19 @@ func (ml *MapLock) getOrCreate(id string) (*game, error) {
return g, nil
}
if !*debug {
if !force {
return nil, errors.New("game not found")
}
new_game_name := idg.Hash()
if id == "" {
id = idg.Hash()
}
_g := NewGame(id, *width, *height)
go _g.run()
ml.Lock()
ml.m[new_game_name] = _g
ml.m[id] = _g
ml.Unlock()
return _g, nil

View File

@ -99,10 +99,11 @@ func addPlayer(ws *websocket.Conn) {
return
}
game, err := games.getOrCreate(gid.Id)
force := *debug
game, err := games.get(gid.Id, force)
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"))
return
}