纠正用户输入以满足绳索游戏的特定要求
我需要用户输入的内容只能是一个字符,但代码里有个bug,让我可以一次输入多个字符。我想提示用户只能输入一个字符,然后再让他们输入,但这个输入不应该算在游戏里。
print ("lets play guess this word.") #time to play
secret_word = input("Enter a secret word to guess: ") # gather the secret word
secret_word = secret_word.lower() # convert to lower
guesses = "" # this is the string that will show what has been guessed later
turns = 6 # how many chances they get to enter a wrong character.
# a very very tricky while loop.
while turns > 0: # will be true until the turns counter makes turns = 0
count = 0 # this count determines wether to print _ or the character
for char in secret_word: # looking at characters in the secret word
if char in guesses: # this is used to display the correct letters and _'s
print (char, end="")
else:
print ("_ ",end="") # this print the _ for every char in secretword
count += 1 # ends the for loop continues to the next part
if count == 0: # you won the game end the loop.
print ()
print ("You win")
break
print ()
print ()
print ()
guess = input("guess a character:")
count2 = 0
if len(guess) > 1:
count2 += 1
while count2 > 0:
print ("you can only guess 1 character at a time")
count2 -= 1
guess = guess.lower() #lower # it is time to guess the letters.
guesses += guess
if guess not in secret_word: # if statement for if guess is not in word
turns -= 1 # subtract from turns
print ()
print ()
print ("Wrong")
print ("Letters guessed so far: ",guesses) # end of loop show guessed letters
print ("You have", + turns, 'more guesses') # show turns left
if turns == 0: # END GAME
print ("The word was",secret_word,"You Loose")
这里有个截图,显示代码在Python中是可以工作的:
我还需要帮助,让它只能接受一个字符,并且不允许输入数字。我在尝试实现这个功能时添加了这部分代码,但它并没有阻止多个字符被输入并算入单词中。
count2 = 0
if len(guess) > 1:
count2 += 1
while count2 > 0:
print ("you can only guess 1 character at a time")
count2 -= 1
这是我的输出:
lets play guess this word.
Enter a secret word to guess: computer
_ _ _ _ _ _ _ _
guess a character:abcdefghijklmnopqrstuvwxyz
you can only guess 1 character at a time
Wrong
Letters guessed so far: abcdefghijklmnopqrstuvwxyz
You have 5 more guesses
computer
You win
1 个回答
1
你缺少的就是在用户输入无效内容后,能够重新回到循环的语句。根据你现在的结构,你需要的语句是 continue
,它会让程序跳到循环的下一次迭代:
while turns > 0:
# Print current guesses; get input; etc...
# Check for invalid input
if len(guess) > 1:
print("you can only guess 1 character at a time")
continue # This makes us return to the top of the while loop.
# We definitely have valid input by the time we get here, so handle the new guess.
这个例子比你原来的版本简单了一些;我把 count2
去掉了,因为它没有起到什么重要作用。但基本思路是一样的:在你提醒用户输入无效后,你需要请求新的输入——也就是跳回循环的开头,而不是直接往下走。