首页 > 解决方案 > 用正确的猜测字母替换下划线,Python hangman

问题描述

我正在创建一个刽子手游戏,无法用猜到的正确字母替换“_”。

我已经看到了其他答案,但仍然无法找到相关的解决方案。我无法理解:Python 刽子手,替换字母?


# some code

#vars
real_word = random_word()
secret_word = str(['_'] * len(real_word))
attempts = 999
letter = []
letters_guessed = []

# some code

# If correct guess  
if letter in real_word:
        # Here replace '_' with letter # IF CORRECT


预期结果:如果猜对了字母,将其替换为 secret_word 中的下划线(一个字母可以代替 1 个以上的下划线)。

标签: python

解决方案


跟踪当前字母的最简单方法是使用列表。列表是可变的,因此可以轻松地在它们中间更改值。使用以下代码,它将换出匹配的字母。

real_word = "test"
secret_word = ["_"] * len(real_word)

guess = input("Guess letter: ")

# Loop through the letters in the real word
for i, letter in enumerate(real_word):
  # Check if the current looped letter is equal to the guess
  if letter != "_" and guess == letter:
    # Set the underscore at that position to the correct letter
    secret_word[i] = letter

# Output list as joined string
print("".join(secret_word))

随着猜测t,代码将输出t__t


推荐阅读