]> git.cworth.org Git - lmno.games/blob - empathy/empathy.jsx
Add a button to advance from prompt voting to playing the actual game
[lmno.games] / empathy / empathy.jsx
1 function undisplay(element) {
2   element.style.display="none";
3 }
4
5 function add_message(severity, message) {
6   message = `<div class="message ${severity}" onclick="undisplay(this)">
7 <span class="hide-button" onclick="undisplay(this.parentElement)">&times;</span>
8 ${message}
9 </div>`;
10   const message_area = document.getElementById('message-area');
11   message_area.insertAdjacentHTML('beforeend', message);
12 }
13
14 /*********************************************************
15  * Handling server-sent event stream                     *
16  *********************************************************/
17
18 const events = new EventSource("events");
19
20 events.onerror = function(event) {
21   if (event.target.readyState === EventSource.CLOSED) {
22     setTimeout(() => {
23       add_message("danger", "Connection to server lost.");
24     }, 1000);
25   }
26 };
27
28 events.addEventListener("game-info", event => {
29   const info = JSON.parse(event.data);
30
31   window.game.set_game_info(info);
32 });
33
34 events.addEventListener("player-info", event => {
35   const info = JSON.parse(event.data);
36
37   window.game.set_player_info(info);
38 });
39
40 events.addEventListener("player-enter", event => {
41   const info = JSON.parse(event.data);
42
43   window.game.set_other_player_info(info);
44 });
45
46 events.addEventListener("player-update", event => {
47   const info = JSON.parse(event.data);
48
49   if (info.id === window.game.state.player_info.id)
50     window.game.set_player_info(info);
51   else
52     window.game.set_other_player_info(info);
53 });
54
55 events.addEventListener("game-state", event => {
56   const state = JSON.parse(event.data);
57
58   for (let prompt of state.prompts) {
59     window.game.add_or_update_prompt(prompt);
60   }
61
62   window.game.set_active_prompt(state.active_prompt);
63 });
64
65 events.addEventListener("prompt", event => {
66   const prompt = JSON.parse(event.data);
67
68   window.game.add_or_update_prompt(prompt);
69 });
70
71 events.addEventListener("start", event => {
72   const prompt = JSON.parse(event.data);
73
74   window.game.set_active_prompt(prompt);
75 });
76
77 /*********************************************************
78  * Game and supporting classes                           *
79  *********************************************************/
80
81 function copy_to_clipboard(id)
82 {
83   const tmp = document.createElement("input");
84   tmp.setAttribute("value", document.getElementById(id).innerHTML);
85   document.body.appendChild(tmp);
86   tmp.select();
87   document.execCommand("copy");
88   document.body.removeChild(tmp);
89 }
90
91 const GameInfo = React.memo(props => {
92   if (! props.id)
93     return null;
94
95   return (
96     <div className="game-info">
97       <span className="game-id">{props.id}</span>
98       {" "}
99       Share this link to invite friends:{" "}
100       <span id="game-share-url">{props.url}</span>
101       {" "}
102       <button
103         className="inline"
104         onClick={() => copy_to_clipboard('game-share-url')}
105       >Copy Link</button>
106     </div>
107   );
108 });
109
110 const PlayerInfo = React.memo(props => {
111   if (! props.player.id)
112     return null;
113
114   return (
115     <div className="player-info">
116       <span className="players-header">Players: </span>
117       {props.player.name}
118       {props.other_players.map(other => (
119         <span key={other.id}>
120           {", "}
121           {other.name}
122         </span>
123       ))}
124     </div>
125   );
126 });
127
128 function fetch_method_json(method, api = '', data = {}) {
129   const response = fetch(api, {
130     method: method,
131     headers: {
132       'Content-Type': 'application/json'
133     },
134     body: JSON.stringify(data)
135   });
136   return response;
137 }
138
139 function fetch_post_json(api = '', data = {}) {
140   return fetch_method_json('POST', api, data);
141 }
142
143 async function fetch_put_json(api = '', data = {}) {
144   return fetch_method_json('PUT', api, data);
145 }
146
147 class CategoryRequest extends React.PureComponent {
148   constructor(props) {
149     super(props);
150     this.category = React.createRef();
151
152     this.handle_change = this.handle_change.bind(this);
153     this.handle_submit = this.handle_submit.bind(this);
154   }
155
156   handle_change(event) {
157     const category_input = this.category.current;
158     const category = category_input.value;
159
160     if (/[0-9]/.test(category))
161       category_input.setCustomValidity("");
162   }
163
164   handle_submit(event) {
165     const form = event.currentTarget;
166     const category_input = this.category.current;
167     const category = category_input.value;
168
169     /* Prevent the default page-changing form-submission behavior. */
170     event.preventDefault();
171
172     const match = category.match(/[0-9]+/);
173     if (match === null) {
174       category_input.setCustomValidity("Category must include a number");
175       form.reportValidity();
176       return;
177     }
178
179     fetch_post_json("prompts", {
180       items: parseInt(match[0], 10),
181       prompt: category
182     });
183
184     form.reset();
185   }
186
187   render() {
188     return (
189       <div className="category-request">
190         <h2>Submit a Category</h2>
191         <p>
192           Suggest a category to play. Don't forget to include the
193           number of items for each person to submit.
194         </p>
195
196         <form onSubmit={this.handle_submit} >
197           <div className="form-field large">
198             <input
199               type="text"
200               id="category"
201               placeholder="6 things at the beach"
202               required
203               autoComplete="off"
204               onChange={this.handle_change}
205               ref={this.category}
206             />
207           </div>
208
209           <div className="form-field large">
210             <button type="submit">
211               Send
212             </button>
213           </div>
214
215         </form>
216       </div>
217     );
218   }
219 }
220
221 const PromptOptions = React.memo(props => {
222
223   if (props.prompts.length === 0)
224     return null;
225
226   return (
227     <div className="prompt-options">
228       <h2>Vote on Categories</h2>
229       <p>
230         Select any categories below that you'd like to play.
231         You can choose as many as you'd like.
232       </p>
233       {props.prompts.map(p => {
234         return (
235           <button
236             className="vote-button"
237             key={p.id}
238             onClick={() => fetch_post_json(`vote/${p.id}`) }
239           >
240             {p.prompt}
241             <div className="vote-choices">
242               {p.votes.map(v => {
243                 return (
244                   <div
245                     key={v}
246                     className="vote-choice"
247                   >
248                     {v}
249                   </div>
250                 );
251               })}
252             </div>
253           </button>
254         );
255       })}
256     </div>
257   );
258 });
259
260 const LetsPlay = React.memo(props => {
261
262   function handle_click(prompt_id) {
263     fetch_post_json
264   }
265
266   const quorum = Math.round((props.num_players + 1) / 2);
267   const max_votes = props.prompts.reduce(
268     (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
269
270   if (max_votes < quorum)
271     return null;
272
273   const candidates = props.prompts.filter(p => p.votes.length >= quorum);
274   const index = Math.floor(Math.random() * candidates.length);
275   const winner = candidates[index];
276
277   return (
278     <div className="lets-play">
279       <h2>Let's Play</h2>
280       <p>
281         That should be enough voting. If you're not waiting for any
282         other players to join, then let's start.
283       </p>
284       <button
285         className="lets-play"
286         onClick={() => fetch_post_json(`start/${winner.id}`) }
287       >
288         Start Game
289       </button>
290     </div>
291   );
292 });
293
294 const ActivePrompt = React.memo(props => {
295
296   function handle_submit(event) {
297
298     /* Prevent the default page-changing form-submission behavior. */
299     event.preventDefault();
300   }
301
302   return (
303     <div className="active-prompt">
304       <h2>The Game of Empathy</h2>
305       <p>
306         Remember, you're trying to match your answers with
307         what the other players submit.
308         Give {props.prompt.items} responses for the following prompt:
309       </p>
310       <h2>{props.prompt.prompt}</h2>
311       <form onSubmit={handle_submit}>
312         {Array(props.prompt.items).fill(null).map((whocares,i) => {
313           return (
314             <div
315               key={i}
316               className="form-field large">
317               <input
318                 type="text"
319                 name={`response_${i}`}
320                 required
321                 autoComplete="off"
322               />
323             </div>
324           );
325         })}
326
327         <div
328           key="submit-button"
329           className="form-field large">
330           <button type="submit">
331             Send
332           </button>
333         </div>
334
335       </form>
336     </div>
337   );
338 });
339
340 class Game extends React.PureComponent {
341   constructor(props) {
342     super(props);
343     this.state = {
344       game_info: {},
345       player_info: {},
346       other_players: [],
347       prompts: []
348     };
349   }
350
351   set_game_info(info) {
352     this.setState({
353       game_info: info
354     });
355   }
356
357   set_player_info(info) {
358     this.setState({
359       player_info: info
360     });
361   }
362
363   set_other_player_info(info) {
364     const other_players_copy = [...this.state.other_players];
365     const idx = other_players_copy.findIndex(o => o.id === info.id);
366     if (idx >= 0) {
367       other_players_copy[idx] = info;
368     } else {
369       other_players_copy.push(info);
370     }
371     this.setState({
372       other_players: other_players_copy
373     });
374   }
375
376   add_or_update_prompt(prompt) {
377     const prompts_copy = [...this.state.prompts];
378     const idx = prompts_copy.findIndex(p => p.id === prompt.id);
379     if (idx >= 0) {
380       prompts_copy[idx] = prompt;
381     } else {
382       prompts_copy.push(prompt);
383     }
384     this.setState({
385       prompts: prompts_copy
386     });
387   }
388
389   set_active_prompt(prompt) {
390     this.setState({
391       active_prompt: prompt
392     });
393   }
394
395   render() {
396     const state = this.state;
397
398     if (state.active_prompt) {
399       return <ActivePrompt
400                prompt={state.active_prompt}
401              />;
402     }
403
404     return [
405       <GameInfo
406         key="game-info"
407         id={state.game_info.id}
408         url={state.game_info.url}
409       />,
410       <PlayerInfo
411         key="player-info"
412         game={this}
413         player={state.player_info}
414         other_players={state.other_players}
415       />,
416       <p key="spacer"></p>,
417       <CategoryRequest
418         key="category-request"
419       />,
420       <PromptOptions
421         key="prompts"
422         prompts={state.prompts}
423       />,
424       <LetsPlay
425         key="lets-play"
426         num_players={1+state.other_players.length}
427         prompts={state.prompts}
428       />
429     ];
430   }
431 }
432
433 ReactDOM.render(<Game
434                   ref={(me) => window.game = me}
435                 />, document.getElementById("empathy"));