Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame: Is there any easy way to find the letter/number of ANY alphanumeric pressed?

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.

like image 236
Jeremy Avatar asked Dec 15 '22 23:12

Jeremy


1 Answers

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.

like image 119
sloth Avatar answered Dec 27 '22 11:12

sloth