2016-07-22 49 views
1

我想在PyGame(如幾何衝刺)中做背景不斷移動的'Runner'風格的遊戲。到目前爲止,一切正常,但背景圖像的渲染限制了幀速率超過每秒35幀。在添加無限/重複背景元素之前,它可以輕鬆地以60 fps運行。這兩行代碼是負責的(當被移除時,遊戲可以以60 + fps運行):在PyGame中渲染大圖像導致低幀率

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

有什麼我可以做的,使遊戲運行更快?提前致謝!

簡化源代碼:

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() 

這裏的背景圖片:

enter image description here

回答

1

您是否嘗試過使用convert()

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

documentation

你會經常要調用Surface.convert()不帶參數,創建一個副本,這將吸引更多很快在屏幕上。

對於alpha透明度,如在.png圖像中,加載後使用convert_alpha()方法,以便圖像具有每像素透明度。

+0

非常感謝!它現在就像微風一樣奔跑! –