使用 python 使用 .replace() 在 hangman 中将"_"替换为字母的错误



祝大家一切顺利!

我是一个相对初学者在Python和我试图编程一个绞刑游戏,但我似乎得到一些错误,而试图取代"_"用用户猜对的字母。我尝试了很多测试和打印在不同的地方,但我仍然不能找出错误在哪里。有人能帮帮我吗?下面是我的代码:

#import random
import secrets
with open('dictionary.txt') as f:
lines = [line.rstrip() for line in f]
def randomWord():
wordR = secrets.choice(lines)
wordR = wordR.lower()
return wordR
def hangMan(word):
guessWord = "_" *len(word)
correctGuesses = []
wrongGuesses = []
lives = 0
guessedWord = False
print(word)
print(
"""
O
O O
O O O
O O O O
O O O O O
O O O O O O
"""
)
while not guessedWord and lives < 7:
print(guessWord + "n")
print("Correct Guesses: ", ",".join(correctGuesses)+"n")
print("Wrong Guesses: ", ",".join(wrongGuesses)+"n")
guessLetter = input("Guess a letter: ").lower()
if guessLetter.isalpha:
if guessLetter in word:
print( f"Nice job! You guessed the letter: {guessLetter}"+"n")
correctGuesses.append(guessLetter)
print(f"You have {7-lives} lives left!n")
#replace the _ with the letter
for x, i in enumerate(word):
if guessLetter == i:
guessWord = guessWord.replace(guessWord[x], guessLetter) #not working need fix
if guessWord == word:
guessedWord = True
print(f"Nice job! You have successfully guessed the word: {word}")
break
elif guessLetter in correctGuesses:
print("You have already guessed this letter correctly before!n ")
elif not guessLetter in word:
print(f"{guessLetter} isn't one of the characters!n ")
wrongGuesses.append(guessLetter)
lives+=1
print(guessWord + "n")
if lives == 0:
print(
"""
O
O O
O O O
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 1:
print (
"""
O O
O O O
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 2:
print(
"""
O O O
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 3:
print(
"""
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 4:
print(
"""
O O O O O
O O O O O O
"""
)
elif lives == 5:
print (
"""
O O O O O O
"""
)
elif lives == 6:
print(f"Oh no! The pyramid got completely deconstructed! You lost! The word was {word}!")
def main():
wordR2 = randomWord()
hangMan(wordR2)
while "yes" in input("Do you want to play again? ").lower():
wordR2 = randomWord()
hangMan(wordR2)

if __name__ == "__main__":
main()

所以当我运行它时,我没有得到任何错误,我假设你的意思是它只是不按预期工作。

首先,在您的原始代码中,guessLetter in correctGuesses位于guessLetter in word之后,因此guessLetter in correctGuesses总是会被跳过。颠倒顺序可以解决这个问题。

第二,使用guessWord.replace(guessWord[x], guessLetter)会导致所有出现的guessWord[x]都被guessLetter取代。所以如果你有guessWord = "_____"word = "hello",你猜"e",那么如果你做guessWord = guessWord.replace("_", "e")所有的"_"将被替换,导致guessWord == "eeeee"。你需要改变特定的索引,但是由于字符串是不可变的,你不能做guessWord[1] = "e",你必须把三个字符串加在一起:第一个字符串是不变的第一部分,第二部分是改变的字母,第三部分是不变的最后一部分("guessWord = guessWord[:1]+"e"+guessWord[2:])。

第三,最次要的部分是,如果你失去6条生命(lives==6),它说你输了,但你可以继续。只需添加一个break来结束当前游戏。

#import random
import secrets
with open('dictionary.txt') as f:
lines = [line.rstrip() for line in f]
def randomWord():
wordR = secrets.choice(lines)
wordR = wordR.lower()
return wordR
def hangMan(word):
guessWord = "_" *len(word)
correctGuesses = []
wrongGuesses = []
lives = 0
guessedWord = False
print(word)
print(
"""
O
O O
O O O
O O O O
O O O O O
O O O O O O
"""
)
while not guessedWord and lives < 7:
print(guessWord + "n")
print("Correct Guesses: ", ",".join(correctGuesses)+"n")
print("Wrong Guesses: ", ",".join(wrongGuesses)+"n")
guessLetter = input("Guess a letter: ").lower()
if guessLetter.isalpha:
if guessLetter in correctGuesses: #needs to be in front, otherwise it will never run
print("You have already guessed this letter correctly before!n ")
elif guessLetter in word:
print( f"Nice job! You guessed the letter: {guessLetter}"+"n")
correctGuesses.append(guessLetter)
print(f"You have {7-lives} lives left!n")
for x, i in enumerate(word):
if guessLetter == i:
guessWord = guessWord[:x]+guessLetter+guessWord[x+1:]
#can't use replace, because that replaces all of it
#I used indexing to add three strings together: the beginning part of the word, the letter, and the end part
if guessWord == word:
guessedWord = True
print(f"Nice job! You have successfully guessed the word: {word}")
break
elif not guessLetter in word:
print(f"{guessLetter} isn't one of the characters!n ")
wrongGuesses.append(guessLetter)
lives+=1
print(guessWord + "n")
if lives == 0:
print(
"""
O
O O
O O O
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 1:
print (
"""
O O
O O O
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 2:
print(
"""
O O O
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 3:
print(
"""
O O O O
O O O O O
O O O O O O
"""
)
elif lives == 4:
print(
"""
O O O O O
O O O O O O
"""
)
elif lives == 5:
print (
"""
O O O O O O
"""
)
elif lives == 6:
print(f"Oh no! The pyramid got completely deconstructed! You lost! The word was {word}!")
break # so that game ends when you lose
def main():
wordR2 = randomWord()
hangMan(wordR2)
while "yes" in input("Do you want to play again? ").lower():
wordR2 = randomWord()
hangMan(wordR2)

if __name__ == "__main__":
main()

str.replace()是一个inplace方法,这意味着您刚刚编写的代码将返回一个NoneType。

所以,也许删除guessWord =将工作。

最新更新