# 用Python实现字母猜谜游戏(简化版Hangman):掌握字符串处理与JSON存档


背景介绍

字母猜谜游戏(如简化版Hangman)是经典的文字互动游戏,玩家通过猜测字母还原隐藏单词。这个项目不仅能锻炼字符串处理文件IO逻辑控制等核心编程技能,还能实践用户交互设计。本文将一步步实现一个支持存档/读档的简化版Hangman,帮助你巩固Python基础。

思路分析

要实现这个游戏,需解决以下核心问题:
1. 状态管理:随机选单词,维护已猜字母、剩余次数、当前显示(下划线占位)。
2. 用户交互:处理字母输入、验证合法性(单个字母、未重复),支持存档/加载。
3. 逻辑控制:判断猜测是否正确、胜利/失败条件、次数限制。
4. 数据持久化:将游戏状态序列化为JSON并保存,加载时反序列化恢复状态。

代码实现

我们将代码分为状态显示输入验证存档/读档游戏逻辑四大模块,依赖Python标准库random(随机选单词)和json(处理JSON文件)。

1. 游戏状态显示函数

display_game_state 负责将单词的猜测状态可视化(已猜字母显示,未猜的用下划线):

def display_game_state(guessed_letters, target_word, remaining_attempts):
    """显示当前游戏状态:已猜字母的位置显示,未猜的用下划线,剩余次数"""
    display_chars = []
    for char in target_word:
        # 已猜字母显示,否则用下划线
        display_chars.append(char if char in guessed_letters else "_")
    # 用空格分隔字符,增强可读性
    display_str = " ".join(display_chars)
    print(f"当前单词: {display_str}")
    print(f"剩余猜测次数: {remaining_attempts}")
    return display_str  # 返回显示字符串,用于存档

2. 输入验证函数

is_valid_guess 检查用户输入是否为单个字母未被猜测过

def is_valid_guess(guess, guessed_letters):
    """验证猜测是否合法:单个字母、未重复"""
    guess = guess.lower()  # 统一小写
    if len(guess) != 1:
        return False, "请输入单个字母!"
    if not guess.isalpha():
        return False, "请输入字母(a-z)!"
    if guess in guessed_letters:
        return False, "该字母已猜过,请换一个!"
    return True, ""

3. 存档与读档函数

save_game 将游戏状态(单词、已猜字母、剩余次数、当前显示)保存为JSON;load_game 从JSON文件恢复状态:

def save_game(state, filename="game_save.json"):
    """将游戏状态保存到JSON文件"""
    try:
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(state, f, indent=2)  # 缩进美化,便于阅读
    except Exception as e:
        print(f"存档失败:{e}")

def load_game(filename="game_save.json"):
    """从JSON文件加载游戏状态"""
    if not os.path.exists(filename):
        print(f"存档文件 {filename} 不存在!")
        return None
    try:
        with open(filename, "r", encoding="utf-8") as f:
            state = json.load(f)
        # 验证必要字段是否存在
        required = ["target_word", "guessed_letters", "remaining_attempts"]
        if not all(k in state for k in required):
            print("存档格式错误:缺少核心字段!")
            return None
        return state
    except json.JSONDecodeError:
        print("存档文件格式错误(非JSON)!")
        return None
    except Exception as e:
        print(f"加载失败:{e}")
        return None

4. 游戏逻辑主函数

play_game 处理核心猜测逻辑,支持存档、胜利/失败判断:

def play_game(target_word, initial_guessed=None, initial_remaining=None):
    """开始或继续游戏,处理猜测循环"""
    # 初始化状态:已猜字母(深拷贝避免引用问题)、剩余次数
    guessed_letters = initial_guessed.copy() if initial_guessed else []
    remaining_attempts = initial_remaining if initial_remaining is not None else 10
    # 显示初始状态
    current_display = display_game_state(guessed_letters, target_word, remaining_attempts)
    game_over = False

    while not game_over and remaining_attempts > 0:
        # 处理用户输入
        guess = input("\n请输入字母(或'save'保存、'quit'退出): ").strip().lower()

        # 特殊指令:保存或退出
        if guess in ["save", "quit"]:
            if guess == "save":
                # 保存当前状态
                state = {
                    "target_word": target_word,
                    "guessed_letters": guessed_letters,
                    "remaining_attempts": remaining_attempts,
                    "current_display": current_display
                }
                save_game(state)
                print("游戏已保存至 game_save.json!")
                continue  # 不消耗次数,继续游戏
            else:  # quit
                print("游戏退出,感谢游玩!")
                game_over = True
                break

        # 验证输入合法性
        valid, error = is_valid_guess(guess, guessed_letters)
        if not valid:
            print(error)
            continue

        # 记录猜测
        guessed_letters.append(guess)

        # 判断是否猜对
        correct = guess in target_word
        if correct:
            print(f"✓ 猜对了!字母 '{guess}' 在单词中!")
        else:
            remaining_attempts -= 1
            print(f"✗ 猜错了!字母 '{guess}' 不在单词中。剩余次数: {remaining_attempts}")

        # 更新显示
        current_display = display_game_state(guessed_letters, target_word, remaining_attempts)

        # 检查胜利/失败
        if all(c in guessed_letters for c in target_word):
            print(f"\n🎉 恭喜获胜!你用了 {10 - remaining_attempts} 次猜测,单词是:{target_word}")
            game_over = True
        elif remaining_attempts == 0:
            print(f"\n💀 游戏失败!正确单词是:{target_word}")
            game_over = True

    # 游戏结束后询问是否再来一局
    if not game_over:  # 正常结束(非quit)
        play_again = input("再来一局?(y/n): ").strip().lower()
        if play_again == "y":
            start_game()
        else:
            print("再见!")

5. 游戏入口函数

start_game 提供“新游戏”或“加载存档”的选项:

def start_game():
    """游戏入口:选择新游戏或加载存档"""
    print("\n===== 字母猜谜游戏 (简化版Hangman) =====")
    print("1. 开始新游戏")
    print("2. 加载存档继续游戏")
    choice = input("请选择 (1/2): ").strip()

    WORD_LIST = ["python", "java", "programming", "javascript", "html", "css"]
    if choice == "1":
        # 随机选单词,开始新游戏
        target_word = random.choice(WORD_LIST)
        play_game(target_word)
    elif choice == "2":
        # 尝试加载存档
        state = load_game()
        if state:
            print("成功加载存档,继续游戏!")
            play_game(
                target_word=state["target_word"],
                initial_guessed=state["guessed_letters"],
                initial_remaining=state["remaining_attempts"]
            )
        else:
            print("加载失败,开始新游戏!")
            target_word = random.choice(WORD_LIST)
            play_game(target_word)
    else:
        print("无效选择,默认开始新游戏!")
        target_word = random.choice(WORD_LIST)
        play_game(target_word)

主程序执行

通过 if __name__ == "__main__" 启动游戏:

if __name__ == "__main__":
    start_game()

功能测试与扩展

运行程序后,你可以:
– 选择“1”开始新游戏,输入字母猜测,输入save保存进度。
– 选择“2”加载存档,继续之前的游戏。
– 输入重复字母或非字母时,程序会提示错误。

扩展方向

  • 增加单词难度(如带空格、大小写)。
  • 美化界面(ASCII艺术展示Hangman)。
  • 统计游戏记录(胜场、平均猜测次数)。

总结

通过这个项目,我们实践了:
字符串处理:动态生成带空格的显示字符串,区分已猜/未猜字母。
文件IO与JSON:用json模块实现游戏状态的持久化,支持存档/读档。
逻辑控制:通过循环、条件判断处理猜测、胜利/失败判定。
用户交互:验证输入合法性,提供友好的反馈。

希望这个项目能帮助你巩固Python基础,享受编程的乐趣!


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注