xxxxxxxxxx
101
let w = 8;
let columns, rows;
let initialColumns, initialRows; // Store initial values
let board;
function setup() {
createCanvas(640, 240);
noStroke(); // Remove cell borders
initializeGrid();
}
function draw() {
background(255);
updateAutomata();
displayAutomata();
}
function mousePressed() {
// Change initial conditions when the mouse is clicked
initializeGrid();
}
function mouseWheel(event) {
// Adjust cell size based on scroll direction
w += event.delta / 100;
w = constrain(w, 1, 20); // Adjust the range of cell sizes
initializeGrid();
}
function updateAutomata() {
for (let x = 1; x < columns - 1; x++) {
for (let y = 1; y < rows - 1; y++) {
let neighbors = countNeighbors(x, y);
updateCellState(x, y, neighbors);
}
}
}
function displayAutomata() {
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
board[i][j].show();
board[i][j].previous = board[i][j].state;
}
}
}
function initializeGrid() {
initialColumns = floor(width / w);
initialRows = floor(height / w);
// Check for valid array dimensions
if (initialColumns <= 2 || initialRows <= 2) {
console.error("Invalid initial array dimensions. Please choose a larger canvas size or smaller cell size.");
return;
}
// Reset to initial values
columns = initialColumns;
rows = initialRows;
board = create2DArray(columns, rows);
for (let i = 1; i < columns - 1; i++) {
for (let j = 1; j < rows - 1; j++) {
board[i][j] = new Cell(floor(random(2)), i * w, j * w, w);
}
}
}
function create2DArray(columns, rows) {
let arr = new Array(columns);
for (let i = 0; i < columns; i++) {
arr[i] = new Array(rows);
for (let j = 0; j < rows; j++) {
arr[i][j] = new Cell(0, i * w, j * w, w);
}
}
return arr;
}
function countNeighbors(x, y) {
let neighbors = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
neighbors += board[x + i][y + j].previous;
}
}
neighbors -= board[x][y].previous;
return neighbors;
}
function updateCellState(x, y, neighbors) {
if (board[x][y].state == 1 && neighbors < 2) {
board[x][y].state = 0;
} else if (board[x][y].state == 1 && neighbors > 3) {
board[x][y].state = 0;
} else if (board[x][y].state == 0 && neighbors == 3) {
board[x][y].state = 1;
}
}