gpt4 book ai didi

python - 运行代码时为 "pygame.error: display Surface quit"

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:23 39 4
gpt4 key购买 nike

我正在尝试使用 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()

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

最佳答案

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

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

# [...]

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

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

请注意,您可能添加了一个 Indentation当您复制代码时。

关于python - 运行代码时为 "pygame.error: display Surface quit",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916052/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com