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-exit", event => {
49 const info = JSON.parse(event.data);
51 window.game.remove_player(info);
54 events.addEventListener("player-update", event => {
55 const info = JSON.parse(event.data);
57 if (info.id === window.game.state.player_info.id)
58 window.game.set_player_info(info);
60 window.game.set_other_player_info(info);
63 events.addEventListener("game-state", event => {
64 const state = JSON.parse(event.data);
66 window.game.reset_game_state();
68 window.game.set_prompts(state.prompts);
70 window.game.set_active_prompt(state.active_prompt);
72 window.game.set_players_answered(state.players_answered);
74 window.game.set_players_answering(state.players_answering);
76 window.game.set_answering_idle(state.answering_idle);
78 window.game.set_end_answers(state.end_answers);
80 window.game.set_ambiguities(state.ambiguities);
82 window.game.set_players_judged(state.players_judged);
84 window.game.set_players_judging(state.players_judging);
86 window.game.set_judging_idle(state.judging_idle);
88 window.game.set_end_judging(state.end_judging);
90 window.game.set_scores(state.scores);
92 window.game.set_new_game_votes(state.new_game_votes);
94 window.game.state_ready();
97 events.addEventListener("prompt", event => {
98 const prompt = JSON.parse(event.data);
100 window.game.add_or_update_prompt(prompt);
103 events.addEventListener("start", event => {
104 const prompt = JSON.parse(event.data);
106 window.game.set_active_prompt(prompt);
109 events.addEventListener("player-answered", event => {
110 const player = JSON.parse(event.data);
112 window.game.set_player_answered(player);
115 events.addEventListener("player-answering", event => {
116 const player = JSON.parse(event.data);
118 window.game.set_player_answering(player);
121 events.addEventListener("answering-idle", event => {
122 const value = JSON.parse(event.data);
124 window.game.set_answering_idle(value);
127 events.addEventListener("vote-end-answers", event => {
128 const player = JSON.parse(event.data);
130 window.game.set_player_vote_end_answers(player);
133 events.addEventListener("unvote-end-answers", event => {
134 const player = JSON.parse(event.data);
136 window.game.set_player_unvote_end_answers(player);
139 events.addEventListener("ambiguities", event => {
140 const ambiguities = JSON.parse(event.data);
142 window.game.set_ambiguities(ambiguities);
145 events.addEventListener("player-judged", event => {
146 const player = JSON.parse(event.data);
148 window.game.set_player_judged(player);
151 events.addEventListener("player-judging", event => {
152 const player = JSON.parse(event.data);
154 window.game.set_player_judging(player);
157 events.addEventListener("judging-idle", event => {
158 const value = JSON.parse(event.data);
160 window.game.set_judging_idle(value);
163 events.addEventListener("vote-end-judging", event => {
164 const player = JSON.parse(event.data);
166 window.game.set_player_vote_end_judging(player);
169 events.addEventListener("unvote-end-judging", event => {
170 const player = JSON.parse(event.data);
172 window.game.set_player_unvote_end_judging(player);
175 events.addEventListener("scores", event => {
176 const scores = JSON.parse(event.data);
178 window.game.set_scores(scores);
181 events.addEventListener("vote-new-game", event => {
182 const player = JSON.parse(event.data);
184 window.game.set_player_vote_new_game(player);
187 events.addEventListener("unvote-new-game", event => {
188 const player = JSON.parse(event.data);
190 window.game.set_player_unvote_new_game(player);
193 /*********************************************************
194 * Game and supporting classes *
195 *********************************************************/
197 function copy_to_clipboard(id)
199 const tmp = document.createElement("input");
200 tmp.setAttribute("value", document.getElementById(id).innerHTML);
201 document.body.appendChild(tmp);
203 document.execCommand("copy");
204 document.body.removeChild(tmp);
207 const GameInfo = React.memo(props => {
212 <div className="game-info">
213 <span className="game-id">{props.id}</span>
215 Share this link to invite friends:{" "}
216 <span id="game-share-url">{props.url}</span>
220 onClick={() => copy_to_clipboard('game-share-url')}
226 const PlayerInfo = React.memo(props => {
227 if (! props.player.id)
230 const all_players = [props.player, ...props.other_players];
232 const sorted_players = all_players.sort((a,b) => {
233 return b.score - a.score;
236 const names_and_scores = sorted_players.map(player => {
238 return `${player.name} (${player.score})`;
244 <div className="player-info">
245 <span className="players-header">Players: </span>
246 <span>{names_and_scores}</span>
251 function fetch_method_json(method, api = '', data = {}) {
252 const response = fetch(api, {
255 'Content-Type': 'application/json'
257 body: JSON.stringify(data)
262 function fetch_post_json(api = '', data = {}) {
263 return fetch_method_json('POST', api, data);
266 async function fetch_put_json(api = '', data = {}) {
267 return fetch_method_json('PUT', api, data);
270 class CategoryRequest extends React.PureComponent {
273 this.category = React.createRef();
275 this.handle_change = this.handle_change.bind(this);
276 this.handle_submit = this.handle_submit.bind(this);
279 handle_change(event) {
280 const category_input = this.category.current;
281 const category = category_input.value;
283 const match = category.match(/[0-9]+/);
285 const num_items = parseInt(match[0], 10);
286 if (num_items <= MAX_PROMPT_ITEMS)
287 category_input.setCustomValidity("");
291 async handle_submit(event) {
292 const form = event.currentTarget;
293 const category_input = this.category.current;
294 const category = category_input.value;
296 /* Prevent the default page-changing form-submission behavior. */
297 event.preventDefault();
299 const match = category.match(/[0-9]+/);
300 if (match === null) {
301 category_input.setCustomValidity("Category must include a number");
302 form.reportValidity();
306 const num_items = parseInt(match[0], 10);
308 if (num_items > MAX_PROMPT_ITEMS) {
309 category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
310 form.reportValidity();
314 const response = await fetch_post_json("prompts", {
319 if (response.status === 200) {
320 const result = await response.json();
321 if (! result.valid) {
322 add_message("danger", result.message);
326 add_message("danger", "An error occurred submitting your category");
334 <div className="category-request">
335 <h2>Submit a Category</h2>
337 Suggest a category to play. Don't forget to include the
338 number of items for each person to submit.
341 <form onSubmit={this.handle_submit} >
342 <div className="form-field large">
346 placeholder="6 things at the beach"
349 onChange={this.handle_change}
354 <div className="form-field large">
355 <button type="submit">
366 const PromptOptions = React.memo(props => {
368 if (props.prompts.length === 0)
372 <div className="prompt-options">
373 <h2>Vote on Categories</h2>
375 Select any categories below that you'd like to play.
376 You can choose as many as you'd like.
378 {props.prompts.map(p => {
381 className="vote-button"
383 onClick={() => fetch_post_json(`vote/${p.id}`) }
386 <div className="vote-choices">
391 className="vote-choice"
405 const LetsPlay = React.memo(props => {
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);
411 if (max_votes < quorum)
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];
419 <div className="lets-play">
422 That should be enough voting. If you're not waiting for any
423 other players to join, then let's start.
426 className="lets-play"
427 onClick={() => fetch_post_json(`start/${winner.id}`) }
435 class Ambiguities extends React.PureComponent {
440 const word_sets = props.words.map(word => {
441 const set = new Set();
447 word_sets: word_sets,
451 this.submitted = false;
452 this.judging_sent_recently = false;
455 async handle_submit() {
457 /* Don't submit a second time. */
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))
467 if (response.status === 200) {
468 const result = await response.json();
469 if (! result.valid) {
470 add_message("danger", result.message);
474 add_message("danger", "An error occurred submitting the results of your judging");
478 this.submitted = true;
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
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);
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. */
506 const new_set = new Set([...set].filter(w => w !== word));
509 word_sets: [...this.state.word_sets.slice(0, idx),
512 ...this.state.word_sets.slice(idx+1)]
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]);
524 word_sets: [...this.state.word_sets.slice(0, idx1),
525 ...this.state.word_sets.slice(idx1 + 1, idx2),
527 ...this.state.word_sets.slice(idx2 + 1)]
532 word_sets: [...this.state.word_sets.slice(0, idx2),
534 ...this.state.word_sets.slice(idx2 + 1, idx1),
535 ...this.state.word_sets.slice(idx1 + 1)]
539 /* First click of a word selects it. */
547 let move_on_button = null;
549 if (this.props.idle) {
552 className="vote-button"
553 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
556 <div className="vote-choices">
557 {[...this.props.votes].map(v => {
561 className="vote-choice"
572 if (this.props.players_judged.has(this.props.player.name)) {
574 <div className="please-wait">
575 <h2>Submission received</h2>
577 The following players have completed judging:{' '}
578 {[...this.props.players_judged].join(', ')}
581 Still waiting for the following players:
584 {Object.keys(this.props.players_judging).map(player => {
590 {this.props.players_judging[player] ?
591 <span className="typing"/> : null }
602 const btn_class = "ambiguity-button";
603 const btn_selected_class = btn_class + " selected";
606 <div className="ambiguities">
607 <h2>Judging Answers</h2>
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
614 <h2>{this.props.prompt.prompt}</h2>
615 {this.state.word_sets.map(set => {
618 className="ambiguity-group"
619 key={Array.from(set)[0]}
621 {Array.from(set).map(word => {
624 className={this.state.selected === word ?
625 btn_selected_class : btn_class }
627 onClick={() => this.handle_click(word)}
637 Click here when done judging:<br/>
639 onClick={() => this.handle_submit()}
649 class ActivePrompt extends React.PureComponent {
653 const items = props.prompt.items;
655 this.submitted = false;
657 this.answers = [...Array(items)].map(() => React.createRef());
658 this.answering_sent_recently = false;
660 this.handle_submit = this.handle_submit.bind(this);
661 this.handle_change = this.handle_change.bind(this);
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.
671 /* Rate limit so that we don't send an "answering" notification
672 * more frequently than necessary.
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);
681 async handle_submit(event) {
682 const form = event.currentTarget;
684 /* Prevent the default page-changing form-submission behavior. */
685 event.preventDefault();
687 /* And don't submit a second time. */
691 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
692 answers: this.answers.map(r => r.current.value)
694 if (response.status === 200) {
695 const result = await response.json();
696 if (! result.valid) {
697 add_message("danger", result.message);
701 add_message("danger", "An error occurred submitting your answers");
705 /* Everything worked. Server is happy with our answers. */
707 this.submitted = true;
711 let move_on_button = null;
712 if (this.props.idle) {
715 className="vote-button"
716 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
719 <div className="vote-choices">
720 {[...this.props.votes].map(v => {
724 className="vote-choice"
735 if (this.props.players_answered.has(this.props.player.name)) {
737 <div className="please-wait">
738 <h2>Submission received</h2>
740 The following players have submitted their answers:{' '}
741 {[...this.props.players_answered].join(', ')}
744 Still waiting for the following players:
747 {Object.keys(this.props.players_answering).map(player => {
753 {this.props.players_answering[player] ?
754 <span className="typing"/> : null }
766 <div className="active-prompt">
767 <h2>The Game of Empathy</h2>
769 Remember, you're trying to match your answers with
770 what the other players submit.
771 Give {this.props.prompt.items} answer
772 {this.props.prompt.items > 1 ? 's' : ''} for the following prompt:
774 <h2>{this.props.prompt.prompt}</h2>
775 <form onSubmit={this.handle_submit}>
776 {[...Array(this.props.prompt.items)].map((whocares,i) => {
780 className="form-field large">
786 onChange={this.handle_change}
787 ref={this.answers[i]}
795 className="form-field large">
796 <button type="submit">
807 class Game extends React.PureComponent {
816 players_answered: new Set(),
817 players_answering: {},
818 answering_idle: false,
819 end_answers_votes: new Set(),
821 players_judged: new Set(),
824 end_judging_votes: new Set(),
826 new_game_votes: new Set(),
831 set_game_info(info) {
837 set_player_info(info) {
843 set_other_player_info(info) {
844 const other_players_copy = [...this.state.other_players];
845 const idx = other_players_copy.findIndex(o => o.id === info.id);
847 other_players_copy[idx] = info;
849 other_players_copy.push(info);
852 other_players: other_players_copy
856 remove_player(info) {
858 other_players: this.state.other_players.filter(o => o.id !== info.id)
866 players_answered: new Set(),
867 players_answering: {},
868 answering_idle: false,
869 end_answers_votes: new Set(),
871 players_judged: new Set(),
874 end_judging_votes: new Set(),
876 new_game_votes: new Set(),
881 set_prompts(prompts) {
887 add_or_update_prompt(prompt) {
888 const prompts_copy = [...this.state.prompts];
889 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
891 prompts_copy[idx] = prompt;
893 prompts_copy.push(prompt);
896 prompts: prompts_copy
900 set_active_prompt(prompt) {
902 active_prompt: prompt
906 set_players_answered(players) {
908 players_answered: new Set(players)
912 set_player_answered(player) {
913 const new_players_answering = {...this.state.players_answering};
914 delete new_players_answering[player];
917 players_answered: new Set([...this.state.players_answered, player]),
918 players_answering: new_players_answering
922 set_players_answering(players) {
923 const players_answering = {};
924 for (let player of players) {
925 players_answering[player] = {active: false};
928 players_answering: players_answering
932 set_player_answering(player) {
935 ...this.state.players_answering,
936 [player]: {active: true}
941 set_answering_idle(value) {
943 answering_idle: value
947 set_end_answers(players) {
949 end_answers_votes: new Set(players)
953 set_player_vote_end_answers(player) {
955 end_answers_votes: new Set([...this.state.end_answers_votes, player])
959 set_player_unvote_end_answers(player) {
961 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
965 set_ambiguities(ambiguities) {
967 ambiguities: ambiguities
971 set_players_judged(players) {
973 players_judged: new Set(players)
977 set_player_judged(player) {
978 const new_players_judging = {...this.state.players_judging};
979 delete new_players_judging[player];
982 players_judged: new Set([...this.state.players_judged, player]),
983 players_judging: new_players_judging
987 set_players_judging(players) {
988 const players_judging = {};
989 for (let player of players) {
990 players_judging[player] = {active: false};
993 players_judging: players_judging
997 set_player_judging(player) {
1000 ...this.state.players_judging,
1001 [player]: {active: true}
1006 set_judging_idle(value) {
1012 set_end_judging(players) {
1014 end_judging_votes: new Set(players)
1018 set_player_vote_end_judging(player) {
1020 end_judging_votes: new Set([...this.state.end_judging_votes, player])
1024 set_player_unvote_end_judging(player) {
1026 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1030 set_scores(scores) {
1036 set_new_game_votes(players) {
1038 new_game_votes: new Set(players)
1042 set_player_vote_new_game(player) {
1044 new_game_votes: new Set([...this.state.new_game_votes, player])
1048 set_player_unvote_new_game(player) {
1050 new_game_votes: new Set([...this.state.new_game_votes].filter(p => p !== player))
1061 const state = this.state;
1062 const players_total = 1 + state.other_players.length;
1066 <div className="scores">
1067 <h2>{state.active_prompt.prompt}</h2>
1070 {state.scores.scores.map(score => {
1072 <li key={score.player}>
1073 {score.players.join("/")}: {score.score}
1078 <h2>Words submitted</h2>
1080 {state.scores.words.map(word => {
1082 <li key={word.word}>
1083 {word.word} ({word.players.length}): {word.players.join(', ')}
1089 className="vote-button"
1090 onClick={() => fetch_post_json(`new-game/${state.active_prompt.id}`) }
1093 <div className="vote-choices">
1094 {[...state.new_game_votes].map(v => {
1098 className="vote-choice"
1110 if (state.ambiguities){
1112 prompt={state.active_prompt}
1113 words={state.ambiguities}
1114 player={state.player_info}
1115 players_judged={state.players_judged}
1116 players_judging={state.players_judging}
1117 idle={state.judging_idle}
1118 votes={state.end_judging_votes}
1122 if (state.active_prompt) {
1123 return <ActivePrompt
1124 prompt={state.active_prompt}
1125 player={state.player_info}
1126 players_answered={state.players_answered}
1127 players_answering={state.players_answering}
1128 idle={state.answering_idle}
1129 votes={state.end_answers_votes}
1139 id={state.game_info.id}
1140 url={state.game_info.url}
1145 player={state.player_info}
1146 other_players={state.other_players}
1148 <p key="spacer"></p>,
1150 key="category-request"
1154 prompts={state.prompts}
1158 num_players={1+state.other_players.length}
1159 prompts={state.prompts}
1165 ReactDOM.render(<Game
1166 ref={(me) => window.game = me}
1167 />, document.getElementById("empathy"));