From: Carl Worth Date: Mon, 8 Jun 2020 13:59:43 +0000 (-0700) Subject: Empathy: Add routes to receive prompts and votes on prompts X-Git-Url: https://git.cworth.org/git?a=commitdiff_plain;ds=sidebyside;h=7671bd12ebaa902c287b0730eeda39dae9f418c8;p=empires-server Empathy: Add routes to receive prompts and votes on prompts The received votes are added to the prompt objects themselves, so we don't need to send anything beyond the prompts, and the votes will just ride along "for free". Also, because prompts are a part of the Empathy game's "state" property, they will always be sent as part of the "game-state" event sent when a new client joins, so we don't need any explicit code in the Empathy class to take care of that either. --- diff --git a/empathy.js b/empathy.js index 12a743e..f2a6859 100644 --- a/empathy.js +++ b/empathy.js @@ -4,10 +4,62 @@ const Game = require("./game.js"); class Empathy extends Game { constructor(id) { super(id); + this.state = { + prompts: [] + }; + this.next_prompt_id = 1; } } Empathy.router = express.Router(); +const router = Empathy.router; + +class Prompt { + constructor(id, items, prompt) { + this.id = id; + this.items = items; + this.prompt = prompt; + this.votes = []; + } + + add_vote(player_name) { + if (this.votes.find(v => v === player_name)) + return; + + this.votes.push(player_name); + } +} + +router.post('/prompts', (request, response) => { + const game = request.game; + + const prompt = new Prompt(game.next_prompt_id, + request.body.items, + request.body.prompt); + game.next_prompt_id++; + + game.state.prompts.push(prompt); + + game.broadcast_event_object('prompt', prompt); +}); + +router.post('/vote/:prompt_id([0-9]+)', (request, response) => { + const prompt_id = parseInt(request.params.prompt_id, 10); + const game = request.game; + const player = game.players_by_session[request.session.id]; + + prompt = game.state.prompts.find(p => p.id === prompt_id); + if (! prompt || ! player) { + response.sendStatus(404); + return; + } + + prompt.add_vote(player.name); + + game.broadcast_event_object('prompt', prompt); + + response.sendStatus(200); +}); Empathy.meta = { name: "Empathy",