如何在Python中实现可被指定事件终止的游戏计时器函数?
实现可终止的同步计时器
可以用后台线程+线程安全的信号量来实现这个需求,避开threading.Timer单次触发的局限。下面是完整的实现代码:
import threading import time class GameTimer: def __init__(self, initial_time): self.time_remaining = initial_time self._stop_event = threading.Event() self._lock = threading.Lock() self._timer_thread = None def _timer_loop(self): while not self._stop_event.is_set(): # 等待1秒,若期间收到停止信号则直接退出 if self._stop_event.wait(1): break with self._lock: if self.time_remaining <= 0: self._stop_event.set() break self.time_remaining -= 1 def start(self): # 避免重复启动多个计时线程 if self._timer_thread is None or not self._timer_thread.is_alive(): self._stop_event.clear() self._timer_thread = threading.Thread(target=self._timer_loop, daemon=True) self._timer_thread.start() def stop(self): self._stop_event.set() if self._timer_thread is not None: self._timer_thread.join() def get_time(self): with self._lock: return self.time_remaining
使用示例
# 初始化10秒计时器 timer = GameTimer(10) timer.start() # 模拟游戏逻辑循环 while True: current_time = timer.get_time() print(f"剩余时间: {current_time}秒") if current_time <= 0: print("时间耗尽!游戏结束") break # 模拟答对题目触发终止 user_input = input("输入'答对'终止计时器: ") if user_input.strip() == "答对": timer.stop() print("答对题目,计时器已终止") break time.sleep(0.5)
关键细节说明
- 线程安全:用
threading.Lock保护time_remaining的读写操作,防止主线程和计时线程同时修改导致数据异常。 - 即时终止:
threading.Event的wait(1)方法让计时线程在等待1秒的过程中,一旦收到停止信号就能立刻退出,无需等待满1秒。 - 守护线程:设置
daemon=True确保程序退出时,计时线程会自动终止,不会阻塞程序关闭。 - 防重复启动:
start方法中加入状态判断,避免多次调用启动多个并行的计时线程。
如果偏好函数式实现,核心逻辑一致,可通过闭包或全局变量维护时间和终止信号。
内容的提问来源于stack exchange,提问作者Terylbalite
相关产品推荐
相关产品推荐

