【问题标题】:pygame.key.get_pressed() is not workingpygame.key.get_pressed() 不工作
【发布时间】:2013-07-30 04:12:51
【问题描述】:

我在 Stack Overflow 上读过与此类似的问题,但它们没有帮助。这是我的代码:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Hello World')
pygame.mouse.set_visible(1)

done = False
clock = pygame.time.Clock()

while not done:
    clock.tick(60)

    keyState = pygame.key.get_pressed()

    if keyState[pygame.K_ESCAPE]:
        print('\nGame Shuting Down!')
        done = True

escape 不会退出游戏或打印消息。这是一个错误吗?如果我打印 keyState[pygame.K_ESCAPE] 的值,它总是为零。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    问题是你没有处理 pygame 的事件队列。您应该在循环结束时简单地调用pygame.event.pump(),然后您的代码就可以正常工作了:

    ...
    while not done:
        clock.tick(60)
    
        keyState = pygame.key.get_pressed()
    
        if keyState[pygame.K_ESCAPE]:
            print('\nGame Shuting Down!')
            done = True
        pygame.event.pump() # process event queue
    

    来自docs(强调我的):

    pygame.event.pump()

    内部处理 pygame 事件处理程序

    pump() -> None

    对于游戏的每一帧,您都需要对事件队列进行某种调用。这可以确保您的程序可以在内部与操作系统的其余部分进行交互。 如果您没有在游戏中使用其他事件函数,则应调用 pygame.event.pump() 以允许 pygame 处理内部行动。

    如果您的程序通过其他 pygame.event 函数持续处理队列中的事件,则不需要此函数。

    有一些重要的事情必须在事件队列内部处理。主窗口可能需要重新绘制或响应系统。 如果您长时间未能调用事件队列,系统可能会判定您的程序已锁定

    请注意,如果您只是在主循环中的任何位置调用pygame.event.get(),则不必这样做;如果你不这样做,你应该打电话给pygame.event.clear(),这样事件队列就不会填满了。

    【讨论】:

    • 其实你可能只需要调用pygame.event.poll() 可能会稍微快一点。
    【解决方案2】:

    我可以建议改用事件队列吗?这可能是一个更好的主意:

    while True: #game loop
        for event in pygame.event.get(): #loop through all the current events, such as key presses. 
            if event.type == QUIT:
                die()
    
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE: #it's better to have these as multiple statments in case you want to track more than one type of key press in the future. 
                    pauseGame()
    

    【讨论】:

    • 我以前使用过这种方法,但它不能很好地处理同时按键。
    • 您可以将布尔值设置为变量,并在有keydown 时将它们设为真,当有keyup 时将它们再次设为假。然后您只需检查哪些变量是正确的。我会在一秒钟内用一个例子来编辑我的答案
    • @ZeroDivide 你可以混合和匹配,使用事件和 get_state 取决于应该使用哪个键。
    【解决方案3】:

    做这样的事情:

    import pygame
    from pygame.locals import *
    
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption('Hello World')
    pygame.mouse.set_visible(1)
    
    done = False
    clock = pygame.time.Clock()
    
    while not done:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
    
        key = pygame.key.get_pressed()
    
        if key[K_ESCAPE]:
            print('\nGame Shuting Down!')
    
        pygame.display.flip()
    

    你不需要 pygame. 上的 if 语句,你也应该调用 pygame.display.flip() 以便它正确显示窗口然后你需要一个事件循环来退出程序

    【讨论】:

      【解决方案4】:

      您应该提供pygamepython 的版本。

      我在使用pygame 1.9.4devpython 3.6.5 时遇到了类似的问题

      我在降级pygame 并重新安装python 后解决了这个问题。

      注意:如果你使用pyenv,安装python时必须确保设置--enable-framework选项。

      # exit current virtualenv
      $ pyenv deactivate
      # reinstall python
      $ PYTHON_CONFIGURE_OPTS="--enable-framework" pyenv install 3.6.5
      # And reinstall pygame again.
      pip install https://github.com/pygame/pygame/archive/1.9.3.zip
      

      使用下面的代码来检查它是否工作。

      import pygame
      import sys
      
      
      def run():
          """Initialize pygame, settings, and screen object."""
          pygame.init()
          screen = pygame.display.set_mode((300, 200))
          pygame.display.set_caption('Keyboard Test')
      
          # main loop
          while True:
              for event in pygame.event.get():
                  if event.type == pygame.QUIT:
                      sys.exit()
                  elif event.type == pygame.KEYDOWN:
                      print('KEY pressed is ' + str(event.key) + '.')
      
              # Make the most recently drawn screen visible.
              pygame.display.flip()
      
      
      run()
      

      【讨论】:

        猜你喜欢
        • 2013-06-26
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 2021-01-10
        相关资源
        最近更新 更多