You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

猜字游戏重复功能异常:输入yes未重启游戏反而重复询问

问题原因

输入yes后游戏不重启,核心原因是第一次游戏结束后关键变量未重置:

  • count_attempts已累计到3次上限,第二次进入外层循环时,内层循环的count_attempts < limit_attempts条件不成立
  • guess_word要么已等于hidden_word(获胜场景),要么是最后一次错误输入(失败场景),内层循环的guess_word != hidden_word条件也不满足

两个条件同时失效,导致内层循环直接跳过,程序立刻进入“是否再玩”的输入环节,看起来像游戏未重启。

修复方案

将需要重置的变量(count_attempts、guess_word)放到外层while play_again == 'yes'循环内部,确保每次启动新游戏时初始化这些变量。

修改后的代码
print('                                    Welcome to the gussing game :)')
print("\n\nyou have only 3 attempts to win ")

hidden_word = 'zak'
limit_attempts = 3
play_again = 'yes'


while play_again == 'yes':
    # 每次新游戏重置尝试次数和猜测的单词
    count_attempts = 0
    guess_word = ''
    while (guess_word != hidden_word) and (count_attempts < limit_attempts):
        guess_word = input("\nplease enter your word: ")
        count_attempts += 1
        if count_attempts == limit_attempts and guess_word != hidden_word:
            print("Sorry,  you lose due to Out of attempts ")
        elif guess_word != hidden_word:
            print("Wrong attempt, try again ...")
        else:
            print(" Wow you won !!")
    play_again = input('\ndo you want to play again (yes or no): ').lower()
说明

把count_attempts = 0和guess_word = ''移到外层循环内,保证每次重新开始游戏时,尝试次数归零、猜测的单词清空,内层循环能正常触发,游戏即可正常重启。

内容的提问来源于stack exchange,提问作者Zakaria Mohamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:15:51