如何在井字棋游戏中结合input函数实时显示剩余操作时间
井字棋回合剩余时间显示解决方案
问题描述
我制作了一款井字棋(tictactoe)游戏,并在回合操作中添加了时间限制。目前的问题是如何让玩家看到剩余操作时间,我不清楚如何在运行input类函数的同时,执行显示剩余时间的代码。
当前代码(属于类的方法):
from inputimeout import inputimeout, TimeoutOccurred import time # 补充原代码缺失的导入 def play_turn(self): while True: try: choice = int(inputimeout(prompt=f"{self.players[self.current_player].name}, choose a move: ", timeout=5)) if 1 <= int(choice) <= 9 and self.board.update_board(choice, self.players[self.current_player].symbol): break else: print("Invalid move,try again") except TimeoutOccurred: print("Timed out!!") time.sleep(2) return except ValueError: print("Please enter a number between 1 and 9")
解决方案
要实现输入操作与剩余时间显示并行,最直接的方式是使用多线程:一个线程负责等待用户输入,另一个线程实时更新剩余时间的显示。
修改后的代码示例
from inputimeout import inputimeout, TimeoutOccurred import time import threading def play_turn(self): # 用可变列表存储状态,线程间可修改 remaining_time = [5] timeout_flag = [False] def countdown(): while remaining_time[0] > 0 and not timeout_flag[0]: # 用\r实现同一行刷新剩余时间,避免刷屏 print(f"\r剩余操作时间: {remaining_time[0]}秒", end="") time.sleep(1) remaining_time[0] -= 1 if remaining_time[0] == 0 and not timeout_flag[0]: timeout_flag[0] = True # 启动后台倒计时线程 countdown_thread = threading.Thread(target=countdown) countdown_thread.daemon = True # 主线程结束时自动终止子线程 countdown_thread.start() while True: try: choice = int(inputimeout( prompt=f"\n{self.players[self.current_player].name}, choose a move (1-9): ", timeout=remaining_time[0] )) timeout_flag[0] = True # 标记输入完成,停止倒计时 countdown_thread.join(timeout=1) # 等待倒计时线程结束 # 清除倒计时行的显示 print("\r" + " " * 20 + "\r", end="") if 1 <= choice <= 9 and self.board.update_board(choice, self.players[self.current_player].symbol): break else: print("Invalid move, try again") # 重置时间并重启倒计时 remaining_time[0] = 5 timeout_flag[0] = False countdown_thread = threading.Thread(target=countdown) countdown_thread.daemon = True countdown_thread.start() except TimeoutOccurred: print("\r" + " " * 20 + "\r", end="") print("Timed out!!") time.sleep(2) return except ValueError: print("\r" + " " * 20 + "\r", end="") print("Please enter a number between 1 and 9") # 重置时间并重启倒计时 remaining_time[0] = 5 timeout_flag[0] = False countdown_thread = threading.Thread(target=countdown) countdown_thread.daemon = True countdown_thread.start()
关键说明
- 多线程分离:将输入逻辑与倒计时逻辑拆分为两个独立线程,实现并行执行
- 行刷新技巧:使用
\r回车符在同一行更新剩余时间,避免多次打印导致界面混乱 - 状态同步:通过可变列表
remaining_time和timeout_flag在主线程与子线程间传递状态,控制倒计时的启停 - 错误处理:输入无效或超时后,重置剩余时间并重新启动倒计时线程,保证下一次输入的时间显示正常
内容的提问来源于stack exchange,提问作者مالك خالد
相关产品推荐
相关产品推荐

