]> git.cworth.org Git - empires-server/commitdiff
Send multiple game-state events (if needed) when a client connects
authorCarl Worth <cworth@cworth.org>
Mon, 11 May 2020 21:52:09 +0000 (14:52 -0700)
committerCarl Worth <cworth@cworth.org>
Mon, 11 May 2020 21:52:09 +0000 (14:52 -0700)
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.

server.js

index b7a99a594267232fc2fcd457517dc2e914fc66f2..244e6da0bf26026b83329309868c5b2cbf6d0376 100644 (file)
--- 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);