如何将字母从一个列表随机删除到另一个列表,但要移动到正确的位置



我刚开始学习python,作为学习的一部分,我正在尝试制作简单的程序。

所以我试图制作一个刽子手游戏,但我被困住了。

我想不出更好的方法来识别玩家需要猜测的单词中的字母 - - 并将字母添加到玩家到目前为止猜测的 var 的正确位置。

代码:

import random
list_of_words = ["door", "house", "work", "trip", "plane", "sky", "line", "song", "ever","life"]
random_word = list_of_words[random.randint(0, len(list_of_words) - 1)]

guessed_word = "_" * len(random_word)
print("Hello!, welcom to my hangman Game")
print("try to guess what word could that be??? ")
print(guessed_word)
guessed_word = guessed_word.split()
random_word = list(random_word)
print(random_word, guessed_word)

while len(random_word) != 0:
letter = input("guess a letter >>>... ")
if letter in random_word:
print(f"YAY! thats right, {letter} is in the word")
index = random_word.index(letter)
random_word.remove(letter)
guessed_word[index] = letter
print("this is your word now >> ", guessed_word)
else:
print("the word isnt there")
print("yay, you found the word")

因此,代码运行良好,它会识别玩家何时完成选择所有正确的字母。 问题是如何复制单词并显示玩家进度。 因此,一开始它会将字母放在正确的位置,但之后它不会更改字母的位置。

这里有几件事是错误的。

  • 只找到一个出现的字母(door只会找到第一个 o(
  • 删除项目会丢失对索引的跟踪
  • guessed_word分裂错误

这些问题已修复:

import random
list_of_words = ["door", "house", "work", "trip", "plane", "sky", "line", "song", "ever","life"]
random_word = list_of_words[random.randint(0, len(list_of_words) - 1)]

guessed_word = "_" * len(random_word)
print("Hello!, welcom to my hangman Game")
print("try to guess what word could that be??? ")

# Convert to list first
guessed_word = list(guessed_word)
# Print separated with spaces second
print(' '.join(guessed_word))
random_word = list(random_word)
# Check if the guessed word is the same as the random word, if it is, the word is fully guessed
while random_word != guessed_word:
letter = input("guess a letter >>>... ")
if letter in random_word:
print(f"YAY! thats right, {letter} is in the word")
# find all indices of the letter
indices = [i for i, x in enumerate(random_word) if x == letter] # * see notes
# Update all indices of the guessed word with the letter
for i in indices:
guessed_word[i] = letter
# Don't remove the letter from the random word
# Print with spaces, because it's nicer that way!
print("this is your word now >> ", ' '.join(guessed_word))
else:
print("the word isnt there")
print("yay, you found the word")

希望这有帮助!祝你玩得开心!

笔记:

列表理解可能很可怕,看看这个

你只需要替换

guessed_word = guessed_word.split()

跟:

guessed_word = list(guessed_word)

以及举例说明的原因:

>>> x="work"
>>> x.split()
['work']
>>> list(x)
['w', 'o', 'r', 'k']
>>>

x.split()将每个空格的句子拆分为分隔符 - 您希望按字母拆分。

最新更新