1 const express = require("express");
2 const Game = require("./game.js");
4 class Empathy extends Game {
13 this.next_prompt_id = 1;
16 add_prompt(items, prompt_string) {
17 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
18 this.next_prompt_id++;
20 this.state.prompts.push(prompt);
22 this.broadcast_event_object('prompt', prompt);
27 /* Returns true if vote toggled, false for player or prompt not found */
28 toggle_vote(prompt_id, session_id) {
29 const player = this.players_by_session[session_id];
31 const prompt = this.state.prompts.find(p => p.id === prompt_id);
32 if (! prompt || ! player)
35 prompt.toggle_vote(player.name);
37 this.broadcast_event_object('prompt', prompt);
42 /* Returns true on success, false for prompt not found. */
44 const prompt = this.state.prompts.find(p => p.id === prompt_id);
48 /* Ignore any start request that comes in while a prompt is
49 * already being played. */
50 if (this.state.active_prompt)
53 this.state.active_prompt = prompt;
55 this.broadcast_event_object('start', prompt);
60 receive_answer(prompt_id, session_id, answers) {
61 const player = this.players_by_session[session_id];
63 return { valid: false, message: "Player not found" };
65 const prompt = this.state.prompts.find(p => p.id === prompt_id);
67 return { valid: false, message: "Prompt not found" };
69 if (prompt !== this.state.active_prompt)
70 return { valid: false, message: "Prompt no longer active" };
72 /* Save the complete answers for our own use later. */
78 /* And notify players how many players have answered. */
79 this.state.players_answered++;
81 this.broadcast_event_object('answered', this.state.players_answered);
83 return { valid: true };
87 Empathy.router = express.Router();
88 const router = Empathy.router;
91 constructor(id, items, prompt) {
98 toggle_vote(player_name) {
99 if (this.votes.find(v => v === player_name))
100 this.votes = this.votes.filter(v => v !== player_name);
102 this.votes.push(player_name);
106 router.post('/prompts', (request, response) => {
107 const game = request.game;
109 game.add_prompt(request.body.items, request.body.prompt);
112 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
113 const game = request.game;
114 const prompt_id = parseInt(request.params.prompt_id, 10);
116 if (game.toggle_vote(prompt_id, request.session.id))
117 response.sendStatus(200);
119 response.sendStatus(404);
122 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
123 const game = request.game;
124 const prompt_id = parseInt(request.params.prompt_id, 10);
126 if (game.start(prompt_id))
127 response.sendStatus(200);
129 response.sendStatus(404);
132 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
133 const game = request.game;
134 const prompt_id = parseInt(request.params.prompt_id, 10);
136 const result = game.receive_answer(prompt_id,
138 request.body.answers);
139 response.json(result);
144 identifier: "empathy",
147 exports.Game = Empathy;