xxxxxxxxxx
108
let scale = 2;
let w = 160;
let columns, rows, layers;
let boards = [];
let growing_state = -1;
let seed_x, seed_y;
function setup() {
createCanvas(w, w);
background(255);
frameRate(20);
columns = w / scale;
rows = w / scale;
layers = 8;
for (let n = 0; n < layers; n++) {
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 * scale, j * scale, scale);
}
}
// console.log(board)
boards.push(board);
}
// console.log(boards)
for (let k = 0; k < layers; k++) {
for (let i = 0; i < columns; i++) {
for (let j = 0; j < rows; j++) {
boards[k][i][j].show();
}
}
}
}
function draw() {
background(255);
// Looping but skipping the edge cells
for (let z = 1; z < layers - 1; z++) {
for (let x = 1; x < columns - 1; x++) {
for (let y = 1; y < rows - 1; y++) {
let neighbors = 0;
for (let k = -1; k <= 1; k++) {
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
//Use the previous state when counting neighbors
neighbors += boards[z + k][x + i][y + j].previous;
}
}
}
neighbors -= boards[z][x][y].previous;
// desicion
if (growing_state == -1) {
if (neighbors >= 13 && neighbors <= 22) {
boards[z][x][y].state = 1;
} else {
boards[z][x][y].state = 0;
}
} else {
if (neighbors >= 6 && neighbors <= 7) {
boards[z][x][y].state = 1;
} else if (boards[z][x][y].state == 1) {
boards[z][x][y].state = 1;
} else {
boards[z][x][y].state = 0;
}
}
}
}
}
for (let k = 0; k < layers; k++) {
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
boards[k][i][j].show();
// save the previous state before the next generation!
boards[k][i][j].previous = boards[k][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 * scale, j * scale, scale);
}
}
return arr;
}
function mousePressed() {
growing_state *= -1;
seed_x = mouseX;
seed_y = mouseY;
// console.log(growing_state);
}