write a falling sand simulation in plain javascript on a canvas. use one flat Uint8Array for a 320x180 grid, scan it bottom-up each tick, and give sand two rules: fall straight down if the cell below is empty, otherwise slide diagonally to a random free side. pour from two spouts, color each grain in warm golden shades with a little random jitter, and render crisp 4px cells on a dark slate #0d1117 background.
keep the grid flat and scan bottom-up, or grains fall several cells per tick. a moved[] flag stops a grain moving twice in one tick.
const W = 320, H = 180;
const EMPTY = 0, SAND = 1;
const grid = new Uint8Array(W * H); // one byte per cell: what is in it
const tone = new Uint8Array(W * H); // shade (high bits) + jitter (low bits)
const moved = new Uint8Array(W * H); // stops a cell moving twice per tick
let frame = 0;
const at = (x, y) => y * W + x;
const inside = (x, y) => x >= 0 && x < W && y >= 0 && y < H;
function spawn(x, y, type, shade = 0) {
if (!inside(x, y) || grid[at(x, y)] !== EMPTY) return;
grid[at(x, y)] = type;
tone[at(x, y)] = (shade << 6) | (Math.random() * 64);
}
function move(a, b) {
[grid[a], grid[b]] = [grid[b], grid[a]];
[tone[a], tone[b]] = [tone[b], tone[a]];
moved[b] = 1;
}
function updateSand(x, y) {
const i = at(x, y), below = i + W;
if (grid[below] === EMPTY) return move(i, below); // gravity
const d = Math.random() < 0.5 ? -1 : 1;
for (const s of [d, -d]) // diagonal slide
if (inside(x + s, y + 1) && grid[below + s] === EMPTY) return move(i, below + s);
}
function update() {
moved.fill(0);
const flip = frame++ % 2;
for (let y = H - 2; y >= 0; y--) // scan bottom-up
for (let k = 0; k < W; k++) {
const x = flip ? W - 1 - k : k, i = at(x, y);
if (grid[i] === SAND && !moved[i]) updateSand(x, y);
}
}







