From c074397c1f2d7dd97ac7bd69c8eb40a5524b8b2f Mon Sep 17 00:00:00 2001 From: Stephen McQuay Date: Fri, 18 Oct 2013 23:55:52 -0700 Subject: [PATCH] bugfix for incorrect logic in game creation --- control.go | 9 ++++++--- game.go | 13 +++++++++---- protocol.go | 5 +++-- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/control.go b/control.go index 009d1fa..859d828 100644 --- a/control.go +++ b/control.go @@ -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) diff --git a/game.go b/game.go index bac71fb..903725d 100644 --- a/game.go +++ b/game.go @@ -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 diff --git a/protocol.go b/protocol.go index 197a343..c19254a 100644 --- a/protocol.go +++ b/protocol.go @@ -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 }