Skip to content

Instantly share code, notes, and snippets.

@Mellen
Last active January 22, 2017 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mellen/26a35e398b1ff7c6ded89ca1ccea9149 to your computer and use it in GitHub Desktop.
Save Mellen/26a35e398b1ff7c6ded89ca1ccea9149 to your computer and use it in GitHub Desktop.
Sandpiles
<!DOCTYPE html>
<html>
<head>
<title>sandpile</title>
</head>
<body>
<canvas id="canv" width="300" height="300"></canvas>
<script src="js/sandpile.js" type="text/javascript"></script>
</body>
</html>
(function()
{
var canvas = document.getElementById('canv');
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
var SandPile = function()
{
this.max = 3;
};
SandPile.prototype.start = function()
{
context.fillStyle='#000000';
context.fillRect(0, 0, width, height);
this.pile = [];
for(var x = 0; x < width; x++)
{
for(var y = 0; y < height; y++)
{
this.pile.push(0);
}
}
var index = width/2 + ((height/2)*width);
this.pile[index] = 16777216;
this.currentFrame = context.getImageData(0, 0, width, height);
this.setColour(width/2, height/2);
requestAnimationFrame(this.step.bind(this));
};
SandPile.prototype.step = function(d)
{
for(var x = 0; x < width; x++)
{
for(var y = 0; y < height; y++)
{
var index = x + (y*width);
if(this.pile[index] > this.max)
{
var upy = y-1;
if(upy >= 0)
{
this.pile[x + (upy*width)]++;
this.setColour(x, upy);
}
var downy = y+1;
if(downy < height)
{
this.pile[x + (downy*width)]++
this.setColour(x, downy);
}
var leftx = x-1;
if(leftx >=0)
{
this.pile[leftx + (y*width)]++;
this.setColour(leftx, y);
}
var rightx = x+1;
if(rightx < width)
{
this.pile[rightx + (y*width)]++
this.setColour(rightx, y);
}
this.pile[index] -= 4;
this.setColour(x,y);
}
}
}
context.putImageData(this.currentFrame, 0, 0);
requestAnimationFrame(this.step.bind(this));
};
SandPile.prototype.setColour = function(x, y)
{
var index = x + (y*width);
var p = this.pile[index];
var r = 255;
var g = 255;
var b = 255;
if(p <= 8)
{
r = p * 32;
b = p * 32;
g = p * 32;
}
this.currentFrame.data[index*4] = r;
this.currentFrame.data[index*4 + 1] = g;
this.currentFrame.data[index*4 + 2] = b;
this.currentFrame.data[index*4 + 3] = 255;
};
var sp = new SandPile();
sp.start();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment