2

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

bappi
  • 137
  • 9
  • `name_string += "d"` – Barmar Feb 27 '20 at 18:54
  • If you find yourself creating a huge number of cases you're probably doing something wildly over-complicated. You shouldn't at all need to 1) check if the letter pressed is 'a' and 2) add 'a' to the name and then do that again for any possible key press. Just capture the letter as a variable and add that variable, whatever it happens to be. – Metropolis Feb 27 '20 at 18:56

1 Answers1

2

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
Rabbid76
  • 202,892
  • 27
  • 131
  • 174