]> git.cworth.org Git - empires-server/commitdiff
Generalize the handling of the /move request
authorCarl Worth <cworth@cworth.org>
Mon, 1 Jun 2020 21:16:04 +0000 (14:16 -0700)
committerCarl Worth <cworth@cworth.org>
Mon, 1 Jun 2020 21:20:38 +0000 (14:20 -0700)
Implementing it at the "lmno" level instead of in "tictactoe".

This means that future game implementations that involve clients
sending moves to the server (which, is obviously a common thing), can
simply implement an "add_move" method in the Game class at not need to
implement the route handler piece of things.

game.js
lmno.js
tictactoe.js

diff --git a/game.js b/game.js
index faef43798b79482e4f2e0cdc1656ec66718601c9..f1f764fa1968425d597e4e2ab47e4b8d916650a8 100644 (file)
--- a/game.js
+++ b/game.js
@@ -78,6 +78,10 @@ class Game {
     }
   }
 
+  broadcast_move(move) {
+    this.broadcast_event("move", move);
+  }
+
 }
 
 module.exports = Game;
diff --git a/lmno.js b/lmno.js
index 5e67350992497abacf41247720d0b304fc8cab8e..8d66b41ea09e066ffc2acce777a744c83f837c99 100644 (file)
--- a/lmno.js
+++ b/lmno.js
@@ -264,6 +264,26 @@ for (let key in engines) {
     game.handle_events(request, response);
   });
 
+  /* Further, add some routes conditionally depending on whether the
+   * engine provides specific, necessary methods for the routes. */
+  if (engine.Game.prototype.add_move) {
+    engine.router.post('/move', (request, response) => {
+      const game = request.game;
+      const move = request.body.move;
+
+      const legal = game.add_move(move);
+
+      /* Inform this client whether the move was legal. */
+      response.send(JSON.stringify(legal));
+
+      /* And only if legal, inform all clients. */
+      if (! legal)
+        return;
+
+      game.broadcast_move(move);
+    });
+  }
+
   /* And mount the whole router at the path for the game. */
   app.use(`/${engine.Game.meta.identifier}/[a-zA-Z0-9]{4}/`, engine.router);
 }
index 15216952b3577ceb7cdee0dc4b20c924b67181f3..2a8dd06f9d580398e483e7a554883beee54bcc4e 100644 (file)
@@ -29,28 +29,8 @@ class TicTacToe extends Game {
 
     return true;
   }
-
-  broadcast_move(move) {
-    this.broadcast_event("move", move);
-  }
 }
 
-router.post('/move', (request, response) => {
-  const game = request.game;
-  const move = request.body.move;
-
-  const legal = game.add_move(move);
-
-  /* Inform this client whether the move was legal. */
-  response.send(JSON.stringify(legal));
-
-  /* And only if legal, inform all clients. */
-  if (! legal)
-    return;
-
-  game.broadcast_move(move);
-});
-
 exports.router = router;
 exports.Game = TicTacToe;