The goal is to watch walking evolve. Each creature is a soft body of nodes and springs, scored by how far its centre of mass travels to the right in 10 simulated seconds.
Let the run go, or press PAUSE to stop it and STEP to run one generation at a time. The FITNESS chart shows the champion's score rising as the population learns.
To test a design, build one in CREATURE LAB, press TEST, then DROP IN to add it to the population. MORE SETTINGS holds the population size, mutation, seed, gravity and friction.
A soft body is a creature made of nodes, point masses of 1 kg each, joined by springs. Some springs are muscles, whose natural length changes in a rhythm. Each creature is scored by its fitness, which is mainly the distance its centre of mass travels to the right in 10 simulated seconds. A genetic algorithm breeds each new generation from the best creatures: it keeps the fittest, combines pairs with crossover, and makes small random changes, called mutation. Nothing about walking is coded in. The gaits come from selection on the score.
A generation is one cycle over the population, 80 creatures by default. Each creature is simulated for 10 s at 240 steps per second and scored. The creatures are then grouped into species, groups of similar bodies, and the next population is bred from the species' shares of the slots. The first population is 80 random creatures. One cycle is Evolver.step: evaluate, speciate, summarise, then breed1.
function NEXT-GENERATION(population):
for each creature m: SIMULATE and score m # fitness, see FITNESS below
SPECIATE(population)
for each species s: # fitness sharing
share[s] ← mean over its members of (fitness − lowest + 1)
for each species s:
quota[s] ← its share of the P slots, rounded down, with leftovers to the largest parts
next ← empty list
for each species s with quota[s] > 0:
survivors ← the top half of s by fitness
add the best creature of s unchanged, if s is large or holds the best
while next has fewer than quota[s] children from s:
child ← crossover of two tournament winners, or a copy of one
add MUTATE(child) to next
return next
function NEXT-GENERATION(population, P):
for each creature m in population:
m.fitness, m.distance, m.exploded, m.fallen ← SIMULATE and FITNESS of m.genome
SPECIATE(population) # the species list and one representative each
lowest ← smallest fitness in population
best ← the creature with the highest fitness, the first one on ties
for each species s, in order:
s.share ← sum over members m of (m.fitness − lowest + 1) / |s|
total ← sum of s.share over all species
for each species s, in order:
exact ← P · s.share / total
quota[s] ← floor(exact)
remaining ← P − sum of quota
order ← species sorted by fractional part of exact, largest first, earlier species first on ties
for r from 0 to remaining − 1:
quota[order[r mod number of species]] ← quota[order[r mod number of species]] + 1
next ← empty list
for each species s, in order, with quota[s] > 0:
ranked ← members of s sorted by fitness, highest first, then lowest id
survivors ← the first max(1, ceil(0.5 · |s|)) creatures of ranked
made ← 0
if |s| ≥ 5 or best is a member of s: # elite
add a copy of ranked[0], unchanged, to next
made ← 1
while made < quota[s]:
if |survivors| ≥ 2 and RANDOM() < 0.6:
a ← TOURNAMENT(survivors, 3)
b ← TOURNAMENT(survivors, 3)
child ← CROSSOVER(a, b) # the fitter of a and b dominates
parents ← [a, b]
else:
a ← TOURNAMENT(survivors, 3)
child ← a copy of a.genome
parents ← [a]
add MUTATE(child, mutation rate) to next
made ← made + 1
the injected user creatures replace the last slots of next
while |next| > P: remove the last creature
while |next| < P: add a random creature
return next
The simple version is the cycle: score, group, share the slots, and breed. The full version adds the species representatives, the largest-remainder quotas, the elite rule, and the injection of user creatures. The random draws happen in the same order as in the JavaScript, which is what keeps a seed reproducible in both4.
A genome is the creature's recipe: a list of nodes and a list of springs. A node has x and y in metres, relative to the body. A spring has two end indices a and b, a rest length (its natural length, in metres), a stiffness k in newtons per metre, a damping c, a muscle flag, and for a muscle an amplitude, a frequency in hertz and a phase in radians. Each gene is rounded to the 0.0001 grid5.
A genome is written as one line of text, w1|x,y;…|a,b,rest,k,c,muscle,amp,freq,phase;…, and the decoder reads it back to the same genome, in JavaScript and in Python67. That is how a creature is shared.
Bodies have 2 to 12 nodes and at most 40 springs. Random creatures have 3 to 7 nodes8. The repair step runs after every operator9. It clamps each value to its range, drops self-links, out-of-range springs and duplicates, and keeps at least one spring and one muscle. Then it connects the body: while some node cannot be reached from node 0, the lowest-index unreached node is linked to the nearest reached node, and the lowest index wins a tie. The result is always connected, has a muscle, and has no duplicate springs.
Fitness is measured from the spawn point. A body is spawned with its centre at x = 2 m and its lowest node 0.45 m above the ground10. Its spine is the pair of nodes farthest apart at spawn. The spin σ is the total turning of that spine, summed step by step, so a body that tumbles accumulates a large spin. Each step adds the magnitude of the 2D cross product of the old and new unit spine vectors, which is the sine of the small turn11.
Here u_k is the unit vector along the spine after step k, and the cross product is in the plane. The sum is in radians, because the sine of a small turn is almost the turn itself. A body that spins less than one radian in total is not penalised.
Here \Delta x_c is the travel of the centre of mass in x, which is the mean node position, measured from the spawn point. The penalty is 1.0 m per radian of spin beyond the first radian. The speed bonus is 0.5 s times the mean forward speed over the second half: the centre of mass moves from x_{\mathrm{mid}} at 5 s to x_{\mathrm{end}} at 10 s. A body whose centre of mass drops below −1.5 m has fallen. Its travel and spin are then frozen where it fell, and it gets no speed bonus. A body whose state becomes NaN is scored 0 and marked exploded.
function FITNESS(creature):
if creature exploded:
return 0
travel ← x of the centre of mass at the end, minus x at spawn # frozen at the fall
penalty ← 1.0 · max(0, spin − 1) # spin in radians
bonus ← 0.5 s · mean forward speed of the second half, or 0 if it fell
return travel − penalty + bonus
function FITNESS(creature):
if creature exploded:
return 0
if creature fell: # centre of mass below −1.5 m at some step
distance ← travel at the step of the fall
spin used ← spin at the step of the fall
bonus ← 0
else:
distance ← x of the centre of mass at the end, minus x at spawn
spin used ← spin at the end
bonus ← 0.5 · (x at the end − x at the midpoint) / ((steps − midpoint) · DT)
# the midpoint is step 1200, so the second half is 5 s
penalty ← 1.0 · max(0, spin used − 1) # SPIN_PENALTY and SPIN_FREE
return distance − penalty + bonus
The simple version lists the three terms. The full version separates the fallen case from the standing case, because a fall freezes both the distance and the spin, and removes the bonus. A body that is on its feet keeps its bonus. The spin used in the penalty is the value at the fall for a fallen body, and the value at the end otherwise.
Example. The runner in the results travels 13.72 m in 10 s and scores 14.32, so its speed bonus minus its spin penalty is +0.60 m15.
Each spring applies Hooke's law along the line between its two nodes. The force grows in proportion to how far the spring is stretched past its rest length. A damper adds a force that depends on how fast the length changes, which removes energy. A muscle differs in one respect: its rest length is not constant. It swings around the rest length in a rhythm1617.
Here p_a and p_b are the positions of the two end nodes, and L is the current length. In the code L is raised to at least 10^{-9} m before the direction is taken, so the division never divides by zero. The unit vector n points from node a to node b. L_0(t) is the rest length. For a muscle it swings by \pm\mathrm{amp} times the rest length, at \mathrm{freq} hertz, with phase \phi in radians. The code writes the angular speed as 2\pi\,\mathrm{freq}, and it evaluates the sine with the polynomial described at the end of this section.
Here k is the stiffness and c the damping. The damping term is the rate of change of the length, (v_b - v_a)\cdot n, so it is positive while the spring is stretching. The spring pulls node a towards b when f is positive, and node b towards a by the same amount. Forces are summed per node over all springs. The arena colours each muscle by its tension: pink when it is stretched past its current rest length, cyan when it is squeezed short of it21.
Each node has mass 1 kg. Gravity pulls every node down with g = 9.8 m/s² by default, and a linear drag of 0.1 per second slows every node's velocity22.
Time moves forward in fixed steps of \Delta t = 1/240 s. Each step computes all forces from the positions at its start. It then updates the velocities, then the positions, then the ground contact. This is semi-implicit Euler: the new velocity is used to move the position in the same step2324.
Here F is the sum of the spring forces on the node, \hat{e}_y is the upward unit vector, and c_d = 0.1 per second is the drag. Gravity acts only in y. The drag factor is applied after the force and gravity. Each velocity component is then clamped to ±30 m/s. The clamp is counted, and it does not end a run by itself. The position moves with the clamped velocity.
The forces are summed in two passes: every a-end of every spring in spring order, then every b-end. The two languages use this same order, so their floating-point sums agree bit for bit. The sine inside the muscle is a polynomial in basic arithmetic, not a library call, for the same reason26.
Example. The check spring in the known limit below has stiffness 200 N/m and rest length 0.4 m, released 1.0 m long. Its stored energy is ½ · 200 · (1.0 − 0.4)² = 36 J, which the test reads as 35.8 J at its first step27.
The ground is a height function h(x) over the terrain (see Terrains below). A node that ends a step below the surface is moved back onto it. Its velocity into the surface is then reversed with the restitution e, which is the bounce, or stopped. The restitution is 0.2 by default and applies only to impacts faster than 0.5 m/s. Slower impacts are inelastic, so resting feet do not jitter28.
Here v_n and v_t are the normal and tangential velocity components relative to the surface, and s is the speed into the surface. e_r is the restitution, and e is the restitution that is actually used, which is zero for a slow impact. \lambda is the limit on the tangential change. Coulomb friction caps the tangential force at the friction coefficient times the normal force, and the code applies that cap to the tangential speed. The kinetic coefficient \mu_k is the friction setting, 0.8 by default. The static coefficient \mu_s is 1.2 times it. A foot whose sideways speed is within \mu_s\lambda sticks. A faster foot slides and loses \mu_k\lambda of its sideways speed in that contact.
The whole step, as the code runs it, is:
function SIMULATE-STEP(creature, t): # one step of 1/240 s
for each spring s = (a, b):
n ← unit vector from node a to node b
L₀ ← rest length of s at time t # a muscle swings, a passive spring does not
f ← k · (L − L₀) + c · (rate of change of L)
push node a along n with f, and node b with −f
for each node:
v ← (v + (F − g in y) · Δt) · (1 − drag · Δt)
x ← x + v · Δt
for each node below the ground:
put it back on the ground
reflect or stop its normal speed, and apply friction to its sideways speed
function SIMULATE-STEP(creature, t): # one step of Δt = 1/240 s
for each spring s = (a, b), in spring order:
dx, dy ← position of b − position of a
L ← sqrt(dx² + dy²), raised to 10⁻⁹ if smaller
n ← (dx, dy) / L
L₀ ← rest · (1 + amp · sin(2π · freq · t + phase)) if s is a muscle, else rest
f ← k · (L − L₀) + c · ((v_b − v_a) · n)
store f and n for s
for each spring s, in spring order:
F_a ← F_a + f_s · n_s # a-ends of all springs first
for each spring s, in spring order:
F_b ← F_b − f_s · n_s # then b-ends
for each node i:
v_x ← (v_x + F_x · Δt) · (1 − 0.1 · Δt)
v_y ← (v_y + (F_y − g) · Δt) · (1 − 0.1 · Δt)
for each component of v: clamp to ±30 and count each clamp
x_i ← x_i + v_x · Δt
y_i ← y_i + v_y · Δt
for each node i: # ground contact
h, slope ← GROUND(terrain, x_i)
if y_i < h:
y_i ← h
n ← (−slope, 1) / sqrt(1 + slope²)
t ← (1, slope) / sqrt(1 + slope²)
v_n ← v · n, v_t ← v · t
if v_n < 0: # moving into the ground
s ← −v_n
e ← restitution if s > 0.5 else 0
v_n ← −e · v_n
λ ← (1 + e) · s
if |v_t| ≤ 1.2 · friction · λ: v_t ← 0 # sticks
else: v_t ← v_t − friction · λ · sign(v_t) # slides
v ← v_n · n + v_t · t
if any position or velocity is not finite:
mark the creature exploded and freeze it
if the creature has not fallen: # bookkeeping
com ← mean node position, comY ← mean node y
spin ← spin + |u_prev × u_new|, then u_prev ← u_new
if comY < −1.5: record the fall: distance and spin are frozen
if step is the midpoint: com_mid ← com
The simple version is one step: spring forces, velocities, positions, then contact. The full version keeps the code's order, which is what makes the two languages agree: forces are summed in two passes, velocity clamps are counted, a non-finite state freezes the creature, and the centre of mass, spine and fall test are updated after contact. The bookkeeping is skipped for a creature that has already fallen.
Non-obvious. The ground check uses the positions after the velocity update. Contact changes only the velocity of a node that is moving into the ground, but it moves every node below the surface back onto it, even a node that is moving away.
Known limit: nodes pass through each other. There is no contact between nodes, so two nodes of one body can cross. A spring's force is k(L - L_0) along the line between its ends. When the ends cross, the length passes through zero and the direction n flips, so the force pushes the wrong way. Undamped, this adds energy. In the test with one spring (stiffness 200 N/m, rest length 0.4 m, released 1.0 m apart, with no gravity, no drag and no damping), the energy rose from 35.8 J to 59.6 J, a gain of 67%27. A spring whose length never comes near zero keeps its energy within about 5%. Drag damps the effect but does not prevent it. The physics has not been changed, because the evolved champions depend on it. A minimum-separation contact would fix it, and would need a new evolution run.
A parent is chosen by a tournament: three creatures are drawn at random, with replacement, from the survivors of the species, and the fittest wins. A tie keeps the earlier draw. The survivors are the top half of each species, rounded up and never fewer than one3334.
A child is made by crossover with probability 0.6, otherwise it is a copy of one tournament winner. Crossover needs at least two survivors. With fewer, the child is always a copy, and no random number is drawn for the crossover test35.
Crossover aligns the two parents by node index: node i of one parent is node i of the other. The dominant parent is the fitter one, and it sets the node count. A node that both parents have takes the other parent's position with probability 1/2, and otherwise the dominant parent's. A spring that both parents have, with the same pair of end nodes, takes the other parent's genes with probability 1/2. Springs that only the dominant parent has are kept. Springs that only the weaker parent has are dropped. This is the rule NEAT uses for disjoint genes. The child is then repaired.
Each node is jittered with probability rate/2, where rate is the mutation setting, 0.5 by default. The jitter moves x and y each by up to ±0.06 m. Each spring is jittered with the same probability: its rest length by up to ±10%, its stiffness and damping by up to ±20%, its amplitude by ±0.05, its frequency by up to ±20%, and its phase by ±0.5 rad. Every value is then clamped to its range36.
Five structural operators then each fire on their own chance, scaled by the rate37. A new node is added with chance 0.15 × rate, up to 12 nodes. It is placed within ±0.3 m of a random node, linked to that node, and linked to its nearest other node. A node is removed with chance 0.10 × rate, down to 2 nodes. A spring is added with chance 0.20 × rate, up to 40 springs, by trying up to 12 random pairs. A spring is removed with chance 0.15 × rate, keeping at least one. A spring is toggled between muscle and passive with chance 0.20 × rate. Every child, including a copy, is mutated and then repaired.
Speciation keeps new body plans alive. A new shape usually scores below the old champions at first, so without protection it would die out before it could improve. Creatures are grouped into species, and each species is bred with its own share of the slots.
Here n is the node count, s the spring count, and m = \text{muscles} / \text{springs} the muscle fraction. E is the set of end-node pairs of a creature's springs, and J is its Jaccard similarity with another creature, the share of pairs they have in common. A pair is counted once. Two creatures with the same topology have J = 1 and distance 0. When both sets are empty, J is set to 138.
Creatures are assigned in population order. Each joins the first species whose representative is less than 1.2 away, and a creature that matches none founds a new species. Species with no members are dropped. After the grouping, each species draws one random member as its representative for the next generation40.
A species' share of the slots comes from its members' fitness. Fitness can be negative, so each value is first shifted by the population's lowest fitness and by 1, which makes every shifted value at least 1. A species' share is the mean shifted fitness of its members. Dividing the sum by the species size means a large species does not get more slots just for being large.
Here f_i is the fitness of creature i, S_s the share of species s, and P the population size. Each species first gets the floor of its exact quota q_s. The slots left over are given one each to the species with the largest fractional parts, with earlier species first on ties. This is the largest-remainder method, and it makes the quotas sum to exactly P.
Within a species, the elite rule copies its best creature unchanged into the next population. The rule applies when the species has at least 5 members, or when it holds the best creature of the generation. Injected user creatures take the last slots of the next population, replacing children34.
| Parameter | What it does | Default |
|---|---|---|
| population | Creatures per generation (UI: 40, 80, 120). | 80 |
| duration | Simulated seconds per creature. | 10 s |
| time step | Fixed physics step (1/240 s). | 0.00417 s |
| mutation rate | Scales every mutation chance (UI slider). | 0.50 |
| crossover rate | Share of children made by crossover (the rest are copies). | 0.60 |
| tournament size | Candidates per parent pick, from the top half of a species. | 3 |
| survivors | Share of each species that may be parents, rounded up. | 50% |
| elite threshold | Species of at least this size keep their best unchanged, and so does the species holding the best creature. | 5 |
| species threshold | Compatibility distance below which creatures share a species. | 1.2 |
| gravity | Acceleration (UI: 2 to 20 m/s²). | 9.8 |
| friction | Kinetic coefficient (UI: 0.1 to 1.5); static is 1.2 times. | 0.80 |
| restitution | Bounce on impacts faster than 0.5 m/s. | 0.20 |
| drag | Linear drag on every node, per second. | 0.1 /s |
| velocity clamp | Largest velocity component allowed in a step, counted but not fatal. | 30 m/s |
| spring stiffness k | Random start range (N/m). Mutation keeps it within 20 to 600. | 60 to 250 |
| spring damping c | Random start range. Mutation keeps it within 0.2 to 10. | 0.5 to 6 |
| muscle amplitude | Random start range for the rest-length swing (fraction of rest). Mutation keeps it within 0 to 0.4. | 0.10 to 0.35 |
| muscle frequency | Random start range (Hz). Mutation keeps it within 0.4 to 4 Hz. | 0.8 to 3.0 |
| spin penalty | Metres lost per radian of spine rotation beyond 1 rad. Tumbling must cost more than it earns. | 1.00 |
| speed bonus | Seconds of mean forward speed in the second half added to the score (no bonus after a fall). | 0.5 s |
| fall line | Centre-of-mass height below which a body has fallen. | −1.5 m |
How these were chosen: The physics constants (step, drag, velocity clamp, restitution threshold, fall line) are standard for explicit simulation and were set by hand. None was tuned against the node-crossing limit. The genetic parameters (crossover 0.6, tournament 3, the top half as parents, elites of 5, threshold 1.2, the compatibility weights) follow the usual NEAT-style defaults and were set by hand. The mutation sizes and the speed bonus are judgement calls. The spin penalty began at 0.25 m per radian. A two-node body then tumbled sixteen turns for 99 m and scored 79, so the penalty went to 1.0043. The checks were the 300-generation runs below, and a friction sweep on the inchworm from 0.1 to 1.2, whose figures are quoted in the results file44. Gravity and friction are the UI's to change, and each change alters what evolves.
Flat: a plain floor. Hills: a ramp-in from 3 m to 5 m, then two sine waves with 0.35 m and 0.12 m amplitude. Steps: 0.15 m risers every 1.2 m from 3 m, up to eight. Gaps: 0.9 m holes every 3.2 m from 4 m, where a body that falls through is scored where it fell. The start is always 2 m from the origin, on flat ground45.
| Run | Gen 100 | Gen 200 | Gen 300 best | Champion |
|---|---|---|---|---|
| seed 1, flat | 2.13 | 5.74 | 14.32 | runner, generation 299: 13.7 m in 10 s, a one-hop skipper at 1.4 m/s |
| seed 2, flat | 1.67 | 7.17 | 11.70 | 10 nodes at generation 297: 12.9 m in 10 s, gait not characterised in the results |
| seed 3, flat | 2.20 | 4.82 | 14.07 | inchworm, generation 300: 15.3 m in 10 s, centre of mass never above 0.31 m |
| seed 1, hills | 1.26 | 2.55 | 3.14 | 8 nodes, uneven ground: 3.8 m |
Scores in metres, best of each run's population. The per-generation numbers are in the results file46, and the champion code of every generation is in the JSON47. Earlier runs (60 generations, spin penalty 0.25, no speed bonus) are kept in results/walkers_evolution_v1.md48.
Honest results: every flat run climbs from random flailing to bodies that cover 12 m or more in 10 s, with no explosions. The two best bodies are different body plans from different seeds: a 10-node skipper that gets off the ground once, and an 11-node low crawler that never leaves the ground by more than 0.31 m. Neither runs as a clean gait, and no champion hops three times, so there is no hopper preset. The best scores were still rising by about 3 m between generations 250 and 300, so these runs are not converged. The hills runs are much slower to learn. The full numbers and the study command are in the results file49.