如何使用 pygame 检查同时按下的两个键盘键?

How do I check for two keyboard keys being pressed at the same time with pygame?

我正在尝试将一些功能添加到我的 pygame 游戏中,这些功能在两个键时执行(例如 a + ESC) 同时按下。我尝试使用

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN and event.key == pygame.K_a and event.key == pygame.K_ESCAPE:
    # do something

但是当我同时按下两个键时它不识别

使用pygame.key.get_pressed()获取所有键盘按钮的状态。

keys = pygame.key.get_pressed()
if keys[pygame.K_a] and keys[pygame.K_ESCAPE]:
    # [...]

KEYDOWN 事件发生在其中一个键上时检查键的状态(aESC) :

for event in pygame.event.get():
    # [...]

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_a or event.key == pygame.K_ESCAPE: # <--- or 

            keys = pygame.key.get_pressed()
            if keys[pygame.K_a] and keys[pygame.K_ESCAPE]:
                print("a and ESC")

同一个条件组合:

event_list = pygame.event.get()
keys = pygame.key.get_pressed()
for event in event_list:
    # [...]        

    if event.type == pygame.KEYDOWN and \
        ((event.key == pygame.K_a and keys[pygame.K_ESCAPE]) or \
        (event.key == pygame.K_ESCAPE and keys[pygame.K_a])):
        
        print("a and ESC")

注意:pygame.event.get()必须在pygame.key.get_pressed()之前调用,因为pygame.event.get()返回的按键状态是在事件发生时设置的被评估。