Skip to main content
edited tags
Link
200_success
  • 145.6k
  • 22
  • 191
  • 481
Source Link

Conway's Game of Life in React

I have built a version of Conway's Game of Life in React. If you don't know what it is, the Game of Life is a simple algorithm that causes patterns and shapes to appear in a 2D array of cells.

While the app has functionality, I feel that it's performance could be significantly improved upon. I am trying to make it run as efficiently as possible.

Most of the logic is in the GridContainer component. I believe the createGrid() function which is called from componentDidMount() is causing the majority of the performance issues.

Index files which calls the App component:

var React = require('react');
var createReactClass = require('create-react-class');
var ReactDOM = require('react-dom');

// components
var App = require('./components/App.jsx');

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

var React = require('react');
var PropTypes = React.PropTypes;

App component which calls the main GridContainer component:

var React = require('react');
var createReactClass = require('create-react-class');

// components
var GridContainer = require('./GridContainer.jsx');

var App = createReactClass({
  render: function(){
    return(
      <GridContainer dim={51}/>
    );
  }
});

module.exports = App;

GridContainer component which has the state and logic:

var React = require('react');
var createReactClass = require('create-react-class');
var ReactDOM = require('react-dom');
var Row = require('react-bootstrap').Row;
var Col = require('react-bootstrap').Col;
var FontAwesome = require('react-fontawesome');

// components
var Cell = require('./Cell.jsx');
var Grid = require('./Grid.jsx');

var GridContainer = createReactClass({
  getInitialState: function() {
    return {
      matrix: [],
      generations: 0,
      neighborCells: [[0, 1], [1, 0], [-1, 0], [0, -1], [-1, -1], [1, 1], [-1, 1], [1, -1]]
    };
  },

  componentWillMount: function() {
    this.freshGrid();
  },

  freshGrid: function() {
    var matrix = [];
    var dim = this.props.dim;

    var Cell = function() {
      this.neighborsCount = 0;
      this.isAlive = false;
    }

    var counter = 0;
    for (var i = 0; i < dim; i++) {
      var row = [];
      for (var j = 0; j < dim; j++) {
        counter++;
        var cell = new Cell();
        row.push(cell);

        if (counter%2 == 0) {
          cell.isAlive = true;
        }
      }
      matrix.push(row);
    }

    this.setState({matrix: matrix});
  },

  createGrid: function() {
    this.interval = setInterval(function() {
      this.clearNeighborsCount(this.state.matrix);
      var newMatrix = JSON.parse(JSON.stringify(this.state.matrix));
      this.countNeighbours(newMatrix);
      this.updateCells(newMatrix);
      this.setState({matrix: newMatrix});
    }.bind(this), 100)
  },

  countNeighbours: function(newMatrix) {
    var dim = this.props.dim;

    for (var i = 0; i < dim; i++) {
      for (var j = 0; j < dim; j++) {
        this.countNeighboursCell(i, j, newMatrix);
      }
    }
  },

  countNeighboursCell: function(row, col, newMatrix) {
    var neighborCells = this.state.neighborCells;
    var cell = newMatrix[row][col];

    for (var i = 0; i < neighborCells.length; i++) {
      var neighborPos = neighborCells[i];
      var x = row + neighborPos[0];
      var y = col + neighborPos[1];

      if (this.isWithinGrid(x, y)) {
        var neighbor = newMatrix[x][y];
        if (neighbor.isAlive) {
          cell.neighborsCount++;
        }
      }
    }
  },

  isWithinGrid: function(row, col) {
    var dim = this.props.dim;

    if (row >= 0 && col >= 0 && row < dim && col < dim) {
      return true;
    }
    return false;
  },

  updateCells: function(newMatrix) {
    var dim = this.props.dim;

    for (var i = 0; i < dim; i++) {
      for (var j = 0; j < dim; j++) {
        var currentCell = newMatrix[i][j];

        if (currentCell.isAlive && (currentCell.neighborsCount == 2 || currentCell.neighborsCount == 3)) {
          currentCell.isAlive = true;
        } else if (!currentCell.isAlive && currentCell.neighborsCount == 3) {
          currentCell.isAlive = true;
        } else {
          currentCell.isAlive = false;
        }
      }
    }
  },

  clearNeighborsCount: function() {
    var dim = this.props.dim;

    for (var i = 0; i < dim; i++) {
      for (var j = 0; j < dim; j++) {
        this.state.matrix[i][j].neighborsCount = 0;
      }
    }
  },

  togglePause: function(e) {
    if (e.target.innerHTML === 'Pause') {
      clearInterval(this.interval);
      e.target.innerHTML = 'Play';
    } else {
      e.target.innerHTML = 'Pause';
      this.createGrid();
    }
  },

  reset: function() {
    this.freshGrid();
  },

  componentDidMount: function() {
    this.createGrid();
  },

  render: function() {
    var dim = this.props.dim;

    var cells = [];
    for (var i = 0; i < dim; i++) {
      var row = [];
      for (var j = 0; j < dim; j++) {
        row.push(<Cell dim={10} isAlive={this.state.matrix[i][j].isAlive} key={i*dim+j} row={i} col={j} />)
      }
      cells.push(row);
    };

    return (
      <Row>
        <Col xs={12} md={10}>
          <Grid cells={cells} dim={this.props.dim} />
        </Col>
    </Row>
    )
  }
});

module.exports = GridContainer;

Grid component which renders an array of Cell components:

var React = require('react');
var PropTypes = require('prop-types');

var Grid = function(props) {
  var gridStyle = {
    width: props.dim * 10,
    height: props.dim * 10,
    background: "#FAFAFA",
    margin: "0 auto",
    WebKitBoxShadow: "0 0 5px rgba(0, 0, 0, 1)",
    MozBoxShadow: "0 0 5px rgba(0, 0, 0, 1)",
    boxShadow: "0 0 5px rgba(0, 0, 0, 1)"
  };

  return (
    <div style={gridStyle}>
      {props.cells}
    </div>
  )
}

Grid.propTypes = {
  cells: PropTypes.array.isRequired
};

module.exports = Grid;

Individual cell component:

var React = require('react');
var PropTypes = require('prop-types');

var Cell = function(props) {
  var dim = props.dim;

  var cellStyle = {
        width: dim,
        height: dim,
        dislay: "inline-block",
        float: "left",
        border: "1px solid #000",
        background: props.isAlive ? "#FFF" : "#151515"
    }

  return (<div onClick={props.clicked} style={cellStyle}></div>)
};

Cell.propTypes = {
  dim: PropTypes.number.isRequired,
  clicked: PropTypes.func
}

module.exports = Cell;