我遇到的问题是游戏没有结束,因为while循环没有结束,即使函数 is_word_guessed()返回True。 游戏规则是: 你猜猜这个词有6个猜测。出于测试目的,我目前正在使用secret_word ='apple'。我没有添加用于选择随机单词的代码,它工作正常。 如果你猜对了,你就不会失去任何猜测。 如果你猜错了,并且猜测是一个声音,你就会失去 2 猜测。 如果你猜错了,并且猜测是一个辅音,你就会失去 1 猜测。 如果你猜到一个你已经猜到的单词,或猜一个不是字母的单词,或者你猜两个或两个以上的单词,你就会失去1个警告。你从3个警告开始,如果你全部丢失,你就会失去一个猜测。最终得分是secret_word * guesses_remaining的唯一字母数。
import string
secret_word='apple'
def is_word_guessed(secret_word, letters_guessed):
if secret_word == letters_guessed:
return True
else:
return False
def get_guessed_word(secret_word, letters_guessed):
b=''
for char in secret_word:
if char in letters_guessed:
b=b+char
else:
b=b+"_ "
return b
def get_available_letters(letters_guessed):
s=''
letters=string.ascii_lowercase
for char in letters:
if char not in letters_guessed:
s=s+char
return s
def get_unique_letters(secret_word):
unique=''
for char in secret_word:
if char not in unique:
unique+=char
return len(unique)
print (get_unique_letters(secret_word))
def hangman(secret_word):
print("Welcome to the game of hangman!")
print ("I am thinking a word that is", str(len(secret_word)), "long.")
warnings_remaining=3
guesses_remaining=6
letters_guessed=''
while not is_word_guessed(secret_word, letters_guessed):
# checking that user has guesses left
if guesses_remaining==0:
break
else:
# checking if we have to remove a guess
if warnings_remaining==0:
guesses_remaining-=1
warnings_remaining=3
print ("---------")
print("You have", str(guesses_remaining), "guesses left.")
print("Available letters:", get_available_letters(letters_guessed))
user_guess=input("Please guess a letter:")
# checking that the input is a valid letter
if len(user_guess) != 1 or user_guess not in string.ascii_letters:
warnings_remaining-=1
print("Oops! That is not a valid letter!", "You have", warnings_remaining, "warnings left.")
elif user_guess in letters_guessed:
warnings_remaining-=1
print("Oops! That letter has alredy been guessed. You now have", warnings_remaining, "warnings left.")
# checking if the guess is right or wrong
elif user_guess in secret_word:
letters_guessed+=user_guess
print ("Good guess:", get_guessed_word(secret_word, letters_guessed))
else:
letters_guessed+=user_guess
print ("Oops! That letter is not in my word:", get_guessed_word(secret_word, letters_guessed))
if user_guess in 'aeiou':
guesses_remaining-=2
else:
guesses_remaining-=1
if guesses_remaining==0:
print("Sorry, you ran out of guesses. The word was:", secret_word)
else:
print("Congratulations, you won!")
print("Your total score for this game is:", get_unique_letters(secret_word)*guesses_remaining)
hangman(secret_word)
答案 0 :(得分:2)
您未考虑is_word_guessed()
变量中的双字母。快速解决方法是仅将def is_word_guessed(secret_word, letters_guessed):
if set(secret_word) == set(letters_guessed):
return True
else:
return False
函数中的字母转换为集合来比较字母:
fish_frame = fish_frame.drop(fish_frame.columns[-1],axis=1)