def getRandomList(): """ generates a list of birds with random position and velocity """ listOfBirds = [] for i in xrange(hp.numberOfBirds - hp.numberOfBirds / 10): pos = [ random.randint(hp.x_min + hp.boundaryThreshold, hp.x_max - hp.boundaryThreshold), random.randint(hp.y_min + hp.boundaryThreshold, hp.y_max - hp.boundaryThreshold), random.randint(hp.z_min + hp.boundaryThreshold, hp.z_max - hp.boundaryThreshold) ] # pos[2]=0 speed = random.randint(hp.v_min, hp.v_max) u_x = random.random() plusMinusRandom = random.random() if plusMinusRandom > 0.5: u_x *= -1 u_y = random.random() plusMinusRandom = random.random() if plusMinusRandom > 0.5: u_y *= -1 while u_y**2 + u_x**2 >= 1: u_y = random.random() u_z = math.sqrt(1 - u_x**2 - u_y**2) plusMinusRandom = random.random() if plusMinusRandom > 0.5: u_z *= -1 # u_z=0 direction = [u_x, u_y, u_z] listOfBirds.append(bird.Bird(i, pos, speed, direction, hp.acc_min, 1)) for i in range(hp.numberOfBirds - hp.numberOfBirds / 10, hp.numberOfBirds): pos = [ random.randint(hp.x_min + hp.boundaryThreshold, hp.x_max - hp.boundaryThreshold), random.randint(hp.y_min + hp.boundaryThreshold, hp.y_max - hp.boundaryThreshold), random.randint(hp.z_min + hp.boundaryThreshold, hp.z_max - hp.boundaryThreshold) ] listOfBirds.append(bird.Bird(i, pos, 0, [1, 0, 0], 0, -1)) ##setting the boundary # ct = bird.Bird.birdCount # listOfBirds.append(bird.Bird(ct,[0,0,0],0,[1,0,0],0,-1)) return listOfBirds
def main(): root = Tk() root.title('FlappyBird') canvas = Canvas(width=width, height=height) canvas.pack() game = True ground = g.Ground() ground.move(canvas, 0) background = PhotoImage(file="images/background_day.gif") canvas.create_image(width / 2, height / 2 + 20, image=background) bird = b.Bird() pipes = ps.Pipes() bird.draw(canvas, 0) n = 0 #every 200th loop create a new pipe while game: if n % 100 == 0: n = 0 pipes.add() bird.update(root) for pipe in pipes.pipes: pipe.move() if (pipe.x <= bird.x + bird.size and bird.x - bird.size <= pipe.x + pipe.w): if (pipe.y1 - 1 <= bird.y - bird.size and bird.y + bird.size <= pipe.y2) == False: #game=False pass else: pass pipe.draw(canvas, 1) bird.draw(canvas, 1) ground.move(canvas, 1) root.update() n += 1 root.mainloop()
def nextGeneration(saved_bots, height, surface, colour): # print('\nNew generation') prev_pop_fitnesses = calculateFitness(saved_bots) p_mutation = 0.1 size_mutation = 0.1 # Pick new bots with higher probability based on fitness bots = [] # New bird children = [] # Old birds that brains are inherited from for bot in range(0, len(saved_bots)): new_bot = bird.Bird(height, surface, colour) children.append(pickOne(saved_bots, prev_pop_fitnesses)) new_bot.brain = children[bot].brain bots.append(new_bot) # Children fitnesses new_pop_fitnesses = ([child.fitness for child in children]) # print('Avg fitness old pop :', np.mean(prev_pop_fitnesses), 'Avg fitness new pop: ', np.mean(new_pop_fitnesses)) # Mutate bots' brains for bot in bots: # print('Pre mutation: ', bot.brain.w) bot.brain.mutate(p_mutation, size_mutation) # print('Post mutation: ', bot.brain.w) return bots
def main(): pygame.init() pygame.display.set_caption('Flappy Bird') load_static_data() init = True while True: set_new_background() set_new_pipes() movementInfo = showWelcomeAnimation() # if first iteration if init: birds = [ bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']), bird.Bird(movementInfo['playery'], movementInfo['playerIndexGen']) ] init = False else: for i in range(len(birds)): birds[i].y = movementInfo['playery'] birds[i].playerIndexGen = movementInfo['playerIndexGen'] birds[i].score = 0 # start round mainGame(movementInfo, birds) # breed birds (crossover and mutate) breed(birds)
def __init__(self): self.setup_pygame() self.game_active = False self.score = 0 self.high_score = 0 self.bird = bird.Bird() self.pipes = pipes.Pipes() self.floor_x_pos = 0
def generate_next_generation(birds): elite_birds = int((0.65) * len(birds)) loser_birds = int((0.10) * len(birds)) mutated_birds = int((0.25) * len(birds)) new_generation = [] dict_birds_scores = {} for bird in birds: dict_birds_scores[bird] = bird.fitness # sort dictionary based on fitness sorted_birds = sorted(dict_birds_scores.items(), key=lambda kv: kv[1]) # print(sorted_birds) reverse_sorted_birds = dict(list(reversed(sorted_birds))) # print(reverse_sorted_birds) dict_sorted_birds = dict(sorted_birds) # add loser birds to next generation counter = 0 for key, value in dict_sorted_birds.items(): if counter < loser_birds: newBird = bird_module.Bird(WINDOW_HEIGHT, key.brain.parameters) newBird.score = 0 new_generation.append(newBird) else: break counter += 1 # add elite birds to next generation counter = 0 for k, v in reverse_sorted_birds.items(): if counter < elite_birds: newBird = bird_module.Bird(WINDOW_HEIGHT, k.brain.parameters) newBird.score = 0 new_generation.append(newBird) else: break counter += 1 # pick birds randomly, mutate them randomly, add to next gen for i in range(mutated_birds): new_generation.append(pickOneBird(birds)) return new_generation
def getBestBirdBrain(): pkl_file = open('best_bird.brain', 'rb') best_brain = pickle.load(pkl_file) best_bird = bird_module.Bird(WINDOW_HEIGHT, None) best_bird.brain = best_brain return best_bird
def setup(): size(800, 600) background(200) # global mybir d global score score = 0 global mybird mybird = bird.Bird() mybird.show()
def main(): pygame.init() screen = pygame.display.set_mode((800, 526)) background1 = pygame.image.load("./image/background.png") background2 = pygame.image.load("./image/background.png") ground1 = pygame.image.load("./image/ground.png") ground2 = pygame.image.load("./image/ground.png") title_obj = start_and_end.Title(screen) bird_obj = bird.Bird(screen) # 创建鸟对象 pillar_obj = pillar.Create(screen) # 创建柱子对象 pillar_obj.cre() # 创建柱子对象 tap_obj = start_and_end.Tap(screen) # 创建tap提示对象 start_button_obj = start_and_end.Startbutton(screen) b = 0 # 移动背景用的数字 # 窗口名字 pygame.display.set_caption('flappy bird') score_num = score.Score() score_num.score() while True: # 小鸟跳 bird_obj.jump() # 移动背景 b -= bird.Bird.b move_background(screen, background1, background2, b) if b < -800: b = 0 # 小鸟死 bird_obj.check_die(bird_obj) # 显示标题 title_obj.display() # 显示柱子 pillar_obj.display() # 显示地面 move_background(screen, ground1, ground2, b) # 显示小鸟 bird_obj.display() # 开始按钮 try: start_button_obj.display() if bird_obj.start_flag: del start_button_obj except UnboundLocalError: pass # 显示tap提示 try: if bird_obj.down_speed: del tap_obj elif bird_obj.start_flag: tap_obj.display() except UnboundLocalError: pass # 刷新 pygame.display.update() # 帧数 clock = pygame.time.Clock() clock.tick(200)
def __init__(self, width, height): self.mWidth = width self.mHeight = height self.mBlueSky = sky.Sky(self.mWidth, self.mHeight) self.mGround = ground.Ground(self.mWidth, self.mHeight) self.mMountain = mountain.Mountain(self.mWidth, self.mHeight) self.mMoon = moon.Moon(self.mWidth, self.mHeight) self.mWater = water.Water(self.mWidth, self.mHeight) self.mHouse = house.House(self.mWidth, self.mHeight) self.mCloud = cloud.Cloud(self.mWidth, self.mHeight) self.mBird = bird.Bird(self.mWidth, self.mHeight)
def main(): pygame.init() width = 500 height = 800 WIN = pygame.display.set_mode((width, height)) pygame.display.set_icon( pygame.image.load(os.path.join("imgs", "bird1.png"))) pygame.display.set_caption("Flappy Bird") run = True clock = pygame.time.Clock() b = bird.Bird() bg = background.bg() pipe = Pipe.Pipe() pipes = [pipe] base = Base.Base() score = 0 while run: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: print("Your score: " + str(score)) run = False pygame.quit() quit() add_pipe = False rem = [] for p in pipes: if p.collide(b): print("Your score: " + str(score)) run = False if not p.passed and p.x < b.x: p.passed = True add_pipe = True if p.x + p.pipe_top.get_width() < 0: rem.append(p) if add_pipe: score += 1 pipes.append(Pipe.Pipe()) for r in rem: pipes.remove(r) move(WIN, b, pipes, base) draw(WIN, b, bg, pipes, base, score)
def pickOne(screen, saved_birds): index = 0 r = random.random() while r > 0: r = r - saved_birds[index].fitness index += 1 index -= 1 bird_parent = saved_birds[index] child = bird.Bird(screen, bird_parent.brain) child.mutate() return child
def __setup(self): # create a bird self.bird = bird.Bird(resource.bird_gif, 140, 270) # create pipes self.pipes = [] y = self.__gen_pipe_pos_y() p = Pipe(resource.pipe_up, 500, y) self.pipes.append(p) p = Pipe(resource.pipe_down, 500, y + Game.PIPE_HEIGHT_OFFSET) self.pipes.append(p) self.state = 'INIT' self.record.reset()
def pickOneBird(mating_pool): bird = random.choice(mating_pool) # mutation the birds brain a bit (flipping signs of weights randomly) # don't mutate really good birds even if they were choosen to mutate if bird.score >= 10000: return bird bird.mutate(0.1) # make new bird but copy this birds brain over to new bird newBird = bird_module.Bird(WINDOW_HEIGHT, bird.brain.parameters) newBird.score = 0 return newBird
def __init__(self, width, height, fps): pygame.font.init() game_mouse.Game.__init__(self, "Flappy Bird", width, height, fps) self.state = 'Main Menu' self.main_menu = main_menu.Main_Menu(width, height) self.end_menu = end_menu.End_Menu(width, height) self.pause = pause_menu.Pause_Menu(width, height) self.barriers = barriers.Barriers(height, width) self.bird = bird.Bird(width, height) self.score = score.Score(width, height) self.scores_menu = displayscoresmenu.ScoresMenu(width, height) self.background = background.Background(height, width) self.music = { "state" : "", "songs" : ["sounds/palm-beach.wav", "sounds/chubby-cat.wav", "sounds/the-awakening.wav"], "current" : ""} self.instruction_menu = instruction_menu.InstructionMenu(width, height) self.bugs = [] self.bug = bug.Bug return
def on_init(self): pygame.init() pygame.display.set_caption("Flappy Bird") self._display_surf = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT), pygame.HWSURFACE) self._running = True # set icon icon = pygame.image.load(BIRD_IMG) pygame.display.set_icon(icon) # bird object self.bird = bird.Bird() # images self.bird_image = pygame.image.load(BIRD_IMG) self.buildings_image = pygame.image.load(BG_CITY_IMG) self.sun_image = pygame.image.load(SUN_IMG) # clock self.clock = pygame.time.Clock() # pipe object self.pipe = pipe.Pipe()
def main(genomes, config): global GEN GEN += 1 # inits score = 0 birds = [] base = base_c.Base(730) pipes = [pipe_c.Pipe(600)] win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) nets = [] ge = [] for _, g in genomes: net = neat.nn.FeedForwardNetwork.create(g, config) nets.append(net) birds.append(bird_c.Bird(230, 350)) g.fitness = 0 ge.append(g) # clock clock = pygame.time.Clock() # game loop run = True while run: # FPS clock.tick(30) # quit logic for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() 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() # pipe logic rem = [] add_pipe = False for pipe in pipes: for x, bird in enumerate(birds): if pipe.collide(bird): ge[x].fitness -= 1 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() if add_pipe: score += 1 for g in ge: g.fitness += 5 pipes.append(pipe_c.Pipe(600)) for r in rem: pipes.remove(r) for x, bird in enumerate(birds): if bird.y + bird.img.get_height() >= 730 or bird.y < 0: birds.pop(x) nets.pop(x) # bird move # bird.move() # base move base.move() draw_window(win, birds, pipes, base, score, GEN)
def main(): clock = pygame.time.Clock() framecounter = 0 run = 1 state = 0 f = open("highscore.txt", "r") highscore = f.read() f.close() print(highscore) # main loop while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = 0 if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: run = 0 if state == 0: if event.key == pygame.K_SPACE: b = bird.Bird() first_base = base.Base(0, VELOCITY) bases = [first_base] first_pipe = pipe.Pipe(512, VELOCITY) pipes = [first_pipe] score = 0 distance = 0 flag = 0 activate = False state = 1 elif state == 1: if event.key == pygame.K_SPACE: b.jump() if event.key == pygame.K_d: activate = not activate if state == 0: SCREEN.blit(BG_IMG, (0, 0)) f = open("highscore.txt", "r") highscore = f.read() f.close() hs = FONT.render("HIGHSCORE : " + highscore, True, (255, 255, 255)) SCREEN.blit(hs, (WIDTH // 2 - hs.get_width() // 2, HEIGHT // 2 - hs.get_height() // 2 - 50)) start = FONT.render('Press JUMP (space) to play (esc to quit)', True, (255, 255, 255)) if (framecounter // 25) % 2 == 0: SCREEN.blit(start, (WIDTH // 2 - start.get_width() // 2, HEIGHT // 2 - start.get_height() // 2)) elif state == 1: # Pipes and bases spawning if pipes[-1].x < THRESHOLDS['pipe']: pipes.append(pipe.Pipe(288, VELOCITY)) elif pipes[0].x + pipes[0].sprite1.get_width() < 0: flag = 0 pipes.pop(0) if bases[-1].x < 0: bases.append( base.Base(bases[-1].x + bases[-1].sprite.get_width(), VELOCITY)) elif bases[0].x < THRESHOLDS['base']: bases.pop(0) # Score/distance count if flag == 0: if pipes[0].x < 144: score += 1 flag = 1 distance -= VELOCITY / 10 # Updating and drawing SCREEN.blit(BG_IMG, (0, 0)) b.update() b.draw(SCREEN) for p in pipes: p.update() p.draw(SCREEN) for bs in bases: bs.update() bs.draw(SCREEN) scr = FONT.render('Score : ' + str(score), True, (255, 255, 255)) dist = FONT.render('Distance : ' + str(round(distance)), True, (255, 255, 255)) SCREEN.blit(scr, (0, 0)) SCREEN.blit(dist, (0, 15)) # Animation if framecounter > 12: framecounter = 0 b.img_count = 0 if framecounter > 9: b.img_count = 1 elif framecounter > 6: b.img_count = 2 elif framecounter > 3: b.img_count = 1 # Collision detection for p in pipes: if p.collide(b): if score > int(highscore): f = open("highscore.txt", "w") f.write(str(score)) f.close() state = 0 if b.rect.bottom > 400 or b.y < -50: if score > int(highscore): f = open("highscore.txt", "w") f.write(str(score)) f.close() state = 0 # Update display framecounter += 1 pygame.display.flip() # Clock tick clock.tick(FPS) pygame.quit()
def run(self): """ The main loop for running the game :return: none """ run = True clock = pygame.time.Clock() new_pipe_timer = 0 next_animation_timer = 0 while run: if self.state == state_start_screen: # start background self.draw() # print the headline first_line = self.font.render( 'Welcome to the super cool FlappyPython', False, (255, 255, 255)) self.win.blit(first_line, (round((self.win.get_width() / 2) - (first_line.get_rect().width / 2)), 50)) # print the start button pygame.draw.rect(self.win, (0, 0, 255), (round( (self.win.get_width() / 2)) - 150, 300, 300, 100)) # print the button text button_text = self.font.render('Start', False, (255, 255, 255)) self.win.blit(button_text, (round((self.win.get_width() / 2) - (button_text.get_rect().width / 2)), 325)) # event loop for event in pygame.event.get(): # exit actions if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): run = False # check button click if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() if round((self.win.get_width() / 2)) - 150 <= pos[0] <= round( (self.win.get_width() / 2)) + 150 and 300 <= pos[1] <= 400: self.state = state_start_game # additionally we can progress with space if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.state = state_start_game # display everything pygame.display.update() elif self.state == state_start_game: game_is_running = True self.bird = bird.Bird(self.win, 50, round(self.win.get_height() / 2)) self.score = 0 # delete previous pipes self.pipes = [] while game_is_running: # check for collision of bird with pipes if self.bird.is_colliding(self.pipes): game_is_running = False self.state = state_after_game # set up the game clock dt = clock.tick(60) # print the background self.draw() # set up timers new_pipe_timer += dt next_animation_timer += dt if new_pipe_timer > 1500: self.pipes.append(self.create_new_pipe()) new_pipe_timer = 0 # move pipes and check for border collisions for singlepipe in self.pipes: singlepipe.move_left() if singlepipe.out_of_frame(): self.pipes.remove(singlepipe) self.score += 1 del singlepipe else: singlepipe.draw() # bird movement if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: self.bird.go_up() if next_animation_timer > 250: self.bird.next_animation() else: self.bird.go_down() next_animation_timer = 0 # print the bird self.bird.draw() # print the score score_message = self.font.render( 'Score: ' + str(self.score), False, (255, 0, 0)) self.win.blit(score_message, (0, 0)) # event loop for event in pygame.event.get(): # exit options if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): game_is_running = False run = False # display everything pygame.display.update() else: # self.state == end something # game is over, print an end message end_message = self.font.render( 'YOU FAILED!! Your score is: ' + str(self.score), False, (255, 0, 0)) self.win.blit(end_message, (round((self.win.get_width() / 2) - (end_message.get_rect().width / 2)), round((self.win.get_height() / 2) - (end_message.get_rect().height / 2)))) # print the menue button pygame.draw.rect(self.win, (0, 0, 255), (round( (self.win.get_width() / 2)) - 150, 400, 300, 100)) # print the button text button_text = self.font.render('Back to menue', False, (255, 255, 255)) self.win.blit(button_text, (round((self.win.get_width() / 2) - (button_text.get_rect().width / 2)), 425)) # event loop for event in pygame.event.get(): # exit events if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): run = False # button click event if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() if round((self.win.get_width() / 2)) - 150 <= pos[0] <= round( (self.win.get_width() / 2)) + 150 and 400 <= pos[1] <= 500: self.state = state_start_screen # additionally we can progress with space if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: self.state = state_start_screen # display everything pygame.display.update()
def play(self): while True: for event in pygame.event.get(): # 退出事件 if event.type == gloc.QUIT: pygame.quit() sys.exit() # 键盘事件 elif event.type == gloc.KEYDOWN: # 空格/上键 if event.key == gloc.K_SPACE or event.key == gloc.K_UP: # 游戏界面,小鸟存活,未暂停 # ----> 游戏开始/小鸟拍翅膀 if (not self.start and not self.ranking and not self.setting and not self.paused and self.bird.alive): self.pressed = True # 限制小鸟高度 if self.bird.rect.top > -2 * self.bird.rect.height: self.bird.fly() self.sound['wing_sound'].play() # P键/Esc键 elif event.key == gloc.K_p or event.key == gloc.K_ESCAPE: # 游戏界面,小鸟存活,未暂停 # ----> 游戏暂停/开始 if (not self.start and not self.ranking and not self.setting and self.pressed and self.bird.alive): self.paused = not self.paused # G键 elif event.key == gloc.K_g: if self.start and not hasattr(self, "ai_model"): self.init_vars(ai=True) self.ai_model = DoubleDQN() # 鼠标移动事件 elif event.type == gloc.MOUSEMOTION: # 设置界面 if self.setting and self.mouse_down: pos = pygame.mouse.get_pos() # RGB设置 # 身体 if pygame.Rect(64, 195, 40, 11).collidepoint(pos): self.body_rgb[0] = (pos[0] - 64) * 255 / 40 self.R1_set.set_point(self.body_rgb[0] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(125, 195, 40, 11).collidepoint(pos): self.body_rgb[1] = (pos[0] - 125) * 255 / 40 self.G1_set.set_point(self.body_rgb[1] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(189, 195, 40, 11).collidepoint(pos): self.body_rgb[2] = (pos[0] - 189) * 255 / 40 self.B1_set.set_point(self.body_rgb[2] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) # 嘴 elif pygame.Rect(64, 245, 40, 11).collidepoint(pos): self.mouth_rgb[0] = (pos[0] - 64) * 255 / 40 self.R2_set.set_point(self.mouth_rgb[0] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(125, 245, 40, 11).collidepoint(pos): self.mouth_rgb[1] = (pos[0] - 125) * 255 / 40 self.G2_set.set_point(self.mouth_rgb[1] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(189, 245, 40, 11).collidepoint(pos): self.mouth_rgb[2] = (pos[0] - 189) * 255 / 40 self.B2_set.set_point(self.mouth_rgb[2] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) # 音量设置 elif pygame.Rect(105, 352, 110, 15).collidepoint(pos): self.volume = (pos[0] - 105) * 100 / 110 self.volume_set.set_point(self.volume / 100) pygame.mixer.music.set_volume(self.volume * 0.4 / 100) elif pygame.Rect(105, 402, 110, 15).collidepoint(pos): self.sound_volume = (pos[0] - 105) * 100 / 110 self.sound_set.set_point(self.sound_volume / 100) for i in self.sound.keys(): self.sound[i].set_volume( self.sound_volume * self.sound_default[i] / 100) # 移出区域视为设置结束 else: self.mouse_down = False # 鼠标点击释放 elif event.type == gloc.MOUSEBUTTONUP: # 设置界面 if self.setting and self.mouse_down: self.mouse_down = False # 鼠标点击事件 elif event.type == gloc.MOUSEBUTTONDOWN: pos = event.pos # 鼠标左键 if event.button == 1: # 开始界面 if self.start: # 进入游戏界面 if self.start_image_rect.collidepoint(pos): self.start = False # 进入排行界面 elif self.score_image_rect.collidepoint(pos): self.start = False self.ranking = True # 进入设置界面 elif self.setting_image_rect.collidepoint(pos): self.start = False self.setting = True # 排行榜界面 elif self.ranking: # 回到开始界面 if self.back_rect.collidepoint(pos): self.ranking = False self.start = True # 设置界面 elif self.setting: # 回到开始界面 if self.setting_image_rect.collidepoint(pos): self.start = True self.setting = False setting.write_json(self.bird_color, self.background_index, self.volume, self.sound_volume) # 小鸟设置 elif pygame.Rect(52, 105, 30, 30)\ .collidepoint(pos): self.bird_color = (self.bird_color - 1) % 5 self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(202, 105, 30, 30)\ .collidepoint(pos): self.bird_color = (self.bird_color + 1) % 5 self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) # RGB设置 # 身体 elif pygame.Rect(64, 195, 40, 11)\ .collidepoint(pos): self.mouse_down = True self.body_rgb[0] = (pos[0] - 64) * 255 / 40 self.R1_set.set_point(self.body_rgb[0] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(125, 195, 40, 11)\ .collidepoint(pos): self.mouse_down = True self.body_rgb[1] = (pos[0] - 125) * 255 / 40 self.G1_set.set_point(self.body_rgb[1] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(189, 195, 40, 11)\ .collidepoint(pos): self.mouse_down = True self.body_rgb[2] = (pos[0] - 189) * 255 / 40 self.B1_set.set_point(self.body_rgb[2] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) # 嘴 elif pygame.Rect(64, 245, 40, 11)\ .collidepoint(pos): self.mouse_down = True self.mouth_rgb[0] = (pos[0] - 64) * 255 / 40 self.R2_set.set_point(self.mouth_rgb[0] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(125, 245, 40, 11)\ .collidepoint(pos): self.mouse_down = True self.mouth_rgb[1] = (pos[0] - 125) * 255 / 40 self.G2_set.set_point(self.mouth_rgb[1] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) elif pygame.Rect(189, 245, 40, 11)\ .collidepoint(pos): self.mouse_down = True self.mouth_rgb[2] = (pos[0] - 189) * 255 / 40 self.B2_set.set_point(self.mouth_rgb[2] / 255) self.customize_bird.seperate( self.body_rgb, self.mouth_rgb) self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color) # 背景设置 elif pygame.Rect(100, 292, 30, 30)\ .collidepoint(pos): self.background_index = ( self.background_index - 1) % 3 if self.background_index != 2: self.background = self.background_list[ self.background_index] elif pygame.Rect(200, 292, 30, 30)\ .collidepoint(pos): self.background_index = ( self.background_index + 1) % 3 if self.background_index != 2: self.background = self.background_list[ self.background_index] # 音量设置 elif pygame.Rect(105, 352, 110, 15)\ .collidepoint(pos): self.mouse_down = True self.volume = (pos[0] - 105) * 100 / 110 self.volume_set.set_point(self.volume / 100) pygame.mixer.music.set_volume(self.volume * 0.4 / 100) elif pygame.Rect(105, 402, 110, 15)\ .collidepoint(pos): self.mouse_down = True self.sound_volume = (pos[0] - 105) * 100 / 110 self.sound_set.set_point(self.sound_volume / 100) for i in self.sound.keys(): self.sound[i].set_volume( self.sound_volume * self.sound_default[i] / 100) # 分享画面 elif self.share: if self.copy_rect.collidepoint(pos): try: share.copy(self.image_data) except AttributeError: pass elif self.save_rect.collidepoint(pos): share.save(self.image_data) elif self.email_rect.collidepoint(pos): share.send_email(self.image_data, self.score) elif self.back_rect.collidepoint(pos): self.share = False # 游戏界面,小鸟存活 elif (self.pressed and self.bird.alive and self.pause_image_rect.collidepoint(pos)): self.paused = not self.paused # ----> 游戏开始/小鸟拍翅膀 elif not self.paused and self.bird.alive: self.pressed = True # 限制小鸟高度 if self.bird.rect.top > -2 * self.bird.rect.height: self.bird.fly() self.sound['wing_sound'].play() # 游戏结束界面 elif not self.bird.alive: pos = pygame.mouse.get_pos() if self.retry_rect.collidepoint(pos): self.init_vars() self.start = False elif self.share_rect.collidepoint(pos): self.image_data = pygame.surfarray.array3d( pygame.display.get_surface()) self.share = True elif self.menu_rect.collidepoint(pos): self.init_vars() # 游戏基础画面 self.screen.blit(self.background, (0, 0)) # 绘制地面 self.screen.blit(self.land.image, self.land.rect) if self.bird.alive and not self.paused: self.land.move() # 游戏开始画面 if self.start: # 绘制游戏名 self.screen.blit(self.title, self.title_rect) # 绘制开始按钮 self.screen.blit(self.start_image, self.start_image_rect) # 绘制排行按钮 self.screen.blit(self.score_image, self.score_image_rect) # 绘制设置按钮 self.screen.blit(self.setting_image, self.setting_image_rect) # 设置 elif self.setting: self.screen.blit(self.board_image, self.board_rect) self.screen.blit(self.setting_image, self.setting_image_rect) # 绘制小鸟设置 self.screen.blit(self.array_left, (52, 105)) self.screen.blit(self.array_right, (202, 105)) if self.bird_color in [0, 1, 2]: self.screen.blit( self.bird.images[self.bird.image_index(self.delay)], (120, 100)) elif self.bird_color == 3: self.screen.blit( self.random_bird[self.bird.image_index(self.delay)], (120, 100)) self.screen.blit( self.random_text, ((self.width - self.random_text.get_width()) // 2, 150)) elif self.bird_color == 4: self.screen.blit( self.bird.images[self.bird.image_index(self.delay)], (120, 100)) self.screen.blit( self.custom_text, ((self.width - self.custom_text.get_width()) // 2, 150)) self.screen.blit( self.body_text, ((self.width - self.body_text.get_width()) // 2, 170)) self.body_rgb = list(self.bird.images[0].get_at((23, 24))) self.screen.blit(self.R_text, (50, 190)) self.R1_set.set_point(self.body_rgb[0] / 255) self.R1_set.display() self.screen.blit(self.G_text, (113, 190)) self.G1_set.set_point(self.body_rgb[1] / 255) self.G1_set.display() self.screen.blit(self.B_text, (175, 190)) self.B1_set.set_point(self.body_rgb[2] / 255) self.B1_set.display() self.screen.blit( self.mouth_text, ((self.width - self.mouth_text.get_width()) // 2, 220)) self.mouth_rgb = list(self.bird.images[0].get_at((30, 27))) self.screen.blit(self.R_text, (50, 240)) self.R2_set.set_point(self.mouth_rgb[0] / 255) self.R2_set.display() self.screen.blit(self.G_text, (113, 240)) self.G2_set.set_point(self.mouth_rgb[1] / 255) self.G2_set.display() self.screen.blit(self.B_text, (175, 240)) self.B2_set.set_point(self.mouth_rgb[2] / 255) self.B2_set.display() # 绘制背景设置 self.screen.blit(self.bg_text, (50, 300)) self.screen.blit(self.array_left, (100, 292)) self.screen.blit(self.array_right, (200, 292)) self.screen.blit(self.bg_text_list[self.background_index], (150, 300)) # 绘制音量设置 self.screen.blit(self.volume_text, (50, 350)) self.volume_set.display() # 绘制音效设置 self.screen.blit(self.sound_text, (50, 400)) self.sound_set.display() # 排行界面 elif self.ranking: self.screen.blit(self.board_image, self.board_rect) if self.value is None: self.value = score.Sql.get_score() for i in range(len(self.value)): self.screen.blit(self.cups[i], self.cup_rects[i]) time_tran = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime( self.value[i][0])).split() score_text = self.rank_font.render(str(self.value[i][1]), True, (0, 0, 0)) time_text1 = self.setting_font.render( time_tran[0], True, (0, 0, 0)) time_text2 = self.setting_font.render( time_tran[1], True, (0, 0, 0)) self.screen.blit( score_text, (self.cup_rects[i][0] + 50, self.cup_rects[i][1] + 10)) self.screen.blit( time_text1, (self.cup_rects[i][0] + 95, self.cup_rects[i][1] + 5)) self.screen.blit(time_text2, (self.cup_rects[i][0] + 105, self.cup_rects[i][1] + 23)) self.screen.blit(self.back_image, self.back_rect) # 分享画面 elif self.share: self.screen.blit(self.board_image, self.board_rect) self.screen.blit(self.copy_image, self.copy_rect) self.screen.blit(self.save_image, self.save_rect) self.screen.blit(self.email_image, self.email_rect) self.screen.blit(self.back_image, self.back_rect) # 游戏画面 else: # 准备画面 if not self.pressed: # 绘制小鸟 self.screen.blit( self.bird.images[self.bird.image_index(self.delay)], self.bird.rect) # 绘制ready self.screen.blit(self.ready_image, self.ready_rect) # 绘制press开始 self.screen.blit(self.press_start_image, self.press_start_rect) else: # 移动小鸟 if not self.paused: self.bird.move(self.delay) if self.ai and not self.paused and self.bird.alive: self.screen.blit(self.bg_black, (0, 0)) # 绘制pipe for upipe, dpipe in zip(self.upperpipes, self.lowerpipes): self.screen.blit(upipe.image, upipe.rect) self.screen.blit(dpipe.image, dpipe.rect) # 绘制小鸟 self.screen.blit(self.bird.image, self.bird.rect) # 绘制地面 self.screen.blit(self.land.image, self.land.rect) if self.ai and not self.paused and self.bird.alive: img = pygame.surfarray.array3d( pygame.display.get_surface()) if not hasattr(self.ai_model, "currentState"): self.ai_model.currentState = \ self.ai_model.set_initial_state(img) self.ai_model.currentState = \ self.ai_model.update_state(img) _, action_index = self.ai_model.getAction() if action_index == 1: if self.bird.rect.top > -2 * self.bird.rect.height: self.bird.fly() if self.bird.alive: # 绘制分数 score.display(self.screen, self.bg_size, self.score) if not self.paused: # 绘制暂停按钮 self.screen.blit(self.pause_image, self.pause_image_rect) # 移动pipe for upipe, dpipe in zip(self.upperpipes, self.lowerpipes): upipe.move() dpipe.move() else: # 绘制继续按钮 self.screen.blit(self.resume_image, self.resume_image_rect) # 生成和删除pipe if 0 < self.upperpipes[0].rect.left < 5: new_upipe, new_dpipe = pipe.get_pipe( self.bg_size, self.land.rect.top) self.upperpipes.append(new_upipe) self.lowerpipes.append(new_dpipe) self.pipe_group.add(new_upipe, new_dpipe) if self.upperpipes[0].rect.right < 0: self.pipe_group.remove(self.upperpipes[0], self.lowerpipes[0]) self.upperpipes.pop(0) self.lowerpipes.pop(0) # 得分 if self.bird.alive: for upipe in self.upperpipes: if (upipe.rect.centerx <= self.bird.rect.centerx < upipe.rect.centerx + 4): self.score += 1 self.sound['point_sound'].play() # 检测碰撞 if self.bird.alive and self.checkCrash(): self.bird.alive = False self.sound['hit_sound'].play() self.sound['die_sound'].play() # 游戏结束画面 if not self.bird.alive: # 绘制gameover字样 self.screen.blit(self.gameover_image, self.gameover_image_rect) # 绘制成绩面板 self.screen.blit(self.score_panel, self.score_panel_rect) score.show_score(self.screen, self.bg_size, self.score) if not self.recorded and self.value is None: self.value = score.Sql.get_score() if self.value: best_score = self.value[0][1] score.show_best(self.screen, self.bg_size, best_score) # 绘制奖牌 if self.score >= 100: self.screen.blit(self.white_medal, self.medal_rect) elif self.score >= 60: self.screen.blit(self.gold_medal, self.medal_rect) elif self.score >= 30: self.screen.blit(self.silver_medal, self.medal_rect) elif self.score >= 10: self.screen.blit(self.brooze_medal, self.medal_rect) # 绘制重新开始 self.screen.blit(self.retry_image, self.retry_rect) self.screen.blit(self.share_image, self.share_rect) self.screen.blit(self.menu_image, self.menu_rect) # 保存分数 if not self.recorded: new_record = score.Sql.set_score(self.score) self.value = score.Sql.get_score() self.recorded = True if new_record: self.screen.blit(self.new_image, self.new_rect) # 画面刷新 self.delay = (self.delay + 1) % 30 pygame.display.update() self.clock.tick(30)
def init_vars(self, ai: bool = False): # 读取设置 (self.bird_color, self.background_index, self.volume, self.sound_volume) = setting.read_config() # 设置音量 pygame.mixer.music.set_volume(self.volume * 0.4 / 100) for i in self.sound.keys(): self.sound[i].set_volume(self.sound_volume * self.sound_default[i] / 100) # 游戏分数 self.score = 0 # 背景 if self.background_index == 2: pipe.PIPE_INDEX = random.choice([0, 1]) elif self.background_index in [0, 1]: pipe.PIPE_INDEX = self.background_index self.background = self.background_list[pipe.PIPE_INDEX] # 是否开挂 self.ai = ai # 游戏开始画面 self.start = True # 排行榜画面 self.ranking = False self.value = None # 设置画面 self.setting = False self.mouse_down = False self.R1_set = setting.Setting_line(self.screen, rect=(64, 199), lenth=40, point=0.5, color=(255, 0, 0), height=3) self.G1_set = setting.Setting_line(self.screen, rect=(125, 199), lenth=40, point=0.5, color=(0, 255, 0), height=3) self.B1_set = setting.Setting_line(self.screen, rect=(189, 199), lenth=40, point=0.5, color=(0, 0, 255), height=3) self.R2_set = setting.Setting_line(self.screen, rect=(64, 249), lenth=40, point=0.5, color=(255, 0, 0), height=3) self.G2_set = setting.Setting_line(self.screen, rect=(125, 249), lenth=40, point=0.5, color=(0, 255, 0), height=3) self.B2_set = setting.Setting_line(self.screen, rect=(189, 249), lenth=40, point=0.5, color=(0, 0, 255), height=3) self.volume_set = setting.Setting_line(self.screen, rect=(105, 358), lenth=110, point=self.volume / 100, color=(230, 100, 0)) self.sound_set = setting.Setting_line(self.screen, rect=(105, 408), lenth=110, point=self.sound_volume / 100, color=(230, 100, 0)) # 游戏画面 self.bird = bird.Bird(self.bg_size, self.land.rect.top, self.bird_color, ai=ai) self.delay = 0 self.paused = False self.pressed = False self.upperpipes = [] self.lowerpipes = [] self.pipe_group = pygame.sprite.Group() if not ai: upipe, dpipe = pipe.get_pipe(self.bg_size, self.land.rect.top, self.width + 200) else: upipe, dpipe = pipe.get_pipe(self.bg_size, self.land.rect.top, self.width) self.upperpipes.append(upipe) self.lowerpipes.append(dpipe) self.pipe_group.add(upipe, dpipe) if not ai: upipe, dpipe = pipe.get_pipe(self.bg_size, self.land.rect.top, 1.5 * self.width + 200) else: upipe, dpipe = pipe.get_pipe(self.bg_size, self.land.rect.top, 1.5 * self.width) self.upperpipes.append(upipe) self.lowerpipes.append(dpipe) self.pipe_group.add(upipe, dpipe) # 游戏结束画面 self.recorded = False # 分享画面 self.share = False
import os.path import random import time import pygame import bird import pipe WHITE = pygame.Color(255, 255, 255) pygame.init() screen = pygame.display.set_mode([300, 300]) bird_yellow = bird.Bird(os.path.join('img', 'bird')) pipe = pipe.PipeObstacle(os.path.join('img', 'pipe.png')) tb = round(1000 / 8) t1 = round(time.time() * 1000) i = 0 y = 10 g = 3 n = 300 yy = 0 done = False while not done: t = round(time.time() * 1000) for e in pygame.event.get(): if e.type == pygame.QUIT:
pygame.init() #Create some constant values to make the code more readable. width = 1000 height = 600 white = (255, 255, 255) #r g b #Create the pygame drawing surface and clock screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() #Player starts off with zero points points = 0 #Create the game objects bird = bird.Bird(100, 0, screen) coin = sprite.Sprite(width, 0, "coin.png", screen) walls = wall.Wall(screen) #Run the main game loop running = True while running: #Check for events such as user input for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: #The up key will send the bird upward if event.key == pygame.K_UP: bird.dy = bird.dy - 4 #The escape key will close the game
def main(): try: with open('pets.csv', 'r') as f: reader = csv.reader(f) your_list = list(reader) for i in range(0, len(your_list)): if your_list[i][0] == 'Dog': d = dog.Dog(your_list[i][1], your_list[i][2], your_list[i][3],your_list[i][4]) name_list.append(d.name) elif your_list[i][0] == 'Cat': c = cat.Cat(your_list[i][1], your_list[i][2], your_list[i][3], your_list[i][4]) name_list.append(c.name) elif your_list[i][0] == 'Fish': f = fish.Fish(your_list[i][1], your_list[i][2], your_list[i][3], your_list[i][4]) name_list.append(f.name) elif your_list[i][0] == 'Bird': b = bird.Bird(your_list[i][1], your_list[i][2], your_list[i][3], your_list[i][4]) name_list.append(b.name) # Show only pets of a certain type # Based on the user input, show only the pets that are dogs/cats/fish/birds. def animal_type(enter): for i in range(0, len(your_list)): if your_list[i][0] == enter.title(): print('-', your_list[i][3]) return '' # Search for a Pet - # you will call your own binary search function to search for the first pet name that matches the user entered string. # If a pet is found in the list, then print all the details for that pet and the index in the list where it was found. # If the pet is not in the list, then print a message informing the user that the pet is not in the list. def search(enter): low = 0 high = len(your_list)-1 insertion_sort_name(your_list) while low <= high: mid = int((low + high) / 2) if ' ' + enter.title() == your_list[mid][1]: print("The index is " + str(mid) + " in the list.") return your_list[mid] elif ' ' + enter.title() < str(your_list[mid][1]): high = mid - 1 else: # enter > your_list[mid] low = mid + 1 return 'The pet is not in the list.' # Sort list based on pet name - # For all the sort options you can implement either selection sort or insertion sort on the list of pet objects. # After sorting the list, display the sorted list. def insertion_sort_name(list): keyIndex = 1 while keyIndex < len(list): insert_nameorder(list, keyIndex) keyIndex += 1 def insert_nameorder(list, keyIndex): key = list[keyIndex][1] j = keyIndex -1 while (list[j][1] >= key) and (j >= 0): list[j + 1][1] = list[j][1] j -= 1 list[j + 1][1] = key # Sort list based on pet color - After sorting the list, display the sorted list. def insertion_sort_color(list): keyIndex = 1 while keyIndex < len(list): insert_colororder(list, keyIndex) keyIndex += 1 def insert_colororder(list, keyIndex): key = list[keyIndex][4] j = keyIndex - 1 while (list[j][4] >= key) and (j >= 0): list[j + 1][4] = list[j][4] j -= 1 list[j + 1][4] = key print('Your Pet Finder menu: ') print('===========================') enter1 = 0 while enter1 != 6: print('1. Display the names of all the pets.') print('2. Certain types of pets.') print('3. Search for a Pet.') print('4. Sort list based on pet name.') print('5. Sort list based on pet color.') print('6. Exit the program.') enter1 = float(input('Enter your choice: ')) if enter1 == 1: # Print only the names of all the pets print('Here are the names of pets:') print(name_list) print('') elif enter1 == 2: enter2 = input('What kind of pet would you like to see (dog/cat/fish/bird): ') print(animal_type(enter2)) elif enter1 == 3: enter3 = input('Search pet name: ') print(search(enter3)) print('') elif enter1 == 4: insertion_sort_name(your_list) print('Sorted list: ', your_list) print('') elif enter1 == 5: insertion_sort_color(your_list) print('Sorted list: ', your_list) print('') elif enter1 == 6: exit() else: print('Invalid value.') except IOError: print('An error occurred trying to read') print('Non-numeric data is allowed.') print('Your Pet Finder menu: ') print('===========================') print('1. Display the names of all the pets.') print('2. Certain types of pets.') print('3. Search for a Pet.') print('4. Sort list based on pet name.') print('5. Sort list based on pet color.') print('6. Exit the program.') enter1 = float(input('Enter your choice: ')) except ValueError: print('Non-numeric data is allowed.') print('Your Pet Finder menu: ') print('===========================') print('1. Display the names of all the pets.') print('2. Certain types of pets.') print('3. Search for a Pet.') print('4. Sort list based on pet name.') print('5. Sort list based on pet color.') print('6. Exit the program.') enter1 = float(input('Enter your choice: ')) except Exception as err: print(err) print('Non-numeric data is allowed.') print('Your Pet Finder menu: ') print('===========================') print('1. Display the names of all the pets.') print('2. Certain types of pets.') print('3. Search for a Pet.') print('4. Sort list based on pet name.') print('5. Sort list based on pet color.') print('6. Exit the program.') enter1 = float(input('Enter your choice: '))
# Window pygame.display.update() clock.tick(120) # Global variables screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() background = create_background() floor = create_floor() score_font = create_score_font() high_score = get_high_score() flapper = bird.Bird(screen, 125, height / 2, pygame, gravity, upswing) pipe_queue = [] # Pipe spawn timer pygame.init() SPAWNPIPE = pygame.USEREVENT pygame.time.set_timer(SPAWNPIPE, 1200) def start_game(): pygame.display.set_caption("Flappy Bird") bird_icon = pygame.image.load('assets/yellowbird-upflap.png').convert() pygame.display.set_icon(bird_icon) while True: logic() draw_all()
birds = [] savedBirds = [] score = 0 current_generation = 0 pipesOnScreen = [] BackGround = Background('background.png', [0, 0]) if type_of_play == 'best': totalBirds = 1 birds.append(getBestBirdBrain()) elif type_of_play == 'train': totalBirds = 400 # initialize totalBirds for i in range(totalBirds): # create new bird, add to list of birds birds.append(bird.Bird(size[1], None)) else: totalBirds = 1 flag_key_released = True all_sprites.add(birds) while not done: # Clear the screen and set the screen background screen.fill(BLACK) # screen.blit(BackGround.image, BackGround.rect) for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN:
def main(genomes, config): global WIN, gen SCREEN = WIN gen += 1 # start by creating lists holding the genome itself, the # neural network associated with the genome and the # bird object that uses that network to play nets = [] birds = [] ge = [] for genome_id, genome in genomes: genome.fitness = 0 # start with fitness level of 0 net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) birds.append(bird.Bird()) ge.append(genome) first_base = base.Base(0, VELOCITY) bases = [first_base] first_pipe = pipe.Pipe(512, VELOCITY) pipes = [first_pipe] framecounter = 0 score = 0 distance = 0 flag = 0 activate = False clock = pygame.time.Clock() run = 1 # main loop while run: pipe_ind = 0 if len(birds) > 0: if len(pipes ) > 1 and 144 > pipes[0].x + pipes[0].sprite1.get_width(): pipe_ind = 1 else: run = 0 break for x, b in enumerate( birds ): # give each bird a fitness of 0.1 for each frame it stays alive ge[x].fitness += 0.1 output = nets[birds.index(b)].activate( (b.y, abs(b.y - pipes[pipe_ind].y), abs(b.y - pipes[pipe_ind].bottom))) if output[0] > 0.5: b.jump() # Pipes and bases spawning if pipes[-1].x < THRESHOLDS['pipe']: pipes.append(pipe.Pipe(288, VELOCITY)) elif pipes[0].x + pipes[0].sprite1.get_width() < 0: flag = 0 pipes.pop(0) if bases[-1].x < 0: bases.append( base.Base(bases[-1].x + bases[-1].sprite.get_width(), VELOCITY)) elif bases[0].x < THRESHOLDS['base']: bases.pop(0) # Score/distance count if flag == 0: if pipes[0].x < 144: for genome in ge: genome.fitness += 5 score += 1 flag = 1 distance -= VELOCITY / 10 # Updating and drawing SCREEN.blit(BG_IMG, (0, 0)) for b in birds: b.update() b.draw(SCREEN) for p in pipes: p.update() p.draw(SCREEN) for bs in bases: bs.update() bs.draw(SCREEN) scr = FONT.render('Score : ' + str(score), True, (0, 0, 0)) dist = FONT.render('Distance : ' + str(round(distance)), True, (0, 0, 0)) SCREEN.blit(scr, (0, 0)) SCREEN.blit(dist, (0, 15)) # Animation for b in birds: if framecounter > 12: framecounter = 0 b.img_count = 0 if framecounter > 9: b.img_count = 1 elif framecounter > 6: b.img_count = 2 elif framecounter > 3: b.img_count = 1 framecounter += 1 # Update display pygame.display.flip() # controls for event in pygame.event.get(): if event.type == pygame.QUIT: run = 0 pygame.quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: activate = not activate if event.key == pygame.K_ESCAPE: run = 0 pygame.quit() # Collision detection for p in pipes: for b in birds: if p.collide(b): ge[birds.index(b)].fitness -= 1 nets.pop(birds.index(b)) ge.pop(birds.index(b)) birds.pop(birds.index(b)) for b in birds: if b.rect.bottom > 400 or b.y < -50: ge[birds.index(b)].fitness -= 1 nets.pop(birds.index(b)) ge.pop(birds.index(b)) birds.pop(birds.index(b)) # Clock tick clock.tick(FPS)
def create_Bird(name, age, height, weight, type_of_wings, type_of_beak): """Tworzy obiekt klasy Bird""" return bird.Bird(name, age, height, weight, type_of_wings, type_of_beak)
import pygame import bird, pipe, ga screen = pygame.display.set_mode((600, 600)) screen.fill((0, 0, 0)) POPULATION = 150 birds = [] saved_birds = [] for i in range(POPULATION): birds.append(bird.Bird(screen)) pipes = [] pipes.append(pipe.Pipe(screen)) # initiate fonts for displaying scores current_score = 0 max_score = 0 pygame.font.init() myfont = pygame.font.SysFont('calibri', 20) score_surface = myfont.render(f'Score: {current_score}', False, (255, 255, 255)) max_score_surface = myfont.render(f'Max Score: {max_score}', False, (255, 255, 255)) # create buttons plus_button = pygame.image.load('plus.png').convert_alpha() minus_button = pygame.image.load('minus.png').convert_alpha() plus_b = screen.blit(plus_button, (screen.get_width() - 140, 20)) minus_b = screen.blit(minus_button, (screen.get_width() - 140, 40))
import bird import datetime import penguin import parrot today_time = datetime.datetime.now() print(today_time) bird1 = bird.Bird() print(bird1.get_attribute()) bird2 = penguin.Penguin("Apu vai") print(bird2.get_attribute()) bird3 = parrot.Parrot("Tipu") print(bird3.get_attribute())