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_judging_idle(state.judging_idle);
82 window.game.set_end_judging(state.end_judging);
84 window.game.set_scores(state.scores);
87 events.addEventListener("prompt", event => {
88 const prompt = JSON.parse(event.data);
90 window.game.add_or_update_prompt(prompt);
93 events.addEventListener("start", event => {
94 const prompt = JSON.parse(event.data);
96 window.game.set_active_prompt(prompt);
99 events.addEventListener("player-answered", event => {
100 const player = JSON.parse(event.data);
102 window.game.set_player_answered(player);
105 events.addEventListener("player-answering", event => {
106 const player = JSON.parse(event.data);
108 window.game.set_player_answering(player);
111 events.addEventListener("answering-idle", event => {
112 const value = JSON.parse(event.data);
114 window.game.set_answering_idle(value);
117 events.addEventListener("vote-end-answers", event => {
118 const player = JSON.parse(event.data);
120 window.game.set_player_vote_end_answers(player);
123 events.addEventListener("unvote-end-answers", event => {
124 const player = JSON.parse(event.data);
126 window.game.set_player_unvote_end_answers(player);
129 events.addEventListener("ambiguities", event => {
130 const ambiguities = JSON.parse(event.data);
132 window.game.set_ambiguities(ambiguities);
135 events.addEventListener("player-judged", event => {
136 const player = JSON.parse(event.data);
138 window.game.set_player_judged(player);
141 events.addEventListener("player-judging", event => {
142 const player = JSON.parse(event.data);
144 window.game.set_player_judging(player);
147 events.addEventListener("judging-idle", event => {
148 const value = JSON.parse(event.data);
150 window.game.set_judging_idle(value);
153 events.addEventListener("vote-end-judging", event => {
154 const player = JSON.parse(event.data);
156 window.game.set_player_vote_end_judging(player);
159 events.addEventListener("unvote-end-judging", event => {
160 const player = JSON.parse(event.data);
162 window.game.set_player_unvote_end_judging(player);
165 events.addEventListener("scores", event => {
166 const scores = JSON.parse(event.data);
168 window.game.set_scores(scores);
171 /*********************************************************
172 * Game and supporting classes *
173 *********************************************************/
175 function copy_to_clipboard(id)
177 const tmp = document.createElement("input");
178 tmp.setAttribute("value", document.getElementById(id).innerHTML);
179 document.body.appendChild(tmp);
181 document.execCommand("copy");
182 document.body.removeChild(tmp);
185 const GameInfo = React.memo(props => {
190 <div className="game-info">
191 <span className="game-id">{props.id}</span>
193 Share this link to invite friends:{" "}
194 <span id="game-share-url">{props.url}</span>
198 onClick={() => copy_to_clipboard('game-share-url')}
204 const PlayerInfo = React.memo(props => {
205 if (! props.player.id)
209 <div className="player-info">
210 <span className="players-header">Players: </span>
212 {props.player.score > 0 ? ` (${props.player.score})` : ""}
213 {props.other_players.map(other => (
214 <span key={other.id}>
217 {other.score > 0 ? ` (${other.score})` : ""}
224 function fetch_method_json(method, api = '', data = {}) {
225 const response = fetch(api, {
228 'Content-Type': 'application/json'
230 body: JSON.stringify(data)
235 function fetch_post_json(api = '', data = {}) {
236 return fetch_method_json('POST', api, data);
239 async function fetch_put_json(api = '', data = {}) {
240 return fetch_method_json('PUT', api, data);
243 class CategoryRequest extends React.PureComponent {
246 this.category = React.createRef();
248 this.handle_change = this.handle_change.bind(this);
249 this.handle_submit = this.handle_submit.bind(this);
252 handle_change(event) {
253 const category_input = this.category.current;
254 const category = category_input.value;
256 const match = category.match(/[0-9]+/);
258 const num_items = parseInt(match[0], 10);
259 if (num_items <= MAX_PROMPT_ITEMS)
260 category_input.setCustomValidity("");
264 async handle_submit(event) {
265 const form = event.currentTarget;
266 const category_input = this.category.current;
267 const category = category_input.value;
269 /* Prevent the default page-changing form-submission behavior. */
270 event.preventDefault();
272 const match = category.match(/[0-9]+/);
273 if (match === null) {
274 category_input.setCustomValidity("Category must include a number");
275 form.reportValidity();
279 const num_items = parseInt(match[0], 10);
281 if (num_items > MAX_PROMPT_ITEMS) {
282 category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
283 form.reportValidity();
287 const response = await fetch_post_json("prompts", {
292 if (response.status === 200) {
293 const result = await response.json();
294 if (! result.valid) {
295 add_message("danger", result.message);
299 add_message("danger", "An error occurred submitting your category");
307 <div className="category-request">
308 <h2>Submit a Category</h2>
310 Suggest a category to play. Don't forget to include the
311 number of items for each person to submit.
314 <form onSubmit={this.handle_submit} >
315 <div className="form-field large">
319 placeholder="6 things at the beach"
322 onChange={this.handle_change}
327 <div className="form-field large">
328 <button type="submit">
339 const PromptOptions = React.memo(props => {
341 if (props.prompts.length === 0)
345 <div className="prompt-options">
346 <h2>Vote on Categories</h2>
348 Select any categories below that you'd like to play.
349 You can choose as many as you'd like.
351 {props.prompts.map(p => {
354 className="vote-button"
356 onClick={() => fetch_post_json(`vote/${p.id}`) }
359 <div className="vote-choices">
364 className="vote-choice"
378 const LetsPlay = React.memo(props => {
380 const quorum = Math.round((props.num_players + 1) / 2);
381 const max_votes = props.prompts.reduce(
382 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
384 if (max_votes < quorum)
387 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
388 const index = Math.floor(Math.random() * candidates.length);
389 const winner = candidates[index];
392 <div className="lets-play">
395 That should be enough voting. If you're not waiting for any
396 other players to join, then let's start.
399 className="lets-play"
400 onClick={() => fetch_post_json(`start/${winner.id}`) }
408 class Ambiguities extends React.PureComponent {
413 const word_sets = props.words.map(word => {
414 const set = new Set();
420 word_sets: word_sets,
424 this.submitted = false;
425 this.judging_sent_recently = false;
428 async handle_submit() {
430 /* Don't submit a second time. */
434 const response = await fetch_post_json(
435 `judged/${this.props.prompt.id}`,{
436 word_groups: this.state.word_sets.map(set => Array.from(set))
440 if (response.status === 200) {
441 const result = await response.json();
442 if (! result.valid) {
443 add_message("danger", result.message);
447 add_message("danger", "An error occurred submitting the results of your judging");
451 this.submitted = true;
456 /* Let the server know we are doing some judging, (but rate limit
457 * this so we don't send a "judging" notification more frquently
460 if (! this.judging_sent_recently) {
461 fetch_post_json(`judging/${this.props.prompt.id}`);
462 this.judging_sent_recently = true;
463 setTimeout(() => { this.judging_sent_recently = false; }, 1000);
466 if (this.state.selected == word) {
467 /* Second click on same word removes the word from the group. */
468 const idx = this.state.word_sets.findIndex(s => s.has(word));
469 const set = this.state.word_sets[idx];
470 if (set.size === 1) {
471 /* When the word is already alone, there's nothing to do but
472 * to un-select it. */
479 const new_set = new Set([...set].filter(w => w !== word));
482 word_sets: [...this.state.word_sets.slice(0, idx),
485 ...this.state.word_sets.slice(idx+1)]
487 } else if (this.state.selected) {
488 /* Click of a second word groups the two together. */
489 const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
490 const idx2 = this.state.word_sets.findIndex(s => s.has(word));
491 const set1 = this.state.word_sets[idx1];
492 const set2 = this.state.word_sets[idx2];
493 const new_set = new Set([...set2, ...set1]);
497 word_sets: [...this.state.word_sets.slice(0, idx1),
498 ...this.state.word_sets.slice(idx1 + 1, idx2),
500 ...this.state.word_sets.slice(idx2 + 1)]
505 word_sets: [...this.state.word_sets.slice(0, idx2),
507 ...this.state.word_sets.slice(idx2 + 1, idx1),
508 ...this.state.word_sets.slice(idx1 + 1)]
512 /* First click of a word selects it. */
520 let move_on_button = null;
522 if (this.props.idle) {
525 className="vote-button"
526 onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
529 <div className="vote-choices">
530 {[...this.props.votes].map(v => {
534 className="vote-choice"
545 if (this.props.players_judged.has(this.props.player.name)) {
547 <div className="please-wait">
548 <h2>Submission received</h2>
550 The following players have completed judging:
551 {[...this.props.players_judged].join(', ')}
554 Still waiting for the following players:
557 {Object.keys(this.props.players_judging).map(player => {
563 {this.props.players_judging[player] ?
564 <span className="typing"/> : null }
575 const btn_class = "ambiguity-button";
576 const btn_selected_class = btn_class + " selected";
579 <div className="ambiguities">
580 <h2>Judging Answers</h2>
582 Click on each pair of answers that should be scored as equivalent,
583 (and click any word twice to split it out from a group). Remember,
584 what goes around comes around, so it's best to be generous when
587 {this.state.word_sets.map(set => {
590 className="ambiguity-group"
591 key={Array.from(set)[0]}
593 {Array.from(set).map(word => {
596 className={this.state.selected === word ?
597 btn_selected_class : btn_class }
599 onClick={() => this.handle_click(word)}
609 Click here when done judging:<br/>
611 onClick={() => this.handle_submit()}
621 class ActivePrompt extends React.PureComponent {
625 const items = props.prompt.items;
627 this.submitted = false;
629 this.answers = [...Array(items)].map(() => React.createRef());
630 this.answering_sent_recently = false;
632 this.handle_submit = this.handle_submit.bind(this);
633 this.handle_change = this.handle_change.bind(this);
636 handle_change(event) {
637 /* We don't care (or even look) at what the player is typing at
638 * this point. We simply want to be informed that the player _is_
639 * typing so that we can tell the server (which will tell other
640 * players) that there is activity here.
643 /* Rate limit so that we don't send an "answering" notification
644 * more frequently than necessary.
646 if (! this.answering_sent_recently) {
647 fetch_post_json(`answering/${this.props.prompt.id}`);
648 this.answering_sent_recently = true;
649 setTimeout(() => { this.answering_sent_recently = false; }, 1000);
653 async handle_submit(event) {
654 const form = event.currentTarget;
656 /* Prevent the default page-changing form-submission behavior. */
657 event.preventDefault();
659 /* And don't submit a second time. */
663 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
664 answers: this.answers.map(r => r.current.value)
666 if (response.status === 200) {
667 const result = await response.json();
668 if (! result.valid) {
669 add_message("danger", result.message);
673 add_message("danger", "An error occurred submitting your answers");
677 /* Everything worked. Server is happy with our answers. */
679 this.submitted = true;
683 let move_on_button = null;
684 if (this.props.idle) {
687 className="vote-button"
688 onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
691 <div className="vote-choices">
692 {[...this.props.votes].map(v => {
696 className="vote-choice"
707 if (this.props.players_answered.has(this.props.player.name)) {
709 <div className="please-wait">
710 <h2>Submission received</h2>
712 The following players have submitted their answers:
713 {[...this.props.players_answered].join(', ')}
716 Still waiting for the following players:
719 {Object.keys(this.props.players_answering).map(player => {
725 {this.props.players_answering[player] ?
726 <span className="typing"/> : null }
738 <div className="active-prompt">
739 <h2>The Game of Empathy</h2>
741 Remember, you're trying to match your answers with
742 what the other players submit.
743 Give {this.props.prompt.items} answers for the following prompt:
745 <h2>{this.props.prompt.prompt}</h2>
746 <form onSubmit={this.handle_submit}>
747 {[...Array(this.props.prompt.items)].map((whocares,i) => {
751 className="form-field large">
757 onChange={this.handle_change}
758 ref={this.answers[i]}
766 className="form-field large">
767 <button type="submit">
778 class Game extends React.PureComponent {
787 players_answered: new Set(),
788 players_answering: {},
789 answering_idle: false,
790 end_answers_votes: new Set(),
792 players_judged: new Set(),
795 end_judging_votes: new Set(),
800 set_game_info(info) {
806 set_player_info(info) {
812 set_other_player_info(info) {
813 const other_players_copy = [...this.state.other_players];
814 const idx = other_players_copy.findIndex(o => o.id === info.id);
816 other_players_copy[idx] = info;
818 other_players_copy.push(info);
821 other_players: other_players_copy
829 players_answered: new Set(),
830 players_answering: {},
831 answering_idle: false,
832 end_answers_votes: new Set(),
834 players_judged: new Set(),
837 end_judging_votes: new Set(),
842 set_prompts(prompts) {
848 add_or_update_prompt(prompt) {
849 const prompts_copy = [...this.state.prompts];
850 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
852 prompts_copy[idx] = prompt;
854 prompts_copy.push(prompt);
857 prompts: prompts_copy
861 set_active_prompt(prompt) {
863 active_prompt: prompt
867 set_players_answered(players) {
869 players_answered: new Set(players)
873 set_player_answered(player) {
874 const new_players_answering = {...this.state.players_answering};
875 delete new_players_answering[player];
878 players_answered: new Set([...this.state.players_answered, player]),
879 players_answering: new_players_answering
883 set_players_answering(players) {
884 const players_answering = {};
885 for (let player of players) {
886 players_answering[player] = {active: false};
889 players_answering: players_answering
893 set_player_answering(player) {
896 ...this.state.players_answering,
897 [player]: {active: true}
902 set_answering_idle(value) {
904 answering_idle: value
908 set_end_answers(players) {
910 end_answers_votes: new Set(players)
914 set_player_vote_end_answers(player) {
916 end_answers_votes: new Set([...this.state.end_answers_votes, player])
920 set_player_unvote_end_answers(player) {
922 end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
926 set_ambiguities(ambiguities) {
928 ambiguities: ambiguities
932 set_players_judged(players) {
934 players_judged: new Set(players)
938 set_player_judged(player) {
939 const new_players_judging = {...this.state.players_judging};
940 delete new_players_judging[player];
943 players_judged: new Set([...this.state.players_judged, player]),
944 players_judging: new_players_judging
948 set_players_judging(players) {
949 const players_judging = {};
950 for (let player of players) {
951 players_judging[player] = {active: false};
954 players_judging: players_judging
958 set_player_judging(player) {
961 ...this.state.players_judging,
962 [player]: {active: true}
967 set_judging_idle(value) {
968 console.log("Setting judging idle to " + value);
974 set_end_judging(players) {
976 end_judging_votes: new Set(players)
980 set_player_vote_end_judging(player) {
982 end_judging_votes: new Set([...this.state.end_judging_votes, player])
986 set_player_unvote_end_judging(player) {
988 end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
999 const state = this.state;
1000 const players_total = 1 + state.other_players.length;
1004 <div className="scores">
1007 {state.scores.scores.map(score => {
1009 <li key={score.player}>
1010 {score.player}: {score.score}
1015 <h2>Words submitted</h2>
1017 {state.scores.words.map(word => {
1019 <li key={word.word}>
1020 {`${word.word}: ${word.players.join(', ')}`}
1026 className="new-game"
1027 onClick={() => fetch_post_json('reset') }
1035 if (state.ambiguities){
1037 prompt={state.active_prompt}
1038 words={state.ambiguities}
1039 player={state.player_info}
1040 players_judged={state.players_judged}
1041 players_judging={state.players_judging}
1042 idle={state.judging_idle}
1043 votes={state.end_judging_votes}
1047 if (state.active_prompt) {
1048 return <ActivePrompt
1049 prompt={state.active_prompt}
1050 player={state.player_info}
1051 players_answered={state.players_answered}
1052 players_answering={state.players_answering}
1053 idle={state.answering_idle}
1054 votes={state.end_answers_votes}
1061 id={state.game_info.id}
1062 url={state.game_info.url}
1067 player={state.player_info}
1068 other_players={state.other_players}
1070 <p key="spacer"></p>,
1072 key="category-request"
1076 prompts={state.prompts}
1080 num_players={1+state.other_players.length}
1081 prompts={state.prompts}
1087 ReactDOM.render(<Game
1088 ref={(me) => window.game = me}
1089 />, document.getElementById("empathy"));