xxxxxxxxxx
119
let grid;
let cols, rows;
const resolution = 10;
let frameCount = 0;
let movingCells = [];
function setup() {
createCanvas(800, 600);
cols = width / resolution;
rows = height / resolution;
grid = make2DArray(cols, rows);
// Initialize grid with random shades of pink
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = {
alive: floor(random(2)),
color: randomPink()
};
}
}
// Add random moving cells
for (let i = 0; i < 20; i++) {
movingCells.push({
x: 0,
y: floor(random(rows)),
color: randomPink()
});
}
}
function draw() {
background(0);
// Update and draw moving cells
for (let cell of movingCells) {
cell.x = (cell.x + 1) % cols;
grid[cell.x][cell.y].alive = 1;
grid[cell.x][cell.y].color = cell.color; // Update the color of the moving cell
}
// Draw the grid
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j].alive == 1) {
noStroke();
fill(grid[i][j].color); // Use the color stored in the cell
rect(x, y, resolution, resolution);
}
}
}
// Update Game of Life grid
if (frameCount % 10 === 0) {
grid = nextGeneration();
}
frameCount++;
}
function nextGeneration() {
let next = make2DArray(cols, rows);
// Apply Game of Life rules
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j].alive;
let neighbors = countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = { alive: 1, color: randomPink() };
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = { alive: 0, color: grid[i][j].color };
} else {
next[i][j] = { alive: state, color: grid[i][j].color };
}
}
}
// Move the special cells in the next generation
for (let cell of movingCells) {
let newX = (cell.x + 1) % cols;
next[newX][cell.y] = {
alive: 1,
color: cell.color
};
}
return next;
}
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += grid[col][row].alive;
}
}
sum -= grid[x][y].alive;
return sum;
}
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function randomPink() {
// Generate a random shade of pink
return [random(180, 255), random(100, 180), random(150, 200)];
}