From c9c80e294186a8b2ef742806559a0655d624c05f Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Sat, 2 May 2020 16:53:13 -0700 Subject: [PATCH] Add an ID value to each player This is a first baby step toward implementing the more complete API for the game which we defined today, and which can be found here: https://git.cworth.org/git/empires-api In this commit we also introduce a 'Game' class to encapsulate all data necessary for the game, (so the 'players' array we had before, but also the 'next_player_id' which we need now). --- server.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 7b95a6b..4957f32 100644 --- a/server.js +++ b/server.js @@ -3,7 +3,21 @@ const body_parser = require("body-parser"); const app = express(); -const players = []; +class Game { + constructor() { + this.players = []; + this.next_player_id = 1; + } + + add_player(name, character) { + this.players.push({id: this.next_player_id, + name: name, + character: character}) + this.next_player_id++; + } +} + +game = new Game(); app.use(body_parser.urlencoded({ extended: false })); app.use(body_parser.json()); @@ -13,12 +27,11 @@ app.get('/', function (requses, response) { }); app.get('/players', function (request, response) { - response.send(players); + response.send(game.players); }); app.post('/register', function (request, response) { - players.push({name: request.body.name, - character: request.body.character}); + game.add_player(request.body.name, request.body.character); response.send(); }); -- 2.43.0