1

My goal is a 2 player pygame played on one keyboard where each player can move up, down, left and right.

I wonder if it is preferable to use only the event module or also the key module for this. Most examples I've seen only use the key module, like so:

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            x_change = -5
        elif event.key == pygame.K_RIGHT:
            x_change = 5
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            x_change = 0
x += x_change

The problem with this: When left and right are pressed at the same time and then one key is lifted, x_change is set to zero.

I tried fixing this with a variable that tracks how many keys are pressed, but no success. So I am wondering if the above method is just not the proper way to do it. I have hope that the pygame.key module solves my problem but have problems understanding the documentation.

Anyone with pygame experience here who can recommend when to use which module?

Felix Lipo
  • 31
  • 6

1 Answers1

1

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.

pygame.key.get_pressed() returns a list 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 and get continuous movement:

speed = 5
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
    y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174