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

Python猜单词游戏:优化字母存在性与位置检查的冗余代码

优化猜单词游戏的核心逻辑

我们可以通过状态跟踪的方式彻底消除冗余代码,核心思路是维护一个显示当前猜测进度的列表,每次用户输入字母后,遍历目标单词更新这个进度列表,替代逐个位置写判断的冗余操作。

关键优化点与实现步骤

  • 状态初始化:用与目标单词长度一致的下划线列表,记录已猜中字母的位置
  • 输入逻辑封装:把单个字母的输入验证做成独立函数,避免重复代码
  • 动态更新进度:遍历目标单词的每个字符,匹配成功就更新进度列表,无需硬编码每个位置的判断

完整优化代码

import random

def get_valid_input():
    while True:
        user_input = input("Guess a letter: ").lower()
        # 确保输入是单个字母
        if len(user_input) == 1 and user_input.isalpha():
            return user_input
        print("Please type only one single letter.")

# 游戏初始化
name_list = ["sound", "train", "table", "phone", "mouse", "water"]
pick_word = random.choice(name_list).lower()
# 用下划线初始化进度,长度和目标单词一致
progress = ["_"] * len(pick_word)
# 记录已猜过的字母,避免重复猜测
guessed_letters = set()
# 可选:设置最大尝试次数
max_attempts = 6

print(f"Welcome to Word Guess! The word has {len(pick_word)} letters.")

# 游戏主循环
while "_" in progress and max_attempts > 0:
    print("\nCurrent progress: " + " ".join(progress))
    print(f"Guessed letters: {', '.join(guessed_letters) if guessed_letters else 'None'}")
    
    guess = get_valid_input()
    
    if guess in guessed_letters:
        print("You already guessed that letter! Try another one.")
        continue
    
    guessed_letters.add(guess)
    
    if guess in pick_word:
        print("Correct!")
        # 遍历单词每个位置,更新进度
        for idx, char in enumerate(pick_word):
            if char == guess:
                progress[idx] = guess
    else:
        max_attempts -= 1
        print(f"Wrong! You have {max_attempts} attempts left.")

# 游戏结束判定
if "_" not in progress:
    print(f"\nCongratulations! You guessed the word: {pick_word}")
else:
    print(f"\nGame over! The word was: {pick_word}")

为什么这比原代码更好

  1. 彻底消除冗余:无需为每个字母位置写单独的if判断,无论单词长度如何都能适配
  2. 逻辑清晰可扩展:新增功能(比如最大尝试次数、重复猜测提示)只需少量修改
  3. 代码复用性高:输入验证函数可以在其他场景复用
  4. 状态统一管理:进度列表集中控制显示内容,避免分散的字符串拼接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:01:19