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 that 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 this.broadcast_event_object('ambiguities', this.state.ambiguities);
267 receive_judged(prompt_id, session_id, word_groups) {
268 const player = this.players_by_session[session_id];
270 return { valid: false, message: "Player not found" };
272 const prompt = this.state.prompts.find(p => p.id === prompt_id);
274 return { valid: false, message: "Prompt not found" };
276 if (prompt !== this.state.active_prompt)
277 return { valid: false, message: "Prompt no longer active" };
279 /* Each player submits some number of groups of answers that
280 * should be considered equivalent. The server expands that into
281 * the set of pair-wise equivalencies that are expressed. The
282 * reason for that is so that the server can determine which
283 * pair-wise equivalencies have majority support.
285 for (let group of word_groups) {
287 for (let i = 0; i < group.length - 1; i++) {
288 for (let j = i + 1; j < group.length; j++) {
289 let eq = [group[i], group[j]];
291 /* Put the two words into a reliable order so that we don't
292 * miss a pair of equivalent equivalencies just because they
293 * happen to be in the opposite order. */
294 if (eq[0].localeCompare(eq[1]) > 0) {
295 eq = [group[j], group[i]];
298 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
300 const exist = this.equivalencies[key];
304 this.equivalencies[key] = {
314 /* Update state (to be sent out to any future clients) */
315 this.state.players_judging.delete(player.name);
316 this.state.players_judged.push(player.name);
318 /* And notify all players this this player has judged. */
319 this.broadcast_event_object('player-judged', player.name);
321 /* If no players are left in the judging list then we don't need
322 * to wait for the judging_idle_timer to fire, because a person
323 * who isn't there obviously can't be judging. So we can broadcast
324 * the idle event right away. Note that we do this only if the
325 * judging phase has been going for a while to avoid the case of
326 * the first player being super fast and emptying the
327 * players_judging list before anyone else even got in.
329 if (this.state.players_judging.size === 0 &&
330 ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
332 this.broadcast_event_object('judging-idle', true);
335 return { valid: true };
338 receive_judging(prompt_id, session_id) {
339 const player = this.players_by_session[session_id];
341 return { valid: false, message: "Player not found" };
343 const prompt = this.state.prompts.find(p => p.id === prompt_id);
345 return { valid: false, message: "Prompt not found" };
347 if (prompt !== this.state.active_prompt)
348 return { valid: false, message: "Prompt no longer active" };
350 if (this.judging_idle_timer) {
351 clearTimeout(this.judging_idle_timer);
352 this.judging_idle_timer = 0;
354 if (! this.state.judging_idle) {
355 this.judging_idle_timer = setTimeout(() => {
356 this.state.judging_idle = true;
357 this.broadcast_event_object('judging-idle', true);
358 }, PHASE_IDLE_TIMEOUT * 1000);
361 if (this.judging_start_time_ms === 0)
362 this.judging_start_time_ms = Date.now();
364 /* Notify all players this this player is actively judging. */
365 this.state.players_judging.add(player.name);
366 this.broadcast_event_object('player-judging', player.name);
368 return { valid: true };
371 /* Returns true if vote toggled, false for player or prompt not found */
372 toggle_end_judging(prompt_id, session_id) {
373 const player = this.players_by_session[session_id];
375 const prompt = this.state.prompts.find(p => p.id === prompt_id);
376 if (! prompt || ! player)
379 if (this.state.end_judging.has(player.name)) {
380 this.state.end_judging.delete(player.name);
381 this.broadcast_event_object('unvote-end-judging', player.name);
383 this.state.end_judging.add(player.name);
384 this.broadcast_event_object('vote-end-judging', player.name);
391 return word.trim().toLowerCase();
395 const word_submitters = {};
397 /* Perform a (non-strict) majority ruling on equivalencies,
398 * dropping all that didn't get enough votes. */
399 const quorum = Math.floor((this.players.length + 1)/2);
400 const agreed_equivalencies = Object.values(this.equivalencies).filter(
401 eq => eq.count >= quorum);
403 /* And with that agreed set of equivalencies, construct the full
405 const word_maps = {};
407 for (let e of agreed_equivalencies) {
408 const word0_canon = this.canonize(e.words[0]);
409 const word1_canon = this.canonize(e.words[1]);
410 let group = word_maps[word0_canon];
412 group = word_maps[word1_canon];
414 group = { words: [], players: new Set()};
416 if (! word_maps[word0_canon]) {
417 word_maps[word0_canon] = group;
418 group.words.push(e.words[0]);
421 if (! word_maps[word1_canon]) {
422 word_maps[word1_canon] = group;
423 group.words.push(e.words[1]);
427 /* Now go through answers from each player and add the player
428 * to the set corresponding to each word group. */
429 for (let a of this.answers) {
430 for (let word of a.answers) {
431 const word_canon = this.canonize(word);
432 /* If there's no group yet, this is a singleton word. */
433 if (word_maps[word_canon]) {
434 word_maps[word_canon].players.add(a.player);
436 const group = { words: [word], players: new Set() };
437 group.players.add(a.player);
438 word_maps[word_canon] = group;
443 /* Now that we've assigned the players to these word maps, we now
444 * want to collapse the groups down to a single array of
447 * The difference between "word_maps" and "word_groups" is that
448 * the former has a property for every word that maps to a group,
449 * (so if you iterate over the keys you will see the same group
450 * multiple times). In contrast, iterating over"word_groups" will
451 * have you visit each group only once. */
452 const word_groups = Object.entries(word_maps).filter(
453 entry => entry[0] === this.canonize(entry[1].words[0]))
454 .map(entry => entry[1]);
456 /* Now, go through each word group and assign the scores out to
457 * the corresponding players.
459 * Note: We do this by going through the word groups, (as opposed
460 * to the list of words from the players again), specifically to
461 * avoid giving a player points for a wrod group twice (in the
462 * case where a player submits two different words that the group
463 * ends up judging as equivalent).
465 this.players.forEach(p => p.round_score = 0);
466 for (let group of word_groups) {
467 group.players.forEach(p => p.round_score += group.players.size);
470 const scores = this.players.map(p => {
477 scores.sort((a,b) => {
478 return b.score - a.score;
481 /* Put the word groups into a form the client can consume.
483 const words_submitted = word_groups.map(
486 word: group.words.join('/'),
487 players: Array.from(group.players).map(p => p.name)
492 words_submitted.sort((a,b) => {
493 return b.players.length - a.players.length;
496 /* Put this round's scores into the game state object so it will
497 * be sent to any new clients that join. */
498 this.state.scores = {
500 words: words_submitted
503 /* And broadcast the scores to all connected clients. */
504 this.broadcast_event_object('scores', this.state.scores);
508 Empathy.router = express.Router();
509 const router = Empathy.router;
512 constructor(id, items, prompt) {
515 this.prompt = prompt;
519 toggle_vote(player_name) {
520 if (this.votes.find(v => v === player_name))
521 this.votes = this.votes.filter(v => v !== player_name);
523 this.votes.push(player_name);
527 router.post('/prompts', (request, response) => {
528 const game = request.game;
530 const result = game.add_prompt(request.body.items, request.body.prompt);
532 response.json(result);
535 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
536 const game = request.game;
537 const prompt_id = parseInt(request.params.prompt_id, 10);
539 if (game.toggle_vote(prompt_id, request.session.id))
542 response.sendStatus(404);
545 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
546 const game = request.game;
547 const prompt_id = parseInt(request.params.prompt_id, 10);
549 if (game.start(prompt_id))
552 response.sendStatus(404);
555 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
556 const game = request.game;
557 const prompt_id = parseInt(request.params.prompt_id, 10);
559 const result = game.receive_answer(prompt_id,
561 request.body.answers);
562 response.json(result);
564 /* If every registered player has answered, then there's no need to
565 * wait for anything else. */
566 if (game.state.players_answered.length >= game.players.length)
567 game.perform_judging();
570 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
571 const game = request.game;
572 const prompt_id = parseInt(request.params.prompt_id, 10);
574 const result = game.receive_answering(prompt_id,
576 response.json(result);
579 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
580 const game = request.game;
581 const prompt_id = parseInt(request.params.prompt_id, 10);
583 if (game.toggle_end_answers(prompt_id, request.session.id))
586 response.sendStatus(404);
588 /* The majority rule here includes all players that have answered as
589 * well as all that have started typing. */
590 const players_involved = (game.state.players_answered.length +
591 game.state.players_answering.size);
593 if (game.state.end_answers.size > players_involved / 2)
594 game.perform_judging();
597 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
598 const game = request.game;
599 const prompt_id = parseInt(request.params.prompt_id, 10);
601 const result = game.receive_judged(prompt_id,
603 request.body.word_groups);
604 response.json(result);
606 /* If every registered player has judged, then there's no need to
607 * wait for anything else. */
608 if (game.state.players_judged.length >= game.players.length)
609 game.compute_scores();
612 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
613 const game = request.game;
614 const prompt_id = parseInt(request.params.prompt_id, 10);
616 const result = game.receive_judging(prompt_id,
618 response.json(result);
621 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
622 const game = request.game;
623 const prompt_id = parseInt(request.params.prompt_id, 10);
625 if (game.toggle_end_judging(prompt_id, request.session.id))
628 response.sendStatus(404);
630 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
631 game.compute_scores();
634 router.post('/reset', (request, response) => {
635 const game = request.game;
643 identifier: "empathy",
646 exports.Game = Empathy;