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

Python Hangman游戏:如何将下划线替换为猜对的字母?

解决Hangman游戏中猜对字母替换下划线的问题

核心问题在于Python的字符串是不可变类型,没法直接修改单个字符,所以我们可以把completion转成列表来操作,修改后再转回字符串。以下是补全并修改后的代码:

import random
  
# 读取单词文件并随机选择单词
with open("Words.txt", "r") as file:
    words = file.read().split()
    word = random.choice(words)

# 初始化变量
guessed_letters = ""
guessed_words = ""
completion = list("_" * len(word))  # 转成列表方便修改
lives = 8

# 游戏主循环
while lives > 0 and "_" in completion:
    print("\n当前进度: " + "".join(completion))
    print(f"剩余生命: {lives}")
    guess = input("请猜一个字母或单词: ").lower()

    # 处理重复猜测
    if guess in guessed_letters or guess in guessed_words:
        print("你已经猜过这个内容了,请换一个。")
        continue

    # 猜测单词的情况
    if len(guess) > 1:
        guessed_words += guess + " "
        if guess == word:
            completion = list(word)
            print("恭喜你猜对单词了!")
        else:
            lives -= 1
            print(f"猜错了,剩余生命: {lives}")
        continue

    # 猜测字母的情况
    guessed_letters += guess + " "
    if guess in word:
        # 遍历单词每个位置,替换对应下划线
        for i in range(len(word)):
            if word[i] == guess:
                completion[i] = guess
        print("猜对字母了!")
    else:
        lives -= 1
        print(f"猜错了,剩余生命: {lives}")

# 游戏结束判断
if "_" not in completion:
    print(f"\n游戏胜利!正确单词是: {word}")
else:
    print(f"\n游戏失败!正确单词是: {word}")

关键修改说明

  • 把completion初始化为列表:completion = list("_" * len(word)),这样可以直接修改指定位置的元素
  • 当猜对字母时,遍历目标单词的每个索引,匹配到相同字母就替换列表对应位置的元素
  • 用"".join(completion)把列表转回字符串,方便打印显示
  • 增加了游戏主循环,处理多次猜测、重复猜测、单词猜测等完整逻辑

Words.txt 文件内容

banana
nike
jordan
game
whole
hole
hi
hello

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:56:06