1 const express = require("express");
2 const Game = require("./game.js");
4 class Empathy extends Game {
12 this.next_prompt_id = 1;
15 add_prompt(items, prompt_string) {
16 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
17 this.next_prompt_id++;
19 this.state.prompts.push(prompt);
21 this.broadcast_event_object('prompt', prompt);
26 /* Returns true if vote toggled, false for player or prompt not found */
27 toggle_vote(prompt_id, session_id) {
28 const player = this.players_by_session[session_id];
30 const prompt = this.state.prompts.find(p => p.id === prompt_id);
31 if (! prompt || ! player)
34 prompt.toggle_vote(player.name);
36 this.broadcast_event_object('prompt', prompt);
41 /* Returns true on success, false for prompt not found. */
43 const prompt = this.state.prompts.find(p => p.id === prompt_id);
47 /* Ignore any start request that comes in while a prompt is
48 * already being played. */
49 if (this.state.active_prompt)
52 this.state.active_prompt = prompt;
54 this.broadcast_event_object('start', prompt);
59 receive_answer(prompt_id, session_id, answers) {
60 const player = this.players_by_session[session_id];
62 return { valid: false, message: "Player not found" };
64 const prompt = this.state.prompts.find(p => p.id === prompt_id);
66 return { valid: false, message: "Prompt not found" };
68 if (prompt !== this.state.active_prompt)
69 return { valid: false, message: "Prompt no longer active" };
71 /* Save the complete answers for our own use later. */
77 return { valid: true };
81 Empathy.router = express.Router();
82 const router = Empathy.router;
85 constructor(id, items, prompt) {
92 toggle_vote(player_name) {
93 if (this.votes.find(v => v === player_name))
94 this.votes = this.votes.filter(v => v !== player_name);
96 this.votes.push(player_name);
100 router.post('/prompts', (request, response) => {
101 const game = request.game;
103 game.add_prompt(request.body.items, request.body.prompt);
106 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
107 const game = request.game;
108 const prompt_id = parseInt(request.params.prompt_id, 10);
110 if (game.toggle_vote(prompt_id, request.session.id))
111 response.sendStatus(200);
113 response.sendStatus(404);
116 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
117 const game = request.game;
118 const prompt_id = parseInt(request.params.prompt_id, 10);
120 if (game.start(prompt_id))
121 response.sendStatus(200);
123 response.sendStatus(404);
126 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
127 const game = request.game;
128 const prompt_id = parseInt(request.params.prompt_id, 10);
130 const result = game.receive_answer(prompt_id,
132 request.body.answers);
133 response.json(result);
138 identifier: "empathy",
141 exports.Game = Empathy;