Skip to content

Commit 7118c21

Browse files
committed
Add python improvement examples
1 parent 52898f7 commit 7118c21

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

improvement/boids.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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]

improvement/trees.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""This code produces a tree-like plot."""
2+
3+
from math import sin, cos
4+
from matplotlib import pyplot as plt
5+
s=1
6+
d=[[0,1,0]]
7+
plt.plot([0,0],[0,1])
8+
for i in range(5):
9+
n=[]
10+
for j in range(len(d)):
11+
n.append([d[j][0]+s*sin(d[j][2]-0.1), d[j][1]+s*cos(d[j][2]-0.1), d[j][2]-0.1])
12+
n.append([d[j][0]+s*sin(d[j][2]+0.1), d[j][1]+s*cos(d[j][2]+0.1), d[j][2]+0.1])
13+
plt.plot([d[j][0], n[-2][0]],[d[j][1], n[-2][1]])
14+
plt.plot([d[j][0], n[-1][0]],[d[j][1], n[-1][1]])
15+
d=n
16+
s*=0.6
17+
plt.savefig('tree.png')

0 commit comments

Comments
 (0)