【问题标题】:Pygame not exiting even after receiving keypress [duplicate]Pygame即使在收到按键后也没有退出[重复]
【发布时间】:2021-08-17 19:34:01
【问题描述】:

所以我试图使用一个函数退出 pygame,但它不起作用。它肯定进入了功能块,但由于某种原因在按键后没有退出。请帮忙。

import pygame
from pygame import mixer
from random import *
from math import *

pygame.init()

screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("The Rake Game")
font = pygame.font.Font('freesansbold.ttf',32)

running = True

class Paths:
    def __init__(self):
        self.game_state = 'intro'

    def intro(self):
        screen.fill((120,120,120))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        pygame.display.update()

    def state_manager(self):
        if self.game_state == 'intro':
            self.intro()

a = Paths()

while running:
    a.state_manager()

【问题讨论】:

    标签: python pygame game-loop


    【解决方案1】:

    running 是全局命名空间中的变量。如果要将变量解释为全局变量,则必须使用 global statement

    class Paths:
        # [...]
    
        def intro(self):
            global running  # <--- add global statement
    
            screen.fill((120,120,120))
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
    
            pygame.display.update()
    

    【讨论】:

      【解决方案2】:

      “running”与任何东西都没有关联。您需要一个 while 运行循环。

      running = True
      while running:
      
              for event in pygame.event.get():
                  if event.type == pygame.QUIT:
                      running = False
      
              screen.fill((120,120,120))
              pygame.display.update()
      

      但是这不会像你一样退出:

      while True:
          a.state_manager()
      

      这总是正确的。从它周围删除while true,它应该退出

      【讨论】:

      • 嗨!我试过它仍然无法退出。
      • pygame,QUIT 事件仅在单击关闭窗口的 x 时生成,而不是在按键时生成。
      • @marienbad 你的答案是错误的。在答案中添加代码会创建多个事件循环。见Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
      • 大声笑我应该在 intro() 函数中指定它,但认为这从上下文中是显而易见的。我不应该在睡前这样做,哈哈。
      • @marienbad 知道你的答案是错误的,请考虑更正或删除答案。
      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      相关资源
      最近更新 更多