xxxxxxxxxx
78
let piles;
function sandpiles(x, y) {
let arr = new Array(x);
for (var i = 0; i < arr.length; i++) {
arr[i] = new Array(y);
}
return arr;
}
function topple() {
let nextpiles = new sandpiles(width, height);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
let num = sandpiles(x, y);
if (num < 4) {
nextpiles[x][y] = sandpiles[x][y];
}
}
}
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
let num = sandpiles(x, y);
if (num >= 4) {
nextpiles[x][y] += (num - 4);
if (x+1 < width) {
nextpiles[x+1][y]++;
} else if (x-1 >= 0) {
nextpiles[x-1][y]++;
} else if (y+1 < height) {
nextpiles[x][y+1]++;
} else if (x-1 >= 0) {
nextpiles[x][y-1]++;
}
}
}
}
piles = nextpiles;
}
function render() {
loadPixels();
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
let num = sandpiles[x][y];
let col = color(255, 0, 0);
if (num == 0) {
col = color(255, 255, 0);
} else if (num == 1) {
col = color(0, 185, 63);
} else if (num == 2) {
col = color(0, 104, 255);
} else if (num == 3) {
col = color(122, 0, 229);
}
pixels[x+y*width] = col;
}
}
updatePixels();
}
function setup() {
createCanvas(200, 200);
piles = sandpiles(width, height);
piles[width/2][height/2] = 1000;
}
function draw(){
render();
topple();
}