I'm trying to create a timer for my text-based RPG. I would like it set up so that if a user doesn't input something within a given time the program will exit with a message.
I have tried different import to complete this, but every time it's had an issue with implementing an outside timer function in the functions I've already created. The best I could come up with is letting it run, but the user can still input things and continue with the game.
from threading import Timer
def Timed():
timeout = 5
t = Timer(timeout, print, ['The guards catch you. They execute you on the spot.. You die.'])
t.start()
def escape_scene():
Timed()
decisions = ["left", "right", "up"]
print("You walk into an opening filled with guards! Where do you go?")
answer = ""
while answer not in decisions:
print("Options: left/right/up")
answer = input()
if answer == "left":
nothing()
elif answer == "right":
nothing()
elif answer == "up":
example()
else:
print("That is not an option.")
escape_scene()
I know it's not the command-line solution but maybe you can consider using pyxel which gives you more options and flexibility. For example here is the timer implementation:
import time
import pyxel
class App:
def __init__(self):
pyxel.init(250, 150, display_scale=3, title='Viul\'s RPG')
self.timer = True
self.start = time.time()
self.time_left = None
pyxel.run(self.update, self.draw)
def update(self):
self.time_left = 5 - int(time.time()-self.start)
if self.time_left >= 0 and (pyxel.btn(pyxel.KEY_LEFT) or pyxel.btn(pyxel.KEY_RIGHT) or pyxel.btn(pyxel.KEY_UP)):
self.timer = False
def draw(self):
pyxel.cls(pyxel.COLOR_BLACK)
if self.timer and self.time_left >= 0:
pyxel.text(x=1, y=1, s='You walk into an opening filled with guards! Where do you go?', col=pyxel.COLOR_WHITE)
pyxel.text(x=1, y=10, s='Options:', col=pyxel.COLOR_WHITE)
pyxel.text(x=35, y=10, s='Left, Right, Up', col=pyxel.COLOR_GREEN)
pyxel.text(x=1, y=20, s='Time left:', col=pyxel.COLOR_WHITE)
pyxel.text(x=45, y=20, s=str(self.time_left), col=pyxel.COLOR_RED)
elif self.timer and self.time_left < 0:
pyxel.text(x=1, y=1, s='The guards catch you. They execute you on the spot.. You die.', col=pyxel.COLOR_WHITE)
elif not self.timer:
pyxel.text(x=1, y=1, s='You run away from them as fast as you can...', col=pyxel.COLOR_WHITE)
App()
Output: