[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Inverse function to pygame.key.name?



Ethan Glasser-Camp wrote:
Imagine a game like Simon, where keystrokes are recorded and then
matched against user input. How do we record the keystrokes?

1) Store it as a numeric value, corresponding to a "keyboard button id
constant". So if the user presses 'a', we store 97. I don't like this
because generally I prefer my files to be plain-text as much ass
possible. Besides, what if a different version of pygame, or a version
on a different machine, uses a different number for the letter 'a'? I
would much prefer storee a string like 'a'.

1) Store it as a string. We can get these strings, e.g. by using the
pygame.key.name function. but I don't know how to translate that
string back into a pygame.constant. Many strings can be translated
into a variable prefixed with pygame.constants.K_ -- in this case,
pygame.constants.K_a. But many of the strings returned by
pygame.key.name don't have this property: 'up' corresponds to K_UP
(not K_up); 'delete' to K_DELETE; '/' to K_SLASH; etc.


It wouldn't be hard to build a table from the pygame constants.

KeyIdMap = {}
KeyNameMap = {}
import pygame.constants
for name, value in vars(pygame.constants).iteritems():
    if name.startswith("K_"):
        KeyIdMap[value] = name
        KeyNameMap[name] = value

print KeyIdMap[pygame.K_DELETE]
'K_DELETE'
print KeyNameMap["K_DELETE"]
127
print pygame.K_DELETE
127