首页 > 解决方案 > 如何每次尝试将用户输入限制为一个字符串 - Python

问题描述

完全的初学者,过去几周一直在学习,现在正致力于创建一个游戏作为我大学课程的一部分。

我决定变得复杂(对于初学者),因为我把它捡得很好,但是这个让我很难过。

我想将用户每次尝试限制为一个字符串。目前他们可以输入任意数量的角色(asdfghjkl),并且它将每个正确的角色输入到游戏中,这意味着他们可以在 3 次或更少的尝试中获胜。我的目标是如果他们输入多个字符,它会返回一条自定义错误消息,然后提示他们重试。包括完整的游戏,因为我不完全确定根据回复包括哪些部分..

    '''
    import random
    import time


    file = open("name_game.txt", "r+")
    f = file.readlines()
    word = random.choice(f)


    def age():
        try:
            user_age = int(input("First, How old are you? "))
            if user_age > 11:  # 11 due to high school age.
                print("You're a bit old for this!")
                print("\nY = Yes, N = No")
                user_input = input("Would you like to continue anyway? ")
                if user_input == "Y" or user_input == "y":
                    user_name()
                elif user_input == "N" or user_input == "n":
                    print("Exiting Game")
                    time.sleep(1.0)
                    exit()
                else:
                    print("You entered an invalid option.\nExiting.")
            elif user_age <= 3:
                print("You're too young for this, sorry!")
                print("Exiting Game")
                time.sleep(1.0)  # exiting game as they can't continue.
                exit()
            else:
                print("Continue!")
                user_name()
        except ValueError:
            print("*"*31)
            print("Please enter a numerical value.")
            print("*" * 31)
            time.sleep(1)
            age()


    def user_name():
        name_input = input("What is your name? ")
        print("Guess the word,", name_input + "!")
        print("Number of letters in word:", len(word.strip()))


    def try_again():
        char = ''
        attempts = 10
        score = 0

        while attempts > 0:
            fail_count = 0

            for letter in word.strip():
                if letter in char:
                    print(letter, end=" ")
                else:
                    print("_ ", end="")
                    fail_count += 1

            print("\nScore:", score)

            if fail_count == 0:
                print("Congrats, you're a winner!! \nResult:", word.title())
                print("Your final Score: ", score)  # print the score
                user_input = input("Would you like to play again? ")
                if user_input == "Y" or user_input == "y":
                    try_again()
                    break
                elif user_input == "N" or user_input == "n":
                    print("Exiting Game")
                    time.sleep(1.0)
                    exit()

            guess_letter = input("Guess a letter:")
            char += guess_letter

            if guess_letter not in word:
                attempts -= 1
                score -= 1
                print("Incorrect \nYou have", + attempts, "attempts left")

                if attempts == 0:
                    print("The word was:", word.title())
                    print("Better luck next time!")
                    user_input = input("Would you like to play again? ")
                    if user_input == "Y" or user_input == "y":
                        try_again()
                        break
                    elif user_input == "N" or user_input == "n":
                        print("Exiting Game")
                        time.sleep(1.0)
                        exit()
                        break


    age()
    try_again()
    '''

我的分数也有问题,它似乎将索引中正确字符的数量加在一起。因此,如果他们猜测 a + b + c,那么它会返回 +3 的分数。我似乎无法弄清楚如何只将分数增加 1。

任何帮助将非常感激?我已经找了好几天了。

标签: python-3.xuser-inputlimitmaxlength

解决方案


您必须让它检查输入字符串的长度,如果它大于 1,则继续下一次迭代,同时不影响得分或失败尝试。您可以这样做:

while attempts > 0:
    if len(inputted_character) > 1:
        # I don't know the name of your input, name it however is necessary.
        print("please only input a single character.")
        continue  # this will jump to the next iteration without running the rest of the code in the loop.

    # continue with your code below.

推荐阅读