如何解决我如何在 pygame 中退出窗口?
我想在按下 esc 按钮后关闭游戏。我能怎么做?我应该把它放在哪里? 我也发现了一些我无法解决的问题,所以如果你帮我解决它们我会很高兴
这是代码:
#Import Libraries
import pygame
import random
#PyGame Initialization
pygame.init()
#Images Variables
background = pygame.image.load('images/sfondo.png')
bird = pygame.image.load('images/uccello.png')
base = pygame.image.load('images/base.png')
gameover = pygame.image.load('images/gameover.png')
tube1 = pygame.image.load('images/tubo.png')
tube2 = pygame.transform.flip(tube1,False,True)
#display Create
display = pygame.display.set_mode((288,512))
FPS = 60
#Define Functions
def draw_object():
display.blit(background,(0,0))
display.blit(bird,(birdx,birdy))
def display_update():
pygame.display.update()
pygame.time.Clock().tick(FPS)
def animations():
global birdx,birdy,bird_vely
birdx,birdy = 60,150
bird_vely = 0
#Move Control
animations()
while True:
bird_vely += 1
birdy += bird_vely
for event in pygame.event.get():
if ( event.type == pygame.KEYDOWN
and event.key == pygame.K_UP):
bird_vely = -10
if event.type == pygame.QUIT:
pygame.quit()
draw_object()
display_update()
解决方法
您可以通过在代码中实现以下代码片段来实现:
running = True
while running:
# other code
event = pygame.event.wait ()
if event.type == pygame.QUIT:
running = False # Be interpreter friendly
pygame.quit()
确保在退出主函数之前调用 pygame.quit()
你也可以参考这个线程 Pygame escape key to exit
,您必须在 QUIT
事件发生时终止应用程序循环。您已实现 QUIT
事件,但并未终止循环。添加变量 run = True
并在事件发生时设置 run = False
。
要在按下 ESC 时终止游戏,您必须实现 KEYDOWN
事件。当 run = False
事件发生且 KEDOWN
发生时设置 event.key == pgame.K_ESC
:
run = True
while run:
bird_vely += 1
birdy += bird_vely
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pgame.K_ESC:
run = False
elif event.key == pygame.K_UP:
bird_vely = -10
draw_object()
display_update()
pygame.quit()
exit()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。