# L-26 MCS 260 Fri 11 Mar 2016 : orbiting.py

"""
Simulation of moon circulating the earth while the earth
is orbiting the sun.
"""

from math import cos, sin, pi
from turtle import Turtle

def three_turtles(radius):
    """
    Returns a tuple of three turtles,
    the first turtle is centered at (0, 0),
    the second turtle is centered at (2*radius, 0),
    the third turtle is at (3*radius, 0).
    """
    green = Turtle(shape='circle')
    green.color('green')
    green.penup()
    green.goto(3*radius, 0)
    red = Turtle(shape='circle')
    red.color('red')
    red.penup()
    red.goto(2*radius, 0)
    yellow = Turtle(shape='circle')
    yellow.color('yellow')
    return (yellow, red, green)

def circulate(trt, ctr, rad, agl):
    """
    Places the turtle trt at angle agl,
    on an ellipse with center at ctr, (rad, 0)
    is the rightmost point and (0, 2*rad/3) is
    the highest point on the ellipse.
    """
    xpt = ctr[0] + rad*cos(agl)
    ypt = ctr[1] + (2*rad/3)*sin(agl)
    trt.goto(xpt, ypt)

def pull_circulate(tr0, tr1, rad, agl):
    """
    Pulls tr1 in the direction of tr0
    so the distance between tr1 and tr0 is rad.
    Then places tr1 on a circle centered at
    the position tr0, with angle agl.
    """
    ctr = tr0.position()
    xpt = ctr[0] + rad*cos(agl)
    ypt = ctr[1] + rad*sin(agl)
    tr1.goto(xpt, ypt)

def main():
    """
    Displays one turtle orbiting another one.
    """
    from turtle import window_height, window_width
    wdh = min(window_height()/6, window_width()/6) - 20
    (distance, ndays) = (wdh, 365)
    day = 2*pi/ndays
    mth = 12*day
    (era, mna) = (day, mth)
    input('hit enter to begin')
    (sun, earth, moon) = three_turtles(distance)
    earth.pendown()
    moon.pendown()
    for _ in range(0, ndays):
        circulate(earth, (0, 0), 2*distance, era)
        pull_circulate(earth, moon, distance, mna)
        (era, mna) = (era + day, mna + mth)
    input('hit enter to exit')

main()
