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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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 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.

HTML

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

CSS

              
                light-gray = #b3b3b3
med-gray = #666
dark-gray = #222223
pink = #F21368

html
  font-size: 10px
  font-family: Helvetica, sans-serif
  background-color: dark-gray //#f2f2f2
  height: 100%


body
  display: flex
  justify-content: center
  align-items: center
  height: 100%
  color: dark-brown
  
h1
  font-size: 7vw
  line-height: 2rem
  font-weight: 600
  
@media screen and (min-width: 555px) 
  h1
    font-size: 4rem
    line-height: 3rem
  
a
  display: block
  line-height: inherit
  color: inherit
  text-decoration: none
  border-bottom: 6px solid pink
  
.wrapper
  padding: 24px
  background: white
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.8)

.stats
  display: flex
  justify-content: space-between
  font-size: 1.5rem
  line-height: 3rem
  flex-wrap: wrap
  &__header
    font-weight: 600
  p
    margin-right: 1em
    flex: 0 0 auto
  
.board
  border: 1px solid light-gray
  flex: 0 0 auto;
  
.row
  height: 10px
  display: block
  margin: 0
  padding: 0
  border-bottom: 1px solid light-gray
  &:last-child
    border-bottom: none

.cell
  display: inline-block
  width: 10px
  height: 10px
  border-right: 1px solid light-gray
  &.alive 
    background-color: tomato
  &:last-child
    border-right: none
   
 .buttons
   display: flex
   align-content: space-between
   margin: 0 0 8px 0
   
 .button
   flex: 1 1 auto
   margin: 0 4px 0 0;
   position: relative
   cursor: pointer
   background-color: transparent
   padding: 6px 14px
   border: 1px solid light-gray
   color: med-gray
   transition: all 0.5s
   z-index: 2
   &:last-child 
     margin: 0
   &:disabled
     pointer-events: none
     color: light-gray
   &:after
       content: ''
       background-color: pink
       width: 0
       height: 100%
       position: absolute
       top: 0
       left: 0
       transition: all 0.2s
       z-index: -1
   &:hover 
     color: white
     &:after
       width: 100%
       
.graph
  height: 30px
  
.bars
  rect
    fill: pink
              
            
!

JS

              
                const { Component } = React;
const { render } = ReactDOM;

class Cell extends Component {
  constructor(props) {
    super(props);
  }
  
  shouldComponentUpdate(nextProps, nextState) {
    if(nextProps.color !== this.props.color) return true;
    return false;
  }
  
  render() {
    const { status, color, pos, onClick } = this.props;
    return (
      <div 
        className={`cell pos-${pos}`}
        onClick={() => onClick(pos)}
        style={{ backgroundColor: color }} />
    );
  }
}

class Grid {
  constructor({ height, width }) {
    this.cells = {};
    const regEx = new RegExp(`-|^${width}\\b|\\b${height}$`)

    for(let y = 0; y < height; y++) {
      for(let x = 0; x < width; x++) {
        const pos = `${x},${y}`;
        
        this.cells[pos] = {
          pos,
          status: Math.random() > 0.5 ? 1 : 0,
          age: 0,
          neighbors: [
            `${x-1},${y-1}`,
            `${x},${y-1}`,
            `${x+1},${y-1}`,
            `${x-1},${y}`,
            `${x+1},${y}`,
            `${x-1},${y+1}`,
            `${x},${y+1}`,
            `${x+1},${y+1}`
          ].filter(pos => {
            return !regEx.test(pos)
          })
        };
      }
    }
  }
  
  getNextStatus(cell) {
    const status = cell.status;
    const neighbors = cell.neighbors.map(id => this.cells[id]);
    const aliveNeighbors = neighbors.filter(cell => cell.status === 1);
    
    if(status === 1) {
      if(aliveNeighbors.length < 2 || aliveNeighbors.length > 3)  return 0; // die from under population or over population
      return 1;
    } else {
      if(aliveNeighbors.length === 3) return 1; // is born
      return 0;
    }
  }
  
  nextTick() {
    for(let id in this.cells) {
      let cell = this.cells[id];
      const nextStatus = this.getNextStatus(cell);
      const age = nextStatus === 1 ? cell.age + 1 : 0;
      Object.assign(cell, { nextStatus, age });
    }
    
    for(let id in this.cells) {
      let cell = this.cells[id];
      Object.assign(cell, { status: cell.nextStatus, nextStatus: null });
    }
  }
  
  reset() {
    for(let id in this.cells) {
      const cell = this.cells[id];
      Object.assign(cell, { status: 0, age: 0 });
    }
  }

  getCellsArray() {
    return Object.keys(this.cells).map(id => this.cells[id])
  }
}

const Board = ({ width, height, cells, onCellClick }) => {
  const rows = [];
  const Cells = cells.map(cell => {
    const pos = cell.pos.split(',');
    const x = +pos[0];
    const y = +pos[1];
    const saturation = Math.min(100, cell.age);
    const color = cell.status === 1 ? `hsl(${(x / width) * 360}, ${saturation}%, 50%)` : '#f2f2f2' ;
    return (
      <Cell 
        key={cell.pos} 
        {...cell} 
        onClick={onCellClick}
        color={color} />
    );
  });
  for(let i = 0; i < height; i++) {
    const start = i * width;
    const end = start + width;
    rows.push(
      <div className="row" key={`row${i}`}>
        {Cells.slice(start, end)}
      </div>
    );
  }
  return (
    <div className="board">
      {rows}
    </div>
  )
}

const Button = ({ text, ...props }) => (
  <button className="button" {...props}>{text}</button>
);

const Bar = (props) => (
  <g className="bars">
    <rect {...props} />
  </g>
);

const Graph = ({ width, height, max, data }) => {
  const viewBoxSize = 1000;
  return (
    <svg className="graph" style={{ width }}>
      <svg viewBox={`0 0 ${viewBoxSize} ${viewBoxSize}`} preserveAspectRatio="none">
        {data.map((num, index) => {
          const barHeight = viewBoxSize * (num / max);
          const barWidth = viewBoxSize/100;
          return (
            <Bar 
              height={barHeight}
              width={barWidth} 
              x={index * barWidth} 
              y={viewBoxSize - barHeight} />
          );
        })}
      </svg>
    </svg>
  );
}

class App extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      width: 0,
      height: 0,
      cells: [],
      speed: 100,
      generations: 0,
      gameStarted: false,
      numAliveCellStats: []
    };

    this.adjustForScreen = this.adjustForScreen.bind(this);
    this.nextTick = this.nextTick.bind(this);
    this.bringCellToLife = this.bringCellToLife.bind(this);
    this.start = this.start.bind(this);
    this.stop = this.stop.bind(this);
    this.clear = this.clear.bind(this);
  }
  
  componentDidMount() {
    console.log('componentDidMount')
    this.adjustForScreen();
    this.start();
  }
  
  adjustForScreen() {
    console.log('adjustForScreen');
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;
    const MIN_WIDTH = 4;
    const MAX_WIDTH = 50;
    const MIN_HEIGHT = 4;
    const MAX_HEIGHT = 50;
    const WIDTH = Math.min(MAX_WIDTH, Math.floor(((screenWidth / 10) - 12) || MIN_WIDTH));
    const HEIGHT = Math.min(MAX_HEIGHT, Math.floor((screenHeight / 10) - 28) || MIN_HEIGHT);
    console.log(`width: ${WIDTH}, height: ${HEIGHT}`);
    var t0 = performance.now();
    const grid = new Grid({ width: WIDTH, height: HEIGHT });
    var t1 = performance.now();
    console.log(`Time to create grid with ${ HEIGHT * WIDTH } cells: ${(t1 - t0)}ms`);
    this.grid = grid;
    
    this.setState(() => {
      return {
        width: WIDTH,
        height: HEIGHT,
        cells: grid.getCellsArray(),
      };
    })
  }
  
  start() {
     this.timeoutId = window.setTimeout(
      this.nextTick,
      this.state.speed
    );
    this.setState({ gameStarted : true });
  }
  
  stop() {
    window.clearTimeout(this.timeoutId);
    this.setState({ gameStarted : false });
  }
  
  clear() {
    this.stop();
    this.grid.reset();
  }
  
  nextTick() {
    this.grid.nextTick();
    const cells = this.grid.getCellsArray();
    const numAliveCells = cells.filter(cell => cell.status === 1).length;
    const generations = numAliveCells ? this.state.generations + 1 : 0;
    const numAliveCellStats = this.state.numAliveCellStats.concat(numAliveCells).slice(-100);
    this.setState(() => {
      this.timeoutId = window.setTimeout(this.nextTick, this.state.speed);
      return {
        cells,
        generations,
        numAliveCellStats
      };
    });
  }
  
  bringCellToLife(pos) {
    this.grid.cells[pos].status = 1;
    const cells = this.grid.getCellsArray();
    this.setState(() => ({ cells }));
  }
  
  render() {
    const { cells, width, height, generations, numAliveCellStats, gameStarted } = this.state;
    const boardSize = (width * 10) + width;
    const numTotalCells = cells.length;
    const numAliveCells = cells.filter(cell => cell.status === 1).length;
    const oldestCell = cells.length ? cells.reduce((a, b) => a.age > b.age ? a : b) : 'n/a';
    return (
      <div className="wrapper">
        <h1 className="title">
          <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Conway's Game of Life</a>
        </h1>
        
        <div className="stats" style={{ width: boardSize }}>
          <p><span className="stats__header">Generations:</span> {generations}</p>
          <p><span className="stats__header">Population:</span> {numAliveCells}</p>
          <p><span className="stats__header">Oldest cell age:</span> {oldestCell.age}</p>
        </div>
        
        <Graph 
          width={boardSize} 
          height="30" 
          data={numAliveCellStats} 
          max={numTotalCells/2}/>
        
        <div className="buttons">
          <Button text="Start" onClick={this.start} disabled={gameStarted}/>
          <Button text="Stop" onClick={this.stop} disabled={!gameStarted}/>
          <Button text="Clear" onClick={this.clear}/>
        </div>
        
        <Board
          onCellClick={this.bringCellToLife}
          width={width}
          height={height}
          cells={cells}/>
      </div>
    );
  } 
}

render(
  <App/>,
  document.getElementById('root')
);
              
            
!
999px

Console