2014-03-01 59 views
1

我是新來的python,並且遇到了一個我正在製作的hang子手遊戲的問題。所以我有一個名爲「當前」的列表,裏面填充了連字符( - ),其長度與人猜測的單詞的長度相同。當他們正確地猜出一個字母時,它會在正確的地方用字母替換連字符。我遇到的問題是,如果一個單詞中有兩個或更多相同的字母,那麼它在第一次出現這封信時就會起作用,但之後它會說這封信已經被猜到了,因此它不起作用,而我不能弄清楚如何解決這個問題。Python - Hangman與一個詞中的多個字母的遊戲

current = "_" * len(theword) 
x = list(current) 
print (x) 

guessed = [] 

while current != theword and lives > 0: 

    print ("You have %d lives left" % lives) 
    guess = input("Please input one letter or type 'exit' to quit.") 
    guess = guess.lower() 


    if guess == "exit": 
     break 
    elif guess in guessed: 

     print ("You have already guessed this letter, please try again.") 



    guessed.append(guess) 

    if guess in theword: 
     index = theword.find(guess) 
     x = list(current) 
     x[index] = guess 
     current = "".join(x) 
     print ("Correct! \nYour guesses: %s" % (guessed)) 
     print(x) 


    else: 
     print ("Incorrect, try again") 
     lives = lives -1 


if current == theword: 
    print ("Well done, you have won!") 

感謝

回答

0

相反的:

if guess in theword: 
     index = theword.find(guess) 
     x = list(current) 
     x[index] = guess 
     current = "".join(x) 
     print ("Correct! \nYour guesses: %s" % (guessed)) 
     print(x) 

試試這個:

for index,character in enumerate(theword): 
    x = list(current) 
    if character == guess: 
     x[index] = guess 
1

通過使用string.find法,你只能得到字符的首次出現在這個詞裏。通過定義這個方法,你會得到所有出現:

def find_all(word, guess): 
    return [i for i, letter in enumerate(word) if letter == guess] 

你還應該加上一個「繼續」檢查,如果你之前已經猜到了信後,這樣你就不能再次添加到列表中。

這應該工作:

def find_all(word, guess): 
    return [i for i, letter in enumerate(word) if letter == guess] 

current = "_" * len(theword) 
x = list(current) 
print (x) 

guessed = [] 

while current != theword and lives > 0: 

    print ("You have %d lives left" % lives) 
    guess = input("Please input one letter or type 'exit' to quit.") 
    guess = guess.lower() 


    if guess == "exit": 
     break 
    elif guess in guessed: 
     print ("You have already guessed this letter, please try again.") 
     continue 

    guessed.append(guess) 

    if guess in theword: 
     indices = find_all(theword, guess) 
     x = list(current) 
     for i in indices: 
      x[i] = guess 
      current = "".join(x) 
      print ("Correct! \nYour guesses: %s" % (guessed)) 
      print(x) 

    else: 
     print ("Incorrect, try again") 
     lives = lives -1 
+0

謝謝你的偉大工程! – user3160631

相關問題