Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h2>Minesweeper React</h2>

<h5>Based on the classic game, <a target="_new" href="http://en.wikipedia.org/wiki/Minesweeper_(video_game)">Minesweeper</a></h5>

<main id="app"></main>
              
            
!

CSS

              
                body, html
{
  padding: 1rem;  
}

#game-container {
  float: left;
  
  border: 1px solid #CCC;
  margin-bottom: 10px;
  padding: 15px;
}

.row
{
  display: flex;
}

.cell {
  width: 35px;
  height: 25px;
  border: 1px solid #CCC;
  padding: 10px 5px 5px 5px;

  background-color: #EEE;

  font-size: 16px;
  text-align: center;
  box-shadow: inset 5px 5px 10px #FFF, inset -3px -3px 5px #777;
  
  cursor: pointer;
  transition-property: background-color, box-shadow;
  transition-duration: 1s;
  transition-timing-function: ease-out;
}

.cell::selection {
  background: transparent;
}
.cell.revealed, .cell.flagged {
  cursor: default;
}
.cell.revealed {
  background-color: #DDD;
  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
}

$cellColors: (
  1: 'blue',
  2: 'green',
  3: 'red',
  4: 'purple',
  5: 'maroon',
  6: 'turquoise',
  7: 'black',
  8: 'white'
);

@each $name, $value in $cellColors {
  .cell.revealed.adj-#{$name} {
    color: #{$value};
  }
}

.cell.revealed.adj-M {
  font-family: "FontAwesome";
  background-color: #FFCCCC;
  
  &:after
  {
    content: '\f1e2';
  }
}

.cell.flagged {
  font-family: "FontAwesome";
  
  &:after
  {
    content: '\f024';
  }
}

.clearfix:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

.status-msg {
  margin-bottom: 10px;
}

label {
  margin-right: 10px;
}

input[type="number"] {
  width: 70px;
  margin-right: 10px;
}

.m10 {
  margin: 10px 0;
}

.small-font
{
  font-size: .85rem;
}

              
            
!

JS

              
                /*
	Minesweeper.js
	Author: Brian Glaz
	
	Desccription:
		React implementation of the classc game, Minesweeper	
*/

class GameContainer extends React.Component {
  constructor() {
    super();

    this.state = {
      grid: [], //will hold an array or cells
      minesFound: 0, //number of mines correctly flagged by user
      falseMines: 0, //number of mines incorrectly flagged
      minesRemaining: 10, //total number of mines - mines flagged
      statusMsg: "Playing...", //game status msg, 'Won','Lost', or 'Playing'
      statusMsgColor: "#000000", //status message font color
      playing: true,
      movesMade: 0, //keep track of the number of moves
      options: {
        rows: 8, //number of rows in the grid
        cols: 8, //number of columns in the grid
        mines: 10 //number of mines in the grid
      },
      userOptions: {
        rows: 8,
        cols: 8,
        mines: 10
      }
    };

    const methodsToBind = [
      "flagCell",
      "revealCell",
      "newGame",
      "validate",
      "handleMinMaxInputBlur",
      "gridToConsole"
    ];

    methodsToBind.forEach(
      methodName => (this[methodName] = this[methodName].bind(this))
    );

    //save initial state
    this.initialState = { ...this.state };

    if (!!localStorage["minesweeper-react"]) {
      this.loadFromLocal();
    } else {
      this.init(true);
    }
  }

  init(constructing = false) {
    const state = this.state,
      grid = Array.from(state.grid);

    //populate the grid with cells
    for (let r = 0; r < state.options["rows"]; r++) {
      grid.push([]);
      for (let c = 0; c < state.options["cols"]; c++) {
        grid[r].push({
          xpos: c,
          ypos: r,
          isMine: false,
          isRevealed: false,
          isFlagged: false,
          value: 0
        });
      }
    }

    //randomly assign mines
    if (state.options.mines > state.options.rows * state.options.cols) {
      state.options.mines = state.options.rows * state.options.cols;
    }

    let assignedMines = 0;
    while (assignedMines < state.options.mines) {
      let ypos = Math.floor(Math.random() * state.options.rows),
        xpos = Math.floor(Math.random() * state.options.cols),
        cell = grid[ypos][xpos];
      //assign and increment if cell is not already a mine
      if (!cell.isMine) {
        cell.isMine = true;
        cell.value = "M";
        assignedMines++;
      }
    }

    //update cell values, check for adjacent mines
    for (let ypos = 0; ypos < state.options["rows"]; ypos++) {
      for (let xpos = 0; xpos < state.options["cols"]; xpos++) {
        //no need to update mines
        if (!grid[ypos][xpos].isMine) {
          let mineCount = 0,
            adjCells = this.getAdjacentCells(xpos, ypos, grid);
          for (let i = adjCells.length; i--; ) {
            if (adjCells[i].isMine) {
              mineCount++;
            }
          }

          grid[ypos][xpos].value = mineCount;
        }
      }
    }
    if (constructing) {
      state.grid = grid;
    } else {
      this.setState({ grid });
    }
  }

  newGame() {
    const state = this.state,
      userOptions = state.userOptions, //grab a copy of user options from inputs
      newState = { ...this.initialState, userOptions, options: userOptions }; //apply user options on top of default options

    newState.minesRemaining = newState.options.mines;
    this.setState(newState, this.init);
  }

  getAdjacentCells(xpos, ypos, grid = []) {
    const state = this.state;
    let results = [];
    for (
      let rowPos = ypos > 0 ? -1 : 0;
      rowPos <= (ypos < state.options.rows - 1 ? 1 : 0);
      rowPos++
    ) {
      for (
        let colPos = xpos > 0 ? -1 : 0;
        colPos <= (xpos < state.options.cols - 1 ? 1 : 0);
        colPos++
      ) {
        results.push(Object.assign({}, grid[ypos + rowPos][xpos + colPos]));
      }
    }
    return results;
  }

  revealCell(xpos, ypos, moveCount = false) {
    const state = this.state,
      grid = Array.from(state.grid);

    let cell = grid[ypos][xpos];

    if (!cell.isRevealed && !cell.isFlagged && state.playing) {
      cell.isRevealed = true;

      //end the game if user clicked a mine
      if (cell.isMine) {
        this.setState({
          statusMsg: "Sorry, you lost!",
          playing: false,
          statusMsgColor: "#EE0000"
        });
      } else if (!cell.isFlagged && cell.value == 0) {
        //if the clicked cell has 0 adjacent mines, we need to recurse to reveal out all adjacent 0 cells
        const adjCells = this.getAdjacentCells(cell.xpos, cell.ypos, grid);
        for (let i = 0, len = adjCells.length; i < len; i++) {
          this.revealCell(adjCells[i].xpos, adjCells[i].ypos, grid);
        }
      }
      if (moveCount) {
        this.setState({ movesMade: state.movesMade + 1 });
      }

      this.setState({ grid });
    }
  }

  flagCell(xpos, ypos, e) {
    e.preventDefault();
    const state = this.state,
      grid = Array.from(state.grid);
    let cell = grid[ypos][xpos];

    if (!cell.isRevealed && state.playing) {
      if (!cell.isFlagged) {
        cell.isFlagged = true;
        this.setState({ minesRemaining: state.minesRemaining - 1 });
        if (cell.isMine) {
          this.setState({ minesFound: state.minesFound + 1 });
        } else {
          this.setState({ falseMines: state.falseMines + 1 });
        }
      } else {
        cell.isFlagged = false;
        this.setState({ minesRemaining: state.minesRemaining + 1 });
        if (cell.isMine) {
          this.setState({ minesFound: state.minesFound - 1 });
        } else {
          this.setState({ falseMines: state.falseMines + 1 });
        }
      }

      this.setState({ grid, movesMade: state.movesMade + 1 });
    }
  }

  validate() {
    const state = this.state;

    if (state.minesFound == state.options.mines && state.falseMines == 0) {
      this.setState({
        statusMsg: "You won!!",
        playing: false,
        statusMsgColor: "#00CC00"
      });
    } else {
      this.setState({
        statusMsg: "Sorry, you lost!",
        playing: false,
        statusMsgColor: "#EE0000"
      });
    }
  }

  handleMinMaxInputBlur(newStateObj = {}) {
    let newState = Object.assign({ ...this.state.userOptions }, newStateObj);
    this.setState({ userOptions: newState });
  }

  gridToConsole() {
    const state = this.state;
    let result = "";
    for (let r = 0, r_len = state.grid.length; r < r_len; r++) {
      for (let c = 0, c_len = state.grid[r].length; c < c_len; c++) {
        result += state.grid[r][c].value + " ";
      }
      result += "\n";
    }
    console.log(result);
  }

  saveToLocal(nextState) {
    const jsonData = JSON.stringify(nextState);
    localStorage["minesweeper-react"] = jsonData;
  }

  loadFromLocal() {
    this.state = JSON.parse(localStorage["minesweeper-react"]);
  }

  componentWillUpdate(nextProps, nextState) {
    this.saveToLocal(nextState);
  }

  render() {
    const state = this.state;

    return (
      <div>
        <section id="game-cotainer" className="clearfix">
          {state.grid.map((row, ypos) => {
            return (
              <div className="row" key={`row-${ypos}`}>
                {row.map((col, xpos) => {
                  const cell = state.grid[ypos][xpos];
                  return (
                    <Cell
                      key={`cell-${xpos}-${ypos}`}
                      value={cell.value}
                      isRevealed={cell.isRevealed}
                      isFlagged={cell.isFlagged}
                      isMine={cell.isMine}
                      xpos={cell.xpos}
                      ypos={cell.ypos}
                      onLeftClick={this.revealCell}
                      onRightClick={this.flagCell}
                    />
                  );
                })}
              </div>
            );
          })}
        </section>

        <div>
          <div className="m10">
            F = Flagged, M = Mine, Left Click to reveal a cell, Right Click to
            flag a cell
          </div>

          <div className="status-msg">
            <strong>Mines Remaining:</strong> {state.minesRemaining}
          </div>

          <div className="status-msg">
            <strong>Moves Made:</strong> {state.movesMade}
          </div>

          <div className="status-msg">
            <strong>Game Status:</strong>{" "}
            <span style={{ color: state.statusMsgColor }}>
              {state.statusMsg}
            </span>
          </div>

          <div className="m10">
            <input type="button" value="Did I win?" onClick={this.validate} />
          </div>

          <div className="m10">
            <label for="new_rows">Rows:</label>
            <MinMaxInput
              stateVal="rows"
              placeholder="rows"
              min="3"
              max="19"
              value={state.userOptions.rows}
              onBlur={this.handleMinMaxInputBlur}
            />
            <label for="new_cols">Cols:</label>
            <MinMaxInput
              stateVal="cols"
              placeholder="cols"
              min="3"
              max="19"
              value={state.userOptions.cols}
              onBlur={this.handleMinMaxInputBlur}
            />
            <label for="new_mines">Mines:</label>
            <MinMaxInput
              stateVal="mines"
              placeholder="mines"
              min="1"
              max={state.userOptions.cols * state.userOptions.rows}
              value={state.userOptions.mines}
              onBlur={this.handleMinMaxInputBlur}
            />
            <div className="small-font">*max size: 19 x 19</div>
            <input
              type="button"
              className="m10"
              value="Create new game!"
              onClick={this.newGame}
            />
          </div>

          <div>
            <input type="button" value="Cheat!" onClick={this.gridToConsole} />
            <div className="small-font">*grid layout printed to JS console</div>
          </div>
        </div>
      </div>
    );
  }
}

//Cell component representing individual cells on the game board
const Cell = props => {
  const {
    value,
    isRevealed,
    isFlagged,
    isMine,
    xpos,
    ypos,
    onLeftClick,
    onRightClick
  } = props;

  const getCssClasses = () => {
    return classNames("cell", `adj-${value}`, {
      revealed: isRevealed,
      flagged: isFlagged
    });
  };

  const handleClick = e => {
    onLeftClick(xpos, ypos, true);
  };

  const handleRightClick = e => {
    onRightClick(xpos, ypos, e);
  };

  return (
    <div
      className={getCssClasses()}
      onClick={handleClick}
      onContextMenu={handleRightClick}
    >
      {isRevealed && !isMine && value !== 0 ? value : ""}
    </div>
  );
};

//Helper input component to validate user inputted options
const MinMaxInput = props => {
  const { min, max, placeholder, stateVal, value, onBlur } = props;

  const handleBlur = e => {
    let val = parseInt(e.target.value);
    if (val < min) {
      val = min;
    } else if (val > max) {
      val = max;
    }

    e.target.value = val;

    let returnObj = {};
    returnObj[stateVal] = val;
    onBlur(returnObj);
  };

  return (
    <input
      type="number"
      placeholder={placeholder}
      defaultValue={value}
      min={min}
      max={max}
      onBlur={handleBlur}
    />
  );
};

ReactDOM.render(<GameContainer />, document.getElementById("app"));

              
            
!
999px

Console