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