添加背景pygame后游戏开始滞后

时间:2020-06-26 10:44:06

标签: pygame

当我使用screen.fill制作背景时,我的代码正在检查英雄与大量射弹的碰撞-程序仍然没有滞后。但是当我决定添加绘制的背景(3600x1200 pix)作为精灵时,fps下降到约20 fps。我删除了所有弹丸,但fps仍然非常低。选择如此大的背景来移动它,而不是移动主要英雄。这是我的代码和显示背景的问题行(没有它,一切都很好)。

#import modules
import pygame as pg
from hero import Hero
#self-made classes
from obstruction import Obstruction
from setting import Settings
import gf
from time import sleep
**from back_ground import Background**
from command_block import Command_Line
#main function
def run_game():
    #pygame activation
    pg.init()
    #window settings
    settings = Settings()
    screen = pg.display.set_mode((settings.screen_width,settings.screen_height))
    pg.display.set_caption(settings.caption)
    hero = Hero(0, 0, "Right", 1/240, pg.image.load('images/hero/hero1.png'), 128, 16, 15, 0.08, 0.2, settings,27)
    bg = Background('images/sky.png', [0,0])
    cl = Command_Line(hero)
    #class creating
    projectiles = []
    #here was some projectile creating
    #variables initialization etc.
    work=True
    myfont = pg.font.SysFont('TimesNewRoman',int(settings.screen_width*0.025))
    #main loop
    while work:
        sleep()
        hero.is_running = False
        hero.idle = True
        gf.check_events(hero, projectiles, settings, cl)
        gf.jump(hero, projectiles)
        #updating hero rect due to coordinate changing and hero image due to direction changing
        hero.update_rect()
        hero.orientation()
        #screen filling with backgroung color
        screen.fill([255, 255, 255])
        screen.blit(bg.image, bg.rect)
        #displaying projectiles(walls,floor,etc.)
        for projectile in projectiles:
            projectile.display(screen)
        #displaying hero image and all his atributes
        hero.display(screen, myfont)
        gf.command_block_draw(settings,myfont,screen,cl)
        #test string for displaying problematic variables
        gf.test_string_draw(settings,myfont,hero,screen)
        #display updating
        pg.display.flip()
    #quit
    pg.quit()

#running game
run_game()

行:

screen.blit(bg.image, bg.rect)

BackGround类:

import pygame as pg

class Background(pg.sprite.Sprite):
    def __init__(self, image_file, location):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location

1 个答案:

答案 0 :(得分:0)

确保对图像进行convert()。

更改这一行代码将大大提高您的性能。

它可以将Surface转换为pygame预先喜欢的格式,从而加快所有后续的blit。

mem used 0