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