From: Carl Worth Date: Mon, 11 May 2020 21:52:09 +0000 (-0700) Subject: Send multiple game-state events (if needed) when a client connects X-Git-Url: https://git.cworth.org/git?a=commitdiff_plain;h=7363a23acc24ac73720927802043748e602e2da4;p=empires-server Send multiple game-state events (if needed) when a client connects This implements the latest change as of version 0.6 of the API protocol. This change fixes a bug in the current empires-html client where reloading the browser when in the middle of the game would break the client, (by displaying some content that's inappropriate for the current state). By sending each step-wise transition through the game states, the client does not get confused. --- diff --git a/server.js b/server.js index b7a99a5..244e6da 100644 --- a/server.js +++ b/server.js @@ -166,20 +166,21 @@ class Game { this.broadcast_string(`event: ${type}\ndata: ${data}\n`); } - game_state_event_data() { + game_state_event_data(old_state, new_state) { var old_state_name; - if (this.old_state) - old_state_name = GameState.properties[this.old_state].name; + if (old_state) + old_state_name = GameState.properties[old_state].name; else old_state_name = "none"; - const new_state_name = GameState.properties[this.state].name; + const new_state_name = GameState.properties[new_state].name; return `{"old_state":"${old_state_name}","new_state":"${new_state_name}"}`; } /* Inform clients about a state change. */ broadcast_state_change() { - this.broadcast_event("game-state", this.game_state_event_data()); + const event_data = this.game_state_event_data(this.old_state, this.state); + this.broadcast_event("game-state", event_data); } /* Change game state and broadcast the change to all clients. */ @@ -217,8 +218,17 @@ function handle_events(request, response) { response.write(players_data); } - /* And we need to inform the client of the current game state. */ - response.write("event: game-state\n" + "data: " + game.game_state_event_data() + "\n\n"); + /* And we need to inform the client of the current game state. + * + * In fact, we need to cycle through each state transition from the + * beginning so the client can see each. + */ + var old_state = null; + for (var state = GameState.JOIN; state <= game.state; state++) { + var event_data = game.game_state_event_data(old_state, state); + response.write("event: game-state\n" + "data: " + event_data + "\n\n"); + old_state = state; + } /* Add this new client to our list of clients. */ const id = game.add_client(response);