I am creating a Python game using pygame
. The game is working fine but the more I add characters to the game, the game is getting slower. How can I fix it?
This is the main code:
finish = False
background_x = 0
background_y = 0
REFRESH_RATE = 180
background = pygame.image.load(BACKGROUND_IAMGE)
while not finish:
clock.tick(REFRESH_RATE)
SCREEN.blit(background, (background_x, background_y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
block_on_right = False
block_on_left = False
is_player_on_block = False
for block in blocks:
block.load_image(background_x)
if player.is_crash(block):
for i in range(player.vy):
if player.get_bottom_y() - i == block.get_y():
is_player_on_block = True
if player.y + i == block.get_bottom_y():
player.set_jump(False)
for i in range(player.vx):
if player.get_right_x() - i == block.get_x():
block_on_right = True
if player.x + i == block.get_right_x():
block_on_left = True
for monster in monsters:
if monster.is_crash(block):
monster.turn_around()
keys = pygame.key.get_pressed()
if (keys[pygame.K_UP] or keys[pygame.K_SPACE] or keys[pygame.K_w]) and not player.is_mid_air():
player.set_jump(True)
if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and not block_on_right:
if player.get_direction() != "right":
player.turn_around()
player.set_walk(True)
background_x -= player.vx
player.x += player.vx
if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and not block_on_left:
if player.get_direction() != "left":
player.turn_around()
player.set_walk(True)
if background_x != 0:
background_x += player.vx
player.x -= player.vx
if not any(keys):
player.stand_still()
player.set_walk(False)
for monster in monsters:
SCREEN.blit(monster.get_image(), (background_x + monster.get_x(), monster.get_y()))
monster.step()
if player.get_bottom_y() == FLOOR_Y or is_player_on_block:
player.set_is_mid_air(False)
else:
player.set_is_mid_air(True)
player.fall()
player.check_jump()
player_image = player.get_image().convert()
player_image.set_colorkey(PINK)
SCREEN.blit(player_image, (player.x + background_x, player.y))
pygame.display.flip()
pygame.quit()
I'm no expert at efficiently reducing execution time, but a few tips (see if they help).
Firstly, see if you can do with a slower refresh rate.
Secondly,I noticed you are redrawing the background every iteration. I think there is a way to update only parts of the screen. So you should be able to draw the background once, and then redraw only part of the screen where your characters are. This may help, especially if your background is static.
If it is still slower, see if you can reduce the dimensions of your images (May be a bad idea, but worth a try)
Hope at-least some of these are implementable.