【发布时间】:2014-10-29 23:05:20
【问题描述】:
这是我的完整代码:
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()
抱歉,代码块很大,但我想提供一个完整的程序,以帮助解决我的错误。到目前为止,一旦调用 play,当我输入一个字母时,它只会不断打印出“剩余 8 条生命:”。几个字母后,它只会打印出“你赢了”。我很难找到我的错误,python 专家的任何帮助将不胜感激。
【问题讨论】:
-
也许应该在code review
-
不,这不是用于代码审查 - 程序不起作用
-
这里是关于生命未减的提示。这条线有什么作用?
lives_remaining -= 0 -
当然!愚蠢的错误,但现在完全明白了。谢谢。
标签: python python-3.x