2014-11-03 67 views
0

我正在嘗試編寫一個函數來玩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 
+0

我的第一句話就是「功能分解」。不要將整個程序寫入一個函數,而是將其寫入多個函數中。然後,您可以全面測試每個子功能,這使問題確定變得更容易。 – 2014-11-03 00:55:30

回答

0

Hangman遊戲循環未終止問題的原因是遊戲while循環檢查的letters_correct計數器變量。

while letters_correct != len(word): 

讓我們說這個詞是香蕉,我想信一個

在你的代碼來處理一個正確的猜測分支開始這一行:

letters_correct = letters_correct + 1 

在我的詞的情況下香蕉並猜測a然後letters_correct vari能力應該是遞增3倍。現在,如果我猜n letters_correct應爲增加兩倍

在你當前的實現中,我猜的順序只會增加letters_correct兩次(2),當它應該是5.所以,當增加letters_count遞增時,猜測出現在word的次數。

letters_count = letters_count + word.count(guess) 

這樣在遊戲循環中檢查letters_count變量實際上能夠達到單詞的長度。

0

你曾考慮過你的話有同樣的信函的多個的情況呢?

目前,如果用戶猜測正確,您只需遞增letters_correct一次。如果您每次發生一次正確的字母數量增加,它應該工作。