Почему моя платформенная игра в PyGame вдруг стала такой медленной? - PullRequest
1 голос
/ 20 апреля 2020

Итак, у меня есть платформенная игра, которую я сделал в PyGame, которая все работает, поэтому я сейчас пытаюсь сделать ее немного более красочной. Таким образом, код, который я изменил, был:

 def draw(self, screen):
     """ Draw everything on this level. """

     # Draw the background
     screen.fill(BLUE)

, и я изменил его на:

def draw(self, screen):
    """ Draw everything on this level. """

    # Image from http://freepik
    background_image = pygame.image.load("pink background.jpg").convert()

    # Draw the background
    screen.blit(background_image, [0, 0])

, чтобы розовый фон стал фоном :) Теперь это единственный Я изменил код, но теперь все движется гораздо медленнее, например, игрок, которым управляет пользователь, и движущаяся платформа. Есть два уровня, и я не изменил код для фона второго уровня, и игрок все еще прекрасно там двигается :)

Я действительно думал, что мог бы изменить линию:

# Limit to 60 frames per second
clock.tick(60)

случайно, но все равно точно так же.

Я надеюсь, что кто-то может помочь :) и спасибо заранее:)

Ошибка происходит где-то в этом коде: `

def main ():

    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption('Platformer with moving platforms')

    # Create the player
    player = Player()

    # Create all the levels
    level_list = []
    level_list.append(Level_01(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 200
    player.rect.y = SCREEN_HEIGHT - player.rect.height - 30
    active_sprite_list.add(player)

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop --------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.right >= 500:
            diff = player.rect.right - 500
            player.rect.right = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.left <= 120:
            diff = 120 - player.rect.left
            player.rect.left = 120
            current_level.shift_world(diff)

        # If the player touches the floor they die.
        if player.rect.y == SCREEN_HEIGHT - player.rect.height:
            done = True

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:

            all_lines = []
            list_of_files = os.listdir()
            if username1 in list_of_files:
                file1 = open(username1, "r")
                for line in file1:
                    all_lines.append(line)

            all_lines[2] = str(1)

            with open(username1, 'w') as filehandle:
                for listitem in all_lines:
                    filehandle.write(str(listitem))

            done = True

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

        current_level.draw(screen)
        active_sprite_list.draw(screen)

        # Select the font to use, size, bold, italics

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

        # Limit to 60 frames per second
        clock.tick(60)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()

if __name__ == "__main__":
    main()

`

1 Ответ

3 голосов
/ 20 апреля 2020

Не загружайте изображение в основной l oop. Определите (загрузите) его вне l oop и затем используйте его через переменную. Это ваша проблема, потому что он загружает образ (в данном случае FPS = 60) раз в секунду с вашего диска.

...