5. Physics and simulation¶
So far motion has been written as a formula of time. Real things move because forces act on them, and a simulation finds the motion step by step from the forces. Figure 5.1 shows the forces on the kite before any code: drawing a free-body diagram first is the habit that keeps a simulation honest.

Figure 5.1. Free-body diagram of the kite. Three forces act on one point mass: gravity, the string’s tension (only when stretched beyond its rest length \(L_0\)) and drag from the gusty wind. Newton’s second law, \(m\mathbf{a}=\sum\mathbf{F}\), gives the acceleration.
Watch the result: the finished film as an animated GIF.
5.1 Forces and integration¶
Natural motion comes from Newton's second law: the acceleration of a body is the total force on it divided by its mass, a = F/m. A computer cannot solve this continuously, so it takes small time steps Δt and updates velocity and position in turn. This is numerical integration. The simplest rule, explicit Euler, moves the position with the old velocity:
x ← x + v Δt, v ← v + a Δt.
Semi-implicit (symplectic) Euler updates the velocity first and moves with the new velocity:
v ← v + a Δt, x ← x + v Δt.
The change looks trivial, but it matters. Test both on a spring, where the exact answer is known: a mass on a spring of stiffness k swings for ever with constant energy ½kx² + ½mv². A good method keeps that energy constant.
def spring_energy(method, dt=0.05, steps=400, k=4.0, m=1.0):
x, v = 1.0, 0.0
E = []
for _ in range(steps):
a = -k * x / m
if method == "explicit":
x, v = x + v * dt, v + a * dt
else:
v = v + a * dt
x = x + v * dt
E.append(0.5 * k * x * x + 0.5 * m * v * v)
return np.array(E)
E0 = 0.5 * 4.0 * 1.0 ** 2
ex, si = spring_energy("explicit"), spring_energy("semi")
plt.figure(figsize=(7, 3))
plt.plot(ex / E0, label="explicit Euler"); plt.plot(si / E0, label="semi-implicit Euler")
plt.axhline(1, color="k", lw=0.8, ls=":"); plt.xlabel("step"); plt.ylabel("energy / starting energy")
plt.legend(); plt.title("A spring should keep its energy"); plt.tight_layout(); plt.show()
print(f"after 400 steps (20 s): explicit {ex[-1] / E0:.2f} x start, semi-implicit {si[-1] / E0:.2f} x start "
f"(range {si.min() / E0:.2f} to {si.max() / E0:.2f})")

after 400 steps (20 s): explicit 53.52 x start, semi-implicit 1.05 x start (range 0.95 to 1.05)
The dotted line is the truth: energy stays at 1. Explicit Euler (blue) gains energy every step and has grown about fifty-fold after 20 seconds, so a spring drawn with it would fling itself off the screen. Semi-implicit Euler (orange) wobbles a little around 1 but never drifts, so it can run for ever. We use it for everything that moves.
The kite. Basant, the spring kite festival, filled Lahore's sky with kites. Ours is a point mass held by a string from a rooftop at the lower left. Three forces act on it (drawn in the free-body diagram in the guide):
-
Gravity, m g, straight down.
-
String tension from Hooke's law: if the string is stretched beyond its rest length L₀ by ΔL, it pulls towards the anchor with force k ΔL. A string can pull but not push, so the force is zero when slack.
-
Wind, modelled as drag: a force proportional to the difference between the wind velocity and the kite's velocity, c(w − v). The wind blows right and lifts upwards, and it gusts: each component is a constant plus a few sine waves of different periods, so it never quite repeats.
Units are pixels and seconds; g = 20 pixels per second squared is chosen so the motion reads well, not to match the real value of 9.8 m s⁻².
@dataclass
class Kite:
anchor: tuple = (4.0, GROUND - 2.0)
pos: np.ndarray = field(default_factory=lambda: np.array([40.0, 40.0]))
vel: np.ndarray = field(default_factory=lambda: np.zeros(2))
m: float = 1.0; g: float = 20.0; k: float = 6.0; L0: float = 90.0; drag: float = 1.5
def wind(self, t):
return np.array([10 + 4 * math.sin(0.7 * t) + 2 * math.sin(2.3 * t), -30 - 3 * math.sin(1.3 * t)])
def forces(self, t):
d = self.pos - np.array(self.anchor)
L = np.linalg.norm(d)
tension = -self.k * max(L - self.L0, 0) * d / L
gravity = np.array([0.0, self.m * self.g])
air = self.drag * (self.wind(t) - self.vel)
return gravity, tension, air
def step(self, t, dt):
self.vel += sum(self.forces(t)) / self.m * dt
self.pos += self.vel * dt
def draw(self, c):
line(c, *self.anchor, *self.pos, 15)
x, y = self.pos
diamond = (np.abs(X - x) / 3 + np.abs(Y - y) / 4) <= 1
fill(c, diamond, 5); fill(c, diamond & (X > x), 6)
for i in range(1, 6):
put_pixel(c, x - 1 - i * 0.4, y + 3 + i + math.sin(i + x) * 0.8, 9)
kite, dt, track = Kite(), 1 / 80, []
for n in range(80 * 12): # 12 seconds in steps of 1/80 s
kite.step(n * dt, dt)
track.append(kite.pos.copy())
track = np.array(track)
g, T, A = kite.forces(12.0)
print("position after 12 s:", track[-1].round(1), " string length:", round(float(np.linalg.norm(track[-1] - kite.anchor)), 1))
print("forces now gravity:", g.round(1), " tension:", T.round(1), " wind:", A.round(1), " total:", (g + T + A).round(1))
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.plot(np.arange(len(track)) * dt, track[:, 1], label="height y (pixels, down is +)")
ax.plot(np.arange(len(track)) * dt, track[:, 0], label="x (pixels)")
ax.set_xlabel("time (s)"); ax.legend(); ax.set_title("The kite rises, then rides the gusts"); plt.tight_layout(); plt.show()
position after 12 s: [54.5 20.1] string length: 96.2
forces now gravity: [ 0. 20.] tension: [-19.4 31.5] wind: [ 18.3 -48.8] total: [-1.2 2.8]

The kite starts at (40, 40) with no speed. In the first few seconds the wind lifts it (y falls, as y counts downwards) and pushes it right until the string goes taut; from then it hovers near the end of its string, swaying as the gusts rise and fall. The printout checks the physics at 12 seconds: the string is a little longer than its rest length of 90, so it is stretched and pulling; the tension points back towards the anchor (down and left, negative x and positive y); and the three forces nearly cancel, so the total is small. A kite at rest on a taut string is exactly a balance of these three forces.
5.2 A flock of pigeons¶
The pigeons of the Badshahi courtyard wheel together. Craig Reynolds (1987) showed that a flock needs no leader: each bird follows three local rules about the neighbours it can see (here, those within 25 pixels).
-
Separation: steer away from birds that are too close (closer than 5 pixels), more strongly the closer they are.
-
Alignment: steer towards the average heading of neighbours.
-
Cohesion: steer towards the average position of neighbours.
We add a fourth, a gentle pull towards a point above the mosque, so the flock stays on screen, and keep each bird's speed between 8 and 22 pixels a second. With numpy all birds are updated at once: d``[``i, j``] is the vector from bird j to bird i, and summing over j adds up the effect of all neighbours.
@dataclass
class Flock:
n: int = 14; seed: int = 3
def __post_init__(self):
rng = np.random.default_rng(self.seed)
self.p = rng.uniform([20, 10], [140, 40], (self.n, 2))
self.v = rng.normal(0, 8, (self.n, 2)) + [12, 0]
def step(self, dt):
d = self.p[:, None, :] - self.p[None, :, :]
dist = np.linalg.norm(d, axis=2) + np.eye(self.n) * 1e9 # a bird is not its own neighbour
near = dist < 25
cnt = near.sum(1, keepdims=True).clip(1)
cohesion = (near[..., None] * -d).sum(1) / cnt * 0.6
alignment = ((near @ self.v) / cnt - self.v) * 0.5
separation = ((dist < 5)[..., None] * d / dist[..., None] ** 2).sum(1) * 60
home = (np.array([80, 25]) - self.p) * 0.4
self.v += (cohesion + alignment + separation + home) * dt
speed = np.linalg.norm(self.v, axis=1, keepdims=True)
self.v *= np.clip(speed, 8, 22) / speed
self.p += self.v * dt
def spread(self):
d = np.linalg.norm(self.p[:, None] - self.p[None], axis=2)
return d[np.triu_indices(self.n, 1)].mean()
def heading_agreement(self):
u = self.v / np.linalg.norm(self.v, axis=1, keepdims=True)
return float(np.linalg.norm(u.mean(0))) # 1 = all fly the same way, 0 = random
def draw(self, c, frame=0):
for i, (x, y) in enumerate(self.p):
dy = -1 if (frame + i) % 4 < 2 else 1 # a two-frame wing flap
put_pixel(c, x, y, 15); put_pixel(c, x - 1, y + dy, 15); put_pixel(c, x + 1, y + dy, 15)
flock = Flock()
print(f"start: mean distance between birds {flock.spread():5.1f} px, heading agreement {flock.heading_agreement():.2f}")
for s in range(1, 201):
flock.step(1 / 20)
if s in (40, 200):
print(f"{s / 20:4.0f} s: mean distance between birds {flock.spread():5.1f} px, heading agreement {flock.heading_agreement():.2f}")
inside = ((flock.p >= 0) & (flock.p < [W, H])).all(1)
print(f"birds inside the canvas: {inside.sum()} of {flock.n}; flock centre at {flock.p.mean(0).round(0)}")
start: mean distance between birds 43.1 px, heading agreement 0.73
2 s: mean distance between birds 20.0 px, heading agreement 0.31
10 s: mean distance between birds 13.5 px, heading agreement 0.54
birds inside the canvas: 12 of 14; flock centre at [63. 7.]
The numbers show a flock forming. At the start the birds are scattered across the sky (43 pixels apart on average) and fairly aligned (0.73), because they were all given a push to the right. Within two seconds they have drawn together (20 pixels apart), and after ten they are packed within about 14 pixels of each other. Heading agreement first falls to 0.31 and then recovers to about a half: the pull towards the mosque turns the flock round, and birds on the inside of a turn point a different way from those outside, so the flock wheels over the dome, as courtyard pigeons do, rather than flying off in a line. The flock centre sits near (63, 7), above the central dome; two birds at the top edge are briefly off the canvas (12 of 14 inside), which is harmless because put_pixel ignores them. No rule mentions 'the flock': it emerges from each bird watching its neighbours, which is why this is called emergent behaviour.
5.3 Putting it together: the film¶
The film loop now has three clocks running together: the phase of the day, the physics time of the kite and birds, and the frame number for the wing flap. The kite takes four small physics steps per frame (sub-stepping) because springs need short steps to stay stable; the birds take one.
def film(n=240, fps=20, substeps=4):
kite, flock, frames = Kite(), Flock(), []
dt = 1 / fps
for f in range(n):
for s in range(substeps):
kite.step(f * dt + s * dt / substeps, dt / substeps)
flock.step(dt)
frames.append(render(-0.05 + 1.1 * f / n, extras=(lambda c, f=f: flock.draw(c, f), kite.draw)))
return frames
frames = film()
save_gif(frames, OUT / "badshahi_film.gif")
fig, axes = plt.subplots(1, 4, figsize=(12, 2.6))
for ax, i in zip(axes, (30, 90, 150, 225)):
show(frames[i], f"frame {i}", ax)
plt.tight_layout(); plt.show()
print(len(frames), "frames saved to", OUT / "badshahi_film.gif", f"({(OUT / 'badshahi_film.gif').stat().st_size / 1e6:.1f} MB)")

240 frames saved to data\badshahi_film.gif (0.4 MB)
Four frames from the twelve-second film. In frame 30 it is morning (phase 0.09): the sun is low on the left, the flock wheels over the central dome and the kite flies to the left on its taut string. In frame 90 (phase 0.36) the sun is high in the west, on the right. Frame 150 (phase 0.64) is deep night: the building has its night colours, the moon has risen and the birds, drawn in black, all but vanish against the sky, as real birds do. Frame 225 (phase 0.98) is the twilight before dawn, with the purple glow low in the sky; the kite still rides the wind. The whole film comes from about 250 lines of code and no drawn images.
5.4 What you have learned¶
-
A picture is an array of palette indices; a palette turns them into colours, and swapping palette entries recolours a scene at once.
-
Lines and circles are drawn with whole-number algorithms (Bresenham, midpoint); filled shapes are inside tests.
-
Architecture can be written as geometry: a Mughal arch is two overlapping discs, an onion dome a width that varies with height.
-
Dithering imitates more colours than the palette has.
-
A scene is a list of components, each a class with a few numbers and a draw method; symmetry halves the work.
-
Animation is drawing the scene as a function of time, many times a second.
-
Motion comes from forces and integration; semi-implicit Euler keeps energy where explicit Euler explodes.
-
Complex group behaviour can emerge from a few local rules.
The guide's later chapters draw the design as diagrams, rebuild the same picture in C as old graphics.h programs did, and turn the film into a game you control.