Reputation: 55
I am trying to create a function where if a key is pressed, variables are changed. This will be put into a class that moves a sprite on a screen. The while loop is broken when the key is released. However, nothing happens. The while loop is running and I get no error. Does anyone know why this might be happening? I am not sure if I am using the function pygame.key.get_pressed()
correctly.
import pygame
from pygame.locals import *
def move():
for event in pygame.event.get():
if event.type == QUIT:
pygame.QUIT()
sys.exit()
while True:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
print("something happens")
#runs this, but when up arrow key is pressed does nothing
if event.type == KEYUP:
False
screen = pygame.display.set_mode((512,384))
move()
pygame.display.update()
Upvotes: 1
Views: 1624
Reputation: 59
You can do something like this:
def move():
for event in pygame.event.get():
if event.type == QUIT:
pygame.QUIT()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
print("up pressed")
# etc.
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
print("up released")
# etc.
For more key names you can go to the Pygame Key Docs
Upvotes: 2
Reputation: 142641
get_pressed()
returns list with information about pressed keys but this list is updated by pygame.event.get()
and other event functions so you have to execute pygame.event.get()
all the time. And this is why we do it in while-loop
import pygame
pygame.init()
screen = pygame.display.set_mode((512,384))
while True:
# get events and (somewhere in background) update list
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# get current list.
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
print("UP")
Upvotes: 1