【发布时间】:2021-06-25 13:51:07
【问题描述】:
我目前使用的 IDE 是 jupyter notebook,但每当我单击图形窗口顶部的十字按钮时,它就会停止响应。这很令人困惑,特别是因为我在我的班级的 check_events 方法中使用 event.type == pygame.QUIT 打破了循环。我究竟做错了什么?以下是我的代码:
class Game():
def __init__(self):
pygame.init() #Provides access to all the features of pygame
self.running, self.playing = True, False
self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False
self.DISPLAY_W, self.DISPLAY_H = 480, 270 #Display width and display height variables to determine canvas size
#In other words, these are canvas dimensions
self.display = pygame.Surface((self.DISPLAY_W, self.DISPLAY_H)) #Creating our canvas
self.window = pygame.display.set_mode((self.DISPLAY_W, self.DISPLAY_H)) #Creating our window
self.font_name = pygame.font.get_default_font()
self.BLACK, self.WHITE = (0,0,0), (255,255,255) #RGB values for these colors
def game_loop(self):
while self.playing:
self.check_events() #To see what the player is doing while playing the game
if self.START_KEY:
self.playing = False
self.display.fill(self.BLACK) #Resetting our frame
self.draw_text("Welcome to Ants vs Bees", 20, self.DISPLAY_W/2, self.DISPLAY_H/2)
self.window.blit(self.display, (0,0)) #Aligning our display with our window
pygame.display.update() #Moves the image onto our screen
self.reset_keys()
def check_events(self):
for event in pygame.event.get():
#Goes through a list of everything a player can do on the computer
if event.type == pygame.QUIT: #To check if players hits the cross button at top of window
self.running, self.playing = False, False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN: #To check if enter key was pressed
self.START_KEY = True
if event.key == pygame.K_BACKSPACE: #To check if backspace key was pressed
self.BACK_KEY = True
if event.key == pygame.K_DOWN: #To check if down key was pressed
self.DOWN_KEY = True
if event.key == pygame.K_UP: #To check if up key was pressed
self.UP_KEY = True
def reset_keys(self):
self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False
def draw_text(self, text, size, x, y):
font = pygame.font.Font(self.font_name, size) #Loading up our font
text_surface = font.render(text, True, self.WHITE) #Creates a rectangular image of our text
text_rect = text_surface.get_rect()
text_rect.center = (x,y)
self.display.blit(text_surface, text_rect)
#Driver code
firstrun = Game()
while firstrun.running:
firstrun.playing = True
firstrun.game_loop()
【问题讨论】:
-
您需要致电
pygame.quit()和sys.exit() -
为什么你有两个退出条件相同的主循环?任何一个都没有效果
-
@mousetail 因为这两个循环将允许我在菜单之间切换,我目前正在实施中
标签: python python-3.x jupyter-notebook pygame