Skip to content

Instantly share code, notes, and snippets.

@vyuvalv
Created November 22, 2020 14:49
Show Gist options
  • Save vyuvalv/dd8581c77c5db6e9decf32fc94ba4293 to your computer and use it in GitHub Desktop.
Save vyuvalv/dd8581c77c5db6e9decf32fc94ba4293 to your computer and use it in GitHub Desktop.
Step 2 - Next Generation
// Calculate the next generation grid
nextGeneration() {
let nextUniverse = this.grid;
let cells = [];
const lastColumn = this.columns - 1, lastRow = this.rows - 1;
for (let col = 0; col < this.columns; col++) {
for (let row = 0; row < this.rows; row++) {
let state = nextUniverse[col][row];
// check cell neighbours
const totalNeighbours = this.countNeighbours(nextUniverse, col, row, lastColumn, lastRow);
state = this.runRulesOfLife(state, totalNeighbours);
// Assign the new Generation Cells
cells.push({
state: state,
col: col,
row: row,
x: col * this.columnWidth,
y: row * this.rowHeight,
neighbours: totalNeighbours
});
}
}
// Drawing after calculated new state for each cell
cells.forEach(cell => {
// Sets the new state in grid
nextUniverse[cell.col][cell.row] = cell.state;
// Draw the cells
this.renderCell(cell.state, cell.x, cell.y, this.columnWidth, this.rowHeight);
});
// set the next generation grid
this.grid = nextUniverse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment