css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

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.

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.

            
              $primary-color: #536C4C ;
$accent-color: #26486D;
$bg-color: aliceblue;
$blood-color: #A02F3C;
$text-color: white;
$banner1-bg: #0fb8ad;
$banner2-bg: #1fc8db;
$banner3-bg: #2cb5e8;
$alive-cell: #ffa333;


.bannerHead{
   background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(141deg, $banner1-bg 0%, $banner2-bg 51%, $banner3-bg 75% ); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(141deg, $banner1-bg 0%, $banner2-bg 51%, $banner3-bg 75% ); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(141deg, $banner1-bg 0%, $banner2-bg 51%, $banner3-bg 75% ); /* For Firefox 3.6 to 15 */
  background: linear-gradient(141deg, $banner1-bg 0%, $banner2-bg 51%, $banner3-bg 75% ); /* Standard syntax */
  border-radius: 3px;
  padding: 15px;
  font-size: 28px;
  text-align: center;
  color: $text-color;
  width: 98%;
  margin: auto;

}

.cellHolder{
  border: 2px solid $banner1-bg;
  margin: auto;
  width: 618px;
  background-color: silver;
  height: 480px;

}

#gameInfo{
  font-size: 14px;
}

a:link {
  text-decoration: none;
  color: $text-color *.9;
}

a:visited {
  text-decoration: none;
  color: $text-color * .9;
}

a:hover {
  text-decoration: none;
  color: $text-color;
}

body{
  background-color: $bg-color;
  font-family: Tahoma, Geneva, sans-serif;
}

td{
  border: 1px solid silver;
  width: 14px;
  height: 14px;
  background-color: silver * 1.2;
  border-radius: 1px;
}

.alive{
  background-color: $alive-cell;
}

.control_banner{
  margin: auto;
  width: 618px;
  background-color: silver * 1.1;  
  padding: 5px;
  border-radius: 1px;
}

.generations{
  font-size: 20px;
}

            
          
!
            
              const {Component} = React;
const {Provider, connect} = ReactRedux;
const {combineReducers, createStore, bindActionCreators} = Redux;
const {Button} = ReactBootstrap;
const {ButtonToolbar} = ReactBootstrap;
//the initialization below and above accomplish nearly the same thing, but const and let are different. I used let and put this note here mainly as a reminder to myself of the different ways to initialize variables when I go back and look at these notes
let ButtonGroup = ReactBootstrap.ButtonGroup;

const grid_height = 34;
const grid_width = 44;





//FUNCTIONS--------------------------
//this will make the grid for the game, if the grid needs to be empty then false will be passed in for the third parameter and makeGrid pass 0 as the status, otherwise it will randomly generate 0's and 1's which correspond to being dead or alive. this will set the gameboard up with random cells at the beginning
const makeGrid = (height, width, empty) => {
  let grid = [];
  if  (empty==true) {
    for (let i=0;i<height;i++){
      let row = [];
       for (let j=0;j<width;j++){
           row.push({status: 0});
        }
       grid.push(row);
     }
    return grid;
  } else {
    for (let i=0;i<height;i++){
      let row = [];
       for (let j=0;j<width;j++){
         let value = Math.round(Math.random());
           row.push({status: value});
        }
       grid.push(row);
     }
    return grid;
  }
};










//COMPONENTS--------------------------
//these are all 'dumb' components, so they don't care about state
const Header = () => (
  <div className='bannerHead'>
    ReactJS Game of Life
    <br />
    <a id='gameInfo' href='https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life'>Click Here For More Info</a>
  </div>

);


const App = () => (
    <div>
      <Header />
      <br />
         <div className='control_banner'>
           <ControlButtons />
           <GenerationCounter />
         </div>
      <GameBoard />
      <br />
    </div>
);











//CONTAINERS--------------------------
//this creates a table as the gameboard, the cells are created by using the 2d array that was passed into state with the makeGrid function. it must be mapped through twice, and then the index is passed into the changeCell action so it can be used for determining which cell you have clicked on
class Game_Board extends Component{
    componentDidMount(){
      //this starts the board and generation counter
     let timer = setInterval(() => {this.playGame()}, 100);
     this.props.getTimer(timer);
}

    playGame(){
      this.props.nextCell(this.props.board);
      this.props.tickGame();
      //make a different action that will handle applying the 
    }
  
  render(){
  return (
      <div className="cellHolder">
         <table>
           <tbody>
           {this.props.board.map((row,i) => 
               <tr key={i}> 
                 {row.map((column,j) =>
                  <td 
                    key={j}
                    className= {(column.status == 1 ? 'alive' : '')}
                    onClick={() => this.props.changeCell(i,j, column.status)}
                    ></td>
                     )}               
             </tr> )}  
           </tbody>
         </table>
      </div>
    );
  }
}; 

//map state to props is necessary for mapping your data in the store to props that can be accessed in your containers; containers are just 'smart' containers
 const mapStateToProps1 = (state) =>{
  return{
    board: state.board,
    generations: state.generations,
    timer: state.timer
  };
}
 
 //match dispatch to props is needed to get your action creators in your container as props
 function matchDispatchToProps1(dispatch){
  return bindActionCreators({
                              changeCell: changeCell,
                              nextCell: nextCell,
                              tickGame: tickGame,
                              getTimer: getTimer,
                              moveFunction: moveFunction
                            }, dispatch)
}

//connect is used to connect the props and container, this constant is what we will use in our App since this has access to the props
const GameBoard = connect(mapStateToProps1, matchDispatchToProps1)(Game_Board);






class Control_Buttons extends Component{
  
  //this changes the generations to 0 and stops the interval for the ticking
  clearButton(){
    let stopTimer = this.props.timer;
    clearInterval(stopTimer);
    this.props.clearGame(true);
  }
  //this generates a new randomly generated board and stops the iterval for ticking
   randomButton(){
     let stopTimer = this.props.timer;
     clearInterval(stopTimer);
     this.props.randomGame();
  }
  //this starts the ticking for generations, as long as the game is not currently running
  tickTest2(){
    if(this.props.generations.gameOn == false){
          let timer = setInterval(() => {this.playGame()}, 100);
          this.props.getTimer(timer);
    } 
  }
  playGame(){
      this.props.nextCell(this.props.board);
      this.props.tickGame();
  }
  //this pauses the ticking, but doesn't zero out the generations
  pauseButton(){
    let stopTimer = this.props.timer;
    clearInterval(stopTimer);
    this.props.stopGame();
  }
  render(){
    return(
        
          <ButtonToolbar>
            <ButtonGroup>
                <Button bsStyle="info"
                  onClick = {() => this.tickTest2()}
                  >Start</Button> 
                <Button bsStyle="info" 
                  onClick = {() => this.pauseButton()}>Pause</Button>
            </ButtonGroup>
            <ButtonGroup>
                <Button bsStyle="info" 
               onClick = {() => this.randomButton()}
                   >Randomize</Button>
                <Button bsStyle="info" 
                  onClick = {() => this.clearButton()}
                  >Clear</Button>
            </ButtonGroup>
          </ButtonToolbar>
       
    );
  }
};


//for passing in actions as props
 function matchDispatchToProps2(dispatch){
  return bindActionCreators({ 
                              clearGame: clearGame,
                              randomGame: randomGame,
                              stopGame: stopGame,
                              getTimer: getTimer,
                              tickGame: tickGame,
                              stopGame: stopGame,
                              nextCell: nextCell
                            }, dispatch)
}

//for connecting the props to the container
const ControlButtons = connect(mapStateToProps1, matchDispatchToProps2)(Control_Buttons);







class Generation_Counter extends Component{
  // this begins the ticking when the page first loads, eventually this will include the game rules, so the game will start when you first open the page
  componentDidMount(){
    //this.tickTest1();
  }
 
 //this is used to start the generations counter, the timerId needs to be sent to state so it can be used later to stop this counter
  tickTest1(){
      let timer = setInterval(this.props.tickGame, 400);
      this.props.getTimer(timer);
  }
  render(){
    return(
          <div>
            <div className='generations'> Generations: {this.props.generations.generationState}</div>
          </div>
    );
  }
};


const mapStateToProps3 = (state) =>{
  return{
    generations: state.generations
  };
}

 function matchDispatchToProps3(dispatch){
  return bindActionCreators({
                            tickGame: tickGame,
                            getTimer: getTimer
                           }, dispatch)
}

const GenerationCounter = connect(mapStateToProps3, matchDispatchToProps3)(Generation_Counter);













//REDUCERS--------------------------

//this handles changes to the gameboard
const initialGrid = makeGrid(grid_height, grid_width, false);
const gridReducer = (state = initialGrid, action) => {
  switch(action.type){
    case 'CHANGE':
      let newState = state.slice(0);
      console.log("Heres the x " + action.status + " And heres the y " + action.status);
      let cell = newState[action.x][action.y];
      if(cell.status == 0){
        cell.status = 1;       
      }
      else {
        cell.status = 0;
      }
      return newState;
    case 'CLEAR':
      const emptyGrid = makeGrid(grid_height, grid_width, true);
      return emptyGrid;
    case 'RANDOM':
      const randomGrid = makeGrid(grid_height, grid_width, false);
      return randomGrid;
    case 'NEXT_CELL':
      const board = action.board;
      //this counts the live neighbors that around a cell, since a status of 1 is alive and a status of 0 is dead
  function countLiveNeighbors(x, y, boardState){
    let topRow = x-1 < 0 ? grid_height -1 : x-1;
    let bottomRow = x + 1 == grid_height ? 0 : x + 1;
    let leftColumn = y-1 < 0 ? grid_width -1 : y-1;
    let rightColumn = y+1 == grid_width ? 0 : y+1;
    
    let total = 0;
    total += boardState[topRow][leftColumn].status;
    total += boardState[topRow][y].status;
    total += boardState[topRow][rightColumn].status;
    total += boardState[x][leftColumn].status;
    total += boardState[x][rightColumn].status;
    total += boardState[bottomRow][leftColumn].status;
    total += boardState[bottomRow][y].status;
    total += boardState[bottomRow][rightColumn].status;
    return total;   
    
};
      
  //this returns a new status based on the number of live neighbors a cell has
   function updateBoard(x, y, boardState){
    let liveNeighbors = countLiveNeighbors(x,y,boardState);
     //these are the rules for live cells
     if (boardState[x][y].status == 1) {
        if (liveNeighbors < 2){
          return {status: 0};
      } else if (liveNeighbors == 2 || liveNeighbors == 3){
           return {status: 1};
      } else if (liveNeighbors > 3) {
           return {status: 0};
      }
       //these are the rules for dead cells
     } else if (boardState[x][y].status == 0){
         if (liveNeighbors == 3) {
           return {status: 1};
        } else {
          return {status: 0};
        }
     }
  };
    function nextCellGeneration(board){
    let newBoard = [];
    board.map((row, i) => {
      let newRow = [];
        row.map((cell, j) => {
           let updatedCell = updateBoard(i,j,board);
           newRow.push(updatedCell);
        })
      newBoard.push(newRow);
    })
    return newBoard;
  };
      return nextCellGeneration(board);
    default:
      return state;
  }
};


//this is used to collect the setInterval ID, so it can be passed into the clear interval function when the generations need to stop being counted, I need to combine the timer and boardtimer because they will always need to start and stop at the same time, since the generations and board are always tracked together
const timeReducer = (state={}, action) => {
  switch(action.type){
    case 'TIMER':
      let timerId = action.timerId;
      return timerId;
    default:
      return state;
  }
};

//this handles changes to the generations
const initialGenerations = {generationState: 0, gameOn: true}
const generationsReducer = (state = initialGenerations, action) => {
  switch(action.type){
    case 'CLEAR':
      state = {
        generationState: 0, 
        gameOn: false
      };
      return state;
    case 'TICK':
      return {
        generationState: state.generationState +1, 
        gameOn: true
      };
    case 'STOP':
      return {
        generationState: state.generationState, 
        gameOn: false
      };
     case 'RANDOM':
      return {
        generationState: 0, 
        gameOn: false
      };
    default:
      return state;
  }
  
}


//must combine all reducers to pass into Store
const reducers = combineReducers({
  board: gridReducer,
  generations: generationsReducer,
  timer: timeReducer
});










//ACTIONS--------------------------

//this toggles the cell status between dead and alive
const changeCell = (x,y, status) => {
  return{
    type: 'CHANGE',
    x: x,
    y: y,
    status: status
  };
}

const stopGame = () => {
  return {
    type: 'STOP'
  };
}

//this is for clearing the gameboard
const clearGame = () => {
  return{
    type: 'CLEAR'
  };
}

//randomizes the gameboard
const randomGame = () => {
  return{
    type: 'RANDOM'
  };
}

//causes generations to tick
const tickGame = () => {
  return {
    type: 'TICK'
  };
}

//this is used to get the setInterval ID, so it can be passed into clearInterval() and the timer can be stopped later
const getTimer = (x) => {
  return {
    type: 'TIMER',
    timerId: x
  };
}

//this is passed the current gameboard, so that the game rules can be applied to it in the grid reducer
const nextCell = (x) => {
  return {
    type: 'NEXT_CELL',
    board: x
  };
}

const moveFunction = (x) => {
  return {
    type: 'MOVE',
    storedFunction: x
  }
}








//STORE--------------------------


const store = createStore(reducers);

//PROVIDER--------------------------

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>, document.getElementById('app'));
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console