我被编码为一个简单的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()
函数位置的调用片段。
为了提高性能,不要在每个框架中构建研磨。
创建一个窗口大小的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()