You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame:如何用pygame.key.get_pressed()遍历数字并检测按键?

Simplify Number Key Press Detection with pygame.key.get_pressed()

You can achieve the concise syntax you want by leveraging the fact that Pygame's number key constants (pygame.K_1, pygame.K_2, ..., pygame.K_0) match the ASCII values of their corresponding character representations. Here's how to implement it:

Solution Code

import pygame
pygame.init()

# Your Pygame window setup goes here

while True:
    keys = pygame.key.get_pressed()
    
    # Check all digit keys (1-9, 0)
    for num in [1,2,3,4,5,6,7,8,9,0]:
        # Map number to corresponding Pygame key code
        key_code = ord(str(num))
        if keys[key_code]:
            print(str(num))
    
    # Handle quit event to avoid infinite loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

How It Works

  • ord(str(num)) converts the number to its string character, then retrieves its ASCII value. For example:
    • ord(str(1)) returns 49, which is exactly pygame.K_1
    • ord(str(0)) returns 48, which matches pygame.K_0
  • This dynamic mapping eliminates the need for repetitive if statements for each digit key.
  • The loop iterates over your target numbers, checking each corresponding key press in one go.

Alternative: Explicit Dictionary Mapping

If you prefer avoiding string conversion, use a dictionary to explicitly map numbers to their Pygame key constants:

num_key_map = {
    1: pygame.K_1,
    2: pygame.K_2,
    3: pygame.K_3,
    4: pygame.K_4,
    5: pygame.K_5,
    6: pygame.K_6,
    7: pygame.K_7,
    8: pygame.K_8,
    9: pygame.K_9,
    0: pygame.K_0
}

while True:
    keys = pygame.key.get_pressed()
    
    for num, key in num_key_map.items():
        if keys[key]:
            print(str(num))
    
    # Quit event handling as before
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

Both approaches work with pygame.key.get_pressed() as requested, keeping your code clean even when expanding to more digit keys.

内容的提问来源于stack exchange,提问作者Jobo Fernandez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:33:08