简体   繁体   English

刽子手中的嵌套 While 循环

[英]Nested While loop in hangman

I am creating a hangman game.Here are the conditions我正在创建一个刽子手游戏。这是条件

  • User will be given six chances for wrong choices用户将有六次错误选择的机会
  • If the letter was already entered, user will be notified that letter already exists (user will not be penalised for double wrong entry)如果字母已经输入,用户将被通知字母已经存在(用户不会因两次输入错误而受到惩罚)

Now my question is :现在我的问题是:

  • I want to display the message that "user lost the game" if the number of wrong guessed letters goes to 7 and exists the loop but it is not happening如果错误猜测的字母数达到 7 并且存在循环但它没有发生,我想显示“用户输了游戏”的消息

here is my code:这是我的代码:

print("Welcome to Hangman"
      "__________________")
word = "Python"
wordlist=list(word)
wordlist.sort()

print(wordlist)
print("Word's length is", len(word))
letter=" "
used_letter=[]
bad_letter=[]
guess=[]
tries=0
while len(bad_letter)<7:

    while guess != wordlist or letter !="exit":
        letter = input("Guess your letter:")
        if letter in word and letter not in used_letter:
            guess.append(letter)
            print("good guess")
        elif letter in used_letter:
            print("letter already used")
        else:
            bad_letter.append(letter)
            print("bad guess")
        used_letter.append(letter)
        tries+=1
        print("You have ",6 - len(bad_letter), " tries remaining")
        print(guess)
        print("You have made ",tries," tries so far")
        guess.sort()

    print("Thank you for playing the game, you guessed in ",tries," tries.")
    print("Your guessed word is", word)
print("you lost the game")

I am very new to python so i would appreciate help in basic concepts我对 python 很陌生,所以我很感激在基本概念方面的帮助

It seems like your while len(bad_letter) < loop is never exiting because of the while loop below it which is checking for the right answer or exit entry runs forever.看起来你的while len(bad_letter) < loop永远不会退出,因为它下面的 while 循环正在检查正确的答案或退出条目永远运行。

What you should do is only have one master while loop which takes in a new input each time and then check to see if that input matches any of the conditions you are looking for.您应该做的是只有一个主 while 循环,每次都接收一个新输入,然后检查该输入是否与您正在寻找的任何条件匹配。

You could structure it something like this:你可以像这样构造它:

bad_letter = []
tries = 0
found_word = False

while len(bad_letter) < 7:
    letter = input("Guess your letter:")
    if letter == 'exit':
        break  # Exit game loop

    if letter in word and letter not in used_letter:
        guess.append(letter)
        print("good guess")
    elif letter in used_letter:
        print("letter already used")
    else:
        bad_letter.append(letter)
        print("bad guess")

    used_letter.append(letter)
    tries+=1
    print("You have ", 6 - len(bad_letter), " tries remaining")
    print(guess)
    print("You have made ",tries," tries so far")
    guess.sort()

    if guess == wordlist:
        found_word = True
        break  # Exits the while loop

print("Thankyou for playing tha game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
if found_word:
    print("You won")
else:
    print("you lost the game")

Solution解决方案

word = 'Zam'
guesses = []
guesses_string = ''
bad_guesses = []
chances = 6

def one_letter(message=""):
    user_input = 'more than one letter'
    while len(user_input) > 1 or user_input == '':
        user_input = input(message)
    return user_input


while chances > 0:
    if sorted(word.lower()) == sorted(guesses_string.lower()):
        print("\nYou guessed every letter! (" + guesses_string + ")")
        break
    guess = one_letter("\nGuess a letter: ")
    if guess in guesses or guess in bad_guesses:
        print("You already guessed the letter " + guess + ".")
        continue
    elif guess.lower() in word.lower():
        print("Good guess " + guess + " is in the word!.")
        guesses.append(guess)
        guesses_string = ''.join(guesses)
        print("Letters guessed: " + guesses_string)
    else:
        print("Sorry, " + guess + " is not in the word.")
        bad_guesses.append(guess)
        chances -= 1
        print(str(chances) + " chances remaning.")

if chances == 0:
    print("\nGame Over, You Lose.")
else:
    word_guess = ''
    while word_guess.lower() != word.lower():
        word_guess = input("Guess the word: ('quit' to give up) ")    
        if word_guess.lower() == 'quit':
           print("You gave up, the word was " + word.title() + "!")
           break
    if word_guess.lower() == word.lower():
        print("\nCongratulations YOU WON! The word was "
            + word.title() + "!")

Hey there!嘿! I'm new to programming (week 2) and keep seeing these 'hangman' games popup, since today is my break from learning, I the goals you were trying to achieve and ran with it.我是编程新手(第 2 周),并且不断看到这些“刽子手”游戏弹出窗口,因为今天是我学习的休息时间,我实现了您试图实现的目标并实现了它。 Added some extra features in here such as breaking the loop if the all letters are guessed, and then asking the user to guess the final word.在这里添加了一些额外的功能,例如如果所有字母都猜对了就打破循环,然后让用户猜出最后一个单词。

Notes笔记

There is a ton of Refactoring you could do with this(almost breaks my heart to post this raw form) but I just blurted it on on the go.你可以用这个进行大量的重构(发布这个原始表单几乎让我心碎)但我只是在旅途中脱口而出。 Also note that my original goal was to stick to your problem of not allowing the same letter to be entered twice.另请注意,我最初的目标是解决您不允许输入两次相同字母的问题。 So this solution only works for words that contain no duplicate letters.所以这个解决方案只适用于不包含重复字母的单词。

Hope this helps!希望这可以帮助! When I get some time I'll Refactor it and update, best of luck!当我有时间时,我会重构它并更新,祝你好运!

Updates Added bad_guesses = [] allows to stop from entering bad guess twice.更新添加了bad_guesses = []允许停止输入错误猜测两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM