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(),
42 this.answering_idle_timer = 0;
43 this.answering_start_time_ms = 0;
44 this.judging_idle_timer = 0;
45 this.judging_start_time_ms = 0;
46 this.next_prompt_id = 1;
47 this.equivalencies = {};
52 /* Before closing out the current round, we accumulate the score
53 * for each player into their runnning total. */
54 for (let score of this.state.scores.scores) {
55 const player = this.players.find(p => p.name === score.player);
57 player.score += score.score;
59 player.score = score.score;
61 /* And broadcast that new score out. */
62 this.broadcast_event('player-update', player.info_json());
65 /* Now that we're done with the active prompt, we remove it from
66 * the list of prompts and also remove any prompts that received
67 * no votes. This keeps the list of prompts clean.
69 const active_id = this.state.active_prompt.id;
71 this.state.prompts.filter(
72 p => p.id !== active_id && p.votes.length > 0
75 this.state.active_prompt = null;
76 this.state.players_answered = [];
77 this.state.players_answering = new Set();
78 this.state.answering_idle = false;
79 this.state.end_answers = new Set();
80 this.state.ambiguities = null;
81 this.state.players_judged = [];
82 this.state.players_judging = new Set();
83 this.state.judging_idle = false;
84 this.state.end_judging = new Set();
85 this.state.scores = null;
88 if (this.answering_idle_timer) {
89 clearTimeout(this.answering_idle_timer);
91 this.answering_idle_timer = 0;
92 this.answering_start_time_ms = 0;
93 if (this.judging_idle_timer) {
94 clearTimeout(this.judging_idle_timer);
96 this.judging_idle_timer = 0;
97 this.judging_start_time_ms = 0;
98 this.equivalencies = {};
100 this.broadcast_event_object('game-state', this.state);
103 add_prompt(items, prompt_string) {
104 if (items > MAX_PROMPT_ITEMS)
107 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
110 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
111 this.next_prompt_id++;
113 this.state.prompts.push(prompt);
115 this.broadcast_event_object('prompt', prompt);
123 /* Returns true if vote toggled, false for player or prompt not found */
124 toggle_vote(prompt_id, session_id) {
125 const player = this.players_by_session[session_id];
127 const prompt = this.state.prompts.find(p => p.id === prompt_id);
128 if (! prompt || ! player)
131 prompt.toggle_vote(player.name);
133 this.broadcast_event_object('prompt', prompt);
138 /* Returns true on success, false for prompt not found. */
140 const prompt = this.state.prompts.find(p => p.id === prompt_id);
144 /* Ignore any start request that comes in while a prompt is
145 * already being played. */
146 if (this.state.active_prompt)
149 this.state.active_prompt = prompt;
151 this.broadcast_event_object('start', prompt);
156 receive_answer(prompt_id, session_id, answers) {
157 const player = this.players_by_session[session_id];
159 return { valid: false, message: "Player not found" };
161 const prompt = this.state.prompts.find(p => p.id === prompt_id);
163 return { valid: false, message: "Prompt not found" };
165 if (prompt !== this.state.active_prompt)
166 return { valid: false, message: "Prompt no longer active" };
168 /* Save the complete answers for our own use later. */
174 /* Update state (to be sent out to any future clients) */
175 this.state.players_answering.delete(player.name);
176 this.state.players_answered.push(player.name);
178 /* And notify all players that this player has answered. */
179 this.broadcast_event_object('player-answered', player.name);
181 /* If no players are left in the answering list then we don't need
182 * to wait for the answering_idle_timer to fire, because a person
183 * who isn't there obviously can't be typing. So we can broadcast
184 * the idle event right away. Note that we do this only if the
185 * answering phase has been going for a while to avoid the case of
186 * the first player being super fast and emptying the
187 * players_answering list before anyone else even got in.
189 if (this.state.players_answering.size === 0 &&
190 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
192 this.broadcast_event_object('answering-idle', true);
195 return { valid: true };
198 receive_answering(prompt_id, session_id) {
199 const player = this.players_by_session[session_id];
201 return { valid: false, message: "Player not found" };
203 const prompt = this.state.prompts.find(p => p.id === prompt_id);
205 return { valid: false, message: "Prompt not found" };
207 if (prompt !== this.state.active_prompt)
208 return { valid: false, message: "Prompt no longer active" };
210 if (this.answering_idle_timer) {
211 clearTimeout(this.answering_idle_timer);
212 this.ansering_idle_timer = 0;
214 if (! this.state.answering_idle) {
215 this.answering_idle_timer = setTimeout(() => {
216 this.state.answering_idle = true;
217 this.broadcast_event_object('answering-idle', true);
218 }, PHASE_IDLE_TIMEOUT * 1000);
221 if (this.answering_start_time_ms === 0)
222 this.answering_start_time_ms = Date.now();
224 /* Notify all players that this player is actively answering. */
225 this.state.players_answering.add(player.name);
226 this.broadcast_event_object('player-answering', player.name);
228 return { valid: true };
231 /* Returns true if vote toggled, false for player or prompt not found */
232 toggle_end_answers(prompt_id, session_id) {
233 const player = this.players_by_session[session_id];
235 const prompt = this.state.prompts.find(p => p.id === prompt_id);
236 if (! prompt || ! player)
239 if (this.state.end_answers.has(player.name)) {
240 this.state.end_answers.delete(player.name);
241 this.broadcast_event_object('unvote-end-answers', player.name);
243 this.state.end_answers.add(player.name);
244 this.broadcast_event_object('vote-end-answers', player.name);
253 for (let a of this.answers) {
254 for (let word of a.answers) {
255 const key = this.canonize(word);
256 word_map[key] = word;
260 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
261 return a.toLowerCase().localeCompare(b.toLowerCase());
264 if (this.judging_start_time_ms === 0) {
265 this.judging_start_time_ms = Date.now();
268 this.broadcast_event_object('ambiguities', this.state.ambiguities);
271 receive_judged(prompt_id, session_id, word_groups) {
272 const player = this.players_by_session[session_id];
274 return { valid: false, message: "Player not found" };
276 const prompt = this.state.prompts.find(p => p.id === prompt_id);
278 return { valid: false, message: "Prompt not found" };
280 if (prompt !== this.state.active_prompt)
281 return { valid: false, message: "Prompt no longer active" };
283 /* Each player submits some number of groups of answers that
284 * should be considered equivalent. The server expands that into
285 * the set of pair-wise equivalencies that are expressed. The
286 * reason for that is so that the server can determine which
287 * pair-wise equivalencies have majority support.
289 for (let group of word_groups) {
291 for (let i = 0; i < group.length - 1; i++) {
292 for (let j = i + 1; j < group.length; j++) {
293 let eq = [group[i], group[j]];
295 /* Put the two words into a reliable order so that we don't
296 * miss a pair of equivalent equivalencies just because they
297 * happen to be in the opposite order. */
298 if (eq[0].localeCompare(eq[1]) > 0) {
299 eq = [group[j], group[i]];
302 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
304 const exist = this.equivalencies[key];
308 this.equivalencies[key] = {
318 /* Update state (to be sent out to any future clients) */
319 this.state.players_judging.delete(player.name);
320 this.state.players_judged.push(player.name);
322 /* And notify all players that this player has judged. */
323 this.broadcast_event_object('player-judged', player.name);
325 /* If no players are left in the judging list then we don't need
326 * to wait for the judging_idle_timer to fire, because a person
327 * who isn't there obviously can't be judging. So we can broadcast
328 * the idle event right away. Note that we do this only if the
329 * judging phase has been going for a while to avoid the case of
330 * the first player being super fast and emptying the
331 * players_judging list before anyone else even got in.
333 if (this.state.players_judging.size === 0 &&
334 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
336 this.broadcast_event_object('judging-idle', true);
339 return { valid: true };
342 receive_judging(prompt_id, session_id) {
344 const player = this.players_by_session[session_id];
346 return { valid: false, message: "Player not found" };
348 const prompt = this.state.prompts.find(p => p.id === prompt_id);
350 return { valid: false, message: "Prompt not found" };
352 if (prompt !== this.state.active_prompt)
353 return { valid: false, message: "Prompt no longer active" };
355 if (this.judging_idle_timer) {
356 clearTimeout(this.judging_idle_timer);
357 this.judging_idle_timer = 0;
359 if (! this.state.judging_idle) {
360 this.judging_idle_timer = setTimeout(() => {
361 this.state.judging_idle = true;
362 this.broadcast_event_object('judging-idle', true);
363 }, PHASE_IDLE_TIMEOUT * 1000);
366 /* Notify all players that this player is actively judging. */
367 this.state.players_judging.add(player.name);
368 this.broadcast_event_object('player-judging', player.name);
370 return { valid: true };
373 /* Returns true if vote toggled, false for player or prompt not found */
374 toggle_end_judging(prompt_id, session_id) {
375 const player = this.players_by_session[session_id];
377 const prompt = this.state.prompts.find(p => p.id === prompt_id);
378 if (! prompt || ! player)
381 if (this.state.end_judging.has(player.name)) {
382 this.state.end_judging.delete(player.name);
383 this.broadcast_event_object('unvote-end-judging', player.name);
385 this.state.end_judging.add(player.name);
386 this.broadcast_event_object('vote-end-judging', player.name);
393 return word.trim().toLowerCase();
397 const word_submitters = {};
399 /* Perform a (non-strict) majority ruling on equivalencies,
400 * dropping all that didn't get enough votes. */
401 const quorum = Math.floor((this.players.length + 1)/2);
402 const agreed_equivalencies = Object.values(this.equivalencies).filter(
403 eq => eq.count >= quorum);
405 /* And with that agreed set of equivalencies, construct the full
407 const word_maps = {};
409 for (let e of agreed_equivalencies) {
410 const word0_canon = this.canonize(e.words[0]);
411 const word1_canon = this.canonize(e.words[1]);
412 let group = word_maps[word0_canon];
414 group = word_maps[word1_canon];
416 group = { words: [], players: new Set()};
418 if (! word_maps[word0_canon]) {
419 word_maps[word0_canon] = group;
420 group.words.push(e.words[0]);
423 if (! word_maps[word1_canon]) {
424 word_maps[word1_canon] = group;
425 group.words.push(e.words[1]);
429 /* Now go through answers from each player and add the player
430 * to the set corresponding to each word group. */
431 for (let a of this.answers) {
432 for (let word of a.answers) {
433 const word_canon = this.canonize(word);
434 /* If there's no group yet, this is a singleton word. */
435 if (word_maps[word_canon]) {
436 word_maps[word_canon].players.add(a.player);
438 const group = { words: [word], players: new Set() };
439 group.players.add(a.player);
440 word_maps[word_canon] = group;
445 /* Now that we've assigned the players to these word maps, we now
446 * want to collapse the groups down to a single array of
449 * The difference between "word_maps" and "word_groups" is that
450 * the former has a property for every word that maps to a group,
451 * (so if you iterate over the keys you will see the same group
452 * multiple times). In contrast, iterating over"word_groups" will
453 * have you visit each group only once. */
454 const word_groups = Object.entries(word_maps).filter(
455 entry => entry[0] === this.canonize(entry[1].words[0]))
456 .map(entry => entry[1]);
458 /* Now, go through each word group and assign the scores out to
459 * the corresponding players.
461 * Note: We do this by going through the word groups, (as opposed
462 * to the list of words from the players again), specifically to
463 * avoid giving a player points for a wrod group twice (in the
464 * case where a player submits two different words that the group
465 * ends up judging as equivalent).
467 this.players.forEach(p => p.round_score = 0);
468 for (let group of word_groups) {
469 group.players.forEach(p => p.round_score += group.players.size);
472 const scores = this.players.map(p => {
479 scores.sort((a,b) => {
480 return b.score - a.score;
483 /* Put the word groups into a form the client can consume.
485 const words_submitted = word_groups.map(
488 word: group.words.join('/'),
489 players: Array.from(group.players).map(p => p.name)
494 words_submitted.sort((a,b) => {
495 return b.players.length - a.players.length;
498 /* Put this round's scores into the game state object so it will
499 * be sent to any new clients that join. */
500 this.state.scores = {
502 words: words_submitted
505 /* And broadcast the scores to all connected clients. */
506 this.broadcast_event_object('scores', this.state.scores);
510 Empathy.router = express.Router();
511 const router = Empathy.router;
514 constructor(id, items, prompt) {
517 this.prompt = prompt;
521 toggle_vote(player_name) {
522 if (this.votes.find(v => v === player_name))
523 this.votes = this.votes.filter(v => v !== player_name);
525 this.votes.push(player_name);
529 router.post('/prompts', (request, response) => {
530 const game = request.game;
532 const result = game.add_prompt(request.body.items, request.body.prompt);
534 response.json(result);
537 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
538 const game = request.game;
539 const prompt_id = parseInt(request.params.prompt_id, 10);
541 if (game.toggle_vote(prompt_id, request.session.id))
544 response.sendStatus(404);
547 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
548 const game = request.game;
549 const prompt_id = parseInt(request.params.prompt_id, 10);
551 if (game.start(prompt_id))
554 response.sendStatus(404);
557 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
558 const game = request.game;
559 const prompt_id = parseInt(request.params.prompt_id, 10);
561 const result = game.receive_answer(prompt_id,
563 request.body.answers);
564 response.json(result);
566 /* If every registered player has answered, then there's no need to
567 * wait for anything else. */
568 if (game.state.players_answered.length >= game.players.length)
569 game.perform_judging();
572 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
573 const game = request.game;
574 const prompt_id = parseInt(request.params.prompt_id, 10);
576 const result = game.receive_answering(prompt_id,
578 response.json(result);
581 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
582 const game = request.game;
583 const prompt_id = parseInt(request.params.prompt_id, 10);
585 if (game.toggle_end_answers(prompt_id, request.session.id))
588 response.sendStatus(404);
590 /* The majority rule here includes all players that have answered as
591 * well as all that have started typing. */
592 const players_involved = (game.state.players_answered.length +
593 game.state.players_answering.size);
595 if (game.state.end_answers.size > players_involved / 2)
596 game.perform_judging();
599 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
600 const game = request.game;
601 const prompt_id = parseInt(request.params.prompt_id, 10);
603 const result = game.receive_judged(prompt_id,
605 request.body.word_groups);
606 response.json(result);
608 /* If every registered player has judged, then there's no need to
609 * wait for anything else. */
610 if (game.state.players_judged.length >= game.players.length)
611 game.compute_scores();
614 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
615 const game = request.game;
616 const prompt_id = parseInt(request.params.prompt_id, 10);
618 const result = game.receive_judging(prompt_id,
620 response.json(result);
623 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
624 const game = request.game;
625 const prompt_id = parseInt(request.params.prompt_id, 10);
627 if (game.toggle_end_judging(prompt_id, request.session.id))
630 response.sendStatus(404);
632 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
633 game.compute_scores();
636 router.post('/reset', (request, response) => {
637 const game = request.game;
645 identifier: "empathy",
648 exports.Game = Empathy;