xxxxxxxxxx
63
let w = 300;
let h = 300;
let size = 3;
let game, nextGen;
let count;
let dispersion = 30;
function setup() {
createCanvas(w, h);
noStroke();
//frameRate(5);
game = new Array(h);
for (let i=0;i<h;i++) {
game[i] = new Array(w);
for (let j=0;j<w;j++)
game[i][j] = random(100) < dispersion ? 1 : 0;
}
background(237, 222, 180);
/*createLoop({duration: 10,
startLoop:40,
gif:true,
download: true,
fileName: 'game-of-sand.gif',
open: true});//*/
}
function draw() {
fill(237, 222, 180, 2);
rect(0, 0, w, h);
fill(212, 119, 6);
nextGen = new Array(h);
for (let i=0;i<h;i++) {
nextGen[i] = new Array(w);
for (let j=0;j<w;j++) {
// draw
if (game[i][j] === 1) rect(i,j, 1, 1);
// compute next gen
count = neighbours(game, i, j);
if (game[i][j] === 0 && (count === 3 || count == 6 || count == 7))
nextGen[i][j] = 1;
else if (game[i][j] === 1 && (count === 2 || count === 3))
nextGen[i][j] = 1;
else {
nextGen[i][j] = 0;
}
}
}
// hard copy next generation
for (let i = 0 ; i < h ; i++)
for (let j = 0 ; j < w ; j++)
game[i][j] = nextGen[i][j];
}
function neighbours(game, x, y) {
let c = 0;
for (let i = -1 ; i <= 1 ; i++)
for (let j = -1 ; j <= 1 ; j++)
if (!(i==0 && j==0))
c += game[(x+i+w) % w][(y+j+h) % h];
return c;
}