Sign in to follow this  
djtschke

pygame: breaking while loop

Recommended Posts

Hello everybody ! Here another newbie question: I coded a while loop to scroll the background of my windows to the left when I press the right arrow key. What I actually want to achieve is that the background scrolls while I am pressing the right arrow key and stops when I release the key. I experimented with if event.type == pygame.KEYUP but I won't get it work. Here is the code for the left scrolling: elif event.type == pygame.KEYDOWN: while event.key == pygame.K_RIGHT: x -= 0.2 y = 0 screen.blit(bg, (x, y)) pygame.display.flip() I hope somebody can help me (to be honest I am sure :) ). best regards, djtschke

Share this post


Link to post
Share on other sites
It's best to avoid doing a loop of that nature inside your main game loop. Try something of this nature:

rightDown = False

while True: # main game loop
if rightDown:
x -= 0.2
screen.blit(bg, (x, 0))
pygame.display.flip()

# perform other updates here

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
rightDown = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
rightDown = False

# handle other events here



This allows you to press other keys as well as move to the right.

Another option is to enable key repeats. With key repeats enabled you'll receive multiple KEYDOWN events while the key is held down. That way you could do something like this:

while True: # main game loop
# perform other updates here

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x -= 0.2
screen.blit(bg, (x, 0))
pygame.display.flip()

# handle other events here

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this