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 = 15;
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 = {};
54 /* Before closing out the current round, we accumulate into each
55 * player's overall score the results from the current round.
57 * Note: Rather than applying the actual points from each round
58 * into the player's score, we instead accumulate up the number of
59 * players that they bested in each round. This ensures that each
60 * round receives an equal weight in the overall scoring. */
61 let bested = this.state.scores.scores.reduce(
62 (total, score) => total + score.players.length, 0);
63 for (let i = 0; i < this.state.scores.scores.length; i++) {
64 const score = this.state.scores.scores[i];
65 bested -= score.players.length;
66 for (let player_name of score.players) {
67 const player = this.players.find(p => p.name === player_name);
69 player.score += bested;
71 player.score = bested;
73 /* And broadcast that new score out. */
74 this.broadcast_event('player-update', player.info_json());
78 /* Now that we're done with the active prompt, we remove it from
79 * the list of prompts and also remove any prompts that received
80 * more negative votes than positive. This keeps the list of
83 const active_id = this.state.active_prompt.id;
85 this.state.prompts.filter(
86 p => p.id !== active_id && p.votes.length >= p.votes_against.length
89 this.state.active_prompt = null;
90 this.state.players_answered = [];
91 this.state.players_answering = new Set();
92 this.state.answering_idle = false;
93 this.state.end_answers = new Set();
94 this.state.ambiguities = null;
95 this.state.players_judged = [];
96 this.state.players_judging = new Set();
97 this.state.judging_idle = false;
98 this.state.end_judging = new Set();
99 this.state.scores = null;
100 this.state.new_game_votes = new Set();
103 if (this.answering_idle_timer) {
104 clearTimeout(this.answering_idle_timer);
106 this.answering_idle_timer = 0;
107 this.answering_start_time_ms = 0;
108 if (this.judging_idle_timer) {
109 clearTimeout(this.judging_idle_timer);
111 this.judging_idle_timer = 0;
112 this.judging_start_time_ms = 0;
113 this.equivalencies = {};
116 this.broadcast_event('game-state', this.game_state_json());
119 add_prompt(items, prompt_string) {
120 if (items > MAX_PROMPT_ITEMS) {
123 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
130 message: "Category must require at least one item"
134 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
135 this.next_prompt_id++;
137 this.state.prompts.push(prompt);
139 this.broadcast_event_object('prompt', prompt);
147 /* Returns true if vote toggled, false for player or prompt not found */
148 toggle_vote(prompt_id, session_id) {
149 const player = this.players_by_session[session_id];
151 const prompt = this.state.prompts.find(p => p.id === prompt_id);
152 if (! prompt || ! player)
155 prompt.toggle_vote(player.name);
157 this.broadcast_event_object('prompt', prompt);
162 toggle_vote_against(prompt_id, session_id) {
163 const player = this.players_by_session[session_id];
165 const prompt = this.state.prompts.find(p => p.id === prompt_id);
166 if (! prompt || ! player)
169 prompt.toggle_vote_against(player.name);
171 this.broadcast_event_object('prompt', prompt);
176 /* Returns true on success, false for prompt not found. */
178 const prompt = this.state.prompts.find(p => p.id === prompt_id);
182 /* Ignore any start request that comes in while a prompt is
183 * already being played. */
184 if (this.state.active_prompt)
187 this.state.active_prompt = prompt;
189 this.broadcast_event_object('start', prompt);
194 receive_answer(prompt_id, session_id, answers) {
195 const player = this.players_by_session[session_id];
197 return { valid: false, message: "Player not found" };
199 const prompt = this.state.prompts.find(p => p.id === prompt_id);
201 return { valid: false, message: "Prompt not found" };
203 if (prompt !== this.state.active_prompt)
204 return { valid: false, message: "Prompt no longer active" };
206 /* Save the complete answers for our own use later. */
212 /* Update state (to be sent out to any future clients) */
213 this.state.players_answering.delete(player.name);
214 this.state.players_answered.push(player.name);
216 /* And notify all players that this player has answered. */
217 this.broadcast_event_object('player-answered', player.name);
219 /* If no players are left in the answering list then we don't need
220 * to wait for the answering_idle_timer to fire, because a person
221 * who isn't there obviously can't be typing. So we can broadcast
222 * the idle event right away. Note that we do this only if the
223 * answering phase has been going for a while to avoid the case of
224 * the first player being super fast and emptying the
225 * players_answering list before anyone else even got in.
227 if (this.state.players_answering.size === 0 &&
228 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
230 this.broadcast_event_object('answering-idle', true);
233 return { valid: true };
236 receive_answering(prompt_id, session_id) {
237 const player = this.players_by_session[session_id];
239 return { valid: false, message: "Player not found" };
241 const prompt = this.state.prompts.find(p => p.id === prompt_id);
243 return { valid: false, message: "Prompt not found" };
245 if (prompt !== this.state.active_prompt)
246 return { valid: false, message: "Prompt no longer active" };
248 if (this.answering_idle_timer) {
249 clearTimeout(this.answering_idle_timer);
250 this.ansering_idle_timer = 0;
252 if (! this.state.answering_idle) {
253 this.answering_idle_timer = setTimeout(() => {
254 this.state.answering_idle = true;
255 this.broadcast_event_object('answering-idle', true);
256 }, PHASE_IDLE_TIMEOUT * 1000);
259 if (this.answering_start_time_ms === 0)
260 this.answering_start_time_ms = Date.now();
262 /* Notify all players that this player is actively answering. */
263 this.state.players_answering.add(player.name);
264 this.broadcast_event_object('player-answering', player.name);
266 return { valid: true };
269 /* Returns true if vote toggled, false for player or prompt not found */
270 toggle_end_answers(prompt_id, session_id) {
271 const player = this.players_by_session[session_id];
273 const prompt = this.state.prompts.find(p => p.id === prompt_id);
274 if (! prompt || ! player)
277 if (this.state.end_answers.has(player.name)) {
278 this.state.end_answers.delete(player.name);
279 this.broadcast_event_object('unvote-end-answers', player.name);
281 this.state.end_answers.add(player.name);
282 this.broadcast_event_object('vote-end-answers', player.name);
291 for (let a of this.answers) {
292 for (let word of a.answers) {
293 const key = this.canonize(word);
294 word_map[key] = word;
298 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
299 return a.toLowerCase().localeCompare(b.toLowerCase());
302 if (this.judging_start_time_ms === 0) {
303 this.judging_start_time_ms = Date.now();
306 this.broadcast_event_object('ambiguities', this.state.ambiguities);
308 /* Notify all players of every player that is judging. */
309 for (let player_name of this.state.players_answered) {
310 this.state.players_judging.add(player_name);
311 this.broadcast_event_object('player-judging', player_name);
315 reset_judging_timeout() {
316 if (this.judging_idle_timer) {
317 clearTimeout(this.judging_idle_timer);
318 this.judging_idle_timer = 0;
320 if (! this.state.judging_idle) {
321 this.judging_idle_timer = setTimeout(() => {
322 this.state.judging_idle = true;
323 this.broadcast_event_object('judging-idle', true);
324 }, PHASE_IDLE_TIMEOUT * 1000);
328 receive_judged(prompt_id, session_id, word_groups) {
329 const player = this.players_by_session[session_id];
331 return { valid: false, message: "Player not found" };
333 const prompt = this.state.prompts.find(p => p.id === prompt_id);
335 return { valid: false, message: "Prompt not found" };
337 if (prompt !== this.state.active_prompt)
338 return { valid: false, message: "Prompt no longer active" };
340 this.reset_judging_timeout();
342 /* Each player submits some number of groups of answers that
343 * should be considered equivalent. The server expands that into
344 * the set of pair-wise equivalencies that are expressed. The
345 * reason for that is so that the server can determine which
346 * pair-wise equivalencies have majority support.
348 for (let group of word_groups) {
350 const words = group.words;
352 this.kudos[player.name] = [...words];
354 for (let i = 0; i < words.length - 1; i++) {
355 for (let j = i + 1; j < words.length; j++) {
356 let eq = [words[i], words[j]];
358 /* Put the two words into a reliable order so that we don't
359 * miss a pair of equivalent equivalencies just because they
360 * happen to be in the opposite order. */
361 if (eq[0].localeCompare(eq[1]) > 0) {
362 eq = [words[j], words[i]];
365 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
367 const exist = this.equivalencies[key];
371 this.equivalencies[key] = {
381 /* Update state (to be sent out to any future clients) */
382 this.state.players_judging.delete(player.name);
383 this.state.players_judged.push(player.name);
385 /* And notify all players that this player has judged. */
386 this.broadcast_event_object('player-judged', player.name);
388 /* If no players are left in the judging list then we don't need
389 * to wait for the judging_idle_timer to fire, because a person
390 * who isn't there obviously can't be judging. So we can broadcast
391 * the idle event right away. Note that we do this only if the
392 * judging phase has been going for a while to avoid the case of
393 * the first player being super fast and emptying the
394 * players_judging list before anyone else even got in.
396 if (this.state.players_judging.size === 0 &&
397 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
399 this.broadcast_event_object('judging-idle', true);
402 return { valid: true };
405 receive_judging(prompt_id, session_id) {
407 const player = this.players_by_session[session_id];
409 return { valid: false, message: "Player not found" };
411 const prompt = this.state.prompts.find(p => p.id === prompt_id);
413 return { valid: false, message: "Prompt not found" };
415 if (prompt !== this.state.active_prompt)
416 return { valid: false, message: "Prompt no longer active" };
418 this.reset_judging_timeout();
420 /* Notify all players that this player is actively judging. */
421 this.state.players_judging.add(player.name);
422 this.broadcast_event_object('player-judging', player.name);
424 return { valid: true };
427 /* Returns true if vote toggled, false for player or prompt not found */
428 toggle_end_judging(prompt_id, session_id) {
429 const player = this.players_by_session[session_id];
431 const prompt = this.state.prompts.find(p => p.id === prompt_id);
432 if (! prompt || ! player)
435 if (this.state.end_judging.has(player.name)) {
436 this.state.end_judging.delete(player.name);
437 this.broadcast_event_object('unvote-end-judging', player.name);
439 this.state.end_judging.add(player.name);
440 this.broadcast_event_object('vote-end-judging', player.name);
446 /* Returns true if vote toggled, false for player or prompt not found */
447 toggle_new_game(prompt_id, session_id) {
448 const player = this.players_by_session[session_id];
450 const prompt = this.state.prompts.find(p => p.id === prompt_id);
451 if (! prompt || ! player)
454 if (this.state.new_game_votes.has(player.name)) {
455 this.state.new_game_votes.delete(player.name);
456 this.broadcast_event_object('unvote-new-game', player.name);
458 this.state.new_game_votes.add(player.name);
459 this.broadcast_event_object('vote-new-game', player.name);
466 return word.trim().toLowerCase();
470 const word_submitters = {};
472 /* Perform a (non-strict) majority ruling on equivalencies,
473 * dropping all that didn't get enough votes. */
474 const quorum = Math.floor((this.state.players_judged.length + 1)/2);
475 const agreed_equivalencies = Object.values(this.equivalencies).filter(
476 eq => eq.count >= quorum);
478 /* And with that agreed set of equivalencies, construct the full
480 const word_maps = {};
482 for (let e of agreed_equivalencies) {
483 const word0_canon = this.canonize(e.words[0]);
484 const word1_canon = this.canonize(e.words[1]);
485 let group = word_maps[word0_canon];
487 group = word_maps[word1_canon];
495 if (! word_maps[word0_canon]) {
496 word_maps[word0_canon] = group;
497 group.words.push(e.words[0]);
500 if (! word_maps[word1_canon]) {
501 word_maps[word1_canon] = group;
502 group.words.push(e.words[1]);
506 /* Now go through answers from each player and add the player
507 * to the set corresponding to each word group. */
508 for (let a of this.answers) {
509 for (let word of a.answers) {
510 const word_canon = this.canonize(word);
511 /* If there's no group yet, this is a singleton word. */
512 if (word_maps[word_canon]) {
513 word_maps[word_canon].players.add(a.player);
520 group.players.add(a.player);
521 word_maps[word_canon] = group;
526 /* Apply kudos from each player to the word maps, (using a set so
527 * that no word_map can get multiple kudos from a single
529 for (let player of Object.keys(this.kudos)) {
530 for (let word of this.kudos[player]) {
531 const word_canon = this.canonize(word);
532 if (! word_maps[word_canon])
534 word_maps[word_canon].kudos.add(player);
538 /* Now that we've assigned the players to these word maps, we now
539 * want to collapse the groups down to a single array of
542 * The difference between "word_maps" and "word_groups" is that
543 * the former has a property for every word that maps to a group,
544 * (so if you iterate over the keys you will see the same group
545 * multiple times). In contrast, iterating over"word_groups" will
546 * have you visit each group only once. */
547 const word_groups = Object.entries(word_maps).filter(
548 entry => entry[0] === this.canonize(entry[1].words[0]))
549 .map(entry => entry[1]);
551 /* Now, go through each word group and assign the scores out to
552 * the corresponding players.
554 * Note: We do this by going through the word groups, (as opposed
555 * to the list of words from the players again), specifically to
556 * avoid giving a player points for a word group twice (in the
557 * case where a player submits two different words that the group
558 * ends up judging as equivalent).
560 this.players.forEach(p => {
564 for (let group of word_groups) {
565 group.players.forEach(p => {
566 p.round_score += group.players.size;
567 p.round_kudos += group.kudos.size;
571 const scores = this.players.filter(p => p.active).map(p => {
574 score: p.round_score,
579 scores.sort((a,b) => {
580 const delta = b.score - a.score;
583 return b.kudos - a.kudos;
586 /* After sorting individual players by score, group players
587 * together who have the same score. */
588 const reducer = (list, next) => {
590 && list[list.length-1].score == next.score
591 && list[list.length-1].kudos == next.kudos
594 list[list.length-1].players.push(next.player);
597 players: [next.player],
605 const grouped_scores = scores.reduce(reducer, []);
607 /* Put the word groups into a form the client can consume.
609 const words_submitted = word_groups.map(
612 word: group.words.join('/'),
613 players: Array.from(group.players).map(p => p.name),
614 kudos: Array.from(group.kudos)
619 words_submitted.sort((a,b) => {
620 const delta = b.players.length - a.players.length;
623 return b.kudos.length - a.kudos.length;
626 /* Put this round's scores into the game state object so it will
627 * be sent to any new clients that join. */
628 this.state.scores = {
629 scores: grouped_scores,
630 words: words_submitted
633 /* And broadcast the scores to all connected clients. */
634 this.broadcast_event_object('scores', this.state.scores);
638 Empathy.router = express.Router();
639 const router = Empathy.router;
642 constructor(id, items, prompt) {
645 this.prompt = prompt;
647 this.votes_against = [];
650 toggle_vote(player_name) {
651 if (this.votes.find(v => v === player_name))
652 this.votes = this.votes.filter(v => v !== player_name);
654 this.votes.push(player_name);
657 toggle_vote_against(player_name) {
658 if (this.votes_against.find(v => v === player_name)) {
659 this.votes_against = this.votes_against.filter(v => v !== player_name);
661 this.votes_against.push(player_name);
662 /* When voting against, we also remove any vote _for_ the same
664 this.votes = this.votes.filter(v => v !== player_name);
669 router.post('/prompts', (request, response) => {
670 const game = request.game;
672 const result = game.add_prompt(request.body.items, request.body.prompt);
674 response.json(result);
677 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
678 const game = request.game;
679 const prompt_id = parseInt(request.params.prompt_id, 10);
681 if (game.toggle_vote(prompt_id, request.session.id))
684 response.sendStatus(404);
687 router.post('/vote_against/:prompt_id([0-9]+)', (request, response) => {
688 const game = request.game;
689 const prompt_id = parseInt(request.params.prompt_id, 10);
691 if (game.toggle_vote_against(prompt_id, request.session.id))
694 response.sendStatus(404);
697 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
698 const game = request.game;
699 const prompt_id = parseInt(request.params.prompt_id, 10);
701 if (game.start(prompt_id))
704 response.sendStatus(404);
707 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
708 const game = request.game;
709 const prompt_id = parseInt(request.params.prompt_id, 10);
711 const result = game.receive_answer(prompt_id,
713 request.body.answers);
714 response.json(result);
716 /* If every registered player has answered, then there's no need to
717 * wait for anything else. */
718 if (game.state.players_answered.length >= game.active_players)
719 game.perform_judging();
722 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
723 const game = request.game;
724 const prompt_id = parseInt(request.params.prompt_id, 10);
726 const result = game.receive_answering(prompt_id,
728 response.json(result);
731 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
732 const game = request.game;
733 const prompt_id = parseInt(request.params.prompt_id, 10);
735 if (game.toggle_end_answers(prompt_id, request.session.id))
738 response.sendStatus(404);
740 /* The majority rule here includes all players that have answered as
741 * well as all that have started typing. */
742 const players_involved = (game.state.players_answered.length +
743 game.state.players_answering.size);
745 if (game.state.end_answers.size > players_involved / 2)
746 game.perform_judging();
749 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
750 const game = request.game;
751 const prompt_id = parseInt(request.params.prompt_id, 10);
753 const result = game.receive_judged(prompt_id,
755 request.body.word_groups);
756 response.json(result);
758 /* If every player who answered has also judged, then there's no
759 * need to wait for anything else. */
760 const judged_set = new Set(game.state.players_judged);
761 if ([...game.state.players_answered].filter(x => !judged_set.has(x)).length === 0)
762 game.compute_scores();
765 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
766 const game = request.game;
767 const prompt_id = parseInt(request.params.prompt_id, 10);
769 const result = game.receive_judging(prompt_id,
771 response.json(result);
774 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
775 const game = request.game;
776 const prompt_id = parseInt(request.params.prompt_id, 10);
778 if (game.toggle_end_judging(prompt_id, request.session.id))
781 response.sendStatus(404);
783 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
784 game.compute_scores();
787 router.post('/new-game/:prompt_id([0-9]+)', (request, response) => {
788 const game = request.game;
789 const prompt_id = parseInt(request.params.prompt_id, 10);
791 if (game.toggle_new_game(prompt_id, request.session.id))
794 response.sendStatus(404);
796 if (game.state.new_game_votes.size > (game.state.players_answered.length / 2))
800 router.post('/reset', (request, response) => {
801 const game = request.game;
809 identifier: "empathy",
812 exports.Game = Empathy;