-1

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?

rezarg
  • 13
  • 8
  • Could you give a sample code? I don't understand about `keeps going for about 30 seconds.` and `When you're a higher level, the loop runs for many minutes.` – ferdy Nov 08 '21 at 04:05
  • You need to explain a lot more, and it would be best if you could show the code for the relevant loop. Is the code taking that long deliberately? Or are you running some kind of inefficient algorithm that takes so long when the dataset (e.g. something in your character's details) gets too large? – Blckknght Nov 08 '21 at 04:05
  • Please add some code that we could refer to help you with your problem –  Nov 08 '21 at 04:07
  • There are a lot of ways this could be done, and the best one would really depend on your exact use case. Refer to this answer - https://stackoverflow.com/questions/2408560/non-blocking-console-input. Another very simple approach is simply to ask users to press the sigint key combination depending on the OS (Ctrl+C on windows) and handle that in your program. – Wiggy A. Nov 08 '21 at 04:24
  • I have a command that loops, and each loop lowers a "Fuel" variable by a random amount. If fuel is 0, the loop stops. The higher your level, the slower your fuel depletes. I'm trying to make it stop the loop even if the fuel is above 0 – rezarg Nov 08 '21 at 04:25

2 Answers2

0
  1. Accept a character.
  2. 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.
}
0

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 ...