Ejemplo n.º 1
0
def run_game():
    pygame.init()
    dino_settings = Settings()
    screen = pygame.display.set_mode((dino_settings.screen_width, dino_settings.screen_height))
    pygame.display.set_caption("dino")
    score = float(0)
    while True:
        ground = Ground(dino_settings, screen)
        dinosaur = Dinosaur(dino_settings, screen)
        clouds = Group()
        birds = Group()
        cactus = Group()
        gf.create_clouds(dino_settings, screen, clouds)
        gf.create_birds(dino_settings, screen, birds)
        gf.create_cactus(dino_settings, screen, cactus)
        sb = Scoreboard(dino_settings, screen)
        while not dinosaur.dead:
            gf.check_events(dinosaur)
            ground.update()
            dinosaur.update()
            score += 3
            dino_settings.score = int(score)
            sb.prep_score()
            gf.update_clouds(dino_settings, screen, clouds)
            gf.update_birds(dino_settings, screen, birds, dinosaur)
            gf.update_cactus(dino_settings, screen, cactus, dinosaur)
            gf.update_screen(dino_settings, screen, ground, clouds, dinosaur, cactus, birds, sb)
        while dinosaur.dead:
            exit_game = False
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    if button.rect.collidepoint(mouse_x, mouse_y):
                        exit_game = True
            if exit_game:
                if dino_settings.score > dino_settings.high_score:
                    dino_settings.high_score = dino_settings.score
                    sb.prep_high_score()
                dino_settings.score = 0
                score = 0
                break
            
            button = Button(dino_settings, screen)
            button.blitme()
            pygame.display.flip()
Ejemplo n.º 2
0
def setup():
    window = pygame.display.set_mode((WIDTH, HEIGHT))

    player = Bird(200, 200)
    base = Ground(HEIGHT - ground.GROUND_IMG.get_height() / 2)
    pipes = [Pipe(700)]
    running = True
    simulation_speed = 30

    clock = pygame.time.Clock()

    add_pipe = False
    while running:
        clock.tick(simulation_speed)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    player.jump()

        player.update()
        base.update()
        for pipe in pipes:
            if pipe.collide(player):
                print("you lose")  # no real game end

            if not pipe.passed and pipe.x < player.x:
                pipe.passed = True
                add_pipe = True

            if pipe.x + pipe.img.get_width() < 0:
                pipes.remove(pipe)

            if add_pipe:
                pipes.append(Pipe(700))
                add_pipe = False

            pipe.update()

        draw(window, player, base, pipes)
Ejemplo n.º 3
0
def gameplay():
    global high_score
    context.speed = 4
    context.gameOver = False
    context.gameQuit = False
    start_time = time.time()
    playersDino = [createDino() for i in range(50)]
    playersDino.append(createDino(2))
    print("--- %s seconds ---" % (time.time() - start_time))
    new_ground = Ground(context)
    scb = Scoreboard(context)
    highsc = Scoreboard(context, width * 0.78)
    counter = 0

    cacti = pygame.sprite.Group()
    pteras = pygame.sprite.Group()
    clouds = pygame.sprite.Group()
    context.last_obstacle = pygame.sprite.Group()

    Cactus.containers = cacti
    Ptera.containers = pteras
    Cloud.containers = clouds

    retbutton_image, _ = load_image('replay_button.png', 35, 31, -1)
    gameover_image, _ = load_image('game_over.png', 190, 11, -1)

    temp_images, temp_rect = load_sprite_sheet('numbers.png', 12, 1, 11,
                                               int(11 * 6 / 5), -1)
    HI_image = pygame.Surface((22, int(11 * 6 / 5)))
    HI_rect = HI_image.get_rect()
    HI_image.fill(vl.background_col)
    HI_image.blit(temp_images[10], temp_rect)
    temp_rect.left += temp_rect.width
    HI_image.blit(temp_images[11], temp_rect)
    HI_rect.top = height * 0.1
    HI_rect.left = width * 0.73

    while not context.gameQuit:
        current_score = 0
        while not context.gameOver:
            if pygame.display.get_surface() == None:
                print("Couldn't load display surface")
                context.gameQuit = True
                context.gameOver = True
            else:
                capture_event(context, playersDino)

            for player in playersDino:
                player.status()

            # print(len(context.last_obstacle))
            verificar_colizoes(playersDino, (cacti, pteras))

            criar_obstatuclos(counter, cacti, pteras, clouds)

            if len(playersDino) > 0:
                current_score = playersDino[0].score
            newPlyers = []

            for player in playersDino:
                player.update()
                if (not player.isDead):
                    newPlyers.append(player)
            playersDino = newPlyers
            cacti.update()
            pteras.update()
            clouds.update()
            new_ground.update()

            scb.update(current_score)
            highsc.update(high_score)

            if pygame.display.get_surface() != None:
                screen.fill(vl.background_col)
                new_ground.draw()
                clouds.draw(screen)
                scb.draw()
                if high_score != 0:
                    highsc.draw()
                    screen.blit(HI_image, HI_rect)
                cacti.draw(screen)
                pteras.draw(screen)
                for player in playersDino:
                    player.draw()

                pygame.display.update()
            clock.tick(vl.FPS)

            if len(playersDino) == 0:
                context.gameOver = True
                if current_score > high_score:
                    high_score = current_score

            if counter % 700 == 599:
                context.speed += 1

            counter = (counter + 1)

        if context.gameQuit:
            break

        while context.gameOver:
            if pygame.display.get_surface() == None:
                print("Couldn't load display surface")
                context.gameQuit = True
                context.gameOver = False
            else:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        context.gameQuit = True
                        context.gameOver = False
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            context.gameQuit = True
                            context.gameOver = False

                        if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
                            context.gameOver = False
                            gameplay()
            highsc.update(high_score)
            if pygame.display.get_surface() != None:
                disp_gameOver_msg(retbutton_image, gameover_image)
                if high_score != 0:
                    highsc.draw()
                    screen.blit(HI_image, HI_rect)
                pygame.display.update()
            clock.tick(vl.FPS)

    pygame.quit()
    quit()
Ejemplo n.º 4
0
class game:
    def __init__(self):
        pygame.init()
        self.w = 576
        self.h = 1024
        self.clock = pygame.time.Clock()
        self.win = pygame.display.set_mode((self.w, self.h))

        self.gameOverBoucle = False
        pygame.display.set_caption("Flappy Bird")
        self.bg = pygame.image.load("assets/bg1.png").convert_alpha()
        self.startingimage = pygame.image.load(
            "assets/startingscreen.png").convert_alpha()
        self.launch = False
        self.list_pipes = []
        self.bird = Bird(self.w // 6, 400 - 25)
        self.ground = Ground()
        self.score = Score()

    def runSolo(self):
        self.timeClock = 0
        self.game = True
        self.all_sprites_list = pygame.sprite.RenderUpdates()
        self.all_sprites_list.add(self.bird)
        self.all_sprites_list.add(self.ground)
        self.win.blit(self.bg, (0, 0))
        pygame.display.update()

        while self.game:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game = False
                    sys.exit()

            self.updateScore()
            self.ground.update()
            self.bird.updateImgs()
            self.all_sprites_list.remove(self.bird)
            self.all_sprites_list.add(self.bird)

            keys = pygame.key.get_pressed()
            if keys[pygame.K_SPACE] and not self.launch and self.timeClock > 5:
                self.bird.jump()
                self.launch = True
                self.win.blit(self.bg, (0, 0))
                self.list_pipes.append(Pipe())
                self.all_sprites_list.add(self.list_pipes[-1])

            if keys[pygame.
                    K_SPACE] and self.launch:  # Le joueur appuie sur espace et la partie est lancée
                self.bird.jump(
                )  # Utilise la méthode "Jump" de l'instance bird du jeu

            if self.launch:
                self.bird.affectGravity()  # On affecte la gravité à l'oiseau
                if self.list_pipes[-1].rect.x <= (
                        2 *
                        self.w) // 5:  # Si le dernier Pipe a passé l'oiseau
                    self.list_pipes.append(Pipe(
                    ))  # On créé un nouveau Pipe qui sera généré tout à droite
                    self.all_sprites_list.add(self.list_pipes[-1])

                if self.list_pipes[0].rect.x <= -self.list_pipes[
                        0].w:  # Si le Pipe sort de l'écran
                    self.all_sprites_list.remove(self.list_pipes[0])
                    self.list_pipes.pop(0)  # Supprime le Pipe de la liste

                for pipe in self.list_pipes:  # Itère dans la liste de tous les Pipes
                    pipe.update(
                    )  # Met à jour la position X des Pipes en utilsant leur méthode correspondante
                    if self.bird.collide(
                            pipe
                    ):  # Si la méthode collide de Bird renvoie True = L'oiseau entre en contact avec le Pipe
                        self.launch = False
                        self.game = False
                        self.gameOverScreen(
                        )  # Arrete toutes les variables et lance l'écran de fin
                        return
            else:
                self.win.blit(self.startingimage, (117, 150))

            self.all_sprites_list.remove(self.ground)
            self.all_sprites_list.add(self.ground)

            if self.game:
                self.all_sprites_list.update()
                self.all_sprites_list.clear(self.win, self.bg)
                spriteslist = self.all_sprites_list.draw(self.win)
                pygame.display.update(spriteslist)
                self.score.draw(self.win)
                self.timeClock += 1
            self.clock.tick(30)

    def runBot(self, genomes, config):
        nets = []
        ge = []
        birds = []

        for i, g in genomes:
            net = neat.nn.FeedForwardNetwork.create(g, config)
            nets.append(net)
            birds.append(Bird(self.w // 6, 400 - 25))
            g.fitness = 0
            ge.append(g)

        self.timeClock = 0
        self.game = True

        self.list_pipes.append(Pipe())

        while self.game:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.game = False
                    sys.exit()

            pipe_ind = 0
            if len(birds) > 0:
                if len(self.list_pipes
                       ) > 1 and birds[0].rect.x > self.list_pipes[
                           0].rect.x + self.list_pipes[0].rect.w:
                    pipe_ind = 1
            else:
                self.game = False
                self.reset()
                break

            for x, bird in enumerate(birds):
                bird.updateImgs()
                bird.affectGravity()
                for pipe in self.list_pipes:
                    if pipe.rect.x <= bird.rect.x and pipe.rect.x >= bird.rect.x + self.ground.xspeed:
                        bird.score += 1

                ge[x].fitness += 0.01

                # ici output est la valeur retournée par les gènes
                output = nets[x].activate((
                    bird.rect.y,  # Hauteur de l'oiseau
                    abs(bird.rect.y - (self.list_pipes[pipe_ind].y + 100)),
                    abs(bird.rect.y - (self.list_pipes[pipe_ind].y - 100))
                ))  # ^ Differences de hauteur avec le Pipe du Haut et du Bas

                # Si la valeur est supérieure à 0.5
                if output[0] > 0.5:
                    bird.jump()  # L'oiseau saute

            self.ground.update()

            if self.list_pipes[-1].rect.x <= (2 * self.w) // 5:
                self.list_pipes.append(Pipe())
            if self.list_pipes[0].rect.x <= -self.list_pipes[0].w:

                self.list_pipes.pop(0)
            for pipe in self.list_pipes:
                pipe.update()
                for i, bird in enumerate(
                        birds):  # pour tous les oiseaux encore vivants
                    if bird.collide(pipe):  # Si l'oiseau percute un Pipe
                        ge[i].fitness -= 1  # Décrémente de 1 sa fitness
                        birds.pop(i)  # Retire l'oiseau des oiseaux restants

                        nets.pop(i)
                        ge.pop(i)

                    # Si les oiseaux encore vivants passent un Pipe
                    if pipe.rect.x <= bird.rect.x and pipe.rect.x >= bird.rect.x + self.ground.xspeed:
                        for g in ge:
                            g.fitness += 5  # Augmente de 5 les fitness de tous les oiseaux encore vivants

            if self.game:
                self.win.blit(self.bg, (0, 0))
                for pipe in self.list_pipes:
                    pipe.draw(self.win)
                self.ground.draw(self.win)

                for bird in birds:
                    bird.draw(self.win)

                pygame.display.update()
                self.timeClock += 1
            self.clock.tick(30)

    def reset(self):
        self.score.reset()
        self.bird.reset()
        self.list_pipes = []
        self.ground.reset()
        self.win.blit(self.bg, (0, 0))

    def updateScore(self):
        for pipe in self.list_pipes:
            if pipe.rect.x <= self.bird.rect.x and pipe.rect.x >= self.bird.rect.x + self.ground.xspeed:
                self.score.addscore()
                self.win.blit(self.bg, (0, 0))

    def gameOverScreen(self):
        self.gameOverBoucle = True
        self.timeClock = 0
        while self.gameOverBoucle:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.gameOverBoucle = False
                    return
            keys = pygame.key.get_pressed()
            if keys[pygame.K_SPACE] and self.timeClock >= 20:
                self.gameOverBoucle = False
                for pipe in self.list_pipes:
                    self.all_sprites_list.remove(pipe)
                self.reset()
                self.runSolo()
                return
            self.score.updateNewHighscore(self.win)
            self.all_sprites_list.clear(self.win, self.bg)
            self.bird.draw(self.win)
            for pipe in self.list_pipes:
                pipe.draw(self.win)
            self.ground.draw(self.win)
            self.score.draw(self.win)
            self.score.draw_panel(self.win)
            pygame.display.update()

            self.timeClock += 1
        pygame.quit()
Ejemplo n.º 5
0
class DinoGameEnv:
    def __init__(self):
        self.crow_height_index = 0
        self.i = 0
        self.high_score = 0
        self.nearest = 800
        self.second_nearest = 1000
        self.t_reward = 0

        self.discrete_spaces = np.linspace(1, 8, num=25)

        self.action_complete = True

        self.old_states = []
        self.new_states = []

        self.allow_rendering = False

        pygame.mixer.pre_init(44100, -16, 2, 2048) # fix audio delay
        pygame.init()

        self.scr_size = (self.width,self.height) = (600,150)
        self.FPS = 60

        # background_col = (235,235,235)
        self.background_col = (255,255,255)

        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.scr_size)
        pygame.display.set_caption("T-Rex Rush")

        temp_images,temp_rect = self.load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1)
        self.HI_image = pygame.Surface((22,int(11*6/5)))
        self.HI_rect = self.HI_image.get_rect()
        self.HI_image.fill(self.background_col)
        self.HI_image.blit(temp_images[10],temp_rect)
        temp_rect.left += temp_rect.width
        self.HI_image.blit(temp_images[11],temp_rect)
        self.HI_rect.top = self.height*0.1
        self.HI_rect.left = self.width*0.73

    def render(self):
        if pygame.display.get_surface() != None:
            self.screen.fill(self.background_col)
            self.new_ground.draw()
            # clouds.draw(screen)
            self.scb.draw()
            if self.high_score != 0:
                self.highsc.draw()
                self.screen.blit(self.HI_image,self.HI_rect)
            self.cacti.draw(self.screen)
            self.crows.draw(self.screen)
            self.playerDino.draw()

            pygame.display.update()

    def load_sprite_sheet(
            self,
            sheetname,
            nx,
            ny,
            scalex = -1,
            scaley = -1,
            colorkey = None,
            ):
        fullname = os.path.join('sprites_copy',sheetname)
        sheet = pygame.image.load(fullname)
        sheet = sheet.convert()

        sheet_rect = sheet.get_rect()

        sprites = []

        sizex = sheet_rect.width/nx
        sizey = sheet_rect.height/ny

        for i in range(0,ny):
            for j in range(0,nx):
                rect = pygame.Rect((j*sizex,i*sizey,sizex,sizey))
                image = pygame.Surface(rect.size)
                image = image.convert()
                image.blit(sheet,(0,0),rect)

                if colorkey is not None:
                    if colorkey is -1:
                        colorkey = image.get_at((0,0))
                    image.set_colorkey(colorkey,RLEACCEL)

                if scalex != -1 or scaley != -1:
                    image = pygame.transform.scale(image,(scalex,scaley))

                sprites.append(image)

        sprite_rect = sprites[0].get_rect()

        return sprites,sprite_rect

    def reset(self):
        self.gamespeed = 4
        self.startMenu = False
        self.gameOver = False
        self.gameQuit = False
        self.playerDino = Dino(44,47)
        self.new_ground = Ground(-1*self.gamespeed)
        self.scb = Scoreboard()
        self.highsc = Scoreboard(self.width*0.78)
        self.counter = 0

        self.t_reward = 0
        self.crow_height_index = 0

        self.nearest = 800
        self.second_nearest = 1000
        self.action_complete = True

        self.cacti = pygame.sprite.Group()
        self.crows = pygame.sprite.Group()
        self.last_obstacle = pygame.sprite.Group()

        Cactus.containers = self.cacti
        Crow.containers = self.crows

        self.old_states = []
        self.new_states = []

        self.old_states.append(self.new_ground.speed/-4)
        self.old_states.append(np.digitize(9.0, self.discrete_spaces))
        self.old_states.append(np.digitize(9.0, self.discrete_spaces))
        self.old_states.append(self.crow_height_index)
        # self.old_states.append("Crouch" if self.playerDino.rect[2] != 44 else " standing")
        self.old_states.append(0 if self.playerDino.rect[2] != 44 else 1)

        self.play()

        return np.array(self.old_states, dtype=np.float64)

    def play(self):
        for c in self.cacti:
            c.movement[0] = -1*self.gamespeed
            if pygame.sprite.collide_mask(self.playerDino,c):
                self.playerDino.isDead = True

        for p in self.crows:
            p.movement[0] = -1*self.gamespeed
            if pygame.sprite.collide_mask(self.playerDino,p):
                self.playerDino.isDead = True

        if len(self.cacti) < 2:
            if len(self.cacti) == 0:
                self.last_obstacle.empty()
                self.last_obstacle.add(Cactus(self.gamespeed,40,40))
            else:
                for l in self.last_obstacle:
                    if l.rect.right < self.width*0.7 and random.randrange(0,200) == 10:
                        self.last_obstacle.empty()
                        self.last_obstacle.add(Cactus(self.gamespeed, 40, 40))

        if len(self.crows) == 0 and random.randrange(0,200) == 30 and self.counter == 1:
            for l in self.last_obstacle:
                if l.rect.right < self.width*0.7:
                    self.last_obstacle.empty()
                    self.last_obstacle.add(Crow(self.gamespeed, 40, 40))

        self.playerDino.update()
        self.cacti.update()
        # self.crows.update()
        self.new_ground.update()
        self.scb.update(self.playerDino.score)

        all_loc = []
        self.nearest = 1000
        self.crow_height_index = 0

        for c in self.cacti:
            if c.rect.left > 80:
                all_loc.append(c.rect.left)
                if c.rect.left < self.nearest:
                    self.nearest = c.rect.left

        for p in self.crows:
            if p.rect.left > 80:
                all_loc.append(p.rect.left)
                if p.rect.left < self.nearest:
                    self.nearest = p.rect.left
                    self.crow_height_index = p.crow_height_index + 1

        if len(all_loc) > 1:
            all_loc.remove(min(all_loc))
            self.second_nearest = min(all_loc)
        else:
            self.second_nearest += self.playerDino.rect.right

        # print(nearest - self.playerDino.rect.right, second_nearest - self.playerDino.rect.right)

        self.new_states = []

        self.new_states.append(self.new_ground.speed/-4)
        # self.new_states.append(np.digitize(self.nearest, self.discrete_spaces))
        self.new_states.append(np.digitize(round(self.nearest / self.playerDino.rect.right,2), self.discrete_spaces))
        self.new_states.append(np.digitize(round(self.second_nearest / self.playerDino.rect.right,2), self.discrete_spaces))
        self.new_states.append(self.crow_height_index)
        # self.new_states.append("Jump" if self.playerDino.rect[1] != 100 else "running")
        # self.new_states.append("Crouch" if self.playerDino.rect[2] != 44 else " standing")
        self.new_states.append(0 if self.playerDino.rect[2] != 44 else 1)


        if(self.playerDino.rect[1] == 100 and (self.playerDino.rect[2] == 44 or self.playerDino.rect[2] == 59)):
            self.i = 0
            self.action_complete = True

        if(self.playerDino.rect[1] != 100):
            self.i += 1

        self.highsc.update(self.high_score)

        if self.allow_rendering:
            self.render()

        self.clock.tick(self.FPS)

        if self.playerDino.isDead:
            # print('Reward: -1000')

            # print("final_ states: ", self.new_states)
            # print("<<<<<<GAME OVER>>>>>>>")
            self.gameOver = True
            # self.reset()

        if self.counter%700 == 699:
            self.new_ground.speed -= 1
            self.gamespeed += 1
            self.t_reward += 99

        self.counter = (self.counter + 1)

    def step(self, action): ## 0 - stay, 1 - jump, 2 - crouch, 3 - standup
        # while not self.gameQuit:
        #     while not self.gameOver:
        self.t_reward = 0
        if True:
            if action == 0: ## event.key == pygame.K_SPACE
                self.action_complete = False
                if self.playerDino.rect.bottom == int(0.98*self.height):
                    self.playerDino.isJumping = True
                    # if pygame.mixer.get_init() != None:
                    #     jump_sound.play()
                    self.playerDino.movement[1] = -1*self.playerDino.jumpSpeed
                    # self.t_reward -= 36
                while True:
                    self.play()
                    if self.action_complete :
                        self.action_complete = False
                        break

            if action == 1:      ## event.key == pygame.K_DOWN
                # if not (self.playerDino.isJumping and self.playerDino.isDead):
                #     self.playerDino.isDucking = True

                self.play()

            if action == 2:
                self.playerDino.isDucking = False
                self.play()

            if action == 4:
                self.close()
                return 0, 0, True
            else:
                self.play()

        self.t_reward += 1

        if self.gameOver:

            self.t_reward -= 101

        return np.array(self.new_states), self.t_reward, self.gameOver

        # self.close()

    def close(self):
        pygame.display.quit()
        pygame.quit()
        quit()
Ejemplo n.º 6
0
Archivo: main.py Proyecto: ginus4/Trex
def gameplay():
    global high_score
    gamespeed = 4
    startMenu = False
    gameOver = False
    gameQuit = False
    playerDino = Dino(44,47)
    new_ground = Ground(-1*gamespeed)
    scb = Scoreboard()
    highsc = Scoreboard(width*0.78)
    counter = 0

    cacti = pygame.sprite.Group()
    pteras = pygame.sprite.Group()
    clouds = pygame.sprite.Group()
    last_obstacle = pygame.sprite.Group()

    Cactus.containers = cacti
    Ptera.containers = pteras
    Cloud.containers = clouds

    retbutton_image,retbutton_rect = load_image('replay_button.png',35,31,-1)
    gameover_image,gameover_rect = load_image('game_over.png',190,11,-1)

    temp_images,temp_rect = load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1)
    HI_image = pygame.Surface((22,int(11*6/5)))
    HI_rect = HI_image.get_rect()
    HI_image.fill(background_col)
    HI_image.blit(temp_images[10],temp_rect)
    temp_rect.left += temp_rect.width
    HI_image.blit(temp_images[11],temp_rect)
    HI_rect.top = height*0.1
    HI_rect.left = width*0.73

    while not gameQuit:
        while startMenu:
            pass
        while not gameOver:
            if pygame.display.get_surface() == None:
                print("Couldn't load display surface")
                gameQuit = True
                gameOver = True
            else:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        gameQuit = True
                        gameOver = True

                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_SPACE:
                            if playerDino.rect.bottom == int(0.98*height):
                                playerDino.isJumping = True
                                if pygame.mixer.get_init() != None:
                                    jump_sound.play()
                                playerDino.movement[1] = -1*playerDino.jumpSpeed

                        if event.key == pygame.K_DOWN:
                            if not (playerDino.isJumping and playerDino.isDead):
                                playerDino.isDucking = True

                    if event.type == pygame.KEYUP:
                        if event.key == pygame.K_DOWN:
                            playerDino.isDucking = False
            for c in cacti:
                c.movement[0] = -1*gamespeed
                if pygame.sprite.collide_mask(playerDino,c):
                    playerDino.isDead = True
                    if pygame.mixer.get_init() != None:
                        die_sound.play()

            for p in pteras:
                p.movement[0] = -1*gamespeed
                if pygame.sprite.collide_mask(playerDino,p):
                    playerDino.isDead = True
                    if pygame.mixer.get_init() != None:
                        die_sound.play()

            if len(cacti) < 2:
                if len(cacti) == 0:
                    last_obstacle.empty()
                    last_obstacle.add(Cactus(gamespeed,40,40))
                else:
                    for l in last_obstacle:
                        if l.rect.right < width*0.7 and random.randrange(0,50) == 10:
                            last_obstacle.empty()
                            last_obstacle.add(Cactus(gamespeed, 40, 40))

            if len(pteras) == 0 and random.randrange(0,200) == 10 and counter > 500:
                for l in last_obstacle:
                    if l.rect.right < width*0.8:
                        last_obstacle.empty()
                        last_obstacle.add(Ptera(gamespeed, 46, 40))

            if len(clouds) < 5 and random.randrange(0,300) == 10:
                Cloud(width,random.randrange(height/5,height/2))

            playerDino.update()
            cacti.update()
            pteras.update()
            clouds.update()
            new_ground.update()
            scb.update(playerDino.score)
            highsc.update(high_score)

            if pygame.display.get_surface() != None:
                screen.fill(background_col)
                new_ground.draw(screen)
                clouds.draw(screen)
                scb.draw(screen)
                if high_score != 0:
                    highsc.draw(screen)
                    screen.blit(HI_image,HI_rect)
                cacti.draw(screen)
                pteras.draw(screen)
                playerDino.draw(screen)

                pygame.display.update()
            clock.tick(FPS)

            if playerDino.isDead:
                gameOver = True
                if playerDino.score > high_score:
                    high_score = playerDino.score

            if counter%700 == 699:
                new_ground.speed -= 1
                gamespeed += 1

            counter = (counter + 1)

        if gameQuit:
            break

        while gameOver:
            if pygame.display.get_surface() == None:
                print("Couldn't load display surface")
                gameQuit = True
                gameOver = False
            else:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        gameQuit = True
                        gameOver = False
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            gameQuit = True
                            gameOver = False

                        if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
                            gameOver = False
                            gameplay()
            highsc.update(high_score)
            if pygame.display.get_surface() != None:
                disp_gameOver_msg(retbutton_image,gameover_image)
                if high_score != 0:
                    highsc.draw(screen)
                    screen.blit(HI_image,HI_rect)
                pygame.display.update()
            clock.tick(FPS)

    pygame.quit()
    quit()
Ejemplo n.º 7
0
ground = Ground(Rect(0,500,800,300),5)
player_group = pygame.sprite.Group()
player_group.add(player)
running = True

while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False
        elif event.type == ADDCLOUD:
            new_cloud = Cloud()
            clouds.add(new_cloud)
    screen.blit(background, (0, 0))
    pressed_keys = pygame.key.get_pressed()
    player.update(pressed_keys)
    clouds.update()
    ground.update()
    ground.draw(screen)
    clouds.draw(screen)
    player_group.draw(screen)


    
    

    pygame.display.flip()
    framelock.tick(60)
Ejemplo n.º 8
0
def train_model(genomes, config):
    global generation
    nets = []
    ge = []
    birds = []

    generation += 1

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(Bird(200, 200))
        g.fitness = 0
        ge.append(g)

    window = pygame.display.set_mode((WIDTH, HEIGHT))

    base = Ground(HEIGHT - ground.GROUND_IMG.get_height() / 2)
    pipes = [Pipe(700)]
    running = True
    simulation_speed = 30

    clock = pygame.time.Clock()

    add_pipe = False
    score = 0
    while running:
        clock.tick(simulation_speed)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    player.jump()

        pipe_index = 0
        if len(birds) > 0:
            if len(pipes) > 1 and birds[
                    0].x > pipes[0].x + pipes[0].img.get_width():
                pipe_index = 1
        else:
            running = False
            break  #end generation

        base.update()

        for index, bird in enumerate(birds):
            bird.update()
            ge[index].fitness += 0.3

            output = nets[index].activate(
                (bird.y, abs(bird.y - pipes[pipe_index].height),
                 abs(bird.y - pipes[pipe_index].bottom)))

            if output[0] > 0.5:
                bird.jump()

        for pipe in pipes:
            for index, bird in enumerate(birds):
                if pipe.collide(bird):
                    ge[index].fitness = -0.5
                    birds.pop(index)
                    nets.pop(index)
                    ge.pop(index)

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x + pipe.img.get_width() < 0:
                pipes.remove(pipe)

            if add_pipe:
                score += 1
                for g in ge:
                    g.fitness += 5
                pipes.append(Pipe(700))
                add_pipe = False

            pipe.update()

            for index, bird in enumerate(birds):
                if bird.y + bird.img.get_height() >= HEIGHT - 100 or bird.y < 0:
                    bird.y = HEIGHT - bird.img.get_height() - 100
                    birds.pop(index)
                    nets.pop(index)
                    ge.pop(index)

        draw(window, birds, base, pipes, score, generation)
Ejemplo n.º 9
0
 def run(self):
     
     while self.paused[0] == 1:
         pass
     
     sky = Sky(self.queue)
     sun = Sun(self.queue, 300, 100)
     moon = Moon(self.queue, 300, 100)
     ground = Ground(self.queue)
     
     time = 75
     self.shared[0] = time
     day = 0
     seasons = ["spring", "summer", "fall", "winter"]
     season = "spring"
     self.shared[2] = seasons.index(season)
     seasonStages = ["early", "mid", "mid", "late"]
     seasonStage = "mid"
     
     weatherOptions = ["clear", "clear", "clear", "clear", "cloudy", "cloudy", "overcast", "rain", "rain", "storm"]
     weather = choice(weatherOptions)
     self.shared[1] = weatherOptions.index(weather)
     
     self.queue.put(QueueItem("cont"))   
     self.paused[0] = 1
     self.paused[3] = 0
     while self.paused[0] == 1:
         pass
     
     while True:
         
         sky.update(time)
         sun.update(time)
         moon.update(time, day)
         ground.update(time, season, seasonStage, seasons)
         
         sun.draw()
         moon.draw()
         ground.draw()
                
         time += 3
         if time > 1600:
             time = 0
             day += 1
             if day > 15:
                 day = 0
             season = seasons[int(day/4)]
             self.shared[2] = seasons.index(season)
             seasonStage = seasonStages[day%len(seasonStages)]
             
             if season == "winter" and seasonStage == "early":
                 weather = "rain"
             else: 
                 weather = choice(weatherOptions)
         
         self.shared[0] = time
         self.shared[1] = weatherOptions.index(weather)
         self.queue.put(QueueItem("cont"))
         self.paused[0] = 1
         sleep(0.05)
         while self.paused[0] == 1:
             pass
Ejemplo n.º 10
0
class Game:
    def __init__(self):
        # initialize game window, etc
        pygame.init()
        pygame.mixer.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("GEO-Run")
        self.clock = pygame.time.Clock()
        self.speed = 100
        self.gernation = 0

    def eval_genomes(self, genomes, config):
        """
        runs the simulation of the current population of
        players and sets their fitness based on the distance they
        reach in the game.
        """

        self.gernation += 1

        self.score = 0

        self.ground = Ground(*GROUND)

        self.obstacles = [Obstacle()]

        # 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

        # list with neural network of each genum
        self.nets = []
        # list with player
        self.players = []
        # list whit genums
        self.myGenomes = []

        for genome_id, genome in genomes:  # len(genomes) == 30 because of POP_SITZE = 30
            genome.fitness = 0  # start with fitness level of 0
            # creat the first version of a neural network for each genum
            net = neat.nn.FeedForwardNetwork.create(genome, config)
            self.nets.append(net)
            self.players.append(Player(self))
            self.myGenomes.append(genome)

        # start Game
        self.run()

    def run(self):
        # Game Loop
        self.playing = True
        while self.playing and len(
                self.players
        ) > 0:  # only run the game is at least one player is alife
            self.clock.tick(self.speed)
            self.events()
            self.update()
            self.draw()

    def update(self):
        # Game Loop - Update
        self.ground.update()
        for player in self.players:
            player.update()
        for obs in self.obstacles:
            obs.update()

        # determine the next obstacle
        for i, obs in enumerate(self.obstacles):
            if obs.rect.right > PLAYER_X:
                nextObstIndex = i
                break

        for x, player in enumerate(
                self.players
        ):  # give each player a fitness of 0.1 for each frame it stays alive
            self.myGenomes[x].fitness += 0.1

            # Var. for Input layer
            self.nextObs_dis = player.rect.right - self.obstacles[
                nextObstIndex].rect.left
            self.nextObs_hight = self.obstacles[nextObstIndex].rect.height
            self.nextObs_width = self.obstacles[nextObstIndex].rect.width
            self.player_y = player.rect.bottom

            # send player Y-location, next obstacle distance, next obstacle hight, next obstacle widht
            # determine from network whether to jump or not
            output = self.nets[x].activate(
                (self.player_y, self.nextObs_dis, self.nextObs_hight,
                 self.nextObs_width))
            if output[
                    0] > 0.5:  # i use the tanh activation function so result will be between -1 and 1. if over 0.5 jump
                player.jump()

        # check if a player hits the ground - only if falling
        for player in self.players:
            if player.velocity.y > 0:
                hits = pygame.sprite.collide_rect(player, self.ground)
                # if player hits a ground, put him on the ground
                if hits:
                    player.pos.y = self.ground.rect.y
                    player.velocity.y = 0

        # ckeck if a player hits a obstacle
        for obs in self.obstacles:
            if obs.rect.left < PLAYER_X + 30:
                for i, player in enumerate(self.players):
                    hits = pygame.sprite.collide_rect(player, obs)

                    # if a player collide with an obstacle -> fitness -= 1
                    # he is also deleted from all lists
                    # bad code!! because deleting something from a iterating list
                    if hits:
                        self.myGenomes[i].fitness -= 1
                        self.nets.pop(i)
                        self.myGenomes.pop(i)
                        self.players.pop(i)

        # kill old obstacles and count up score
        for i, obs in enumerate(self.obstacles):
            if obs.rect.left < -60:
                self.score += 10
                self.obstacles.pop(i)

                # gives an player reward for passing through a obstical (not required)
                for genome in self.myGenomes:
                    genome.fitness += 5

        # only spawn new obstacles when the last one is far enough away
        if self.obstacles[-1].rect.x < 800:
            self.obstacles.append(Obstacle())

    def events(self):
        # Game Loop - events
        for event in pygame.event.get():
            # check for closing window
            if event.type == pygame.QUIT:
                self.playing = False
                pygame.quit()
                quit()

    def draw(self):
        # Game Loop - draw
        self.screen.fill(BLACK)
        self.ground.draw(self.screen)

        for player in self.players:
            player.draw(self.screen)
        for obs in self.obstacles:
            obs.draw(self.screen)

        # drawing important Informations
        self.draw_text("Score: " + str(self.score), 48, WHITE, WIDTH / 2,
                       HEIGHT / 6)
        self.draw_text("Generation: " + str(self.gernation), 30, WHITE,
                       WIDTH / 2, HEIGHT / 3.5)
        self.draw_text("Alive: " + str(len(self.players)), 30, WHITE,
                       WIDTH / 2, HEIGHT / 3)
        self.draw_text("NextObs_dis: " + str(self.nextObs_dis), 20, WHITE, 100,
                       20)
        self.draw_text("NextObs_hight: " + str(self.nextObs_hight), 20, WHITE,
                       100, 40)
        self.draw_text("NextObs_width: " + str(self.nextObs_width), 20, WHITE,
                       100, 60)
        self.draw_text("Player_Y: " + str(self.player_y), 20, WHITE, 100, 80)

        # *after* drawing everything, flip the display
        pygame.display.flip()

    # for easy text creating
    def draw_text(self, text, size, color, x, y):
        font = pygame.font.SysFont(None, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        self.screen.blit(text_surface, text_rect)
Ejemplo n.º 11
0
class FlappyUnicorn:
    """ A general class to manage the game. """
    def __init__(self):
        """ Constructor """
        pygame.init()
        pygame.mixer.init()

        # Load game icon
        self.game_icon = pygame.image.load('images/game/icon.png')
        pygame.display.set_icon(self.game_icon)

        self.settings = Settings()

        # Set screen dimensions.
        self.SCREEN_HEIGHT, self.SCREEN_WIDTH = self.settings.screen_height, self.settings.screen_width
        pygame.display.set_caption("Flappy Unicorn")
        self.screen = pygame.display.set_mode(
            (self.SCREEN_WIDTH, self.SCREEN_HEIGHT))
        self.screen_rect = self.screen.get_rect()

        self.game_active = False
        self.game_over = False

        self.pillar_time_elapsed = 0
        self.cloud_time_elapsed = 0
        self.clock_tick = 0

        # Audio instance.
        self.audio = Audio()

        # Create start and game over screens.
        self.start_screen = StartScreen(self)
        self.game_over_screen = GameOver(self)

        # Create an animated flying unicorn
        self.unicorn = Unicorn(self)
        self.unicorn_sprite = pygame.sprite.Group(self.unicorn)

        # Create the background
        self.background = Background(self)

        # Create ground.
        self.ground = Ground(self)

        # Create cloud.
        self.clouds = pygame.sprite.Group()

        # Create pillar sprite group.
        self.pillars = pygame.sprite.Group()

        # Create the scoreboard.
        self.scoreboard = Scoreboard(self)

    def run(self):
        """ Main game loop. """

        # Create clock to track time.
        clock = pygame.time.Clock()

        while True:
            # Check key pressed events.
            self._check_key_events()
            self._update_screen()

            # Update clock and time elapsed.
            self.pillar_time_elapsed += clock.get_time()
            self.cloud_time_elapsed += clock.get_time()

            clock.tick(60)

    def _check_key_events(self):
        """ Check for key pressed events. """
        for event in pygame.event.get():
            # Quit / Exit game.
            if event.type == pygame.QUIT:
                sys.exit(0)

            # Key pressed event.
            if event.type == pygame.KEYDOWN:
                self._check_key_down_events(event)

            # Mouse clicked event.
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_position = pygame.mouse.get_pos()
                self._check_button_clicked(mouse_position)

    def _check_key_down_events(self, event):
        """ Respond to a key pressed down event. """

        if not self.game_over and not self.start_screen.screen_active:
            if event.key == pygame.K_SPACE:
                self.unicorn.jump_count = 0
                self.audio.play_sound('wings')

        elif event.key == pygame.K_q:
            sys.exit(0)

        elif event.key == pygame.K_p:
            self.game_active = True
            self.start_screen.screen_active = False

    def _check_button_clicked(self, mouse_position):
        """ Check if player clicked a button and process request. """

        # Start game button
        if self.start_screen.start_button.rect.collidepoint(mouse_position):
            self.game_active = True
            self.start_screen.screen_active = False
            pygame.mouse.set_visible(False)

        # Retry Button
        if self.game_over_screen.retry_button.rect.collidepoint(
                mouse_position):
            self.restart()

    def _check_unicorn_collision(self):
        """ Respond to a collision event. """

        for unicorn in self.unicorn_sprite:
            if unicorn.rect.bottom >= self.settings.gnd_col_zone or unicorn.rect.top <= self.screen_rect.top:
                self._game_over_loop()
                self.audio.play_sound('hit')
                return

        obstacle_collision = pygame.sprite.groupcollide(
            self.unicorn_sprite, self.pillars, False, False)
        if obstacle_collision:
            self._game_over_loop()
            self.audio.play_sound('hit')

    def _check_clouds(self):
        """ Manage clouds on screen. """

        if self.cloud_time_elapsed > self.settings.cloud_frequency and len(
                self.clouds) < self.settings.cloud_qty:
            self.cloud_time_elapsed = 0
            new_cloud = Cloud(self)
            self.clouds.add(new_cloud)

        self._check_cloud_edges()

    def _check_cloud_edges(self):
        """ Loop through cloud sprites and check if cloud is still on screen.
            Remove clouds that have scrolled off the display.
        """
        for cloud in self.clouds:
            if cloud.cloud_rect.right <= 0:
                self.clouds.remove(cloud)

    def _create_pillar(self):
        """ Create a new pillar object and add to the pillar sprite group. """
        top_pillar = PillarTop(self)
        bottom_pillar = PillarBottom(self, top_pillar.rect)
        pillars = [top_pillar, bottom_pillar]
        self.pillars.add(*pillars)

    def _check_pillars(self):
        """ A method that manages the pillar obstacles. """

        if self.pillar_time_elapsed > self.settings.pillar_frequency:
            # If a certain time has elapsed (settings.pillar_frequency) create a new pillar.
            self.pillar_time_elapsed = 0
            self._create_pillar()

        self._check_pillar_edges()

    def _check_pillar_edges(self):
        """
            Loop through the group of pillar sprites and check their right edge.
            Remove pillar sprites that have left the screen.
        """
        for pillar in self.pillars.copy():
            if pillar.rect.right <= 0:
                self.pillars.remove(pillar)

    def _perform_checks(self):
        """ Check sprite positions. """

        self._check_pillars()
        self._check_clouds()
        self._check_unicorn_collision()
        self.scoreboard.check_score_zone(self.unicorn_sprite, self.pillars)

    def _update_screen(self):
        """ Update surfaces and flip screen. """

        # Update background image.
        self.background.update()

        if self.game_active:
            self._perform_checks()
            self.scoreboard.update()

            # Draw the pillar sprites that have been added to the pillar sprite group.
            for pillar in self.pillars.sprites():
                pillar.draw_pillars()

            # Update unicorn position and animation.
            self.unicorn_sprite.update()
            self.unicorn_sprite.draw(self.screen)

            # Draw new clouds to screen.
            for cloud in self.clouds.sprites():
                cloud.draw_cloud()

            if not self.game_over:
                # Update scrolling ground position.
                self.ground.update()
                # Update clouds position
                self.clouds.update()
                # Update pillar position
                self.pillars.update()

        elif not self.game_over:
            # Start Screen.
            self.ground.blit_background(start_screen=True)
            self.start_screen.blit_me()
        else:
            self._game_over_loop()

        # Flip the new display to screen.
        pygame.display.flip()

    def _game_over_loop(self):
        """
            Halt game blit game over and retry button to screen.
            Enable mouse cursor.
        """
        self.game_over = True
        self.game_active = False

        if self.unicorn.rect.bottom >= self.screen_rect.bottom:
            self.unicorn.rect.bottom = self.screen_rect.bottom

        self.unicorn_sprite.update(animation=False)
        self.unicorn_sprite.draw(self.screen)
        self.pillars.draw(self.screen)
        self.ground.blit_background()
        self.scoreboard.update()
        self.game_over_screen.blit_me()

        # Enable mouse cursor.
        pygame.mouse.set_visible(True)

    def restart(self):
        """ Reset game attributes and start a new game. """
        self.pillars.empty()
        self.clouds.empty()
        self.unicorn.reset_rect()
        self.scoreboard.score = 0
        self.pillar_time_elapsed = 0
        self.cloud_time_elapsed = 0
        self.game_over = False
        self.game_active = True
        pygame.mouse.set_visible(False)