"pygame.error: display Surface quit" when running the code

"pygame.error: display Surface quit" when running the code

我正在尝试用 Pygame 制作一个简单的移动游戏,因为我目前正在学习它。每当我尝试 运行 代码时,我总是遇到一个问题:"pygame.error: display Surface quit"

我尝试在末尾添加 "break",但 window 立即关闭!我已尝试搜索解决方案,但找不到对我的代码有帮助的解决方案。

import pygame
import random
pygame.init()
# Window setup
size = [400, 400]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

# player position
x = size[0] // 2
y = size[1] // 2

# ball position
ballX = random.randrange(0, size[0])
ballY = random.randrange(0, size[1])

# colours
red = pygame.color.Color('#FF8080')
blue = pygame.color.Color('#8080FF')
white = pygame.color.Color('#FFFFFF')
black = pygame.color.Color('#000000')


def CheckOffScreenX(x):
    if x > size[0]:
        x = 0
    elif x < 0:
        x = size[0]
    return x
def CheckOffScreenY(y):
    if y > size[1]:
        y = 0
    elif y < 0:
        y = size[1]
    return y

# Game loop
done = False
while not done:
    screen.fill(black)


    keys = pygame.key.get_pressed()

    #player movement
    if keys[pygame.K_w]:
        y -=1
    if keys[pygame.K_s]:
        y +=1
    if keys[pygame.K_a]:
        x -=1
    if keys[pygame.K_d]:
        x +=1

    # Check offscreen
    x = CheckOffScreenX(x)
    y = CheckOffScreenY(y)

    # draw player
    pygame.draw.circle(screen, red, [x, y], 6)
    pygame.display.flip()

    # draw ball
    pygame.draw.circle(screen, blue, [ballX, ballY], 6)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    clock.tick(32)
    pygame.quit()

如有任何帮助,我们将不胜感激!

问题出在 pygame.quit() 主循环内部。 pygame.quit() 取消初始化所有 pygame 模块。模块未初始化后,所有对 pygyme 指令的进一步调用(在下一帧中)将导致崩溃。
当应用程序结束时,在主循环之后执行 pygame.quit()

done = False
while not done:
    screen.fill(black)

    # [...]

    # pygame.quit() <----- delete

pygame.quit() # <---- add

请注意,您可能在复制代码时添加了 Indentation