]> git.cworth.org Git - lmno-server/blob - empathy.js
Reset timer handle after clearTimeout
[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       end_judging: new Set(),
38       scores: null
39     };
40     this.answers = [];
41     this.answering_idle_timer = 0;
42     this.answering_start_time_ms = 0;
43     this.next_prompt_id = 1;
44     this.equivalencies = {};
45   }
46
47   reset() {
48
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);
53       if (player.score)
54         player.score += score.score;
55       else
56         player.score = score.score;
57
58       /* And broadcast that new score out. */
59       this.broadcast_event('player-update', player.info_json());
60     }
61
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.
65      */
66     const active_id = this.state.active_prompt.id;
67     this.state.prompts =
68       this.state.prompts.filter(
69         p => p.id !== active_id && p.votes.length > 0
70       );
71
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;
82
83     this.answers = [];
84     if (this.answering_idle_timer) {
85       clearTimeout(this.answering_idle_timer);
86     }
87     this.answering_idle_timer = 0;
88     this.answering_start_time_ms = 0;
89     this.equivalencies = {};
90
91     this.broadcast_event_object('game-state', this.state);
92   }
93
94   add_prompt(items, prompt_string) {
95     if (items > MAX_PROMPT_ITEMS)
96       return {
97         valid: false,
98         message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
99       };
100
101     const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
102     this.next_prompt_id++;
103
104     this.state.prompts.push(prompt);
105
106     this.broadcast_event_object('prompt', prompt);
107
108     return {
109       valid: true,
110       id: prompt.id
111     };
112   }
113
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];
117
118     const prompt = this.state.prompts.find(p => p.id === prompt_id);
119     if (! prompt || ! player)
120       return false;
121
122     prompt.toggle_vote(player.name);
123
124     this.broadcast_event_object('prompt', prompt);
125
126     return true;
127   }
128
129   /* Returns true on success, false for prompt not found. */
130   start(prompt_id) {
131     const prompt = this.state.prompts.find(p => p.id === prompt_id);
132     if (! prompt)
133       return false;
134
135     /* Ignore any start request that comes in while a prompt is
136      * already being played. */
137     if (this.state.active_prompt)
138       return false;
139
140     this.state.active_prompt = prompt;
141
142     this.broadcast_event_object('start', prompt);
143
144     return true;
145   }
146
147   receive_answer(prompt_id, session_id, answers) {
148     const player = this.players_by_session[session_id];
149     if (! player)
150       return { valid: false, message: "Player not found" };
151
152     const prompt = this.state.prompts.find(p => p.id === prompt_id);
153     if (! prompt)
154       return { valid: false, message: "Prompt not found" };
155
156     if (prompt !== this.state.active_prompt)
157       return { valid: false, message: "Prompt no longer active" };
158
159     /* Save the complete answers for our own use later. */
160     this.answers.push({
161       player: player,
162       answers: answers
163     });
164
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);
168
169     /* And notify all players that this player has answered. */
170     this.broadcast_event_object('player-answered', player.name);
171
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.
179      */
180     if (this.state.players_answering.size === 0 &&
181         ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
182     {
183       this.broadcast_event_object('answering-idle', true);
184     }
185
186     return { valid: true };
187   }
188
189   receive_answering(prompt_id, session_id) {
190     const player = this.players_by_session[session_id];
191     if (! player)
192       return { valid: false, message: "Player not found" };
193
194     const prompt = this.state.prompts.find(p => p.id === prompt_id);
195     if (! prompt)
196       return { valid: false, message: "Prompt not found" };
197
198     if (prompt !== this.state.active_prompt)
199       return { valid: false, message: "Prompt no longer active" };
200
201     if (this.answering_idle_timer) {
202       clearTimeout(this.answering_idle_timer);
203       this.ansering_idle_timer = 0;
204     }
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);
210     }
211
212     if (this.answering_start_time_ms === 0)
213       this.answering_start_time_ms = Date.now();
214
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);
218
219     return { valid: true };
220   }
221
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];
225
226     const prompt = this.state.prompts.find(p => p.id === prompt_id);
227     if (! prompt || ! player)
228       return false;
229
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);
233     } else {
234       this.state.end_answers.add(player.name);
235       this.broadcast_event_object('vote-end-answers', player.name);
236     }
237
238     return true;
239   }
240
241   perform_judging() {
242     const word_map = {};
243
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;
248       }
249     }
250
251     this.state.ambiguities = Object.values(word_map).sort((a,b) => {
252       return a.toLowerCase().localeCompare(b.toLowerCase());
253     });
254
255     this.broadcast_event_object('ambiguities', this.state.ambiguities);
256   }
257
258   receive_judged(prompt_id, session_id, word_groups) {
259     const player = this.players_by_session[session_id];
260     if (! player)
261       return { valid: false, message: "Player not found" };
262
263     const prompt = this.state.prompts.find(p => p.id === prompt_id);
264     if (! prompt)
265       return { valid: false, message: "Prompt not found" };
266
267     if (prompt !== this.state.active_prompt)
268       return { valid: false, message: "Prompt no longer active" };
269
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.
275      */
276     for (let group of word_groups) {
277
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]];
281
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]];
287           }
288
289           const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
290
291           const exist = this.equivalencies[key];
292           if (exist) {
293             exist.count++;
294           } else {
295             this.equivalencies[key] = {
296               count: 1,
297               words: eq
298             };
299           }
300
301         }
302       }
303     }
304
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);
308
309     /* And notify all players this this player has judged. */
310     this.broadcast_event_object('player-judged', player.name);
311
312     return { valid: true };
313   }
314
315   receive_judging(prompt_id, session_id) {
316     const player = this.players_by_session[session_id];
317     if (! player)
318       return { valid: false, message: "Player not found" };
319
320     const prompt = this.state.prompts.find(p => p.id === prompt_id);
321     if (! prompt)
322       return { valid: false, message: "Prompt not found" };
323
324     if (prompt !== this.state.active_prompt)
325       return { valid: false, message: "Prompt no longer active" };
326
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);
330
331     return { valid: true };
332   }
333
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];
337
338     const prompt = this.state.prompts.find(p => p.id === prompt_id);
339     if (! prompt || ! player)
340       return false;
341
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);
345     } else {
346       this.state.end_judging.add(player.name);
347       this.broadcast_event_object('vote-end-judging', player.name);
348     }
349
350     return true;
351   }
352
353   canonize(word) {
354     return word.trim().toLowerCase();
355   }
356
357   compute_scores() {
358     const word_submitters = {};
359
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);
365
366     /* And with that agreed set of equivalencies, construct the full
367      * groups. */
368     const word_maps = {};
369
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];
374       if (! group)
375         group = word_maps[word1_canon];
376       if (! group)
377         group = { words: [], players: new Set()};
378
379       if (! word_maps[word0_canon]) {
380         word_maps[word0_canon] = group;
381         group.words.push(e.words[0]);
382       }
383
384       if (! word_maps[word1_canon]) {
385         word_maps[word1_canon] = group;
386         group.words.push(e.words[1]);
387       }
388     }
389
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);
398         } else {
399           const group = { words: [word], players: new Set() };
400           group.players.add(a.player);
401           word_maps[word_canon] = group;
402         }
403       }
404     }
405
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
408      * word_groups.
409      *
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]);
418
419     /* Now, go through each word group and assign the scores out to
420      * the corresponding players.
421      *
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).
427      */
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);
431     }
432
433     const scores = this.players.map(p => {
434       return {
435         player: p.name,
436         score: p.round_score
437       };
438     });
439
440     scores.sort((a,b) => {
441       return b.score - a.score;
442     });
443
444     /* Put the word groups into a form the client can consume.
445      */
446     const words_submitted = word_groups.map(
447       group => {
448         return {
449           word: group.words.join('/'),
450           players: Array.from(group.players).map(p => p.name)
451         };
452       }
453     );
454
455     words_submitted.sort((a,b) => {
456       return b.players.length - a.players.length;
457     });
458
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 = {
462       scores: scores,
463       words: words_submitted
464     };
465
466     /* And broadcast the scores to all connected clients. */
467     this.broadcast_event_object('scores', this.state.scores);
468   }
469 }
470
471 Empathy.router = express.Router();
472 const router = Empathy.router;
473
474 class Prompt {
475   constructor(id, items, prompt) {
476     this.id = id;
477     this.items = items;
478     this.prompt = prompt;
479     this.votes = [];
480   }
481
482   toggle_vote(player_name) {
483     if (this.votes.find(v => v === player_name))
484       this.votes = this.votes.filter(v => v !== player_name);
485     else
486       this.votes.push(player_name);
487   }
488 }
489
490 router.post('/prompts', (request, response) => {
491   const game = request.game;
492
493   const result = game.add_prompt(request.body.items, request.body.prompt);
494
495   response.json(result);
496 });
497
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);
501
502   if (game.toggle_vote(prompt_id, request.session.id))
503     response.send('');
504   else
505     response.sendStatus(404);
506 });
507
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);
511
512   if (game.start(prompt_id))
513     response.send('');
514   else
515     response.sendStatus(404);
516 });
517
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);
521
522   const result = game.receive_answer(prompt_id,
523                                      request.session.id,
524                                      request.body.answers);
525   response.json(result);
526
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();
531 });
532
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);
536
537   const result = game.receive_answering(prompt_id,
538                                         request.session.id);
539   response.json(result);
540 });
541
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);
545
546   if (game.toggle_end_answers(prompt_id, request.session.id))
547     response.send('');
548   else
549     response.sendStatus(404);
550
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);
555
556   if (game.state.end_answers.size > players_involved / 2)
557     game.perform_judging();
558 });
559
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);
563
564   const result = game.receive_judged(prompt_id,
565                                      request.session.id,
566                                      request.body.word_groups);
567   response.json(result);
568
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();
573 });
574
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);
578
579   const result = game.receive_judging(prompt_id,
580                                       request.session.id);
581   response.json(result);
582 });
583
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);
587
588   if (game.toggle_end_judging(prompt_id, request.session.id))
589     response.send('');
590   else
591     response.sendStatus(404);
592
593   if (game.state.end_judging.size > (game.state.players_answered.length / 2))
594     game.compute_scores();
595 });
596
597 router.post('/reset', (request, response) => {
598   const game = request.game;
599   game.reset();
600
601   response.send('');
602 });
603
604 Empathy.meta = {
605   name: "Empathy",
606   identifier: "empathy",
607 };
608
609 exports.Game = Empathy;