CodeRigor

LESSON

Slime trails on a grid

Agents sense a trail, steer toward it, move, deposit and let it diffuse and fade. Build each piece on a wrapping grid and test it against brute force.

Thousands of simple agents can draw branching, vein-like networks if each one only reads a trail, steers toward the strongest nearby signal and adds to the trail itself. This lesson pairs with Coding Adventure: Ant and Slime Simulations by Sebastian Lague, linked under Watch & read. The video covers ant and slime simulations, among them slime on a grid; here you build the pieces in NumPy and test each against a brute-force loop.

The world is a grid of floats, the trail, and each agent has a float position (x, y) and a heading. Index the grid as trail[row, col]: the row comes from y and the column from x. A position belongs to the cell (⌊y⌋ mod height, ⌊x⌋ mod width), so the grid wraps like a torus and nothing ever leaves it. The modulo is applied after the floor, and np.floor matters: truncating with int() sends −0.5 to cell 0 instead of the last cell.

One tick has six steps, always in the same order.

One tick of the simulation
start / 5
The three sensors read the trail as it was at the start of the tick. Deposit, diffuse and decay then change the whole grid.
One tick of the simulation
The three sensors read the trail as it was at the start of the tick. Deposit, diffuse and decay then change the whole grid.

A sensor looks at the point distance ahead of the agent along some angle, and reads the cell that point falls in. The left sensor uses the heading plus a sensor angle, the right sensor the heading minus it. The steering rule compares three readings. If the center is larger than both sides, keep going. If it is smaller than both, the agent is at a ridge or a gap, so turn by a random amount between −a and +a. Otherwise turn by a fixed amount toward the larger side, and if the sides are equal, keep the heading. Test the two strict cases first; a rule that starts by comparing left with right sends agents off a ridge they should have stayed on.

Python
import numpy as np

trail = np.zeros((3, 5))
trail[2, 1] = 4.0                                        # row 2 (y), column 1 (x)
x, y = np.array([1.5, 1.5]), np.array([1.5, 2.5])
angle = np.array([np.pi / 2, np.pi / 2])                 # both face +y
sx, sy = x + np.cos(angle), y + np.sin(angle)            # one cell ahead
print(trail[np.floor(sy).astype(int) % 3, np.floor(sx).astype(int) % 5].round(6).tolist())

The first agent finds the 4.0 one row below it. The second stands in the last row, and its sensor wraps to row 0, where the trail is empty.

Depositing is where a quiet bug lives. Agents often share a cell, and each must add its amount. The shortcut trail[rows, cols] += amount reads every cell once, adds once and writes once, so with a repeated index only one of the additions survives. np.add.at(trail, (rows, cols), amount) applies every one.

Python
import numpy as np

idx = np.array([1, 1, 2])           # two agents in cell 1
a = np.zeros(3)
a[idx] += 1.0
b = np.zeros(3)
np.add.at(b, idx, 1.0)
print(a.tolist(), b.tolist())

The trail is then blurred and faded. Diffusing replaces each cell by (1 − r)·cell + r·m, where m is the mean of its 3×3 neighborhood, itself included, on the torus. Every cell is counted in nine neighborhoods, so the total does not change, whatever r is. Decay multiplies by e^(−k·dt). The exponential form composes, so two ticks of 0.2 and 0.3 fade the trail exactly as much as one tick of 0.5, which a subtraction clamped at zero would not.

Python
import numpy as np

trail = np.zeros((3, 3))
trail[1, 1] = 9.0
blur = sum(np.roll(trail, (dy, dx), axis=(0, 1)) for dy in (-1, 0, 1) for dx in (-1, 0, 1)) / 9
out = 0.5 * trail + 0.5 * blur
print(out[1, 1], out[0, 0], out.sum())
A single spike of 10, with and without diffusion
Peak value of one deposit over nine ticks. Fading alone is a slow exponential; diffusing by 0.5 first spreads the peak, so it falls much faster while the total mass fades at the same rate.
A single spike of 10, with and without diffusion
Peak value of one deposit over nine ticks. Fading alone is a slow exponential; diffusing by 0.5 first spreads the peak, so it falls much faster while the total mass fades at the same rate.

Two mistakes recur. The first is the dropped duplicate above. The second is swapping the axes: wrapping x by the height and y by the width. On a square grid nothing visibly goes wrong, which is why the hidden tests use a wide one. Smaller versions of the same slip are indexing trail[x, y] and truncating instead of flooring.

Verification here has three parts. Each function is compared with a loop that visits every agent or every cell. Diffusion must keep the total. And a whole tick must obey a mass balance: with n agents depositing a and decay rate k over dt, the total after a tick is (before + n·a)·e^(−k·dt). Iterating that recurrence from zero settles at n·a·e^(−k·dt) / (1 − e^(−k·dt)); for 60 agents, a = 1 and k·dt = 0.1 that is 570.5, and a 32×32 run of the reference reaches 570.5 after 200 ticks.

Python
import math

mass = 0.0
for _ in range(200):
    mass = (mass + 60 * 1.0) * math.exp(-0.1)
print(round(mass, 1))

Know what this does not show. The checks prove that your functions do what the specification says and that no mass leaks. They say nothing about whether the picture looks like slime: that depends on the sensor distance, the angles and the rates, and only your eyes can judge it.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →