cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - Activehtmlicon-personicon-teamoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

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.

            
              $gridSize: 40;
$rowSize: 60;
$cellSize: 15px;
$border: 1px solid #EFEFEF;
$background: #CAEBF2;
$alive: #FF3B3F;
$dead: #A9A9A9;
  
* {
  box-sizing: border-box;
}

body {
  background-color: $background;
  width: 100%;
  height: 100%;
  position: relative;
}

#game-container {
  height: auto;
  width: $rowSize * $cellSize + 40px;
  padding: 10px;
  margin: 30px auto;
  background-color: darken($background, 20%);
  border-radius: 4px;
}
#grid {
  width: $rowSize * $cellSize + 2px;
  height: $gridSize * $cellSize + 2px;
  border: $border;
  margin: 15px auto;
  display: block;
  position: relative;
}

.row {
  width: 100%;
  height: $cellSize;
}
.cell {
  width: $cellSize;
  height: $cellSize;
  display: inline-block;
  border: $border;
}
.alive {
  background-color: $alive;
}
.dead {
  background-color: $dead;
}

h1, h4, h5 {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-weight: 300;
  text-align: center;
  margin-bottom: 5px;
}

h5 {
  margin-top: 5px;
}

.menu {
  width: 100%;
  margin: 5px auto 0 auto;
  text-align: center;
  font-family: Helvetica Neue;
  font-weight: 300;
  cursor: pointer;
  
  h3 {
    display: inline-block;
    position: relative;
    font-weight: 300;
    padding: 10px;
    margin: 0;
  }
  button {
    display: inline-block;
    position: relative;
    margin: 0 5px;
    padding: 5px 10px;
    background-color: darken($background, 40%);
    border: none;
    border-radius: 4px;
    &:hover {
      background-color: $background;
    }
  }
  .population {
    background-color: lighten($alive, 20%);
  }
  .active {
    background-color: darken($alive, 20%);
    color: #EFEFEF;
  }
}

#debug {
  position: fixed;
  bottom: 5px;
  left: 5px;
  width: 15px;
  height: 15px;
  content: '';
  border: none;
  background-color: darken($background, 10%);
}
            
          
!
            
              // Components
class BaseComponent extends React.Component {
  _bind(...methods) {
    methods.forEach( (method) => this[method] = this[method].bind(this) );
  }
}

class Cell extends BaseComponent {
  constructor(props) {
    super(props);
    this._bind('handleClick');
  }
  handleClick(e) {
    const target = e.target;
    if (target.className === 'cell dead') {
      // target.className = 'cell alive';
      this.props.onChange('add', e.target.id);
    } else {
      // target.className = 'cell dead';
      this.props.onChange('delete', e.target.id);
    }
  }
  render() {
    const status = this.props.value === 1 ? 'cell alive' : 'cell dead';
    const cellId = `${this.props.row}x${this.props.idx}`;
    return (<div className={status} id={cellId} onClick={this.handleClick}></div>)
  }
}

class Row extends BaseComponent {
  constructor(props) {
    super(props);
    this._bind('handleChange');
  }
  handleChange(type, cell) {
    this.props.onChange(type, cell);
  }
  render() {
    const cells = this.props.cells.map((cell, idx) => <Cell row={this.props.row} value={cell[0]} sum={cell[1]} idx={idx} onChange={this.handleChange} />);
    return (<div className="row">
      {cells}
    </div>);
  }
}
                                     
class Grid extends BaseComponent {
  constructor(props) {
    super(props);
    this._bind('handleChange');
  } 
  handleChange(type, cell) {
    this.props.onChange(type, cell);
  }
  render() {
    const rows = this.props.grid.map((row, idx) => <Row cells={row} row={idx} onChange={this.handleChange}/>);            
    return (<div id="grid">
      {rows}
    </div>)
  }
}

class App extends BaseComponent {
  constructor() {
    super();
    this.state = { 
      grid: [], 
      counter: 0, 
      paused: false, 
      gridSize: 40, 
      rowSize: 60, 
      ratio: 0.7 };
    this._bind(
      'updateState', 
      'buildGrid', 
      'findSums', 
      'applyRules', 
      'start', 
      'stop', 
      'clear', 
      'handleChange', 
      'more', 
      'fewer', 
      'normal', 
      'printout',
    );
  }
  componentWillMount() {
    this.updateState();
  }
  componentDidMount() {
    this.setState({update: false});
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.update === true) {
      return true;
    }
  }
  updateState() {
    let oldGrid = this.state.grid;
    let newGrid = [];
    let counter = this.state.counter;
    let rows = this.state.gridSize;
    let cells = this.state.rowSize;
    if (counter === 0 && oldGrid.length === 0) {
      newGrid = this.buildGrid(oldGrid, rows, cells);
    } else {
      newGrid = this.applyRules(oldGrid);
    }
    newGrid = this.findSums(newGrid);
    counter++;
    this.setState({ grid: newGrid, counter: counter, update: true});
    this.intervalID = requestAnimationFrame(this.updateState);
  }
  buildGrid(grid, rows, cells) {
    for (let  row = 0; row < rows; row++) {
      grid.push([]);
      for (let cell = 0; cell < cells; cell++) {
        const r = Math.random();
        if(r > this.state.ratio) {
          grid[row].push([1]);
        } else {
          grid[row].push([0]);
        }
      }
    }
    return grid;
  }
  findSums(grid) {
    let newGrid = [];
    grid.forEach((row, rIdx) => {
      let newRow = [];
      row.forEach((cell, cIdx) => {
         let newArr = [];
         newArr.push(cell[0]);
         const neighbourhood = [
          [(rIdx - 1),(cIdx - 1)],
          [(rIdx - 1),(cIdx)],
          [(rIdx - 1),(cIdx + 1)],
          [(rIdx),(cIdx-1)],
          [(rIdx),(cIdx)],
          [(rIdx),(cIdx + 1)],
          [(rIdx + 1),(cIdx - 1)],
          [(rIdx + 1),(cIdx)],
          [(rIdx + 1),(cIdx + 1)]
        ];
        let nValues = neighbourhood.map(arr => {
          let x = arr[0]
          let y = arr[1]
          if (x < 0) {
            x = x + this.state.gridSize;
          } else if (x >= this.state.gridSize) {
            x = x - this.state.gridSize;
          }
          if (arr[0] < 0) {
            
          }
          if (arr[0] < 0 || arr[1] < 0 || arr[0] >= this.state.gridSize || arr[1] >= this.state.rowSize) {
            return 0;
          } else {
            return grid[arr[0]][arr[1]][0];
          }
        });
        let sum = nValues.reduce((sumValues ,n) => sumValues + n);
        newArr.push(sum);
        newRow.push(newArr);
      });
      newGrid.push(newRow);
    });
    return newGrid;
  }
  applyRules(grid) {
    let newGrid = []
    grid.map(row => {
      let newRow = [];
      row.map(cell => {
        const value = cell[0];
        const sum = cell[1];
        if (sum === 3) {
          newRow.push([1]);
        } else if (sum === 4) {
          newRow.push([value]);
        } else {
          newRow.push([0]);
        }
      });
      newGrid.push(newRow);
    });
    return newGrid;
  }
  start() {
    this.setState({ paused: false });
    this.intervalID = requestAnimationFrame(this.updateState);
  }
  stop() {
    cancelAnimationFrame(this.intervalID);
    this.setState({paused: true});
  }
  clear() {
    const grid = this.state.grid;
    if (this.state.paused !== false) {
      cancelAnimationFrame(this.intervalID);
      this.setState({ paused: true });
    }
    let newGrid = [];
    grid.map(row => {
      let newRow = [];
      row.map(cell => newRow.push([0]));
      newGrid.push(newRow);
    });
    this._tempGrid = newGrid;
    this.setState({paused: true, counter: 0, grid: newGrid, update: true});
  }
  handleChange(type, cell) {
    let grid = this.state.grid;
    let arr = cell.split('x');
    if (this.state.paused === true && this.state.counter === 0 && this.state.timer === null) {
      if (type === 'add') {
        grid[arr[0]][arr[1]][0] = 1;
      } else if (type === 'delete') {
        grid[arr[0]][arr[1]][0] = 0;
      }
      let newGrid = this.findSums(grid);
      this.setState({grid: newGrid, update: true});
    } else if (this.state.paused === false) {
      alert('You must pause the simulation and clear the board before you can set up your own.');
    } else if (this.state.counter > 0) {
      alert('You must reset the simulation by pressing "Clear" before you can customize the board.');
    }
  }
  more() {
    cancelAnimationFrame(this.intervalID);
    this.clear();
    this.setState({ ratio: 0.5, grid: [], counter: 0, update: true});
    this.start();
  }
  fewer() {
    cancelAnimationFrame(this.intervalID);
    this.clear();
    this.setState({ ratio: 0.9, grid: [], counter: 0, update: true});
    this.start();
  }
  normal() {
    cancelAnimationFrame(this.intervalID);
    this.clear();
    this.setState({ ratio: 0.7, grid: [], counter: 0, update: true});
    this.start();
  }
  printout() {
    console.log(JSON.stringify(this.state));
  }
  render() { 
    const playPause = this.state.paused === true ? <button id="start" onClick={this.start}><i className="fa fa-play"></i></button> :
      <button id="stop" onClick={this.stop}><i className="fa fa-pause"></i></button>;
    return (<div class="container">
      <h1>Conway's Game of Life</h1>
      <h5><a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Click here for an explanation</a></h5>
      <h5>To make your own custom starting state, press clear, click on some squares, and then press Play.</h5>
      <div id="game-container">
        <div className="menu">
          <h3>Generation: {this.state.counter}</h3>
          {playPause}
          <button id="clear" onClick={this.clear}>Clear</button>
        </div><div className="menu">
          <h3 id="restart">Restart with:</h3>
            <button value="0.9" name="population" id="fewer" onClick={this.fewer}>Fewer</button>
          <button value="0.9" name="population" id="fewer" onClick={this.normal}>Normal Amount</button>
          <button value="0.9" name="population" id="fewer" onClick={this.more}>More</button>
        </div>  
        <Grid grid={this.state.grid} onChange={this.handleChange} />
      </div>
        <h4>Coded by <a href="http://lukewalker.org" target="_blank">Luke Walker</a>, to complete <a href="https://www.freecodecamp.com/challenges/build-the-game-of-life" target="_blank">this Free Code Camp project</a>.</h4>
        <button id="debug" onClick={this.printout}></button>
    </div>)
  }
}

ReactDOM.render(<App />, document.querySelector('#app'));


            
          
!
999px
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console