Pen Settings

HTML

CSS

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

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

              
                <div id="container"></div>
              
            
!

CSS

              
                body {
  background: -webkit-radial-gradient(center, circle, rgba(0, 150, 150, 1) 20%, rgba(0,0,0,1));
  background: -moz-radial-gradient(center, circle, rgba(0, 150, 150, 1) 20%, rgba(0,0,0,1));
background: -ms-radial-gradient(center, circle, rgba(0, 150, 150, 1) 20%, rgba(0,0,0,1));  
  background: -o-radial-gradient(center, circle, rgba(0, 150, 150, 1) 20%, rgba(0,0,0,1)); 
  background: radial-gradient(center, circle, rgba(0, 150, 150, 1) 20%, rgba(0,0,0,1));
}

#container {
  width: 850px;
  height: 510px;
  margin: 100px auto 40px;
  text-align: center;
}

#game {
  background: black;
  margin: 20px auto 40px;
  position: relative;
  border: 15px solid rgba(50,50,50,1);
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0,0,0,.5), 0 -5px 20px rgba(0,0,0,.3);
}

.top-controls {
  position: relative;
  margin: 0 auto;
  min-width: 300px;
  height: 50px;
  background: rgba(60,60,60,1);
  position: absolute;
  text-align: left;
  padding-bottom: 10px;
  top: -75px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  border-right: 3px solid rgba(50,50,50,1);
  border-left: 3px solid rgba(50,50,50,1);
  border-top: 3px solid rgba(50,50,50,1);
  box-shadow: 0 -5px 20px rgba(0,0,0,.3);
  .control-button {
    background: rgba(20,20,20, 1);
    color: white;
    font-size: 1.1rem;
    position: relative;
    display: inline-block;
    top: 12px;
    left: 10px;
    margin: 0 3px;
    padding: 10px 15px;
    border: 1px solid rgba(0,140,130, 1);
    border-radius: 10px;
    cursor: pointer;
    &:focus {
      outline: 3px solid rgba(0,140,130, 1);
      border-radius: 10px;
    }
  }
  .generations {
    position: relative;
    left: 255px;
    bottom: 20px;
    color: rgba(230, 230, 230, 1);
    font-size: 1.3rem;
  }
}

h3 {
  position: absolute;
}

.person {
  width: 14px;
  height: 14px;
  box-sizing: border-box;
  border: 1px solid rgba(40,40,40,1);
  display: block;
  float: left;
  margin-top: 0;
  margin: 0;
}
.active {
    background: rgba(130, 30, 40, 1);
}

              
            
!

JS

              
                // Handling cloned objects
//http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object

// Optimised by switching to 0 and 1 integers instead of booleans as recommended here:
//https://www.reddit.com/r/algorithms/comments/1etjf4/optimizing_conways_game_of_life/

class TopPanel extends React.Component {

  pauseGame() {
    this.props.pauseGame();
  }

  runGame() {
    if (this.props.aliveCount > 0) {
     this.props.runGame();
    }
  }

  clearBoard() {
    // true for clearSquares
    this.props.clearGame(true);
  }

  render() {
    let panelWidth = {
      width: this.props.width
    };
    return (
      <div
        style={panelWidth}
        className="top-controls"
      >
        <button
          className="control-button"
          onClick={this.runGame.bind(this)}
        >
          Run
        </button>
        <button
          className="control-button"
          onClick={this.pauseGame.bind(this)}
        >
          Pause
        </button>
        <button
          className="control-button"
          onClick={this.clearBoard.bind(this)}
        >
          Clear
        </button>
        <div
          className="generations"
        >
          Generations: {this.props.generations}
        </div>
      </div>
    );
  }
}

class Person extends React.Component {
  clickSquare() {
    this.props.clickSquare(this.props.id);
  }

  render() {
    let aliveColor = this.props.newPerson ? "rgba(0,220,200,1)" : "rgba(0,100,100, 1)";
    let backgroundColor = this.props.isAlive ? aliveColor : 'none';
    let squareStyle = {
      height: this.props.squareSize,
      width: this.props.squareSize,
      background: backgroundColor
    }
    return (
      <span
        onClick={this.clickSquare.bind(this)}
        className={"person"} style={squareStyle}>
      </span>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      people: [],
      squareSize: 14,
      numCols: 50,
      numRows: 30,
      generations: 1,
      aliveStates: null,
      paused: false,
      aliveCount: 0,
      newPeople: []
    };
  }

  componentWillMount() {
    // stores keys of coordinates with alive or dead boolean.
    // example: aliveStates['0,0'] = 1 (true);
    this.resetBoard();
  }

  resetBoard(clearSquares = false) {
    let aliveStates = {}
    let aliveCount = 0;
    let people = [];
    if (clearSquares) {
      this.setState({
        paused: true
      });
    }

    let alive;
    for (let row = 0; row < this.state.numRows; row++) {
      // Make columns
      for (let col = 0; col < this.state.numCols; col++) {
        if (clearSquares) {
          alive = 0;
        }
        else {
          alive = Math.floor(Math.random() * 10) > 6 ? 1 : 0;
          people.push([row, col]);
        }
        if (alive === 1) {
          aliveCount++;
        }
        aliveStates[`${row},${col}`] = alive;
      }
    }

    if (clearSquares) {
      this.setState({
        aliveStates: aliveStates,
        generations: 0,
        aliveCount: 0
      });
    }
    else {
      let squareSize = this.state.squareSize;
      let amount = this.state.numRows * this.state.numCols;
      this.setState({
        people: people,
        aliveStates: aliveStates,
        totalSquares: amount,
        aliveCount: aliveCount
      });
    }
  }

  getNeighbors(currentRow, currentCol) {
    let numCols = this.state.numCols;
    let numRows = this.state.numRows;
    let moveDirections = [
      [-1, -1],
      [-1, 0],
      [-1, 1],
      [0, -1],
      [0, 1],
      [1, -1],
      [1, 0],
      [1, 1]
    ];

    let currentPair = [];
    let neighbors = moveDirections.map(pair => {
      currentPair = [currentRow + pair[0], currentCol + pair[1]];
      if (currentPair[0] < 0) {
        currentPair = [numRows - 1, currentPair[1]];
      }

     else if (currentPair[0] >= numRows) {
        currentPair = [0, currentPair[1]];
      }

      if (currentPair[1] >= numCols) {
        currentPair = [currentPair[0], 0];
      }

      else if (currentPair[1] < 0) {
        currentPair = [currentPair[0], numCols - 1];
      }
      return currentPair;
    });
    return neighbors;
  }

  checkAlive(isAlive,currentRow, currentCol) {
    // returns 2 dimensional array of neighbors
    let neighbors = this.getNeighbors(currentRow, currentCol);

    let livingNeighbors = 0;

    for (var i = 0; i < neighbors.length; i++) {
      if (this.state.aliveStates[`${neighbors[i][0]},${neighbors[i][1]}`] === 1) {
        livingNeighbors += 1;
      }
    }

    if (isAlive === 1) {
      if (livingNeighbors < 2 || livingNeighbors > 3) {
        return 0;
      }
      return 1;
    }

    else {
      // wasn't alive
      if (livingNeighbors === 3) {
        return 1;
      }
      return 0;
    }
  }

  updatePopulation() {
    let people = this.state.people;
    let newPeople = [];
    let aliveCount = 0;
    let aliveStates = JSON.parse(JSON.stringify(this.state.aliveStates));

    for(let i = 0; i < this.state.totalSquares; i++) {
      let currentRow = people[i][0];
      let currentCol = people[i][1];
      let location = `${currentRow},${currentCol}`;
      let wasAlive = aliveStates[location];
      let isAlive = this.checkAlive(wasAlive, currentRow, currentCol);

      if (wasAlive) {
        aliveCount++;
      }

      if (!wasAlive && isAlive) {
        newPeople.push(location);
      }

      aliveStates[location] = isAlive;
    }

    setTimeout(() => {
      if (this.state.paused) {
        return;
      }
      if (aliveCount === 0) {
         this.setState({
          aliveStates: aliveStates,
          generations: 0,
          aliveCount: 0,
          paused: true,
          newPeople: []
        });
        return;
      }

      this.setState({
        aliveStates: aliveStates,
        generations: this.state.generations + 1,
        aliveCount: aliveCount,
        newPeople: newPeople,
        updateQueue: []
      });
    }, 60);
  }

  renderSquares() {
    if (!this.state.paused && this.state.aliveCount > 0) {
     this.updatePopulation();
    }
    if (!this.state.people || this.state.people.length < 1 || !this.state.aliveStates) {
      return null;
    }
    let aliveStates = this.state.aliveStates;
    let newPeople = this.state.newPeople;
    let alive;
    let coords;
    let result = this.state.people.map(location => {
      coords = `${location[0]},${location[1]}`;
      alive = aliveStates[coords];
      let newPerson = newPeople.indexOf(coords) !== -1 ?
          true : false;
      return (
        <Person
          key={coords}
          id={coords}
          squareSize={this.state.squareSize}
          clickSquare={this.clickSquare.bind(this)}
          newPerson={newPerson}
          isAlive={alive}
        />
      );
    });
    return result;
  }
  // Controls
  pauseGame() {
    this.setState({
      paused: true
    });
  }

  runGame() {
    if (this.state.aliveCount > 0) {
      this.setState({
        paused: false
      });
    }
  }

  // Handles updating squares
  clickSquare(location) {
    let aliveStates = JSON.parse(JSON.stringify(this.state.aliveStates));
    let aliveCount = this.state.aliveCount;
    let newPeople = JSON.parse(JSON.stringify(this.state.newPeople));
    let alive = aliveStates[location] === 0 ? 1 : 0;
      aliveStates[location] = alive;
    if (this.state.paused) {
      if (alive) {
        aliveCount++;
        if (newPeople.indexOf(location) === -1) {
          newPeople.push(location);
        }
      }
      else {
        aliveCount--;
      }
      this.setState({
        aliveStates: aliveStates,
        aliveCount: aliveCount,
        newPeople: newPeople
      });
    }
  }

  render() {
    let gameStyles = {
      height: this.state.numRows * this.state.squareSize + 1.5 + 'px',
      width: this.state.numCols * this.state.squareSize + 1.5 + 'px'
    }
    return (
        <div className="game-of-life">
          <div
            id="game"
            style={gameStyles}
          >
            <TopPanel
              width={this.state.numCols * this.state.squareSize * 4 / 6}
              generations={this.state.generations}
              pauseGame={this.pauseGame.bind(this)}
              runGame={this.runGame.bind(this)}
              aliveCount={this.state.aliveCount}
              clearGame={this.resetBoard.bind(this)}
            />
            {this.renderSquares()}
          </div>
      </div>
    );
  }
}

ReactDOM.render(
  <Game />, document.getElementById('container')
);

              
            
!
999px

Console