From fbf331eedc7d4579ec861c140e26a11b04278c1c Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Mon, 1 Jun 2020 14:16:04 -0700 Subject: [PATCH] Generalize the handling of the /move request 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 | 4 ++++ lmno.js | 20 ++++++++++++++++++++ tictactoe.js | 20 -------------------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/game.js b/game.js index faef437..f1f764f 100644 --- 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 5e67350..8d66b41 100644 --- 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); } diff --git a/tictactoe.js b/tictactoe.js index 1521695..2a8dd06 100644 --- a/tictactoe.js +++ b/tictactoe.js @@ -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; -- 2.43.0