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

如何检查列表重复元素并获取所有索引?猜单词游戏问题

解决Hangman游戏重复字母仅显示一次的问题

你的问题出在使用word.index(guess)时,这个方法只会返回目标字母第一次出现的索引,导致重复字母无法全部在guess_list中显示。要解决这个问题,需要遍历目标单词的所有索引,找到所有匹配该字母的位置并逐个更新guess_list。

以下是修改后的完整代码:

import random
from words import words
from test import one, two, three, four, five, six, seven, eight, nine

lives_left = 9
letters_picked = []

# 选择目标单词(修正拼写错误:origional → original)
word_original = words[random.randint(0, len(words)-1)]  # 修正索引越界问题,原代码会取到超出列表范围的索引

# 创建空白猜测列表
guess_list = ["_"] * len(word_original)

# 将目标单词转为字符列表
word = list(word_original)

# 游戏循环
while lives_left > 0 and guess_list != word:
    print("Word: " + str(guess_list))
    print("Wrong letters: " + str(letters_picked))
    guess = input("Guess: ")
    
    if guess in word:
        print("Letter in word!")
        # 遍历所有索引,更新所有匹配的位置
        for idx, letter in enumerate(word):
            if letter == guess:
                guess_list[idx] = guess
    elif guess not in word:
        print("Letter not in word!")
        letters_picked.append(guess)
        lives_left -= 1
    
    # 选择对应的Hangman图案
    if lives_left == 9:
        hangman = "Full lives!"
    elif lives_left == 8:
        hangman = one
    elif lives_left == 7:
        hangman = two
    elif lives_left == 6:
        hangman = three
    elif lives_left == 5:
        hangman = four
    elif lives_left == 4:
        hangman = five
    elif lives_left == 3:
        hangman = six
    elif lives_left == 2:
        hangman = seven
    elif lives_left == 1:
        hangman = eight
    
    # 显示Hangman和剩余生命
    print(hangman)
    print(f"{lives_left} lives left")

# 失败提示
if lives_left == 0:
    print(nine)
    print("You ran out of lives!")
    print(f"The word was {word_original}")
# 胜利提示
else:
    print("Congrats! You got the word!")
    print(f"You had {lives_left} lives left.")  # 修正整数与字符串拼接的错误

关键修改说明:

  1. 重复字母处理:用enumerate遍历word的每个索引和字符,找到所有与guess匹配的位置,更新guess_list对应索引的值,确保所有重复字母都能显示。
  2. 索引越界修正:原代码random.randint(0, len(words))会取到等于len(words)的索引,超出列表范围,改为random.randint(0, len(words)-1)。
  3. 拼写错误修正:word_origional改为正确的word_original。
  4. 字符串拼接修正:胜利提示中用f-string避免整数与字符串直接拼接的错误。

内容的提问来源于stack exchange,提问作者Zac Zoom Godfrey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:12:27