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 PromptOption = React.memo(props => {
368 const prompt = props.prompt;
370 if (prompt.votes_against.find(v => v === props.player.name))
375 className="vote-button"
377 onClick={() => fetch_post_json(`vote/${prompt.id}`) }
380 className="hide-button"
381 onClick={(event) => {
382 event.stopPropagation();
383 fetch_post_json(`vote_against/${prompt.id}`);
389 <div className="vote-choices">
390 {prompt.votes.map(v => {
394 className="vote-choice"
405 const PromptOptions = React.memo(props => {
407 if (props.prompts.length === 0)
411 <div className="prompt-options">
412 <h2>Vote on Categories</h2>
414 Select any categories below that you'd like to play.
415 You can choose as many as you'd like.
417 {props.prompts.map(p => <PromptOption prompt={p} player={props.player} />)}
422 const LetsPlay = React.memo(props => {
424 const quorum = Math.round((props.num_players + 1) / 2);
425 const max_votes = props.prompts.reduce(
426 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
428 if (max_votes < quorum)
431 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
432 const index = Math.floor(Math.random() * candidates.length);
433 const winner = candidates[index];
436 <div className="lets-play">
439 That should be enough voting. If you're not waiting for any
440 other players to join, then let's start.
443 className="lets-play"
444 onClick={() => fetch_post_json(`start/${winner.id}`) }
452 class Ambiguities extends React.PureComponent {
457 function canonize(word) {
458 return word.replace(/((a|an|the) )?(.*?)s?$/i, '$3');
461 const word_sets = [];
463 for (let word of props.words) {
464 const word_canon = canonize(word);
465 console.log("Canonized " + word + " to " + word_canon);
466 let found_match = false;
467 for (let set of word_sets) {
468 const set_canon = canonize(set.values().next().value);
469 console.log("Comparing " + word_canon + " to " + set_canon);
470 if (word_canon === set_canon) {
477 const set = new Set();
484 word_sets: word_sets,
488 this.submitted = false;
489 this.judging_sent_recently = false;
492 async handle_submit() {
494 /* Don't submit a second time. */
498 const response = await fetch_post_json(
499 `judged/${this.props.prompt.id}`,{
500 word_groups: this.state.word_sets.map(set => Array.from(set))
504 if (response.status === 200) {
505 const result = await response.json();
506 if (! result.valid) {
507 add_message("danger", result.message);
511 add_message("danger", "An error occurred submitting the results of your judging");
515 this.submitted = true;
520 /* Let the server know we are doing some judging, (but rate limit
521 * this so we don't send a "judging" notification more frquently
524 if (! this.judging_sent_recently) {
525 fetch_post_json(`judging/${this.props.prompt.id}`);
526 this.judging_sent_recently = true;
527 setTimeout(() => { this.judging_sent_recently = false; }, 1000);
530 if (this.state.selected == word) {
531 /* Second click on same word removes the word from the group. */
532 const idx = this.state.word_sets.findIndex(s => s.has(word));
533 const set = this.state.word_sets[idx];
534 if (set.size === 1) {
535 /* When the word is already alone, there's nothing to do but
536 * to un-select it. */
543 const new_set = new Set([...set].filter(w => w !== word));
546 word_sets: [...this.state.word_sets.slice(0, idx),
549 ...this.state.word_sets.slice(idx+1)]
551 } else if (this.state.selected) {
552 /* Click of a second word groups the two together. */
553 const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
554 const idx2 = this.state.word_sets.findIndex(s => s.has(word));
555 const set1 = this.state.word_sets[idx1];
556 const set2 = this.state.word_sets[idx2];
557 const new_set = new Set([...set2, ...set1]);
561 word_sets: [...this.state.word_sets.slice(0, idx1),
562 ...this.state.word_sets.slice(idx1 + 1, idx2),
564 ...this.state.word_sets.slice(idx2 + 1)]
569 word_sets: [...this.state.word_sets.slice(0, idx2),
571 ...this.state.word_sets.slice(idx2 + 1, idx1),
572 ...this.state.word_sets.slice(idx1 + 1)]
576 /* First click of a word selects it. */
584 let move_on_button = null;
586 if (this.props.idle) {
589 className="vote-button"
590 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
593 <div className="vote-choices">
594 {[...this.props.votes].map(v => {
598 className="vote-choice"
609 let still_waiting = null;
610 const judging_players = Object.keys(this.props.players_judging);
611 if (judging_players.length) {
615 Still waiting for the following player
616 {judging_players.length > 1 ? 's' : '' }
620 {judging_players.map(player => {
627 {this.props.players_judging[player].active ?
631 <span>{'.'}</span><span>{'.'}</span><span>{'.'}</span>
641 if (this.props.players_judged.has(this.props.player.name)) {
643 <div className="please-wait">
644 <h2>Submission received</h2>
646 The following players have completed judging:{' '}
647 {[...this.props.players_judged].join(', ')}
656 const btn_class = "ambiguity-button";
657 const btn_selected_class = btn_class + " selected";
660 <div className="ambiguities">
661 <h2>Judging Answers</h2>
663 Click on each pair of answers that should be scored as equivalent,
664 (and click any word twice to split it out from a group). Remember,
665 what goes around comes around, so it's best to be generous when
668 <h2>{this.props.prompt.prompt}</h2>
669 {this.state.word_sets.map(set => {
672 className="ambiguity-group"
673 key={Array.from(set)[0]}
675 {Array.from(set).map(word => {
678 className={this.state.selected === word ?
679 btn_selected_class : btn_class }
681 onClick={() => this.handle_click(word)}
691 Click here when done judging:<br/>
693 onClick={() => this.handle_submit()}
703 class ActivePrompt extends React.PureComponent {
707 const items = props.prompt.items;
709 this.submitted = false;
711 this.answers = [...Array(items)].map(() => React.createRef());
712 this.answering_sent_recently = false;
714 this.handle_submit = this.handle_submit.bind(this);
715 this.handle_change = this.handle_change.bind(this);
718 handle_change(event) {
719 /* We don't care (or even look) at what the player is typing at
720 * this point. We simply want to be informed that the player _is_
721 * typing so that we can tell the server (which will tell other
722 * players) that there is activity here.
725 /* Rate limit so that we don't send an "answering" notification
726 * more frequently than necessary.
728 if (! this.answering_sent_recently) {
729 fetch_post_json(`answering/${this.props.prompt.id}`);
730 this.answering_sent_recently = true;
731 setTimeout(() => { this.answering_sent_recently = false; }, 1000);
735 async handle_submit(event) {
736 const form = event.currentTarget;
738 /* Prevent the default page-changing form-submission behavior. */
739 event.preventDefault();
741 /* And don't submit a second time. */
745 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
746 answers: this.answers.map(r => r.current.value)
748 if (response.status === 200) {
749 const result = await response.json();
750 if (! result.valid) {
751 add_message("danger", result.message);
755 add_message("danger", "An error occurred submitting your answers");
759 /* Everything worked. Server is happy with our answers. */
761 this.submitted = true;
765 let move_on_button = null;
766 if (this.props.idle) {
769 className="vote-button"
770 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
773 <div className="vote-choices">
774 {[...this.props.votes].map(v => {
778 className="vote-choice"
789 let still_waiting = null;
790 const answering_players = Object.keys(this.props.players_answering);;
791 if (answering_players.length) {
795 Still waiting for the following player
796 {answering_players.length > 1 ? 's' : ''}
800 {answering_players.map(player => {
807 {this.props.players_answering[player].active ?
811 <span>{'.'}</span><span>{'.'}</span><span>{'.'}</span>
821 if (this.props.players_answered.has(this.props.player.name)) {
823 <div className="please-wait">
824 <h2>Submission received</h2>
826 The following players have submitted their answers:{' '}
827 {[...this.props.players_answered].join(', ')}
837 <div className="active-prompt">
838 <h2>The Game of Empathy</h2>
840 Remember, you're trying to match your answers with
841 what the other players submit.
842 Give {this.props.prompt.items} answer
843 {this.props.prompt.items > 1 ? 's' : ''} for the following prompt:
845 <h2>{this.props.prompt.prompt}</h2>
846 <form onSubmit={this.handle_submit}>
847 {[...Array(this.props.prompt.items)].map((whocares,i) => {
851 className="form-field large">
857 onChange={this.handle_change}
858 ref={this.answers[i]}
866 className="form-field large">
867 <button type="submit">
878 class Game extends React.PureComponent {
887 players_answered: new Set(),
888 players_answering: {},
889 answering_idle: false,
890 end_answers_votes: new Set(),
892 players_judged: new Set(),
895 end_judging_votes: new Set(),
897 new_game_votes: new Set(),
902 set_game_info(info) {
908 set_player_info(info) {
914 set_other_player_info(info) {
915 const other_players_copy = [...this.state.other_players];
916 const idx = other_players_copy.findIndex(o => o.id === info.id);
918 other_players_copy[idx] = info;
920 other_players_copy.push(info);
923 other_players: other_players_copy
927 remove_player(info) {
929 other_players: this.state.other_players.filter(o => o.id !== info.id)
937 players_answered: new Set(),
938 players_answering: {},
939 answering_idle: false,
940 end_answers_votes: new Set(),
942 players_judged: new Set(),
945 end_judging_votes: new Set(),
947 new_game_votes: new Set(),
952 set_prompts(prompts) {
958 add_or_update_prompt(prompt) {
959 const prompts_copy = [...this.state.prompts];
960 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
962 prompts_copy[idx] = prompt;
964 prompts_copy.push(prompt);
967 prompts: prompts_copy
971 set_active_prompt(prompt) {
973 active_prompt: prompt
977 set_players_answered(players) {
979 players_answered: new Set(players)
983 set_player_answered(player) {
984 const new_players_answering = {...this.state.players_answering};
985 delete new_players_answering[player];
988 players_answered: new Set([...this.state.players_answered, player]),
989 players_answering: new_players_answering
993 set_players_answering(players) {
994 const players_answering = {};
995 for (let player of players) {
996 players_answering[player] = {active: false};
999 players_answering: players_answering
1003 set_player_answering(player) {
1004 /* Set the player as actively answering now. */
1006 players_answering: {
1007 ...this.state.players_answering,
1008 [player]: {active: true}
1011 /* And arrange to have them marked idle very shortly.
1013 * Note: This timeout is intentionally very, very short. We only
1014 * need it long enough that the browser has latched onto the state
1015 * change to "active" above. We actually use a CSS transition
1016 * delay to control the user-perceptible length of time after
1017 * which an active player appears inactive.
1021 players_answering: {
1022 ...this.state.players_answering,
1023 [player]: {active: false}
1029 set_answering_idle(value) {
1031 answering_idle: value
1035 set_end_answers(players) {
1037 end_answers_votes: new Set(players)
1041 set_player_vote_end_answers(player) {
1043 end_answers_votes: new Set([...this.state.end_answers_votes, player])
1047 set_player_unvote_end_answers(player) {
1049 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
1053 set_ambiguities(ambiguities) {
1055 ambiguities: ambiguities
1059 set_players_judged(players) {
1061 players_judged: new Set(players)
1065 set_player_judged(player) {
1066 const new_players_judging = {...this.state.players_judging};
1067 delete new_players_judging[player];
1070 players_judged: new Set([...this.state.players_judged, player]),
1071 players_judging: new_players_judging
1075 set_players_judging(players) {
1076 const players_judging = {};
1077 for (let player of players) {
1078 players_judging[player] = {active: false};
1081 players_judging: players_judging
1085 set_player_judging(player) {
1086 /* Set the player as actively judging now. */
1089 ...this.state.players_judging,
1090 [player]: {active: true}
1093 /* And arrange to have them marked idle very shortly.
1095 * Note: This timeout is intentionally very, very short. We only
1096 * need it long enough that the browser has latched onto the state
1097 * change to "active" above. We actually use a CSS transition
1098 * delay to control the user-perceptible length of time after
1099 * which an active player appears inactive.
1104 ...this.state.players_judging,
1105 [player]: {active: false}
1112 set_judging_idle(value) {
1118 set_end_judging(players) {
1120 end_judging_votes: new Set(players)
1124 set_player_vote_end_judging(player) {
1126 end_judging_votes: new Set([...this.state.end_judging_votes, player])
1130 set_player_unvote_end_judging(player) {
1132 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1136 set_scores(scores) {
1142 set_new_game_votes(players) {
1144 new_game_votes: new Set(players)
1148 set_player_vote_new_game(player) {
1150 new_game_votes: new Set([...this.state.new_game_votes, player])
1154 set_player_unvote_new_game(player) {
1156 new_game_votes: new Set([...this.state.new_game_votes].filter(p => p !== player))
1167 const state = this.state;
1168 const players_total = 1 + state.other_players.length;
1172 let perfect_score = 0;
1174 i < state.active_prompt.items &&
1175 i < state.scores.words.length;
1178 perfect_score += state.scores.words[i].players.length;
1182 <div className="scores">
1183 <h2>{state.active_prompt.prompt}</h2>
1186 {state.scores.scores.map(score => {
1188 if (score.score == perfect_score) {
1189 perfect = <span className="label">Perfect!</span>;
1192 <li key={score.players[0]}>
1193 {score.players.join("/")}: {score.score} {perfect}
1198 <h2>Words submitted</h2>
1200 {state.scores.words.map(word => {
1202 <li key={word.word}>
1203 {word.word} ({word.players.length}): {word.players.join(', ')}
1209 className="vote-button"
1210 onClick={() => fetch_post_json(`new-game/${state.active_prompt.id}`) }
1213 <div className="vote-choices">
1214 {[...state.new_game_votes].map(v => {
1218 className="vote-choice"
1230 if (state.ambiguities){
1232 prompt={state.active_prompt}
1233 words={state.ambiguities}
1234 player={state.player_info}
1235 players_judged={state.players_judged}
1236 players_judging={state.players_judging}
1237 idle={state.judging_idle}
1238 votes={state.end_judging_votes}
1242 if (state.active_prompt) {
1243 return <ActivePrompt
1244 prompt={state.active_prompt}
1245 player={state.player_info}
1246 players_answered={state.players_answered}
1247 players_answering={state.players_answering}
1248 idle={state.answering_idle}
1249 votes={state.end_answers_votes}
1259 id={state.game_info.id}
1260 url={state.game_info.url}
1265 player={state.player_info}
1266 other_players={state.other_players}
1268 <p key="spacer"></p>,
1270 key="category-request"
1274 prompts={state.prompts}
1275 player={state.player_info}
1279 num_players={1+state.other_players.length}
1280 prompts={state.prompts}
1286 ReactDOM.render(<Game
1287 ref={(me) => window.game = me}
1288 />, document.getElementById("empathy"));