' Projects animation of the sun, earth and moon.
' The moon orbits the earth, and the earth orbits the sun.
' The program uses clever trickery to determine
' the drawing order of the objects based on their y-coordinates.

' This program is free software: released under Creative Commons Zero (CC0) license
' by Svjatoslav Agejenko.
' Email: svjatoslav@svjatoslav.eu
' Homepage: http://www.svjatoslav.eu

' Changelog:
' 1999, Initial version
' 2024, Improved program readability


DECLARE SUB drawEarthMoonSystem (a2!, b2!, c2!)

DIM SHARED moonX
DIM SHARED moonY
SCREEN 7, , , 1

' Initialize the earth rotation angle
earthRotationAngle = 0

' Main loop to update and draw the objects
1 :
    SOUND 0, .5

    ' Increment the earthRotationAngle for every frame
    earthRotationAngle = earthRotationAngle + .01

    ' Calculate the x and y coordinates of the earth
    earthX = SIN(earthRotationAngle) * 100 + 100
    earthY = COS(earthRotationAngle) * 30 + 100

    ' Because we dont do proper earth, moon and sun Z-sorting,
    ' instead we implement clever trickery to determine, should
    ' sun be drawn before earth-moon system, or after.
    IF earthY >= 100 THEN
        ' Draw the sun
        CIRCLE (100, 100), 50, 12
        PAINT (100, 100), 12
    END IF

    ' Call the subroutine to draw the earth-moon system
    drawEarthMoonSystem earthX, earthY, (earthY - 70) / 2 + 2

    IF earthY < 100 THEN
        ' Draw the sun
        CIRCLE (100, 100), 50, 12
        PAINT (100, 100), 12
    END IF

    ' Copy the screen to buffer
    PCOPY 0, 1

    ' Clear the screen
    CLS

    ' Check if a key is pressed
    IF INKEY$ = "" THEN GOTO 1

' End the program
SYSTEM

SUB drawEarthMoonSystem (a2, b2, c2)
    moonSize = (b2 - 70) / 2 + 2

    ' Increment the moon's x and y coordinates
    moonX = moonX + .1
    moonY = moonY + .01

    ' Calculate the x and y offsets for the moon
    moonOffsetX = SIN(moonX) * moonSize * 2
    moonOffsetY = COS(moonX) * 10

    ' Because we don't do proper earth and moon Z-sorting,
    ' instead we implement clever trickery to determine, should
    ' earth be drawn before moon or after.
    IF moonOffsetY > 0 THEN
        ' Draw the earth
        CIRCLE (a2, b2), c2, 1
        PAINT (a2, b2), 1
    END IF

    ' Calculate the x and y coordinates of the moon and draw it
    moonXCoord = moonOffsetX + a2
    moonYCoord = moonOffsetY + b2
    CIRCLE (moonXCoord, moonYCoord), ((moonOffsetY + 20) * moonSize) \ 50, 14
    PAINT (moonXCoord, moonYCoord), 14

    IF moonOffsetY <= 0 THEN
        ' Draw the earth
        CIRCLE (a2, b2), c2, 1
        PAINT (a2, b2), 1
    END IF
END SUB

