d7e6f6f63df15514bfcec0758616797c54655fdc
[lmno.games] / empathy / 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 PromptOptions = React.memo(props => {
367
368   if (props.prompts.length === 0)
369     return null;
370
371   return (
372     <div className="prompt-options">
373       <h2>Vote on Categories</h2>
374       <p>
375         Select any categories below that you'd like to play.
376         You can choose as many as you'd like.
377       </p>
378       {props.prompts.map(p => {
379         return (
380           <button
381             className="vote-button"
382             key={p.id}
383             onClick={() => fetch_post_json(`vote/${p.id}`) }
384           >
385             {p.prompt}
386             <div className="vote-choices">
387               {p.votes.map(v => {
388                 return (
389                   <div
390                     key={v}
391                     className="vote-choice"
392                   >
393                     {v}
394                   </div>
395                 );
396               })}
397             </div>
398           </button>
399         );
400       })}
401     </div>
402   );
403 });
404
405 const LetsPlay = React.memo(props => {
406
407   const quorum = Math.round((props.num_players + 1) / 2);
408   const max_votes = props.prompts.reduce(
409     (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
410
411   if (max_votes < quorum)
412     return null;
413
414   const candidates = props.prompts.filter(p => p.votes.length >= quorum);
415   const index = Math.floor(Math.random() * candidates.length);
416   const winner = candidates[index];
417
418   return (
419     <div className="lets-play">
420       <h2>Let's Play</h2>
421       <p>
422         That should be enough voting. If you're not waiting for any
423         other players to join, then let's start.
424       </p>
425       <button
426         className="lets-play"
427         onClick={() => fetch_post_json(`start/${winner.id}`) }
428       >
429         Start Game
430       </button>
431     </div>
432   );
433 });
434
435 class Ambiguities extends React.PureComponent {
436
437   constructor(props) {
438     super(props);
439
440     const word_sets = props.words.map(word => {
441       const set = new Set();
442       set.add(word);
443       return set;
444     });
445
446     this.state = {
447       word_sets: word_sets,
448       selected: null
449     };
450
451     this.submitted = false;
452     this.judging_sent_recently = false;
453   }
454
455   async handle_submit() {
456
457     /* Don't submit a second time. */
458     if (this.submitted)
459       return;
460
461     const response = await fetch_post_json(
462       `judged/${this.props.prompt.id}`,{
463         word_groups: this.state.word_sets.map(set => Array.from(set))
464       }
465     );
466
467     if (response.status === 200) {
468       const result = await response.json();
469       if (! result.valid) {
470         add_message("danger", result.message);
471         return;
472       }
473     } else {
474       add_message("danger", "An error occurred submitting the results of your judging");
475       return;
476     }
477
478     this.submitted = true;
479   }
480
481   handle_click(word) {
482
483     /* Let the server know we are doing some judging, (but rate limit
484      * this so we don't send a "judging" notification more frquently
485      * than necessary.
486      */
487     if (! this.judging_sent_recently) {
488       fetch_post_json(`judging/${this.props.prompt.id}`);
489       this.judging_sent_recently = true;
490       setTimeout(() => { this.judging_sent_recently = false; }, 1000);
491     }
492
493     if (this.state.selected == word) {
494       /* Second click on same word removes the word from the group. */
495       const idx = this.state.word_sets.findIndex(s => s.has(word));
496       const set = this.state.word_sets[idx];
497       if (set.size === 1) {
498         /* When the word is already alone, there's nothing to do but
499          * to un-select it. */
500         this.setState({
501           selected: null
502         });
503         return;
504       }
505
506       const new_set = new Set([...set].filter(w => w !== word));
507       this.setState({
508         selected: null,
509         word_sets: [...this.state.word_sets.slice(0, idx),
510                     new_set,
511                     new Set().add(word),
512                     ...this.state.word_sets.slice(idx+1)]
513       });
514     } else if (this.state.selected) {
515       /* Click of a second word groups the two together. */
516       const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
517       const idx2 = this.state.word_sets.findIndex(s => s.has(word));
518       const set1 = this.state.word_sets[idx1];
519       const set2 = this.state.word_sets[idx2];
520       const new_set = new Set([...set2, ...set1]);
521       if (idx1 < idx2) {
522         this.setState({
523           selected: null,
524           word_sets: [...this.state.word_sets.slice(0, idx1),
525                       ...this.state.word_sets.slice(idx1 + 1, idx2),
526                       new_set,
527                       ...this.state.word_sets.slice(idx2 + 1)]
528         });
529       } else {
530         this.setState({
531           selected: null,
532           word_sets: [...this.state.word_sets.slice(0, idx2),
533                       new_set,
534                       ...this.state.word_sets.slice(idx2 + 1, idx1),
535                       ...this.state.word_sets.slice(idx1 + 1)]
536         });
537       }
538     } else {
539       /* First click of a word selects it. */
540       this.setState({
541         selected: word
542       });
543     }
544   }
545
546   render() {
547     let move_on_button = null;
548
549     if (this.props.idle) {
550       move_on_button = (
551         <button
552           className="vote-button"
553           onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
554         >
555           Move On
556           <div className="vote-choices">
557             {[...this.props.votes].map(v => {
558               return (
559                 <div
560                   key={v}
561                   className="vote-choice"
562                 >
563                   {v}
564                   </div>
565               );
566             })}
567           </div>
568         </button>
569       );
570     }
571
572     if (this.props.players_judged.has(this.props.player.name)) {
573       return (
574         <div className="please-wait">
575           <h2>Submission received</h2>
576           <p>
577             The following players have completed judging:{' '}
578             {[...this.props.players_judged].join(', ')}
579           </p>
580           <p>
581             Still waiting for the following players:
582           </p>
583           <ul>
584             {Object.keys(this.props.players_judging).map(player => {
585               return (
586                 <li
587                   key={player}
588                 >
589                   {player}
590                   {this.props.players_judging[player] ?
591                    <span className="typing"/> : null }
592                 </li>
593               );
594             })}
595           </ul>
596           {move_on_button}
597
598         </div>
599       );
600     }
601
602     const btn_class = "ambiguity-button";
603     const btn_selected_class = btn_class + " selected";
604
605     return (
606       <div className="ambiguities">
607         <h2>Judging Answers</h2>
608         <p>
609           Click on each pair of answers that should be scored as equivalent,
610           (and click any word twice to split it out from a group). Remember,
611           what goes around comes around, so it's best to be generous when
612           judging.
613         </p>
614         <h2>{this.props.prompt.prompt}</h2>
615         {this.state.word_sets.map(set => {
616           return (
617             <div
618               className="ambiguity-group"
619               key={Array.from(set)[0]}
620             >
621               {Array.from(set).map(word => {
622                 return (
623                   <button
624                     className={this.state.selected === word ?
625                                btn_selected_class : btn_class }
626                     key={word}
627                     onClick={() => this.handle_click(word)}
628                   >
629                     {word}
630                   </button>
631                 );
632               })}
633             </div>
634           );
635         })}
636         <p>
637           Click here when done judging:<br/>
638           <button
639             onClick={() => this.handle_submit()}
640           >
641             Send
642           </button>
643         </p>
644       </div>
645     );
646   }
647 }
648
649 class ActivePrompt extends React.PureComponent {
650
651   constructor(props) {
652     super(props);
653     const items = props.prompt.items;
654
655     this.submitted = false;
656
657     this.answers = [...Array(items)].map(() => React.createRef());
658     this.answering_sent_recently = false;
659
660     this.handle_submit = this.handle_submit.bind(this);
661     this.handle_change = this.handle_change.bind(this);
662   }
663
664   handle_change(event) {
665     /* We don't care (or even look) at what the player is typing at
666      * this point. We simply want to be informed that the player _is_
667      * typing so that we can tell the server (which will tell other
668      * players) that there is activity here.
669      */
670
671     /* Rate limit so that we don't send an "answering" notification
672      * more frequently than necessary.
673      */
674     if (! this.answering_sent_recently) {
675       fetch_post_json(`answering/${this.props.prompt.id}`);
676       this.answering_sent_recently = true;
677       setTimeout(() => { this.answering_sent_recently = false; }, 1000);
678     }
679   }
680
681   async handle_submit(event) {
682     const form = event.currentTarget;
683
684     /* Prevent the default page-changing form-submission behavior. */
685     event.preventDefault();
686
687     /* And don't submit a second time. */
688     if (this.submitted)
689       return;
690
691     const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
692       answers: this.answers.map(r => r.current.value)
693     });
694     if (response.status === 200) {
695       const result = await response.json();
696       if (! result.valid) {
697         add_message("danger", result.message);
698         return;
699       }
700     } else {
701       add_message("danger", "An error occurred submitting your answers");
702       return;
703     }
704
705     /* Everything worked. Server is happy with our answers. */
706     form.reset();
707     this.submitted = true;
708   }
709
710   render() {
711     let move_on_button = null;
712     if (this.props.idle) {
713       move_on_button =(
714         <button
715           className="vote-button"
716           onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
717         >
718           Move On
719           <div className="vote-choices">
720             {[...this.props.votes].map(v => {
721               return (
722                 <div
723                   key={v}
724                   className="vote-choice"
725                 >
726                   {v}
727                 </div>
728               );
729             })}
730           </div>
731         </button>
732       );
733     }
734
735     if (this.props.players_answered.has(this.props.player.name)) {
736       return (
737         <div className="please-wait">
738           <h2>Submission received</h2>
739           <p>
740             The following players have submitted their answers:{' '}
741             {[...this.props.players_answered].join(', ')}
742           </p>
743           <p>
744           Still waiting for the following players:
745           </p>
746           <ul>
747             {Object.keys(this.props.players_answering).map(player => {
748               return (
749                 <li
750                   key={player}
751                 >
752                   {player}
753                   {this.props.players_answering[player] ?
754                    <span className="typing"/> : null }
755                 </li>
756               );
757             })}
758           </ul>
759           {move_on_button}
760
761         </div>
762       );
763     }
764
765     return (
766       <div className="active-prompt">
767         <h2>The Game of Empathy</h2>
768         <p>
769           Remember, you're trying to match your answers with
770           what the other players submit.
771           Give {this.props.prompt.items} answers for the following prompt:
772         </p>
773         <h2>{this.props.prompt.prompt}</h2>
774         <form onSubmit={this.handle_submit}>
775           {[...Array(this.props.prompt.items)].map((whocares,i) => {
776             return (
777               <div
778                 key={i}
779                 className="form-field large">
780                 <input
781                   type="text"
782                   name={`answer_${i}`}
783                   required
784                   autoComplete="off"
785                   onChange={this.handle_change}
786                   ref={this.answers[i]}
787                 />
788               </div>
789             );
790           })}
791
792           <div
793             key="submit-button"
794             className="form-field large">
795             <button type="submit">
796               Send
797             </button>
798           </div>
799
800         </form>
801       </div>
802     );
803   }
804 }
805
806 class Game extends React.PureComponent {
807   constructor(props) {
808     super(props);
809     this.state = {
810       game_info: {},
811       player_info: {},
812       other_players: [],
813       prompts: [],
814       active_prompt: null,
815       players_answered: new Set(),
816       players_answering: {},
817       answering_idle: false,
818       end_answers_votes: new Set(),
819       ambiguities: null,
820       players_judged: new Set(),
821       players_judging: {},
822       judging_idle: false,
823       end_judging_votes: new Set(),
824       scores: null,
825       new_game_votes: new Set(),
826       ready: false
827     };
828   }
829
830   set_game_info(info) {
831     this.setState({
832       game_info: info
833     });
834   }
835
836   set_player_info(info) {
837     this.setState({
838       player_info: info
839     });
840   }
841
842   set_other_player_info(info) {
843     const other_players_copy = [...this.state.other_players];
844     const idx = other_players_copy.findIndex(o => o.id === info.id);
845     if (idx >= 0) {
846       other_players_copy[idx] = info;
847     } else {
848       other_players_copy.push(info);
849     }
850     this.setState({
851       other_players: other_players_copy
852     });
853   }
854
855   remove_player(info) {
856     this.setState({
857       other_players: this.state.other_players.filter(o => o.id !== info.id)
858     });
859   }
860
861   reset_game_state() {
862     this.setState({
863       prompts: [],
864       active_prompt: null,
865       players_answered: new Set(),
866       players_answering: {},
867       answering_idle: false,
868       end_answers_votes: new Set(),
869       ambiguities: null,
870       players_judged: new Set(),
871       players_judging: {},
872       judging_idle: false,
873       end_judging_votes: new Set(),
874       scores: null,
875       new_game_votes: new Set(),
876       ready: false
877     });
878   }
879
880   set_prompts(prompts) {
881     this.setState({
882       prompts: prompts
883     });
884   }
885
886   add_or_update_prompt(prompt) {
887     const prompts_copy = [...this.state.prompts];
888     const idx = prompts_copy.findIndex(p => p.id === prompt.id);
889     if (idx >= 0) {
890       prompts_copy[idx] = prompt;
891     } else {
892       prompts_copy.push(prompt);
893     }
894     this.setState({
895       prompts: prompts_copy
896     });
897   }
898
899   set_active_prompt(prompt) {
900     this.setState({
901       active_prompt: prompt
902     });
903   }
904
905   set_players_answered(players) {
906     this.setState({
907       players_answered: new Set(players)
908     });
909   }
910
911   set_player_answered(player) {
912     const new_players_answering = {...this.state.players_answering};
913     delete new_players_answering[player];
914
915     this.setState({
916       players_answered: new Set([...this.state.players_answered, player]),
917       players_answering: new_players_answering
918     });
919   }
920
921   set_players_answering(players) {
922     const players_answering = {};
923     for (let player of players) {
924       players_answering[player] = {active: false};
925     }
926     this.setState({
927       players_answering: players_answering
928     });
929   }
930
931   set_player_answering(player) {
932     this.setState({
933       players_answering: {
934         ...this.state.players_answering,
935         [player]: {active: true}
936       }
937     });
938   }
939
940   set_answering_idle(value) {
941     this.setState({
942       answering_idle: value
943     });
944   }
945
946   set_end_answers(players) {
947     this.setState({
948       end_answers_votes: new Set(players)
949     });
950   }
951
952   set_player_vote_end_answers(player) {
953     this.setState({
954       end_answers_votes: new Set([...this.state.end_answers_votes, player])
955     });
956   }
957
958   set_player_unvote_end_answers(player) {
959     this.setState({
960       end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
961     });
962   }
963
964   set_ambiguities(ambiguities) {
965     this.setState({
966       ambiguities: ambiguities
967     });
968   }
969
970   set_players_judged(players) {
971     this.setState({
972       players_judged: new Set(players)
973     });
974   }
975
976   set_player_judged(player) {
977     const new_players_judging = {...this.state.players_judging};
978     delete new_players_judging[player];
979
980     this.setState({
981       players_judged: new Set([...this.state.players_judged, player]),
982       players_judging: new_players_judging
983     });
984   }
985
986   set_players_judging(players) {
987     const players_judging = {};
988     for (let player of players) {
989       players_judging[player] = {active: false};
990     }
991     this.setState({
992       players_judging: players_judging
993     });
994   }
995
996   set_player_judging(player) {
997     this.setState({
998       players_judging: {
999         ...this.state.players_judging,
1000         [player]: {active: true}
1001       }
1002     });
1003   }
1004
1005   set_judging_idle(value) {
1006     this.setState({
1007       judging_idle: value
1008     });
1009   }
1010
1011   set_end_judging(players) {
1012     this.setState({
1013       end_judging_votes: new Set(players)
1014     });
1015   }
1016
1017   set_player_vote_end_judging(player) {
1018     this.setState({
1019       end_judging_votes: new Set([...this.state.end_judging_votes, player])
1020     });
1021   }
1022
1023   set_player_unvote_end_judging(player) {
1024     this.setState({
1025       end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1026     });
1027   }
1028
1029   set_scores(scores) {
1030     this.setState({
1031       scores: scores
1032     });
1033   }
1034
1035   set_new_game_votes(players) {
1036     this.setState({
1037       new_game_votes: new Set(players)
1038     });
1039   }
1040
1041   set_player_vote_new_game(player) {
1042     this.setState({
1043       new_game_votes: new Set([...this.state.new_game_votes, player])
1044     });
1045   }
1046
1047   set_player_unvote_new_game(player) {
1048     this.setState({
1049       new_game_votes: new Set([...this.state.new_game_votes].filter(p => p !== player))
1050     });
1051   }
1052
1053   state_ready() {
1054     this.setState({
1055       ready: true
1056     });
1057   }
1058
1059   render() {
1060     const state = this.state;
1061     const players_total = 1 + state.other_players.length;
1062
1063     if (state.scores) {
1064       return (
1065         <div className="scores">
1066           <h2>{state.active_prompt.prompt}</h2>
1067           <h2>Scores</h2>
1068           <ul>
1069             {state.scores.scores.map(score => {
1070               return (
1071                 <li key={score.player}>
1072                   {score.players.join("/")}: {score.score}
1073                 </li>
1074               );
1075             })}
1076           </ul>
1077           <h2>Words submitted</h2>
1078           <ul>
1079             {state.scores.words.map(word => {
1080               return (
1081                 <li key={word.word}>
1082                   {word.word} ({word.players.length}): {word.players.join(', ')}
1083                 </li>
1084               );
1085             })}
1086           </ul>
1087           <button
1088             className="vote-button"
1089             onClick={() => fetch_post_json(`new-game/${state.active_prompt.id}`) }
1090           >
1091             New Game
1092             <div className="vote-choices">
1093               {[...state.new_game_votes].map(v => {
1094                 return (
1095                   <div
1096                     key={v}
1097                     className="vote-choice"
1098                   >
1099                     {v}
1100                   </div>
1101                 );
1102               })}
1103             </div>
1104           </button>
1105         </div>
1106       );
1107     }
1108
1109     if (state.ambiguities){
1110       return <Ambiguities
1111                prompt={state.active_prompt}
1112                words={state.ambiguities}
1113                player={state.player_info}
1114                players_judged={state.players_judged}
1115                players_judging={state.players_judging}
1116                idle={state.judging_idle}
1117                votes={state.end_judging_votes}
1118              />;
1119     }
1120
1121     if (state.active_prompt) {
1122       return <ActivePrompt
1123                prompt={state.active_prompt}
1124                player={state.player_info}
1125                players_answered={state.players_answered}
1126                players_answering={state.players_answering}
1127                idle={state.answering_idle}
1128                votes={state.end_answers_votes}
1129              />;
1130     }
1131
1132     if (! state.ready)
1133       return null;
1134
1135     return [
1136       <GameInfo
1137         key="game-info"
1138         id={state.game_info.id}
1139         url={state.game_info.url}
1140       />,
1141       <PlayerInfo
1142         key="player-info"
1143         game={this}
1144         player={state.player_info}
1145         other_players={state.other_players}
1146       />,
1147       <p key="spacer"></p>,
1148       <CategoryRequest
1149         key="category-request"
1150       />,
1151       <PromptOptions
1152         key="prompts"
1153         prompts={state.prompts}
1154       />,
1155       <LetsPlay
1156         key="lets-play"
1157         num_players={1+state.other_players.length}
1158         prompts={state.prompts}
1159       />
1160     ];
1161   }
1162 }
1163
1164 ReactDOM.render(<Game
1165                   ref={(me) => window.game = me}
1166                 />, document.getElementById("empathy"));