Ejemplo n.º 1
0
class Game(object):
    def __init__(self):
        pygame.init()
        self.camera = Vector2(400, 0)
        self.ground = Ground()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((screenWidth, screenHeight))
        self.player = Player()

    def logicLoop(self):
        self.camera_control()
        self.player.logic(self)

    def camera_control(self):
        lerp = 0.1
        self.camera.x += (self.player.bounds.x - screenWidth / 2 -
                          self.camera.x) * lerp
        self.camera.y += (self.player.bounds.y - screenHeight / 2 -
                          self.camera.y) * lerp

    def drawLoop(self):
        self.screen.fill(0)
        self.player.draw(self.screen, self.camera)
        self.ground.draw(self.screen, self.camera)
        pygame.display.flip()
Ejemplo n.º 2
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.º 3
0
	# EACH EVENT
	for event in pygame.event.get():

		# IF QUIT...
		if event.type == pygame.QUIT:
			run = False


	# DRAW OBJECTS
	# Log Objects
	for i in range(len(logs)):
		logs[i].move()
		logs[i].draw()

	# Other Objects
	top.draw()
	apple.draw()
	bot.draw()
	frog.draw()


	# Move Frog
	if keys[pygame.K_UP]: 	# 'Up' has different calculations than down or side-to-side.

		# if frog

		# Q: How to check for the NEXT log?

		# TOP GROUND
		if frog.y == row[1]:
			frog.y -= 50
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
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.º 6
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.º 7
0
class Application:
    def __init__(self):

        self.display = (1000, 800)  # window'un boyutlari
        self.mouseX = 0  # mouse hareketinin x koordinati
        self.mouseY = 0  # mouse hareketinin y koordinati
        self.flag = False
        self.flag2 = False
        self.currentValue = 0
        self.antenna = Antenna()
        self.plane = Plane()
        self.ground = Ground(100, 100)  # ground'un boyutlari
        self.sidebar = SideBar()

    def resetCamera(self):
        glMatrixMode(
            GL_PROJECTION
        )  # characteristics of camera such as clip planes, field of view, projection method
        glLoadIdentity()  # replace the current matrix with the identity matrix
        width, height = self.display  # display'in degerleri width ve height'a atandi
        gluPerspective(90.0, width / float(height), 1,
                       200.0)  # set up a perspective projection matrix
        glTranslatef(0.0, 0.0,
                     -5)  # multiply the current matrix by a translation matrix
        glEnable(GL_DEPTH_TEST)  # enable server-side GL capabilities
        glMatrixMode(
            GL_MODELVIEW
        )  # model matrix defines the frame’s position of the primitives you are going to draw
        # ModelView is the matrix that represents your camera(position, pointing and up vector.)
        # The reason for two separate matrices, instead of one, is that lighting is applied after the modelview view matrix
        # (i.e. on eye coordinates) and before the projection matrix. Otherwise, the matrices could be combined.

    def start(self):
        glutInit(sys.argv)  # used to initialize the GLUT library
        pygame.init()  # initialize all imported pygame modules
        self.screen = pygame.display.set_mode(
            self.display, OPENGL | DOUBLEBUF
            | OPENGLBLIT)  # initialize a window or screen for display

        glLightfv(GL_LIGHT0, GL_POSITION,
                  (-40, 200, 100, 0.0))  # set light source parameters
        glLightfv(GL_LIGHT0, GL_AMBIENT,
                  (0.2, 0.2, 0.2, 1.0))  # set light source parameters
        glLightfv(GL_LIGHT0, GL_DIFFUSE,
                  (0.5, 0.5, 0.5, 1.0))  # set light source parameters
        glEnable(GL_LIGHT0)  # enable server-side GL capabilities
        glEnable(GL_LIGHTING)  # enable server-side GL capabilities
        glEnable(GL_COLOR_MATERIAL)  # enable server-side GL capabilities
        glEnable(GL_DEPTH_TEST)  # enable server-side GL capabilities
        glShadeModel(GL_SMOOTH)  # most obj files expect to be smooth-shaded

        self.resetCamera()
        self.antenna.prepare()  # antenna objesi olusturuldu
        self.plane.prepare()  # plane objesi olusturuldu
        self.loop()

    def check(self):
        glMatrixMode(GL_PROJECTION)  # kamera ayarlarını sıfırla

        for event in pygame.event.get(
        ):  # pygame.event.get = (get events from the queue)
            if event.type == pygame.QUIT:
                self.plane.stop()  # plane objesi icin thread sona erer
                pygame.quit()  # uninitialize all pygame modules
                quit()

            if event.type == pygame.MOUSEBUTTONDOWN:  # eger mouse'a basili ise
                if event.button == 4:  # forward
                    glScaled(1.05, 1.05, 1.05)  # zoom-in
                elif event.button == 5:  # backward
                    glScaled(0.95, 0.95, 0.95)  # zoom-out

            if pygame.key.get_pressed()[K_LCTRL] and pygame.mouse.get_pressed(
            )[0]:  # object rotation (CTRL ve mouse'un sol butonuna basilmis ise)
                if self.flag == True:  # ilk basistaki hareketi engellemek icin
                    self.mouseX, self.mouseY = pygame.mouse.get_rel(
                    )  # get the amount of mouse movement
                    glRotatef(self.mouseX / 5, 0.0, 0.0, 1.0)
                    glRotatef(self.mouseY / 5, cos(radians(self.currentValue)),
                              abs(sin(radians(self.currentValue))), 0.0)
                    self.currentValue += self.mouseX / 5
                elif self.flag == False:
                    pygame.mouse.get_rel()  # get the amount of mouse movement
                    self.flag = True
            else:
                self.flag = False

            if pygame.key.get_pressed()[K_LCTRL] and pygame.mouse.get_pressed(
            )[2]:  # camera rotation (CTRL ve mouse'un sag kligine basilmis ise)
                if self.flag2 == True:  # ilk basistaki hareketi engellemek icin
                    self.mouseX, self.mouseY = pygame.mouse.get_rel(
                    )  # get the amount of mouse movement
                    glTranslatef(-self.mouseX / 25, self.mouseY / 25, 0.0)
                elif self.flag2 == False:
                    pygame.mouse.get_rel()  # get the amount of mouse movement
                    self.flag2 = True
            else:
                self.flag2 = False

            if event.type == pygame.KEYDOWN and event.key == pygame.K_r:  # eger klavyeye basilmissa ve basilan harf r ise
                self.currentValue = 0
                self.resetCamera()
        glMatrixMode(
            GL_MODELVIEW
        )  # model çizmek için matrisi sıfırla. Applies subsequent matrix operations to the modelview matrix stack.

    def loop(self):
        self.plane.start()  # plane objesi icin thread baslatilir
        self.sidebar.setFunc(self.antenna, self.plane)

        while True:
            glClear(GL_COLOR_BUFFER_BIT
                    | GL_DEPTH_BUFFER_BIT)  # clear buffers to preset values

            self.antenna.rotateToPoint(self.plane.coord[0],
                                       self.plane.coord[1],
                                       self.plane.coord[2])
            self.check()  # mouse ve klavye kontrolleri icin
            self.ground.draw()  # ground objesini cizdir
            self.antenna.draw()  # antenna objesini cizdir
            self.plane.draw()  # plane objesini cizdir
            self.sidebar.draw()  #sidebar objesini cizdir

            pygame.display.flip(
            )  # update the full display surface to the screen
            pygame.time.wait(10)  # pause the program for an amount of time
Ejemplo n.º 8
0
class FlappyBirdUser:
    WIN_WIDTH = 500
    WIN_HEIGHT = 800

    def __init__(self):
        self.running = False
        self.window = pygame.display.set_mode(
            (self.WIN_WIDTH, self.WIN_HEIGHT))
        self.clock = pygame.time.Clock()
        self.score = 0
        self.bird = Bird(230, 350)
        self.ground = Ground(730)
        self.pipes = [Pipe(600)]

    def run(self):
        self.running = True
        while self.running:
            self.loop()
        pygame.quit()
        quit()

    def loop(self):
        self.clock.tick(30)
        self.handle_events()
        add_pipe = False
        pipes_to_remove = []
        for pipe in self.pipes:
            if pipe.collide(self.bird):
                # self.running = False
                pass
            if not pipe.passed and pipe.x < self.bird.x:
                pipe.passed = True
                add_pipe = True
            if pipe.is_out_of_map():
                pipes_to_remove.append(pipe)

        if add_pipe:
            self.score += 1
            self.pipes.append(Pipe(600))

        for pipe_to_remove in pipes_to_remove:
            self.pipes.remove(pipe_to_remove)

        if self.bird.y + self.bird.animation.image.get_height(
        ) >= 730 or self.bird.y < 0:
            self.running = False

        self.update()
        self.draw_window()

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                self.bird.jump()

    def update(self):
        for pipe in self.pipes:
            pipe.move()
        self.bird.move()
        self.ground.move()

    def draw_window(self):
        self.window.blit(BACKGROUND_IMAGE, (0, 0))
        for pipe in self.pipes:
            pipe.draw(self.window)
        self.ground.draw(self.window)
        self.bird.draw(self.window)
        text_score = STAT_FONT.render("Score: " + str(self.score), 1,
                                      (255, 255, 255))
        self.window.blit(text_score,
                         (self.WIN_WIDTH - 10 - text_score.get_width(), 10))

        pygame.display.update()
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)