Example #1
0
    def __init__(self):

        #loading music
        mixer.music.load('Music/bg.mp3')
        mixer.music.play(-1)

        #setting background and display
        self.background_colour = (0, 0, 0)
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

        #getting screen width and height
        self.screen_width = self.screen.get_width()
        self.screen_height = self.screen.get_height()

        #calling classes
        self.spacecraft = Spacecraft(self)
        self.bg_stars = Distant_Stars(self)
        self.fl_objs = Flying_Object_Collection(self)

        self.score = 0
        self.level = 1
        self.spawn_freq_factor = 4500

        self.score_font = pygame.font.SysFont("Calibri", 30)

        #making event for trigering the time for respawn
        self.SPAWN = pygame.USEREVENT
        pygame.time.set_timer(self.SPAWN, self.spawn_freq_factor)

        #setting FPS to make sure smooth movement of game
        self.FPS = 360
        self.clock = pygame.time.Clock()
Example #2
0
 def __init__(self, sp: Spacecraft):
     """ travel to mars from earth
     using the Hohmann Transfer Orbit """
     self.spacecraft = sp
     self.mission = sp.get_mission()
     self.sun = sp.solar_system.get_the_sun()
     self.init()
     self.velocity = sp.velocity
     self.range = 0
Example #3
0
    def __init__(self):
        """
        Initializes the list with parcels and the spacecrafts.
        """
        global current_solution

        # load the list with all parcel objects
        self.all_parcels = self.load_parcels(INPUT)

        # make list with all unpacked parcels (only ID)
        self.unpacked_parcels = []
        for p in self.all_parcels:
            self.unpacked_parcels.append(p.ID)

        # load spacecraft objects
        self.spacecrafts = []
        self.spacecrafts.append(Spacecraft('Cygnus', 2000, 18.9, 7400, \
                                390000000, 0.73, 'USA'))
        self.spacecrafts.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                                175000000, 0.74, 'Russia'))
        self.spacecrafts.append(Spacecraft('Kounotori', 5200, 14, 10500, \
                                420000000, 0.71, 'Japan'))
        self.spacecrafts.append(Spacecraft('Dragon', 6000, 10, 12200, \
                                347000000, 0.72, 'USA'))

        if INPUT == INPUT_3:
            self.spacecrafts.append(Spacecraft('TianZhou', 6500, 15, 13500, \
                                    412000000, 0.75, 'China'))
            self.spacecrafts.append(Spacecraft('Verne ATV', 7500, 48, 20500, \
                                    1080000000, 0.72, 'Europe'))
Example #4
0
def main():
    # Define 6U CubeSat mass, dimensions, drag coefficient
    sc_mass = 8
    sc_dim = [226.3e-3, 100.0e-3, 366.0e-3]
    J = 1 / 12 * sc_mass * np.diag([
        sc_dim[1]**2 + sc_dim[2]**2, sc_dim[0]**2 + sc_dim[2]**2,
        sc_dim[0]**2 + sc_dim[1]**2
    ])
    sc_dipole = np.array([0, 0.018, 0])

    # Define two `PDController` objects—one to represent no control and one
    # to represent PD control with the specified gains
    no_controller = PDController(k_d=np.diag([0, 0, 0]),
                                 k_p=np.diag([0, 0, 0]))
    controller = PDController(k_d=np.diag([.01, .01, .01]),
                              k_p=np.diag([.1, .1, .1]))

    # Northrop Grumman LN-200S Gyros
    gyros = Gyros(bias_stability=1, angular_random_walk=0.07)
    perfect_gyros = Gyros(bias_stability=0, angular_random_walk=0)

    # NewSpace Systems Magnetometer
    magnetometer = Magnetometer(resolution=10e-9)
    perfect_magnetometer = Magnetometer(resolution=0)

    # Adcole Maryland Aerospace MAI-SES Static Earth Sensor
    earth_horizon_sensor = EarthHorizonSensor(accuracy=0.25)
    perfect_earth_horizon_sensor = EarthHorizonSensor(accuracy=0)

    # Sinclair Interplanetary 60 mNm-sec RXWLs
    actuators = Actuators(rxwl_mass=226e-3,
                          rxwl_radius=0.5 * 65e-3,
                          rxwl_max_torque=20e-3,
                          rxwl_max_momentum=0.18,
                          noise_factor=0.03)
    perfect_actuators = Actuators(rxwl_mass=226e-3,
                                  rxwl_radius=0.5 * 65e-3,
                                  rxwl_max_torque=np.inf,
                                  rxwl_max_momentum=np.inf,
                                  noise_factor=0.0)

    # define some orbital parameters
    mu_earth = 3.986004418e14
    R_e = 6.3781e6
    orbit_radius = R_e + 400e3
    orbit_w = np.sqrt(mu_earth / orbit_radius**3)
    period = 2 * np.pi / orbit_w

    # define a function that returns the inertial position and velocity of the
    # spacecraft (in m & m/s) at any given time
    def position_velocity_func(t):
        r = orbit_radius / np.sqrt(2) * np.array([
            -np.cos(orbit_w * t),
            np.sqrt(2) * np.sin(orbit_w * t),
            np.cos(orbit_w * t),
        ])
        v = orbit_w * orbit_radius / np.sqrt(2) * np.array([
            np.sin(orbit_w * t),
            np.sqrt(2) * np.cos(orbit_w * t),
            -np.sin(orbit_w * t),
        ])
        return r, v

    # compute the initial inertial position and velocity
    r_0, v_0 = position_velocity_func(0)

    # define the body axes in relation to where we want them to be:
    # x = Earth-pointing
    # y = pointing along the velocity vector
    # z = normal to the orbital plane
    b_x = -normalize(r_0)
    b_y = normalize(v_0)
    b_z = cross(b_x, b_y)

    # construct the nominal DCM from inertial to body (at time 0) from the body
    # axes and compute the equivalent quaternion
    dcm_0_nominal = np.stack([b_x, b_y, b_z])
    q_0_nominal = dcm_to_quaternion(dcm_0_nominal)

    # compute the nominal angular velocity required to achieve the reference
    # attitude; first in inertial coordinates then body
    w_nominal_i = 2 * np.pi / period * normalize(cross(r_0, v_0))
    w_nominal = np.matmul(dcm_0_nominal, w_nominal_i)

    # provide some initial offset in both the attitude and angular velocity
    q_0 = quaternion_multiply(
        np.array(
            [0, np.sin(2 * np.pi / 180 / 2), 0,
             np.cos(2 * np.pi / 180 / 2)]), q_0_nominal)
    w_0 = w_nominal + np.array([0.005, 0, 0])

    # define a function that will model perturbations
    def perturb_func(satellite):
        return (satellite.approximate_gravity_gradient_torque() +
                satellite.approximate_magnetic_field_torque())

    # define a function that returns the desired state at any given point in
    # time (the initial state and a subsequent rotation about the body x, y, or
    # z axis depending upon which nominal angular velocity term is nonzero)
    def desired_state_func(t):
        if w_nominal[0] != 0:
            dcm_nominal = np.matmul(t1_matrix(w_nominal[0] * t), dcm_0_nominal)
        elif w_nominal[1] != 0:
            dcm_nominal = np.matmul(t2_matrix(w_nominal[1] * t), dcm_0_nominal)
        elif w_nominal[2] != 0:
            dcm_nominal = np.matmul(t3_matrix(w_nominal[2] * t), dcm_0_nominal)
        return dcm_nominal, w_nominal

    # construct three `Spacecraft` objects composed of all relevant spacecraft
    # parameters and objects that resemble subsystems on-board
    # 1st Spacecraft: no controller
    # 2nd Spacecraft: PD controller with perfect sensors and actuators
    # 3rd Spacecraft: PD controller with imperfect sensors and actuators

    satellite_no_control = Spacecraft(
        J=J,
        controller=no_controller,
        gyros=perfect_gyros,
        magnetometer=perfect_magnetometer,
        earth_horizon_sensor=perfect_earth_horizon_sensor,
        actuators=perfect_actuators,
        q=q_0,
        w=w_0,
        r=r_0,
        v=v_0)

    satellite_perfect = Spacecraft(
        J=J,
        controller=controller,
        gyros=perfect_gyros,
        magnetometer=perfect_magnetometer,
        earth_horizon_sensor=perfect_earth_horizon_sensor,
        actuators=perfect_actuators,
        q=q_0,
        w=w_0,
        r=r_0,
        v=v_0)

    satellite_noise = Spacecraft(J=J,
                                 controller=controller,
                                 gyros=gyros,
                                 magnetometer=magnetometer,
                                 earth_horizon_sensor=earth_horizon_sensor,
                                 actuators=actuators,
                                 q=q_0,
                                 w=w_0,
                                 r=r_0,
                                 v=v_0)

    # Simulate the behavior of all three spacecraft over time
    simulate(satellite=satellite_no_control,
             nominal_state_func=desired_state_func,
             perturbations_func=perturb_func,
             position_velocity_func=position_velocity_func,
             stop_time=6000,
             tag=r"(No Control)")

    simulate(satellite=satellite_perfect,
             nominal_state_func=desired_state_func,
             perturbations_func=perturb_func,
             position_velocity_func=position_velocity_func,
             stop_time=6000,
             tag=r"(Perfect Estimation \& Control)")

    simulate(satellite=satellite_noise,
             nominal_state_func=desired_state_func,
             perturbations_func=perturb_func,
             position_velocity_func=position_velocity_func,
             stop_time=6000,
             tag=r"(Actual Estimation \& Control)")
Example #5
0
def main():
    """main call function"""
    craft = Spacecraft()
    goal = Spacecraft()
    craft.add_module("MOS1_MOT")
    craft.add_module("MOS2_MOT")
    craft.add_module("MOS3_REC")
    craft.add_module("MOS4_REC")
    craft.add_module("MOS5_TAN")
    craft.add_module("MOS6_SOL")
    craft.add_module("MOS7_RAD")

    goal.add_module("MOS1_MOT")
    goal.add_module("MOS2_MOT")
    goal.add_module("MOS3_REC")
    goal.add_module("MOS4_REC")
    goal.add_module("MOS5_TAN")
    goal.add_module("MOS6_SOL")
    goal.add_module("MOS7_RAD")

    craft.connect("MOS1_MOT", 2, "MOS2_MOT", 0)
    craft.connect("MOS2_MOT", 1, "MOS3_REC", 3)
    craft.connect("MOS2_MOT", 2, "MOS4_REC", 0)
    craft.connect("MOS4_REC", 1, "MOS5_TAN", 3)
    craft.connect("MOS3_REC", 2, "MOS5_TAN", 0)
    craft.connect("MOS5_TAN", 1, "MOS6_SOL", 3)
    craft.connect("MOS2_MOT", 3, "MOS7_RAD", 1)

    goal.connect("MOS1_MOT", 2, "MOS2_MOT", 0)
    goal.connect("MOS2_MOT", 2, "MOS3_REC", 0)
    goal.connect("MOS1_MOT", 1, "MOS4_REC", 3)
    goal.connect("MOS4_REC", 2, "MOS5_TAN", 0)
    goal.connect("MOS5_TAN", 2, "MOS6_SOL", 0)
    goal.connect("MOS5_TAN", 1, "MOS7_RAD", 3)
    goal.connect("MOS2_MOT", 1, "MOS5_TAN", 3)
    goal.connect("MOS3_REC", 1, "MOS6_SOL", 3)

    craft.goal = goal
    craft.export_to_file("test")
    craft.goal.export_to_file("goal")
    # order = craft.melt()
    craft.display()
    craft.goal.display()
Example #6
0
This script contains the different versions (functions)
of the random algorithms
"""

from spacefreight import SpaceFreight
from spacecraft import Spacecraft
from solution import Solution
from helpers import *
import random
import numpy as np
import copy

spacefreight = SpaceFreight()

spacecrafts_list = []
spacecrafts_list.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                            175000000, 0.74, 'Russia'))
spacecrafts_list.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                            175000000, 0.74, 'Russia'))
spacecrafts_list.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                            175000000, 0.74, 'Russia'))
spacecrafts_list.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                            175000000, 0.74, 'Russia'))
spacecrafts_list.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                            175000000, 0.74, 'Russia'))
spacecrafts_list.append(Spacecraft('Progress', 2400, 7.6, 7020, \
                            175000000, 0.74, 'Russia'))
spacecrafts_list.append(Spacecraft('Dragon', 6000, 10, 12200, \
                            347000000, 0.72, 'USA'))


def random_algorithm():
Example #7
0
def cubeSat():
    viking = Spacecraft()
    viking1 = Spacecraft()
    Earth = Planet(spacecraft=viking, configuration="earth")
    Moon = Planet(spacecraft=viking, configuration="moon")
    Sun = Planet(spacecraft=viking, configuration="sun")
    solarsystem = solarSystem(spacecraft=viking)
    solarsystem.addPlanet(Earth)
    solarsystem.addPlanet(Moon)
    #solarsystem.addPlanet(Sun)

    ## CubeSat Trajectory
    xpos = -1.501540312811781e4
    ypos = -2.356897680091111e4
    zpos = 2.241504923500546e3
    xvel = -4.855378922082240e-1
    yvel = -5.048763191594085e0
    zvel = -8.799883161637991e-1

    # viking.leapFrog(solarsystem, xpos, ypos, zpos, xvel, yvel, zvel\
    # 	,75,10612)
    solarsystem.addPlanet(Sun)
    viking1.leapFrog(solarsystem, xpos, ypos, zpos, xvel, yvel, zvel\
     ,75,10612)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    # ax.plot(numpy.array(viking.xarray),\
    # 	numpy.array(viking.yarray),\
    # 	numpy.array(viking.zarray),\
    # 	label="Sim Trajectory - Sans Sun")
    ax.plot(numpy.array(viking1.xarray),\
     numpy.array(viking1.yarray),\
     numpy.array(viking1.zarray),\
     label="Sim Trajectory - With Sun")
    # ax.plot(numpy.array(config.stkscx5_2x_sans_sun),\
    # 	numpy.array(config.stkscy5_2x_sans_sun),\
    # 	numpy.array(config.stkscz5_2x_sans_sun),\
    # 	label="STK Trajectory - Sans Sun")
    ax.plot(numpy.array(config.stkscx5_2x_with_sun),\
     numpy.array(config.stkscy5_2x_with_sun),\
     numpy.array(config.stkscz5_2x_with_sun),\
     label="STK Trajectory - With Sun")
    ax.plot(numpy.array(config.stkscx5_2x_all),\
     numpy.array(config.stkscy5_2x_all),\
     numpy.array(config.stkscz5_2x_all),\
     label="STK Trajectory - All Effects")
    ax.plot(config.moonx[:config.index],\
     config.moony[:config.index],config.moonz[:config.index],\
     label="Moon Position")

    # u = numpy.linspace(0, 2 * numpy.pi, 100)
    # v = numpy.linspace(0, numpy.pi, 100)
    # x = Earth.radius * numpy.outer(numpy.cos(u), numpy.sin(v))
    # y = Earth.radius * numpy.outer(numpy.sin(u), numpy.sin(v))
    # z = Earth.radius * numpy.outer(numpy.ones(numpy.size(u)), numpy.cos(v))

    # xm = Moon.radius * numpy.outer(numpy.cos(u), numpy.sin(v))\
    #  + config.moonx[config.index]
    # ym = Moon.radius * numpy.outer(numpy.cos(u), numpy.sin(v))\
    #  + config.moony[config.index]
    # zm = Moon.radius * numpy.outer(numpy.cos(u), numpy.sin(v))\
    #  + config.moonz[config.index]

    # ax.plot_surface(xm,ym,zm, rstride=4, cstride=4,color='r',\
    # 	label="Moon")
    # ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='r',\
    #  label="Earth")

    plt.title("Passive Trajectory")
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    # plotx=[]
    # ploty=[]
    # plotz=[]
    plotx1 = []
    ploty1 = []
    plotz1 = []
    for i in range(len(viking1.xarray)):
        if i % 4 == 0:
            # plotx.extend([viking.xarray[i]])
            # ploty.extend([viking.yarray[i]])
            # plotz.extend([viking.zarray[i]])
            plotx1.extend([viking1.xarray[i]])
            ploty1.extend([viking1.yarray[i]])
            plotz1.extend([viking1.zarray[i]])

    # viking.xarray=plotx
    # viking.yarray=ploty
    # viking.zarray=plotz
    viking1.xarray = plotx1
    viking1.yarray = ploty1
    viking1.zarray = plotz1

    # plt.plot(viking.xarray, label="sim sans sun")
    plt.plot(viking1.xarray, label="sim with sun")
    #plt.plot(config.stkscx5_2x_sans_sun,label="stk sans sun")
    plt.plot(config.stkscx5_2x_with_sun, label="stk with sun")
    plt.plot(config.stkscx5_2x_all, label="stk, all effects")
    plt.title('Spacecraft x position')
    plt.xlabel('Time (9 days)')
    plt.ylabel('Spacecraft position (km)')
    plt.legend(loc='upper left')
    plt.show()

    # plt.plot(viking.yarray, label="sim sans sun")
    plt.plot(viking1.yarray, label="sim with sun")
    #plt.plot(config.stkscy5_2x_sans_sun,label="stk sans sun")
    plt.plot(config.stkscy5_2x_with_sun, label="stk with sun")
    plt.plot(config.stkscy5_2x_all, label="stk, all effects")
    plt.xlabel('Time (9 days)')
    plt.ylabel('Spacecraft position (km)')
    plt.title('Spacecraft y position')
    plt.legend(loc='lower left')
    plt.show()

    # plt.plot(viking.zarray, label="sim sans sun")
    plt.plot(viking1.zarray, label="sim with sun")
    #plt.plot(config.stkscz5_2x_sans_sun,label="stk sans sun")
    plt.plot(config.stkscz5_2x_with_sun, label="stk with sun")
    plt.plot(config.stkscz5_2x_all, label="stk, all effects")
    plt.xlabel('Time (9 days)')
    plt.ylabel('Spacecraft position (km)')
    plt.title('Spacecraft z position')
    plt.legend(loc='upper left')
    plt.show()

    # plt.plot(numpy.array(viking.xarray)[:2652]-\
    # 	numpy.array(config.stkscx5_2x_sans_sun)[:2652],\
    # 	 label="error in km - sans sun sim & sans sun STK")
    # plt.plot(numpy.array(viking.xarray)[:2652]-\
    # 	 numpy.array(config.stkscx5_2x_with_sun)[:2652],\
    # 	 label="error in km - sans sun sim & with sun STK")
    # plt.plot(numpy.array(viking1.xarray)[:2652]-\
    # 	numpy.array(config.stkscx5_2x_sans_sun)[:2652],\
    # 	 label="error in km - with sun sim & sans sun STK")
    plt.plot(numpy.array(viking1.xarray)[:2652]-\
      numpy.array(config.stkscx5_2x_with_sun)[:2652],\
      label="error in km - with sun sim & with sun STK")
    # plt.plot(numpy.array(viking.xarray)[:2652]-\
    # 	numpy.array(config.stkscx5_2x_all)[:2652],\
    # 	 label="error in km - sans sun sim & all effects STK")
    # plt.plot(numpy.array(viking.xarray)[:2652]-\
    # 	 numpy.array(config.stkscx5_2x_all)[:2652],\
    # 	 label="error in km - sans sun sim & all effects STK")
    # plt.plot(numpy.array(viking1.xarray)[:2652]-\
    # 	numpy.array(config.stkscx5_2x_all)[:2652],\
    # 	 label="error in km - with sun sim & all effects STK")
    plt.plot(numpy.array(viking1.xarray)[:2652]-\
      numpy.array(config.stkscx5_2x_all)[:2652],\
      label="error in km - with sun sim & all effects STK")

    plt.title('Accumulated Error between Python and STK 9 days - x')
    plt.xlabel('Time (9 days)')
    plt.ylabel('Error in km')
    plt.legend(loc='lower left')
    plt.show()

    # plt.plot(numpy.array(viking.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_sans_sun)[:2652],\
    # 	 label="error in km - sans sun sim & sans sun STK")
    # plt.plot(numpy.array(viking.yarray)[:2652]-\
    # 	 numpy.array(config.stkscy5_2x_with_sun)[:2652],\
    # 	 label="error in km - sans sun sim & with sun")
    # plt.plot(numpy.array(viking1.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_sans_sun)[:2652],\
    # 	 label="error in km - with sun sim & sans sun STK")
    plt.plot(numpy.array(viking1.yarray)[:2652]-\
      numpy.array(config.stkscy5_2x_with_sun)[:2652],\
      label="error in km - with sun sim & with sun")
    # plt.plot(numpy.array(viking.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_all)[:2652],\
    # 	 label="error in km - sans sun sim & all effects STK")
    # plt.plot(numpy.array(viking.yarray)[:2652]-\
    # 	 numpy.array(config.stkscy5_2x_all)[:2652],\
    # 	 label="error in km - sans sun sim & all effects STK")
    # plt.plot(numpy.array(viking1.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_all)[:2652],\
    # 	 label="error in km - with sun sim & all effects STK")
    plt.plot(numpy.array(viking1.yarray)[:2652]-\
      numpy.array(config.stkscy5_2x_all)[:2652],\
      label="error in km - with sun sim & all effects STK")
    plt.xlabel('Time (9 days)')
    plt.ylabel('Error in km')
    plt.title('Accumulated Error between Python and STK 9 days - y')
    plt.legend(loc='lower left')
    plt.show()

    # plt.plot(numpy.array(viking.zarray)[:2652]-\
    # 	numpy.array(config.stkscz5_2x_sans_sun)[:2652],\
    # 	 label="error in km - sans sun sim & sans sun STK")
    # plt.plot(numpy.array(viking.zarray)[:2652]-\
    # 	 numpy.array(config.stkscz5_2x_with_sun)[:2652],\
    # 	 label="error in km - sans sun sim & with sun STK")
    # plt.plot(numpy.array(viking1.zarray)[:2652]-\
    # 	numpy.array(config.stkscz5_2x_sans_sun)[:2652],\
    # 	 label="error in km - with sun sim & sans sun STK")
    plt.plot(numpy.array(viking1.zarray)[:2652]-\
      numpy.array(config.stkscz5_2x_with_sun)[:2652],\
      label="error in km - with sun sim & with sun STK")
    # plt.plot(numpy.array(viking.zarray)[:2652]-\
    # 	numpy.array(config.stkscz5_2x_all)[:2652],\
    # 	 label="error in km - sans sun sim & all effects STK")
    # plt.plot(numpy.array(viking.zarray)[:2652]-\
    # 	 numpy.array(config.stkscz5_2x_all)[:2652],\
    # 	 label="error in km - sans sun sim & all effects STK")
    # plt.plot(numpy.array(viking1.zarray)[:2652]-\
    # 	numpy.array(config.stkscz5_2x_all)[:2652],\
    # 	 label="error in km - with sun sim & all effects STK")
    plt.plot(numpy.array(viking1.zarray)[:2652]-\
      numpy.array(config.stkscz5_2x_all)[:2652],\
      label="error in km - with sun sim & all effects STK")
    plt.xlabel('Time (9 days)')
    plt.ylabel('Error in km')
    plt.title('Accumulated Error between Python and STK 9 days - z')
    plt.legend(loc='lower left')
    plt.show()

    # plt.plot(numpy.sqrt((numpy.array(viking.xarray)[:2652]\
    # 	-numpy.array(config.stkscx5_2x_sans_sun)[:2652])**2 + \
    # (numpy.array(viking.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_sans_sun)[:2652])**2 +\
    # 	 (numpy.array(viking.zarray)[:2652]-\
    # 	 	numpy.array(config.stkscz5_2x_sans_sun)[:2652])**2)\
    # ,label="Total Accumulated Error Sans Sun Sim & Sans Sun STK- km")
    # plt.plot(numpy.sqrt((numpy.array(viking.xarray)[:2652]\
    # 	-numpy.array(config.stkscx5_2x_with_sun)[:2652])**2 + \
    # (numpy.array(viking.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_with_sun)[:2652])**2 +\
    # 	 (numpy.array(viking.zarray)[:2652]-\
    # 	 	numpy.array(config.stkscz5_2x_with_sun)[:2652])**2)\
    # ,label="Total Accumulated Error Sans Sun Sim & With Sun STK- km")
    # plt.plot(numpy.sqrt((numpy.array(viking1.xarray)[:2652]\
    # 	-numpy.array(config.stkscx5_2x_sans_sun)[:2652])**2 + \
    # (numpy.array(viking1.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_sans_sun)[:2652])**2 +\
    # 	 (numpy.array(viking1.zarray)[:2652]-\
    # 	 	numpy.array(config.stkscz5_2x_sans_sun)[:2652])**2)\
    # ,label="Total Accumulated Error With Sun Sim & Sans Sun STK- km")
    plt.plot(numpy.sqrt((numpy.array(viking1.xarray)[:2652]\
     -numpy.array(config.stkscx5_2x_with_sun)[:2652])**2 + \
    (numpy.array(viking1.yarray)[:2652]-\
     numpy.array(config.stkscy5_2x_with_sun)[:2652])**2 +\
      (numpy.array(viking1.zarray)[:2652]-\
       numpy.array(config.stkscz5_2x_with_sun)[:2652])**2)\
    ,label="Total Accumulated Error With Sun Sim & With Sun STK- km")
    # plt.plot(numpy.sqrt((numpy.array(viking.xarray)[:2652]\
    # 	-numpy.array(config.stkscx5_2x_all)[:2652])**2 + \
    # (numpy.array(viking.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_all)[:2652])**2 +\
    # 	 (numpy.array(viking.zarray)[:2652]-\
    # 	 	numpy.array(config.stkscz5_2x_all)[:2652])**2)\
    # ,label="Total Accumulated Error Sans Sun Sim & All Effects STK- km")
    # plt.plot(numpy.sqrt((numpy.array(viking.xarray)[:2652]\
    # 	-numpy.array(config.stkscx5_2x_all)[:2652])**2 + \
    # (numpy.array(viking.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_all)[:2652])**2 +\
    # 	 (numpy.array(viking.zarray)[:2652]-\
    # 	 	numpy.array(config.stkscz5_2x_all)[:2652])**2)\
    # ,label="Total Accumulated Error Sans Sun Sim & All Effects STK- km")
    # plt.plot(numpy.sqrt((numpy.array(viking1.xarray)[:2652]\
    # 	-numpy.array(config.stkscx5_2x_all)[:2652])**2 + \
    # (numpy.array(viking1.yarray)[:2652]-\
    # 	numpy.array(config.stkscy5_2x_all)[:2652])**2 +\
    # 	 (numpy.array(viking1.zarray)[:2652]-\
    # 	 	numpy.array(config.stkscz5_2x_all)[:2652])**2)\
    # ,label="Total Accumulated Error With Sun Sim & All Effects STK- km")
    plt.plot(numpy.sqrt((numpy.array(viking1.xarray)[:2652]\
     -numpy.array(config.stkscx5_2x_all)[:2652])**2 + \
    (numpy.array(viking1.yarray)[:2652]-\
     numpy.array(config.stkscy5_2x_all)[:2652])**2 +\
      (numpy.array(viking1.zarray)[:2652]-\
       numpy.array(config.stkscz5_2x_all)[:2652])**2)\
    ,label="Total Accumulated Error With Sun Sim & All Effects STK- km")
    plt.title('Total Accumulated Error - 9 days')
    plt.legend(loc='upper left')
    plt.show()
Example #8
0
def runUnitTestStatic():
    ##########################################################################
    ############################ THE STATIC UNIVERSE #########################
    ##########################################################################
    viking = Spacecraft()
    Earth = Planet(spacecraft=viking, configuration="earth")
    heavyEarth = Planet(spacecraft=viking, configuration="heavyearth")
    solarsystem = solarSystem(spacecraft=viking)
    solarsystem.addPlanet(Earth)

    ## Planet Potential Landscape
    heavyEarth.showPotential()

    ## Falling from height along x axis
    viking.leapFrog(solarsystem, Earth.radius + .100, 0, 0, 0, 0, 0, .25, 18)
    plt.plot((numpy.array(viking.xarray) - Earth.radius) * 1000,
             label="position")
    plt.plot(numpy.array(viking.xdotarray) * 1000, label="velocity")
    plt.title("x-Position, Falling from 100m Height above Earth's Surface")
    plt.xlabel("time (4.5 sec)")
    plt.ylabel("x")
    plt.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Falling from height along y axis
    viking.leapFrog(solarsystem, 0, Earth.radius + .100, 0, 0, 0, 0, .25, 18)
    plt.plot((numpy.array(viking.yarray) - Earth.radius) * 1000,
             label="position")
    plt.plot(numpy.array(viking.ydotarray) * 1000, label="velocity")
    plt.title("y-Position, Falling from 100m Height above Earth's Surface")
    plt.xlabel("time (4.5 sec)")
    plt.ylabel("y")
    plt.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Falling from height along z axis
    viking.leapFrog(solarsystem, 0, 0, Earth.radius + .100, 0, 0, 0, .25, 18)
    plt.plot((numpy.array(viking.zarray) - Earth.radius) * 1000,
             label="position")
    plt.plot(numpy.array(viking.zdotarray) * 1000, label="velocity")
    plt.title("z-Position, Falling from 100m Height above Earth's Surface")
    plt.xlabel("time (4.5 sec)")
    plt.ylabel("z")
    plt.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Ballistic trajectory in xy plane
    viking.leapFrog(solarsystem, Earth.radius + .50, 0, 0, 0, .500, 0, .25, 18)
    plt.plot((numpy.array(viking.yarray))*1000,(numpy.array(viking.xarray)-Earth.radius)*1000\
     ,label="ballistic position")
    plt.xlabel("y position")
    plt.ylabel("x position")
    plt.title("Ballistic Trajectory in xy Plane")
    plt.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Ballistic trajectory in xz plane
    viking.leapFrog(solarsystem, Earth.radius + .50, 0, 0, 0, 0, .500, .25, 18)
    plt.plot(numpy.array(viking.zarray)*1000,(numpy.array(viking.xarray)-Earth.radius)*1000\
     ,label="ballistic position")
    plt.xlabel("z position")
    plt.ylabel("x position")
    plt.title("Ballistic Trajectory in xz Plane")
    plt.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Ballistic trajectory in yz plane
    viking.leapFrog(solarsystem, 0, Earth.radius + .50, 0, 0, 0, .500, .25, 18)
    plt.plot(numpy.array(viking.zarray)*1000,(numpy.array(viking.yarray)-Earth.radius)*1000\
     ,label="ballistic position")
    plt.xlabel("z position")
    plt.ylabel("y position")
    plt.title("Ballistic Trajectory in yz Plane")
    plt.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Ballistic trajectory in xyz space
    viking.leapFrog(solarsystem, Earth.radius + .50, 0, 0, 0, .500, .500, .25,
                    18)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(numpy.array(viking.zarray)*1000,numpy.array(viking.yarray)*1000\
     ,(numpy.array(viking.xarray)-Earth.radius)*1000,label="ballistic position")
    plt.title("Ballistic Trajectory in 3d Space")
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Nodal Regression
    viking.leapFrog(solarsystem, (Earth.radius), 0., 0., 0., (5.5921),
                    (5.5921), 60, 270)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(numpy.array(viking.zarray),\
     numpy.array(viking.yarray),\
     numpy.array(viking.xarray),\
     label="Spacecraft Position")
    plt.title("Nodal Regression (short-term)")
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Plot direction of anguluar momentum vector
    viking.leapFrog(solarsystem, (Earth.radius), 0., 0., 0., (5.5921),
                    (5.5921), 60, 73571)
    xdirection = numpy.array(viking.yarray)[:] * numpy.array(
        viking.zdotarray)[:] - numpy.array(viking.zarray)[:] * numpy.array(
            viking.ydotarray)[:]
    ydirection = numpy.array(viking.zarray)[:] * numpy.array(
        viking.xdotarray)[:] - numpy.array(viking.xarray)[:] * numpy.array(
            viking.zdotarray)[:]
    zdirection = numpy.array(viking.xarray)[:] * numpy.array(
        viking.ydotarray)[:] - numpy.array(viking.yarray)[:] * numpy.array(
            viking.xdotarray)[:]
    for i in range(len(xdirection)):
        xdirection[i] = xdirection[i] / (
            numpy.sqrt(xdirection[i]**2 + ydirection[i]**2 + zdirection[i]**2))
        ydirection[i] = ydirection[i] / (
            numpy.sqrt(xdirection[i]**2 + ydirection[i]**2 + zdirection[i]**2))
        zdirection[i] = zdirection[i] / (
            numpy.sqrt(xdirection[i]**2 + ydirection[i]**2 + zdirection[i]**2))
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(xdirection,
            ydirection,
            zdirection,
            label="Direction of angular momentum vector")
    plt.title(
        "Precession of Angular Momentum Vector for Circular Orbit at Earth Radius, Theoretical Time Required for Full 1 Period"
    )
    ax.legend(loc='upper right')
    plt.show()

    ## And the energy
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    potential = lambdify((x,y,z), Earth.potential\
      , modules = 'numpy')
    potential_energy = viking.mass * (potential(numpy.array(viking.xarray),
                                                numpy.array(viking.yarray),
                                                numpy.array(viking.zarray)))
    kinetic_energy = .5 * viking.mass * (numpy.array(viking.xdotarray)**2 +
                                         numpy.array(viking.ydotarray)**2 +
                                         numpy.array(viking.zdotarray)**2)
    total = potential_energy[:40000] + kinetic_energy[:40000]
    plt.plot(potential_energy, label="Potential Energy")
    plt.plot(kinetic_energy, label="Kinetic Energy")
    plt.plot(total, label="Total Energy")
    plt.title("Conservation of Energy (Verification of Numeric Integrator)")
    plt.xlabel("Time (1.5 million timesteps)")
    plt.ylabel("Energy")
    plt.legend()
    plt.show()

    ## Nodal and Apsidal
    viking.leapFrog(solarsystem, (Earth.radius), 0., 0., 0., (7), (7), 200,
                    15000)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(numpy.array(viking.zarray),\
     numpy.array(viking.yarray),\
     numpy.array(viking.xarray),\
     label="Spacecraft Position")
    plt.title(
        "Long-Term Orbit around Earth-Like Planet, Nodal and Apsidal Precession"
    )
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Get plot of energy
    viking.leapFrog(solarsystem, Earth.radius, 0., 0., 0., 7, 7, 1, 40000)
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    potential = lambdify((x,y,z), Earth.potential\
      , modules = 'numpy')
    potential_energy = viking.mass * (potential(numpy.array(viking.xarray),
                                                numpy.array(viking.yarray),
                                                numpy.array(viking.zarray)))
    kinetic_energy = .5 * viking.mass * (numpy.array(viking.xdotarray)**2 +
                                         numpy.array(viking.ydotarray)**2 +
                                         numpy.array(viking.zdotarray)**2)
    total = potential_energy[:40000] + kinetic_energy[:40000]
    plt.plot(potential_energy, label="Potential Energy")
    plt.plot(kinetic_energy, label="Kinetic Energy")
    plt.plot(total, label="Total Energy")
    plt.title("Conservation of Energy (Verification of Numeric Integrator)")
    plt.xlabel("Time (1.5 million timesteps)")
    plt.ylabel("Energy")
    plt.legend()
    plt.show()
    print len(potential_energy)
    print len(kinetic_energy)
    print "Initial total energy: " + str(total[0]) + "\n"
    print "Final total energy: " + str(total[-1]) + "\n"

    ## Just-Less-Than-Escape velocity
    viking.leapFrog(solarsystem, (Earth.radius), 0., 0., 0., (0), (11.1), 100,
                    16500)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(numpy.array(viking.zarray),\
     numpy.array(viking.yarray),\
     numpy.array(viking.xarray),\
     label="Spacecraft Position")
    plt.title("Just-Less-Than-Escape Velocity (11.1 km/s)")
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Escape velocity
    viking.leapFrog(solarsystem, (Earth.radius), 0., 0., 0., (0), (11.2), 200,
                    16500)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(numpy.array(viking.zarray),\
     numpy.array(viking.yarray),\
     numpy.array(viking.xarray),\
     label="Spacecraft Position")
    plt.title("Escape Velocity (11.2 km/s)")
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Add a gravitating body
    anotherxEarth = Planet(
        spacecraft=viking, configuration="anotherxearth"
    )  #mass=5.972e24,eci_x=0,eci_y=25000,eci_z=20000,J2=1.7555e10)
    solarsystem.addPlanet(anotherxEarth)

    ## Two Gravitating Bodies
    viking.leapFrog(solarsystem, (Earth.radius), 0., 0., 0., (12), (0), 10,
                    20000)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot(numpy.array(viking.zarray),\
     numpy.array(viking.yarray),\
     numpy.array(viking.xarray),\
     label="Spacecraft Position")
    plt.title(
        "Trajectory under the influence of Two Earth-Like Planets, 30,000 km Separation"
    )
    ax.legend(loc='upper right', prop={'size': 10})
    plt.show()

    ## Conservation of energy, two bodies
    x = Symbol('x')
    y = Symbol('y')
    z = Symbol('z')
    potential = lambdify((x,y,z), solarsystem.landscape\
      , modules = 'numpy')
    potential_energy = viking.mass * (potential(numpy.array(viking.xarray),
                                                numpy.array(viking.yarray),
                                                numpy.array(viking.zarray)))
    kinetic_energy = .5 * viking.mass * (numpy.array(viking.xdotarray)**2 +
                                         numpy.array(viking.ydotarray)**2 +
                                         numpy.array(viking.zdotarray)**2)
    total = potential_energy[:20000] + kinetic_energy[:20000]
    plt.plot(potential_energy, label="Potential Energy")
    plt.plot(kinetic_energy, label="Kinetic Energy")
    plt.plot(total, label="Total Energy")
    plt.title(
        "Conservation of Energy, 2 Gravitating Bodies (Verification of Numeric Integrator)"
    )
    plt.xlabel("Time (200,000 timesteps)")
    plt.ylabel("Energy")
    plt.legend()
    plt.show()
    print len(potential_energy)
    print len(kinetic_energy)
    print "Initial total energy: " + str(total[0]) + "\n"
    print "Final total energy: " + str(total[-1]) + "\n"

    viking.leapFrog(solarsystem, 50000, 0, 0, 0, 0, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - X")
    plt.legend(loc='upper right')
    plt.show()

    viking.leapFrog(solarsystem, 50000, 0, 0, 0, .5, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - X")
    plt.legend(loc='upper right')
    plt.show()

    viking.leapFrog(solarsystem, 50000, 0, 0, 0, 0, 0.5, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - X")
    plt.legend(loc='upper right')
    plt.show()

    newsolarsystem = solarSystem(spacecraft=viking)
    anotheryEarth = Planet(spacecraft=viking, configuration="anotheryearth")
    newsolarsystem.addPlanet(Earth)
    newsolarsystem.addPlanet(anotheryEarth)

    viking.leapFrog(newsolarsystem, 0, 50000, 0, 0, 0, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - Y")
    plt.legend(loc='upper right')
    plt.show()

    viking.leapFrog(newsolarsystem, 0, 50000, 0, .5, 0, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - Y")
    plt.legend(loc='upper right')
    plt.show()

    viking.leapFrog(newsolarsystem, 0, 50000, 0, 0, 0, 0.5, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - Y")
    plt.legend(loc='upper right')
    plt.show()

    newnewsolarsystem = solarSystem(spacecraft=viking)
    anotherzEarth = Planet(spacecraft=viking, configuration="anotherzearth")
    newnewsolarsystem.addPlanet(Earth)
    newnewsolarsystem.addPlanet(anotherzEarth)

    viking.leapFrog(newnewsolarsystem, 0, 0, 50000, 0, 0, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - Z")
    plt.legend(loc='upper right')
    plt.show()

    viking.leapFrog(newnewsolarsystem, 0, 0, 50000, .5, 0, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - Z")
    plt.legend(loc='upper right')
    plt.show()

    viking.leapFrog(newnewsolarsystem, 0, 0, 50000, 0, 0.5, 0, 60, 2000)
    plt.plot(viking.xarray, label='x')
    plt.plot(viking.yarray, label='y')
    plt.plot(viking.zarray, label='z')
    plt.xlabel("time")
    plt.ylabel("position")
    plt.title("Adding Planets Verification - Z")
    plt.legend(loc='upper right')
    plt.show()
Example #9
0
class Astros:
    def __init__(self):

        #loading music
        mixer.music.load('Music/bg.mp3')
        mixer.music.play(-1)

        #setting background and display
        self.background_colour = (0, 0, 0)
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

        #getting screen width and height
        self.screen_width = self.screen.get_width()
        self.screen_height = self.screen.get_height()

        #calling classes
        self.spacecraft = Spacecraft(self)
        self.bg_stars = Distant_Stars(self)
        self.fl_objs = Flying_Object_Collection(self)

        self.score = 0
        self.level = 1
        self.spawn_freq_factor = 4500

        self.score_font = pygame.font.SysFont("Calibri", 30)

        #making event for trigering the time for respawn
        self.SPAWN = pygame.USEREVENT
        pygame.time.set_timer(self.SPAWN, self.spawn_freq_factor)

        #setting FPS to make sure smooth movement of game
        self.FPS = 360
        self.clock = pygame.time.Clock()

    def _fire_bullet(self):

        self.spacecraft.firing = True
        pygame.time.wait(500)
        self.spacecraft.firing = False

    def _check_key_down_events(self, event):
        '''This method deals with the key down event'''

        if event.key == pygame.K_RIGHT:
            self.spacecraft.rotate_right = True

        if event.key == pygame.K_LEFT:
            self.spacecraft.rotate_left = True

        if event.key == pygame.K_UP:
            self.spacecraft.speed_up = True

        if event.key == pygame.K_DOWN:
            self.spacecraft.slow_down = True

        if event.key == pygame.K_ESCAPE:
            self.destroy()

        if event.key == pygame.K_SPACE:

            bullet_thread = threading.Thread(target=self._fire_bullet)
            bullet_thread.start()

    def _check_key_up_events(self, event):
        '''This method deals with all key up events'''

        if event.key == pygame.K_RIGHT:
            self.spacecraft.rotate_right = False

        if event.key == pygame.K_LEFT:
            self.spacecraft.rotate_left = False

        if event.key == pygame.K_UP:
            self.spacecraft.speed_up = False

        if event.key == pygame.K_DOWN:
            self.spacecraft.slow_down = False

        if event.key == pygame.K_SPACE:
            self.spacecraft.firing = False

    def _check_events(self):
        '''checking all events'''
        for event in pygame.event.get():

            #keydown
            if event.type == pygame.KEYDOWN:
                self._check_key_down_events(event)

            #keyup
            elif event.type == pygame.KEYUP:
                self._check_key_up_events(event)

            #spawn
            elif event.type == self.SPAWN:

                if self.fl_objs.frost_ball == False:
                    self.fl_objs.create_flying_object(Flying_Object.count)

            #booster's active time
            if self.fl_objs.frost_ball and pygame.time.get_ticks(
            ) - self.frost_ball_timer > 7000:
                self.fl_objs.frost_ball = False

    def update_score(self):
        '''updates the score on the screen'''

        self.score_txt = self.score_font.render('Score: ' + str(self.score),
                                                True, (255, 255, 255))
        self.x_score = self.screen.get_rect(
        ).x + self.score_txt.get_rect().right / 8
        self.y_score = self.screen.get_rect(
        ).y + self.score_txt.get_rect().bottom / 2
        self.pos_score = (self.x_score, self.y_score)

        self.screen.blit(self.score_txt, self.pos_score)

    def update_level(self):
        '''updates the level'''

        if self.score >= self.level * 20:  #condition for level up
            level_music = mixer.Sound('Music/levelup.mp3')
            level_music.play()

            self.level += 1

            if self.level <= 4:
                level_up_img = pygame.image.load('Images/Level_Up.jpg')
                self.screen.blit(
                    pygame.transform.smoothscale(level_up_img,
                                                 self.screen.get_size()),
                    (0, 0))
                pygame.display.flip()

                pygame.time.delay(2500)

                self.spawn_freq_factor -= 1100

                self.SPAWN = pygame.USEREVENT
                pygame.time.set_timer(self.SPAWN, self.spawn_freq_factor)

            else:  #if the user survived till the end of 4th level, he is declared as a winner
                winner_img = pygame.image.load('Images/Winner.jpg')
                self.screen.blit(
                    pygame.transform.smoothscale(winner_img,
                                                 self.screen.get_size()),
                    (0, 0))
                pygame.display.flip()

                pygame.time.delay(2500)
                self.running = False

    def game_over(self):
        '''method for game over'''

        self.game_over_font = pygame.font.SysFont("Arial", 100, True)
        self.game_over_txt = self.game_over_font.render(
            'Game Over!', True, (255, 0, 0))

        self.x_game_over = self.screen.get_rect(
        ).centerx - self.game_over_txt.get_rect().width / 2
        self.y_game_over = self.screen.get_rect(
        ).centery - self.game_over_txt.get_rect().height / 2
        self.pos_game_over = (self.x_game_over, self.y_game_over)

        self.screen.blit(self.game_over_txt, (self.pos_game_over))
        pygame.display.flip()

        pygame.time.delay(2000)
        self.destroy()

    def destroy(self):

        mixer.music.stop()
        self.running = False

    def _update_screen(self):
        '''úpdates all the elements of the game'''
        self.screen.fill(self.background_colour)

        self.bg_stars.update()
        self.fl_objs.update()
        self.spacecraft.update()

        self.update_score()
        self.update_level()

        pygame.display.flip()

    def run_game(self):
        ''''main game loop'''
        self.running = True
        while self.running:

            self._check_events()
            self._update_screen()
            self.clock.tick(self.FPS)
Example #10
0
# ------------------------------------------------------

# All of these values where given in the exercise
fSpacecraftMassKg = 2662.8 * 0.45359237
fReferenceArea = 2.81
fDragCoefficient = 1.60

fEarthMass = 5.972 * math.pow(10, 24)
fEarthRadius = 6371 * 1000

fInitialAltitude = 325 * 1000 * 0.3048
fInitialVelocity = 22.5 * 1000 * 0.3048
fFlightPathDeg = -1.5

# Create spacecraft and planet objects with their respective properties
currentSpacecraft = Spacecraft(fSpacecraftMassKg, fReferenceArea,
                               fDragCoefficient)
currentPlanet = Planet(fEarthMass, fEarthRadius)

# Create parachutes for during the re-entry, both parachute areas where found experimentally
drogueChute = Parachute(186 * 0.514444, 225 * 0.3048, 47, 1.75, 0.694, 0)
mainChute = Parachute(225 * 0.3048, 28 * 0.3048, 5 * 60 + 31, 1.75, 154,
                      10 * 1000 * 0.3048)

# ------------------------------------------------------
# Simulate the whole thing
# ------------------------------------------------------

# Create, run and save the simulation
currentSimulation = ReEntry(currentSpacecraft, currentPlanet, fInitialAltitude,
                            fInitialVelocity, fFlightPathDeg, drogueChute,
                            mainChute)