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

如何实现Hangman类游戏输入stop/exit时终止整个程序?

解决Hangman游戏中输入stop/exit终止整个程序的问题

你的核心问题是:当前的break只能跳出所在的局部循环,无法终止最外层的游戏循环。下面提供几种简单有效的修改方案:

方案一:使用全局终止标志

定义布尔变量作为全局运行标志,在触发终止指令时修改标志,让最外层循环检测到后退出。

修改步骤

  1. 最外层循环前定义game_active = True
  2. 用户输入stop/exit时,先设置game_active = False,再break当前局部循环
  3. 最外层循环条件改为while game_active:

修改后的完整代码

import random  # 原代码用到choice,需导入random模块
word4 = ["test", "play", "four"]  # 示例4字母单词列表
word5 = ["apple", "grape", "table"]  # 示例5字母单词列表

game_active = True
while game_active:  # 用标志变量控制整个游戏循环
    print("Welcome to Guess-The-Letter game")
    print("")

    # 选择猜测次数
    while True:
        num_guess = input("how many times do you want to guess [1-10]: ")
        if num_guess.lower() in ["stop", "exit"]:
            print("Game Ends!")
            game_active = False
            break
        try:
            num_guess = int(num_guess)
        except ValueError:
            print("Not a number!")
            continue
        if num_guess < 1 or num_guess > 10:
            print("Out of Range")
        else:
            result1 = num_guess
            break
    if not game_active:
        break  # 提前退出,避免执行后续代码

    # 选择单词长度
    while True:
        length = input("please enter the length of the word [4-5]: ")
        if length.lower() in ["stop", "exit"]:
            print("Game Ends!")
            game_active = False
            break
        try:
            length = int(length)
        except ValueError:
            print("Not a number!")
            continue
        if length < 4 or length > 5:
            print("Out of Range")
        else:
            result2 = length
            break
    if not game_active:
        break

    # 选择单词
    if result2 == 4:
        word = random.choice(word4)
    elif result2 == 5:
        word = random.choice(word5)
    guess_list = []
    sec_word = ["*" for _ in range(len(word))]  # 简化原代码的循环
    guess = ""
    print("Selecting the word...")

    # 猜字母环节
    while result1 > 0 and game_active:
        print("word is:", "".join(sec_word))
        print("Guess remaining:", result1)
        print("Previous guess:", guess)
        guess = input("Please guess a letter: ")
        if guess in guess_list:
            print(f"{guess} has been guessed before", end=" ")
        guess_list.append(guess)
        if guess.lower() in ["stop", "exit"]:
            print("Game Ends!")
            game_active = False
            break
        if guess in word:
            # 简化原代码的逐个索引判断,直接遍历替换
            for idx, char in enumerate(word):
                if char == guess:
                    sec_word[idx] = guess
            print(f"{guess} is in the word!")
        else:
            print(f"{guess} is not in the word! Try again")
        print("")
        if "".join(sec_word) == word:
            print("You win!")
            break
        result1 -= 1

方案二:用函数封装游戏逻辑

把整个游戏逻辑放到函数里,触发终止指令时直接return,结束整个函数执行:

import random
word4 = ["test", "play", "four"]
word5 = ["apple", "grape", "table"]

def hangman_game():
    while True:
        print("Welcome to Guess-The-Letter game")
        print("")

        # 选择猜测次数
        while True:
            num_guess = input("how many times do you want to guess [1-10]: ")
            if num_guess.lower() in ["stop", "exit"]:
                print("Game Ends!")
                return  # 直接返回,终止整个函数
            try:
                num_guess = int(num_guess)
            except ValueError:
                print("Not a number!")
                continue
            if num_guess < 1 or num_guess > 10:
                print("Out of Range")
            else:
                result1 = num_guess
                break

        # 选择单词长度
        while True:
            length = input("please enter the length of the word [4-5]: ")
            if length.lower() in ["stop", "exit"]:
                print("Game Ends!")
                return
            try:
                length = int(length)
            except ValueError:
                print("Not a number!")
                continue
            if length < 4 or length > 5:
                print("Out of Range")
            else:
                result2 = length
                break

        # 选择单词及猜字母逻辑
        if result2 == 4:
            word = random.choice(word4)
        elif result2 == 5:
            word = random.choice(word5)
        guess_list = []
        sec_word = ["*" for _ in range(len(word))]
        guess = ""
        print("Selecting the word...")

        while result1 > 0:
            print("word is:", "".join(sec_word))
            print("Guess remaining:", result1)
            print("Previous guess:", guess)
            guess = input("Please guess a letter: ")
            if guess in guess_list:
                print(f"{guess} has been guessed before", end=" ")
            guess_list.append(guess)
            if guess.lower() in ["stop", "exit"]:
                print("Game Ends!")
                return
            if guess in word:
                for idx, char in enumerate(word):
                    if char == guess:
                        sec_word[idx] = guess
                print(f"{guess} is in the word!")
            else:
                print(f"{guess} is not in the word! Try again")
            print("")
            if "".join(sec_word) == word:
                print("You win!")
                break
            result1 -= 1

hangman_game()

额外优化提示

  • 把num_guess.lower() == "stop" or num_guess.lower() == "exit"简化为num_guess.lower() in ["stop", "exit"],更简洁
  • 原代码中逐个索引替换字母的逻辑,用enumerate遍历简化,避免重复代码
  • 补充了原代码缺失的random模块导入和单词列表示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:35:23