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

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



Hi,

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.

I've attached a script that computes the name for a given constant, as
well as the K_ name, and prints both if they're different.

In other words, is there a way to take the name given by
pygame.key.name and return a numeric value for it, so that we can
match it against user input? If not, is there a better string to keep
track of?

Ethan
#! /usr/bin/python

import pygame
pygame.init()

for c in dir(pygame.constants):
    if not c.startswith("K_"): continue
    name = pygame.key.name(getattr(pygame.constants, c))
    name2 = c[2:].lower()
    if name != name2: print name, name2

Attachment: signature.asc
Description: OpenPGP digital signature