1#!/usr/bin/env python 2""" turtle-example-suite: 3 4 tdemo_planets_and_moon.py 5 6Gravitational system simulation using the 7approximation method from Feynman-lectures, 8p.9-8, using turtlegraphics. 9 10Example: heavy central body, light planet, 11very light moon! 12Planet has a circular orbit, moon a stable 13orbit around the planet. 14 15You can hold the movement temporarily by 16pressing the left mouse button with the 17mouse over the scrollbar of the canvas. 18 19""" 20from turtle import Shape, Turtle, mainloop, Vec2D as Vec 21from time import sleep 22 23G = 8 24 25class 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() 38 39class 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 68 69## create compound yellow/blue turtleshape for planets 70 71def 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() 87 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) 93 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!" 109 110if __name__ == '__main__': 111 main() 112 mainloop() 113