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