Python - Hangman游戏,一个单词中有多个字母

时间:2014-03-01 12:42:20

标签: python

我是python的新手,我正在制作一个刽子手游戏的问题。所以我有一个名为" current"其中填充连字符( - )的次数与人猜测的单词长度相同。当他们正确地猜出一个字母时,它会用正确位置的字母替换连字符。我遇到的问题是,如果一个单词中有两个或两个以上相同的字母,那么这个字母第一次出现就会起作用,但之后会说这封信已经被猜到了因此它不起作用我无法弄清楚如何解决这个问题。

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!")

由于

2 个答案:

答案 0 :(得分:1)

通过使用string.find-method,您只能获得单词中第一次出现的字符。通过定义此方法,您可以获得所有实例:

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

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