【问题标题】:Pygame lags after drawing full window gridPygame 在绘制完整的窗口网格后滞后
【发布时间】:2020-08-22 07:24:25
【问题描述】:

我编写了一个简单的 pygame 网格窗口。但 pygame 窗口在那之后开始滞后。

这是简单的代码????

import pygame
import random

pygame.init()
pygame.font.init()

screen_width = 500
screen_height = screen_width

screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")

def drawGrid():
    grid_list = []
    blockSize = 25
    for x in range(screen_width):
        for y in range(screen_height):
            rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
            pygame.draw.rect(screen, (255,255,255), rect, 1)

running = True
while running:
    screen.fill((0,0,0))
    drawGrid()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.display.update()

我尝试改变drawGrid()函数位置的调用sn-p。

【问题讨论】:

    标签: python pygame game-development


    【解决方案1】:

    为了提高性能,不要在每一帧都构建研磨。

    用窗口大小创建一个pygame.Surface,并在这个表面上绘制网格:

    grid_surf = pygame.Surface((screen_width,screen_height))
    drawGrid(grid_surf)
    

    这个表面是场景的背景。 blit 在每一帧的开头:

    screen.blit(grid_surf, (0, 0))
    

    示例代码:

    import pygame
    import random
    
    pygame.init()
    pygame.font.init()
    
    screen_width = 500
    screen_height = screen_width
    
    screen = pygame.display.set_mode((screen_width,screen_height))
    pygame.display.set_caption("Snake GaMe By Akila")
    
    def drawGrid(surf):
        grid_list = []
        blockSize = 25
        for x in range(screen_width):
            for y in range(screen_height):
                rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
                pygame.draw.rect(surf, (255,255,255), rect, 1)
    
    grid_surf = pygame.Surface((screen_width,screen_height))
    drawGrid(grid_surf)
    
    running = True
    while running:
        screen.blit(grid_surf, (0, 0))
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        pygame.display.update()
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2017-04-30
      • 1970-01-01
      相关资源
      最近更新 更多