xxxxxxxxxx
111
let w = 5;
let columns, rows;
let board;
function setup() {
createCanvas(400, 400);
columns = width / w;
rows = height / w;
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 draw() {
//skip esge
for (let x = 1; x < columns - 1; x++) {
for (let y = 1; y < rows - 1; y++) {
let neighbors = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
//Use previous state when counting neighbors
neighbors += board[x + i][y + j].previous;
}
}
neighbors -= board[x][y].previous;
//Set new state based on the neighbor count
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;
}
}
}
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
// evaluates to 255 when state is 0 and 0 when state is 1
board[i][j].show();
// save previous state
board[i][j].previous = board[i][j].state;
}
}
}
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 mouseDragged() {
// Update cell state when the mouse is dragged
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
// Check if mouse is within the boundaries
if (
mouseX > board[i][j].x &&
mouseX < board[i][j].x + w &&
mouseY > board[i][j].y &&
mouseY < board[i][j].y + w
) {
// Update the cell state to 1 (alive)
board[i][j].state = 1;
board[i][j].previous = board[i][j].state;
}
}
}
}
class Cell {
constructor(state, x, y, w) {
// What is the cell’s state?
this.state = state;
this.previous = this.state;
// position and size
this.x = x;
this.y = y;
this.w = w;
}
show() {
// stroke(0);
if (this.previous === 0 && this.state == 1) {
stroke(255,255,0); //yellow
fill(255, 255, 0);
} else if (this.state == 1) {
stroke(255); //black
fill(255);
} else if (this.previous == 1 && this.state === 0) {
stroke(218,165,32) //gold
fill(218,165,32);
} else {
stroke(0); //white
fill(0);
}
square(this.x, this.y, this.w);
}
}