]> git.cworth.org Git - empires-server/blob - empathy.js
empathy: Better separation of concerns between routes and game class
[empires-server] / empathy.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 class Empathy extends Game {
5   constructor(id) {
6     super(id);
7     this.state = {
8       prompts: []
9     };
10     this.next_prompt_id = 1;
11   }
12
13   add_prompt(items, prompt_string) {
14     const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
15     this.next_prompt_id++;
16
17     this.state.prompts.push(prompt);
18
19     this.broadcast_event_object('prompt', prompt);
20
21     return prompt;
22   }
23
24   /* Returns true if vote toggled, false for player or prompt not found */
25   toggle_vote(prompt_id, session_id) {
26     const player = this.players_by_session[session_id];
27
28     const prompt = this.state.prompts.find(p => p.id === prompt_id);
29     if (! prompt || ! player)
30       return false;
31
32     prompt.toggle_vote(player.name);
33
34     this.broadcast_event_object('prompt', prompt);
35
36     return true;
37   }
38 }
39
40 Empathy.router = express.Router();
41 const router = Empathy.router;
42
43 class Prompt {
44   constructor(id, items, prompt) {
45     this.id = id;
46     this.items = items;
47     this.prompt = prompt;
48     this.votes = [];
49   }
50
51   toggle_vote(player_name) {
52     if (this.votes.find(v => v === player_name))
53       this.votes = this.votes.filter(v => v !== player_name);
54     else
55       this.votes.push(player_name);
56   }
57 }
58
59 router.post('/prompts', (request, response) => {
60   const game = request.game;
61
62   game.add_prompt(request.body.items, request.body.prompt);
63 });
64
65 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
66   const game = request.game;
67   const prompt_id = parseInt(request.params.prompt_id, 10);
68
69   if (game.toggle_vote(prompt_id, request.session.id))
70     response.sendStatus(200);
71   else
72     response.sendStatus(404);
73 });
74
75 Empathy.meta = {
76   name: "Empathy",
77   identifier: "empathy",
78 };
79
80 exports.Game = Empathy;