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))returns49, which is exactlypygame.K_1ord(str(0))returns48, which matchespygame.K_0
- This dynamic mapping eliminates the need for repetitive
ifstatements 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
相关产品推荐
相关产品推荐

