这是我的完整代码:
import random
guessesMade = 0
lives_remaining = 8
roundsPlayed = 0
roundsWon = 0
guessed_letters = ''
words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
def pick_a_word():
word_position = random.randint(0, len(words) - 1)
return words[word_position]
print(pick_a_word())
def play():
print('Welcome to hangman! The rules are simple: A word will be chosen at random and will be represented by a sequence of blanks. Each blank constitutes a letter in the word. You will be asked to enter a letter and if the letter is contained in the word you will be notified. You can only make an incorrect guess 8 times before you lose the round. To win the round you must guess all the letters and reveal the word. Good luck!\n\n')
word = pick_a_word()
while True:
guess = get_guess(word)
if process_guess(guess,word):
print('You won.')
break
elif lives_remaining == 0:
print("\nI'm sorry, but you have run out of guesses. The word was {}.".format(randWord))
break
def get_guess(word):
print_word_with_blanks(word)
print('Lives Remaining: ' + str(lives_remaining))
guess = input('Guess a letter or the word if you know it.')
return guess
def print_word_with_blanks(word):
display_word=''
for letter in display_word:
if guessed_letters.find(letter) > -1:
display_word = display_word + letter
else:
display_word = display_word + '-'
print(display_word)
def process_guess(guess,word):
if len(guess) > 1 and len(guess == len(word)):
return whole_word_guess(guess,word)
else:
return single_letter_guess(guess, word)
def whole_word_guess(guess,word):
global guessesLeft
if guess.lower() == word.lower():
return True
else:
guessesLeft -=1
return False
def single_letter_guess(guess,word):
global guessed_letters
global lives_remaining
if word.find(guess) == -1:
lives_remaining -= 0
guessed_letters = guessed_letters + guess.lower()
if all_letters_guessed(word):
return True
return False
def all_letters_guessed(word):
for letter in word:
if guessed_letters.find(letter.lower()) == -1:
return False
return True
play()
对于大代码块感到抱歉,但我想查看整个程序以帮助修复我的错误。截至目前,一旦播放被称为播放,它就会在我输入单个字母时不断打印出“剩下的8个生命:”。几个字母之后它只打印出“你赢了”。我很难找到我的错误,蟒蛇专家的任何帮助将不胜感激。
答案 0 :(得分:1)
在此功能中:
def print_word_with_blanks(word):
display_word=''
for letter in display_word:
if guessed_letters.find(letter) > -1:
display_word = display_word + letter
else:
display_word = display_word + '-'
print(display_word)
您忽略了作为参数传入的word
,并且循环遍历display_word
,这是空的。因此,实际的单词(带空格)根本不会打印出来。
大概你的意思是说:
for letter in word:
...
或者你可以更简洁地写一下:
def print_word_with_blanks(word):
print(''.join(c if c in guessed_letters else '-' for c in word))
您遇到的另一个问题是:
def all_letters_guessed(word):
for letter in word:
if guessed_letters.find(letter.lower()) == -1:
return False
return True
这是缩进的方式,它总是在循环的第一次迭代时返回true或false。它应该是这样的:
def all_letters_guessed(word):
for letter in word:
if guessed_letters.find(letter.lower()) == -1:
return False
return True
所以return True
仅在整个循环结束后才会触发。
或者更好的是:
def all_letters_guessed(word):
return all(c.lower() in guessed_letters for c in word)