我无法让我的代码正确循环

时间:2017-02-14 05:56:45

标签: python while-loop raw-input

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

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 个答案:

答案 0 :(得分: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()

我不明白你的确切要求,但这是你在找什么?

程序交互如下所示,

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

答案 1 :(得分: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

如果猜到的字符是我们当前正在检查的字符,请将其添加到显示屏,然后将开关翻转为“真实”

    #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

我们在这里查看了'开关'如果它是' True'我们不需要过生活,

否则,'开关为“假”'我们生活。