2017-02-14 31 views
0

我该如何让这段代码工作,以便用户可以将他们的猜测输入到函数中,直到他们得到正确猜测的整个单词或者没有更多的生命剩下为止?现在,用户只能输入一个字符串,然后循环突然结束。我无法让我的代码正常循环

secret_words_list = ['voldemort', 'hogwarts'] 
def hangman(): 
    lives = 5 
    while lives >= 0: 
     answer = random.choice(secret_words_list) 
     guess = raw_input('Write your answer here: ') 
     hangman_display = '' 
     for char in answer: 
      if char in guess: 
       hangman_display += char 
       lives -= 1 
      elif char == ' ': 
       hangman_display += char 
      else: 
       hangman_display += "-" 
       lives -= 1 
     if hangman_display == answer: 
      print("You win") 
    print(hangman_display) 
+2

也许是因为你为每个字符除了''取走了生命? – Julien

+0

也许你可以看到: caimaoy

+0

对于每个字符检查你减少了一个生命,而不是包括它在for循环之后(每迭代一次)? – Vinay

回答

0
import random 
secret_words_list = ['voldemort', 'hogwarts'] 
def hangman(): 
    lives = 5 
    while lives >= 0: 
     answer = random.choice(secret_words_list) 
     guess = raw_input('Write your answer here: ') 
     hangman_display = '' 
     for char in answer: 
      if char in guess: 
       hangman_display += char 
       #lives -= 1 
      elif char == ' ': 
       hangman_display += char 
      else: 
       hangman_display += "-" 
       #lives -= 1 
     if hangman_display == answer: 
      print("You win") 
      break 
     else: 
      lives -=1 
    print(hangman_display) 

hangman() 

我din't了解您的具体要求,但这个你在找什么?

节目互动就像下面的东西,

Write your answer here: vol 
-o------ 
Write your answer here: hog 
hog----- 
Write your answer here: hogwart 
hogwart- 
Write your answer here: hogwarts 
You win 
hogwarts 
0

它为什么突然终止的原因是因为它是检查在逐个字符的基础,而不是检查整个单词,然后决定是否猜测是不正确的。

Here's my code for this solution, documented so you can understand:

基本上,有充当开关变量,当你有一个正确的猜测打开它,然后有一个检查“for”循环后看到一个生命是否需要被带走或不。

您可以看到,这是我在循环前创建的'正确'变量所做的,并检查以下内容。

希望这有助于^^ 康纳

编辑:

我要去打破这一点,使得它不是一个巨大的转储:P

检查代码,如果你无法理解这一点。

您会收到输入信息,测试它是否是一个字母,然后用显示屏做doohickey。

检查过每一个字符是...

#we need to check if we need to take a life away 
correct = False 

这就是“开关”我谈创建,只是一个布尔变量。

#loop through the word to guess, character by character. 
for char in word: 
    #if the character is in the old display, add it to the new on. 
    if char in lastdisplay: 
     display += char 

在这里,如果预先显示字符,我们将在新的显示中显示字符。

#if the character is in the guess, add it to the display. 
    elif char in guess: 
     display += char 
     #we made a correct guess! 
     correct = True 

如果猜测字符是,我们目前正在检查其添加到显示器,并翻转开关为“True”

#otherwise we need to add a blank space in our display. 
    else:    
     if char == ' ': 
      display += ' ' #space 
     else: 
      display += '_' #empty character 

否则,一切都没有发生过的人物,添加在一个空间/空白并继续循环。

#if we didn't get a correct letter, take a life. 
if not correct: 
    lives -= 1 

这里的是我们检查“开关”,如果是“真”,我们并不需要采取一个生命,

否则“开关‘假’,我们采取生活。

+0

非常感谢你!!!!! –