123

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.

            
              0.7<link href="https://fonts.googleapis.com/css?family=Architects+Daughter" rel="stylesheet">
<div id="container"></div>
            
          
!
            
              body {
  background-image: url(http://c2064.in-berlin.de/fcc/leaderboard-bg.jpg);
  background-size: 100%;
  font-family: "Architects Daughter", "Courier New", sans-serif;
}

.main {
  width: 90%;
  max-width: 1184px;
  background-color: rgba(24,84,4,0.4);
  margin: 20px auto;
  border-radius: 20px;
  padding-bottom: 0.1px;
  padding-left: 10px;
  padding-right: 10px;
  
  h1 {
    text-align: center;
    font-size: 4em;
  }
}

.TopPanel {
  width: 90%;
  margin: 0 auto;
  text-align: center;
  padding: 10px;
  
  button {
    margin: 3px;
    width: 120px;
    background-color: rgba(24,84,4,0.7);
    color: white;
    font-family: "Architects Daughter", "Courier New", sans-serif;
  }
  
  .slider-wrapper {
    width: 250px;
    margin-top: 15px;    
    float: left;

    .slider-handle {
      background-image: linear-gradient(rgb(32,71,14) 0px, rgb(42,91,19) 100%);
    }
    
    .slider-value {
      margin-left: 10px;
    }
  }
  
  
  
  .generation {
    width: 250px;
    color: rgb(32,71,14);
    font-size: 30px;
    float: right;
  }
}

.GameBoard.table {
  table-layout: fixed;
  
  td {
    margin: 0;
    padding: 0;
    border: 1px solid darkgreen;
    cursor: pointer;
  }
}

            
          
!
            
              // React/Redux Boilerplate with Reducers and Actions
const BOARD_ROWS = 24,
      BOARD_COLS = 40,
      FIELD_BORNE = 1,
      FIELD_ALIVE = 2,
      FIELD_DYING = 3,
      FIELD_DEAD = 4,
      FIELD_COLORS = [
        null,
        "rgba(32,71,14,0.8)",
        "rgb(32,71,14)",
        "rgba(32,71,14,0.2)",
        "rgba(0,0,0,0)"
      ],
      FIELDS_AROUND = [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]];


// React /////////////////////////////////////////////////////////
const Component = React.Component;

// Redux /////////////////////////////////////////////////////////
const Provider = ReactRedux.Provider;
const connect = ReactRedux.connect;
const createStore = Redux.createStore;
const combineReducers = Redux.combineReducers;
const bindActionCreators = Redux.bindActionCreators;

// TopPanel /////////////////////////////////////////
class TopPanelClass extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      run: false,
      clear: false,
    };
  }  

  onClickRun(e) {
    this.props.runAction(!this.props.gameBoard.running);
  }
  
  onClickClear(e) {
    this.props.clearAction(this.state.clear? 0.15:0);
    this.setState({ clear: !this.state.clear });
  }
  
  render() {
    return (
      <div className="TopPanel">
        <Slider />
        <button
          className="btn btn-default btn-large"
          onClick={(e) => this.onClickRun(e)}>
          {this.props.gameBoard.running?"Pause":"Run"}
        </button>
        <button
          className="btn btn-default btn-large"
          onClick={(e) => this.onClickClear(e)}>
          {this.state.clear?"Random":"Clear"}
        </button>
        <div className="generation"><span>Generation: {this.props.gameBoard.generation}</span></div>
      </div>
    )
  }
}

const TopPanel = connect(
  ({gameBoard}) => { return {gameBoard}; },
  (dispatch) => bindActionCreators({runAction, clearAction}, dispatch)
)(TopPanelClass);


// TopPanel /////////////////////////////////////////
class SliderClass extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      cols: BOARD_COLS,
    };
  }  

  componentDidMount() {
    var slider = $(".slider");
    slider.slider({
      min: 10,
      max: 70,
      step: 1,
      orientation: "horizontal",
      value: this.state.cols,
      tooltip: "show",
      handle: "round",
    }).on('slide', (e) => {
      console.log( "Before getValue" );
      var cols = slider.slider("getValue");
      console.log( "Slide", cols );
      this.setState({ cols: cols });
    }).on('slideStop', (e) => {
      console.log( "Before getValue" );
      var cols = slider.slider("getValue");
      console.log( "SlideStop", cols );
      this.props.setCols(cols);
    });
  }
  
  render() {
    return (
      <div className="slider-wrapper">
        <span className="slider"></span>
        <span className="slider-value">{this.state.cols}</span>
      </div>
    )
  }
}

const Slider = connect(
  null,
  (dispatch) => bindActionCreators({setCols}, dispatch)
)(SliderClass);



// GameBoard /////////////////////////////////////////
class GameBoardClass extends Component {
  constructor(props) {
    super(props);
    
    let ms = 1000 / props.gameBoard.framesPerSec;
    
    this.state = {
      interval: setInterval(() => this.calcNextGeneration(), ms)      
    };
  }
  
  fieldsAround(i,j) {
    let board = this.props.gameBoard.board,
        rows = this.props.gameBoard.rows,
        cols = this.props.gameBoard.cols;
    
    let fields = FIELDS_AROUND.reduce((sum, pos) => {
          if( i+pos[0] < 0 || i+pos[0] >= rows || j+pos[1] < 0 || j+pos[1] >= cols ) return sum;
      
          let field = board[i+pos[0]] && board[i+pos[0]][j+pos[1]];
          return sum + (field === FIELD_BORNE || field === FIELD_ALIVE? 1:0);
          //  
        }, 0);
    return fields;
  }
  
  calcNextGeneration(gameBoard) {
    if( !this.props.gameBoard.running ) return;
    
    this.props.incGeneration();
    
    let currentBoard = this.props.gameBoard.board,
        newBoard = [];
    for( var i=0 ; i<this.props.gameBoard.rows ; i++ ) {
      newBoard.push([]);
      for( var j=0 ; j<this.props.gameBoard.cols ; j++ ) {
        let field = currentBoard[i] && currentBoard[i][j] || FIELD_DEAD;
        
        if( field === FIELD_DYING ) field = FIELD_DEAD;
        if( field === FIELD_BORNE ) field = FIELD_ALIVE;
        
        switch(this.fieldsAround(i,j)) {
          case 0:
          case 1:
          case 4:
          case 5:
          case 6:
          case 7:
          case 8:                                
            if( field === FIELD_ALIVE ) field = FIELD_DYING;
            break;
          case 3:
            if( field === FIELD_DEAD ) field = FIELD_BORNE;
            break;
            break;
        }
        
        newBoard[i].push(field);
      }
    }
    
    this.props.setBoard(newBoard);
  }

  renderRow(row, i) {
    debugger;
    let size = this.props.gameBoard.width / this.props.gameBoard.cols;
    return (
      <tr key={i} style={{ lineHeight: size + "px" }}>
        { row.map((state, j) => <td key={j} width={size}><Field state={state} row={i} col={j}/></td>) } 
      </tr>
    )
  }
  
  render() {
    return (
      <table className="GameBoard table">
        <tbody>
          {this.props.gameBoard.board.map((row, i) => this.renderRow(row, i))}
        </tbody>
      </table>
    )
  }
}

const GameBoard = connect(
  ({gameBoard}) => { return {gameBoard}; },
  (dispatch) => bindActionCreators({setBoard, incGeneration}, dispatch)
)(GameBoardClass);
FIELD_ALIVE


// Field /////////////////////////////////////////
class FieldClass extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
    };
  }
  
  clickOnField(e) {
    this.props.setAction({row: this.props.row, col: this.props.col});
  }

  render() {
    let color = FIELD_COLORS[this.props.state];
    
    return (
      <div 
        className="field"
        width="100%"
        height="100%"
        style={{ backgroundColor: color}}
        onClick={(e) => this.clickOnField(e)}
      >
        <span style={{ opacity: 0}}>.</span>
      </div>
    )
  }
}

const Field = connect(
  ({gameBoard}) => { return {gameBoard}; },
  (dispatch) => bindActionCreators({setAction}, dispatch)
)(FieldClass);

// Redux Reducers /////////////////////////////////////////////////////////

const GameBoardReducer = function(state, action) {  
  if( state === undefined ) {
    let state = { 
      rows: BOARD_ROWS,
      cols: BOARD_COLS,
      width: Math.min( document.body.clientWidth * 0.9, 1184 ),
      board: fillBoard(0.15, BOARD_ROWS, BOARD_COLS),
      running: true,
      framesPerSec: 5,
      generation: 0,
    }
    
    return state;
  }
  
  switch(action.type) {
  case SET_BOARD_ACTION:    
    return { ...state, board: action.payload };
  case RUN_ACTION:
    return { ...state, running: action.payload };
  case CLEAR_ACTION:
    return { ...state, board: fillBoard(action.payload, state.rows, state.cols), generation: 0, running: false };
  case SET_ACTION:
    let pos = action.payload;
    state.board[pos.row][pos.col] = state.board[pos.row][pos.col] === FIELD_DEAD? FIELD_ALIVE: FIELD_DEAD;
    return { ...state }
  case INC_GENERATION:
    return { ...state, generation: state.generation+1 }
  case SET_COLS_ACTION:
    var cols = action.payload,
        rows = parseInt( cols * 0.6 );
    return { ...state, board: fillBoard(0.15, rows, cols), rows: rows, cols: cols, running: false, generation: 0 }
  }

  return state;
}

const fillBoard = function(random, rows, cols) {
  let board = [];
  for( var i=0 ; i<rows ; i++ ) {
    board.push([]);
    for( var j=0 ; j<cols ; j++ ) {
      board[i].push(Math.random()<random? FIELD_ALIVE: FIELD_DEAD);
    }
  }   
  
  return board;
}

const rootReducer = combineReducers({
  gameBoard: GameBoardReducer
});

// Redux Actions ////////////////////////////////////////////////////////////
const RUN_ACTION = "RUN_ACTION";
const PAUSE_ACTION = "PAUSE_ACTION";
const CLEAR_ACTION = "CLEAR_ACTION";
const SET_ACTION = "SET_ACTION";
const SET_BOARD_ACTION = "SET_BOARD_ACTION";
const INC_GENERATION = "INC_GENERATION";
const SET_COLS_ACTION = "SET_COLS_ACTION";

function runAction(run) {
  return {
    type: RUN_ACTION,
    payload: run
  }
}

function clearAction(percentage) {
  return {
    type: CLEAR_ACTION,
    payload: percentage
  }
}

function setAction(pos) {
  return {
    type: SET_ACTION,
    payload: pos
  }
}

function setBoard(board) {
  return {
    type: SET_BOARD_ACTION,
    payload: board
  }
}

function setCols(cols) {
  return {
    type: SET_COLS_ACTION,
    payload: cols
  }
}

function incGeneration() {
  return {
    type: INC_GENERATION
  }
}


// App ///////////////////////////////////////////////////////////////////////
class App extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
    }    
  }
  
  render() {
    return (
      <div className="main">
        <h1>The Game Of Life</h1>
        <TopPanel />
        <GameBoard />
      </div>
    )
  }
}

ReactDOM.render(<Provider store={createStore(rootReducer)}><App /></Provider>, document.getElementById("container"));

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

Console