刽子手Python游戏

cs7cruho  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(146)

我正在为一个项目编写一个基于Python的终端游戏Hangman。目前,如果玩家做出正确的猜测或不正确的猜测,正确猜测的字母和剩余的字母都会正确显示。
我有一个问题,显示字母,如果球员作出了无效的猜测。我有一个for循环,显示猜测的字母和未猜测的字母,这是预期的工作。但是,我在函数的开头有一个if else语句,用来判断用户是否输入了正确的字符,但问题是只有用户输入了正确的字符,这些字符才会显示出来。因此,如果用户重复一个字母,输入一个数字而不是字母,或者输入多个字符,显示字母的代码就不会运行,这样用户就无法看到他们的“游戏屏幕”。
这是主游戏的主要功能。

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()

我已经把循环复制到第391行的第一个有效性检查器中进行测试,它确实工作了。我也可以把循环放到其他错误语句中,但这最终会使代码变得非常庞大。我试着把循环移到它自己的函数中,但它引用了其他只在new_game函数中的变量。我也试着定义一个内部函数,但我无法让它工作。我在内部函数中加入了外部函数所需的变量。
任何帮助弄清楚这一点将不胜感激。此外,任何其他提示,以清理此代码将是伟大的,如果你注意到任何荒谬的!我有很多重复的打印语句,我试图避免重复,但我不能让它工作的方式,我想要的,除非我打印出来的每一次。

lx0bsm1f

lx0bsm1f1#

你可以把for循环放在它自己的函数中,并在调用它时传递它所需要的变量。

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

我不确定这一点,但是你能不能不要让字母在你跳出if语句之后显示出来?就像in一样,在if语句之后(但不在其中)立即运行for循环,这可能会起作用。

相关问题