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(),
40 new_game_votes: new Set()
43 this.answering_idle_timer = 0;
44 this.answering_start_time_ms = 0;
45 this.judging_idle_timer = 0;
46 this.judging_start_time_ms = 0;
47 this.next_prompt_id = 1;
48 this.equivalencies = {};
53 /* Before closing out the current round, we accumulate into each
54 * player's overall score the results from the current round.
56 * Note: Rather than applying the actual points from each round
57 * into the player's score, we instead accumulate up the number of
58 * players that they bested in each round. This ensures that each
59 * round receives an equal weight in the overall scoring. */
60 let bested = this.state.scores.scores.reduce(
61 (total, score) => total + score.players.length, 0);
62 for (let i = 0; i < this.state.scores.scores.length; i++) {
63 const score = this.state.scores.scores[i];
64 bested -= score.players.length;
65 for (let player_name of score.players) {
66 const player = this.players.find(p => p.name === player_name);
68 player.score += bested;
70 player.score = bested;
72 /* And broadcast that new score out. */
73 this.broadcast_event('player-update', player.info_json());
77 /* Now that we're done with the active prompt, we remove it from
78 * the list of prompts and also remove any prompts that received
79 * more negative votes than positive. This keeps the list of
82 const active_id = this.state.active_prompt.id;
84 this.state.prompts.filter(
85 p => p.id !== active_id && p.votes.length >= p.votes_against.length
88 this.state.active_prompt = null;
89 this.state.players_answered = [];
90 this.state.players_answering = new Set();
91 this.state.answering_idle = false;
92 this.state.end_answers = new Set();
93 this.state.ambiguities = null;
94 this.state.players_judged = [];
95 this.state.players_judging = new Set();
96 this.state.judging_idle = false;
97 this.state.end_judging = new Set();
98 this.state.scores = null;
99 this.state.new_game_votes = new Set();
102 if (this.answering_idle_timer) {
103 clearTimeout(this.answering_idle_timer);
105 this.answering_idle_timer = 0;
106 this.answering_start_time_ms = 0;
107 if (this.judging_idle_timer) {
108 clearTimeout(this.judging_idle_timer);
110 this.judging_idle_timer = 0;
111 this.judging_start_time_ms = 0;
112 this.equivalencies = {};
114 this.broadcast_event('game-state', this.game_state_json());
117 add_prompt(items, prompt_string) {
118 if (items > MAX_PROMPT_ITEMS)
121 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
124 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
125 this.next_prompt_id++;
127 this.state.prompts.push(prompt);
129 this.broadcast_event_object('prompt', prompt);
137 /* Returns true if vote toggled, false for player or prompt not found */
138 toggle_vote(prompt_id, session_id) {
139 const player = this.players_by_session[session_id];
141 const prompt = this.state.prompts.find(p => p.id === prompt_id);
142 if (! prompt || ! player)
145 prompt.toggle_vote(player.name);
147 this.broadcast_event_object('prompt', prompt);
152 toggle_vote_against(prompt_id, session_id) {
153 const player = this.players_by_session[session_id];
155 const prompt = this.state.prompts.find(p => p.id === prompt_id);
156 if (! prompt || ! player)
159 prompt.toggle_vote_against(player.name);
161 this.broadcast_event_object('prompt', prompt);
166 /* Returns true on success, false for prompt not found. */
168 const prompt = this.state.prompts.find(p => p.id === prompt_id);
172 /* Ignore any start request that comes in while a prompt is
173 * already being played. */
174 if (this.state.active_prompt)
177 this.state.active_prompt = prompt;
179 this.broadcast_event_object('start', prompt);
184 receive_answer(prompt_id, session_id, answers) {
185 const player = this.players_by_session[session_id];
187 return { valid: false, message: "Player not found" };
189 const prompt = this.state.prompts.find(p => p.id === prompt_id);
191 return { valid: false, message: "Prompt not found" };
193 if (prompt !== this.state.active_prompt)
194 return { valid: false, message: "Prompt no longer active" };
196 /* Save the complete answers for our own use later. */
202 /* Update state (to be sent out to any future clients) */
203 this.state.players_answering.delete(player.name);
204 this.state.players_answered.push(player.name);
206 /* And notify all players that this player has answered. */
207 this.broadcast_event_object('player-answered', player.name);
209 /* If no players are left in the answering list then we don't need
210 * to wait for the answering_idle_timer to fire, because a person
211 * who isn't there obviously can't be typing. So we can broadcast
212 * the idle event right away. Note that we do this only if the
213 * answering phase has been going for a while to avoid the case of
214 * the first player being super fast and emptying the
215 * players_answering list before anyone else even got in.
217 if (this.state.players_answering.size === 0 &&
218 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
220 this.broadcast_event_object('answering-idle', true);
223 return { valid: true };
226 receive_answering(prompt_id, session_id) {
227 const player = this.players_by_session[session_id];
229 return { valid: false, message: "Player not found" };
231 const prompt = this.state.prompts.find(p => p.id === prompt_id);
233 return { valid: false, message: "Prompt not found" };
235 if (prompt !== this.state.active_prompt)
236 return { valid: false, message: "Prompt no longer active" };
238 if (this.answering_idle_timer) {
239 clearTimeout(this.answering_idle_timer);
240 this.ansering_idle_timer = 0;
242 if (! this.state.answering_idle) {
243 this.answering_idle_timer = setTimeout(() => {
244 this.state.answering_idle = true;
245 this.broadcast_event_object('answering-idle', true);
246 }, PHASE_IDLE_TIMEOUT * 1000);
249 if (this.answering_start_time_ms === 0)
250 this.answering_start_time_ms = Date.now();
252 /* Notify all players that this player is actively answering. */
253 this.state.players_answering.add(player.name);
254 this.broadcast_event_object('player-answering', player.name);
256 return { valid: true };
259 /* Returns true if vote toggled, false for player or prompt not found */
260 toggle_end_answers(prompt_id, session_id) {
261 const player = this.players_by_session[session_id];
263 const prompt = this.state.prompts.find(p => p.id === prompt_id);
264 if (! prompt || ! player)
267 if (this.state.end_answers.has(player.name)) {
268 this.state.end_answers.delete(player.name);
269 this.broadcast_event_object('unvote-end-answers', player.name);
271 this.state.end_answers.add(player.name);
272 this.broadcast_event_object('vote-end-answers', player.name);
281 for (let a of this.answers) {
282 for (let word of a.answers) {
283 const key = this.canonize(word);
284 word_map[key] = word;
288 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
289 return a.toLowerCase().localeCompare(b.toLowerCase());
292 if (this.judging_start_time_ms === 0) {
293 this.judging_start_time_ms = Date.now();
296 this.broadcast_event_object('ambiguities', this.state.ambiguities);
298 /* Notify all players of every player that is judging. */
299 for (let player_name of this.state.players_answered) {
300 this.state.players_judging.add(player_name);
301 this.broadcast_event_object('player-judging', player_name);
305 reset_judging_timeout() {
306 if (this.judging_idle_timer) {
307 clearTimeout(this.judging_idle_timer);
308 this.judging_idle_timer = 0;
310 if (! this.state.judging_idle) {
311 this.judging_idle_timer = setTimeout(() => {
312 this.state.judging_idle = true;
313 this.broadcast_event_object('judging-idle', true);
314 }, PHASE_IDLE_TIMEOUT * 1000);
318 receive_judged(prompt_id, session_id, word_groups) {
319 const player = this.players_by_session[session_id];
321 return { valid: false, message: "Player not found" };
323 const prompt = this.state.prompts.find(p => p.id === prompt_id);
325 return { valid: false, message: "Prompt not found" };
327 if (prompt !== this.state.active_prompt)
328 return { valid: false, message: "Prompt no longer active" };
330 this.reset_judging_timeout();
332 /* Each player submits some number of groups of answers that
333 * should be considered equivalent. The server expands that into
334 * the set of pair-wise equivalencies that are expressed. The
335 * reason for that is so that the server can determine which
336 * pair-wise equivalencies have majority support.
338 for (let group of word_groups) {
340 for (let i = 0; i < group.length - 1; i++) {
341 for (let j = i + 1; j < group.length; j++) {
342 let eq = [group[i], group[j]];
344 /* Put the two words into a reliable order so that we don't
345 * miss a pair of equivalent equivalencies just because they
346 * happen to be in the opposite order. */
347 if (eq[0].localeCompare(eq[1]) > 0) {
348 eq = [group[j], group[i]];
351 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
353 const exist = this.equivalencies[key];
357 this.equivalencies[key] = {
367 /* Update state (to be sent out to any future clients) */
368 this.state.players_judging.delete(player.name);
369 this.state.players_judged.push(player.name);
371 /* And notify all players that this player has judged. */
372 this.broadcast_event_object('player-judged', player.name);
374 /* If no players are left in the judging list then we don't need
375 * to wait for the judging_idle_timer to fire, because a person
376 * who isn't there obviously can't be judging. So we can broadcast
377 * the idle event right away. Note that we do this only if the
378 * judging phase has been going for a while to avoid the case of
379 * the first player being super fast and emptying the
380 * players_judging list before anyone else even got in.
382 if (this.state.players_judging.size === 0 &&
383 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
385 this.broadcast_event_object('judging-idle', true);
388 return { valid: true };
391 receive_judging(prompt_id, session_id) {
393 const player = this.players_by_session[session_id];
395 return { valid: false, message: "Player not found" };
397 const prompt = this.state.prompts.find(p => p.id === prompt_id);
399 return { valid: false, message: "Prompt not found" };
401 if (prompt !== this.state.active_prompt)
402 return { valid: false, message: "Prompt no longer active" };
404 this.reset_judging_timeout();
406 /* Notify all players that this player is actively judging. */
407 this.state.players_judging.add(player.name);
408 this.broadcast_event_object('player-judging', player.name);
410 return { valid: true };
413 /* Returns true if vote toggled, false for player or prompt not found */
414 toggle_end_judging(prompt_id, session_id) {
415 const player = this.players_by_session[session_id];
417 const prompt = this.state.prompts.find(p => p.id === prompt_id);
418 if (! prompt || ! player)
421 if (this.state.end_judging.has(player.name)) {
422 this.state.end_judging.delete(player.name);
423 this.broadcast_event_object('unvote-end-judging', player.name);
425 this.state.end_judging.add(player.name);
426 this.broadcast_event_object('vote-end-judging', player.name);
432 /* Returns true if vote toggled, false for player or prompt not found */
433 toggle_new_game(prompt_id, session_id) {
434 const player = this.players_by_session[session_id];
436 const prompt = this.state.prompts.find(p => p.id === prompt_id);
437 if (! prompt || ! player)
440 if (this.state.new_game_votes.has(player.name)) {
441 this.state.new_game_votes.delete(player.name);
442 this.broadcast_event_object('unvote-new-game', player.name);
444 this.state.new_game_votes.add(player.name);
445 this.broadcast_event_object('vote-new-game', player.name);
452 return word.trim().toLowerCase();
456 const word_submitters = {};
458 /* Perform a (non-strict) majority ruling on equivalencies,
459 * dropping all that didn't get enough votes. */
460 const quorum = Math.floor((this.state.players_judged.length + 1)/2);
461 const agreed_equivalencies = Object.values(this.equivalencies).filter(
462 eq => eq.count >= quorum);
464 /* And with that agreed set of equivalencies, construct the full
466 const word_maps = {};
468 for (let e of agreed_equivalencies) {
469 const word0_canon = this.canonize(e.words[0]);
470 const word1_canon = this.canonize(e.words[1]);
471 let group = word_maps[word0_canon];
473 group = word_maps[word1_canon];
475 group = { words: [], players: new Set()};
477 if (! word_maps[word0_canon]) {
478 word_maps[word0_canon] = group;
479 group.words.push(e.words[0]);
482 if (! word_maps[word1_canon]) {
483 word_maps[word1_canon] = group;
484 group.words.push(e.words[1]);
488 /* Now go through answers from each player and add the player
489 * to the set corresponding to each word group. */
490 for (let a of this.answers) {
491 for (let word of a.answers) {
492 const word_canon = this.canonize(word);
493 /* If there's no group yet, this is a singleton word. */
494 if (word_maps[word_canon]) {
495 word_maps[word_canon].players.add(a.player);
497 const group = { words: [word], players: new Set() };
498 group.players.add(a.player);
499 word_maps[word_canon] = group;
504 /* Now that we've assigned the players to these word maps, we now
505 * want to collapse the groups down to a single array of
508 * The difference between "word_maps" and "word_groups" is that
509 * the former has a property for every word that maps to a group,
510 * (so if you iterate over the keys you will see the same group
511 * multiple times). In contrast, iterating over"word_groups" will
512 * have you visit each group only once. */
513 const word_groups = Object.entries(word_maps).filter(
514 entry => entry[0] === this.canonize(entry[1].words[0]))
515 .map(entry => entry[1]);
517 /* Now, go through each word group and assign the scores out to
518 * the corresponding players.
520 * Note: We do this by going through the word groups, (as opposed
521 * to the list of words from the players again), specifically to
522 * avoid giving a player points for a wrod group twice (in the
523 * case where a player submits two different words that the group
524 * ends up judging as equivalent).
526 this.players.forEach(p => p.round_score = 0);
527 for (let group of word_groups) {
528 group.players.forEach(p => p.round_score += group.players.size);
531 const scores = this.players.filter(p => p.active).map(p => {
538 scores.sort((a,b) => {
539 return b.score - a.score;
542 /* After sorting individual players by score, group players
543 * together who have the same score. */
544 const reducer = (list, next) => {
545 if (list.length && list[list.length-1].score == next.score)
546 list[list.length-1].players.push(next.player);
548 list.push({players: [next.player], score: next.score});
552 const grouped_scores = scores.reduce(reducer, []);
554 /* Put the word groups into a form the client can consume.
556 const words_submitted = word_groups.map(
559 word: group.words.join('/'),
560 players: Array.from(group.players).map(p => p.name)
565 words_submitted.sort((a,b) => {
566 return b.players.length - a.players.length;
569 /* Put this round's scores into the game state object so it will
570 * be sent to any new clients that join. */
571 this.state.scores = {
572 scores: grouped_scores,
573 words: words_submitted
576 /* And broadcast the scores to all connected clients. */
577 this.broadcast_event_object('scores', this.state.scores);
581 Empathy.router = express.Router();
582 const router = Empathy.router;
585 constructor(id, items, prompt) {
588 this.prompt = prompt;
590 this.votes_against = [];
593 toggle_vote(player_name) {
594 if (this.votes.find(v => v === player_name))
595 this.votes = this.votes.filter(v => v !== player_name);
597 this.votes.push(player_name);
600 toggle_vote_against(player_name) {
601 if (this.votes_against.find(v => v === player_name))
602 this.votes_against = this.votes_against.filter(v => v !== player_name);
604 this.votes_against.push(player_name);
608 router.post('/prompts', (request, response) => {
609 const game = request.game;
611 const result = game.add_prompt(request.body.items, request.body.prompt);
613 response.json(result);
616 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
617 const game = request.game;
618 const prompt_id = parseInt(request.params.prompt_id, 10);
620 if (game.toggle_vote(prompt_id, request.session.id))
623 response.sendStatus(404);
626 router.post('/vote_against/:prompt_id([0-9]+)', (request, response) => {
627 const game = request.game;
628 const prompt_id = parseInt(request.params.prompt_id, 10);
630 if (game.toggle_vote_against(prompt_id, request.session.id))
633 response.sendStatus(404);
636 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
637 const game = request.game;
638 const prompt_id = parseInt(request.params.prompt_id, 10);
640 if (game.start(prompt_id))
643 response.sendStatus(404);
646 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
647 const game = request.game;
648 const prompt_id = parseInt(request.params.prompt_id, 10);
650 const result = game.receive_answer(prompt_id,
652 request.body.answers);
653 response.json(result);
655 /* If every registered player has answered, then there's no need to
656 * wait for anything else. */
657 if (game.state.players_answered.length >= game.active_players)
658 game.perform_judging();
661 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
662 const game = request.game;
663 const prompt_id = parseInt(request.params.prompt_id, 10);
665 const result = game.receive_answering(prompt_id,
667 response.json(result);
670 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
671 const game = request.game;
672 const prompt_id = parseInt(request.params.prompt_id, 10);
674 if (game.toggle_end_answers(prompt_id, request.session.id))
677 response.sendStatus(404);
679 /* The majority rule here includes all players that have answered as
680 * well as all that have started typing. */
681 const players_involved = (game.state.players_answered.length +
682 game.state.players_answering.size);
684 if (game.state.end_answers.size > players_involved / 2)
685 game.perform_judging();
688 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
689 const game = request.game;
690 const prompt_id = parseInt(request.params.prompt_id, 10);
692 const result = game.receive_judged(prompt_id,
694 request.body.word_groups);
695 response.json(result);
697 /* If every player who answered has also judged, then there's no
698 * need to wait for anything else. */
699 const judged_set = new Set(game.state.players_judged);
700 if ([...game.state.players_answered].filter(x => !judged_set.has(x)).length === 0)
701 game.compute_scores();
704 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
705 const game = request.game;
706 const prompt_id = parseInt(request.params.prompt_id, 10);
708 const result = game.receive_judging(prompt_id,
710 response.json(result);
713 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
714 const game = request.game;
715 const prompt_id = parseInt(request.params.prompt_id, 10);
717 if (game.toggle_end_judging(prompt_id, request.session.id))
720 response.sendStatus(404);
722 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
723 game.compute_scores();
726 router.post('/new-game/:prompt_id([0-9]+)', (request, response) => {
727 const game = request.game;
728 const prompt_id = parseInt(request.params.prompt_id, 10);
730 if (game.toggle_new_game(prompt_id, request.session.id))
733 response.sendStatus(404);
735 if (game.state.new_game_votes.size > (game.state.players_answered.length / 2))
739 router.post('/reset', (request, response) => {
740 const game = request.game;
748 identifier: "empathy",
751 exports.Game = Empathy;