所以我最近看了一个关于如何创建hangman的python教程。我试了一下但是它的源代码存在一些问题,所以我一直在努力编写类似的代码,效果很好。我最近才碰到一个问题。基本上,每当你猜到'secret'字符串中的最后一个字母时,它就不会用字母替换空白。我想知道为什么会这样,以及如何解决它。
这是代码
import random
words = '''aardvark baboon calf camel deer dingo alligator ant jackal iguana
falcon flamingo macaw manatee marmoset flee emu narwhal leopord ocelot
lemming opossum dog dolphin dove beaver bison wallaby rabbit salamander
seagull sheep skunk tiget tortoise unicorn dragon zombie'''.split()
def randomWord(wordList):
wIndex = random.randint(0, len(wordList) - 1)
return wordList[wIndex]
def displayGame(wrong, right, secret):
print('Wrong Guesses:', end=' ')
for letter in wrong:
print(letter, end=' ')
print()
blanks = '_' * len(secret)
for i in range(0, len(secret) - 1):
if secret[i] in right:
blanks = blanks[:i] + secret[i] + blanks[i+1:]
for letter in blanks:
print(letter, end=' ')
print()
def getGuess(guessed):
while True:
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in guessed:
print('You have already guessed that letter.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please print a letter.')
else:
return guess
def playAgain():
print('Would you like to play again? (yes or no)', end=' ')
while True:
keepGoing = input()
if keepGoing == 'yes':
return True
elif keepGoing == 'no':
return False
else:
print('Yes or no please.')
print('Guessing Game!')
print()
wrong = ''
right = ''
secret = randomWord(words)
gameOver = False
while True:
while gameOver == False:
displayGame(wrong, right, secret)
guess = getGuess(wrong + right)
if guess in secret:
right += guess
foundAll = True
for i in range(0, len(secret) - 1):
if secret[i] not in right:
foundAll = False
break
if foundAll:
print('Congratulations! You won! The word was ' + secret)
gameOver = True
break
else:
wrong += guess
if len(wrong) > 7:
print('You ran out of guesses! Game over! The word was ' + secret)
gameOver = True
break
keepGoing = playAgain()
if keepGoing:
wrong = ''
right = ''
secret = randomWord(words)
gameOver = False
else:
print('Thanks for playing!')
break
这是破碎的输出
Would you like to play again? (yes or no) yes
Wrong Guesses:
_ _ _ _ _ _
a
Wrong Guesses:
_ _ a _ _ _
m
Wrong Guesses: m
_ _ a _ _ _
l
Wrong Guesses: m l
_ _ a _ _ _
c
Wrong Guesses: m l c
_ _ a _ _ _
e
Wrong Guesses: m l c
_ e a _ e _
r
Wrong Guesses: m l c
_ e a _ e _
d
Wrong Guesses: m l c d
_ e a _ e _
b
Wrong Guesses: m l c d
b e a _ e _
v
Congratulations! You won! The word was beaver
答案 0 :(得分:1)
问题在于
for i in range(0, len(secret) - 1)
范围会排除最后一个值,并且您要从此
中减去1