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 the score
54 * for each player into their runnning total. */
55 for (let score of this.state.scores.scores) {
56 const player = this.players.find(p => p.name === score.player);
58 player.score += score.score;
60 player.score = score.score;
62 /* And broadcast that new score out. */
63 this.broadcast_event('player-update', player.info_json());
66 /* Now that we're done with the active prompt, we remove it from
67 * the list of prompts and also remove any prompts that received
68 * no votes. This keeps the list of prompts clean.
70 const active_id = this.state.active_prompt.id;
72 this.state.prompts.filter(
73 p => p.id !== active_id && p.votes.length > 0
76 this.state.active_prompt = null;
77 this.state.players_answered = [];
78 this.state.players_answering = new Set();
79 this.state.answering_idle = false;
80 this.state.end_answers = new Set();
81 this.state.ambiguities = null;
82 this.state.players_judged = [];
83 this.state.players_judging = new Set();
84 this.state.judging_idle = false;
85 this.state.end_judging = new Set();
86 this.state.scores = null;
87 this.state.new_game_votes = new Set();
90 if (this.answering_idle_timer) {
91 clearTimeout(this.answering_idle_timer);
93 this.answering_idle_timer = 0;
94 this.answering_start_time_ms = 0;
95 if (this.judging_idle_timer) {
96 clearTimeout(this.judging_idle_timer);
98 this.judging_idle_timer = 0;
99 this.judging_start_time_ms = 0;
100 this.equivalencies = {};
102 this.broadcast_event('game-state', this.game_state_json());
105 add_prompt(items, prompt_string) {
106 if (items > MAX_PROMPT_ITEMS)
109 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
112 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
113 this.next_prompt_id++;
115 this.state.prompts.push(prompt);
117 this.broadcast_event_object('prompt', prompt);
125 /* Returns true if vote toggled, false for player or prompt not found */
126 toggle_vote(prompt_id, session_id) {
127 const player = this.players_by_session[session_id];
129 const prompt = this.state.prompts.find(p => p.id === prompt_id);
130 if (! prompt || ! player)
133 prompt.toggle_vote(player.name);
135 this.broadcast_event_object('prompt', prompt);
140 /* Returns true on success, false for prompt not found. */
142 const prompt = this.state.prompts.find(p => p.id === prompt_id);
146 /* Ignore any start request that comes in while a prompt is
147 * already being played. */
148 if (this.state.active_prompt)
151 this.state.active_prompt = prompt;
153 this.broadcast_event_object('start', prompt);
158 receive_answer(prompt_id, session_id, answers) {
159 const player = this.players_by_session[session_id];
161 return { valid: false, message: "Player not found" };
163 const prompt = this.state.prompts.find(p => p.id === prompt_id);
165 return { valid: false, message: "Prompt not found" };
167 if (prompt !== this.state.active_prompt)
168 return { valid: false, message: "Prompt no longer active" };
170 /* Save the complete answers for our own use later. */
176 /* Update state (to be sent out to any future clients) */
177 this.state.players_answering.delete(player.name);
178 this.state.players_answered.push(player.name);
180 /* And notify all players that this player has answered. */
181 this.broadcast_event_object('player-answered', player.name);
183 /* If no players are left in the answering list then we don't need
184 * to wait for the answering_idle_timer to fire, because a person
185 * who isn't there obviously can't be typing. So we can broadcast
186 * the idle event right away. Note that we do this only if the
187 * answering phase has been going for a while to avoid the case of
188 * the first player being super fast and emptying the
189 * players_answering list before anyone else even got in.
191 if (this.state.players_answering.size === 0 &&
192 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
194 this.broadcast_event_object('answering-idle', true);
197 return { valid: true };
200 receive_answering(prompt_id, session_id) {
201 const player = this.players_by_session[session_id];
203 return { valid: false, message: "Player not found" };
205 const prompt = this.state.prompts.find(p => p.id === prompt_id);
207 return { valid: false, message: "Prompt not found" };
209 if (prompt !== this.state.active_prompt)
210 return { valid: false, message: "Prompt no longer active" };
212 if (this.answering_idle_timer) {
213 clearTimeout(this.answering_idle_timer);
214 this.ansering_idle_timer = 0;
216 if (! this.state.answering_idle) {
217 this.answering_idle_timer = setTimeout(() => {
218 this.state.answering_idle = true;
219 this.broadcast_event_object('answering-idle', true);
220 }, PHASE_IDLE_TIMEOUT * 1000);
223 if (this.answering_start_time_ms === 0)
224 this.answering_start_time_ms = Date.now();
226 /* Notify all players that this player is actively answering. */
227 this.state.players_answering.add(player.name);
228 this.broadcast_event_object('player-answering', player.name);
230 return { valid: true };
233 /* Returns true if vote toggled, false for player or prompt not found */
234 toggle_end_answers(prompt_id, session_id) {
235 const player = this.players_by_session[session_id];
237 const prompt = this.state.prompts.find(p => p.id === prompt_id);
238 if (! prompt || ! player)
241 if (this.state.end_answers.has(player.name)) {
242 this.state.end_answers.delete(player.name);
243 this.broadcast_event_object('unvote-end-answers', player.name);
245 this.state.end_answers.add(player.name);
246 this.broadcast_event_object('vote-end-answers', player.name);
255 for (let a of this.answers) {
256 for (let word of a.answers) {
257 const key = this.canonize(word);
258 word_map[key] = word;
262 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
263 return a.toLowerCase().localeCompare(b.toLowerCase());
266 if (this.judging_start_time_ms === 0) {
267 this.judging_start_time_ms = Date.now();
270 this.broadcast_event_object('ambiguities', this.state.ambiguities);
272 /* Notify all players of every player that is judging. */
273 for (let player_name of this.state.players_answered) {
274 this.state.players_judging.add(player_name);
275 this.broadcast_event_object('player-judging', player_name);
279 reset_judging_timeout() {
280 if (this.judging_idle_timer) {
281 clearTimeout(this.judging_idle_timer);
282 this.judging_idle_timer = 0;
284 if (! this.state.judging_idle) {
285 this.judging_idle_timer = setTimeout(() => {
286 this.state.judging_idle = true;
287 this.broadcast_event_object('judging-idle', true);
288 }, PHASE_IDLE_TIMEOUT * 1000);
292 receive_judged(prompt_id, session_id, word_groups) {
293 const player = this.players_by_session[session_id];
295 return { valid: false, message: "Player not found" };
297 const prompt = this.state.prompts.find(p => p.id === prompt_id);
299 return { valid: false, message: "Prompt not found" };
301 if (prompt !== this.state.active_prompt)
302 return { valid: false, message: "Prompt no longer active" };
304 this.reset_judging_timeout();
306 /* Each player submits some number of groups of answers that
307 * should be considered equivalent. The server expands that into
308 * the set of pair-wise equivalencies that are expressed. The
309 * reason for that is so that the server can determine which
310 * pair-wise equivalencies have majority support.
312 for (let group of word_groups) {
314 for (let i = 0; i < group.length - 1; i++) {
315 for (let j = i + 1; j < group.length; j++) {
316 let eq = [group[i], group[j]];
318 /* Put the two words into a reliable order so that we don't
319 * miss a pair of equivalent equivalencies just because they
320 * happen to be in the opposite order. */
321 if (eq[0].localeCompare(eq[1]) > 0) {
322 eq = [group[j], group[i]];
325 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
327 const exist = this.equivalencies[key];
331 this.equivalencies[key] = {
341 /* Update state (to be sent out to any future clients) */
342 this.state.players_judging.delete(player.name);
343 this.state.players_judged.push(player.name);
345 /* And notify all players that this player has judged. */
346 this.broadcast_event_object('player-judged', player.name);
348 /* If no players are left in the judging list then we don't need
349 * to wait for the judging_idle_timer to fire, because a person
350 * who isn't there obviously can't be judging. So we can broadcast
351 * the idle event right away. Note that we do this only if the
352 * judging phase has been going for a while to avoid the case of
353 * the first player being super fast and emptying the
354 * players_judging list before anyone else even got in.
356 if (this.state.players_judging.size === 0 &&
357 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
359 this.broadcast_event_object('judging-idle', true);
362 return { valid: true };
365 receive_judging(prompt_id, session_id) {
367 const player = this.players_by_session[session_id];
369 return { valid: false, message: "Player not found" };
371 const prompt = this.state.prompts.find(p => p.id === prompt_id);
373 return { valid: false, message: "Prompt not found" };
375 if (prompt !== this.state.active_prompt)
376 return { valid: false, message: "Prompt no longer active" };
378 this.reset_judging_timeout();
380 /* Notify all players that this player is actively judging. */
381 this.state.players_judging.add(player.name);
382 this.broadcast_event_object('player-judging', player.name);
384 return { valid: true };
387 /* Returns true if vote toggled, false for player or prompt not found */
388 toggle_end_judging(prompt_id, session_id) {
389 const player = this.players_by_session[session_id];
391 const prompt = this.state.prompts.find(p => p.id === prompt_id);
392 if (! prompt || ! player)
395 if (this.state.end_judging.has(player.name)) {
396 this.state.end_judging.delete(player.name);
397 this.broadcast_event_object('unvote-end-judging', player.name);
399 this.state.end_judging.add(player.name);
400 this.broadcast_event_object('vote-end-judging', player.name);
406 /* Returns true if vote toggled, false for player or prompt not found */
407 toggle_new_game(prompt_id, session_id) {
408 const player = this.players_by_session[session_id];
410 const prompt = this.state.prompts.find(p => p.id === prompt_id);
411 if (! prompt || ! player)
414 if (this.state.new_game_votes.has(player.name)) {
415 this.state.new_game_votes.delete(player.name);
416 this.broadcast_event_object('unvote-new-game', player.name);
418 this.state.new_game_votes.add(player.name);
419 this.broadcast_event_object('vote-new-game', player.name);
426 return word.trim().toLowerCase();
430 const word_submitters = {};
432 /* Perform a (non-strict) majority ruling on equivalencies,
433 * dropping all that didn't get enough votes. */
434 const quorum = Math.floor((this.state.players_judged.length + 1)/2);
435 const agreed_equivalencies = Object.values(this.equivalencies).filter(
436 eq => eq.count >= quorum);
438 /* And with that agreed set of equivalencies, construct the full
440 const word_maps = {};
442 for (let e of agreed_equivalencies) {
443 const word0_canon = this.canonize(e.words[0]);
444 const word1_canon = this.canonize(e.words[1]);
445 let group = word_maps[word0_canon];
447 group = word_maps[word1_canon];
449 group = { words: [], players: new Set()};
451 if (! word_maps[word0_canon]) {
452 word_maps[word0_canon] = group;
453 group.words.push(e.words[0]);
456 if (! word_maps[word1_canon]) {
457 word_maps[word1_canon] = group;
458 group.words.push(e.words[1]);
462 /* Now go through answers from each player and add the player
463 * to the set corresponding to each word group. */
464 for (let a of this.answers) {
465 for (let word of a.answers) {
466 const word_canon = this.canonize(word);
467 /* If there's no group yet, this is a singleton word. */
468 if (word_maps[word_canon]) {
469 word_maps[word_canon].players.add(a.player);
471 const group = { words: [word], players: new Set() };
472 group.players.add(a.player);
473 word_maps[word_canon] = group;
478 /* Now that we've assigned the players to these word maps, we now
479 * want to collapse the groups down to a single array of
482 * The difference between "word_maps" and "word_groups" is that
483 * the former has a property for every word that maps to a group,
484 * (so if you iterate over the keys you will see the same group
485 * multiple times). In contrast, iterating over"word_groups" will
486 * have you visit each group only once. */
487 const word_groups = Object.entries(word_maps).filter(
488 entry => entry[0] === this.canonize(entry[1].words[0]))
489 .map(entry => entry[1]);
491 /* Now, go through each word group and assign the scores out to
492 * the corresponding players.
494 * Note: We do this by going through the word groups, (as opposed
495 * to the list of words from the players again), specifically to
496 * avoid giving a player points for a wrod group twice (in the
497 * case where a player submits two different words that the group
498 * ends up judging as equivalent).
500 this.players.forEach(p => p.round_score = 0);
501 for (let group of word_groups) {
502 group.players.forEach(p => p.round_score += group.players.size);
505 const scores = this.players.filter(p => p.active).map(p => {
512 scores.sort((a,b) => {
513 return b.score - a.score;
516 /* Put the word groups into a form the client can consume.
518 const words_submitted = word_groups.map(
521 word: group.words.join('/'),
522 players: Array.from(group.players).map(p => p.name)
527 words_submitted.sort((a,b) => {
528 return b.players.length - a.players.length;
531 /* Put this round's scores into the game state object so it will
532 * be sent to any new clients that join. */
533 this.state.scores = {
535 words: words_submitted
538 /* And broadcast the scores to all connected clients. */
539 this.broadcast_event_object('scores', this.state.scores);
543 Empathy.router = express.Router();
544 const router = Empathy.router;
547 constructor(id, items, prompt) {
550 this.prompt = prompt;
554 toggle_vote(player_name) {
555 if (this.votes.find(v => v === player_name))
556 this.votes = this.votes.filter(v => v !== player_name);
558 this.votes.push(player_name);
562 router.post('/prompts', (request, response) => {
563 const game = request.game;
565 const result = game.add_prompt(request.body.items, request.body.prompt);
567 response.json(result);
570 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
571 const game = request.game;
572 const prompt_id = parseInt(request.params.prompt_id, 10);
574 if (game.toggle_vote(prompt_id, request.session.id))
577 response.sendStatus(404);
580 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
581 const game = request.game;
582 const prompt_id = parseInt(request.params.prompt_id, 10);
584 if (game.start(prompt_id))
587 response.sendStatus(404);
590 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
591 const game = request.game;
592 const prompt_id = parseInt(request.params.prompt_id, 10);
594 const result = game.receive_answer(prompt_id,
596 request.body.answers);
597 response.json(result);
599 /* If every registered player has answered, then there's no need to
600 * wait for anything else. */
601 if (game.state.players_answered.length >= game.active_players)
602 game.perform_judging();
605 router.post('/answering/: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_answering(prompt_id,
611 response.json(result);
614 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
615 const game = request.game;
616 const prompt_id = parseInt(request.params.prompt_id, 10);
618 if (game.toggle_end_answers(prompt_id, request.session.id))
621 response.sendStatus(404);
623 /* The majority rule here includes all players that have answered as
624 * well as all that have started typing. */
625 const players_involved = (game.state.players_answered.length +
626 game.state.players_answering.size);
628 if (game.state.end_answers.size > players_involved / 2)
629 game.perform_judging();
632 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
633 const game = request.game;
634 const prompt_id = parseInt(request.params.prompt_id, 10);
636 const result = game.receive_judged(prompt_id,
638 request.body.word_groups);
639 response.json(result);
641 /* If every player who answered has also judged, then there's no
642 * need to wait for anything else. */
643 if (game.state.players_judged.length >= game.state.players_answered.length)
644 game.compute_scores();
647 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
648 const game = request.game;
649 const prompt_id = parseInt(request.params.prompt_id, 10);
651 const result = game.receive_judging(prompt_id,
653 response.json(result);
656 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
657 const game = request.game;
658 const prompt_id = parseInt(request.params.prompt_id, 10);
660 if (game.toggle_end_judging(prompt_id, request.session.id))
663 response.sendStatus(404);
665 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
666 game.compute_scores();
669 router.post('/new-game/: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_new_game(prompt_id, request.session.id))
676 response.sendStatus(404);
678 if (game.state.new_game_votes.size > (game.state.players_answered.length / 2))
682 router.post('/reset', (request, response) => {
683 const game = request.game;
691 identifier: "empathy",
694 exports.Game = Empathy;