def crossover(self): #sorting population by fitness - returning best in pop self.grade() l = len(self.population) # picking birds with highest fitness to be parents for new birds parents = self.population[int(l * (1 - BEST_RATE)):] # picking 2 best performing birds to add unchanged to the population leaders = [ Bird(parents[-1].net.weights), Bird(parents[-2].net.weights) ] #adding them to new population result = leaders #breeding with random parents - for specified cross rate while len(result) < POP_SIZE: # taking 2 random and different ids to breed ids = random.sample(range(len(parents)), 2) new_bird = self.breed(parents[ids[0]].net, parents[ids[1]].net) #mutating by MUTE_RATE new_bird = self.mutate(new_bird) result.append(new_bird) self.population = result return result
def main(): config = Config( FPS, WIN_WIDTH, WIN_HEIGHT ) game = Game(config) game.sprite_manager.register([ SpriteConfig('bg', os.path.join(local_dir, "assets/bg.png"), [pygame.transform.scale2x]), SpriteConfig('bird1', os.path.join(local_dir, "assets/bird1.png"), [pygame.transform.scale2x]), SpriteConfig('bird2', os.path.join(local_dir, "assets/bird2.png"), [pygame.transform.scale2x]), SpriteConfig('bird3', os.path.join(local_dir, "assets/bird3.png"), [pygame.transform.scale2x]), SpriteConfig('base', os.path.join(local_dir, "assets/base.png"), [pygame.transform.scale2x]), SpriteConfig('pipe', os.path.join(local_dir, "assets/pipe.png"), [pygame.transform.scale2x]), ]) background = Background(game.sprite_manager.get('bg')) birds = [ Bird(230, 350, game.sprite_manager.get('bird1')), Bird(130, 350, game.sprite_manager.get('bird1')), ] game.state.add([background] + birds) game.start()
def mainLoop(clock, window, sprites, audio): run = True status = Status.inMenu tick = 0 drawer = Drawer(window) hitBoxe = HitBoxe(audio.hitSound, audio.dieSound, audio.pointSound) base = Base(sprites.base) bird = Bird(sprites.bird, audio.wingSound, hitBoxe) pipes = Pipes(sprites.pipe, hitBoxe) score = Score(sprites.numbers) while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): run = False if status == Status.inMenu and event.type == pygame.KEYUP and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): status = Status.inGame if status == Status.inGame and event.type == pygame.KEYDOWN and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): bird.jump() if status == Status.inGameOver and event.type == pygame.KEYUP and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): status = Status.inMenu tick = 0 base = Base(sprites.base) bird = Bird(sprites.bird, audio.wingSound, hitBoxe) pipes = Pipes(sprites.pipe, hitBoxe) score = Score(sprites.numbers) if status == Status.inGame: hitBase = hitBoxe.birdHitBase(bird, base) hitPipe = hitBoxe.birdHitPipes(bird, pipes) hitBoxe.birdPassPipe(bird, pipes.pipes, score) if hitBase or hitPipe: status = Status.inGameOver bird.die() if status == Status.inMenu: drawer.drawInMenu(sprites.background, sprites.message, base, bird, tick) elif status == Status.inGame: drawer.drawInGame(sprites.background, base, bird, pipes, score, tick) else: drawer.drawInGameOver(sprites.background, sprites.gameOver, base, bird, pipes, score, tick) if tick < FPS: tick += 1 else: tick = 0
def nextGeneration(self): self.counter += 1 dead = self.dead nextGen = [] if (dead): for b in dead: if (0 < b.centerY < WINDOW_HEIGHT): b.score += 10 self.saveStats() dead.sort(key=(lambda b: b.score)) dead[-1].save('gen' + str(self.counter)) be.clear_session() winnerThreshold = floor(self.popSize * self.winnerThreshold) winners = dead[-winnerThreshold:] weights = [b.score for b in winners] weightSum = sum(weights) logger.info('Best Quarter Score avg: %f', weightSum / winnerThreshold) logger.info('Scores: %s', str(weights)) logger.info('Generation %d', self.counter) weights = [w / weightSum for w in weights] winners = [b.brain for b in winners] dead = [b.brain for b in dead] # reproduce winners # half size because there are 2 resulting children in each iteration. winnerSize = floor(self.popSize * self.winnerPerc / 2) zipper = zip(np.random.choice(winners, size=winnerSize, p=weights), np.random.choice(winners, size=winnerSize, p=weights)) for mom, dad in zipper: child1, child2 = mom.crossover(dad) child1.mutate() child2.mutate() nextGen.append(Bird(child1)) nextGen.append(Bird(child2)) # reproduce any genome with equal probability. # half size because there are 2 resulting children in each iteration. equalPoolSize = floor(self.popSize * self.equalPerc / 2) zipper = zip(np.random.choice(dead, size=equalPoolSize), np.random.choice(dead, size=equalPoolSize)) for mom, dad in zipper: child1, child2 = mom.crossover(dad) child1.mutate() child2.mutate() nextGen.append(Bird(child1)) nextGen.append(Bird(child2)) for i in range(self.popSize - len(nextGen)): nextGen.append(Bird()) self.alive = nextGen self.dead = []
def run_game(): # This plays when you start up main.py pygame.init() # Initialize/open pygame gameDisplay = pygame.display.set_mode( (DISPLAY_W, DISPLAY_H)) # Set boundries for the game window pygame.display.set_caption('Learn to fly') # Title of the game running = True # Set running to true to use the running loop bgImg = pygame.image.load(BG_FILENAME) # Load background image pipes = PipeCollection(gameDisplay) pipes.create_new_set() bird = Bird(gameDisplay) label_font = pygame.font.SysFont("monospace", DATA_FONT_SIZE) # Choose font and size clock = pygame.time.Clock() # Pygame has a clock which can be used dt = 0 # delta time game_time = 0 # BeginTime = 0 num_iterations = 1 # From here the loop starts, all of the above will not play again while running: # While the variable running is true dt = clock.tick( FPS ) # The difference in time takes the frames per second into account game_time += dt # Add delta time to total time gameDisplay.blit( bgImg, (0, 0)) # Draw background image from the upper right corner for event in pygame.event.get(): # If something happens if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: # When a key is pressed, put running to false, which stops the loop if event.key == pygame.K_SPACE: bird.jump() else: running = False pipes.update(dt) # update the drawn pipe bird.update(dt, pipes.pipes) # update bird and give list of pipes if bird.state == BIRD_DEAD: # every time the bird dies, create new game, but increase iterations pipes.create_new_set() game_time = 0 bird = Bird(gameDisplay) num_iterations += 1 update_data_labels(gameDisplay, dt, game_time, num_iterations, label_font) # While running, update the text pygame.display.update( ) # Draw all of what is called on top of the layers that are there (30 times per second, FPS)
def mutate(self, bird): if random.random() < MUT_RATE: w = self.decode_weights(bird.net.weights) r = [] for i in w: if random.random() < 0.5: r.append(random.triangular(-1, 1) * i) else: r.append(i) mutated_weights = self.encode_weight(r) return Bird(mutated_weights) else: return Bird(bird.net.weights)
def reset(self): self.flappy_env.reset() self.birds['ai'] = self.flappy_env.bird = Bird( self.flappy_env.width // 4, self.flappy_env.height // 2, img_name='flappy', ghost_rate=0.) self.birds['human'] = Bird( self.flappy_env.width // 4 - 1.5 * self.birds['ai'].rayon, self.flappy_env.height // 2, 'flappy2') self.bulle = tools.loadImage("bulle2", self.birds['ai'].rayon + 10, self.birds['ai'].rayon + 10) return np.array(self.state)
def on_init(self): pygame.init() self.screen = pygame.display.set_mode((576, 1025)) self.clock = pygame.time.Clock() self.gameActive = True self.gravity = 0.25 self.score = 0 self.scoreText = Text(self.score, 40) self.highScore = 0 self.highScoreText = Text(f'High score: {int(self.score)}', 40) self.background = pygame.image.load( "assets/background-day.png").convert() self.background = pygame.transform.scale2x(self.background) self.floor = Floor() self.bird = Bird() self.pipes = [] self.SPAWNPIPE = pygame.USEREVENT self.BIRDFLAP = pygame.USEREVENT + 1 pygame.time.set_timer(self.SPAWNPIPE, 1200) pygame.time.set_timer(self.BIRDFLAP, 200)
def crossover(bird1, bird2, k=1): b1_layers = bird1.get_layers() b2_layers = bird2.get_layers() b_layers = [] for layers in zip(b1_layers, b2_layers): flatten_layer1 = layers[0].flatten() flatten_layer2 = layers[1].flatten() flatten_layers = [flatten_layer1, flatten_layer2] length = len(flatten_layer1) k_points = [0] k_points += sorted(np.random.choice(range(0, length), k)) k_points.append(length) choices = [] for i, (k1, k2) in enumerate(zip(k_points, k_points[1:])): for n in range(k2 - k1): choices.append(i % 2) b_layer = [] for i, c in enumerate(choices): b_layer.append(flatten_layers[c][i]) b_layer = np.array(b_layer).reshape(layers[0].shape) b_layers.append(b_layer) bird = Bird() bird.set_layers(b_layers) return bird
def __init__(self, width=288, height=512): """ Initialize the game. Argument: width (int): width of game screen in pixels height (int): height of game screen in pixels """ pygame.init() # Frame rate of the game self.fps = 30 # Game clock which ticks according to the game framerate self.clock = pygame.time.Clock() # Set up display self.width, self.height = width, height self.screen = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption('Flappy Bird') # Set up game objects self.bg = pygame.image.load('assets/background.png').convert_alpha() self.game_text = GameText() self.player = Bird(0.2 * width, 0.45 * height) self.base = Base() self.pipes = [] # List of flags indicating whether or not the pass through of the pipe # pairs has been counted yet self.pipe_counted = [False, False] # Set game difficulty as [0,1,2] = [easy, medium, or hard] self.level = 2
def new_population(self): top = self.get_top() childA, childB = self.crossover(top[0], top[1]) childC, childD = self.crossover(top[0], top[2]) for bird in self.population: bird.kill() self.population = [] self.population.append(childA) self.population.append(childB) self.game.all_sprites.add(childA) self.game.all_sprites.add(childB) self.game.birds.add(childA) self.game.birds.add(childB) self.population.append(childC) self.population.append(childD) self.game.all_sprites.add(childC) self.game.all_sprites.add(childD) self.game.birds.add(childC) self.game.birds.add(childD) for i in range(self.n - 4): bird = Bird(i + 4, 100, 400, self, self.game) mutated = self.mutate(top[i]) bird.brain.layers = mutated.brain.layers self.population.append(bird) self.game.all_sprites.add(bird) self.game.birds.add(bird)
def __init__(self, width, height, n): super().__init__(width, height) predicted_d = Bird.avoid_range - ( Bird.attraction_weight / (Bird.avoidance_weight * Bird.neighborhood_size)) # predicted_d = 150 h_margin = 0 count = 0 start_x = 200 if Bird.neighborhood_size == 6: move_x = predicted_d / 2 height = math.sqrt(predicted_d**2 - move_x**2) elif Bird.neighborhood_size == 4: move_x = 0 height = predicted_d for i in range(0, n): if i % 10 == 0: h_margin += height start_x += move_x move_x *= -1 if Bird.neighborhood_size == 4 and (i == 0 or i == 9 or i == 90 or i == 99): continue self.birds.append( Bird(start_x + (predicted_d * (i % 10)), 100 + h_margin, count)) count += 1 self.p_stds = np.full(len(self.birds), 0.0) self.v_stds = np.full(len(self.birds), 0.0)
def __init__(self, width, height, good_count, bad_count): super().__init__(width, height) targets = [[200, 100], [600, 250], [200, 600], [600, 450], [1000, 100], [1000, 600]] for t in targets: self.targets.append(pygame.Vector2(t[0], t[1])) left_targets = [ self.targets[3], self.targets[1], self.targets[0], self.targets[2] ] right_targets = [ self.targets[3], self.targets[1], self.targets[4], self.targets[5] ] for i in range(0, good_count): bird = Bird(600 + (50 * (i % 2)), 600 + (25 * i), i) if i % 2 == 0: bird.target_sequence.extend(left_targets) else: bird.target_sequence.extend(right_targets) self.birds.append(bird) for i in range(0, bad_count): bird = NonFlocker(200 + ((i % 2)) * 40, 350 + (65 * i), i + good_count) if i % 2 == 0: bird.target_sequence.extend(left_targets) else: bird.target_sequence.extend(right_targets) self.birds.append(bird)
def __init__(self): self.bird = Bird(0.72, -20, 0.92) self.gap_size = 200 self.width = 50 self.speed = 5 pipe = Pipe(self.gap_size, self.width, self.speed) self.pipes = [pipe]
def __init__(self): self.blinks_detector = BlinkDetector() self.blinks_detector.start() pygame.init() pygame.event.set_allowed([ QUIT, KEYDOWN, KEYUP, Pipes.SPAWN_PIPE_EVENT, Bird.BIRD_FLAP_EVENT ]) self.active = True self.score = 0 self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), DOUBLEBUF) self.screen.set_alpha(None) self.clock = pygame.time.Clock() self.font = pygame.font.Font('fonts/04B_19.ttf', 40) # Game objects self.bg_surface = pygame.transform.scale2x( pygame.image.load("assets/background-day.png").convert()) self.gameover_surface = pygame.transform.scale2x( pygame.image.load("assets/gameover.png").convert_alpha()) self.gameover_rect = self.gameover_surface.get_rect( center=(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)) self.floor = Floor() self.bird = Bird() self.bird.start_flapping() self.pipes = Pipes() self.pipes.start_spawning()
def enter(): global boy grass = Grass() bird = Bird() game_world.add_object(grass, 0) game_world.add_object(bird, 1)
def create_first_population(population_length): # todo: bias are all zeros birds = [] for _ in range(population_length): birds.append(Bird()) return birds
def __init__(self): """constructor""" pygame.init() self.screen_width = 1300 self.screen_height = 700 pygame.display.set_caption('FloppyBird') self.screen = pygame.display.set_mode( (self.screen_width, self.screen_height)) self.run = True self.jump = False self.debug = False self.pipegroup = pygame.sprite.Group() self.clock = pygame.time.Clock() self.bird = Bird(self.screen) self.background = Background(self.screen, self.screen_width) self.font = pygame.font.Font('freesansbold.ttf', 32) self.points = 0 self.score = self.font.render(str(self.points), True, (0, 0, 0)) self.score_rect = self.score.get_rect() self.score_rect.center = (self.screen_width // 2, 50) self.bird_grav = 4 self.bird_max_grav = 8 self.bird_jump_height = 15 # pygame.display.set_icon(pygame.image.load()) self.flopdabird()
def __init__(self): self.bird = Bird() self.pipes = [] for i in range(4): self.pipes.append(Pipe()) self.pipes[i].x = i * 300 + 300
def new_population(self, best_bird): for i in range(self.n_birds): bird_nn = copy.deepcopy(best_bird.nn) new_bird = Bird(bird_nn) new_bird.mutate(0.1) self.middle_sprites.add(new_bird) self.birds.append(new_bird)
def __init__(self): self.birds = [] self.nbBirds = 50 for i in range(self.nbBirds): self.birds.append(Bird()) self.gen = 0 self.best_score = 0
def on_init(self, genomes, config): """ Initialize before the main loop """ pygame.init() self.win = pygame.display.set_mode(self.size) pygame.display.set_caption("Flappy bird") self.clock = pygame.time.Clock() self.score = 0 self.gen += 1 self.nets = [] self.ge = [] self.birds = [] for _, genome in genomes: genome.fitness = 0 net = neat.nn.FeedForwardNetwork.create(genome, config) self.nets.append(net) self.birds.append(Bird(230, 350)) self.ge.append(genome) self.base = Base(self.win_height) self.pipes = [Pipe(self.win_width + 200)] self.run = True
def create_bird(self): r = 20 pix = QPixmap(":/images/bird.png").scaled(r * 2, r * 2) b = Bird(r=r, pixmap=pix) b.setPos(250, 80) self.scene.addItem(b) return b
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Flying Bird") bird = Bird(ai_settings, screen) mountains = Group() button = Button(ai_settings, screen, "PLAY") # 创建计分板 sb = Scoreboard(ai_settings, screen) while True: gf.check_events(bird, button, ai_settings, mountains) if ai_settings.state: bird.update_bird() mountains.update(ai_settings) gf.update_mountains(bird, mountains, ai_settings) gf.built_mountains(mountains, ai_settings, screen) gf.update_screen(ai_settings, screen, bird, mountains, button, sb)
def initialize(width,height): population_size = 10 hidden_layer = 5 input_layer = 2 bird_list = pygame.sprite.Group() for pop_idx in range(population_size): bird = Bird(width,height,pop_idx,40 + 40 * pop_idx) #initialize alpha beta layers alpha = np.zeros((hidden_layer,input_layer)) beta = np.zeros((input_layer,hidden_layer+1)) for i in range(hidden_layer): for j in range(input_layer): if j == 0: alpha[i][j] = 0 else: alpha[i][j] = random.uniform(-0.5,0.5) for i in range(input_layer): for j in range(hidden_layer+1): if j == 0: beta[i][j] = 0 else: beta[i][j] = random.uniform(-0.5,0.5) bird.alpha = alpha bird.beta = beta bird_list.add(bird) return bird_list
def __init(self): self.birds_flock = [Bird() for i in range(0, self._number_of_objects)] self.best_solution = [ 0.0 for i in range(0, self._number_of_dimensions) ] self.best_fitness = 1.0 for bird in range(len(self.birds_flock)): rand_positions = [ 0.0 for i in range(0, self._number_of_dimensions) ] rand_velocity = [0.0 for i in range(0, self._number_of_dimensions)] for i in range(0, rand_positions.__len__()): rand_positions[i] = (self.__maximum_x - self.__minimum_x ) * random.random() + self.__minimum_x rand_velocity[i] = (self.__maximum_x * 0.1 - self.__minimum_x * 0.1) * random.random() + self.__maximum_x fitness = self.cost_function(rand_positions) self.birds_flock[bird].velocity = rand_velocity self.birds_flock[bird].best_position = rand_positions self.birds_flock[bird].best_fitness = fitness self.birds_flock[bird].current_fitness = fitness self.birds_flock[bird].position = rand_positions if self.birds_flock[bird].current_fitness < self.best_fitness: self.best_fitness = self.birds_flock[bird].current_fitness self.best_solution[0] = self.birds_flock[bird].position[0] self.best_solution[1] = self.birds_flock[bird].position[1]
def load_all(self): self.game_w = GAME_SIZE[0] self.game_h = GAME_SIZE[1] self.floor_y = self.game_h - FLOOR_Y self.bird_x = self.game_w / 3 - FLOOR_Y self.bird_y = self.game_h / 2 self.pipe_w = PIPE_W self.build_y = self.floor_y - 229 self.mes_x = (self.game_w - MES_W) / 2 self.mes_y = (self.game_h - MES_H) / 2 self.game_p = self.game_w - DIST - self.pipe_w self.max_s = self.floor_y - MIN_PIPE_H - DIST self.min_pipe_h = MIN_PIPE_H self.end_s_x = (self.game_w - 139) / 2 self.sc_x = (self.game_w - 70) / 2 self.score = 0 self.sprites = pygame.sprite.LayeredUpdates() self.tubes = pygame.sprite.LayeredUpdates() self.background = make_back(self) self.screen.blit(self.background, (0, 0)) ######################################################################## self.floor = Floor(0, self.floor_y, self.game_w) self.floor.mVel = 0 self.bird = Bird(self, self.bird_x, self.bird_y) self.bird.mAcc = 0 self.end_scores = EndScore(self.end_s_x, 200) self.message = Message(self.mes_x, self.mes_y) self.currentS = CurrentScore(self, self.sc_x, 100) ######################################################################## self.sprites.add(self.floor, layer=0) self.sprites.add(self.bird, layer=2) self.sprites.add(self.message, layer=3)
def __init__(self): pygame.init() self.screen_width = 800 self.screen_height = 800 self.screen = pygame.display.set_mode( (self.screen_width, self.screen_height)) pygame.display.set_caption("Flappy Bird") self.screen_rect = self.screen.get_rect() # Background self.top_bg = pygame.image.load("images/top_bg.png") self.top_bg_rect = self.top_bg.get_rect() self.bottom_bg = pygame.image.load("images/bottom_bg.png") self.bottom_bg_rect = self.bottom_bg.get_rect() self.bottom_bg_rect.top = self.top_bg_rect.bottom - 5 # Game title & tap self.title = pygame.image.load("images/title_tap.png") self.title_rect = self.title.get_rect() self.title_rect.x = 170 self.title_rect.y = 100 # Intances of this game self.pipes = pygame.sprite.Group() self.stats = GameStats(self) self.bird = Bird(self) self.scoreboard = Scoreboard(self) self.scoreboard.prep_score_statistic() # Pipe property self.ground_move_rate = 3 self.pipe_collide = None
def start_game(): birds = [] for _ in range(POPULATION): player = Bird(SHAPE) birds.append(player) pipes = init_pipes() return birds, pipes
def run_game(): pygame.init() settings = Settings() clock = pygame.time.Clock() #tela screen = pygame.display.set_mode(settings.SCREEN_DIMENSION) pygame.display.set_caption('Flappy Bird - Python') surface = pygame.image.load('images/bluebird-midflap.png') pygame.display.set_icon(surface) #objetos bird = Bird(settings, screen) ground = Ground(screen, settings) button = Button(screen, settings) game_over = GameOverButton(screen, settings) score = Scoreboard(screen) #grupos ground_group = Group() pipe_up_group = Group() pipe_down_group = Group() #adições ground_group.add(ground) #------------------------------------------------------------------------------------------------------------------- while True: clock.tick(30) function.check_events(bird, screen, settings, pipe_up_group, pipe_down_group, score) function.update_screen(screen, bird, settings, ground_group, button, game_over, pipe_up_group, pipe_down_group, score)