2
votes

I am trying to make a 'Runner' style game in PyGame (like Geometry Dash) where the background is constantly moving. So far everything works fine, but the rendering of the background images restricts the frame rate from exceeding 35 frames per second. Before I added the infinite/repeating background element, it could easily run at 60 fps. These two lines of code are responsible (when removed, game can run at 60+fps):

screen.blit(bg, (bg_x, 0)) | screen.blit(bg, (bg_x2, 0))

Is there anything I could do to make the game run faster? Thanks in advance!

Simplified Source Code:

import pygame
pygame.init()

screen = pygame.display.set_mode((1000,650), 0, 32)
clock  = pygame.time.Clock()

def text(text, x, y, color=(0,0,0), size=30, font='Calibri'): # blits text to the screen
    text = str(text)

    font = pygame.font.SysFont(font, size)
    text = font.render(text, True, color)

    screen.blit(text, (x, y))

def game():
    bg = pygame.image.load('background.png')
    bg_x = 0 # stored positions for the background images
    bg_x2 = 1000

    pygame.time.set_timer(pygame.USEREVENT, 1000)
    frames = 0 # counts number of frames for every second
    fps = 0

    while True:
        frames += 1
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.USEREVENT: # updates fps every second
                fps = frames
                frames = 0 # reset frame count

        bg_x -= 10 # move the background images
        bg_x2 -= 10

        if bg_x == -1000: # if the images go off the screen, move them to the other end to be 'reused'
            bg_x = 1000
        elif bg_x2 == -1000:
            bg_x2 = 1000

        screen.fill((0,0,0))
        screen.blit(bg, (bg_x, 0))
        screen.blit(bg, (bg_x2, 0))

        text(fps, 0, 0)

        pygame.display.update()
        #clock.tick(60)

game()

Here is the background image:

enter image description here

1

1 Answers

1
votes

Have you tried using convert()?

    bg = pygame.image.load('background.png').convert()

From the documentation:

You will often want to call Surface.convert() with no arguments, to create a copy that will draw more quickly on the screen.

For alpha transparency, like in .png images use the convert_alpha() method after loading so that the image has per pixel transparency.