文本RPG定时器功能实现求助:超时未输入时程序自动退出
解决文本RPG中定时器超时后阻止用户继续输入的问题
你的核心问题在于:threading.Timer 只是启动了一个独立线程执行打印操作,但主线程仍会一直阻塞在 input() 调用上,导致超时后用户依然能输入内容并继续游戏。要实现超时后强制终止程序、阻止用户继续交互的效果,需要让超时事件能打断主线程的输入等待。
下面是两种可行的实现方案:
方案一:使用 threading.Event 实现跨平台超时输入
通过事件对象标记超时状态,在输入流程中同步检查状态,超时则直接终止程序:
from threading import Timer, Event timeout_event = Event() def timed_exit(): print('\nThe guards catch you. They execute you on the spot. You die.') timeout_event.set() exit() def escape_scene(): timeout = 5 # 启动超时定时器 t = Timer(timeout, timed_exit) t.start() decisions = ["left", "right", "up"] print("You walk into an opening filled with guards! Where do you go?") answer = "" while answer not in decisions: # 检查是否已触发超时 if timeout_event.is_set(): break print("Options: left/right/up") try: answer = input() # 用户成功输入,取消定时器 t.cancel() except: pass if answer == "left": nothing() elif answer == "right": nothing() elif answer == "up": example() else: print("That is not an option.") # 递归重新进入场景前,先取消当前定时器 t.cancel() escape_scene() # 替换为你的实际游戏逻辑函数 def nothing(): print("You chose left/right, nothing happens.") def example(): print("You climbed up and escaped!") escape_scene()
方案二:使用 signal 模块(仅Unix/Linux/macOS)
如果游戏运行在类Unix系统上,可借助信号机制实现更简洁的超时控制:
import signal def timeout_handler(signum, frame): print('\nThe guards catch you. They execute you on the spot. You die.') exit() def escape_scene(): timeout = 5 # 设置信号触发的超时逻辑 signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout) 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") try: answer = input() # 用户输入成功,取消信号定时器 signal.alarm(0) except: pass if answer == "left": nothing() elif answer == "right": nothing() elif answer == "up": example() else: print("That is not an option.") # 递归前取消信号定时器 signal.alarm(0) escape_scene() # 替换为你的实际游戏逻辑函数 def nothing(): print("You chose left/right, nothing happens.") def example(): print("You climbed up and escaped!") escape_scene()
关键注意事项:
- 用户输入成功后必须取消定时器/信号,避免后续误触发超时逻辑。
- 递归调用场景函数时,一定要先取消当前的定时器,否则会出现多个定时器同时运行的问题,导致错误触发超时。
内容的提问来源于stack exchange,提问作者Viul
相关产品推荐
相关产品推荐

