对于作业,我需要写一个基本的HANGMAN游戏 . 这一切都有效,除了这一部分......
该游戏应该为这个神秘词中的每个字母打印其中一个下划线(“_”);然后当用户猜出(正确)字母时,它们将被放入 .
例如
假设这个词是"word"
用户猜测"W"
W _ _ _
用户猜测"D"
W _ _ D
但是,在许多情况下,一旦用户进行了一些猜测,一些下划线就会丢失,因此最终看起来像:
W _ D
代替:
W _ _ D
我无法弄清楚我的代码的哪一部分正在实现这一点 . 任何帮助,将不胜感激!干杯!
这是我的代码:
import random
choice = None
list = ["HANGMAN", "ASSIGNEMENT", "PYTHON", "SCHOOL", "PROGRAMMING", "CODING", "CHALLENGE"]
while choice != "0":
print('''
******************
Welcome to Hangman
******************
Please select a menu option:
0 - Exit
1 - Enter a new list of words
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
print("Exiting the program...")
elif choice =="1":
list = []
x = 0
while x != 5:
word = str(input("Enter a new word to put in the list: "))
list.append(word)
word = word.upper()
x += 1
elif choice == "2":
word = random.choice(list)
word = word.upper()
hidden_word = " _ " * len(word)
lives = 6
guessed = []
while lives != 0 and hidden_word != word:
print("\n******************************")
print("The word is")
print(hidden_word)
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print("*******************************")
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print("************************")
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You ahve no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = input("\n That is not a valid option! Please try again!\n Choice: ")
2 回答
你有
hidden_word = " _ " * len(word)
这意味着在两个字母的单词开头,你有[空格] [下划线] [空格] [空格] [下划线] [空格] .然后当你执行
word_so_far += hidden_word[i]
时,对于i = 0,你将追加一个空格,而不是下划线 .最快的解决方案似乎是:
将hidden_word设置为_的(
hidden_word = " _ " * len(word)
)当您打印出单词时,请执行
hidden_word.replace("_"," _ ")
以添加下划线周围的空格@Foon向您展示了解决方案的问题 .
如果您可以将代码划分为小功能块,则可以更轻松地专注于该任务,并且可以更轻松地进行测试 . 当您遇到特定任务的问题时,通过将问题变为函数来帮助隔离问题 .
像这样的东西 .