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 class="col-md-10 col-md-offset-1 info">
<h2>info:<small>if you click on the white buttons it will generate an random board with live and false cells.Inside of the java portion, right at the beggining you can manipulate cell size, grid height and width. Enjoy :)</small></h2>
</div>

<div id='app' class='container'>

</div>


              
            
!

CSS

              
                .grid  
  position: relative
  margin: auto
  margin-top: 20px
 
  height: 600px
  width: 500px   
  
  .isAlive
    background-color: red

.cell
  background-color: white
  border-style: solid
  border-width: 1px
  border-color: green


  
              
            
!

JS

              
                let cellSize = 12;
let gridHeight = 15;
let gridWidth = 20;

 class App extends React.Component { 
 
  render() {   
    return(
      <div className="col-md-10">
       <GameManager />   
      </div>
    )
  } 
};
 
class GameManager extends React.Component {  
  constructor(props) {
    super(props);
    this.state= {
      gridSize: [],
      algorithmBoard: [],
      generationCount: 0,
      timing: null,      
      
      divStyle : {
        position: 'absolute',      
        width: cellSize,
        height: cellSize       
      }
    }       
  } 
  //////////////////when click on cell update state //////////////////////////////////////
  sendBoolToGameManager = (posTop, posLeft) => {
    //toggles betwen true and false;
    this.state.algorithmBoard[posTop][posLeft] 
    ?
    this.state.algorithmBoard[posTop][posLeft]   = !this.state.algorithmBoard[posTop][posLeft]   
    :
    this.state.algorithmBoard[posTop][posLeft]   = !this.state.algorithmBoard[posTop][posLeft] 
    
    this.state.gridSize[posTop][posLeft] = <Cell positionBottom={posTop * cellSize} positionLeft={posLeft * cellSize} 
                              sendBoolToGameManager ={this.sendBoolToGameManager} 
                              isAlive={this.state.algorithmBoard[posTop][posLeft]}
                              divStyle={this.state.divStyle}/>;  
    //when we update the state all elements rerender on VirtualDOM, but only those who have changed rerender on the actual DOM
    this.setState({      
      gridSize:  this.state.gridSize,
      algorithmBoard: this.state.algorithmBoard
    })
  };  

  renderGrid = (rows, cols) => {
    let board = [];
    let tempAlgorithmBoard = [];
    // Creates all lines:
    for(var i=0; i < rows; i++){

      // Creates an empty line
      board[i] = [];
      tempAlgorithmBoard[i] = [];

      for(var j=0; j < cols; j++){
        // Initializes the Cells with props
        tempAlgorithmBoard[i][j] = Math.round(Math.random()) === 0 ? true : false;
        board[i][j] = <Cell positionBottom={i*cellSize} positionLeft={j*cellSize}
                        sendBoolToGameManager={this.sendBoolToGameManager}                  
                        isAlive={tempAlgorithmBoard[i][j]}
                        divStyle={this.state.divStyle}/>;
        
      }
    }

    this.setState({
      gridSize: board,
      algorithmBoard: tempAlgorithmBoard
    })    
    
  };  

////////////////////////////////setting the game and algorithm logic////////////////////////////
  nextGrid = () => {  
    
    this.checkNeigbours( this.getLivingNeighbors );
     this.setState({
       generationCount: this.state.generationCount + 1
     })    
  };  

  checkNeigbours = ( magicFunction ) => {
      let board = this.state.algorithmBoard;
      let tempBoard = [];
      for(var i  = 0; i <  board.length; i++){
        tempBoard[i] = [];
        for(var j = 0; j < board[i].length; j++){
          /////////////////////////////THE GAME OF LIFE LOGIC///////////////////////
            let count = magicFunction( i, j, board, board.length, board[i].length);            
            let living = board[i][j];            
            let result = false;
           // Apply the rules and set the next state.
                if (living && count < 2)
                    result = false;
                if (living && (count == 2 || count == 3))
                    result = true;
                if (living && count > 3)
                    result = false;
                if (!living && count == 3)
                    result = true;
          //tre sa updatez boardul de abia dupa ce am terminat totul de examinat
                tempBoard[i][j] = result;
        }
      } 
   
    this.updateBoard(tempBoard, this.state.algorithmBoard, this.state.gridSize)
    };

  getLivingNeighbors = ( row, col, cells, rowSize, colSize) => {
  ///// The first if statement of each pair is simply checking that we're not on the edge of the grid////   
  
     let count = 0;

   // Check cell on the right only if you are not on the right edge of the grid.
   if (col != colSize - 1)
       if (cells[row][col + 1] === true)
           count = count + 1;

   // Check cell on the bottom right only if you are not on the right edge of the grid and on first row.
   if (row != 0 && col !=colSize - 1)
       if (cells[row - 1][col + 1] === true) 
           count++;

   // Check cell on the bottom.
   if (row != 0)
       if (cells[row - 1][col] === true) 
           count++;

   // Check cell on the bottom left.
   if (row != 0 && col != 0)
       if (cells[row - 1][col - 1] === true) 
           count++;

   // Check cell on the left.
   if (col != 0)
       if (cells[row][col - 1] === true) 
           count++;

   // Check cell on the top left.
   if (row != rowSize - 1 && col != 0)
       if (cells[row + 1][col - 1] === true) 
           count++;

   // Check cell on the top.
   if (row != rowSize - 1)
       if (cells[row + 1][col] === true) 
           count++;

   // Check cell on the top right.
   if (row != rowSize - 1 && col != colSize - 1)
       if (cells[row + 1][col + 1] === true) 
           count++;

   return count;
};

  updateBoard = (tempBoard, boolBoard, cellBoard) => {
    boolBoard = tempBoard;
    for(var i in boolBoard) {
      for (var j in boolBoard[i]){        
          cellBoard[i][j] = <Cell positionBottom={i*cellSize} positionLeft={j*cellSize} 
                              sendBoolToGameManager ={this.sendBoolToGameManager} 
                              isAlive={boolBoard[i][j]}
                              divStyle={this.state.divStyle}/>;
      }
    } 
   
   this.setState({
     gridSize: cellBoard,
     algorithmBoard: boolBoard
   })     
  }; 
///////////////////////////////////end algorithm logic////////////////////////////////////
 
 smallBoard = () => {
     this.state.generationCount = 0;  
    this.renderGrid(20,30);
  };
 mediumBoard = () => {
    this.state.generationCount = 0;  
    this.renderGrid(30,50);
  };
 largeBoard = () => {
    this.state.generationCount = 0;  
    this.renderGrid(50,70);
  };

 stopBoard = () => {       
    clearInterval(this.state.timing);
  };

 runBoard = () => {
  clearInterval(this.state.timing);
  this.state.timing = setInterval(this.nextGrid, 100);
};

 clearBoard = () => {
   
  this.state.generationCount = 0;  
  clearInterval(this.state.timing);
  for(var i in this.state.algorithmBoard) {
      for (var j in this.state.algorithmBoard[i]){
          this.state.algorithmBoard[i][j] = false;
          this.state.gridSize[i][j] = <Cell positionBottom={i*cellSize} positionLeft={j*cellSize} 
                              sendBoolToGameManager ={this.sendBoolToGameManager} 
                              isAlive={false}
                              divStyle={this.state.divStyle}/>;
      }
    } 
   
   this.setState({
     gridSize:  this.state.gridSize,
     algorithmBoard: this.state.algorithmBoard
   })     
 
};

 componentWillMount() {
   this.renderGrid( gridHeight, gridWidth );
}

 componentDidMount() {
  this.state.timing = setInterval(this.nextGrid, 100);
}

  render() {    
    return(
      <div className="app">
        <Grid gridSize={this.state.gridSize} /> 
        <div className="row"> 
          <button className='btn btn-default ' onClick={this.smallBoard} >20x30</button>  
          <button className='btn btn-default' onClick={this.mediumBoard}>30x50</button>
          <button className='btn btn-default ' onClick={this.largeBoard}>50x70</button>
        </div>     
        <div className="row"> 
         
          <button className='btn btn-danger' onClick={this.stopBoard}>Pause</button>
          <button className='btn btn-danger' onClick={this.runBoard}>Run</button>
          <button className='btn btn-danger' onClick={this.clearBoard}>Clear</button>
        </div>         
         
        <div>Count = {this.state.generationCount}</div>
      </div>
    )
  }
}

class Grid extends React.Component {  
  
  render() {  
    return(
      <div className="grid">
        {this.props.gridSize}          
      </div>
    )
  }
}

class Cell extends React.Component {

  handleMouseClick = (evn) => {
    
    if( this.props.isAlive){
      //i am sending an message to gameManager and asking it to change the props of this cell
      this.props.sendBoolToGameManager( this.props.positionBottom/cellSize , this.props.positionLeft/cellSize );
    }else{
      
      this.props.sendBoolToGameManager( this.props.positionBottom/cellSize , this.props.positionLeft/cellSize );
    }
 
  };

  render() {
    this.props.divStyle.bottom = this.props.positionBottom;
    this.props.divStyle.left = this.props.positionLeft;    
    
    return(
      <div style={ this.props.divStyle }
        className={ this.props.isAlive ? 'cell isAlive' : 'cell' }        
        onClick={ this.handleMouseClick }
      />      
    )
  }
}


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

              
            
!
999px

Console