Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

My main question is that I have produced two functions, that will check for an event:

def get_pygame_events():

  pygame_events = pygame.event.get()

  return pygame_events

and

def get_keys_pressed(self):

  keys_pressed = get_pygame_events()  #pygame.event.get(pygame.KEYDOWN)

  # print(keys_pressed)

  keys_pressed_list = []

  for event in keys_pressed:

    if event.type == pygame.KEYDOWN:

      if event.key == K_LEFT:

        keys_pressed_list.append("left")

      if event.key == K_RIGHT:

        keys_pressed_list.append("right")

      if event.key == K_UP:

        keys_pressed_list.append("up")

      if event.key == K_DOWN:

        keys_pressed_list.append("down")

      if event.key == K_a:

        keys_pressed_list.append("a")

      if  event.key == K_d:

        keys_pressed_list.append("b")

      if event.key == K_w:

        keys_pressed_list.append("w")

      if event.key == K_s:

        keys_pressed_list.append("s")

      if event.key == K_SPACE:

        keys_pressed_list.append("space")

      if event.key == K_q:

        keys_pressed_list.append("q")

      if event.key == K_e:

        keys_pressed_list.append("e")

    if event.type == pygame.MOUSEBUTTONDOWN:

      keys_pressed_list.append("click")

      return (keys_pressed_list, event.pos)

  return keys_pressed_list

I expected that if I could do something similar to:

while True:

  Variable1 = get_pygame_events()

  Variable2 = get_keys_pressed()

  if Variable2 == ["w"]:

    print("w")

How can I update my code so that by holding down the W (or any) key, it should identify the event happening, and in my case, it should print the w every time it passes through the while loop?

1 Answer

0 votes
by (108k points)

In that case, you have to use pygame.KEYDOWN and pygame.KEYUP so that you can identify if a key is really pressed down or released. You can initiate keyboard repeat by using pygame.key.set_repeat so that it can generate many pygame.KEYDOWN events when a key is held down.

Alternatively, you can use pygame.key.get_pressed() in Python to check if a key is currently held down:

while True:

    ...

    pressed = pygame.key.get_pressed()

    if pressed[pygame.K_w]:

       print("w is pressed")

    if pressed[pygame.K_s]:

       print("s is pressed")

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Nov 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...