]> git.cworth.org Git - empires-server/blob - empathy.js
Empathy: Add support for starting the actual game
[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       active_prompt: null
10     };
11     this.next_prompt_id = 1;
12   }
13
14   add_prompt(items, prompt_string) {
15     const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
16     this.next_prompt_id++;
17
18     this.state.prompts.push(prompt);
19
20     this.broadcast_event_object('prompt', prompt);
21
22     return prompt;
23   }
24
25   /* Returns true if vote toggled, false for player or prompt not found */
26   toggle_vote(prompt_id, session_id) {
27     const player = this.players_by_session[session_id];
28
29     const prompt = this.state.prompts.find(p => p.id === prompt_id);
30     if (! prompt || ! player)
31       return false;
32
33     prompt.toggle_vote(player.name);
34
35     this.broadcast_event_object('prompt', prompt);
36
37     return true;
38   }
39
40   /* Returns true on success, false for prompt not found. */
41   start(prompt_id) {
42     const prompt = this.state.prompts.find(p => p.id === prompt_id);
43     if (! prompt)
44       return false;
45
46     this.state.active_prompt = prompt;
47
48     this.broadcast_event_object('start', prompt);
49
50     return true;
51   }
52 }
53
54 Empathy.router = express.Router();
55 const router = Empathy.router;
56
57 class Prompt {
58   constructor(id, items, prompt) {
59     this.id = id;
60     this.items = items;
61     this.prompt = prompt;
62     this.votes = [];
63   }
64
65   toggle_vote(player_name) {
66     if (this.votes.find(v => v === player_name))
67       this.votes = this.votes.filter(v => v !== player_name);
68     else
69       this.votes.push(player_name);
70   }
71 }
72
73 router.post('/prompts', (request, response) => {
74   const game = request.game;
75
76   game.add_prompt(request.body.items, request.body.prompt);
77 });
78
79 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
80   const game = request.game;
81   const prompt_id = parseInt(request.params.prompt_id, 10);
82
83   if (game.toggle_vote(prompt_id, request.session.id))
84     response.sendStatus(200);
85   else
86     response.sendStatus(404);
87 });
88
89 router.post('/start/:prompt_id([[0-9]+)', (request, response) => {
90   const game = request.game;
91   const prompt_id = parseInt(request.params.prompt_id, 10);
92
93   if (game.start(prompt_id))
94     response.sendStatus(200);
95   else
96     response.sendStatus(404);
97 });
98
99 Empathy.meta = {
100   name: "Empathy",
101   identifier: "empathy",
102 };
103
104 exports.Game = Empathy;