Skip to content

Instantly share code, notes, and snippets.

@cbscribe
Created January 16, 2020 18:57
Show Gist options
  • Save cbscribe/e81cc9f685ac706baddcc2f038ced713 to your computer and use it in GitHub Desktop.
Save cbscribe/e81cc9f685ac706baddcc2f038ced713 to your computer and use it in GitHub Desktop.
Solar system simulation
# http://nssdc.gsfc.nasa.gov/planetary/factsheet/
import turtle
import math
turtle.bgcolor("black")
G = 6.67428e-11
AU = 149.6e9 # m
SCALE = 250 / (2 * AU) # pixels/AU
TIMESTEP = 24 * 3600 # s
sun = turtle.Pen()
sun.shape("circle")
sun.turtlesize(5)
sun.color("yellow")
sun.mass = 1.989e30 # kg
# Earth
earth = turtle.Pen()
earth.shape("circle")
earth.turtlesize(1)
earth.color("blue")
earth.up()
earth.px, earth.py = 1*AU, 0
earth.vx, earth.vy = 0, -29.8e3 # m/s
earth.goto(earth.px*SCALE, earth.py*SCALE)
# Mars
mars = turtle.Pen()
mars.shape("circle")
mars.turtlesize(0.6)
mars.color("red")
mars.up()
mars.px, mars.py = 1.5*AU, 0
mars.vx, mars.vy = 0, -24.1e3 # m/s
mars.goto(mars.px*SCALE, mars.py*SCALE)
planets = [earth, mars]
while True:
for planet in planets:
r = math.sqrt(planet.px**2 + planet.py**2)
a = G * sun.mass / r**2 # Thanks, Newton!
angle = math.atan2(-planet.py, -planet.px)
ax = a * math.cos(angle)
ay = a * math.sin(angle)
planet.vx += ax * TIMESTEP
planet.vy += ay * TIMESTEP
planet.px += planet.vx * TIMESTEP
planet.py += planet.vy * TIMESTEP
planet.goto(planet.px*SCALE, planet.py*SCALE)
planet.down()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment