]> git.cworth.org Git - lmno-server/blob - empathy.js
Adapt the idle treatment from the answering phase to the judging phase
[lmno-server] / empathy.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 const MAX_PROMPT_ITEMS = 20;
5
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.
10  *
11  * Specified in seconds
12  */
13 const PHASE_MINIMUM_TIME = 30;
14
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.
19  *
20  * Specified in seconds
21  */
22 const PHASE_IDLE_TIMEOUT = 30;
23
24 class Empathy extends Game {
25   constructor(id) {
26     super(id);
27     this.state = {
28       prompts: [],
29       active_prompt: null,
30       players_answered: [],
31       players_answering: new Set(),
32       answering_idle: false,
33       end_answers: new Set(),
34       ambiguities: null,
35       players_judged: [],
36       players_judging: new Set(),
37       judging_idle: false,
38       end_judging: new Set(),
39       scores: null
40     };
41     this.answers = [];
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 = {};
48   }
49
50   reset() {
51
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);
56       if (player.score)
57         player.score += score.score;
58       else
59         player.score = score.score;
60
61       /* And broadcast that new score out. */
62       this.broadcast_event('player-update', player.info_json());
63     }
64
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.
68      */
69     const active_id = this.state.active_prompt.id;
70     this.state.prompts =
71       this.state.prompts.filter(
72         p => p.id !== active_id && p.votes.length > 0
73       );
74
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;
86
87     this.answers = [];
88     if (this.answering_idle_timer) {
89       clearTimeout(this.answering_idle_timer);
90     }
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);
95     }
96     this.judging_idle_timer = 0;
97     this.judging_start_time_ms = 0;
98     this.equivalencies = {};
99
100     this.broadcast_event_object('game-state', this.state);
101   }
102
103   add_prompt(items, prompt_string) {
104     if (items > MAX_PROMPT_ITEMS)
105       return {
106         valid: false,
107         message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
108       };
109
110     const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
111     this.next_prompt_id++;
112
113     this.state.prompts.push(prompt);
114
115     this.broadcast_event_object('prompt', prompt);
116
117     return {
118       valid: true,
119       id: prompt.id
120     };
121   }
122
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];
126
127     const prompt = this.state.prompts.find(p => p.id === prompt_id);
128     if (! prompt || ! player)
129       return false;
130
131     prompt.toggle_vote(player.name);
132
133     this.broadcast_event_object('prompt', prompt);
134
135     return true;
136   }
137
138   /* Returns true on success, false for prompt not found. */
139   start(prompt_id) {
140     const prompt = this.state.prompts.find(p => p.id === prompt_id);
141     if (! prompt)
142       return false;
143
144     /* Ignore any start request that comes in while a prompt is
145      * already being played. */
146     if (this.state.active_prompt)
147       return false;
148
149     this.state.active_prompt = prompt;
150
151     this.broadcast_event_object('start', prompt);
152
153     return true;
154   }
155
156   receive_answer(prompt_id, session_id, answers) {
157     const player = this.players_by_session[session_id];
158     if (! player)
159       return { valid: false, message: "Player not found" };
160
161     const prompt = this.state.prompts.find(p => p.id === prompt_id);
162     if (! prompt)
163       return { valid: false, message: "Prompt not found" };
164
165     if (prompt !== this.state.active_prompt)
166       return { valid: false, message: "Prompt no longer active" };
167
168     /* Save the complete answers for our own use later. */
169     this.answers.push({
170       player: player,
171       answers: answers
172     });
173
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);
177
178     /* And notify all players that this player has answered. */
179     this.broadcast_event_object('player-answered', player.name);
180
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.
188      */
189     if (this.state.players_answering.size === 0 &&
190         ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
191     {
192       this.broadcast_event_object('answering-idle', true);
193     }
194
195     return { valid: true };
196   }
197
198   receive_answering(prompt_id, session_id) {
199     const player = this.players_by_session[session_id];
200     if (! player)
201       return { valid: false, message: "Player not found" };
202
203     const prompt = this.state.prompts.find(p => p.id === prompt_id);
204     if (! prompt)
205       return { valid: false, message: "Prompt not found" };
206
207     if (prompt !== this.state.active_prompt)
208       return { valid: false, message: "Prompt no longer active" };
209
210     if (this.answering_idle_timer) {
211       clearTimeout(this.answering_idle_timer);
212       this.ansering_idle_timer = 0;
213     }
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);
219     }
220
221     if (this.answering_start_time_ms === 0)
222       this.answering_start_time_ms = Date.now();
223
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);
227
228     return { valid: true };
229   }
230
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];
234
235     const prompt = this.state.prompts.find(p => p.id === prompt_id);
236     if (! prompt || ! player)
237       return false;
238
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);
242     } else {
243       this.state.end_answers.add(player.name);
244       this.broadcast_event_object('vote-end-answers', player.name);
245     }
246
247     return true;
248   }
249
250   perform_judging() {
251     const word_map = {};
252
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;
257       }
258     }
259
260     this.state.ambiguities = Object.values(word_map).sort((a,b) => {
261       return a.toLowerCase().localeCompare(b.toLowerCase());
262     });
263
264     this.broadcast_event_object('ambiguities', this.state.ambiguities);
265   }
266
267   receive_judged(prompt_id, session_id, word_groups) {
268     const player = this.players_by_session[session_id];
269     if (! player)
270       return { valid: false, message: "Player not found" };
271
272     const prompt = this.state.prompts.find(p => p.id === prompt_id);
273     if (! prompt)
274       return { valid: false, message: "Prompt not found" };
275
276     if (prompt !== this.state.active_prompt)
277       return { valid: false, message: "Prompt no longer active" };
278
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.
284      */
285     for (let group of word_groups) {
286
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]];
290
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]];
296           }
297
298           const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
299
300           const exist = this.equivalencies[key];
301           if (exist) {
302             exist.count++;
303           } else {
304             this.equivalencies[key] = {
305               count: 1,
306               words: eq
307             };
308           }
309
310         }
311       }
312     }
313
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);
317
318     /* And notify all players this this player has judged. */
319     this.broadcast_event_object('player-judged', player.name);
320
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.
328      */
329     if (this.state.players_judging.size === 0 &&
330         ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
331     {
332       this.broadcast_event_object('judging-idle', true);
333     }
334
335     return { valid: true };
336   }
337
338   receive_judging(prompt_id, session_id) {
339     const player = this.players_by_session[session_id];
340     if (! player)
341       return { valid: false, message: "Player not found" };
342
343     const prompt = this.state.prompts.find(p => p.id === prompt_id);
344     if (! prompt)
345       return { valid: false, message: "Prompt not found" };
346
347     if (prompt !== this.state.active_prompt)
348       return { valid: false, message: "Prompt no longer active" };
349
350     if (this.judging_idle_timer) {
351       clearTimeout(this.judging_idle_timer);
352       this.judging_idle_timer = 0;
353     }
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);
359     }
360
361     if (this.judging_start_time_ms === 0)
362       this.judging_start_time_ms = Date.now();
363
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);
367
368     return { valid: true };
369   }
370
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];
374
375     const prompt = this.state.prompts.find(p => p.id === prompt_id);
376     if (! prompt || ! player)
377       return false;
378
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);
382     } else {
383       this.state.end_judging.add(player.name);
384       this.broadcast_event_object('vote-end-judging', player.name);
385     }
386
387     return true;
388   }
389
390   canonize(word) {
391     return word.trim().toLowerCase();
392   }
393
394   compute_scores() {
395     const word_submitters = {};
396
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);
402
403     /* And with that agreed set of equivalencies, construct the full
404      * groups. */
405     const word_maps = {};
406
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];
411       if (! group)
412         group = word_maps[word1_canon];
413       if (! group)
414         group = { words: [], players: new Set()};
415
416       if (! word_maps[word0_canon]) {
417         word_maps[word0_canon] = group;
418         group.words.push(e.words[0]);
419       }
420
421       if (! word_maps[word1_canon]) {
422         word_maps[word1_canon] = group;
423         group.words.push(e.words[1]);
424       }
425     }
426
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);
435         } else {
436           const group = { words: [word], players: new Set() };
437           group.players.add(a.player);
438           word_maps[word_canon] = group;
439         }
440       }
441     }
442
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
445      * word_groups.
446      *
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]);
455
456     /* Now, go through each word group and assign the scores out to
457      * the corresponding players.
458      *
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).
464      */
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);
468     }
469
470     const scores = this.players.map(p => {
471       return {
472         player: p.name,
473         score: p.round_score
474       };
475     });
476
477     scores.sort((a,b) => {
478       return b.score - a.score;
479     });
480
481     /* Put the word groups into a form the client can consume.
482      */
483     const words_submitted = word_groups.map(
484       group => {
485         return {
486           word: group.words.join('/'),
487           players: Array.from(group.players).map(p => p.name)
488         };
489       }
490     );
491
492     words_submitted.sort((a,b) => {
493       return b.players.length - a.players.length;
494     });
495
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 = {
499       scores: scores,
500       words: words_submitted
501     };
502
503     /* And broadcast the scores to all connected clients. */
504     this.broadcast_event_object('scores', this.state.scores);
505   }
506 }
507
508 Empathy.router = express.Router();
509 const router = Empathy.router;
510
511 class Prompt {
512   constructor(id, items, prompt) {
513     this.id = id;
514     this.items = items;
515     this.prompt = prompt;
516     this.votes = [];
517   }
518
519   toggle_vote(player_name) {
520     if (this.votes.find(v => v === player_name))
521       this.votes = this.votes.filter(v => v !== player_name);
522     else
523       this.votes.push(player_name);
524   }
525 }
526
527 router.post('/prompts', (request, response) => {
528   const game = request.game;
529
530   const result = game.add_prompt(request.body.items, request.body.prompt);
531
532   response.json(result);
533 });
534
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);
538
539   if (game.toggle_vote(prompt_id, request.session.id))
540     response.send('');
541   else
542     response.sendStatus(404);
543 });
544
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);
548
549   if (game.start(prompt_id))
550     response.send('');
551   else
552     response.sendStatus(404);
553 });
554
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);
558
559   const result = game.receive_answer(prompt_id,
560                                      request.session.id,
561                                      request.body.answers);
562   response.json(result);
563
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();
568 });
569
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);
573
574   const result = game.receive_answering(prompt_id,
575                                         request.session.id);
576   response.json(result);
577 });
578
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);
582
583   if (game.toggle_end_answers(prompt_id, request.session.id))
584     response.send('');
585   else
586     response.sendStatus(404);
587
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);
592
593   if (game.state.end_answers.size > players_involved / 2)
594     game.perform_judging();
595 });
596
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);
600
601   const result = game.receive_judged(prompt_id,
602                                      request.session.id,
603                                      request.body.word_groups);
604   response.json(result);
605
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();
610 });
611
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);
615
616   const result = game.receive_judging(prompt_id,
617                                       request.session.id);
618   response.json(result);
619 });
620
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);
624
625   if (game.toggle_end_judging(prompt_id, request.session.id))
626     response.send('');
627   else
628     response.sendStatus(404);
629
630   if (game.state.end_judging.size > (game.state.players_answered.length / 2))
631     game.compute_scores();
632 });
633
634 router.post('/reset', (request, response) => {
635   const game = request.game;
636   game.reset();
637
638   response.send('');
639 });
640
641 Empathy.meta = {
642   name: "Empathy",
643   identifier: "empathy",
644 };
645
646 exports.Game = Empathy;