def new(self): # Initialise sprite groups. self.bird_group = pygame.sprite.Group() self.pipes = pygame.sprite.Group() self.ground_group = pygame.sprite.Group() self.all_sprites = pygame.sprite.Group() # Initialise bird. self.bird = Bird(self) self.bird_group.add(self.bird) self.all_sprites.add(self.bird) # Initialise ground. self.ground = Ground() self.ground_group.add(self.ground) self.all_sprites.add(self.ground) # Initialise bottom pipe. self.pipe_down = Bottom_Pipe(self) self.pipes.add(self.pipe_down) self.all_sprites.add(self.pipe_down) # Initialise top pipe. self.pipe_up = Top_Pipe(self) self.pipes.add(self.pipe_up) self.all_sprites.add(self.pipe_up) self.run()
def reset(): global pipetick, pipes, eventtick, birds, score, fitnesslist, gen, newnetnum pipetick = 240 pipes = [Pipe(screen, 1)] eventtick = 0 score = 0 gen += 1 # print(gen) print(fitnesslist) nets = copy.deepcopy(population.combfunc(fitnesslist, newnetnum)) print(fitnesslist) for i in range(int(popsize * (1 - newnetrate))): birds.append( Bird(screen, copy.deepcopy(nets[random.randint(0, len(nets) - 1)]))) birds[-1].net.mutate() for i in range(int(popsize * newnetrate)): birds.append(Bird(screen)) for i in range(0, popsize): # birds[i].net.mutate() pass for i in range(topkeepnum): print( f'Saved net: {fitnesslist[-(i+1)][0]},fitnesslist: {fitnesslist[-(i+1)][1]},score: {fitnesslist[-(i+1)][0].score}' ) birds.append(Bird( screen, fitnesslist[-(i + 1)] [0].net)) # makes sure the best of the last generation continues fitnesslist = [] for i in birds: i.reset() print('New Generation')
def runGame(self): for i in range(10): globals()["bird" + str(i)] = Bird() globals()["bird" + str(i) + "Show"] = 1 globals()["bird" + str(i)].birdPosition = (BirdPosition[0], np.random.randint( 200, 300)) vector = Vector arena = Arena() pipeHeight = arena.upperPipe1.get_height() running = True screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) surface = pygame.Surface(screen.get_size()) surface = surface.convert() clock = pygame.time.Clock() passing = [1] * 10 while running: clock.tick(30) arena.moveImage() arena.drawBackground(surface) arena.drawPipe(surface) arena.drawBase(surface) arena.drawScore(surface) sum = 0 for i in range(10): if passing[i] == 1: globals()["bird" + str(i) + "Show"], pipePosition = self.gameOver( eval("bird" + str(i)), arena) eval("bird" + str(i)).drawBIrd(surface) eval("bird" + str(i)).movement() passing[i] = globals()["bird" + str(i) + "Show"] horizontalDistance, verticalDistance = vector.distance( eval("bird" + str(i)).birdPosition, pipePosition, pipeHeight) input = np.array([horizontalDistance, verticalDistance]) # Working with Neural Network feedForward = self.neuralNetwork.feedForward( input, eval("neuralNetwork" + str(i))[0], eval("neuralNetwork" + str(i))[1]) eval("bird" + str(i)).neuralNetworkJump(feedForward) elif passing[i] == 0: continue screen.blit(surface, (0, 0)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if np.sum(passing) == 0: break
def main(): global CLOCK, SCREEN, bird, floor, point, last_pipe, point_sound pygame.init() # 初始化pygame pygame.mixer.init() point_sound = ResourceLoader.get_sound("point.wav") wing_sound = ResourceLoader.get_sound("wing.wav") die_sound = ResourceLoader.get_sound("die.wav") CLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # 初始化一个用于显示的窗口 pygame.display.set_caption('flappyBird') # 设置窗口标题. bird = Bird(window_size, wing_sound, die_sound) floor = Floor(window_size) background = ResourceLoader.get_image("background-day.png") message = ResourceLoader.get_image("message.png") message_rect = (message.get_rect(centerx=SCREEN_WIDTH / 2, centery=SCREEN_HEIGHT / 2)) reset() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_SPACE or event.key == K_UP: if not bird.isDie: bird.fly() else: reset() if not bird.isDie: bird.update() floor.update() SCREEN.blit(background, (0, 0)) if not bird.begin_fly and not bird.isDie: SCREEN.blit(message, (message_rect.x, message_rect.y)) else: for i in range(COUNT): center_y = make_center_y() pipe_top = pipes_top[i] pipe_botom = pipes_botom[i] if not bird.isDie: pipe_top.update(center_y) pipe_botom.update(center_y) SCREEN.blit(pipe_top.image, (pipe_top.rect.x, pipe_top.rect.y)) SCREEN.blit(pipe_botom.image, (pipe_botom.rect.x, pipe_botom.rect.y)) SCREEN.blit(floor.image, (floor.rect.x, floor.rect.y)) SCREEN.blit(bird.get_bird_image(), (bird.rect.x, bird.rect.y)) if bird.isDie: game_over = ResourceLoader.get_image("gameover.png") SCREEN.blit(game_over, ( (SCREEN_WIDTH - game_over.get_rect().width) / 2, (SCREEN_HEIGHT - game_over.get_rect().height) / 2)) if bird.begin_fly: show_point() if check_conlision(): bird.die() pygame.display.flip() CLOCK.tick(FPS)
def __init__(self): self.bird = Bird() self.pipes = [Pipe(800), Pipe(1200), Pipe(1600)] self.bestFitness = 0 self.genome = Genome() self.nodeInnovationNo = InnovationNumber() self.connectionInnovationNo = InnovationNumber() self.initGenome() self.evaluator = Evaluator(10, self.genome, self.nodeInnovationNo, self.connectionInnovationNo)
def crossover(cls, bird1, bird2): #swap weight gen_bird1 = bird1.ANN.encode( ) #mutation on a gene so that the actual bird.ANN will not be change gen_bird2 = bird2.ANN.encode() for i in gen_bird1: if ( np.random.rand(0, 100) < CROSSOVER_RATE * 100 ): #Create a random number from 0 and 100 and check with possibility of CROSSOVER_RATE gen_bird1[i], gen_bird2[i] = gen_bird2[i], gen_bird1[1] return [Bird_Class.Bird(gen_bird1), Bird_Class.Bird(gen_bird2)]
def runBird(self, individu, display=False): vector = Vector arena = Arena() pipeHeight = arena.upperPipe1.get_height() bird = Bird() running = True age = 0 if display: screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) surface = pygame.Surface(screen.get_size()) surface = surface.convert() clock = pygame.time.Clock() while running: arena.moveImage() # Draw Arena if display: arena.drawBackground(surface) arena.drawPipe(surface) arena.drawBase(surface) arena.drawScore(surface) # Draw Bird bird.drawBIrd(surface) bird.movement() running, pipePosition = self.gameOver(bird, arena) # Working with vector horizontalDistance, verticalDistance = vector.distance( bird.birdPosition, pipePosition, pipeHeight) input = np.array([horizontalDistance, verticalDistance]) #Working with Neural Network feedForward = self.neuralNetowk.feedForward( input, individu[0], individu[1]) bird.neuralNetworkJump(feedForward) if display: clock.tick(30) screen.blit(surface, (0, 0)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bird.jump(event.key) age += 1 return arena.score + age
def spawn_bird_and_nest(self): x, y = self.gen_bird_starting_pos() if x > 0 and y > 0: bird = Bird(self.size, x, y, self.topological_map, self.bird_lifetime) nest = Nest(self.size, x, y, self.topological_map, self.hatch_time, bird) bird.has_nest = True bird.nest = nest # keep tabs of the book-keeping data self.nest_list.append(nest) self.bird_list.append(bird) self.location_matrix[x][y].append(bird) self.location_matrix[x][y].append(nest) self.recolor(x, y)
def create_new_generation(cls, bird_list): new_generation = [] #selection elite_birds = ANN.selection(bird_list) new_generation.extend(elite_birds) #mutation for i in range(0, round(MUTATION_PERCENTAGE * 100 / POPULATION)): new_generation.append(ANN.mutation(bird_list[i])) # crossover with the elite birds for i in range( round((MUTATION_PERCENTAGE * 100 / POPULATION)), round(((MUTATION_PERCENTAGE * 100 / POPULATION) + (CROSSOVER_PERCENTAGE * 100 / POPULATION)))): new_generation.append( ANN.crossover( bird_list[i], elite_birds[random.randint(0, len(elite_birds) - 1)])[0]) #random bird to increase diversity for i in range(POPULATION - len(new_generation)): new_generation.append(Bird_Class.Bird()) return new_generation
def initializeBirds(self): self.birdsFlock = [Bird() for i in range(0, Globals.NUM_OF_BIRDS)] self.bestSolution = [0.0 for i in range(0, Globals.DIMENSION)] self.bestFitness = 1.0 for bird in range(len(self.birdsFlock)): randPositions = [0.0 for i in range(0, Globals.DIMENSION)] randVelocity = [0.0 for i in range(0, Globals.DIMENSION)] for i in range(0, randPositions.__len__()): randPositions[i] = (Globals.MAXIMUM_X - Globals.MINIMUM_X ) * random.random() + Globals.MINIMUM_X randVelocity[i] = (Globals.MAXIMUM_X * 0.1 - Globals.MINIMUM_X * 0.1) * random.random() + Globals.MINIMUM_X fitness = self.objectiveFunction(randPositions) self.birdsFlock[bird].velocity = randVelocity self.birdsFlock[bird].bestPosition = randPositions self.birdsFlock[bird].bestFitness = fitness self.birdsFlock[bird].currentFitness = fitness self.birdsFlock[bird].position = randPositions if self.birdsFlock[bird].currentFitness < self.bestFitness: self.bestFitness = self.birdsFlock[bird].currentFitness self.bestSolution[0] = self.birdsFlock[bird].position[0] self.bestSolution[1] = self.birdsFlock[bird].position[1]
def __init__(self): global win win = pygame.display.set_mode( (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT)) ### LOADING IMAGE ASSETS ### self.background = pygame.image.load( 'Assets/background.png').convert_alpha() self.background = pygame.transform.scale( self.background, (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT)) self.ground1 = pygame.image.load('Assets/ground.png').convert_alpha() self.ground2 = pygame.image.load('Assets/ground.png').convert_alpha() self.message = pygame.image.load('Assets/message1.png').convert_alpha() self.downflap = pygame.image.load( 'Assets/bluebird-downflap.png').convert_alpha() self.midflap = pygame.image.load( 'Assets/bluebird-midflap.png').convert_alpha() self.upflap = pygame.image.load( 'Assets/bluebird-upflap.png').convert_alpha() self.lower_pipe = pygame.image.load('Assets/pipe.png').convert_alpha() self.upper_pipe = pygame.image.load('Assets/pipe.png').convert_alpha() self.upper_pipe = pygame.transform.rotate(self.upper_pipe, 180) self.zero = pygame.image.load('Assets/0.png').convert_alpha() self.one = pygame.image.load('Assets/1.png').convert_alpha() self.two = pygame.image.load('Assets/2.png').convert_alpha() self.three = pygame.image.load('Assets/3.png').convert_alpha() self.four = pygame.image.load('Assets/4.png').convert_alpha() self.five = pygame.image.load('Assets/5.png').convert_alpha() self.six = pygame.image.load('Assets/6.png').convert_alpha() self.seven = pygame.image.load('Assets/7.png').convert_alpha() self.eight = pygame.image.load('Assets/8.png').convert_alpha() self.nine = pygame.image.load('Assets/9.png').convert_alpha() ### ----------------------- ### self.score = 0 self.ground1_posx = -168 self.ground2_posx = 168 self.ground_posy = 400 # initialize bird object self.bird = list() self.bird.append( Bird.Bird(win, self.downflap, self.midflap, self.upflap)) #initialize pipe object self.pipes = list() self.pipes.append(Pipe.Pipe(win, self.lower_pipe, self.upper_pipe)) self.pipe_timer = 0 self.game_over = False self.clock = pygame.time.Clock()
def csv_to_birds(csvfilename): with open(csvfilename,'r') as csvfile: readCSV = csv.reader(csvfile, delimiter=';') birds = [] for row in readCSV: if row[0] != "filename": birds.append(Bird.Bird(row[0],row[1],row[2],row[3])) return birds
def run_agent(pos, player, queue, sema=None, train=True): global WIDTH, HEIGHT if not train: pygame.init() surface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("FlappyBirdAI") clock = pygame.time.Clock() score = 0 bird = Bird.Bird(WIDTH, HEIGHT, 8) obs = Obstacles.Obstacles(WIDTH, HEIGHT, 30, 50, 125, 200, 2) end = False while not end: if not train: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() end = True if event.type == pygame.MOUSEBUTTONDOWN: end = True obsx, obsy = obs.getClosestObsticle(bird.x, bird.size) data = [ bird.x / WIDTH, bird.y / HEIGHT, obsx / WIDTH, obsy / HEIGHT, bird.velocity / 100 ] jump = player.forward(data, 's') if jump == 1: bird.jump() out = bird.move() obs.moveObstacles() hit, rev = obs.detectCollision(bird.x, bird.y, bird.size) if hit or out or (score > 200000 and train): end = True if train: print(pos, score) if not queue is None: queue.put((pos, score)) else: score += 1 + rev if not train: if hit or out: col = (255, 0, 0) else: col = (0, 255, 0) surface.fill((0, 0, 0)) bird.draw(surface, col) obs.draw(surface) pygame.display.flip() clock.tick(60) if not sema is None: sema.release()
def clear_data(self): self.score = 0 self.bird = Bird.Bird(self.window, self.fpsClock, self.FPS, Coords.Coords((100, int(480 / 2)))) self.curTime = self.prevTime = pg.time.get_ticks() self.time_diff = 3500 self.grass = Grass.Grass(self.window, Coords.Coords((640, 480))) self.cloud = Cloud.Cloud(self.window, Coords.Coords((640, 480))) self.pipes = [Pipe.Pipe(self.window, Coords.Coords((640, 480)))]
def mutation(cls, bird): #change some weights randomly gen = bird.ANN.encode() for i in range(TOTAL_WEIGHT): if (np.random.rand(0, 100) < MUTATION_RATE * 100): gen[i] = np.random.uniform(-1, 1) #random float from -1 to 1 new_bird = Bird_Class.Bird(gen) return new_bird
def selection(cls, bird_list): elite_birds_copy = [ ] #create a copy of list to put all elite bird in to avoid inconsistency problem elite_birds = bird_list[0:round(SELECTION_PERCENTAGE * POPULATION)] for bird in elite_birds: gen = bird.ANN.encode() #encode to gen elite_birds_copy.append( Bird_Class.Bird(gen)) #decode gen to read weight return elite_birds_copy
def __init__(self, game_window): self.game_window = game_window self.obstacles_sprite_group = pygame.sprite.Group() self.flappy_sprite_group = pygame.sprite.Group() self.flappy_bird = Bird(INIT_BIRD_X_POS, INIT_BIRD_Y_POS, 0, BIRD_WIDTH, BIRD_HEIGHT) self.obstacles_list = [] self.spawn_obstacles() self.backgrounds = [] self.spawn_backgrounds() self.background_sprites_group = pygame.sprite.Group() self.add_sprites_to_groups() pygame.font.init() self.running = True self.a_font = pygame.font.SysFont('Courier', 30) self.flappy_font = pygame.font.Font('../res/04B_19__.TTF', 50) self.score_handler = ScoreHandler() self.curr_st_str = "game" self.name = "game" self.stars = [] self.spawn_stars()
def play_bird(): global WIN, GEN win = WIN bird = Bird.Bird(230, 350, BIRD_IMGS) ground = Ground.Ground(730, GROUND_IMG) pipes = [Pipe.Pipe(600, PIPE_IMG)] clock = pygame.time.Clock() score = 0 run = True while run: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bird.jump() bird.move() if ground.collide(bird): run = False add_pipe = False rem = [] for pipe in pipes: if pipe.collide(bird): run = False if not pipe.passed and pipe.x < bird.x: pipe.passed = True add_pipe = True if pipe.x + pipe.PIPE_TOP.get_width() < 0: rem.append(pipe) pipe.move() if add_pipe: score += 1 pipes.append(Pipe.Pipe(600, PIPE_IMG)) for r in rem: pipes.remove(r) ground.move() draw_play_window(win, bird, pipes, ground, score)
def __init__(self): pygame.init() self.Backgrounds = [ 'Sky.png' ] #'WinterMountain.png', 'Mountain.png', 'Basic.png' self.gameWidth = 350 self.indexBackground = random.randint(0, len(self.Backgrounds) - 1) self.gameHeight = 500 self.gameDisplay = pygame.display.set_mode( (self.gameWidth, self.gameHeight)) pygame.display.set_caption('FlappyBird') self.background = pygame.image.load( 'Resources\\Backgrounds\\background' + self.Backgrounds[self.indexBackground]) self.fps = pygame.time.Clock() self.score = 0 self.frameRate = 50 self.bird = Bird(self.gameWidth, self.gameHeight) self.pipes = [ pipes(self.gameWidth, self.gameHeight, 50), pipes(self.gameWidth, self.gameHeight, 300) ]
def updateArena(self): self.vector = Vector self.arena = Arena() self.pipeHeight = self.arena.upperPipe1.get_height() self.pipeWidth = self.arena.upperPipe1.get_width() self.bird = Bird() self.runing = True while self.runing == True: self.clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: self.runing = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.bird.jump(event.key) self.arena.moveImage() #Draw Arena self.arena.drawBackground(self.surface) self.arena.drawPipe(self.surface) self.arena.drawBase(self.surface) self.arena.drawScore(self.surface) #Draw Bird self.bird.drawBIrd(self.surface) self.bird.movement() self.gameOver() horizontalDistance, verticalDistance = self.vector.distance( self.bird.birdPosition, self.pipePosition, self.pipeHeight) self.screen.blit(self.surface, (0, 0)) # pygame.display.flip() pygame.display.update()
def convert_input_to_birdy(line): ''' Parse the bird input to create a bird object. ''' m = line.strip().split('|') name = m[0] mass = float(m[1]) initX = float(m[2]) initY = float(m[3]) radB = float(m[4]) moveX = float(m[5]) moveY = float(m[6]) return Bird(name, mass, initX, initY, radB, moveX, moveY)
def createMap(): screen.fill((255, 255, 255)) screen.blit(background, (0, 0)) # 显示管道 screen.blit(Pipeline.pineUp, (Pipeline.wallk, -300)) screen.blit(Pipeline.pineDowm, (Pipeline.wallk, 500)) Pipeline.updatePipeline() # 显示小鸟 if Bird.dead: Bird.Status = 2 elif Bird.jump: Bird.status = 1 screen.blit(Bird.biredStatus[Bird.status], (Bird.birdX, Bird.birdY)) # 设置小鸟的坐标 Bird.birdUpdate() # 显示分数 screen.blit( font.render('Score: ' + str(Pipeline.score), -1, (255, 255, 255)), (100, 50)) pygame.display.update()
def makeChild(pool): #the procedure to select a new parent. The more the fitness, the more chance that it gets selected N = 0 r = np.random.random() while r > 0: r -= pool[N].fitness N += 1 N -= 1 #the parent clones its dna dna = pool[N].dna.Clone() dna.Mutate() #mutation. TO CHANGE MUTATION RATE, GOTO THE bird.py FILE child = bird.Bird() #new bird object #child's dna is set equal to the parent dna child.dna.Set_Weights(dna.weights) child.dna.Set_Biases(dna.biases) return child
def start(self): self.generation += 1 # init birds self.birds = [] for i in range(self.population): bird = Bird.Bird() self.birds.append(bird) if self.generation > 1: bird.neuron.breed(self.best.save) bird.neuron.mutation() # init pipes self.pipes = [] self.pipe_cooldown = config.cfg['game']['pipe']['spawn-cooldown'] self.spawn_pipe() # init scoring self.score = 0
def crossover(birds, generation): birdTopY = 330 birdLeftX = 250 velocity = 0 birds.sort() newBirds = [] nrBirds = 8 birds = birds[:nrBirds] newBirds += birds # function that mutates birds mutation(newBirds) # crossover magic for i in range(60): indexes = random.sample(range(nrBirds), 2) bird1w1 = np.split(birds[indexes[0]].w1, 2)[0] bird2w1 = np.split(birds[indexes[1]].w1, 2)[1] indexes = random.sample(range(nrBirds), 2) split = random.randint(2, 6) bird1w2 = birds[indexes[0]].w2[0][:split] bird2w2 = birds[indexes[1]].w2[0][split:] indexes = random.sample(range(nrBirds), 2) bird1b1 = np.split(birds[indexes[0]].b1, 2)[0] bird2b1 = np.split(birds[indexes[1]].b1, 2)[1] indexes = random.sample(range(nrBirds), 2) randomBird = random.randint(0, 1) b2 = birds[indexes[randomBird]].b2 w1 = np.concatenate((bird1w1, bird2w1), axis=0) w2 = np.concatenate(([bird1w2], [bird2w2]), axis=1) b1 = np.concatenate((bird1w1, bird2w1), axis=0) input = np.array([[0], [0], [0]]) newBirds.append( Bird(input, w1, w2, b1, b2, birdLeftX, birdTopY, velocity, 0)) return newBirds
def __init__(self, populationSize, starter, nodeInnovation, connectionInnovation): self.nodeInnovation = nodeInnovation self.connectionInnovation = connectionInnovation self.populationSize = populationSize self.config = Configuration() self.highestScore = 0 self.bestGenome = None self.population = [] self.birds = [Bird() for _ in range(populationSize)] self.species = [] for i in range(populationSize): self.population.append(Genome(starter)) self.nextGeneration = [] self.speciesMap = {} self.fitnessMap = {}
def __init__(self, windowWidth, windowHeight, layers, mutation=0.1, populationSize=50): self.populationSize = populationSize self.windowWidth = windowWidth self.windowHeight = windowHeight self.mutation = mutation self.birds = [ Bird(self.windowWidth, self.windowHeight, layers) for _ in range(self.populationSize) ] self.generation = 0 self.matingPool = [] self.bestFitness = 0 self.bestBird = None self.total = 0.0 self.alive = self.populationSize
fitnesslist = [] # probs stored as [[net, fitness],...] font = pygame.font.Font(None, 60) # net settings popsize = 50 newnetrate = 0.1 # fraction of totally random nets newnetnum = 3 # how many parent nets are generated gen = 0 stripemptynets = True topkeepnum = 3 # not included in popnum population = Population() birds = [] for i in range(popsize): # print(i) birds.append(Bird(screen)) # protect innovation def reset(): global pipetick, pipes, eventtick, birds, score, fitnesslist, gen, newnetnum pipetick = 240 pipes = [Pipe(screen, 1)] eventtick = 0 score = 0 gen += 1 # print(gen) print(fitnesslist) nets = copy.deepcopy(population.combfunc(fitnesslist, newnetnum)) print(fitnesslist) for i in range(int(popsize * (1 - newnetrate))):
from Bird import * print('\nClass Instances Of:\n', Bird.__doc__) polly = Bird('Squawk, squawk!') print('\nNumber Of Birds:', polly.count) print('Polly Says:', polly.talk()) harry = Bird('Tweet, tweet!') print('\nNumber Of Birds:', harry.count) print('Harry Says:', harry.talk())
def main(genomes, config): nets = [] ge = [] score = 0 birds = [] #set up neural Network for _, g in genomes: net = neat.nn.FeedForwardNetwork.create(g,config) nets.append(net) birds.append(Bird.Bird(230, 350)) g.fitness = 0 ge.append(g) base = Ground.Base(730) pipes = [Pipe(600)] win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) clock = pygame.time.Clock() run = True while run: clock.tick(30) for event in pygame.event.get(): #click red x button if event.type == pygame.QUIT : run = False pygame.quit() quit() base.move() pipe_ind = 0 if len(birds) > 0: if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width(): pipe_ind = 1 else: run = False break for x, bird in enumerate(birds): bird.move() ge[x].fitness += 0.1 output = nets[x].activate((bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom))) if output[0] > 0.5: bird.jump() add_pipe = False rem = [] for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(bird): ge[x].fitness -= 1 #remove from existence birds.pop(x) nets.pop(x) ge.pop(x) if not pipe.passed and pipe.x < bird.x: pipe.passed = True add_pipe = True if pipe.x + pipe.PIPE_TOP.get_width() < 0: rem.append(pipe) pipe.move() #add pipe if distance good if add_pipe: score += 1 #add 5 fitness to remaining birds for g in ge: g.fitness += 5 pipes.append(Pipe(600)) #remove pipes that have been passed for r in rem: pipes.remove(r) #if bird hits ground / goes off screen for x, bird in enumerate(birds): if bird.y + bird.img.get_height() >= 730 or bird.y < 0: birds.pop(x) nets.pop(x) ge.pop(x) draw_window(win, birds, pipes, base, score)
#sounds #pygame.mixer.music.load(os.path.join("sounds", "music.mid")) sfx_slap = pygame.mixer.Sound(os.path.join("sounds", "slap.wav")) images = { 'f': pygame.image.load(os.path.join("images", "fish.png")).convert_alpha(), 'm': pygame.image.load(os.path.join("images", "mountain.png")).convert_alpha(), 'a': pygame.image.load(os.path.join("images", "alien.png")).convert_alpha(), 'b': pygame.image.load(os.path.join("images", "bird.png")).convert_alpha(), } Fish.getstuff((images['f'], None), sfx_slap) Mountain.getstuff((images['m'], None))#,sounds) Alien.getstuff((images['a'], None)) Bird.getstuff((images['b'], None)) Player.getstuff((images['b'], None)) Bullet.getstuff((images['f'], None), sfx_slap) player = Player.Player() fish = Fish.Fish((0,0)) mountains = pygame.sprite.Group() aliens = pygame.sprite.Group() pools = pygame.sprite.Group() birds = pygame.sprite.Group() bullets = pygame.sprite.Group() def newlevel(level): fish.active = False
from Bird import * print( '\nClass Instances Of:\n' , Bird.__doc__ ) polly = Bird( 'Squawk, squawk!' ) print( '\nNumber Of Birds:' , polly.count ) print( 'Polly Says:' , polly.talk() ) harry = Bird( 'Tweet, tweet!' ) print( '\nNumber Of Birds:' , harry.count ) print( 'Harry Says:' , harry.talk() )