python - Python 中的 Hangman 游戏

我是 Python 的新手,目前正在尝试编写我的第一段合适的代码,以模拟刽子手游戏。有一个问题我无法理解。我的代码如下所示:

import random
word_lst = ["green","red","blue"]
selected_word = random.choice(word_lst)
blank_lst = []
for element in range(len(selected_word)):
    blank_lst.append("_")
choices_left = 10
selected_word_lst = list(selected_word)
while blank_lst != selected_word_lst and choices_left != 0:
    print(blank_lst)
    print(choices_left)
    letter_selection = input("Choose a letter ")
    if letter_selection in selected_word_lst:
        print("correct selection")
        for element in selected_word_lst:
            letter_selection_pos = selected_word_lst.index(letter_selection)
            blank_lst[letter_selection_pos] = letter_selection
    else:
        print("incorrect selection")
        choices_left -= 1
if blank_lst == selected_word_lst:
    print("You win")
elif choices_left == 0:
    print("You lose")

明显的问题是,对于具有重复字母的单词(在我的小测试代码中为绿色),即使您正确选择了字母,程序也只会用正确选择的字母替换其中一个空格。

任何关于如何让它工作的提示都将不胜感激。

最佳答案

使用enumerate 遍历selected_word_list 中的字母;那么您就不必使用 index 来查找它们的位置。

https://stackoverflow.com/questions/67503274/

相关文章:

python - 如何获取字典中最大值的键,如果有重复,还返回最大数字键

python - 对象没有属性

django - 从在 WSL 上运行的 django 连接到在 Windows 上运行的 Post

android-studio - 如何降级 Kotlin 版本

vue.js - 如何将第三方脚本代码添加到 Nuxt 中?

reactjs - 在@auth0 中 Jest 模拟 Auth0Client

python-3.x - 使用 pytest 禁用在控制台上打印日志输出

emacs - 如何更改 emacs 中行号模式的背景颜色?

apache-spark - Spark 窗口函数中的条件

javascript - 如何仅在特定页面中删除页脚组件?