Skip to content

Instantly share code, notes, and snippets.

@PabloRegen
Last active March 5, 2019 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PabloRegen/e45b4397f768156aab12e1e7bce65fc3 to your computer and use it in GitHub Desktop.
Save PabloRegen/e45b4397f768156aab12e1e7bce65fc3 to your computer and use it in GitHub Desktop.
Generate next game iteration
class App extends Component {
state = {...};
runStopButton = () => {...}
handleClearBoard = () => {...}
handleNewBoard = () => {...}
handleToggleCellStatus = () => {...}
handleStep = () => {
const nextStep = prevState => {
const boardStatus = prevState.boardStatus;
const clonedBoardStatus = JSON.parse(JSON.stringify(boardStatus));
const amountTrueNeighbors = (r,c) => {
const neighbors = [[-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1], [0, -1]];
return neighbors.reduce((trueNeighbors, neighbor) => {
const x = r + neighbor[0];
const y = c + neighbor[1];
const isNeighborOnBoard = (x >= 0 && x < totalBoardRows && y >= 0 && y < totalBoardColumns);
/* No need to count more than 4 alive neighbors */
if (trueNeighbors < 4 && isNeighborOnBoard && boardStatus[x][y]) {
return trueNeighbors + 1;
} else {
return trueNeighbors;
}
}, 0);
};
for (let r = 0; r < totalBoardRows; r++) {
for (let c = 0; c < totalBoardColumns; c++) {
const totalTrueNeighbors = amountTrueNeighbors(r,c);
if (!boardStatus[r][c]) {
if (totalTrueNeighbors === 3) clonedBoardStatus[r][c] = true;
} else {
if (totalTrueNeighbors < 2 || totalTrueNeighbors > 3) clonedBoardStatus[r][c] = false;
}
}
}
return clonedBoardStatus;
};
this.setState(prevState => ({
boardStatus: nextStep(prevState),
generation: prevState.generation + 1
}));
}
// Other methods ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment