I'm making a python console game, and one of the commands has a loop that keeps going for about 30 seconds. This can take longer depending on your level. When you're a higher level, the loop runs for many minutes. I've gotten many complaints and people asking me to add a cancel feature. I can't figure out how to cancel a loop early. How can I make the loop cancel early using an Input or something else?
CodePudding user response:
- Accept a character.
- If the character is Q (for quit), then write break.
Syntax:
loop()
{
char c
input(c)
if(c=='Q' or c=='q')
{
break
}
//other things in loop goes here.
}
CodePudding user response:
If you want your loop to run in the background, maybe you need asyncio or threading.
Or you just want to cancel the loop, maybe you need signal to handle Ctrl-C
or something else.
import signal
cancel_loop = False
def handler(signum, frame):
print('sigint received')
cancel_loop = True
signal.signal(signal.SIGINT, handler)
while not cancel_loop:
# your code ...