Example #1
0
 def __init__(self):
     self.dinosaur = Dinosaur(win, 500 - 100, 450)
     self.bg_colour = win.fill((255, 255, 255))
     self.cactuses = [Cactus(win, 1000), Cactus(win, 1000)]
     self.bg = pygame.image.load("imgs/floor.png")
     self.timer = time.time()
     self.score = -1
Example #2
0
def make_cactus(set, screen, cacti):

    # Makes new cacti when less than 3 on screen
    limit = len(cacti)

    if limit < set.cacti_allowed:
        new_cactus = Cactus(set, screen)
        cacti.add(new_cactus)
Example #3
0
def run_game():

    crrnt_sttngs = Settings()
    # Screen vars
    screen_width = crrnt_sttngs.screen_width
    screen_height = crrnt_sttngs.screen_height
    bg_color = crrnt_sttngs.bg_color
    # Game vars
    init_speed = crrnt_sttngs.init_speed
    # Misc vars
    logo = pygame.image.load("assets/dino_still_ground.png")

    # Initialize the game and create a screen object
    pygame.init()
    pygame.display.set_icon(logo)
    pygame.display.set_caption("Python Port of chrome://dino")
    screen = pygame.display.set_mode([screen_width, screen_height])

    # Init dino and cactus
    start_bt = Button(crrnt_sttngs, screen, "Play!")
    dino = Dino(screen, crrnt_sttngs)
    cactus = Cactus(screen, crrnt_sttngs, 'small')

    # Main loop of the game
    print("[INFO] The game starts.")
    
    #cactuses = Group()
    
    
    while True:

        # Use the ioresolv module to check events
        ioresolv.check_events(dino)
        dino.update(crrnt_sttngs.dhmax)
        sleep(1/crrnt_sttngs.init_speed)
        cactus.update()
        start_bt.update()
Example #4
0
def criar_obstatuclos(counter, cacti, pteras, clouds):
    last_obstacle = context.last_obstacle

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

    for l in last_obstacle:
        if l.rect.right > context.width * 0.7:
            return

    if len(cacti) < 2:
        r = 10
        if len(cacti) > 0:
            r = random.randrange(0, 60)

        if r == 10:
            last_obstacle.add(Cactus(context, 30, 40))
            return
        elif r == 30:
            last_obstacle.add(Cactus(context, 70, 50))
            return

    if len(pteras) == 0 and random.randrange(0, 100) == 10 and counter > 500:
        last_obstacle.add(Ptera(context, 46, 40))
    def gameloop(self):

        while not self.gameExit:
            self.display.fill(self.white)
            pygame.draw.line(self.display, self.black, (0, self.height - 50),
                             (self.width, self.height - 50))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.gameExit = True
            if self.counter % (random.randrange(100, 110)) == 0:
                self.cac = True
                from cactus import Cactus
                self.cactuses.append(Cactus())
            for c in self.cactuses:
                c.showCactus()
                c.hitbox = [c.rect.x, c.rect.y + 5, 41, 45]
                c.rect.x -= 13
                if c.rect.x <= -c.rect.width:
                    self.cactuses = self.cactuses[1:]
            pic = self.take_photo()
            result = self.predict(pic)
            if result == 0:
                pass
            else:
                self.dino.jump()
            self.dino.updateVariables()
            self.score += 1
            text = pygame.font.Font('freesansbold.ttf', 20)
            textSurf = text.render("Score: " + str(self.score), True,
                                   self.black)
            self.display.blit(textSurf, [10, 10])
            self.dino.show()
            self.dinoHitbox = pygame.Rect(self.dino.hitbox)
            pygame.display.update()
            if self.dino.var > 50:
                self.dino.var -= 10
            if self.collision() and self.cac:
                self.gameExit = True
            self.clock.tick(30)
            self.counter += 1
        pygame.quit()
        self.camera.release()
        cv2.destroyAllWindows()
        quit()
Example #6
0
    def main(self):
        isJump = False
        jumpCount = 10
        clock = pygame.time.Clock()
        score = 0
        while True:

            clock.tick(60)
            #gen cactuses
            if time.time() - self.timer >= random.randrange(1, 40):
                self.timer = time.time()
                self.cactuses.append(Cactus(win, 1000))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            keys = pygame.key.get_pressed()

            if not (isJump):  # Checks is user is not jumping
                if keys[pygame.K_SPACE]:
                    isJump = True
            else:
                # This is what will happen if we are jumping
                if jumpCount >= -10:
                    self.dinosaur.y -= (jumpCount * abs(jumpCount) / 5) * 1
                    jumpCount -= 0.5
                else:  # This will execute if our jump is finished
                    jumpCount = 10
                    isJump = False
                    # Resetting our Variables
            # del cactuses off of screen
            for cactus in self.cactuses:
                if cactus.x < -84:
                    self.cactuses.remove(cactus)
            # Check for collision between dinosaur and cactus
            for cactus in self.cactuses:
                if cactus.collision(self.dinosaur, win):
                    return False
            self.draw()
            pygame.display.update()
Example #7
0
 def updateSprites(self):
     Cactus.update()
     for i in self.sprites:
         if isinstance(i.object, Cactus):
             continue
         i.object.update()
Example #8
0
def createNewP(vel, lista, x):
    if randint(0, 7) < 5:
        lista.append(Cactus(randint(0, 4), vel, x))
    else:
        lista.append(Bird(vel, x))
Example #9
0
def get_cactus():
    return Cactus(Game.win_width, Game.win_height - 221, 96, 96)
Example #10
0
def createNewP(vel, listap, x):
    #or (time.clock() - tempoIni < 20)
    if randint(0, 7) < 5:
        listap.append(Cactus(randint(0, 4), vel, x))
    else:
        listap.append(Bird(vel, x))
Example #11
0
    if random.randint(0, 100) in list(
            range(int(CACTUS_PROBABILITY +
                      CACTUS_SPAWN_GAIN**counter))) and latest > cactus_spacer:
        cacti.append(makeCactus(printer, "resources/cactus/cactus.txt"))
        latest = -1

    if random.randint(0, 100) in list(
            range(int(PTEROSAUR_PROBABILITY + PTEROSAUR_SPAWN_GAIN**counter))
    ) and latest > pterosaur_spacer and counter > 1000:
        pterosaurs.append(
            makePterosaur(printer, "resources/pterosaur/pterosaur1.txt"))
        latest = -1

    # speed = 20
    speed = int(15 + counter * SPEED_GAIN)
    Cactus.changeSpeed(speed)
    Pterosaur.changeSpeed(speed)

    #speed
    speed_string = f"Speed: {speed}"
    printer.putText(printer.term_dim_x - 20 - len(speed_string),
                    8,
                    speed_string,
                    color=colors.blackwhite)

    # Score
    scorestring = f"Score: {counter}"

    # Spacer

    spacerstring = f"Spacer: {cactus_spacer}"
Example #12
0
    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)
Example #13
0
File: main.py Project: 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()
Example #14
0
def makeCactus(printer, path):
    temp_sprite = Sprite.fromFilePath(path)
    printer.attachSprite(temp_sprite)
    return Cactus(temp_sprite, speed=-5)
Example #15
0
def main(genomes, config):
    nn = []  #lista sieci neurnowych
    ge = []  #lista genomów
    dinos = []  #lista dino

    os.environ['SDL_VIDEO_WINDOW_POS'] = '400,50'  # ustiawienie pozycji okna
    window = pygame.display.set_mode(
        (WIN_WIDTH, WIN_HEIGHT))  # stworzenie okna

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(
            g, config)  #stowrzenie sieci neuronowej
        nn.append(net)  #dodanie jej do listy sieci
        dinos.append(Dino(50, 450))  #stworzenie dino i dodanie go do listy
        g.fitness = 0  #ustawienie funkcji fitness
        ge.append(g)  #dodanie genomu do listy

    run = True
    bg = Background(0)
    cactuses = [Cactus()]
    score = 0
    add_cactus = False

    while run:
        cactus_ind = 0
        if len(dinos) > 0:
            if len(cactuses) > 1 and dinos[
                    0].x > cactuses[0].x + cactuses[0].IMG.get_width():
                cactus_ind = 1
        else:
            run = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        for x, dino in enumerate(dinos):
            dino.move()
            output = nn[x].activate((dino.y, dino.x - cactuses[cactus_ind].x))
            if output[0] > 0.5 and not dino.is_jumping:
                dino.jump()
                ge[x].fitness -= 1.5

        remove_cactus = []
        for cactus in cactuses:
            for x, dino in enumerate(dinos):
                if not cactus.passed and cactus.x < dino.x:  # pokonanie przez Dino
                    score += 1
                    cactus.passed = True
                    add_cactus = True
                if cactus.collide(dino):
                    dinos.pop(x)
                    nn.pop(x)
                    ge.pop(x)
            if cactus.x + cactus.IMG.get_width() < 0:  # wyjsce poza ekran
                remove_cactus.append(cactus)

        for cactus in cactuses:
            cactus.move()

        if add_cactus:
            cactuses.append(Cactus())
            for g in ge:
                g.fitness += 3
            add_cactus = False

        for r in remove_cactus:
            cactuses.remove(r)
        bg.move()
        draw_window(window, dinos, bg, cactuses, score)
Example #16
0
        '                                        Available values: [0 .. INT_MAX] (default = 0)'
    )


#
#==============================================================================
if __name__ == '__main__':
    options, fns = parse_options()

    if not fns:
        pass  # error handling

    data = load_data(fns, options)

    if options['dry_run']:
        for d in data:
            d1 = map(lambda x: min(x, options['timeout']), d[1])

            print('{0}:'.format(d[0]))
            print('    # solved: {0}'.format(d[2]))
            print('    min. val: {0:.1f}'.format(float(min(d1))))
            print('    max. val: {0:.1f}'.format(float(max(d1))))
            print('    avg. val: {0:.1f}'.format(float(sum(d1)) / len(d1)))
    else:
        if options['plot_type'] == 'cactus':
            plotter = Cactus(options)
        else:
            plotter = Scatter(options)

        plotter.create(data)
def create_cc(dino_settings, screen, cactus, cactus_num):
    cc = Cactus(dino_settings, screen)
    cc_width = cc.rect.width
    cc.x = 700 * (cactus_num + 1)
    cc.rect.x = cc.x
    cactus.add(cc)