0

I'm a bit confused with the method key.get_pressed()

So I have checked the pygame website, and it says that the method will "returns a sequence of boolean values representing the state of every key on the keyboard.....and use the key constant values to index the array".

I saw people writting codes like:

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
       ......

Here is the question: pygame.key.get_pressed() actually returns a tuple, so how can people use a bracket to index the value? I mean it should be like "tuple[sequence]", right?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Tuples are indexed by integers. Is the key constant an integer? – Dan Getz Dec 23 '19 at 15:43
  • 2
    `pygame.K_LEFT` is a constant and represents a well defined number respectively index. In `pygame`, there exists the declaration `K_LEFT = 276`. See [`pygame.key`](https://www.pygame.org/docs/ref/key.html) and [`pygame.locals`](https://www.pygame.org/docs/ref/locals.html#module-pygame.locals). `print(pygame.K_LEFT)` to see what I mean. – Rabbid76 Dec 23 '19 at 15:58

1 Answers1

0

pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button.

In Python the elements of lists and tuples can be accessed by subscription. In the code of your of your question

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
      .....

pygame.K_LEFT is a constant and represents a well defined number respectively index. In pygame, there exists the declaration K_LEFT = 276 (Do print(pygame.K_LEFT) to see what I mean). See also pygame.key and pygame.locals.
Hence the expression keys[pygame.K_LEFT] retrieves the element (value) associated with pygame.K_LEFT.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174