xxxxxxxxxx
// Set the size of the grid
var resolution = 10;
// Calculate the number of rows and columns in the grid based on the size of the canvas
var rows, cols, grid,bbndry,
function setup() {
createCanvas(400, 400);
rows = height / resolution;
cols = width / resolution
// Initialize the grid with random values
grid = createRandomGrid();
bdry = createRandomBoundary();
}
function createRandomGrid() {
var grid = new Array(cols);
for (var i = 0; i < cols; i++) {
grid[i] = new Array(rows);
for (var j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
return grid;
}
function createRandomBoundary(){
let arr = []
let num = random(10);
for (var i = 0; i < num; i++){
let obj = {x:random(width),
y:random(height),
w: random(width/10),
h: ranodm(height/10)
}
arr.push(obj)
return arr
}
}
// Create a random grid with either a 0 or 1 at each position
function draw() {
// Draw the grid
background(255);
for (var i = 0; i < cols; i++) {
for (var j = 0; j < rows; j++) {
if (grid[i][j] == 1) {
fill(0);
} else {
fill(255);
}
stroke(0);
rect(i * resolution, j * resolution, resolution, resolution);
}
// bndry.forEach(o=>{
// fill('red');
// rect(o.x, o.y, o.w, o.h);
// })
// Create a new grid to hold the updated cell values
var next = new Array(cols);
for (var i = 0; i < cols; i++) {
next[i] = new Array(rows);
}
// Calculate the new cell values
for (var i = 0; i < cols; i++) {
for (var j = 0; j < rows; j++) {
// Count the number of live neighbors
var neighbors = countNeighbors(grid, i, j);
// Rules for the game of life
if (grid[i][j] == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (grid[i][j] == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = grid[i][j];
}
}
}
// Set the new grid as the current grid
grid = next;
}
// Count the number of live neighbors
function countNeighbors(grid, x, y) {
var sum = 0;
for (var i = -1; i < 2; i++) {
for (var j = -1; j < 2; j++) {
var col = (x + i + cols) % cols;
var row = (y + j + rows) % rows;
sum += grid[col][row];
}
}
sum -= grid[x][y];
return sum;
}