I am making a program that makes a random Brainf*ck program in python and runs it. I have an interpreter and I need it to check for long loops (more than 5 seconds).
The interpreter is:
while i < len(code):
if code[i] == '<':
if pointerLocation > 0:
pointerLocation -= 1
elif code[i] == '>':
pointerLocation += 1
if len(array) <= pointerLocation:
array.append(0)
elif code[i] == '+':
array[pointerLocation] += 1
elif code[i] == '-':
if array[pointerLocation] > 0:
array[pointerLocation] -= 1
elif code[i] == '.':
print(array[pointerLocation], chr(array[pointerLocation]))
result += chr(array[pointerLocation])
elif code[i] == ',':
#x = input("Input (1 CHARACTER!):")
x = 'h'
#increase time if user inputs
t1 += 5
try:
y = int(x)
except ValueError:
y = ord(x)
array[pointerLocation] = y
elif code[i] == '[':
if array[pointerLocation] == 0:
open_braces = 1
while open_braces > 0 and i+1 < len(code):
i += 1
if code[i] == '[':
open_braces += 1
elif code[i] == ']':
open_braces -= 1
elif code[i] == ']':
# you don't need to check array[pointerLocation] because the matching '[' will skip behind this instruction if array[pointerLocation] is zero
open_braces = 1
while open_braces > 0:
if t > 5:
return [result,code,t]
print(123)
i -= 1
if code[i] == '[':
open_braces -= 1
elif code[i] == ']':
open_braces += 1
# i still gets incremented in your main while loop
i -= 1
i += 1
Sorry for the long snippet, but I do believe it is all neccessary.
Set up an alarm when you enter the loop for 5 seconds. Cancel it when you exit. If the signal triggers then you handle it.
A weaker version of this is to obtain the time when you enter the loop, then check on each iteration to see if it's more than 5 seconds on each iteration.