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);
93 events.addEventListener("prompt", event => {
94 const prompt = JSON.parse(event.data);
96 window.game.add_or_update_prompt(prompt);
99 events.addEventListener("start", event => {
100 const prompt = JSON.parse(event.data);
102 window.game.set_active_prompt(prompt);
105 events.addEventListener("player-answered", event => {
106 const player = JSON.parse(event.data);
108 window.game.set_player_answered(player);
111 events.addEventListener("player-answering", event => {
112 const player = JSON.parse(event.data);
114 window.game.set_player_answering(player);
117 events.addEventListener("answering-idle", event => {
118 const value = JSON.parse(event.data);
120 window.game.set_answering_idle(value);
123 events.addEventListener("vote-end-answers", event => {
124 const player = JSON.parse(event.data);
126 window.game.set_player_vote_end_answers(player);
129 events.addEventListener("unvote-end-answers", event => {
130 const player = JSON.parse(event.data);
132 window.game.set_player_unvote_end_answers(player);
135 events.addEventListener("ambiguities", event => {
136 const ambiguities = JSON.parse(event.data);
138 window.game.set_ambiguities(ambiguities);
141 events.addEventListener("player-judged", event => {
142 const player = JSON.parse(event.data);
144 window.game.set_player_judged(player);
147 events.addEventListener("player-judging", event => {
148 const player = JSON.parse(event.data);
150 window.game.set_player_judging(player);
153 events.addEventListener("judging-idle", event => {
154 const value = JSON.parse(event.data);
156 window.game.set_judging_idle(value);
159 events.addEventListener("vote-end-judging", event => {
160 const player = JSON.parse(event.data);
162 window.game.set_player_vote_end_judging(player);
165 events.addEventListener("unvote-end-judging", event => {
166 const player = JSON.parse(event.data);
168 window.game.set_player_unvote_end_judging(player);
171 events.addEventListener("scores", event => {
172 const scores = JSON.parse(event.data);
174 window.game.set_scores(scores);
177 /*********************************************************
178 * Game and supporting classes *
179 *********************************************************/
181 function copy_to_clipboard(id)
183 const tmp = document.createElement("input");
184 tmp.setAttribute("value", document.getElementById(id).innerHTML);
185 document.body.appendChild(tmp);
187 document.execCommand("copy");
188 document.body.removeChild(tmp);
191 const GameInfo = React.memo(props => {
196 <div className="game-info">
197 <span className="game-id">{props.id}</span>
199 Share this link to invite friends:{" "}
200 <span id="game-share-url">{props.url}</span>
204 onClick={() => copy_to_clipboard('game-share-url')}
210 const PlayerInfo = React.memo(props => {
211 if (! props.player.id)
214 const all_players = [props.player, ...props.other_players];
216 const sorted_players = all_players.sort((a,b) => {
217 return b.score - a.score;
220 const names_and_scores = sorted_players.map(player => {
222 return `${player.name} (${player.score})`;
228 <div className="player-info">
229 <span className="players-header">Players: </span>
230 <span>{names_and_scores}</span>
235 function fetch_method_json(method, api = '', data = {}) {
236 const response = fetch(api, {
239 'Content-Type': 'application/json'
241 body: JSON.stringify(data)
246 function fetch_post_json(api = '', data = {}) {
247 return fetch_method_json('POST', api, data);
250 async function fetch_put_json(api = '', data = {}) {
251 return fetch_method_json('PUT', api, data);
254 class CategoryRequest extends React.PureComponent {
257 this.category = React.createRef();
259 this.handle_change = this.handle_change.bind(this);
260 this.handle_submit = this.handle_submit.bind(this);
263 handle_change(event) {
264 const category_input = this.category.current;
265 const category = category_input.value;
267 const match = category.match(/[0-9]+/);
269 const num_items = parseInt(match[0], 10);
270 if (num_items <= MAX_PROMPT_ITEMS)
271 category_input.setCustomValidity("");
275 async handle_submit(event) {
276 const form = event.currentTarget;
277 const category_input = this.category.current;
278 const category = category_input.value;
280 /* Prevent the default page-changing form-submission behavior. */
281 event.preventDefault();
283 const match = category.match(/[0-9]+/);
284 if (match === null) {
285 category_input.setCustomValidity("Category must include a number");
286 form.reportValidity();
290 const num_items = parseInt(match[0], 10);
292 if (num_items > MAX_PROMPT_ITEMS) {
293 category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
294 form.reportValidity();
298 const response = await fetch_post_json("prompts", {
303 if (response.status === 200) {
304 const result = await response.json();
305 if (! result.valid) {
306 add_message("danger", result.message);
310 add_message("danger", "An error occurred submitting your category");
318 <div className="category-request">
319 <h2>Submit a Category</h2>
321 Suggest a category to play. Don't forget to include the
322 number of items for each person to submit.
325 <form onSubmit={this.handle_submit} >
326 <div className="form-field large">
330 placeholder="6 things at the beach"
333 onChange={this.handle_change}
338 <div className="form-field large">
339 <button type="submit">
350 const PromptOptions = React.memo(props => {
352 if (props.prompts.length === 0)
356 <div className="prompt-options">
357 <h2>Vote on Categories</h2>
359 Select any categories below that you'd like to play.
360 You can choose as many as you'd like.
362 {props.prompts.map(p => {
365 className="vote-button"
367 onClick={() => fetch_post_json(`vote/${p.id}`) }
370 <div className="vote-choices">
375 className="vote-choice"
389 const LetsPlay = React.memo(props => {
391 const quorum = Math.round((props.num_players + 1) / 2);
392 const max_votes = props.prompts.reduce(
393 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
395 if (max_votes < quorum)
398 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
399 const index = Math.floor(Math.random() * candidates.length);
400 const winner = candidates[index];
403 <div className="lets-play">
406 That should be enough voting. If you're not waiting for any
407 other players to join, then let's start.
410 className="lets-play"
411 onClick={() => fetch_post_json(`start/${winner.id}`) }
419 class Ambiguities extends React.PureComponent {
424 const word_sets = props.words.map(word => {
425 const set = new Set();
431 word_sets: word_sets,
435 this.submitted = false;
436 this.judging_sent_recently = false;
439 async handle_submit() {
441 /* Don't submit a second time. */
445 const response = await fetch_post_json(
446 `judged/${this.props.prompt.id}`,{
447 word_groups: this.state.word_sets.map(set => Array.from(set))
451 if (response.status === 200) {
452 const result = await response.json();
453 if (! result.valid) {
454 add_message("danger", result.message);
458 add_message("danger", "An error occurred submitting the results of your judging");
462 this.submitted = true;
467 /* Let the server know we are doing some judging, (but rate limit
468 * this so we don't send a "judging" notification more frquently
471 if (! this.judging_sent_recently) {
472 fetch_post_json(`judging/${this.props.prompt.id}`);
473 this.judging_sent_recently = true;
474 setTimeout(() => { this.judging_sent_recently = false; }, 1000);
477 if (this.state.selected == word) {
478 /* Second click on same word removes the word from the group. */
479 const idx = this.state.word_sets.findIndex(s => s.has(word));
480 const set = this.state.word_sets[idx];
481 if (set.size === 1) {
482 /* When the word is already alone, there's nothing to do but
483 * to un-select it. */
490 const new_set = new Set([...set].filter(w => w !== word));
493 word_sets: [...this.state.word_sets.slice(0, idx),
496 ...this.state.word_sets.slice(idx+1)]
498 } else if (this.state.selected) {
499 /* Click of a second word groups the two together. */
500 const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
501 const idx2 = this.state.word_sets.findIndex(s => s.has(word));
502 const set1 = this.state.word_sets[idx1];
503 const set2 = this.state.word_sets[idx2];
504 const new_set = new Set([...set2, ...set1]);
508 word_sets: [...this.state.word_sets.slice(0, idx1),
509 ...this.state.word_sets.slice(idx1 + 1, idx2),
511 ...this.state.word_sets.slice(idx2 + 1)]
516 word_sets: [...this.state.word_sets.slice(0, idx2),
518 ...this.state.word_sets.slice(idx2 + 1, idx1),
519 ...this.state.word_sets.slice(idx1 + 1)]
523 /* First click of a word selects it. */
531 let move_on_button = null;
533 if (this.props.idle) {
536 className="vote-button"
537 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
540 <div className="vote-choices">
541 {[...this.props.votes].map(v => {
545 className="vote-choice"
556 if (this.props.players_judged.has(this.props.player.name)) {
558 <div className="please-wait">
559 <h2>Submission received</h2>
561 The following players have completed judging:
562 {[...this.props.players_judged].join(', ')}
565 Still waiting for the following players:
568 {Object.keys(this.props.players_judging).map(player => {
574 {this.props.players_judging[player] ?
575 <span className="typing"/> : null }
586 const btn_class = "ambiguity-button";
587 const btn_selected_class = btn_class + " selected";
590 <div className="ambiguities">
591 <h2>Judging Answers</h2>
593 Click on each pair of answers that should be scored as equivalent,
594 (and click any word twice to split it out from a group). Remember,
595 what goes around comes around, so it's best to be generous when
598 {this.state.word_sets.map(set => {
601 className="ambiguity-group"
602 key={Array.from(set)[0]}
604 {Array.from(set).map(word => {
607 className={this.state.selected === word ?
608 btn_selected_class : btn_class }
610 onClick={() => this.handle_click(word)}
620 Click here when done judging:<br/>
622 onClick={() => this.handle_submit()}
632 class ActivePrompt extends React.PureComponent {
636 const items = props.prompt.items;
638 this.submitted = false;
640 this.answers = [...Array(items)].map(() => React.createRef());
641 this.answering_sent_recently = false;
643 this.handle_submit = this.handle_submit.bind(this);
644 this.handle_change = this.handle_change.bind(this);
647 handle_change(event) {
648 /* We don't care (or even look) at what the player is typing at
649 * this point. We simply want to be informed that the player _is_
650 * typing so that we can tell the server (which will tell other
651 * players) that there is activity here.
654 /* Rate limit so that we don't send an "answering" notification
655 * more frequently than necessary.
657 if (! this.answering_sent_recently) {
658 fetch_post_json(`answering/${this.props.prompt.id}`);
659 this.answering_sent_recently = true;
660 setTimeout(() => { this.answering_sent_recently = false; }, 1000);
664 async handle_submit(event) {
665 const form = event.currentTarget;
667 /* Prevent the default page-changing form-submission behavior. */
668 event.preventDefault();
670 /* And don't submit a second time. */
674 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
675 answers: this.answers.map(r => r.current.value)
677 if (response.status === 200) {
678 const result = await response.json();
679 if (! result.valid) {
680 add_message("danger", result.message);
684 add_message("danger", "An error occurred submitting your answers");
688 /* Everything worked. Server is happy with our answers. */
690 this.submitted = true;
694 let move_on_button = null;
695 if (this.props.idle) {
698 className="vote-button"
699 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
702 <div className="vote-choices">
703 {[...this.props.votes].map(v => {
707 className="vote-choice"
718 if (this.props.players_answered.has(this.props.player.name)) {
720 <div className="please-wait">
721 <h2>Submission received</h2>
723 The following players have submitted their answers:
724 {[...this.props.players_answered].join(', ')}
727 Still waiting for the following players:
730 {Object.keys(this.props.players_answering).map(player => {
736 {this.props.players_answering[player] ?
737 <span className="typing"/> : null }
749 <div className="active-prompt">
750 <h2>The Game of Empathy</h2>
752 Remember, you're trying to match your answers with
753 what the other players submit.
754 Give {this.props.prompt.items} answers for the following prompt:
756 <h2>{this.props.prompt.prompt}</h2>
757 <form onSubmit={this.handle_submit}>
758 {[...Array(this.props.prompt.items)].map((whocares,i) => {
762 className="form-field large">
768 onChange={this.handle_change}
769 ref={this.answers[i]}
777 className="form-field large">
778 <button type="submit">
789 class Game extends React.PureComponent {
798 players_answered: new Set(),
799 players_answering: {},
800 answering_idle: false,
801 end_answers_votes: new Set(),
803 players_judged: new Set(),
806 end_judging_votes: new Set(),
811 set_game_info(info) {
817 set_player_info(info) {
823 set_other_player_info(info) {
824 const other_players_copy = [...this.state.other_players];
825 const idx = other_players_copy.findIndex(o => o.id === info.id);
827 other_players_copy[idx] = info;
829 other_players_copy.push(info);
832 other_players: other_players_copy
836 remove_player(info) {
838 other_players: this.state.other_players.filter(o => o.id !== info.id)
846 players_answered: new Set(),
847 players_answering: {},
848 answering_idle: false,
849 end_answers_votes: new Set(),
851 players_judged: new Set(),
854 end_judging_votes: new Set(),
859 set_prompts(prompts) {
865 add_or_update_prompt(prompt) {
866 const prompts_copy = [...this.state.prompts];
867 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
869 prompts_copy[idx] = prompt;
871 prompts_copy.push(prompt);
874 prompts: prompts_copy
878 set_active_prompt(prompt) {
880 active_prompt: prompt
884 set_players_answered(players) {
886 players_answered: new Set(players)
890 set_player_answered(player) {
891 const new_players_answering = {...this.state.players_answering};
892 delete new_players_answering[player];
895 players_answered: new Set([...this.state.players_answered, player]),
896 players_answering: new_players_answering
900 set_players_answering(players) {
901 const players_answering = {};
902 for (let player of players) {
903 players_answering[player] = {active: false};
906 players_answering: players_answering
910 set_player_answering(player) {
913 ...this.state.players_answering,
914 [player]: {active: true}
919 set_answering_idle(value) {
921 answering_idle: value
925 set_end_answers(players) {
927 end_answers_votes: new Set(players)
931 set_player_vote_end_answers(player) {
933 end_answers_votes: new Set([...this.state.end_answers_votes, player])
937 set_player_unvote_end_answers(player) {
939 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
943 set_ambiguities(ambiguities) {
945 ambiguities: ambiguities
949 set_players_judged(players) {
951 players_judged: new Set(players)
955 set_player_judged(player) {
956 const new_players_judging = {...this.state.players_judging};
957 delete new_players_judging[player];
960 players_judged: new Set([...this.state.players_judged, player]),
961 players_judging: new_players_judging
965 set_players_judging(players) {
966 const players_judging = {};
967 for (let player of players) {
968 players_judging[player] = {active: false};
971 players_judging: players_judging
975 set_player_judging(player) {
978 ...this.state.players_judging,
979 [player]: {active: true}
984 set_judging_idle(value) {
985 console.log("Setting judging idle to " + value);
991 set_end_judging(players) {
993 end_judging_votes: new Set(players)
997 set_player_vote_end_judging(player) {
999 end_judging_votes: new Set([...this.state.end_judging_votes, player])
1003 set_player_unvote_end_judging(player) {
1005 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1009 set_scores(scores) {
1016 const state = this.state;
1017 const players_total = 1 + state.other_players.length;
1021 <div className="scores">
1024 {state.scores.scores.map(score => {
1026 <li key={score.player}>
1027 {score.player}: {score.score}
1032 <h2>Words submitted</h2>
1034 {state.scores.words.map(word => {
1036 <li key={word.word}>
1037 {`${word.word}: ${word.players.join(', ')}`}
1043 className="new-game"
1044 onClick={() => fetch_post_json('reset') }
1052 if (state.ambiguities){
1054 prompt={state.active_prompt}
1055 words={state.ambiguities}
1056 player={state.player_info}
1057 players_judged={state.players_judged}
1058 players_judging={state.players_judging}
1059 idle={state.judging_idle}
1060 votes={state.end_judging_votes}
1064 if (state.active_prompt) {
1065 return <ActivePrompt
1066 prompt={state.active_prompt}
1067 player={state.player_info}
1068 players_answered={state.players_answered}
1069 players_answering={state.players_answering}
1070 idle={state.answering_idle}
1071 votes={state.end_answers_votes}
1078 id={state.game_info.id}
1079 url={state.game_info.url}
1084 player={state.player_info}
1085 other_players={state.other_players}
1087 <p key="spacer"></p>,
1089 key="category-request"
1093 prompts={state.prompts}
1097 num_players={1+state.other_players.length}
1098 prompts={state.prompts}
1104 ReactDOM.render(<Game
1105 ref={(me) => window.game = me}
1106 />, document.getElementById("empathy"));