如何在倒计时结束时终止Hangman游戏的while循环并重启游戏?
Hangman 计时器终止循环问题解决
你的原始代码
def timer(): for t in reversed(range(1, 11)): sleep(1) print(t) if foundAllLetters == True: break if remaining_attempts == 0: break if t == 1: sleep(1) print('TIMES UP!') t1 = Thread(target=timer) t1.start() while True: displayBoard(hang, missedLetters, correctLetters, secretWord) guess = getGuess(missedLetters + correctLetters)
问题分析
你尝试在计时器结束时设置gameIsDone = True但没效果,核心原因是:线程内部直接赋值的变量是局部变量,不会影响主线程的同名变量。也就是说,你在timer函数里设置的gameIsDone和主线程里的gameIsDone是两个完全不同的变量,主线程根本感知不到变化。
解决方法
1. 使用全局变量共享状态
把gameIsDone声明为全局变量,这样timer线程和主线程操作的是同一个变量:
import threading from time import sleep # 全局变量控制游戏结束状态 gameIsDone = False foundAllLetters = False remaining_attempts = 3 # 根据你的实际游戏逻辑调整初始值 def timer(): global gameIsDone # 声明使用全局变量 for t in reversed(range(1, 11)): sleep(1) print(t) if foundAllLetters or remaining_attempts == 0: break if t == 1: sleep(1) print('TIMES UP!') gameIsDone = True # 修改全局变量,通知主线程结束循环 # 游戏初始化函数,用于重启游戏 def init_game(): global gameIsDone, foundAllLetters, remaining_attempts gameIsDone = False foundAllLetters = False remaining_attempts = 3 # 这里添加你的游戏初始化逻辑:比如随机选单词、清空猜对/猜错的字母列表 secret_word = "hangman" missed_letters = [] correct_letters = [] hangman_graphics = [] # 你的刽子手图形数据 return hangman_graphics, missed_letters, correct_letters, secret_word # 主游戏循环 while True: # 初始化新游戏 hang, missed, correct, secret = init_game() # 启动计时器线程 timer_thread = threading.Thread(target=timer) timer_thread.start() # 游戏主循环:直到gameIsDone变为True while not gameIsDone: displayBoard(hang, missed, correct, secret) guess = getGuess(missed + correct) # 这里添加你的猜测处理逻辑(示例) if guess in secret: correct.append(guess) # 检查是否猜中所有字母 if all(c in correct for c in secret): foundAllLetters = True gameIsDone = True print("恭喜你赢了!") else: missed.append(guess) remaining_attempts -= 1 if remaining_attempts == 0: gameIsDone = True print("你输了!刽子手完成了!") # 等待计时器线程结束,避免线程残留 timer_thread.join() # 询问是否重玩(可选) play_again = input("再玩一次吗?(y/n): ").lower() if play_again != 'y': break
2. 关键修改点
- 在
timer函数里用global gameIsDone声明要操作全局变量,这样赋值才会影响主线程。 - 把游戏循环的条件从
while True改成while not gameIsDone,这样当计时器触发gameIsDone = True时,主循环会自动退出。 - 添加
init_game函数统一初始化游戏状态,方便重启时重置所有变量。 - 用
thread.join()等待计时器线程结束,避免线程堆积。
为什么之前的尝试无效
- 直接在timer里写
gameIsDone = True会创建一个局部变量,和主线程的gameIsDone无关,主线程根本看不到这个变化。 - 修改
t = 1也没用,因为t是timer函数里的局部变量,主循环根本不监听这个变量。
内容的提问来源于stack exchange,提问作者Ella
相关产品推荐
相关产品推荐

