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 /* Returns true on success, false for prompt not found. */
153 const prompt = this.state.prompts.find(p => p.id === prompt_id);
157 /* Ignore any start request that comes in while a prompt is
158 * already being played. */
159 if (this.state.active_prompt)
162 this.state.active_prompt = prompt;
164 this.broadcast_event_object('start', prompt);
169 receive_answer(prompt_id, session_id, answers) {
170 const player = this.players_by_session[session_id];
172 return { valid: false, message: "Player not found" };
174 const prompt = this.state.prompts.find(p => p.id === prompt_id);
176 return { valid: false, message: "Prompt not found" };
178 if (prompt !== this.state.active_prompt)
179 return { valid: false, message: "Prompt no longer active" };
181 /* Save the complete answers for our own use later. */
187 /* Update state (to be sent out to any future clients) */
188 this.state.players_answering.delete(player.name);
189 this.state.players_answered.push(player.name);
191 /* And notify all players that this player has answered. */
192 this.broadcast_event_object('player-answered', player.name);
194 /* If no players are left in the answering list then we don't need
195 * to wait for the answering_idle_timer to fire, because a person
196 * who isn't there obviously can't be typing. So we can broadcast
197 * the idle event right away. Note that we do this only if the
198 * answering phase has been going for a while to avoid the case of
199 * the first player being super fast and emptying the
200 * players_answering list before anyone else even got in.
202 if (this.state.players_answering.size === 0 &&
203 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
205 this.broadcast_event_object('answering-idle', true);
208 return { valid: true };
211 receive_answering(prompt_id, session_id) {
212 const player = this.players_by_session[session_id];
214 return { valid: false, message: "Player not found" };
216 const prompt = this.state.prompts.find(p => p.id === prompt_id);
218 return { valid: false, message: "Prompt not found" };
220 if (prompt !== this.state.active_prompt)
221 return { valid: false, message: "Prompt no longer active" };
223 if (this.answering_idle_timer) {
224 clearTimeout(this.answering_idle_timer);
225 this.ansering_idle_timer = 0;
227 if (! this.state.answering_idle) {
228 this.answering_idle_timer = setTimeout(() => {
229 this.state.answering_idle = true;
230 this.broadcast_event_object('answering-idle', true);
231 }, PHASE_IDLE_TIMEOUT * 1000);
234 if (this.answering_start_time_ms === 0)
235 this.answering_start_time_ms = Date.now();
237 /* Notify all players that this player is actively answering. */
238 this.state.players_answering.add(player.name);
239 this.broadcast_event_object('player-answering', player.name);
241 return { valid: true };
244 /* Returns true if vote toggled, false for player or prompt not found */
245 toggle_end_answers(prompt_id, session_id) {
246 const player = this.players_by_session[session_id];
248 const prompt = this.state.prompts.find(p => p.id === prompt_id);
249 if (! prompt || ! player)
252 if (this.state.end_answers.has(player.name)) {
253 this.state.end_answers.delete(player.name);
254 this.broadcast_event_object('unvote-end-answers', player.name);
256 this.state.end_answers.add(player.name);
257 this.broadcast_event_object('vote-end-answers', player.name);
266 for (let a of this.answers) {
267 for (let word of a.answers) {
268 const key = this.canonize(word);
269 word_map[key] = word;
273 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
274 return a.toLowerCase().localeCompare(b.toLowerCase());
277 if (this.judging_start_time_ms === 0) {
278 this.judging_start_time_ms = Date.now();
281 this.broadcast_event_object('ambiguities', this.state.ambiguities);
283 /* Notify all players of every player that is judging. */
284 for (let player_name of this.state.players_answered) {
285 this.state.players_judging.add(player_name);
286 this.broadcast_event_object('player-judging', player_name);
290 reset_judging_timeout() {
291 if (this.judging_idle_timer) {
292 clearTimeout(this.judging_idle_timer);
293 this.judging_idle_timer = 0;
295 if (! this.state.judging_idle) {
296 this.judging_idle_timer = setTimeout(() => {
297 this.state.judging_idle = true;
298 this.broadcast_event_object('judging-idle', true);
299 }, PHASE_IDLE_TIMEOUT * 1000);
303 receive_judged(prompt_id, session_id, word_groups) {
304 const player = this.players_by_session[session_id];
306 return { valid: false, message: "Player not found" };
308 const prompt = this.state.prompts.find(p => p.id === prompt_id);
310 return { valid: false, message: "Prompt not found" };
312 if (prompt !== this.state.active_prompt)
313 return { valid: false, message: "Prompt no longer active" };
315 this.reset_judging_timeout();
317 /* Each player submits some number of groups of answers that
318 * should be considered equivalent. The server expands that into
319 * the set of pair-wise equivalencies that are expressed. The
320 * reason for that is so that the server can determine which
321 * pair-wise equivalencies have majority support.
323 for (let group of word_groups) {
325 for (let i = 0; i < group.length - 1; i++) {
326 for (let j = i + 1; j < group.length; j++) {
327 let eq = [group[i], group[j]];
329 /* Put the two words into a reliable order so that we don't
330 * miss a pair of equivalent equivalencies just because they
331 * happen to be in the opposite order. */
332 if (eq[0].localeCompare(eq[1]) > 0) {
333 eq = [group[j], group[i]];
336 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
338 const exist = this.equivalencies[key];
342 this.equivalencies[key] = {
352 /* Update state (to be sent out to any future clients) */
353 this.state.players_judging.delete(player.name);
354 this.state.players_judged.push(player.name);
356 /* And notify all players that this player has judged. */
357 this.broadcast_event_object('player-judged', player.name);
359 /* If no players are left in the judging list then we don't need
360 * to wait for the judging_idle_timer to fire, because a person
361 * who isn't there obviously can't be judging. So we can broadcast
362 * the idle event right away. Note that we do this only if the
363 * judging phase has been going for a while to avoid the case of
364 * the first player being super fast and emptying the
365 * players_judging list before anyone else even got in.
367 if (this.state.players_judging.size === 0 &&
368 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
370 this.broadcast_event_object('judging-idle', true);
373 return { valid: true };
376 receive_judging(prompt_id, session_id) {
378 const player = this.players_by_session[session_id];
380 return { valid: false, message: "Player not found" };
382 const prompt = this.state.prompts.find(p => p.id === prompt_id);
384 return { valid: false, message: "Prompt not found" };
386 if (prompt !== this.state.active_prompt)
387 return { valid: false, message: "Prompt no longer active" };
389 this.reset_judging_timeout();
391 /* Notify all players that this player is actively judging. */
392 this.state.players_judging.add(player.name);
393 this.broadcast_event_object('player-judging', player.name);
395 return { valid: true };
398 /* Returns true if vote toggled, false for player or prompt not found */
399 toggle_end_judging(prompt_id, session_id) {
400 const player = this.players_by_session[session_id];
402 const prompt = this.state.prompts.find(p => p.id === prompt_id);
403 if (! prompt || ! player)
406 if (this.state.end_judging.has(player.name)) {
407 this.state.end_judging.delete(player.name);
408 this.broadcast_event_object('unvote-end-judging', player.name);
410 this.state.end_judging.add(player.name);
411 this.broadcast_event_object('vote-end-judging', player.name);
417 /* Returns true if vote toggled, false for player or prompt not found */
418 toggle_new_game(prompt_id, session_id) {
419 const player = this.players_by_session[session_id];
421 const prompt = this.state.prompts.find(p => p.id === prompt_id);
422 if (! prompt || ! player)
425 if (this.state.new_game_votes.has(player.name)) {
426 this.state.new_game_votes.delete(player.name);
427 this.broadcast_event_object('unvote-new-game', player.name);
429 this.state.new_game_votes.add(player.name);
430 this.broadcast_event_object('vote-new-game', player.name);
437 return word.trim().toLowerCase();
441 const word_submitters = {};
443 /* Perform a (non-strict) majority ruling on equivalencies,
444 * dropping all that didn't get enough votes. */
445 const quorum = Math.floor((this.state.players_judged.length + 1)/2);
446 const agreed_equivalencies = Object.values(this.equivalencies).filter(
447 eq => eq.count >= quorum);
449 /* And with that agreed set of equivalencies, construct the full
451 const word_maps = {};
453 for (let e of agreed_equivalencies) {
454 const word0_canon = this.canonize(e.words[0]);
455 const word1_canon = this.canonize(e.words[1]);
456 let group = word_maps[word0_canon];
458 group = word_maps[word1_canon];
460 group = { words: [], players: new Set()};
462 if (! word_maps[word0_canon]) {
463 word_maps[word0_canon] = group;
464 group.words.push(e.words[0]);
467 if (! word_maps[word1_canon]) {
468 word_maps[word1_canon] = group;
469 group.words.push(e.words[1]);
473 /* Now go through answers from each player and add the player
474 * to the set corresponding to each word group. */
475 for (let a of this.answers) {
476 for (let word of a.answers) {
477 const word_canon = this.canonize(word);
478 /* If there's no group yet, this is a singleton word. */
479 if (word_maps[word_canon]) {
480 word_maps[word_canon].players.add(a.player);
482 const group = { words: [word], players: new Set() };
483 group.players.add(a.player);
484 word_maps[word_canon] = group;
489 /* Now that we've assigned the players to these word maps, we now
490 * want to collapse the groups down to a single array of
493 * The difference between "word_maps" and "word_groups" is that
494 * the former has a property for every word that maps to a group,
495 * (so if you iterate over the keys you will see the same group
496 * multiple times). In contrast, iterating over"word_groups" will
497 * have you visit each group only once. */
498 const word_groups = Object.entries(word_maps).filter(
499 entry => entry[0] === this.canonize(entry[1].words[0]))
500 .map(entry => entry[1]);
502 /* Now, go through each word group and assign the scores out to
503 * the corresponding players.
505 * Note: We do this by going through the word groups, (as opposed
506 * to the list of words from the players again), specifically to
507 * avoid giving a player points for a wrod group twice (in the
508 * case where a player submits two different words that the group
509 * ends up judging as equivalent).
511 this.players.forEach(p => p.round_score = 0);
512 for (let group of word_groups) {
513 group.players.forEach(p => p.round_score += group.players.size);
516 const scores = this.players.filter(p => p.active).map(p => {
523 scores.sort((a,b) => {
524 return b.score - a.score;
527 /* After sorting individual players by score, group players
528 * together who have the same score. */
529 const reducer = (list, next) => {
530 if (list.length && list[list.length-1].score == next.score)
531 list[list.length-1].players.push(next.player);
533 list.push({players: [next.player], score: next.score});
537 const grouped_scores = scores.reduce(reducer, []);
539 /* Put the word groups into a form the client can consume.
541 const words_submitted = word_groups.map(
544 word: group.words.join('/'),
545 players: Array.from(group.players).map(p => p.name)
550 words_submitted.sort((a,b) => {
551 return b.players.length - a.players.length;
554 /* Put this round's scores into the game state object so it will
555 * be sent to any new clients that join. */
556 this.state.scores = {
557 scores: grouped_scores,
558 words: words_submitted
561 /* And broadcast the scores to all connected clients. */
562 this.broadcast_event_object('scores', this.state.scores);
566 Empathy.router = express.Router();
567 const router = Empathy.router;
570 constructor(id, items, prompt) {
573 this.prompt = prompt;
577 toggle_vote(player_name) {
578 if (this.votes.find(v => v === player_name))
579 this.votes = this.votes.filter(v => v !== player_name);
581 this.votes.push(player_name);
585 router.post('/prompts', (request, response) => {
586 const game = request.game;
588 const result = game.add_prompt(request.body.items, request.body.prompt);
590 response.json(result);
593 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
594 const game = request.game;
595 const prompt_id = parseInt(request.params.prompt_id, 10);
597 if (game.toggle_vote(prompt_id, request.session.id))
600 response.sendStatus(404);
603 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
604 const game = request.game;
605 const prompt_id = parseInt(request.params.prompt_id, 10);
607 if (game.start(prompt_id))
610 response.sendStatus(404);
613 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
614 const game = request.game;
615 const prompt_id = parseInt(request.params.prompt_id, 10);
617 const result = game.receive_answer(prompt_id,
619 request.body.answers);
620 response.json(result);
622 /* If every registered player has answered, then there's no need to
623 * wait for anything else. */
624 if (game.state.players_answered.length >= game.active_players)
625 game.perform_judging();
628 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
629 const game = request.game;
630 const prompt_id = parseInt(request.params.prompt_id, 10);
632 const result = game.receive_answering(prompt_id,
634 response.json(result);
637 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
638 const game = request.game;
639 const prompt_id = parseInt(request.params.prompt_id, 10);
641 if (game.toggle_end_answers(prompt_id, request.session.id))
644 response.sendStatus(404);
646 /* The majority rule here includes all players that have answered as
647 * well as all that have started typing. */
648 const players_involved = (game.state.players_answered.length +
649 game.state.players_answering.size);
651 if (game.state.end_answers.size > players_involved / 2)
652 game.perform_judging();
655 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
656 const game = request.game;
657 const prompt_id = parseInt(request.params.prompt_id, 10);
659 const result = game.receive_judged(prompt_id,
661 request.body.word_groups);
662 response.json(result);
664 /* If every player who answered has also judged, then there's no
665 * need to wait for anything else. */
666 const judged_set = new Set(game.state.players_judged);
667 if ([...game.state.players_answered].filter(x => !judged_set.has(x)).length === 0)
668 game.compute_scores();
671 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
672 const game = request.game;
673 const prompt_id = parseInt(request.params.prompt_id, 10);
675 const result = game.receive_judging(prompt_id,
677 response.json(result);
680 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
681 const game = request.game;
682 const prompt_id = parseInt(request.params.prompt_id, 10);
684 if (game.toggle_end_judging(prompt_id, request.session.id))
687 response.sendStatus(404);
689 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
690 game.compute_scores();
693 router.post('/new-game/:prompt_id([0-9]+)', (request, response) => {
694 const game = request.game;
695 const prompt_id = parseInt(request.params.prompt_id, 10);
697 if (game.toggle_new_game(prompt_id, request.session.id))
700 response.sendStatus(404);
702 if (game.state.new_game_votes.size > (game.state.players_answered.length / 2))
706 router.post('/reset', (request, response) => {
707 const game = request.game;
715 identifier: "empathy",
718 exports.Game = Empathy;