Falling Sand Simulation in Animated ASCII

Three moving spouts pour coloured sand that tumbles and piles into striped dunes, then a trapdoor opens and the box drains to start again.

Motion Lab80×3230 fps4.5 KB
Look

Use it Docs

Paste two lines into any page, use it from React, play it in a terminal, put a GIF in a README, or hand the Agent prompt to your coding agent. Every tab follows the look you pick above.

<script type="module" src="https://www.ascii-magic.com/ascii/ascii.js"></script>

<ascii-art piece="falling-sand"></ascii-art>

Export

Pause on the frame you like, pick a look, then download it at an exact size.

Share

← Falling LeavesFern Fractal →

This falling sand simulation is drawn entirely in text characters. Grains in eight sand colors drop from three wandering spouts, tumble down each other's slopes and settle into layered dunes inside a gray box, until a trapdoor in the floor lets the whole pile run out. Every grain obeys the same three rules on an 80 by 32 character grid, so each slope, slide and funnel you see is computed, not hand animated.

To be upfront: most people searching for falling sand want a sandbox game where you paint materials with the mouse, and this is not that. The piece plays itself, like a screensaver, and repeats about every 24 seconds. What it offers instead is a lightweight animation you can embed on a web page, export as a GIF, video or wallpaper, or play in a terminal, plus a clear guide to the rules if you are building your own.

How a falling sand simulation works

A falling sand simulation splits the picture into a grid of cells. Each cell is empty or holds one grain, and every step moves each grain by a tiny local rule. Nothing in the code knows about piles or dunes: those shapes emerge from thousands of grains checking only their nearest cells. The classic rule set fits in one sentence: a grain falls if the cell below is empty, otherwise slides diagonally down to the left or right if that cell is open, picking the side at random so heaps stay symmetrical, and otherwise rests.

Those rules explain why piles form natural slopes. A grain only stops when it is supported below and on both diagonals, so a heap can never be steeper than one cell sideways for every cell down. Extra sand rolls down the sides until the slope is stable again, a simple version of the angle of repose, the steepest slope a real heap of sand can hold.

Falling sand games, a whole genre of sandbox toys, grow from this loop by adding materials, such as water that spreads sideways or heavy grains that sink through lighter ones. The full source of this piece is at the bottom of this page, and it uses four details most builders add:

  • Bottom up: update the lowest row first, so lower grains make room before the ones above them move.
  • Alternating sweeps: scan left to right, then right to left on the next step, so sand does not drift toward one wall.
  • Moved flags: mark each grain once it moves, so it cannot fall twice in one step.
  • No corner cutting: a grain slides diagonally only if the cell beside it is empty too.

Inside this sand animation: spouts, stripes and a trapdoor

The piece draws a slate gray box 76 cells wide and 30 rows deep inside its 80 by 32 grid. Three spouts along the top each sway up to nine columns either side on their own slow sine wave. On about 85 percent of steps each spout drops a grain. The sand physics runs at 40 steps per second and the picture is drawn at 30 frames per second. Random choices come from a fixed seed, so every loop plays out the same way.

A grain in mid fall is drawn as a small dot, the top grain of a pile as a lower half block so the surface reads smooth, and packed grains as solid and shaded blocks speckled with a darker tone of their own color. Behind the box sits a dim navy field of shade characters.

The stripes come from timing, not painting. Every two seconds all three spouts switch to the next of eight sand colors, from ivory and gold through orange and dusty pink to rust and dark brown, offset so no two pour the same color at once. Each batch lands on the last as a thin layer, and the wandering spouts bend those layers into dunes, like sand art in a jar. A small corner label reads pouring, settling or draining as the cycle moves through four stages:

  • Pouring, for about 15 seconds: the spouts fill the box and the striped dunes climb.
  • Settling, for about a second: the spouts stop and the last falling grains land.
  • Draining: a trapdoor about nine cells wide opens in the middle of the floor. Grains above it drop out, neighbors slide diagonally into the gap, and a funnel cuts through the layers.
  • Emptying: about six seconds later the whole floor drops away and the loop restarts with an empty box.

Embed it, export it or play it in a terminal

The player at the top of this page can pause, run at half, normal or double speed, resize, switch between dark and light, and redraw the sand as Halftone dots, ASCII, Dense ASCII, Numbers, Binary, Letters, Blocks, Squares, Lines or your own characters. Halftone dots turn the dunes into soft printed bands, and Blocks keep the chunky feel of a pixel sandbox.

Like every piece in the library, Falling Sand is MIT licensed for personal and commercial work, and credit is appreciated but not required. The code tabs and exports give you:

  • Web page: add the ascii.js script tag from the HTML tab once, then place <ascii-art piece="falling-sand"> and its closing tag where the sand should appear. It draws on a canvas, weighs a few KB, plays only while on screen and holds a still frame for visitors who prefer reduced motion.
  • Attributes: size, speed, still, bg, look, chars, mono, contrast, dot-size and density. For example, speed="0.5" calms the pour behind text, and mono gives a single color version for handouts.
  • React: copy the piece file and kit.js into your project, and the component in the React tab draws each frame as text.
  • Terminal: npx ascii-magic-art falling-sand plays the piece in color in a terminal, and --frame prints one still frame instead.
  • README: download the GIF, commit it and paste the snippet from the README tab. Copy as text grabs the current frame as plain text for a code block.
  • Exports: a GIF, MP4 or WebM video at 1920x1080 with a 4K option, and PNG wallpapers and social sizes, for desktop, phone, thumbnails, banners and stories.

Where a sand animation fits: loaders, waits, heroes and lessons

Sand filling a box reads instantly as time passing and work piling up, which is why this piece is tagged as a loader. It fits well in these places:

  • Loading and progress states: show it while a report builds or an upload finishes. It loops on its own clock and does not measure real progress, so pair it with honest status text. For a setup guide, see ASCII loading spinners and progress bars for websites.
  • Hourglass style waits: the draining stage looks like the top of an hourglass emptying, a softer alternative to a spinner. For a literal hourglass animation that turns over when the top runs out, see Hourglass.
  • Command line tools: play it as a short splash while a tool starts up, or print a single frame in a welcome message. See Splash screens and loaders for command line tools.
  • Hero backgrounds and wallpapers: warm sand on dark navy sits well behind a headline at half speed, and a frame with tall striped dunes makes a calm desktop or phone background. See ASCII art wallpapers for desktop and phone.
  • Lessons: it is a compact demonstration of emergence, granular flow and grid simulation. Pair it with Chladni Figures, where sand gathers on the still lines of a vibrating plate, or Double Pendulum for chaos.
  • More rule based systems: the Algorithms category has Rule 30, Diffusion Aggregation and Game of Life, and the Motion Lab category holds the rest of the physics set. The full ASCII library has about 734 pieces in 24 categories.

/FAQS

Falling Sand Simulation in Animated ASCII: frequently asked questions

Q. What is a falling sand simulation?
A falling sand simulation is a grid where every cell is empty or holds a grain, and simple local rules move each grain on every step. A grain falls if the space below is empty, slides diagonally if it can, and otherwise rests. Piles, slopes and small avalanches emerge from those rules alone, which is what makes the idea so satisfying to watch and to build.
Q. Is this a falling sand game I can play?
No, this piece is a self-playing animation rather than an interactive game, so you cannot draw sand or add materials with the mouse. It runs the same rules on its own: three spouts pour, the dunes build, and a trapdoor drains the box. You can pause it, change its speed and size, embed it, export it or play it in a terminal.
Q. How do I code my own falling sand simulation?
Start with a 2D array of cells and loop over it from the bottom row up on each step. Move a grain down if the cell below is empty, otherwise try a random diagonal, otherwise leave it. Alternate the scan direction each step, flag grains that have moved so they only move once, and draw each cell as a pixel or a character.
Q. What is cellular automaton sand?
Cellular automaton sand is sand modeled as cells on a grid that change state based on their neighbors. Strictly, a classic cellular automaton such as the Game of Life updates every cell at once from the previous frame. Most sand code, including this piece, updates cells in place from the bottom up instead, which is simpler and stops two grains from claiming the same empty cell.
Q. How does sand physics work in a pixel simulation?
It works through fall, slide and rest rules rather than real forces such as momentum or friction. Because a grain only stops when the cells below and on both diagonals are full, no pile can be steeper than one cell across for each cell down. Extra sand rolls down the sides until the slope is stable, a simple stand-in for the angle of repose.
Q. How long is the sand animation loop?
One full cycle lasts about 24 seconds at normal speed. The spouts pour for roughly 15 seconds, the sand settles for a moment, a trapdoor opens in the middle of the floor, and about six seconds later the whole floor drops away. The random choices use a fixed seed and the box is empty when it restarts, so every loop looks identical.
Q. How do I add a sand animation to my website?
Add the ascii.js script tag from the HTML tab once, then place <ascii-art piece="falling-sand"> and its closing tag where you want the sand. It draws on a canvas, weighs a few KB and plays only while it is on screen. Use the speed, size, bg or look attributes to fit your design, and the React tab has a component version.
Q. Can I use a sand simulation as a loading animation?
Yes, it is tagged as a loader, and sand filling a box reads at a glance as work in progress. Show the embed while content loads, then remove it when the content arrives. It runs on its own loop and does not track real progress, so keep a short status line beside it. For a live builder, see ASCII loading spinners and progress bars for websites.
Q. Is there an hourglass animation in ASCII?
Yes, the Hourglass piece shows sand running through a wooden hourglass that turns over as soon as the top is empty. Falling Sand is a looser take on the same idea: when its trapdoor opens, a funnel cuts through the striped dunes much like the top of an hourglass draining. Both suit waiting states, timers and loading screens.
Q. Can I play the sand animation in a terminal?
Yes, the Terminal tab on this page gives a one-line command that plays Falling Sand in color in a terminal window. Add --frame to print a single still frame instead, which works well in a startup message or a script. For a fuller setup with your own command line tool, see Splash screens and loaders for command line tools.
Q. Can I download the sand animation as a GIF, video or wallpaper?
Yes, this page exports a GIF, a video as MP4 or WebM at 1920x1080 with a 4K option, and PNG wallpapers in desktop, phone and social sizes. For a still, a moment with tall striped dunes just before the trapdoor opens looks strongest. The piece is MIT licensed, so exports can go into commercial projects too.
Q. Can I change how the sand is drawn?
Yes, the player can redraw the piece as Halftone dots, ASCII, Dense ASCII, Numbers, Binary, Letters, Blocks, Squares, Lines or your own characters, with sliders for dot size and density. On an embed, the look, chars, mono and contrast attributes do the same job. Try the looks in the player first, then copy the matching attribute onto your tag.

Source GitHub

MIT licensed and open source on GitHub. It imports one small helper file, kit.js. This is the animation itself: what gets drawn in every frame. The look you pick is applied on top by the player, like a filter, so this file stays the same in every look while the snippets above change with it. Edit it to change the animation; see the docs to make your own.

/* falling-sand: coloured sand pours from moving spouts, piles into striped dunes, then drains through a trapdoor. */
import { Grid, palette, gradient, KEYS, rng, clamp } from "../lib/kit.js";

const all = [], G = {};
const add = (n, c) => { G[n] = all.length; all.push(...c); };
add("bg", gradient(["#08090f", "#0e1220", "#141a30", "#1a2240"], 4));
add("wall", ["#3a3f52", "#5a6278", "#8a92a8"]);
const SAND = ["#e8c27a", "#d88a4a", "#c85a3a", "#f0dca8", "#b8743a", "#e8a0a0", "#f4e4c4", "#9a6a3a"];
SAND.forEach((c, i) => add("s" + i, [c]));
add("dark", SAND.map((c) => {
  const v = [1, 3, 5].map((i) => Math.round(parseInt(c.slice(i, i + 2), 16) * 0.62));
  return "#" + v.map((x) => x.toString(16).padStart(2, "0")).join("");
}));
add("ui", ["#5a6478", "#8b949e"]);

export const meta = {
  slug: "falling-sand",
  name: "Falling Sand",
  category: "motion-lab",
  note: "Three moving spouts pour coloured sand that tumbles and piles into striped dunes, then a trapdoor opens and the box drains to start again.",
  tags: ["sand", "particles", "cellular-automaton", "physics", "loader", "hourglass"],
  cols: 80, rows: 32, fps: 30,
  palette: palette(all),
};

const K = (n, i) => KEYS[G[n] + i];
const SPS = 40, PER = 24, POUR = 15.5, OPEN = 16.5;

export default function create() {
  const { cols, rows } = meta;
  const g = new Grid(cols, rows);
  const L = 2, R = cols - 3, B = rows - 2;           // inner box: x in [L, R], y in [0, B)
  const W = cols, H = rows;
  const cell = new Uint8Array(W * H), moved = new Uint8Array(W * H);
  let n = 0, rand;
  const reset = () => { cell.fill(0); n = 0; rand = rng(4242); };
  const step = () => {
    const tt = n / SPS;
    moved.fill(0);
    const open = tt > OPEN;
    const ltr = n % 2 === 0;
    for (let y = B - 1; y >= 0; y--) {
      for (let k = L; k <= R; k++) {
        const x = ltr ? k : L + R - k;
        const i = x + y * W;
        const c = cell[i];
        if (!c || moved[i]) continue;
        const below = y + 1;
        if (below >= B) {
          // the trapdoor in the middle of the floor
          if (open && (tt > 22.6 || Math.abs(x - cols / 2) < 5)) { cell[i] = 0; }
          continue;
        }
        const d = x + below * W;
        if (!cell[d]) { cell[d] = c; cell[i] = 0; moved[d] = 1; continue; }
        const first = rand() < 0.5 ? -1 : 1;
        for (const s of [first, -first]) {
          const nx = x + s;
          if (nx < L || nx > R) continue;
          const dd = nx + below * W;
          if (!cell[dd] && !cell[nx + y * W]) { cell[dd] = c; cell[i] = 0; moved[dd] = 1; break; }
        }
      }
    }
    if (tt < POUR) {
      const band = 1 + (Math.floor(tt / 2) % SAND.length);
      for (let s = 0; s < 3; s++) {
        const sx = Math.round(cols * (0.22 + s * 0.28) + Math.sin(tt * (0.5 + s * 0.23) + s * 2) * 9);
        if (rand() < 0.85) { const i = sx + 1 * W; if (!cell[i]) cell[i] = 1 + ((band - 1 + s * 3) % SAND.length); }
      }
    }
    n++;
  };
  reset();
  return (t) => {
    const lt = t % PER;
    const want = Math.floor(lt * SPS);
    if (want < n) reset();
    while (n < want) step();
    g.clear();
    for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
      const v = 0.25 + (y / rows) * 0.6;
      g.set(x, y, (x * 3 + y) % 5 === 0 ? "·" : "░", K("bg", Math.min(3, Math.floor(v * 4))));
    }
    const tt = n / SPS;
    for (let y = 0; y < B; y++) for (let x = L; x <= R; x++) {
      const c = cell[x + y * W];
      if (!c) continue;
      const falling = moved[x + y * W] && y + 1 < B && !cell[x + (y + 1) * W];
      const top = y === 0 || !cell[x + (y - 1) * W];
      if (falling) g.set(x, y, "•", K("s" + (c - 1), 0));
      else g.set(x, y, top ? "▄" : (x + y) % 3 === 0 ? "▓" : "█", top ? K("s" + (c - 1), 0) : (x * 7 + y * 3) % 5 === 0 ? K("dark", c - 1) : K("s" + (c - 1), 0));
    }
    // box
    for (let y = 0; y <= B; y++) { g.set(L - 1, y, "█", K("wall", 1)); g.set(R + 1, y, "█", K("wall", 1)); }
    const open = tt > OPEN;
    for (let x = L - 1; x <= R + 1; x++) {
      const gap = open && (tt > 22.6 || Math.abs(x - cols / 2) < 5) && x >= L && x <= R;
      g.set(x, B, gap ? " " : "▀", K("wall", 2));
      if (!gap) g.set(x, B + 1, "▀", K("wall", 0));
    }
    // spouts
    if (tt < POUR) for (let s = 0; s < 3; s++) {
      const sx = Math.round(cols * (0.22 + s * 0.28) + Math.sin(tt * (0.5 + s * 0.23) + s * 2) * 9);
      g.text(sx - 1, 0, "▀█▀", K("wall", 2));
    }
    const label = tt < POUR ? "pouring" : open ? "draining" : "settling";
    g.text(cols - 12, rows - 1, label.padStart(10), K("ui", 1));
    return g.frame();
  };
}

More motion lab

Simulations: pendulums, waves, particles and fields.

/YOUR OWN

Turn your own image or video into ASCII

The pieces here are hand-built animations. To turn your own photo, logo or video into animated ASCII, use the ASCII Magic editor.