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_scores(state.scores);
68 window.game.set_ambiguities(state.ambiguities);
71 events.addEventListener("prompt", event => {
72 const prompt = JSON.parse(event.data);
74 window.game.add_or_update_prompt(prompt);
77 events.addEventListener("start", event => {
78 const prompt = JSON.parse(event.data);
80 window.game.set_active_prompt(prompt);
83 events.addEventListener("player-answered", event => {
84 const player = JSON.parse(event.data);
86 window.game.set_player_answered(player);
89 events.addEventListener("player-answering", event => {
90 const player = JSON.parse(event.data);
92 window.game.set_player_answering(player);
95 events.addEventListener("vote-end-answers", event => {
96 const player = JSON.parse(event.data);
98 window.game.set_player_vote_end_answers(player);
101 events.addEventListener("unvote-end-answers", event => {
102 const player = JSON.parse(event.data);
104 window.game.set_player_unvote_end_answers(player);
107 events.addEventListener("ambiguities", event => {
108 const ambiguities = JSON.parse(event.data);
110 window.game.set_ambiguities(ambiguities);
113 events.addEventListener("player-judged", event => {
114 const player = JSON.parse(event.data);
116 window.game.set_player_judged(player);
119 events.addEventListener("player-judging", event => {
120 const player = JSON.parse(event.data);
122 window.game.set_player_judging(player);
125 events.addEventListener("vote-end-judging", event => {
126 const player = JSON.parse(event.data);
128 window.game.set_player_vote_end_judging(player);
131 events.addEventListener("unvote-end-judging", event => {
132 const player = JSON.parse(event.data);
134 window.game.set_player_unvote_end_judging(player);
137 events.addEventListener("scores", event => {
138 const scores = JSON.parse(event.data);
140 window.game.set_scores(scores);
143 /*********************************************************
144 * Game and supporting classes *
145 *********************************************************/
147 function copy_to_clipboard(id)
149 const tmp = document.createElement("input");
150 tmp.setAttribute("value", document.getElementById(id).innerHTML);
151 document.body.appendChild(tmp);
153 document.execCommand("copy");
154 document.body.removeChild(tmp);
157 const GameInfo = React.memo(props => {
162 <div className="game-info">
163 <span className="game-id">{props.id}</span>
165 Share this link to invite friends:{" "}
166 <span id="game-share-url">{props.url}</span>
170 onClick={() => copy_to_clipboard('game-share-url')}
176 const PlayerInfo = React.memo(props => {
177 if (! props.player.id)
181 <div className="player-info">
182 <span className="players-header">Players: </span>
184 {props.player.score > 0 ? ` (${props.player.score})` : ""}
185 {props.other_players.map(other => (
186 <span key={other.id}>
189 {other.score > 0 ? ` (${other.score})` : ""}
196 function fetch_method_json(method, api = '', data = {}) {
197 const response = fetch(api, {
200 'Content-Type': 'application/json'
202 body: JSON.stringify(data)
207 function fetch_post_json(api = '', data = {}) {
208 return fetch_method_json('POST', api, data);
211 async function fetch_put_json(api = '', data = {}) {
212 return fetch_method_json('PUT', api, data);
215 class CategoryRequest extends React.PureComponent {
218 this.category = React.createRef();
220 this.handle_change = this.handle_change.bind(this);
221 this.handle_submit = this.handle_submit.bind(this);
224 handle_change(event) {
225 const category_input = this.category.current;
226 const category = category_input.value;
228 const match = category.match(/[0-9]+/);
230 const num_items = parseInt(match[0], 10);
231 if (num_items <= MAX_PROMPT_ITEMS)
232 category_input.setCustomValidity("");
236 async handle_submit(event) {
237 const form = event.currentTarget;
238 const category_input = this.category.current;
239 const category = category_input.value;
241 /* Prevent the default page-changing form-submission behavior. */
242 event.preventDefault();
244 const match = category.match(/[0-9]+/);
245 if (match === null) {
246 category_input.setCustomValidity("Category must include a number");
247 form.reportValidity();
251 const num_items = parseInt(match[0], 10);
253 if (num_items > MAX_PROMPT_ITEMS) {
254 category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
255 form.reportValidity();
259 const response = await fetch_post_json("prompts", {
264 if (response.status === 200) {
265 const result = await response.json();
266 if (! result.valid) {
267 add_message("danger", result.message);
271 add_message("danger", "An error occurred submitting your category");
279 <div className="category-request">
280 <h2>Submit a Category</h2>
282 Suggest a category to play. Don't forget to include the
283 number of items for each person to submit.
286 <form onSubmit={this.handle_submit} >
287 <div className="form-field large">
291 placeholder="6 things at the beach"
294 onChange={this.handle_change}
299 <div className="form-field large">
300 <button type="submit">
311 const PromptOptions = React.memo(props => {
313 if (props.prompts.length === 0)
317 <div className="prompt-options">
318 <h2>Vote on Categories</h2>
320 Select any categories below that you'd like to play.
321 You can choose as many as you'd like.
323 {props.prompts.map(p => {
326 className="vote-button"
328 onClick={() => fetch_post_json(`vote/${p.id}`) }
331 <div className="vote-choices">
336 className="vote-choice"
350 const LetsPlay = React.memo(props => {
352 function handle_click(prompt_id) {
356 const quorum = Math.round((props.num_players + 1) / 2);
357 const max_votes = props.prompts.reduce(
358 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
360 if (max_votes < quorum)
363 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
364 const index = Math.floor(Math.random() * candidates.length);
365 const winner = candidates[index];
368 <div className="lets-play">
371 That should be enough voting. If you're not waiting for any
372 other players to join, then let's start.
375 className="lets-play"
376 onClick={() => fetch_post_json(`start/${winner.id}`) }
384 class Ambiguities extends React.PureComponent {
389 const word_sets = props.words.map(word => {
390 const set = new Set();
396 word_sets: word_sets,
402 async handle_submit() {
403 const response = await fetch_post_json(
404 `judging/${this.props.prompt.id}`,{
405 word_groups: this.state.word_sets.map(set => Array.from(set))
409 if (response.status === 200) {
410 const result = await response.json();
411 if (! result.valid) {
412 add_message("danger", result.message);
416 add_message("danger", "An error occurred submitting your answers");
426 if (this.state.selected == word) {
427 /* Second click on same word removes the word from the group. */
428 const idx = this.state.word_sets.findIndex(s => s.has(word));
429 const set = this.state.word_sets[idx];
432 const new_set = new Set([...set].filter(w => w !== word));
435 word_sets: [...this.state.word_sets.slice(0, idx),
438 ...this.state.word_sets.slice(idx+1)]
440 } else if (this.state.selected) {
441 /* Click of a second word groups the two together. */
442 const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
443 const idx2 = this.state.word_sets.findIndex(s => s.has(word));
444 const set1 = this.state.word_sets[idx1];
445 const set2 = this.state.word_sets[idx2];
446 const new_set = new Set([...set2, ...set1]);
450 word_sets: [...this.state.word_sets.slice(0, idx1),
451 ...this.state.word_sets.slice(idx1 + 1, idx2),
453 ...this.state.word_sets.slice(idx2 + 1)]
458 word_sets: [...this.state.word_sets.slice(0, idx2),
460 ...this.state.word_sets.slice(idx2 + 1, idx1),
461 ...this.state.word_sets.slice(idx1 + 1)]
465 /* First click of a word selects it. */
473 if (this.state.submitted)
475 <div className="please-wait">
476 <h2>Submission received</h2>
478 The following players have completed judging:
479 {[...this.props.players_judged].join(', ')}
482 Still waiting for the following players:
485 {Object.entries(this.props.players_judging).map(player => {
491 {this.props.players_judging[player] ?
492 <span className="typing"/> : null }
498 className="vote-button"
499 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
502 <div className="vote-choices">
503 {[...this.props.votes].map(v => {
507 className="vote-choice"
519 const btn_class = "ambiguity-button";
520 const btn_selected_class = btn_class + " selected";
523 <div className="ambiguities">
524 <h2>Judging Answers</h2>
526 Click on each pair of answers that should be scored as equivalent,
527 (and click any word twice to split it out from a group). Remember,
528 what goes around comes around, so it's best to be generous when
531 {this.state.word_sets.map(set => {
534 className="ambiguity-group"
535 key={Array.from(set)[0]}
537 {Array.from(set).map(word => {
540 className={this.state.selected === word ?
541 btn_selected_class : btn_class }
543 onClick={() => this.handle_click(word)}
553 Click here when done judging:<br/>
555 onClick={() => this.handle_submit()}
565 class ActivePrompt extends React.PureComponent {
569 const items = props.prompt.items;
575 this.answers = [...Array(items)].map(() => React.createRef());
576 this.handle_submit = this.handle_submit.bind(this);
579 async handle_submit(event) {
580 const form = event.currentTarget;
582 /* Prevent the default page-changing form-submission behavior. */
583 event.preventDefault();
585 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
586 answers: this.answers.map(r => r.current.value)
588 if (response.status === 200) {
589 const result = await response.json();
590 if (! result.valid) {
591 add_message("danger", result.message);
595 add_message("danger", "An error occurred submitting your answers");
599 /* Everything worked. Server is happy with our answers. */
607 if (this.state.submitted)
609 <div className="please-wait">
610 <h2>Submission received</h2>
612 The following players have submitted their answers:
613 {[...this.props.players_answered].join(', ')}
616 Still waiting for the following players:
619 {Object.entries(this.props.players_answering).map(player => {
625 {this.props.players_answering[player] ?
626 <span className="typing"/> : null }
632 className="vote-button"
633 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
636 <div className="vote-choices">
637 {[...this.props.votes].map(v => {
641 className="vote-choice"
654 <div className="active-prompt">
655 <h2>The Game of Empathy</h2>
657 Remember, you're trying to match your answers with
658 what the other players submit.
659 Give {this.props.prompt.items} answers for the following prompt:
661 <h2>{this.props.prompt.prompt}</h2>
662 <form onSubmit={this.handle_submit}>
663 {[...Array(this.props.prompt.items)].map((whocares,i) => {
667 className="form-field large">
673 ref={this.answers[i]}
681 className="form-field large">
682 <button type="submit">
693 class Game extends React.PureComponent {
702 players_answered: new Set(),
703 players_answering: {},
704 end_answers_votes: new Set(),
706 players_judged: new Set(),
708 end_judging_votes: new Set(),
713 set_game_info(info) {
719 set_player_info(info) {
725 set_other_player_info(info) {
726 const other_players_copy = [...this.state.other_players];
727 const idx = other_players_copy.findIndex(o => o.id === info.id);
729 other_players_copy[idx] = info;
731 other_players_copy.push(info);
734 other_players: other_players_copy
742 players_answered: new Set(),
743 players_answering: {},
744 end_answers_votes: new Set(),
746 players_judged: new Set(),
748 end_judging_votes: new Set(),
753 set_prompts(prompts) {
759 add_or_update_prompt(prompt) {
760 const prompts_copy = [...this.state.prompts];
761 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
763 prompts_copy[idx] = prompt;
765 prompts_copy.push(prompt);
768 prompts: prompts_copy
772 set_active_prompt(prompt) {
774 active_prompt: prompt
778 set_player_answered(player) {
779 const new_players_answering = {...this.state.players_answering};
780 delete new_players_answering[player];
783 players_answered: new Set([...this.state.players_answered, player]),
784 players_answering: new_players_answering
788 set_player_answering(player) {
791 ...this.state.players_answering,
792 [player]: {active: true}
797 set_player_vote_end_answers(player) {
799 end_answers_votes: new Set([...this.state.end_answers_votes, player])
803 set_player_unvote_end_answers(player) {
805 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
809 set_ambiguities(ambiguities) {
811 ambiguities: ambiguities
815 set_player_judged(player) {
816 const new_players_judging = {...this.state.players_judging};
817 delete new_players_judging[player];
820 players_judged: new Set([...this.state.players_judged, player]),
821 players_judging: new_players_judging
825 set_player_judging(player) {
828 ...this.state.players_judging,
829 [player]: {active: true}
835 set_player_vote_end_judging(player) {
837 end_judging_votes: new Set([...this.state.end_judging_votes, player])
841 set_player_unvote_end_judging(player) {
843 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
854 const state = this.state;
855 const players_total = 1 + state.other_players.length;
859 <div className="scores">
862 {state.scores.scores.map(score => {
864 <li key={score.player}>
865 {score.player}: {score.score}
870 <h2>Words submitted</h2>
872 {state.scores.words.map(word => {
875 {`${word.word}: ${word.players.join(', ')}`}
882 onClick={() => fetch_post_json('reset') }
890 if (state.ambiguities){
892 prompt={state.active_prompt}
893 words={state.ambiguities}
894 players_judged={state.players_judged}
895 players_judging={state.players_judging}
896 votes={state.end_judging_votes}
900 if (state.active_prompt) {
902 prompt={state.active_prompt}
903 players_answered={state.players_answered}
904 players_answering={state.players_answering}
905 votes={state.end_answers_votes}
912 id={state.game_info.id}
913 url={state.game_info.url}
918 player={state.player_info}
919 other_players={state.other_players}
921 <p key="spacer"></p>,
923 key="category-request"
927 prompts={state.prompts}
931 num_players={1+state.other_players.length}
932 prompts={state.prompts}
938 ReactDOM.render(<Game
939 ref={(me) => window.game = me}
940 />, document.getElementById("empathy"));