kv manohar kv manohar - 3 months ago 26
Python Question

pygame.event.get() is not returning any event

import pygame
from pygame.locals import *

...
...

while True:
#comment
for event in pygame.event.get():
if event.type == KEYDOWN:
key_pressed = pygame.key.get_pressed()
#do something


I replaced
#comment
with a print statement and found that the
for loop
is not at all executed i.e, print statement is running infinitely.

What I'm expecting is that,
get_pressed()
returns the key pressed as soon as the key is pressed, but it's not happening.

What's wrong in the above code and how do I correct it?

EDIT: Adding link to python script file
python script

Answer

pygame.event.get() grabs all of the events that have registered in the event queue and keeps them in the order they happened. pygame.key.get_pressed() only has the keys that are pressed in that moment. That means that they have to be pressed when your game tries to access them.

You don't need to use both of these methods together. Instead just loop through the events and do something when a key matches one that you want. A common thing is to react to the cursor keys which is shown below:

import pygame
from pygame.locals import *

pygame.init()
...
...

while True:
    #comment
    for event in pygame.event.get():

        if event.type == KEYDOWN:

            if event.key == pygame.K_DOWN:
                print('Down was pressed')

            if event.key == pygame.K_UP:
                print('Up was pressed')

            if event.key == pygame.K_RIGHT:
                print('Right was pressed')

            if event.key == pygame.K_LEFT:
                print('Left was pressed')
Comments