Debian Codegraph @

Lib/turtledemo/planet_and_moon.py

raw
1 """turtledemo/planets_and_moon.py
2
3 Gravitational system simulation using the
4 approximation method from Feynman-lectures,
5 p.9-8, using turtlegraphics.
6
7 Example: heavy central body, light planet,
8 very light moon!
9 Planet has a circular orbit, moon a stable
10 orbit around the planet.
11
12 You can hold the movement temporarily by
13 pressing the left mouse button with the
14 mouse over the scrollbar of the canvas.
15
16 """
17 from turtle import Shape, Turtle, mainloop, Vec2D as Vec
18
19 G = 8
20
21 class GravSys(object):
22 def __init__(self):
23 self.planets = []
24 self.t = 0
25 self.dt = 0.01
26 def init(self):
27 for p in self.planets:
28 p.init()
29 def start(self):
30 for i in range(10000):
31 self.t += self.dt
32 for p in self.planets:
33 p.step()
34
35 class Star(Turtle):
36 def __init__(self, m, x, v, gravSys, shape):
37 Turtle.__init__(self, shape=shape)
38 self.penup()
39 self.m = m
40 self.setpos(x)
41 self.v = v
42 gravSys.planets.append(self)
43 self.gravSys = gravSys
44 self.resizemode("user")
45 self.pendown()
46 def init(self):
47 dt = self.gravSys.dt
48 self.a = self.acc()
49 self.v = self.v + 0.5*dt*self.a
50 def acc(self):
51 a = Vec(0,0)
52 for planet in self.gravSys.planets:
53 if planet != self:
54 v = planet.pos()-self.pos()
55 a += (G*planet.m/abs(v)**3)*v
56 return a
57 def step(self):
58 dt = self.gravSys.dt
59 self.setpos(self.pos() + dt*self.v)
60 if self.gravSys.planets.index(self) != 0:
61 self.setheading(self.towards(self.gravSys.planets[0]))
62 self.a = self.acc()
63 self.v = self.v + dt*self.a
64
65 ## create compound yellow/blue turtleshape for planets
66
67 def main():
68 s = Turtle()
69 s.reset()
70 s.getscreen().tracer(0,0)
71 s.ht()
72 s.pu()
73 s.fd(6)
74 s.lt(90)
75 s.begin_poly()
76 s.circle(6, 180)
77 s.end_poly()
78 m1 = s.get_poly()
79 s.begin_poly()
80 s.circle(6,180)
81 s.end_poly()
82 m2 = s.get_poly()
83
84 planetshape = Shape("compound")
85 planetshape.addcomponent(m1,"orange")
86 planetshape.addcomponent(m2,"blue")
87 s.getscreen().register_shape("planet", planetshape)
88 s.getscreen().tracer(1,0)
89
90 ## setup gravitational system
91 gs = GravSys()
92 sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle")
93 sun.color("yellow")
94 sun.shapesize(1.8)
95 sun.pu()
96 earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet")
97 earth.pencolor("green")
98 earth.shapesize(0.8)
99 moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet")
100 moon.pencolor("blue")
101 moon.shapesize(0.5)
102 gs.init()
103 gs.start()
104 return "Done!"
105
106 if __name__ == '__main__':
107 main()
108 mainloop()