gpt4 book ai didi

python pygame暂停函数

转载 作者:行者123 更新时间:2023-12-01 00:18:34 27 4
gpt4 key购买 nike

我是初学者,我的代码有问题。在这里您可以看到我的代码的简短摘录。

这是我创建的一个简单的蛇游戏,但我试图添加一个暂停。我明白了,但是当我开始暂停时,我无法关闭它。

我的代码中可能存在一个基本错误,所以我无法前进。我希望你能帮助我。

提前谢谢您!

def checkquit(e):
running = True
pause = False
for ev in e:
if ev.type == pygame.QUIT:
exit(0)
running = True

if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
quit(0)
running = True

if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
pause = False

while pause:
#running = False
pause = True
red = (255,0,0)

screen = pygame.display.set_mode((800,500))
screen.fill((0,0,0))

my_font = pygame.font.SysFont("monospace", 50)
my_font_two = pygame.font.SysFont("monospace", 10)

text1 = myfont.render("Pause!", 100, red)
text2 = myfont.render("Please restart the game", 100, red)

screen.blit(text2, (10, 200))
screen.blit(text1, (230, 100))

pygame.display.update()

for ev in e:
if ev.type == pygame.QUIT:
pause = False
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
pause = False
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
pause = True

最佳答案

暂停屏幕显示在单独的应用程序循环中。您还必须获取该循环中的事件。请注意,在您的代码中,e 的内容在“暂停”循环中永远不会改变:

def checkquit(e):
global running
running = True
pause = False
for ev in e:
if ev.type == pygame.QUIT:
exit(0)
running = True
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
quit(0)
running = True
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
pause = True

while pause:

# [...]


# get the new events
e = pygame.event.get()

# handle the events in the loop
for ev in e:
if ev.type == pygame.QUIT:
pause = False
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
pause = False
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
pause = True

runnung 似乎是全局命名空间中的变量。您必须使用 global statement改变它的状态。此外,在“暂停”循环中重新创建窗口表面是多余的。

屏幕 = pygame.display.set_mode((800,500))

<小时/>

我建议更改游戏流程。使用 1 个应用程序循环。例如:

myfont=pygame.font.SysFont("monospace",50)
myfonttwo=pygame.font.SysFont("monospace",10)
text1=myfont.render("Pause!",100,red)
text2=myfont.render("Please restart the game",100,red)

def checkquit(e):
global running, pause
for ev in e:
if ev.type == pygame.QUIT:
exit(0)
running = True
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
if pause:
pause = False
else:
quit(0)
running = True
if ev.type == pygame.KEYDOWN and ev.key == pygame.K_p:
pause = not pause

running, pause = True, False
while running:
events = pygame.event.get()
checkquit(events)

screen.fill((0,0,0))
if pause:
# draw pause screen
screen.blit(text2,(10,200))
screen.blit(text1,(230,100))

else:
# draw game
# [...]

pygame.display.update()

关于python pygame暂停函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121322/

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