1

所以我尝试制作一个游戏,让计算机从 10 个给定的数字中随机选择一个 4 位数字。然后计算机将用户的猜测与随机选择的代码进行比较,并相应地给出反馈:

  • G = 正确放置的正确数字
  • C = 正确的数字,但位置不正确
  • F = 数字不在计算机选择的代码中

但是,反馈并不总是正确输出。Fox 示例,当我猜测 9090 时,我得到的反馈是 FCF,而反馈应该由 4 个字母组成....我该如何解决这个问题?

#chooses the random pincode that needs to be hacked
import random
pincode = [
    '1231', '9997', '8829', '6765',  '9114', '5673', '0103', '4370', '8301', '1022'
]

name = None

#Main code for the game
def main():
    global code
    global guess

    #Chooses random pincode
    code = random.choice(pincode)

    #Sets guessestaken to 0
    guessesTaken = 0

    while guessesTaken < 10:

        #Makes sure every turn, an extra guess is added
        guessesTaken = guessesTaken + 1

        #Asks for user input
        print("This is turn " + str(guessesTaken) + ". Try a code!")
        guess = input()

        #Easteregg codes
        e1 = "1955"
        e2 = "1980"

        #Checks if only numbers have been inputted
        if guess.isdigit() == False:
            print("You can only use numbers, remember?")
            guessesTaken = guessesTaken - 1
            continue

        #Checks whether guess is 4 numbers long
        if len(guess) != len(code):
            print("The code is only 4 numbers long! Try again!")
            guessesTaken = guessesTaken - 1
            continue

        #Checks the code
        if guess == code:

            #In case the user guesses the code in 1 turn
            if (guessesTaken) == 1:
                print("Well done, " + name + "! You've hacked the code in " +
                      str(guessesTaken) + " turn!")

            #In cases the user guesses the code in more than 1 turn
            else:
                print("Well done, " + name + "! You've hacked the code in " +
                      str(guessesTaken) + " turns!")
            return

        #Sets empty list for the feedback on the user inputted code
        feedback = []
        nodouble = []

        #Iterates from 0 to 4
        for i in range(4):

            #Compares the items in the list to eachother
            if guess[i] == code[i]:

                #A match means the letter G is added to feedback
                feedback.append("G")
                nodouble.append(guess[i])

            #Checks if the guess number is contained in the code
            elif guess[i] in code:

                #Makes sure the position of the numbers isn't the same
                if guess[i] != code[i]:
                    if guess[i] not in nodouble:

                        #The letter is added to feedback[]  if there's a match
                        feedback.append("C")
                        nodouble.append(guess[i])

            #If the statements above are false, this is executed
            elif guess[i] not in code:

                #No match at all means an F is added to feedback[]
                feedback.append("F")
                nodouble.append(guess[i])

        #Easteregg
        if guess != code and guess == e1 or guess == e2:
            print("Yeah!")
            guessesTaken = guessesTaken - 1
        else:
            print(*feedback, sep=' ')


main()

您可以在这里尝试游戏: https ://repl.it/@optimusrobertus/Hack-The-Pincode

编辑2: 在这里,您可以看到我的意思的一个例子。

4

1 回答 1

0

这是我想出的。让我知道它是否有效。

from random import randint


class PinCodeGame(object):

    def __init__(self):
        self._attempt = 10
        self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
                    '1022']
        self._easterEggs = ['1955', '1980', '1807', '0609']

    def introduction(self):
        print("Hi there stranger! What do I call you? ")
        player_name = input()
        return player_name

    def show_game_rules(self):
        print("10 turns. 4 numbers. The goal? Hack the pincode.")
        print(
            "For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
        )

    def tutorial_needed(self):
        # Asks for tutorial
        print("Do you want a tutorial? (yes / no)")
        tutorial = input().lower()

        # While loop for giving the tutorial
        while tutorial != "no" or tutorial != "yes":
            # Gives tutorial
            if tutorial == "yes":
                return True

            # Skips tutorial
            elif tutorial == "no":
                return False

            # Checks if the correct input has been given
            else:
                print("Please answer with either yes or no.")
                tutorial = input()

    def generate_code(self):
        return self._code[randint(0, len(self._code))]

    def is_valid_guess(self, guess):
        return len(guess) == 4 and guess.isdigit()

    def play(self, name):
        attempts = 0
        code = self.generate_code()
        digits = [code.count(str(i)) for i in range(10)]

        while attempts < self._attempt:
            attempts += 1
            print("Attempt #", attempts)
            guess = input()
            hints = ['F'] * 4
            count_digits = [i for i in digits]
            if self.is_valid_guess(guess):
                if guess == code or guess in self._easterEggs:
                    print("Well done, " + name + "! You've hacked the code in " +
                        str(attempts) + " turn!")
                    return True, code
                else:
                    for i, digit in enumerate(guess):
                        index = int(digit)
                        if count_digits[index] > 0 and code[i] == digit:
                            count_digits[index] -= 1
                            hints[i] = 'G'
                        elif count_digits[index] > 0:
                            count_digits[index] -= 1
                            hints[i] = 'C'
                    print(*hints, sep=' ')
            else:
                print("Invalid input, guess should be 4 digits long.")
                attempts -= 1
        return False, code


def main():
    # initialise game
    game = PinCodeGame()
    player_name = game.introduction()
    print("Hi, " + player_name)
    if game.tutorial_needed():
        game.show_game_rules()
    while True:
        result, code = game.play(player_name)
        if result:
            print(
                "Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
        else:
            print("Hahahahaha! You've lost! The correct code was " + code +
                ". Do you want to try again, and win this time? (yes / no)")
        play_again = input().lower()
        if play_again == "no":
            return


main()
于 2019-06-18T03:47:21.340 回答