xxxxxxxxxx
126
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < cols; i++) {
arr[i] = new Array(rows);
}
return arr;
}
let grid;
let cols;
let rows;
let res = 10;
let USER = 0;
let RUN = 1;
let STATE = USER;
function setup() {
createCanvas(900, 600);
frameRate(30);
cols = width / res;
rows = height / res;
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = 0;
}
}
}
function draw() {
background(255);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * res;
let y = j * res;
stroke(127);
if (grid[i][j]) {
fill(0);
} else {
fill(255);
}
rect(x, y, res, res);
}
}
if (STATE == RUN) {
let next = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let sum = 0;
let neighbours = countNeighbours(grid, i, j);
if (!state && neighbours == 3) {
next[i][j] = 1;
} else if (state && (neighbours < 2 || neighbours > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
grid = next;
}
fill(0, 127);
rect(0, 0, 200, 40);
textSize(20);
fill(0, 255, 0);
if (STATE == USER) {
text("User designing cells", 10, 27.5);
} else {
text("Running simulation", 10, 27.5);
}
}
function countNeighbours(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += grid[col][row];
}
}
sum -= grid[x][y];
return sum;
}
function keyPressed() {
if (key == " ") {
STATE = !STATE;
}
if (key == "r") {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
STATE = RUN;
}
if (key == "c") {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = 0;
}
}
STATE = USER;
}
}
function mousePressed() {
if (STATE == USER) {
let mx = floor(mouseX / res);
let my = floor(mouseY / res);
grid[mx][my] = !grid[mx][my];
}
}