结束我的秘密文字游戏并在Python中输出用户猜测计数

时间:2018-10-24 00:04:10

标签: python for-loop while-loop

我正在尝试用Python编写类似于Hangman的文字游戏。 用户可以猜测多少次没有限制。

除了一个小问题,我的游戏正常运行: 当用户猜出完整的单词时,游戏不会结束并告诉他们他们赢了,并且猜了多少次。

def main():

    print("Welcome to the Secret Word Game!")
    print()


    word = ["m","o","u","n","t","a","i","n"]

    guessed = []
    wrong = []

    guesses = 0

    while True:

        out = ""
        for letter in word:
            if letter in guessed:
                out = out + letter
            else:
                out = out + "*"

        if out == word:
            print("You guessed", word)
            break

        print("Guess a letter from the secret word:", out)

        guess = input()

        if guess in guessed or guess in wrong:
            print("Already guessed", guess)
            guesses +=1
        elif guess in word:
            print("Correct!",guess,"is in the secret word!")
            guessed.append(guess)
            guesses+=1
        else:
            print("Wrong!")
            wrong.append(guess)
            guesses+=1

    print()
    print(guesses)




main()

1 个答案:

答案 0 :(得分:0)

您不会退出,因为您的终止条件不可能为True:

    if out == word:

out是长度为8的字符串; word是8个单字符字符串的列表。如果将word的初始化更改为

    word = "mountain"

然后您的程序运行正常,产生逐个猜测的更新和适当数量的猜测。

Welcome to the Secret Word Game!

Guess a letter from the secret word: ********
n
Correct! n is in the secret word!
Guess a letter from the secret word: ***n***n
e
Wrong!
Guess a letter from the secret word: ***n***n
t
Correct! t is in the secret word!
Guess a letter from the secret word: ***nt**n
a
Correct! a is in the secret word!
Guess a letter from the secret word: ***nta*n
o
Correct! o is in the secret word!
Guess a letter from the secret word: *o*nta*n
i
Correct! i is in the secret word!
Guess a letter from the secret word: *o*ntain
f
Wrong!
Guess a letter from the secret word: *o*ntain
m
Correct! m is in the secret word!
Guess a letter from the secret word: mo*ntain
u
Correct! u is in the secret word!
You guessed mountain

9