]> git.cworth.org Git - lmno.games/blob - scribe/scribe.jsx
Rename local variable from "active" to "grid_active"
[lmno.games] / scribe / scribe.jsx
1 function team_symbol(team) {
2   if (team === "+")
3     return "+";
4   else
5     return "o";
6 }
7
8 function undisplay(element) {
9   element.style.display="none";
10 }
11
12 function add_message(severity, message) {
13   message = `<div class="message ${severity}" onclick="undisplay(this)">
14 <span class="hide-button" onclick="undisplay(this.parentElement)">&times;</span>
15 ${message}
16 </div>`;
17   const message_area = document.getElementById('message-area');
18   message_area.insertAdjacentHTML('beforeend', message);
19 }
20
21 /*********************************************************
22  * Handling server-sent event stream                     *
23  *********************************************************/
24
25 const events = new EventSource("events");
26
27 events.onerror = function(event) {
28   if (event.target.readyState === EventSource.CLOSED) {
29     setTimeout(() => {
30       add_message("danger", "Connection to server lost.");
31     }, 1000);
32   }
33 };
34
35 events.addEventListener("game-info", event => {
36   const info = JSON.parse(event.data);
37
38   window.game.set_game_info(info);
39 });
40
41 events.addEventListener("player-info", event => {
42   const info = JSON.parse(event.data);
43
44   window.game.set_player_info(info);
45 });
46
47 events.addEventListener("player-enter", event => {
48   const info = JSON.parse(event.data);
49
50   window.game.set_other_player_info(info);
51 });
52
53 events.addEventListener("player-update", event => {
54   const info = JSON.parse(event.data);
55
56   if (info.id === window.game.state.player_info.id)
57     window.game.set_player_info(info);
58   else
59     window.game.set_other_player_info(info);
60 });
61
62 events.addEventListener("move", event => {
63   const move = JSON.parse(event.data);
64
65   window.game.receive_move(move);
66 });
67
68 events.addEventListener("game-state", event => {
69   const state = JSON.parse(event.data);
70
71   window.game.reset_board();
72
73   for (let square of state.moves) {
74     window.game.receive_move(square);
75   }
76 });
77
78 /*********************************************************
79  * Game and supporting classes                           *
80  *********************************************************/
81
82 const scribe_glyphs = [
83   {
84     name: "Single",
85     squares: [1,0,0,
86               0,0,0,
87               0,0,0]
88   },
89   {
90     name: "Double",
91     squares: [1,1,0,
92               0,0,0,
93               0,0,0]
94   },
95   {
96     name: "Line",
97     squares: [1,1,1,
98               0,0,0,
99               0,0,0]
100   },
101   {
102     name: "Pipe",
103     squares: [0,0,1,
104               1,1,1,
105               0,0,0]
106   },
107   {
108     name: "Squat-T",
109     squares: [1,1,1,
110               0,1,0,
111               0,0,0]
112   },
113   {
114     name: "4-block",
115     squares: [1,1,0,
116               1,1,0,
117               0,0,0]
118   },
119   {
120     name: "T",
121     squares: [1,1,1,
122               0,1,0,
123               0,1,0]
124   },
125   {
126     name: "Cross",
127     squares: [0,1,0,
128               1,1,1,
129               0,1,0]
130   },
131   {
132     name: "6-block",
133     squares: [1,1,1,
134               1,1,1,
135               0,0,0]
136   },
137   {
138     name: "Bomber",
139     squares: [1,1,1,
140               0,1,1,
141               0,0,1]
142   },
143   {
144     name: "Chair",
145     squares: [0,0,1,
146               1,1,1,
147               1,0,1]
148   },
149   {
150     name: "J",
151     squares: [0,0,1,
152               1,0,1,
153               1,1,1]
154   },
155   {
156     name: "Earring",
157     squares: [0,1,1,
158               1,0,1,
159               1,1,1]
160   },
161   {
162     name: "House",
163     squares: [0,1,0,
164               1,1,1,
165               1,1,1]
166   },
167   {
168     name: "H",
169     squares: [1,0,1,
170               1,1,1,
171               1,0,1]
172   },
173   {
174     name: "U",
175     squares: [1,0,1,
176               1,0,1,
177               1,1,1]
178   },
179   {
180     name: "Ottoman",
181     squares: [1,1,1,
182               1,1,1,
183               1,0,1]
184   },
185   {
186     name: "O",
187     squares: [1,1,1,
188               1,0,1,
189               1,1,1]
190   },
191   {
192     name: "9-block",
193     squares: [1,1,1,
194               1,1,1,
195               1,1,1]
196   }
197 ];
198
199 function copy_to_clipboard(id)
200 {
201   const tmp = document.createElement("input");
202   tmp.setAttribute("value", document.getElementById(id).innerHTML);
203   document.body.appendChild(tmp);
204   tmp.select();
205   document.execCommand("copy");
206   document.body.removeChild(tmp);
207 }
208
209 function GameInfo(props) {
210   if (! props.id)
211     return null;
212
213   return (
214     <div className="game-info">
215       <span className="game-id">{props.id}</span>
216       {" "}
217       Share this link to invite a friend:{" "}
218       <span id="game-share-url">{props.url}</span>
219       {" "}
220       <button
221         className="inline"
222         onClick={() => copy_to_clipboard('game-share-url')}
223       >Copy Link</button>
224     </div>
225   );
226 }
227
228 function TeamButton(props) {
229   return <button className="inline"
230                  onClick={() => props.game.join_team(props.team)}>
231            {props.label}
232          </button>;
233 }
234
235 function TeamChoices(props) {
236   let other_team;
237   if (props.player.team === "+")
238     other_team = "o";
239   else
240     other_team = "+";
241
242   if (props.player.team === "") {
243     if (props.first_move) {
244       return null;
245     } else {
246       return [
247         <TeamButton key="+" game={props.game} team="+" label="Join ðŸž¥" />,
248         " ",
249         <TeamButton key="o" game={props.game} team="o" label="Join ðŸž‡" />
250       ];
251     }
252   } else {
253     return <TeamButton game={props.game} team={other_team} label="Switch" />;
254   }
255 }
256
257 function PlayerInfo(props) {
258   if (! props.player.id)
259     return null;
260
261   const choices = <TeamChoices
262                     game={props.game}
263                     first_move={props.first_move}
264                     player={props.player}
265                   />;
266
267   return (
268     <div className="player-info">
269       <span className="players-header">Players: </span>
270       {props.player.name}
271       {props.player.team ? ` (${props.player.team})` : ""}
272       {props.first_move ? "" : " "}
273       {choices}
274       {props.other_players.map(other => (
275         <span key={other.id}>
276           {", "}
277           {other.name}
278           {other.team ? ` (${other.team})` : ""}
279         </span>
280       ))}
281     </div>
282   );
283 }
284
285 function Glyph(props) {
286
287   const glyph_dots = [];
288
289   let last_square = 0;
290   for (let i = 0; i < 9; i++) {
291     if (props.squares[i])
292       last_square = i;
293   }
294
295   const height = Math.floor(20 * (Math.floor(last_square / 3) + 1));
296
297   const viewbox=`0 0 60 ${height}`;
298
299   for (let row = 0; row < 3; row++) {
300     for (let col = 0; col < 3; col++) {
301       if (props.squares[3 * row + col]) {
302         let cy = 10 + 20 * row;
303         let cx = 10 + 20 * col;
304         glyph_dots.push(
305           <circle
306             key={3 * row + col}
307             cx={cx}
308             cy={cy}
309             r="8"
310           />
311         );
312       }
313     }
314   }
315
316   return (<div className="glyph-and-name">
317             {props.name}
318             <div className="glyph">
319               <svg viewBox={viewbox}>
320                 <g fill="#287789">
321                   {glyph_dots}
322                 </g>
323               </svg>
324             </div>
325           </div>
326          );
327 }
328
329 function Square(props) {
330   let className = "square";
331
332   if (props.value) {
333     className += " occupied";
334   } else if (props.active) {
335     className += " open";
336   }
337
338   if (props.last_move) {
339     className += " last-move";
340   }
341
342   const onClick = props.active ? props.onClick : null;
343
344   return (
345     <div className={className}
346          onClick={onClick}>
347       {props.value}
348     </div>
349   );
350 }
351
352 function MiniGrid(props) {
353   function grid_square(j) {
354     const value = props.squares[j];
355     const last_move = props.last_moves.includes(j);
356     return (
357       <Square
358         value={value}
359         active={props.active}
360         last_move={last_move}
361         onClick={() => props.onClick(j)}
362       />
363     );
364   }
365
366   /* Even if my parent thinks I'm active because of the last move, I
367    * might not _really_ be active if I'm full. */
368   let occupied = 0;
369   props.squares.forEach(element => {
370     if (element)
371       occupied++;
372   });
373
374   let class_name = "mini-grid";
375   if (props.active && occupied < 9)
376     class_name += " active";
377
378   return (
379     <div className={class_name}>
380       {grid_square(0)}
381       {grid_square(1)}
382       {grid_square(2)}
383       {grid_square(3)}
384       {grid_square(4)}
385       {grid_square(5)}
386       {grid_square(6)}
387       {grid_square(7)}
388       {grid_square(8)}
389     </div>
390   );
391 }
392
393 class Board extends React.Component {
394   mini_grid(i) {
395     /* This mini grid is active only if both:
396      *
397      * 1. It is our turn (this.props.active === true)
398      *
399      * 2. One of the following conditions is met:
400      *
401      *    a. This is this players first turn (last_two_moves[0] === null)
402      *    b. This mini grid corresponds to this players last turn
403      *    c. The mini grid that corresponds to the players last turn is full
404      */
405     let grid_active = false;
406     if (this.props.active) {
407       grid_active = true;
408       if (this.props.last_two_moves.length > 1) {
409         /* First index (0) gives us our last move, (that is, of the
410          * last two moves, it's the first one, so two moves ago).
411          *
412          * Second index (1) gives us the second number from that move,
413          * (that is, the index within the mini-grid that we last
414          * played).
415          */
416         const target = this.props.last_two_moves[0][1];
417         let occupied = 0;
418         this.props.squares[target].forEach(element => {
419           if (element)
420             occupied++;
421         });
422         /* If the target mini-grid isn't full then this grid is
423          * only active if it is that target. */
424         if (occupied < 9)
425           grid_active = (i === target);
426       }
427     }
428
429     /* We want to highlight each of the last two moves (both "+" and
430      * "o"). So we filter the last two moves that have a first index
431      * that matches this mini_grid and pass down their second index
432      * be highlighted.
433      */
434     const last_moves = this.props.last_two_moves.filter(move => move[0] === i)
435           .map(move => move[1]);
436
437     const squares = this.props.squares[i];
438     return (
439       <MiniGrid
440         squares={squares}
441         active={grid_active}
442         last_moves={last_moves}
443         onClick={(j) => this.props.onClick(i,j)}
444       />
445     );
446   }
447
448   render() {
449     return (
450       <div className="board-container">
451         <div className="board">
452           {this.mini_grid(0)}
453           {this.mini_grid(1)}
454           {this.mini_grid(2)}
455           {this.mini_grid(3)}
456           {this.mini_grid(4)}
457           {this.mini_grid(5)}
458           {this.mini_grid(6)}
459           {this.mini_grid(7)}
460           {this.mini_grid(8)}
461         </div>
462       </div>
463     );
464   }
465 }
466
467 function fetch_method_json(method, api = '', data = {}) {
468   const response = fetch(api, {
469     method: method,
470     headers: {
471       'Content-Type': 'application/json'
472     },
473     body: JSON.stringify(data)
474   });
475   return response;
476 }
477
478 function fetch_post_json(api = '', data = {}) {
479   return fetch_method_json('POST', api, data);
480 }
481
482 async function fetch_put_json(api = '', data = {}) {
483   return fetch_method_json('PUT', api, data);
484 }
485
486 class Game extends React.Component {
487   constructor(props) {
488     super(props);
489     this.state = {
490       game_info: {},
491       player_info: {},
492       other_players: [],
493       squares: [...Array(9)].map(() => Array(9).fill(null)),
494       moves: [],
495       next_to_play: "+",
496     };
497   }
498
499   set_game_info(info) {
500     this.setState({
501       game_info: info
502     });
503   }
504
505   set_player_info(info) {
506     this.setState({
507       player_info: info
508     });
509   }
510
511   set_other_player_info(info) {
512     const other_players_copy = [...this.state.other_players];
513     const idx = other_players_copy.findIndex(o => o.id === info.id);
514     if (idx >= 0) {
515       other_players_copy[idx] = info;
516     } else {
517       other_players_copy.push(info);
518     }
519     this.setState({
520       other_players: other_players_copy
521     });
522   }
523
524   reset_board() {
525     this.setState({
526       next_to_play: "+"
527     });
528   }
529
530   receive_move(move) {
531     if (this.state.moves.length === 81) {
532       return;
533     }
534     const symbol = team_symbol(this.state.next_to_play);
535     const new_squares = this.state.squares.map(arr => arr.slice());
536     new_squares[move[0]][move[1]] = symbol;
537     const new_moves = [...this.state.moves, move];
538     let next_to_play;
539     if (this.state.next_to_play === "+")
540       next_to_play = "o";
541     else
542       next_to_play = "+";
543     this.setState({
544       squares: new_squares,
545       moves: new_moves,
546       next_to_play: next_to_play
547     });
548   }
549
550   async handle_click(i, j, first_move) {
551     let move = {
552       move: [i, j]
553     };
554     if (first_move) {
555       move.assert_first_move = true;
556     }
557     const response = await fetch_post_json("move", move);
558     if (response.status == 200) {
559       const result = await response.json();
560       if (! result.legal)
561         add_message("danger", result.message);
562     } else {
563       add_message("danger", `Error occurred sending move`);
564     }
565   }
566
567   join_team(team) {
568     fetch_put_json("player", {team: team});
569   }
570
571   render() {
572     const state = this.state;
573     const first_move = state.moves.length === 0;
574     const my_team = state.player_info.team;
575     var board_active;
576
577     let status;
578     if (this.state.moves.length === 81)
579     {
580       status = "Game over";
581       board_active = false;
582     }
583     else if (first_move)
584     {
585       if (state.other_players.length == 0) {
586         status = "You can move or wait for another player to join.";
587       } else {
588         let qualifier;
589         if (state.other_players.length == 1) {
590           qualifier = "Either";
591         } else {
592           qualifier = "Any";
593         }
594         status = `${qualifier} player can make the first move.`;
595       }
596       board_active = true;
597     }
598     else if (my_team === "")
599     {
600       status = "You're just watching the game.";
601       board_active = false;
602     }
603     else if (my_team === state.next_to_play)
604     {
605       status = "Your turn. Make a move.";
606       board_active = true;
607     }
608     else
609     {
610       status = "Waiting for another player to ";
611       if (state.other_players.length == 0) {
612         status += "join.";
613       } else {
614         status += "move.";
615       }
616       board_active = false;
617     }
618
619     return [
620       <GameInfo
621         key="game-info"
622         id={state.game_info.id}
623         url={state.game_info.url}
624       />,
625       <PlayerInfo
626         key="player-info"
627         game={this}
628         first_move={first_move}
629         player={state.player_info}
630         other_players={state.other_players}
631       />,
632       <div key="game" className="game">
633         <div>{status}</div>
634         <div className="game-board">
635           <Board
636             active={board_active}
637             squares={state.squares}
638             last_two_moves={state.moves.slice(-2)}
639             onClick={(i,j) => this.handle_click(i, j, first_move)}
640           />
641         </div>
642       </div>,
643       <div key="glyphs" className="glyphs">
644         {
645           scribe_glyphs.map(glyph => {
646             return (
647               <Glyph
648                 key={glyph.name}
649                 name={glyph.name}
650                 squares={glyph.squares}
651               />
652             );
653           })
654         }
655       </div>
656     ];
657   }
658 }
659
660 ReactDOM.render(<Game
661                   ref={(me) => window.game = me}
662                 />, document.getElementById("scribe"));