]> git.cworth.org Git - lmno.games/blob - empathy.jsx
0789b463fe5813cb3fc23b8cb4a84610dd32b2a5
[lmno.games] / empathy.jsx
1 const MAX_PROMPT_ITEMS = 20;
2
3 function undisplay(element) {
4   element.style.display="none";
5 }
6
7 function add_message(severity, message) {
8   message = `<div class="message ${severity}" onclick="undisplay(this)">
9 <span class="hide-button" onclick="undisplay(this.parentElement)">&times;</span>
10 ${message}
11 </div>`;
12   const message_area = document.getElementById('message-area');
13   message_area.insertAdjacentHTML('beforeend', message);
14 }
15
16 /*********************************************************
17  * Handling server-sent event stream                     *
18  *********************************************************/
19
20 const events = new EventSource("events");
21
22 events.onerror = function(event) {
23   if (event.target.readyState === EventSource.CLOSED) {
24     setTimeout(() => {
25       add_message("danger", "Connection to server lost.");
26     }, 1000);
27   }
28 };
29
30 events.addEventListener("game-info", event => {
31   const info = JSON.parse(event.data);
32
33   window.game.set_game_info(info);
34 });
35
36 events.addEventListener("player-info", event => {
37   const info = JSON.parse(event.data);
38
39   window.game.set_player_info(info);
40 });
41
42 events.addEventListener("player-enter", event => {
43   const info = JSON.parse(event.data);
44
45   window.game.set_other_player_info(info);
46 });
47
48 events.addEventListener("player-exit", event => {
49   const info = JSON.parse(event.data);
50
51   window.game.remove_player(info);
52 });
53
54 events.addEventListener("player-update", event => {
55   const info = JSON.parse(event.data);
56
57   if (info.id === window.game.state.player_info.id)
58     window.game.set_player_info(info);
59   else
60     window.game.set_other_player_info(info);
61 });
62
63 events.addEventListener("game-state", event => {
64   const state = JSON.parse(event.data);
65
66   window.game.reset_game_state();
67
68   window.game.set_prompts(state.prompts);
69
70   window.game.set_active_prompt(state.active_prompt);
71
72   window.game.set_players_answered(state.players_answered);
73
74   window.game.set_players_answering(state.players_answering);
75
76   window.game.set_answering_idle(state.answering_idle);
77
78   window.game.set_end_answers(state.end_answers);
79
80   window.game.set_ambiguities(state.ambiguities);
81
82   window.game.set_players_judged(state.players_judged);
83
84   window.game.set_players_judging(state.players_judging);
85
86   window.game.set_judging_idle(state.judging_idle);
87
88   window.game.set_end_judging(state.end_judging);
89
90   window.game.set_scores(state.scores);
91
92   window.game.set_new_game_votes(state.new_game_votes);
93
94   window.game.state_ready();
95 });
96
97 events.addEventListener("prompt", event => {
98   const prompt = JSON.parse(event.data);
99
100   window.game.add_or_update_prompt(prompt);
101 });
102
103 events.addEventListener("start", event => {
104   const prompt = JSON.parse(event.data);
105
106   window.game.set_active_prompt(prompt);
107 });
108
109 events.addEventListener("player-answered", event => {
110   const player = JSON.parse(event.data);
111
112   window.game.set_player_answered(player);
113 });
114
115 events.addEventListener("player-answering", event => {
116   const player = JSON.parse(event.data);
117
118   window.game.set_player_answering(player);
119 });
120
121 events.addEventListener("answering-idle", event => {
122   const value = JSON.parse(event.data);
123
124   window.game.set_answering_idle(value);
125 });
126
127 events.addEventListener("vote-end-answers", event => {
128   const player = JSON.parse(event.data);
129
130   window.game.set_player_vote_end_answers(player);
131 });
132
133 events.addEventListener("unvote-end-answers", event => {
134   const player = JSON.parse(event.data);
135
136   window.game.set_player_unvote_end_answers(player);
137 });
138
139 events.addEventListener("ambiguities", event => {
140   const ambiguities = JSON.parse(event.data);
141
142   window.game.set_ambiguities(ambiguities);
143 });
144
145 events.addEventListener("player-judged", event => {
146   const player = JSON.parse(event.data);
147
148   window.game.set_player_judged(player);
149 });
150
151 events.addEventListener("player-judging", event => {
152   const player = JSON.parse(event.data);
153
154   window.game.set_player_judging(player);
155 });
156
157 events.addEventListener("judging-idle", event => {
158   const value = JSON.parse(event.data);
159
160   window.game.set_judging_idle(value);
161 });
162
163 events.addEventListener("vote-end-judging", event => {
164   const player = JSON.parse(event.data);
165
166   window.game.set_player_vote_end_judging(player);
167 });
168
169 events.addEventListener("unvote-end-judging", event => {
170   const player = JSON.parse(event.data);
171
172   window.game.set_player_unvote_end_judging(player);
173 });
174
175 events.addEventListener("scores", event => {
176   const scores = JSON.parse(event.data);
177
178   window.game.set_scores(scores);
179 });
180
181 events.addEventListener("vote-new-game", event => {
182   const player = JSON.parse(event.data);
183
184   window.game.set_player_vote_new_game(player);
185 });
186
187 events.addEventListener("unvote-new-game", event => {
188   const player = JSON.parse(event.data);
189
190   window.game.set_player_unvote_new_game(player);
191 });
192
193 /*********************************************************
194  * Game and supporting classes                           *
195  *********************************************************/
196
197 function copy_to_clipboard(id)
198 {
199   const tmp = document.createElement("input");
200   tmp.setAttribute("value", document.getElementById(id).innerHTML);
201   document.body.appendChild(tmp);
202   tmp.select();
203   document.execCommand("copy");
204   document.body.removeChild(tmp);
205 }
206
207 const GameInfo = React.memo(props => {
208   if (! props.id)
209     return null;
210
211   return (
212     <div className="game-info">
213       <span className="game-id">{props.id}</span>
214       {" "}
215       Share this link to invite friends:{" "}
216       <span id="game-share-url">{props.url}</span>
217       {" "}
218       <button
219         className="inline"
220         onClick={() => copy_to_clipboard('game-share-url')}
221       >Copy Link</button>
222     </div>
223   );
224 });
225
226 const PlayerInfo = React.memo(props => {
227   if (! props.player.id)
228     return null;
229
230   const all_players = [props.player, ...props.other_players];
231
232   const sorted_players = all_players.sort((a,b) => {
233     return b.score - a.score;
234   });
235
236   const names_and_scores = sorted_players.map(player => {
237     if (player.score)
238       return `${player.name} (${player.score})`;
239     else
240       return player.name;
241   }).join(', ');
242
243   return (
244     <div className="player-info">
245       <span className="players-header">Players: </span>
246       <span>{names_and_scores}</span>
247     </div>
248   );
249 });
250
251 function fetch_method_json(method, api = '', data = {}) {
252   const response = fetch(api, {
253     method: method,
254     headers: {
255       'Content-Type': 'application/json'
256     },
257     body: JSON.stringify(data)
258   });
259   return response;
260 }
261
262 function fetch_post_json(api = '', data = {}) {
263   return fetch_method_json('POST', api, data);
264 }
265
266 async function fetch_put_json(api = '', data = {}) {
267   return fetch_method_json('PUT', api, data);
268 }
269
270 class CategoryRequest extends React.PureComponent {
271   constructor(props) {
272     super(props);
273     this.category = React.createRef();
274
275     this.handle_change = this.handle_change.bind(this);
276     this.handle_submit = this.handle_submit.bind(this);
277   }
278
279   handle_change(event) {
280     const category_input = this.category.current;
281     const category = category_input.value;
282
283     const match = category.match(/[0-9]+/);
284     if (match) {
285       const num_items = parseInt(match[0], 10);
286       if (num_items <= MAX_PROMPT_ITEMS)
287         category_input.setCustomValidity("");
288     }
289   }
290
291   async handle_submit(event) {
292     const form = event.currentTarget;
293     const category_input = this.category.current;
294     const category = category_input.value;
295
296     /* Prevent the default page-changing form-submission behavior. */
297     event.preventDefault();
298
299     const match = category.match(/[0-9]+/);
300     if (match === null) {
301       category_input.setCustomValidity("Category must include a number");
302       form.reportValidity();
303       return;
304     }
305
306     const num_items = parseInt(match[0], 10);
307
308     if (num_items > MAX_PROMPT_ITEMS) {
309       category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
310       form.reportValidity();
311       return;
312     }
313
314     const response = await fetch_post_json("prompts", {
315       items: num_items,
316       prompt: category
317     });
318
319     if (response.status === 200) {
320       const result = await response.json();
321       if (! result.valid) {
322         add_message("danger", result.message);
323         return;
324       }
325     } else {
326       add_message("danger", "An error occurred submitting your category");
327     }
328
329     form.reset();
330   }
331
332   render() {
333     return (
334       <div className="category-request">
335         <h2>Submit a Category</h2>
336         <p>
337           Suggest a category to play. Don't forget to include the
338           number of items for each person to submit.
339         </p>
340
341         <form onSubmit={this.handle_submit} >
342           <div className="form-field large">
343             <input
344               type="text"
345               id="category"
346               placeholder="6 things at the beach"
347               required
348               autoComplete="off"
349               onChange={this.handle_change}
350               ref={this.category}
351             />
352           </div>
353
354           <div className="form-field large">
355             <button type="submit">
356               Send
357             </button>
358           </div>
359
360         </form>
361       </div>
362     );
363   }
364 }
365
366 const PromptOption = React.memo(props => {
367
368   const prompt = props.prompt;
369
370   if (prompt.votes_against.find(v => v === props.player.name))
371     return false;
372
373   return (
374     <button
375       className="vote-button"
376       key={prompt.id}
377       onClick={() => fetch_post_json(`vote/${prompt.id}`) }
378     >
379       <span
380         className="hide-button"
381         onClick={(event) => {
382           event.stopPropagation();
383           fetch_post_json(`vote_against/${prompt.id}`);
384         }}
385       >
386         &times;
387       </span>
388       {prompt.prompt}
389       <div className="vote-choices">
390         {prompt.votes.map(v => {
391           return (
392             <div
393               key={v}
394               className="vote-choice"
395             >
396               {v}
397             </div>
398           );
399         })}
400       </div>
401     </button>
402   );
403 });
404
405 const PromptOptions = React.memo(props => {
406
407   if (props.prompts.length === 0)
408     return null;
409
410   return (
411     <div className="prompt-options">
412       <h2>Vote on Categories</h2>
413       <p>
414         Select any categories below that you'd like to play.
415         You can choose as many as you'd like.
416       </p>
417     {props.prompts.map(p => <PromptOption prompt={p} player={props.player} />)}
418     </div>
419   );
420 });
421
422 const LetsPlay = React.memo(props => {
423
424   const quorum = Math.round((props.num_players + 1) / 2);
425   const max_votes = props.prompts.reduce(
426     (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
427
428   if (max_votes < quorum)
429     return null;
430
431   const candidates = props.prompts.filter(p => p.votes.length >= quorum);
432   const index = Math.floor(Math.random() * candidates.length);
433   const winner = candidates[index];
434
435   return (
436     <div className="lets-play">
437       <h2>Let's Play</h2>
438       <p>
439         That should be enough voting. If you're not waiting for any
440         other players to join, then let's start.
441       </p>
442       <button
443         className="lets-play"
444         onClick={() => fetch_post_json(`start/${winner.id}`) }
445       >
446         Start Game
447       </button>
448     </div>
449   );
450 });
451
452 class Ambiguities extends React.PureComponent {
453
454   constructor(props) {
455     super(props);
456
457     function canonize(word) {
458       return word.replace(/((a|an|the) )?(.*?)s?$/i, '$3');
459     }
460
461     const word_sets = [];
462
463     for (let word of props.words) {
464       const word_canon = canonize(word);
465       console.log("Canonized " + word + " to " + word_canon);
466       let found_match = false;
467       for (let set of word_sets) {
468         const set_canon = canonize(set.values().next().value);
469         console.log("Comparing " + word_canon + " to " + set_canon);
470         if (word_canon === set_canon) {
471           set.add(word);
472           found_match = true;;
473           break;
474         }
475       }
476       if (! found_match) {
477         const set = new Set();
478         set.add(word);
479         word_sets.push(set);
480       }
481     }
482
483     this.state = {
484       word_sets: word_sets,
485       selected: null
486     };
487
488     this.submitted = false;
489     this.judging_sent_recently = false;
490   }
491
492   async handle_submit() {
493
494     /* Don't submit a second time. */
495     if (this.submitted)
496       return;
497
498     const response = await fetch_post_json(
499       `judged/${this.props.prompt.id}`,{
500         word_groups: this.state.word_sets.map(set => Array.from(set))
501       }
502     );
503
504     if (response.status === 200) {
505       const result = await response.json();
506       if (! result.valid) {
507         add_message("danger", result.message);
508         return;
509       }
510     } else {
511       add_message("danger", "An error occurred submitting the results of your judging");
512       return;
513     }
514
515     this.submitted = true;
516   }
517
518   handle_click(word) {
519
520     /* Let the server know we are doing some judging, (but rate limit
521      * this so we don't send a "judging" notification more frquently
522      * than necessary.
523      */
524     if (! this.judging_sent_recently) {
525       fetch_post_json(`judging/${this.props.prompt.id}`);
526       this.judging_sent_recently = true;
527       setTimeout(() => { this.judging_sent_recently = false; }, 1000);
528     }
529
530     if (this.state.selected == word) {
531       /* Second click on same word removes the word from the group. */
532       const idx = this.state.word_sets.findIndex(s => s.has(word));
533       const set = this.state.word_sets[idx];
534       if (set.size === 1) {
535         /* When the word is already alone, there's nothing to do but
536          * to un-select it. */
537         this.setState({
538           selected: null
539         });
540         return;
541       }
542
543       const new_set = new Set([...set].filter(w => w !== word));
544       this.setState({
545         selected: null,
546         word_sets: [...this.state.word_sets.slice(0, idx),
547                     new_set,
548                     new Set().add(word),
549                     ...this.state.word_sets.slice(idx+1)]
550       });
551     } else if (this.state.selected) {
552       /* Click of a second word groups the two together. */
553       const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
554       const idx2 = this.state.word_sets.findIndex(s => s.has(word));
555       const set1 = this.state.word_sets[idx1];
556       const set2 = this.state.word_sets[idx2];
557       const new_set = new Set([...set2, ...set1]);
558       if (idx1 < idx2) {
559         this.setState({
560           selected: null,
561           word_sets: [...this.state.word_sets.slice(0, idx1),
562                       ...this.state.word_sets.slice(idx1 + 1, idx2),
563                       new_set,
564                       ...this.state.word_sets.slice(idx2 + 1)]
565         });
566       } else {
567         this.setState({
568           selected: null,
569           word_sets: [...this.state.word_sets.slice(0, idx2),
570                       new_set,
571                       ...this.state.word_sets.slice(idx2 + 1, idx1),
572                       ...this.state.word_sets.slice(idx1 + 1)]
573         });
574       }
575     } else {
576       /* First click of a word selects it. */
577       this.setState({
578         selected: word
579       });
580     }
581   }
582
583   render() {
584     let move_on_button = null;
585
586     if (this.props.idle) {
587       move_on_button = (
588         <button
589           className="vote-button"
590           onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
591         >
592           Move On
593           <div className="vote-choices">
594             {[...this.props.votes].map(v => {
595               return (
596                 <div
597                   key={v}
598                   className="vote-choice"
599                 >
600                   {v}
601                   </div>
602               );
603             })}
604           </div>
605         </button>
606       );
607     }
608
609     let still_waiting = null;
610     const judging_players = Object.keys(this.props.players_judging);
611     if (judging_players.length) {
612       still_waiting = (
613         <div>
614           <p>
615             Still waiting for the following player
616             {judging_players.length > 1 ? 's' : '' }
617             :
618           </p>
619           <ul>
620             {judging_players.map(player => {
621               return (
622                 <li
623                   key={player}
624                 >
625                   {player}{' '}
626                   <span className=
627                   {this.props.players_judging[player].active ?
628                    "typing active"
629                    :
630                    "typing idle"}>
631                     <span>{'.'}</span><span>{'.'}</span><span>{'.'}</span>
632                   </span>
633                 </li>
634               );
635             })}
636           </ul>
637         </div>
638       );
639     }
640
641     if (this.props.players_judged.has(this.props.player.name)) {
642       return (
643         <div className="please-wait">
644           <h2>Submission received</h2>
645           <p>
646             The following players have completed judging:{' '}
647             {[...this.props.players_judged].join(', ')}
648           </p>
649           {still_waiting}
650           {move_on_button}
651
652         </div>
653       );
654     }
655
656     const btn_class = "ambiguity-button";
657     const btn_selected_class = btn_class + " selected";
658
659     return (
660       <div className="ambiguities">
661         <h2>Judging Answers</h2>
662         <p>
663           Click on each pair of answers that should be scored as equivalent,
664           (and click any word twice to split it out from a group). Remember,
665           what goes around comes around, so it's best to be generous when
666           judging.
667         </p>
668         <h2>{this.props.prompt.prompt}</h2>
669         {this.state.word_sets.map(set => {
670           return (
671             <div
672               className="ambiguity-group"
673               key={Array.from(set)[0]}
674             >
675               {Array.from(set).map(word => {
676                 return (
677                   <button
678                     className={this.state.selected === word ?
679                                btn_selected_class : btn_class }
680                     key={word}
681                     onClick={() => this.handle_click(word)}
682                   >
683                     {word}
684                   </button>
685                 );
686               })}
687             </div>
688           );
689         })}
690         <p>
691           Click here when done judging:<br/>
692           <button
693             onClick={() => this.handle_submit()}
694           >
695             Send
696           </button>
697         </p>
698       </div>
699     );
700   }
701 }
702
703 class ActivePrompt extends React.PureComponent {
704
705   constructor(props) {
706     super(props);
707     const items = props.prompt.items;
708
709     this.submitted = false;
710
711     this.answers = [...Array(items)].map(() => React.createRef());
712     this.answering_sent_recently = false;
713
714     this.handle_submit = this.handle_submit.bind(this);
715     this.handle_change = this.handle_change.bind(this);
716   }
717
718   handle_change(event) {
719     /* We don't care (or even look) at what the player is typing at
720      * this point. We simply want to be informed that the player _is_
721      * typing so that we can tell the server (which will tell other
722      * players) that there is activity here.
723      */
724
725     /* Rate limit so that we don't send an "answering" notification
726      * more frequently than necessary.
727      */
728     if (! this.answering_sent_recently) {
729       fetch_post_json(`answering/${this.props.prompt.id}`);
730       this.answering_sent_recently = true;
731       setTimeout(() => { this.answering_sent_recently = false; }, 1000);
732     }
733   }
734
735   async handle_submit(event) {
736     const form = event.currentTarget;
737
738     /* Prevent the default page-changing form-submission behavior. */
739     event.preventDefault();
740
741     /* And don't submit a second time. */
742     if (this.submitted)
743       return;
744
745     const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
746       answers: this.answers.map(r => r.current.value)
747     });
748     if (response.status === 200) {
749       const result = await response.json();
750       if (! result.valid) {
751         add_message("danger", result.message);
752         return;
753       }
754     } else {
755       add_message("danger", "An error occurred submitting your answers");
756       return;
757     }
758
759     /* Everything worked. Server is happy with our answers. */
760     form.reset();
761     this.submitted = true;
762   }
763
764   render() {
765     let move_on_button = null;
766     if (this.props.idle) {
767       move_on_button =(
768         <button
769           className="vote-button"
770           onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
771         >
772           Move On
773           <div className="vote-choices">
774             {[...this.props.votes].map(v => {
775               return (
776                 <div
777                   key={v}
778                   className="vote-choice"
779                 >
780                   {v}
781                 </div>
782               );
783             })}
784           </div>
785         </button>
786       );
787     }
788
789     let still_waiting = null;
790     const answering_players = Object.keys(this.props.players_answering);;
791     if (answering_players.length) {
792       still_waiting = (
793         <div>
794           <p>
795             Still waiting for the following player
796             {answering_players.length > 1 ? 's' : ''}
797             :
798           </p>
799           <ul>
800             {answering_players.map(player => {
801               return (
802                 <li
803                   key={player}
804                 >
805                   {player}{' '}
806                   <span className=
807                   {this.props.players_answering[player].active ?
808                    "typing active"
809                    :
810                    "typing idle"}>
811                     <span>{'.'}</span><span>{'.'}</span><span>{'.'}</span>
812                   </span>
813                 </li>
814               );
815             })}
816           </ul>
817         </div>
818       );
819     }
820
821     if (this.props.players_answered.has(this.props.player.name)) {
822       return (
823         <div className="please-wait">
824           <h2>Submission received</h2>
825           <p>
826             The following players have submitted their answers:{' '}
827             {[...this.props.players_answered].join(', ')}
828           </p>
829           {still_waiting}
830           {move_on_button}
831
832         </div>
833       );
834     }
835
836     return (
837       <div className="active-prompt">
838         <h2>The Game of Empathy</h2>
839         <p>
840           Remember, you're trying to match your answers with
841           what the other players submit.
842           Give {this.props.prompt.items} answer
843           {this.props.prompt.items > 1 ? 's' : ''} for the following prompt:
844         </p>
845         <h2>{this.props.prompt.prompt}</h2>
846         <form onSubmit={this.handle_submit}>
847           {[...Array(this.props.prompt.items)].map((whocares,i) => {
848             return (
849               <div
850                 key={i}
851                 className="form-field large">
852                 <input
853                   type="text"
854                   name={`answer_${i}`}
855                   required
856                   autoComplete="off"
857                   onChange={this.handle_change}
858                   ref={this.answers[i]}
859                 />
860               </div>
861             );
862           })}
863
864           <div
865             key="submit-button"
866             className="form-field large">
867             <button type="submit">
868               Send
869             </button>
870           </div>
871
872         </form>
873       </div>
874     );
875   }
876 }
877
878 class Game extends React.PureComponent {
879   constructor(props) {
880     super(props);
881     this.state = {
882       game_info: {},
883       player_info: {},
884       other_players: [],
885       prompts: [],
886       active_prompt: null,
887       players_answered: new Set(),
888       players_answering: {},
889       answering_idle: false,
890       end_answers_votes: new Set(),
891       ambiguities: null,
892       players_judged: new Set(),
893       players_judging: {},
894       judging_idle: false,
895       end_judging_votes: new Set(),
896       scores: null,
897       new_game_votes: new Set(),
898       ready: false
899     };
900   }
901
902   set_game_info(info) {
903     this.setState({
904       game_info: info
905     });
906   }
907
908   set_player_info(info) {
909     this.setState({
910       player_info: info
911     });
912   }
913
914   set_other_player_info(info) {
915     const other_players_copy = [...this.state.other_players];
916     const idx = other_players_copy.findIndex(o => o.id === info.id);
917     if (idx >= 0) {
918       other_players_copy[idx] = info;
919     } else {
920       other_players_copy.push(info);
921     }
922     this.setState({
923       other_players: other_players_copy
924     });
925   }
926
927   remove_player(info) {
928     this.setState({
929       other_players: this.state.other_players.filter(o => o.id !== info.id)
930     });
931   }
932
933   reset_game_state() {
934     this.setState({
935       prompts: [],
936       active_prompt: null,
937       players_answered: new Set(),
938       players_answering: {},
939       answering_idle: false,
940       end_answers_votes: new Set(),
941       ambiguities: null,
942       players_judged: new Set(),
943       players_judging: {},
944       judging_idle: false,
945       end_judging_votes: new Set(),
946       scores: null,
947       new_game_votes: new Set(),
948       ready: false
949     });
950   }
951
952   set_prompts(prompts) {
953     this.setState({
954       prompts: prompts
955     });
956   }
957
958   add_or_update_prompt(prompt) {
959     const prompts_copy = [...this.state.prompts];
960     const idx = prompts_copy.findIndex(p => p.id === prompt.id);
961     if (idx >= 0) {
962       prompts_copy[idx] = prompt;
963     } else {
964       prompts_copy.push(prompt);
965     }
966     this.setState({
967       prompts: prompts_copy
968     });
969   }
970
971   set_active_prompt(prompt) {
972     this.setState({
973       active_prompt: prompt
974     });
975   }
976
977   set_players_answered(players) {
978     this.setState({
979       players_answered: new Set(players)
980     });
981   }
982
983   set_player_answered(player) {
984     const new_players_answering = {...this.state.players_answering};
985     delete new_players_answering[player];
986
987     this.setState({
988       players_answered: new Set([...this.state.players_answered, player]),
989       players_answering: new_players_answering
990     });
991   }
992
993   set_players_answering(players) {
994     const players_answering = {};
995     for (let player of players) {
996       players_answering[player] = {active: false};
997     }
998     this.setState({
999       players_answering: players_answering
1000     });
1001   }
1002
1003   set_player_answering(player) {
1004     /* Set the player as actively answering now. */
1005     this.setState({
1006       players_answering: {
1007         ...this.state.players_answering,
1008         [player]: {active: true}
1009       }
1010     });
1011     /* And arrange to have them marked idle very shortly.
1012      *
1013      * Note: This timeout is intentionally very, very short. We only
1014      * need it long enough that the browser has latched onto the state
1015      * change to "active" above. We actually use a CSS transition
1016      * delay to control the user-perceptible length of time after
1017      * which an active player appears inactive.
1018      */
1019     setTimeout(() => {
1020       this.setState({
1021         players_answering: {
1022           ...this.state.players_answering,
1023           [player]: {active: false}
1024         }
1025       });
1026     }, 100);
1027   }
1028
1029   set_answering_idle(value) {
1030     this.setState({
1031       answering_idle: value
1032     });
1033   }
1034
1035   set_end_answers(players) {
1036     this.setState({
1037       end_answers_votes: new Set(players)
1038     });
1039   }
1040
1041   set_player_vote_end_answers(player) {
1042     this.setState({
1043       end_answers_votes: new Set([...this.state.end_answers_votes, player])
1044     });
1045   }
1046
1047   set_player_unvote_end_answers(player) {
1048     this.setState({
1049       end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
1050     });
1051   }
1052
1053   set_ambiguities(ambiguities) {
1054     this.setState({
1055       ambiguities: ambiguities
1056     });
1057   }
1058
1059   set_players_judged(players) {
1060     this.setState({
1061       players_judged: new Set(players)
1062     });
1063   }
1064
1065   set_player_judged(player) {
1066     const new_players_judging = {...this.state.players_judging};
1067     delete new_players_judging[player];
1068
1069     this.setState({
1070       players_judged: new Set([...this.state.players_judged, player]),
1071       players_judging: new_players_judging
1072     });
1073   }
1074
1075   set_players_judging(players) {
1076     const players_judging = {};
1077     for (let player of players) {
1078       players_judging[player] = {active: false};
1079     }
1080     this.setState({
1081       players_judging: players_judging
1082     });
1083   }
1084
1085   set_player_judging(player) {
1086     /* Set the player as actively judging now. */
1087     this.setState({
1088       players_judging: {
1089         ...this.state.players_judging,
1090         [player]: {active: true}
1091       }
1092     });
1093     /* And arrange to have them marked idle very shortly.
1094      *
1095      * Note: This timeout is intentionally very, very short. We only
1096      * need it long enough that the browser has latched onto the state
1097      * change to "active" above. We actually use a CSS transition
1098      * delay to control the user-perceptible length of time after
1099      * which an active player appears inactive.
1100      */
1101     setTimeout(() => {
1102       this.setState({
1103         players_judging: {
1104           ...this.state.players_judging,
1105           [player]: {active: false}
1106         }
1107       });
1108     }, 100);
1109
1110   }
1111
1112   set_judging_idle(value) {
1113     this.setState({
1114       judging_idle: value
1115     });
1116   }
1117
1118   set_end_judging(players) {
1119     this.setState({
1120       end_judging_votes: new Set(players)
1121     });
1122   }
1123
1124   set_player_vote_end_judging(player) {
1125     this.setState({
1126       end_judging_votes: new Set([...this.state.end_judging_votes, player])
1127     });
1128   }
1129
1130   set_player_unvote_end_judging(player) {
1131     this.setState({
1132       end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1133     });
1134   }
1135
1136   set_scores(scores) {
1137     this.setState({
1138       scores: scores
1139     });
1140   }
1141
1142   set_new_game_votes(players) {
1143     this.setState({
1144       new_game_votes: new Set(players)
1145     });
1146   }
1147
1148   set_player_vote_new_game(player) {
1149     this.setState({
1150       new_game_votes: new Set([...this.state.new_game_votes, player])
1151     });
1152   }
1153
1154   set_player_unvote_new_game(player) {
1155     this.setState({
1156       new_game_votes: new Set([...this.state.new_game_votes].filter(p => p !== player))
1157     });
1158   }
1159
1160   state_ready() {
1161     this.setState({
1162       ready: true
1163     });
1164   }
1165
1166   render() {
1167     const state = this.state;
1168     const players_total = 1 + state.other_players.length;
1169
1170     if (state.scores) {
1171
1172       let perfect_score = 0;
1173       for (let i = 0;
1174            i < state.active_prompt.items &&
1175            i < state.scores.words.length;
1176            i++)
1177       {
1178         perfect_score += state.scores.words[i].players.length;
1179       }
1180
1181       return (
1182         <div className="scores">
1183           <h2>{state.active_prompt.prompt}</h2>
1184           <h2>Scores</h2>
1185           <ul>
1186             {state.scores.scores.map(score => {
1187               let perfect = null;
1188               if (score.score == perfect_score) {
1189                 perfect = <span className="label">Perfect!</span>;
1190               }
1191               return (
1192                 <li key={score.players[0]}>
1193                   {score.players.join("/")}: {score.score} {perfect}
1194                 </li>
1195               );
1196             })}
1197           </ul>
1198           <h2>Words submitted</h2>
1199           <ul>
1200             {state.scores.words.map(word => {
1201               return (
1202                 <li key={word.word}>
1203                   {word.word} ({word.players.length}): {word.players.join(', ')}
1204                 </li>
1205               );
1206             })}
1207           </ul>
1208           <button
1209             className="vote-button"
1210             onClick={() => fetch_post_json(`new-game/${state.active_prompt.id}`) }
1211           >
1212             New Game
1213             <div className="vote-choices">
1214               {[...state.new_game_votes].map(v => {
1215                 return (
1216                   <div
1217                     key={v}
1218                     className="vote-choice"
1219                   >
1220                     {v}
1221                   </div>
1222                 );
1223               })}
1224             </div>
1225           </button>
1226         </div>
1227       );
1228     }
1229
1230     if (state.ambiguities){
1231       return <Ambiguities
1232                prompt={state.active_prompt}
1233                words={state.ambiguities}
1234                player={state.player_info}
1235                players_judged={state.players_judged}
1236                players_judging={state.players_judging}
1237                idle={state.judging_idle}
1238                votes={state.end_judging_votes}
1239              />;
1240     }
1241
1242     if (state.active_prompt) {
1243       return <ActivePrompt
1244                prompt={state.active_prompt}
1245                player={state.player_info}
1246                players_answered={state.players_answered}
1247                players_answering={state.players_answering}
1248                idle={state.answering_idle}
1249                votes={state.end_answers_votes}
1250              />;
1251     }
1252
1253     if (! state.ready)
1254       return null;
1255
1256     return [
1257       <GameInfo
1258         key="game-info"
1259         id={state.game_info.id}
1260         url={state.game_info.url}
1261       />,
1262       <PlayerInfo
1263         key="player-info"
1264         game={this}
1265         player={state.player_info}
1266         other_players={state.other_players}
1267       />,
1268       <p key="spacer"></p>,
1269       <CategoryRequest
1270         key="category-request"
1271       />,
1272       <PromptOptions
1273         key="prompts"
1274         prompts={state.prompts}
1275         player={state.player_info}
1276       />,
1277       <LetsPlay
1278         key="lets-play"
1279         num_players={1+state.other_players.length}
1280         prompts={state.prompts}
1281       />
1282     ];
1283   }
1284 }
1285
1286 ReactDOM.render(<Game
1287                   ref={(me) => window.game = me}
1288                 />, document.getElementById("empathy"));