我如何优化这个简单的 python pygame 代码

How could I optimise this simple python pygame code

我被设置了一个使用 pygame 制作游戏的挑战(我正在制作蛇所以应该很容易......但我从未使用过 pygame)所以使用更高效的语言不是 option.So 我的问题是我更新蛇形网格太慢而且我在 pygame 方面没有足够的经验来解决这个问题,help.Also 的任何人都可以请注意,如果我只填充网格,它不会在蛇身后清除。 使用 python 3.8

import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Snake")

pureblue = (0,0,255)
purered = (255,0,0)
puregreen = (0,255,0)
white = (255,255,255)
black = (1,1,1)
grey = (50,50,50)
darkgrey = (25,25,25)


clock = pygame.time.Clock()

snake_block = 10
snake_speed = 30

font_style = pygame.font.SysFont(None, 50)

def drawGrid():
    blockSize = 10 
    for x in range(display_width):
        for y in range(display_height):
            rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
            pygame.draw.rect(display, darkgrey, rect, 1)

def message(msg, colour):
    text = font_style.render(msg, True, colour)
    display.blit(text, [display_width/2, display_height/2])

def SnakeGameLoop():
    game_over = False

    X = display_width/2
    Y = display_height/2

    X_change = 0
    Y_change = 0

    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    X_change = -10
                    Y_change = 0
                elif event.key == pygame.K_RIGHT:
                    X_change = 10
                    Y_change = 0
                elif event.key == pygame.K_UP:
                    X_change = 0
                    Y_change = -10
                elif event.key == pygame.K_DOWN:
                    X_change = 0
                    Y_change = 10

        if X >= display_width or X < 0 or Y >= display_height or Y < 0:
            game_over = True

        X += X_change
        Y += Y_change
        display.fill(grey)
        drawGrid()
        pygame.draw.rect(display,puregreen,[X,Y,10,10])

        pygame.display.update()
        clock.tick(15)

    message("You lost", purered)
    pygame.display.update()
    time.sleep(2)

    pygame.quit()
    quit()

SnakeGameLoop()

为了提高游戏性能,在 pygame.Surface 具有屏幕大小的对象上绘制网格, 应用程序循环之前:

def drawGrid(surf):
    surf.fill(grey)
    blockSize = 10 
    for x in range(display_width):
        for y in range(display_height):
            rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
            pygame.draw.rect(surf, darkgrey, rect, 1)

grid_surf = pygame.Surface(display.get_size())
drawGrid(grid_surf)

blit 在显示器上每帧绘制一次表面而不是每帧绘制一次网格, 应用程序循环中:

def SnakeGameLoop():
    # [...]

    while not game_over:
        # [...]

        display.blit(grid_surf, (0, 0))
        
        pygame.draw.rect(display,puregreen,[X,Y,10,10])

        pygame.display.update()