Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for React: Conway's Game of Life.
Utkarsh Yadav
Utkarsh Yadav

Posted on

     

React: Conway's Game of Life.

Table of Content

  • What is Conway's Game of Life
  • Rules of the Game.
  • Coding out the simulation using React
  • CodeSandBox Playground

What is Conway's Game of Life

The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.

View full details for the Gamehere

Rule of the Game

  • Any live cell with fewer than two live neighbors dies, as if by underpopulation.
  • Any live cell with two or three live neighbors lives on to the next generation.
  • Any live cell with more than three live neighbors dies, as if by overpopulation.
  • Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Coding out simulator using React

Generating Empty Grid (our first task)

  • The total number ofRow andcolumns for the grid is to be set initially.

Note: Totally depends as per the requirement. The best is to use 30/30.

constnumRows=30;constnumCols=30;
Enter fullscreen modeExit fullscreen mode
constgenerateEmptyGrid=()=>{constrows=[];for(leti=0;i<numRows;i++){rows.push(Array.from(Array(numCols),()=>0));}returnrows;};
Enter fullscreen modeExit fullscreen mode

Explanation:

  • we used Arrayrows [] length ofnumRows: 30
  • For every row index we are pushingnumCols: 30 columns.
  • This function will be later used as a clear function to clear, to set the grid to empty.
[{1, 2, 3, ...., 30},{1, 2, 3, ...., 30},..    30th row]
Enter fullscreen modeExit fullscreen mode

Putting Random stuff on the grid

Requirement:Button andfuntion

  • Creating FunctiongenerateRandomStuff()
constgenerateRandomStuff=()=>{constrows=[];for(leti=0;i<numRows;i++){rows.push(Array.from(Array(numCols),()=>(Math.random()>0.5?1:0)));}returnrows;};
Enter fullscreen modeExit fullscreen mode
  • In this function, we are actually randomizing the column's number and choosing random columns in each row and if theMath.Random() value for the columns is greater than 0.5 we put that1: black else0:cleared;

State management forsetting Random Stuff andclearing the stuff from the grid

const[grid,setGrid]=useState(()=>{returngenerateEmptyGrid();});
Enter fullscreen modeExit fullscreen mode
  • using use State: we can do the state management for the grid.
  • Initially: The grid is set to empty.

Generate Random stuff: TO do this we will call for the function

constgenerateRandomStuff=()=>
Enter fullscreen modeExit fullscreen mode

and set it in grid :setGrid(generateRandomStuff())

<buttononClick={()=>{setGrid(generateRandomStuff());}}>RandomStuff</button>
Enter fullscreen modeExit fullscreen mode

Alt Text

Generate Empty Grid: To do this we will call for the function

constgenerateEmptyGrid=()=>
Enter fullscreen modeExit fullscreen mode

and set it in Empty the grid :setGrid(generateEmptyGrid())

<buttononClick={()=>{setGrid(generateEmptyGrid());}}>Clear</button>
Enter fullscreen modeExit fullscreen mode

Alt Text

Running Simulation (Logic) :)

  • For the simulation we need some preprocessing.
constredundant=[[0.1],[0,-1],[1,-1],[-1,1],[1,1],[-1,-1],[1,0],[-1,0]];
Enter fullscreen modeExit fullscreen mode

an array is taken with all steps, where we can move

  • We can move in all eight directions in the grid.
const[Simulation,setSimulation]=useState(false);construnningRef=useRef(Simulation);runningRef.current=Simulation;construnSimulation=useCallback(()=>{if(!runningRef.current){return;}setGrid((g)=>{returnproduce(g,(gridCopy)=>{for(leti=0;i<numRows;i++){for(letk=0;k<numCols;k++){letneighbors=0;redundant.forEach(([x,y])=>{constnewI=i+x;constnewK=k+y;if(newI>=0&&newK>=0&&newI<numRows&&newK<numCols){neighbors+=g[newI][newK];}});if(neighbors<2||neighbors>3){gridCopy[i][k]=0;}elseif(g[i][k]===0&&neighbors===3){gridCopy[i][k]=1;}}}});});setTimeout(runSimulation,100);},[]);
Enter fullscreen modeExit fullscreen mode
  • we will make a statesimulation andsetStimulation which will be initiallyfalse. and will be triggered totrue using the button.
  • const runSimulation = useCallback(() =>{}: here we will be using callback function.

  • Logic:

    • we will traverse the grid from index {0,0} to {numRows,numCols}
    • Take a counter for theneigbours.

What we exactly want is:

  1. if there is a cell in the grid which isset with exactly2 or3 neighbors in any of the direction.
  2. if there is a cell in the grid that is notset and has threeset or live neighbors becomeset or live.
  3. All other cells that areset or live are now set todead or unset, whereas allunset will remainunset.
redundant.forEach(([x,y])=>{constnewI=i+x;constnewK=k+y;if(newI>=0&&newK>=0&&newI<numRows&&newK<numCols){neighbors+=g[newI][newK];}});
Enter fullscreen modeExit fullscreen mode
  • we will move in 8 directions fromredundant array
  • following the above rule we have written, three cases.

After completion of the simulation, we run the function once after the interval of time.

For this we usesetTimeout(runSimulation, 100);

  • Button for the simulation.
<buttononClick={()=>{setSimulation(!Simulation);if(!Simulation){runningRef.current=true;runSimulation();}}}>{Simulation?"Stop":"start"}Simulation</button>
Enter fullscreen modeExit fullscreen mode

Alt Text

Note: Usingimmer for mutating the state.

If you like the content. kindly let me know.

Happy Coding.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
markhker profile image
Mark Hkr 😎
I code things
  • Joined

There is a small error that causes mistakes in the algorithm.
In the firs item of theredundant variable you have[0.1] and it should be[0, 1]
With that fixed, the program run as expected.
Cheers, great tutorial.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Ask me about Typescript, JavaScript, React, Next
  • Location
    Germany
  • Education
    Technische Universität Chemnitz
  • Pronouns
    he/him
  • Work
    Ex- Cognizant
  • Joined

More fromUtkarsh Yadav

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp