xxxxxxxxxx
131
//jiayuan li
//reference :Daniel Shiffman
// Video: https://youtu.be/FWSR_7kZuYg
var c;
let grid;
let cols;
let rows;
let resolution = 10;
class Cell {
constructor(history) {
this.state = 0;
this.history = history;
}
}
function preload() {
myImage = loadImage('9.png');
}
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function setup() {
//createCanvas(600, 400);
createCanvas(640, 360);
myImage.resize(width, height);
cols = width / resolution;
rows = height / resolution;
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = new Cell(0);
grid[i][j].state = floor(random(2));
}
}
}
function draw() {
background(0);
//noLoop();
// strokeWeight(0.1);
noStroke();
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
//if (grid[i][j].state == 1) {
if (grid[i][j].history > 0) {
c = myImage.get(x, y);
fill(c[0], c[1], c[2], grid[i][j].history * 10);
//fill(255);
stroke(255);
noStroke();
rect(x, y, resolution - 1, resolution - 1);
} else {
c = myImage.get(x, y);
fill(brightness(c));
//fill(255);
stroke(255);
noStroke();
rect(x, y, resolution - 1, resolution - 1);
}
}
}
let next = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
next[i][j] = new Cell(grid[i][j].history);
}
}
// Compute next based on grid
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j].state;
// Count live neighbors!
let sum = 0;
let neighbors = countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j].state = 1;
//next[i][j].history++;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j].state = 0;
} else {
next[i][j].state = state;
}
if (next[i][j].state == 1) {
next[i][j].history++;
}
}
}
grid = next;
}
function countNeighbors(grid, x, y) {
let sum = 0;
// For a 5x5 grid, but you would have to
// drastically change the GOL rules since
// there are now 24 neighbors instead of 9
// for (let i = -2; i <= 2; i++) {
// for (let j = -2; j <= 2; j++) {
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].state;
}
}
sum -= grid[x][y].state;
return sum;
}