我正在为我的游戏制作开始菜单,但是当我按开始菜单中创建的退出按钮时,它不会退出。我的代码有什么问题吗?
我尝试为退出创建函数,将其放入使用窗口退出按钮退出游戏的代码中,但没有任何效果。
import pygame
import os
pygame.mixer.pre_init()
pygame.mixer.init(44100, 16, 2, 262144)
pygame.init()
from pygame.locals import*
pygame.mixer.music.load(os.path.join(os.getcwd(), 'Sounds',
'intro.ogg'))
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1)
FPS = 60
white = (255,255,255)
grey = (128,128,128)
black = (0,0,0)
red = (255,0,0)
orange = (255,128,0)
yellow = (255,255,0)
green = (0,255,0)
Lgreen = (128,255,0)
blue = (0,0,255)
Lblue = (0,255,255)
purple = (255,0,255)
pink = (255,0,127)
pygame.display.set_caption('Snake Universe')
Title = pygame.image.load('Graphics/Title.png')
Play = pygame.image.load('Graphics/Play.png')
Option = pygame.image.load('Graphics/Option.png')
Exit = pygame.image.load('Graphics/Exit.png')
LinePX = pygame.image.load('Graphics/LinePX.png')
LineO = pygame.image.load('Graphics/LineO.png')
clock = pygame.time.Clock()
movie = pygame.movie.Movie('Video/bg.mpg')
screen = pygame.display.set_mode((1280, 720))
bgE = pygame.image.load('Graphics/transparent.png')
movie_screen = pygame.Surface(movie.get_size()).convert()
movie.set_display(movie_screen)
movie.play()
y = 235
y1 = 3000
cnt = 0
playing = True
while playing:
cnt+=1
if cnt>=1870:
cnt=0
movie.rewind()
movie.play()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_RETURN:
if y == 426:
movie.stop()
playing = False
pygame.quit()
quit()
if event.key == pygame.K_UP:
y += 1
if y == 3236:
y = 235
y1 = 3000
if y == 236:
y = 425
y1 = 3000
if y == 426:
y1 =335
y = 3235
if event.key == pygame.K_DOWN:
y += 1
if y == 236:
y = 3235
y1 = 335
if y == 3236:
y1 = 3000
y = 425
if y == 426:
y1 = 3000
y = 235
if event.type == pygame.QUIT:
movie.stop()
playing = False
pygame.quit()
quit()
screen.blit(movie_screen,(0, 0))
screen.blit(Title, (360, 0))
screen.blit(Play, (460, 250))
screen.blit(Exit, (460, 450))
screen.blit(LinePX, (482.5, y))
screen.blit(LineO, (482.5, y1))
screen.blit(Option, (460, 350))
screen.blit(bgE, (-100, 0))
pygame.display.update()
clock.tick(FPS)
我希望它退出窗口,但是它什么也不做。
答案 0 :(得分:2)
只要playing
为True
,主循环就会运行。
playing = True while playing: # [...]
在处理pygame.QUIT
事件时,playing
被设置了False
,主循环条件失败了:
if event.type == pygame.QUIT: playing = False # [...]
请注意,pygame.quit()
不会终止循环,但是会取消初始化所有pygame模块,如果在应用程序的 middle 中完成,则会导致以下异常
如果要通过键盘输入键pygame.K_KP_ENTER
退出应用程序,则在处理pygame.KEYDOWN
事件时必须执行相同的操作:
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_KP_ENTER:
playing = False
或者您必须在pygame.event.post()
前发送pygame.QUIT
事件:
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_KP_ENTER:
pygame.event.post(pygame.event.Event(pygame.QUIT))