How to create an empty string and update it

bappi :

I am making a game with pygame, and I want the player to enter his name, so then it appears on the screen when playing. I tried with a list :

def input_player_name():
    player_name_screen = True
    name_list = []
    win.blit(player_name_bg, (0, 0))
    while player_name_screen:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    name_list.append("a")
                elif event.key == pygame.K_b:
                    name_list.append("b")
                elif event.key == pygame.K_c:
                    name_list.append("c")
                elif event.key == pygame.K_d:
                    name_list.append("d")
                elif event.key == pygame.K_e:
                    name_list.append("e")
                elif event.key == pygame.K_RETURN:
                    print (name_list)
                    player_name_screen = False

        pygame.display.update()
        clock.tick(fps)

This works. But I want to do it with a string, so it creates an empty string, that the player updates while typing his name on the keyboard. Is there a way to do it ? Or maybe can you redirect me to an already existing page where someone asked this question (I couldn't find it yet) ? Thank you for your answer =D

Rabbid76 :

Use event.unicode:

e.g.:

player_name_screen = True
name = ""

while player_name_screen:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                print (name)
                player_name_screen = False
            else:
                name += event.unicode

If you want to restrict the input to letters, then you can do something like:

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RETURN:
        print (name)
        player_name_screen = False
    elif 'a' <= event.unicode <= 'z' or 'A' <= event.unicode <= 'Z':
        name += event.unicode

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13905&siteId=1