1 function team_symbol(team) {
8 function undisplay(element) {
9 element.style.display="none";
12 function add_message(severity, message) {
13 message = `<div class="message ${severity}" onclick="undisplay(this)">
14 <span class="hide-button" onclick="undisplay(this.parentElement)">×</span>
17 const message_area = document.getElementById('message-area');
18 message_area.insertAdjacentHTML('beforeend', message);
21 /*********************************************************
22 * Handling server-sent event stream *
23 *********************************************************/
25 const events = new EventSource("events");
27 events.onerror = function(event) {
28 if (event.target.readyState === EventSource.CLOSED) {
30 add_message("danger", "Connection to server lost.");
35 events.addEventListener("game-info", event => {
36 const info = JSON.parse(event.data);
38 window.game.set_game_info(info);
41 events.addEventListener("player-info", event => {
42 const info = JSON.parse(event.data);
44 window.game.set_player_info(info);
47 events.addEventListener("player-enter", event => {
48 const info = JSON.parse(event.data);
50 window.game.set_other_player_info(info);
53 events.addEventListener("player-update", event => {
54 const info = JSON.parse(event.data);
56 if (info.id === window.game.state.player_info.id)
57 window.game.set_player_info(info);
59 window.game.set_other_player_info(info);
62 events.addEventListener("move", event => {
63 const move = JSON.parse(event.data);
65 window.game.receive_move(move);
68 events.addEventListener("game-state", event => {
69 const state = JSON.parse(event.data);
71 window.game.reset_board();
73 for (let square of state.moves) {
74 window.game.receive_move(square);
78 /*********************************************************
79 * Game and supporting classes *
80 *********************************************************/
82 const scribe_glyphs = [
199 function copy_to_clipboard(id)
201 const tmp = document.createElement("input");
202 tmp.setAttribute("value", document.getElementById(id).innerHTML);
203 document.body.appendChild(tmp);
205 document.execCommand("copy");
206 document.body.removeChild(tmp);
209 function GameInfo(props) {
214 <div className="game-info">
215 <span className="game-id">{props.id}</span>
217 Share this link to invite a friend:{" "}
218 <span id="game-share-url">{props.url}</span>
222 onClick={() => copy_to_clipboard('game-share-url')}
228 function TeamButton(props) {
229 return <button className="inline"
230 onClick={() => props.game.join_team(props.team)}>
235 function TeamChoices(props) {
237 if (props.player.team === "+")
242 if (props.player.team === "") {
243 if (props.first_move) {
247 <TeamButton key="+" game={props.game} team="+" label="Join 🞥" />,
249 <TeamButton key="o" game={props.game} team="o" label="Join 🞇" />
253 return <TeamButton game={props.game} team={other_team} label="Switch" />;
257 function PlayerInfo(props) {
258 if (! props.player.id)
261 const choices = <TeamChoices
263 first_move={props.first_move}
264 player={props.player}
268 <div className="player-info">
269 <span className="players-header">Players: </span>
271 {props.player.team ? ` (${props.player.team})` : ""}
272 {props.first_move ? "" : " "}
274 {props.other_players.map(other => (
275 <span key={other.id}>
278 {other.team ? ` (${other.team})` : ""}
285 function Glyph(props) {
287 const glyph_dots = [];
290 for (let i = 0; i < 9; i++) {
291 if (props.squares[i])
295 const height = Math.floor(20 * (Math.floor(last_square / 3) + 1));
297 const viewbox=`0 0 60 ${height}`;
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;
316 return (<div className="glyph-and-name">
318 <div className="glyph">
319 <svg viewBox={viewbox}>
329 function Square(props) {
330 let className = "square";
332 if (props.value.symbol) {
333 className += " occupied";
334 } else if (props.active) {
335 className += " open";
338 if (props.value.glyph) {
339 if (props.value.symbol === '+')
340 className += " glyph-plus";
342 className += " glyph-o";
345 if (props.last_move) {
346 className += " last-move";
349 const onClick = props.active ? props.onClick : null;
352 <div className={className}
359 function MiniGrid(props) {
360 function grid_square(j) {
361 const value = props.squares[j];
362 const last_move = props.last_moves.includes(j);
364 /* Even if the grid is active, the square is only active if
366 const square_active = (props.active && (value.symbol === null));
371 active={square_active}
372 last_move={last_move}
373 onClick={() => props.onClick(j)}
378 /* Even if my parent thinks I'm active because of the last move, I
379 * might not _really_ be active if I'm full. */
381 props.squares.forEach(element => {
386 let class_name = "mini-grid";
387 if (props.active && occupied < 9)
388 class_name += " active";
391 <div className={class_name}>
405 class Board extends React.Component {
407 /* This mini grid is active only if both:
409 * 1. It is our turn (this.props.active === true)
411 * 2. One of the following conditions is met:
413 * a. This is this players first turn (last_two_moves[0] === null)
414 * b. This mini grid corresponds to this players last turn
415 * c. The mini grid that corresponds to the players last turn is full
417 let grid_active = false;
418 if (this.props.active) {
420 if (this.props.last_two_moves.length > 1) {
421 /* First index (0) gives us our last move, (that is, of the
422 * last two moves, it's the first one, so two moves ago).
424 * Second index (1) gives us the second number from that move,
425 * (that is, the index within the mini-grid that we last
428 const target = this.props.last_two_moves[0][1];
430 this.props.mini_grids[target].squares.forEach(element => {
434 /* If the target mini-grid isn't full then this grid is
435 * only active if it is that target. */
437 grid_active = (i === target);
441 /* We want to highlight each of the last two moves (both "+" and
442 * "o"). So we filter the last two moves that have a first index
443 * that matches this mini_grid and pass down their second index
446 const last_moves = this.props.last_two_moves.filter(move => move[0] === i)
447 .map(move => move[1]);
449 const squares = this.props.mini_grids[i].squares;
454 last_moves={last_moves}
455 onClick={(j) => this.props.onClick(i,j)}
462 <div className="board-container">
463 <div className="board">
479 function fetch_method_json(method, api = '', data = {}) {
480 const response = fetch(api, {
483 'Content-Type': 'application/json'
485 body: JSON.stringify(data)
490 function fetch_post_json(api = '', data = {}) {
491 return fetch_method_json('POST', api, data);
494 async function fetch_put_json(api = '', data = {}) {
495 return fetch_method_json('PUT', api, data);
498 class Game extends React.Component {
505 mini_grids: [...Array(9)].map(() => ({
509 squares: Array(9).fill({
519 set_game_info(info) {
525 set_player_info(info) {
531 set_other_player_info(info) {
532 const other_players_copy = [...this.state.other_players];
533 const idx = other_players_copy.findIndex(o => o.id === info.id);
535 other_players_copy[idx] = info;
537 other_players_copy.push(info);
540 other_players: other_players_copy
550 find_connected_recursive(recursion_state, position) {
552 if (position < 0 || position >= 9)
555 if (recursion_state.visited[position])
558 recursion_state.visited[position] = true;
560 if (recursion_state.mini_grid[position].symbol !== recursion_state.target)
563 recursion_state.connected[position] = true;
566 if (position % 3 !== 0)
567 this.find_connected_recursive(recursion_state, position - 1);
569 if (position % 3 !== 2)
570 this.find_connected_recursive(recursion_state, position + 1);
572 this.find_connected_recursive(recursion_state, position - 3);
574 this.find_connected_recursive(recursion_state, position + 3);
577 /* Find all cells within a mini-grid that are 4-way connected to the
579 find_connected(mini_grid, position) {
580 const connected = Array(9).fill(false);
582 /* If the given cell is empty then there is nothing connected. */
583 if (mini_grid[position] === null)
586 const cell = mini_grid[position].symbol;
588 let recursion_state = {
589 mini_grid: mini_grid,
590 connected: connected,
591 visited: Array(9).fill(false),
594 this.find_connected_recursive(recursion_state, position);
599 /* Determine whether a connected group of cells is a glyph.
601 * Here, 'connected' is a length-9 array of Booleans, true
602 * for the connected cells in a mini-grid.
604 is_glyph(connected) {
606 /* Now that we have a set of connected cells, let's collect some
607 * stats on them, (width, height, number of cells, configuration
608 * of corner cells, etc.).
616 for (let i = 0; i < 9; i++) {
617 const row = Math.floor(i/3);
625 min_row = Math.min(row, min_row);
626 min_col = Math.min(col, min_col);
627 max_row = Math.max(row, max_row);
628 max_col = Math.max(col, max_col);
631 const width = max_col - min_col + 1;
632 const height = max_row - min_row + 1;
634 /* Corners, (top-left, top-right, bottom-left, and bottom-right) */
635 const tl = connected[3 * min_row + min_col];
636 const tr = connected[3 * min_row + max_col];
637 const bl = connected[3 * max_row + min_col];
638 const br = connected[3 * max_row + max_col];
640 const count_true = (acc, val) => acc + (val ? 1 : 0);
641 const corners_count = [tl, tr, bl, br].reduce(count_true, 0);
642 const top_corners_count = [tl, tr].reduce(count_true, 0);
643 const bottom_corners_count = [bl, br].reduce(count_true, 0);
644 const left_corners_count = [tl, bl].reduce(count_true, 0);
645 const right_corners_count = [tr, br].reduce(count_true, 0);
647 let two_corners_in_a_line = false;
648 if (top_corners_count === 2 ||
649 bottom_corners_count === 2 ||
650 left_corners_count === 2 ||
651 right_corners_count === 2)
653 two_corners_in_a_line = true;
656 let zero_corners_in_a_line = false;
657 if (top_corners_count === 0 ||
658 bottom_corners_count === 0 ||
659 left_corners_count === 0 ||
660 right_corners_count === 0)
662 zero_corners_in_a_line = true;
665 /* Now we have the information we need to determine glyphs. */
675 return (width === 3 || height === 3);
677 /* Pipe, Squat-T, and 4-block, but not Tetris S */
678 return two_corners_in_a_line;
680 if (width !== 3 || height !== 3 || ! connected[4])
682 /* Pentomino P and U are not glyphs (not 3x3) */
683 /* Pentomino V is not a glyph (center not connected) */
686 else if (corners_count === 0 || two_corners_in_a_line)
688 /* Pentomino X is glyph Cross (no corners) */
689 /* Pentomino T is glyph T (has a row or column with 2 corners) */
692 /* The corner counting above excludes pentomino F, W, and Z
693 * which are not glyphs. */
698 /* 6-Block has width or height of 2. */
699 /* Bomber, Chair, and J have 3 corners occupied. */
700 if (width === 2 || height === 2 || corners_count === 3)
704 /* Earring and U have no center square occupied */
705 /* H has 4 corners occupied */
706 /* House has a row or column with 0 corners occupied */
707 if ((! connected[4]) || corners_count === 4 || zero_corners_in_a_line)
712 if (corners_count === 4)
719 /* Should be unreachable */
724 const mini_grid_index = move[0];
725 const position = move[1];
727 /* Don't allow any moves after the board is full */
728 if (this.state.moves.length === 81) {
732 /* Set the team's symbol into the board state. */
733 const symbol = team_symbol(this.state.next_to_play);
734 const new_mini_grids = this.state.mini_grids.map(obj => {
735 const new_obj = {...obj};
736 new_obj.squares = obj.squares.slice();
739 new_mini_grids[mini_grid_index].squares[position] = {
744 /* With the symbol added to the squares, we need to see if this
745 * newly-placed move forms a glyph or not. */
746 const connected = this.find_connected(
747 new_mini_grids[mini_grid_index].squares, position);
748 const is_glyph = this.is_glyph(connected);
750 for (let i = 0; i < 9; i++) {
752 new_mini_grids[mini_grid_index].squares[i].glyph = is_glyph;
755 /* And append the move to the list of moves. */
756 const new_moves = [...this.state.moves, move];
758 /* Finally, compute the next player to move. */
760 if (this.state.next_to_play === "+")
765 /* And shove all those state modifications toward React. */
767 mini_grids: new_mini_grids,
769 next_to_play: next_to_play
773 async handle_click(i, j, first_move) {
778 move.assert_first_move = true;
780 const response = await fetch_post_json("move", move);
781 if (response.status == 200) {
782 const result = await response.json();
784 add_message("danger", result.message);
786 add_message("danger", `Error occurred sending move`);
791 fetch_put_json("player", {team: team});
795 const state = this.state;
796 const first_move = state.moves.length === 0;
797 const my_team = state.player_info.team;
801 if (this.state.moves.length === 81)
803 status = "Game over";
804 board_active = false;
808 if (state.other_players.length == 0) {
809 status = "You can move or wait for another player to join.";
812 if (state.other_players.length == 1) {
813 qualifier = "Either";
817 status = `${qualifier} player can make the first move.`;
821 else if (my_team === "")
823 status = "You're just watching the game.";
824 board_active = false;
826 else if (my_team === state.next_to_play)
828 status = "Your turn. Make a move.";
833 status = "Waiting for another player to ";
834 if (state.other_players.length == 0) {
839 board_active = false;
845 id={state.game_info.id}
846 url={state.game_info.url}
851 first_move={first_move}
852 player={state.player_info}
853 other_players={state.other_players}
855 <div key="game" className="game">
857 <div className="game-board">
859 active={board_active}
860 mini_grids={state.mini_grids}
861 last_two_moves={state.moves.slice(-2)}
862 onClick={(i,j) => this.handle_click(i, j, first_move)}
866 <div key="glyphs" className="glyphs">
868 scribe_glyphs.map(glyph => {
873 squares={glyph.squares}
883 ReactDOM.render(<Game
884 ref={(me) => window.game = me}
885 />, document.getElementById("scribe"));