-1

first time asking a question. I am pretty new to python and I have made this script which is very basic but somehow does not work. the pygame.QUIT() function works but the other ones including K_e, K_9 and K_0 do not produce any result, or at least don't print anythong to the console. Here is the code.

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.K_e:
            if editing_mode:
                editing_mode = False
            else:
                editing_mode = True
            print(editing_mode)
        if event.type == pygame.K_e:
            selected_block -= 1
            print(selected_block)
        if event.type == pygame.K_0:
            selected_block += 1
            print(selected_block)

Another line in my loop a little bit further works perfectly. here it is:

keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        speed_x -= 6
    if keys[pygame.K_d]:
        speed_x += 6

I only want the event to happen once when the keys E, 9 and 0 are pressed and this is why I used different loops. Thank you for your help.

I tried pressing the keys but nothing was printed even if the pygame.quit function works. I tried using the editing mode, after enabling it by pressing e even if nothing was printed and it did not work.

Polloc
  • 1
  • 1

1 Answers1

1

As I understand the documentation, the event is not the key itself but pygame.KEYDOWN. The pressed key is found inside the event.key attribute.

The updated code would look like this:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key = pygame.K_e:
                if editing_mode:
                    editing_mode = False
                else:
                    editing_mode = True
                print(editing_mode)
            elif event.key == pygame.K_e:
                selected_block -= 1
                print(selected_block)
            elif event.key == pygame.K_0:
                selected_block += 1
                print(selected_block)

I'm using elif instead of multiple ifs because the different keys belong to the same chain of logic and it makes a bit more readable.

white
  • 601
  • 3
  • 8