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