如何检查刽子手游戏的重复输入(字母)?
示例:
字是苹果
输入是猜一封信:a
输出很好!
然后猜猜下一个字
输入是猜一封信:a
输出应该是你猜的那封信。
我的代码:
def checkValidGuess():
word = getHiddenWord()
lives = 10
num = ["1","2","3","4","5","6","7","8","9",]
#guessed = ''
while lives != 0 and word:
print("\nYou have", lives,"guesses left")
letter = input("Guess a letter or enter '0' to guess the word: ")
if letter.lower() in word:
print("Well done!", letter, "is in my word!")
lives -= 1
elif len(letter)>1:
print("You can only guess one letter at a time!")
print("Try again!")
elif letter in num:
print("You can only input letter a - z!")
print("Try again!")
#elif letter in guessed:
#print("repeat")
elif letter == "0":
wword = input("What is the word?").lower()
if wword == word:
print("Well done! You got the word correct!")
break
else:
print("Uh oh! That is not the word!")
lives -= 1
#elif letter == "":
#print("Uh oh! the letter you entered is not in my word.")
#print("Try again!")
else:
print("Uh oh! the letter you entered is not in my word.")
print("Try again!")
lives -= 1
感谢。
答案 0 :(得分:2)
您可以将输入存储在列表中,我们称之为temp
。
然后,当用户输入新信件时,您可以检查列表中是否存在输入。
guess = input()
if guess in temp:
print "You've already guessed {}".format(guess)
else:
#do whatever you want
答案 1 :(得分:1)
这是一个简单的方法。首先初始化一个列表:
guesses = []
然后在你的循环中:
letter = input("Guess a letter or enter '0' to guess the word: ")
if letter in guesses:
print("Already guessed!")
continue
guesses.append(letter)
答案 2 :(得分:0)
因此,您可能希望在计划中反转支票的顺序,以便首先处理再试一次。在更改之后,添加另一个条件,确定该字母是否与已经猜到的字母匹配。这导致类似:
already_guessed = set() # I made this a set to only keep unique values
while lives > 0 and word: # I changed this to test > 0
print(f"\nYou have {lives} guesses left") # I also added an f-string for print formatting
letter = input("Guess a letter or enter '0' to guess the word: ")
if len(letter) > 1:
print("You can only guess one letter at a time!")
print("Try again!")
continue # If you reach this point, start the loop again!
elif letter in already_guessed:
print("You already guessed that!")
print("Try again")
continue
elif letter in num:
print("You can only input letter a - z!")
print("Try again!")
continue
elif letter.lower() in word:
print("Well done!", letter, "is in my word!")
lives -= 1
else:
already_guessed.update(letter)
# It wasn't a bad character, etc. and it wasn't in the word\
# so add the good character not in the word to your already guessed
# and go again!
您需要添加其他条件分支,但这应该可以帮助您。祝你好运。