xxxxxxxxxx
110
let cols, rows; // Grid dimensions
let grid;
let nextGrid;
let cellSize = 10; // Size of each cell
let playing = true; // Toggle simulation state
function setup() {
createCanvas(800, 600);
cols = floor(width / cellSize);
rows = floor(height / cellSize);
grid = createEmptyGrid();
nextGrid = createEmptyGrid();
randomizeGrid(grid); // Initialize with random state
// Add UI
let playPauseButton = createButton("Play/Pause");
playPauseButton.mousePressed(() => (playing = !playing));
let resetButton = createButton("Reset");
resetButton.mousePressed(() => randomizeGrid(grid));
let clearButton = createButton("Clear");
clearButton.mousePressed(() => (grid = createEmptyGrid()));
}
function draw() {
background(30);
drawGrid(grid);
if (playing) {
computeNextGrid();
swapGrids();
}
}
function mouseDragged() {
let col = floor(mouseX / cellSize);
let row = floor(mouseY / cellSize);
if (col >= 0 && col < cols && row >= 0 && row < rows) {
grid[col][row] = 1; // Activate cells with drag
}
}
function createEmptyGrid() {
let grid = new Array(cols);
for (let i = 0; i < cols; i++) {
grid[i] = new Array(rows).fill(0);
}
return grid;
}
function randomizeGrid(grid) {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = random() < 0.2 ? 1 : 0; // Randomly activate ~20% of cells
}
}
}
function drawGrid(grid) {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
if (grid[i][j] === 1) {
fill(color(map(i, 0, cols, 100, 255), map(j, 0, rows, 100, 255), 200));
} else {
fill(30);
}
noStroke();
rect(i * cellSize, j * cellSize, cellSize, cellSize);
}
}
}
function computeNextGrid() {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let neighbors = countNeighbors(i, j);
// Conway's Game of Life Rules:
if (state === 0 && neighbors === 3) {
nextGrid[i][j] = 1; // Birth
} else if (state === 1 && (neighbors < 2 || neighbors > 3)) {
nextGrid[i][j] = 0; // Death
} else {
nextGrid[i][j] = state; // Survival
}
}
}
}
function countNeighbors(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];
}
}
sum -= grid[x][y];
return sum;
}
function swapGrids() {
let temp = grid;
grid = nextGrid;
nextGrid = temp;
}