I am having an issue breaking out of a for loop in python, using pygame. Specifically, I'm trying to break out of the loop on release of a key. For example when key "W" is held down, the code should execute, but then immediately break out of loop when the "W" is released.
I have tried to use pygame.key.get_pressed()
and if event.type == KEYUP:
but I cannot seem to get it right. Can anyone help?
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
doQuitStuff()
elif event.type == pygame.MOUSEBUTTONDOWN:
doMouseButtonStuff()
elif event.type == KEYDOWN:
if event.key == pygame.K_p:
doPStuff()
elif event.key == pygame.K_e:
doEStuff()
elif event.key in foo:
doFooStuff()
for i in xrange(100):
doThisStuffOnlyIfKeyInFooIsHeldDown() #This for loop finishes
#execution even if I release the
#key in "foo"
You have to do without for
loop - and while True
will do as loop.
run_loop = False
i = 0
while True:
# - events -
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_w:
# start loop
run_loop = True
i = 0
elif event.type == KEYUP:
if event.key == pygame.K_w:
# stop loop
run_loop = False
# - updates -
if run_loop and i < 100:
i += 1
doThisStuffOnlyIfKeyInFooIsHeldDown()
# - draws -
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.