【问题标题】:"pygame.error: display Surface quit" when running the code运行代码时出现“pygame.error: display Surface quit”
【发布时间】:2019-07-07 02:02:21
【问题描述】:

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

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

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

任何帮助将不胜感激!

【问题讨论】:

    标签: python python-3.x pygame pygame-surface


    【解决方案1】:

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

    done = False
    while not done:
        screen.fill(black)
    
        # [...]
    
        # pygame.quit() <----- delete
    
    pygame.quit() # <---- add
    

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

    【讨论】:

    • 啊,非常感谢!!我正在从一本书中学习 Python,我开始认为这本书主要是针对 Python 2 的!
    • @AzaamHoldman 谢谢。别客气。请注意,这在 Python 2 中没有什么不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多