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(),
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);
203 this.ansering_idle_timer = 0;
205 if (! this.state.answering_idle) {
206 this.answering_idle_timer = setTimeout(() => {
207 this.state.answering_idle = true;
208 this.broadcast_event_object('answering-idle', true);
209 }, PHASE_IDLE_TIMEOUT * 1000);
212 if (this.answering_start_time_ms === 0)
213 this.answering_start_time_ms = Date.now();
215 /* Notify all players that this player is actively answering. */
216 this.state.players_answering.add(player.name);
217 this.broadcast_event_object('player-answering', player.name);
219 return { valid: true };
222 /* Returns true if vote toggled, false for player or prompt not found */
223 toggle_end_answers(prompt_id, session_id) {
224 const player = this.players_by_session[session_id];
226 const prompt = this.state.prompts.find(p => p.id === prompt_id);
227 if (! prompt || ! player)
230 if (this.state.end_answers.has(player.name)) {
231 this.state.end_answers.delete(player.name);
232 this.broadcast_event_object('unvote-end-answers', player.name);
234 this.state.end_answers.add(player.name);
235 this.broadcast_event_object('vote-end-answers', player.name);
244 for (let a of this.answers) {
245 for (let word of a.answers) {
246 const key = this.canonize(word);
247 word_map[key] = word;
251 this.state.ambiguities = Object.values(word_map).sort((a,b) => {
252 return a.toLowerCase().localeCompare(b.toLowerCase());
255 this.broadcast_event_object('ambiguities', this.state.ambiguities);
258 receive_judged(prompt_id, session_id, word_groups) {
259 const player = this.players_by_session[session_id];
261 return { valid: false, message: "Player not found" };
263 const prompt = this.state.prompts.find(p => p.id === prompt_id);
265 return { valid: false, message: "Prompt not found" };
267 if (prompt !== this.state.active_prompt)
268 return { valid: false, message: "Prompt no longer active" };
270 /* Each player submits some number of groups of answers that
271 * should be considered equivalent. The server expands that into
272 * the set of pair-wise equivalencies that are expressed. The
273 * reason for that is so that the server can determine which
274 * pair-wise equivalencies have majority support.
276 for (let group of word_groups) {
278 for (let i = 0; i < group.length - 1; i++) {
279 for (let j = i + 1; j < group.length; j++) {
280 let eq = [group[i], group[j]];
282 /* Put the two words into a reliable order so that we don't
283 * miss a pair of equivalent equivalencies just because they
284 * happen to be in the opposite order. */
285 if (eq[0].localeCompare(eq[1]) > 0) {
286 eq = [group[j], group[i]];
289 const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
291 const exist = this.equivalencies[key];
295 this.equivalencies[key] = {
305 /* Update state (to be sent out to any future clients) */
306 this.state.players_judging.delete(player.name);
307 this.state.players_judged.push(player.name);
309 /* And notify all players this this player has judged. */
310 this.broadcast_event_object('player-judged', player.name);
312 return { valid: true };
315 receive_judging(prompt_id, session_id) {
316 const player = this.players_by_session[session_id];
318 return { valid: false, message: "Player not found" };
320 const prompt = this.state.prompts.find(p => p.id === prompt_id);
322 return { valid: false, message: "Prompt not found" };
324 if (prompt !== this.state.active_prompt)
325 return { valid: false, message: "Prompt no longer active" };
327 /* Notify all players this this player is actively judging. */
328 this.state.players_judging.add(player.name);
329 this.broadcast_event_object('player-judging', player.name);
331 return { valid: true };
334 /* Returns true if vote toggled, false for player or prompt not found */
335 toggle_end_judging(prompt_id, session_id) {
336 const player = this.players_by_session[session_id];
338 const prompt = this.state.prompts.find(p => p.id === prompt_id);
339 if (! prompt || ! player)
342 if (this.state.end_judging.has(player.name)) {
343 this.state.end_judging.delete(player.name);
344 this.broadcast_event_object('unvote-end-judging', player.name);
346 this.state.end_judging.add(player.name);
347 this.broadcast_event_object('vote-end-judging', player.name);
354 return word.trim().toLowerCase();
358 const word_submitters = {};
360 /* Perform a (non-strict) majority ruling on equivalencies,
361 * dropping all that didn't get enough votes. */
362 const quorum = Math.floor((this.players.length + 1)/2);
363 const agreed_equivalencies = Object.values(this.equivalencies).filter(
364 eq => eq.count >= quorum);
366 /* And with that agreed set of equivalencies, construct the full
368 const word_maps = {};
370 for (let e of agreed_equivalencies) {
371 const word0_canon = this.canonize(e.words[0]);
372 const word1_canon = this.canonize(e.words[1]);
373 let group = word_maps[word0_canon];
375 group = word_maps[word1_canon];
377 group = { words: [], players: new Set()};
379 if (! word_maps[word0_canon]) {
380 word_maps[word0_canon] = group;
381 group.words.push(e.words[0]);
384 if (! word_maps[word1_canon]) {
385 word_maps[word1_canon] = group;
386 group.words.push(e.words[1]);
390 /* Now go through answers from each player and add the player
391 * to the set corresponding to each word group. */
392 for (let a of this.answers) {
393 for (let word of a.answers) {
394 const word_canon = this.canonize(word);
395 /* If there's no group yet, this is a singleton word. */
396 if (word_maps[word_canon]) {
397 word_maps[word_canon].players.add(a.player);
399 const group = { words: [word], players: new Set() };
400 group.players.add(a.player);
401 word_maps[word_canon] = group;
406 /* Now that we've assigned the players to these word maps, we now
407 * want to collapse the groups down to a single array of
410 * The difference between "word_maps" and "word_groups" is that
411 * the former has a property for every word that maps to a group,
412 * (so if you iterate over the keys you will see the same group
413 * multiple times). In contrast, iterating over"word_groups" will
414 * have you visit each group only once. */
415 const word_groups = Object.entries(word_maps).filter(
416 entry => entry[0] === this.canonize(entry[1].words[0]))
417 .map(entry => entry[1]);
419 /* Now, go through each word group and assign the scores out to
420 * the corresponding players.
422 * Note: We do this by going through the word groups, (as opposed
423 * to the list of words from the players again), specifically to
424 * avoid giving a player points for a wrod group twice (in the
425 * case where a player submits two different words that the group
426 * ends up judging as equivalent).
428 this.players.forEach(p => p.round_score = 0);
429 for (let group of word_groups) {
430 group.players.forEach(p => p.round_score += group.players.size);
433 const scores = this.players.map(p => {
440 scores.sort((a,b) => {
441 return b.score - a.score;
444 /* Put the word groups into a form the client can consume.
446 const words_submitted = word_groups.map(
449 word: group.words.join('/'),
450 players: Array.from(group.players).map(p => p.name)
455 words_submitted.sort((a,b) => {
456 return b.players.length - a.players.length;
459 /* Put this round's scores into the game state object so it will
460 * be sent to any new clients that join. */
461 this.state.scores = {
463 words: words_submitted
466 /* And broadcast the scores to all connected clients. */
467 this.broadcast_event_object('scores', this.state.scores);
471 Empathy.router = express.Router();
472 const router = Empathy.router;
475 constructor(id, items, prompt) {
478 this.prompt = prompt;
482 toggle_vote(player_name) {
483 if (this.votes.find(v => v === player_name))
484 this.votes = this.votes.filter(v => v !== player_name);
486 this.votes.push(player_name);
490 router.post('/prompts', (request, response) => {
491 const game = request.game;
493 const result = game.add_prompt(request.body.items, request.body.prompt);
495 response.json(result);
498 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
499 const game = request.game;
500 const prompt_id = parseInt(request.params.prompt_id, 10);
502 if (game.toggle_vote(prompt_id, request.session.id))
505 response.sendStatus(404);
508 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
509 const game = request.game;
510 const prompt_id = parseInt(request.params.prompt_id, 10);
512 if (game.start(prompt_id))
515 response.sendStatus(404);
518 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
519 const game = request.game;
520 const prompt_id = parseInt(request.params.prompt_id, 10);
522 const result = game.receive_answer(prompt_id,
524 request.body.answers);
525 response.json(result);
527 /* If every registered player has answered, then there's no need to
528 * wait for anything else. */
529 if (game.state.players_answered.length >= game.players.length)
530 game.perform_judging();
533 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
534 const game = request.game;
535 const prompt_id = parseInt(request.params.prompt_id, 10);
537 const result = game.receive_answering(prompt_id,
539 response.json(result);
542 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
543 const game = request.game;
544 const prompt_id = parseInt(request.params.prompt_id, 10);
546 if (game.toggle_end_answers(prompt_id, request.session.id))
549 response.sendStatus(404);
551 /* The majority rule here includes all players that have answered as
552 * well as all that have started typing. */
553 const players_involved = (game.state.players_answered.length +
554 game.state.players_answering.size);
556 if (game.state.end_answers.size > players_involved / 2)
557 game.perform_judging();
560 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
561 const game = request.game;
562 const prompt_id = parseInt(request.params.prompt_id, 10);
564 const result = game.receive_judged(prompt_id,
566 request.body.word_groups);
567 response.json(result);
569 /* If every registered player has judged, then there's no need to
570 * wait for anything else. */
571 if (game.state.players_judged.length >= game.players.length)
572 game.compute_scores();
575 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
576 const game = request.game;
577 const prompt_id = parseInt(request.params.prompt_id, 10);
579 const result = game.receive_judging(prompt_id,
581 response.json(result);
584 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
585 const game = request.game;
586 const prompt_id = parseInt(request.params.prompt_id, 10);
588 if (game.toggle_end_judging(prompt_id, request.session.id))
591 response.sendStatus(404);
593 if (game.state.end_judging.size > (game.state.players_answered.length / 2))
594 game.compute_scores();
597 router.post('/reset', (request, response) => {
598 const game = request.game;
606 identifier: "empathy",
609 exports.Game = Empathy;