简体   繁体   English

刽子手 python 游戏

[英]Hangman python game

I am writing a python based terminal game of Hangman for a project.我正在为一个项目编写一个基于 python 的 Hangman 终端游戏。 Currently, the correctly guessed letters and letters remaining are displayed correctly if the player makes a correct guess or an incorrect guess.目前,如果玩家猜对或猜错,猜对的字母和剩余的字母都会正确显示。

I am having an issues displaying the letters if the player makes an invalid guess.如果玩家猜测无效,我会在显示字母时遇到问题。 I have a for loop that displays the guessed letters and unguessed letters which works as expected.我有一个 for 循环,显示按预期工作的猜到的字母和未猜到的字母。 However, I have an if else statement at the start of the function that determines if the user inputs a correct character.但是,我在 function 的开头有一个 if else 语句,用于确定用户是否输入了正确的字符。 The problem I have is that the letters are only displayed if the user makes a valid entry.我遇到的问题是,只有在用户进行有效输入时才会显示这些字母。 So if the user repeats a letter, inputs a number instead of a letter, or inputs multiple characters, the code to display the letters doesn't run so the user wont be able to see their “gamescreen”.因此,如果用户重复一个字母,输入数字而不是字母,或输入多个字符,显示字母的代码将不会运行,因此用户将无法看到他们的“游戏画面”。

This is the main function for the main game.这是主要游戏的主要 function。


def new_game(category, difficulty):
    """
    Starts a new game which takes the category and difficulty
    parameters chosen by the user to generate a word from the spreadsheet.
    """
    # Generate the word the player is trying to guess
    random_word = random.choice(
        SHEET.worksheet(difficulty + "_" + category)
        .get_values().pop()).upper()
    # Print the category and difficulty level chosen by the user
    print(f"Category: { category.capitalize() }")
    print(f"Difficulty level: { difficulty.capitalize() }")
    guessed_letters = ""
    wrong_guesses = 0
    print_hangman(wrong_guesses)
    # Print random word for testing.
    print(f"your word is: {random_word}")
    # Display blank letters in word for user.
    print(len(random_word) * " _ " + "\n ")
    # Create a loop that ends when the player loses. Break if player wins.
    while wrong_guesses < 7:
        player_choice = input("Please pick a letter...: \n").upper()
        print(f"Category: { category.capitalize() }")
        print(f"Difficulty level: { difficulty.capitalize() } \n")
        print_hangman(wrong_guesses)
        clear()
        # Prints error message if player choice is not a letter from a-z.
        if not player_choice.isalpha():
            print(
                f"{player_choice} is not a valid letter... " +
                f"You have {7 - wrong_guesses} guess(es) remaining...")
            print_hangman(wrong_guesses)
            guessed_letters = guessed_letters + player_choice
            wrong_letters = 0
            # Prints the players guessed letters and remaining blank spaces.
            for letter in random_word:
                if letter in guessed_letters:
                    print(
                        f" { letter.upper() } ", end=""
                        )
                else:
                    print(" _ ", end="")
                    wrong_letters += 1
            print("")
            print("\nPreviously guessed letters: \n")
            print(f"{list(guessed_letters.upper())}" + "\n ")
        # Print error message if player inputs more than one letter.
        elif len(player_choice) != 1:
            print(
                "Please input one letter at a time..." +
                f"You have {7 - wrong_guesses} guess(es) remaining...")
            print_hangman(wrong_guesses)
            print("\nPreviously guessed letters: \n")
            print(f"{list(guessed_letters.upper())}" + "\n ")
        # Print error message if player repeats the same letter.
        elif player_choice in guessed_letters:
            print(
                f"{player_choice.upper()} has already been guessed..." +
                f"You have {7 - wrong_guesses} guess(es) remaining...")
            print_hangman(wrong_guesses)
            print("\nPreviously guessed letters: \n")
            print(f"{list(guessed_letters.upper())}" + "\n ")
        # Runs if player makes a valid input.
        else:
            if player_choice in random_word:
                print(
                    f"Correct, {player_choice.upper()} is in the word! " +
                    f"You have {7 - wrong_guesses} guess(es) remaining...")
            else:
                # Add 1 to the wrong_guesses variable
                wrong_guesses += 1
                print(
                    f"Sorry, {player_choice.upper()} is not in the word... " +
                    f"You have {7 - wrong_guesses} guess(es) remaining..."
                    )
            print_hangman(wrong_guesses)
            # Adds all letters guessed by the user
            # to the guessed_letters variable.
            guessed_letters = guessed_letters + player_choice
            wrong_letters = 0
            # Loop that displays correct letters and letters remaining.
            for letter in random_word:
                if letter in guessed_letters:
                    print(
                        f" { letter.upper() } ", end=""
                        )
                else:
                    print(" _ ", end="")
                    wrong_letters += 1
            print(" ")
            print("\nPreviously guessed letters: \n")
            print(f"{list(guessed_letters.upper())}" + "\n ")
            if wrong_letters == 0:
                print(
                    colorama.Fore.GREEN +
                    "Congratulations, you won! \n"
                    )
                print(f"The word is {random_word.upper()}!\n")
                sub_menu()
                break
    else:
        print(
            colorama.Fore.RED +
            "\nSorry, you lose... Please try again...\n")
        print(f"The word was {random_word.upper()}...\n")
        sub_menu()

I've copied the loop into the first validity checker at line 391 to test and it does work.我已将循环复制到第 391 行的第一个有效性检查器中进行测试,它确实有效。 I can also put the loop into the other error statements but this ends up making the code very bulky.我也可以将循环放入其他错误语句中,但这最终会使代码变得非常庞大。 I've tried moving the loop into its own function but it is referencing other variables that are only in the new_game function. I also tried to define an inner function but I couldn't get it to work, I had variables in the inner function that were needed in the outer function.我已经尝试将循环移动到它自己的 function 中,但它引用了仅在 new_game function 中的其他变量。我还尝试定义一个内部 function 但我无法让它工作,我在内部 function 中有变量在外部 function 中需要这些。

Any help on figuring this out would be greatly appreciated.任何帮助解决这个问题的帮助将不胜感激。 Also any other tips to clean up this code would be great if you notice anything ridiculous.如果您发现任何荒谬的事情,清理此代码的任何其他提示也会很棒。 I have a lot of repeating print statements that I tried to avoid repeating but I couldn't get it to work the way I wanted unless I printed them out every time.我有很多重复的打印语句,我试图避免重复,但我无法让它按照我想要的方式工作,除非我每次都打印出来。

You can put the for loop in its own function and pass it the variables it needs when calling it.您可以将 for 循环放在它自己的 function 中,并在调用它时将它需要的变量传递给它。 The function might look like this: function 可能如下所示:

def display_letters(random_word, guessed_letters, wrong_letters):
   for letter in random_word:
      if letter in guessed_letters:
         print(
             f" { letter.upper() } ", end=""
             )
      else:
         print(" _ ", end="")
         wrong_letters += 1
         return wrong_letters

I'm not sure about this but could you not just have the letters display after you fall out of the if statement?我不确定这一点,但你能不能在你退出 if 语句后只显示字母? As in, immediately after the if statement (but not in it) just run the for loop.就像在 if 语句之后(但不在其中)一样,立即运行 for 循环。 That might work.那可能行得通。

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

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