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 = 10;
24 class Empathy extends Game {
31 players_answering: new Set(),
32 answering_idle: false,
33 end_answers: new Set(),
36 players_judging: new Set(),
37 end_judging: new Set(),
41 this.answering_idle_timer = 0;
42 this.answering_start_time_ms = 0;
43 this.next_prompt_id = 1;
44 this.equivalencies = {};
49 /* Before closing out the current round, we accumulate that score
50 * for each player into their runnning total. */
51 for (let score of this.state.scores.scores) {
52 const player = this.players.find(p => p.name === score.player);
54 player.score += score.score;
56 player.score = score.score;
58 /* And broadcast that new score out. */
59 this.broadcast_event('player-update', player.info_json());
62 /* Now that we're done with the active prompt, we remove it from
63 * the list of prompts and also remove any prompts that received
64 * no votes. This keeps the list of prompts clean.
66 const active_id = this.state.active_prompt.id;
68 this.state.prompts.filter(
69 p => p.id !== active_id && p.votes.length > 0
72 this.state.active_prompt = null;
73 this.state.players_answered = [];
74 this.state.players_answering = new Set();
75 this.state.answering_idle = false;
76 this.state.end_answers = new Set();
77 this.state.ambiguities = null;
78 this.state.players_judged = [];
79 this.state.players_judging = new Set();
80 this.state.end_judging = new Set();
81 this.state.scores = null;
84 if (this.answering_idle_timer) {
85 clearTimeout(this.answering_idle_timer);
87 this.answering_idle_timer = 0;
88 this.answering_start_time_ms = 0;
89 this.equivalencies = {};
91 this.broadcast_event_object('game-state', this.state);
94 add_prompt(items, prompt_string) {
95 if (items > MAX_PROMPT_ITEMS)
98 message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
101 const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
102 this.next_prompt_id++;
104 this.state.prompts.push(prompt);
106 this.broadcast_event_object('prompt', prompt);
114 /* Returns true if vote toggled, false for player or prompt not found */
115 toggle_vote(prompt_id, session_id) {
116 const player = this.players_by_session[session_id];
118 const prompt = this.state.prompts.find(p => p.id === prompt_id);
119 if (! prompt || ! player)
122 prompt.toggle_vote(player.name);
124 this.broadcast_event_object('prompt', prompt);
129 /* Returns true on success, false for prompt not found. */
131 const prompt = this.state.prompts.find(p => p.id === prompt_id);
135 /* Ignore any start request that comes in while a prompt is
136 * already being played. */
137 if (this.state.active_prompt)
140 this.state.active_prompt = prompt;
142 this.broadcast_event_object('start', prompt);
147 receive_answer(prompt_id, session_id, answers) {
148 const player = this.players_by_session[session_id];
150 return { valid: false, message: "Player not found" };
152 const prompt = this.state.prompts.find(p => p.id === prompt_id);
154 return { valid: false, message: "Prompt not found" };
156 if (prompt !== this.state.active_prompt)
157 return { valid: false, message: "Prompt no longer active" };
159 /* Save the complete answers for our own use later. */
165 /* Update state (to be sent out to any future clients) */
166 this.state.players_answering.delete(player.name);
167 this.state.players_answered.push(player.name);
169 /* And notify all players that this player has answered. */
170 this.broadcast_event_object('player-answered', player.name);
172 /* If no players are left in the answering list then we don't need
173 * to wait for the answering_idle_timer to fire, because a person
174 * who isn't there obviously can't be typing. So we can broadcast
175 * the idle event right away. Note that we do this only if the
176 * answering phase has been going for a while to avoid the case of
177 * the first player being super fast and emptying the
178 * players_answering list before anyone else even got in.
180 if (this.state.players_answering.size === 0 &&
181 ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
183 this.broadcast_event_object('answering-idle', true);
186 return { valid: true };
189 receive_answering(prompt_id, session_id) {
190 const player = this.players_by_session[session_id];
192 return { valid: false, message: "Player not found" };
194 const prompt = this.state.prompts.find(p => p.id === prompt_id);
196 return { valid: false, message: "Prompt not found" };
198 if (prompt !== this.state.active_prompt)
199 return { valid: false, message: "Prompt no longer active" };
201 if (this.answering_idle_timer) {
202 clearTimeout(this.answering_idle_timer);
204 if (! this.state.answering_idle) {
205 this.answering_idle_timer = setTimeout(() => {
206 this.state_answering_idle = true;
207 this.broadcast_event_object('answering-idle', true);
208 }, PHASE_IDLE_TIMEOUT * 1000);
211 if (this.answering_start_time_ms === 0)
212 this.answering_start_time_ms = Date.now();
214 /* Notify all players that this player is actively answering. */
215 this.state.players_answering.add(player.name);
216 this.broadcast_event_object('player-answering', player.name);
218 return { valid: true };
221 /* Returns true if vote toggled, false for player or prompt not found */
222 toggle_end_answers(prompt_id, session_id) {
223 const player = this.players_by_session[session_id];
225 const prompt = this.state.prompts.find(p => p.id === prompt_id);
226 if (! prompt || ! player)
229 if (this.state.end_answers.has(player.name)) {
230 this.state.end_answers.delete(player.name);
231 this.broadcast_event_object('unvote-end-answers', player.name);
233 this.state.end_answers.add(player.name);
234 this.broadcast_event_object('vote-end-answers', player.name);
243 for (let a of this.answers) {
244 for (let word of a.answers) {
245 const key = this.canonize(word);
246 word_map[key] = word;
250 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
251 return a.toLowerCase().localeCompare(b.toLowerCase());
254 this.broadcast_event_object('ambiguities', this.state.ambiguities);
257 receive_judged(prompt_id, session_id, word_groups) {
258 const player = this.players_by_session[session_id];
260 return { valid: false, message: "Player not found" };
262 const prompt = this.state.prompts.find(p => p.id === prompt_id);
264 return { valid: false, message: "Prompt not found" };
266 if (prompt !== this.state.active_prompt)
267 return { valid: false, message: "Prompt no longer active" };
269 /* Each player submits some number of groups of answers that
270 * should be considered equivalent. The server expands that into
271 * the set of pair-wise equivalencies that are expressed. The
272 * reason for that is so that the server can determine which
273 * pair-wise equivalencies have majority support.
275 for (let group of word_groups) {
277 for (let i = 0; i < group.length - 1; i++) {
278 for (let j = i + 1; j < group.length; j++) {
279 let eq = [group[i], group[j]];
281 /* Put the two words into a reliable order so that we don't
282 * miss a pair of equivalent equivalencies just because they
283 * happen to be in the opposite order. */
284 if (eq[0].localeCompare(eq[1]) > 0) {
285 eq = [group[j], group[i]];
288 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
290 const exist = this.equivalencies[key];
294 this.equivalencies[key] = {
304 /* Update state (to be sent out to any future clients) */
305 this.state.players_judging.delete(player.name);
306 this.state.players_judged.push(player.name);
308 /* And notify all players this this player has judged. */
309 this.broadcast_event_object('player-judged', player.name);
311 return { valid: true };
314 receive_judging(prompt_id, session_id) {
315 const player = this.players_by_session[session_id];
317 return { valid: false, message: "Player not found" };
319 const prompt = this.state.prompts.find(p => p.id === prompt_id);
321 return { valid: false, message: "Prompt not found" };
323 if (prompt !== this.state.active_prompt)
324 return { valid: false, message: "Prompt no longer active" };
326 /* Notify all players this this player is actively judging. */
327 this.state.players_judging.add(player.name);
328 this.broadcast_event_object('player-judging', player.name);
330 return { valid: true };
333 /* Returns true if vote toggled, false for player or prompt not found */
334 toggle_end_judging(prompt_id, session_id) {
335 const player = this.players_by_session[session_id];
337 const prompt = this.state.prompts.find(p => p.id === prompt_id);
338 if (! prompt || ! player)
341 if (this.state.end_judging.has(player.name)) {
342 this.state.end_judging.delete(player.name);
343 this.broadcast_event_object('unvote-end-judging', player.name);
345 this.state.end_judging.add(player.name);
346 this.broadcast_event_object('vote-end-judging', player.name);
353 return word.trim().toLowerCase();
357 const word_submitters = {};
359 /* Perform a (non-strict) majority ruling on equivalencies,
360 * dropping all that didn't get enough votes. */
361 const quorum = Math.floor((this.players.length + 1)/2);
362 const agreed_equivalencies = Object.values(this.equivalencies).filter(
363 eq => eq.count >= quorum);
365 /* And with that agreed set of equivalencies, construct the full
367 const word_maps = {};
369 for (let e of agreed_equivalencies) {
370 const word0_canon = this.canonize(e.words[0]);
371 const word1_canon = this.canonize(e.words[1]);
372 let group = word_maps[word0_canon];
374 group = word_maps[word1_canon];
376 group = { words: [], players: new Set()};
378 if (! word_maps[word0_canon]) {
379 word_maps[word0_canon] = group;
380 group.words.push(e.words[0]);
383 if (! word_maps[word1_canon]) {
384 word_maps[word1_canon] = group;
385 group.words.push(e.words[1]);
389 /* Now go through answers from each player and add the player
390 * to the set corresponding to each word group. */
391 for (let a of this.answers) {
392 for (let word of a.answers) {
393 const word_canon = this.canonize(word);
394 /* If there's no group yet, this is a singleton word. */
395 if (word_maps[word_canon]) {
396 word_maps[word_canon].players.add(a.player);
398 const group = { words: [word], players: new Set() };
399 group.players.add(a.player);
400 word_maps[word_canon] = group;
405 /* Now that we've assigned the players to these word maps, we now
406 * want to collapse the groups down to a single array of
409 * The difference between "word_maps" and "word_groups" is that
410 * the former has a property for every word that maps to a group,
411 * (so if you iterate over the keys you will see the same group
412 * multiple times). In contrast, iterating over"word_groups" will
413 * have you visit each group only once. */
414 const word_groups = Object.entries(word_maps).filter(
415 entry => entry[0] === this.canonize(entry[1].words[0]))
416 .map(entry => entry[1]);
418 /* Now, go through each word group and assign the scores out to
419 * the corresponding players.
421 * Note: We do this by going through the word groups, (as opposed
422 * to the list of words from the players again), specifically to
423 * avoid giving a player points for a wrod group twice (in the
424 * case where a player submits two different words that the group
425 * ends up judging as equivalent).
427 this.players.forEach(p => p.round_score = 0);
428 for (let group of word_groups) {
429 group.players.forEach(p => p.round_score += group.players.size);
432 const scores = this.players.map(p => {
439 scores.sort((a,b) => {
440 return b.score - a.score;
443 /* Put the word groups into a form the client can consume.
445 const words_submitted = word_groups.map(
448 word: group.words.join('/'),
449 players: Array.from(group.players).map(p => p.name)
454 words_submitted.sort((a,b) => {
455 return b.players.length - a.players.length;
458 /* Put this round's scores into the game state object so it will
459 * be sent to any new clients that join. */
460 this.state.scores = {
462 words: words_submitted
465 /* And broadcast the scores to all connected clients. */
466 this.broadcast_event_object('scores', this.state.scores);
470 Empathy.router = express.Router();
471 const router = Empathy.router;
474 constructor(id, items, prompt) {
477 this.prompt = prompt;
481 toggle_vote(player_name) {
482 if (this.votes.find(v => v === player_name))
483 this.votes = this.votes.filter(v => v !== player_name);
485 this.votes.push(player_name);
489 router.post('/prompts', (request, response) => {
490 const game = request.game;
492 const result = game.add_prompt(request.body.items, request.body.prompt);
494 response.json(result);
497 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
498 const game = request.game;
499 const prompt_id = parseInt(request.params.prompt_id, 10);
501 if (game.toggle_vote(prompt_id, request.session.id))
504 response.sendStatus(404);
507 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
508 const game = request.game;
509 const prompt_id = parseInt(request.params.prompt_id, 10);
511 if (game.start(prompt_id))
514 response.sendStatus(404);
517 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
518 const game = request.game;
519 const prompt_id = parseInt(request.params.prompt_id, 10);
521 const result = game.receive_answer(prompt_id,
523 request.body.answers);
524 response.json(result);
526 /* If every registered player has answered, then there's no need to
527 * wait for anything else. */
528 if (game.state.players_answered.length >= game.players.length)
529 game.perform_judging();
532 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
533 const game = request.game;
534 const prompt_id = parseInt(request.params.prompt_id, 10);
536 const result = game.receive_answering(prompt_id,
538 response.json(result);
541 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
542 const game = request.game;
543 const prompt_id = parseInt(request.params.prompt_id, 10);
545 if (game.toggle_end_answers(prompt_id, request.session.id))
548 response.sendStatus(404);
550 /* The majority rule here includes all players that have answered as
551 * well as all that have started typing. */
552 const players_involved = (game.state.players_answered.length +
553 game.state.players_answering.size);
555 if (game.state.end_answers.size > players_involved / 2)
556 game.perform_judging();
559 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
560 const game = request.game;
561 const prompt_id = parseInt(request.params.prompt_id, 10);
563 const result = game.receive_judged(prompt_id,
565 request.body.word_groups);
566 response.json(result);
568 /* If every registered player has judged, then there's no need to
569 * wait for anything else. */
570 if (game.state.players_judged.length >= game.players.length)
571 game.compute_scores();
574 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
575 const game = request.game;
576 const prompt_id = parseInt(request.params.prompt_id, 10);
578 const result = game.receive_judging(prompt_id,
580 response.json(result);
583 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
584 const game = request.game;
585 const prompt_id = parseInt(request.params.prompt_id, 10);
587 if (game.toggle_end_judging(prompt_id, request.session.id))
590 response.sendStatus(404);
592 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
593 game.compute_scores();
596 router.post('/reset', (request, response) => {
597 const game = request.game;
605 identifier: "empathy",
608 exports.Game = Empathy;