2

I am making a game that involves inputs from the user in a pygame window. The input is needed for the user to enter a username or nickname. I noticed that some games on the web allow for numerical inputs so I used...

event.unicode.isnumeric():
    name += event.unicode

to handle them. In the case of alphabetical letters, there is...

event.unicode.isalpha():
    name += event.unicode

In both of these examples, I understand that they can be represented at K_1, K_a, for example, but I believe the if statement would be too long.

The question is, is there a way to have a function that makes use of all the symbols, /?._, without making the if statement too long?

I have tried guessing event.unicode.issymbol(), event.unicode.issymbolic() and event.unicode.symbol() but they do not work.

I have also tried looking at the pygame documentation at pygame.key but this too is not helpful.

name = "" ## stating a variable and assigning to ""
while True:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.unicode.isalpha(): ## if alphabetical letter, a-z
                name += event.unicode ## add letter to name
            elif event.key == K_BACKSPACE: ## if backspace
                name = name[:-1] ## remove last value in name
            elif event.key == K_SPACE: ## if space
                name += event.unicode ## add space
            elif event.unicode.isnumeric(): ## if numerical value, 0-9
                name += event.unicode ## add number to name

elif event.unicode.symbol(): ## if adding
    name += event.unicode

Displays this:

elif event.unicode.symbol():
AttributeError: 'str' object has no attribute 'symbol'

same would happen for issymbolic and issymbol

I expect is to work for all symbolic values such as ".", "/", "_", "-", "(", ")", "+" and so on.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • `event.unicode` is of type `str`, and Python strings do not have a `symbol()` method. However you can make your own `symbols` set with `symbols = {".", "/", "_", "-", "(", ")", "+"}` and test for membership in it with `if event.unicode in symbols: ...`. – martineau Jun 09 '19 at 21:19
  • 1
    I have tried this. And my code works thanks and well explained. – Arif Othman Jun 09 '19 at 21:56
  • Arif: That's good to hear. Note that this technique is only going to detect the values you put into the set, when in fact that are many other [Unicode symbols](https://en.wikipedia.org/wiki/List_of_Unicode_characters#Unicode_symbols) — so technically it's not really a generic Unicode symbol detector. For that you would probably need to use `unicodedata.category()` — which I _think_ returns information like [this](http://www.unicode.org/reports/tr44/tr44-6.html#General_Category_Values). – martineau Jun 09 '19 at 22:14
  • For what characters (other than `\b`) do you **not** want to execute `name+=event.unicode`? – Davis Herring Jun 10 '19 at 00:04

0 Answers0