1 const express = require("express");
2 const Game = require("./game.js");
4 const MAX_PROMPT_ITEMS = 20;
6 /* This time parameter specifies a time period in which a phase will
7 * not be considered idle in any circumstance. That is, this should be
8 * a reasonable time in which any "active" player should have at least
9 * started interacting with the current phase.
11 * Specified in seconds
13 const PHASE_MINIMUM_TIME = 30;
15 /* This parameter gives the amount of time that the game will wait to
16 * see activity from pending players. If this amount of time passes
17 * with no activity from any of them, the server will emit an "idle"
18 * event which will let clients issue a vote to end the current phase.
20 * Specified in seconds
22 const PHASE_IDLE_TIMEOUT = 30;
24 class Empathy extends Game {
31 players_answering: new Set(),
32 answering_idle: false,
33 end_answers: new Set(),
36 players_judging: new Set(),
38 end_judging: new Set(),
42 this.answering_idle_timer = 0;
43 this.answering_start_time_ms = 0;
44 this.judging_idle_timer = 0;
45 this.judging_start_time_ms = 0;
46 this.next_prompt_id = 1;
47 this.equivalencies = {};
52 /* Before closing out the current round, we accumulate the score
53 * for each player into their runnning total. */
54 for (let score of this.state.scores.scores) {
55 const player = this.players.find(p => p.name === score.player);
57 player.score += score.score;
59 player.score = score.score;
61 /* And broadcast that new score out. */
62 this.broadcast_event('player-update', player.info_json());
65 /* Now that we're done with the active prompt, we remove it from
66 * the list of prompts and also remove any prompts that received
67 * no votes. This keeps the list of prompts clean.
69 const active_id = this.state.active_prompt.id;
71 this.state.prompts.filter(
72 p => p.id !== active_id && p.votes.length > 0
75 this.state.active_prompt = null;
76 this.state.players_answered = [];
77 this.state.players_answering = new Set();
78 this.state.answering_idle = false;
79 this.state.end_answers = new Set();
80 this.state.ambiguities = null;
81 this.state.players_judged = [];
82 this.state.players_judging = new Set();
83 this.state.judging_idle = false;
84 this.state.end_judging = new Set();
85 this.state.scores = null;
88 if (this.answering_idle_timer) {
89 clearTimeout(this.answering_idle_timer);
91 this.answering_idle_timer = 0;
92 this.answering_start_time_ms = 0;
93 if (this.judging_idle_timer) {
94 clearTimeout(this.judging_idle_timer);
96 this.judging_idle_timer = 0;
97 this.judging_start_time_ms = 0;
98 this.equivalencies = {};
100 this.broadcast_event_object('game-state', this.state);
103 add_prompt(items, prompt_string) {
104 if (items > MAX_PROMPT_ITEMS)
107 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
110 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
111 this.next_prompt_id++;
113 this.state.prompts.push(prompt);
115 this.broadcast_event_object('prompt', prompt);
123 /* Returns true if vote toggled, false for player or prompt not found */
124 toggle_vote(prompt_id, session_id) {
125 const player = this.players_by_session[session_id];
127 const prompt = this.state.prompts.find(p => p.id === prompt_id);
128 if (! prompt || ! player)
131 prompt.toggle_vote(player.name);
133 this.broadcast_event_object('prompt', prompt);
138 /* Returns true on success, false for prompt not found. */
140 const prompt = this.state.prompts.find(p => p.id === prompt_id);
144 /* Ignore any start request that comes in while a prompt is
145 * already being played. */
146 if (this.state.active_prompt)
149 this.state.active_prompt = prompt;
151 this.broadcast_event_object('start', prompt);
156 receive_answer(prompt_id, session_id, answers) {
157 const player = this.players_by_session[session_id];
159 return { valid: false, message: "Player not found" };
161 const prompt = this.state.prompts.find(p => p.id === prompt_id);
163 return { valid: false, message: "Prompt not found" };
165 if (prompt !== this.state.active_prompt)
166 return { valid: false, message: "Prompt no longer active" };
168 /* Save the complete answers for our own use later. */
174 /* Update state (to be sent out to any future clients) */
175 this.state.players_answering.delete(player.name);
176 this.state.players_answered.push(player.name);
178 /* And notify all players that this player has answered. */
179 this.broadcast_event_object('player-answered', player.name);
181 /* If no players are left in the answering list then we don't need
182 * to wait for the answering_idle_timer to fire, because a person
183 * who isn't there obviously can't be typing. So we can broadcast
184 * the idle event right away. Note that we do this only if the
185 * answering phase has been going for a while to avoid the case of
186 * the first player being super fast and emptying the
187 * players_answering list before anyone else even got in.
189 if (this.state.players_answering.size === 0 &&
190 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
192 this.broadcast_event_object('answering-idle', true);
195 return { valid: true };
198 receive_answering(prompt_id, session_id) {
199 const player = this.players_by_session[session_id];
201 return { valid: false, message: "Player not found" };
203 const prompt = this.state.prompts.find(p => p.id === prompt_id);
205 return { valid: false, message: "Prompt not found" };
207 if (prompt !== this.state.active_prompt)
208 return { valid: false, message: "Prompt no longer active" };
210 if (this.answering_idle_timer) {
211 clearTimeout(this.answering_idle_timer);
212 this.ansering_idle_timer = 0;
214 if (! this.state.answering_idle) {
215 this.answering_idle_timer = setTimeout(() => {
216 this.state.answering_idle = true;
217 this.broadcast_event_object('answering-idle', true);
218 }, PHASE_IDLE_TIMEOUT * 1000);
221 if (this.answering_start_time_ms === 0)
222 this.answering_start_time_ms = Date.now();
224 /* Notify all players that this player is actively answering. */
225 this.state.players_answering.add(player.name);
226 this.broadcast_event_object('player-answering', player.name);
228 return { valid: true };
231 /* Returns true if vote toggled, false for player or prompt not found */
232 toggle_end_answers(prompt_id, session_id) {
233 const player = this.players_by_session[session_id];
235 const prompt = this.state.prompts.find(p => p.id === prompt_id);
236 if (! prompt || ! player)
239 if (this.state.end_answers.has(player.name)) {
240 this.state.end_answers.delete(player.name);
241 this.broadcast_event_object('unvote-end-answers', player.name);
243 this.state.end_answers.add(player.name);
244 this.broadcast_event_object('vote-end-answers', player.name);
253 for (let a of this.answers) {
254 for (let word of a.answers) {
255 const key = this.canonize(word);
256 word_map[key] = word;
260 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
261 return a.toLowerCase().localeCompare(b.toLowerCase());
264 if (this.judging_start_time_ms === 0) {
265 this.judging_start_time_ms = Date.now();
268 this.broadcast_event_object('ambiguities', this.state.ambiguities);
271 reset_judging_timeout() {
272 if (this.judging_idle_timer) {
273 clearTimeout(this.judging_idle_timer);
274 this.judging_idle_timer = 0;
276 if (! this.state.judging_idle) {
277 this.judging_idle_timer = setTimeout(() => {
278 this.state.judging_idle = true;
279 this.broadcast_event_object('judging-idle', true);
280 }, PHASE_IDLE_TIMEOUT * 1000);
284 receive_judged(prompt_id, session_id, word_groups) {
285 const player = this.players_by_session[session_id];
287 return { valid: false, message: "Player not found" };
289 const prompt = this.state.prompts.find(p => p.id === prompt_id);
291 return { valid: false, message: "Prompt not found" };
293 if (prompt !== this.state.active_prompt)
294 return { valid: false, message: "Prompt no longer active" };
296 this.reset_judging_timeout();
298 /* Each player submits some number of groups of answers that
299 * should be considered equivalent. The server expands that into
300 * the set of pair-wise equivalencies that are expressed. The
301 * reason for that is so that the server can determine which
302 * pair-wise equivalencies have majority support.
304 for (let group of word_groups) {
306 for (let i = 0; i < group.length - 1; i++) {
307 for (let j = i + 1; j < group.length; j++) {
308 let eq = [group[i], group[j]];
310 /* Put the two words into a reliable order so that we don't
311 * miss a pair of equivalent equivalencies just because they
312 * happen to be in the opposite order. */
313 if (eq[0].localeCompare(eq[1]) > 0) {
314 eq = [group[j], group[i]];
317 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
319 const exist = this.equivalencies[key];
323 this.equivalencies[key] = {
333 /* Update state (to be sent out to any future clients) */
334 this.state.players_judging.delete(player.name);
335 this.state.players_judged.push(player.name);
337 /* And notify all players that this player has judged. */
338 this.broadcast_event_object('player-judged', player.name);
340 /* If no players are left in the judging list then we don't need
341 * to wait for the judging_idle_timer to fire, because a person
342 * who isn't there obviously can't be judging. So we can broadcast
343 * the idle event right away. Note that we do this only if the
344 * judging phase has been going for a while to avoid the case of
345 * the first player being super fast and emptying the
346 * players_judging list before anyone else even got in.
348 if (this.state.players_judging.size === 0 &&
349 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
351 this.broadcast_event_object('judging-idle', true);
354 return { valid: true };
357 receive_judging(prompt_id, session_id) {
359 const player = this.players_by_session[session_id];
361 return { valid: false, message: "Player not found" };
363 const prompt = this.state.prompts.find(p => p.id === prompt_id);
365 return { valid: false, message: "Prompt not found" };
367 if (prompt !== this.state.active_prompt)
368 return { valid: false, message: "Prompt no longer active" };
370 this.reset_judging_timeout();
372 /* Notify all players that this player is actively judging. */
373 this.state.players_judging.add(player.name);
374 this.broadcast_event_object('player-judging', player.name);
376 return { valid: true };
379 /* Returns true if vote toggled, false for player or prompt not found */
380 toggle_end_judging(prompt_id, session_id) {
381 const player = this.players_by_session[session_id];
383 const prompt = this.state.prompts.find(p => p.id === prompt_id);
384 if (! prompt || ! player)
387 if (this.state.end_judging.has(player.name)) {
388 this.state.end_judging.delete(player.name);
389 this.broadcast_event_object('unvote-end-judging', player.name);
391 this.state.end_judging.add(player.name);
392 this.broadcast_event_object('vote-end-judging', player.name);
399 return word.trim().toLowerCase();
403 const word_submitters = {};
405 /* Perform a (non-strict) majority ruling on equivalencies,
406 * dropping all that didn't get enough votes. */
407 const quorum = Math.floor((this.players.length + 1)/2);
408 const agreed_equivalencies = Object.values(this.equivalencies).filter(
409 eq => eq.count >= quorum);
411 /* And with that agreed set of equivalencies, construct the full
413 const word_maps = {};
415 for (let e of agreed_equivalencies) {
416 const word0_canon = this.canonize(e.words[0]);
417 const word1_canon = this.canonize(e.words[1]);
418 let group = word_maps[word0_canon];
420 group = word_maps[word1_canon];
422 group = { words: [], players: new Set()};
424 if (! word_maps[word0_canon]) {
425 word_maps[word0_canon] = group;
426 group.words.push(e.words[0]);
429 if (! word_maps[word1_canon]) {
430 word_maps[word1_canon] = group;
431 group.words.push(e.words[1]);
435 /* Now go through answers from each player and add the player
436 * to the set corresponding to each word group. */
437 for (let a of this.answers) {
438 for (let word of a.answers) {
439 const word_canon = this.canonize(word);
440 /* If there's no group yet, this is a singleton word. */
441 if (word_maps[word_canon]) {
442 word_maps[word_canon].players.add(a.player);
444 const group = { words: [word], players: new Set() };
445 group.players.add(a.player);
446 word_maps[word_canon] = group;
451 /* Now that we've assigned the players to these word maps, we now
452 * want to collapse the groups down to a single array of
455 * The difference between "word_maps" and "word_groups" is that
456 * the former has a property for every word that maps to a group,
457 * (so if you iterate over the keys you will see the same group
458 * multiple times). In contrast, iterating over"word_groups" will
459 * have you visit each group only once. */
460 const word_groups = Object.entries(word_maps).filter(
461 entry => entry[0] === this.canonize(entry[1].words[0]))
462 .map(entry => entry[1]);
464 /* Now, go through each word group and assign the scores out to
465 * the corresponding players.
467 * Note: We do this by going through the word groups, (as opposed
468 * to the list of words from the players again), specifically to
469 * avoid giving a player points for a wrod group twice (in the
470 * case where a player submits two different words that the group
471 * ends up judging as equivalent).
473 this.players.forEach(p => p.round_score = 0);
474 for (let group of word_groups) {
475 group.players.forEach(p => p.round_score += group.players.size);
478 const scores = this.players.map(p => {
485 scores.sort((a,b) => {
486 return b.score - a.score;
489 /* Put the word groups into a form the client can consume.
491 const words_submitted = word_groups.map(
494 word: group.words.join('/'),
495 players: Array.from(group.players).map(p => p.name)
500 words_submitted.sort((a,b) => {
501 return b.players.length - a.players.length;
504 /* Put this round's scores into the game state object so it will
505 * be sent to any new clients that join. */
506 this.state.scores = {
508 words: words_submitted
511 /* And broadcast the scores to all connected clients. */
512 this.broadcast_event_object('scores', this.state.scores);
516 Empathy.router = express.Router();
517 const router = Empathy.router;
520 constructor(id, items, prompt) {
523 this.prompt = prompt;
527 toggle_vote(player_name) {
528 if (this.votes.find(v => v === player_name))
529 this.votes = this.votes.filter(v => v !== player_name);
531 this.votes.push(player_name);
535 router.post('/prompts', (request, response) => {
536 const game = request.game;
538 const result = game.add_prompt(request.body.items, request.body.prompt);
540 response.json(result);
543 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
544 const game = request.game;
545 const prompt_id = parseInt(request.params.prompt_id, 10);
547 if (game.toggle_vote(prompt_id, request.session.id))
550 response.sendStatus(404);
553 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
554 const game = request.game;
555 const prompt_id = parseInt(request.params.prompt_id, 10);
557 if (game.start(prompt_id))
560 response.sendStatus(404);
563 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
564 const game = request.game;
565 const prompt_id = parseInt(request.params.prompt_id, 10);
567 const result = game.receive_answer(prompt_id,
569 request.body.answers);
570 response.json(result);
572 /* If every registered player has answered, then there's no need to
573 * wait for anything else. */
574 if (game.state.players_answered.length >= game.players.length)
575 game.perform_judging();
578 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
579 const game = request.game;
580 const prompt_id = parseInt(request.params.prompt_id, 10);
582 const result = game.receive_answering(prompt_id,
584 response.json(result);
587 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
588 const game = request.game;
589 const prompt_id = parseInt(request.params.prompt_id, 10);
591 if (game.toggle_end_answers(prompt_id, request.session.id))
594 response.sendStatus(404);
596 /* The majority rule here includes all players that have answered as
597 * well as all that have started typing. */
598 const players_involved = (game.state.players_answered.length +
599 game.state.players_answering.size);
601 if (game.state.end_answers.size > players_involved / 2)
602 game.perform_judging();
605 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
606 const game = request.game;
607 const prompt_id = parseInt(request.params.prompt_id, 10);
609 const result = game.receive_judged(prompt_id,
611 request.body.word_groups);
612 response.json(result);
614 /* If every registered player has judged, then there's no need to
615 * wait for anything else. */
616 if (game.state.players_judged.length >= game.players.length)
617 game.compute_scores();
620 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
621 const game = request.game;
622 const prompt_id = parseInt(request.params.prompt_id, 10);
624 const result = game.receive_judging(prompt_id,
626 response.json(result);
629 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
630 const game = request.game;
631 const prompt_id = parseInt(request.params.prompt_id, 10);
633 if (game.toggle_end_judging(prompt_id, request.session.id))
636 response.sendStatus(404);
638 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
639 game.compute_scores();
642 router.post('/reset', (request, response) => {
643 const game = request.game;
651 identifier: "empathy",
654 exports.Game = Empathy;