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_end_judging(state.end_judging);
82 window.game.set_scores(state.scores);
85 events.addEventListener("prompt", event => {
86 const prompt = JSON.parse(event.data);
88 window.game.add_or_update_prompt(prompt);
91 events.addEventListener("start", event => {
92 const prompt = JSON.parse(event.data);
94 window.game.set_active_prompt(prompt);
97 events.addEventListener("player-answered", event => {
98 const player = JSON.parse(event.data);
100 window.game.set_player_answered(player);
103 events.addEventListener("player-answering", event => {
104 const player = JSON.parse(event.data);
106 window.game.set_player_answering(player);
109 events.addEventListener("answering-idle", event => {
110 const value = JSON.parse(event.data);
112 window.game.set_answering_idle(value);
115 events.addEventListener("vote-end-answers", event => {
116 const player = JSON.parse(event.data);
118 window.game.set_player_vote_end_answers(player);
121 events.addEventListener("unvote-end-answers", event => {
122 const player = JSON.parse(event.data);
124 window.game.set_player_unvote_end_answers(player);
127 events.addEventListener("ambiguities", event => {
128 const ambiguities = JSON.parse(event.data);
130 window.game.set_ambiguities(ambiguities);
133 events.addEventListener("player-judged", event => {
134 const player = JSON.parse(event.data);
136 window.game.set_player_judged(player);
139 events.addEventListener("player-judging", event => {
140 const player = JSON.parse(event.data);
142 window.game.set_player_judging(player);
145 events.addEventListener("vote-end-judging", event => {
146 const player = JSON.parse(event.data);
148 window.game.set_player_vote_end_judging(player);
151 events.addEventListener("unvote-end-judging", event => {
152 const player = JSON.parse(event.data);
154 window.game.set_player_unvote_end_judging(player);
157 events.addEventListener("scores", event => {
158 const scores = JSON.parse(event.data);
160 window.game.set_scores(scores);
163 /*********************************************************
164 * Game and supporting classes *
165 *********************************************************/
167 function copy_to_clipboard(id)
169 const tmp = document.createElement("input");
170 tmp.setAttribute("value", document.getElementById(id).innerHTML);
171 document.body.appendChild(tmp);
173 document.execCommand("copy");
174 document.body.removeChild(tmp);
177 const GameInfo = React.memo(props => {
182 <div className="game-info">
183 <span className="game-id">{props.id}</span>
185 Share this link to invite friends:{" "}
186 <span id="game-share-url">{props.url}</span>
190 onClick={() => copy_to_clipboard('game-share-url')}
196 const PlayerInfo = React.memo(props => {
197 if (! props.player.id)
201 <div className="player-info">
202 <span className="players-header">Players: </span>
204 {props.player.score > 0 ? ` (${props.player.score})` : ""}
205 {props.other_players.map(other => (
206 <span key={other.id}>
209 {other.score > 0 ? ` (${other.score})` : ""}
216 function fetch_method_json(method, api = '', data = {}) {
217 const response = fetch(api, {
220 'Content-Type': 'application/json'
222 body: JSON.stringify(data)
227 function fetch_post_json(api = '', data = {}) {
228 return fetch_method_json('POST', api, data);
231 async function fetch_put_json(api = '', data = {}) {
232 return fetch_method_json('PUT', api, data);
235 class CategoryRequest extends React.PureComponent {
238 this.category = React.createRef();
240 this.handle_change = this.handle_change.bind(this);
241 this.handle_submit = this.handle_submit.bind(this);
244 handle_change(event) {
245 const category_input = this.category.current;
246 const category = category_input.value;
248 const match = category.match(/[0-9]+/);
250 const num_items = parseInt(match[0], 10);
251 if (num_items <= MAX_PROMPT_ITEMS)
252 category_input.setCustomValidity("");
256 async handle_submit(event) {
257 const form = event.currentTarget;
258 const category_input = this.category.current;
259 const category = category_input.value;
261 /* Prevent the default page-changing form-submission behavior. */
262 event.preventDefault();
264 const match = category.match(/[0-9]+/);
265 if (match === null) {
266 category_input.setCustomValidity("Category must include a number");
267 form.reportValidity();
271 const num_items = parseInt(match[0], 10);
273 if (num_items > MAX_PROMPT_ITEMS) {
274 category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
275 form.reportValidity();
279 const response = await fetch_post_json("prompts", {
284 if (response.status === 200) {
285 const result = await response.json();
286 if (! result.valid) {
287 add_message("danger", result.message);
291 add_message("danger", "An error occurred submitting your category");
299 <div className="category-request">
300 <h2>Submit a Category</h2>
302 Suggest a category to play. Don't forget to include the
303 number of items for each person to submit.
306 <form onSubmit={this.handle_submit} >
307 <div className="form-field large">
311 placeholder="6 things at the beach"
314 onChange={this.handle_change}
319 <div className="form-field large">
320 <button type="submit">
331 const PromptOptions = React.memo(props => {
333 if (props.prompts.length === 0)
337 <div className="prompt-options">
338 <h2>Vote on Categories</h2>
340 Select any categories below that you'd like to play.
341 You can choose as many as you'd like.
343 {props.prompts.map(p => {
346 className="vote-button"
348 onClick={() => fetch_post_json(`vote/${p.id}`) }
351 <div className="vote-choices">
356 className="vote-choice"
370 const LetsPlay = React.memo(props => {
372 const quorum = Math.round((props.num_players + 1) / 2);
373 const max_votes = props.prompts.reduce(
374 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
376 if (max_votes < quorum)
379 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
380 const index = Math.floor(Math.random() * candidates.length);
381 const winner = candidates[index];
384 <div className="lets-play">
387 That should be enough voting. If you're not waiting for any
388 other players to join, then let's start.
391 className="lets-play"
392 onClick={() => fetch_post_json(`start/${winner.id}`) }
400 class Ambiguities extends React.PureComponent {
405 const word_sets = props.words.map(word => {
406 const set = new Set();
412 word_sets: word_sets,
416 this.submitted = false;
417 this.judging_sent_recently = false;
420 async handle_submit() {
422 /* Don't submit a second time. */
426 const response = await fetch_post_json(
427 `judged/${this.props.prompt.id}`,{
428 word_groups: this.state.word_sets.map(set => Array.from(set))
432 if (response.status === 200) {
433 const result = await response.json();
434 if (! result.valid) {
435 add_message("danger", result.message);
439 add_message("danger", "An error occurred submitting the results of your judging");
443 this.submitted = true;
448 /* Let the server know we are doing some judging, (but rate limit
449 * this so we don't send a "judging" notification more frquently
452 if (! this.judging_sent_recently) {
453 fetch_post_json(`judging/${this.props.prompt.id}`);
454 this.judging_sent_recently = true;
455 setTimeout(() => { this.judging_sent_recently = false; }, 1000);
458 if (this.state.selected == word) {
459 /* Second click on same word removes the word from the group. */
460 const idx = this.state.word_sets.findIndex(s => s.has(word));
461 const set = this.state.word_sets[idx];
462 if (set.size === 1) {
463 /* When the word is already alone, there's nothing to do but
464 * to un-select it. */
471 const new_set = new Set([...set].filter(w => w !== word));
474 word_sets: [...this.state.word_sets.slice(0, idx),
477 ...this.state.word_sets.slice(idx+1)]
479 } else if (this.state.selected) {
480 /* Click of a second word groups the two together. */
481 const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
482 const idx2 = this.state.word_sets.findIndex(s => s.has(word));
483 const set1 = this.state.word_sets[idx1];
484 const set2 = this.state.word_sets[idx2];
485 const new_set = new Set([...set2, ...set1]);
489 word_sets: [...this.state.word_sets.slice(0, idx1),
490 ...this.state.word_sets.slice(idx1 + 1, idx2),
492 ...this.state.word_sets.slice(idx2 + 1)]
497 word_sets: [...this.state.word_sets.slice(0, idx2),
499 ...this.state.word_sets.slice(idx2 + 1, idx1),
500 ...this.state.word_sets.slice(idx1 + 1)]
504 /* First click of a word selects it. */
512 if (this.props.players_judged.has(this.props.player.name)) {
514 <div className="please-wait">
515 <h2>Submission received</h2>
517 The following players have completed judging:
518 {[...this.props.players_judged].join(', ')}
521 Still waiting for the following players:
524 {Object.keys(this.props.players_judging).map(player => {
530 {this.props.players_judging[player] ?
531 <span className="typing"/> : null }
537 className="vote-button"
538 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
541 <div className="vote-choices">
542 {[...this.props.votes].map(v => {
546 className="vote-choice"
559 const btn_class = "ambiguity-button";
560 const btn_selected_class = btn_class + " selected";
563 <div className="ambiguities">
564 <h2>Judging Answers</h2>
566 Click on each pair of answers that should be scored as equivalent,
567 (and click any word twice to split it out from a group). Remember,
568 what goes around comes around, so it's best to be generous when
571 {this.state.word_sets.map(set => {
574 className="ambiguity-group"
575 key={Array.from(set)[0]}
577 {Array.from(set).map(word => {
580 className={this.state.selected === word ?
581 btn_selected_class : btn_class }
583 onClick={() => this.handle_click(word)}
593 Click here when done judging:<br/>
595 onClick={() => this.handle_submit()}
605 class ActivePrompt extends React.PureComponent {
609 const items = props.prompt.items;
611 this.submitted = false;
613 this.answers = [...Array(items)].map(() => React.createRef());
614 this.answering_sent_recently = false;
616 this.handle_submit = this.handle_submit.bind(this);
617 this.handle_change = this.handle_change.bind(this);
620 handle_change(event) {
621 /* We don't care (or even look) at what the player is typing at
622 * this point. We simply want to be informed that the player _is_
623 * typing so that we can tell the server (which will tell other
624 * players) that there is activity here.
627 /* Rate limit so that we don't send an "answering" notification
628 * more frequently than necessary.
630 if (! this.answering_sent_recently) {
631 fetch_post_json(`answering/${this.props.prompt.id}`);
632 this.answering_sent_recently = true;
633 setTimeout(() => { this.answering_sent_recently = false; }, 1000);
637 async handle_submit(event) {
638 const form = event.currentTarget;
640 /* Prevent the default page-changing form-submission behavior. */
641 event.preventDefault();
643 /* And don't submit a second time. */
647 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
648 answers: this.answers.map(r => r.current.value)
650 if (response.status === 200) {
651 const result = await response.json();
652 if (! result.valid) {
653 add_message("danger", result.message);
657 add_message("danger", "An error occurred submitting your answers");
661 /* Everything worked. Server is happy with our answers. */
663 this.submitted = true;
667 let move_on_button = null;
668 if (this.props.idle) {
671 className="vote-button"
672 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
675 <div className="vote-choices">
676 {[...this.props.votes].map(v => {
680 className="vote-choice"
691 if (this.props.players_answered.has(this.props.player.name)) {
693 <div className="please-wait">
694 <h2>Submission received</h2>
696 The following players have submitted their answers:
697 {[...this.props.players_answered].join(', ')}
700 Still waiting for the following players:
703 {Object.keys(this.props.players_answering).map(player => {
709 {this.props.players_answering[player] ?
710 <span className="typing"/> : null }
722 <div className="active-prompt">
723 <h2>The Game of Empathy</h2>
725 Remember, you're trying to match your answers with
726 what the other players submit.
727 Give {this.props.prompt.items} answers for the following prompt:
729 <h2>{this.props.prompt.prompt}</h2>
730 <form onSubmit={this.handle_submit}>
731 {[...Array(this.props.prompt.items)].map((whocares,i) => {
735 className="form-field large">
741 onChange={this.handle_change}
742 ref={this.answers[i]}
750 className="form-field large">
751 <button type="submit">
762 class Game extends React.PureComponent {
771 players_answered: new Set(),
772 players_answering: {},
773 answering_idle: false,
774 end_answers_votes: new Set(),
776 players_judged: new Set(),
778 end_judging_votes: new Set(),
783 set_game_info(info) {
789 set_player_info(info) {
795 set_other_player_info(info) {
796 const other_players_copy = [...this.state.other_players];
797 const idx = other_players_copy.findIndex(o => o.id === info.id);
799 other_players_copy[idx] = info;
801 other_players_copy.push(info);
804 other_players: other_players_copy
812 players_answered: new Set(),
813 players_answering: {},
814 answering_idle: false,
815 end_answers_votes: new Set(),
817 players_judged: new Set(),
819 end_judging_votes: new Set(),
824 set_prompts(prompts) {
830 add_or_update_prompt(prompt) {
831 const prompts_copy = [...this.state.prompts];
832 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
834 prompts_copy[idx] = prompt;
836 prompts_copy.push(prompt);
839 prompts: prompts_copy
843 set_active_prompt(prompt) {
845 active_prompt: prompt
849 set_players_answered(players) {
851 players_answered: new Set(players)
855 set_player_answered(player) {
856 const new_players_answering = {...this.state.players_answering};
857 delete new_players_answering[player];
860 players_answered: new Set([...this.state.players_answered, player]),
861 players_answering: new_players_answering
865 set_players_answering(players) {
866 const players_answering = {};
867 for (let player of players) {
868 players_answering[player] = {active: false};
871 players_answering: players_answering
875 set_player_answering(player) {
878 ...this.state.players_answering,
879 [player]: {active: true}
884 set_answering_idle(value) {
886 answering_idle: value
890 set_end_answers(players) {
892 end_answers_votes: new Set(players)
896 set_player_vote_end_answers(player) {
898 end_answers_votes: new Set([...this.state.end_answers_votes, player])
902 set_player_unvote_end_answers(player) {
904 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
908 set_ambiguities(ambiguities) {
910 ambiguities: ambiguities
914 set_players_judged(players) {
916 players_judged: new Set(players)
920 set_player_judged(player) {
921 const new_players_judging = {...this.state.players_judging};
922 delete new_players_judging[player];
925 players_judged: new Set([...this.state.players_judged, player]),
926 players_judging: new_players_judging
930 set_players_judging(players) {
931 const players_judging = {};
932 for (let player of players) {
933 players_judging[player] = {active: false};
936 players_judging: players_judging
940 set_player_judging(player) {
943 ...this.state.players_judging,
944 [player]: {active: true}
949 set_end_judging(players) {
951 end_judging_votes: new Set(players)
955 set_player_vote_end_judging(player) {
957 end_judging_votes: new Set([...this.state.end_judging_votes, player])
961 set_player_unvote_end_judging(player) {
963 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
974 const state = this.state;
975 const players_total = 1 + state.other_players.length;
979 <div className="scores">
982 {state.scores.scores.map(score => {
984 <li key={score.player}>
985 {score.player}: {score.score}
990 <h2>Words submitted</h2>
992 {state.scores.words.map(word => {
995 {`${word.word}: ${word.players.join(', ')}`}
1001 className="new-game"
1002 onClick={() => fetch_post_json('reset') }
1010 if (state.ambiguities){
1012 prompt={state.active_prompt}
1013 words={state.ambiguities}
1014 player={state.player_info}
1015 players_judged={state.players_judged}
1016 players_judging={state.players_judging}
1017 votes={state.end_judging_votes}
1021 if (state.active_prompt) {
1022 return <ActivePrompt
1023 prompt={state.active_prompt}
1024 player={state.player_info}
1025 players_answered={state.players_answered}
1026 players_answering={state.players_answering}
1027 idle={state.answering_idle}
1028 votes={state.end_answers_votes}
1035 id={state.game_info.id}
1036 url={state.game_info.url}
1041 player={state.player_info}
1042 other_players={state.other_players}
1044 <p key="spacer"></p>,
1046 key="category-request"
1050 prompts={state.prompts}
1054 num_players={1+state.other_players.length}
1055 prompts={state.prompts}
1061 ReactDOM.render(<Game
1062 ref={(me) => window.game = me}
1063 />, document.getElementById("empathy"));