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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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='interface'></div>

              
            
!

CSS

              
                $p: 10px
$rows: 10
$cols: $rows

.space
  padding: $p
  margin: $p

.round
  border-radius: $p/2
  border: none

*, h1, h2
  font-family: avenir
  text-align: center
  font-weight: bold

html
  background: navy
  height: 100vh
  padding: 0
  margin: 0
  box-sizing: border-box
  
body
  // @extend .space
  height: 100vh
  padding: 0
  margin: 0
  box-sizing: border-box
  background: navy /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, maroon, navy) /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, maroon, navy) /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, maroon, navy) /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, maroon, navy) /* Standard syntax */
  
#interface
  @extend .space, .round
  color: whitesmoke
  margin: 0
  width: 100%
  display: flex
  justify-content: center

#grid
  display: grid
  grid-template-columns: repeat(10, 1fr)
  gap: 0 2px
  height: $p * $rows * 1.7
  width: $p * $cols * 1.5

// .chrome
//   width: $p * $cols * 1.5

// .not-chrome
//   width: $p * $cols * 1.7

#grid-border
  @extend .space, .round
  background: black
  text-align: center
  display: flex
  justify-content: center

.cell
  border: 0.1px solid white
  width: $p * 1.5
  height: $p * 1.5
  margin: 0
  padding: 0
  // float: left

.on
  background: black

.off
  background: whitesmoke

#controls
  @extend .space, .round
  background: whitesmoke
  text-align: center

#run, #stop, #seed, #clear
  @extend .space, .round
  background: black
  color: white

#gofullpage
  color: goldenrod
              
            
!

JS

              
                let browser = navigator.userAgent.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i)[1].toLowerCase();
let browserStyle = (browser == 'chrome') ? browser : 'not-chrome';

let numRows = 10;

// individual Cell component
class Cell extends React.Component {

  // need arrow function to refer to the right "this" for props
  // but an arrow function in codepen needs ";" after it
  clickedCell = () => {
    this.props.clickedCell(this.props.row, this.props.col);
    // this.props.runStart(); // auto-run if user edits
  };

render() {
  return (
    <button 
      id={this.props.cellID}
      className={this.props.cellState + ' cell w3-hover-grey w3-hover-shadow w3-ripple'}
      onClick={this.clickedCell}>
    </button>
  );
}

}



// cell Grid component
class Grid extends React.Component {

  render() {
    // this.props are passed down from parent component
    let rows = this.props.rows;
    let cols = this.props.cols;
    let cellState = "";
    let cells = [];
    // create cells
    for (var i=0; i<rows; i++) {
      for (var j=0; j<cols; j++) {
        let cellID = i + ' ' + j;
        cellState = this.props.grid[i][j] ? "on" : "off";
        cells.push(
          <Cell 
            id={cellID}
            cellState={cellState} 
            row={i} col={j} 
            clickedCell={this.props.clickedCell}
            runStart={this.props.runStart}
            />
        );
      }
    }
    // finally render cells
    return (
      <div id='grid-border'>
        <div id='grid' className={browserStyle}>
          {cells}
        </div>
      </div>
    );
  }

}



// run/stop/seed/clear Controls component
class Controls extends React.Component {

  render() {
    return (
      <div id='controls'>
        <button id='run' 
          className='w3-card w3-hover-green w3-hover-shadow w3-ripple' 
          onClick={this.props.runStart}>Run</button>
        <button id='stop' 
          className='w3-card w3-hover-red w3-hover-shadow w3-ripple' 
          onClick={this.props.stop}>Stop</button>
        <button id='seed' 
          className='w3-card w3-hover-teal w3-hover-shadow w3-ripple' 
          onClick={this.props.seed}>Seed</button>
        <button id='clear' 
          className='w3-card w3-hover-yellow w3-hover-shadow w3-ripple' 
          onClick={this.props.clear}>Clear</button>
      </div>
    );
  }

}



// main Interface component
class Interface extends React.Component {

  constructor() {
    super();
    // no need to use this.state = {...} b/c row/col don't change
    this.rows = numRows;
    this.cols = this.rows;
    // state = "my properties" ; props = "properties passed down to me"
    this.state = {
      generation: 0,
      // 2d array of booleans:
      grid: initializeArray(this.rows, this.cols)
    };
  }

  clickedCell = (row, col) => { // arrow functions preserve "this" context
    // create deep copy
    let gridCopy = deepCopyArray(this.state.grid);
    // change cell state
    gridCopy[row][col] = !gridCopy[row][col];
    // update the part(s) of this.state that change
    this.setState({
      grid: gridCopy
    });
  };

seed = () => { // arrow functions preserve "this" context
  let r = this.rows;
  let c = this.cols;
  let gridNext = deepCopyArray(this.state.grid);
  // calculate the future state
  for (var i=0; i<r; i++) {
    for (var j=0; j<c; j++) {
      gridNext[i][j] = (Math.round(Math.random()*2) === 1);
    }
  }
  // update state
  this.setState({
    grid: gridNext
  });
  say('seed planted');
};

clear = () => { // arrow functions preserve "this" context
  // stop timer
  clearInterval(this.timer);
  // create empty array
  let r = this.rows;
  let c = this.cols;
  let gridClear = initializeArray(r,c);
  // update grid and generations
  this.setState({
    grid: gridClear,
    generation: 0
  });
  say('cleared grid');
};

stop = () => { // arrow functions preserve "this" context
  clearInterval(this.timer);
  say('stopped simulation');
};

runStart = () => { // arrow functions preserve "this" context
  say('running simulation');
  // button clicks to start timer repeatedly calling run()
  clearInterval(this.timer);
  this.timer = setInterval(() => this.run(), 200);
};

run = () => { // arrow functions preserve "this" context
  // setup rough stagnation check
  let stagnating = true;
  // reset in case already stopped and pressed run again
  if (String(this.state.generation).includes('stop')) {
    this.state.generation = 0;
  }
  // setup for loop
  let r = this.rows;
  let c = this.cols;
  // create deep copy
  let g = this.state.grid;
  // initialize the future state
  let gridNext = deepCopyArray(this.state.grid);
  // calculate the future state
  for (var i=0; i<r; i++) {
    for (var j=0; j<c; j++) {
      let sum = 0;
      // left side
      if (i>0 && j>0 && g[i-1][j-1]) sum++;
      if (i>0 && g[i-1][j]) sum++;
      if (i>0 && j<c-1 && g[i-1][j+1]) sum++;
      // upda and down
      if (j>0 && g[i][j-1]) sum++;
      if (j<c-1 && g[i][j+1]) sum++;
      // right side
      if (i<r-1 && j>0 && g[i+1][j-1]) sum++;
      if (i<r-1 && g[i+1][j]) sum++;
      if (i<r-1 && j<c-1 && g[i+1][j+1]) sum++;
      // check sum and past state --> future state
      if (g[i][j] && (sum < 2 || sum > 3)) {
        gridNext[i][j] = false;
        stagnating = false;
      }
      if (!g[i][j] && sum === 3) {
        gridNext[i][j] = true;
        stagnating = false;
      }
    }
  }
  // stop running generations if detected stagnation
  let nextGen = this.state.generation + 1;
  if (stagnating) {
    clearInterval(this.timer);
    nextGen = this.state.generation + 1 + ' - stopped changing';
    say('simulation paused; stability detected');
  }
  // update state
  this.setState({
    grid: gridNext,
    generation: nextGen
  });
};

componentDidMount() { // right when component finished loading
  this.seed();
  this.runStart();
  _showRedirectLinkAsNeeded('boRvYg');
}

render() {
  return (
    <div>
      <p id='gofullpage'></p>
      <h1>Conway's Game of Life</h1>
      <h2>Generations: {this.state.generation}</h2>
      <Controls 
        runStart={this.runStart} 
        stop={this.stop} 
        seed={this.seed} 
        clear={this.clear} 
        />
      <Grid 
        grid={this.state.grid} 
        rows={this.rows} 
        cols={this.cols} 
        clickedCell={this.clickedCell} 
        runStart={this.runStart}
        />
      <p>More Info: <a href="https://en.wikipedia.org/wiki/Conway's_Game_of_Life" target='_blank'>en.wikipedia.org/wiki/Conway's_Game_of_Life</a></p>
    </div>
  );
}

}


// where React actually renders all components:
// (need here below the components)
ReactDOM.render(
  <Interface/>,
  document.getElementById('interface')
);


// convenience functions:

function deepCopyArray(array) { // as opposed to passing reference
  return JSON.parse(JSON.stringify(array));
}

function initializeArray(rows, cols) { // note bug if used for seed()
  return Array(rows).fill(Array(cols).fill(false));
}

function say(what) {
  responsiveVoice.speak(what, 'UK English Male');
}

              
            
!
999px

Console