Boids
The Boids algorithm was an artificial life program developed by Craig Reynolds in 1986 to model flocking behavior of birds. Complicated behaviors emerge from these three basic rules:
Separation: steer to avoid crowding local flock-mates
Alignment: steer towards the average heading of local flock-mates
Cohesion: steer to move toward the average position (center of mass) of local flock-mates
Basically, each boid considers all other boids within a set distance to be part of its flock, adjusting its own velocity to both match that of flock members in its cone of vision and attempting to avoid collisions.
I’ve implemented the algorithm in just a few lines of code and uploaded the sketch file to OpenProcessing, i.e. jsfiddle for Processing. Fork it and try enforcing different rules and see what emerges.
The source code is under 200 lines: