Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...