• Advertisement
Sign in to follow this  

pygame: breaking while loop

This topic is 2932 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement