import os
import math

#CREATE CLEAR CONSOLE COMMAND ON WINDOWS OR LINUX
try:
    clear = lambda: os.system('cls')
except:
    try:
        clear = lambda: os.system('clear')
    except:
        clear = lambda: print("\n---I WAS UNABLE TO DEFINE A CLEAR FUNCTION---\n")

def printgraphic(filename):
    clear()
    file = open(filename, 'r')
    file_contents = file.read()
    print(file_contents)
    file.close()

graphics = False

turns = 0
timeintervalsize = 0.001
playerturninterval = 1000

#ALL VALUES IN SI-UNITS
gravitationalconstant = 6.6743e-11
bodymass = 5.9722e+24
bodyradius = 6371.0e+3
atmosphereextent = 0.015 #percent of bodyradius
atmosphereheight = atmosphereextent*bodyradius #above surface
atmospheredensity = 1.225 #at surface level
scaleheight = 7800

shipmass = 5000.0
crashtolerance = 10.0
heattolerance = 1000.0
aerodynamiccoefficcient = 0.8
aerodynamicarea = 13.0
startingfuel = 10000.0
fuel = startingfuel
fuelpower = 1000.0
fuelwheight = 1.0


velocity = 0.0
acceleration = 0.0
burn= 0.0
heat = 0.0
airdensity = 0.0
airtemperature = 0
event = ""

aerodynamicacceleration = 0

if graphics:
    printgraphic("menu.txt")
input("PRESS ANY KEY TO START")
clear()

#INPUTNUMBER FUNCTION FOR CONVERTING STRING TO INT OR INTERPRETING "" AS 0
def inputnumber(text):
    value = input(text)
    if (value == ""):
        value = 0
    else:
        try:
            value = float(value)
        except:
            print("There was a problem, please try again...\n")
            value = inputnumber(text)
    return value

height = inputnumber("Please enter starting height above ground: ")
mass = shipmass + fuel*fuelwheight
input("Your maneuver can now begin.")

#MAIN FLIGHT CALCULATIONS LOOP
while (height > 0 and heat <= heattolerance):
        
    #PLAYER ACTION
    if (turns%playerturninterval==0):
        #REPORT
        #print(str(airdensity))
        #if (event == ""):
        #    clear()
        tryburn = inputnumber("HIGH " + '{:8.2f}'.format(round(height,3)) + " | VEL " + '{:8.2f}'.format(round(velocity,3)) +
                              " | FUEL " + '{:8.2f}'.format(round(fuel,3)) + " | HEAT " + '{:8.2f}'.format(round(heat,3)) + " | BURN ")

        #BURN
        if (tryburn >= fuel and fuel != 0):
            event = "FUEL OUT"
            burn = fuel
        else:
            burn = tryburn
            event = ""
        fuel -= burn
        mass -= burn*fuelwheight
        

    #ACCELERATION BY GRAVITY
    gravitationalacceleration = -gravitationalconstant*bodymass/(height+bodyradius)**2

    #ACCELERATION BY AERODYNAMICS
    if (height<=atmosphereheight):
        airdensity = atmospheredensity * 2.71828182845904523536**(-height/scaleheight)
        aerodynamicacceleration = (1/2*airdensity * velocity * abs(velocity) * aerodynamiccoefficcient * aerodynamicarea)/mass
    else:
        aerodynamicacceleration = 0
    
    #ACCELERATION BY THRUST
    burnacceleration = burn*fuelpower/mass
    
    #ACCELERATION
    acceleration = burnacceleration + gravitationalacceleration - aerodynamicacceleration
    
    #VELOCITY
    velocity += acceleration*timeintervalsize
    #HEIGHT
    height += velocity*timeintervalsize

    #HEAT
    heatingrate = 1.83e-4*(abs(velocity)**3)*math.sqrt(airdensity/aerodynamicarea)
    coolingrate = 0
    heat += (heatingrate-coolingrate)*timeintervalsize

    #DO TIME TICK
    turns += 1


#RATING CALCULATED HERE
try: #try to divide by velocity, catch for division by zero
    velocitybonus = abs(50*crashtolerance/velocity)
except:
    velocitybonus = 100
velocitybonus = (100,velocitybonus)[velocitybonus<100]

fuelbonus = fuel/startingfuel*100

rating = velocitybonus + fuelbonus
if (rating < 0):
    rating = 0 

#SCENARIOS
#HEATDEATH
if (heat > heattolerance):
    rating += 50
    if graphics:
        printgraphic("burned.txt")
    print("You burned up in the atmosphere with a final velocity of " + str(round(velocity,3)) + ", your rating is " + str(round(rating)))
#SOFTLANDING
elif (abs(velocity) <= crashtolerance):
    rating += 50
    if graphics:
        printgraphic("landed.txt")
    print("You achieved a soft landing with a final velocity of " + str(round(velocity,3)) + ", your rating is " + str(round(rating)))
#CRASHLANDING
else:
    rating -= 25
    if graphics:
        printgraphic("crashed.txt")
    print("You achieved a crashlanding with a final velocity of " + str(round(velocity,3)) + ", your rating is " + str(round(rating)))

#END
print("The end.")

ask = True
while (ask):
    control = input("Enter X to exit: ")
    if control == "x" or control == "X":
        ask = False
