Pygame: Is there any easy way to find the letter/n

2020-01-29 03:11发布

问题:

Game I'm working on currently needs to let people time in their name for highscore board. I'm slightly familiar with how to deal with key presses, but I've only dealt with looking for specific ones. Is there an easy way to get the letter of any key pressed without having to do something like this:

for event in pygame.event.get(): 
    if event.type == KEYUP: 
        if event.key == K_a:
           newLetter = 'a'
        elif event.key == K_b:
           newLetter = 'b'

           ...
       elif event.key == K_z:
           newLetter = 'z'

While that would work, I have a feeling there is a more efficient way to go about it. I just can't figure it out or find any guides on it.

回答1:

There a basically two ways:

Option 1: use pygame.key.name().

It's as simple as

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
    print(pygame.key.name(event.key))

The advantage over using chr is that chr works only if the value of event.key is between 0 and 255 (inclusive).

If you press menu, Alt Gr, Tab or LShift, pygame.key.name will happily return menu, alt gr, tab and left shift, while chr will crash, crash, return whitespace, and crash.


Option 2: use the unicode attribute of the pygame.KEYDOWN event

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
    print(event.unicode)

It will get you the letter/number or an empty string when using a function key, and it will also take modifiers into account, e.g. if you hold Shift while pressing a it will return A instead of just a.

The pygame.KEYDOWN event has additional attributes unicode and scancode. unicode represents a single character string that is the fully translated character entered. This takes into account the shift and composition keys. scancode represents the platform-specific key code.



回答2:

if you look K_a is just 97 thats the ascii code for 'a' , I will extrapolate to K_? is the ascii code for whatever the question mark represents

if event.type == KEYUP: 
    print chr(event.key) #convert ascii code to a character

maybe?

as pointed out this will not work with ascii over 255 (no longer ascii really)

you can use the method outlined below or just use unichr(event.key) instead of chr