1
+ """
2
+ A deliberately bad implementation of
3
+ [Boids](http://dl.acm.org/citation.cfm?doid=37401.37406)
4
+ for use as an exercise on refactoring.
5
+
6
+ This code simulates the swarming behaviour of bird-like objects ("boids").
7
+ """
8
+
9
+ from matplotlib import pyplot as plt
10
+ from matplotlib import animation
11
+
12
+ import random
13
+
14
+ boids_x = [random .uniform (- 450 ,50.0 ) for x in range (50 )]
15
+ boids_y = [random .uniform (300.0 ,600.0 ) for x in range (50 )]
16
+ boid_x_velocities = [random .uniform (0 ,10.0 ) for x in range (50 )]
17
+ boid_y_velocities = [random .uniform (- 20.0 ,20.0 ) for x in range (50 )]
18
+ boids = (boids_x ,boids_y ,boid_x_velocities ,boid_y_velocities )
19
+
20
+ def update_boids (boids ):
21
+ xs ,ys ,xvs ,yvs = boids
22
+ # Fly towards the middle
23
+ for i in range (len (xs )):
24
+ for j in range (len (xs )):
25
+ xvs [i ]= xvs [i ]+ (xs [j ]- xs [i ])* 0.01 / len (xs )
26
+ for i in range (len (xs )):
27
+ for j in range (len (xs )):
28
+ yvs [i ]= yvs [i ]+ (ys [j ]- ys [i ])* 0.01 / len (xs )
29
+ # Fly away from nearby boids
30
+ for i in range (len (xs )):
31
+ for j in range (len (xs )):
32
+ if (xs [j ]- xs [i ])** 2 + (ys [j ]- ys [i ])** 2 < 100 :
33
+ xvs [i ]= xvs [i ]+ (xs [i ]- xs [j ])
34
+ yvs [i ]= yvs [i ]+ (ys [i ]- ys [j ])
35
+ # Try to match speed with nearby boids
36
+ for i in range (len (xs )):
37
+ for j in range (len (xs )):
38
+ if (xs [j ]- xs [i ])** 2 + (ys [j ]- ys [i ])** 2 < 10000 :
39
+ xvs [i ]= xvs [i ]+ (xvs [j ]- xvs [i ])* 0.125 / len (xs )
40
+ yvs [i ]= yvs [i ]+ (yvs [j ]- yvs [i ])* 0.125 / len (xs )
41
+ # Move according to velocities
42
+ for i in range (len (xs )):
43
+ xs [i ]= xs [i ]+ xvs [i ]
44
+ ys [i ]= ys [i ]+ yvs [i ]
0 commit comments