]> git.cworth.org Git - empires-server/blob - empathy.js
Fix buggy regular expression
[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     /* Ignore any start request that comes in while a prompt is
47      * already being played. */
48     if (this.state.active_prompt)
49       return false;
50
51     this.state.active_prompt = prompt;
52
53     this.broadcast_event_object('start', prompt);
54
55     return true;
56   }
57 }
58
59 Empathy.router = express.Router();
60 const router = Empathy.router;
61
62 class Prompt {
63   constructor(id, items, prompt) {
64     this.id = id;
65     this.items = items;
66     this.prompt = prompt;
67     this.votes = [];
68   }
69
70   toggle_vote(player_name) {
71     if (this.votes.find(v => v === player_name))
72       this.votes = this.votes.filter(v => v !== player_name);
73     else
74       this.votes.push(player_name);
75   }
76 }
77
78 router.post('/prompts', (request, response) => {
79   const game = request.game;
80
81   game.add_prompt(request.body.items, request.body.prompt);
82 });
83
84 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
85   const game = request.game;
86   const prompt_id = parseInt(request.params.prompt_id, 10);
87
88   if (game.toggle_vote(prompt_id, request.session.id))
89     response.sendStatus(200);
90   else
91     response.sendStatus(404);
92 });
93
94 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
95   const game = request.game;
96   const prompt_id = parseInt(request.params.prompt_id, 10);
97
98   if (game.start(prompt_id))
99     response.sendStatus(200);
100   else
101     response.sendStatus(404);
102 });
103
104 Empathy.meta = {
105   name: "Empathy",
106   identifier: "empathy",
107 };
108
109 exports.Game = Empathy;