]> git.cworth.org Git - empires-server/commitdiff
Empathy: Add routes to receive prompts and votes on prompts
authorCarl Worth <cworth@cworth.org>
Mon, 8 Jun 2020 13:59:43 +0000 (06:59 -0700)
committerCarl Worth <cworth@cworth.org>
Mon, 8 Jun 2020 13:59:43 +0000 (06:59 -0700)
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.

empathy.js

index 12a743e87aad296cace8420b8fb6f28cfd8dfe7e..f2a6859ad3998cfa0d310c1e8c7e68f3818ef151 100644 (file)
@@ -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",