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