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 * no votes. This keeps the list of prompts clean.
81 const active_id = this.state.active_prompt.id;
83 this.state.prompts.filter(
84 p => p.id !== active_id && p.votes.length > 0
87 this.state.active_prompt = null;
88 this.state.players_answered = [];
89 this.state.players_answering = new Set();
90 this.state.answering_idle = false;
91 this.state.end_answers = new Set();
92 this.state.ambiguities = null;
93 this.state.players_judged = [];
94 this.state.players_judging = new Set();
95 this.state.judging_idle = false;
96 this.state.end_judging = new Set();
97 this.state.scores = null;
98 this.state.new_game_votes = new Set();
101 if (this.answering_idle_timer) {
102 clearTimeout(this.answering_idle_timer);
104 this.answering_idle_timer = 0;
105 this.answering_start_time_ms = 0;
106 if (this.judging_idle_timer) {
107 clearTimeout(this.judging_idle_timer);
109 this.judging_idle_timer = 0;
110 this.judging_start_time_ms = 0;
111 this.equivalencies = {};
113 this.broadcast_event('game-state', this.game_state_json());
116 add_prompt(items, prompt_string) {
117 if (items > MAX_PROMPT_ITEMS)
120 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
123 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
124 this.next_prompt_id++;
126 this.state.prompts.push(prompt);
128 this.broadcast_event_object('prompt', prompt);
136 /* Returns true if vote toggled, false for player or prompt not found */
137 toggle_vote(prompt_id, session_id) {
138 const player = this.players_by_session[session_id];
140 const prompt = this.state.prompts.find(p => p.id === prompt_id);
141 if (! prompt || ! player)
144 prompt.toggle_vote(player.name);
146 this.broadcast_event_object('prompt', prompt);
151 toggle_vote_against(prompt_id, session_id) {
152 const player = this.players_by_session[session_id];
154 const prompt = this.state.prompts.find(p => p.id === prompt_id);
155 if (! prompt || ! player)
158 prompt.toggle_vote_against(player.name);
160 this.broadcast_event_object('prompt', prompt);
165 /* Returns true on success, false for prompt not found. */
167 const prompt = this.state.prompts.find(p => p.id === prompt_id);
171 /* Ignore any start request that comes in while a prompt is
172 * already being played. */
173 if (this.state.active_prompt)
176 this.state.active_prompt = prompt;
178 this.broadcast_event_object('start', prompt);
183 receive_answer(prompt_id, session_id, answers) {
184 const player = this.players_by_session[session_id];
186 return { valid: false, message: "Player not found" };
188 const prompt = this.state.prompts.find(p => p.id === prompt_id);
190 return { valid: false, message: "Prompt not found" };
192 if (prompt !== this.state.active_prompt)
193 return { valid: false, message: "Prompt no longer active" };
195 /* Save the complete answers for our own use later. */
201 /* Update state (to be sent out to any future clients) */
202 this.state.players_answering.delete(player.name);
203 this.state.players_answered.push(player.name);
205 /* And notify all players that this player has answered. */
206 this.broadcast_event_object('player-answered', player.name);
208 /* If no players are left in the answering list then we don't need
209 * to wait for the answering_idle_timer to fire, because a person
210 * who isn't there obviously can't be typing. So we can broadcast
211 * the idle event right away. Note that we do this only if the
212 * answering phase has been going for a while to avoid the case of
213 * the first player being super fast and emptying the
214 * players_answering list before anyone else even got in.
216 if (this.state.players_answering.size === 0 &&
217 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
219 this.broadcast_event_object('answering-idle', true);
222 return { valid: true };
225 receive_answering(prompt_id, session_id) {
226 const player = this.players_by_session[session_id];
228 return { valid: false, message: "Player not found" };
230 const prompt = this.state.prompts.find(p => p.id === prompt_id);
232 return { valid: false, message: "Prompt not found" };
234 if (prompt !== this.state.active_prompt)
235 return { valid: false, message: "Prompt no longer active" };
237 if (this.answering_idle_timer) {
238 clearTimeout(this.answering_idle_timer);
239 this.ansering_idle_timer = 0;
241 if (! this.state.answering_idle) {
242 this.answering_idle_timer = setTimeout(() => {
243 this.state.answering_idle = true;
244 this.broadcast_event_object('answering-idle', true);
245 }, PHASE_IDLE_TIMEOUT * 1000);
248 if (this.answering_start_time_ms === 0)
249 this.answering_start_time_ms = Date.now();
251 /* Notify all players that this player is actively answering. */
252 this.state.players_answering.add(player.name);
253 this.broadcast_event_object('player-answering', player.name);
255 return { valid: true };
258 /* Returns true if vote toggled, false for player or prompt not found */
259 toggle_end_answers(prompt_id, session_id) {
260 const player = this.players_by_session[session_id];
262 const prompt = this.state.prompts.find(p => p.id === prompt_id);
263 if (! prompt || ! player)
266 if (this.state.end_answers.has(player.name)) {
267 this.state.end_answers.delete(player.name);
268 this.broadcast_event_object('unvote-end-answers', player.name);
270 this.state.end_answers.add(player.name);
271 this.broadcast_event_object('vote-end-answers', player.name);
280 for (let a of this.answers) {
281 for (let word of a.answers) {
282 const key = this.canonize(word);
283 word_map[key] = word;
287 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
288 return a.toLowerCase().localeCompare(b.toLowerCase());
291 if (this.judging_start_time_ms === 0) {
292 this.judging_start_time_ms = Date.now();
295 this.broadcast_event_object('ambiguities', this.state.ambiguities);
297 /* Notify all players of every player that is judging. */
298 for (let player_name of this.state.players_answered) {
299 this.state.players_judging.add(player_name);
300 this.broadcast_event_object('player-judging', player_name);
304 reset_judging_timeout() {
305 if (this.judging_idle_timer) {
306 clearTimeout(this.judging_idle_timer);
307 this.judging_idle_timer = 0;
309 if (! this.state.judging_idle) {
310 this.judging_idle_timer = setTimeout(() => {
311 this.state.judging_idle = true;
312 this.broadcast_event_object('judging-idle', true);
313 }, PHASE_IDLE_TIMEOUT * 1000);
317 receive_judged(prompt_id, session_id, word_groups) {
318 const player = this.players_by_session[session_id];
320 return { valid: false, message: "Player not found" };
322 const prompt = this.state.prompts.find(p => p.id === prompt_id);
324 return { valid: false, message: "Prompt not found" };
326 if (prompt !== this.state.active_prompt)
327 return { valid: false, message: "Prompt no longer active" };
329 this.reset_judging_timeout();
331 /* Each player submits some number of groups of answers that
332 * should be considered equivalent. The server expands that into
333 * the set of pair-wise equivalencies that are expressed. The
334 * reason for that is so that the server can determine which
335 * pair-wise equivalencies have majority support.
337 for (let group of word_groups) {
339 for (let i = 0; i < group.length - 1; i++) {
340 for (let j = i + 1; j < group.length; j++) {
341 let eq = [group[i], group[j]];
343 /* Put the two words into a reliable order so that we don't
344 * miss a pair of equivalent equivalencies just because they
345 * happen to be in the opposite order. */
346 if (eq[0].localeCompare(eq[1]) > 0) {
347 eq = [group[j], group[i]];
350 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
352 const exist = this.equivalencies[key];
356 this.equivalencies[key] = {
366 /* Update state (to be sent out to any future clients) */
367 this.state.players_judging.delete(player.name);
368 this.state.players_judged.push(player.name);
370 /* And notify all players that this player has judged. */
371 this.broadcast_event_object('player-judged', player.name);
373 /* If no players are left in the judging list then we don't need
374 * to wait for the judging_idle_timer to fire, because a person
375 * who isn't there obviously can't be judging. So we can broadcast
376 * the idle event right away. Note that we do this only if the
377 * judging phase has been going for a while to avoid the case of
378 * the first player being super fast and emptying the
379 * players_judging list before anyone else even got in.
381 if (this.state.players_judging.size === 0 &&
382 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
384 this.broadcast_event_object('judging-idle', true);
387 return { valid: true };
390 receive_judging(prompt_id, session_id) {
392 const player = this.players_by_session[session_id];
394 return { valid: false, message: "Player not found" };
396 const prompt = this.state.prompts.find(p => p.id === prompt_id);
398 return { valid: false, message: "Prompt not found" };
400 if (prompt !== this.state.active_prompt)
401 return { valid: false, message: "Prompt no longer active" };
403 this.reset_judging_timeout();
405 /* Notify all players that this player is actively judging. */
406 this.state.players_judging.add(player.name);
407 this.broadcast_event_object('player-judging', player.name);
409 return { valid: true };
412 /* Returns true if vote toggled, false for player or prompt not found */
413 toggle_end_judging(prompt_id, session_id) {
414 const player = this.players_by_session[session_id];
416 const prompt = this.state.prompts.find(p => p.id === prompt_id);
417 if (! prompt || ! player)
420 if (this.state.end_judging.has(player.name)) {
421 this.state.end_judging.delete(player.name);
422 this.broadcast_event_object('unvote-end-judging', player.name);
424 this.state.end_judging.add(player.name);
425 this.broadcast_event_object('vote-end-judging', player.name);
431 /* Returns true if vote toggled, false for player or prompt not found */
432 toggle_new_game(prompt_id, session_id) {
433 const player = this.players_by_session[session_id];
435 const prompt = this.state.prompts.find(p => p.id === prompt_id);
436 if (! prompt || ! player)
439 if (this.state.new_game_votes.has(player.name)) {
440 this.state.new_game_votes.delete(player.name);
441 this.broadcast_event_object('unvote-new-game', player.name);
443 this.state.new_game_votes.add(player.name);
444 this.broadcast_event_object('vote-new-game', player.name);
451 return word.trim().toLowerCase();
455 const word_submitters = {};
457 /* Perform a (non-strict) majority ruling on equivalencies,
458 * dropping all that didn't get enough votes. */
459 const quorum = Math.floor((this.state.players_judged.length + 1)/2);
460 const agreed_equivalencies = Object.values(this.equivalencies).filter(
461 eq => eq.count >= quorum);
463 /* And with that agreed set of equivalencies, construct the full
465 const word_maps = {};
467 for (let e of agreed_equivalencies) {
468 const word0_canon = this.canonize(e.words[0]);
469 const word1_canon = this.canonize(e.words[1]);
470 let group = word_maps[word0_canon];
472 group = word_maps[word1_canon];
474 group = { words: [], players: new Set()};
476 if (! word_maps[word0_canon]) {
477 word_maps[word0_canon] = group;
478 group.words.push(e.words[0]);
481 if (! word_maps[word1_canon]) {
482 word_maps[word1_canon] = group;
483 group.words.push(e.words[1]);
487 /* Now go through answers from each player and add the player
488 * to the set corresponding to each word group. */
489 for (let a of this.answers) {
490 for (let word of a.answers) {
491 const word_canon = this.canonize(word);
492 /* If there's no group yet, this is a singleton word. */
493 if (word_maps[word_canon]) {
494 word_maps[word_canon].players.add(a.player);
496 const group = { words: [word], players: new Set() };
497 group.players.add(a.player);
498 word_maps[word_canon] = group;
503 /* Now that we've assigned the players to these word maps, we now
504 * want to collapse the groups down to a single array of
507 * The difference between "word_maps" and "word_groups" is that
508 * the former has a property for every word that maps to a group,
509 * (so if you iterate over the keys you will see the same group
510 * multiple times). In contrast, iterating over"word_groups" will
511 * have you visit each group only once. */
512 const word_groups = Object.entries(word_maps).filter(
513 entry => entry[0] === this.canonize(entry[1].words[0]))
514 .map(entry => entry[1]);
516 /* Now, go through each word group and assign the scores out to
517 * the corresponding players.
519 * Note: We do this by going through the word groups, (as opposed
520 * to the list of words from the players again), specifically to
521 * avoid giving a player points for a wrod group twice (in the
522 * case where a player submits two different words that the group
523 * ends up judging as equivalent).
525 this.players.forEach(p => p.round_score = 0);
526 for (let group of word_groups) {
527 group.players.forEach(p => p.round_score += group.players.size);
530 const scores = this.players.filter(p => p.active).map(p => {
537 scores.sort((a,b) => {
538 return b.score - a.score;
541 /* After sorting individual players by score, group players
542 * together who have the same score. */
543 const reducer = (list, next) => {
544 if (list.length && list[list.length-1].score == next.score)
545 list[list.length-1].players.push(next.player);
547 list.push({players: [next.player], score: next.score});
551 const grouped_scores = scores.reduce(reducer, []);
553 /* Put the word groups into a form the client can consume.
555 const words_submitted = word_groups.map(
558 word: group.words.join('/'),
559 players: Array.from(group.players).map(p => p.name)
564 words_submitted.sort((a,b) => {
565 return b.players.length - a.players.length;
568 /* Put this round's scores into the game state object so it will
569 * be sent to any new clients that join. */
570 this.state.scores = {
571 scores: grouped_scores,
572 words: words_submitted
575 /* And broadcast the scores to all connected clients. */
576 this.broadcast_event_object('scores', this.state.scores);
580 Empathy.router = express.Router();
581 const router = Empathy.router;
584 constructor(id, items, prompt) {
587 this.prompt = prompt;
589 this.votes_against = [];
592 toggle_vote(player_name) {
593 if (this.votes.find(v => v === player_name))
594 this.votes = this.votes.filter(v => v !== player_name);
596 this.votes.push(player_name);
599 toggle_vote_against(player_name) {
600 if (this.votes_against.find(v => v === player_name))
601 this.votes_against = this.votes_against.filter(v => v !== player_name);
603 this.votes_against.push(player_name);
607 router.post('/prompts', (request, response) => {
608 const game = request.game;
610 const result = game.add_prompt(request.body.items, request.body.prompt);
612 response.json(result);
615 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
616 const game = request.game;
617 const prompt_id = parseInt(request.params.prompt_id, 10);
619 if (game.toggle_vote(prompt_id, request.session.id))
622 response.sendStatus(404);
625 router.post('/vote_against/:prompt_id([0-9]+)', (request, response) => {
626 const game = request.game;
627 const prompt_id = parseInt(request.params.prompt_id, 10);
629 if (game.toggle_vote_against(prompt_id, request.session.id))
632 response.sendStatus(404);
635 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
636 const game = request.game;
637 const prompt_id = parseInt(request.params.prompt_id, 10);
639 if (game.start(prompt_id))
642 response.sendStatus(404);
645 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
646 const game = request.game;
647 const prompt_id = parseInt(request.params.prompt_id, 10);
649 const result = game.receive_answer(prompt_id,
651 request.body.answers);
652 response.json(result);
654 /* If every registered player has answered, then there's no need to
655 * wait for anything else. */
656 if (game.state.players_answered.length >= game.active_players)
657 game.perform_judging();
660 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
661 const game = request.game;
662 const prompt_id = parseInt(request.params.prompt_id, 10);
664 const result = game.receive_answering(prompt_id,
666 response.json(result);
669 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
670 const game = request.game;
671 const prompt_id = parseInt(request.params.prompt_id, 10);
673 if (game.toggle_end_answers(prompt_id, request.session.id))
676 response.sendStatus(404);
678 /* The majority rule here includes all players that have answered as
679 * well as all that have started typing. */
680 const players_involved = (game.state.players_answered.length +
681 game.state.players_answering.size);
683 if (game.state.end_answers.size > players_involved / 2)
684 game.perform_judging();
687 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
688 const game = request.game;
689 const prompt_id = parseInt(request.params.prompt_id, 10);
691 const result = game.receive_judged(prompt_id,
693 request.body.word_groups);
694 response.json(result);
696 /* If every player who answered has also judged, then there's no
697 * need to wait for anything else. */
698 const judged_set = new Set(game.state.players_judged);
699 if ([...game.state.players_answered].filter(x => !judged_set.has(x)).length === 0)
700 game.compute_scores();
703 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
704 const game = request.game;
705 const prompt_id = parseInt(request.params.prompt_id, 10);
707 const result = game.receive_judging(prompt_id,
709 response.json(result);
712 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
713 const game = request.game;
714 const prompt_id = parseInt(request.params.prompt_id, 10);
716 if (game.toggle_end_judging(prompt_id, request.session.id))
719 response.sendStatus(404);
721 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
722 game.compute_scores();
725 router.post('/new-game/:prompt_id([0-9]+)', (request, response) => {
726 const game = request.game;
727 const prompt_id = parseInt(request.params.prompt_id, 10);
729 if (game.toggle_new_game(prompt_id, request.session.id))
732 response.sendStatus(404);
734 if (game.state.new_game_votes.size > (game.state.players_answered.length / 2))
738 router.post('/reset', (request, response) => {
739 const game = request.game;
747 identifier: "empathy",
750 exports.Game = Empathy;