def __init__(self, json): self.number = json['flight_number'] self.name = json['mission_name'].encode('utf-8') self.launchpad = json['launch_site']['site_name'].encode('utf-8') self.details = json['details'].encode('utf-8') self.video = json['links']['video_link'] self.launchDate = json['launch_date_utc'] self.staticFireDate = json['static_fire_date_utc'] self.launchSuccess = json['launch_success'] self.upcoming = json['upcoming'] self.rocket = Rocket(json['rocket'])
def crossover(self, parent1, parent2): p = (parent1, parent2) child = Rocket() b = 0 if parent2.color == "red" or parent1.color == "red": child.color = "blue" if parent1.fitness < parent2.fitness: b = 1 #child.DNA = list(p[b].DNA[:(WIDTH//CELL_SIZE//2)]) #child.DNA += (p[1 - b].DNA[:(WIDTH//CELL_SIZE//2)]).copy() first = p[b].DNA[:int(WIDTH // CELL_SIZE // 2)] second = p[b - 1].DNA[int(WIDTH // CELL_SIZE // 2):] new = first + second child.DNA = new return child
def calculate(self): """ Main """ self.rocket = Rocket.Rocket() self.rocket.drag = self.importDragData() thrustProfile = ThrustProfile.ThrustProfile() self.rocket.flightStats = thrustProfile.getThrustProfile( self.airPressure, self.airVolume, self.waterVolume, self.d_noz) # Set values. self.rocket.payloadMass = self.payloadMass self.rocket.structuralMass = self.structuralMass self.rocket.frontalArea = self.frontalArea self.rocket.tankRadius = self.tankRadius self.rocket.tankThickness = self.tankThickness # Start Calculations self.rocket.calcLength() self.getStresses() self.rocket.launch() # Output points = self.rocket.getAllPoints() print "\nDry Mass: {0}(kg) or {1}(lb)".format( self.structuralMass + self.payloadMass, (self.structuralMass + self.payloadMass) / self.__lb_kg) print "\nApogee Height: {0}(m)".format(str(self.getMaxHeight())) print "\nTank Stats:\nVolume: {0}(L) Length: {1}(m) Area: {2}(m^2) Radius: {3}(cm)".format( str(self.rocket.volume * 1000), str(self.rocket.length), str(self.rocket.frontalArea), str(math.sqrt(self.rocket.frontalArea / 3.14) * 100)) print "Hoop Stress: {0}(MPa) Longitudinal Stress: {1}(MPa)".format( str(self.rocket.hoopStressCurrent / 1000000), str(self.rocket.longStressCurrent / 1000000)) self.writeOut(points)
class Launch: def __init__(self, json): self.number = json['flight_number'] self.name = json['mission_name'].encode('utf-8') self.launchpad = json['launch_site']['site_name'].encode('utf-8') self.details = json['details'].encode('utf-8') self.video = json['links']['video_link'] self.launchDate = json['launch_date_utc'] self.staticFireDate = json['static_fire_date_utc'] self.launchSuccess = json['launch_success'] self.upcoming = json['upcoming'] self.rocket = Rocket(json['rocket']) def imprimir(self): cadena = "" cadena += "#" + str(self.number) + " · " + self.name + "\n" cadena += self.details + "\n" cadena += "Launched from " + self.launchpad + "\n" cadena += "Launched on " + self.launchDate.encode('utf-8') + "\n" cadena += "Static fired on " + self.staticFireDate.encode( 'utf-8') + "\n" cadena += "Launch success: " + ("Yes" if self.launchSuccess else "No") + "\n" cadena += self.rocket.imprimir().encode('utf-8') cadena += self.video.encode('utf-8') + "\n" return cadena
def run(weighting, position, velocity, orientation, dorientation): action = [0, 0, 0, 0, 0.00001] done = False fuel = 60000 positionarray = np.array([position]) orientationarray = np.array([orientation]) totalreward = 0 while done == False: position, velocity, orientation, dorientation, done, reward, fuel = rocket.step( action[0], action[1], action[2], action[3], action[4], position, velocity, fuel, orientation, dorientation) positionarray = np.append(positionarray, [position], axis=0) orientationarray = np.append(orientationarray, [orientation], axis=0) totalreward += reward observation = np.vstack( (position, velocity, orientation, dorientation)) observation = np.reshape(observation, 12) action = neural(observation, weighting, 10) action[0] = resize(action[0], 0, 1, -0.35, 0.35) action[1] = resize(action[1], 0, 1, -0.35, 0.35) action[2] = resize(action[2], 0, 1, -0.35, 0.35) action[3] = resize(action[3], 0, 1, -0.35, 0.35) if position[2] < 1000: action[4] = resize(action[4], 0, 1, 0.6, 1) else: action[4] = 0.00001 if fuel == 1000000: #save working config pass return totalreward, positionarray, orientationarray
def loop(self): # LOOP: (2 steps) # Step 2: Selection # Evaluate the fitness of each element of the population and build a mating pool. self.matingPool = [] # Calculate fitness, and build the matingPool according to it totalFitness = 0 for p in self.population: p.calcFitness() totalFitness += p.fitness # Used to calculate Average Fitness # Calculate Maximum Fitness if p.fitness > self.maxFitness: self.maxFitness = p.fitness # Append p to the matingPool * p.fitness for f in range(int(p.fitness * 100)): self.matingPool.append(p) # Calculate average fitness self.avgFitness = totalFitness / self.popSize # ~Step 2: Selection # Step 3: Reproduction (4 substeps) # Repeat N times (N = popSize). if self.matingPool: newPopulation = [] # Looping N times (N = popSize) for i in range(self.popSize): # Substep a: Pick two parents with probability according to relative fitness. a = int(random(len(self.matingPool))) b = int(random(len(self.matingPool))) parentA = self.matingPool[a] parentB = self.matingPool[b] # ~Substep a # Substep b: Crossover--create a "child" by combining the DNA of these two parents. child = Rocket.Rocket(self.startX, self.startY, self.target, self.lifespan) child._dna = parentA._dna.crossover(parentB._dna) # ~Substep b # Substep c: Mutation--mutate the child's DNA based on a given probability (Mutation Rate). child._dna.mutate(0.01) # Mutation Rate: 1% # ~Substep c # Substep d: Add the new child to a new population. newPopulation.append(child) # ~Substep d # ~Step 3: Reproduction # Step 4: Replace the old population with the new population. self.population = newPopulation
def NaturalSelection(self): newRockets = [ Rocket(self.startPos, self.lifeSpan, self) for i in range(self.population_size) ] if len(self.matingPool) > 0: for i in range(len(self.rockets)): parentA = self.matingPool[randint(0, len(self.matingPool) - 1)].dna parentB = self.matingPool[randint(0, len(self.matingPool) - 1)].dna childDNA = parentA.crossOver(parentB) childDNA.Mutation() newRockets[i] = Rocket(self.startPos, self.lifeSpan, self, childDNA) self.rockets = newRockets
def new_gen(self): for i in range(POPULATION_SIZE): m = Rocket() for i in range(WIDTH // CELL_SIZE): for j in range(HEIGHT // CELL_SIZE): x = uniform(-1, 1) y = uniform(-1, 1) while y == 0: y = uniform(-1, 1) m.DNA[i].append(x / y) self.members.append(m)
def func(y0, t): # unpack the state vector x = y0[0] # distance (altitude) xd = y0[1] # velocity (radial) Rocket.stages[0].setCurrentFuelOx(y0[2]) # the amount of stage fuel [kg] # atmospheric conditions pressure = 1.0 * exp(-x / H) # atmospheric pressure [atm] (the 1.0 is pressure at sea level) density = 1.2230948554874 * pressure # atmospheric density [kg/m^3] accel_thrust = Rocket.stages[0].getCurrentThrust() / Rocket.getTotalMass() # engine thrust accel_grav = G * M / pow(R_planet + x, 2) # accel due to gravity based on dist from Kerbin surface (if going straight out) # drag force (!) F_d = 0.5*density*pow(xd, 2) * Rocket.getCd() * Rocket.getArea() accel_drag = copysign(F_d / Rocket.getTotalMass(), -xd) # drag should always be opposite of velocity xdd = -accel_grav + accel_thrust + accel_drag # total acceleration return [xd, xdd, -Rocket.stages[0].getMassFlowRate(pressure)] # velocity, acceleration, mass flow rate (m_dot)
def __init__(self): self.members = [] # list of rockets self.best = Rocket() # member with the highest fitness in population self.avarge_fitness = 0 self.finished = 0 self.generation = 1 self.new_gen() self.time = datetime.now() self.target_size = 40 self.target = (WIDTH - 80, int(HEIGHT / 2 - 20)) self.max_distance = hypot(self.target[0] + self.target_size // 2, self.target[1] + self.target_size // 2) self.found_way = []
def finale(self, x, y, z): extraSparkLife = 10 origin = self.gbestLoc vel = np.array([0] * self.dimensions) finaleRocket = Rocket.Rocket(0, origin, vel, self.func, self.dimensions, self.numSparks, self.steps) finaleRocket.explode(x, y, z, extraSparkLife) rbestLoc, rbestVal = finaleRocket.getRBestSparkLocationAndValue() if rbestVal < self.gbest: self.gbest = rbestVal self.gbestLoc = rbestLoc #self.gbestRecordingCounter += 2* finaleRocket.getRocketFunctionEvals() self.gbestEachBenchmark.append(self.gbest)
def add_new_rockets(self): self.spawn_delay = 1.0 # gives the new bordersize to the indicators for n in range(len(self.indicator_x)): self.indicator_x[n].set_border_size(self.board_width, self.board_height) for n in range(len(self.indicator_y)): self.indicator_y[n].set_border_size(self.board_width, self.board_height) #create a new rocket self.rockets_x.append( Rocket.Rocket(self.play_field_width, self.board_height - 1, 1, self.play_field_width, self.play_field_height, self.rockets_x[0].get_update_round())) self.rockets_y.append( Rocket.Rocket(self.play_field_height, self.board_width - 1, 3, self.play_field_width, self.play_field_height, self.rockets_x[0].get_update_round())) # create a new indicatorss self.indicator_x.append( Indicator.Indicator(self.board_width, self.board_height - 1, 1, self.board_width, self.board_height)) self.indicator_y.append( Indicator.Indicator(self.board_width - 1, self.board_height, 3, self.board_width, self.board_height)) # self.rocket_x_ypos.append(-1) self.rocket_y_xpos.append(-1) for n in range(len(self.rockets_x)): self.rockets_x[n].set_speed(self.board_height - 5) for n in range(len(self.rockets_y)): self.rockets_y[n].set_speed(self.board_width - 3)
def __init__(self, play_field_width, play_field_height, board_width, board_height): self.play_field_width = play_field_width self.play_field_height = play_field_height self.board_width = board_width self.board_height = board_height self.sq_w = 0 self.sq_h = 0 self.timer = 0 self.rocket_spawn_time = 0.0 self.rocket_spawn_delay = 0.0 # creates the rockets self.rockets_x = [ Rocket.Rocket(-400, 2, 1), Rocket.Rocket(-10000, 1, 1), Rocket.Rocket(-10000, 4, 1), Rocket.Rocket(-10000, 3, 1) ] self.rockets_y = [ Rocket.Rocket(0, -10000, 3), Rocket.Rocket(2, -10000, 3) ] self.rockets_moving = False # holding the new ypos of the horizontal rockets self.rocket_x_ypos = [-1, -1, -1, -1] self.next_rocket_x = 0 # creates the indicators in the x axis self.indicator_x = [ Indicator.Indicator(-1, -1, 1, 3, 5), Indicator.Indicator(-1, -1, 1, 3, 5), Indicator.Indicator(-1, -1, 1, 3, 5), Indicator.Indicator(-1, -1, 1, 3, 5) ] # creates the indicators in the y axis self.indicator_y = [ Indicator.Indicator(-1, -1, 3, 3, 5), Indicator.Indicator(-1, -1, 3, 3, 5) ] self.rocket_y_xpos = [-1, -1] self.next_rocket_y = 0 self.show_indicator = False self.rocket_ready = True self.spawn_delay = 1.5 self.update_once = True
def GLOW_Optimization_Driver(Num_Stages, VelocitySplitRange, VelocitySplitStep, IspRange, IspStep, PropMassFractRange, PropMassFractStep, Altitude, PayloadMass, MaxGLOW, MinGLOW): # Array to hold data Data = [] # Determines Ideal Velocity Videal = 1.25 * np.sqrt(3.9857E14 / (Altitude + 6378000)) # Loop through range of Velocity Split # Split is the velocity percentage of the second stage for split in tqdm( range(VelocitySplitRange[0], VelocitySplitRange[1] + 1, VelocitySplitStep)): DeltaVsplit = [Videal * split / 100, Videal * (100 - split) / 100] # Loops through Isp of first stage for Isp1 in range(IspRange[0], IspRange[1] + 1, IspStep): # Loops through Isp of second stage for Isp2 in range(IspRange[0], IspRange[1] + 1, IspStep): # Loops through Propellant Mass Fraction of First Stage for PropMassFract1 in range(PropMassFractRange[0], PropMassFractRange[1] + 1, PropMassFractStep): # Loops through propellant Mass Fraction of Second Stage for PropMassFract2 in range(PropMassFractRange[0], PropMassFractRange[1] + 1, PropMassFractStep): Isp = [Isp2, Isp1] PropMassFract = [PropMassFract2, PropMassFract1] rocket = Rocket.Rocket(Num_Stages, Isp, DeltaVsplit, PayloadMass, PropMassFract) rocket.createStages() rocket.calcStageMass() if rocket.GLOW != "Not Possible": if rocket.GLOW <= MaxGLOW: if rocket.GLOW >= MinGLOW: Data.append([ 100 - split, split, Isp1, Isp2, PropMassFract1, PropMassFract2, rocket.GLOW ]) return Data
def __init__(self, popSize, x, y, lifespan, target): self.population = [] self.popSize = popSize self.matingPool = [] self.lifespan = lifespan self.startX = x self.startY = y self.target = target self.maxFitness = -1 self.avgFitness = -1 # SETUP: (1 step) # Step 1: Initialize # Create a population of N elements (N = popSize) each with randomly generated DNA. for i in range(self.popSize): self.population.append(Rocket.Rocket(x, y, target, lifespan))
def run_rotating(self, origin): for i in range(self.num_rockets): v_min, v_max = utils.vel_min_max(self.func) v_min = v_min * V_ADJUST v_max = v_max * V_ADJUST velocity = np.random.uniform(v_min, v_max, self.dimensions) new_rocket = Rocket.Rocket(i, origin, velocity, self.func, self.dimensions, self.numSparks, self.steps) self.rockets.append(new_rocket) for j in range(self.num_iterations): #print("Global Best So Far = ", self.gbest) new_rockets = [] for i in range(len(self.rockets)): rbestLoc, rbestVal = self.rockets[i].launch( self.steps, self.X, self.Y, self.Z, 2) if rbestVal < self.gbest: self.gbest = rbestVal self.gbestLoc = rbestLoc self.gbestRecordingCounter += self.rockets[ i].getRocketFunctionEvals() if self.gbestRecordingCounter > self.gbestRecordingBenchmark: self.gbestEachBenchmark.append(self.gbest) self.gbestRecordingCounter -= self.gbestRecordingBenchmark if i + 1 != self.num_rockets: new_velocity = np.subtract( self.rockets[i + 1].pbest, self.rockets[i].pbest) * ( 1.25 / self.steps) #reduce velocity step size else: new_velocity = np.subtract( self.rockets[0].pbest, self.rockets[i].pbest) * ( 1.25 / self.steps) #reduce velocity step size new_rocket = self.rockets[i].spawnNewRocket( new_velocity, rbestLoc, self.rockets[i].id) new_rockets.append(new_rocket) self.rockets = new_rockets self.newthing.append(self.gbest)
def fitness_function(self): best = Rocket() for member in self.members: d = hypot(self.target[0] - member.p_location.x, self.target[1] - member.p_location.y) time = 30 if member.reached and not member.color == "red": time = member.time.seconds member.color = "red" max_way = hypot(self.target[0] - x_start, self.target[1] - y_start) travaled_way = hypot(x_start - member.p_location.x, y_start - member.p_location.y) way_points = travaled_way / max_way fit_value = (((30 - time) / 30 / 2) + ( (self.max_distance - d) / self.max_distance + way_points)) / 2 #fit_value = fit_value ** 2 member.fitness = fit_value if member.fitness > best.fitness: best = member self.avarge_fitness += member.fitness self.avarge_fitness /= POPULATION_SIZE self.best = best
r_init = 4 * (10**6 ) # m distance away from planet during landing/docking stage v0 = -12.1 * 10**3 # initial velocity (m/s) ### Will have to change m_mars = 6.39 * (10**23) r = 3.3895 * (10**6) G = 6.67408 * (10**-11) F_thrust1 = 1.45 * 10**5 # kg*m/s^2 Reverse thrust of rocket F_thrust2 = 2.765 * 10**5 #F_thrust3 = 1.5*10**5 v_ex = -10.8 * 10**(2) # m/s velocity of ejecting fuel mass_fuel = 89000 #creating Rocket with current position, velocity, and current fuel left rocket = Rocket(y=r_init, v=v0, a=-accel_grav(r_init + r), thrust=F_thrust1, fuel=mass_fuel) F_thrust3 = 3.8 * rocket.getMass() # Time for Simulation dt = 1 # day tmax = 1500 # days timestep = int(tmax / dt) #initializers m,y,v,a,time= np.zeros(timestep), np.zeros(timestep), \ np.zeros(timestep), np.zeros(timestep),np.zeros(timestep) m[0] = rocket.getMass() + rocket.getFuel()
from Rocket import * r = Rocket() r.RenderToModel() print repr(r)
def Initialize(self): self.rockets = [] for i in range(self.population_size): self.rockets.append(Rocket(self.startPos, self.lifeSpan, self))
''' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * File name : RocketTrajectoryMain.py * Purpose : To rapidly test rocket trajectories for fufillment of mission design requirements * @author : Harrison Leece * @author : Debugged by * Date : 2019-01-23 * Notes : None * Warnings : None * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Revision History * ================ * Ver Date Modified by: Reason for change or modification * ----- ---------- ------------ --------------------------------------------------------------------- * 1.0.0 2019-01-23 Harrison L Initial release * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' import Rocket import numpy as np import matplotlib.pyplot as plt rocket = Rocket(330, .65, 220, 9/12, .25) tuple = rocket.flight_simulation() print(tuple[6])
input3 = float( input( "Try again! What is the gravitational constant G?\n ____x 10^-11> " )) if input3 == 6.67408: print('Correct!') G = input3 * (10**-11) F_thrust = 2 * 10**5 # kg*m/s^2 Reverse thrust of rocket ### Will Have to change constant v_ex = -4 * 10**( 3) # m/s velocity of ejecting fuel ### Will have to change constant mass_fuel = MASS_FUEL #creating Rocket with current position, velocity, and current fuel left rocket = Rocket(y=r_init, v=v0, a=-accel_grav(r_init + r), thrust=F_thrust, fuel=mass_fuel) # Time for Simulation dt = 1 # day tmax = 500 # days timestep = int(tmax / dt) m = [rocket.getMass() + rocket.getFuel()] y = [rocket.getY()] v = [rocket.getVelocity()] a = [rocket.getAcceleration()] time = [0] ifinal = -1 for i in range(1, timestep): dm = rocket.getThrust() / v_ex
class Solver: """ Solves for the trajectory. Make sure to set: - air pressure (psi) - air volume (m^3) - water volume (m^3) - structural mass (lb) - payload mass (lb) - frontal area (ft^2)""" # Private Variables __psi_100 = 689475.729 __ft_2 = 0.092903 __lb_kg = 0.453592 # Default Values airPressure = 25 * __psi_100 # Pa airVolume = .0015 # m^3 waterVolume = .0005 # m^3 structuralMass = 5 * __lb_kg # kg payloadMass = 1 * __lb_kg # kg frontalArea = .25 * __ft_2 # m^2 tankThickness = 00.1 # m tankRadius = 0.1 # m d_noz = 0.01 # m rocket = Rocket.Rocket() # Class Methods @staticmethod def importDragData(): """ Returns a list of drag tuples from the given drag csv. """ drag = [] dragfile = open("drag.csv", "r") dragstr = dragfile.read() for line in dragstr.splitlines(): point = line.split(',')[0], line.split(',')[1], line.split(',')[2] drag.append(point) return drag @staticmethod def writeOut(data): """ Writes the given list of points to a file named 'out.csv'. """ _file = open("_out.csv", "w") _file.write( "Time (s),X (m),Y (m),Velocity (m/s),Acceleration (g),Mass (kg),Thrust (N),Drag (custom),Comment\n" ) _file.write( str(data[-1].time) + "," + str(data[-1].x) + "," + str(data[-1].y) + ",," + str(data[-1].acceleration / 9.81) + "," + str(data[-1].mass) + ",,,Max Height\n-,-,-,-,-\n") for point in data: _file.write( str(point.time) + "," + str(point.x) + "," + str(point.y) + "," + str(point.velocity) + "," + str(point.acceleration / 9.81) + "," + str(point.mass) + "," + str(point.thrust) + "," + str(point.drag) + "," + point.comment + "\n") _file.close() # Instance Methods def __init__(self): pass def calculate(self): """ Main """ self.rocket = Rocket.Rocket() self.rocket.drag = self.importDragData() thrustProfile = ThrustProfile.ThrustProfile() self.rocket.flightStats = thrustProfile.getThrustProfile( self.airPressure, self.airVolume, self.waterVolume, self.d_noz) # Set values. self.rocket.payloadMass = self.payloadMass self.rocket.structuralMass = self.structuralMass self.rocket.frontalArea = self.frontalArea self.rocket.tankRadius = self.tankRadius self.rocket.tankThickness = self.tankThickness # Start Calculations self.rocket.calcLength() self.getStresses() self.rocket.launch() # Output points = self.rocket.getAllPoints() print "\nDry Mass: {0}(kg) or {1}(lb)".format( self.structuralMass + self.payloadMass, (self.structuralMass + self.payloadMass) / self.__lb_kg) print "\nApogee Height: {0}(m)".format(str(self.getMaxHeight())) print "\nTank Stats:\nVolume: {0}(L) Length: {1}(m) Area: {2}(m^2) Radius: {3}(cm)".format( str(self.rocket.volume * 1000), str(self.rocket.length), str(self.rocket.frontalArea), str(math.sqrt(self.rocket.frontalArea / 3.14) * 100)) print "Hoop Stress: {0}(MPa) Longitudinal Stress: {1}(MPa)".format( str(self.rocket.hoopStressCurrent / 1000000), str(self.rocket.longStressCurrent / 1000000)) self.writeOut(points) def getMaxHeight(self): points = self.rocket.getAllPoints() if len(points) > 0: maxPoint = points[-1] return maxPoint.y def getStresses(self): """ Calculates the stresses and forces on the rocket body. Accounts for both internal pressure loads and external drag forces. """ # self.flightStats: {Time, Thrust, MassFlow, Current Mass, Current Air Volume, Current Water Volume, Total # Air Volume, Total Water Volume, Current Air Mass, Current Water Mass} # Get the current tank status. self.rocket.hoopStressCurrent = self.airPressure * self.tankRadius / self.tankThickness self.rocket.longStressCurrent = self.airPressure * self.tankRadius / ( 2 * self.tankThickness) return 0
display_width = 400 display_height = 600 clock = pygame.time.Clock() gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Rockets') rocket_width = display_width // 16 rocket_height = display_height // 8 img = pygame.image.load('Rocket.bmp') img = pygame.transform.scale(img, (rocket_width, rocket_height)) meteor_img = pygame.image.load('Meteor.png') meteor_img = pygame.transform.scale(meteor_img, (40, 40)) cloud_img = pygame.image.load('cloud.png') cloud_img = pygame.transform.scale(cloud_img, (65, 40)) rocket = Rocket.Rocket(display_width / 2, display_height - (display_height / 3)) color = SkyColor.SkyColor() FPS = 30 font = pygame.font.SysFont(None, 25) meteors = [0, 0, 0, 0, 0] for meteor in meteors: meteor = Meteor.Meteor() clouds = [0, 0, 0, 0, 0, 0, 0, 0, 0] for x in range(0, 9): clouds[x] = Cloud.Cloud() pygame.font.init() height_font = pygame.font.SysFont("Courier", 20) text_height = height_font.render("Height: {0}".format(rocket.getHeight()),
display_width = 400 display_height = 600 clock = pygame.time.Clock() gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Rockets') rocket_width = display_width // 5 rocket_length = display_height // 6 img = pygame.image.load('rock2.png') img = pygame.transform.scale(img, (rocket_width, rocket_length)) rocket_width = rocket_width* (1/3) rocket_length = rocket_length* (3/4) + 3 meteor_img = pygame.image.load('Meteor.png') meteor_img = pygame.transform.scale(meteor_img, (40, 40)) rocket = Rocket.Rocket(display_width/2 - rocket_width/2, display_height - (display_height / 3) - 10, rocket_width, rocket_length) color = SkyColor.SkyColor() FPS = 30 font = pygame.font.SysFont(None, 25) meteors = [0, 0, 0, 0, 0] for meteor in meteors: meteor = Meteor.Meteor() clouds = [0,0,0,0,0,0,0,0,0] for x in range(0, 9): clouds[x] = Cloud.Cloud('cloud.png', 60, 40) pygame.font.init() height_font = pygame.font.SysFont("Courier", 20) text_height = height_font.render("Height: {0}".format(rocket.getHeight()),False,(0,0,0))
from math import exp, copysign from matplotlib.pyplot import plot, xlabel, ylabel, legend from Component import Component import Stage import Rocket ## definitions Stage1 = Stage.Stage() Stage1.addComp(Component(.84, .2, 600)) #Command Pod Mk1 Stage1.addComp(Component(4.5, .2, 1600, m_fuel = 1.8, m_ox = 2.2)) #FL-T800 Fuel Tank Stage1.addComp(Component(1.5,.2, 950, thrust = 200, I_sp_sea = 320, I_sp_vac = 370)) #LV-T45 Liquid Fuel Engine Rocket = Rocket.Rocket() Rocket.addStage(Stage1) # planet properties G = 6.67e-11 # grav_accitational constant [m^3/kg/s^2] M = 5.29e22 # mass of Kerbin [kg] H = 5000.0 # scale height of planet [m] R_planet = 600000.0 # radius of planet [m] t_0 = 0.0 # start time [s] t_f = 230 # end time [s] N = 100 # number of time points ## acceleration function def func(y0, t): # unpack the state vector
def run_recursive(self, origin, iterations_left, total_iterations): ''' Has tendency to get stuck in local minimum. Thoughts on how to get out: - random chance to do explosion from spot on path, - Neighborhood PSO in local search instead - Increase the step number? - Decrease the spark number - random restart - Priority Queue for picking next with timing component? ''' if iterations_left == 0: return #print("Iteration", total_iterations - iterations_left + 1) if len(self.rockets) == 0: # first run through, build rockets for i in range(self.num_rockets): v_min, v_max = utils.vel_min_max(self.func) velocity = np.random.uniform(v_min, v_max, self.dimensions) new_rocket = Rocket.Rocket(i, origin, velocity, self.func, self.dimensions, self.numSparks, self.steps) self.rockets.append(new_rocket) # EndIf # Now we launch and record data rbestValLocs = [] for rocket in self.rockets: rbestLoc, rbestVal = rocket.launch( self.steps, self.X, self.Y, self.Z, 2) # return loc and val with parameter of 2 if rbestVal < self.gbest: self.gbest = rbestVal self.gbestLoc = rbestLoc rbestValLocs.append((rbestVal, rbestLoc, rocket)) self.gbestRecordingCounter += rocket.getRocketFunctionEvals() if self.gbestRecordingCounter > self.gbestRecordingBenchmark: self.gbestEachBenchmark.append(self.gbest) self.gbestRecordingCounter -= self.gbestRecordingBenchmark orderedRbest = sorted( rbestValLocs, key=lambda x: x[0]) #sort from smallest to largest ''' for triple in orderedRbest: print("rbestVal: ", triple[0], " at ", triple[1]) ''' #now we have them ordered, we want the best numRockets/spawn number numSpawn = 4 mostPromising = orderedRbest[0:len(orderedRbest) // numSpawn] new_rockets = [] next_id = 0 for triple in mostPromising: rbestVal, rbestLoc, rocket = triple #print("Spawning from rbestVal: ", rbestVal, " at ", rbestLoc) for i in range(numSpawn): v_min, v_max = utils.vel_min_max(self.func) velocity = np.random.uniform(v_min, v_max, self.dimensions) * ( iterations_left / total_iterations) new_rocket = rocket.spawnNewRocket(velocity, rbestLoc, next_id) new_rockets.append(new_rocket) next_id += 1 self.rockets = new_rockets return self.run_recursive(origin, iterations_left - 1, total_iterations)
for unit in gc.my_units(): Globals.radar.update_location(unit) if Units.try_go_to_rocket(gc, unit): continue if unit.location.is_on_map(): if Globals.radar.check_if_enemies_gone(gc, unit): Globals.everyone_to_mars = True if unit.location.map_location().planet == bc.Planet.Mars and Globals.on_mars is False: Globals.on_mars = True Navigation.BFS(gc.starting_map(bc.Planet.Mars), Globals.radar.get_enemy_center(bc.Planet.Mars), gc) if unit.unit_type == bc.UnitType.Worker: s = time.time() Worker.manage_worker(gc, unit) Globals.wtime += (time.time() - s) elif unit.unit_type == bc.UnitType.Rocket: Rocket.manage_rockets(gc, unit) elif unit.unit_type == bc.UnitType.Healer: Healer.manage_healers(gc, unit) elif unit.unit_type == bc.UnitType.Knight: Knight.turn(gc, unit) # Knight.manage_knights(gc, unit, Globals.earth_enemy_center, earth_enemy_map, eneGlobals.us) elif unit.unit_type == bc.UnitType.Mage: Mage.manage_mages(gc, unit) # Mage.manage_mages(gc, unit, Globals.earth_enemy_center, earth_enemy_map, Globals.us) elif unit.unit_type == bc.UnitType.Ranger: s = time.time() Ranger.turn(gc, unit) Globals.rtime += (time.time() - s) elif unit.unit_type == bc.UnitType.Factory: Factory.factory_manager(gc, unit) print("Workers: ", Globals.wtime, "Rangers: ", Globals.rtime, "Find Karb: ", Globals.ftime)
fps = 50 displayWidth = 1200 displayHeight = 900 speed = 250 UP = 'up' DOWN = 'down' RIGHT = 'right' LEFT = 'left' LEVEL = 1 missleMap = [] enemyMap = [] tracker = 0 rocket = Rocket.Rocket() #test Alien alien = Alien.Alien(250, 30, 0) def runGame(): global missleMap speedUp = False movX, movY = 0, 0 s = "Score " + str(score) while True: playSound("Idle.wav") key = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
##print("Scout rifle info:") ##print(weaponList[3].scoutRifle, weaponList[3].scoutRifleAttributes,weaponList[3].scoutRifleList) weaponList.append(smg.SMG()) ##print("SMG info:") ##print(weaponList[4].smg, weaponList[4].smgAttributes,weaponList[4].smgList) weaponList.append(sw.Sword()) ##print("Sword info:") ##print(weaponList[5].sword, weaponList[5].swordAttributes) weaponList.append(gr.Grenade()) ##print("Grenade launcher info:") ##print(weaponList[6].grenade, weaponList[6].grenadeLauncherAttributes,weaponList[6].grenadeLauncherList) weaponList.append(ro.Rocket()) ##print("Rocket launcher info:") ##print(weaponList[7].rocket, weaponList[7].rocketAttributes,weaponList[7].rocketLauncherList) weaponList.append(ma.Machine()) ##print("Machine gun info:") ##print(weaponList[8].machine, weaponList[8].machineGunAttributes,weaponList[8].machineGunList) weaponList.append(sr.Sniper()) ##print("Sniper info:") ##print(weaponList[9].sniper, weaponList[9].sniperAttributes,weaponList[9].sniperList) weaponList.append(sa.Sidearm()) ##print("Sidearm info:") ##print(weaponList[10].sidearm, weaponList[10].sidearmAttributes,weaponList[10].sidearmList)
def createRocket1(): global rocket1 rocket1=Rocket(can,b1.x2,b1.y2,"red")
def game(): global tTime, lastTime running = True fps = time.Clock() rick = Rocket() while running: for evnt in event.get(): if evnt.type == QUIT: return "quit" if evnt.type == KEYDOWN: if evnt.key == K_SPACE: rick.jump() keys = key.get_pressed() if keys[K_LEFT]: rick.rotL() elif keys[K_RIGHT]: rick.rotR() rick.xPos += rick.xSpeed rick.yPos += rick.ySpeed for b in blocks: if collision(b[0], b[1], b[2], b[3], rick.getCentreX(), rick.getCentreY(), rick.getRadius()): if rick.ang1 > rick.ang2: rick.ang1 -= 2 * pi if (rick.ang1 <= 0 and 0 <= rick.ang2) or (rick.ang1 <= pi and pi <= rick.ang2): bounceX(rick) else: rick.xSpeed = 0 if ((rick.ang1 <= (1 / 2) * pi and (1 / 2) * pi <= rick.ang2) or (rick.ang1 <= (3 / 2) * pi and (3 / 2) * pi <= rick.ang2) ) and time.get_ticks() - lastTime > 100: lastTime = time.get_ticks() bounceY(rick) else: rick.YSpeed = 0 #if rick.onGround: #print(0) #else: #print(1) if rick.getCentreY() + rick.getRadius() >= 698: rick.onGround = True rick.yPos = 700 - rick.getRadius() else: rick.onGround = False if rick.onGround: rick.refreshJumps() rick.xSpeed = 0 rick.ySpeed = 0 rick.bSpeed = 0 else: rick.ySpeed += GRAVITY ########################### screen.fill((0, 0, 0)) #Hitbox draw.circle(screen, (0, 0, 0), (int(rick.xPos), int(rick.yPos)), 22, 1) #Points of arc draw.circle(screen, (255, 0, 0), (int(rick.xPos + (22 * cos(rick.ang1))), int(rick.yPos - (22 * sin(rick.ang1)))), 3, 0) draw.circle(screen, (255, 0, 0), (int(rick.xPos + (22 * cos(rick.ang2))), int(rick.yPos - (22 * sin(rick.ang2)))), 3, 0) #Sprite screen.blit(rot_center(sprite, degrees(rick.angle)), (rick.xPos - 20, rick.yPos - 22)) #Wall draw.rect(screen, WHITE, wallR) draw.rect(screen, WHITE, wallL) draw.rect(screen, WHITE, floorRect) draw.rect(screen, WHITE, midRect) fps.tick(80) display.flip()
def game(): size = (900, 910) screen = initialize(size) rocketYSpeed = 3 rocketXSpeed = 3 opponentSpeed = 3 opponentLives = 5 done = False bulletSpeed = 5 noOfMovesSinceLastOpponent = 0 rocket = Rocket(size[0]/2, size[1]-100) bullets = [] opponents = [Opponent((i+1)*80,25,size[0],size[1],opponentLives) for i in range(math.floor(size[0]/80),0,10)] stars = [Star(randrange(size[0]), randrange(size[1]), size[1]) for i in range(200)] score = Score(size[1]) pygame.display.set_caption("Spiel") # ================= # = Main Programm = # ================= clock = pygame.time.Clock() while not done: # Main event loop for event in pygame.event.get(): if (event.type == pygame.KEYDOWN and event.key == pygame.K_q) or (event.type == pygame.QUIT): print ("The game was quit") done = True if event.type == pygame.KEYDOWN and event.key == pygame.K_p: print ("Color changed") rocket.switchColor() if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: bullets.append(Bullet(rocket.x - 17, rocket.y - 5)) bullets.append(Bullet(rocket.x + 58, rocket.y - 5)) if event.type == pygame.KEYDOWN and event.key == pygame.K_s: score.addScore() pressed = pygame.key.get_pressed() if pressed[pygame.K_UP]: rocket.moveY(-rocketYSpeed) if pressed[pygame.K_DOWN]: rocket.moveY(+rocketYSpeed) if pressed[pygame.K_LEFT]: rocket.moveX(-rocketXSpeed) if pressed[pygame.K_RIGHT]: rocket.moveX(+rocketXSpeed) # Game dynamics for b in bullets: b.move(bulletSpeed) if (b.isOffScreen()): bullets.remove(b) for o in opponents: if (o.isHitByBullet(b)): bullets.remove(b) if (o.isDead()): opponents.remove(o) score.addScore() break for s in stars: s.move() for o in opponents: o.move(opponentSpeed) noOfMovesSinceLastOpponent += 1 if (noOfMovesSinceLastOpponent == 45): noOfMovesSinceLastOpponent = 0 opponents.append(Opponent(size[0]-25,25,size[0],size[1],opponentLives)) # Draw loop drawGameScreen(screen, rocket, bullets, opponents, stars, score) pygame.display.flip() clock.tick(60)