运行时问题 - 加载和 bliting 图像

Runtime question - loading and bliting images

如果图像在数组中,我无法以正常速度 blit 图像。 #brife评论 在我的代码中,我将 10 张图像定义为变量 (x1-x10) 这 100 张图像与特定 class (object.draw_function()) 相关,并将根据特定条件在主循环中进行 bliting。 在 object.draw_function() 中,所有图像都保存在 lst "images_lst" = [img1,img2,img3,img10] 并根据规则从该数组中进行 bliting。

我注意到如果数组的 len 大于 4,5 ,循环 FPS 就会变慢。我不明白为什么?加载图像在循环之外。

代码示例:

#loading images
img1 = pygame.image.load(r'images\game_background1\img1.jpg')
img2 = pygame.image.load(r'images\game_background1\img2.jpg')
img3 = pygame.image.load(r'images\game_background1\img3.jpg')
'
'
'
img10= pygame.image.load(r'images\game_background1\img10.png')

#define font and space size
space_width,space_height = pysical_tm_img.get_width(),pysical_tm_img.get_height() 
font0_0 = pygame.font.SysFont(pygame.font.get_fonts()[0],12)
font0_02 = pygame.font.SysFont(pygame.font.get_fonts()[0],17)    

# define class
class EXAMPLE():
    def __init__(self,x,y,text,power,energy,range):
        self.rect = pygame.Rect(x,y,100,10)
        self.text = text
        self.power = power
        self.energy = energy
        self.range = range

    def draw_func(self,surface):
                img_lst = [img1,text1,img2,text2,img3,text3......img10,text10] 
   
        for i,img in enumerate(img_lst):
            if i % 2 == 0 :
                img_rect = img.get_rect(center=(self.rect.x +20 +  (i *space_width*2),self.rect.top + space_height))
                surface.blit(img,img_rect)
            else:
                img_rect = img.get_rect(center=(self.rect.x +20 + space_width + ((i-1) *space_width*2),self.rect.top + space_height))
                surface.blit(img,img_rect)
         

#main loop
while True:
      if somthing:
          object1 = EXAMPLE(10,10,"abc",100,50,10)
          object1.draw_func(screen)
      elif somthing else:
          object3 = EXAMPLE(10,10,"abc",100,50,10)
          object3.draw_func(screen)

    
    pygame.display.update()

    clock.tick(60)
  1. 我不明白哪里出了问题以及为什么我不能在不减少运行时间的情况下将更多图像添加到我的图像列表中。

  2. 另一个与此代码无关但与运行时相关的问题。如果这段没有主循环的代码在文件号 1 中,并且在这个文件中我导入 pygame 并仅初始化字体。

 pygame.font.init()

在主循环为 运行 的文件 num 2 中,我导入 pygame 并初始化 pygame

 pygame.init()

它会减少我的程序运行时间吗?

确保图像 Surface 与显示器 Surface 具有相同的格式。使用 convert() (or convert_alpha()) 创建具有相同像素格式的 Surface。这提高了显示图像 blit 时的性能,因为格式兼容并且 blit 不需要执行隐式转换。

例如:

img1 = pygame.image.load(r'images\game_background1\img1.jpg').convert()