]> git.cworth.org Git - empires-server/commitdiff
Standardize transmission of game "state" when a client joins
authorCarl Worth <cworth@cworth.org>
Mon, 1 Jun 2020 14:44:37 +0000 (07:44 -0700)
committerCarl Worth <cworth@cworth.org>
Mon, 1 Jun 2020 14:44:37 +0000 (07:44 -0700)
With this addition to the Game class, the TicTacToe class drops its
custom implementation of the handle_events method.

Similarly, future game implementations can simply have a "state"
property and not need to do anything further for new clients to be
provided with the current state when they join.

game.js
tictactoe.js

diff --git a/game.js b/game.js
index 706bfc7a153353358d0064f0b15deed18f44f09e..faef43798b79482e4f2e0cdc1656ec66718601c9 100644 (file)
--- a/game.js
+++ b/game.js
@@ -69,6 +69,13 @@ class Game {
     request.on('close', () => {
       this.remove_client(id);
     });
+
+    /* Finally, if this game class has a "state" property, stream that
+     * current state to the client. */
+    if (this.state) {
+      const state_json = JSON.stringify(this.state);
+      response.write(`event: game-state\ndata: ${state_json}\n\n`);
+    }
   }
 
 }
index 7b91a9bc34461158d41fd1d1495cdc84d33600c0..9140b89da9bad2d2b69e2aca9e3f53ff1c2372f9 100644 (file)
@@ -33,15 +33,6 @@ class TicTacToe extends Game {
   broadcast_move(square) {
     this.broadcast_event("move", square);
   }
-
-  handle_events(request, response) {
-    super.handle_events(request, response);
-
-    /* When a new client joins, give them the current game state,
-     * (which includes the history of moves). */
-    const state_json = JSON.stringify(this.state);
-    response.write(`event: game-state\ndata: ${state_json}\n\n`);
-  }
 }
 
 router.post('/move', (request, response) => {