1 const express = require("express");
2 const Game = require("./game.js");
4 const MAX_PROMPT_ITEMS = 20;
6 class Empathy extends Game {
13 players_answering: new Set(),
14 answering_idle: false,
15 end_answers: new Set(),
18 players_judging: new Set(),
19 end_judging: new Set(),
23 this.answering_idle_timer = 0;
24 this.answering_start_time_ms = 0;
25 this.next_prompt_id = 1;
26 this.equivalencies = {};
31 /* Before closing out the current round, we accumulate that score
32 * for each player into their runnning total. */
33 for (let score of this.state.scores.scores) {
34 const player = this.players.find(p => p.name === score.player);
36 player.score += score.score;
38 player.score = score.score;
40 /* And broadcast that new score out. */
41 this.broadcast_event('player-update', player.info_json());
44 /* Now that we're done with the active prompt, we remove it from
45 * the list of prompts and also remove any prompts that received
46 * no votes. This keeps the list of prompts clean.
48 const active_id = this.state.active_prompt.id;
50 this.state.prompts.filter(
51 p => p.id !== active_id && p.votes.length > 0
54 this.state.active_prompt = null;
55 this.state.players_answered = [];
56 this.state.players_answering = new Set();
57 this.state.answering_idle = false;
58 this.state.end_answers = new Set();
59 this.state.ambiguities = null;
60 this.state.players_judged = [];
61 this.state.players_judging = new Set();
62 this.state.end_judging = new Set();
63 this.state.scores = null;
66 if (this.answering_idle_timer) {
67 clearTimeout(this.answering_idle_timer);
69 this.answering_idle_timer = 0;
70 this.answering_start_time_ms = 0;
71 this.equivalencies = {};
73 this.broadcast_event_object('game-state', this.state);
76 add_prompt(items, prompt_string) {
77 if (items > MAX_PROMPT_ITEMS)
80 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
83 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
84 this.next_prompt_id++;
86 this.state.prompts.push(prompt);
88 this.broadcast_event_object('prompt', prompt);
96 /* Returns true if vote toggled, false for player or prompt not found */
97 toggle_vote(prompt_id, session_id) {
98 const player = this.players_by_session[session_id];
100 const prompt = this.state.prompts.find(p => p.id === prompt_id);
101 if (! prompt || ! player)
104 prompt.toggle_vote(player.name);
106 this.broadcast_event_object('prompt', prompt);
111 /* Returns true on success, false for prompt not found. */
113 const prompt = this.state.prompts.find(p => p.id === prompt_id);
117 /* Ignore any start request that comes in while a prompt is
118 * already being played. */
119 if (this.state.active_prompt)
122 this.state.active_prompt = prompt;
124 this.broadcast_event_object('start', prompt);
129 receive_answer(prompt_id, session_id, answers) {
130 const player = this.players_by_session[session_id];
132 return { valid: false, message: "Player not found" };
134 const prompt = this.state.prompts.find(p => p.id === prompt_id);
136 return { valid: false, message: "Prompt not found" };
138 if (prompt !== this.state.active_prompt)
139 return { valid: false, message: "Prompt no longer active" };
141 /* Save the complete answers for our own use later. */
147 /* Update state (to be sent out to any future clients) */
148 this.state.players_answering.delete(player.name);
149 this.state.players_answered.push(player.name);
151 /* And notify all players that this player has answered. */
152 this.broadcast_event_object('player-answered', player.name);
154 /* If no players are left in the answering list then we don't need
155 * to wait for the answering_idle_timer to fire, because a person
156 * who isn't there obviously can't be typing. So we can broadcast
157 * the idle event right away. Note that we do this only if the
158 * answering phase has been going for a while to avoid the case of
159 * the first player being super fast and emptying the
160 * players_answering list before anyone else even got in.
162 if (this.state.players_answering.size === 0 &&
163 ((Date.now() - this.answering_start_time_ms) / 1000) > 30)
165 this.broadcast_event_object('answering-idle', true);
168 return { valid: true };
171 receive_answering(prompt_id, session_id) {
172 const player = this.players_by_session[session_id];
174 return { valid: false, message: "Player not found" };
176 const prompt = this.state.prompts.find(p => p.id === prompt_id);
178 return { valid: false, message: "Prompt not found" };
180 if (prompt !== this.state.active_prompt)
181 return { valid: false, message: "Prompt no longer active" };
183 if (this.answering_idle_timer) {
184 clearTimeout(this.answering_idle_timer);
186 if (! this.state.answering_idle) {
187 this.answering_idle_timer = setTimeout(() => {
188 this.state_answering_idle = true;
189 this.broadcast_event_object('answering-idle', true);
193 if (this.answering_start_time_ms === 0)
194 this.answering_start_time_ms = Date.now();
196 /* Notify all players that this player is actively answering. */
197 this.state.players_answering.add(player.name);
198 this.broadcast_event_object('player-answering', player.name);
200 return { valid: true };
203 /* Returns true if vote toggled, false for player or prompt not found */
204 toggle_end_answers(prompt_id, session_id) {
205 const player = this.players_by_session[session_id];
207 const prompt = this.state.prompts.find(p => p.id === prompt_id);
208 if (! prompt || ! player)
211 if (this.state.end_answers.has(player.name)) {
212 this.state.end_answers.delete(player.name);
213 this.broadcast_event_object('unvote-end-answers', player.name);
215 this.state.end_answers.add(player.name);
216 this.broadcast_event_object('vote-end-answers', player.name);
225 for (let a of this.answers) {
226 for (let word of a.answers) {
227 const key = this.canonize(word);
228 word_map[key] = word;
232 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
233 return a.toLowerCase().localeCompare(b.toLowerCase());
236 this.broadcast_event_object('ambiguities', this.state.ambiguities);
239 receive_judged(prompt_id, session_id, word_groups) {
240 const player = this.players_by_session[session_id];
242 return { valid: false, message: "Player not found" };
244 const prompt = this.state.prompts.find(p => p.id === prompt_id);
246 return { valid: false, message: "Prompt not found" };
248 if (prompt !== this.state.active_prompt)
249 return { valid: false, message: "Prompt no longer active" };
251 /* Each player submits some number of groups of answers that
252 * should be considered equivalent. The server expands that into
253 * the set of pair-wise equivalencies that are expressed. The
254 * reason for that is so that the server can determine which
255 * pair-wise equivalencies have majority support.
257 for (let group of word_groups) {
259 for (let i = 0; i < group.length - 1; i++) {
260 for (let j = i + 1; j < group.length; j++) {
261 let eq = [group[i], group[j]];
263 /* Put the two words into a reliable order so that we don't
264 * miss a pair of equivalent equivalencies just because they
265 * happen to be in the opposite order. */
266 if (eq[0].localeCompare(eq[1]) > 0) {
267 eq = [group[j], group[i]];
270 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
272 const exist = this.equivalencies[key];
276 this.equivalencies[key] = {
286 /* Update state (to be sent out to any future clients) */
287 this.state.players_judging.delete(player.name);
288 this.state.players_judged.push(player.name);
290 /* And notify all players this this player has judged. */
291 this.broadcast_event_object('player-judged', player.name);
293 return { valid: true };
296 receive_judging(prompt_id, session_id) {
297 const player = this.players_by_session[session_id];
299 return { valid: false, message: "Player not found" };
301 const prompt = this.state.prompts.find(p => p.id === prompt_id);
303 return { valid: false, message: "Prompt not found" };
305 if (prompt !== this.state.active_prompt)
306 return { valid: false, message: "Prompt no longer active" };
308 /* Notify all players this this player is actively judging. */
309 this.state.players_judging.add(player.name);
310 this.broadcast_event_object('player-judging', player.name);
312 return { valid: true };
315 /* Returns true if vote toggled, false for player or prompt not found */
316 toggle_end_judging(prompt_id, session_id) {
317 const player = this.players_by_session[session_id];
319 const prompt = this.state.prompts.find(p => p.id === prompt_id);
320 if (! prompt || ! player)
323 if (this.state.end_judging.has(player.name)) {
324 this.state.end_judging.delete(player.name);
325 this.broadcast_event_object('unvote-end-judging', player.name);
327 this.state.end_judging.add(player.name);
328 this.broadcast_event_object('vote-end-judging', player.name);
335 return word.trim().toLowerCase();
339 const word_submitters = {};
341 /* Perform a (non-strict) majority ruling on equivalencies,
342 * dropping all that didn't get enough votes. */
343 const quorum = Math.floor((this.players.length + 1)/2);
344 const agreed_equivalencies = Object.values(this.equivalencies).filter(
345 eq => eq.count >= quorum);
347 /* And with that agreed set of equivalencies, construct the full
349 const word_maps = {};
351 for (let e of agreed_equivalencies) {
352 const word0_canon = this.canonize(e.words[0]);
353 const word1_canon = this.canonize(e.words[1]);
354 let group = word_maps[word0_canon];
356 group = word_maps[word1_canon];
358 group = { words: [], players: new Set()};
360 if (! word_maps[word0_canon]) {
361 word_maps[word0_canon] = group;
362 group.words.push(e.words[0]);
365 if (! word_maps[word1_canon]) {
366 word_maps[word1_canon] = group;
367 group.words.push(e.words[1]);
371 /* Now go through answers from each player and add the player
372 * to the set corresponding to each word group. */
373 for (let a of this.answers) {
374 for (let word of a.answers) {
375 const word_canon = this.canonize(word);
376 /* If there's no group yet, this is a singleton word. */
377 if (word_maps[word_canon]) {
378 word_maps[word_canon].players.add(a.player);
380 const group = { words: [word], players: new Set() };
381 group.players.add(a.player);
382 word_maps[word_canon] = group;
387 /* Now that we've assigned the players to these word maps, we now
388 * want to collapse the groups down to a single array of
391 * The difference between "word_maps" and "word_groups" is that
392 * the former has a property for every word that maps to a group,
393 * (so if you iterate over the keys you will see the same group
394 * multiple times). In contrast, iterating over"word_groups" will
395 * have you visit each group only once. */
396 const word_groups = Object.entries(word_maps).filter(
397 entry => entry[0] === this.canonize(entry[1].words[0]))
398 .map(entry => entry[1]);
400 /* Now, go through each word group and assign the scores out to
401 * the corresponding players.
403 * Note: We do this by going through the word groups, (as opposed
404 * to the list of words from the players again), specifically to
405 * avoid giving a player points for a wrod group twice (in the
406 * case where a player submits two different words that the group
407 * ends up judging as equivalent).
409 this.players.forEach(p => p.round_score = 0);
410 for (let group of word_groups) {
411 group.players.forEach(p => p.round_score += group.players.size);
414 const scores = this.players.map(p => {
421 scores.sort((a,b) => {
422 return b.score - a.score;
425 /* Put the word groups into a form the client can consume.
427 const words_submitted = word_groups.map(
430 word: group.words.join('/'),
431 players: Array.from(group.players).map(p => p.name)
436 words_submitted.sort((a,b) => {
437 return b.players.length - a.players.length;
440 /* Put this round's scores into the game state object so it will
441 * be sent to any new clients that join. */
442 this.state.scores = {
444 words: words_submitted
447 /* And broadcast the scores to all connected clients. */
448 this.broadcast_event_object('scores', this.state.scores);
452 Empathy.router = express.Router();
453 const router = Empathy.router;
456 constructor(id, items, prompt) {
459 this.prompt = prompt;
463 toggle_vote(player_name) {
464 if (this.votes.find(v => v === player_name))
465 this.votes = this.votes.filter(v => v !== player_name);
467 this.votes.push(player_name);
471 router.post('/prompts', (request, response) => {
472 const game = request.game;
474 const result = game.add_prompt(request.body.items, request.body.prompt);
476 response.json(result);
479 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
480 const game = request.game;
481 const prompt_id = parseInt(request.params.prompt_id, 10);
483 if (game.toggle_vote(prompt_id, request.session.id))
486 response.sendStatus(404);
489 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
490 const game = request.game;
491 const prompt_id = parseInt(request.params.prompt_id, 10);
493 if (game.start(prompt_id))
496 response.sendStatus(404);
499 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
500 const game = request.game;
501 const prompt_id = parseInt(request.params.prompt_id, 10);
503 const result = game.receive_answer(prompt_id,
505 request.body.answers);
506 response.json(result);
508 /* If every registered player has answered, then there's no need to
509 * wait for anything else. */
510 if (game.state.players_answered.length >= game.players.length)
511 game.perform_judging();
514 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
515 const game = request.game;
516 const prompt_id = parseInt(request.params.prompt_id, 10);
518 const result = game.receive_answering(prompt_id,
520 response.json(result);
523 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
524 const game = request.game;
525 const prompt_id = parseInt(request.params.prompt_id, 10);
527 if (game.toggle_end_answers(prompt_id, request.session.id))
530 response.sendStatus(404);
532 /* The majority rule here includes all players that have answered as
533 * well as all that have started typing. */
534 const players_involved = (game.state.players_answered.length +
535 game.state.players_answering.size);
537 if (game.state.end_answers.size > players_involved / 2)
538 game.perform_judging();
541 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
542 const game = request.game;
543 const prompt_id = parseInt(request.params.prompt_id, 10);
545 const result = game.receive_judged(prompt_id,
547 request.body.word_groups);
548 response.json(result);
550 /* If every registered player has judged, then there's no need to
551 * wait for anything else. */
552 if (game.state.players_judged.length >= game.players.length)
553 game.compute_scores();
556 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
557 const game = request.game;
558 const prompt_id = parseInt(request.params.prompt_id, 10);
560 const result = game.receive_judging(prompt_id,
562 response.json(result);
565 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
566 const game = request.game;
567 const prompt_id = parseInt(request.params.prompt_id, 10);
569 if (game.toggle_end_judging(prompt_id, request.session.id))
572 response.sendStatus(404);
574 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
575 game.compute_scores();
578 router.post('/reset', (request, response) => {
579 const game = request.game;
587 identifier: "empathy",
590 exports.Game = Empathy;