所以我正在尝试制作一个小刽子手风格的程序,但在保存正确的猜测时遇到了问题。
到目前为止,我已经达到了第一个正确的猜测在需要的地方输出字母的地步,例如,如果正确的字母是:
_ _ _ a _ _
但是,每当我进行第二次猜测时,即使正确,它也只会打印出正确的猜测并忘记过去的正确猜测。例如,如果 b 在第二次猜测中是正确的字母:
_ _ b _ _ _
这是我的代码
for letter in range(len_word):
print('_', end=" ")
guess = input("The length of the word is " + str(len_word) + ". Guess a letter, or ask for a vowel ... ")
while wrong_guesses < 6:
if guess in letters_in_word:
for letter in range(len(given_word)):
if given_word[letter:letter+1] == guess:
print(guess, end=" ")
else:
print('_', end=" ")
guess = input("The length of the word is " + str(len_word) + ". Guess a letter, or ask for a vowel ... ")
else:
wrong_guesses -= 1
print("Your guess is not in the word, you have " + str(wrong_guesses) + " left.")
guess = input("The length of the word is " + str(len_word) + ". Guess a letter, or ask for a vowel ... ")
我想要的是,如果我第一次猜测我得到了正确的答案,并且它输出了
_ _ _ a _ _
我希望打印出我的下一个猜测(如果不正确)
_ _ _ a _ _
最佳答案
主要问题是如何跟踪刽子手。现在,每当他们猜对时,你就会打印空白并显示正确的字母。有多种方法可以跟踪猜测。考虑使用字符列表,并在每次猜对时更新它,例如:
scoreboard = [_] * len_word
while incorrect_guesses < 6:
// get the guess
any_correct = None
for index, char in enumerate(hangman_word):
if guess == char:
scoreboard[index] = guess
any_correct = True
print(scoreboard)
if not any_correct
print("wrong guess message")
incorrect_guess += 1
这个想法是拥有一个真正的单词字符串和一个向用户显示的列表。 index, char
部分只是让您浏览实际的单词并跟踪您在真实字符串中查看的字符以及它在字符串中的位置。
(您希望使用列表而不是字符串作为答案,因为字符串是不可变的,并且您实际上对可变性投入了大量精力 - 这使得列表成为完美的候选者。)
关于python - Hangman 程序,在更新输出时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878592/