xxxxxxxxxx
76
// World class definition
class World {
// Constructor for the World class
constructor(gridI, gridJ, cellSize) {
this.cellSize = cellSize; // Size of each cell
this.grid = []; // 2D array to store cells
// Create a grid of cells
for (let j = 0; j < gridJ; j++) { // Iterate over rows
let row = [];
for (let i = 0; i < gridI; i++) { // Iterate over columns
let cell = new Cell(i, j, this.cellSize); // Create a new cell
row.push(cell); // Add the cell to the row
}
this.grid.push(row); // Add the row to the grid
}
}
// Function to display all cells in the grid
show() {
strokeWeight(1); // Set the stroke weight
stroke("#f0f0f0"); // Set the stroke color
this.grid.forEach((row) => {
row.forEach((cell) => {
cell.show(); // Call the show function of each cell
});
});
}
// Function to update the state of all cells for the next generation
overWrite() {
this.grid.forEach((row) => {
row.forEach((cell) => {
cell.overWrite(); // Call the overWrite function of each cell
});
});
}
// Function to find and assign neighbors to each cell in the grid
findNeighbours() {
for (let j = 0; j < this.grid.length; j++) { // Iterate over rows
let row = this.grid[j];
for (let i = 0; i < row.length; i++) { // Iterate over columns
let cell = row[i]; // Get the current cell
// Iterate over neighboring cells
for (let dj = -1; dj <= 1; dj++) {
if (this.grid[j + dj]) { // Check if the neighboring row exists
for (let di = -1; di <= 1; di++) {
// Check if the neighboring cell is within the grid and not the cell itself
if (
j + dj >= 0 &&
j + dj < this.grid.length &&
i + di >= 0 &&
i + di < row.length &&
!(dj === 0 && di === 0)
) {
let neighbour = this.grid[j + dj][i + di]; // Get the neighboring cell
cell.addNeighbor(neighbour); // Add the neighbor to the cell's neighbors set
}
}
}
}
}
}
}
// Function to calculate the next state for all cells
next() {
this.grid.forEach((row) => {
row.forEach((cell) => {
cell.next(); // Call the next function of each cell
});
});
}
}