def __init__(self, size=10, life_time=60, origin=None, target=None, prev_child=None): if origin is None: origin = [300, 500] if target is None: target = [300, 100] self.origin = origin self.prev_child = prev_child self.mutation_rate = 0.05 self.average_fitness = 0 self.highest_average_fitness = 1 self.fitness_graph = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.size = size self.life_time = life_time self.target = Vector(target[0], target[1]) self.best_child = Rocket(self.life_time) self.members = [] for member in range(0, self.size): self.members.append( Rocket(self.life_time, origin=self.origin, prev_genes=self.prev_child))
def start(self): self.p1 = Rocket(self.width / 2 - 250, self.height / 2, (255, 0, 0)) self.p2 = Rocket(self.width / 2 + 250, self.height / 2, (0, 0, 255)) self.p2.heading = 180 self.p2.drift_heading = 180 self.levels = [(Wall(5, 5, 1, self.height), Wall(5, 5, self.width, 1), Wall(self.width - 5, 5, 1, self.height), Wall(5, self.height - 5, self.width, 1), Wall(100, 100, 300, 135), Wall(900, 450, 150, 250)), (Wall(5, 5, 1, self.height / 2 - 150), Wall(5, self.height / 2 + 150, 1, self.height / 2 - 150), Wall(5, 5, self.width, 1), Wall(self.width - 5, 5, 1, self.height / 2 - 150), Wall(self.width - 5, self.height / 2 + 150, 1, self.height / 2 - 150), Wall(5, self.height - 5, self.width, 1))] self.current_level = randint(0, len(self.levels) - 1) self.powerup_ids = [ "none", # id = 0 "scatter_shot", # id = 1 "missile" # id = 2 ] self.powerups = [] self.powerup_spawn_timer = 0
def shoot_rockets(self): rocket = Rocket(random.randrange(50, WIDTH - 200), -75, self.rocket_img) rocket1 = Rocket(random.randrange(50, WIDTH - 200), -75, self.rocket_img) self.rockets.append(rocket) self.rockets.append(rocket1)
def __init__(self): """Initialize the game and create game resources.""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height self.screen_bottom = self.screen.get_rect().bottom self.bg_color = self.settings.bg_color pygame.display.set_caption("Lander") # Create and instance to store game stats self.stats = GameStats(self) self.sb = Scoreboard(self) self.rocket = Rocket(self, 1) self.rocket2 = Rocket(self, 2) self.rocket2.rect.top = self.screen_bottom self.flames = Flames(self) self.terrain_group = pygame.sprite.Group() self._create_terrain_group() self.pad = Pad(self) # Make the Play button self.play_button = Button(self, "Start", 500, 500) # Make the info button self.info_button = InfoButton(self, "Instructions", 500, 600) # Set the high score file self.filename = "highscore.txt" # Make a banner of instructions self.banner = Banner(self, "Click on 'Start' or press 's'", 350, 100) self.banner2 = Banner(self, "Press 'q' to Quit", 350, 200) self.show_instructions = Banner( self, "Use up arrow for thrust and left/right arrows to rotate.", 300, 650) self.show_instructions2 = Banner( self, "Land on the platform with parameters green. " "Bonus points for fuel remaining", 300, 700) self.info_displayed = False # Make a bonus points banner bonus_points_str = "place holder" self.banner3 = Banner(self, bonus_points_str, 500, 200) # Get sound file: self.explosion_sound = pygame.mixer.Sound("explosion.wav") self.thrust_sound = pygame.mixer.Sound("thrusters.wav") self.applause_sound = pygame.mixer.Sound("applause.wav") self.alert_sound = pygame.mixer.Sound("alert.wav") pygame.mixer.music.load('lander.wav') pygame.mixer.music.set_volume(1.0)
def __init__(self, title, width, height, iteratons , loc_x, loc_y, population_size=100, mutation_rate=0.1, obstacles=[]): # initialize all variables self.title = title self.width = width self.height = height self.iteratons = iteratons self.target_location = Vector(loc_x, loc_y) self.population_size = population_size self.mutation_rate = mutation_rate self.population = [] self.best_child = Rocket(FPS) self.obstacles = obstacles for i in range(0, self.population_size): self.population.append(Rocket(FPS))
def fight_tank(self): tankNum = int(input("Unesite broj tenkova na ratnom polju: ")) tanks = [] rockets = [] for x in range(0, tankNum): x = random.randint(0, 100) y = random.randint(1, 100) self.route = random.randint(0, 10) tanks.append(Tank(x, y, self.route)) for x in range(0, tankNum): x = random.randint(0, 100) y = random.randint(1, 100) rockets.append(Rocket(x, y)) for index, tank in enumerate(tanks): print("Tenk {} je napravio {} rutu/e".format( index + 1, tank.route)) print("\n") yourTank = int( input("Od {} tenkova, vaš tenk je pod brojem: ".format(tankNum))) chosenTank = tanks[yourTank - 1] for index, tank in enumerate(tanks): distance = chosenTank.get_distance(tank) print("Vaš Tenk je udaljen {} kilometara od tenka broj {}.".format( distance, index + 1)) print("\n") for index, rocket in enumerate(rockets): distance = chosenTank.get_distance(rocket) print( "Vaš tenk je udaljen {} kilometara od rakete broj {}.".format( distance, index + 1))
def run_game(): """Initialize game.""" pygame.init() ai_settings = Settings() screen = pygame.display.set_mode(( ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Domination") rocket = Rocket(screen) # Start the main loop for the game. while True: # Watch for keyboard and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # Redraw the screen during each pass through the loop. screen.fill(ai_settings.bg_color) rocket.blitme() # Make the most recently drawn screen visible. pygame.display.flip()
def __init__(self, width=640, height=480): # config self.tps_max = 100.0 self.width = width self.height = height # initialization pygame.init() self.screen = pygame.display.set_mode((self.width, self.height)) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.player = Rocket(self.screen) breaky = False while True: # handle events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type is pygame.KEYDOWN and event.key is pygame.K_ESCAPE: breaky = True if breaky: break self.tps_delta += self.tps_clock.tick(50) / 1000.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max # drawing self.screen.fill((0, 0, 0)) self.draw() pygame.display.flip()
def fight_ship(self): shipNum = int(input("Unesite broj brodova na ratnom polju: ")) ships = [] rockets = [] for x in range(0, shipNum): x = random.randint(0, 100) y = random.randint(1, 100) self.route = random.randint(0, 10) ships.append(Ship(x, y, self.route)) for x in range(0, shipNum): x = random.randint(0, 100) y = random.randint(1, 100) rockets.append(Rocket(x, y)) for index, ship in enumerate(ships): print("Brod {} je napravio {} rutu/e".format( index + 1, ship.route)) print("\n") yourShip = int( input("Od {} brodova, vaš brod je pod brojem: ".format(shipNum))) chosenShip = ships[yourShip - 1] for index, ship in enumerate(ships): distance = chosenShip.get_distance(ship) print("Vaš Brod je udaljen {} kilometara od broda broj {}.".format( distance, index + 1)) print("\n") for index, rocket in enumerate(rockets): distance = chosenShip.get_distance(rocket) print( "Vaš brod je udaljen {} kilometara od rakete broj {}.".format( distance, index + 1))
def game_function(): """Main function to initialize Space Invaders game.""" pygame.init() game_para = Parameters() # Game screen properties. screen = pygame.display.set_mode( (game_para.screen_width, game_para.screen_height)) pygame.display.set_caption('Space Invaders') # Make a rocket. rocket = Rocket(screen) # Make a group of an aliens. aliens = Group() # Make a group where all fired missiles will be stored. missiles = Group() # Create a row of an aliens. gm.alien_army(game_para, screen, aliens, rocket) # Main loop of the Space Invaders game. while True: # Call for game event function. gm.event_type(game_para, rocket, screen, missiles) # Instance for Rocket smooth movement. rocket.new_position() # Call for missiles add and remove function. gm.missile_management(missiles, aliens) # Call for alien update function. gm.alien_new_position(game_para, aliens) # Call for the screen renew function. gm.screen_renew(screen, rocket, game_para, missiles, aliens)
def __init__(self, windowX: int, windowY: int, width=120, height=30, isNew=False, isMoving=False, imagePath='images/floor.png'): super().__init__(imagePath, windowX, windowY, width, height) self.__isMoving = isMoving # 地板是否左右移动 currHeight = Floor.lastHeight + randint(70, 90) self._rect.x = randint(0, windowX - width) self._rect.y = 50 if isNew else windowY - currHeight Floor.lastHeight = currHeight # 板子上面的东西:火箭 弹簧 怪物 等... self.__itemOn = None if randint(0, 100) < 20: self.__itemOn = Spring(windowX, windowY) self.__itemOn.attachTo(self) if randint(0, 100) < 20: self.__itemOn = Rocket(windowX, windowY, self.getLeft(), self.getTop()) self.__itemOn.attachTo(self)
def prep_rockets(self): self.rockets = Group() for rocket_number in range(self.states.rocket_left): rocket = Rocket(self.setting, self.screen) rocket.rect.x = 10 + rocket_number * rocket.rect.width rocket.rect.y = 10 self.rockets.add(rocket)
def fight(self): # kreiram nekoliko tenkova i raketa s pozicijama slučajnog odabira (biblioteka random) # tenkovi imaju random broj odrađenih/napravljenih ruta na ratnom polju tankNum = int(input("Unesite broj tenkova na ratnom polju:")) # upisao broj 5 tanks = [] rockets = [] for x in range(0,tankNum): # for petlja se vrti od 0 do 5 x = random.randint(0,100) y = random.randint(1,100) self.route = random.randint(0,10) tanks.append(Tank(x,y,self.route)) for x in range(0, tankNum): # for petlja se vrti od 0 do 5 x = random.randint(0, 100) y = random.randint(1,100) rockets.append(Rocket(x, y)) # prikazivanje/ispis napravljene rute svakog tenka u listi na ratnom polju for index, tank in enumerate(tanks): print("Tenk {} je napravio {} rutu/e".format(index+1, tank.route)) print("\n") yourTank = int(input("Od {} tenkova, vaš tenk je pod brojem:".format(tankNum))) chosenTank = tanks[yourTank-1] # prikazivanje/ispis udaljenosti vašeg tenka ostalih tenkova for index, tank in enumerate(tanks): distance = chosenTank.get_distance(tank) print("Vaš tenk je udaljen {} kilometara od tenka broj {}.".format(distance, index+1)) print("\n") # prikazivanje/ispis udaljenosti vašeg tenka od raketa u listi raketa for index, rocket in enumerate(rockets): distance = chosenTank.get_distance(rocket) print("Vaš tenk je udaljen {} kilometara od rakete broj {}.".format(distance, index+1))
def __init__(self): pygame.init() self.tps_delta = 0.0 self.tps_clock = pygame.time.Clock() self.player = Rocket() self.enemies = EnemyCollection(self.player.points) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: self.player.fire_bullet() self.tps_delta += self.tps_clock.tick() / 1000.0 while self.tps_delta > 1 / Settings.MAX_TPS: self.tick() self.tps_delta -= 1 / Settings.MAX_TPS Settings.SCREEN.fill((0, 0, 0)) self.draw() pygame.display.flip()
def eval_genomes(genomes, config): #this function runs once a generation global genomess global rockets global nets global dead_rockets dead_rockets = [] rockets = [] nets = [] for i, (genome_id, genome) in enumerate(genomes): genomess.append(genome) current_fitness = genome.fitness if current_fitness is None: current_fitness = -float('inf') genomess[-1].fitness = 0 rockets.append( Rocket(x_pos=window.width // 2, y_pos=window.height // 2, batch=batch, _id=round(current_fitness, 1))) rockets[-1].insert(space) dead_rockets.append(0) nets.append(neat.nn.FeedForwardNetwork.create(genome, config)) generation_number.text = f"Generation: {generation}" pyglet.app.run() base.iterate_position(reset=True, window_width=window_width, window_height=window_height)
def run(): global nets global rockets for i, path in enumerate(NETWORK_PATH): if not os.path.exists(os.path.dirname(path)): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) if (len(path) == 0): raise FileNotFoundError("No Networks found") nets.append(pickle.load(open(path, "rb"))) rockets.append( Rocket(x_pos=window.width // 2, y_pos=window.height // 2, batch=batch, _id=f" {net_id[i]}")) rocket_images.append(RocketImage(batch=batch)) rockets[-1].insert(space) rockets[-1].visibility(False) rocket_images[-1].attach(rockets[-1]) pyglet.app.run()
def __init__(self, loc_x, loc_y, population_size=50, mutation_rate=0.1, obstacles=[]): # initialize all variables self.target_location = Vector(loc_x, loc_y) self.population_size = population_size self.mutation_rate = mutation_rate self.population = [] self.best_child = Rocket(FPS) self.obstacles = [] # initialize the rockets at random values for i in range(0, self.population_size): self.population.append(Rocket(FPS)) # create obstacle objects for obs in obstacles: self.obstacles.append(Obstacle(obs[0], obs[1], obs[2], obs[3]))
def fight_brod(self): # kreiram nekoliko brodova i raketa s pozicijama slučajnog odabira (biblioteka random) # brodovi imaju random broj odrađenih/napravljenih ruta na ratnom polju brodNum = int(input("Unesite broj broda na ratnom polju:")) # upisao broj 5 brodovi = [] rockets = [] for x in range(0,brodNum): # for petlja se vrti od 0 do 5 x = random.randint(0,100) y = random.randint(1,100) self.route = random.randint(0,10) brodovi.append(Brodovi(x,y,self.route)) for x in range(0, brodNum): # for petlja se vrti od 0 do 5 x = random.randint(0, 100) y = random.randint(1,100) rockets.append(Rocket(x, y)) # prikazivanje/ispis napravljene rute svakog broda u listi na ratnom polju for index, brod in enumerate(brodovi): print("Brod {} je napravio {} rutu/e".format(index+1, brod.route)) print("\n") yourBrod = int(input("Od {} Broda, vaš brod je pod brojem:".format(brodNum))) chosenBrod = brodovi[yourBrod-1] # prikazivanje/ispis udaljenosti vašeg broda od ostalih brodova for index, brod in enumerate(brodovi): distance = chosenBrod.get_distance(brod) print("Vaš brod je udaljen {} kilometara od broda broj {}.".format(distance, index+1)) print("\n") # prikazivanje/ispis udaljenosti vašeg broda od raketa u listi raketa for index, rocket in enumerate(rockets): distance = chosenBrod.get_distance(rocket) print("Vaš brod je udaljen {} kilometara od rakete broj {}.".format(distance, index+1))
def __init__(self): # Config self.tps_max = 100.0 # Initialisation pygame.init() self.resolution = (1024, 600) self.screen = pygame.display.set_mode(self.resolution) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.player = Rocket(self) self.circles = [Circle(self, self.player)] while True: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) # Ticking self.tps_delta += self.tps_clock.tick() / 1000.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max # Drawing self.screen.fill((0, 0, 0)) self.draw() pygame.display.flip()
def _next_gen(self): fitness_list = [] new_generation = [] for member in self.population: fitness = (member.fitness(self.target_location)) * 1000 fitness_list.append((fitness,member)) new_list = sorted(fitness_list, key=lambda rkt: rkt[0]) child1,child2 = new_list[len(new_list)-1][1].crossover(new_list[len(new_list)-2][1]) child1.mutate(self.mutation_rate) child2.mutate(self.mutation_rate) for member in self.population: if ((member.fitness(self.target_location)) * 1000) == new_list[0][0] : new_generation.append(child1) elif ((member.fitness(self.target_location)) * 1000) == new_list[1][0] : new_generation.append(child2) else : temp = Rocket(FPS) temp.forces = member.forces new_generation.append(temp) self.population = [] self.population = new_generation self.best_child = new_list[len(new_list)-1][1]
def __init__(self): """Initialize the game, and create game resources.""" pygame.init() # Get game's settings self.settings = Settings() # Create a main display self.screen = pygame.display.set_mode((1200, 800)) # Set a main display's name pygame.display.set_caption("Space Battle") # Create an instance to store game statistics self.stats = GameStats(self) # Create a scoreboard self.scoreboard = Scoreboard(self) # Create a rocket self.rocket = Rocket(self) # Create a list of bullets self.bullets = pygame.sprite.Group() # Create a fleet of spaceships self.spaceships = pygame.sprite.Group() self._create_fleet() # Make the Start button. self.start_button = PlayButton(self, "Start")
def __init__(self): # Config self.tps_max = 25.0 #Initialization pygame.init() self.screen = pygame.display.set_mode((1280, 720)) icon = pygame.image.load("rocket.png") pygame.display.set_caption("Space rocket") pygame.display.set_icon(icon) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.player = Rocket(self) while True: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) # Ticking self.tps_delta += self.tps_clock.tick( ) / 1000 # dt - to czas ms miedzy klatkami while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max # Drawing self.screen.fill((0, 0, 0)) self.draw() pygame.display.flip()
def __init__(self): # Configuration self.tps_max = 100.0 # Initialization pygame.init() self.screen = pygame.display.set_mode((1280, 720)) self.tps_clock = pygame.time.Clock() self.tps_delta = 0.0 self.player = Rocket(self) while True: # Handling events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) # Ticking self.tps_delta += self.tps_clock.tick() / 1000.0 while self.tps_delta > 1 / self.tps_max: self.tick() self.tps_delta -= 1 / self.tps_max # Drawing self.screen.fill((0, 0, 0)) self.draw() pygame.display.flip()
def run_game(): pygame.init() screen = pygame.display.set_mode((800, 400)) pygame.display.set_caption('Rocket Fire!!!') bg_color = (66, 106, 175) screen.fill(bg_color) rocket = Rocket(screen) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: rocket.moving_up = True elif event.key == pygame.K_DOWN: rocket.moving_down = True elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: rocket.moving_up = False elif event.key == pygame.K_DOWN: rocket.moving_down = False rocket.update() rocket.blitme() pygame.display.flip()
def activate(self): if not self.config: self.log.info('Webserver is not configured. Forbid activation') return host = self.config['HOST'] port = self.config['PORT'] ssl = self.config['SSL'] interfaces = [(host, port)] if ssl['enabled']: # noinspection PyTypeChecker interfaces.append( (ssl['host'], ssl['port'], ssl['key'], ssl['certificate'])) self.log.info('Firing up the Rocket') from errbot.bootstrap import sentry_client if sentry_client is None: wsgi_app = bottle_app else: from raven.contrib.bottle import Sentry bottle_app.catchall = False wsgi_app = Sentry(bottle_app, sentry_client) self.webserver = Rocket( interfaces=interfaces, app_info={'wsgi_app': wsgi_app}, ) self.webserver.start(background=True) self.log.debug('Liftoff!') super().activate()
def run(): global rocket #affichage model1 = pygame.image.load('Model/sma.gif').convert() model2 = pygame.image.load('Model/med.gif').convert() model3 = pygame.image.load('Model/big.gif').convert() modelcanon = pygame.image.load("Model/canon.png").convert() alien.afficher(core.screen, model1, model2, model3, xalien) if rocket != None: rocket.afficher(core.screen, None) canon.Apparaitre(core.screen, modelcanon) #clavier keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: if rocket == None: rocket = Rocket() rocket.position.x = canon.position.x + 14 rocket.position.y = canon.position.y if keys[pygame.K_RIGHT]: canon.position.x = canon.position.x + 10 if canon.position.x < 720 else 720 if keys[pygame.K_LEFT]: canon.position.x = canon.position.x - 10 if canon.position.x > 50 else 50 #deplacement if rocket != None: rocket.deplacement() if rocket.position.y < 0: rocket = None alien.checkCollision()
def __init__(self): max_fps = 100 screen_width = 1280 screen_high = 720 # INITIALIZATION pygame.init() self.screen = pygame.display.set_mode((screen_width, screen_high)) self.fps_clock = pygame.time.Clock() self.fps_delta = 0.0 self.player = Rocket(self) while True: # HANDLE EVENTS for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) # TICKING self.fps_delta += self.fps_clock.tick() / 1000.0 while self.fps_delta > 1 / max_fps: self.tick() self.fps_delta -= 1 / max_fps # DRAWING self.screen.fill((0, 0, 0)) self.draw() pygame.display.flip()
def __init__(self): # config self.max_tps = 300.0 self.tps_delta = 0.0 self.width = 1280 self.height = 720 # initialization pygame.init() self.screen = pygame.display.set_mode((self.width, self.height)) self.tps_clock = pygame.time.Clock() # player self.player = Rocket(self) while True: # handle events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit(0) # ticking self.tps_delta += self.tps_clock.tick() / 1000.0 while self.tps_delta > 1 / self.max_tps: self.tick() # run 300 ticks per second self.tps_delta -= 1 / self.max_tps # drawing self.screen.fill((0, 0, 0)) # clear the screen self.draw() pygame.display.flip()
def run(self): self.setupRoutes() self.logger.debug('Flask Server Starting') self.server = Rocket((self.host, self.port), 'wsgi', {"wsgi_app": self.app}) self.server.start(background=False) #self.app.run(host=self.host, port=self.port) self.logger.debug('Flask Server Stopping')
def set_rockets(self): """Show how many rockets are left.""" self.rockets = Group() for rocket_number in range(self.stats.rockets_left): rocket = Rocket(self.ai_game) rocket.rect.x = 10 + rocket_number * rocket.rect.width rocket.rect.y = 10 self.rockets.add(rocket)