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