1

This is a part of my alphabet in my pygame code. It works perfectly fine, but takes up alot of lines and looks ugly. its also not portable. Ive tried to create a function for it that can add the letter to any variable, not just "username" in my case but haven't succeeded.

event_list = pygame.event.get()

for event in event_list:

    pressed = pygame.key.get_pressed()

    if pressed[pygame.K_a]:
        username += "a"
    if pressed[pygame.K_b]:
        username += "b"
    if pressed[pygame.K_c]:
        username += "c"
    # ....... etc etc

Does anyone have any suggestions on how i can turn this into a function?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

2 Answers2

2

The keyboard events KEYDOWN and KEYUP (see pygame.event module) create a pygame.event.Event object with additional attributes. The key that was pressed can be obtained from the key attribute (e.g. K_RETURN , K_a) and the mod attribute contains a bitset with additional modifiers (e.g. KMOD_LSHIFT). The unicode attribute provides the Unicode representation of the keyboard input.

e.g.:

def input_text(event_list, name):
    
    finished = False
    for event in event_list:
        if event.type == pygame.KEYDOWN:
       
            if event.key == pygame.K_RETURN:
                finished = True
            else:
                name += event.unicode

    return (finished, name)

Call the input_text function in the application loop:

username = ""
password = ""
current_input = "username"

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False

    if current_input == "username":
        finished, username = input_text(event_list, username)
        if finished:
            current_input = "password"

    elif current_input == "password":
        finished, password = input_text(event_list, password)
        if finished:
            current_input = ""
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
1

You can easily get the name of the pressed key:

for event in event_list:
    if event.type == pygame.KEYDOWN:
        name = pygame.key.name(event.key)
        if len(name) == 1:  #  Check if it is a character
            username += pygame.key.name(event.key)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
thshea
  • 1,048
  • 6
  • 18