python - 有没有办法用 MOUSEBUTTONDOWN 事件关闭 pygame 窗口?
问题描述
我正在尝试制作一个退出 pygame 的可点击图像,但我不确定如何关闭它。我曾尝试使用 pygame.quit() 和 sys.exit() 但加载了一秒钟但没有做任何事情。我将在这里展示我的代码(唯一相关的代码是 x 和 y 变量以及底部的退出按钮):
import pygame, sys
clock = pygame.time.Clock()
from pygame.locals import *
pygame.init() # inititates Pygame
pygame.display.set_caption('Lightmind')
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # initiates the window
logo = pygame.image.load("GameLogo.png").convert()
logo = pygame.transform.scale(logo, (256, 256))
start_button = pygame.image.load("StartButton.png").convert()
start_button = pygame.transform.scale(start_button, (256, 256))
exit_button = pygame.image.load("ExitButton.png").convert()
exit_button = pygame.transform.scale(exit_button, (256, 100))
x_2 = 560
y_2 = 400
fade_in = True
fade_out = True
fade_in_ball = True
fade_in_start = True
fade_in_exit = True
running = True
while running: # game loop
for event in pygame.event.get():
if event.type == QUIT:
running = False
pygame.quit()
sys.exit()
# fade in the logo
if fade_in == True:
for i in range(255):
screen.fill((0,0,0))
logo.set_alpha(i)
screen.blit(logo, (560,260))
pygame.display.flip()
clock.tick(60)
fade_in = False
# fade out the logo
if fade_out == True:
for i in range(255):
screen.fill((0,0,0))
logo.set_alpha(255-i)
screen.blit(logo, (560,260))
pygame.display.flip()
clock.tick(60)
fade_out = False
# fade in the start button
if fade_in_start == True:
for i in range(255):
start_button.set_alpha(i)
screen.blit(start_button, (560, 240))
pygame.display.flip()
clock.tick(60)
fade_in_start = False
# fade in the exit button
if fade_in_exit == True:
for i in range(255):
exit_button.set_alpha(i)
screen.blit(exit_button, (x_2, y_2))
pygame.display.flip()
clock.tick(60)
fade_in_exit = False
# make exit button exit game
if event.type == pygame.MOUSEBUTTONDOWN:
x_2, y_2 = event.pos
if exit_button.get_rect().collidepoint(x_2, y_2):
pygame.quit()
sys.exit()
pygame.display.update()
任何帮助表示赞赏!
解决方案
您正在事件循环之外检查事件。将其向上移动:
for event in pygame.event.get():
if event.type == QUIT:
running = False
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
x_2, y_2 = event.pos
if exit_button.get_rect().collidepoint(x_2, y_2):
pygame.quit()
推荐阅读
- angular - 在扩展模式下如何隐藏垫子扩展面板标题
- android - 如何在android studio的项目文件夹中更改.gradle floder目录
- c# - 从 C# 中的 Json 字符串访问字典
- javascript - cordova InAppBrowser 不适用于 _system 参数
- angular - Angular 7 - 整个应用程序的全局 HTTP 拦截器
- php - 在循环中运行多线程的正确方法
- mysql - Postgre 或 mysql id 列自动递增
- java - 为什么这个 Java 代码的行为与这个 C 代码不同?
- ios - 如何避免在 Realm 数据库中以多对多关系添加相同的数据?
- ethereum - 以太坊令牌如何用作电子商务网站上的支付网关