2

Why does this not work

import pygame

pygame.init()

while True:
    pressed = pygame.key.get_pressed()
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if pressed[pygame.K_w]:
                print("w is pressed")
            elif pressed[pygame.K_s]:
                print("s is pressed")

I installed pygame and python today. It should theoretically be the latest of both pygame and python. this code has gone through many iterations and none of them have worked. I even tried:

print(pygame.key.get_pressed()[pygame.K_w])

and that printed only 0. Even when pressing and holding w. I've tried everything. I tried using:

pygame.event.pump()

but that did nothing.

no errors or anything, just nothing happens. it just prints what I type on the screen.

I've never posted on stackoverflow before, so sorry if I did something wrong.

Edit: I altered the code from somewhere from here

import pygame

pygame.init()

while True:
    for event in pygame.event.get() :
      if event.type == pygame.KEYDOWN :
        if event.key == pygame.K_SPACE :
          print ("Space bar pressed down.") #Here you should put you program in the mode associated with the pressed SPACE key
        elif event.key == pygame.K_ESCAPE :
          print ("Escape key pressed down.")
      elif event.type == pygame.KEYUP :
        if event.key == pygame.K_SPACE :
          print ("Space bar released.")
        elif event.key == pygame.K_ESCAPE :
          print ("Escape key released.") #Time to change the mode again

nothing. absolutely nothing.

  • `python -m trace --trace script.py`, any signs of something weird happening? You could also run a [profile](https://stackoverflow.com/a/3561512/929999) just to check and see if something sticks out. – Torxed Feb 16 '19 at 08:01

2 Answers2

1

The state which is returned by pygame.key.get_pressed() is evaluated by pygame.event.get().

This mans pygame.event.get() has to be done first. Note if you would do it in the reverse order, and a key pressed event happens, the the event loop will run, but pygame.key.get_pressed() has already has returned the deprecated states. So the state pressed[pygame.K_w] and event.type == pygame.KEYDOWN will never be fulfilled in the same run of the loop. The will be fulfilled in 2 consecutive runs loops.

Change your code like this, to solve the issue:

events = pygame.event.get()
pressed = pygame.key.get_pressed()

for event in events:
    if event.type == pygame.KEYDOWN:
        if pressed[pygame.K_w]:
            print("w is pressed")
        elif pressed[pygame.K_s]:
            print("s is pressed")
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

You don't create a screen. I'm uncertain if that matters, but I suspect it does.

Also, you're mixing the "for event in pygame.event.get():" pattern, and the "pygame.key.get_pressed()" pattern.

user3757614
  • 1,776
  • 12
  • 10