]> git.cworth.org Git - lmno-server/blob - empathy.js
Broadcast "answering-idle" as soon as the waiting list becomes empty
[lmno-server] / empathy.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 const MAX_PROMPT_ITEMS = 20;
5
6 class Empathy extends Game {
7   constructor(id) {
8     super(id);
9     this.state = {
10       prompts: [],
11       active_prompt: null,
12       players_answered: [],
13       players_answering: new Set(),
14       answering_idle: false,
15       end_answers: new Set(),
16       ambiguities: null,
17       players_judged: [],
18       players_judging: new Set(),
19       end_judging: new Set(),
20       scores: null
21     };
22     this.answers = [];
23     this.answering_idle_timer = 0;
24     this.answering_start_time_ms = 0;
25     this.next_prompt_id = 1;
26     this.equivalencies = {};
27   }
28
29   reset() {
30
31     /* Before closing out the current round, we accumulate that score
32      * for each player into their runnning total. */
33     for (let score of this.state.scores.scores) {
34       const player = this.players.find(p => p.name === score.player);
35       if (player.score)
36         player.score += score.score;
37       else
38         player.score = score.score;
39
40       /* And broadcast that new score out. */
41       this.broadcast_event('player-update', player.info_json());
42     }
43
44     /* Now that we're done with the active prompt, we remove it from
45      * the list of prompts and also remove any prompts that received
46      * no votes. This keeps the list of prompts clean.
47      */
48     const active_id = this.state.active_prompt.id;
49     this.state.prompts =
50       this.state.prompts.filter(
51         p => p.id !== active_id && p.votes.length > 0
52       );
53
54     this.state.active_prompt = null;
55     this.state.players_answered = [];
56     this.state.players_answering = new Set();
57     this.state.answering_idle = false;
58     this.state.end_answers = new Set();
59     this.state.ambiguities = null;
60     this.state.players_judged = [];
61     this.state.players_judging = new Set();
62     this.state.end_judging = new Set();
63     this.state.scores = null;
64
65     this.answers = [];
66     if (this.answering_idle_timer) {
67       clearTimeout(this.answering_idle_timer);
68     }
69     this.answering_idle_timer = 0;
70     this.answering_start_time_ms = 0;
71     this.equivalencies = {};
72
73     this.broadcast_event_object('game-state', this.state);
74   }
75
76   add_prompt(items, prompt_string) {
77     if (items > MAX_PROMPT_ITEMS)
78       return {
79         valid: false,
80         message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
81       };
82
83     const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
84     this.next_prompt_id++;
85
86     this.state.prompts.push(prompt);
87
88     this.broadcast_event_object('prompt', prompt);
89
90     return {
91       valid: true,
92       id: prompt.id
93     };
94   }
95
96   /* Returns true if vote toggled, false for player or prompt not found */
97   toggle_vote(prompt_id, session_id) {
98     const player = this.players_by_session[session_id];
99
100     const prompt = this.state.prompts.find(p => p.id === prompt_id);
101     if (! prompt || ! player)
102       return false;
103
104     prompt.toggle_vote(player.name);
105
106     this.broadcast_event_object('prompt', prompt);
107
108     return true;
109   }
110
111   /* Returns true on success, false for prompt not found. */
112   start(prompt_id) {
113     const prompt = this.state.prompts.find(p => p.id === prompt_id);
114     if (! prompt)
115       return false;
116
117     /* Ignore any start request that comes in while a prompt is
118      * already being played. */
119     if (this.state.active_prompt)
120       return false;
121
122     this.state.active_prompt = prompt;
123
124     this.broadcast_event_object('start', prompt);
125
126     return true;
127   }
128
129   receive_answer(prompt_id, session_id, answers) {
130     const player = this.players_by_session[session_id];
131     if (! player)
132       return { valid: false, message: "Player not found" };
133
134     const prompt = this.state.prompts.find(p => p.id === prompt_id);
135     if (! prompt)
136       return { valid: false, message: "Prompt not found" };
137
138     if (prompt !== this.state.active_prompt)
139       return { valid: false, message: "Prompt no longer active" };
140
141     /* Save the complete answers for our own use later. */
142     this.answers.push({
143       player: player,
144       answers: answers
145     });
146
147     /* Update state (to be sent out to any future clients) */
148     this.state.players_answering.delete(player.name);
149     this.state.players_answered.push(player.name);
150
151     /* And notify all players that this player has answered. */
152     this.broadcast_event_object('player-answered', player.name);
153
154     /* If no players are left in the answering list then we don't need
155      * to wait for the answering_idle_timer to fire, because a person
156      * who isn't there obviously can't be typing. So we can broadcast
157      * the idle event right away. Note that we do this only if the
158      * answering phase has been going for a while to avoid the case of
159      * the first player being super fast and emptying the
160      * players_answering list before anyone else even got in.
161      */
162     if (this.state.players_answering.size === 0 &&
163         ((Date.now() - this.answering_start_time_ms) / 1000) > 30)
164     {
165       this.broadcast_event_object('answering-idle', true);
166     }
167
168     return { valid: true };
169   }
170
171   receive_answering(prompt_id, session_id) {
172     const player = this.players_by_session[session_id];
173     if (! player)
174       return { valid: false, message: "Player not found" };
175
176     const prompt = this.state.prompts.find(p => p.id === prompt_id);
177     if (! prompt)
178       return { valid: false, message: "Prompt not found" };
179
180     if (prompt !== this.state.active_prompt)
181       return { valid: false, message: "Prompt no longer active" };
182
183     if (this.answering_idle_timer) {
184       clearTimeout(this.answering_idle_timer);
185     }
186     if (! this.state.answering_idle) {
187       this.answering_idle_timer = setTimeout(() => {
188         this.state_answering_idle = true;
189         this.broadcast_event_object('answering-idle', true);
190       }, 10 * 1000);
191     }
192
193     if (this.answering_start_time_ms === 0)
194       this.answering_start_time_ms = Date.now();
195
196     /* Notify all players that this player is actively answering. */
197     this.state.players_answering.add(player.name);
198     this.broadcast_event_object('player-answering', player.name);
199
200     return { valid: true };
201   }
202
203   /* Returns true if vote toggled, false for player or prompt not found */
204   toggle_end_answers(prompt_id, session_id) {
205     const player = this.players_by_session[session_id];
206
207     const prompt = this.state.prompts.find(p => p.id === prompt_id);
208     if (! prompt || ! player)
209       return false;
210
211     if (this.state.end_answers.has(player.name)) {
212       this.state.end_answers.delete(player.name);
213       this.broadcast_event_object('unvote-end-answers', player.name);
214     } else {
215       this.state.end_answers.add(player.name);
216       this.broadcast_event_object('vote-end-answers', player.name);
217     }
218
219     return true;
220   }
221
222   perform_judging() {
223     const word_map = {};
224
225     for (let a of this.answers) {
226       for (let word of a.answers) {
227         const key = this.canonize(word);
228         word_map[key] = word;
229       }
230     }
231
232     this.state.ambiguities = Object.values(word_map).sort((a,b) => {
233       return a.toLowerCase().localeCompare(b.toLowerCase());
234     });
235
236     this.broadcast_event_object('ambiguities', this.state.ambiguities);
237   }
238
239   receive_judged(prompt_id, session_id, word_groups) {
240     const player = this.players_by_session[session_id];
241     if (! player)
242       return { valid: false, message: "Player not found" };
243
244     const prompt = this.state.prompts.find(p => p.id === prompt_id);
245     if (! prompt)
246       return { valid: false, message: "Prompt not found" };
247
248     if (prompt !== this.state.active_prompt)
249       return { valid: false, message: "Prompt no longer active" };
250
251     /* Each player submits some number of groups of answers that
252      * should be considered equivalent. The server expands that into
253      * the set of pair-wise equivalencies that are expressed. The
254      * reason for that is so that the server can determine which
255      * pair-wise equivalencies have majority support.
256      */
257     for (let group of word_groups) {
258
259       for (let i = 0; i < group.length - 1; i++) {
260         for (let j = i + 1; j < group.length; j++) {
261           let eq = [group[i], group[j]];
262
263           /* Put the two words into a reliable order so that we don't
264            * miss a pair of equivalent equivalencies just because they
265            * happen to be in the opposite order. */
266           if (eq[0].localeCompare(eq[1]) > 0) {
267             eq = [group[j], group[i]];
268           }
269
270           const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
271
272           const exist = this.equivalencies[key];
273           if (exist) {
274             exist.count++;
275           } else {
276             this.equivalencies[key] = {
277               count: 1,
278               words: eq
279             };
280           }
281
282         }
283       }
284     }
285
286     /* Update state (to be sent out to any future clients) */
287     this.state.players_judging.delete(player.name);
288     this.state.players_judged.push(player.name);
289
290     /* And notify all players this this player has judged. */
291     this.broadcast_event_object('player-judged', player.name);
292
293     return { valid: true };
294   }
295
296   receive_judging(prompt_id, session_id) {
297     const player = this.players_by_session[session_id];
298     if (! player)
299       return { valid: false, message: "Player not found" };
300
301     const prompt = this.state.prompts.find(p => p.id === prompt_id);
302     if (! prompt)
303       return { valid: false, message: "Prompt not found" };
304
305     if (prompt !== this.state.active_prompt)
306       return { valid: false, message: "Prompt no longer active" };
307
308     /* Notify all players this this player is actively judging. */
309     this.state.players_judging.add(player.name);
310     this.broadcast_event_object('player-judging', player.name);
311
312     return { valid: true };
313   }
314
315   /* Returns true if vote toggled, false for player or prompt not found */
316   toggle_end_judging(prompt_id, session_id) {
317     const player = this.players_by_session[session_id];
318
319     const prompt = this.state.prompts.find(p => p.id === prompt_id);
320     if (! prompt || ! player)
321       return false;
322
323     if (this.state.end_judging.has(player.name)) {
324       this.state.end_judging.delete(player.name);
325       this.broadcast_event_object('unvote-end-judging', player.name);
326     } else {
327       this.state.end_judging.add(player.name);
328       this.broadcast_event_object('vote-end-judging', player.name);
329     }
330
331     return true;
332   }
333
334   canonize(word) {
335     return word.trim().toLowerCase();
336   }
337
338   compute_scores() {
339     const word_submitters = {};
340
341     /* Perform a (non-strict) majority ruling on equivalencies,
342      * dropping all that didn't get enough votes. */
343     const quorum = Math.floor((this.players.length + 1)/2);
344     const agreed_equivalencies = Object.values(this.equivalencies).filter(
345       eq => eq.count >= quorum);
346
347     /* And with that agreed set of equivalencies, construct the full
348      * groups. */
349     const word_maps = {};
350
351     for (let e of agreed_equivalencies) {
352       const word0_canon = this.canonize(e.words[0]);
353       const word1_canon = this.canonize(e.words[1]);
354       let group = word_maps[word0_canon];
355       if (! group)
356         group = word_maps[word1_canon];
357       if (! group)
358         group = { words: [], players: new Set()};
359
360       if (! word_maps[word0_canon]) {
361         word_maps[word0_canon] = group;
362         group.words.push(e.words[0]);
363       }
364
365       if (! word_maps[word1_canon]) {
366         word_maps[word1_canon] = group;
367         group.words.push(e.words[1]);
368       }
369     }
370
371     /* Now go through answers from each player and add the player
372      * to the set corresponding to each word group. */
373     for (let a of this.answers) {
374       for (let word of a.answers) {
375         const word_canon = this.canonize(word);
376         /* If there's no group yet, this is a singleton word. */
377         if (word_maps[word_canon]) {
378           word_maps[word_canon].players.add(a.player);
379         } else {
380           const group = { words: [word], players: new Set() };
381           group.players.add(a.player);
382           word_maps[word_canon] = group;
383         }
384       }
385     }
386
387     /* Now that we've assigned the players to these word maps, we now
388      * want to collapse the groups down to a single array of
389      * word_groups.
390      *
391      * The difference between "word_maps" and "word_groups" is that
392      * the former has a property for every word that maps to a group,
393      * (so if you iterate over the keys you will see the same group
394      * multiple times). In contrast, iterating over"word_groups" will
395      * have you visit each group only once. */
396     const word_groups = Object.entries(word_maps).filter(
397       entry => entry[0] === this.canonize(entry[1].words[0]))
398           .map(entry => entry[1]);
399
400     /* Now, go through each word group and assign the scores out to
401      * the corresponding players.
402      *
403      * Note: We do this by going through the word groups, (as opposed
404      * to the list of words from the players again), specifically to
405      * avoid giving a player points for a wrod group twice (in the
406      * case where a player submits two different words that the group
407      * ends up judging as equivalent).
408      */
409     this.players.forEach(p => p.round_score = 0);
410     for (let group of word_groups) {
411       group.players.forEach(p => p.round_score += group.players.size);
412     }
413
414     const scores = this.players.map(p => {
415       return {
416         player: p.name,
417         score: p.round_score
418       };
419     });
420
421     scores.sort((a,b) => {
422       return b.score - a.score;
423     });
424
425     /* Put the word groups into a form the client can consume.
426      */
427     const words_submitted = word_groups.map(
428       group => {
429         return {
430           word: group.words.join('/'),
431           players: Array.from(group.players).map(p => p.name)
432         };
433       }
434     );
435
436     words_submitted.sort((a,b) => {
437       return b.players.length - a.players.length;
438     });
439
440     /* Put this round's scores into the game state object so it will
441      * be sent to any new clients that join. */
442     this.state.scores = {
443       scores: scores,
444       words: words_submitted
445     };
446
447     /* And broadcast the scores to all connected clients. */
448     this.broadcast_event_object('scores', this.state.scores);
449   }
450 }
451
452 Empathy.router = express.Router();
453 const router = Empathy.router;
454
455 class Prompt {
456   constructor(id, items, prompt) {
457     this.id = id;
458     this.items = items;
459     this.prompt = prompt;
460     this.votes = [];
461   }
462
463   toggle_vote(player_name) {
464     if (this.votes.find(v => v === player_name))
465       this.votes = this.votes.filter(v => v !== player_name);
466     else
467       this.votes.push(player_name);
468   }
469 }
470
471 router.post('/prompts', (request, response) => {
472   const game = request.game;
473
474   const result = game.add_prompt(request.body.items, request.body.prompt);
475
476   response.json(result);
477 });
478
479 router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
480   const game = request.game;
481   const prompt_id = parseInt(request.params.prompt_id, 10);
482
483   if (game.toggle_vote(prompt_id, request.session.id))
484     response.send('');
485   else
486     response.sendStatus(404);
487 });
488
489 router.post('/start/:prompt_id([0-9]+)', (request, response) => {
490   const game = request.game;
491   const prompt_id = parseInt(request.params.prompt_id, 10);
492
493   if (game.start(prompt_id))
494     response.send('');
495   else
496     response.sendStatus(404);
497 });
498
499 router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
500   const game = request.game;
501   const prompt_id = parseInt(request.params.prompt_id, 10);
502
503   const result = game.receive_answer(prompt_id,
504                                      request.session.id,
505                                      request.body.answers);
506   response.json(result);
507
508   /* If every registered player has answered, then there's no need to
509    * wait for anything else. */
510   if (game.state.players_answered.length >= game.players.length)
511     game.perform_judging();
512 });
513
514 router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
515   const game = request.game;
516   const prompt_id = parseInt(request.params.prompt_id, 10);
517
518   const result = game.receive_answering(prompt_id,
519                                         request.session.id);
520   response.json(result);
521 });
522
523 router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
524   const game = request.game;
525   const prompt_id = parseInt(request.params.prompt_id, 10);
526
527   if (game.toggle_end_answers(prompt_id, request.session.id))
528     response.send('');
529   else
530     response.sendStatus(404);
531
532   /* The majority rule here includes all players that have answered as
533    * well as all that have started typing. */
534   const players_involved = (game.state.players_answered.length +
535                             game.state.players_answering.size);
536
537   if (game.state.end_answers.size > players_involved / 2)
538     game.perform_judging();
539 });
540
541 router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
542   const game = request.game;
543   const prompt_id = parseInt(request.params.prompt_id, 10);
544
545   const result = game.receive_judged(prompt_id,
546                                      request.session.id,
547                                      request.body.word_groups);
548   response.json(result);
549
550   /* If every registered player has judged, then there's no need to
551    * wait for anything else. */
552   if (game.state.players_judged.length >= game.players.length)
553     game.compute_scores();
554 });
555
556 router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
557   const game = request.game;
558   const prompt_id = parseInt(request.params.prompt_id, 10);
559
560   const result = game.receive_judging(prompt_id,
561                                       request.session.id);
562   response.json(result);
563 });
564
565 router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
566   const game = request.game;
567   const prompt_id = parseInt(request.params.prompt_id, 10);
568
569   if (game.toggle_end_judging(prompt_id, request.session.id))
570     response.send('');
571   else
572     response.sendStatus(404);
573
574   if (game.state.end_judging.size > (game.state.players_answered.length / 2))
575     game.compute_scores();
576 });
577
578 router.post('/reset', (request, response) => {
579   const game = request.game;
580   game.reset();
581
582   response.send('');
583 });
584
585 Empathy.meta = {
586   name: "Empathy",
587   identifier: "empathy",
588 };
589
590 exports.Game = Empathy;