Reputation: 21
I am trying to create an infinite loop of a circle moving across the screen using a while statement, and I would like to know how to use a key stroke to activate a break command to stop the loop?
while run_me:
clock.tick(fps_limit)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run_me = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
T = 1
while T == 1:
posx = posx - 1
screen.fill(black)
pygame.draw.circle(screen, colorcircle, (posx, posy), 50)
pygame.display.flip()
if posx == 0:
posx = posx + 600
Upvotes: 2
Views: 58
Reputation: 104702
You probably don't want to have two loops. Currently you don't do any event handling inside your inner loop, which means there's no good way to stop it. But rather than adding additional pygame.event
stuff in there, why not just reuse the code from the main loop?
Here's code that is probably pretty close to working (it's incomplete, so I've not tested it). Most of the changes are just unindenting the stuff you already had.
while run_me:
clock.tick(fps_limit)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run_me = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
T = 1
elif event.key == pygame.K_RIGHT: # add some code to stop drawing
T = 0
if T == 1: # change this to an `if` rather than a `while`, and unindent
posx = posx - 1
screen.fill(black)
pygame.draw.circle(screen, colorcircle, (posx, posy), 50)
pygame.display.flip()
if posx == 0:
posx = posx + 600
You should probably use a better variable name than T
.
Upvotes: 0
Reputation: 210878
The issue is the endless inner loop. Once this loop is entered, it is never terminated. Never implement a game loop in the main application loop. Use the main application loop and use pygame.key.get_pressed()
to implement a continuous movement.
while run_me:
clock.tick(fps_limit)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run_me = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
posx = posx - 1
if posx == 0:
posx = posx + 600
screen.fill(black)
pygame.draw.circle(screen, colorcircle, (posx, posy), 50)
pygame.display.flip()
Upvotes: 1