Creative Coding From Zero · Episode 10
Cellular Automata
Cellular Automata is Episode 10 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Here is the most outrageous deal in all of programming. You take a grid of cells. You give every cell one tiny, dumb rule that looks only at its immediate neighbors — no memory, no plan, no goal. You run it. And out of that nothing comes everything: gliders that crawl across the screen forever, factories that spit out spaceships, fractal triangles that look hand-carved, things that look uncannily like growth and decay and life. The rule fits on a napkin. The behavior fills textbooks.
This episode is the canonical tour. We build Conway's Game of Life
from scratch, seed it with famous patterns — a glider, a glider gun firing a stream
of spaceships — then jump to Stephen Wolfram's 1D rules that paint
the famous Rule 30, Rule 90, and Rule 110 triangles row by row. You'll get a
B/S-notation control to invent your own life-like universes, all
running live at 60fps. The trick that makes it fast — rendering the whole grid through
one ImageData buffer instead of thousands of rectangles — is the same
trick every CA, fluid, and reaction-diffusion sim in this series leans on. Let's
watch nothing become everything.
What you're looking at
A grid of cells, each one either alive or dead. Every tick, each cell looks at its eight neighbors, counts how many are alive, and consults a rule to decide whether it lives, dies, or is born next tick. That's the whole machine. There is no global controller — every cell decides for itself, in parallel, using only local information. The breathtaking thing is that this purely local process produces large-scale, coordinated, often lifelike structure.
The stage selector walks the six ideas below. The
rule box accepts either B/S notation (for the 2D
life-like stages) or a Wolfram rule number 0–255 (for the 1D stage)
— it relabels itself so you always know which it wants. Speed sets
generations per second. Regenerate reseeds the soup with a fresh
random number; the same seed always reproduces the same starting grid. In the
Patterns stage, click and drag on the grid to paint your own live
cells into the simulation.
Stage 1 — The grid and a rule
We start with the rawest possible cellular automaton: a grid of random cells, ticking under Conway's rule. This is "random soup." Watch the first few generations — the noise instantly thins out, settles into still lifes (blocks, beehives), blinking oscillators, and the occasional glider wandering off. A field of pure static spontaneously organizing itself is the entire promise of the field in ten seconds. No cell knows what a "blinker" is; the pattern is an emergent consequence of the rule, not something anyone programmed.
Stage 2 — Conway's Life (B3/S23)
This is the rule — the one John Conway published in 1970 that launched the
whole subject. In B/S notation it's B3/S23: a dead cell
is Born if it has exactly 3 live neighbors; a live cell
Survives with 2 or 3; everything else dies, of loneliness (<2) or
overcrowding (>3). Four numbers. From them you get a system rich enough to build a
working computer inside — Life is Turing-complete. Here we run it on a denser, slower
soup so you can watch the long settling-down: the churn, the explosions, the slow
crystallization into a quiet ecosystem of debris.
Stage 3 — Patterns (glider & glider gun)
Random soup is mesmerizing but accidental. The real magic of Life is the engineered patterns people discovered by hand. This stage seeds a Gosper glider gun — a 36-cell contraption that oscillates with period 30 and, every 30 ticks, fires a glider. A finite machine emitting an infinite stream of moving objects, forever. Smaller gliders drift diagonally across the field. Try clicking and dragging to paint your own cells in and watch them collide with the stream. (The gun was found in 1970 to win a $50 prize for proving Life could grow without bound.)
Stage 4 — Wolfram's 1D rules
Now we drop from two dimensions to one. A single row of cells, and each cell's next
state depends on just three cells: itself and its two neighbors. Three
binary inputs means 2³ = 8 possible neighborhoods; a rule assigns an output bit to
each, so there are exactly 256 one-dimensional rules — Wolfram
numbered them 0–255. We draw time downward: each new generation is the next
row of pixels. Type 30, 90, or 110 into the
rule box. Rule 90 draws a perfect Sierpiński triangle. Rule
30 produces chaos so good it was used as a random-number generator in
Mathematica. Rule 110 is, astonishingly, Turing-complete — a
one-line rule that can compute anything.
Stage 5 — Custom rules
The B/S box is a doorway to thousands of universes. Conway's
B3/S23 is one point in a huge space of "life-like" rules, and many of the
neighbors are wonderful. Try B36/S23 ("HighLife," which has a pattern
that replicates itself), B2/S ("Seeds," which explodes from
any seed and never settles), B1/S1 (a fractal copier), or
B5678/S45678 ("Diamoeba," which grows blobby amoebas). Each tiny
edit to four digits is a completely different physics. This is generative art at its
purest: you're not designing the picture, you're designing the laws and
letting them paint.
Stage 6 — Colored by age
Same Game of Life, but now we remember how long each cell has been continuously alive and color it by that age through a cosine palette — freshly-born cells glow one hue, long-lived survivors shift through the spectrum. Suddenly the still lifes burn steady and bright while the churning frontier flickers with new colors, and you can see the difference between stable structure and active growth at a glance. The underlying simulation is identical to Stage 2; only the rendering changed. That split — one simulation, many visualizations — is the whole reason we kept the grid as plain numbers and the drawing as a separate step.
How the code works
Four pieces carry the entire demo: the grid as a flat typed array plus the Life step, the fast renderer, the Wolfram step, and the rule parser. Everything else is wiring.
The grid as a typed array + the Life step
A grid is conceptually 2D, but we store it as a one-dimensional
Uint8Array of length W*H and index it as
y*W + x. Flat typed arrays are dramatically faster than arrays-of-arrays:
one contiguous block of memory, no pointer-chasing, and they hand straight to the
renderer. The single most important rule of stepping a CA is double-buffering:
you read the old grid and write into a separate new grid. If you
mutate cells in place, a cell you already updated corrupts the neighbor count of a
cell you haven't reached yet, and your "Life" silently becomes garbage.
// Two buffers. Read `cur`, write `next`, then swap. Never write `cur`.
let cur = new Uint8Array(W * H);
let next = new Uint8Array(W * H);
function stepLife(born, survive) { // born/survive: 9-slot lookup tables
for (let y = 0; y < H; y++) {
const yu = (y - 1 + H) % H, yd = (y + 1) % H; // wrap top/bottom (toroidal)
for (let x = 0; x < W; x++) {
const xl = (x - 1 + W) % W, xr = (x + 1) % W; // wrap left/right
// count the 8 neighbors
const n =
cur[yu*W+xl] + cur[yu*W+x] + cur[yu*W+xr] +
cur[y *W+xl] + cur[y *W+xr] +
cur[yd*W+xl] + cur[yd*W+x] + cur[yd*W+xr];
const alive = cur[y*W+x];
// one branch-free decision via the rule tables
next[y*W+x] = alive ? survive[n] : born[n];
}
}
const t = cur; cur = next; next = t; // swap buffers for the next tick
}
Note the % W / % H wrapping: the grid is a
torus, so a glider that walks off the right edge reappears on the
left. That single choice avoids a whole class of edge artifacts. born and
survive are 9-element arrays (indices 0–8) of 0/1 — we'll fill them from
the rule string below, so the inner loop never parses anything.
Rendering through one ImageData — the perf key
The obvious way to draw a grid is a fillRect per live cell. Do
not do this. At a few hundred cells across, that's tens of thousands of
canvas calls every frame and the demo crawls. The fast way is to write pixels
directly into the byte buffer behind an ImageData and blit the
whole thing in one putImageData. Our grid cells map 1:1 to pixels, so the
image is exactly W×H and we let CSS scale the canvas up to fill the box.
// One ImageData the size of the grid. Its .data is a flat RGBA byte array.
const img = ctx.createImageData(W, H);
const buf = new Uint32Array(img.data.buffer); // view 4 bytes as one int = fast
function render() {
for (let i = 0; i < cur.length; i++) {
// 0xAABBGGRR little-endian: alive = white, dead = near-black
buf[i] = cur[i] ? 0xffffffff : 0xff0a0a0a;
}
ctx.putImageData(img, 0, 0); // one call paints the entire grid
}
The Uint32Array view is the second speed trick: instead of writing four
separate bytes (R, G, B, A) per pixel, we write one 32-bit integer. The byte order is
little-endian, so a pixel is 0xAABBGGRR — alpha highest, red lowest.
Setting imageSmoothingEnabled = false on the context keeps the upscaled
cells crisp instead of blurry. This one function is the difference between 8fps and
60fps; it's why the pitfalls section harps on it.
The Wolfram 1D step
A 1D automaton is even simpler. The current row is a strip of cells; each new cell
depends on a 3-cell neighborhood (left, center, right). Read those three
bits as a number 0–7 and look up the answer in the rule — which is just the rule
number read as 8 bits. Bit k of the rule number is the output for
neighborhood k. That's the whole of Wolfram's scheme.
// `ruleNum` is 0..255. We draw one new row per tick, scrolling downward.
function stepWolfram(row, ruleNum) {
const w = row.length;
const nextRow = new Uint8Array(w);
for (let x = 0; x < w; x++) {
const l = row[(x - 1 + w) % w];
const c = row[x];
const r = row[(x + 1) % w];
const idx = (l << 2) | (c << 1) | r; // 3 bits → 0..7
nextRow[x] = (ruleNum >> idx) & 1; // pull bit `idx` out of the rule
}
return nextRow;
}
To draw the famous triangles we keep a 2D history: each tick we compute a new row, copy every earlier row up by one, and write the new row at the bottom — a scrolling waterfall of time. Seed the very first row with a single live cell in the center and Rule 90 unfurls a Sierpiński triangle; seed it with random noise and Rule 30 boils.
Parsing B/S rule notation
The last piece turns a human string like "B3/S23" into the two
9-element lookup tables the Life step wants. We just scan the digits after
B and after S and flip on the matching slots. Being lenient —
accepting lowercase, missing slashes, extra spaces — makes the live control pleasant
to type into.
// "B3/S23" → { born:[0,0,0,1,0,0,0,0,0], survive:[0,0,1,1,0,0,0,0,0] }
function parseRule(str) {
const born = new Uint8Array(9), survive = new Uint8Array(9);
const m = str.toUpperCase().match(/B([0-8]*)\/?S([0-8]*)/);
if (!m) return { born, survive }; // invalid → empty (cells just die)
for (const d of m[1]) born[+d] = 1; // digits after B
for (const d of m[2]) survive[+d] = 1; // digits after S
return { born, survive };
}
Conway is B3/S23. HighLife is B36/S23. Seeds is
B2/S (no survive digits — every live cell dies every tick, yet the
pattern explodes outward forever). Because the parser produces plain lookup tables,
swapping rules at runtime costs nothing — the hot loop is identical for every
universe.
Common pitfalls
fillRectper cell is too slow. The single biggest mistake. A 300×190 grid is 57,000 cells; afillRecteach is tens of thousands of draw calls per frame and you'll see single-digit fps. Write into oneImageData's byte buffer andputImageDataonce. This is the whole performance story of cellular automata in the browser.- Mutating the grid you're reading. If you write the next state
back into the same array, cells you've already updated poison the neighbor counts of
cells you haven't. The result looks plausible for a frame, then degenerates.
Always double-buffer: read
cur, writenext, swap. - Forgetting edge wrapping. Reading
cur[y*W+x]with an out-of-boundsxorygivesundefined(which counts as 0 in the sum — subtle) or, worse, wraps into the wrong row in a flat array, leaking the right edge onto the next line. Decide on purpose: clamp to dead edges, or wrap toroidally with% W/% Has we do here. - Rule encoding mistakes. Off-by-one in the neighbor count (is a cell its own neighbor? — no), or reading the wrong bit of a Wolfram number, gives a rule that's almost right and therefore very confusing. Test against a known pattern: a blinker must blink; Rule 90 from a single seed must draw a clean Sierpiński triangle.
- Render resolution vs cell size. If the
ImageDatais the canvas's full pixel size but you want chunky cells, you either make the grid smaller and let CSS upscale (cheap, what we do) or draw blocks (slower). Mismatching grid dimensions and image dimensions silently shears the picture diagonally — a classic "why is my grid skewed" bug. - Stepping every animation frame. requestAnimationFrame runs at ~60Hz, but a CA is usually more legible slower. Drive generations off an accumulator (advance N steps per second regardless of frame rate) so the speed slider means something and fast machines don't blur past the interesting transient.
Exercises
- Langton's ant. Add an "ant" — a single agent on the grid with a heading. On a white cell it turns right, flips the cell to black, and steps forward; on a black cell it turns left, flips to white, steps forward. For ~10,000 steps it makes chaos, then spontaneously builds a periodic "highway" off to infinity. It's a cellular automaton with a read/write head — a tiny Turing machine you can watch.
- Brian's Brain. Generalize a cell from 2 states to 3:
off, on, and dying. An off cell turns on iff exactly 2
neighbors are on; an on cell always becomes dying; a dying cell always
becomes off. Store states as 0/1/2 in your
Uint8Arrayand color them distinctly. The result is a perpetual storm of self-propelled gliders that never settles — beautiful, and impossible in two states. - Click to draw. The Patterns stage already lets you paint; wire
it into every stage. Map the mouse position to grid coordinates
(
Math.floor(mx / cellSize)), set those cells alive onmousedown/mousemove, and add a key to clear the grid. Now the simulation is a sandbox — draw a wall and watch a glider stream shatter against it.
What's next
Episode 11 — Reaction-Diffusion: coral from chemistry. We keep the
grid and the per-cell update, but the cells stop being on/off and become two
continuous chemical concentrations that spread and react via the Gray-Scott
equations. The same double-buffered, ImageData-rendered machine you built
here, run on floats instead of bits, grows mitosing spots, labyrinths, and structures
that look exactly like coral, fingerprints, and animal coats. Cellular automata taught
us that local rules make global patterns; reaction-diffusion makes those patterns
organic.