2017-03-22 49 views
-1

所以我有一個關於下面的代碼的快速問題。在程序中,它將顯示一系列破折號以匹配所選的隨機單詞。當玩家猜測時,程序會通過一個循環來檢查猜測。我的問題是,而我真正困惑的是,該計劃如何知道要替換顯示準確和部分顯示的單詞所需的準確短劃線?以及新的+ = so_far [i]在做什麼?總體而言,該部分真的讓我感到困惑,我非常感謝一些澄清。謝謝!有人可以幫我理解這一點嗎?

MAX_WRONG = len(HANGMAN) - 1 

# creating list of random words 
WORDS = ("TECHNOLOGY", "PYTHON", "SCRIPT", "PROCESSOR", "RANDOM",  "COMPUTING") 

# initialize variables 
word = random.choice(WORDS) 

so_far = "-" * len(word) # one dash for every letter in the word to be guessed 

wrong = 0 # number of wrong guesses made 

used = [] # letters already guessed 

# creating the main loop 
print("Welcome to Hangman. Good luck!") 

while wrong < MAX_WRONG and so_far != word: 
    print(HANGMAN[wrong]) 
    print("\nYou've used the following letters:\n", used) 
    print("\nSo far, the word is:\n", so_far) 

# getting the player's guess 
    guess = input("\n\nEnter your guess: ") 
    guess = guess.upper() 

    while guess in used: 

     print("You've already guessed the letter", guess) 
     guess = input("\nEnter your guess: ") 
     guess = guess.upper() 

    used.append(guess) 

# checking the guess 
    if guess in word: 
     print("\nYes!", guess, "is in the word!") 

    # create a new so_far to include guess 
     new = "" 

     for i in range(len(word)): 
      if guess == word[i]: 
       new += guess 
      else: 
       new += so_far[i] 
     so_far = new 

    else: 
     print("\nSorry,", guess, "isn't in the word.") 
     wrong += 1 

# ending the game 

if wrong == MAX_WRONG: 
    print(HANGMAN[wrong]) 
    print("\nYou lose!") 
else: 
    print("\nYou guessed it!") 

print("The word was:", word) 

ext() 
+0

代碼審查可能嗎? – Dev

+0

這是什麼意思?該程序運行良好。我只想澄清一下爲什麼我在範圍內(len(word))塊正在做什麼以及它如何在正確的位置替換未被揭示/部分被揭示的單詞的破折號。 –

+0

我現在明白了,謝謝 –

回答

0

您正在尋找出其中這是否

for i in range(len(word)): 
    if guess == word[i]: 
     new += guess 
    else: 
     new += so_far[i] 
so_far = new 

說,如果你猜字「S」,並說如果要猜出單詞的這部分代碼是「超級」

初始狀態

Sofar : ----- 

在迭代過程的可變'new'被分配了VAL用於每個單詞的匹配。如果不匹配採取從so_far [I] 在我們的情況

字= LEN(「超級」)= 5的長度爲該值 Iter項目1:只會去IG環路因爲「S」僅出現一次。

這意味着所有其他迭代轉到其他條件,因爲所有so_far[i] has '-'作爲值。 所以迭代的第一個循環後,你的價值觀是這樣

new: S---- 

在循環的末尾重新分配newso_far。這意味着現在'so_far'變量已從'-----'更改爲'S----'

我建議你使用pdb在for循環之上進行調試,並在將來遇到這樣的疑惑時獲取詳細信息。

希望這會有所幫助。

相關問題