1 function undisplay(element) {
2 element.style.display="none";
5 function add_message(severity, message) {
6 message = `<div class="message ${severity}" onclick="undisplay(this)">
7 <span class="hide-button" onclick="undisplay(this.parentElement)">×</span>
10 const message_area = document.getElementById('message-area');
11 message_area.insertAdjacentHTML('beforeend', message);
14 /*********************************************************
15 * Handling server-sent event stream *
16 *********************************************************/
18 const events = new EventSource("events");
20 events.onerror = function(event) {
21 if (event.target.readyState === EventSource.CLOSED) {
23 add_message("danger", "Connection to server lost.");
28 events.addEventListener("game-info", event => {
29 const info = JSON.parse(event.data);
31 window.game.set_game_info(info);
34 events.addEventListener("player-info", event => {
35 const info = JSON.parse(event.data);
37 window.game.set_player_info(info);
40 events.addEventListener("player-enter", event => {
41 const info = JSON.parse(event.data);
43 window.game.set_other_player_info(info);
46 events.addEventListener("player-update", event => {
47 const info = JSON.parse(event.data);
49 if (info.id === window.game.state.player_info.id)
50 window.game.set_player_info(info);
52 window.game.set_other_player_info(info);
55 events.addEventListener("game-state", event => {
56 const state = JSON.parse(event.data);
58 window.game.set_prompts(state.prompts);
60 window.game.set_active_prompt(state.active_prompt);
62 window.game.set_scores(state.scores);
64 window.game.set_ambiguities(state.ambiguities);
67 events.addEventListener("prompt", event => {
68 const prompt = JSON.parse(event.data);
70 window.game.add_or_update_prompt(prompt);
73 events.addEventListener("start", event => {
74 const prompt = JSON.parse(event.data);
76 window.game.set_active_prompt(prompt);
79 events.addEventListener("answered", event => {
80 const players_answered = JSON.parse(event.data);
82 window.game.set_players_answered(players_answered);
85 events.addEventListener("ambiguities", event => {
86 const ambiguities = JSON.parse(event.data);
88 window.game.set_ambiguities(ambiguities);
91 events.addEventListener("judged", event => {
92 const players_judged = JSON.parse(event.data);
94 window.game.set_players_judged(players_judged);
97 events.addEventListener("scores", event => {
98 const scores = JSON.parse(event.data);
100 window.game.set_scores(scores);
103 /*********************************************************
104 * Game and supporting classes *
105 *********************************************************/
107 function copy_to_clipboard(id)
109 const tmp = document.createElement("input");
110 tmp.setAttribute("value", document.getElementById(id).innerHTML);
111 document.body.appendChild(tmp);
113 document.execCommand("copy");
114 document.body.removeChild(tmp);
117 const GameInfo = React.memo(props => {
122 <div className="game-info">
123 <span className="game-id">{props.id}</span>
125 Share this link to invite friends:{" "}
126 <span id="game-share-url">{props.url}</span>
130 onClick={() => copy_to_clipboard('game-share-url')}
136 const PlayerInfo = React.memo(props => {
137 if (! props.player.id)
141 <div className="player-info">
142 <span className="players-header">Players: </span>
144 {props.player.score > 0 ? ` (${props.player.score})` : ""}
145 {props.other_players.map(other => (
146 <span key={other.id}>
149 {other.score > 0 ? ` (${other.score})` : ""}
156 function fetch_method_json(method, api = '', data = {}) {
157 const response = fetch(api, {
160 'Content-Type': 'application/json'
162 body: JSON.stringify(data)
167 function fetch_post_json(api = '', data = {}) {
168 return fetch_method_json('POST', api, data);
171 async function fetch_put_json(api = '', data = {}) {
172 return fetch_method_json('PUT', api, data);
175 class CategoryRequest extends React.PureComponent {
178 this.category = React.createRef();
180 this.handle_change = this.handle_change.bind(this);
181 this.handle_submit = this.handle_submit.bind(this);
184 handle_change(event) {
185 const category_input = this.category.current;
186 const category = category_input.value;
188 if (/[0-9]/.test(category))
189 category_input.setCustomValidity("");
192 handle_submit(event) {
193 const form = event.currentTarget;
194 const category_input = this.category.current;
195 const category = category_input.value;
197 /* Prevent the default page-changing form-submission behavior. */
198 event.preventDefault();
200 const match = category.match(/[0-9]+/);
201 if (match === null) {
202 category_input.setCustomValidity("Category must include a number");
203 form.reportValidity();
207 fetch_post_json("prompts", {
208 items: parseInt(match[0], 10),
217 <div className="category-request">
218 <h2>Submit a Category</h2>
220 Suggest a category to play. Don't forget to include the
221 number of items for each person to submit.
224 <form onSubmit={this.handle_submit} >
225 <div className="form-field large">
229 placeholder="6 things at the beach"
232 onChange={this.handle_change}
237 <div className="form-field large">
238 <button type="submit">
249 const PromptOptions = React.memo(props => {
251 if (props.prompts.length === 0)
255 <div className="prompt-options">
256 <h2>Vote on Categories</h2>
258 Select any categories below that you'd like to play.
259 You can choose as many as you'd like.
261 {props.prompts.map(p => {
264 className="vote-button"
266 onClick={() => fetch_post_json(`vote/${p.id}`) }
269 <div className="vote-choices">
274 className="vote-choice"
288 const LetsPlay = React.memo(props => {
290 function handle_click(prompt_id) {
294 const quorum = Math.round((props.num_players + 1) / 2);
295 const max_votes = props.prompts.reduce(
296 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
298 if (max_votes < quorum)
301 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
302 const index = Math.floor(Math.random() * candidates.length);
303 const winner = candidates[index];
306 <div className="lets-play">
309 That should be enough voting. If you're not waiting for any
310 other players to join, then let's start.
313 className="lets-play"
314 onClick={() => fetch_post_json(`start/${winner.id}`) }
322 class Ambiguities extends React.PureComponent {
328 word_groups: props.words.map(word => [word]),
334 async handle_submit() {
335 const response = await fetch_post_json(`judging/${this.props.prompt.id}`,
336 this.state.word_groups);
338 if (response.status === 200) {
339 const result = await response.json();
340 if (! result.valid) {
341 add_message("danger", result.message);
345 add_message("danger", "An error occurred submitting your answers");
355 if (this.state.selected == word) {
356 /* Second click on same word removes the word from the group. */
357 const new_groups = this.state.word_groups.filter(
358 group => (! group.includes(this.state.selected)) || (group.length > 1)).map(
360 return group.filter(w => w !== this.state.selected);
365 word_groups: [...new_groups, [word]]
367 } else if (this.state.selected) {
368 /* Click of a second word groups the two together. */
369 const new_groups = this.state.word_groups.filter(
370 group => (! group.includes(word)) || (group.length > 1)).map(
372 if (group.includes(this.state.selected)) {
373 if (! group.includes(word))
374 return [...group, word];
378 return group.filter(w => w !== word);
384 word_groups: new_groups
387 /* First click of a word selects it. */
395 if (this.state.submitted)
397 <div className="please-wait">
398 <h2>{this.props.players_judged}/
399 {this.props.players_total} players have responded</h2>
401 Please wait for the rest of the players to complete judging.
406 const btn_class = "ambiguity-button";
407 const btn_selected_class = btn_class + " selected";
410 <div className="ambiguities">
411 <h2>Judging Answers</h2>
413 Click on each pair of answers that should be scored as equivalent,
414 (and click any word twice to split it out from a group). Remember,
415 what goes around comes around, so it's best to be generous when
418 {this.state.word_groups.map(word_group => {
421 className="ambiguity-group"
424 {word_group.map(word => {
427 className={this.state.selected === word ?
428 btn_selected_class : btn_class }
430 onClick={() => this.handle_click(word)}
440 Click here when done judging:<br/>
442 onClick={() => this.handle_submit()}
452 class ActivePrompt extends React.PureComponent {
456 const items = props.prompt.items;
462 this.answers = [...Array(items)].map(() => React.createRef());
463 this.handle_submit = this.handle_submit.bind(this);
466 async handle_submit(event) {
467 const form = event.currentTarget;
469 /* Prevent the default page-changing form-submission behavior. */
470 event.preventDefault();
472 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
473 answers: this.answers.map(r => r.current.value)
475 if (response.status === 200) {
476 const result = await response.json();
477 if (! result.valid) {
478 add_message("danger", result.message);
482 add_message("danger", "An error occurred submitting your answers");
486 /* Everything worked. Server is happy with our answers. */
494 if (this.state.submitted)
496 <div className="please-wait">
497 <h2>{this.props.players_answered}/
498 {this.props.players_total} players have responded</h2>
500 Please wait for the rest of the players to submit their answers.
506 <div className="active-prompt">
507 <h2>The Game of Empathy</h2>
509 Remember, you're trying to match your answers with
510 what the other players submit.
511 Give {this.props.prompt.items} answers for the following prompt:
513 <h2>{this.props.prompt.prompt}</h2>
514 <form onSubmit={this.handle_submit}>
515 {[...Array(this.props.prompt.items)].map((whocares,i) => {
519 className="form-field large">
525 ref={this.answers[i]}
533 className="form-field large">
534 <button type="submit">
545 class Game extends React.PureComponent {
560 set_game_info(info) {
566 set_player_info(info) {
572 set_other_player_info(info) {
573 const other_players_copy = [...this.state.other_players];
574 const idx = other_players_copy.findIndex(o => o.id === info.id);
576 other_players_copy[idx] = info;
578 other_players_copy.push(info);
581 other_players: other_players_copy
585 set_prompts(prompts) {
591 add_or_update_prompt(prompt) {
592 const prompts_copy = [...this.state.prompts];
593 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
595 prompts_copy[idx] = prompt;
597 prompts_copy.push(prompt);
600 prompts: prompts_copy
604 set_active_prompt(prompt) {
606 active_prompt: prompt
610 set_players_answered(players_answered) {
612 players_answered: players_answered
616 set_ambiguities(ambiguities) {
618 ambiguities: ambiguities
622 set_players_judged(players_judged) {
624 players_judged: players_judged
635 const state = this.state;
636 const players_total = 1 + state.other_players.length;
640 <div className="scores">
643 {state.scores.scores.map(score => {
645 <li key={score.player}>
646 {score.player}: {score.score}
651 <h2>Words submitted</h2>
653 {state.scores.words.map(word => {
657 {word.players.map(p => {
659 <span key={p}>{p}{" "}</span>
668 onClick={() => fetch_post_json('reset') }
676 if (state.ambiguities){
678 prompt={state.active_prompt}
679 words={state.ambiguities}
680 players_judged={state.players_judged}
681 players_total={players_total}
685 if (state.active_prompt) {
687 prompt={state.active_prompt}
688 players_answered={state.players_answered}
689 players_total={players_total}
696 id={state.game_info.id}
697 url={state.game_info.url}
702 player={state.player_info}
703 other_players={state.other_players}
705 <p key="spacer"></p>,
707 key="category-request"
711 prompts={state.prompts}
715 num_players={1+state.other_players.length}
716 prompts={state.prompts}
722 ReactDOM.render(<Game
723 ref={(me) => window.game = me}
724 />, document.getElementById("empathy"));