From 5c589dc3c8016c2f43174b1cf6de3e934835a142 Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Fri, 5 Jun 2020 06:18:19 -0700 Subject: [PATCH] game: Add a new /player endpoint to allow a player to change their name This sets the name both in the current game's player object as well as in the session, (so it's there for subsequent games as well). We have a simple test for this new endpoint as well. --- game.js | 21 +++++++++++++++++++++ lmno.js | 8 ++++++++ test | 16 ++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/game.js b/game.js index b219336..0adf953 100644 --- a/game.js +++ b/game.js @@ -162,6 +162,27 @@ class Game { } } + handle_player(request, response) { + const player = this.find_player(request.session); + if (! player) { + response.sendStatus(404); + return; + } + + if (request.body.name && (player.name !== request.body.name)) { + player.name = request.body.name; + + /* In addition to setting the name within this game's player + * object, also set the name in the session. */ + request.session.nickname = player.name; + request.session.save(); + + this.broadcast_event("player-update", player.info_json()); + } + + response.send(""); + } + broadcast_move(move) { this.broadcast_event("move", move); } diff --git a/lmno.js b/lmno.js index b6c5b78..1e1d260 100644 --- a/lmno.js +++ b/lmno.js @@ -69,6 +69,8 @@ nunjucks.configure("templates", { * * / Serves -game.html template * + * /player Allows client to set name + * * /events Serves a stream of events. Game can override * the handle_events method, call super() first, * and then have code to add custom events. @@ -289,6 +291,12 @@ for (let key in engines) { response.render(`${game.meta.identifier}-game.html`); }); + router.put('/player', (request, response) => { + const game = request.game; + + game.handle_player(request, response); + }); + router.get('/events', (request, response) => { const game = request.game; diff --git a/test b/test index 9ba6185..e19539b 100755 --- a/test +++ b/test @@ -317,6 +317,11 @@ tictactoe_player_info() | grep ^data } +tictactoe_player() +{ + curl_put $tictactoe_game_path/player "{ \"name\": \"$1\" }" "-b .test-cookie" +} + TEST_SUBSECTION "Tic Tac Toe player-info" TEST "Hit LMNO /profile to set name to 'curl'" @@ -328,6 +333,17 @@ result=$(tictactoe_player_info) test "$result" = 'data: {"id":1,"name":"curl"}' TEST_END +TEST_SUBSECTION "Tic Tac Toe /player" + +TEST "Change name to 'newname'" +tictactoe_player newname +TEST_END + +TEST "Verify player-info event reports 'newname'" +result=$(tictactoe_player_info) +test "$result" = 'data: {"id":1,"name":"newname"}' +TEST_END + TEST_SUBSECTION "Tic Tac Toe /move" TEST "Move to the center square" -- 2.43.0