Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <head>
  <meta charset="UTF-8" />
  <title>Hello React!</title>
</head>
<body>
  <!--div class="container well"-->
    <div id="root"></div>
  <!--/div-->
</body>
            
          
!
            
              body,html,#root
  height: 100%
.squareContainer
  width: 5%
  height: 5%
  border: 1px solid gray
.board  
  display: flex
  flex-wrap: wrap
  width: 80%
  height: 80%  
  margin: auto
.square
  width: 100%
  height: 100%
.black
  background-color: black
.blue
  background-color: blue
.buttonTab
  text-align: center
            
          
!
            
              //Thanks to https://gaearon.github.io/react-dnd/docs-tutorial.html for board template

//All other work by Zeb Girouard

var PropTypes = React.PropTypes;

var rows = 20;
var columns = 20;

var returnAllNeighbors = function(i) {
  var x = i % columns;
  var y = Math.floor(i / columns);  
  var toLeft = (x-1 < 0) ? columns-1 : x-1;
  var toRight = (x+1 === columns) ? 0 : x+1;
  var below = (y+1 === rows) ? 0 : (y+1)*columns;
  var above = (y-1 < 0) ? (rows-1)*columns : (y-1)*columns;
  var currentRow = y*columns;
  var currentColumn = x;
  var topLeft = above + toLeft;
  var top = above + currentColumn;
  var topRight = above + toRight;
  var left = toLeft + currentRow;
  var right = toRight + currentRow;
  var bottomLeft = below + toLeft;
  var bottom = below + currentColumn;
  var bottomRight = below + toRight;
  var allNeighbors = [topLeft, top, topRight, left, right, bottomLeft, bottom, bottomRight]  
  return allNeighbors;
};

var Board = React.createClass({
  getInitialState: function() {
    var squares = [];
    for (let i = 0; i < rows*columns; i++) {
      var alive = Math.random() < 0.5;
      squares.push(this.renderSquare(i,alive));
    }          
    return {squares: squares, isPaused: false, generations: 0};
  },
  componentDidMount: function() {
    var current = this;
    setInterval(function() {
      if (!current.state.isPaused) {
        current.setState({generations: current.state.generations + 1});
        current.setBoard("nextGen")
      }
    }, 500); 
  },
  propTypes: {
    knightPosition: PropTypes.arrayOf(
      PropTypes.number.isRequired
    ).isRequired
  },
  renderSquare: function (i,alive) {
    return (
      <div key={i}
           className="squareContainer">
        <Square alive={alive}>
        </Square>
      </div>
    );
  },
  setBoard: function (type) {
    var squares = [];
    var liveState = []; 
    if (type === "nextGen") {
      var squares = [];
      for (let i = 0; i < rows*columns; i++) {
        var allNeighbors = returnAllNeighbors(i);
        var currentSquareLife = this.state.squares[i].props.children.props.alive;
        // If alive, check if should stay alive or die
        var liveNeighbors = 0;
        for (var j = 0; j< allNeighbors.length; j++) {
          //Neighbor is alive
          var neighbor = allNeighbors[j];
          if (this.state.squares[neighbor].props.children.props.alive) {
            liveNeighbors++;
          }
        }        
        if (currentSquareLife) {
          if (liveNeighbors > 3) {
            squares.push(this.renderSquare(i,false));
          }
          else if (liveNeighbors <= 1) {
            squares.push(this.renderSquare(i,false));
          }
          else {
            squares.push(this.renderSquare(i,true));
          }
        }
        //If dead, check if should be alive next generation
        else {
          if (liveNeighbors === 3) {
            squares.push(this.renderSquare(i,true));
          }
          else {
            squares.push(this.renderSquare(i,false));
          }
        }
      }          
    }
    else if (type === "kill") {
      var alive = false;
      for (let i = 0; i < rows*columns; i++) {
        squares.push(this.renderSquare(i,alive));
      }         
    }  
    this.setState({squares: squares});       
  },
  killAll: function () {
    this.setState({generations: 0});
    this.setBoard("kill");
  },
  pauseGame: function() {
    this.setState({isPaused: true}); 
  },
  resumeGame: function () {
    this.setState({isPaused: false});
  },
  render: function () {
    return (
      <div className="square">
        <nav className="navbar navbar-default">
          <div className="container-fluid">
            <a className="navbar-brand" href="https://codepen.io/ZebGirouard/full/YXbYwb/" target="_blank">Game of Life - Click for More by Zeb Girouard</a>
          </div>
        </nav>
        <div className="buttonTab">
          <button onClick={this.resumeGame}>Play</button>
          <button onClick={this.pauseGame}>Pause</button>
          <button onClick={this.killAll}>Clear</button>
          <p>Generation: {this.state.generations}</p>
        </div>
        <div className="board">
          {this.state.squares}
        </div>
      </div>
    );
  }
});

var Square = React.createClass({
  propTypes: {
    alive: PropTypes.bool
  },
  handleClick: function () {
    this.props.alive = !this.props.alive;
    this.setState({});
  },
  render: function () {
    var alive = this.props.alive;
    var fill = alive ? 'blue' : 'black';

    return (
      <div onClick={this.handleClick} className={"square "+fill}>
        {this.props.children}
      </div>
    );
  }
});

var rootEl = document.getElementById('root');

ReactDOM.render(
  <Board />,
  rootEl
);
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console