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.

            
              body {
  margin: 0;
  padding: 0;
  background-color: #E6E7E8;
}
            
          
!
            
              const routeReducers = reducers => (state, action) =>
  reducers[action.type] ? reducers[action.type](state, action) : state;

const CellType = {
  EMPTY: "EMPTY",
  OLD: "OLD",
  NEW: "NEW"
};

const grid = (rows, cols, value) => {
  let cells = [];
  for (let i = 0, j; i < rows; i++) {
    cells[i] = [];
    for (j = 0; j < cols; j++) {
      cells[i][j] = value(i, j);
    }
  }
  return cells;
};

const setCellType = (cellType, cells, position) =>
  cells.map(
    (row, rowIndex) =>
      rowIndex === position.row
        ? row.map(
            (col, colIndex) =>
              colIndex === position.col ? { type: cellType } : col
          )
        : row
  );

const get = (row, col, cells) => {
  const rowLength = cells.length,
    colLength = cells[0].length;
  return cells[(row + rowLength) % rowLength][(col + colLength) % colLength];
};

const aliveNeighbours = (row, col, cells) =>
  [
    get(row - 1, col - 1, cells),
    get(row - 1, col, cells),
    get(row - 1, col + 1, cells),
    get(row, col - 1, cells),
    get(row, col + 1, cells),
    get(row + 1, col - 1, cells),
    get(row + 1, col, cells),
    get(row + 1, col + 1, cells)
  ].filter(cell => cell.type !== CellType.EMPTY).length;

const next = (row, col, cells) => {
  const cell = cells[row][col],
    neighbours = aliveNeighbours(row, col, cells);
  switch (cell.type) {
    case CellType.EMPTY:
      return neighbours === 3 ? { type: CellType.NEW } : cell;
    case CellType.NEW:
    case CellType.OLD:
      return neighbours === 2 || neighbours === 3
        ? { type: CellType.OLD }
        : { type: CellType.EMPTY };
    default:
      return cell;
  }
};

const store = Redux.createStore(
  routeReducers({
    initialize: (state, action) => {
      const cellTypes = [CellType.EMPTY, CellType.NEW, CellType.OLD];
      return {
        cells: grid(50, 50, () => ({
          type: cellTypes[Math.floor(Math.random() * 3)]
        })),
        generation: 0
      };
    },
    tick: (state, action) => ({
      ...state,
      cells: state.cells.map((row, rowIndex) =>
        row.map((col, colIndex) => next(rowIndex, colIndex, state.cells))
      ),
      generation: state.generation + 1
    }),
    toggle: (state, action) => {
      let cell = state.cells[action.position.row][action.position.col];
      switch (cell.type) {
        case CellType.EMPTY:
          return {
            ...state,
            cells: setCellType(CellType.NEW, state.cells, action.position)
          };
        case CellType.NEW:
        case CellType.OLD:
          return {
            ...state,
            cells: setCellType(CellType.EMPTY, state.cells, action.position)
          };
        default:
          return state;
      }
    },
    clear: (state, action) => ({
      cells: grid(50, 50, () => ({ type: CellType.EMPTY })),
      generation: 0
    }),
    setTimer: (state, action) => ({
      ...state,
      timer: action.timer
    })
  })
);

const run = () => {
  if (!store.getState().timer)
    store.dispatch({
      type: "setTimer",
      timer: setInterval(() => store.dispatch({ type: "tick" }), 100)
    });
};

const pause = () => {
  const timer = store.getState().timer;
  if (timer) store.dispatch({ type: "setTimer", timer: clearInterval(timer) });
};

const toggle = position => {
  store.dispatch({ type: "toggle", position });
};

const clear = () => {
  pause();
  store.dispatch({ type: "clear" });
};

const Header = () => {
  const headerStyle = {
    textAlign: "center",
    fontFamily: "Luckiest Guy",
    fontSize: "40px",
    color: "#01848F",
    marginTop: '10px'
  };
  return <div style={headerStyle}>Game Of Life</div>;
};

const Cell = ({ type, position }) => {
  const cellStyle = {
    width: "12px",
    height: "12px",
    border: "1px solid #9E9E9E",
    display: "inline-block",
    backgroundColor: type === CellType.NEW
      ? "#B2EBF2"
      : type === CellType.OLD ? "#006064" : "white"
  };
  return <div style={cellStyle} onClick={() => toggle(position)} />;
};

const CellRow = ({ row, rowIndex }) => {
  const rowStyle = {
    height: "12px",
    textAlign: "center"
  };
  return (
    <div style={rowStyle}>
      {row.map((cell, colIndex) =>
        <Cell
          type={cell.type}
          key={colIndex}
          position={{ row: rowIndex, col: colIndex }}
        />
      )}
    </div>
  );
};

const CellBoard = ({ cells }) => {
  return (
    <div>
      {cells.map((row, rowIndex) =>
        <CellRow row={row} key={rowIndex} rowIndex={rowIndex} />
      )}
    </div>
  );
};

const ActionButton = ({ buttonLabel, clickHandler }) => {
  const buttonStyle = {
    margin: "5px",
    padding: "5px",
    minWidth: "100px",
    backgroundColor: '#79C7C1',
    color: 'white',
    border: '1px solid transparent',
    fontSize: '18px',
    borderRadius: '5px',
    fontFamily: 'Open Sans',
    cursor: 'pointer'
  };
  return (
    <button style={buttonStyle} onClick={clickHandler}>{buttonLabel}</button>
  );
};

const Generation = ({ generation }) => {
  const generationStyle = {
    fontFamily: 'Open Sans',
    fontSize: '20px',
    color: '#01848F'
  };
  return <div style={generationStyle}>Generation: {generation}</div>;
};

const UserActions = ({
  runHandler,
  pauseHandler,
  clearHandler,
  generation
}) => {
  const actionStyle = {
    textAlign: "center",
    margin: "10px"
  };
  return (
    <div style={actionStyle}>
      <ActionButton buttonLabel="Run" clickHandler={run} />
      <ActionButton buttonLabel="Pause" clickHandler={pause} />
      <ActionButton buttonLabel="Clear" clickHandler={clear} />
      <Generation generation={generation} />
    </div>
  );
};

const App = ({ state }) => {
  return (
    <div>
      <Header />
      <UserActions generation={state.generation} />
      <CellBoard cells={state.cells} />
    </div>
  );
};

const render = () =>
  ReactDOM.render(
    <App state={store.getState()} />,
    document.getElementById("root")
  );

const isClear = (cells) => {
  for(let i = 0, j; i < cells.length; i++) {
    for(j = 0; j < cells[0].length; j++) {
      if(cells[i][j].type !== CellType.EMPTY) return false;
    }
  }
  return true;
}

store.subscribe(() => {
  const state = store.getState();
  if(state.timer && isClear(state.cells)) clear();
});
store.subscribe(render);

store.dispatch({type:'initialize'});
run();

            
          
!
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