我正在嘗試編寫一個函數來玩hang子手,除了事實上該功能無法識別何時獲得遊戲,一切都運行完美。Python Hang子手 - 循環
---編輯---
這裏是我修改後的代碼
def hangman():
word = choose_word(wordlist)
guessed_word = len(word)*['_']
guesses = 10
available_letters = "abcdefghijklmnopqrstuvwxyz"
guessed_letters = ""
letters_correct = 0
print "Welcome to the game, Hangman!"
print "I am thinking of a word that is", len(word), "letters long."
print "Available letters:", available_letters
print "You have", guesses, "guesses."
while letters_correct != len(word):
guess = raw_input("enter your guess:")
if len(guess)==1 and guess.isalpha():
if guessed_letters.find(guess) != -1:
print "You already picked", guess
else:
guessed_letters = guessed_letters + guess
index1 = word.find(guess)
if index1 == -1:
print "The letter",guess,"is not in the word", ' '.join(guessed_word)
guesses = guesses - 1
print "You have", guesses, "guesses left."
if guesses == 0:
return "You are out of guesses. You lose. The word was "+ word + "."
available_letters = available_letters.replace(guess, '')
print "Available letters:", available_letters
else:
letters_correct = letters_correct + word.count(guess)
print"The letter", guess, "is in the word."
for i in range(len(word)):
if guess == word[i]:
guessed_word[i] = guess
print ' '.join(guessed_word)
if letters_correct != len(word):
print "You have", guesses, "guesses left."
available_letters = available_letters.replace(guess, '')
print "Available letters:", available_letters
elif guesses <= 0:
return "You are out of guesses. You lose. The word was "+ word + "."
else:
print "Please guess a single letter in the alphabet."
if letters_correct == len(word):
return "Congratualations! You figured out that the word is "+ word
我的第一句話就是「功能分解」。不要將整個程序寫入一個函數,而是將其寫入多個函數中。然後,您可以全面測試每個子功能,這使問題確定變得更容易。 – 2014-11-03 00:55:30