1 const MAX_PROMPT_ITEMS = 20;
3 function undisplay(element) {
4 element.style.display="none";
7 function add_message(severity, message) {
8 message = `<div class="message ${severity}" onclick="undisplay(this)">
9 <span class="hide-button" onclick="undisplay(this.parentElement)">×</span>
12 const message_area = document.getElementById('message-area');
13 message_area.insertAdjacentHTML('beforeend', message);
16 /*********************************************************
17 * Handling server-sent event stream *
18 *********************************************************/
20 const events = new EventSource("events");
22 events.onerror = function(event) {
23 if (event.target.readyState === EventSource.CLOSED) {
25 add_message("danger", "Connection to server lost.");
30 events.addEventListener("game-info", event => {
31 const info = JSON.parse(event.data);
33 window.game.set_game_info(info);
36 events.addEventListener("player-info", event => {
37 const info = JSON.parse(event.data);
39 window.game.set_player_info(info);
42 events.addEventListener("player-enter", event => {
43 const info = JSON.parse(event.data);
45 window.game.set_other_player_info(info);
48 events.addEventListener("player-update", event => {
49 const info = JSON.parse(event.data);
51 if (info.id === window.game.state.player_info.id)
52 window.game.set_player_info(info);
54 window.game.set_other_player_info(info);
57 events.addEventListener("game-state", event => {
58 const state = JSON.parse(event.data);
60 window.game.reset_game_state();
62 window.game.set_prompts(state.prompts);
64 window.game.set_active_prompt(state.active_prompt);
66 window.game.set_players_answered(state.players_answered);
68 window.game.set_players_answering(state.players_answering);
70 window.game.set_answering_idle(state.answering_idle);
72 window.game.set_end_answers(state.end_answers);
74 window.game.set_ambiguities(state.ambiguities);
76 window.game.set_players_judged(state.players_judged);
78 window.game.set_players_judging(state.players_judging);
80 window.game.set_judging_idle(state.judging_idle);
82 window.game.set_end_judging(state.end_judging);
84 window.game.set_scores(state.scores);
87 events.addEventListener("prompt", event => {
88 const prompt = JSON.parse(event.data);
90 window.game.add_or_update_prompt(prompt);
93 events.addEventListener("start", event => {
94 const prompt = JSON.parse(event.data);
96 window.game.set_active_prompt(prompt);
99 events.addEventListener("player-answered", event => {
100 const player = JSON.parse(event.data);
102 window.game.set_player_answered(player);
105 events.addEventListener("player-answering", event => {
106 const player = JSON.parse(event.data);
108 window.game.set_player_answering(player);
111 events.addEventListener("answering-idle", event => {
112 const value = JSON.parse(event.data);
114 window.game.set_answering_idle(value);
117 events.addEventListener("vote-end-answers", event => {
118 const player = JSON.parse(event.data);
120 window.game.set_player_vote_end_answers(player);
123 events.addEventListener("unvote-end-answers", event => {
124 const player = JSON.parse(event.data);
126 window.game.set_player_unvote_end_answers(player);
129 events.addEventListener("ambiguities", event => {
130 const ambiguities = JSON.parse(event.data);
132 window.game.set_ambiguities(ambiguities);
135 events.addEventListener("player-judged", event => {
136 const player = JSON.parse(event.data);
138 window.game.set_player_judged(player);
141 events.addEventListener("player-judging", event => {
142 const player = JSON.parse(event.data);
144 window.game.set_player_judging(player);
147 events.addEventListener("judging-idle", event => {
148 const value = JSON.parse(event.data);
150 window.game.set_judging_idle(value);
153 events.addEventListener("vote-end-judging", event => {
154 const player = JSON.parse(event.data);
156 window.game.set_player_vote_end_judging(player);
159 events.addEventListener("unvote-end-judging", event => {
160 const player = JSON.parse(event.data);
162 window.game.set_player_unvote_end_judging(player);
165 events.addEventListener("scores", event => {
166 const scores = JSON.parse(event.data);
168 window.game.set_scores(scores);
171 /*********************************************************
172 * Game and supporting classes *
173 *********************************************************/
175 function copy_to_clipboard(id)
177 const tmp = document.createElement("input");
178 tmp.setAttribute("value", document.getElementById(id).innerHTML);
179 document.body.appendChild(tmp);
181 document.execCommand("copy");
182 document.body.removeChild(tmp);
185 const GameInfo = React.memo(props => {
190 <div className="game-info">
191 <span className="game-id">{props.id}</span>
193 Share this link to invite friends:{" "}
194 <span id="game-share-url">{props.url}</span>
198 onClick={() => copy_to_clipboard('game-share-url')}
204 const PlayerInfo = React.memo(props => {
205 if (! props.player.id)
208 const sorted_players = [props.player, ...props.other_players].sort((a,b) => {
209 return b.score - a.score;
213 <div className="player-info">
214 <span className="players-header">Players: </span>
215 {sorted_players.map(player => (
216 <span key={player.id}>
218 {player.score > 0 ? ` (${player.score})` : ""}
226 function fetch_method_json(method, api = '', data = {}) {
227 const response = fetch(api, {
230 'Content-Type': 'application/json'
232 body: JSON.stringify(data)
237 function fetch_post_json(api = '', data = {}) {
238 return fetch_method_json('POST', api, data);
241 async function fetch_put_json(api = '', data = {}) {
242 return fetch_method_json('PUT', api, data);
245 class CategoryRequest extends React.PureComponent {
248 this.category = React.createRef();
250 this.handle_change = this.handle_change.bind(this);
251 this.handle_submit = this.handle_submit.bind(this);
254 handle_change(event) {
255 const category_input = this.category.current;
256 const category = category_input.value;
258 const match = category.match(/[0-9]+/);
260 const num_items = parseInt(match[0], 10);
261 if (num_items <= MAX_PROMPT_ITEMS)
262 category_input.setCustomValidity("");
266 async handle_submit(event) {
267 const form = event.currentTarget;
268 const category_input = this.category.current;
269 const category = category_input.value;
271 /* Prevent the default page-changing form-submission behavior. */
272 event.preventDefault();
274 const match = category.match(/[0-9]+/);
275 if (match === null) {
276 category_input.setCustomValidity("Category must include a number");
277 form.reportValidity();
281 const num_items = parseInt(match[0], 10);
283 if (num_items > MAX_PROMPT_ITEMS) {
284 category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
285 form.reportValidity();
289 const response = await fetch_post_json("prompts", {
294 if (response.status === 200) {
295 const result = await response.json();
296 if (! result.valid) {
297 add_message("danger", result.message);
301 add_message("danger", "An error occurred submitting your category");
309 <div className="category-request">
310 <h2>Submit a Category</h2>
312 Suggest a category to play. Don't forget to include the
313 number of items for each person to submit.
316 <form onSubmit={this.handle_submit} >
317 <div className="form-field large">
321 placeholder="6 things at the beach"
324 onChange={this.handle_change}
329 <div className="form-field large">
330 <button type="submit">
341 const PromptOptions = React.memo(props => {
343 if (props.prompts.length === 0)
347 <div className="prompt-options">
348 <h2>Vote on Categories</h2>
350 Select any categories below that you'd like to play.
351 You can choose as many as you'd like.
353 {props.prompts.map(p => {
356 className="vote-button"
358 onClick={() => fetch_post_json(`vote/${p.id}`) }
361 <div className="vote-choices">
366 className="vote-choice"
380 const LetsPlay = React.memo(props => {
382 const quorum = Math.round((props.num_players + 1) / 2);
383 const max_votes = props.prompts.reduce(
384 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
386 if (max_votes < quorum)
389 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
390 const index = Math.floor(Math.random() * candidates.length);
391 const winner = candidates[index];
394 <div className="lets-play">
397 That should be enough voting. If you're not waiting for any
398 other players to join, then let's start.
401 className="lets-play"
402 onClick={() => fetch_post_json(`start/${winner.id}`) }
410 class Ambiguities extends React.PureComponent {
415 const word_sets = props.words.map(word => {
416 const set = new Set();
422 word_sets: word_sets,
426 this.submitted = false;
427 this.judging_sent_recently = false;
430 async handle_submit() {
432 /* Don't submit a second time. */
436 const response = await fetch_post_json(
437 `judged/${this.props.prompt.id}`,{
438 word_groups: this.state.word_sets.map(set => Array.from(set))
442 if (response.status === 200) {
443 const result = await response.json();
444 if (! result.valid) {
445 add_message("danger", result.message);
449 add_message("danger", "An error occurred submitting the results of your judging");
453 this.submitted = true;
458 /* Let the server know we are doing some judging, (but rate limit
459 * this so we don't send a "judging" notification more frquently
462 if (! this.judging_sent_recently) {
463 fetch_post_json(`judging/${this.props.prompt.id}`);
464 this.judging_sent_recently = true;
465 setTimeout(() => { this.judging_sent_recently = false; }, 1000);
468 if (this.state.selected == word) {
469 /* Second click on same word removes the word from the group. */
470 const idx = this.state.word_sets.findIndex(s => s.has(word));
471 const set = this.state.word_sets[idx];
472 if (set.size === 1) {
473 /* When the word is already alone, there's nothing to do but
474 * to un-select it. */
481 const new_set = new Set([...set].filter(w => w !== word));
484 word_sets: [...this.state.word_sets.slice(0, idx),
487 ...this.state.word_sets.slice(idx+1)]
489 } else if (this.state.selected) {
490 /* Click of a second word groups the two together. */
491 const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
492 const idx2 = this.state.word_sets.findIndex(s => s.has(word));
493 const set1 = this.state.word_sets[idx1];
494 const set2 = this.state.word_sets[idx2];
495 const new_set = new Set([...set2, ...set1]);
499 word_sets: [...this.state.word_sets.slice(0, idx1),
500 ...this.state.word_sets.slice(idx1 + 1, idx2),
502 ...this.state.word_sets.slice(idx2 + 1)]
507 word_sets: [...this.state.word_sets.slice(0, idx2),
509 ...this.state.word_sets.slice(idx2 + 1, idx1),
510 ...this.state.word_sets.slice(idx1 + 1)]
514 /* First click of a word selects it. */
522 let move_on_button = null;
524 if (this.props.idle) {
527 className="vote-button"
528 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
531 <div className="vote-choices">
532 {[...this.props.votes].map(v => {
536 className="vote-choice"
547 if (this.props.players_judged.has(this.props.player.name)) {
549 <div className="please-wait">
550 <h2>Submission received</h2>
552 The following players have completed judging:
553 {[...this.props.players_judged].join(', ')}
556 Still waiting for the following players:
559 {Object.keys(this.props.players_judging).map(player => {
565 {this.props.players_judging[player] ?
566 <span className="typing"/> : null }
577 const btn_class = "ambiguity-button";
578 const btn_selected_class = btn_class + " selected";
581 <div className="ambiguities">
582 <h2>Judging Answers</h2>
584 Click on each pair of answers that should be scored as equivalent,
585 (and click any word twice to split it out from a group). Remember,
586 what goes around comes around, so it's best to be generous when
589 {this.state.word_sets.map(set => {
592 className="ambiguity-group"
593 key={Array.from(set)[0]}
595 {Array.from(set).map(word => {
598 className={this.state.selected === word ?
599 btn_selected_class : btn_class }
601 onClick={() => this.handle_click(word)}
611 Click here when done judging:<br/>
613 onClick={() => this.handle_submit()}
623 class ActivePrompt extends React.PureComponent {
627 const items = props.prompt.items;
629 this.submitted = false;
631 this.answers = [...Array(items)].map(() => React.createRef());
632 this.answering_sent_recently = false;
634 this.handle_submit = this.handle_submit.bind(this);
635 this.handle_change = this.handle_change.bind(this);
638 handle_change(event) {
639 /* We don't care (or even look) at what the player is typing at
640 * this point. We simply want to be informed that the player _is_
641 * typing so that we can tell the server (which will tell other
642 * players) that there is activity here.
645 /* Rate limit so that we don't send an "answering" notification
646 * more frequently than necessary.
648 if (! this.answering_sent_recently) {
649 fetch_post_json(`answering/${this.props.prompt.id}`);
650 this.answering_sent_recently = true;
651 setTimeout(() => { this.answering_sent_recently = false; }, 1000);
655 async handle_submit(event) {
656 const form = event.currentTarget;
658 /* Prevent the default page-changing form-submission behavior. */
659 event.preventDefault();
661 /* And don't submit a second time. */
665 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
666 answers: this.answers.map(r => r.current.value)
668 if (response.status === 200) {
669 const result = await response.json();
670 if (! result.valid) {
671 add_message("danger", result.message);
675 add_message("danger", "An error occurred submitting your answers");
679 /* Everything worked. Server is happy with our answers. */
681 this.submitted = true;
685 let move_on_button = null;
686 if (this.props.idle) {
689 className="vote-button"
690 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
693 <div className="vote-choices">
694 {[...this.props.votes].map(v => {
698 className="vote-choice"
709 if (this.props.players_answered.has(this.props.player.name)) {
711 <div className="please-wait">
712 <h2>Submission received</h2>
714 The following players have submitted their answers:
715 {[...this.props.players_answered].join(', ')}
718 Still waiting for the following players:
721 {Object.keys(this.props.players_answering).map(player => {
727 {this.props.players_answering[player] ?
728 <span className="typing"/> : null }
740 <div className="active-prompt">
741 <h2>The Game of Empathy</h2>
743 Remember, you're trying to match your answers with
744 what the other players submit.
745 Give {this.props.prompt.items} answers for the following prompt:
747 <h2>{this.props.prompt.prompt}</h2>
748 <form onSubmit={this.handle_submit}>
749 {[...Array(this.props.prompt.items)].map((whocares,i) => {
753 className="form-field large">
759 onChange={this.handle_change}
760 ref={this.answers[i]}
768 className="form-field large">
769 <button type="submit">
780 class Game extends React.PureComponent {
789 players_answered: new Set(),
790 players_answering: {},
791 answering_idle: false,
792 end_answers_votes: new Set(),
794 players_judged: new Set(),
797 end_judging_votes: new Set(),
802 set_game_info(info) {
808 set_player_info(info) {
814 set_other_player_info(info) {
815 const other_players_copy = [...this.state.other_players];
816 const idx = other_players_copy.findIndex(o => o.id === info.id);
818 other_players_copy[idx] = info;
820 other_players_copy.push(info);
823 other_players: other_players_copy
831 players_answered: new Set(),
832 players_answering: {},
833 answering_idle: false,
834 end_answers_votes: new Set(),
836 players_judged: new Set(),
839 end_judging_votes: new Set(),
844 set_prompts(prompts) {
850 add_or_update_prompt(prompt) {
851 const prompts_copy = [...this.state.prompts];
852 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
854 prompts_copy[idx] = prompt;
856 prompts_copy.push(prompt);
859 prompts: prompts_copy
863 set_active_prompt(prompt) {
865 active_prompt: prompt
869 set_players_answered(players) {
871 players_answered: new Set(players)
875 set_player_answered(player) {
876 const new_players_answering = {...this.state.players_answering};
877 delete new_players_answering[player];
880 players_answered: new Set([...this.state.players_answered, player]),
881 players_answering: new_players_answering
885 set_players_answering(players) {
886 const players_answering = {};
887 for (let player of players) {
888 players_answering[player] = {active: false};
891 players_answering: players_answering
895 set_player_answering(player) {
898 ...this.state.players_answering,
899 [player]: {active: true}
904 set_answering_idle(value) {
906 answering_idle: value
910 set_end_answers(players) {
912 end_answers_votes: new Set(players)
916 set_player_vote_end_answers(player) {
918 end_answers_votes: new Set([...this.state.end_answers_votes, player])
922 set_player_unvote_end_answers(player) {
924 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
928 set_ambiguities(ambiguities) {
930 ambiguities: ambiguities
934 set_players_judged(players) {
936 players_judged: new Set(players)
940 set_player_judged(player) {
941 const new_players_judging = {...this.state.players_judging};
942 delete new_players_judging[player];
945 players_judged: new Set([...this.state.players_judged, player]),
946 players_judging: new_players_judging
950 set_players_judging(players) {
951 const players_judging = {};
952 for (let player of players) {
953 players_judging[player] = {active: false};
956 players_judging: players_judging
960 set_player_judging(player) {
963 ...this.state.players_judging,
964 [player]: {active: true}
969 set_judging_idle(value) {
970 console.log("Setting judging idle to " + value);
976 set_end_judging(players) {
978 end_judging_votes: new Set(players)
982 set_player_vote_end_judging(player) {
984 end_judging_votes: new Set([...this.state.end_judging_votes, player])
988 set_player_unvote_end_judging(player) {
990 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1001 const state = this.state;
1002 const players_total = 1 + state.other_players.length;
1006 <div className="scores">
1009 {state.scores.scores.map(score => {
1011 <li key={score.player}>
1012 {score.player}: {score.score}
1017 <h2>Words submitted</h2>
1019 {state.scores.words.map(word => {
1021 <li key={word.word}>
1022 {`${word.word}: ${word.players.join(', ')}`}
1028 className="new-game"
1029 onClick={() => fetch_post_json('reset') }
1037 if (state.ambiguities){
1039 prompt={state.active_prompt}
1040 words={state.ambiguities}
1041 player={state.player_info}
1042 players_judged={state.players_judged}
1043 players_judging={state.players_judging}
1044 idle={state.judging_idle}
1045 votes={state.end_judging_votes}
1049 if (state.active_prompt) {
1050 return <ActivePrompt
1051 prompt={state.active_prompt}
1052 player={state.player_info}
1053 players_answered={state.players_answered}
1054 players_answering={state.players_answering}
1055 idle={state.answering_idle}
1056 votes={state.end_answers_votes}
1063 id={state.game_info.id}
1064 url={state.game_info.url}
1069 player={state.player_info}
1070 other_players={state.other_players}
1072 <p key="spacer"></p>,
1074 key="category-request"
1078 prompts={state.prompts}
1082 num_players={1+state.other_players.length}
1083 prompts={state.prompts}
1089 ReactDOM.render(<Game
1090 ref={(me) => window.game = me}
1091 />, document.getElementById("empathy"));